aboutsummaryrefslogtreecommitdiff
path: root/target/hexagon/idef-parser/parser-helpers.c
blob: 7b5ebafec231e7e8910fe91b22ed743f3e38ed5f (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
/*
 *  Copyright(c) 2019-2023 rev.ng Labs Srl. All Rights Reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <assert.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "idef-parser.h"
#include "parser-helpers.h"
#include "idef-parser.tab.h"
#include "idef-parser.yy.h"

void yyerror(YYLTYPE *locp,
             yyscan_t scanner __attribute__((unused)),
             Context *c,
             const char *s)
{
    const char *code_ptr = c->input_buffer;

    fprintf(stderr, "WARNING (%s): '%s'\n", c->inst.name->str, s);

    fprintf(stderr, "Problematic range: ");
    for (int i = locp->first_column; i < locp->last_column; i++) {
        if (code_ptr[i] != '\n') {
            fprintf(stderr, "%c", code_ptr[i]);
        }
    }
    fprintf(stderr, "\n");

    for (unsigned i = 0;
         i < 80 &&
         code_ptr[locp->first_column - 10 + i] != '\0' &&
         code_ptr[locp->first_column - 10 + i] != '\n';
         i++) {
        fprintf(stderr, "%c", code_ptr[locp->first_column - 10 + i]);
    }
    fprintf(stderr, "\n");
    for (unsigned i = 0; i < 9; i++) {
        fprintf(stderr, " ");
    }
    fprintf(stderr, "^");
    for (int i = 0; i < (locp->last_column - locp->first_column) - 1; i++) {
        fprintf(stderr, "~");
    }
    fprintf(stderr, "\n");
    c->inst.error_count++;
}

bool is_direct_predicate(HexValue *value)
{
    return value->pred.id >= '0' && value->pred.id <= '3';
}

bool is_inside_ternary(Context *c)
{
    return c->ternary->len > 0;
}

/* Print functions */
void str_print(Context *c, YYLTYPE *locp, const char *string)
{
    (void) locp;
    EMIT(c, "%s", string);
}

void uint8_print(Context *c, YYLTYPE *locp, uint8_t *num)
{
    (void) locp;
    EMIT(c, "%u", *num);
}

void uint64_print(Context *c, YYLTYPE *locp, uint64_t *num)
{
    (void) locp;
    EMIT(c, "%" PRIu64, *num);
}

void int_print(Context *c, YYLTYPE *locp, int *num)
{
    (void) locp;
    EMIT(c, "%d", *num);
}

void uint_print(Context *c, YYLTYPE *locp, unsigned *num)
{
    (void) locp;
    EMIT(c, "%u", *num);
}

void tmp_print(Context *c, YYLTYPE *locp, HexTmp *tmp)
{
    (void) locp;
    EMIT(c, "tmp_%d", tmp->index);
}

void pred_print(Context *c, YYLTYPE *locp, HexPred *pred, bool is_dotnew)
{
    (void) locp;
    char suffix = is_dotnew ? 'N' : 'V';
    EMIT(c, "P%c%c", pred->id, suffix);
}

void reg_compose(Context *c, YYLTYPE *locp, HexReg *reg, char reg_id[5])
{
    memset(reg_id, 0, 5 * sizeof(char));
    switch (reg->type) {
    case GENERAL_PURPOSE:
        reg_id[0] = 'R';
        break;
    case CONTROL:
        reg_id[0] = 'C';
        break;
    case MODIFIER:
        reg_id[0] = 'M';
        break;
    case DOTNEW:
        reg_id[0] = 'N';
        reg_id[1] = reg->id;
        reg_id[2] = 'N';
        return;
    }
    switch (reg->bit_width) {
    case 32:
        reg_id[1] = reg->id;
        reg_id[2] = 'V';
        break;
    case 64:
        reg_id[1] = reg->id;
        reg_id[2] = reg->id;
        reg_id[3] = 'V';
        break;
    default:
        yyassert(c, locp, false, "Unhandled register bit width!\n");
    }
}

static void reg_arg_print(Context *c, YYLTYPE *locp, HexReg *reg)
{
    char reg_id[5];
    reg_compose(c, locp, reg, reg_id);
    EMIT(c, "%s", reg_id);
}

void reg_print(Context *c, YYLTYPE *locp, HexReg *reg)
{
    (void) locp;
    EMIT(c, "hex_gpr[%u]", reg->id);
}

void imm_print(Context *c, YYLTYPE *locp, HexValue *rvalue)
{
    HexImm *imm = &rvalue->imm;
    switch (imm->type) {
    case I:
        EMIT(c, "i");
        break;
    case VARIABLE:
        EMIT(c, "%ciV", imm->id);
        break;
    case VALUE:
        if (rvalue->bit_width == 32) {
            if (rvalue->signedness == UNSIGNED) {
                EMIT(c, "((uint32_t) 0x%" PRIx32 ")", (uint32_t) imm->value);
            }  else {
                EMIT(c, "((int32_t) 0x%" PRIx32 ")", (int32_t) imm->value);
            }
        } else if (rvalue->bit_width == 64) {
            if (rvalue->signedness == UNSIGNED) {
                EMIT(c, "((uint64_t) 0x%" PRIx64 "ULL)", (uint64_t) imm->value);
            } else {
                EMIT(c, "((int64_t) 0x%" PRIx64 "LL)", (int64_t) imm->value);
            }
        } else {
            g_assert_not_reached();
        }
        break;
    case QEMU_TMP:
        EMIT(c, "qemu_tmp_%" PRIu64, imm->index);
        break;
    case IMM_PC:
        EMIT(c, "ctx->base.pc_next");
        break;
    case IMM_CONSTEXT:
        EMIT(c, "insn->extension_valid");
        break;
    default:
        yyassert(c, locp, false, "Cannot print this expression!");
    }
}

void var_print(Context *c, YYLTYPE *locp, HexVar *var)
{
    (void) locp;
    EMIT(c, "%s", var->name->str);
}

void rvalue_print(Context *c, YYLTYPE *locp, void *pointer)
{
  HexValue *rvalue = (HexValue *) pointer;
  switch (rvalue->type) {
  case REGISTER:
      reg_print(c, locp, &rvalue->reg);
      break;
  case REGISTER_ARG:
      reg_arg_print(c, locp, &rvalue->reg);
      break;
  case TEMP:
      tmp_print(c, locp, &rvalue->tmp);
      break;
  case IMMEDIATE:
      imm_print(c, locp, rvalue);
      break;
  case VARID:
      var_print(c, locp, &rvalue->var);
      break;
  case PREDICATE:
      pred_print(c, locp, &rvalue->pred, rvalue->is_dotnew);
      break;
  default:
      yyassert(c, locp, false, "Cannot print this expression!");
  }
}

void out_assert(Context *c, YYLTYPE *locp,
                void *dummy __attribute__((unused)))
{
    yyassert(c, locp, false, "Unhandled print type!");
}

/* Copy output code buffer */
void commit(Context *c)
{
    /* Emit instruction pseudocode */
    EMIT_SIG(c, "\n" START_COMMENT " ");
    for (char *x = c->inst.code_begin; x < c->inst.code_end; x++) {
        EMIT_SIG(c, "%c", *x);
    }
    EMIT_SIG(c, " " END_COMMENT "\n");

    /* Commit instruction code to output file */
    fwrite(c->signature_str->str, sizeof(char), c->signature_str->len,
           c->output_file);
    fwrite(c->header_str->str, sizeof(char), c->header_str->len,
           c->output_file);
    fwrite(c->out_str->str, sizeof(char), c->out_str->len,
           c->output_file);

    fwrite(c->signature_str->str, sizeof(char), c->signature_str->len,
           c->defines_file);
    fprintf(c->defines_file, ";\n");
}

static void gen_c_int_type(Context *c, YYLTYPE *locp, unsigned bit_width,
                           HexSignedness signedness)
{
    const char *signstr = (signedness == UNSIGNED) ? "u" : "";
    OUT(c, locp, signstr, "int", &bit_width, "_t");
}

static HexValue gen_constant(Context *c,
                             YYLTYPE *locp,
                             const char *value,
                             unsigned bit_width,
                             HexSignedness signedness)
{
    HexValue rvalue;
    assert(bit_width == 32 || bit_width == 64);
    memset(&rvalue, 0, sizeof(HexValue));
    rvalue.type = TEMP;
    rvalue.bit_width = bit_width;
    rvalue.signedness = signedness;
    rvalue.is_dotnew = false;
    rvalue.tmp.index = c->inst.tmp_count;
    OUT(c, locp, "TCGv_i", &bit_width, " tmp_", &c->inst.tmp_count,
        " = tcg_constant_i", &bit_width, "(", value, ");\n");
    c->inst.tmp_count++;
    return rvalue;
}

/* Temporary values creation */
HexValue gen_tmp(Context *c,
                 YYLTYPE *locp,
                 unsigned bit_width,
                 HexSignedness signedness)
{
    HexValue rvalue;
    assert(bit_width == 32 || bit_width == 64);
    memset(&rvalue, 0, sizeof(HexValue));
    rvalue.type = TEMP;
    rvalue.bit_width = bit_width;
    rvalue.signedness = signedness;
    rvalue.is_dotnew = false;
    rvalue.tmp.index = c->inst.tmp_count;
    OUT(c, locp, "TCGv_i", &bit_width, " tmp_", &c->inst.tmp_count,
        " = tcg_temp_new_i", &bit_width, "();\n");
    c->inst.tmp_count++;
    return rvalue;
}

static HexValue gen_constant_from_imm(Context *c,
                                      YYLTYPE *locp,
                                      HexValue *value)
{
    HexValue rvalue;
    assert(value->type == IMMEDIATE);
    memset(&rvalue, 0, sizeof(HexValue));
    rvalue.type = TEMP;
    rvalue.bit_width = value->bit_width;
    rvalue.signedness = value->signedness;
    rvalue.is_dotnew = false;
    rvalue.tmp.index = c->inst.tmp_count;
    /*
     * Here we output the call to `tcg_constant_i<width>` in
     * order to create the temporary value. Note, that we
     * add a cast
     *
     *   `tcg_constant_i<width>`((int<width>_t) ...)`
     *
     * This cast is required to avoid implicit integer
     * conversion warnings since all immediates are
     * output as `((int64_t) 123ULL)`, even if the
     * integer is 32-bit.
     */
    OUT(c, locp, "TCGv_i", &rvalue.bit_width, " tmp_", &c->inst.tmp_count);
    OUT(c, locp, " = tcg_constant_i", &rvalue.bit_width,
        "((int", &rvalue.bit_width, "_t) (", value, "));\n");

    c->inst.tmp_count++;
    return rvalue;
}

HexValue gen_imm_value(Context *c __attribute__((unused)),
                       YYLTYPE *locp,
                       int value,
                       unsigned bit_width,
                       HexSignedness signedness)
{
    (void) locp;
    HexValue rvalue;
    assert(bit_width == 32 || bit_width == 64);
    memset(&rvalue, 0, sizeof(HexValue));
    rvalue.type = IMMEDIATE;
    rvalue.bit_width = bit_width;
    rvalue.signedness = signedness;
    rvalue.is_dotnew = false;
    rvalue.imm.type = VALUE;
    rvalue.imm.value = value;
    return rvalue;
}

HexValue gen_imm_qemu_tmp(Context *c, YYLTYPE *locp, unsigned bit_width,
                          HexSignedness signedness)
{
    (void) locp;
    HexValue rvalue;
    assert(bit_width == 32 || bit_width == 64);
    memset(&rvalue, 0, sizeof(HexValue));
    rvalue.type = IMMEDIATE;
    rvalue.is_dotnew = false;
    rvalue.bit_width = bit_width;
    rvalue.signedness = signedness;
    rvalue.imm.type = QEMU_TMP;
    rvalue.imm.index = c->inst.qemu_tmp_count++;
    return rvalue;
}

HexValue rvalue_materialize(Context *c, YYLTYPE *locp, HexValue *rvalue)
{
    if (rvalue->type == IMMEDIATE) {
        return gen_constant_from_imm(c, locp, rvalue);
    }
    return *rvalue;
}

HexValue gen_rvalue_extend(Context *c, YYLTYPE *locp, HexValue *rvalue)
{
    assert_signedness(c, locp, rvalue->signedness);
    if (rvalue->bit_width > 32) {
        return *rvalue;
    }

    if (rvalue->type == IMMEDIATE) {
        HexValue res = gen_imm_qemu_tmp(c, locp, 64, rvalue->signedness);
        gen_c_int_type(c, locp, 64, rvalue->signedness);
        OUT(c, locp, " ", &res, " = (");
        gen_c_int_type(c, locp, 64, rvalue->signedness);
        OUT(c, locp, ")", rvalue, ";\n");
        return res;
    } else {
        HexValue res = gen_tmp(c, locp, 64, rvalue->signedness);
        bool is_unsigned = (rvalue->signedness == UNSIGNED);
        const char *sign_suffix = is_unsigned ? "u" : "";
        OUT(c, locp, "tcg_gen_ext", sign_suffix,
            "_i32_i64(", &res, ", ", rvalue, ");\n");
        return res;
    }
}

HexValue gen_rvalue_truncate(Context *c, YYLTYPE *locp, HexValue *rvalue)
{
    if (rvalue->type == IMMEDIATE) {
        HexValue res = *rvalue;
        res.bit_width = 32;
        return res;
    } else {
        if (rvalue->bit_width == 64) {
            HexValue res = gen_tmp(c, locp, 32, rvalue->signedness);
            OUT(c, locp, "tcg_gen_trunc_i64_tl(", &res, ", ", rvalue, ");\n");
            return res;
        }
    }
    return *rvalue;
}

/*
 * Attempts to lookup the `Var` struct associated with the given `varid`.
 * The `dst` argument is populated with the found name, bit_width, and
 * signedness, given that `dst` is non-NULL. Returns true if the lookup
 * succeeded and false otherwise.
 */
static bool try_find_variable(Context *c, YYLTYPE *locp,
                              HexValue *dst,
                              HexValue *varid)
{
    yyassert(c, locp, varid, "varid to lookup is NULL");
    yyassert(c, locp, varid->type == VARID,
             "Can only lookup variables by varid");
    for (unsigned i = 0; i < c->inst.allocated->len; i++) {
        Var *curr = &g_array_index(c->inst.allocated, Var, i);
        if (g_string_equal(varid->var.name, curr->name)) {
            if (dst) {
                dst->var.name = curr->name;
                dst->bit_width = curr->bit_width;
                dst->signedness = curr->signedness;
            }
            return true;
        }
    }
    return false;
}

/* Calls `try_find_variable` and asserts succcess. */
static void find_variable(Context *c, YYLTYPE *locp,
                          HexValue *dst,
                          HexValue *varid)
{
    bool found = try_find_variable(c, locp, dst, varid);
    yyassert(c, locp, found, "Use of undeclared variable!\n");
}

/* Handle signedness, if both unsigned -> result is unsigned, else signed */
static inline HexSignedness bin_op_signedness(Context *c, YYLTYPE *locp,
                                              HexSignedness sign1,
                                              HexSignedness sign2)
{
    assert_signedness(c, locp, sign1);
    assert_signedness(c, locp, sign2);
    return (sign1 == UNSIGNED && sign2 == UNSIGNED) ? UNSIGNED : SIGNED;
}

void gen_varid_allocate(Context *c,
                        YYLTYPE *locp,
                        HexValue *varid,
                        unsigned bit_width,
                        HexSignedness signedness)
{
    const char *bit_suffix = (bit_width == 64) ? "i64" : "i32";
    bool found = try_find_variable(c, locp, NULL, varid);
    Var new_var;

    memset(&new_var, 0, sizeof(Var));

    yyassert(c, locp, !found, "Redeclaration of variables not allowed!");
    assert_signedness(c, locp, signedness);

    /* `varid` only carries name information */
    new_var.name = varid->var.name;
    new_var.bit_width = bit_width;
    new_var.signedness = signedness;

    EMIT_HEAD(c, "TCGv_%s %s", bit_suffix, varid->var.name->str);
    EMIT_HEAD(c, " = tcg_temp_new_%s();\n", bit_suffix);
    g_array_append_val(c->inst.allocated, new_var);
}

enum OpTypes {
    IMM_IMM = 0,
    IMM_REG = 1,
    REG_IMM = 2,
    REG_REG = 3,
};

HexValue gen_bin_cmp(Context *c,
                     YYLTYPE *locp,
                     TCGCond type,
                     HexValue *op1,
                     HexValue *op2)
{
    HexValue op1_m = *op1;
    HexValue op2_m = *op2;
    enum OpTypes op_types = (op1_m.type != IMMEDIATE) << 1
                            | (op2_m.type != IMMEDIATE);

    bool op_is64bit = op1_m.bit_width == 64 || op2_m.bit_width == 64;
    const char *bit_suffix = op_is64bit ? "i64" : "i32";
    unsigned bit_width = (op_is64bit) ? 64 : 32;
    HexValue res = gen_tmp(c, locp, bit_width, UNSIGNED);

    /* Extend to 64-bits, if required */
    if (op_is64bit) {
        op1_m = gen_rvalue_extend(c, locp, &op1_m);
        op2_m = gen_rvalue_extend(c, locp, &op2_m);
    }

    switch (op_types) {
    case IMM_IMM:
    case IMM_REG:
        yyassert(c, locp, false, "Binary comparisons between IMM op IMM and"
                                 "IMM op REG not handled!");
        break;
    case REG_IMM:
        OUT(c, locp, "tcg_gen_setcondi_", bit_suffix, "(");
        OUT(c, locp, cond_to_str(type), ", ", &res, ", ", &op1_m, ", ", &op2_m,
            ");\n");
        break;
    case REG_REG:
        OUT(c, locp, "tcg_gen_setcond_", bit_suffix, "(");
        OUT(c, locp, cond_to_str(type), ", ", &res, ", ", &op1_m, ", ", &op2_m,
            ");\n");
        break;
    default:
        fprintf(stderr, "Error in evalutating immediateness!");
        abort();
    }
    return res;
}

static void gen_simple_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                          const char *bit_suffix, HexValue *res,
                          enum OpTypes op_types,
                          HexValue *op1,
                          HexValue *op2,
                          const char *imm_imm,
                          const char *imm_reg,
                          const char *reg_imm,
                          const char *reg_reg)
{
    switch (op_types) {
    case IMM_IMM: {
        HexSignedness signedness = bin_op_signedness(c, locp,
                                                     op1->signedness,
                                                     op2->signedness);
        gen_c_int_type(c, locp, bit_width, signedness);
        OUT(c, locp, " ", res,
            " = ", op1, imm_imm, op2, ";\n");
    } break;
    case IMM_REG:
        OUT(c, locp, imm_reg, bit_suffix,
            "(", res, ", ", op2, ", ", op1, ");\n");
        break;
    case REG_IMM:
        OUT(c, locp, reg_imm, bit_suffix,
            "(", res, ", ", op1, ", ", op2, ");\n");
        break;
    case REG_REG:
        OUT(c, locp, reg_reg, bit_suffix,
            "(", res, ", ", op1, ", ", op2, ");\n");
        break;
    }
}

