summaryrefslogtreecommitdiffstats
path: root/runtime/arch/stub_test.cc
blob: 9cccf7c761e57b8ba5a7f1dbd63f2b5ecb6021f7 (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
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdio>

#include "art_field-inl.h"
#include "class_linker-inl.h"
#include "common_runtime_test.h"
#include "entrypoints/quick/quick_entrypoints_enum.h"
#include "mirror/art_method-inl.h"
#include "mirror/class-inl.h"
#include "mirror/string-inl.h"
#include "scoped_thread_state_change.h"

namespace art {


class StubTest : public CommonRuntimeTest {
 protected:
  // We need callee-save methods set up in the Runtime for exceptions.
  void SetUp() OVERRIDE {
    // Do the normal setup.
    CommonRuntimeTest::SetUp();

    {
      // Create callee-save methods
      ScopedObjectAccess soa(Thread::Current());
      runtime_->SetInstructionSet(kRuntimeISA);
      for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
        Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
        if (!runtime_->HasCalleeSaveMethod(type)) {
          runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
        }
      }
    }
  }

  void SetUpRuntimeOptions(RuntimeOptions *options) OVERRIDE {
    // Use a smaller heap
    for (std::pair<std::string, const void*>& pair : *options) {
      if (pair.first.find("-Xmx") == 0) {
        pair.first = "-Xmx4M";  // Smallest we can go.
      }
    }
    options->push_back(std::make_pair("-Xint", nullptr));
  }

  // Helper function needed since TEST_F makes a new class.
  Thread::tls_ptr_sized_values* GetTlsPtr(Thread* self) {
    return &self->tlsPtr_;
  }

 public:
  size_t Invoke3(size_t arg0, size_t arg1, size_t arg2, uintptr_t code, Thread* self) {
    return Invoke3WithReferrer(arg0, arg1, arg2, code, self, nullptr);
  }

  // TODO: Set up a frame according to referrer's specs.
  size_t Invoke3WithReferrer(size_t arg0, size_t arg1, size_t arg2, uintptr_t code, Thread* self,
                             mirror::ArtMethod* referrer) {
    // Push a transition back into managed code onto the linked list in thread.
    ManagedStack fragment;
    self->PushManagedStackFragment(&fragment);

    size_t result;
    size_t fpr_result = 0;
#if defined(__i386__)
    // TODO: Set the thread?
    __asm__ __volatile__(
        "subl $12, %%esp\n\t"       // Align stack.
        "pushl %[referrer]\n\t"     // Store referrer.
        "call *%%edi\n\t"           // Call the stub
        "addl $16, %%esp"           // Pop referrer
        : "=a" (result)
          // Use the result from eax
        : "a"(arg0), "c"(arg1), "d"(arg2), "D"(code), [referrer]"r"(referrer)
          // This places code into edi, arg0 into eax, arg1 into ecx, and arg2 into edx
        : "memory");  // clobber.
    // TODO: Should we clobber the other registers? EBX gets clobbered by some of the stubs,
    //       but compilation fails when declaring that.
#elif defined(__arm__)
    __asm__ __volatile__(
        "push {r1-r12, lr}\n\t"     // Save state, 13*4B = 52B
        ".cfi_adjust_cfa_offset 52\n\t"
        "push {r9}\n\t"
        ".cfi_adjust_cfa_offset 4\n\t"
        "mov r9, %[referrer]\n\n"
        "str r9, [sp, #-8]!\n\t"   // Push referrer, +8B padding so 16B aligned
        ".cfi_adjust_cfa_offset 8\n\t"
        "ldr r9, [sp, #8]\n\t"

        // Push everything on the stack, so we don't rely on the order. What a mess. :-(
        "sub sp, sp, #20\n\t"
        "str %[arg0], [sp]\n\t"
        "str %[arg1], [sp, #4]\n\t"
        "str %[arg2], [sp, #8]\n\t"
        "str %[code], [sp, #12]\n\t"
        "str %[self], [sp, #16]\n\t"
        "ldr r0, [sp]\n\t"
        "ldr r1, [sp, #4]\n\t"
        "ldr r2, [sp, #8]\n\t"
        "ldr r3, [sp, #12]\n\t"
        "ldr r9, [sp, #16]\n\t"
        "add sp, sp, #20\n\t"

        "blx r3\n\t"                // Call the stub
        "add sp, sp, #12\n\t"       // Pop nullptr and padding
        ".cfi_adjust_cfa_offset -12\n\t"
        "pop {r1-r12, lr}\n\t"      // Restore state
        ".cfi_adjust_cfa_offset -52\n\t"
        "mov %[result], r0\n\t"     // Save the result
        : [result] "=r" (result)
          // Use the result from r0
        : [arg0] "r"(arg0), [arg1] "r"(arg1), [arg2] "r"(arg2), [code] "r"(code), [self] "r"(self),
          [referrer] "r"(referrer)
        : "memory");  // clobber.
#elif defined(__aarch64__)
    __asm__ __volatile__(
        // Spill x0-x7 which we say we don't clobber. May contain args.
        "sub sp, sp, #64\n\t"
        ".cfi_adjust_cfa_offset 64\n\t"
        "stp x0, x1, [sp]\n\t"
        "stp x2, x3, [sp, #16]\n\t"
        "stp x4, x5, [sp, #32]\n\t"
        "stp x6, x7, [sp, #48]\n\t"

        "sub sp, sp, #16\n\t"          // Reserve stack space, 16B aligned
        ".cfi_adjust_cfa_offset 16\n\t"
        "str %[referrer], [sp]\n\t"    // referrer

        // Push everything on the stack, so we don't rely on the order. What a mess. :-(
        "sub sp, sp, #48\n\t"
        ".cfi_adjust_cfa_offset 48\n\t"
        // All things are "r" constraints, so direct str/stp should work.
        "stp %[arg0], %[arg1], [sp]\n\t"
        "stp %[arg2], %[code], [sp, #16]\n\t"
        "str %[self], [sp, #32]\n\t"

        // Now we definitely have x0-x3 free, use it to garble d8 - d15
        "movk x0, #0xfad0\n\t"
        "movk x0, #0xebad, lsl #16\n\t"
        "movk x0, #0xfad0, lsl #32\n\t"
        "movk x0, #0xebad, lsl #48\n\t"
        "fmov d8, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d9, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d10, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d11, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d12, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d13, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d14, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d15, x0\n\t"

        // Load call params into the right registers.
        "ldp x0, x1, [sp]\n\t"
        "ldp x2, x3, [sp, #16]\n\t"
        "ldr x18, [sp, #32]\n\t"
        "add sp, sp, #48\n\t"
        ".cfi_adjust_cfa_offset -48\n\t"


        "blr x3\n\t"              // Call the stub
        "mov x8, x0\n\t"          // Store result
        "add sp, sp, #16\n\t"     // Drop the quick "frame"
        ".cfi_adjust_cfa_offset -16\n\t"

        // Test d8 - d15. We can use x1 and x2.
        "movk x1, #0xfad0\n\t"
        "movk x1, #0xebad, lsl #16\n\t"
        "movk x1, #0xfad0, lsl #32\n\t"
        "movk x1, #0xebad, lsl #48\n\t"
        "fmov x2, d8\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d9\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d10\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d11\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d12\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d13\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d14\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d15\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"

        "mov x9, #0\n\t"              // Use x9 as flag, in clobber list

        // Finish up.
        "2:\n\t"
        "ldp x0, x1, [sp]\n\t"        // Restore stuff not named clobbered, may contain fpr_result
        "ldp x2, x3, [sp, #16]\n\t"
        "ldp x4, x5, [sp, #32]\n\t"
        "ldp x6, x7, [sp, #48]\n\t"
        "add sp, sp, #64\n\t"         // Free stack space, now sp as on entry
        ".cfi_adjust_cfa_offset -64\n\t"

        "str x9, %[fpr_result]\n\t"   // Store the FPR comparison result
        "mov %[result], x8\n\t"              // Store the call result

        "b 3f\n\t"                     // Goto end

        // Failed fpr verification.
        "1:\n\t"
        "mov x9, #1\n\t"
        "b 2b\n\t"                     // Goto finish-up

        // End
        "3:\n\t"
        : [result] "=r" (result)
          // Use the result from r0
        : [arg0] "0"(arg0), [arg1] "r"(arg1), [arg2] "r"(arg2), [code] "r"(code), [self] "r"(self),
          [referrer] "r"(referrer), [fpr_result] "m" (fpr_result)
        : "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20",
          "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x30",
          "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
          "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
          "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
          "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
          "memory");  // clobber.
#elif defined(__x86_64__) && !defined(__APPLE__) && defined(__clang__)
    // Note: Uses the native convention
    // TODO: Set the thread?
    __asm__ __volatile__(
        "pushq %[referrer]\n\t"        // Push referrer
        "pushq (%%rsp)\n\t"             // & 16B alignment padding
        ".cfi_adjust_cfa_offset 16\n\t"
        "call *%%rax\n\t"              // Call the stub
        "addq $16, %%rsp\n\t"          // Pop nullptr and padding
        ".cfi_adjust_cfa_offset -16\n\t"
        : "=a" (result)
          // Use the result from rax
        : "D"(arg0), "S"(arg1), "d"(arg2), "a"(code), [referrer] "c"(referrer)
          // This places arg0 into rdi, arg1 into rsi, arg2 into rdx, and code into rax
        : "rbx", "rbp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
          "memory");  // clobber all
    // TODO: Should we clobber the other registers?
#else
    UNUSED(arg0, arg1, arg2, code, referrer);
    LOG(WARNING) << "Was asked to invoke for an architecture I do not understand.";
    result = 0;
#endif
    // Pop transition.
    self->PopManagedStackFragment(fragment);

    fp_result = fpr_result;
    EXPECT_EQ(0U, fp_result);

    return result;
  }

  // TODO: Set up a frame according to referrer's specs.
  size_t Invoke3WithReferrerAndHidden(size_t arg0, size_t arg1, size_t arg2, uintptr_t code,
                                      Thread* self, mirror::ArtMethod* referrer, size_t hidden) {
    // Push a transition back into managed code onto the linked list in thread.
    ManagedStack fragment;
    self->PushManagedStackFragment(&fragment);

    size_t result;
    size_t fpr_result = 0;
#if defined(__i386__)
    // TODO: Set the thread?
    __asm__ __volatile__(
        "movd %[hidden], %%xmm7\n\t"
        "subl $12, %%esp\n\t"       // Align stack.
        "pushl %[referrer]\n\t"     // Store referrer
        "call *%%edi\n\t"           // Call the stub
        "addl $16, %%esp"           // Pop referrer
        : "=a" (result)
          // Use the result from eax
        : "a"(arg0), "c"(arg1), "d"(arg2), "D"(code), [referrer]"r"(referrer), [hidden]"m"(hidden)
          // This places code into edi, arg0 into eax, arg1 into ecx, and arg2 into edx
        : "memory");  // clobber.
    // TODO: Should we clobber the other registers? EBX gets clobbered by some of the stubs,
    //       but compilation fails when declaring that.
#elif defined(__arm__)
    __asm__ __volatile__(
        "push {r1-r12, lr}\n\t"     // Save state, 13*4B = 52B
        ".cfi_adjust_cfa_offset 52\n\t"
        "push {r9}\n\t"
        ".cfi_adjust_cfa_offset 4\n\t"
        "mov r9, %[referrer]\n\n"
        "str r9, [sp, #-8]!\n\t"   // Push referrer, +8B padding so 16B aligned
        ".cfi_adjust_cfa_offset 8\n\t"
        "ldr r9, [sp, #8]\n\t"

        // Push everything on the stack, so we don't rely on the order. What a mess. :-(
        "sub sp, sp, #24\n\t"
        "str %[arg0], [sp]\n\t"
        "str %[arg1], [sp, #4]\n\t"
        "str %[arg2], [sp, #8]\n\t"
        "str %[code], [sp, #12]\n\t"
        "str %[self], [sp, #16]\n\t"
        "str %[hidden], [sp, #20]\n\t"
        "ldr r0, [sp]\n\t"
        "ldr r1, [sp, #4]\n\t"
        "ldr r2, [sp, #8]\n\t"
        "ldr r3, [sp, #12]\n\t"
        "ldr r9, [sp, #16]\n\t"
        "ldr r12, [sp, #20]\n\t"
        "add sp, sp, #24\n\t"

        "blx r3\n\t"                // Call the stub
        "add sp, sp, #12\n\t"       // Pop nullptr and padding
        ".cfi_adjust_cfa_offset -12\n\t"
        "pop {r1-r12, lr}\n\t"      // Restore state
        ".cfi_adjust_cfa_offset -52\n\t"
        "mov %[result], r0\n\t"     // Save the result
        : [result] "=r" (result)
          // Use the result from r0
        : [arg0] "r"(arg0), [arg1] "r"(arg1), [arg2] "r"(arg2), [code] "r"(code), [self] "r"(self),
          [referrer] "r"(referrer), [hidden] "r"(hidden)
        : "memory");  // clobber.
#elif defined(__aarch64__)
    __asm__ __volatile__(
        // Spill x0-x7 which we say we don't clobber. May contain args.
        "sub sp, sp, #64\n\t"
        ".cfi_adjust_cfa_offset 64\n\t"
        "stp x0, x1, [sp]\n\t"
        "stp x2, x3, [sp, #16]\n\t"
        "stp x4, x5, [sp, #32]\n\t"
        "stp x6, x7, [sp, #48]\n\t"

        "sub sp, sp, #16\n\t"          // Reserve stack space, 16B aligned
        ".cfi_adjust_cfa_offset 16\n\t"
        "str %[referrer], [sp]\n\t"    // referrer

        // Push everything on the stack, so we don't rely on the order. What a mess. :-(
        "sub sp, sp, #48\n\t"
        ".cfi_adjust_cfa_offset 48\n\t"
        // All things are "r" constraints, so direct str/stp should work.
        "stp %[arg0], %[arg1], [sp]\n\t"
        "stp %[arg2], %[code], [sp, #16]\n\t"
        "stp %[self], %[hidden], [sp, #32]\n\t"

        // Now we definitely have x0-x3 free, use it to garble d8 - d15
        "movk x0, #0xfad0\n\t"
        "movk x0, #0xebad, lsl #16\n\t"
        "movk x0, #0xfad0, lsl #32\n\t"
        "movk x0, #0xebad, lsl #48\n\t"
        "fmov d8, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d9, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d10, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d11, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d12, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d13, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d14, x0\n\t"
        "add x0, x0, 1\n\t"
        "fmov d15, x0\n\t"

        // Load call params into the right registers.
        "ldp x0, x1, [sp]\n\t"
        "ldp x2, x3, [sp, #16]\n\t"
        "ldp x18, x17, [sp, #32]\n\t"
        "add sp, sp, #48\n\t"
        ".cfi_adjust_cfa_offset -48\n\t"

        "blr x3\n\t"              // Call the stub
        "mov x8, x0\n\t"          // Store result
        "add sp, sp, #16\n\t"     // Drop the quick "frame"
        ".cfi_adjust_cfa_offset -16\n\t"

        // Test d8 - d15. We can use x1 and x2.
        "movk x1, #0xfad0\n\t"
        "movk x1, #0xebad, lsl #16\n\t"
        "movk x1, #0xfad0, lsl #32\n\t"
        "movk x1, #0xebad, lsl #48\n\t"
        "fmov x2, d8\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d9\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d10\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d11\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d12\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d13\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d14\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"
        "add x1, x1, 1\n\t"

        "fmov x2, d15\n\t"
        "cmp x1, x2\n\t"
        "b.ne 1f\n\t"

        "mov x9, #0\n\t"              // Use x9 as flag, in clobber list

        // Finish up.
        "2:\n\t"
        "ldp x0, x1, [sp]\n\t"        // Restore stuff not named clobbered, may contain fpr_result
        "ldp x2, x3, [sp, #16]\n\t"
        "ldp x4, x5, [sp, #32]\n\t"
        "ldp x6, x7, [sp, #48]\n\t"
        "add sp, sp, #64\n\t"         // Free stack space, now sp as on entry
        ".cfi_adjust_cfa_offset -64\n\t"

        "str x9, %[fpr_result]\n\t"   // Store the FPR comparison result
        "mov %[result], x8\n\t"              // Store the call result

        "b 3f\n\t"                     // Goto end

        // Failed fpr verification.
        "1:\n\t"
        "mov x9, #1\n\t"
        "b 2b\n\t"                     // Goto finish-up

        // End
        "3:\n\t"
        : [result] "=r" (result)
          // Use the result from r0
        : [arg0] "0"(arg0), [arg1] "r"(arg1), [arg2] "r"(arg2), [code] "r"(code), [self] "r"(self),
          [referrer] "r"(referrer), [hidden] "r"(hidden), [fpr_result] "m" (fpr_result)
        : "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20",
          "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x30",
          "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
          "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
          "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
          "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
          "memory");  // clobber.
#elif defined(__x86_64__) && !defined(__APPLE__) && defined(__clang__)
    // Note: Uses the native convention
    // TODO: Set the thread?
    __asm__ __volatile__(
        "pushq %[referrer]\n\t"        // Push referrer
        "pushq (%%rsp)\n\t"            // & 16B alignment padding
        ".cfi_adjust_cfa_offset 16\n\t"
        "call *%%rbx\n\t"              // Call the stub
        "addq $16, %%rsp\n\t"          // Pop nullptr and padding
        ".cfi_adjust_cfa_offset -16\n\t"
        : "=a" (result)
        // Use the result from rax
        : "D"(arg0), "S"(arg1), "d"(arg2), "b"(code), [referrer] "c"(referrer), [hidden] "a"(hidden)
        // This places arg0 into rdi, arg1 into rsi, arg2 into rdx, and code into rax
        : "rbp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
          "memory");  // clobber all
    // TODO: Should we clobber the other registers?
#else
    UNUSED(arg0, arg1, arg2, code, referrer, hidden);
    LOG(WARNING) << "Was asked to invoke for an architecture I do not understand.";
    result = 0;
#endif
    // Pop transition.
    self->PopManagedStackFragment(fragment);

    fp_result = fpr_result;
    EXPECT_EQ(0U, fp_result);

    return result;
  }

  // Method with 32b arg0, 64b arg1
  size_t Invoke3UWithReferrer(size_t arg0, uint64_t arg1, uintptr_t code, Thread* self,
                              mirror::ArtMethod* referrer) {
#if (defined(__x86_64__) && !defined(__APPLE__)) || defined(__aarch64__)
    // Just pass through.
    return Invoke3WithReferrer(arg0, arg1, 0U, code, self, referrer);
#else
    // Need to split up arguments.
    uint32_t lower = static_cast<uint32_t>(arg1 & 0xFFFFFFFF);
    uint32_t upper = static_cast<uint32_t>((arg1 >> 32) & 0xFFFFFFFF);

    return Invoke3WithReferrer(arg0, lower, upper, code, self, referrer);
#endif
  }

  static uintptr_t GetEntrypoint(Thread* self, QuickEntrypointEnum entrypoint) {
    int32_t offset;
#ifdef __LP64__
    offset = GetThreadOffset<8>(entrypoint).Int32Value();
#else
    offset = GetThreadOffset<4>(entrypoint).Int32Value();
#endif
    return *reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(self) + offset);
  }

 protected:
  size_t fp_result;
};


