File: instructions.py

package info (click to toggle)
firefox-esr 68.10.0esr-1~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,143,932 kB
  • sloc: cpp: 5,227,879; javascript: 4,315,531; ansic: 2,467,042; python: 794,975; java: 349,993; asm: 232,034; xml: 228,320; sh: 82,008; lisp: 41,202; makefile: 22,347; perl: 15,555; objc: 5,277; cs: 4,725; yacc: 1,778; ada: 1,681; pascal: 1,673; lex: 1,417; exp: 527; php: 436; ruby: 225; awk: 162; sed: 53; csh: 44
file content (2044 lines) | stat: -rw-r--r-- 62,503 bytes parent folder | download | duplicates (2)
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
"""
Cranelift base instruction set.

This module defines the basic Cranelift instruction set that all targets
support.
"""
from __future__ import absolute_import
from cdsl.operands import Operand, VARIABLE_ARGS
from cdsl.typevar import TypeVar
from cdsl.instructions import Instruction, InstructionGroup
from base.types import f32, f64, b1, iflags, fflags
from base.immediates import imm64, uimm8, uimm32, ieee32, ieee64, offset32
from base.immediates import boolean, intcc, floatcc, memflags, regunit
from base.immediates import trapcode
from base import entities
from cdsl.ti import WiderOrEq
import base.formats  # noqa

GROUP = InstructionGroup("base", "Shared base instruction set")

Int = TypeVar('Int', 'A scalar or vector integer type', ints=True, simd=True)
Bool = TypeVar('Bool', 'A scalar or vector boolean type',
               bools=True, simd=True)
iB = TypeVar('iB', 'A scalar integer type', ints=True)
iAddr = TypeVar('iAddr', 'An integer address type', ints=(32, 64))
Testable = TypeVar(
        'Testable', 'A scalar boolean or integer type',
        ints=True, bools=True)
TxN = TypeVar(
        'TxN', 'A SIMD vector type',
        ints=True, floats=True, bools=True, scalars=False, simd=True)
Any = TypeVar(
        'Any', 'Any integer, float, or boolean scalar or vector type',
        ints=True, floats=True, bools=True, scalars=True, simd=True)
Mem = TypeVar(
        'Mem', 'Any type that can be stored in memory',
        ints=True, floats=True, simd=True)
MemTo = TypeVar(
        'MemTo', 'Any type that can be stored in memory',
        ints=True, floats=True, simd=True)

addr = Operand('addr', iAddr)

#
# Control flow
#
c = Operand('c', Testable, doc='Controlling value to test')
Cond = Operand('Cond', intcc)
x = Operand('x', iB)
y = Operand('y', iB)
EBB = Operand('EBB', entities.ebb, doc='Destination extended basic block')
args = Operand('args', VARIABLE_ARGS, doc='EBB arguments')

jump = Instruction(
        'jump', r"""
        Jump.

        Unconditionally jump to an extended basic block, passing the specified
        EBB arguments. The number and types of arguments must match the
        destination EBB.
        """,
        ins=(EBB, args), is_branch=True, is_terminator=True)

fallthrough = Instruction(
        'fallthrough', r"""
        Fall through to the next EBB.

        This is the same as :inst:`jump`, except the destination EBB must be
        the next one in the layout.

        Jumps are turned into fall-through instructions by the branch
        relaxation pass. There is no reason to use this instruction outside
        that pass.
        """,
        ins=(EBB, args), is_branch=True, is_terminator=True)

brz = Instruction(
        'brz', r"""
        Branch when zero.

        If ``c`` is a :type:`b1` value, take the branch when ``c`` is false. If
        ``c`` is an integer value, take the branch when ``c = 0``.
        """,
        ins=(c, EBB, args), is_branch=True)

brnz = Instruction(
        'brnz', r"""
        Branch when non-zero.

        If ``c`` is a :type:`b1` value, take the branch when ``c`` is true. If
        ``c`` is an integer value, take the branch when ``c != 0``.
        """,
        ins=(c, EBB, args), is_branch=True)

br_icmp = Instruction(
        'br_icmp', r"""
        Compare scalar integers and branch.

        Compare ``x`` and ``y`` in the same way as the :inst:`icmp` instruction
        and take the branch if the condition is true::

            br_icmp ugt v1, v2, ebb4(v5, v6)

        is semantically equivalent to::

            v10 = icmp ugt, v1, v2
            brnz v10, ebb4(v5, v6)

        Some RISC architectures like MIPS and RISC-V provide instructions that
        implement all or some of the condition codes. The instruction can also
        be used to represent *macro-op fusion* on architectures like Intel's.
        """,
        ins=(Cond, x, y, EBB, args), is_branch=True)

f = Operand('f', iflags)

brif = Instruction(
        'brif', r"""
        Branch when condition is true in integer CPU flags.
        """,
        ins=(Cond, f, EBB, args), is_branch=True)

Cond = Operand('Cond', floatcc)
f = Operand('f', fflags)

brff = Instruction(
        'brff', r"""
        Branch when condition is true in floating point CPU flags.
        """,
        ins=(Cond, f, EBB, args), is_branch=True)

x = Operand('x', iB, doc='index into jump table')
Entry = TypeVar('Entry', 'A scalar integer type', ints=True)
entry = Operand('entry', Entry, doc='entry of jump table')
JT = Operand('JT', entities.jump_table)
br_table = Instruction(
        'br_table', r"""
        Indirect branch via jump table.

        Use ``x`` as an unsigned index into the jump table ``JT``. If a jump
        table entry is found, branch to the corresponding EBB. If no entry was
        found or the index is out-of-bounds, branch to the given default EBB.

        Note that this branch instruction can't pass arguments to the targeted
        blocks. Split critical edges as needed to work around this.

        Do not confuse this with "tables" in WebAssembly. ``br_table`` is for
        jump tables with destinations within the current function only -- think
        of a ``match`` in Rust or a ``switch`` in C.  If you want to call a
        function in a dynamic library, that will typically use
        ``call_indirect``.
        """,
        ins=(x, EBB, JT), is_branch=True, is_terminator=True)

Size = Operand('Size', uimm8, 'Size in bytes')
jump_table_entry = Instruction(
    'jump_table_entry', r"""
    Get an entry from a jump table.

    Load a serialized ``entry`` from a jump table ``JT`` at a given index
    ``addr`` with a specific ``Size``. The retrieved entry may need to be
    decoded after loading, depending upon the jump table type used.

    Currently, the only type supported is entries which are relative to the
    base of the jump table.
    """,
    ins=(x, addr, Size, JT), outs=entry)

jump_table_base = Instruction(
    'jump_table_base', r"""
    Get the absolute base address of a jump table.

    This is used for jump tables wherein the entries are stored relative to
    the base of jump table. In order to use these, generated code should first
    load an entry using ``jump_table_entry``, then use this instruction to add
    the relative base back to it.
    """,
    ins=JT, outs=addr)

indirect_jump_table_br = Instruction(
    'indirect_jump_table_br', r"""
    Branch indirectly via a jump table entry.

    Unconditionally jump via a jump table entry that was previously loaded
    with the ``jump_table_entry`` instruction.
    """,
    ins=(addr, JT),
    is_branch=True, is_indirect_branch=True, is_terminator=True)

debugtrap = Instruction('debugtrap', r"""
    Encodes an assembly debug trap.
    """, can_load=True, can_store=True, other_side_effects=True)