static void gen_sub_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                       const char *bit_suffix, HexValue *res,
                       enum OpTypes op_types, HexValue *op1,
                       HexValue *op2)
{
    switch (op_types) {
    case IMM_IMM: {
        HexSignedness signedness = bin_op_signedness(c, locp,
                                                     op1->signedness,
                                                     op2->signedness);
        gen_c_int_type(c, locp, bit_width, signedness);
        OUT(c, locp, " ", res,
            " = ", op1, " - ", op2, ";\n");
    } break;
    case IMM_REG: {
        OUT(c, locp, "tcg_gen_subfi_", bit_suffix,
            "(", res, ", ", op1, ", ", op2, ");\n");
    } break;
    case REG_IMM: {
        OUT(c, locp, "tcg_gen_subi_", bit_suffix,
            "(", res, ", ", op1, ", ", op2, ");\n");
    } break;
    case REG_REG: {
        OUT(c, locp, "tcg_gen_sub_", bit_suffix,
            "(", res, ", ", op1, ", ", op2, ");\n");
    } break;
    }
}

static void gen_asl_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                       bool op_is64bit, const char *bit_suffix,
                       HexValue *res, enum OpTypes op_types,
                       HexValue *op1, HexValue *op2)
{
    HexValue op1_m = *op1;
    HexValue op2_m = *op2;
    switch (op_types) {
    case IMM_IMM: {
        HexSignedness signedness = bin_op_signedness(c, locp,
                                                     op1->signedness,
                                                     op2->signedness);
        gen_c_int_type(c, locp, bit_width, signedness);
        OUT(c, locp, " ", res,
            " = ", op1, " << ", op2, ";\n");
    } break;
    case REG_IMM: {
        OUT(c, locp, "if (", op2, " >= ", &bit_width, ") {\n");
        OUT(c, locp, "tcg_gen_movi_", bit_suffix, "(", res, ", 0);\n");
        OUT(c, locp, "} else {\n");
        OUT(c, locp, "tcg_gen_shli_", bit_suffix,
                "(", res, ", ", op1, ", ", op2, ");\n");
        OUT(c, locp, "}\n");
    } break;
    case IMM_REG:
        op1_m.bit_width = bit_width;
        op1_m = rvalue_materialize(c, locp, &op1_m);
        /* fallthrough */
    case REG_REG: {
        OUT(c, locp, "tcg_gen_shl_", bit_suffix,
            "(", res, ", ", &op1_m, ", ", op2, ");\n");
    } break;
    }
    if (op_types == IMM_REG || op_types == REG_REG) {
        /*
         * Handle left shift by 64/32 which hexagon-sim expects to clear out
         * register
         */
        HexValue zero = gen_constant(c, locp, "0", bit_width, UNSIGNED);
        HexValue edge = gen_imm_value(c, locp, bit_width, bit_width, UNSIGNED);
        edge = rvalue_materialize(c, locp, &edge);
        if (op_is64bit) {
            op2_m = gen_rvalue_extend(c, locp, &op2_m);
        }
        op1_m = rvalue_materialize(c, locp, &op1_m);
        op2_m = rvalue_materialize(c, locp, &op2_m);
        OUT(c, locp, "tcg_gen_movcond_i", &bit_width);
        OUT(c, locp, "(TCG_COND_GEU, ", res, ", ", &op2_m, ", ", &edge);
        OUT(c, locp, ", ", &zero, ", ", res, ");\n");
    }
}

