summaryrefslogtreecommitdiffstats
path: root/src/gallium/drivers/radeon/AMDILPointerManager.cpp
blob: 9cac61cb7180a8a1a6e97fec67674d291b5b3345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
//===-------- AMDILPointerManager.cpp - Manage Pointers for HW-------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//==-----------------------------------------------------------------------===//
// Implementation for the AMDILPointerManager classes. See header file for
// more documentation of class.
// TODO: This fails when function calls are enabled, must always be inlined
//===----------------------------------------------------------------------===//
#include "AMDILPointerManager.h"
#include "AMDILCompilerErrors.h"
#include "AMDILDeviceInfo.h"
#include "AMDILGlobalManager.h"
#include "AMDILKernelManager.h"
#include "AMDILMachineFunctionInfo.h"
#include "AMDILTargetMachine.h"
#include "AMDILUtilityFunctions.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/ValueMap.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionAnalysis.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalValue.h"
#include "llvm/Instructions.h"
#include "llvm/Metadata.h"
#include "llvm/Module.h"
#include "llvm/Support/FormattedStream.h"

#include <stdio.h>
using namespace llvm;
char AMDILPointerManager::ID = 0;
namespace llvm {
  FunctionPass*
    createAMDILPointerManager(TargetMachine &tm AMDIL_OPT_LEVEL_DECL)
    {
      return tm.getSubtarget<AMDILSubtarget>()
        .device()->getPointerManager(tm AMDIL_OPT_LEVEL_VAR);
    }
}

AMDILPointerManager::AMDILPointerManager(
    TargetMachine &tm
    AMDIL_OPT_LEVEL_DECL) :
  MachineFunctionPass(ID),
  TM(tm)
{
  mDebug = DEBUGME;
  initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
}

AMDILPointerManager::~AMDILPointerManager()
{
}

const char*
AMDILPointerManager::getPassName() const
{
  return "AMD IL Default Pointer Manager Pass";
}

void
AMDILPointerManager::getAnalysisUsage(AnalysisUsage &AU) const
{
  AU.setPreservesAll();
  AU.addRequiredID(MachineDominatorsID);
  MachineFunctionPass::getAnalysisUsage(AU);
}

AMDILEGPointerManager::AMDILEGPointerManager(
    TargetMachine &tm
    AMDIL_OPT_LEVEL_DECL) :
  AMDILPointerManager(tm AMDIL_OPT_LEVEL_VAR),
  TM(tm)
{
}

AMDILEGPointerManager::~AMDILEGPointerManager()
{
}
std::string
findSamplerName(MachineInstr* MI,
    FIPMap &FIToPtrMap,
    RVPVec &lookupTable,
    const TargetMachine *TM)
{
  std::string sampler = "unknown";
  assert(MI->getNumOperands() == 5 && "Only an "
      "image read instruction with 5 arguments can "
      "have a sampler.");
  assert(MI->getOperand(3).isReg() && 
      "Argument 3 must be a register to call this function");
  unsigned reg = MI->getOperand(3).getReg();
  // If this register points to an argument, then
  // we can return the argument name.
  if (lookupTable[reg].second && dyn_cast<Argument>(lookupTable[reg].second)) {
    return lookupTable[reg].second->getName();
  }
  // Otherwise the sampler is coming from memory somewhere.
  // If the sampler memory location can be tracked, then
  // we ascertain the sampler name that way.
  // The most common case is when optimizations are disabled
  // or mem2reg is not enabled, then the sampler when it is
  // an argument is passed through the frame index.

  // In the optimized case, the instruction that defined
  // register from operand #3 is a private load.
  MachineRegisterInfo &regInfo = MI->getParent()->getParent()->getRegInfo();
  assert(!regInfo.def_empty(reg) 
      && "We don't have any defs of this register, but we aren't an argument!");
  MachineOperand *defOp = regInfo.getRegUseDefListHead(reg);
  MachineInstr *defMI = defOp->getParent();
  if (isPrivateInst(TM->getInstrInfo(), defMI) && isLoadInst(TM->getInstrInfo(), defMI)) {
    if (defMI->getOperand(1).isFI()) {
      RegValPair &fiRVP = FIToPtrMap[reg];
      if (fiRVP.second && dyn_cast<Argument>(fiRVP.second)) {
        return fiRVP.second->getName();
      } else {
        // FIXME: Fix the case where the value stored is not a kernel argument.
        assert(!"Found a private load of a sampler where the value isn't an argument!");
      }
    } else {
      // FIXME: Fix the case where someone dynamically loads a sampler value
      // from private memory. This is problematic because we need to know the
      // sampler value at compile time and if it is dynamically loaded, we won't
      // know what sampler value to use.
      assert(!"Found a private load of a sampler that isn't from a frame index!");
    }
  } else {
    // FIXME: Handle the case where the def is neither a private instruction
    // and not a load instruction. This shouldn't occur, but putting an assertion
    // just to make sure that it doesn't.
    assert(!"Found a case which we don't handle.");
  }
  return sampler;
}

const char*
AMDILEGPointerManager::getPassName() const
{
  return "AMD IL EG Pointer Manager Pass";
}

// Helper function to determine if the current pointer is from the
// local, region or private address spaces.
  static bool
isLRPInst(MachineInstr *MI,
    const AMDILTargetMachine *ATM)
{
  const AMDILSubtarget *STM
    = ATM->getSubtargetImpl();
  if (!MI) {
    return false;
  }
  if ((isRegionInst(ATM->getInstrInfo(), MI) 
        && STM->device()->usesHardware(AMDILDeviceInfo::RegionMem))
      || (isLocalInst(ATM->getInstrInfo(), MI)
        && STM->device()->usesHardware(AMDILDeviceInfo::LocalMem))
      || (isPrivateInst(ATM->getInstrInfo(), MI)
        && STM->device()->usesHardware(AMDILDeviceInfo::PrivateMem))) {
    return true;
  }
  return false;
}

/// Helper function to determine if the I/O instruction uses
/// global device memory or not.
static bool
usesGlobal(
    const AMDILTargetMachine *ATM,
    MachineInstr *MI) {
  const AMDILSubtarget *STM
    = ATM->getSubtargetImpl();
  switch(MI->getOpcode()) {
    ExpandCaseToAllTypes(AMDIL::GLOBALSTORE);
    ExpandCaseToAllTruncTypes(AMDIL::GLOBALTRUNCSTORE);
    ExpandCaseToAllTypes(AMDIL::GLOBALLOAD);
    ExpandCaseToAllTypes(AMDIL::GLOBALSEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::GLOBALZEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::GLOBALAEXTLOAD);
    return true;
    ExpandCaseToAllTypes(AMDIL::REGIONLOAD);
    ExpandCaseToAllTypes(AMDIL::REGIONSEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::REGIONZEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::REGIONAEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::REGIONSTORE);
    ExpandCaseToAllTruncTypes(AMDIL::REGIONTRUNCSTORE);
    return !STM->device()->usesHardware(AMDILDeviceInfo::RegionMem);
    ExpandCaseToAllTypes(AMDIL::LOCALLOAD);
    ExpandCaseToAllTypes(AMDIL::LOCALSEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::LOCALZEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::LOCALAEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::LOCALSTORE);
    ExpandCaseToAllTruncTypes(AMDIL::LOCALTRUNCSTORE);
    return !STM->device()->usesHardware(AMDILDeviceInfo::LocalMem);
    ExpandCaseToAllTypes(AMDIL::CPOOLLOAD);
    ExpandCaseToAllTypes(AMDIL::CPOOLSEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::CPOOLZEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::CPOOLAEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::CONSTANTLOAD);
    ExpandCaseToAllTypes(AMDIL::CONSTANTSEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::CONSTANTAEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::CONSTANTZEXTLOAD);
    return !STM->device()->usesHardware(AMDILDeviceInfo::ConstantMem);
    ExpandCaseToAllTypes(AMDIL::PRIVATELOAD);
    ExpandCaseToAllTypes(AMDIL::PRIVATESEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::PRIVATEZEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::PRIVATEAEXTLOAD);
    ExpandCaseToAllTypes(AMDIL::PRIVATESTORE);
    ExpandCaseToAllTruncTypes(AMDIL::PRIVATETRUNCSTORE);
    return !STM->device()->usesHardware(AMDILDeviceInfo::PrivateMem);
    default:
    return false;
  }
  return false;
}

// Helper function that allocates the default resource ID for the
// respective I/O types.
static void
allocateDefaultID(
    const AMDILTargetMachine *ATM,
    AMDILAS::InstrResEnc &curRes,
    MachineInstr *MI,
    bool mDebug)
{
  AMDILMachineFunctionInfo *mMFI =
    MI->getParent()->getParent()->getInfo<AMDILMachineFunctionInfo>();
  const AMDILSubtarget *STM
    = ATM->getSubtargetImpl();
  if (mDebug) {
    dbgs() << "Assigning instruction to default ID. Inst:";
    MI->dump();
  }
  // If we use global memory, lets set the Operand to
  // the ARENA_UAV_ID.
  if (usesGlobal(ATM, MI)) {
    curRes.bits.ResourceID =
      STM->device()->getResourceID(AMDILDevice::GLOBAL_ID);
    if (isAtomicInst(ATM->getInstrInfo(), MI)) {
      MI->getOperand(MI->getNumOperands()-1)
        .setImm(curRes.bits.ResourceID);
    }
    AMDILKernelManager *KM = STM->getKernelManager();
    if (curRes.bits.ResourceID == 8 
        && !STM->device()->isSupported(AMDILDeviceInfo::ArenaSegment)) {
        KM->setUAVID(NULL, curRes.bits.ResourceID);
        mMFI->uav_insert(curRes.bits.ResourceID);
    }
  } else if (isPrivateInst(ATM->getInstrInfo(), MI)) {
    curRes.bits.ResourceID =
      STM->device()->getResourceID(AMDILDevice::SCRATCH_ID);
  } else if (isLocalInst(ATM->getInstrInfo(), MI) || isLocalAtomic(ATM->getInstrInfo(), MI)) {
    curRes.bits.ResourceID =
      STM->device()->getResourceID(AMDILDevice::LDS_ID);
    AMDILMachineFunctionInfo *mMFI = 
    MI->getParent()->getParent()->getInfo<AMDILMachineFunctionInfo>();
    mMFI->setUsesLocal();
    if (isAtomicInst(ATM->getInstrInfo(), MI)) {
      assert(curRes.bits.ResourceID && "Atomic resource ID "
          "cannot be zero!");
      MI->getOperand(MI->getNumOperands()-1)
        .setImm(curRes.bits.ResourceID);
    }
  } else if (isRegionInst(ATM->getInstrInfo(), MI) || isRegionAtomic(ATM->getInstrInfo(), MI)) {
    curRes.bits.ResourceID =
      STM->device()->getResourceID(AMDILDevice::GDS_ID);
    AMDILMachineFunctionInfo *mMFI = 
    MI->getParent()->getParent()->getInfo<AMDILMachineFunctionInfo>();
    mMFI->setUsesRegion();
    if (isAtomicInst(ATM->getInstrInfo(), MI)) {
      assert(curRes.bits.ResourceID && "Atomic resource ID "
          "cannot be zero!");
      (MI)->getOperand((MI)->getNumOperands()-1)
        .setImm(curRes.bits.ResourceID);
    }
  } else if (isConstantInst(ATM->getInstrInfo(), MI)) {
    // If we are unknown constant instruction and the base pointer is known.
    // Set the resource ID accordingly, otherwise use the default constant ID.
    // FIXME: this should not require the base pointer to know what constant
    // it is from.
    AMDILGlobalManager *GM = STM->getGlobalManager();
    MachineFunction *MF = MI->getParent()->getParent();
    if (GM->isKernel(MF->getFunction()->getName())) {
      const kernel &krnl = GM->getKernel(MF->getFunction()->getName());
      const Value *V = getBasePointerValue(MI);
      if (V && !dyn_cast<AllocaInst>(V)) {
        curRes.bits.ResourceID = GM->getConstPtrCB(krnl, V->getName());
        curRes.bits.HardwareInst = 1;
      } else if (V && dyn_cast<AllocaInst>(V)) {
          // FIXME: Need a better way to fix this. Requires a rewrite of how
          // we lower global addresses to various address spaces.
          // So for now, lets assume that there is only a single 
          // constant buffer that can be accessed from a load instruction
          // that is derived from an alloca instruction.
          curRes.bits.ResourceID = 2;
          curRes.bits.HardwareInst = 1;
      } else {
        if (isStoreInst(ATM->getInstrInfo(), MI)) {
          if (mDebug) {
            dbgs() << __LINE__ << ": Setting byte store bit on instruction: ";
            MI->dump();
          }
          curRes.bits.ByteStore = 1;
        }
        curRes.bits.ResourceID = STM->device()->getResourceID(AMDILDevice::CONSTANT_ID);
      }
    } else {
      if (isStoreInst(ATM->getInstrInfo(), MI)) {
        if (mDebug) {
          dbgs() << __LINE__ << ": Setting byte store bit on instruction: ";
          MI->dump();
        }
        curRes.bits.ByteStore = 1;
      }
      curRes.bits.ResourceID = STM->device()->getResourceID(AMDILDevice::GLOBAL_ID);
      AMDILKernelManager *KM = STM->getKernelManager();
      KM->setUAVID(NULL, curRes.bits.ResourceID);
      mMFI->uav_insert(curRes.bits.ResourceID);
    }
  } else if (isAppendInst(ATM->getInstrInfo(), MI)) {
    unsigned opcode = MI->getOpcode();
    if (opcode == AMDIL::APPEND_ALLOC
        || opcode == AMDIL::APPEND_ALLOC_NORET) {
      curRes.bits.ResourceID = 1;
    } else {
      curRes.bits.ResourceID = 2;
    }
  }
  setAsmPrinterFlags(MI, curRes);
}