code = Operand('code', trapcode)
trap = Instruction(
        'trap', r"""
        Terminate execution unconditionally.
        """,
        ins=code, is_terminator=True, can_trap=True)

trapz = Instruction(
        'trapz', r"""
        Trap when zero.

        if ``c`` is non-zero, execution continues at the following instruction.
        """,
        ins=(c, code), can_trap=True)

trapnz = Instruction(
        'trapnz', r"""
        Trap when non-zero.

        if ``c`` is zero, execution continues at the following instruction.
        """,
        ins=(c, code), can_trap=True)

Cond = Operand('Cond', intcc)
f = Operand('f', iflags)

trapif = Instruction(
        'trapif', r"""
        Trap when condition is true in integer CPU flags.
        """,
        ins=(Cond, f, code), can_trap=True)

Cond = Operand('Cond', floatcc)
f = Operand('f', fflags)

trapff = Instruction(
        'trapff', r"""
        Trap when condition is true in floating point CPU flags.
        """,
        ins=(Cond, f, code), can_trap=True)

rvals = Operand('rvals', VARIABLE_ARGS, doc='return values')

x_return = Instruction(
        'return', r"""
        Return from the function.

        Unconditionally transfer control to the calling function, passing the
        provided return values. The list of return values must match the
        function signature's return types.
        """,
        ins=rvals, is_return=True, is_terminator=True)

fallthrough_return = Instruction(
        'fallthrough_return', r"""
        Return from the function by fallthrough.

        This is a specialized instruction for use where one wants to append
        a custom epilogue, which will then perform the real return. This
        instruction has no encoding.
        """,
        ins=rvals, is_return=True, is_terminator=True)

FN = Operand(
        'FN',
        entities.func_ref,
        doc='function to call, declared by :inst:`function`')
args = Operand('args', VARIABLE_ARGS, doc='call arguments')

call = Instruction(
        'call', r"""
        Direct function call.

        Call a function which has been declared in the preamble. The argument
        types must match the function's signature.
        """,
        ins=(FN, args), outs=rvals, is_call=True)

SIG = Operand('SIG', entities.sig_ref, doc='function signature')
callee = Operand('callee', iAddr, doc='address of function to call')

call_indirect = Instruction(
        'call_indirect', r"""
        Indirect function call.

        Call the function pointed to by `callee` with the given arguments. The
        called function must match the specified signature.

        Note that this is different from WebAssembly's ``call_indirect``; the
        callee is a native address, rather than a table index. For WebAssembly,
        :inst:`table_addr` and :inst:`load` are used to obtain a native address
        from a table.
        """,
        ins=(SIG, callee, args), outs=rvals, is_call=True)

func_addr = Instruction(
        'func_addr', r"""
        Get the address of a function.

        Compute the absolute address of a function declared in the preamble.
        The returned address can be used as a ``callee`` argument to
        :inst:`call_indirect`. This is also a method for calling functions that
        are too far away to be addressable by a direct :inst:`call`
        instruction.
        """,
        ins=FN, outs=addr)

#
# Memory operations
#

SS = Operand('SS', entities.stack_slot)
Offset = Operand('Offset', offset32, 'Byte offset from base address')
x = Operand('x', Mem, doc='Value to be stored')
a = Operand('a', Mem, doc='Value loaded')
p = Operand('p', iAddr)
MemFlags = Operand('MemFlags', memflags)
args = Operand('args', VARIABLE_ARGS, doc='Address arguments')