static void gen_asr_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                       bool op_is64bit, const char *bit_suffix,
                       HexValue *res, enum OpTypes op_types,
                       HexValue *op1, HexValue *op2)
{
    HexValue op1_m = *op1;
    HexValue op2_m = *op2;
    switch (op_types) {
    case IMM_IMM:
    case IMM_REG:
        yyassert(c, locp, false, "ASR between IMM op IMM, and IMM op REG"
                                 " not handled!");
        break;
    case REG_IMM: {
        HexSignedness signedness = bin_op_signedness(c, locp,
                                                     op1->signedness,
                                                     op2->signedness);
        OUT(c, locp, "{\n");
        gen_c_int_type(c, locp, bit_width, signedness);
        OUT(c, locp, " shift = ", op2, ";\n");
        OUT(c, locp, "if (", op2, " >= ", &bit_width, ") {\n");
        OUT(c, locp, "    shift = ", &bit_width, " - 1;\n");
        OUT(c, locp, "}\n");
        OUT(c, locp, "tcg_gen_sari_", bit_suffix,
            "(", res, ", ", op1, ", shift);\n}\n");
    } break;
    case REG_REG:
        OUT(c, locp, "tcg_gen_sar_", bit_suffix,
            "(", res, ", ", &op1_m, ", ", op2, ");\n");
        break;
    }
    if (op_types == REG_REG) {
        /* Handle right shift by values >= bit_width */
        const char *offset = op_is64bit ? "63" : "31";
        HexValue tmp = gen_tmp(c, locp, bit_width, SIGNED);
        HexValue zero = gen_constant(c, locp, "0", bit_width, SIGNED);
        HexValue edge = gen_imm_value(c, locp, bit_width, bit_width, UNSIGNED);

        edge = rvalue_materialize(c, locp, &edge);
        if (op_is64bit) {
            op2_m = gen_rvalue_extend(c, locp, &op2_m);
        }
        op1_m = rvalue_materialize(c, locp, &op1_m);
        op2_m = rvalue_materialize(c, locp, &op2_m);

        OUT(c, locp, "tcg_gen_extract_", bit_suffix, "(",
            &tmp, ", ", &op1_m, ", ", offset, ", 1);\n");
        OUT(c, locp, "tcg_gen_sub_", bit_suffix, "(",
            &tmp, ", ", &zero, ", ", &tmp, ");\n");
        OUT(c, locp, "tcg_gen_movcond_i", &bit_width);
        OUT(c, locp, "(TCG_COND_GEU, ", res, ", ", &op2_m, ", ", &edge);
        OUT(c, locp, ", ", &tmp, ", ", res, ");\n");
    }
}

static void gen_lsr_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                       bool op_is64bit, const char *bit_suffix,
                       HexValue *res, enum OpTypes op_types,
                       HexValue *op1, HexValue *op2)
{
    HexValue op1_m = *op1;
    HexValue op2_m = *op2;
    switch (op_types) {
    case IMM_IMM:
    case IMM_REG:
        yyassert(c, locp, false, "LSR between IMM op IMM, and IMM op REG"
                                 " not handled!");
        break;
    case REG_IMM:
        OUT(c, locp, "if (", op2, " >= ", &bit_width, ") {\n");
        OUT(c, locp, "tcg_gen_movi_", bit_suffix, "(", res, ", 0);\n");
        OUT(c, locp, "} else {\n");
        OUT(c, locp, "tcg_gen_shri_", bit_suffix,
            "(", res, ", ", op1, ", ", op2, ");\n");
        OUT(c, locp, "}\n");
        break;
    case REG_REG:
        OUT(c, locp, "tcg_gen_shr_", bit_suffix,
            "(", res, ", ", &op1_m, ", ", op2, ");\n");
        break;
    }
    if (op_types == REG_REG) {
        /* Handle right shift by values >= bit_width */
        HexValue zero = gen_constant(c, locp, "0", bit_width, UNSIGNED);
        HexValue edge = gen_imm_value(c, locp, bit_width, bit_width, UNSIGNED);
        edge = rvalue_materialize(c, locp, &edge);
        if (op_is64bit) {
            op2_m = gen_rvalue_extend(c, locp, &op2_m);
        }
        op1_m = rvalue_materialize(c, locp, &op1_m);
        op2_m = rvalue_materialize(c, locp, &op2_m);
        OUT(c, locp, "tcg_gen_movcond_i", &bit_width);
        OUT(c, locp, "(TCG_COND_GEU, ", res, ", ", &op2_m, ", ", &edge);
        OUT(c, locp, ", ", &zero, ", ", res, ");\n");
    }
}

/*
 * Note: This implementation of logical `and` does not mirror that in C.
 * We do not short-circuit logical expressions!
 */
static void gen_andl_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                        const char *bit_suffix, HexValue *res,
                        enum OpTypes op_types, HexValue *op1,
                        HexValue *op2)
{
    (void) bit_width;
    HexValue tmp1, tmp2;
    HexValue zero = gen_constant(c, locp, "0", 32, UNSIGNED);
    memset(&tmp1, 0, sizeof(HexValue));
    memset(&tmp2, 0, sizeof(HexValue));
    switch (op_types) {
    case IMM_IMM:
    case IMM_REG:
    case REG_IMM:
        yyassert(c, locp, false, "ANDL between IMM op IMM, IMM op REG, and"
                                 " REG op IMM, not handled!");
        break;
    case REG_REG:
        tmp1 = gen_bin_cmp(c, locp, TCG_COND_NE, op1, &zero);
        tmp2 = gen_bin_cmp(c, locp, TCG_COND_NE, op2, &zero);
        OUT(c, locp, "tcg_gen_and_", bit_suffix,
            "(", res, ", ", &tmp1, ", ", &tmp2, ");\n");
        break;
    }
}

static void gen_minmax_op(Context *c, YYLTYPE *locp, unsigned bit_width,
                          HexValue *res, enum OpTypes op_types,
                          HexValue *op1, HexValue *op2, bool minmax)
{
    const char *mm;
    HexValue op1_m = *op1;
    HexValue op2_m = *op2;
    bool is_unsigned;

    assert_signedness(c, locp, res->signedness);
    is_unsigned = res->signedness == UNSIGNED;

    if (minmax) {
        /* Max */
        mm = is_unsigned ? "tcg_gen_umax" : "tcg_gen_smax";
    } else {
        /* Min */
        mm = is_unsigned ? "tcg_gen_umin" : "tcg_gen_smin";
    }
    switch (op_types) {
    case IMM_IMM:
        yyassert(c, locp, false, "MINMAX between IMM op IMM, not handled!");
        break;
    case IMM_REG:
        op1_m.bit_width = bit_width;
        op1_m = rvalue_materialize(c, locp, &op1_m);
        OUT(c, locp, mm, "_i", &bit_width, "(");
        OUT(c, locp, res, ", ", &op1_m, ", ", op2, ");\n");
        break;
    case REG_IMM:
        op2_m.bit_width = bit_width;
        op2_m = rvalue_materialize(c, locp, &op2_m);
        /* Fallthrough */
    case REG_REG:
        OUT(c, locp, mm, "_i", &bit_width, "(");
        OUT(c, locp, res, ", ", op1, ", ", &op2_m, ");\n");
        break;
    }
}