TEST_F(StubTest, Memcpy) {
#if defined(__i386__) || (defined(__x86_64__) && !defined(__APPLE__))
  Thread* self = Thread::Current();

  uint32_t orig[20];
  uint32_t trg[20];
  for (size_t i = 0; i < 20; ++i) {
    orig[i] = i;
    trg[i] = 0;
  }

  Invoke3(reinterpret_cast<size_t>(&trg[4]), reinterpret_cast<size_t>(&orig[4]),
          10 * sizeof(uint32_t), StubTest::GetEntrypoint(self, kQuickMemcpy), self);

  EXPECT_EQ(orig[0], trg[0]);

  for (size_t i = 1; i < 4; ++i) {
    EXPECT_NE(orig[i], trg[i]);
  }

  for (size_t i = 4; i < 14; ++i) {
    EXPECT_EQ(orig[i], trg[i]);
  }

  for (size_t i = 14; i < 20; ++i) {
    EXPECT_NE(orig[i], trg[i]);
  }

  // TODO: Test overlapping?

#else
  LOG(INFO) << "Skipping memcpy as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping memcpy as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

TEST_F(StubTest, LockObject) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  static constexpr size_t kThinLockLoops = 100;

  Thread* self = Thread::Current();

  const uintptr_t art_quick_lock_object = StubTest::GetEntrypoint(self, kQuickLockObject);

  // Create an object
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  StackHandleScope<2> hs(soa.Self());
  Handle<mirror::String> obj(
      hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), "hello, world!")));
  LockWord lock = obj->GetLockWord(false);
  LockWord::LockState old_state = lock.GetState();
  EXPECT_EQ(LockWord::LockState::kUnlocked, old_state);

  Invoke3(reinterpret_cast<size_t>(obj.Get()), 0U, 0U, art_quick_lock_object, self);

  LockWord lock_after = obj->GetLockWord(false);
  LockWord::LockState new_state = lock_after.GetState();
  EXPECT_EQ(LockWord::LockState::kThinLocked, new_state);
  EXPECT_EQ(lock_after.ThinLockCount(), 0U);  // Thin lock starts count at zero

  for (size_t i = 1; i < kThinLockLoops; ++i) {
    Invoke3(reinterpret_cast<size_t>(obj.Get()), 0U, 0U, art_quick_lock_object, self);

    // Check we're at lock count i

    LockWord l_inc = obj->GetLockWord(false);
    LockWord::LockState l_inc_state = l_inc.GetState();
    EXPECT_EQ(LockWord::LockState::kThinLocked, l_inc_state);
    EXPECT_EQ(l_inc.ThinLockCount(), i);
  }

  // Force a fat lock by running identity hashcode to fill up lock word.
  Handle<mirror::String> obj2(hs.NewHandle(
      mirror::String::AllocFromModifiedUtf8(soa.Self(), "hello, world!")));

  obj2->IdentityHashCode();

  Invoke3(reinterpret_cast<size_t>(obj2.Get()), 0U, 0U, art_quick_lock_object, self);

  LockWord lock_after2 = obj2->GetLockWord(false);
  LockWord::LockState new_state2 = lock_after2.GetState();
  EXPECT_EQ(LockWord::LockState::kFatLocked, new_state2);
  EXPECT_NE(lock_after2.FatLockMonitor(), static_cast<Monitor*>(nullptr));

  // Test done.