load = Instruction(
        'load', r"""
        Load from memory at ``p + Offset``.

        This is a polymorphic instruction that can load any value type which
        has a memory representation.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

load_complex = Instruction(
        'load_complex', r"""
        Load from memory at ``sum(args) + Offset``.

        This is a polymorphic instruction that can load any value type which
        has a memory representation.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

store = Instruction(
        'store', r"""
        Store ``x`` to memory at ``p + Offset``.

        This is a polymorphic instruction that can store any value type with a
        memory representation.
        """,
        ins=(MemFlags, x, p, Offset), can_store=True)

store_complex = Instruction(
        'store_complex', r"""
        Store ``x`` to memory at ``sum(args) + Offset``.

        This is a polymorphic instruction that can store any value type with a
        memory representation.
        """,
        ins=(MemFlags, x, args, Offset), can_store=True)


iExt8 = TypeVar(
        'iExt8', 'An integer type with more than 8 bits',
        ints=(16, 64))
x = Operand('x', iExt8)
a = Operand('a', iExt8)

uload8 = Instruction(
        'uload8', r"""
        Load 8 bits from memory at ``p + Offset`` and zero-extend.

        This is equivalent to ``load.i8`` followed by ``uextend``.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

uload8_complex = Instruction(
        'uload8_complex', r"""
        Load 8 bits from memory at ``sum(args) + Offset`` and zero-extend.

        This is equivalent to ``load.i8`` followed by ``uextend``.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

sload8 = Instruction(
        'sload8', r"""
        Load 8 bits from memory at ``p + Offset`` and sign-extend.

        This is equivalent to ``load.i8`` followed by ``sextend``.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

sload8_complex = Instruction(
        'sload8_complex', r"""
        Load 8 bits from memory at ``sum(args) + Offset`` and sign-extend.

        This is equivalent to ``load.i8`` followed by ``sextend``.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

istore8 = Instruction(
        'istore8', r"""
        Store the low 8 bits of ``x`` to memory at ``p + Offset``.

        This is equivalent to ``ireduce.i8`` followed by ``store.i8``.
        """,
        ins=(MemFlags, x, p, Offset), can_store=True)

istore8_complex = Instruction(
        'istore8_complex', r"""
        Store the low 8 bits of ``x`` to memory at ``sum(args) + Offset``.

        This is equivalent to ``ireduce.i8`` followed by ``store.i8``.
        """,
        ins=(MemFlags, x, args, Offset), can_store=True)

iExt16 = TypeVar(
        'iExt16', 'An integer type with more than 16 bits',
        ints=(32, 64))
x = Operand('x', iExt16)
a = Operand('a', iExt16)

uload16 = Instruction(
        'uload16', r"""
        Load 16 bits from memory at ``p + Offset`` and zero-extend.

        This is equivalent to ``load.i16`` followed by ``uextend``.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

uload16_complex = Instruction(
        'uload16_complex', r"""
        Load 16 bits from memory at ``sum(args) + Offset`` and zero-extend.

        This is equivalent to ``load.i16`` followed by ``uextend``.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

sload16 = Instruction(
        'sload16', r"""
        Load 16 bits from memory at ``p + Offset`` and sign-extend.

        This is equivalent to ``load.i16`` followed by ``sextend``.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

sload16_complex = Instruction(
        'sload16_complex', r"""
        Load 16 bits from memory at ``sum(args) + Offset`` and sign-extend.

        This is equivalent to ``load.i16`` followed by ``sextend``.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

istore16 = Instruction(
        'istore16', r"""
        Store the low 16 bits of ``x`` to memory at ``p + Offset``.

        This is equivalent to ``ireduce.i16`` followed by ``store.i16``.
        """,
        ins=(MemFlags, x, p, Offset), can_store=True)

istore16_complex = Instruction(
        'istore16_complex', r"""
        Store the low 16 bits of ``x`` to memory at ``sum(args) + Offset``.

        This is equivalent to ``ireduce.i16`` followed by ``store.i16``.
        """,
        ins=(MemFlags, x, args, Offset), can_store=True)

iExt32 = TypeVar(
        'iExt32', 'An integer type with more than 32 bits',
        ints=(64, 64))
x = Operand('x', iExt32)
a = Operand('a', iExt32)

uload32 = Instruction(
        'uload32', r"""
        Load 32 bits from memory at ``p + Offset`` and zero-extend.

        This is equivalent to ``load.i32`` followed by ``uextend``.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

uload32_complex = Instruction(
        'uload32_complex', r"""
        Load 32 bits from memory at ``sum(args) + Offset`` and zero-extend.

        This is equivalent to ``load.i32`` followed by ``uextend``.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

sload32 = Instruction(
        'sload32', r"""
        Load 32 bits from memory at ``p + Offset`` and sign-extend.

        This is equivalent to ``load.i32`` followed by ``sextend``.
        """,
        ins=(MemFlags, p, Offset), outs=a, can_load=True)

sload32_complex = Instruction(
        'sload32_complex', r"""
        Load 32 bits from memory at ``sum(args) + Offset`` and sign-extend.

        This is equivalent to ``load.i32`` followed by ``sextend``.
        """,
        ins=(MemFlags, args, Offset), outs=a, can_load=True)

istore32 = Instruction(
        'istore32', r"""
        Store the low 32 bits of ``x`` to memory at ``p + Offset``.

        This is equivalent to ``ireduce.i32`` followed by ``store.i32``.
        """,
        ins=(MemFlags, x, p, Offset), can_store=True)

istore32_complex = Instruction(
        'istore32_complex', r"""
        Store the low 32 bits of ``x`` to memory at ``sum(args) + Offset``.

        This is equivalent to ``ireduce.i32`` followed by ``store.i32``.
        """,
        ins=(MemFlags, x, args, Offset), can_store=True)

x = Operand('x', Mem, doc='Value to be stored')
a = Operand('a', Mem, doc='Value loaded')
Offset = Operand('Offset', offset32, 'In-bounds offset into stack slot')

stack_load = Instruction(
        'stack_load', r"""
        Load a value from a stack slot at the constant offset.

        This is a polymorphic instruction that can load any value type which
        has a memory representation.

        The offset is an immediate constant, not an SSA value. The memory
        access cannot go out of bounds, i.e.
        :math:`sizeof(a) + Offset <= sizeof(SS)`.
        """,
        ins=(SS, Offset), outs=a, can_load=True)

stack_store = Instruction(
        'stack_store', r"""
        Store a value to a stack slot at a constant offset.

        This is a polymorphic instruction that can store any value type with a
        memory representation.

        The offset is an immediate constant, not an SSA value. The memory
        access cannot go out of bounds, i.e.
        :math:`sizeof(a) + Offset <= sizeof(SS)`.
        """,
        ins=(x, SS, Offset), can_store=True)

stack_addr = Instruction(
        'stack_addr', r"""
        Get the address of a stack slot.

        Compute the absolute address of a byte in a stack slot. The offset must
        refer to a byte inside the stack slot:
        :math:`0 <= Offset < sizeof(SS)`.
        """,
        ins=(SS, Offset), outs=addr)

#
# Global values.
#

GV = Operand('GV', entities.global_value)

global_value = Instruction(
        'global_value', r"""
        Compute the value of global GV.
        """,
        ins=GV, outs=a)

# A specialized form of global_value instructions that only handles
# symbolic names.
symbol_value = Instruction(
        'symbol_value', r"""
        Compute the value of global GV, which is a symbolic value.
        """,
        ins=GV, outs=a)

#
# WebAssembly bounds-checked heap accesses.
#

HeapOffset = TypeVar('HeapOffset', 'An unsigned heap offset', ints=(32, 64))

H = Operand('H', entities.heap)
p = Operand('p', HeapOffset)
Size = Operand('Size', uimm32, 'Size in bytes')

heap_addr = Instruction(
        'heap_addr', r"""
        Bounds check and compute absolute address of heap memory.

        Verify that the offset range ``p .. p + Size - 1`` is in bounds for the
        heap H, and generate an absolute address that is safe to dereference.

        1. If ``p + Size`` is not greater than the heap bound, return an
           absolute address corresponding to a byte offset of ``p`` from the
           heap's base address.
        2. If ``p + Size`` is greater than the heap bound, generate a trap.
        """,
        ins=(H, p, Size), outs=addr)

#
# WebAssembly bounds-checked table accesses.
#

TableOffset = TypeVar('TableOffset', 'An unsigned table offset', ints=(32, 64))

T = Operand('T', entities.table)
p = Operand('p', TableOffset)
Offset = Operand('Offset', offset32, 'Byte offset from element address')

table_addr = Instruction(
        'table_addr', r"""
        Bounds check and compute absolute address of a table entry.

        Verify that the offset ``p`` is in bounds for the table T, and generate
        an absolute address that is safe to dereference.

        ``Offset`` must be less than the size of a table element.

        1. If ``p`` is not greater than the table bound, return an absolute
           address corresponding to a byte offset of ``p`` from the table's
           base address.
        2. If ``p`` is greater than the table bound, generate a trap.
        """,
        ins=(T, p, Offset), outs=addr)


#
# Materializing constants.
#

N = Operand('N', imm64)
a = Operand('a', Int, doc='A constant integer scalar or vector value')
iconst = Instruction(
        'iconst', r"""
        Integer constant.

        Create a scalar integer SSA value with an immediate constant value, or
        an integer vector where all the lanes have the same value.
        """,
        ins=N, outs=a)

N = Operand('N', ieee32)
a = Operand('a', f32, doc='A constant f32 scalar value')
f32const = Instruction(
        'f32const', r"""
        Floating point constant.

        Create a :type:`f32` SSA value with an immediate constant value.
        """,
        ins=N, outs=a)

N = Operand('N', ieee64)
a = Operand('a', f64, doc='A constant f64 scalar value')
f64const = Instruction(
        'f64const', r"""
        Floating point constant.

        Create a :type:`f64` SSA value with an immediate constant value.
        """,
        ins=N, outs=a)

N = Operand('N', boolean)
a = Operand('a', Bool, doc='A constant boolean scalar or vector value')
bconst = Instruction(
        'bconst', r"""
        Boolean constant.

        Create a scalar boolean SSA value with an immediate constant value, or
        a boolean vector where all the lanes have the same value.
        """,
        ins=N, outs=a)

#
# Generics.
#

nop = Instruction(
        'nop', r"""
        Just a dummy instruction

        Note: this doesn't compile to a machine code nop
        """)

c = Operand('c', Testable, doc='Controlling value to test')
x = Operand('x', Any, doc='Value to use when `c` is true')
y = Operand('y', Any, doc='Value to use when `c` is false')
a = Operand('a', Any)

select = Instruction(
        'select', r"""
        Conditional select.

        This instruction selects whole values. Use :inst:`vselect` for
        lane-wise selection.
        """,
        ins=(c, x, y), outs=a)

cc = Operand('cc', intcc, doc='Controlling condition code')
flags = Operand('flags', iflags, doc='The machine\'s flag register')

selectif = Instruction(
        'selectif', r"""
        Conditional select, dependent on integer condition codes.
        """,
        ins=(cc, flags, x, y), outs=a)

x = Operand('x', Any)

copy = Instruction(
        'copy', r"""
        Register-register copy.

        This instruction copies its input, preserving the value type.

        A pure SSA-form program does not need to copy values, but this
        instruction is useful for representing intermediate stages during
        instruction transformations, and the register allocator needs a way of
        representing register copies.
        """,
        ins=x, outs=a)

spill = Instruction(
        'spill', r"""
        Spill a register value to a stack slot.

        This instruction behaves exactly like :inst:`copy`, but the result
        value is assigned to a spill slot.
        """,
        ins=x, outs=a, can_store=True)

fill = Instruction(
        'fill', r"""
        Load a register value from a stack slot.

        This instruction behaves exactly like :inst:`copy`, but creates a new
        SSA value for the spilled input value.
        """,
        ins=x, outs=a, can_load=True)

src = Operand('src', regunit)
dst = Operand('dst', regunit)

regmove = Instruction(
        'regmove', r"""
        Temporarily divert ``x`` from ``src`` to ``dst``.

        This instruction moves the location of a value from one register to
        another without creating a new SSA value. It is used by the register
        allocator to temporarily rearrange register assignments in order to
        satisfy instruction constraints.

        The register diversions created by this instruction must be undone
        before the value leaves the EBB. At the entry to a new EBB, all live
        values must be in their originally assigned registers.
        """,
        ins=(x, src, dst),
        other_side_effects=True)

copy_special = Instruction(
        'copy_special', r"""
        Copies the contents of ''src'' register to ''dst'' register.

        This instructions copies the contents of one register to another
        register without involving any SSA values. This is used for copying
        special registers, e.g. copying the stack register to the frame
        register in a function prologue.
        """,
        ins=(src, dst),
        other_side_effects=True)

delta = Operand('delta', Int)
adjust_sp_down = Instruction(
    'adjust_sp_down', r"""
    Subtracts ``delta`` offset value from the stack pointer register.

    This instruction is used to adjust the stack pointer by a dynamic amount.
    """,
    ins=(delta,),
    other_side_effects=True)

StackOffset = Operand('Offset', imm64, 'Offset from current stack pointer')
adjust_sp_up_imm = Instruction(
    'adjust_sp_up_imm', r"""
    Adds ``Offset`` immediate offset value to the stack pointer register.

    This instruction is used to adjust the stack pointer, primarily in function
    prologues and epilogues. ``Offset`` is constrained to the size of a signed
    32-bit integer.
    """,
    ins=(StackOffset,),
    other_side_effects=True)

StackOffset = Operand('Offset', imm64, 'Offset from current stack pointer')
adjust_sp_down_imm = Instruction(
    'adjust_sp_down_imm', r"""
    Subtracts ``Offset`` immediate offset value from the stack pointer
    register.

    This instruction is used to adjust the stack pointer, primarily in function
    prologues and epilogues. ``Offset`` is constrained to the size of a signed
    32-bit integer.
    """,
    ins=(StackOffset,),
    other_side_effects=True)

f = Operand('f', iflags)

ifcmp_sp = Instruction(
    'ifcmp_sp', r"""
    Compare ``addr`` with the stack pointer and set the CPU flags.

    This is like :inst:`ifcmp` where ``addr`` is the LHS operand and the stack
    pointer is the RHS.
    """,
    ins=addr, outs=f)

regspill = Instruction(
        'regspill', r"""
        Temporarily divert ``x`` from ``src`` to ``SS``.

        This instruction moves the location of a value from a register to a
        stack slot without creating a new SSA value. It is used by the register
        allocator to temporarily rearrange register assignments in order to
        satisfy instruction constraints.

        See also :inst:`regmove`.
        """,
        ins=(x, src, SS),
        other_side_effects=True)


regfill = Instruction(
        'regfill', r"""
        Temporarily divert ``x`` from ``SS`` to ``dst``.

        This instruction moves the location of a value from a stack slot to a
        register without creating a new SSA value. It is used by the register
        allocator to temporarily rearrange register assignments in order to
        satisfy instruction constraints.

        See also :inst:`regmove`.
        """,
        ins=(x, SS, dst),
        other_side_effects=True)
#
# Vector operations
#

x = Operand('x', TxN, doc='Vector to split')
lo = Operand('lo', TxN.half_vector(), doc='Low-numbered lanes of `x`')
hi = Operand('hi', TxN.half_vector(), doc='High-numbered lanes of `x`')

vsplit = Instruction(
        'vsplit', r"""
        Split a vector into two halves.

        Split the vector `x` into two separate values, each containing half of
        the lanes from ``x``. The result may be two scalars if ``x`` only had
        two lanes.
        """,
        ins=x, outs=(lo, hi), is_ghost=True)

Any128 = TypeVar(
        'Any128', 'Any scalar or vector type with as most 128 lanes',
        ints=True, floats=True, bools=True, scalars=True, simd=(1, 128))
x = Operand('x', Any128, doc='Low-numbered lanes')
y = Operand('y', Any128, doc='High-numbered lanes')
a = Operand('a', Any128.double_vector(), doc='Concatenation of `x` and `y`')

vconcat = Instruction(
        'vconcat', r"""
        Vector concatenation.

        Return a vector formed by concatenating ``x`` and ``y``. The resulting
        vector type has twice as many lanes as each of the inputs. The lanes of
        ``x`` appear as the low-numbered lanes, and the lanes of ``y`` become
        the high-numbered lanes of ``a``.

        It is possible to form a vector by concatenating two scalars.
        """,
        ins=(x, y), outs=a, is_ghost=True)

c = Operand('c', TxN.as_bool(), doc='Controlling vector')
x = Operand('x', TxN, doc='Value to use where `c` is true')
y = Operand('y', TxN, doc='Value to use where `c` is false')
a = Operand('a', TxN)

vselect = Instruction(
        'vselect', r"""
        Vector lane select.

        Select lanes from ``x`` or ``y`` controlled by the lanes of the boolean
        vector ``c``.
        """,
        ins=(c, x, y), outs=a)

x = Operand('x', TxN.lane_of())

splat = Instruction(
        'splat', r"""
        Vector splat.

        Return a vector whose lanes are all ``x``.
        """,
        ins=x, outs=a)

x = Operand('x', TxN, doc='SIMD vector to modify')
y = Operand('y', TxN.lane_of(), doc='New lane value')
Idx = Operand('Idx', uimm8, doc='Lane index')

insertlane = Instruction(
        'insertlane', r"""
        Insert ``y`` as lane ``Idx`` in x.

        The lane index, ``Idx``, is an immediate value, not an SSA value. It
        must indicate a valid lane index for the type of ``x``.
        """,
        ins=(x, Idx, y), outs=a)

x = Operand('x', TxN)
a = Operand('a', TxN.lane_of())

extractlane = Instruction(
        'extractlane', r"""
        Extract lane ``Idx`` from ``x``.

        The lane index, ``Idx``, is an immediate value, not an SSA value. It
        must indicate a valid lane index for the type of ``x``.
        """,
        ins=(x, Idx), outs=a)

#
# Integer arithmetic
#

a = Operand('a', Int.as_bool())
Cond = Operand('Cond', intcc)
x = Operand('x', Int)
y = Operand('y', Int)

icmp = Instruction(
        'icmp', r"""
        Integer comparison.

        The condition code determines if the operands are interpreted as signed
        or unsigned integers.

        ====== ======== =========
        Signed Unsigned Condition
        ====== ======== =========
        eq     eq       Equal
        ne     ne       Not equal
        slt    ult      Less than
        sge    uge      Greater than or equal
        sgt    ugt      Greater than
        sle    ule      Less than or equal
        ====== ======== =========

        When this instruction compares integer vectors, it returns a boolean
        vector of lane-wise comparisons.
        """,
        ins=(Cond, x, y), outs=a)

a = Operand('a', b1)
x = Operand('x', iB)
Y = Operand('Y', imm64)

icmp_imm = Instruction(
        'icmp_imm', r"""
        Compare scalar integer to a constant.

        This is the same as the :inst:`icmp` instruction, except one operand is
        an immediate constant.

        This instruction can only compare scalars. Use :inst:`icmp` for
        lane-wise vector comparisons.
        """,
        ins=(Cond, x, Y), outs=a)

f = Operand('f', iflags)
x = Operand('x', iB)
y = Operand('y', iB)

ifcmp = Instruction(
        'ifcmp', r"""
        Compare scalar integers and return flags.

        Compare two scalar integer values and return integer CPU flags
        representing the result.
        """,
        ins=(x, y), outs=f)

ifcmp_imm = Instruction(
        'ifcmp_imm', r"""
        Compare scalar integer to a constant and return flags.

        Like :inst:`icmp_imm`, but returns integer CPU flags instead of testing
        a specific condition code.
        """,
        ins=(x, Y), outs=f)

a = Operand('a', Int)
x = Operand('x', Int)
y = Operand('y', Int)

iadd = Instruction(
        'iadd', r"""
        Wrapping integer addition: :math:`a := x + y \pmod{2^B}`.

        This instruction does not depend on the signed/unsigned interpretation
        of the operands.
        """,
        ins=(x, y), outs=a)

isub = Instruction(
        'isub', r"""
        Wrapping integer subtraction: :math:`a := x - y \pmod{2^B}`.

        This instruction does not depend on the signed/unsigned interpretation
        of the operands.
        """,
        ins=(x, y), outs=a)

imul = Instruction(
        'imul', r"""
        Wrapping integer multiplication: :math:`a := x y \pmod{2^B}`.

        This instruction does not depend on the signed/unsigned interpretation
        of the
        operands.

        Polymorphic over all integer types (vector and scalar).
        """,
        ins=(x, y), outs=a)

umulhi = Instruction(
        'umulhi', r"""
        Unsigned integer multiplication, producing the high half of a
        double-length result.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y), outs=a)

smulhi = Instruction(
        'smulhi', """
        Signed integer multiplication, producing the high half of a
        double-length result.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y), outs=a)

udiv = Instruction(
        'udiv', r"""
        Unsigned integer division: :math:`a := \lfloor {x \over y} \rfloor`.

        This operation traps if the divisor is zero.
        """,
        ins=(x, y), outs=a, can_trap=True)

sdiv = Instruction(
        'sdiv', r"""
        Signed integer division rounded toward zero: :math:`a := sign(xy)
        \lfloor {|x| \over |y|}\rfloor`.

        This operation traps if the divisor is zero, or if the result is not
        representable in :math:`B` bits two's complement. This only happens
        when :math:`x = -2^{B-1}, y = -1`.
        """,
        ins=(x, y), outs=a, can_trap=True)

urem = Instruction(
        'urem', """
        Unsigned integer remainder.

        This operation traps if the divisor is zero.
        """,
        ins=(x, y), outs=a, can_trap=True)

srem = Instruction(
        'srem', """
        Signed integer remainder. The result has the sign of the dividend.

        This operation traps if the divisor is zero.
        """,
        ins=(x, y), outs=a, can_trap=True)

a = Operand('a', iB)
x = Operand('x', iB)
Y = Operand('Y', imm64)

iadd_imm = Instruction(
        'iadd_imm', """
        Add immediate integer.

        Same as :inst:`iadd`, but one operand is an immediate constant.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, Y), outs=a)

imul_imm = Instruction(
        'imul_imm', """
        Integer multiplication by immediate constant.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, Y), outs=a)

udiv_imm = Instruction(
        'udiv_imm', """
        Unsigned integer division by an immediate constant.

        This operation traps if the divisor is zero.
        """,
        ins=(x, Y), outs=a)

sdiv_imm = Instruction(
        'sdiv_imm', """
        Signed integer division by an immediate constant.

        This operation traps if the divisor is zero, or if the result is not
        representable in :math:`B` bits two's complement. This only happens
        when :math:`x = -2^{B-1}, Y = -1`.
        """,
        ins=(x, Y), outs=a)

urem_imm = Instruction(
        'urem_imm', """
        Unsigned integer remainder with immediate divisor.

        This operation traps if the divisor is zero.
        """,
        ins=(x, Y), outs=a)

srem_imm = Instruction(
        'srem_imm', """
        Signed integer remainder with immediate divisor.

        This operation traps if the divisor is zero.
        """,
        ins=(x, Y), outs=a)

irsub_imm = Instruction(
        'irsub_imm', """
        Immediate reverse wrapping subtraction: :math:`a := Y - x \\pmod{2^B}`.

        Also works as integer negation when :math:`Y = 0`. Use :inst:`iadd_imm`
        with a negative immediate operand for the reverse immediate
        subtraction.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, Y), outs=a)

#
# Integer arithmetic with carry and/or borrow.
#
a = Operand('a', iB)
x = Operand('x', iB)
y = Operand('y', iB)
c_in = Operand('c_in', b1, doc="Input carry flag")
c_out = Operand('c_out', b1, doc="Output carry flag")
b_in = Operand('b_in', b1, doc="Input borrow flag")
b_out = Operand('b_out', b1, doc="Output borrow flag")

iadd_cin = Instruction(
        'iadd_cin', r"""
        Add integers with carry in.

        Same as :inst:`iadd` with an additional carry input. Computes:

        .. math::

            a = x + y + c_{in} \pmod 2^B

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y, c_in), outs=a)

iadd_cout = Instruction(
        'iadd_cout', r"""
        Add integers with carry out.

        Same as :inst:`iadd` with an additional carry output.

        .. math::

            a &= x + y \pmod 2^B \\
            c_{out} &= x+y >= 2^B

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y), outs=(a, c_out))

iadd_carry = Instruction(
        'iadd_carry', r"""
        Add integers with carry in and out.

        Same as :inst:`iadd` with an additional carry input and output.

        .. math::

            a &= x + y + c_{in} \pmod 2^B \\
            c_{out} &= x + y + c_{in} >= 2^B

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y, c_in), outs=(a, c_out))

isub_bin = Instruction(
        'isub_bin', r"""
        Subtract integers with borrow in.

        Same as :inst:`isub` with an additional borrow flag input. Computes:

        .. math::

            a = x - (y + b_{in}) \pmod 2^B

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y, b_in), outs=a)

isub_bout = Instruction(
        'isub_bout', r"""
        Subtract integers with borrow out.

        Same as :inst:`isub` with an additional borrow flag output.

        .. math::

            a &= x - y \pmod 2^B \\
            b_{out} &= x < y

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y), outs=(a, b_out))

isub_borrow = Instruction(
        'isub_borrow', r"""
        Subtract integers with borrow in and out.

        Same as :inst:`isub` with an additional borrow flag input and output.

        .. math::

            a &= x - (y + b_{in}) \pmod 2^B \\
            b_{out} &= x < y + b_{in}

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, y, b_in), outs=(a, b_out))

#
# Bitwise operations.
#

# TODO: Which types should permit boolean operations? Any reason to restrict?
bits = TypeVar(
        'bits', 'Any integer, float, or boolean scalar or vector type',
        ints=True, floats=True, bools=True, scalars=True, simd=True)

x = Operand('x', bits)
y = Operand('y', bits)
a = Operand('a', bits)

band = Instruction(
        'band', """
        Bitwise and.
        """,
        ins=(x, y), outs=a)

bor = Instruction(
        'bor', """
        Bitwise or.
        """,
        ins=(x, y), outs=a)

bxor = Instruction(
        'bxor', """
        Bitwise xor.
        """,
        ins=(x, y), outs=a)

bnot = Instruction(
        'bnot', """
        Bitwise not.
        """,
        ins=x, outs=a)

band_not = Instruction(
        'band_not', """
        Bitwise and not.

        Computes `x & ~y`.
        """,
        ins=(x, y), outs=a)

bor_not = Instruction(
        'bor_not', """
        Bitwise or not.

        Computes `x | ~y`.
        """,
        ins=(x, y), outs=a)

bxor_not = Instruction(
        'bxor_not', """
        Bitwise xor not.

        Computes `x ^ ~y`.
        """,
        ins=(x, y), outs=a)

# Bitwise binary ops with immediate arg.
x = Operand('x', iB)
Y = Operand('Y', imm64)
a = Operand('a', iB)

band_imm = Instruction(
        'band_imm', """
        Bitwise and with immediate.

        Same as :inst:`band`, but one operand is an immediate constant.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, Y), outs=a)