// Function that parses the arguments and updates the lookupTable with the
// pointer -> register mapping. This function also checks for cacheable
// pointers and updates the CacheableSet with the arguments that
// can be cached based on the readonlypointer annotation. The final
// purpose of this function is to update the imageSet and counterSet
// with all pointers that are either images or atomic counters.
uint32_t
parseArguments(MachineFunction &MF,
    RVPVec &lookupTable,
    const AMDILTargetMachine *ATM,
    CacheableSet &cacheablePtrs,
    ImageSet &imageSet,
    AppendSet &counterSet,
    bool mDebug)
{
  const AMDILSubtarget *STM
    = ATM->getSubtargetImpl();
  uint32_t writeOnlyImages = 0;
  uint32_t readOnlyImages = 0;
  std::string cachedKernelName = "llvm.readonlypointer.annotations.";
  cachedKernelName.append(MF.getFunction()->getName());
  GlobalVariable *GV = MF.getFunction()->getParent()
    ->getGlobalVariable(cachedKernelName);
  unsigned cbNum = 0;
  unsigned regNum = AMDIL::R1;
  AMDILMachineFunctionInfo *mMFI = MF.getInfo<AMDILMachineFunctionInfo>();
  for (Function::const_arg_iterator I = MF.getFunction()->arg_begin(),
      E = MF.getFunction()->arg_end(); I != E; ++I) {
    const Argument *curArg = I;
    if (mDebug) {
      dbgs() << "Argument: ";
      curArg->dump();
    }
    Type *curType = curArg->getType();
    // We are either a scalar or vector type that
    // is passed by value that is not a opaque/struct
    // type. We just need to increment regNum
    // the correct number of times to match the number
    // of registers that it takes up.
    if (curType->isFPOrFPVectorTy() ||
        curType->isIntOrIntVectorTy()) {
      // We are scalar, so increment once and
      // move on
      if (!curType->isVectorTy()) {
        lookupTable[regNum] = std::make_pair<unsigned, const Value*>(~0U, curArg);
        ++regNum;
        ++cbNum;
        continue;
      }
      VectorType *VT = dyn_cast<VectorType>(curType);
      // We are a vector type. If we are 64bit type, then
      // we increment length / 2 times, otherwise we
      // increment length / 4 times. The only corner case
      // is with vec3 where the vector gets scalarized and
      // therefor we need a loop count of 3.
      size_t loopCount = VT->getNumElements();
      if (loopCount != 3) {
        if (VT->getScalarSizeInBits() == 64) {
          loopCount = loopCount >> 1;
        } else {
          loopCount = (loopCount + 2) >> 2;
        }
        cbNum += loopCount;
      } else {
        cbNum++;
      }
      while (loopCount--) {
        lookupTable[regNum] = std::make_pair<unsigned, const Value*>(~0U, curArg);
        ++regNum;
      }
    } else if (curType->isPointerTy()) {
      Type *CT = dyn_cast<PointerType>(curType)->getElementType();
      const StructType *ST = dyn_cast<StructType>(CT);
      if (ST && ST->isOpaque()) {
        StringRef name = ST->getName();
        bool i1d_type  = name == "struct._image1d_t";
        bool i1da_type = name == "struct._image1d_array_t";
        bool i1db_type = name == "struct._image1d_buffer_t";
        bool i2d_type  = name == "struct._image2d_t";
        bool i2da_type = name == "struct._image2d_array_t";
        bool i3d_type  = name == "struct._image3d_t";
        bool c32_type  = name == "struct._counter32_t";
        bool c64_type  = name == "struct._counter64_t";
        if (i2d_type || i3d_type || i2da_type ||
            i1d_type || i1db_type || i1da_type) {
          imageSet.insert(I);
          uint32_t imageNum = readOnlyImages + writeOnlyImages;
          if (STM->getGlobalManager()
              ->isReadOnlyImage(MF.getFunction()->getName(), imageNum)) {
            if (mDebug) {
              dbgs() << "Pointer: '" << curArg->getName()
                << "' is a read only image # " << readOnlyImages << "!\n";
            }
            // We store the cbNum along with the image number so that we can
            // correctly encode the 'info' intrinsics.
            lookupTable[regNum] = std::make_pair<unsigned, const Value*>
              ((cbNum << 16 | readOnlyImages++), curArg);
          } else if (STM->getGlobalManager()
              ->isWriteOnlyImage(MF.getFunction()->getName(), imageNum)) {
            if (mDebug) {
              dbgs() << "Pointer: '" << curArg->getName()
                << "' is a write only image # " << writeOnlyImages << "!\n";
            }
            // We store the cbNum along with the image number so that we can
            // correctly encode the 'info' intrinsics.
            lookupTable[regNum] = std::make_pair<unsigned, const Value*>
              ((cbNum << 16 | writeOnlyImages++), curArg);
          } else {
            assert(!"Read/Write images are not supported!");
          }
          ++regNum;
          cbNum += 2;
          continue;
        } else if (c32_type || c64_type) {
          if (mDebug) {
            dbgs() << "Pointer: '" << curArg->getName()
              << "' is a " << (c32_type ? "32" : "64")
              << " bit atomic counter type!\n";
          }
          counterSet.push_back(I);
        }
      }

      if (STM->device()->isSupported(AMDILDeviceInfo::CachedMem) 
          && GV && GV->hasInitializer()) {
        const ConstantArray *nameArray 
          = dyn_cast_or_null<ConstantArray>(GV->getInitializer());
        if (nameArray) {
          for (unsigned x = 0, y = nameArray->getNumOperands(); x < y; ++x) {
            const GlobalVariable *gV= dyn_cast_or_null<GlobalVariable>(
                nameArray->getOperand(x)->getOperand(0));
            const ConstantDataArray *argName =
              dyn_cast_or_null<ConstantDataArray>(gV->getInitializer());
            if (!argName) {
              continue;
            }
            std::string argStr = argName->getAsString();
            std::string curStr = curArg->getName();
            if (!strcmp(argStr.data(), curStr.data())) {
              if (mDebug) {
                dbgs() << "Pointer: '" << curArg->getName() 
                  << "' is cacheable!\n";
              }
              cacheablePtrs.insert(curArg);
            }
          }
        }
      }
      uint32_t as = dyn_cast<PointerType>(curType)->getAddressSpace();
      // Handle the case where the kernel argument is a pointer
      if (mDebug) {
        dbgs() << "Pointer: " << curArg->getName() << " is assigned ";
        if (as == AMDILAS::GLOBAL_ADDRESS) {
          dbgs() << "uav " << STM->device()
            ->getResourceID(AMDILDevice::GLOBAL_ID);
        } else if (as == AMDILAS::PRIVATE_ADDRESS) {
          dbgs() << "scratch " << STM->device()
            ->getResourceID(AMDILDevice::SCRATCH_ID);
        } else if (as == AMDILAS::LOCAL_ADDRESS) {
          dbgs() << "lds " << STM->device()
            ->getResourceID(AMDILDevice::LDS_ID);
        } else if (as == AMDILAS::CONSTANT_ADDRESS) {
          dbgs() << "cb " << STM->device()
            ->getResourceID(AMDILDevice::CONSTANT_ID);
        } else if (as == AMDILAS::REGION_ADDRESS) {
          dbgs() << "gds " << STM->device()
            ->getResourceID(AMDILDevice::GDS_ID);
        } else {
          assert(!"Found an address space that we don't support!");
        }
        dbgs() << " @ register " << regNum << ". Inst: ";
        curArg->dump();
      }
      switch (as) {
        default:
          lookupTable[regNum] = std::make_pair<unsigned, const Value*>
            (STM->device()->getResourceID(AMDILDevice::GLOBAL_ID), curArg);
          break;
        case AMDILAS::LOCAL_ADDRESS:
          lookupTable[regNum] = std::make_pair<unsigned, const Value*>
            (STM->device()->getResourceID(AMDILDevice::LDS_ID), curArg);
          mMFI->setHasLocalArg();
          break;
        case AMDILAS::REGION_ADDRESS:
          lookupTable[regNum] = std::make_pair<unsigned, const Value*>
            (STM->device()->getResourceID(AMDILDevice::GDS_ID), curArg);
          mMFI->setHasRegionArg();
          break;
        case AMDILAS::CONSTANT_ADDRESS:
          lookupTable[regNum] = std::make_pair<unsigned, const Value*>
            (STM->device()->getResourceID(AMDILDevice::CONSTANT_ID), curArg);
          break;
        case AMDILAS::PRIVATE_ADDRESS:
          lookupTable[regNum] = std::make_pair<unsigned, const Value*>
            (STM->device()->getResourceID(AMDILDevice::SCRATCH_ID), curArg);
          break;
      }
      // In this case we need to increment it once.
      ++regNum;
      ++cbNum;
    } else {
      // Is anything missing that is legal in CL?
      assert(0 && "Current type is not supported!");
      lookupTable[regNum] = std::make_pair<unsigned, const Value*>
        (STM->device()->getResourceID(AMDILDevice::GLOBAL_ID), curArg);
      ++regNum;
      ++cbNum;
    }
  }
  return writeOnlyImages;
}
// The call stack is interesting in that even in SSA form, it assigns
// registers to the same value's over and over again. So we need to
// ignore the values that are assigned and just deal with the input
// and return registers.
static void
parseCall(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    RVPVec &lookupTable,
    MachineBasicBlock::iterator &mBegin,
    MachineBasicBlock::iterator mEnd,
    bool mDebug)
{
  SmallVector<unsigned, 8> inputRegs;
  AMDILAS::InstrResEnc curRes;
  if (mDebug) {
    dbgs() << "Parsing Call Stack Start.\n";
  }
  MachineBasicBlock::iterator callInst = mBegin;
  MachineInstr *CallMI = callInst;
  getAsmPrinterFlags(CallMI, curRes);
  MachineInstr *MI = --mBegin;
  unsigned reg = AMDIL::R1;
  // First we need to check the input registers.
  do {
    // We stop if we hit the beginning of the call stack
    // adjustment.
    if (MI->getOpcode() == AMDIL::ADJCALLSTACKDOWN
        || MI->getOpcode() == AMDIL::ADJCALLSTACKUP
        || MI->getNumOperands() != 2
        || !MI->getOperand(0).isReg()) {
      break;
    }
    reg = MI->getOperand(0).getReg();
    if (MI->getOperand(1).isReg()) {
      unsigned reg1 = MI->getOperand(1).getReg();
      inputRegs.push_back(reg1);
      if (lookupTable[reg1].second) {
        curRes.bits.PointerPath = 1;
      }
    }
    lookupTable.erase(reg);
    if ((signed)reg < 0 
    || mBegin == CallMI->getParent()->begin()) {
      break;
    }
    MI = --mBegin;
  } while (1);
  mBegin = callInst;
  MI = ++mBegin;
  // If the next registers operand 1 is not a register or that register
  // is not R1, then we don't have any return values.
  if (MI->getNumOperands() == 2 
      && MI->getOperand(1).isReg() 
      && MI->getOperand(1).getReg() == AMDIL::R1) {
    // Next we check the output register.
    reg = MI->getOperand(0).getReg();
    // Now we link the inputs to the output.
    for (unsigned x = 0; x < inputRegs.size(); ++x) {
      if (lookupTable[inputRegs[x]].second) {
        curRes.bits.PointerPath = 1;
        lookupTable[reg] = lookupTable[inputRegs[x]];
        InstToPtrMap[CallMI].insert(
            lookupTable[reg].second);
        break;
      }
    }
    lookupTable.erase(MI->getOperand(1).getReg());
  }
  setAsmPrinterFlags(CallMI, curRes);
  if (mDebug) {
    dbgs() << "Parsing Call Stack End.\n";
  }
  return;
}