#else
  LOG(INFO) << "Skipping lock_object as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping lock_object as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


class RandGen {
 public:
  explicit RandGen(uint32_t seed) : val_(seed) {}

  uint32_t next() {
    val_ = val_ * 48271 % 2147483647 + 13;
    return val_;
  }

  uint32_t val_;
};


// NO_THREAD_SAFETY_ANALYSIS as we do not want to grab exclusive mutator lock for MonitorInfo.
static void TestUnlockObject(StubTest* test) NO_THREAD_SAFETY_ANALYSIS {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  static constexpr size_t kThinLockLoops = 100;

  Thread* self = Thread::Current();

  const uintptr_t art_quick_lock_object = StubTest::GetEntrypoint(self, kQuickLockObject);
  const uintptr_t art_quick_unlock_object = StubTest::GetEntrypoint(self, kQuickUnlockObject);
  // Create an object
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init
  static constexpr size_t kNumberOfLocks = 10;  // Number of objects = lock
  StackHandleScope<kNumberOfLocks + 1> hs(self);
  Handle<mirror::String> obj(
      hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), "hello, world!")));
  LockWord lock = obj->GetLockWord(false);
  LockWord::LockState old_state = lock.GetState();
  EXPECT_EQ(LockWord::LockState::kUnlocked, old_state);

  test->Invoke3(reinterpret_cast<size_t>(obj.Get()), 0U, 0U, art_quick_unlock_object, self);
  // This should be an illegal monitor state.
  EXPECT_TRUE(self->IsExceptionPending());
  self->ClearException();

  LockWord lock_after = obj->GetLockWord(false);
  LockWord::LockState new_state = lock_after.GetState();
  EXPECT_EQ(LockWord::LockState::kUnlocked, new_state);

  test->Invoke3(reinterpret_cast<size_t>(obj.Get()), 0U, 0U, art_quick_lock_object, self);

  LockWord lock_after2 = obj->GetLockWord(false);
  LockWord::LockState new_state2 = lock_after2.GetState();
  EXPECT_EQ(LockWord::LockState::kThinLocked, new_state2);

  test->Invoke3(reinterpret_cast<size_t>(obj.Get()), 0U, 0U, art_quick_unlock_object, self);

  LockWord lock_after3 = obj->GetLockWord(false);
  LockWord::LockState new_state3 = lock_after3.GetState();
  EXPECT_EQ(LockWord::LockState::kUnlocked, new_state3);

  // Stress test:
  // Keep a number of objects and their locks in flight. Randomly lock or unlock one of them in
  // each step.

  RandGen r(0x1234);

  constexpr size_t kIterations = 10000;  // Number of iterations
  constexpr size_t kMoveToFat = 1000;     // Chance of 1:kMoveFat to make a lock fat.

  size_t counts[kNumberOfLocks];
  bool fat[kNumberOfLocks];  // Whether a lock should be thin or fat.
  Handle<mirror::String> objects[kNumberOfLocks];

  // Initialize = allocate.
  for (size_t i = 0; i < kNumberOfLocks; ++i) {
    counts[i] = 0;
    fat[i] = false;
    objects[i] = hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), ""));
  }

  for (size_t i = 0; i < kIterations; ++i) {
    // Select which lock to update.
    size_t index = r.next() % kNumberOfLocks;

    // Make lock fat?
    if (!fat[index] && (r.next() % kMoveToFat == 0)) {
      fat[index] = true;
      objects[index]->IdentityHashCode();

      LockWord lock_iter = objects[index]->GetLockWord(false);
      LockWord::LockState iter_state = lock_iter.GetState();
      if (counts[index] == 0) {
        EXPECT_EQ(LockWord::LockState::kHashCode, iter_state);
      } else {
        EXPECT_EQ(LockWord::LockState::kFatLocked, iter_state);
      }
    } else {
      bool take_lock;  // Whether to lock or unlock in this step.
      if (counts[index] == 0) {
        take_lock = true;
      } else if (counts[index] == kThinLockLoops) {
        take_lock = false;
      } else {
        // Randomly.
        take_lock = r.next() % 2 == 0;
      }

      if (take_lock) {
        test->Invoke3(reinterpret_cast<size_t>(objects[index].Get()), 0U, 0U, art_quick_lock_object,
                      self);
        counts[index]++;
      } else {
        test->Invoke3(reinterpret_cast<size_t>(objects[index].Get()), 0U, 0U,
                      art_quick_unlock_object, self);
        counts[index]--;
      }

      EXPECT_FALSE(self->IsExceptionPending());

      // Check the new state.
      LockWord lock_iter = objects[index]->GetLockWord(true);
      LockWord::LockState iter_state = lock_iter.GetState();
      if (fat[index]) {
        // Abuse MonitorInfo.
        EXPECT_EQ(LockWord::LockState::kFatLocked, iter_state) << index;
        MonitorInfo info(objects[index].Get());
        EXPECT_EQ(counts[index], info.entry_count_) << index;
      } else {
        if (counts[index] > 0) {
          EXPECT_EQ(LockWord::LockState::kThinLocked, iter_state);
          EXPECT_EQ(counts[index] - 1, lock_iter.ThinLockCount());
        } else {
          EXPECT_EQ(LockWord::LockState::kUnlocked, iter_state);
        }
      }
    }
  }

  // Unlock the remaining count times and then check it's unlocked. Then deallocate.
  // Go reverse order to correctly handle Handles.
  for (size_t i = 0; i < kNumberOfLocks; ++i) {
    size_t index = kNumberOfLocks - 1 - i;
    size_t count = counts[index];
    while (count > 0) {
      test->Invoke3(reinterpret_cast<size_t>(objects[index].Get()), 0U, 0U, art_quick_unlock_object,
                    self);
      count--;
    }

    LockWord lock_after4 = objects[index]->GetLockWord(false);
    LockWord::LockState new_state4 = lock_after4.GetState();
    EXPECT_TRUE(LockWord::LockState::kUnlocked == new_state4
                || LockWord::LockState::kFatLocked == new_state4);
  }

  // Test done.