bor_imm = Instruction(
        'bor_imm', """
        Bitwise or with immediate.

        Same as :inst:`bor`, but one operand is an immediate constant.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, Y), outs=a)

bxor_imm = Instruction(
        'bxor_imm', """
        Bitwise xor with immediate.

        Same as :inst:`bxor`, but one operand is an immediate constant.

        Polymorphic over all scalar integer types, but does not support vector
        types.
        """,
        ins=(x, Y), outs=a)

# Shift/rotate.
x = Operand('x', Int, doc='Scalar or vector value to shift')
y = Operand('y', iB, doc='Number of bits to shift')
Y = Operand('Y', imm64)

a = Operand('a', Int)

rotl = Instruction(
        'rotl', r"""
        Rotate left.

        Rotate the bits in ``x`` by ``y`` places.
        """,
        ins=(x, y), outs=a)

rotr = Instruction(
        'rotr', r"""
        Rotate right.

        Rotate the bits in ``x`` by ``y`` places.
        """,
        ins=(x, y), outs=a)

rotl_imm = Instruction(
        'rotl_imm', r"""
        Rotate left by immediate.
        """,
        ins=(x, Y), outs=a)

rotr_imm = Instruction(
        'rotr_imm', r"""
        Rotate right by immediate.
        """,
        ins=(x, Y), outs=a)

ishl = Instruction(
        'ishl', r"""
        Integer shift left. Shift the bits in ``x`` towards the MSB by ``y``
        places. Shift in zero bits to the LSB.

        The shift amount is masked to the size of ``x``.

        When shifting a B-bits integer type, this instruction computes:

        .. math::
            s &:= y \pmod B,                \\
            a &:= x \cdot 2^s \pmod{2^B}.
        """,
        ins=(x, y), outs=a)

ushr = Instruction(
        'ushr', r"""
        Unsigned shift right. Shift bits in ``x`` towards the LSB by ``y``
        places, shifting in zero bits to the MSB. Also called a *logical
        shift*.

        The shift amount is masked to the size of the register.

        When shifting a B-bits integer type, this instruction computes:

        .. math::
            s &:= y \pmod B,                \\
            a &:= \lfloor x \cdot 2^{-s} \rfloor.
        """,
        ins=(x, y), outs=a)

sshr = Instruction(
        'sshr', r"""
        Signed shift right. Shift bits in ``x`` towards the LSB by ``y``
        places, shifting in sign bits to the MSB. Also called an *arithmetic
        shift*.

        The shift amount is masked to the size of the register.
        """,
        ins=(x, y), outs=a)

ishl_imm = Instruction(
        'ishl_imm', r"""
        Integer shift left by immediate.

        The shift amount is masked to the size of ``x``.
        """,
        ins=(x, Y), outs=a)

ushr_imm = Instruction(
        'ushr_imm', r"""
        Unsigned shift right by immediate.

        The shift amount is masked to the size of the register.
        """,
        ins=(x, Y), outs=a)

sshr_imm = Instruction(
        'sshr_imm', r"""
        Signed shift right by immediate.

        The shift amount is masked to the size of the register.
        """,
        ins=(x, Y), outs=a)

#
# Bit counting.
#

x = Operand('x', iB)
a = Operand('a', iB)

bitrev = Instruction(
        'bitrev', r"""
        Reverse the bits of a integer.

        Reverses the bits in ``x``.
        """,
        ins=x, outs=a)

clz = Instruction(
        'clz', r"""
        Count leading zero bits.

        Starting from the MSB in ``x``, count the number of zero bits before
        reaching the first one bit. When ``x`` is zero, returns the size of x
        in bits.
        """,
        ins=x, outs=a)

cls = Instruction(
        'cls', r"""
        Count leading sign bits.

        Starting from the MSB after the sign bit in ``x``, count the number of
        consecutive bits identical to the sign bit. When ``x`` is 0 or -1,
        returns one less than the size of x in bits.
        """,
        ins=x, outs=a)

ctz = Instruction(
        'ctz', r"""
        Count trailing zeros.

        Starting from the LSB in ``x``, count the number of zero bits before
        reaching the first one bit. When ``x`` is zero, returns the size of x
        in bits.
        """,
        ins=x, outs=a)

popcnt = Instruction(
        'popcnt', r"""
        Population count

        Count the number of one bits in ``x``.
        """,
        ins=x, outs=a)

#
# Floating point.
#

Float = TypeVar(
        'Float', 'A scalar or vector floating point number',
        floats=True, simd=True)
fB = TypeVar('fB', 'A scalar floating point number', floats=True)

Cond = Operand('Cond', floatcc)
x = Operand('x', Float)
y = Operand('y', Float)
a = Operand('a', Float.as_bool())

fcmp = Instruction(
        'fcmp', r"""
        Floating point comparison.

        Two IEEE 754-2008 floating point numbers, `x` and `y`, relate to each
        other in exactly one of four ways:

        == ==========================================
        UN Unordered when one or both numbers is NaN.
        EQ When :math:`x = y`. (And :math:`0.0 = -0.0`).
        LT When :math:`x < y`.
        GT When :math:`x > y`.
        == ==========================================

        The 14 :type:`floatcc` condition codes each correspond to a subset of
        the four relations, except for the empty set which would always be
        false, and the full set which would always be true.

        The condition codes are divided into 7 'ordered' conditions which don't
        include UN, and 7 unordered conditions which all include UN.

        +-------+------------+---------+------------+-------------------------+
        |Ordered             |Unordered             |Condition                |
        +=======+============+=========+============+=========================+
        |ord    |EQ | LT | GT|uno      |UN          |NaNs absent / present.   |
        +-------+------------+---------+------------+-------------------------+
        |eq     |EQ          |ueq      |UN | EQ     |Equal                    |
        +-------+------------+---------+------------+-------------------------+
        |one    |LT | GT     |ne       |UN | LT | GT|Not equal                |
        +-------+------------+---------+------------+-------------------------+
        |lt     |LT          |ult      |UN | LT     |Less than                |
        +-------+------------+---------+------------+-------------------------+
        |le     |LT | EQ     |ule      |UN | LT | EQ|Less than or equal       |
        +-------+------------+---------+------------+-------------------------+
        |gt     |GT          |ugt      |UN | GT     |Greater than             |
        +-------+------------+---------+------------+-------------------------+
        |ge     |GT | EQ     |uge      |UN | GT | EQ|Greater than or equal    |
        +-------+------------+---------+------------+-------------------------+

        The standard C comparison operators, `<, <=, >, >=`, are all ordered,
        so they are false if either operand is NaN. The C equality operator,
        `==`, is ordered, and since inequality is defined as the logical
        inverse it is *unordered*. They map to the :type:`floatcc` condition
        codes as follows:

        ==== ====== ============
        C    `Cond` Subset
        ==== ====== ============
        `==` eq     EQ
        `!=` ne     UN | LT | GT
        `<`  lt     LT
        `<=` le     LT | EQ
        `>`  gt     GT
        `>=` ge     GT | EQ
        ==== ====== ============

        This subset of condition codes also corresponds to the WebAssembly
        floating point comparisons of the same name.

        When this instruction compares floating point vectors, it returns a
        boolean vector with the results of lane-wise comparisons.
        """,
        ins=(Cond, x, y), outs=a)

f = Operand('f', fflags)

ffcmp = Instruction(
        'ffcmp', r"""
        Floating point comparison returning flags.

        Compares two numbers like :inst:`fcmp`, but returns floating point CPU
        flags instead of testing a specific condition.
        """,
        ins=(x, y), outs=f)

x = Operand('x', Float)
y = Operand('y', Float)
z = Operand('z', Float)
a = Operand('a', Float, 'Result of applying operator to each lane')

fadd = Instruction(
        'fadd', r"""
        Floating point addition.
        """,
        ins=(x, y), outs=a)

fsub = Instruction(
        'fsub', r"""
        Floating point subtraction.
        """,
        ins=(x, y), outs=a)

fmul = Instruction(
        'fmul', r"""
        Floating point multiplication.
        """,
        ins=(x, y), outs=a)

fdiv = Instruction(
        'fdiv', r"""
        Floating point division.

        Unlike the integer division instructions :clif:inst:`sdiv` and
        :clif:inst:`udiv`, this can't trap. Division by zero is infinity or
        NaN, depending on the dividend.
        """,
        ins=(x, y), outs=a)

sqrt = Instruction(
        'sqrt', r"""
        Floating point square root.
        """,
        ins=x, outs=a)

fma = Instruction(
        'fma', r"""
        Floating point fused multiply-and-add.

        Computes :math:`a := xy+z` without any intermediate rounding of the
        product.
        """,
        ins=(x, y, z), outs=a)

a = Operand('a', Float, '``x`` with its sign bit inverted')
fneg = Instruction(
        'fneg', r"""
        Floating point negation.

        Note that this is a pure bitwise operation.
        """,
        ins=x, outs=a)

a = Operand('a', Float, '``x`` with its sign bit cleared')
fabs = Instruction(
        'fabs', r"""
        Floating point absolute value.

        Note that this is a pure bitwise operation.
        """,
        ins=x, outs=a)

a = Operand('a', Float, '``x`` with its sign bit changed to that of ``y``')
fcopysign = Instruction(
        'fcopysign', r"""
        Floating point copy sign.

        Note that this is a pure bitwise operation. The sign bit from ``y`` is
        copied to the sign bit of ``x``.
        """,
        ins=(x, y), outs=a)

a = Operand('a', Float, 'The smaller of ``x`` and ``y``')

fmin = Instruction(
        'fmin', r"""
        Floating point minimum, propagating NaNs.

        If either operand is NaN, this returns a NaN.
        """,
        ins=(x, y), outs=a)

a = Operand('a', Float, 'The larger of ``x`` and ``y``')

fmax = Instruction(
        'fmax', r"""
        Floating point maximum, propagating NaNs.

        If either operand is NaN, this returns a NaN.
        """,
        ins=(x, y), outs=a)

a = Operand('a', Float, '``x`` rounded to integral value')

ceil = Instruction(
        'ceil', r"""
        Round floating point round to integral, towards positive infinity.
        """,
        ins=x, outs=a)

floor = Instruction(
        'floor', r"""
        Round floating point round to integral, towards negative infinity.
        """,
        ins=x, outs=a)

trunc = Instruction(
        'trunc', r"""
        Round floating point round to integral, towards zero.
        """,
        ins=x, outs=a)

nearest = Instruction(
        'nearest', r"""
        Round floating point round to integral, towards nearest with ties to
        even.
        """,
        ins=x, outs=a)

#
# CPU flag operations
#


Cond = Operand('Cond', intcc)
f = Operand('f', iflags)
a = Operand('a', b1)

trueif = Instruction(
        'trueif', r"""
        Test integer CPU flags for a specific condition.

        Check the CPU flags in ``f`` against the ``Cond`` condition code and
        return true when the condition code is satisfied.
        """,
        ins=(Cond, f), outs=a)

Cond = Operand('Cond', floatcc)
f = Operand('f', fflags)

trueff = Instruction(
        'trueff', r"""
        Test floating point CPU flags for a specific condition.

        Check the CPU flags in ``f`` against the ``Cond`` condition code and
        return true when the condition code is satisfied.
        """,
        ins=(Cond, f), outs=a)

#
# Conversions
#

x = Operand('x', Mem)
a = Operand('a', MemTo, 'Bits of `x` reinterpreted')

bitcast = Instruction(
        'bitcast', r"""
        Reinterpret the bits in `x` as a different type.

        The input and output types must be storable to memory and of the same
        size. A bitcast is equivalent to storing one type and loading the other
        type from the same address.
        """,
        ins=x, outs=a)

Bool = TypeVar(
        'Bool',
        'A scalar or vector boolean type',
        bools=True, simd=True)
BoolTo = TypeVar(
        'BoolTo',
        'A smaller boolean type with the same number of lanes',
        bools=True, simd=True)

x = Operand('x', Bool)
a = Operand('a', BoolTo)

breduce = Instruction(
        'breduce', r"""
        Convert `x` to a smaller boolean type in the platform-defined way.

        The result type must have the same number of vector lanes as the input,
        and each lane must not have more bits that the input lanes. If the
        input and output types are the same, this is a no-op.
        """, ins=x, outs=a, constraints=WiderOrEq(Bool, BoolTo))

BoolTo = TypeVar(
        'BoolTo',
        'A larger boolean type with the same number of lanes',
        bools=True, simd=True)

x = Operand('x', Bool)
a = Operand('a', BoolTo)

bextend = Instruction(
        'bextend', r"""
        Convert `x` to a larger boolean type in the platform-defined way.

        The result type must have the same number of vector lanes as the input,
        and each lane must not have fewer bits that the input lanes. If the
        input and output types are the same, this is a no-op.
        """, ins=x, outs=a, constraints=WiderOrEq(BoolTo, Bool))

IntTo = TypeVar(
        'IntTo', 'An integer type with the same number of lanes',
        ints=True, simd=True)

x = Operand('x', Bool)
a = Operand('a', IntTo)

bint = Instruction(
        'bint', r"""
        Convert `x` to an integer.

        True maps to 1 and false maps to 0. The result type must have the same
        number of vector lanes as the input.
        """, ins=x, outs=a)

bmask = Instruction(
        'bmask', r"""
        Convert `x` to an integer mask.

        True maps to all 1s and false maps to all 0s. The result type must have
        the same number of vector lanes as the input.
        """, ins=x, outs=a)

Int = TypeVar('Int', 'A scalar or vector integer type', ints=True, simd=True)
IntTo = TypeVar(
        'IntTo', 'A smaller integer type with the same number of lanes',
        ints=True, simd=True)

x = Operand('x', Int)
a = Operand('a', IntTo)

ireduce = Instruction(
        'ireduce', r"""
        Convert `x` to a smaller integer type by dropping high bits.

        Each lane in `x` is converted to a smaller integer type by discarding
        the most significant bits. This is the same as reducing modulo
        :math:`2^n`.

        The result type must have the same number of vector lanes as the input,
        and each lane must not have more bits that the input lanes. If the
        input and output types are the same, this is a no-op.
        """,
        ins=x, outs=a, constraints=WiderOrEq(Int, IntTo))


IntTo = TypeVar(
        'IntTo', 'A larger integer type with the same number of lanes',
        ints=True, simd=True)

x = Operand('x', Int)
a = Operand('a', IntTo)

uextend = Instruction(
        'uextend', r"""
        Convert `x` to a larger integer type by zero-extending.

        Each lane in `x` is converted to a larger integer type by adding
        zeroes. The result has the same numerical value as `x` when both are
        interpreted as unsigned integers.

        The result type must have the same number of vector lanes as the input,
        and each lane must not have fewer bits that the input lanes. If the
        input and output types are the same, this is a no-op.
        """,
        ins=x, outs=a, constraints=WiderOrEq(IntTo, Int))

sextend = Instruction(
        'sextend', r"""
        Convert `x` to a larger integer type by sign-extending.

        Each lane in `x` is converted to a larger integer type by replicating
        the sign bit. The result has the same numerical value as `x` when both
        are interpreted as signed integers.

        The result type must have the same number of vector lanes as the input,
        and each lane must not have fewer bits that the input lanes. If the
        input and output types are the same, this is a no-op.
        """,
        ins=x, outs=a, constraints=WiderOrEq(IntTo, Int))

FloatTo = TypeVar(
        'FloatTo', 'A scalar or vector floating point number',
        floats=True, simd=True)

x = Operand('x', Float)
a = Operand('a', FloatTo)

fpromote = Instruction(
        'fpromote', r"""
        Convert `x` to a larger floating point format.

        Each lane in `x` is converted to the destination floating point format.
        This is an exact operation.

        Cranelift currently only supports two floating point formats
        - :type:`f32` and :type:`f64`. This may change in the future.

        The result type must have the same number of vector lanes as the input,
        and the result lanes must not have fewer bits than the input lanes. If
        the input and output types are the same, this is a no-op.
        """,
        ins=x, outs=a, constraints=WiderOrEq(FloatTo, Float))

fdemote = Instruction(
        'fdemote', r"""
        Convert `x` to a smaller floating point format.

        Each lane in `x` is converted to the destination floating point format
        by rounding to nearest, ties to even.

        Cranelift currently only supports two floating point formats
        - :type:`f32` and :type:`f64`. This may change in the future.

        The result type must have the same number of vector lanes as the input,
        and the result lanes must not have more bits than the input lanes. If
        the input and output types are the same, this is a no-op.
        """,
        ins=x, outs=a, constraints=WiderOrEq(Float, FloatTo))

x = Operand('x', Float)
a = Operand('a', IntTo)

fcvt_to_uint = Instruction(
        'fcvt_to_uint', r"""
        Convert floating point to unsigned integer.

        Each lane in `x` is converted to an unsigned integer by rounding
        towards zero. If `x` is NaN or if the unsigned integral value cannot be
        represented in the result type, this instruction traps.

        The result type must have the same number of vector lanes as the input.
        """,
        ins=x, outs=a, can_trap=True)

fcvt_to_uint_sat = Instruction(
        'fcvt_to_uint_sat', r"""
        Convert floating point to unsigned integer as fcvt_to_uint does, but
        saturates the input instead of trapping. NaN and negative values are
        converted to 0.
        """,
        ins=x, outs=a)

fcvt_to_sint = Instruction(
        'fcvt_to_sint', r"""
        Convert floating point to signed integer.

        Each lane in `x` is converted to a signed integer by rounding towards
        zero. If `x` is NaN or if the signed integral value cannot be
        represented in the result type, this instruction traps.

        The result type must have the same number of vector lanes as the input.
        """,
        ins=x, outs=a, can_trap=True)

fcvt_to_sint_sat = Instruction(
        'fcvt_to_sint_sat', r"""
        Convert floating point to signed integer as fcvt_to_sint does, but
        saturates the input instead of trapping. NaN values are converted to 0.
        """,
        ins=x, outs=a)

x = Operand('x', Int)
a = Operand('a', FloatTo)

fcvt_from_uint = Instruction(
        'fcvt_from_uint', r"""
        Convert unsigned integer to floating point.

        Each lane in `x` is interpreted as an unsigned integer and converted to
        floating point using round to nearest, ties to even.

        The result type must have the same number of vector lanes as the input.
        """,
        ins=x, outs=a)

fcvt_from_sint = Instruction(
        'fcvt_from_sint', r"""
        Convert signed integer to floating point.

        Each lane in `x` is interpreted as a signed integer and converted to
        floating point using round to nearest, ties to even.

        The result type must have the same number of vector lanes as the input.
        """,
        ins=x, outs=a)

#
# Legalization helper instructions.
#

WideInt = TypeVar(
        'WideInt', 'An integer type with lanes from `i16` upwards',
        ints=(16, 64), simd=True)
x = Operand('x', WideInt)
lo = Operand(
        'lo', WideInt.half_width(), 'The low bits of `x`')
hi = Operand(
        'hi', WideInt.half_width(), 'The high bits of `x`')

isplit = Instruction(
        'isplit', r"""
        Split an integer into low and high parts.

        Vectors of integers are split lane-wise, so the results have the same
        number of lanes as the input, but the lanes are half the size.

        Returns the low half of `x` and the high half of `x` as two independent
        values.
        """,
        ins=x, outs=(lo, hi), is_ghost=True)


NarrowInt = TypeVar(
        'NarrowInt', 'An integer type with lanes type to `i32`',
        ints=(8, 32), simd=True)
lo = Operand('lo', NarrowInt)
hi = Operand('hi', NarrowInt)
a = Operand(
        'a', NarrowInt.double_width(),
        doc='The concatenation of `lo` and `hi`')

iconcat = Instruction(
        'iconcat', r"""
        Concatenate low and high bits to form a larger integer type.

        Vectors of integers are concatenated lane-wise such that the result has
        the same number of lanes as the inputs, but the lanes are twice the
        size.
        """,
        ins=(lo, hi), outs=a, is_ghost=True)

GROUP.close()