// Detect if the current instruction conflicts with another instruction
// and add the instruction to the correct location accordingly.
static void
detectConflictInst(
    MachineInstr *MI,
    AMDILAS::InstrResEnc &curRes,
    RVPVec &lookupTable,
    InstPMap &InstToPtrMap,
    bool isLoadStore,
    unsigned reg,
    unsigned dstReg,
    bool mDebug)
{
  // If the instruction does not have a point path flag
  // associated with it, then we know that no other pointer
  // hits this instruciton.
  if (!curRes.bits.PointerPath) {
    if (dyn_cast<PointerType>(lookupTable[reg].second->getType())) {
      curRes.bits.PointerPath = 1;
    }
    // We don't want to transfer to the register number
    // between load/store because the load dest can be completely
    // different pointer path and the store doesn't have a real
    // destination register.
    if (!isLoadStore) {
      if (mDebug) {
        if (dyn_cast<PointerType>(lookupTable[reg].second->getType())) {
          dbgs() << "Pointer: " << lookupTable[reg].second->getName();
          assert(dyn_cast<PointerType>(lookupTable[reg].second->getType())
              && "Must be a pointer type for an instruction!");
          switch (dyn_cast<PointerType>(
                lookupTable[reg].second->getType())->getAddressSpace())
          {
            case AMDILAS::GLOBAL_ADDRESS:  dbgs() << " UAV: "; break;
            case AMDILAS::LOCAL_ADDRESS: dbgs() << " LDS: "; break;
            case AMDILAS::REGION_ADDRESS: dbgs() << " GDS: "; break;
            case AMDILAS::PRIVATE_ADDRESS: dbgs() << " SCRATCH: "; break;
            case AMDILAS::CONSTANT_ADDRESS: dbgs() << " CB: "; break;

          }
          dbgs() << lookupTable[reg].first << " Reg: " << reg
            << " assigned to reg " << dstReg << ". Inst: ";
          MI->dump();
        }
      }
      // We don't want to do any copies if the register is not virtual
      // as it is the result of a CALL. ParseCallInst handles the
      // case where the input and output need to be linked up 
      // if it occurs. The easiest way to check for virtual
      // is to check the top bit.
      lookupTable[dstReg] = lookupTable[reg];
    }
  } else {
    if (dyn_cast<PointerType>(lookupTable[reg].second->getType())) {
      // Otherwise we have a conflict between two pointers somehow.
      curRes.bits.ConflictPtr = 1;
      if (mDebug) {
        dbgs() << "Pointer: " << lookupTable[reg].second->getName();
        assert(dyn_cast<PointerType>(lookupTable[reg].second->getType())
            && "Must be a pointer type for a conflict instruction!");
        switch (dyn_cast<PointerType>(
              lookupTable[reg].second->getType())->getAddressSpace())
        {
          case AMDILAS::GLOBAL_ADDRESS:  dbgs() << " UAV: "; break;
          case AMDILAS::LOCAL_ADDRESS: dbgs() << " LDS: "; break;
          case AMDILAS::REGION_ADDRESS: dbgs() << " GDS: "; break;
          case AMDILAS::PRIVATE_ADDRESS: dbgs() << " SCRATCH: "; break;
          case AMDILAS::CONSTANT_ADDRESS: dbgs() << " CB: "; break;

        }
        dbgs() << lookupTable[reg].first << " Reg: " << reg;
        if (InstToPtrMap[MI].size() > 1) {
          dbgs() << " conflicts with:\n ";
          for (PtrSet::iterator psib = InstToPtrMap[MI].begin(),
              psie = InstToPtrMap[MI].end(); psib != psie; ++psib) {
            dbgs() << "\t\tPointer: " << (*psib)->getName() << " ";
            assert(dyn_cast<PointerType>((*psib)->getType())
                && "Must be a pointer type for a conflict instruction!");
            (*psib)->dump();
          }
        } else {
          dbgs() << ".";
        }
        dbgs() << " Inst: ";
        MI->dump();
      }
    }
    // Add the conflicting values to the pointer set for the instruction
    InstToPtrMap[MI].insert(lookupTable[reg].second);
    // We don't want to add the destination register if
    // we are a load or store.
    if (!isLoadStore) {
      InstToPtrMap[MI].insert(lookupTable[dstReg].second);
    }
  }
  setAsmPrinterFlags(MI, curRes);
}

// In this case we want to handle a load instruction.
static void
parseLoadInst(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    FIPMap &FIToPtrMap,
    RVPVec &lookupTable,
    CPoolSet &cpool,
    BlockCacheableInfo &bci,
    MachineInstr *MI,
    bool mDebug)
{
  assert(isLoadInst(ATM->getInstrInfo(), MI) && "Only a load instruction can be parsed by "
      "the parseLoadInst function.");
  AMDILAS::InstrResEnc curRes;
  getAsmPrinterFlags(MI, curRes);
  unsigned dstReg = MI->getOperand(0).getReg();
  unsigned idx = 0;
  const Value *basePtr = NULL;
  if (MI->getOperand(1).isReg()) {
    idx = MI->getOperand(1).getReg();
    basePtr = lookupTable[idx].second;
    // If we don't know what value the register
    // is assigned to, then we need to special case
    // this instruction.
  } else if (MI->getOperand(1).isFI()) {
    idx = MI->getOperand(1).getIndex();
    lookupTable[dstReg] = FIToPtrMap[idx];
  } else if (MI->getOperand(1).isCPI()) {
    cpool.insert(MI);
  } 
  // If we are a hardware local, then we don't need to track as there
  // is only one resource ID that we need to know about, so we
  // map it using allocateDefaultID, which maps it to the default.
  // This is also the case for REGION_ADDRESS and PRIVATE_ADDRESS.
  if (isLRPInst(MI, ATM) || !basePtr) {
    allocateDefaultID(ATM, curRes, MI, mDebug);
    return;
  }
  // We have a load instruction so we map this instruction
  // to the pointer and insert it into the set of known
  // load instructions.
  InstToPtrMap[MI].insert(basePtr);
  PtrToInstMap[basePtr].push_back(MI);

  if (isGlobalInst(ATM->getInstrInfo(), MI)) {
    // Add to the cacheable set for the block. If there was a store earlier
    // in the block, this call won't actually add it to the cacheable set.
    bci.addPossiblyCacheableInst(ATM, MI);
  }

  if (mDebug) {
    dbgs() << "Assigning instruction to pointer ";
    dbgs() << basePtr->getName() << ". Inst: ";
    MI->dump();
  }
  detectConflictInst(MI, curRes, lookupTable, InstToPtrMap, true,
      idx, dstReg, mDebug);
}

// In this case we want to handle a store instruction.
static void
parseStoreInst(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    FIPMap &FIToPtrMap,
    RVPVec &lookupTable,
    CPoolSet &cpool,
    BlockCacheableInfo &bci,
    MachineInstr *MI,
    ByteSet &bytePtrs,
    ConflictSet &conflictPtrs,
    bool mDebug)
{
  assert(isStoreInst(ATM->getInstrInfo(), MI) && "Only a store instruction can be parsed by "
      "the parseStoreInst function.");
  AMDILAS::InstrResEnc curRes;
  getAsmPrinterFlags(MI, curRes);
  unsigned dstReg = MI->getOperand(0).getReg();

  // If the data part of the store instruction is known to
  // be a pointer, then we need to mark this pointer as being
  // a byte pointer. This is the conservative case that needs
  // to be handled correctly.
  if (lookupTable[dstReg].second && lookupTable[dstReg].first != ~0U) {
    curRes.bits.ConflictPtr = 1;
    if (mDebug) {
      dbgs() << "Found a case where the pointer is being stored!\n";
      MI->dump();
      dbgs() << "Pointer is ";
      lookupTable[dstReg].second->print(dbgs());
      dbgs() << "\n";
    }
    //PtrToInstMap[lookupTable[dstReg].second].push_back(MI);
    if (lookupTable[dstReg].second->getType()->isPointerTy()) {
      conflictPtrs.insert(lookupTable[dstReg].second);
    }
  }

  // Before we go through the special cases, for the cacheable information
  // all we care is if the store if global or not.
  if (!isLRPInst(MI, ATM)) {
    bci.setReachesExit();
  }

  // If the address is not a register address,
  // then we need to lower it as an unknown id.
  if (!MI->getOperand(1).isReg()) {
    if (MI->getOperand(1).isCPI()) {
      if (mDebug) {
        dbgs() << "Found an instruction with a CPI index #"
          << MI->getOperand(1).getIndex() << "!\n";
      }
      cpool.insert(MI);
    } else if (MI->getOperand(1).isFI()) {
      if (mDebug) {
        dbgs() << "Found an instruction with a frame index #"
          << MI->getOperand(1).getIndex() << "!\n";
      }
      // If we are a frame index and we are storing a pointer there, lets
      // go ahead and assign the pointer to the location within the frame
      // index map so that we can get the value out later.
      FIToPtrMap[MI->getOperand(1).getIndex()] = lookupTable[dstReg];
    }

    allocateDefaultID(ATM, curRes, MI, mDebug);
    return;
  }
  unsigned reg = MI->getOperand(1).getReg();
  // If we don't know what value the register
  // is assigned to, then we need to special case
  // this instruction.
  if (!lookupTable[reg].second) {
    allocateDefaultID(ATM, curRes, MI, mDebug);
    return;
  }
  // const Value *basePtr = lookupTable[reg].second;
  // If we are a hardware local, then we don't need to track as there
  // is only one resource ID that we need to know about, so we
  // map it using allocateDefaultID, which maps it to the default.
  // This is also the case for REGION_ADDRESS and PRIVATE_ADDRESS.
  if (isLRPInst(MI, ATM)) {
    allocateDefaultID(ATM, curRes, MI, mDebug);
    return;
  }

  // We have a store instruction so we map this instruction
  // to the pointer and insert it into the set of known
  // store instructions.
  InstToPtrMap[MI].insert(lookupTable[reg].second);
  PtrToInstMap[lookupTable[reg].second].push_back(MI);
  uint16_t RegClass = MI->getDesc().OpInfo[0].RegClass;
  switch (RegClass) {
    default:
      break;
    case AMDIL::GPRI8RegClassID:
    case AMDIL::GPRV2I8RegClassID:
    case AMDIL::GPRI16RegClassID:
      if (usesGlobal(ATM, MI)) {
        if (mDebug) {
          dbgs() << "Annotating instruction as Byte Store. Inst: ";
          MI->dump();
        }
        curRes.bits.ByteStore = 1;
        setAsmPrinterFlags(MI, curRes);
        const PointerType *PT = dyn_cast<PointerType>(
            lookupTable[reg].second->getType());
        if (PT) {
          bytePtrs.insert(lookupTable[reg].second);
        }
      }
      break;
  };
  // If we are a truncating store, then we need to determine the
  // size of the pointer that we are truncating to, and if we
  // are less than 32 bits, we need to mark the pointer as a
  // byte store pointer.
  switch (MI->getOpcode()) {
    case AMDIL::GLOBALTRUNCSTORE_i16i8:
    case AMDIL::GLOBALTRUNCSTORE_v2i16i8:
    case AMDIL::GLOBALTRUNCSTORE_i32i8:
    case AMDIL::GLOBALTRUNCSTORE_v2i32i8:
    case AMDIL::GLOBALTRUNCSTORE_i64i8:
    case AMDIL::GLOBALTRUNCSTORE_v2i64i8:
    case AMDIL::GLOBALTRUNCSTORE_i32i16:
    case AMDIL::GLOBALTRUNCSTORE_i64i16:
    case AMDIL::GLOBALSTORE_i8:
    case AMDIL::GLOBALSTORE_i16:
      curRes.bits.ByteStore = 1;
      setAsmPrinterFlags(MI, curRes);
      bytePtrs.insert(lookupTable[reg].second);
      break;
    default:
      break;
  }

  if (mDebug) {
    dbgs() << "Assigning instruction to pointer ";
    dbgs() << lookupTable[reg].second->getName() << ". Inst: ";
    MI->dump();
  }
  detectConflictInst(MI, curRes, lookupTable, InstToPtrMap, true,
      reg, dstReg, mDebug);
}