#else
  UNUSED(test);
  LOG(INFO) << "Skipping unlock_object as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping unlock_object as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

TEST_F(StubTest, UnlockObject) {
  // This will lead to monitor error messages in the log.
  ScopedLogSeverity sls(LogSeverity::FATAL);

  TestUnlockObject(this);
}

#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
extern "C" void art_quick_check_cast(void);
#endif

TEST_F(StubTest, CheckCast) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  Thread* self = Thread::Current();

  const uintptr_t art_quick_check_cast = StubTest::GetEntrypoint(self, kQuickCheckCast);

  // Find some classes.
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  StackHandleScope<2> hs(soa.Self());
  Handle<mirror::Class> c(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;")));
  Handle<mirror::Class> c2(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;")));

  EXPECT_FALSE(self->IsExceptionPending());

  Invoke3(reinterpret_cast<size_t>(c.Get()), reinterpret_cast<size_t>(c.Get()), 0U,
          art_quick_check_cast, self);

  EXPECT_FALSE(self->IsExceptionPending());

  Invoke3(reinterpret_cast<size_t>(c2.Get()), reinterpret_cast<size_t>(c2.Get()), 0U,
          art_quick_check_cast, self);

  EXPECT_FALSE(self->IsExceptionPending());

  Invoke3(reinterpret_cast<size_t>(c.Get()), reinterpret_cast<size_t>(c2.Get()), 0U,
          art_quick_check_cast, self);

  EXPECT_FALSE(self->IsExceptionPending());

  // TODO: Make the following work. But that would require correct managed frames.

  Invoke3(reinterpret_cast<size_t>(c2.Get()), reinterpret_cast<size_t>(c.Get()), 0U,
          art_quick_check_cast, self);

  EXPECT_TRUE(self->IsExceptionPending());
  self->ClearException();

#else
  LOG(INFO) << "Skipping check_cast as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping check_cast as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


TEST_F(StubTest, APutObj) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  Thread* self = Thread::Current();

  // Do not check non-checked ones, we'd need handlers and stuff...
  const uintptr_t art_quick_aput_obj_with_null_and_bound_check =
      StubTest::GetEntrypoint(self, kQuickAputObjectWithNullAndBoundCheck);

  // Create an object
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  StackHandleScope<5> hs(soa.Self());
  Handle<mirror::Class> c(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;")));
  Handle<mirror::Class> ca(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;")));

  // Build a string array of size 1
  Handle<mirror::ObjectArray<mirror::Object>> array(
      hs.NewHandle(mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), ca.Get(), 10)));

  // Build a string -> should be assignable
  Handle<mirror::String> str_obj(
      hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), "hello, world!")));

  // Build a generic object -> should fail assigning
  Handle<mirror::Object> obj_obj(hs.NewHandle(c->AllocObject(soa.Self())));

  // Play with it...

  // 1) Success cases
  // 1.1) Assign str_obj to array[0..3]

  EXPECT_FALSE(self->IsExceptionPending());

  Invoke3(reinterpret_cast<size_t>(array.Get()), 0U, reinterpret_cast<size_t>(str_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(str_obj.Get(), array->Get(0));

  Invoke3(reinterpret_cast<size_t>(array.Get()), 1U, reinterpret_cast<size_t>(str_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(str_obj.Get(), array->Get(1));

  Invoke3(reinterpret_cast<size_t>(array.Get()), 2U, reinterpret_cast<size_t>(str_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(str_obj.Get(), array->Get(2));

  Invoke3(reinterpret_cast<size_t>(array.Get()), 3U, reinterpret_cast<size_t>(str_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(str_obj.Get(), array->Get(3));

  // 1.2) Assign null to array[0..3]

  Invoke3(reinterpret_cast<size_t>(array.Get()), 0U, reinterpret_cast<size_t>(nullptr),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(nullptr, array->Get(0));

  Invoke3(reinterpret_cast<size_t>(array.Get()), 1U, reinterpret_cast<size_t>(nullptr),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(nullptr, array->Get(1));

  Invoke3(reinterpret_cast<size_t>(array.Get()), 2U, reinterpret_cast<size_t>(nullptr),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(nullptr, array->Get(2));

  Invoke3(reinterpret_cast<size_t>(array.Get()), 3U, reinterpret_cast<size_t>(nullptr),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(nullptr, array->Get(3));

  // TODO: Check _which_ exception is thrown. Then make 3) check that it's the right check order.

  // 2) Failure cases (str into str[])
  // 2.1) Array = null
  // TODO: Throwing NPE needs actual DEX code

//  Invoke3(reinterpret_cast<size_t>(nullptr), 0U, reinterpret_cast<size_t>(str_obj.Get()),
//          reinterpret_cast<uintptr_t>(&art_quick_aput_obj_with_null_and_bound_check), self);
//
//  EXPECT_TRUE(self->IsExceptionPending());
//  self->ClearException();

  // 2.2) Index < 0

  Invoke3(reinterpret_cast<size_t>(array.Get()), static_cast<size_t>(-1),
          reinterpret_cast<size_t>(str_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_TRUE(self->IsExceptionPending());
  self->ClearException();

  // 2.3) Index > 0

  Invoke3(reinterpret_cast<size_t>(array.Get()), 10U, reinterpret_cast<size_t>(str_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_TRUE(self->IsExceptionPending());
  self->ClearException();

  // 3) Failure cases (obj into str[])

  Invoke3(reinterpret_cast<size_t>(array.Get()), 0U, reinterpret_cast<size_t>(obj_obj.Get()),
          art_quick_aput_obj_with_null_and_bound_check, self);

  EXPECT_TRUE(self->IsExceptionPending());
  self->ClearException();

  // Tests done.
#else
  LOG(INFO) << "Skipping aput_obj as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping aput_obj as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

TEST_F(StubTest, AllocObject) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  // This will lead to OOM  error messages in the log.
  ScopedLogSeverity sls(LogSeverity::FATAL);

  // TODO: Check the "Unresolved" allocation stubs

  Thread* self = Thread::Current();
  // Create an object
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  StackHandleScope<2> hs(soa.Self());
  Handle<mirror::Class> c(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;")));

  // Play with it...

  EXPECT_FALSE(self->IsExceptionPending());
  {
    // Use an arbitrary method from c to use as referrer
    size_t result = Invoke3(static_cast<size_t>(c->GetDexTypeIndex()),    // type_idx
                            reinterpret_cast<size_t>(c->GetVirtualMethod(0)),  // arbitrary
                            0U,
                            StubTest::GetEntrypoint(self, kQuickAllocObject),
                            self);

    EXPECT_FALSE(self->IsExceptionPending());
    EXPECT_NE(reinterpret_cast<size_t>(nullptr), result);
    mirror::Object* obj = reinterpret_cast<mirror::Object*>(result);
    EXPECT_EQ(c.Get(), obj->GetClass());
    VerifyObject(obj);
  }

  {
    // We can use nullptr in the second argument as we do not need a method here (not used in
    // resolved/initialized cases)
    size_t result = Invoke3(reinterpret_cast<size_t>(c.Get()), reinterpret_cast<size_t>(nullptr), 0U,
                            StubTest::GetEntrypoint(self, kQuickAllocObjectResolved),
                            self);

    EXPECT_FALSE(self->IsExceptionPending());
    EXPECT_NE(reinterpret_cast<size_t>(nullptr), result);
    mirror::Object* obj = reinterpret_cast<mirror::Object*>(result);
    EXPECT_EQ(c.Get(), obj->GetClass());
    VerifyObject(obj);
  }

  {
    // We can use nullptr in the second argument as we do not need a method here (not used in
    // resolved/initialized cases)
    size_t result = Invoke3(reinterpret_cast<size_t>(c.Get()), reinterpret_cast<size_t>(nullptr), 0U,
                            StubTest::GetEntrypoint(self, kQuickAllocObjectInitialized),
                            self);

    EXPECT_FALSE(self->IsExceptionPending());
    EXPECT_NE(reinterpret_cast<size_t>(nullptr), result);
    mirror::Object* obj = reinterpret_cast<mirror::Object*>(result);
    EXPECT_EQ(c.Get(), obj->GetClass());
    VerifyObject(obj);
  }

  // Failure tests.

  // Out-of-memory.
  {
    Runtime::Current()->GetHeap()->SetIdealFootprint(1 * GB);

    // Array helps to fill memory faster.
    Handle<mirror::Class> ca(
        hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;")));

    // Use arbitrary large amount for now.
    static const size_t kMaxHandles = 1000000;
    std::unique_ptr<StackHandleScope<kMaxHandles>> hsp(new StackHandleScope<kMaxHandles>(self));

    std::vector<Handle<mirror::Object>> handles;
    // Start allocating with 128K
    size_t length = 128 * KB / 4;
    while (length > 10) {
      Handle<mirror::Object> h(hsp->NewHandle<mirror::Object>(
          mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), ca.Get(), length / 4)));
      if (self->IsExceptionPending() || h.Get() == nullptr) {
        self->ClearException();

        // Try a smaller length
        length = length / 8;
        // Use at most half the reported free space.
        size_t mem = Runtime::Current()->GetHeap()->GetFreeMemory();
        if (length * 8 > mem) {
          length = mem / 8;
        }
      } else {
        handles.push_back(h);
      }
    }
    LOG(INFO) << "Used " << handles.size() << " arrays to fill space.";

    // Allocate simple objects till it fails.
    while (!self->IsExceptionPending()) {
      Handle<mirror::Object> h = hsp->NewHandle(c->AllocObject(soa.Self()));
      if (!self->IsExceptionPending() && h.Get() != nullptr) {
        handles.push_back(h);
      }
    }
    self->ClearException();

    size_t result = Invoke3(reinterpret_cast<size_t>(c.Get()), reinterpret_cast<size_t>(nullptr), 0U,
                            StubTest::GetEntrypoint(self, kQuickAllocObjectInitialized),
                            self);
    EXPECT_TRUE(self->IsExceptionPending());
    self->ClearException();
    EXPECT_EQ(reinterpret_cast<size_t>(nullptr), result);
  }

  // Tests done.
#else
  LOG(INFO) << "Skipping alloc_object as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping alloc_object as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

TEST_F(StubTest, AllocObjectArray) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  // TODO: Check the "Unresolved" allocation stubs

  // This will lead to OOM  error messages in the log.
  ScopedLogSeverity sls(LogSeverity::FATAL);

  Thread* self = Thread::Current();
  // Create an object
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  StackHandleScope<2> hs(self);
  Handle<mirror::Class> c(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;")));

  // Needed to have a linked method.
  Handle<mirror::Class> c_obj(
      hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;")));

  // Play with it...

  EXPECT_FALSE(self->IsExceptionPending());

  // For some reason this does not work, as the type_idx is artificial and outside what the
  // resolved types of c_obj allow...

  if ((false)) {
    // Use an arbitrary method from c to use as referrer
    size_t result = Invoke3(static_cast<size_t>(c->GetDexTypeIndex()),    // type_idx
                            10U,
                            reinterpret_cast<size_t>(c_obj->GetVirtualMethod(0)),  // arbitrary
                            StubTest::GetEntrypoint(self, kQuickAllocArray),
                            self);

    EXPECT_FALSE(self->IsExceptionPending());
    EXPECT_NE(reinterpret_cast<size_t>(nullptr), result);
    mirror::Array* obj = reinterpret_cast<mirror::Array*>(result);
    EXPECT_EQ(c.Get(), obj->GetClass());
    VerifyObject(obj);
    EXPECT_EQ(obj->GetLength(), 10);
  }

  {
    // We can use nullptr in the second argument as we do not need a method here (not used in
    // resolved/initialized cases)
    size_t result = Invoke3(reinterpret_cast<size_t>(c.Get()), 10U,
                            reinterpret_cast<size_t>(nullptr),
                            StubTest::GetEntrypoint(self, kQuickAllocArrayResolved),
                            self);
    EXPECT_FALSE(self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
    EXPECT_NE(reinterpret_cast<size_t>(nullptr), result);
    mirror::Object* obj = reinterpret_cast<mirror::Object*>(result);
    EXPECT_TRUE(obj->IsArrayInstance());
    EXPECT_TRUE(obj->IsObjectArray());
    EXPECT_EQ(c.Get(), obj->GetClass());
    VerifyObject(obj);
    mirror::Array* array = reinterpret_cast<mirror::Array*>(result);
    EXPECT_EQ(array->GetLength(), 10);
  }

  // Failure tests.

  // Out-of-memory.
  {
    size_t result = Invoke3(reinterpret_cast<size_t>(c.Get()),
                            GB,  // that should fail...
                            reinterpret_cast<size_t>(nullptr),
                            StubTest::GetEntrypoint(self, kQuickAllocArrayResolved),
                            self);

    EXPECT_TRUE(self->IsExceptionPending());
    self->ClearException();
    EXPECT_EQ(reinterpret_cast<size_t>(nullptr), result);
  }

  // Tests done.
#else
  LOG(INFO) << "Skipping alloc_array as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping alloc_array as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


TEST_F(StubTest, StringCompareTo) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  // TODO: Check the "Unresolved" allocation stubs

  Thread* self = Thread::Current();

  const uintptr_t art_quick_string_compareto = StubTest::GetEntrypoint(self, kQuickStringCompareTo);

  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  // Create some strings
  // Use array so we can index into it and use a matrix for expected results
  // Setup: The first half is standard. The second half uses a non-zero offset.
  // TODO: Shared backing arrays.
  const char* c[] = { "", "", "a", "aa", "ab",
      "aacaacaacaacaacaac",  // This one's under the default limit to go to __memcmp16.
      "aacaacaacaacaacaacaacaacaacaacaacaac",     // This one's over.
      "aacaacaacaacaacaacaacaacaacaacaacaaca" };  // As is this one. We need a separate one to
                                                  // defeat object-equal optimizations.
  static constexpr size_t kBaseStringCount  = arraysize(c);
  static constexpr size_t kStringCount = 2 * kBaseStringCount;

  StackHandleScope<kStringCount> hs(self);
  Handle<mirror::String> s[kStringCount];

  for (size_t i = 0; i < kBaseStringCount; ++i) {
    s[i] = hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), c[i]));
  }

  RandGen r(0x1234);

  for (size_t i = kBaseStringCount; i < kStringCount; ++i) {
    s[i] = hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), c[i - kBaseStringCount]));
    int32_t length = s[i]->GetLength();
    if (length > 1) {
      // Set a random offset and length.
      int32_t new_offset = 1 + (r.next() % (length - 1));
      int32_t rest = length - new_offset - 1;
      int32_t new_length = 1 + (rest > 0 ? r.next() % rest : 0);

      s[i]->SetField32<false>(mirror::String::CountOffset(), new_length);
      s[i]->SetField32<false>(mirror::String::OffsetOffset(), new_offset);
    }
  }

  // TODO: wide characters

  // Matrix of expectations. First component is first parameter. Note we only check against the
  // sign, not the value. As we are testing random offsets, we need to compute this and need to
  // rely on String::CompareTo being correct.
  int32_t expected[kStringCount][kStringCount];
  for (size_t x = 0; x < kStringCount; ++x) {
    for (size_t y = 0; y < kStringCount; ++y) {
      expected[x][y] = s[x]->CompareTo(s[y].Get());
    }
  }

  // Play with it...

  for (size_t x = 0; x < kStringCount; ++x) {
    for (size_t y = 0; y < kStringCount; ++y) {
      // Test string_compareto x y
      size_t result = Invoke3(reinterpret_cast<size_t>(s[x].Get()),
                              reinterpret_cast<size_t>(s[y].Get()), 0U,
                              art_quick_string_compareto, self);

      EXPECT_FALSE(self->IsExceptionPending());

      // The result is a 32b signed integer
      union {
        size_t r;
        int32_t i;
      } conv;
      conv.r = result;
      int32_t e = expected[x][y];
      EXPECT_TRUE(e == 0 ? conv.i == 0 : true) << "x=" << c[x] << " y=" << c[y] << " res=" <<
          conv.r;
      EXPECT_TRUE(e < 0 ? conv.i < 0 : true)   << "x=" << c[x] << " y="  << c[y] << " res=" <<
          conv.r;
      EXPECT_TRUE(e > 0 ? conv.i > 0 : true)   << "x=" << c[x] << " y=" << c[y] << " res=" <<
          conv.r;
    }
  }

  // TODO: Deallocate things.

  // Tests done.
#else
  LOG(INFO) << "Skipping string_compareto as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping string_compareto as I don't know how to do that on " << kRuntimeISA <<
      std::endl;
#endif
}


static void GetSetBooleanStatic(ArtField* f, Thread* self,
                                mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  constexpr size_t num_values = 5;
  uint8_t values[num_values] = { 0, 1, 2, 128, 0xFF };

  for (size_t i = 0; i < num_values; ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              static_cast<size_t>(values[i]),
                              0U,
                              StubTest::GetEntrypoint(self, kQuickSet8Static),
                              self,
                              referrer);

    size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                           0U, 0U,
                                           StubTest::GetEntrypoint(self, kQuickGetBooleanStatic),
                                           self,
                                           referrer);
    // Boolean currently stores bools as uint8_t, be more zealous about asserting correct writes/gets.
    EXPECT_EQ(values[i], static_cast<uint8_t>(res)) << "Iteration " << i;
  }
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping set_boolean_static as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_boolean_static as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}
static void GetSetByteStatic(ArtField* f, Thread* self, mirror::ArtMethod* referrer,
                             StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  int8_t values[] = { -128, -64, 0, 64, 127 };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              static_cast<size_t>(values[i]),
                              0U,
                              StubTest::GetEntrypoint(self, kQuickSet8Static),
                              self,
                              referrer);

    size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                           0U, 0U,
                                           StubTest::GetEntrypoint(self, kQuickGetByteStatic),
                                           self,
                                           referrer);
    EXPECT_EQ(values[i], static_cast<int8_t>(res)) << "Iteration " << i;
  }
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping set_byte_static as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_byte_static as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


static void GetSetBooleanInstance(Handle<mirror::Object>* obj, ArtField* f, Thread* self,
                                  mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  uint8_t values[] = { 0, true, 2, 128, 0xFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              reinterpret_cast<size_t>(obj->Get()),
                              static_cast<size_t>(values[i]),
                              StubTest::GetEntrypoint(self, kQuickSet8Instance),
                              self,
                              referrer);

    uint8_t res = f->GetBoolean(obj->Get());
    EXPECT_EQ(values[i], res) << "Iteration " << i;

    f->SetBoolean<false>(obj->Get(), res);

    size_t res2 = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                            reinterpret_cast<size_t>(obj->Get()),
                                            0U,
                                            StubTest::GetEntrypoint(self, kQuickGetBooleanInstance),
                                            self,
                                            referrer);
    EXPECT_EQ(res, static_cast<uint8_t>(res2));
  }
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping set_boolean_instance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_boolean_instance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}
static void GetSetByteInstance(Handle<mirror::Object>* obj, ArtField* f,
                             Thread* self, mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  int8_t values[] = { -128, -64, 0, 64, 127 };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              reinterpret_cast<size_t>(obj->Get()),
                              static_cast<size_t>(values[i]),
                              StubTest::GetEntrypoint(self, kQuickSet8Instance),
                              self,
                              referrer);

    int8_t res = f->GetByte(obj->Get());
    EXPECT_EQ(res, values[i]) << "Iteration " << i;
    f->SetByte<false>(obj->Get(), ++res);

    size_t res2 = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                            reinterpret_cast<size_t>(obj->Get()),
                                            0U,
                                            StubTest::GetEntrypoint(self, kQuickGetByteInstance),
                                            self,
                                            referrer);
    EXPECT_EQ(res, static_cast<int8_t>(res2));
  }
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping set_byte_instance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_byte_instance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

static void GetSetCharStatic(ArtField* f, Thread* self, mirror::ArtMethod* referrer,
                             StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  uint16_t values[] = { 0, 1, 2, 255, 32768, 0xFFFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              static_cast<size_t>(values[i]),
                              0U,
                              StubTest::GetEntrypoint(self, kQuickSet16Static),
                              self,
                              referrer);

    size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                           0U, 0U,
                                           StubTest::GetEntrypoint(self, kQuickGetCharStatic),
                                           self,
                                           referrer);

    EXPECT_EQ(values[i], static_cast<uint16_t>(res)) << "Iteration " << i;
  }
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping set_char_static as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_char_static as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}
static void GetSetShortStatic(ArtField* f, Thread* self,
                              mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  int16_t values[] = { -0x7FFF, -32768, 0, 255, 32767, 0x7FFE };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              static_cast<size_t>(values[i]),
                              0U,
                              StubTest::GetEntrypoint(self, kQuickSet16Static),
                              self,
                              referrer);

    size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                           0U, 0U,
                                           StubTest::GetEntrypoint(self, kQuickGetShortStatic),
                                           self,
                                           referrer);

    EXPECT_EQ(static_cast<int16_t>(res), values[i]) << "Iteration " << i;
  }
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping set_short_static as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_short_static as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