/* Code generation functions */
HexValue gen_bin_op(Context *c,
                    YYLTYPE *locp,
                    OpType type,
                    HexValue *op1,
                    HexValue *op2)
{
    /* Replicate operands to avoid side effects */
    HexValue op1_m = *op1;
    HexValue op2_m = *op2;
    enum OpTypes op_types;
    bool op_is64bit;
    HexSignedness signedness;
    unsigned bit_width;
    const char *bit_suffix;
    HexValue res;

    memset(&res, 0, sizeof(HexValue));

    /*
     * If the operands are VARID's we need to look up the
     * type information.
     */
    if (op1_m.type == VARID) {
        find_variable(c, locp, &op1_m, &op1_m);
    }
    if (op2_m.type == VARID) {
        find_variable(c, locp, &op2_m, &op2_m);
    }

    op_types = (op1_m.type != IMMEDIATE) << 1
               | (op2_m.type != IMMEDIATE);
    op_is64bit = op1_m.bit_width == 64 || op2_m.bit_width == 64;
    /* Shift greater than 32 are 64 bits wide */

    if (type == ASL_OP && op2_m.type == IMMEDIATE &&
        op2_m.imm.type == VALUE && op2_m.imm.value >= 32) {
        op_is64bit = true;
    }

    bit_width = (op_is64bit) ? 64 : 32;
    bit_suffix = op_is64bit ? "i64" : "i32";

    /* Extend to 64-bits, if required */
    if (op_is64bit) {
        op1_m = gen_rvalue_extend(c, locp, &op1_m);
        op2_m = gen_rvalue_extend(c, locp, &op2_m);
    }

    signedness = bin_op_signedness(c, locp, op1_m.signedness, op2_m.signedness);
    if (op_types != IMM_IMM) {
        res = gen_tmp(c, locp, bit_width, signedness);
    } else {
        res = gen_imm_qemu_tmp(c, locp, bit_width, signedness);
    }

    switch (type) {
    case ADD_OP:
        gen_simple_op(c, locp, bit_width, bit_suffix, &res,
                      op_types, &op1_m, &op2_m,
                      " + ",
                      "tcg_gen_addi_",
                      "tcg_gen_addi_",
                      "tcg_gen_add_");
        break;
    case SUB_OP:
        gen_sub_op(c, locp, bit_width, bit_suffix, &res, op_types,
                   &op1_m, &op2_m);
        break;
    case MUL_OP:
        gen_simple_op(c, locp, bit_width, bit_suffix, &res,
                      op_types, &op1_m, &op2_m,
                      " * ",
                      "tcg_gen_muli_",
                      "tcg_gen_muli_",
                      "tcg_gen_mul_");
        break;
    case ASL_OP:
        gen_asl_op(c, locp, bit_width, op_is64bit, bit_suffix, &res, op_types,
                   &op1_m, &op2_m);
        break;
    case ASR_OP:
        gen_asr_op(c, locp, bit_width, op_is64bit, bit_suffix, &res, op_types,
                   &op1_m, &op2_m);
        break;
    case LSR_OP:
        gen_lsr_op(c, locp, bit_width, op_is64bit, bit_suffix, &res, op_types,
                   &op1_m, &op2_m);
        break;
    case ANDB_OP:
        gen_simple_op(c, locp, bit_width, bit_suffix, &res,
                      op_types, &op1_m, &op2_m,
                      " & ",
                      "tcg_gen_andi_",
                      "tcg_gen_andi_",
                      "tcg_gen_and_");
        break;
    case ORB_OP:
        gen_simple_op(c, locp, bit_width, bit_suffix, &res,
                      op_types, &op1_m, &op2_m,
                      " | ",
                      "tcg_gen_ori_",
                      "tcg_gen_ori_",
                      "tcg_gen_or_");
        break;
    case XORB_OP:
        gen_simple_op(c, locp, bit_width, bit_suffix, &res,
                      op_types, &op1_m, &op2_m,
                      " ^ ",
                      "tcg_gen_xori_",
                      "tcg_gen_xori_",
                      "tcg_gen_xor_");
        break;
    case ANDL_OP:
        gen_andl_op(c, locp, bit_width, bit_suffix, &res, op_types, &op1_m,
                    &op2_m);
        break;
    case MINI_OP:
        gen_minmax_op(c, locp, bit_width, &res, op_types, &op1_m, &op2_m,
                      false);
        break;
    case MAXI_OP:
        gen_minmax_op(c, locp, bit_width, &res, op_types, &op1_m, &op2_m, true);
        break;
    }
    return res;
}

HexValue gen_cast_op(Context *c,
                     YYLTYPE *locp,
                     HexValue *src,
                     unsigned target_width,
                     HexSignedness signedness)
{
    HexValue res;
    assert_signedness(c, locp, src->signedness);
    if (src->bit_width == target_width) {
        res = *src;
    } else if (src->bit_width < target_width) {
        res = gen_rvalue_extend(c, locp, src);
    } else {
        /* src->bit_width > target_width */
        res = gen_rvalue_truncate(c, locp, src);
    }
    res.signedness = signedness;
    return res;
}


/*
 * Implements an extension when the `src_width` is an immediate.
 * If the `value` to extend is also an immediate we use `extract/sextract`
 * from QEMU `bitops.h`. If `value` is a TCGv then we rely on
 * `tcg_gen_extract/tcg_gen_sextract`.
 */
static HexValue gen_extend_imm_width_op(Context *c,
                                        YYLTYPE *locp,
                                        HexValue *src_width,
                                        unsigned dst_width,
                                        HexValue *value,
                                        HexSignedness signedness)
{
    /*
     * If the source width is not an immediate value, we need to guard
     * our extend op with if statements to handle the case where
     * `src_width_m` is 0.
     */
    const char *sign_prefix;
    bool need_guarding;

    assert_signedness(c, locp, signedness);
    assert(dst_width == 64 || dst_width == 32);
    assert(src_width->type == IMMEDIATE);

    sign_prefix = (signedness == UNSIGNED) ? "" : "s";
    need_guarding = (src_width->imm.type != VALUE);

    if (src_width->imm.type == VALUE &&
        src_width->imm.value == 0) {
        /*
         * We can bail out early if the source width is known to be zero
         * at translation time.
         */
        return gen_imm_value(c, locp, 0, dst_width, signedness);
    }

    if (value->type == IMMEDIATE) {
        /*
         * If both the value and source width are immediates,
         * we can perform the extension at translation time
         * using QEMUs bitops.
         */
        HexValue res = gen_imm_qemu_tmp(c, locp, dst_width, signedness);
        gen_c_int_type(c, locp, dst_width, signedness);
        OUT(c, locp, " ", &res, " = 0;\n");
        if (need_guarding) {
            OUT(c, locp, "if (", src_width, " != 0) {\n");
        }
        OUT(c, locp, &res, " = ", sign_prefix, "extract", &dst_width);
        OUT(c, locp, "(", value, ", 0, ", src_width, ");\n");
        if (need_guarding) {
            OUT(c, locp, "}\n");
        }
        return res;
    } else {
        /*
         * If the source width is an immediate and the value to
         * extend is a TCGv, then use tcg_gen_extract/tcg_gen_sextract
         */
        HexValue res = gen_tmp(c, locp, dst_width, signedness);

        /*
         * If the width is an immediate value we know it is non-zero
         * at this point, otherwise we need an if-statement
         */
        if (need_guarding) {
            OUT(c, locp, "if (", src_width, " != 0) {\n");
        }
        OUT(c, locp, "tcg_gen_", sign_prefix, "extract_i", &dst_width);
        OUT(c, locp, "(", &res, ", ", value, ", 0, ", src_width,
            ");\n");
        if (need_guarding) {
            OUT(c, locp, "} else {\n");
            OUT(c, locp, "tcg_gen_movi_i", &dst_width, "(", &res,
                ", 0);\n");
            OUT(c, locp, "}\n");
        }
        return res;
    }
}

/*
 * Implements an extension when the `src_width` is given by
 * a TCGv. Here we need to reimplement the behaviour of
 * `tcg_gen_extract` and the like using shifts and masks.
 */
static HexValue gen_extend_tcg_width_op(Context *c,
                                        YYLTYPE *locp,
                                        HexValue *src_width,
                                        unsigned dst_width,
                                        HexValue *value,
                                        HexSignedness signedness)
{
    HexValue src_width_m = rvalue_materialize(c, locp, src_width);
    HexValue zero = gen_constant(c, locp, "0", dst_width, UNSIGNED);
    HexValue shift = gen_tmp(c, locp, dst_width, UNSIGNED);
    HexValue res;

    assert_signedness(c, locp, signedness);
    assert(dst_width == 64 || dst_width == 32);
    assert(src_width->type != IMMEDIATE);

    res = gen_tmp(c, locp, dst_width, signedness);

    OUT(c, locp, "tcg_gen_subfi_i", &dst_width);
    OUT(c, locp, "(", &shift, ", ", &dst_width, ", ", &src_width_m, ");\n");
    if (signedness == UNSIGNED) {
        HexValue mask = gen_constant(c, locp, "-1", dst_width, UNSIGNED);
        OUT(c, locp, "tcg_gen_shr_i", &dst_width, "(",
            &res, ", ", &mask, ", ", &shift, ");\n");
        OUT(c, locp, "tcg_gen_and_i", &dst_width, "(",
            &res, ", ", &res, ", ", value, ");\n");
    } else {
        OUT(c, locp, "tcg_gen_shl_i", &dst_width, "(",
            &res, ", ", value, ", ", &shift, ");\n");
        OUT(c, locp, "tcg_gen_sar_i", &dst_width, "(",
            &res, ", ", &res, ", ", &shift, ");\n");
    }
    OUT(c, locp, "tcg_gen_movcond_i", &dst_width, "(TCG_COND_EQ, ", &res,
        ", ");
    OUT(c, locp, &src_width_m, ", ", &zero, ", ", &zero, ", ", &res,
        ");\n");

    return res;
}

HexValue gen_extend_op(Context *c,
                       YYLTYPE *locp,
                       HexValue *src_width,
                       unsigned dst_width,
                       HexValue *value,
                       HexSignedness signedness)
{
    unsigned bit_width = (dst_width == 64) ? 64 : 32;
    HexValue value_m = *value;
    HexValue src_width_m = *src_width;

    assert_signedness(c, locp, signedness);
    yyassert(c, locp, value_m.bit_width <= bit_width &&
                      src_width_m.bit_width <= bit_width,
                      "Extending to a size smaller than the current size"
                      " makes no sense");

    if (value_m.bit_width < bit_width) {
        value_m = gen_rvalue_extend(c, locp, &value_m);
    }

    if (src_width_m.bit_width < bit_width) {
        src_width_m = gen_rvalue_extend(c, locp, &src_width_m);
    }

    if (src_width_m.type == IMMEDIATE) {
        return gen_extend_imm_width_op(c, locp, &src_width_m, bit_width,
                                       &value_m, signedness);
    } else {
        return gen_extend_tcg_width_op(c, locp, &src_width_m, bit_width,
                                       &value_m, signedness);
    }
}