// In this case we want to handle an atomic instruction.
static void
parseAtomicInst(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    RVPVec &lookupTable,
    BlockCacheableInfo &bci,
    MachineInstr *MI,
    ByteSet &bytePtrs,
    bool mDebug)
{
  assert(isAtomicInst(ATM->getInstrInfo(), MI) && "Only an atomic instruction can be parsed by "
      "the parseAtomicInst function.");
  AMDILAS::InstrResEnc curRes;
  unsigned dstReg = MI->getOperand(0).getReg();
  unsigned reg = 0;
  getAsmPrinterFlags(MI, curRes);
  unsigned numOps = MI->getNumOperands();
  bool found = false;
  while (--numOps) {
    MachineOperand &Op = MI->getOperand(numOps);
    if (!Op.isReg()) {
      continue;
    }
    reg = Op.getReg();
    // If the register is not known to be owned by a pointer
    // then we can ignore it
    if (!lookupTable[reg].second) {
      continue;
    }
    // if the pointer is known to be local, region or private, then we
    // can ignore it.  Although there are no private atomics, we still
    // do this check so we don't have to write a new function to check
    // for only local and region.
    if (isLRPInst(MI, ATM)) {
      continue;
    }
    found = true;
    InstToPtrMap[MI].insert(lookupTable[reg].second);
    PtrToInstMap[lookupTable[reg].second].push_back(MI);

	// We now know we have an atomic operation on global memory.
	// This is a store so must update the cacheable information.
    bci.setReachesExit();

	// Only do if have SC with arena atomic bug fix (EPR 326883).
	// TODO: enable once SC with EPR 326883 has been promoted to CAL.
    if (ATM->getSubtargetImpl()->calVersion() >= CAL_VERSION_SC_150) {
      // Force pointers that are used by atomics to be in the arena.
      // If they were allowed to be accessed as RAW they would cause
      // all access to use the slow complete path.
      if (mDebug) {
        dbgs() << __LINE__ << ": Setting byte store bit on atomic instruction: ";
        MI->dump();
      }
	  curRes.bits.ByteStore = 1;
      bytePtrs.insert(lookupTable[reg].second);
	}

    if (mDebug) {
      dbgs() << "Assigning instruction to pointer ";
      dbgs() << lookupTable[reg].second->getName() << ". Inst: ";
      MI->dump();
    }
    detectConflictInst(MI, curRes, lookupTable, InstToPtrMap, true,
        reg, dstReg, mDebug);
  }
  if (!found) {
    allocateDefaultID(ATM, curRes, MI, mDebug);
  }
}
// In this case we want to handle a counter instruction.
static void
parseAppendInst(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    RVPVec &lookupTable,
    MachineInstr *MI,
    bool mDebug)
{
  assert(isAppendInst(ATM->getInstrInfo(), MI) && "Only an atomic counter instruction can be "
      "parsed by the parseAppendInst function.");
  AMDILAS::InstrResEnc curRes;
  unsigned dstReg = MI->getOperand(0).getReg();
  unsigned reg = MI->getOperand(1).getReg();
  getAsmPrinterFlags(MI, curRes);
  // If the register is not known to be owned by a pointer
  // then we set it to the default
  if (!lookupTable[reg].second) {
    allocateDefaultID(ATM, curRes, MI, mDebug);
    return;
  }
  InstToPtrMap[MI].insert(lookupTable[reg].second);
  PtrToInstMap[lookupTable[reg].second].push_back(MI);
  if (mDebug) {
    dbgs() << "Assigning instruction to pointer ";
    dbgs() << lookupTable[reg].second->getName() << ". Inst: ";
    MI->dump();
  }
  detectConflictInst(MI, curRes, lookupTable, InstToPtrMap, true,
      reg, dstReg, mDebug);
}
// In this case we want to handle an Image instruction.
static void
parseImageInst(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    FIPMap &FIToPtrMap,
    RVPVec &lookupTable,
    MachineInstr *MI,
    bool mDebug)
{
  assert(isImageInst(ATM->getInstrInfo(), MI) && "Only an image instruction can be "
      "parsed by the parseImageInst function.");
  AMDILAS::InstrResEnc curRes;
  getAsmPrinterFlags(MI, curRes);
  // AMDILKernelManager *km = 
  //   (AMDILKernelManager *)ATM->getSubtargetImpl()->getKernelManager();
  AMDILMachineFunctionInfo *mMFI = MI->getParent()->getParent()
    ->getInfo<AMDILMachineFunctionInfo>();
  if (MI->getOpcode() == AMDIL::IMAGE2D_WRITE
      || MI->getOpcode() == AMDIL::IMAGE3D_WRITE) {
    unsigned dstReg = MI->getOperand(0).getReg();
    curRes.bits.ResourceID = lookupTable[dstReg].first & 0xFFFF;
    curRes.bits.isImage = 1;
    InstToPtrMap[MI].insert(lookupTable[dstReg].second);
    PtrToInstMap[lookupTable[dstReg].second].push_back(MI);
    if (mDebug) {
      dbgs() << "Assigning instruction to pointer ";
      dbgs() << lookupTable[dstReg].second->getName() << ". Inst: ";
      MI->dump();
    }
  } else {
    // unsigned dstReg = MI->getOperand(0).getReg();
    unsigned reg = MI->getOperand(1).getReg();

    // If the register is not known to be owned by a pointer
    // then we set it to the default
    if (!lookupTable[reg].second) {
      assert(!"This should not happen for images!");
      allocateDefaultID(ATM, curRes, MI, mDebug);
      return;
    }
    InstToPtrMap[MI].insert(lookupTable[reg].second);
    PtrToInstMap[lookupTable[reg].second].push_back(MI);
    if (mDebug) {
      dbgs() << "Assigning instruction to pointer ";
      dbgs() << lookupTable[reg].second->getName() << ". Inst: ";
      MI->dump();
    }    
    switch (MI->getOpcode()) {
      case AMDIL::IMAGE2D_READ:
      case AMDIL::IMAGE2D_READ_UNNORM:
      case AMDIL::IMAGE3D_READ:
      case AMDIL::IMAGE3D_READ_UNNORM:
        curRes.bits.ResourceID = lookupTable[reg].first & 0xFFFF;
        if (MI->getOperand(3).isReg()) {
          // Our sampler is not a literal value.
          char buffer[256];
          memset(buffer, 0, sizeof(buffer));
          std::string sampler_name = "";
          unsigned reg = MI->getOperand(3).getReg();
          if (lookupTable[reg].second) {
            sampler_name = lookupTable[reg].second->getName();
          }
          if (sampler_name.empty()) {
            sampler_name = findSamplerName(MI, lookupTable, FIToPtrMap, ATM);
          }
          uint32_t val = mMFI->addSampler(sampler_name, ~0U);
          if (mDebug) {
            dbgs() << "Mapping kernel sampler " << sampler_name
              << " to sampler number " << val << " for Inst:\n";
            MI->dump();
          }
          MI->getOperand(3).ChangeToImmediate(val);
        } else {
          // Our sampler is known at runtime as a literal, lets make sure
          // that the metadata for it is known.
          char buffer[256];
          memset(buffer, 0, sizeof(buffer));
          sprintf(buffer,"_%d", (int32_t)MI->getOperand(3).getImm());
          std::string sampler_name = std::string("unknown") + std::string(buffer);
          uint32_t val = mMFI->addSampler(sampler_name, MI->getOperand(3).getImm());
          if (mDebug) {
            dbgs() << "Mapping internal sampler " << sampler_name 
              << " to sampler number " << val << " for Inst:\n";
            MI->dump();
          }
          MI->getOperand(3).setImm(val);
        }
        break;
      case AMDIL::IMAGE2D_INFO0:
      case AMDIL::IMAGE3D_INFO0:
        curRes.bits.ResourceID = lookupTable[reg].first >> 16;
        break;
      case AMDIL::IMAGE2D_INFO1:
      case AMDIL::IMAGE2DA_INFO1:
        curRes.bits.ResourceID = (lookupTable[reg].first >> 16) + 1;
        break;
    };
    curRes.bits.isImage = 1;
  }
  setAsmPrinterFlags(MI, curRes);
}
// This case handles the rest of the instructions
static void
parseInstruction(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    RVPVec &lookupTable,
    CPoolSet &cpool,
    MachineInstr *MI,
    bool mDebug)
{
  assert(!isAtomicInst(ATM->getInstrInfo(), MI) && !isStoreInst(ATM->getInstrInfo(), MI) && !isLoadInst(ATM->getInstrInfo(), MI) &&
      !isAppendInst(ATM->getInstrInfo(), MI) && !isImageInst(ATM->getInstrInfo(), MI) &&
      "Atomic/Load/Store/Append/Image insts should not be handled here!");
  unsigned numOps = MI->getNumOperands();
  // If we don't have any operands, we can skip this instruction
  if (!numOps) {
    return;
  }
  // if the dst operand is not a register, then we can skip
  // this instruction. That is because we are probably a branch
  // or jump instruction.
  if (!MI->getOperand(0).isReg()) {
    return;
  }
  // If we are a LOADCONST_i32, we might be a sampler, so we need
  // to propogate the LOADCONST to IMAGE[2|3]D_READ instructions.
  if (MI->getOpcode() == AMDIL::LOADCONST_i32) {
    uint32_t val = MI->getOperand(1).getImm();
    MachineOperand* oldPtr = &MI->getOperand(0);
    MachineOperand* moPtr = oldPtr->getNextOperandForReg();
    while (moPtr) {
      oldPtr = moPtr;
      moPtr = oldPtr->getNextOperandForReg();
      switch (oldPtr->getParent()->getOpcode()) {
        default:
          break;
        case AMDIL::IMAGE2D_READ:
        case AMDIL::IMAGE2D_READ_UNNORM:
        case AMDIL::IMAGE3D_READ:
        case AMDIL::IMAGE3D_READ_UNNORM:
          if (mDebug) {
            dbgs() << "Found a constant sampler for image read inst: ";
            oldPtr->getParent()->print(dbgs());
          }
          oldPtr->ChangeToImmediate(val);
          break;
      }
    }
  }
  AMDILAS::InstrResEnc curRes;
  getAsmPrinterFlags(MI, curRes);
  unsigned dstReg = MI->getOperand(0).getReg();
  unsigned reg = 0;
  while (--numOps) {
    MachineOperand &Op = MI->getOperand(numOps);
    // if the operand is not a register, then we can ignore it
    if (!Op.isReg()) {
      if (Op.isCPI()) {
        cpool.insert(MI);
      }
      continue;
    }
    reg = Op.getReg();
    // If the register is not known to be owned by a pointer
    // then we can ignore it
    if (!lookupTable[reg].second) {
      continue;
    }
    detectConflictInst(MI, curRes, lookupTable, InstToPtrMap, false,
        reg, dstReg, mDebug);

  }
}

// This function parses the basic block and based on the instruction type,
// calls the function to finish parsing the instruction.
static void
parseBasicBlock(
    const AMDILTargetMachine *ATM,
    MachineBasicBlock *MB,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    FIPMap &FIToPtrMap,
    RVPVec &lookupTable,
    ByteSet &bytePtrs,
    ConflictSet &conflictPtrs, 
    CPoolSet &cpool,
    BlockCacheableInfo &bci,
    bool mDebug)
{
  for (MachineBasicBlock::iterator mbb = MB->begin(), mbe = MB->end();
      mbb != mbe; ++mbb) {
    MachineInstr *MI = mbb;
    if (MI->getOpcode() == AMDIL::CALL) {
      parseCall(ATM, InstToPtrMap, PtrToInstMap, lookupTable,
          mbb, mbe, mDebug);
    } 
    else if (isLoadInst(ATM->getInstrInfo(), MI)) {
      parseLoadInst(ATM, InstToPtrMap, PtrToInstMap,
          FIToPtrMap, lookupTable, cpool, bci, MI, mDebug);
    } else if (isStoreInst(ATM->getInstrInfo(), MI)) {
      parseStoreInst(ATM, InstToPtrMap, PtrToInstMap,
          FIToPtrMap, lookupTable, cpool, bci, MI, bytePtrs, conflictPtrs, mDebug);
    } else if (isAtomicInst(ATM->getInstrInfo(), MI)) {
      parseAtomicInst(ATM, InstToPtrMap, PtrToInstMap,
          lookupTable, bci, MI, bytePtrs, mDebug);
    } else if (isAppendInst(ATM->getInstrInfo(), MI)) {
      parseAppendInst(ATM, InstToPtrMap, PtrToInstMap,
          lookupTable, MI, mDebug);
    } else if (isImageInst(ATM->getInstrInfo(), MI)) {
      parseImageInst(ATM, InstToPtrMap, PtrToInstMap,
          FIToPtrMap, lookupTable, MI, mDebug);
    } else {
      parseInstruction(ATM, InstToPtrMap, PtrToInstMap,
          lookupTable, cpool, MI, mDebug);
    }
  }
}