static void GetSetCharInstance(Handle<mirror::Object>* obj, ArtField* f,
                               Thread* self, mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  uint16_t values[] = { 0, 1, 2, 255, 32768, 0xFFFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              reinterpret_cast<size_t>(obj->Get()),
                              static_cast<size_t>(values[i]),
                              StubTest::GetEntrypoint(self, kQuickSet16Instance),
                              self,
                              referrer);

    uint16_t res = f->GetChar(obj->Get());
    EXPECT_EQ(res, values[i]) << "Iteration " << i;
    f->SetChar<false>(obj->Get(), ++res);

    size_t res2 = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                            reinterpret_cast<size_t>(obj->Get()),
                                            0U,
                                            StubTest::GetEntrypoint(self, kQuickGetCharInstance),
                                            self,
                                            referrer);
    EXPECT_EQ(res, static_cast<uint16_t>(res2));
  }
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping set_char_instance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_char_instance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}
static void GetSetShortInstance(Handle<mirror::Object>* obj, ArtField* f,
                             Thread* self, mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  int16_t values[] = { -0x7FFF, -32768, 0, 255, 32767, 0x7FFE };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              reinterpret_cast<size_t>(obj->Get()),
                              static_cast<size_t>(values[i]),
                              StubTest::GetEntrypoint(self, kQuickSet16Instance),
                              self,
                              referrer);

    int16_t res = f->GetShort(obj->Get());
    EXPECT_EQ(res, values[i]) << "Iteration " << i;
    f->SetShort<false>(obj->Get(), ++res);

    size_t res2 = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                            reinterpret_cast<size_t>(obj->Get()),
                                            0U,
                                            StubTest::GetEntrypoint(self, kQuickGetShortInstance),
                                            self,
                                            referrer);
    EXPECT_EQ(res, static_cast<int16_t>(res2));
  }
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping set_short_instance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set_short_instance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