/*
 * Implements `rdeposit` for the special case where `width`
 * is of TCGv type. In this case we need to reimplement the behaviour
 * of `tcg_gen_deposit*` using binary operations and masks/shifts.
 *
 * Note: this is the only type of `rdeposit` that occurs, meaning the
 * `width` is _NEVER_ of IMMEDIATE type.
 */
void gen_rdeposit_op(Context *c,
                     YYLTYPE *locp,
                     HexValue *dst,
                     HexValue *value,
                     HexValue *begin,
                     HexValue *width)
{
    /*
     * Otherwise if the width is not known, we fallback on reimplementing
     * desposit in TCG.
     */
    HexValue begin_m = *begin;
    HexValue value_m = *value;
    HexValue width_m = *width;
    const char *mask_str = (dst->bit_width == 32)
        ? "0xffffffffUL"
        : "0xffffffffffffffffUL";
    HexValue mask = gen_constant(c, locp, mask_str, dst->bit_width,
                                 UNSIGNED);
    const char *dst_width_str = (dst->bit_width == 32) ? "32" : "64";
    HexValue k64 = gen_constant(c, locp, dst_width_str, dst->bit_width,
                                UNSIGNED);
    HexValue res;
    HexValue zero;

    assert(dst->bit_width >= value->bit_width);
    assert(begin->type == IMMEDIATE && begin->imm.type == VALUE);
    assert(dst->type == REGISTER_ARG);

    yyassert(c, locp, width->type != IMMEDIATE,
             "Immediate index to rdeposit not handled!");

    yyassert(c, locp, value_m.bit_width == dst->bit_width &&
                      begin_m.bit_width == dst->bit_width &&
                      width_m.bit_width == dst->bit_width,
                      "Extension/truncation should be taken care of"
                      " before rdeposit!");

    width_m = rvalue_materialize(c, locp, &width_m);

    /*
     * mask = 0xffffffffffffffff >> (64 - width)
     * mask = mask << begin
     * value = (value << begin) & mask
     * res = dst & ~mask
     * res = res | value
     * dst = (width != 0) ? res : dst
     */
    k64 = gen_bin_op(c, locp, SUB_OP, &k64, &width_m);
    mask = gen_bin_op(c, locp, LSR_OP, &mask, &k64);
    mask = gen_bin_op(c, locp, ASL_OP, &mask, &begin_m);
    value_m = gen_bin_op(c, locp, ASL_OP, &value_m, &begin_m);
    value_m = gen_bin_op(c, locp, ANDB_OP, &value_m, &mask);

    OUT(c, locp, "tcg_gen_not_i", &dst->bit_width, "(", &mask, ", ",
        &mask, ");\n");
    res = gen_bin_op(c, locp, ANDB_OP, dst, &mask);
    res = gen_bin_op(c, locp, ORB_OP, &res, &value_m);

    /*
     * We don't need to truncate `res` here, since all operations involved use
     * the same bit width.
     */

    /* If the width is zero, then return the identity dst = dst */
    zero = gen_constant(c, locp, "0", res.bit_width, UNSIGNED);
    OUT(c, locp, "tcg_gen_movcond_i", &res.bit_width, "(TCG_COND_NE, ",
        dst);
    OUT(c, locp, ", ", &width_m, ", ", &zero, ", ", &res, ", ", dst,
        ");\n");
}

void gen_deposit_op(Context *c,
                    YYLTYPE *locp,
                    HexValue *dst,
                    HexValue *value,
                    HexValue *index,
                    HexCast *cast)
{
    HexValue value_m = *value;
    unsigned bit_width = (dst->bit_width == 64) ? 64 : 32;
    unsigned width = cast->bit_width;

    yyassert(c, locp, index->type == IMMEDIATE,
             "Deposit index must be immediate!\n");

    /*
     * Using tcg_gen_deposit_i**(dst, dst, ...) requires dst to be
     * initialized.
     */
    gen_inst_init_args(c, locp);

    /* If the destination value is 32, truncate the value, otherwise extend */
    if (dst->bit_width != value->bit_width) {
        if (bit_width == 32) {
            value_m = gen_rvalue_truncate(c, locp, &value_m);
        } else {
            value_m = gen_rvalue_extend(c, locp, &value_m);
        }
    }
    value_m = rvalue_materialize(c, locp, &value_m);
    OUT(c, locp, "tcg_gen_deposit_i", &bit_width, "(", dst, ", ", dst, ", ");
    OUT(c, locp, &value_m, ", ", index, " * ", &width, ", ", &width, ");\n");
}

HexValue gen_rextract_op(Context *c,
                         YYLTYPE *locp,
                         HexValue *src,
                         unsigned begin,
                         unsigned width)
{
    unsigned bit_width = (src->bit_width == 64) ? 64 : 32;
    HexValue res = gen_tmp(c, locp, bit_width, UNSIGNED);
    OUT(c, locp, "tcg_gen_extract_i", &bit_width, "(", &res);
    OUT(c, locp, ", ", src, ", ", &begin, ", ", &width, ");\n");
    return res;
}

HexValue gen_extract_op(Context *c,
                        YYLTYPE *locp,
                        HexValue *src,
                        HexValue *index,
                        HexExtract *extract)
{
    unsigned bit_width = (src->bit_width == 64) ? 64 : 32;
    unsigned width = extract->bit_width;
    const char *sign_prefix;
    HexValue res;

    yyassert(c, locp, index->type == IMMEDIATE,
             "Extract index must be immediate!\n");
    assert_signedness(c, locp, extract->signedness);

    sign_prefix = (extract->signedness == UNSIGNED) ? "" : "s";
    res = gen_tmp(c, locp, bit_width, extract->signedness);

    OUT(c, locp, "tcg_gen_", sign_prefix, "extract_i", &bit_width,
        "(", &res, ", ", src);
    OUT(c, locp, ", ", index, " * ", &width, ", ", &width, ");\n");

    /* Some extract operations have bit_width != storage_bit_width */
    if (extract->storage_bit_width > bit_width) {
        HexValue tmp = gen_tmp(c, locp, extract->storage_bit_width,
                               extract->signedness);
        const char *sign_suffix = (extract->signedness == UNSIGNED) ? "u" : "";
        OUT(c, locp, "tcg_gen_ext", sign_suffix, "_i32_i64(",
            &tmp, ", ", &res, ");\n");
        res = tmp;
    }
    return res;
}

void gen_write_reg(Context *c, YYLTYPE *locp, HexValue *reg, HexValue *value)
{
    HexValue value_m = *value;
    yyassert(c, locp, reg->type == REGISTER, "reg must be a register!");
    value_m = gen_rvalue_truncate(c, locp, &value_m);
    value_m = rvalue_materialize(c, locp, &value_m);
    OUT(c,
        locp,
        "gen_log_reg_write(ctx, ", &reg->reg.id, ", ",
        &value_m, ");\n");
}

void gen_assign(Context *c,
                YYLTYPE *locp,
                HexValue *dst,
                HexValue *value)
{
    HexValue value_m = *value;
    unsigned bit_width;

    yyassert(c, locp, !is_inside_ternary(c),
             "Assign in ternary not allowed!");

    if (dst->type == REGISTER) {
        gen_write_reg(c, locp, dst, &value_m);
        return;
    }

    if (dst->type == VARID) {
        find_variable(c, locp, dst, dst);
    }
    bit_width = dst->bit_width == 64 ? 64 : 32;

    if (bit_width != value_m.bit_width) {
        if (bit_width == 64) {
            value_m = gen_rvalue_extend(c, locp, &value_m);
        } else {
            value_m = gen_rvalue_truncate(c, locp, &value_m);
        }
    }

    const char *imm_suffix = (value_m.type == IMMEDIATE) ? "i" : "";
    OUT(c, locp, "tcg_gen_mov", imm_suffix, "_i", &bit_width,
        "(", dst, ", ", &value_m, ");\n");
}

HexValue gen_convround(Context *c,
                       YYLTYPE *locp,
                       HexValue *src)
{
    HexValue src_m = *src;
    unsigned bit_width = src_m.bit_width;
    const char *size = (bit_width == 32) ? "32" : "64";
    HexValue res = gen_tmp(c, locp, bit_width, src->signedness);
    HexValue mask = gen_constant(c, locp, "0x3", bit_width, UNSIGNED);
    HexValue one = gen_constant(c, locp, "1", bit_width, UNSIGNED);
    HexValue and;
    HexValue src_p1;

    and = gen_bin_op(c, locp, ANDB_OP, &src_m, &mask);
    src_p1 = gen_bin_op(c, locp, ADD_OP, &src_m, &one);

    OUT(c, locp, "tcg_gen_movcond_i", size, "(TCG_COND_EQ, ", &res);
    OUT(c, locp, ", ", &and, ", ", &mask, ", ");
    OUT(c, locp, &src_p1, ", ", &src_m, ");\n");

    return res;
}

static HexValue gen_convround_n_b(Context *c,
                                  YYLTYPE *locp,
                                  HexValue *a,
                                  HexValue *n)
{
    HexValue one = gen_constant(c, locp, "1", 32, UNSIGNED);
    HexValue res = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue tmp = gen_tmp(c, locp, 32, UNSIGNED);
    HexValue tmp_64 = gen_tmp(c, locp, 64, UNSIGNED);

    assert(n->type != IMMEDIATE);
    OUT(c, locp, "tcg_gen_ext_i32_i64(", &res, ", ", a, ");\n");
    OUT(c, locp, "tcg_gen_shl_i32(", &tmp);
    OUT(c, locp, ", ", &one, ", ", n, ");\n");
    OUT(c, locp, "tcg_gen_and_i32(", &tmp);
    OUT(c, locp, ", ", &tmp, ", ", a, ");\n");
    OUT(c, locp, "tcg_gen_shri_i32(", &tmp);
    OUT(c, locp, ", ", &tmp, ", 1);\n");
    OUT(c, locp, "tcg_gen_ext_i32_i64(", &tmp_64, ", ", &tmp, ");\n");
    OUT(c, locp, "tcg_gen_add_i64(", &res);
    OUT(c, locp, ", ", &res, ", ", &tmp_64, ");\n");

    return res;
}