// Follows the Reverse Post Order Traversal of the basic blocks to
// determine which order to parse basic blocks in.
void
parseFunction(
    const AMDILPointerManager *PM,
    const AMDILTargetMachine *ATM,
    MachineFunction &MF,
    InstPMap &InstToPtrMap,
    PtrIMap &PtrToInstMap,
    FIPMap &FIToPtrMap,
    RVPVec &lookupTable,
    ByteSet &bytePtrs,
    ConflictSet &conflictPtrs,
    CPoolSet &cpool,
    MBBCacheableMap &mbbCacheable,
    bool mDebug)
{
  if (mDebug) {
    MachineDominatorTree *dominatorTree = &PM
      ->getAnalysis<MachineDominatorTree>();
    dominatorTree->dump();
  }

  std::list<MachineBasicBlock*> prop_worklist;

  ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
  for (ReversePostOrderTraversal<MachineFunction*>::rpo_iterator
      curBlock = RPOT.begin(), endBlock = RPOT.end();
      curBlock != endBlock; ++curBlock) {
    MachineBasicBlock *MB = (*curBlock);
    BlockCacheableInfo &bci = mbbCacheable[MB];
    for (MachineBasicBlock::pred_iterator mbbit = MB->pred_begin(),
        mbbitend = MB->pred_end();
        mbbit != mbbitend;
        mbbit++) {
      MBBCacheableMap::const_iterator mbbcmit = mbbCacheable.find(*mbbit);
      if (mbbcmit != mbbCacheable.end() &&
          mbbcmit->second.storeReachesExit()) {
        bci.setReachesTop();
        break;
      }
    }

    if (mDebug) {
      dbgs() << "[BlockOrdering] Parsing CurrentBlock: "
        << MB->getNumber() << "\n";
    }
    parseBasicBlock(ATM, MB, InstToPtrMap, PtrToInstMap,
        FIToPtrMap, lookupTable, bytePtrs, conflictPtrs, cpool, bci, mDebug);

    if (bci.storeReachesExit())
      prop_worklist.push_back(MB);

    if (mDebug) {
      dbgs() << "BCI info: Top: " << bci.storeReachesTop() << " Exit: " 
        << bci.storeReachesExit() << "\n Instructions:\n";
      for (CacheableInstrSet::const_iterator cibit = bci.cacheableBegin(),
          cibitend = bci.cacheableEnd();
          cibit != cibitend;
          cibit++)
      {
        (*cibit)->dump();
      }
    }
  }

  // This loop pushes any "storeReachesExit" flags into successor
  // blocks until the flags have been fully propagated. This will
  // ensure that blocks that have reachable stores due to loops
  // are labeled appropriately.
  while (!prop_worklist.empty()) {
    MachineBasicBlock *wlb = prop_worklist.front();
    prop_worklist.pop_front();
    for (MachineBasicBlock::succ_iterator mbbit = wlb->succ_begin(),
        mbbitend = wlb->succ_end();
        mbbit != mbbitend;
        mbbit++)
    {
      BlockCacheableInfo &blockCache = mbbCacheable[*mbbit];
      if (!blockCache.storeReachesTop()) {
        blockCache.setReachesTop();
        prop_worklist.push_back(*mbbit);
      }
      if (mDebug) {
        dbgs() << "BCI Prop info: " << (*mbbit)->getNumber() << " Top: " 
          << blockCache.storeReachesTop() << " Exit: " 
          << blockCache.storeReachesExit()
          << "\n";
      }
    }
  }
}

// Helper function that dumps to dbgs() information about
// a pointer set.
  void
dumpPointers(AppendSet &Ptrs, const char *str)
{
  if (Ptrs.empty()) {
    return;
  }
  dbgs() << "[Dump]" << str << " found: " << "\n";
  for (AppendSet::iterator sb = Ptrs.begin();
      sb != Ptrs.end(); ++sb) {
    (*sb)->dump();
  }
  dbgs() << "\n";
}
// Helper function that dumps to dbgs() information about
// a pointer set.
  void
dumpPointers(PtrSet &Ptrs, const char *str)
{
  if (Ptrs.empty()) {
    return;
  }
  dbgs() << "[Dump]" << str << " found: " << "\n";
  for (PtrSet::iterator sb = Ptrs.begin();
      sb != Ptrs.end(); ++sb) {
    (*sb)->dump();
  }
  dbgs() << "\n";
}
// Function that detects all the conflicting pointers and adds
// the pointers that are detected to the conflict set, otherwise
// they are added to the raw or byte set based on their usage.
void
detectConflictingPointers(
    const AMDILTargetMachine *ATM,
    InstPMap &InstToPtrMap,
    ByteSet &bytePtrs,
    RawSet &rawPtrs,
    ConflictSet &conflictPtrs,
    bool mDebug)
{
  if (InstToPtrMap.empty()) {
    return;
  }
  PtrSet aliasedPtrs;
  const AMDILSubtarget *STM = ATM->getSubtargetImpl();
  for (InstPMap::iterator
      mapIter = InstToPtrMap.begin(), iterEnd = InstToPtrMap.end();
      mapIter != iterEnd; ++mapIter) {
    if (mDebug) {
      dbgs() << "Instruction: ";
      (mapIter)->first->dump();
    }
    MachineInstr* MI = mapIter->first;
    AMDILAS::InstrResEnc curRes;
    getAsmPrinterFlags(MI, curRes);
    if (curRes.bits.isImage) {
      continue;
    }
    bool byte = false;
    // We might have a case where more than 1 pointers is going to the same
    // I/O instruction
    if (mDebug) {
      dbgs() << "Base Pointer[s]:\n";
    }
    for (PtrSet::iterator cfIter = mapIter->second.begin(),
        cfEnd = mapIter->second.end(); cfIter != cfEnd; ++cfIter) {
      if (mDebug) {
        (*cfIter)->dump();
      }
      if (bytePtrs.count(*cfIter)) {
        if (mDebug) {
          dbgs() << "Byte pointer found!\n";
        }
        byte = true;
        break;
      }
    }
    if (byte) {
      for (PtrSet::iterator cfIter = mapIter->second.begin(),
          cfEnd = mapIter->second.end(); cfIter != cfEnd; ++cfIter) {
        const Value *ptr = (*cfIter);
        if (isLRPInst(mapIter->first, ATM)) {
          // We don't need to deal with pointers to local/region/private
          // memory regions
          continue;
        }
        if (mDebug) {
          dbgs() << "Adding pointer " << (ptr)->getName()
            << " to byte set!\n";
        }
        const PointerType *PT = dyn_cast<PointerType>(ptr->getType());
        if (PT) {
          bytePtrs.insert(ptr);
        }
      }
    } else {
      for (PtrSet::iterator cfIter = mapIter->second.begin(),
          cfEnd = mapIter->second.end(); cfIter != cfEnd; ++cfIter) {
        const Value *ptr = (*cfIter);
        // bool aliased = false;
        if (isLRPInst(mapIter->first, ATM)) {
          // We don't need to deal with pointers to local/region/private
          // memory regions
          continue;
        }
        const Argument *arg = dyn_cast_or_null<Argument>(*cfIter);
        if (!arg) {
          continue;
        }
        if (!STM->device()->isSupported(AMDILDeviceInfo::NoAlias) 
            && !arg->hasNoAliasAttr()) {
          if (mDebug) {
            dbgs() << "Possible aliased pointer found!\n";
          }
          aliasedPtrs.insert(ptr);
        }
        if (mapIter->second.size() > 1) {
          if (mDebug) {
            dbgs() << "Adding pointer " << ptr->getName()
              << " to conflict set!\n";
          }
          const PointerType *PT = dyn_cast<PointerType>(ptr->getType());
          if (PT) {
            conflictPtrs.insert(ptr);
          }
        }
        if (mDebug) {
          dbgs() << "Adding pointer " << ptr->getName()
            << " to raw set!\n";
        }
        const PointerType *PT = dyn_cast<PointerType>(ptr->getType());
        if (PT) {
          rawPtrs.insert(ptr);
        }
      }
    }
    if (mDebug) {
      dbgs() << "\n";
    }
  }
  // If we have any aliased pointers and byte pointers exist,
  // then make sure that all of the aliased pointers are 
  // part of the byte pointer set.
  if (!bytePtrs.empty()) {
    for (PtrSet::iterator aIter = aliasedPtrs.begin(),
        aEnd = aliasedPtrs.end(); aIter != aEnd; ++aIter) {
      if (mDebug) {
        dbgs() << "Moving " << (*aIter)->getName() 
          << " from raw to byte.\n";
      }
      bytePtrs.insert(*aIter);
      rawPtrs.erase(*aIter);
    }
  }
}
// Function that detects aliased constant pool operations.
void
detectAliasedCPoolOps(
    TargetMachine &TM,
    CPoolSet &cpool,
    bool mDebug
    )
{
  const AMDILSubtarget *STM = &TM.getSubtarget<AMDILSubtarget>();
  if (mDebug && !cpool.empty()) {
    dbgs() << "Instructions w/ CPool Ops: \n";
  }
  // The algorithm for detecting aliased cpool is as follows.
  // For each instruction that has a cpool argument
  // follow def-use chain
  //   if instruction is a load and load is a private load,
  //      switch to constant pool load
  for (CPoolSet::iterator cpb = cpool.begin(), cpe = cpool.end();
      cpb != cpe; ++cpb) {
    if (mDebug) {
      (*cpb)->dump();
    }
    std::queue<MachineInstr*> queue;
    std::set<MachineInstr*> visited;
    queue.push(*cpb);
    MachineInstr *cur;
    while (!queue.empty()) {
      cur = queue.front();
      queue.pop();
      if (visited.count(cur)) {
        continue;
      }
      if (isLoadInst(TM.getInstrInfo(), cur) && isPrivateInst(TM.getInstrInfo(), cur)) { 
        // If we are a private load and the register is
        // used in the address register, we need to
        // switch from private to constant pool load.
        if (mDebug) {
          dbgs() << "Found an instruction that is a private load "
            << "but should be a constant pool load.\n";
          cur->print(dbgs());
          dbgs() << "\n";
        }
        AMDILAS::InstrResEnc curRes;
        getAsmPrinterFlags(cur, curRes);
        curRes.bits.ResourceID = STM->device()->getResourceID(AMDILDevice::GLOBAL_ID);
        curRes.bits.ConflictPtr = 1;
        setAsmPrinterFlags(cur, curRes);
        cur->setDesc(TM.getInstrInfo()->get(
              (cur->getOpcode() - AMDIL::PRIVATEAEXTLOAD_f32) 
              + AMDIL::CPOOLAEXTLOAD_f32));
      } else {
        if (cur->getOperand(0).isReg()) {
          MachineOperand* ptr = cur->getOperand(0).getNextOperandForReg();
          while (ptr && !ptr->isDef() && ptr->isReg()) {
            queue.push(ptr->getParent());
            ptr = ptr->getNextOperandForReg();
          } 
        }
      }
      visited.insert(cur);
    }
  }
}
// Function that detects fully cacheable pointers. Fully cacheable pointers
// are pointers that have no writes to them and -fno-alias is specified.
void
detectFullyCacheablePointers(
    const AMDILTargetMachine *ATM,
    PtrIMap &PtrToInstMap,
    RawSet &rawPtrs,
    CacheableSet &cacheablePtrs,
    ConflictSet &conflictPtrs,
    bool mDebug
    )
{
  if (PtrToInstMap.empty()) {
    return;
  }
  const AMDILSubtarget *STM
    = ATM->getSubtargetImpl();
  // 4XXX hardware doesn't support cached uav opcodes and we assume
  // no aliasing for this to work. Also in debug mode we don't do
  // any caching.
  if (STM->device()->getGeneration() == AMDILDeviceInfo::HD4XXX
      || !STM->device()->isSupported(AMDILDeviceInfo::CachedMem)) {
    return;
  }
  if (STM->device()->isSupported(AMDILDeviceInfo::NoAlias)) {
    for (PtrIMap::iterator mapIter = PtrToInstMap.begin(), 
        iterEnd = PtrToInstMap.end(); mapIter != iterEnd; ++mapIter) {
      if (mDebug) {
        dbgs() << "Instruction: ";
        mapIter->first->dump();
      }
      // Skip the pointer if we have already detected it.
      if (cacheablePtrs.count(mapIter->first)) {
        continue;
      }
      bool cacheable = true;
      for (std::vector<MachineInstr*>::iterator 
          miBegin = mapIter->second.begin(),
          miEnd = mapIter->second.end(); miBegin != miEnd; ++miBegin) {
        if (isStoreInst(ATM->getInstrInfo(), *miBegin) ||
            isImageInst(ATM->getInstrInfo(), *miBegin) ||
            isAtomicInst(ATM->getInstrInfo(), *miBegin)) {
          cacheable = false;
          break;
        }
      }
      // we aren't cacheable, so lets move on to the next instruction
      if (!cacheable) {
        continue;
      }
      // If we are in the conflict set, lets move to the next instruction
      // FIXME: we need to check to see if the pointers that conflict with
      // the current pointer are also cacheable. If they are, then add them
      // to the cacheable list and not fail.
      if (conflictPtrs.count(mapIter->first)) {
        continue;
      }
      // Otherwise if we have no stores and no conflicting pointers, we can
      // be added to the cacheable set.
      if (mDebug) {
        dbgs() << "Adding pointer " << mapIter->first->getName();
        dbgs() << " to cached set!\n";
      }
      const PointerType *PT = dyn_cast<PointerType>(mapIter->first->getType());
      if (PT) {
        cacheablePtrs.insert(mapIter->first);
      }
    }
  }
}