static void GetSet32Static(ArtField* f, Thread* self, mirror::ArtMethod* referrer,
                           StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  uint32_t values[] = { 0, 1, 2, 255, 32768, 1000000, 0xFFFFFFFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              static_cast<size_t>(values[i]),
                              0U,
                              StubTest::GetEntrypoint(self, kQuickSet32Static),
                              self,
                              referrer);

    size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                           0U, 0U,
                                           StubTest::GetEntrypoint(self, kQuickGet32Static),
                                           self,
                                           referrer);

    EXPECT_EQ(res, values[i]) << "Iteration " << i;
  }
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping set32static as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set32static as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


static void GetSet32Instance(Handle<mirror::Object>* obj, ArtField* f,
                             Thread* self, mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  uint32_t values[] = { 0, 1, 2, 255, 32768, 1000000, 0xFFFFFFFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              reinterpret_cast<size_t>(obj->Get()),
                              static_cast<size_t>(values[i]),
                              StubTest::GetEntrypoint(self, kQuickSet32Instance),
                              self,
                              referrer);

    int32_t res = f->GetInt(obj->Get());
    EXPECT_EQ(res, static_cast<int32_t>(values[i])) << "Iteration " << i;

    res++;
    f->SetInt<false>(obj->Get(), res);

    size_t res2 = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                            reinterpret_cast<size_t>(obj->Get()),
                                            0U,
                                            StubTest::GetEntrypoint(self, kQuickGet32Instance),
                                            self,
                                            referrer);
    EXPECT_EQ(res, static_cast<int32_t>(res2));
  }
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping set32instance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set32instance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))