static HexValue gen_convround_n_c(Context *c,
                                  YYLTYPE *locp,
                                  HexValue *a,
                                  HexValue *n)
{
    HexValue res = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue one = gen_constant(c, locp, "1", 32, UNSIGNED);
    HexValue tmp = gen_tmp(c, locp, 32, UNSIGNED);
    HexValue tmp_64 = gen_tmp(c, locp, 64, UNSIGNED);

    OUT(c, locp, "tcg_gen_ext_i32_i64(", &res, ", ", a, ");\n");
    OUT(c, locp, "tcg_gen_subi_i32(", &tmp);
    OUT(c, locp, ", ", n, ", 1);\n");
    OUT(c, locp, "tcg_gen_shl_i32(", &tmp);
    OUT(c, locp, ", ", &one, ", ", &tmp, ");\n");
    OUT(c, locp, "tcg_gen_ext_i32_i64(", &tmp_64, ", ", &tmp, ");\n");
    OUT(c, locp, "tcg_gen_add_i64(", &res);
    OUT(c, locp, ", ", &res, ", ", &tmp_64, ");\n");

    return res;
}

HexValue gen_convround_n(Context *c,
                         YYLTYPE *locp,
                         HexValue *src,
                         HexValue *pos)
{
    HexValue zero = gen_constant(c, locp, "0", 64, UNSIGNED);
    HexValue l_32 = gen_constant(c, locp, "1", 32, UNSIGNED);
    HexValue cond = gen_tmp(c, locp, 32, UNSIGNED);
    HexValue cond_64 = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue mask = gen_tmp(c, locp, 32, UNSIGNED);
    HexValue n_64 = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue res = gen_tmp(c, locp, 64, UNSIGNED);
    /* If input is 64 bit cast it to 32 */
    HexValue src_casted = gen_cast_op(c, locp, src, 32, src->signedness);
    HexValue pos_casted = gen_cast_op(c, locp, pos, 32, pos->signedness);
    HexValue r1;
    HexValue r2;
    HexValue r3;

    src_casted = rvalue_materialize(c, locp, &src_casted);
    pos_casted = rvalue_materialize(c, locp, &pos_casted);

    /*
     * r1, r2, and r3 represent the results of three different branches.
     *   - r1 picked if pos_casted == 0
     *   - r2 picked if (src_casted & ((1 << (pos_casted - 1)) - 1)) == 0),
     *     that is if bits 0, ..., pos_casted-1 are all 0.
     *   - r3 picked otherwise.
     */
    r1 = gen_rvalue_extend(c, locp, &src_casted);
    r2 = gen_convround_n_b(c, locp, &src_casted, &pos_casted);
    r3 = gen_convround_n_c(c, locp, &src_casted, &pos_casted);

    /*
     * Calculate the condition
     *   (src_casted & ((1 << (pos_casted - 1)) - 1)) == 0),
     * which checks if the bits 0,...,pos-1 are all 0.
     */
    OUT(c, locp, "tcg_gen_sub_i32(", &mask);
    OUT(c, locp, ", ", &pos_casted, ", ", &l_32, ");\n");
    OUT(c, locp, "tcg_gen_shl_i32(", &mask);
    OUT(c, locp, ", ", &l_32, ", ", &mask, ");\n");
    OUT(c, locp, "tcg_gen_sub_i32(", &mask);
    OUT(c, locp, ", ", &mask, ", ", &l_32, ");\n");
    OUT(c, locp, "tcg_gen_and_i32(", &cond);
    OUT(c, locp, ", ", &src_casted, ", ", &mask, ");\n");
    OUT(c, locp, "tcg_gen_extu_i32_i64(", &cond_64, ", ", &cond, ");\n");

    OUT(c, locp, "tcg_gen_ext_i32_i64(", &n_64, ", ", &pos_casted, ");\n");

    /*
     * if the bits 0, ..., pos_casted-1 are all 0, then pick r2 otherwise,
     * pick r3.
     */
    OUT(c, locp, "tcg_gen_movcond_i64");
    OUT(c, locp, "(TCG_COND_EQ, ", &res, ", ", &cond_64, ", ", &zero);
    OUT(c, locp, ", ", &r2, ", ", &r3, ");\n");

    /* Lastly, if the pos_casted == 0, then pick r1 */
    OUT(c, locp, "tcg_gen_movcond_i64");
    OUT(c, locp, "(TCG_COND_EQ, ", &res, ", ", &n_64, ", ", &zero);
    OUT(c, locp, ", ", &r1, ", ", &res, ");\n");

    /* Finally shift back val >>= n */
    OUT(c, locp, "tcg_gen_shr_i64(", &res);
    OUT(c, locp, ", ", &res, ", ", &n_64, ");\n");

    res = gen_rvalue_truncate(c, locp, &res);
    return res;
}

HexValue gen_round(Context *c,
                   YYLTYPE *locp,
                   HexValue *src,
                   HexValue *pos)
{
    HexValue zero = gen_constant(c, locp, "0", 64, UNSIGNED);
    HexValue one = gen_constant(c, locp, "1", 64, UNSIGNED);
    HexValue res;
    HexValue n_m1;
    HexValue shifted;
    HexValue sum;
    HexValue src_width;
    HexValue a;
    HexValue b;

    assert_signedness(c, locp, src->signedness);
    yyassert(c, locp, src->bit_width <= 32,
             "fRNDN not implemented for bit widths > 32!");

    res = gen_tmp(c, locp, 64, src->signedness);

    src_width = gen_imm_value(c, locp, src->bit_width, 32, UNSIGNED);
    a = gen_extend_op(c, locp, &src_width, 64, src, SIGNED);
    a = rvalue_materialize(c, locp, &a);

    src_width = gen_imm_value(c, locp, 5, 32, UNSIGNED);
    b = gen_extend_op(c, locp, &src_width, 64, pos, UNSIGNED);
    b = rvalue_materialize(c, locp, &b);

    n_m1 = gen_bin_op(c, locp, SUB_OP, &b, &one);
    shifted = gen_bin_op(c, locp, ASL_OP, &one, &n_m1);
    sum = gen_bin_op(c, locp, ADD_OP, &shifted, &a);

    OUT(c, locp, "tcg_gen_movcond_i64");
    OUT(c, locp, "(TCG_COND_EQ, ", &res, ", ", &b, ", ", &zero);
    OUT(c, locp, ", ", &a, ", ", &sum, ");\n");

    return res;
}

/* Circular addressing mode with auto-increment */
void gen_circ_op(Context *c,
                 YYLTYPE *locp,
                 HexValue *addr,
                 HexValue *increment,
                 HexValue *modifier)
{
    HexValue cs = gen_tmp(c, locp, 32, UNSIGNED);
    HexValue increment_m = *increment;
    increment_m = rvalue_materialize(c, locp, &increment_m);
    OUT(c, locp, "gen_read_reg(", &cs, ", HEX_REG_CS0 + MuN);\n");
    OUT(c,
        locp,
        "gen_helper_fcircadd(",
        addr,
        ", ",
        addr,
        ", ",
        &increment_m,
        ", ",
        modifier);
    OUT(c, locp, ", ", &cs, ");\n");
}

HexValue gen_locnt_op(Context *c, YYLTYPE *locp, HexValue *src)
{
    const char *bit_suffix = src->bit_width == 64 ? "64" : "32";
    HexValue src_m = *src;
    HexValue res;

    assert_signedness(c, locp, src->signedness);
    res = gen_tmp(c, locp, src->bit_width == 64 ? 64 : 32, src->signedness);
    src_m = rvalue_materialize(c, locp, &src_m);
    OUT(c, locp, "tcg_gen_not_i", bit_suffix, "(",
        &res, ", ", &src_m, ");\n");
    OUT(c, locp, "tcg_gen_clzi_i", bit_suffix, "(", &res, ", ", &res, ", ");
    OUT(c, locp, bit_suffix, ");\n");
    return res;
}

HexValue gen_ctpop_op(Context *c, YYLTYPE *locp, HexValue *src)
{
    const char *bit_suffix = src->bit_width == 64 ? "64" : "32";
    HexValue src_m = *src;
    HexValue res;
    assert_signedness(c, locp, src->signedness);
    res = gen_tmp(c, locp, src->bit_width == 64 ? 64 : 32, src->signedness);
    src_m = rvalue_materialize(c, locp, &src_m);
    OUT(c, locp, "tcg_gen_ctpop_i", bit_suffix,
        "(", &res, ", ", &src_m, ");\n");
    return res;
}

HexValue gen_rotl(Context *c, YYLTYPE *locp, HexValue *src, HexValue *width)
{
    const char *suffix = src->bit_width == 64 ? "i64" : "i32";
    HexValue amount = *width;
    HexValue res;
    assert_signedness(c, locp, src->signedness);
    res = gen_tmp(c, locp, src->bit_width, src->signedness);
    if (amount.bit_width < src->bit_width) {
        amount = gen_rvalue_extend(c, locp, &amount);
    } else {
        amount = gen_rvalue_truncate(c, locp, &amount);
    }
    amount = rvalue_materialize(c, locp, &amount);
    OUT(c, locp, "tcg_gen_rotl_", suffix, "(",
        &res, ", ", src, ", ", &amount, ");\n");

    return res;
}

HexValue gen_carry_from_add(Context *c,
                            YYLTYPE *locp,
                            HexValue *op1,
                            HexValue *op2,
                            HexValue *op3)
{
    HexValue zero = gen_constant(c, locp, "0", 64, UNSIGNED);
    HexValue res = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue cf = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue op1_m = rvalue_materialize(c, locp, op1);
    HexValue op2_m = rvalue_materialize(c, locp, op2);
    HexValue op3_m = rvalue_materialize(c, locp, op3);
    op3_m = gen_rvalue_extend(c, locp, &op3_m);

    OUT(c, locp, "tcg_gen_add2_i64(", &res, ", ", &cf, ", ", &op1_m, ", ",
        &zero);
    OUT(c, locp, ", ", &op3_m, ", ", &zero, ");\n");
    OUT(c, locp, "tcg_gen_add2_i64(", &res, ", ", &cf, ", ", &res, ", ", &cf);
    OUT(c, locp, ", ", &op2_m, ", ", &zero, ");\n");

    return cf;
}