// Are any of the pointers in PtrSet also in the BytePtrs or the CachePtrs?
static bool
ptrSetIntersectsByteOrCache(
    PtrSet &cacheSet,
    ByteSet &bytePtrs,
    CacheableSet &cacheablePtrs
    )
{
  for (PtrSet::const_iterator psit = cacheSet.begin(),
      psitend = cacheSet.end();
      psit != psitend;
      psit++) {
    if (bytePtrs.find(*psit) != bytePtrs.end() ||
        cacheablePtrs.find(*psit) != cacheablePtrs.end()) {
      return true;
    }
  }
  return false;
}

// Function that detects which instructions are cacheable even if
// all instructions of the pointer are not cacheable. The resulting
// set of instructions will not contain Ptrs that are in the cacheable
// ptr set (under the assumption they will get marked cacheable already)
// or pointers in the byte set, since they are not cacheable.
void
detectCacheableInstrs(
    MBBCacheableMap &bbCacheable,
    InstPMap &InstToPtrMap,
    CacheableSet &cacheablePtrs,
    ByteSet &bytePtrs,
    CacheableInstrSet &cacheableSet,
    bool mDebug
    )

{
  for (MBBCacheableMap::const_iterator mbbcit = bbCacheable.begin(),
      mbbcitend = bbCacheable.end();
      mbbcit != mbbcitend;
      mbbcit++) {
    for (CacheableInstrSet::const_iterator bciit 
        = mbbcit->second.cacheableBegin(),
        bciitend
        = mbbcit->second.cacheableEnd();
        bciit != bciitend;
        bciit++) {
      if (!ptrSetIntersectsByteOrCache(InstToPtrMap[*bciit],
            bytePtrs, 
            cacheablePtrs)) {
        cacheableSet.insert(*bciit);
      }
    }
  }
}
// This function annotates the cacheable pointers with the
// CacheableRead bit. The cacheable read bit is set
// when the number of write images is not equal to the max
// or if the default RAW_UAV_ID is equal to 11. The first
// condition means that there is a raw uav between 0 and 7
// that is available for cacheable reads and the second
// condition means that UAV 11 is available for cacheable
// reads.
void
annotateCacheablePtrs(
    TargetMachine &TM,
    PtrIMap &PtrToInstMap,
    CacheableSet &cacheablePtrs,
    ByteSet &bytePtrs,
    uint32_t numWriteImages,
    bool mDebug)
{
  const AMDILSubtarget *STM = &TM.getSubtarget<AMDILSubtarget>();
  // AMDILKernelManager *KM = (AMDILKernelManager*)STM->getKernelManager();
  PtrSet::iterator siBegin, siEnd;
  std::vector<MachineInstr*>::iterator miBegin, miEnd;
  AMDILMachineFunctionInfo *mMFI = NULL;
  // First we can check the cacheable pointers
  for (siBegin = cacheablePtrs.begin(), siEnd = cacheablePtrs.end();
      siBegin != siEnd; ++siBegin) {
    assert(!bytePtrs.count(*siBegin) && "Found a cacheable pointer "
        "that also exists as a byte pointer!");
    for (miBegin = PtrToInstMap[*siBegin].begin(),
        miEnd = PtrToInstMap[*siBegin].end();
        miBegin != miEnd; ++miBegin) {
      if (mDebug) {
        dbgs() << "Annotating pointer as cacheable. Inst: ";
        (*miBegin)->dump();
      }
      AMDILAS::InstrResEnc curRes;
      getAsmPrinterFlags(*miBegin, curRes);
      assert(!curRes.bits.ByteStore && "No cacheable pointers should have the "
          "byte Store flag set!");
      // If UAV11 is enabled, then we can enable cached reads.
      if (STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID) == 11) {
        curRes.bits.CacheableRead = 1;
        curRes.bits.ResourceID = 11;
        setAsmPrinterFlags(*miBegin, curRes);
        if (!mMFI) {
          mMFI = (*miBegin)->getParent()->getParent()
            ->getInfo<AMDILMachineFunctionInfo>();
        }
        mMFI->uav_insert(curRes.bits.ResourceID);
      }
    }
  }
}

// A byte pointer is a pointer that along the pointer path has a
// byte store assigned to it.
void
annotateBytePtrs(
    TargetMachine &TM,
    PtrIMap &PtrToInstMap,
    ByteSet &bytePtrs,
    RawSet &rawPtrs,
    bool mDebug
    )
{
  const AMDILSubtarget *STM = &TM.getSubtarget<AMDILSubtarget>();
  AMDILKernelManager *KM = STM->getKernelManager();
  PtrSet::iterator siBegin, siEnd;
  std::vector<MachineInstr*>::iterator miBegin, miEnd;
  uint32_t arenaID = STM->device()
          ->getResourceID(AMDILDevice::ARENA_UAV_ID);
  if (STM->device()->isSupported(AMDILDeviceInfo::ArenaSegment)) {
    arenaID = ARENA_SEGMENT_RESERVED_UAVS + 1;
  }
  AMDILMachineFunctionInfo *mMFI = NULL;
  for (siBegin = bytePtrs.begin(), siEnd = bytePtrs.end();
      siBegin != siEnd; ++siBegin) {
          const Value* val = (*siBegin);
    const PointerType *PT = dyn_cast<PointerType>(val->getType());
    if (!PT) {
        continue;
    }
    const Argument *curArg = dyn_cast<Argument>(val);
    assert(!rawPtrs.count(*siBegin) && "Found a byte pointer "
        "that also exists as a raw pointer!");
    bool arenaInc = false;
    for (miBegin = PtrToInstMap[*siBegin].begin(),
        miEnd = PtrToInstMap[*siBegin].end();
        miBegin != miEnd; ++miBegin) {
      if (mDebug) {
        dbgs() << "Annotating pointer as arena. Inst: ";
        (*miBegin)->dump();
      }
      AMDILAS::InstrResEnc curRes;
      getAsmPrinterFlags(*miBegin, curRes);

      if (STM->device()->usesHardware(AMDILDeviceInfo::ConstantMem)
          && PT->getAddressSpace() == AMDILAS::CONSTANT_ADDRESS) {
        // If hardware constant mem is enabled, then we need to
        // get the constant pointer CB number and use that to specify
        // the resource ID.
        AMDILGlobalManager *GM = STM->getGlobalManager();
        const StringRef funcName = (*miBegin)->getParent()->getParent()
          ->getFunction()->getName();
        if (GM->isKernel(funcName)) {
          const kernel &krnl = GM->getKernel(funcName);
          curRes.bits.ResourceID = GM->getConstPtrCB(krnl,
              (*siBegin)->getName());
          curRes.bits.HardwareInst = 1;
        } else {
          curRes.bits.ResourceID = STM->device()
            ->getResourceID(AMDILDevice::CONSTANT_ID);
        }
      } else if (STM->device()->usesHardware(AMDILDeviceInfo::LocalMem)
          && PT->getAddressSpace() == AMDILAS::LOCAL_ADDRESS) {
        // If hardware local mem is enabled, get the local mem ID from
        // the device to use as the ResourceID
        curRes.bits.ResourceID = STM->device()
          ->getResourceID(AMDILDevice::LDS_ID);
        if (isAtomicInst(TM.getInstrInfo(), *miBegin)) {
          assert(curRes.bits.ResourceID && "Atomic resource ID "
              "cannot be non-zero!");
          (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
            .setImm(curRes.bits.ResourceID);
        }
      } else if (STM->device()->usesHardware(AMDILDeviceInfo::RegionMem)
          && PT->getAddressSpace() == AMDILAS::REGION_ADDRESS) {
        // If hardware region mem is enabled, get the gds mem ID from
        // the device to use as the ResourceID
        curRes.bits.ResourceID = STM->device()
          ->getResourceID(AMDILDevice::GDS_ID);
        if (isAtomicInst(TM.getInstrInfo(), *miBegin)) {
          assert(curRes.bits.ResourceID && "Atomic resource ID "
              "cannot be non-zero!");
          (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
            .setImm(curRes.bits.ResourceID);
        }
      } else if (STM->device()->usesHardware(AMDILDeviceInfo::PrivateMem)
          && PT->getAddressSpace() == AMDILAS::PRIVATE_ADDRESS) {
        curRes.bits.ResourceID = STM->device()
          ->getResourceID(AMDILDevice::SCRATCH_ID);
      } else { 
        if (mDebug) {
          dbgs() << __LINE__ << ": Setting byte store bit on instruction: ";
          (*miBegin)->print(dbgs());
        }
        curRes.bits.ByteStore = 1;
        curRes.bits.ResourceID = (curArg && curArg->hasNoAliasAttr()) ? arenaID
          : STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID);
        if (STM->device()->isSupported(AMDILDeviceInfo::ArenaSegment)) {
          arenaInc = true;
        }
        if (isAtomicInst(TM.getInstrInfo(), *miBegin) &&
            STM->device()->isSupported(AMDILDeviceInfo::ArenaUAV)) {
          (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
            .setImm(curRes.bits.ResourceID);
          // If we are an arena instruction, we need to switch the atomic opcode
          // from the global version to the arena version.
          MachineInstr *MI = *miBegin;
          MI->setDesc(
              TM.getInstrInfo()->get(
                (MI->getOpcode() - AMDIL::ATOM_G_ADD) + AMDIL::ATOM_A_ADD));
        }
        if (mDebug) {
          dbgs() << "Annotating pointer as arena. Inst: ";
          (*miBegin)->dump();
        }
      }
      setAsmPrinterFlags(*miBegin, curRes);
      KM->setUAVID(*siBegin, curRes.bits.ResourceID);
      if (!mMFI) {
        mMFI = (*miBegin)->getParent()->getParent()
          ->getInfo<AMDILMachineFunctionInfo>();
      }
      mMFI->uav_insert(curRes.bits.ResourceID);
    }
    if (arenaInc) {
      ++arenaID;
    }
  }
}
// An append pointer is a opaque object that has append instructions
// in its path.
void
annotateAppendPtrs(
    TargetMachine &TM,
    PtrIMap &PtrToInstMap,
    AppendSet &appendPtrs,
    bool mDebug)
{
  unsigned currentCounter = 0;
  // const AMDILSubtarget *STM = &TM.getSubtarget<AMDILSubtarget>();
  // AMDILKernelManager *KM = (AMDILKernelManager*)STM->getKernelManager();
  MachineFunction *MF = NULL;
  for (AppendSet::iterator asBegin = appendPtrs.begin(),
      asEnd = appendPtrs.end(); asBegin != asEnd; ++asBegin)
  {
    bool usesWrite = false;
    bool usesRead = false;
    const Value* curVal = *asBegin;
    if (mDebug) {
      dbgs() << "Counter: " << curVal->getName() 
        << " assigned the counter " << currentCounter << "\n";
    }
    for (std::vector<MachineInstr*>::iterator 
        miBegin = PtrToInstMap[curVal].begin(),
        miEnd = PtrToInstMap[curVal].end(); miBegin != miEnd; ++miBegin) {
      MachineInstr *MI = *miBegin;
      if (!MF) {
        MF = MI->getParent()->getParent();
      }
      unsigned opcode = MI->getOpcode();
      switch (opcode) {
        default:
          if (mDebug) {
            dbgs() << "Skipping instruction: ";
            MI->dump();
          }
          break;
        case AMDIL::APPEND_ALLOC:
        case AMDIL::APPEND_ALLOC_NORET:
          usesWrite = true;
          MI->getOperand(1).ChangeToImmediate(currentCounter);
          if (mDebug) {
            dbgs() << "Assing to counter " << currentCounter << " Inst: ";
            MI->dump();
          }
          break;
        case AMDIL::APPEND_CONSUME:
        case AMDIL::APPEND_CONSUME_NORET:
          usesRead = true;
          MI->getOperand(1).ChangeToImmediate(currentCounter);
          if (mDebug) {
            dbgs() << "Assing to counter " << currentCounter << " Inst: ";
            MI->dump();
          }
          break;
      };
    }
    if (usesWrite && usesRead && MF) {
      MF->getInfo<AMDILMachineFunctionInfo>()->addErrorMsg(
          amd::CompilerErrorMessage[INCORRECT_COUNTER_USAGE]);
    }
    ++currentCounter;
  }
}
// A raw pointer is any pointer that does not have byte store in its path.
static void
annotateRawPtrs(
    TargetMachine &TM,
    PtrIMap &PtrToInstMap,
    RawSet &rawPtrs,
    ByteSet &bytePtrs,
    uint32_t numWriteImages,
    bool mDebug
    )
{
  const AMDILSubtarget *STM = &TM.getSubtarget<AMDILSubtarget>();
  AMDILKernelManager *KM = STM->getKernelManager();
  PtrSet::iterator siBegin, siEnd;
  std::vector<MachineInstr*>::iterator miBegin, miEnd;
  AMDILMachineFunctionInfo *mMFI = NULL;

  // Now all of the raw pointers will go to the raw uav.
  for (siBegin = rawPtrs.begin(), siEnd = rawPtrs.end();
      siBegin != siEnd; ++siBegin) {
    const PointerType *PT = dyn_cast<PointerType>((*siBegin)->getType());
    if (!PT) {
      continue;
    }
    assert(!bytePtrs.count(*siBegin) && "Found a raw pointer "
        " that also exists as a byte pointers!");
    for (miBegin = PtrToInstMap[*siBegin].begin(),
        miEnd = PtrToInstMap[*siBegin].end();
        miBegin != miEnd; ++miBegin) {
      if (mDebug) {
        dbgs() << "Annotating pointer as raw. Inst: ";
        (*miBegin)->dump();
      }
      AMDILAS::InstrResEnc curRes;
      getAsmPrinterFlags(*miBegin, curRes);
      if (!curRes.bits.ConflictPtr) {
        assert(!curRes.bits.ByteStore 
            && "Found a instruction that is marked as "
            "raw but has a byte store bit set!");
      } else if (curRes.bits.ConflictPtr) {
        if (curRes.bits.ByteStore) {
          curRes.bits.ByteStore = 0;
        }
      }
      if (STM->device()->usesHardware(AMDILDeviceInfo::ConstantMem)
          && PT->getAddressSpace() == AMDILAS::CONSTANT_ADDRESS) {
        // If hardware constant mem is enabled, then we need to
        // get the constant pointer CB number and use that to specify
        // the resource ID.
        AMDILGlobalManager *GM = STM->getGlobalManager();
        const StringRef funcName = (*miBegin)->getParent()->getParent()
          ->getFunction()->getName();
        if (GM->isKernel(funcName)) {
          const kernel &krnl = GM->getKernel(funcName);
          curRes.bits.ResourceID = GM->getConstPtrCB(krnl,
              (*siBegin)->getName());
          curRes.bits.HardwareInst = 1;
        } else {
          curRes.bits.ResourceID = STM->device()
            ->getResourceID(AMDILDevice::CONSTANT_ID);
        }
      } else if (STM->device()->usesHardware(AMDILDeviceInfo::LocalMem)
          && PT->getAddressSpace() == AMDILAS::LOCAL_ADDRESS) {
        // If hardware local mem is enabled, get the local mem ID from
        // the device to use as the ResourceID
        curRes.bits.ResourceID = STM->device()
          ->getResourceID(AMDILDevice::LDS_ID);
        if (isAtomicInst(TM.getInstrInfo(), *miBegin)) {
          assert(curRes.bits.ResourceID && "Atomic resource ID "
              "cannot be non-zero!");
          (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
            .setImm(curRes.bits.ResourceID);
        }
      } else if (STM->device()->usesHardware(AMDILDeviceInfo::RegionMem)
          && PT->getAddressSpace() == AMDILAS::REGION_ADDRESS) {
        // If hardware region mem is enabled, get the gds mem ID from
        // the device to use as the ResourceID
        curRes.bits.ResourceID = STM->device()
          ->getResourceID(AMDILDevice::GDS_ID);
        if (isAtomicInst(TM.getInstrInfo(), *miBegin)) {
          assert(curRes.bits.ResourceID && "Atomic resource ID "
              "cannot be non-zero!");
          (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
            .setImm(curRes.bits.ResourceID);
        }
      } else if (STM->device()->usesHardware(AMDILDeviceInfo::PrivateMem)
          && PT->getAddressSpace() == AMDILAS::PRIVATE_ADDRESS) {
        curRes.bits.ResourceID = STM->device()
          ->getResourceID(AMDILDevice::SCRATCH_ID);
      } else if (!STM->device()->isSupported(AMDILDeviceInfo::MultiUAV)) {
        // If multi uav is enabled, then the resource ID is either the
        // number of write images that are available or the device
        // raw uav id if it is 11.
        if (STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID) >
            STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID)) {
          curRes.bits.ResourceID = STM->device()
            ->getResourceID(AMDILDevice::RAW_UAV_ID);
        } else if (numWriteImages != OPENCL_MAX_WRITE_IMAGES) {
          if (STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID)
              < numWriteImages) {
            curRes.bits.ResourceID = numWriteImages;
          } else {
            curRes.bits.ResourceID = STM->device()
              ->getResourceID(AMDILDevice::RAW_UAV_ID);
          }
        } else {
          if (mDebug) {
            dbgs() << __LINE__ << ": Setting byte store bit on instruction: ";
            (*miBegin)->print(dbgs());
          }
          curRes.bits.ByteStore = 1;
          curRes.bits.ResourceID = STM->device()
            ->getResourceID(AMDILDevice::ARENA_UAV_ID);
        }
        if (isAtomicInst(TM.getInstrInfo(), *miBegin)) {
          (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
            .setImm(curRes.bits.ResourceID);
          if (curRes.bits.ResourceID
              == STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID)) {
            assert(0 && "Found an atomic instruction that has "
                "an arena uav id!");
          }
        }
        KM->setUAVID(*siBegin, curRes.bits.ResourceID);
        if (!mMFI) {
          mMFI = (*miBegin)->getParent()->getParent()
            ->getInfo<AMDILMachineFunctionInfo>();
        }
        mMFI->uav_insert(curRes.bits.ResourceID);
      }
      setAsmPrinterFlags(*miBegin, curRes);
    }
  }

}

void
annotateCacheableInstrs(
    TargetMachine &TM,
    CacheableInstrSet &cacheableSet,
    bool mDebug)
{
  const AMDILSubtarget *STM = &TM.getSubtarget<AMDILSubtarget>();
  // AMDILKernelManager *KM = (AMDILKernelManager*)STM->getKernelManager();

  CacheableInstrSet::iterator miBegin, miEnd;

  for (miBegin = cacheableSet.begin(),
      miEnd = cacheableSet.end();
      miBegin != miEnd; ++miBegin) {
    if (mDebug) {
      dbgs() << "Annotating instr as cacheable. Inst: ";
      (*miBegin)->dump();
    }
    AMDILAS::InstrResEnc curRes;
    getAsmPrinterFlags(*miBegin, curRes);
    // If UAV11 is enabled, then we can enable cached reads.
    if (STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID) == 11) {
      curRes.bits.CacheableRead = 1;
      curRes.bits.ResourceID = 11;
      setAsmPrinterFlags(*miBegin, curRes);
    }
  }
}