static void set_and_check_static(uint32_t f_idx, mirror::Object* val, Thread* self,
                                 mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
  test->Invoke3WithReferrer(static_cast<size_t>(f_idx),
                            reinterpret_cast<size_t>(val),
                            0U,
                            StubTest::GetEntrypoint(self, kQuickSetObjStatic),
                            self,
                            referrer);

  size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f_idx),
                                         0U, 0U,
                                         StubTest::GetEntrypoint(self, kQuickGetObjStatic),
                                         self,
                                         referrer);

  EXPECT_EQ(res, reinterpret_cast<size_t>(val)) << "Value " << val;
}
#endif

static void GetSetObjStatic(ArtField* f, Thread* self, mirror::ArtMethod* referrer,
                            StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  set_and_check_static(f->GetDexFieldIndex(), nullptr, self, referrer, test);

  // Allocate a string object for simplicity.
  mirror::String* str = mirror::String::AllocFromModifiedUtf8(self, "Test");
  set_and_check_static(f->GetDexFieldIndex(), str, self, referrer, test);

  set_and_check_static(f->GetDexFieldIndex(), nullptr, self, referrer, test);
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping setObjstatic as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping setObjstatic as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
static void set_and_check_instance(ArtField* f, mirror::Object* trg,
                                   mirror::Object* val, Thread* self, mirror::ArtMethod* referrer,
                                   StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
  test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                            reinterpret_cast<size_t>(trg),
                            reinterpret_cast<size_t>(val),
                            StubTest::GetEntrypoint(self, kQuickSetObjInstance),
                            self,
                            referrer);

  size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                         reinterpret_cast<size_t>(trg),
                                         0U,
                                         StubTest::GetEntrypoint(self, kQuickGetObjInstance),
                                         self,
                                         referrer);

  EXPECT_EQ(res, reinterpret_cast<size_t>(val)) << "Value " << val;

  EXPECT_EQ(val, f->GetObj(trg));
}
#endif

static void GetSetObjInstance(Handle<mirror::Object>* obj, ArtField* f,
                              Thread* self, mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  set_and_check_instance(f, obj->Get(), nullptr, self, referrer, test);

  // Allocate a string object for simplicity.
  mirror::String* str = mirror::String::AllocFromModifiedUtf8(self, "Test");
  set_and_check_instance(f, obj->Get(), str, self, referrer, test);

  set_and_check_instance(f, obj->Get(), nullptr, self, referrer, test);
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping setObjinstance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping setObjinstance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


// TODO: Complete these tests for 32b architectures.

static void GetSet64Static(ArtField* f, Thread* self, mirror::ArtMethod* referrer,
                           StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if (defined(__x86_64__) && !defined(__APPLE__)) || defined(__aarch64__)
  uint64_t values[] = { 0, 1, 2, 255, 32768, 1000000, 0xFFFFFFFF, 0xFFFFFFFFFFFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3UWithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                               values[i],
                               StubTest::GetEntrypoint(self, kQuickSet64Static),
                               self,
                               referrer);

    size_t res = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                           0U, 0U,
                                           StubTest::GetEntrypoint(self, kQuickGet64Static),
                                           self,
                                           referrer);

    EXPECT_EQ(res, values[i]) << "Iteration " << i;
  }
#else
  UNUSED(f, self, referrer, test);
  LOG(INFO) << "Skipping set64static as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set64static as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}


static void GetSet64Instance(Handle<mirror::Object>* obj, ArtField* f,
                             Thread* self, mirror::ArtMethod* referrer, StubTest* test)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
#if (defined(__x86_64__) && !defined(__APPLE__)) || defined(__aarch64__)
  uint64_t values[] = { 0, 1, 2, 255, 32768, 1000000, 0xFFFFFFFF, 0xFFFFFFFFFFFF };

  for (size_t i = 0; i < arraysize(values); ++i) {
    test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                              reinterpret_cast<size_t>(obj->Get()),
                              static_cast<size_t>(values[i]),
                              StubTest::GetEntrypoint(self, kQuickSet64Instance),
                              self,
                              referrer);

    int64_t res = f->GetLong(obj->Get());
    EXPECT_EQ(res, static_cast<int64_t>(values[i])) << "Iteration " << i;

    res++;
    f->SetLong<false>(obj->Get(), res);

    size_t res2 = test->Invoke3WithReferrer(static_cast<size_t>(f->GetDexFieldIndex()),
                                            reinterpret_cast<size_t>(obj->Get()),
                                            0U,
                                            StubTest::GetEntrypoint(self, kQuickGet64Instance),
                                            self,
                                            referrer);
    EXPECT_EQ(res, static_cast<int64_t>(res2));
  }
#else
  UNUSED(obj, f, self, referrer, test);
  LOG(INFO) << "Skipping set64instance as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping set64instance as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