void gen_addsat64(Context *c,
                  YYLTYPE *locp,
                  HexValue *dst,
                  HexValue *op1,
                  HexValue *op2)
{
    HexValue op1_m = rvalue_materialize(c, locp, op1);
    HexValue op2_m = rvalue_materialize(c, locp, op2);
    OUT(c, locp, "gen_add_sat_i64(ctx, ", dst, ", ", &op1_m, ", ",
                                  &op2_m, ");\n");
}

void gen_inst(Context *c, GString *iname)
{
    c->total_insn++;
    c->inst.name = iname;
    c->inst.allocated = g_array_new(FALSE, FALSE, sizeof(Var));
    c->inst.init_list = g_array_new(FALSE, FALSE, sizeof(HexValue));
    c->inst.strings = g_array_new(FALSE, FALSE, sizeof(GString *));
    EMIT_SIG(c, "void emit_%s(DisasContext *ctx, Insn *insn, Packet *pkt",
             c->inst.name->str);
}


/*
 * Initialize declared but uninitialized registers, but only for
 * non-conditional instructions
 */
void gen_inst_init_args(Context *c, YYLTYPE *locp)
{
    if (!c->inst.init_list) {
        return;
    }

    for (unsigned i = 0; i < c->inst.init_list->len; i++) {
        HexValue *val = &g_array_index(c->inst.init_list, HexValue, i);
        if (val->type == REGISTER_ARG) {
            /* Nothing to do here */
        } else if (val->type == PREDICATE) {
            char suffix = val->is_dotnew ? 'N' : 'V';
            EMIT_HEAD(c, "tcg_gen_movi_i%u(P%c%c, 0);\n", val->bit_width,
                      val->pred.id, suffix);
        } else {
            yyassert(c, locp, false, "Invalid arg type!");
        }
    }

    /* Free argument init list once we have initialized everything */
    g_array_free(c->inst.init_list, TRUE);
    c->inst.init_list = NULL;
}

void gen_inst_code(Context *c, YYLTYPE *locp)
{
    if (c->inst.error_count != 0) {
        fprintf(stderr,
                "Parsing of instruction %s generated %d errors!\n",
                c->inst.name->str,
                c->inst.error_count);
    } else {
        c->implemented_insn++;
        fprintf(c->enabled_file, "%s\n", c->inst.name->str);
        emit_footer(c);
        commit(c);
    }
    free_instruction(c);
}

void gen_pred_assign(Context *c, YYLTYPE *locp, HexValue *left_pred,
                     HexValue *right_pred)
{
    char pred_id[2] = {left_pred->pred.id, 0};
    bool is_direct = is_direct_predicate(left_pred);
    HexValue r = rvalue_materialize(c, locp, right_pred);
    r = gen_rvalue_truncate(c, locp, &r);
    yyassert(c, locp, !is_inside_ternary(c),
             "Predicate assign not allowed in ternary!");
    /* Extract predicate TCGv */
    if (is_direct) {
        *left_pred = gen_tmp(c, locp, 32, UNSIGNED);
    }
    /* Extract first 8 bits, and store new predicate value */
    OUT(c, locp, "tcg_gen_andi_i32(", left_pred, ", ", &r, ", 0xff);\n");
    if (is_direct) {
        OUT(c, locp, "gen_log_pred_write(ctx, ", pred_id, ", ", left_pred,
            ");\n");
    }
}

void gen_cancel(Context *c, YYLTYPE *locp)
{
    OUT(c, locp, "gen_cancel(insn->slot);\n");
}

void gen_load_cancel(Context *c, YYLTYPE *locp)
{
    OUT(c, locp, "if (insn->slot == 0 && pkt->pkt_has_store_s1) {\n");
    OUT(c, locp, "ctx->s1_store_processed = false;\n");
    OUT(c, locp, "process_store(ctx, 1);\n");
    OUT(c, locp, "}\n");
}

void gen_load(Context *c, YYLTYPE *locp, HexValue *width,
              HexSignedness signedness, HexValue *ea, HexValue *dst)
{
    unsigned dst_bit_width;
    unsigned src_bit_width;

    /* Memop width is specified in the load macro */
    assert_signedness(c, locp, signedness);

    /* If dst is a variable, assert that is declared and load the type info */
    if (dst->type == VARID) {
        find_variable(c, locp, dst, dst);
    }

    src_bit_width = width->imm.value * 8;
    dst_bit_width = MAX(dst->bit_width, 32);

    /* Lookup the effective address EA */
    find_variable(c, locp, ea, ea);
    OUT(c, locp, "if (insn->slot == 0 && pkt->pkt_has_store_s1) {\n");
    OUT(c, locp, "probe_noshuf_load(", ea, ", ", width, ", ctx->mem_idx);\n");
    OUT(c, locp, "process_store(ctx, 1);\n");
    OUT(c, locp, "}\n");

    OUT(c, locp, "tcg_gen_qemu_ld_i", &dst_bit_width);
    OUT(c, locp, "(");
    OUT(c, locp, dst, ", ", ea, ", ctx->mem_idx, MO_", &src_bit_width);
    if (signedness == SIGNED) {
        OUT(c, locp, " | MO_SIGN");
    }
    OUT(c, locp, " | MO_TE);\n");
}

void gen_store(Context *c, YYLTYPE *locp, HexValue *width, HexValue *ea,
               HexValue *src)
{
    HexValue src_m = *src;
    /* Memop width is specified in the store macro */
    unsigned mem_width = width->imm.value;
    /* Lookup the effective address EA */
    find_variable(c, locp, ea, ea);
    src_m = rvalue_materialize(c, locp, &src_m);
    OUT(c, locp, "gen_store", &mem_width, "(cpu_env, ", ea, ", ", &src_m);
    OUT(c, locp, ", insn->slot);\n");
}

void gen_sethalf(Context *c, YYLTYPE *locp, HexCast *sh, HexValue *n,
                 HexValue *dst, HexValue *value)
{
    yyassert(c, locp, n->type == IMMEDIATE,
             "Deposit index must be immediate!\n");
    if (dst->type == VARID) {
        find_variable(c, locp, dst, dst);
    }

    gen_deposit_op(c, locp, dst, value, n, sh);
}

void gen_setbits(Context *c, YYLTYPE *locp, HexValue *hi, HexValue *lo,
                 HexValue *dst, HexValue *value)
{
    unsigned len;
    HexValue tmp;

    yyassert(c, locp, hi->type == IMMEDIATE &&
             hi->imm.type == VALUE &&
             lo->type == IMMEDIATE &&
             lo->imm.type == VALUE,
             "Range deposit needs immediate values!\n");

    *value = gen_rvalue_truncate(c, locp, value);
    len = hi->imm.value + 1 - lo->imm.value;
    tmp = gen_tmp(c, locp, 32, value->signedness);
    /* Emit an `and` to ensure `value` is either 0 or 1. */
    OUT(c, locp, "tcg_gen_andi_i32(", &tmp, ", ", value, ", 1);\n");
    /* Use `neg` to map 0 -> 0 and 1 -> 0xffff... */
    OUT(c, locp, "tcg_gen_neg_i32(", &tmp, ", ", &tmp, ");\n");
    OUT(c, locp, "tcg_gen_deposit_i32(", dst, ", ", dst,
        ", ", &tmp, ", ");
    OUT(c, locp, lo, ", ", &len, ");\n");
}

unsigned gen_if_cond(Context *c, YYLTYPE *locp, HexValue *cond)
{
    const char *bit_suffix;
    /* Generate an end label, if false branch to that label */
    OUT(c, locp, "TCGLabel *if_label_", &c->inst.if_count,
        " = gen_new_label();\n");
    *cond = rvalue_materialize(c, locp, cond);
    bit_suffix = (cond->bit_width == 64) ? "i64" : "i32";
    OUT(c, locp, "tcg_gen_brcondi_", bit_suffix, "(TCG_COND_EQ, ", cond,
        ", 0, if_label_", &c->inst.if_count, ");\n");
    return c->inst.if_count++;
}

unsigned gen_if_else(Context *c, YYLTYPE *locp, unsigned index)
{
    unsigned if_index = c->inst.if_count++;
    /* Generate label to jump if else is not verified */
    OUT(c, locp, "TCGLabel *if_label_", &if_index,
        " = gen_new_label();\n");
    /* Jump out of the else statement */
    OUT(c, locp, "tcg_gen_br(if_label_", &if_index, ");\n");
    /* Fix the else label */
    OUT(c, locp, "gen_set_label(if_label_", &index, ");\n");
    return if_index;
}

HexValue gen_rvalue_pred(Context *c, YYLTYPE *locp, HexValue *pred)
{
    /* Predicted instructions need to zero out result args */
    gen_inst_init_args(c, locp);

    if (is_direct_predicate(pred)) {
        bool is_dotnew = pred->is_dotnew;
        char predicate_id[2] = { pred->pred.id, '\0' };
        char *pred_str = (char *) &predicate_id;
        *pred = gen_tmp(c, locp, 32, UNSIGNED);
        if (is_dotnew) {
            OUT(c, locp, "tcg_gen_mov_i32(", pred,
                ", ctx->new_pred_value[");
            OUT(c, locp, pred_str, "]);\n");
        } else {
            OUT(c, locp, "gen_read_preg(", pred, ", ", pred_str, ");\n");
        }
    }

    return *pred;
}

HexValue gen_rvalue_var(Context *c, YYLTYPE *locp, HexValue *var)
{
    find_variable(c, locp, var, var);
    return *var;
}

HexValue gen_rvalue_mpy(Context *c, YYLTYPE *locp, HexMpy *mpy,
                        HexValue *op1, HexValue *op2)
{
    HexValue res;
    memset(&res, 0, sizeof(HexValue));

    assert_signedness(c, locp, mpy->first_signedness);
    assert_signedness(c, locp, mpy->second_signedness);

    *op1 = gen_cast_op(c, locp, op1, mpy->first_bit_width * 2,
                     mpy->first_signedness);
    /* Handle fMPTY3216.. */
    if (mpy->first_bit_width == 32) {
        *op2 = gen_cast_op(c, locp, op2, 64, mpy->second_signedness);
    } else {
        *op2 = gen_cast_op(c, locp, op2, mpy->second_bit_width * 2,
                         mpy->second_signedness);
    }
    res = gen_bin_op(c, locp, MUL_OP, op1, op2);
    /* Handle special cases required by the language */
    if (mpy->first_bit_width == 16 && mpy->second_bit_width == 16) {
        HexValue src_width = gen_imm_value(c, locp, 32, 32, UNSIGNED);
        HexSignedness signedness = bin_op_signedness(c, locp,
                                                     mpy->first_signedness,
                                                     mpy->second_signedness);
        res = gen_extend_op(c, locp, &src_width, 64, &res,
                            signedness);
    }
    return res;
}