// Annotate the instructions along various pointer paths. The paths that
// are handled are the raw, byte and cacheable pointer paths.
static void
annotatePtrPath(
    TargetMachine &TM,
    PtrIMap &PtrToInstMap,
    RawSet &rawPtrs,
    ByteSet &bytePtrs,
    CacheableSet &cacheablePtrs,
    uint32_t numWriteImages,
    bool mDebug
    )
{
  if (PtrToInstMap.empty()) {
    return;
  }
  // First we can check the cacheable pointers
  annotateCacheablePtrs(TM, PtrToInstMap, cacheablePtrs,
      bytePtrs, numWriteImages, mDebug);

  // Next we annotate the byte pointers
  annotateBytePtrs(TM, PtrToInstMap, bytePtrs, rawPtrs, mDebug);

  // Next we annotate the raw pointers
  annotateRawPtrs(TM, PtrToInstMap, rawPtrs, bytePtrs,
      numWriteImages, mDebug);
}
// Allocate MultiUAV pointer ID's for the raw/conflict pointers.
static void
allocateMultiUAVPointers(
    MachineFunction &MF,
    const AMDILTargetMachine *ATM,
    PtrIMap &PtrToInstMap,
    RawSet &rawPtrs,
    ConflictSet &conflictPtrs,
    CacheableSet &cacheablePtrs,
    uint32_t numWriteImages,
    bool mDebug)
{
  if (PtrToInstMap.empty()) {
    return;
  }
  AMDILMachineFunctionInfo *mMFI = MF.getInfo<AMDILMachineFunctionInfo>();
  uint32_t curUAV = numWriteImages;
  bool increment = true;
  const AMDILSubtarget *STM
    = ATM->getSubtargetImpl();
  // If the RAW_UAV_ID is a value that is larger than the max number of write
  // images, then we use that UAV ID.
  if (numWriteImages >= OPENCL_MAX_WRITE_IMAGES) {
    curUAV = STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID);
    increment = false;
  }
  AMDILKernelManager *KM = STM->getKernelManager();
  PtrSet::iterator siBegin, siEnd;
  std::vector<MachineInstr*>::iterator miBegin, miEnd;
  // First lets handle the raw pointers.
  for (siBegin = rawPtrs.begin(), siEnd = rawPtrs.end();
      siBegin != siEnd; ++siBegin) {
    assert((*siBegin)->getType()->isPointerTy() && "We must be a pointer type "
        "to be processed at this point!");
    const PointerType *PT = dyn_cast<PointerType>((*siBegin)->getType());
    if (conflictPtrs.count(*siBegin) || !PT) {
      continue;
    }
    // We only want to process global address space pointers
    if (PT->getAddressSpace() != AMDILAS::GLOBAL_ADDRESS) {
      if ((PT->getAddressSpace() == AMDILAS::LOCAL_ADDRESS
            && STM->device()->usesSoftware(AMDILDeviceInfo::LocalMem))
          || (PT->getAddressSpace() == AMDILAS::CONSTANT_ADDRESS
            && STM->device()->usesSoftware(AMDILDeviceInfo::ConstantMem))
          || (PT->getAddressSpace() == AMDILAS::REGION_ADDRESS
            && STM->device()->usesSoftware(AMDILDeviceInfo::RegionMem))) {
        // If we are using software emulated hardware features, then
        // we need to specify that they use the raw uav and not
        // zero-copy uav. The easiest way to do this is to assume they
        // conflict with another pointer. Any pointer that conflicts
        // with another pointer is assigned to the raw uav or the
        // arena uav if no raw uav exists.
        const PointerType *PT = dyn_cast<PointerType>((*siBegin)->getType());
        if (PT) {
          conflictPtrs.insert(*siBegin);
        }
      }
      if (PT->getAddressSpace() == AMDILAS::PRIVATE_ADDRESS) {
        if (STM->device()->usesSoftware(AMDILDeviceInfo::PrivateMem)) {
          const PointerType *PT = dyn_cast<PointerType>((*siBegin)->getType());
          if (PT) {
            conflictPtrs.insert(*siBegin);
          }
        } else {
          if (mDebug) {
            dbgs() << "Scratch Pointer '" << (*siBegin)->getName()
              << "' being assigned uav "<<
              STM->device()->getResourceID(AMDILDevice::SCRATCH_ID) << "\n";
          }
          for (miBegin = PtrToInstMap[*siBegin].begin(),
              miEnd = PtrToInstMap[*siBegin].end();
              miBegin != miEnd; ++miBegin) {
            AMDILAS::InstrResEnc curRes;
            getAsmPrinterFlags(*miBegin, curRes);
            curRes.bits.ResourceID = STM->device()
              ->getResourceID(AMDILDevice::SCRATCH_ID);
            if (mDebug) {
              dbgs() << "Updated instruction to bitmask ";
              dbgs().write_hex(curRes.u16all);
              dbgs() << " with ResID " << curRes.bits.ResourceID;
              dbgs() << ". Inst: ";
              (*miBegin)->dump();
            }
            setAsmPrinterFlags((*miBegin), curRes);
            KM->setUAVID(*siBegin, curRes.bits.ResourceID);
            mMFI->uav_insert(curRes.bits.ResourceID);
          }
        }
      }
      continue;
    }
    // If more than just UAV 11 is cacheable, then we can remove
    // this check.
    if (cacheablePtrs.count(*siBegin)) {
      if (mDebug) {
        dbgs() << "Raw Pointer '" << (*siBegin)->getName()
          << "' is cacheable, not allocating a multi-uav for it!\n";
      }
      continue;
    }
    if (mDebug) {
      dbgs() << "Raw Pointer '" << (*siBegin)->getName()
        << "' being assigned uav " << curUAV << "\n";
    }
    if (PtrToInstMap[*siBegin].empty()) {
      KM->setUAVID(*siBegin, curUAV);
      mMFI->uav_insert(curUAV);
    }
    // For all instructions here, we are going to set the new UAV to the curUAV
    // number and not the value that it currently is set to.
    for (miBegin = PtrToInstMap[*siBegin].begin(),
        miEnd = PtrToInstMap[*siBegin].end();
        miBegin != miEnd; ++miBegin) {
      AMDILAS::InstrResEnc curRes;
      getAsmPrinterFlags(*miBegin, curRes);
      curRes.bits.ResourceID = curUAV;
      if (isAtomicInst(ATM->getInstrInfo(), *miBegin)) {
        (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
          .setImm(curRes.bits.ResourceID);
        if (curRes.bits.ResourceID
            == STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID)) {
          assert(0 && "Found an atomic instruction that has "
              "an arena uav id!");
        }
      }
      if (curUAV == STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID)) {
        if (mDebug) {
          dbgs() << __LINE__ << ": Setting byte store bit on instruction: ";
          (*miBegin)->print(dbgs());
        }
        curRes.bits.ByteStore = 1;
        curRes.bits.CacheableRead = 0;
      }
      if (mDebug) {
        dbgs() << "Updated instruction to bitmask ";
        dbgs().write_hex(curRes.u16all);
        dbgs() << " with ResID " << curRes.bits.ResourceID;
        dbgs() << ". Inst: ";
        (*miBegin)->dump();
      }
      setAsmPrinterFlags(*miBegin, curRes);
      KM->setUAVID(*siBegin, curRes.bits.ResourceID);
      mMFI->uav_insert(curRes.bits.ResourceID);
    }
    // If we make it here, we can increment the uav counter if we are less
    // than the max write image count. Otherwise we set it to the default
    // UAV and leave it.
    if (increment && curUAV < (OPENCL_MAX_WRITE_IMAGES - 1)) {
      ++curUAV;
    } else {
      curUAV = STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID);
      increment = false;
    }
  }
  if (numWriteImages == 8) {
    curUAV = STM->device()->getResourceID(AMDILDevice::RAW_UAV_ID);
  }
  // Now lets handle the conflict pointers
  for (siBegin = conflictPtrs.begin(), siEnd = conflictPtrs.end();
      siBegin != siEnd; ++siBegin) {
    assert((*siBegin)->getType()->isPointerTy() && "We must be a pointer type "
        "to be processed at this point!");
    const PointerType *PT = dyn_cast<PointerType>((*siBegin)->getType());
    // We only want to process global address space pointers
    if (!PT || PT->getAddressSpace() != AMDILAS::GLOBAL_ADDRESS) {
      continue;
    }
    if (mDebug) {
      dbgs() << "Conflict Pointer '" << (*siBegin)->getName()
        << "' being assigned uav " << curUAV << "\n";
    }
    if (PtrToInstMap[*siBegin].empty()) {
      KM->setUAVID(*siBegin, curUAV);
      mMFI->uav_insert(curUAV);
    }
    for (miBegin = PtrToInstMap[*siBegin].begin(),
        miEnd = PtrToInstMap[*siBegin].end();
        miBegin != miEnd; ++miBegin) {
      AMDILAS::InstrResEnc curRes;
      getAsmPrinterFlags(*miBegin, curRes);
      curRes.bits.ResourceID = curUAV;
      if (isAtomicInst(ATM->getInstrInfo(), *miBegin)) {
        (*miBegin)->getOperand((*miBegin)->getNumOperands()-1)
          .setImm(curRes.bits.ResourceID);
        if (curRes.bits.ResourceID
            == STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID)) {
          assert(0 && "Found an atomic instruction that has "
              "an arena uav id!");
        }
      }
      if (curUAV == STM->device()->getResourceID(AMDILDevice::ARENA_UAV_ID)) {
        if (mDebug) {
          dbgs() << __LINE__ << ": Setting byte store bit on instruction: ";
          (*miBegin)->print(dbgs());
        }
        curRes.bits.ByteStore = 1;
      }
      if (mDebug) {
        dbgs() << "Updated instruction to bitmask ";
        dbgs().write_hex(curRes.u16all);
        dbgs() << " with ResID " << curRes.bits.ResourceID;
        dbgs() << ". Inst: ";
        (*miBegin)->dump();
      }
      setAsmPrinterFlags(*miBegin, curRes);
      KM->setUAVID(*siBegin, curRes.bits.ResourceID);
      mMFI->uav_insert(curRes.bits.ResourceID);
    }
  }
}
// The first thing we should do is to allocate the default
// ID for each load/store/atomic instruction so that 
// it is correctly allocated. Everything else after this
// is just an optimization to more efficiently allocate
// resource ID's.
void
allocateDefaultIDs(
    const AMDILTargetMachine *ATM,
    MachineFunction &MF,
    bool mDebug)
{
  for (MachineFunction::iterator mfBegin = MF.begin(),
      mfEnd = MF.end(); mfBegin != mfEnd; ++mfBegin) {
    MachineBasicBlock *MB = mfBegin;
    for (MachineBasicBlock::iterator mbb = MB->begin(), mbe = MB->end();
        mbb != mbe; ++mbb) {
      MachineInstr *MI = mbb;
      if (isLoadInst(ATM->getInstrInfo(), MI) 
          || isStoreInst(ATM->getInstrInfo(), MI)
          || isAtomicInst(ATM->getInstrInfo(), MI)) {
        AMDILAS::InstrResEnc curRes;
        getAsmPrinterFlags(MI, curRes);
        allocateDefaultID(ATM, curRes, MI, mDebug);
      } 
    }
  }
}

  bool