static void TestFields(Thread* self, StubTest* test, Primitive::Type test_type) {
  // garbage is created during ClassLinker::Init

  JNIEnv* env = Thread::Current()->GetJniEnv();
  jclass jc = env->FindClass("AllFields");
  CHECK(jc != NULL);
  jobject o = env->AllocObject(jc);
  CHECK(o != NULL);

  ScopedObjectAccess soa(self);
  StackHandleScope<4> hs(self);
  Handle<mirror::Object> obj(hs.NewHandle(soa.Decode<mirror::Object*>(o)));
  Handle<mirror::Class> c(hs.NewHandle(obj->GetClass()));
  // Need a method as a referrer
  Handle<mirror::ArtMethod> m(hs.NewHandle(c->GetDirectMethod(0)));

  // Play with it...

  // Static fields.
  ArtField* fields = c->GetSFields();
  size_t num_fields = c->NumStaticFields();
  for (size_t i = 0; i < num_fields; ++i) {
    ArtField* f = &fields[i];
    Primitive::Type type = f->GetTypeAsPrimitiveType();
    if (test_type != type) {
     continue;
    }
    switch (type) {
      case Primitive::Type::kPrimBoolean:
        GetSetBooleanStatic(f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimByte:
        GetSetByteStatic(f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimChar:
        GetSetCharStatic(f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimShort:
        GetSetShortStatic(f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimInt:
        GetSet32Static(f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimLong:
        GetSet64Static(f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimNot:
        // Don't try array.
        if (f->GetTypeDescriptor()[0] != '[') {
          GetSetObjStatic(f, self, m.Get(), test);
        }
        break;
      default:
        break;  // Skip.
    }
  }

  // Instance fields.
  fields = c->GetIFields();
  num_fields = c->NumInstanceFields();
  for (size_t i = 0; i < num_fields; ++i) {
    ArtField* f = &fields[i];
    Primitive::Type type = f->GetTypeAsPrimitiveType();
    if (test_type != type) {
      continue;
    }
    switch (type) {
      case Primitive::Type::kPrimBoolean:
        GetSetBooleanInstance(&obj, f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimByte:
        GetSetByteInstance(&obj, f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimChar:
        GetSetCharInstance(&obj, f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimShort:
        GetSetShortInstance(&obj, f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimInt:
        GetSet32Instance(&obj, f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimLong:
        GetSet64Instance(&obj, f, self, m.Get(), test);
        break;
      case Primitive::Type::kPrimNot:
        // Don't try array.
        if (f->GetTypeDescriptor()[0] != '[') {
          GetSetObjInstance(&obj, f, self, m.Get(), test);
        }
        break;
      default:
        break;  // Skip.
    }
  }

  // TODO: Deallocate things.
}

TEST_F(StubTest, Fields8) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();

  self->TransitionFromSuspendedToRunnable();
  LoadDex("AllFields");
  bool started = runtime_->Start();
  CHECK(started);

  TestFields(self, this, Primitive::Type::kPrimBoolean);
  TestFields(self, this, Primitive::Type::kPrimByte);
}

TEST_F(StubTest, Fields16) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();

  self->TransitionFromSuspendedToRunnable();
  LoadDex("AllFields");
  bool started = runtime_->Start();
  CHECK(started);

  TestFields(self, this, Primitive::Type::kPrimChar);
  TestFields(self, this, Primitive::Type::kPrimShort);
}

TEST_F(StubTest, Fields32) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();

  self->TransitionFromSuspendedToRunnable();
  LoadDex("AllFields");
  bool started = runtime_->Start();
  CHECK(started);

  TestFields(self, this, Primitive::Type::kPrimInt);
}

TEST_F(StubTest, FieldsObj) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();

  self->TransitionFromSuspendedToRunnable();
  LoadDex("AllFields");
  bool started = runtime_->Start();
  CHECK(started);

  TestFields(self, this, Primitive::Type::kPrimNot);
}

TEST_F(StubTest, Fields64) {
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();

  self->TransitionFromSuspendedToRunnable();
  LoadDex("AllFields");
  bool started = runtime_->Start();
  CHECK(started);

  TestFields(self, this, Primitive::Type::kPrimLong);
}

TEST_F(StubTest, IMT) {
#if defined(__i386__) || defined(__arm__) || defined(__aarch64__) || (defined(__x86_64__) && !defined(__APPLE__))
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();

  ScopedObjectAccess soa(self);
  StackHandleScope<7> hs(self);

  JNIEnv* env = Thread::Current()->GetJniEnv();

  // ArrayList

  // Load ArrayList and used methods (JNI).
  jclass arraylist_jclass = env->FindClass("java/util/ArrayList");
  ASSERT_NE(nullptr, arraylist_jclass);
  jmethodID arraylist_constructor = env->GetMethodID(arraylist_jclass, "<init>", "()V");
  ASSERT_NE(nullptr, arraylist_constructor);
  jmethodID contains_jmethod = env->GetMethodID(arraylist_jclass, "contains", "(Ljava/lang/Object;)Z");
  ASSERT_NE(nullptr, contains_jmethod);
  jmethodID add_jmethod = env->GetMethodID(arraylist_jclass, "add", "(Ljava/lang/Object;)Z");
  ASSERT_NE(nullptr, add_jmethod);

  // Get mirror representation.
  Handle<mirror::ArtMethod> contains_amethod(hs.NewHandle(soa.DecodeMethod(contains_jmethod)));

  // Patch up ArrayList.contains.
  if (contains_amethod.Get()->GetEntryPointFromQuickCompiledCode() == nullptr) {
    contains_amethod.Get()->SetEntryPointFromQuickCompiledCode(reinterpret_cast<void*>(
        StubTest::GetEntrypoint(self, kQuickQuickToInterpreterBridge)));
  }

  // List

  // Load List and used methods (JNI).
  jclass list_jclass = env->FindClass("java/util/List");
  ASSERT_NE(nullptr, list_jclass);
  jmethodID inf_contains_jmethod = env->GetMethodID(list_jclass, "contains", "(Ljava/lang/Object;)Z");
  ASSERT_NE(nullptr, inf_contains_jmethod);

  // Get mirror representation.
  Handle<mirror::ArtMethod> inf_contains(hs.NewHandle(soa.DecodeMethod(inf_contains_jmethod)));

  // Object

  jclass obj_jclass = env->FindClass("java/lang/Object");
  ASSERT_NE(nullptr, obj_jclass);
  jmethodID obj_constructor = env->GetMethodID(obj_jclass, "<init>", "()V");
  ASSERT_NE(nullptr, obj_constructor);

  // Create instances.

  jobject jarray_list = env->NewObject(arraylist_jclass, arraylist_constructor);
  ASSERT_NE(nullptr, jarray_list);
  Handle<mirror::Object> array_list(hs.NewHandle(soa.Decode<mirror::Object*>(jarray_list)));

  jobject jobj = env->NewObject(obj_jclass, obj_constructor);
  ASSERT_NE(nullptr, jobj);
  Handle<mirror::Object> obj(hs.NewHandle(soa.Decode<mirror::Object*>(jobj)));

  // Invocation tests.

  // 1. imt_conflict

  // Contains.

  size_t result =
      Invoke3WithReferrerAndHidden(0U, reinterpret_cast<size_t>(array_list.Get()),
                                   reinterpret_cast<size_t>(obj.Get()),
                                   StubTest::GetEntrypoint(self, kQuickQuickImtConflictTrampoline),
                                   self, contains_amethod.Get(),
                                   static_cast<size_t>(inf_contains.Get()->GetDexMethodIndex()));

  ASSERT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(static_cast<size_t>(JNI_FALSE), result);

  // Add object.

  env->CallBooleanMethod(jarray_list, add_jmethod, jobj);

  ASSERT_FALSE(self->IsExceptionPending()) << PrettyTypeOf(self->GetException());

  // Contains.

  result = Invoke3WithReferrerAndHidden(0U, reinterpret_cast<size_t>(array_list.Get()),
                                        reinterpret_cast<size_t>(obj.Get()),
                                        StubTest::GetEntrypoint(self, kQuickQuickImtConflictTrampoline),
                                        self, contains_amethod.Get(),
                                        static_cast<size_t>(inf_contains.Get()->GetDexMethodIndex()));

  ASSERT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(static_cast<size_t>(JNI_TRUE), result);

  // 2. regular interface trampoline

  result = Invoke3WithReferrer(static_cast<size_t>(inf_contains.Get()->GetDexMethodIndex()),
                               reinterpret_cast<size_t>(array_list.Get()),
                               reinterpret_cast<size_t>(obj.Get()),
                               StubTest::GetEntrypoint(self,
                                   kQuickInvokeInterfaceTrampolineWithAccessCheck),
                               self, contains_amethod.Get());

  ASSERT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(static_cast<size_t>(JNI_TRUE), result);

  result = Invoke3WithReferrer(static_cast<size_t>(inf_contains.Get()->GetDexMethodIndex()),
                               reinterpret_cast<size_t>(array_list.Get()),
                               reinterpret_cast<size_t>(array_list.Get()),
                               StubTest::GetEntrypoint(self,
                                   kQuickInvokeInterfaceTrampolineWithAccessCheck),
                               self, contains_amethod.Get());

  ASSERT_FALSE(self->IsExceptionPending());
  EXPECT_EQ(static_cast<size_t>(JNI_FALSE), result);
#else
  LOG(INFO) << "Skipping imt as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping imt as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

TEST_F(StubTest, StringIndexOf) {
#if defined(__arm__) || defined(__aarch64__)
  TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING();

  Thread* self = Thread::Current();
  ScopedObjectAccess soa(self);
  // garbage is created during ClassLinker::Init

  // Create some strings
  // Use array so we can index into it and use a matrix for expected results
  // Setup: The first half is standard. The second half uses a non-zero offset.
  // TODO: Shared backing arrays.
  const char* c_str[] = { "", "a", "ba", "cba", "dcba", "edcba", "asdfghjkl" };
  static constexpr size_t kStringCount = arraysize(c_str);
  const char c_char[] = { 'a', 'b', 'c', 'd', 'e' };
  static constexpr size_t kCharCount = arraysize(c_char);

  StackHandleScope<kStringCount> hs(self);
  Handle<mirror::String> s[kStringCount];

  for (size_t i = 0; i < kStringCount; ++i) {
    s[i] = hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), c_str[i]));
  }

  // Matrix of expectations. First component is first parameter. Note we only check against the
  // sign, not the value. As we are testing random offsets, we need to compute this and need to
  // rely on String::CompareTo being correct.
  static constexpr size_t kMaxLen = 9;
  DCHECK_LE(strlen(c_str[kStringCount-1]), kMaxLen) << "Please fix the indexof test.";

  // Last dimension: start, offset by 1.
  int32_t expected[kStringCount][kCharCount][kMaxLen + 3];
  for (size_t x = 0; x < kStringCount; ++x) {
    for (size_t y = 0; y < kCharCount; ++y) {
      for (size_t z = 0; z <= kMaxLen + 2; ++z) {
        expected[x][y][z] = s[x]->FastIndexOf(c_char[y], static_cast<int32_t>(z) - 1);
      }
    }
  }

  // Play with it...

  for (size_t x = 0; x < kStringCount; ++x) {
    for (size_t y = 0; y < kCharCount; ++y) {
      for (size_t z = 0; z <= kMaxLen + 2; ++z) {
        int32_t start = static_cast<int32_t>(z) - 1;

        // Test string_compareto x y
        size_t result = Invoke3(reinterpret_cast<size_t>(s[x].Get()), c_char[y], start,
                                StubTest::GetEntrypoint(self, kQuickIndexOf), self);

        EXPECT_FALSE(self->IsExceptionPending());

        // The result is a 32b signed integer
        union {
          size_t r;
          int32_t i;
        } conv;
        conv.r = result;

        EXPECT_EQ(expected[x][y][z], conv.i) << "Wrong result for " << c_str[x] << " / " <<
            c_char[y] << " @ " << start;
      }
    }
  }

  // TODO: Deallocate things.

  // Tests done.
#else
  LOG(INFO) << "Skipping indexof as I don't know how to do that on " << kRuntimeISA;
  // Force-print to std::cout so it's also outside the logcat.
  std::cout << "Skipping indexof as I don't know how to do that on " << kRuntimeISA << std::endl;
#endif
}

}  // namespace art