static inline HexValue gen_rvalue_simple_unary(Context *c, YYLTYPE *locp,
                                               HexValue *value,
                                               const char *c_code,
                                               const char *tcg_code)
{
    unsigned bit_width = (value->bit_width == 64) ? 64 : 32;
    HexValue res;
    if (value->type == IMMEDIATE) {
        res = gen_imm_qemu_tmp(c, locp, bit_width, value->signedness);
        gen_c_int_type(c, locp, value->bit_width, value->signedness);
        OUT(c, locp, " ", &res, " = ", c_code, "(", value, ");\n");
    } else {
        res = gen_tmp(c, locp, bit_width, value->signedness);
        OUT(c, locp, tcg_code, "_i", &bit_width, "(", &res, ", ", value,
            ");\n");
    }
    return res;
}


HexValue gen_rvalue_not(Context *c, YYLTYPE *locp, HexValue *value)
{
    return gen_rvalue_simple_unary(c, locp, value, "~", "tcg_gen_not");
}

HexValue gen_rvalue_notl(Context *c, YYLTYPE *locp, HexValue *value)
{
    unsigned bit_width = (value->bit_width == 64) ? 64 : 32;
    HexValue res;
    if (value->type == IMMEDIATE) {
        res = gen_imm_qemu_tmp(c, locp, bit_width, value->signedness);
        gen_c_int_type(c, locp, value->bit_width, value->signedness);
        OUT(c, locp, " ", &res, " = !(", value, ");\n");
    } else {
        HexValue zero = gen_constant(c, locp, "0", bit_width, UNSIGNED);
        HexValue one = gen_constant(c, locp, "0xff", bit_width, UNSIGNED);
        res = gen_tmp(c, locp, bit_width, value->signedness);
        OUT(c, locp, "tcg_gen_movcond_i", &bit_width);
        OUT(c, locp, "(TCG_COND_EQ, ", &res, ", ", value, ", ", &zero);
        OUT(c, locp, ", ", &one, ", ", &zero, ");\n");
    }
    return res;
}

HexValue gen_rvalue_sat(Context *c, YYLTYPE *locp, HexSat *sat,
                        HexValue *width, HexValue *value)
{
    const char *unsigned_str;
    const char *bit_suffix = (value->bit_width == 64) ? "i64" : "i32";
    HexValue res;
    HexValue ovfl;
    /*
     * Note: all saturates are assumed to implicitly set overflow.
     * This assumption holds for the instructions currently parsed
     * by idef-parser.
     */
    yyassert(c, locp, width->imm.value < value->bit_width,
             "To compute overflow, source width must be greater than"
             " saturation width!");
    yyassert(c, locp, !is_inside_ternary(c),
             "Saturating from within a ternary is not allowed!");
    assert_signedness(c, locp, sat->signedness);

    unsigned_str = (sat->signedness == UNSIGNED) ? "u" : "";
    res = gen_tmp(c, locp, value->bit_width, sat->signedness);
    ovfl = gen_tmp(c, locp, 32, sat->signedness);
    OUT(c, locp, "gen_sat", unsigned_str, "_", bit_suffix, "_ovfl(");
    OUT(c, locp, &ovfl, ", ", &res, ", ", value, ", ", &width->imm.value,
        ");\n");
    OUT(c, locp, "gen_set_usr_field_if(ctx, USR_OVF,", &ovfl, ");\n");

    return res;
}

HexValue gen_rvalue_fscr(Context *c, YYLTYPE *locp, HexValue *value)
{
    HexValue key = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue res = gen_tmp(c, locp, 64, UNSIGNED);
    HexValue frame_key = gen_tmp(c, locp, 32, UNSIGNED);
    *value = gen_rvalue_extend(c, locp, value);
    OUT(c, locp, "gen_read_reg(", &frame_key, ", HEX_REG_FRAMEKEY);\n");
    OUT(c, locp, "tcg_gen_concat_i32_i64(",
        &key, ", ", &frame_key, ", ", &frame_key, ");\n");
    OUT(c, locp, "tcg_gen_xor_i64(", &res, ", ", value, ", ", &key, ");\n");
    return res;
}

HexValue gen_rvalue_abs(Context *c, YYLTYPE *locp, HexValue *value)
{
    return gen_rvalue_simple_unary(c, locp, value, "abs", "tcg_gen_abs");
}

HexValue gen_rvalue_neg(Context *c, YYLTYPE *locp, HexValue *value)
{
    return gen_rvalue_simple_unary(c, locp, value, "-", "tcg_gen_neg");
}

HexValue gen_rvalue_brev(Context *c, YYLTYPE *locp, HexValue *value)
{
    HexValue res;
    yyassert(c, locp, value->bit_width <= 32,
             "fbrev not implemented for 64-bit integers!");
    res = gen_tmp(c, locp, value->bit_width, value->signedness);
    *value = rvalue_materialize(c, locp, value);
    OUT(c, locp, "gen_helper_fbrev(", &res, ", ", value, ");\n");
    return res;
}

HexValue gen_rvalue_ternary(Context *c, YYLTYPE *locp, HexValue *cond,
                            HexValue *true_branch, HexValue *false_branch)
{
    bool is_64bit = (true_branch->bit_width == 64) ||
                    (false_branch->bit_width == 64);
    unsigned bit_width = (is_64bit) ? 64 : 32;
    HexValue zero = gen_constant(c, locp, "0", bit_width, UNSIGNED);
    HexValue res = gen_tmp(c, locp, bit_width, UNSIGNED);

    if (is_64bit) {
        *cond = gen_rvalue_extend(c, locp, cond);
        *true_branch = gen_rvalue_extend(c, locp, true_branch);
        *false_branch = gen_rvalue_extend(c, locp, false_branch);
    } else {
        *cond = gen_rvalue_truncate(c, locp, cond);
    }
    *cond = rvalue_materialize(c, locp, cond);
    *true_branch = rvalue_materialize(c, locp, true_branch);
    *false_branch = rvalue_materialize(c, locp, false_branch);

    OUT(c, locp, "tcg_gen_movcond_i", &bit_width);
    OUT(c, locp, "(TCG_COND_NE, ", &res, ", ", cond, ", ", &zero);
    OUT(c, locp, ", ", true_branch, ", ", false_branch, ");\n");

    assert(c->ternary->len > 0);
    g_array_remove_index(c->ternary, c->ternary->len - 1);

    return res;
}

const char *cond_to_str(TCGCond cond)
{
    switch (cond) {
    case TCG_COND_NEVER:
        return "TCG_COND_NEVER";
    case TCG_COND_ALWAYS:
        return "TCG_COND_ALWAYS";
    case TCG_COND_EQ:
        return "TCG_COND_EQ";
    case TCG_COND_NE:
        return "TCG_COND_NE";
    case TCG_COND_LT:
        return "TCG_COND_LT";
    case TCG_COND_GE:
        return "TCG_COND_GE";
    case TCG_COND_LE:
        return "TCG_COND_LE";
    case TCG_COND_GT:
        return "TCG_COND_GT";
    case TCG_COND_LTU:
        return "TCG_COND_LTU";
    case TCG_COND_GEU:
        return "TCG_COND_GEU";
    case TCG_COND_LEU:
        return "TCG_COND_LEU";
    case TCG_COND_GTU:
        return "TCG_COND_GTU";
    default:
        abort();
    }
}

void emit_arg(Context *c, YYLTYPE *locp, HexValue *arg)
{
    switch (arg->type) {
    case REGISTER_ARG:
        if (arg->reg.type == DOTNEW) {
            EMIT_SIG(c, ", TCGv N%cN", arg->reg.id);
        } else {
            bool is64 = (arg->bit_width == 64);
            const char *type = is64 ? "TCGv_i64" : "TCGv_i32";
            char reg_id[5];
            reg_compose(c, locp, &(arg->reg), reg_id);
            EMIT_SIG(c, ", %s %s", type, reg_id);
            /* MuV register requires also MuN to provide its index */
            if (arg->reg.type == MODIFIER) {
                EMIT_SIG(c, ", int MuN");
            }
        }
        break;
    case PREDICATE:
        {
            char suffix = arg->is_dotnew ? 'N' : 'V';
            EMIT_SIG(c, ", TCGv P%c%c", arg->pred.id, suffix);
        }
        break;
    default:
        {
            fprintf(stderr, "emit_arg got unsupported argument!");
            abort();
        }
    }
}

void emit_footer(Context *c)
{
    EMIT(c, "}\n");
    EMIT(c, "\n");
}

void track_string(Context *c, GString *s)
{
    g_array_append_val(c->inst.strings, s);
}

void free_instruction(Context *c)
{
    assert(!is_inside_ternary(c));
    /* Free the strings */
    g_string_truncate(c->signature_str, 0);
    g_string_truncate(c->out_str, 0);
    g_string_truncate(c->header_str, 0);
    /* Free strings allocated by the instruction */
    for (unsigned i = 0; i < c->inst.strings->len; i++) {
        g_string_free(g_array_index(c->inst.strings, GString*, i), TRUE);
    }
    g_array_free(c->inst.strings, TRUE);
    /* Free INAME token value */
    g_string_free(c->inst.name, TRUE);
    /* Free variables and registers */
    g_array_free(c->inst.allocated, TRUE);
    /* Initialize instruction-specific portion of the context */
    memset(&(c->inst), 0, sizeof(Inst));
}

void assert_signedness(Context *c,
                       YYLTYPE *locp,
                       HexSignedness signedness)
{
    yyassert(c, locp,
             signedness != UNKNOWN_SIGNEDNESS,
             "Unspecified signedness");
}