AMDILEGPointerManager::runOnMachineFunction(MachineFunction &MF)
{
  bool changed = false;
  const AMDILTargetMachine *ATM
    = reinterpret_cast<const AMDILTargetMachine*>(&TM);
  AMDILMachineFunctionInfo *mMFI = 
    MF.getInfo<AMDILMachineFunctionInfo>();
  if (mDebug) {
    dbgs() << getPassName() << "\n";
    dbgs() << MF.getFunction()->getName() << "\n";
    MF.dump();
  }
  // Start out by allocating the default ID's to all instructions in the
  // function.
  allocateDefaultIDs(ATM, MF, mDebug);

  // A set of all pointers are tracked in this map and
  // if multiple pointers are detected, they go to the same
  // set.
  PtrIMap PtrToInstMap;

  // All of the instructions that are loads, stores or pointer
  // conflicts are tracked in the map with a set of all values
  // that reference the instruction stored.
  InstPMap InstToPtrMap;

  // In order to track across stack entries, we need a map between a 
  // frame index and a pointer. That way when we load from a frame
  // index, we know what pointer was stored to the frame index.
  FIPMap FIToPtrMap;

  // Set of all the pointers that are byte pointers. Byte pointers
  // are required to have their instructions go to the arena.
  ByteSet bytePtrs;

  // Set of all the pointers that are cacheable. All of the cache pointers
  // are required to go to a raw uav and cannot go to arena.
  CacheableSet cacheablePtrs;

  // Set of all the pointers that go into a raw buffer. A pointer can
  // exist in either rawPtrs or bytePtrs but not both.
  RawSet rawPtrs;

  // Set of all the pointers that end up having a conflicting instruction
  // somewhere in the pointer path.
  ConflictSet conflictPtrs;

  // Set of all pointers that are images
  ImageSet images;

  // Set of all pointers that are counters
  AppendSet counters;

  // Set of all pointers that load from a constant pool
  CPoolSet cpool;

  // Mapping from BB to infomation about the cacheability of the 
  // global load instructions in it.
  MBBCacheableMap bbCacheable;

  // A set of load instructions that are cacheable 
  // even if all the load instructions of the ptr are not. 
  CacheableInstrSet cacheableSet;

  // The lookup table holds all of the registers that
  // are used as we assign pointers values to them.
  // If two pointers collide on the lookup table, then
  // we assign them to the same UAV. If one of the
  // pointers is byte addressable, then we assign
  // them to arena, otherwise we assign them to raw.
  RVPVec lookupTable;

  // First we need to go through all of the arguments and assign the
  // live in registers to the lookup table and the pointer mapping.
  uint32_t numWriteImages = parseArguments(MF, lookupTable, ATM, 
      cacheablePtrs, images, counters, mDebug);

  // Lets do some error checking on the results of the parsing.
  if (counters.size() > OPENCL_MAX_NUM_ATOMIC_COUNTERS) {
    mMFI->addErrorMsg(
        amd::CompilerErrorMessage[INSUFFICIENT_COUNTER_RESOURCES]);
  }
  if (numWriteImages > OPENCL_MAX_WRITE_IMAGES
      || (images.size() - numWriteImages > OPENCL_MAX_READ_IMAGES)) {
    mMFI->addErrorMsg(
        amd::CompilerErrorMessage[INSUFFICIENT_IMAGE_RESOURCES]);
  }

  // Now lets parse all of the instructions and update our
  // lookup tables.
  parseFunction(this, ATM, MF, InstToPtrMap, PtrToInstMap,
      FIToPtrMap, lookupTable, bytePtrs, conflictPtrs, cpool, 
      bbCacheable, mDebug);

  // We need to go over our pointer map and find all the conflicting
  // pointers that have byte stores and put them in the bytePtr map.
  // All conflicting pointers that don't have byte stores go into
  // the rawPtr map.
  detectConflictingPointers(ATM, InstToPtrMap, bytePtrs, rawPtrs,
      conflictPtrs, mDebug);

  // The next step is to detect whether the pointer should be added to
  // the fully cacheable set or not. A pointer is marked as cacheable if
  // no store instruction exists.
  detectFullyCacheablePointers(ATM, PtrToInstMap, rawPtrs,
      cacheablePtrs, conflictPtrs, mDebug);

  // Disable partially cacheable for now when multiUAV is on.
  // SC versions before SC139 have a bug that generates incorrect
  // addressing for some cached accesses.
  if (!ATM->getSubtargetImpl()
      ->device()->isSupported(AMDILDeviceInfo::MultiUAV) &&
      ATM->getSubtargetImpl()->calVersion() >= CAL_VERSION_SC_139) {
    // Now we take the set of loads that have no reachable stores and
    // create a list of additional instructions (those that aren't already
    // in a cacheablePtr set) that are safe to mark as cacheable. 
    detectCacheableInstrs(bbCacheable, InstToPtrMap, cacheablePtrs,
        bytePtrs, cacheableSet, mDebug);

    // Annotate the additional instructions computed above as cacheable.
    // Note that this should not touch any instructions annotated in
    // annotatePtrPath.
    annotateCacheableInstrs(TM, cacheableSet, mDebug);
  }

  // Now that we have detected everything we need to detect, lets go through an
  // annotate the instructions along the pointer path for each of the
  // various pointer types.
  annotatePtrPath(TM, PtrToInstMap, rawPtrs, bytePtrs,
      cacheablePtrs, numWriteImages, mDebug);

  // Annotate the atomic counter path if any exists.
  annotateAppendPtrs(TM, PtrToInstMap, counters, mDebug);

  // If we support MultiUAV, then we need to determine how
  // many write images exist so that way we know how many UAV are
  // left to allocate to buffers.
  if (ATM->getSubtargetImpl()
      ->device()->isSupported(AMDILDeviceInfo::MultiUAV)) {
    // We now have (OPENCL_MAX_WRITE_IMAGES - numPtrs) buffers open for
    // multi-uav allocation.
    allocateMultiUAVPointers(MF, ATM, PtrToInstMap, rawPtrs,
        conflictPtrs, cacheablePtrs, numWriteImages, mDebug);
  }

  // The last step is to detect if we have any alias constant pool operations.
  // This is not likely, but does happen on occasion with double precision 
  // operations.
  detectAliasedCPoolOps(TM, cpool, mDebug);
  if (mDebug) {
    dumpPointers(bytePtrs, "Byte Store Ptrs");
    dumpPointers(rawPtrs, "Raw Ptrs");
    dumpPointers(cacheablePtrs, "Cache Load Ptrs");
    dumpPointers(counters, "Atomic Counters");
    dumpPointers(images, "Images");
  }
  return changed;
}

// The default pointer manager just assigns the default ID's to
// each load/store instruction and does nothing else. This is
// the pointer manager for the 7XX series of cards.
  bool
AMDILPointerManager::runOnMachineFunction(MachineFunction &MF)
{
  bool changed = false;
  const AMDILTargetMachine *ATM
    = reinterpret_cast<const AMDILTargetMachine*>(&TM);
  if (mDebug) {
    dbgs() << getPassName() << "\n";
    dbgs() << MF.getFunction()->getName() << "\n";
    MF.dump();
  }
  // On the 7XX we don't have to do any special processing, so we 
  // can just allocate the default ID and be done with it.
  allocateDefaultIDs(ATM, MF, mDebug);
  return changed;
}