xref: /openbmc/qemu/tcg/optimize.c (revision c3b920b3d6a685484904d3060f3eb69401051bf0)
1 /*
2  * Optimizations for Tiny Code Generator for QEMU
3  *
4  * Copyright (c) 2010 Samsung Electronics.
5  * Contributed by Kirill Batuzov <batuzovk@ispras.ru>
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include "qemu/int128.h"
28 #include "qemu/interval-tree.h"
29 #include "tcg/tcg-op-common.h"
30 #include "tcg-internal.h"
31 #include "tcg-has.h"
32 
33 #define CASE_OP_32_64(x)                        \
34         glue(glue(case INDEX_op_, x), _i32):    \
35         glue(glue(case INDEX_op_, x), _i64)
36 
37 #define CASE_OP_32_64_VEC(x)                    \
38         glue(glue(case INDEX_op_, x), _i32):    \
39         glue(glue(case INDEX_op_, x), _i64):    \
40         glue(glue(case INDEX_op_, x), _vec)
41 
42 typedef struct MemCopyInfo {
43     IntervalTreeNode itree;
44     QSIMPLEQ_ENTRY (MemCopyInfo) next;
45     TCGTemp *ts;
46     TCGType type;
47 } MemCopyInfo;
48 
49 typedef struct TempOptInfo {
50     bool is_const;
51     TCGTemp *prev_copy;
52     TCGTemp *next_copy;
53     QSIMPLEQ_HEAD(, MemCopyInfo) mem_copy;
54     uint64_t val;
55     uint64_t z_mask;  /* mask bit is 0 if and only if value bit is 0 */
56     uint64_t s_mask;  /* mask bit is 1 if value bit matches msb */
57 } TempOptInfo;
58 
59 typedef struct OptContext {
60     TCGContext *tcg;
61     TCGOp *prev_mb;
62     TCGTempSet temps_used;
63 
64     IntervalTreeRoot mem_copy;
65     QSIMPLEQ_HEAD(, MemCopyInfo) mem_free;
66 
67     /* In flight values from optimization. */
68     TCGType type;
69 } OptContext;
70 
71 static inline TempOptInfo *ts_info(TCGTemp *ts)
72 {
73     return ts->state_ptr;
74 }
75 
76 static inline TempOptInfo *arg_info(TCGArg arg)
77 {
78     return ts_info(arg_temp(arg));
79 }
80 
81 static inline bool ti_is_const(TempOptInfo *ti)
82 {
83     return ti->is_const;
84 }
85 
86 static inline uint64_t ti_const_val(TempOptInfo *ti)
87 {
88     return ti->val;
89 }
90 
91 static inline bool ti_is_const_val(TempOptInfo *ti, uint64_t val)
92 {
93     return ti_is_const(ti) && ti_const_val(ti) == val;
94 }
95 
96 static inline bool ts_is_const(TCGTemp *ts)
97 {
98     return ti_is_const(ts_info(ts));
99 }
100 
101 static inline bool ts_is_const_val(TCGTemp *ts, uint64_t val)
102 {
103     return ti_is_const_val(ts_info(ts), val);
104 }
105 
106 static inline bool arg_is_const(TCGArg arg)
107 {
108     return ts_is_const(arg_temp(arg));
109 }
110 
111 static inline bool arg_is_const_val(TCGArg arg, uint64_t val)
112 {
113     return ts_is_const_val(arg_temp(arg), val);
114 }
115 
116 static inline bool ts_is_copy(TCGTemp *ts)
117 {
118     return ts_info(ts)->next_copy != ts;
119 }
120 
121 static TCGTemp *cmp_better_copy(TCGTemp *a, TCGTemp *b)
122 {
123     return a->kind < b->kind ? b : a;
124 }
125 
126 /* Initialize and activate a temporary.  */
127 static void init_ts_info(OptContext *ctx, TCGTemp *ts)
128 {
129     size_t idx = temp_idx(ts);
130     TempOptInfo *ti;
131 
132     if (test_bit(idx, ctx->temps_used.l)) {
133         return;
134     }
135     set_bit(idx, ctx->temps_used.l);
136 
137     ti = ts->state_ptr;
138     if (ti == NULL) {
139         ti = tcg_malloc(sizeof(TempOptInfo));
140         ts->state_ptr = ti;
141     }
142 
143     ti->next_copy = ts;
144     ti->prev_copy = ts;
145     QSIMPLEQ_INIT(&ti->mem_copy);
146     if (ts->kind == TEMP_CONST) {
147         ti->is_const = true;
148         ti->val = ts->val;
149         ti->z_mask = ts->val;
150         ti->s_mask = INT64_MIN >> clrsb64(ts->val);
151     } else {
152         ti->is_const = false;
153         ti->z_mask = -1;
154         ti->s_mask = 0;
155     }
156 }
157 
158 static MemCopyInfo *mem_copy_first(OptContext *ctx, intptr_t s, intptr_t l)
159 {
160     IntervalTreeNode *r = interval_tree_iter_first(&ctx->mem_copy, s, l);
161     return r ? container_of(r, MemCopyInfo, itree) : NULL;
162 }
163 
164 static MemCopyInfo *mem_copy_next(MemCopyInfo *mem, intptr_t s, intptr_t l)
165 {
166     IntervalTreeNode *r = interval_tree_iter_next(&mem->itree, s, l);
167     return r ? container_of(r, MemCopyInfo, itree) : NULL;
168 }
169 
170 static void remove_mem_copy(OptContext *ctx, MemCopyInfo *mc)
171 {
172     TCGTemp *ts = mc->ts;
173     TempOptInfo *ti = ts_info(ts);
174 
175     interval_tree_remove(&mc->itree, &ctx->mem_copy);
176     QSIMPLEQ_REMOVE(&ti->mem_copy, mc, MemCopyInfo, next);
177     QSIMPLEQ_INSERT_TAIL(&ctx->mem_free, mc, next);
178 }
179 
180 static void remove_mem_copy_in(OptContext *ctx, intptr_t s, intptr_t l)
181 {
182     while (true) {
183         MemCopyInfo *mc = mem_copy_first(ctx, s, l);
184         if (!mc) {
185             break;
186         }
187         remove_mem_copy(ctx, mc);
188     }
189 }
190 
191 static void remove_mem_copy_all(OptContext *ctx)
192 {
193     remove_mem_copy_in(ctx, 0, -1);
194     tcg_debug_assert(interval_tree_is_empty(&ctx->mem_copy));
195 }
196 
197 static TCGTemp *find_better_copy(TCGTemp *ts)
198 {
199     TCGTemp *i, *ret;
200 
201     /* If this is already readonly, we can't do better. */
202     if (temp_readonly(ts)) {
203         return ts;
204     }
205 
206     ret = ts;
207     for (i = ts_info(ts)->next_copy; i != ts; i = ts_info(i)->next_copy) {
208         ret = cmp_better_copy(ret, i);
209     }
210     return ret;
211 }
212 
213 static void move_mem_copies(TCGTemp *dst_ts, TCGTemp *src_ts)
214 {
215     TempOptInfo *si = ts_info(src_ts);
216     TempOptInfo *di = ts_info(dst_ts);
217     MemCopyInfo *mc;
218 
219     QSIMPLEQ_FOREACH(mc, &si->mem_copy, next) {
220         tcg_debug_assert(mc->ts == src_ts);
221         mc->ts = dst_ts;
222     }
223     QSIMPLEQ_CONCAT(&di->mem_copy, &si->mem_copy);
224 }
225 
226 /* Reset TEMP's state, possibly removing the temp for the list of copies.  */
227 static void reset_ts(OptContext *ctx, TCGTemp *ts)
228 {
229     TempOptInfo *ti = ts_info(ts);
230     TCGTemp *pts = ti->prev_copy;
231     TCGTemp *nts = ti->next_copy;
232     TempOptInfo *pi = ts_info(pts);
233     TempOptInfo *ni = ts_info(nts);
234 
235     ni->prev_copy = ti->prev_copy;
236     pi->next_copy = ti->next_copy;
237     ti->next_copy = ts;
238     ti->prev_copy = ts;
239     ti->is_const = false;
240     ti->z_mask = -1;
241     ti->s_mask = 0;
242 
243     if (!QSIMPLEQ_EMPTY(&ti->mem_copy)) {
244         if (ts == nts) {
245             /* Last temp copy being removed, the mem copies die. */
246             MemCopyInfo *mc;
247             QSIMPLEQ_FOREACH(mc, &ti->mem_copy, next) {
248                 interval_tree_remove(&mc->itree, &ctx->mem_copy);
249             }
250             QSIMPLEQ_CONCAT(&ctx->mem_free, &ti->mem_copy);
251         } else {
252             move_mem_copies(find_better_copy(nts), ts);
253         }
254     }
255 }
256 
257 static void reset_temp(OptContext *ctx, TCGArg arg)
258 {
259     reset_ts(ctx, arg_temp(arg));
260 }
261 
262 static void record_mem_copy(OptContext *ctx, TCGType type,
263                             TCGTemp *ts, intptr_t start, intptr_t last)
264 {
265     MemCopyInfo *mc;
266     TempOptInfo *ti;
267 
268     mc = QSIMPLEQ_FIRST(&ctx->mem_free);
269     if (mc) {
270         QSIMPLEQ_REMOVE_HEAD(&ctx->mem_free, next);
271     } else {
272         mc = tcg_malloc(sizeof(*mc));
273     }
274 
275     memset(mc, 0, sizeof(*mc));
276     mc->itree.start = start;
277     mc->itree.last = last;
278     mc->type = type;
279     interval_tree_insert(&mc->itree, &ctx->mem_copy);
280 
281     ts = find_better_copy(ts);
282     ti = ts_info(ts);
283     mc->ts = ts;
284     QSIMPLEQ_INSERT_TAIL(&ti->mem_copy, mc, next);
285 }
286 
287 static bool ts_are_copies(TCGTemp *ts1, TCGTemp *ts2)
288 {
289     TCGTemp *i;
290 
291     if (ts1 == ts2) {
292         return true;
293     }
294 
295     if (!ts_is_copy(ts1) || !ts_is_copy(ts2)) {
296         return false;
297     }
298 
299     for (i = ts_info(ts1)->next_copy; i != ts1; i = ts_info(i)->next_copy) {
300         if (i == ts2) {
301             return true;
302         }
303     }
304 
305     return false;
306 }
307 
308 static bool args_are_copies(TCGArg arg1, TCGArg arg2)
309 {
310     return ts_are_copies(arg_temp(arg1), arg_temp(arg2));
311 }
312 
313 static TCGTemp *find_mem_copy_for(OptContext *ctx, TCGType type, intptr_t s)
314 {
315     MemCopyInfo *mc;
316 
317     for (mc = mem_copy_first(ctx, s, s); mc; mc = mem_copy_next(mc, s, s)) {
318         if (mc->itree.start == s && mc->type == type) {
319             return find_better_copy(mc->ts);
320         }
321     }
322     return NULL;
323 }
324 
325 static TCGArg arg_new_constant(OptContext *ctx, uint64_t val)
326 {
327     TCGType type = ctx->type;
328     TCGTemp *ts;
329 
330     if (type == TCG_TYPE_I32) {
331         val = (int32_t)val;
332     }
333 
334     ts = tcg_constant_internal(type, val);
335     init_ts_info(ctx, ts);
336 
337     return temp_arg(ts);
338 }
339 
340 static TCGArg arg_new_temp(OptContext *ctx)
341 {
342     TCGTemp *ts = tcg_temp_new_internal(ctx->type, TEMP_EBB);
343     init_ts_info(ctx, ts);
344     return temp_arg(ts);
345 }
346 
347 static TCGOp *opt_insert_after(OptContext *ctx, TCGOp *op,
348                                TCGOpcode opc, unsigned narg)
349 {
350     return tcg_op_insert_after(ctx->tcg, op, opc, ctx->type, narg);
351 }
352 
353 static TCGOp *opt_insert_before(OptContext *ctx, TCGOp *op,
354                                 TCGOpcode opc, unsigned narg)
355 {
356     return tcg_op_insert_before(ctx->tcg, op, opc, ctx->type, narg);
357 }
358 
359 static bool tcg_opt_gen_mov(OptContext *ctx, TCGOp *op, TCGArg dst, TCGArg src)
360 {
361     TCGTemp *dst_ts = arg_temp(dst);
362     TCGTemp *src_ts = arg_temp(src);
363     TempOptInfo *di;
364     TempOptInfo *si;
365     TCGOpcode new_op;
366 
367     if (ts_are_copies(dst_ts, src_ts)) {
368         tcg_op_remove(ctx->tcg, op);
369         return true;
370     }
371 
372     reset_ts(ctx, dst_ts);
373     di = ts_info(dst_ts);
374     si = ts_info(src_ts);
375 
376     switch (ctx->type) {
377     case TCG_TYPE_I32:
378     case TCG_TYPE_I64:
379         new_op = INDEX_op_mov;
380         break;
381     case TCG_TYPE_V64:
382     case TCG_TYPE_V128:
383     case TCG_TYPE_V256:
384         /* TCGOP_TYPE and TCGOP_VECE remain unchanged.  */
385         new_op = INDEX_op_mov_vec;
386         break;
387     default:
388         g_assert_not_reached();
389     }
390     op->opc = new_op;
391     op->args[0] = dst;
392     op->args[1] = src;
393 
394     di->z_mask = si->z_mask;
395     di->s_mask = si->s_mask;
396 
397     if (src_ts->type == dst_ts->type) {
398         TempOptInfo *ni = ts_info(si->next_copy);
399 
400         di->next_copy = si->next_copy;
401         di->prev_copy = src_ts;
402         ni->prev_copy = dst_ts;
403         si->next_copy = dst_ts;
404         di->is_const = si->is_const;
405         di->val = si->val;
406 
407         if (!QSIMPLEQ_EMPTY(&si->mem_copy)
408             && cmp_better_copy(src_ts, dst_ts) == dst_ts) {
409             move_mem_copies(dst_ts, src_ts);
410         }
411     }
412     return true;
413 }
414 
415 static bool tcg_opt_gen_movi(OptContext *ctx, TCGOp *op,
416                              TCGArg dst, uint64_t val)
417 {
418     /* Convert movi to mov with constant temp. */
419     return tcg_opt_gen_mov(ctx, op, dst, arg_new_constant(ctx, val));
420 }
421 
422 static uint64_t do_constant_folding_2(TCGOpcode op, uint64_t x, uint64_t y)
423 {
424     uint64_t l64, h64;
425 
426     switch (op) {
427     case INDEX_op_add:
428         return x + y;
429 
430     CASE_OP_32_64(sub):
431         return x - y;
432 
433     CASE_OP_32_64(mul):
434         return x * y;
435 
436     case INDEX_op_and:
437     case INDEX_op_and_vec:
438         return x & y;
439 
440     CASE_OP_32_64_VEC(or):
441         return x | y;
442 
443     CASE_OP_32_64_VEC(xor):
444         return x ^ y;
445 
446     case INDEX_op_shl_i32:
447         return (uint32_t)x << (y & 31);
448 
449     case INDEX_op_shl_i64:
450         return (uint64_t)x << (y & 63);
451 
452     case INDEX_op_shr_i32:
453         return (uint32_t)x >> (y & 31);
454 
455     case INDEX_op_shr_i64:
456         return (uint64_t)x >> (y & 63);
457 
458     case INDEX_op_sar_i32:
459         return (int32_t)x >> (y & 31);
460 
461     case INDEX_op_sar_i64:
462         return (int64_t)x >> (y & 63);
463 
464     case INDEX_op_rotr_i32:
465         return ror32(x, y & 31);
466 
467     case INDEX_op_rotr_i64:
468         return ror64(x, y & 63);
469 
470     case INDEX_op_rotl_i32:
471         return rol32(x, y & 31);
472 
473     case INDEX_op_rotl_i64:
474         return rol64(x, y & 63);
475 
476     CASE_OP_32_64_VEC(not):
477         return ~x;
478 
479     CASE_OP_32_64(neg):
480         return -x;
481 
482     CASE_OP_32_64_VEC(andc):
483         return x & ~y;
484 
485     CASE_OP_32_64_VEC(orc):
486         return x | ~y;
487 
488     CASE_OP_32_64_VEC(eqv):
489         return ~(x ^ y);
490 
491     CASE_OP_32_64_VEC(nand):
492         return ~(x & y);
493 
494     CASE_OP_32_64_VEC(nor):
495         return ~(x | y);
496 
497     case INDEX_op_clz_i32:
498         return (uint32_t)x ? clz32(x) : y;
499 
500     case INDEX_op_clz_i64:
501         return x ? clz64(x) : y;
502 
503     case INDEX_op_ctz_i32:
504         return (uint32_t)x ? ctz32(x) : y;
505 
506     case INDEX_op_ctz_i64:
507         return x ? ctz64(x) : y;
508 
509     case INDEX_op_ctpop_i32:
510         return ctpop32(x);
511 
512     case INDEX_op_ctpop_i64:
513         return ctpop64(x);
514 
515     CASE_OP_32_64(bswap16):
516         x = bswap16(x);
517         return y & TCG_BSWAP_OS ? (int16_t)x : x;
518 
519     CASE_OP_32_64(bswap32):
520         x = bswap32(x);
521         return y & TCG_BSWAP_OS ? (int32_t)x : x;
522 
523     case INDEX_op_bswap64_i64:
524         return bswap64(x);
525 
526     case INDEX_op_ext_i32_i64:
527         return (int32_t)x;
528 
529     case INDEX_op_extu_i32_i64:
530     case INDEX_op_extrl_i64_i32:
531         return (uint32_t)x;
532 
533     case INDEX_op_extrh_i64_i32:
534         return (uint64_t)x >> 32;
535 
536     case INDEX_op_muluh_i32:
537         return ((uint64_t)(uint32_t)x * (uint32_t)y) >> 32;
538     case INDEX_op_mulsh_i32:
539         return ((int64_t)(int32_t)x * (int32_t)y) >> 32;
540 
541     case INDEX_op_muluh_i64:
542         mulu64(&l64, &h64, x, y);
543         return h64;
544     case INDEX_op_mulsh_i64:
545         muls64(&l64, &h64, x, y);
546         return h64;
547 
548     case INDEX_op_div_i32:
549         /* Avoid crashing on divide by zero, otherwise undefined.  */
550         return (int32_t)x / ((int32_t)y ? : 1);
551     case INDEX_op_divu_i32:
552         return (uint32_t)x / ((uint32_t)y ? : 1);
553     case INDEX_op_div_i64:
554         return (int64_t)x / ((int64_t)y ? : 1);
555     case INDEX_op_divu_i64:
556         return (uint64_t)x / ((uint64_t)y ? : 1);
557 
558     case INDEX_op_rem_i32:
559         return (int32_t)x % ((int32_t)y ? : 1);
560     case INDEX_op_remu_i32:
561         return (uint32_t)x % ((uint32_t)y ? : 1);
562     case INDEX_op_rem_i64:
563         return (int64_t)x % ((int64_t)y ? : 1);
564     case INDEX_op_remu_i64:
565         return (uint64_t)x % ((uint64_t)y ? : 1);
566 
567     default:
568         g_assert_not_reached();
569     }
570 }
571 
572 static uint64_t do_constant_folding(TCGOpcode op, TCGType type,
573                                     uint64_t x, uint64_t y)
574 {
575     uint64_t res = do_constant_folding_2(op, x, y);
576     if (type == TCG_TYPE_I32) {
577         res = (int32_t)res;
578     }
579     return res;
580 }
581 
582 static bool do_constant_folding_cond_32(uint32_t x, uint32_t y, TCGCond c)
583 {
584     switch (c) {
585     case TCG_COND_EQ:
586         return x == y;
587     case TCG_COND_NE:
588         return x != y;
589     case TCG_COND_LT:
590         return (int32_t)x < (int32_t)y;
591     case TCG_COND_GE:
592         return (int32_t)x >= (int32_t)y;
593     case TCG_COND_LE:
594         return (int32_t)x <= (int32_t)y;
595     case TCG_COND_GT:
596         return (int32_t)x > (int32_t)y;
597     case TCG_COND_LTU:
598         return x < y;
599     case TCG_COND_GEU:
600         return x >= y;
601     case TCG_COND_LEU:
602         return x <= y;
603     case TCG_COND_GTU:
604         return x > y;
605     case TCG_COND_TSTEQ:
606         return (x & y) == 0;
607     case TCG_COND_TSTNE:
608         return (x & y) != 0;
609     case TCG_COND_ALWAYS:
610     case TCG_COND_NEVER:
611         break;
612     }
613     g_assert_not_reached();
614 }
615 
616 static bool do_constant_folding_cond_64(uint64_t x, uint64_t y, TCGCond c)
617 {
618     switch (c) {
619     case TCG_COND_EQ:
620         return x == y;
621     case TCG_COND_NE:
622         return x != y;
623     case TCG_COND_LT:
624         return (int64_t)x < (int64_t)y;
625     case TCG_COND_GE:
626         return (int64_t)x >= (int64_t)y;
627     case TCG_COND_LE:
628         return (int64_t)x <= (int64_t)y;
629     case TCG_COND_GT:
630         return (int64_t)x > (int64_t)y;
631     case TCG_COND_LTU:
632         return x < y;
633     case TCG_COND_GEU:
634         return x >= y;
635     case TCG_COND_LEU:
636         return x <= y;
637     case TCG_COND_GTU:
638         return x > y;
639     case TCG_COND_TSTEQ:
640         return (x & y) == 0;
641     case TCG_COND_TSTNE:
642         return (x & y) != 0;
643     case TCG_COND_ALWAYS:
644     case TCG_COND_NEVER:
645         break;
646     }
647     g_assert_not_reached();
648 }
649 
650 static int do_constant_folding_cond_eq(TCGCond c)
651 {
652     switch (c) {
653     case TCG_COND_GT:
654     case TCG_COND_LTU:
655     case TCG_COND_LT:
656     case TCG_COND_GTU:
657     case TCG_COND_NE:
658         return 0;
659     case TCG_COND_GE:
660     case TCG_COND_GEU:
661     case TCG_COND_LE:
662     case TCG_COND_LEU:
663     case TCG_COND_EQ:
664         return 1;
665     case TCG_COND_TSTEQ:
666     case TCG_COND_TSTNE:
667         return -1;
668     case TCG_COND_ALWAYS:
669     case TCG_COND_NEVER:
670         break;
671     }
672     g_assert_not_reached();
673 }
674 
675 /*
676  * Return -1 if the condition can't be simplified,
677  * and the result of the condition (0 or 1) if it can.
678  */
679 static int do_constant_folding_cond(TCGType type, TCGArg x,
680                                     TCGArg y, TCGCond c)
681 {
682     if (arg_is_const(x) && arg_is_const(y)) {
683         uint64_t xv = arg_info(x)->val;
684         uint64_t yv = arg_info(y)->val;
685 
686         switch (type) {
687         case TCG_TYPE_I32:
688             return do_constant_folding_cond_32(xv, yv, c);
689         case TCG_TYPE_I64:
690             return do_constant_folding_cond_64(xv, yv, c);
691         default:
692             /* Only scalar comparisons are optimizable */
693             return -1;
694         }
695     } else if (args_are_copies(x, y)) {
696         return do_constant_folding_cond_eq(c);
697     } else if (arg_is_const_val(y, 0)) {
698         switch (c) {
699         case TCG_COND_LTU:
700         case TCG_COND_TSTNE:
701             return 0;
702         case TCG_COND_GEU:
703         case TCG_COND_TSTEQ:
704             return 1;
705         default:
706             return -1;
707         }
708     }
709     return -1;
710 }
711 
712 /**
713  * swap_commutative:
714  * @dest: TCGArg of the destination argument, or NO_DEST.
715  * @p1: first paired argument
716  * @p2: second paired argument
717  *
718  * If *@p1 is a constant and *@p2 is not, swap.
719  * If *@p2 matches @dest, swap.
720  * Return true if a swap was performed.
721  */
722 
723 #define NO_DEST  temp_arg(NULL)
724 
725 static bool swap_commutative(TCGArg dest, TCGArg *p1, TCGArg *p2)
726 {
727     TCGArg a1 = *p1, a2 = *p2;
728     int sum = 0;
729     sum += arg_is_const(a1);
730     sum -= arg_is_const(a2);
731 
732     /* Prefer the constant in second argument, and then the form
733        op a, a, b, which is better handled on non-RISC hosts. */
734     if (sum > 0 || (sum == 0 && dest == a2)) {
735         *p1 = a2;
736         *p2 = a1;
737         return true;
738     }
739     return false;
740 }
741 
742 static bool swap_commutative2(TCGArg *p1, TCGArg *p2)
743 {
744     int sum = 0;
745     sum += arg_is_const(p1[0]);
746     sum += arg_is_const(p1[1]);
747     sum -= arg_is_const(p2[0]);
748     sum -= arg_is_const(p2[1]);
749     if (sum > 0) {
750         TCGArg t;
751         t = p1[0], p1[0] = p2[0], p2[0] = t;
752         t = p1[1], p1[1] = p2[1], p2[1] = t;
753         return true;
754     }
755     return false;
756 }
757 
758 /*
759  * Return -1 if the condition can't be simplified,
760  * and the result of the condition (0 or 1) if it can.
761  */
762 static int do_constant_folding_cond1(OptContext *ctx, TCGOp *op, TCGArg dest,
763                                      TCGArg *p1, TCGArg *p2, TCGArg *pcond)
764 {
765     TCGCond cond;
766     TempOptInfo *i1;
767     bool swap;
768     int r;
769 
770     swap = swap_commutative(dest, p1, p2);
771     cond = *pcond;
772     if (swap) {
773         *pcond = cond = tcg_swap_cond(cond);
774     }
775 
776     r = do_constant_folding_cond(ctx->type, *p1, *p2, cond);
777     if (r >= 0) {
778         return r;
779     }
780     if (!is_tst_cond(cond)) {
781         return -1;
782     }
783 
784     i1 = arg_info(*p1);
785 
786     /*
787      * TSTNE x,x -> NE x,0
788      * TSTNE x,i -> NE x,0 if i includes all nonzero bits of x
789      */
790     if (args_are_copies(*p1, *p2) ||
791         (arg_is_const(*p2) && (i1->z_mask & ~arg_info(*p2)->val) == 0)) {
792         *p2 = arg_new_constant(ctx, 0);
793         *pcond = tcg_tst_eqne_cond(cond);
794         return -1;
795     }
796 
797     /* TSTNE x,i -> LT x,0 if i only includes sign bit copies */
798     if (arg_is_const(*p2) && (arg_info(*p2)->val & ~i1->s_mask) == 0) {
799         *p2 = arg_new_constant(ctx, 0);
800         *pcond = tcg_tst_ltge_cond(cond);
801         return -1;
802     }
803 
804     /* Expand to AND with a temporary if no backend support. */
805     if (!TCG_TARGET_HAS_tst) {
806         TCGOp *op2 = opt_insert_before(ctx, op, INDEX_op_and, 3);
807         TCGArg tmp = arg_new_temp(ctx);
808 
809         op2->args[0] = tmp;
810         op2->args[1] = *p1;
811         op2->args[2] = *p2;
812 
813         *p1 = tmp;
814         *p2 = arg_new_constant(ctx, 0);
815         *pcond = tcg_tst_eqne_cond(cond);
816     }
817     return -1;
818 }
819 
820 static int do_constant_folding_cond2(OptContext *ctx, TCGOp *op, TCGArg *args)
821 {
822     TCGArg al, ah, bl, bh;
823     TCGCond c;
824     bool swap;
825     int r;
826 
827     swap = swap_commutative2(args, args + 2);
828     c = args[4];
829     if (swap) {
830         args[4] = c = tcg_swap_cond(c);
831     }
832 
833     al = args[0];
834     ah = args[1];
835     bl = args[2];
836     bh = args[3];
837 
838     if (arg_is_const(bl) && arg_is_const(bh)) {
839         tcg_target_ulong blv = arg_info(bl)->val;
840         tcg_target_ulong bhv = arg_info(bh)->val;
841         uint64_t b = deposit64(blv, 32, 32, bhv);
842 
843         if (arg_is_const(al) && arg_is_const(ah)) {
844             tcg_target_ulong alv = arg_info(al)->val;
845             tcg_target_ulong ahv = arg_info(ah)->val;
846             uint64_t a = deposit64(alv, 32, 32, ahv);
847 
848             r = do_constant_folding_cond_64(a, b, c);
849             if (r >= 0) {
850                 return r;
851             }
852         }
853 
854         if (b == 0) {
855             switch (c) {
856             case TCG_COND_LTU:
857             case TCG_COND_TSTNE:
858                 return 0;
859             case TCG_COND_GEU:
860             case TCG_COND_TSTEQ:
861                 return 1;
862             default:
863                 break;
864             }
865         }
866 
867         /* TSTNE x,-1 -> NE x,0 */
868         if (b == -1 && is_tst_cond(c)) {
869             args[3] = args[2] = arg_new_constant(ctx, 0);
870             args[4] = tcg_tst_eqne_cond(c);
871             return -1;
872         }
873 
874         /* TSTNE x,sign -> LT x,0 */
875         if (b == INT64_MIN && is_tst_cond(c)) {
876             /* bl must be 0, so copy that to bh */
877             args[3] = bl;
878             args[4] = tcg_tst_ltge_cond(c);
879             return -1;
880         }
881     }
882 
883     if (args_are_copies(al, bl) && args_are_copies(ah, bh)) {
884         r = do_constant_folding_cond_eq(c);
885         if (r >= 0) {
886             return r;
887         }
888 
889         /* TSTNE x,x -> NE x,0 */
890         if (is_tst_cond(c)) {
891             args[3] = args[2] = arg_new_constant(ctx, 0);
892             args[4] = tcg_tst_eqne_cond(c);
893             return -1;
894         }
895     }
896 
897     /* Expand to AND with a temporary if no backend support. */
898     if (!TCG_TARGET_HAS_tst && is_tst_cond(c)) {
899         TCGOp *op1 = opt_insert_before(ctx, op, INDEX_op_and, 3);
900         TCGOp *op2 = opt_insert_before(ctx, op, INDEX_op_and, 3);
901         TCGArg t1 = arg_new_temp(ctx);
902         TCGArg t2 = arg_new_temp(ctx);
903 
904         op1->args[0] = t1;
905         op1->args[1] = al;
906         op1->args[2] = bl;
907         op2->args[0] = t2;
908         op2->args[1] = ah;
909         op2->args[2] = bh;
910 
911         args[0] = t1;
912         args[1] = t2;
913         args[3] = args[2] = arg_new_constant(ctx, 0);
914         args[4] = tcg_tst_eqne_cond(c);
915     }
916     return -1;
917 }
918 
919 static void init_arguments(OptContext *ctx, TCGOp *op, int nb_args)
920 {
921     for (int i = 0; i < nb_args; i++) {
922         TCGTemp *ts = arg_temp(op->args[i]);
923         init_ts_info(ctx, ts);
924     }
925 }
926 
927 static void copy_propagate(OptContext *ctx, TCGOp *op,
928                            int nb_oargs, int nb_iargs)
929 {
930     for (int i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
931         TCGTemp *ts = arg_temp(op->args[i]);
932         if (ts_is_copy(ts)) {
933             op->args[i] = temp_arg(find_better_copy(ts));
934         }
935     }
936 }
937 
938 static void finish_bb(OptContext *ctx)
939 {
940     /* We only optimize memory barriers across basic blocks. */
941     ctx->prev_mb = NULL;
942 }
943 
944 static void finish_ebb(OptContext *ctx)
945 {
946     finish_bb(ctx);
947     /* We only optimize across extended basic blocks. */
948     memset(&ctx->temps_used, 0, sizeof(ctx->temps_used));
949     remove_mem_copy_all(ctx);
950 }
951 
952 static bool finish_folding(OptContext *ctx, TCGOp *op)
953 {
954     const TCGOpDef *def = &tcg_op_defs[op->opc];
955     int i, nb_oargs;
956 
957     nb_oargs = def->nb_oargs;
958     for (i = 0; i < nb_oargs; i++) {
959         TCGTemp *ts = arg_temp(op->args[i]);
960         reset_ts(ctx, ts);
961     }
962     return true;
963 }
964 
965 /*
966  * The fold_* functions return true when processing is complete,
967  * usually by folding the operation to a constant or to a copy,
968  * and calling tcg_opt_gen_{mov,movi}.  They may do other things,
969  * like collect information about the value produced, for use in
970  * optimizing a subsequent operation.
971  *
972  * These first fold_* functions are all helpers, used by other
973  * folders for more specific operations.
974  */
975 
976 static bool fold_const1(OptContext *ctx, TCGOp *op)
977 {
978     if (arg_is_const(op->args[1])) {
979         uint64_t t;
980 
981         t = arg_info(op->args[1])->val;
982         t = do_constant_folding(op->opc, ctx->type, t, 0);
983         return tcg_opt_gen_movi(ctx, op, op->args[0], t);
984     }
985     return false;
986 }
987 
988 static bool fold_const2(OptContext *ctx, TCGOp *op)
989 {
990     if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) {
991         uint64_t t1 = arg_info(op->args[1])->val;
992         uint64_t t2 = arg_info(op->args[2])->val;
993 
994         t1 = do_constant_folding(op->opc, ctx->type, t1, t2);
995         return tcg_opt_gen_movi(ctx, op, op->args[0], t1);
996     }
997     return false;
998 }
999 
1000 static bool fold_commutative(OptContext *ctx, TCGOp *op)
1001 {
1002     swap_commutative(op->args[0], &op->args[1], &op->args[2]);
1003     return false;
1004 }
1005 
1006 static bool fold_const2_commutative(OptContext *ctx, TCGOp *op)
1007 {
1008     swap_commutative(op->args[0], &op->args[1], &op->args[2]);
1009     return fold_const2(ctx, op);
1010 }
1011 
1012 /*
1013  * Record "zero" and "sign" masks for the single output of @op.
1014  * See TempOptInfo definition of z_mask and s_mask.
1015  * If z_mask allows, fold the output to constant zero.
1016  * The passed s_mask may be augmented by z_mask.
1017  */
1018 static bool fold_masks_zs(OptContext *ctx, TCGOp *op,
1019                           uint64_t z_mask, int64_t s_mask)
1020 {
1021     const TCGOpDef *def = &tcg_op_defs[op->opc];
1022     TCGTemp *ts;
1023     TempOptInfo *ti;
1024     int rep;
1025 
1026     /* Only single-output opcodes are supported here. */
1027     tcg_debug_assert(def->nb_oargs == 1);
1028 
1029     /*
1030      * 32-bit ops generate 32-bit results, which for the purpose of
1031      * simplifying tcg are sign-extended.  Certainly that's how we
1032      * represent our constants elsewhere.  Note that the bits will
1033      * be reset properly for a 64-bit value when encountering the
1034      * type changing opcodes.
1035      */
1036     if (ctx->type == TCG_TYPE_I32) {
1037         z_mask = (int32_t)z_mask;
1038         s_mask |= INT32_MIN;
1039     }
1040 
1041     if (z_mask == 0) {
1042         return tcg_opt_gen_movi(ctx, op, op->args[0], 0);
1043     }
1044 
1045     ts = arg_temp(op->args[0]);
1046     reset_ts(ctx, ts);
1047 
1048     ti = ts_info(ts);
1049     ti->z_mask = z_mask;
1050 
1051     /* Canonicalize s_mask and incorporate data from z_mask. */
1052     rep = clz64(~s_mask);
1053     rep = MAX(rep, clz64(z_mask));
1054     rep = MAX(rep - 1, 0);
1055     ti->s_mask = INT64_MIN >> rep;
1056 
1057     return true;
1058 }
1059 
1060 static bool fold_masks_z(OptContext *ctx, TCGOp *op, uint64_t z_mask)
1061 {
1062     return fold_masks_zs(ctx, op, z_mask, 0);
1063 }
1064 
1065 static bool fold_masks_s(OptContext *ctx, TCGOp *op, uint64_t s_mask)
1066 {
1067     return fold_masks_zs(ctx, op, -1, s_mask);
1068 }
1069 
1070 /*
1071  * An "affected" mask bit is 0 if and only if the result is identical
1072  * to the first input.  Thus if the entire mask is 0, the operation
1073  * is equivalent to a copy.
1074  */
1075 static bool fold_affected_mask(OptContext *ctx, TCGOp *op, uint64_t a_mask)
1076 {
1077     if (ctx->type == TCG_TYPE_I32) {
1078         a_mask = (uint32_t)a_mask;
1079     }
1080     if (a_mask == 0) {
1081         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1082     }
1083     return false;
1084 }
1085 
1086 /*
1087  * Convert @op to NOT, if NOT is supported by the host.
1088  * Return true f the conversion is successful, which will still
1089  * indicate that the processing is complete.
1090  */
1091 static bool fold_not(OptContext *ctx, TCGOp *op);
1092 static bool fold_to_not(OptContext *ctx, TCGOp *op, int idx)
1093 {
1094     TCGOpcode not_op;
1095     bool have_not;
1096 
1097     switch (ctx->type) {
1098     case TCG_TYPE_I32:
1099         not_op = INDEX_op_not_i32;
1100         have_not = TCG_TARGET_HAS_not_i32;
1101         break;
1102     case TCG_TYPE_I64:
1103         not_op = INDEX_op_not_i64;
1104         have_not = TCG_TARGET_HAS_not_i64;
1105         break;
1106     case TCG_TYPE_V64:
1107     case TCG_TYPE_V128:
1108     case TCG_TYPE_V256:
1109         not_op = INDEX_op_not_vec;
1110         have_not = TCG_TARGET_HAS_not_vec;
1111         break;
1112     default:
1113         g_assert_not_reached();
1114     }
1115     if (have_not) {
1116         op->opc = not_op;
1117         op->args[1] = op->args[idx];
1118         return fold_not(ctx, op);
1119     }
1120     return false;
1121 }
1122 
1123 /* If the binary operation has first argument @i, fold to @i. */
1124 static bool fold_ix_to_i(OptContext *ctx, TCGOp *op, uint64_t i)
1125 {
1126     if (arg_is_const_val(op->args[1], i)) {
1127         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
1128     }
1129     return false;
1130 }
1131 
1132 /* If the binary operation has first argument @i, fold to NOT. */
1133 static bool fold_ix_to_not(OptContext *ctx, TCGOp *op, uint64_t i)
1134 {
1135     if (arg_is_const_val(op->args[1], i)) {
1136         return fold_to_not(ctx, op, 2);
1137     }
1138     return false;
1139 }
1140 
1141 /* If the binary operation has second argument @i, fold to @i. */
1142 static bool fold_xi_to_i(OptContext *ctx, TCGOp *op, uint64_t i)
1143 {
1144     if (arg_is_const_val(op->args[2], i)) {
1145         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
1146     }
1147     return false;
1148 }
1149 
1150 /* If the binary operation has second argument @i, fold to identity. */
1151 static bool fold_xi_to_x(OptContext *ctx, TCGOp *op, uint64_t i)
1152 {
1153     if (arg_is_const_val(op->args[2], i)) {
1154         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1155     }
1156     return false;
1157 }
1158 
1159 /* If the binary operation has second argument @i, fold to NOT. */
1160 static bool fold_xi_to_not(OptContext *ctx, TCGOp *op, uint64_t i)
1161 {
1162     if (arg_is_const_val(op->args[2], i)) {
1163         return fold_to_not(ctx, op, 1);
1164     }
1165     return false;
1166 }
1167 
1168 /* If the binary operation has both arguments equal, fold to @i. */
1169 static bool fold_xx_to_i(OptContext *ctx, TCGOp *op, uint64_t i)
1170 {
1171     if (args_are_copies(op->args[1], op->args[2])) {
1172         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
1173     }
1174     return false;
1175 }
1176 
1177 /* If the binary operation has both arguments equal, fold to identity. */
1178 static bool fold_xx_to_x(OptContext *ctx, TCGOp *op)
1179 {
1180     if (args_are_copies(op->args[1], op->args[2])) {
1181         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1182     }
1183     return false;
1184 }
1185 
1186 /*
1187  * These outermost fold_<op> functions are sorted alphabetically.
1188  *
1189  * The ordering of the transformations should be:
1190  *   1) those that produce a constant
1191  *   2) those that produce a copy
1192  *   3) those that produce information about the result value.
1193  */
1194 
1195 static bool fold_or(OptContext *ctx, TCGOp *op);
1196 static bool fold_orc(OptContext *ctx, TCGOp *op);
1197 static bool fold_xor(OptContext *ctx, TCGOp *op);
1198 
1199 static bool fold_add(OptContext *ctx, TCGOp *op)
1200 {
1201     if (fold_const2_commutative(ctx, op) ||
1202         fold_xi_to_x(ctx, op, 0)) {
1203         return true;
1204     }
1205     return finish_folding(ctx, op);
1206 }
1207 
1208 /* We cannot as yet do_constant_folding with vectors. */
1209 static bool fold_add_vec(OptContext *ctx, TCGOp *op)
1210 {
1211     if (fold_commutative(ctx, op) ||
1212         fold_xi_to_x(ctx, op, 0)) {
1213         return true;
1214     }
1215     return finish_folding(ctx, op);
1216 }
1217 
1218 static bool fold_addsub2(OptContext *ctx, TCGOp *op, bool add)
1219 {
1220     bool a_const = arg_is_const(op->args[2]) && arg_is_const(op->args[3]);
1221     bool b_const = arg_is_const(op->args[4]) && arg_is_const(op->args[5]);
1222 
1223     if (a_const && b_const) {
1224         uint64_t al = arg_info(op->args[2])->val;
1225         uint64_t ah = arg_info(op->args[3])->val;
1226         uint64_t bl = arg_info(op->args[4])->val;
1227         uint64_t bh = arg_info(op->args[5])->val;
1228         TCGArg rl, rh;
1229         TCGOp *op2;
1230 
1231         if (ctx->type == TCG_TYPE_I32) {
1232             uint64_t a = deposit64(al, 32, 32, ah);
1233             uint64_t b = deposit64(bl, 32, 32, bh);
1234 
1235             if (add) {
1236                 a += b;
1237             } else {
1238                 a -= b;
1239             }
1240 
1241             al = sextract64(a, 0, 32);
1242             ah = sextract64(a, 32, 32);
1243         } else {
1244             Int128 a = int128_make128(al, ah);
1245             Int128 b = int128_make128(bl, bh);
1246 
1247             if (add) {
1248                 a = int128_add(a, b);
1249             } else {
1250                 a = int128_sub(a, b);
1251             }
1252 
1253             al = int128_getlo(a);
1254             ah = int128_gethi(a);
1255         }
1256 
1257         rl = op->args[0];
1258         rh = op->args[1];
1259 
1260         /* The proper opcode is supplied by tcg_opt_gen_mov. */
1261         op2 = opt_insert_before(ctx, op, 0, 2);
1262 
1263         tcg_opt_gen_movi(ctx, op, rl, al);
1264         tcg_opt_gen_movi(ctx, op2, rh, ah);
1265         return true;
1266     }
1267 
1268     /* Fold sub2 r,x,i to add2 r,x,-i */
1269     if (!add && b_const) {
1270         uint64_t bl = arg_info(op->args[4])->val;
1271         uint64_t bh = arg_info(op->args[5])->val;
1272 
1273         /* Negate the two parts without assembling and disassembling. */
1274         bl = -bl;
1275         bh = ~bh + !bl;
1276 
1277         op->opc = (ctx->type == TCG_TYPE_I32
1278                    ? INDEX_op_add2_i32 : INDEX_op_add2_i64);
1279         op->args[4] = arg_new_constant(ctx, bl);
1280         op->args[5] = arg_new_constant(ctx, bh);
1281     }
1282     return finish_folding(ctx, op);
1283 }
1284 
1285 static bool fold_add2(OptContext *ctx, TCGOp *op)
1286 {
1287     /* Note that the high and low parts may be independently swapped. */
1288     swap_commutative(op->args[0], &op->args[2], &op->args[4]);
1289     swap_commutative(op->args[1], &op->args[3], &op->args[5]);
1290 
1291     return fold_addsub2(ctx, op, true);
1292 }
1293 
1294 static bool fold_and(OptContext *ctx, TCGOp *op)
1295 {
1296     uint64_t z1, z2, z_mask, s_mask;
1297     TempOptInfo *t1, *t2;
1298 
1299     if (fold_const2_commutative(ctx, op) ||
1300         fold_xi_to_i(ctx, op, 0) ||
1301         fold_xi_to_x(ctx, op, -1) ||
1302         fold_xx_to_x(ctx, op)) {
1303         return true;
1304     }
1305 
1306     t1 = arg_info(op->args[1]);
1307     t2 = arg_info(op->args[2]);
1308     z1 = t1->z_mask;
1309     z2 = t2->z_mask;
1310 
1311     /*
1312      * Known-zeros does not imply known-ones.  Therefore unless
1313      * arg2 is constant, we can't infer affected bits from it.
1314      */
1315     if (ti_is_const(t2) && fold_affected_mask(ctx, op, z1 & ~z2)) {
1316         return true;
1317     }
1318 
1319     z_mask = z1 & z2;
1320 
1321     /*
1322      * Sign repetitions are perforce all identical, whether they are 1 or 0.
1323      * Bitwise operations preserve the relative quantity of the repetitions.
1324      */
1325     s_mask = t1->s_mask & t2->s_mask;
1326 
1327     return fold_masks_zs(ctx, op, z_mask, s_mask);
1328 }
1329 
1330 static bool fold_andc(OptContext *ctx, TCGOp *op)
1331 {
1332     uint64_t z_mask, s_mask;
1333     TempOptInfo *t1, *t2;
1334 
1335     if (fold_const2(ctx, op) ||
1336         fold_xx_to_i(ctx, op, 0) ||
1337         fold_xi_to_x(ctx, op, 0) ||
1338         fold_ix_to_not(ctx, op, -1)) {
1339         return true;
1340     }
1341 
1342     t1 = arg_info(op->args[1]);
1343     t2 = arg_info(op->args[2]);
1344     z_mask = t1->z_mask;
1345 
1346     /*
1347      * Known-zeros does not imply known-ones.  Therefore unless
1348      * arg2 is constant, we can't infer anything from it.
1349      */
1350     if (ti_is_const(t2)) {
1351         uint64_t v2 = ti_const_val(t2);
1352         if (fold_affected_mask(ctx, op, z_mask & v2)) {
1353             return true;
1354         }
1355         z_mask &= ~v2;
1356     }
1357 
1358     s_mask = t1->s_mask & t2->s_mask;
1359     return fold_masks_zs(ctx, op, z_mask, s_mask);
1360 }
1361 
1362 static bool fold_bitsel_vec(OptContext *ctx, TCGOp *op)
1363 {
1364     /* If true and false values are the same, eliminate the cmp. */
1365     if (args_are_copies(op->args[2], op->args[3])) {
1366         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[2]);
1367     }
1368 
1369     if (arg_is_const(op->args[2]) && arg_is_const(op->args[3])) {
1370         uint64_t tv = arg_info(op->args[2])->val;
1371         uint64_t fv = arg_info(op->args[3])->val;
1372 
1373         if (tv == -1 && fv == 0) {
1374             return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1375         }
1376         if (tv == 0 && fv == -1) {
1377             if (TCG_TARGET_HAS_not_vec) {
1378                 op->opc = INDEX_op_not_vec;
1379                 return fold_not(ctx, op);
1380             } else {
1381                 op->opc = INDEX_op_xor_vec;
1382                 op->args[2] = arg_new_constant(ctx, -1);
1383                 return fold_xor(ctx, op);
1384             }
1385         }
1386     }
1387     if (arg_is_const(op->args[2])) {
1388         uint64_t tv = arg_info(op->args[2])->val;
1389         if (tv == -1) {
1390             op->opc = INDEX_op_or_vec;
1391             op->args[2] = op->args[3];
1392             return fold_or(ctx, op);
1393         }
1394         if (tv == 0 && TCG_TARGET_HAS_andc_vec) {
1395             op->opc = INDEX_op_andc_vec;
1396             op->args[2] = op->args[1];
1397             op->args[1] = op->args[3];
1398             return fold_andc(ctx, op);
1399         }
1400     }
1401     if (arg_is_const(op->args[3])) {
1402         uint64_t fv = arg_info(op->args[3])->val;
1403         if (fv == 0) {
1404             op->opc = INDEX_op_and_vec;
1405             return fold_and(ctx, op);
1406         }
1407         if (fv == -1 && TCG_TARGET_HAS_orc_vec) {
1408             op->opc = INDEX_op_orc_vec;
1409             op->args[2] = op->args[1];
1410             op->args[1] = op->args[3];
1411             return fold_orc(ctx, op);
1412         }
1413     }
1414     return finish_folding(ctx, op);
1415 }
1416 
1417 static bool fold_brcond(OptContext *ctx, TCGOp *op)
1418 {
1419     int i = do_constant_folding_cond1(ctx, op, NO_DEST, &op->args[0],
1420                                       &op->args[1], &op->args[2]);
1421     if (i == 0) {
1422         tcg_op_remove(ctx->tcg, op);
1423         return true;
1424     }
1425     if (i > 0) {
1426         op->opc = INDEX_op_br;
1427         op->args[0] = op->args[3];
1428         finish_ebb(ctx);
1429     } else {
1430         finish_bb(ctx);
1431     }
1432     return true;
1433 }
1434 
1435 static bool fold_brcond2(OptContext *ctx, TCGOp *op)
1436 {
1437     TCGCond cond;
1438     TCGArg label;
1439     int i, inv = 0;
1440 
1441     i = do_constant_folding_cond2(ctx, op, &op->args[0]);
1442     cond = op->args[4];
1443     label = op->args[5];
1444     if (i >= 0) {
1445         goto do_brcond_const;
1446     }
1447 
1448     switch (cond) {
1449     case TCG_COND_LT:
1450     case TCG_COND_GE:
1451         /*
1452          * Simplify LT/GE comparisons vs zero to a single compare
1453          * vs the high word of the input.
1454          */
1455         if (arg_is_const_val(op->args[2], 0) &&
1456             arg_is_const_val(op->args[3], 0)) {
1457             goto do_brcond_high;
1458         }
1459         break;
1460 
1461     case TCG_COND_NE:
1462         inv = 1;
1463         QEMU_FALLTHROUGH;
1464     case TCG_COND_EQ:
1465         /*
1466          * Simplify EQ/NE comparisons where one of the pairs
1467          * can be simplified.
1468          */
1469         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[0],
1470                                      op->args[2], cond);
1471         switch (i ^ inv) {
1472         case 0:
1473             goto do_brcond_const;
1474         case 1:
1475             goto do_brcond_high;
1476         }
1477 
1478         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[1],
1479                                      op->args[3], cond);
1480         switch (i ^ inv) {
1481         case 0:
1482             goto do_brcond_const;
1483         case 1:
1484             goto do_brcond_low;
1485         }
1486         break;
1487 
1488     case TCG_COND_TSTEQ:
1489     case TCG_COND_TSTNE:
1490         if (arg_is_const_val(op->args[2], 0)) {
1491             goto do_brcond_high;
1492         }
1493         if (arg_is_const_val(op->args[3], 0)) {
1494             goto do_brcond_low;
1495         }
1496         break;
1497 
1498     default:
1499         break;
1500 
1501     do_brcond_low:
1502         op->opc = INDEX_op_brcond_i32;
1503         op->args[1] = op->args[2];
1504         op->args[2] = cond;
1505         op->args[3] = label;
1506         return fold_brcond(ctx, op);
1507 
1508     do_brcond_high:
1509         op->opc = INDEX_op_brcond_i32;
1510         op->args[0] = op->args[1];
1511         op->args[1] = op->args[3];
1512         op->args[2] = cond;
1513         op->args[3] = label;
1514         return fold_brcond(ctx, op);
1515 
1516     do_brcond_const:
1517         if (i == 0) {
1518             tcg_op_remove(ctx->tcg, op);
1519             return true;
1520         }
1521         op->opc = INDEX_op_br;
1522         op->args[0] = label;
1523         finish_ebb(ctx);
1524         return true;
1525     }
1526 
1527     finish_bb(ctx);
1528     return true;
1529 }
1530 
1531 static bool fold_bswap(OptContext *ctx, TCGOp *op)
1532 {
1533     uint64_t z_mask, s_mask, sign;
1534     TempOptInfo *t1 = arg_info(op->args[1]);
1535 
1536     if (ti_is_const(t1)) {
1537         return tcg_opt_gen_movi(ctx, op, op->args[0],
1538                                 do_constant_folding(op->opc, ctx->type,
1539                                                     ti_const_val(t1),
1540                                                     op->args[2]));
1541     }
1542 
1543     z_mask = t1->z_mask;
1544     switch (op->opc) {
1545     case INDEX_op_bswap16_i32:
1546     case INDEX_op_bswap16_i64:
1547         z_mask = bswap16(z_mask);
1548         sign = INT16_MIN;
1549         break;
1550     case INDEX_op_bswap32_i32:
1551     case INDEX_op_bswap32_i64:
1552         z_mask = bswap32(z_mask);
1553         sign = INT32_MIN;
1554         break;
1555     case INDEX_op_bswap64_i64:
1556         z_mask = bswap64(z_mask);
1557         sign = INT64_MIN;
1558         break;
1559     default:
1560         g_assert_not_reached();
1561     }
1562 
1563     s_mask = 0;
1564     switch (op->args[2] & (TCG_BSWAP_OZ | TCG_BSWAP_OS)) {
1565     case TCG_BSWAP_OZ:
1566         break;
1567     case TCG_BSWAP_OS:
1568         /* If the sign bit may be 1, force all the bits above to 1. */
1569         if (z_mask & sign) {
1570             z_mask |= sign;
1571         }
1572         /* The value and therefore s_mask is explicitly sign-extended. */
1573         s_mask = sign;
1574         break;
1575     default:
1576         /* The high bits are undefined: force all bits above the sign to 1. */
1577         z_mask |= sign << 1;
1578         break;
1579     }
1580 
1581     return fold_masks_zs(ctx, op, z_mask, s_mask);
1582 }
1583 
1584 static bool fold_call(OptContext *ctx, TCGOp *op)
1585 {
1586     TCGContext *s = ctx->tcg;
1587     int nb_oargs = TCGOP_CALLO(op);
1588     int nb_iargs = TCGOP_CALLI(op);
1589     int flags, i;
1590 
1591     init_arguments(ctx, op, nb_oargs + nb_iargs);
1592     copy_propagate(ctx, op, nb_oargs, nb_iargs);
1593 
1594     /* If the function reads or writes globals, reset temp data. */
1595     flags = tcg_call_flags(op);
1596     if (!(flags & (TCG_CALL_NO_READ_GLOBALS | TCG_CALL_NO_WRITE_GLOBALS))) {
1597         int nb_globals = s->nb_globals;
1598 
1599         for (i = 0; i < nb_globals; i++) {
1600             if (test_bit(i, ctx->temps_used.l)) {
1601                 reset_ts(ctx, &ctx->tcg->temps[i]);
1602             }
1603         }
1604     }
1605 
1606     /* If the function has side effects, reset mem data. */
1607     if (!(flags & TCG_CALL_NO_SIDE_EFFECTS)) {
1608         remove_mem_copy_all(ctx);
1609     }
1610 
1611     /* Reset temp data for outputs. */
1612     for (i = 0; i < nb_oargs; i++) {
1613         reset_temp(ctx, op->args[i]);
1614     }
1615 
1616     /* Stop optimizing MB across calls. */
1617     ctx->prev_mb = NULL;
1618     return true;
1619 }
1620 
1621 static bool fold_cmp_vec(OptContext *ctx, TCGOp *op)
1622 {
1623     /* Canonicalize the comparison to put immediate second. */
1624     if (swap_commutative(NO_DEST, &op->args[1], &op->args[2])) {
1625         op->args[3] = tcg_swap_cond(op->args[3]);
1626     }
1627     return finish_folding(ctx, op);
1628 }
1629 
1630 static bool fold_cmpsel_vec(OptContext *ctx, TCGOp *op)
1631 {
1632     /* If true and false values are the same, eliminate the cmp. */
1633     if (args_are_copies(op->args[3], op->args[4])) {
1634         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[3]);
1635     }
1636 
1637     /* Canonicalize the comparison to put immediate second. */
1638     if (swap_commutative(NO_DEST, &op->args[1], &op->args[2])) {
1639         op->args[5] = tcg_swap_cond(op->args[5]);
1640     }
1641     /*
1642      * Canonicalize the "false" input reg to match the destination,
1643      * so that the tcg backend can implement "move if true".
1644      */
1645     if (swap_commutative(op->args[0], &op->args[4], &op->args[3])) {
1646         op->args[5] = tcg_invert_cond(op->args[5]);
1647     }
1648     return finish_folding(ctx, op);
1649 }
1650 
1651 static bool fold_count_zeros(OptContext *ctx, TCGOp *op)
1652 {
1653     uint64_t z_mask, s_mask;
1654     TempOptInfo *t1 = arg_info(op->args[1]);
1655     TempOptInfo *t2 = arg_info(op->args[2]);
1656 
1657     if (ti_is_const(t1)) {
1658         uint64_t t = ti_const_val(t1);
1659 
1660         if (t != 0) {
1661             t = do_constant_folding(op->opc, ctx->type, t, 0);
1662             return tcg_opt_gen_movi(ctx, op, op->args[0], t);
1663         }
1664         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[2]);
1665     }
1666 
1667     switch (ctx->type) {
1668     case TCG_TYPE_I32:
1669         z_mask = 31;
1670         break;
1671     case TCG_TYPE_I64:
1672         z_mask = 63;
1673         break;
1674     default:
1675         g_assert_not_reached();
1676     }
1677     s_mask = ~z_mask;
1678     z_mask |= t2->z_mask;
1679     s_mask &= t2->s_mask;
1680 
1681     return fold_masks_zs(ctx, op, z_mask, s_mask);
1682 }
1683 
1684 static bool fold_ctpop(OptContext *ctx, TCGOp *op)
1685 {
1686     uint64_t z_mask;
1687 
1688     if (fold_const1(ctx, op)) {
1689         return true;
1690     }
1691 
1692     switch (ctx->type) {
1693     case TCG_TYPE_I32:
1694         z_mask = 32 | 31;
1695         break;
1696     case TCG_TYPE_I64:
1697         z_mask = 64 | 63;
1698         break;
1699     default:
1700         g_assert_not_reached();
1701     }
1702     return fold_masks_z(ctx, op, z_mask);
1703 }
1704 
1705 static bool fold_deposit(OptContext *ctx, TCGOp *op)
1706 {
1707     TempOptInfo *t1 = arg_info(op->args[1]);
1708     TempOptInfo *t2 = arg_info(op->args[2]);
1709     int ofs = op->args[3];
1710     int len = op->args[4];
1711     int width = 8 * tcg_type_size(ctx->type);
1712     uint64_t z_mask, s_mask;
1713 
1714     if (ti_is_const(t1) && ti_is_const(t2)) {
1715         return tcg_opt_gen_movi(ctx, op, op->args[0],
1716                                 deposit64(ti_const_val(t1), ofs, len,
1717                                           ti_const_val(t2)));
1718     }
1719 
1720     /* Inserting a value into zero at offset 0. */
1721     if (ti_is_const_val(t1, 0) && ofs == 0) {
1722         uint64_t mask = MAKE_64BIT_MASK(0, len);
1723 
1724         op->opc = INDEX_op_and;
1725         op->args[1] = op->args[2];
1726         op->args[2] = arg_new_constant(ctx, mask);
1727         return fold_and(ctx, op);
1728     }
1729 
1730     /* Inserting zero into a value. */
1731     if (ti_is_const_val(t2, 0)) {
1732         uint64_t mask = deposit64(-1, ofs, len, 0);
1733 
1734         op->opc = INDEX_op_and;
1735         op->args[2] = arg_new_constant(ctx, mask);
1736         return fold_and(ctx, op);
1737     }
1738 
1739     /* The s_mask from the top portion of the deposit is still valid. */
1740     if (ofs + len == width) {
1741         s_mask = t2->s_mask << ofs;
1742     } else {
1743         s_mask = t1->s_mask & ~MAKE_64BIT_MASK(0, ofs + len);
1744     }
1745 
1746     z_mask = deposit64(t1->z_mask, ofs, len, t2->z_mask);
1747     return fold_masks_zs(ctx, op, z_mask, s_mask);
1748 }
1749 
1750 static bool fold_divide(OptContext *ctx, TCGOp *op)
1751 {
1752     if (fold_const2(ctx, op) ||
1753         fold_xi_to_x(ctx, op, 1)) {
1754         return true;
1755     }
1756     return finish_folding(ctx, op);
1757 }
1758 
1759 static bool fold_dup(OptContext *ctx, TCGOp *op)
1760 {
1761     if (arg_is_const(op->args[1])) {
1762         uint64_t t = arg_info(op->args[1])->val;
1763         t = dup_const(TCGOP_VECE(op), t);
1764         return tcg_opt_gen_movi(ctx, op, op->args[0], t);
1765     }
1766     return finish_folding(ctx, op);
1767 }
1768 
1769 static bool fold_dup2(OptContext *ctx, TCGOp *op)
1770 {
1771     if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) {
1772         uint64_t t = deposit64(arg_info(op->args[1])->val, 32, 32,
1773                                arg_info(op->args[2])->val);
1774         return tcg_opt_gen_movi(ctx, op, op->args[0], t);
1775     }
1776 
1777     if (args_are_copies(op->args[1], op->args[2])) {
1778         op->opc = INDEX_op_dup_vec;
1779         TCGOP_VECE(op) = MO_32;
1780     }
1781     return finish_folding(ctx, op);
1782 }
1783 
1784 static bool fold_eqv(OptContext *ctx, TCGOp *op)
1785 {
1786     uint64_t s_mask;
1787 
1788     if (fold_const2_commutative(ctx, op) ||
1789         fold_xi_to_x(ctx, op, -1) ||
1790         fold_xi_to_not(ctx, op, 0)) {
1791         return true;
1792     }
1793 
1794     s_mask = arg_info(op->args[1])->s_mask
1795            & arg_info(op->args[2])->s_mask;
1796     return fold_masks_s(ctx, op, s_mask);
1797 }
1798 
1799 static bool fold_extract(OptContext *ctx, TCGOp *op)
1800 {
1801     uint64_t z_mask_old, z_mask;
1802     TempOptInfo *t1 = arg_info(op->args[1]);
1803     int pos = op->args[2];
1804     int len = op->args[3];
1805 
1806     if (ti_is_const(t1)) {
1807         return tcg_opt_gen_movi(ctx, op, op->args[0],
1808                                 extract64(ti_const_val(t1), pos, len));
1809     }
1810 
1811     z_mask_old = t1->z_mask;
1812     z_mask = extract64(z_mask_old, pos, len);
1813     if (pos == 0 && fold_affected_mask(ctx, op, z_mask_old ^ z_mask)) {
1814         return true;
1815     }
1816 
1817     return fold_masks_z(ctx, op, z_mask);
1818 }
1819 
1820 static bool fold_extract2(OptContext *ctx, TCGOp *op)
1821 {
1822     if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) {
1823         uint64_t v1 = arg_info(op->args[1])->val;
1824         uint64_t v2 = arg_info(op->args[2])->val;
1825         int shr = op->args[3];
1826 
1827         if (op->opc == INDEX_op_extract2_i64) {
1828             v1 >>= shr;
1829             v2 <<= 64 - shr;
1830         } else {
1831             v1 = (uint32_t)v1 >> shr;
1832             v2 = (uint64_t)((int32_t)v2 << (32 - shr));
1833         }
1834         return tcg_opt_gen_movi(ctx, op, op->args[0], v1 | v2);
1835     }
1836     return finish_folding(ctx, op);
1837 }
1838 
1839 static bool fold_exts(OptContext *ctx, TCGOp *op)
1840 {
1841     uint64_t s_mask, z_mask;
1842     TempOptInfo *t1;
1843 
1844     if (fold_const1(ctx, op)) {
1845         return true;
1846     }
1847 
1848     t1 = arg_info(op->args[1]);
1849     z_mask = t1->z_mask;
1850     s_mask = t1->s_mask;
1851 
1852     switch (op->opc) {
1853     case INDEX_op_ext_i32_i64:
1854         s_mask |= INT32_MIN;
1855         z_mask = (int32_t)z_mask;
1856         break;
1857     default:
1858         g_assert_not_reached();
1859     }
1860     return fold_masks_zs(ctx, op, z_mask, s_mask);
1861 }
1862 
1863 static bool fold_extu(OptContext *ctx, TCGOp *op)
1864 {
1865     uint64_t z_mask;
1866 
1867     if (fold_const1(ctx, op)) {
1868         return true;
1869     }
1870 
1871     z_mask = arg_info(op->args[1])->z_mask;
1872     switch (op->opc) {
1873     case INDEX_op_extrl_i64_i32:
1874     case INDEX_op_extu_i32_i64:
1875         z_mask = (uint32_t)z_mask;
1876         break;
1877     case INDEX_op_extrh_i64_i32:
1878         z_mask >>= 32;
1879         break;
1880     default:
1881         g_assert_not_reached();
1882     }
1883     return fold_masks_z(ctx, op, z_mask);
1884 }
1885 
1886 static bool fold_mb(OptContext *ctx, TCGOp *op)
1887 {
1888     /* Eliminate duplicate and redundant fence instructions.  */
1889     if (ctx->prev_mb) {
1890         /*
1891          * Merge two barriers of the same type into one,
1892          * or a weaker barrier into a stronger one,
1893          * or two weaker barriers into a stronger one.
1894          *   mb X; mb Y => mb X|Y
1895          *   mb; strl => mb; st
1896          *   ldaq; mb => ld; mb
1897          *   ldaq; strl => ld; mb; st
1898          * Other combinations are also merged into a strong
1899          * barrier.  This is stricter than specified but for
1900          * the purposes of TCG is better than not optimizing.
1901          */
1902         ctx->prev_mb->args[0] |= op->args[0];
1903         tcg_op_remove(ctx->tcg, op);
1904     } else {
1905         ctx->prev_mb = op;
1906     }
1907     return true;
1908 }
1909 
1910 static bool fold_mov(OptContext *ctx, TCGOp *op)
1911 {
1912     return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
1913 }
1914 
1915 static bool fold_movcond(OptContext *ctx, TCGOp *op)
1916 {
1917     uint64_t z_mask, s_mask;
1918     TempOptInfo *tt, *ft;
1919     int i;
1920 
1921     /* If true and false values are the same, eliminate the cmp. */
1922     if (args_are_copies(op->args[3], op->args[4])) {
1923         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[3]);
1924     }
1925 
1926     /*
1927      * Canonicalize the "false" input reg to match the destination reg so
1928      * that the tcg backend can implement a "move if true" operation.
1929      */
1930     if (swap_commutative(op->args[0], &op->args[4], &op->args[3])) {
1931         op->args[5] = tcg_invert_cond(op->args[5]);
1932     }
1933 
1934     i = do_constant_folding_cond1(ctx, op, NO_DEST, &op->args[1],
1935                                   &op->args[2], &op->args[5]);
1936     if (i >= 0) {
1937         return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[4 - i]);
1938     }
1939 
1940     tt = arg_info(op->args[3]);
1941     ft = arg_info(op->args[4]);
1942     z_mask = tt->z_mask | ft->z_mask;
1943     s_mask = tt->s_mask & ft->s_mask;
1944 
1945     if (ti_is_const(tt) && ti_is_const(ft)) {
1946         uint64_t tv = ti_const_val(tt);
1947         uint64_t fv = ti_const_val(ft);
1948         TCGOpcode opc, negopc = 0;
1949         TCGCond cond = op->args[5];
1950 
1951         switch (ctx->type) {
1952         case TCG_TYPE_I32:
1953             opc = INDEX_op_setcond_i32;
1954             if (TCG_TARGET_HAS_negsetcond_i32) {
1955                 negopc = INDEX_op_negsetcond_i32;
1956             }
1957             tv = (int32_t)tv;
1958             fv = (int32_t)fv;
1959             break;
1960         case TCG_TYPE_I64:
1961             opc = INDEX_op_setcond_i64;
1962             if (TCG_TARGET_HAS_negsetcond_i64) {
1963                 negopc = INDEX_op_negsetcond_i64;
1964             }
1965             break;
1966         default:
1967             g_assert_not_reached();
1968         }
1969 
1970         if (tv == 1 && fv == 0) {
1971             op->opc = opc;
1972             op->args[3] = cond;
1973         } else if (fv == 1 && tv == 0) {
1974             op->opc = opc;
1975             op->args[3] = tcg_invert_cond(cond);
1976         } else if (negopc) {
1977             if (tv == -1 && fv == 0) {
1978                 op->opc = negopc;
1979                 op->args[3] = cond;
1980             } else if (fv == -1 && tv == 0) {
1981                 op->opc = negopc;
1982                 op->args[3] = tcg_invert_cond(cond);
1983             }
1984         }
1985     }
1986 
1987     return fold_masks_zs(ctx, op, z_mask, s_mask);
1988 }
1989 
1990 static bool fold_mul(OptContext *ctx, TCGOp *op)
1991 {
1992     if (fold_const2(ctx, op) ||
1993         fold_xi_to_i(ctx, op, 0) ||
1994         fold_xi_to_x(ctx, op, 1)) {
1995         return true;
1996     }
1997     return finish_folding(ctx, op);
1998 }
1999 
2000 static bool fold_mul_highpart(OptContext *ctx, TCGOp *op)
2001 {
2002     if (fold_const2_commutative(ctx, op) ||
2003         fold_xi_to_i(ctx, op, 0)) {
2004         return true;
2005     }
2006     return finish_folding(ctx, op);
2007 }
2008 
2009 static bool fold_multiply2(OptContext *ctx, TCGOp *op)
2010 {
2011     swap_commutative(op->args[0], &op->args[2], &op->args[3]);
2012 
2013     if (arg_is_const(op->args[2]) && arg_is_const(op->args[3])) {
2014         uint64_t a = arg_info(op->args[2])->val;
2015         uint64_t b = arg_info(op->args[3])->val;
2016         uint64_t h, l;
2017         TCGArg rl, rh;
2018         TCGOp *op2;
2019 
2020         switch (op->opc) {
2021         case INDEX_op_mulu2_i32:
2022             l = (uint64_t)(uint32_t)a * (uint32_t)b;
2023             h = (int32_t)(l >> 32);
2024             l = (int32_t)l;
2025             break;
2026         case INDEX_op_muls2_i32:
2027             l = (int64_t)(int32_t)a * (int32_t)b;
2028             h = l >> 32;
2029             l = (int32_t)l;
2030             break;
2031         case INDEX_op_mulu2_i64:
2032             mulu64(&l, &h, a, b);
2033             break;
2034         case INDEX_op_muls2_i64:
2035             muls64(&l, &h, a, b);
2036             break;
2037         default:
2038             g_assert_not_reached();
2039         }
2040 
2041         rl = op->args[0];
2042         rh = op->args[1];
2043 
2044         /* The proper opcode is supplied by tcg_opt_gen_mov. */
2045         op2 = opt_insert_before(ctx, op, 0, 2);
2046 
2047         tcg_opt_gen_movi(ctx, op, rl, l);
2048         tcg_opt_gen_movi(ctx, op2, rh, h);
2049         return true;
2050     }
2051     return finish_folding(ctx, op);
2052 }
2053 
2054 static bool fold_nand(OptContext *ctx, TCGOp *op)
2055 {
2056     uint64_t s_mask;
2057 
2058     if (fold_const2_commutative(ctx, op) ||
2059         fold_xi_to_not(ctx, op, -1)) {
2060         return true;
2061     }
2062 
2063     s_mask = arg_info(op->args[1])->s_mask
2064            & arg_info(op->args[2])->s_mask;
2065     return fold_masks_s(ctx, op, s_mask);
2066 }
2067 
2068 static bool fold_neg_no_const(OptContext *ctx, TCGOp *op)
2069 {
2070     /* Set to 1 all bits to the left of the rightmost.  */
2071     uint64_t z_mask = arg_info(op->args[1])->z_mask;
2072     z_mask = -(z_mask & -z_mask);
2073 
2074     return fold_masks_z(ctx, op, z_mask);
2075 }
2076 
2077 static bool fold_neg(OptContext *ctx, TCGOp *op)
2078 {
2079     return fold_const1(ctx, op) || fold_neg_no_const(ctx, op);
2080 }
2081 
2082 static bool fold_nor(OptContext *ctx, TCGOp *op)
2083 {
2084     uint64_t s_mask;
2085 
2086     if (fold_const2_commutative(ctx, op) ||
2087         fold_xi_to_not(ctx, op, 0)) {
2088         return true;
2089     }
2090 
2091     s_mask = arg_info(op->args[1])->s_mask
2092            & arg_info(op->args[2])->s_mask;
2093     return fold_masks_s(ctx, op, s_mask);
2094 }
2095 
2096 static bool fold_not(OptContext *ctx, TCGOp *op)
2097 {
2098     if (fold_const1(ctx, op)) {
2099         return true;
2100     }
2101     return fold_masks_s(ctx, op, arg_info(op->args[1])->s_mask);
2102 }
2103 
2104 static bool fold_or(OptContext *ctx, TCGOp *op)
2105 {
2106     uint64_t z_mask, s_mask;
2107     TempOptInfo *t1, *t2;
2108 
2109     if (fold_const2_commutative(ctx, op) ||
2110         fold_xi_to_x(ctx, op, 0) ||
2111         fold_xx_to_x(ctx, op)) {
2112         return true;
2113     }
2114 
2115     t1 = arg_info(op->args[1]);
2116     t2 = arg_info(op->args[2]);
2117     z_mask = t1->z_mask | t2->z_mask;
2118     s_mask = t1->s_mask & t2->s_mask;
2119     return fold_masks_zs(ctx, op, z_mask, s_mask);
2120 }
2121 
2122 static bool fold_orc(OptContext *ctx, TCGOp *op)
2123 {
2124     uint64_t s_mask;
2125 
2126     if (fold_const2(ctx, op) ||
2127         fold_xx_to_i(ctx, op, -1) ||
2128         fold_xi_to_x(ctx, op, -1) ||
2129         fold_ix_to_not(ctx, op, 0)) {
2130         return true;
2131     }
2132 
2133     s_mask = arg_info(op->args[1])->s_mask
2134            & arg_info(op->args[2])->s_mask;
2135     return fold_masks_s(ctx, op, s_mask);
2136 }
2137 
2138 static bool fold_qemu_ld_1reg(OptContext *ctx, TCGOp *op)
2139 {
2140     const TCGOpDef *def = &tcg_op_defs[op->opc];
2141     MemOpIdx oi = op->args[def->nb_oargs + def->nb_iargs];
2142     MemOp mop = get_memop(oi);
2143     int width = 8 * memop_size(mop);
2144     uint64_t z_mask = -1, s_mask = 0;
2145 
2146     if (width < 64) {
2147         if (mop & MO_SIGN) {
2148             s_mask = MAKE_64BIT_MASK(width - 1, 64 - (width - 1));
2149         } else {
2150             z_mask = MAKE_64BIT_MASK(0, width);
2151         }
2152     }
2153 
2154     /* Opcodes that touch guest memory stop the mb optimization.  */
2155     ctx->prev_mb = NULL;
2156 
2157     return fold_masks_zs(ctx, op, z_mask, s_mask);
2158 }
2159 
2160 static bool fold_qemu_ld_2reg(OptContext *ctx, TCGOp *op)
2161 {
2162     /* Opcodes that touch guest memory stop the mb optimization.  */
2163     ctx->prev_mb = NULL;
2164     return finish_folding(ctx, op);
2165 }
2166 
2167 static bool fold_qemu_st(OptContext *ctx, TCGOp *op)
2168 {
2169     /* Opcodes that touch guest memory stop the mb optimization.  */
2170     ctx->prev_mb = NULL;
2171     return true;
2172 }
2173 
2174 static bool fold_remainder(OptContext *ctx, TCGOp *op)
2175 {
2176     if (fold_const2(ctx, op) ||
2177         fold_xx_to_i(ctx, op, 0)) {
2178         return true;
2179     }
2180     return finish_folding(ctx, op);
2181 }
2182 
2183 /* Return 1 if finished, -1 if simplified, 0 if unchanged. */
2184 static int fold_setcond_zmask(OptContext *ctx, TCGOp *op, bool neg)
2185 {
2186     uint64_t a_zmask, b_val;
2187     TCGCond cond;
2188 
2189     if (!arg_is_const(op->args[2])) {
2190         return false;
2191     }
2192 
2193     a_zmask = arg_info(op->args[1])->z_mask;
2194     b_val = arg_info(op->args[2])->val;
2195     cond = op->args[3];
2196 
2197     if (ctx->type == TCG_TYPE_I32) {
2198         a_zmask = (uint32_t)a_zmask;
2199         b_val = (uint32_t)b_val;
2200     }
2201 
2202     /*
2203      * A with only low bits set vs B with high bits set means that A < B.
2204      */
2205     if (a_zmask < b_val) {
2206         bool inv = false;
2207 
2208         switch (cond) {
2209         case TCG_COND_NE:
2210         case TCG_COND_LEU:
2211         case TCG_COND_LTU:
2212             inv = true;
2213             /* fall through */
2214         case TCG_COND_GTU:
2215         case TCG_COND_GEU:
2216         case TCG_COND_EQ:
2217             return tcg_opt_gen_movi(ctx, op, op->args[0], neg ? -inv : inv);
2218         default:
2219             break;
2220         }
2221     }
2222 
2223     /*
2224      * A with only lsb set is already boolean.
2225      */
2226     if (a_zmask <= 1) {
2227         bool convert = false;
2228         bool inv = false;
2229 
2230         switch (cond) {
2231         case TCG_COND_EQ:
2232             inv = true;
2233             /* fall through */
2234         case TCG_COND_NE:
2235             convert = (b_val == 0);
2236             break;
2237         case TCG_COND_LTU:
2238         case TCG_COND_TSTEQ:
2239             inv = true;
2240             /* fall through */
2241         case TCG_COND_GEU:
2242         case TCG_COND_TSTNE:
2243             convert = (b_val == 1);
2244             break;
2245         default:
2246             break;
2247         }
2248         if (convert) {
2249             TCGOpcode xor_opc, neg_opc;
2250 
2251             if (!inv && !neg) {
2252                 return tcg_opt_gen_mov(ctx, op, op->args[0], op->args[1]);
2253             }
2254 
2255             switch (ctx->type) {
2256             case TCG_TYPE_I32:
2257                 neg_opc = INDEX_op_neg_i32;
2258                 xor_opc = INDEX_op_xor_i32;
2259                 break;
2260             case TCG_TYPE_I64:
2261                 neg_opc = INDEX_op_neg_i64;
2262                 xor_opc = INDEX_op_xor_i64;
2263                 break;
2264             default:
2265                 g_assert_not_reached();
2266             }
2267 
2268             if (!inv) {
2269                 op->opc = neg_opc;
2270             } else if (neg) {
2271                 op->opc = INDEX_op_add;
2272                 op->args[2] = arg_new_constant(ctx, -1);
2273             } else {
2274                 op->opc = xor_opc;
2275                 op->args[2] = arg_new_constant(ctx, 1);
2276             }
2277             return -1;
2278         }
2279     }
2280     return 0;
2281 }
2282 
2283 static void fold_setcond_tst_pow2(OptContext *ctx, TCGOp *op, bool neg)
2284 {
2285     TCGOpcode sub_opc, xor_opc, neg_opc, shr_opc;
2286     TCGOpcode uext_opc = 0, sext_opc = 0;
2287     TCGCond cond = op->args[3];
2288     TCGArg ret, src1, src2;
2289     TCGOp *op2;
2290     uint64_t val;
2291     int sh;
2292     bool inv;
2293 
2294     if (!is_tst_cond(cond) || !arg_is_const(op->args[2])) {
2295         return;
2296     }
2297 
2298     src2 = op->args[2];
2299     val = arg_info(src2)->val;
2300     if (!is_power_of_2(val)) {
2301         return;
2302     }
2303     sh = ctz64(val);
2304 
2305     switch (ctx->type) {
2306     case TCG_TYPE_I32:
2307         sub_opc = INDEX_op_sub_i32;
2308         xor_opc = INDEX_op_xor_i32;
2309         shr_opc = INDEX_op_shr_i32;
2310         neg_opc = INDEX_op_neg_i32;
2311         if (TCG_TARGET_extract_valid(TCG_TYPE_I32, sh, 1)) {
2312             uext_opc = INDEX_op_extract_i32;
2313         }
2314         if (TCG_TARGET_sextract_valid(TCG_TYPE_I32, sh, 1)) {
2315             sext_opc = INDEX_op_sextract_i32;
2316         }
2317         break;
2318     case TCG_TYPE_I64:
2319         sub_opc = INDEX_op_sub_i64;
2320         xor_opc = INDEX_op_xor_i64;
2321         shr_opc = INDEX_op_shr_i64;
2322         neg_opc = INDEX_op_neg_i64;
2323         if (TCG_TARGET_extract_valid(TCG_TYPE_I64, sh, 1)) {
2324             uext_opc = INDEX_op_extract_i64;
2325         }
2326         if (TCG_TARGET_sextract_valid(TCG_TYPE_I64, sh, 1)) {
2327             sext_opc = INDEX_op_sextract_i64;
2328         }
2329         break;
2330     default:
2331         g_assert_not_reached();
2332     }
2333 
2334     ret = op->args[0];
2335     src1 = op->args[1];
2336     inv = cond == TCG_COND_TSTEQ;
2337 
2338     if (sh && sext_opc && neg && !inv) {
2339         op->opc = sext_opc;
2340         op->args[1] = src1;
2341         op->args[2] = sh;
2342         op->args[3] = 1;
2343         return;
2344     } else if (sh && uext_opc) {
2345         op->opc = uext_opc;
2346         op->args[1] = src1;
2347         op->args[2] = sh;
2348         op->args[3] = 1;
2349     } else {
2350         if (sh) {
2351             op2 = opt_insert_before(ctx, op, shr_opc, 3);
2352             op2->args[0] = ret;
2353             op2->args[1] = src1;
2354             op2->args[2] = arg_new_constant(ctx, sh);
2355             src1 = ret;
2356         }
2357         op->opc = INDEX_op_and;
2358         op->args[1] = src1;
2359         op->args[2] = arg_new_constant(ctx, 1);
2360     }
2361 
2362     if (neg && inv) {
2363         op2 = opt_insert_after(ctx, op, sub_opc, 3);
2364         op2->args[0] = ret;
2365         op2->args[1] = ret;
2366         op2->args[2] = arg_new_constant(ctx, 1);
2367     } else if (inv) {
2368         op2 = opt_insert_after(ctx, op, xor_opc, 3);
2369         op2->args[0] = ret;
2370         op2->args[1] = ret;
2371         op2->args[2] = arg_new_constant(ctx, 1);
2372     } else if (neg) {
2373         op2 = opt_insert_after(ctx, op, neg_opc, 2);
2374         op2->args[0] = ret;
2375         op2->args[1] = ret;
2376     }
2377 }
2378 
2379 static bool fold_setcond(OptContext *ctx, TCGOp *op)
2380 {
2381     int i = do_constant_folding_cond1(ctx, op, op->args[0], &op->args[1],
2382                                       &op->args[2], &op->args[3]);
2383     if (i >= 0) {
2384         return tcg_opt_gen_movi(ctx, op, op->args[0], i);
2385     }
2386 
2387     i = fold_setcond_zmask(ctx, op, false);
2388     if (i > 0) {
2389         return true;
2390     }
2391     if (i == 0) {
2392         fold_setcond_tst_pow2(ctx, op, false);
2393     }
2394 
2395     return fold_masks_z(ctx, op, 1);
2396 }
2397 
2398 static bool fold_negsetcond(OptContext *ctx, TCGOp *op)
2399 {
2400     int i = do_constant_folding_cond1(ctx, op, op->args[0], &op->args[1],
2401                                       &op->args[2], &op->args[3]);
2402     if (i >= 0) {
2403         return tcg_opt_gen_movi(ctx, op, op->args[0], -i);
2404     }
2405 
2406     i = fold_setcond_zmask(ctx, op, true);
2407     if (i > 0) {
2408         return true;
2409     }
2410     if (i == 0) {
2411         fold_setcond_tst_pow2(ctx, op, true);
2412     }
2413 
2414     /* Value is {0,-1} so all bits are repetitions of the sign. */
2415     return fold_masks_s(ctx, op, -1);
2416 }
2417 
2418 static bool fold_setcond2(OptContext *ctx, TCGOp *op)
2419 {
2420     TCGCond cond;
2421     int i, inv = 0;
2422 
2423     i = do_constant_folding_cond2(ctx, op, &op->args[1]);
2424     cond = op->args[5];
2425     if (i >= 0) {
2426         goto do_setcond_const;
2427     }
2428 
2429     switch (cond) {
2430     case TCG_COND_LT:
2431     case TCG_COND_GE:
2432         /*
2433          * Simplify LT/GE comparisons vs zero to a single compare
2434          * vs the high word of the input.
2435          */
2436         if (arg_is_const_val(op->args[3], 0) &&
2437             arg_is_const_val(op->args[4], 0)) {
2438             goto do_setcond_high;
2439         }
2440         break;
2441 
2442     case TCG_COND_NE:
2443         inv = 1;
2444         QEMU_FALLTHROUGH;
2445     case TCG_COND_EQ:
2446         /*
2447          * Simplify EQ/NE comparisons where one of the pairs
2448          * can be simplified.
2449          */
2450         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[1],
2451                                      op->args[3], cond);
2452         switch (i ^ inv) {
2453         case 0:
2454             goto do_setcond_const;
2455         case 1:
2456             goto do_setcond_high;
2457         }
2458 
2459         i = do_constant_folding_cond(TCG_TYPE_I32, op->args[2],
2460                                      op->args[4], cond);
2461         switch (i ^ inv) {
2462         case 0:
2463             goto do_setcond_const;
2464         case 1:
2465             goto do_setcond_low;
2466         }
2467         break;
2468 
2469     case TCG_COND_TSTEQ:
2470     case TCG_COND_TSTNE:
2471         if (arg_is_const_val(op->args[3], 0)) {
2472             goto do_setcond_high;
2473         }
2474         if (arg_is_const_val(op->args[4], 0)) {
2475             goto do_setcond_low;
2476         }
2477         break;
2478 
2479     default:
2480         break;
2481 
2482     do_setcond_low:
2483         op->args[2] = op->args[3];
2484         op->args[3] = cond;
2485         op->opc = INDEX_op_setcond_i32;
2486         return fold_setcond(ctx, op);
2487 
2488     do_setcond_high:
2489         op->args[1] = op->args[2];
2490         op->args[2] = op->args[4];
2491         op->args[3] = cond;
2492         op->opc = INDEX_op_setcond_i32;
2493         return fold_setcond(ctx, op);
2494     }
2495 
2496     return fold_masks_z(ctx, op, 1);
2497 
2498  do_setcond_const:
2499     return tcg_opt_gen_movi(ctx, op, op->args[0], i);
2500 }
2501 
2502 static bool fold_sextract(OptContext *ctx, TCGOp *op)
2503 {
2504     uint64_t z_mask, s_mask, s_mask_old;
2505     TempOptInfo *t1 = arg_info(op->args[1]);
2506     int pos = op->args[2];
2507     int len = op->args[3];
2508 
2509     if (ti_is_const(t1)) {
2510         return tcg_opt_gen_movi(ctx, op, op->args[0],
2511                                 sextract64(ti_const_val(t1), pos, len));
2512     }
2513 
2514     s_mask_old = t1->s_mask;
2515     s_mask = s_mask_old >> pos;
2516     s_mask |= -1ull << (len - 1);
2517 
2518     if (pos == 0 && fold_affected_mask(ctx, op, s_mask & ~s_mask_old)) {
2519         return true;
2520     }
2521 
2522     z_mask = sextract64(t1->z_mask, pos, len);
2523     return fold_masks_zs(ctx, op, z_mask, s_mask);
2524 }
2525 
2526 static bool fold_shift(OptContext *ctx, TCGOp *op)
2527 {
2528     uint64_t s_mask, z_mask;
2529     TempOptInfo *t1, *t2;
2530 
2531     if (fold_const2(ctx, op) ||
2532         fold_ix_to_i(ctx, op, 0) ||
2533         fold_xi_to_x(ctx, op, 0)) {
2534         return true;
2535     }
2536 
2537     t1 = arg_info(op->args[1]);
2538     t2 = arg_info(op->args[2]);
2539     s_mask = t1->s_mask;
2540     z_mask = t1->z_mask;
2541 
2542     if (ti_is_const(t2)) {
2543         int sh = ti_const_val(t2);
2544 
2545         z_mask = do_constant_folding(op->opc, ctx->type, z_mask, sh);
2546         s_mask = do_constant_folding(op->opc, ctx->type, s_mask, sh);
2547 
2548         return fold_masks_zs(ctx, op, z_mask, s_mask);
2549     }
2550 
2551     switch (op->opc) {
2552     CASE_OP_32_64(sar):
2553         /*
2554          * Arithmetic right shift will not reduce the number of
2555          * input sign repetitions.
2556          */
2557         return fold_masks_s(ctx, op, s_mask);
2558     CASE_OP_32_64(shr):
2559         /*
2560          * If the sign bit is known zero, then logical right shift
2561          * will not reduce the number of input sign repetitions.
2562          */
2563         if (~z_mask & -s_mask) {
2564             return fold_masks_s(ctx, op, s_mask);
2565         }
2566         break;
2567     default:
2568         break;
2569     }
2570 
2571     return finish_folding(ctx, op);
2572 }
2573 
2574 static bool fold_sub_to_neg(OptContext *ctx, TCGOp *op)
2575 {
2576     TCGOpcode neg_op;
2577     bool have_neg;
2578 
2579     if (!arg_is_const(op->args[1]) || arg_info(op->args[1])->val != 0) {
2580         return false;
2581     }
2582 
2583     switch (ctx->type) {
2584     case TCG_TYPE_I32:
2585         neg_op = INDEX_op_neg_i32;
2586         have_neg = true;
2587         break;
2588     case TCG_TYPE_I64:
2589         neg_op = INDEX_op_neg_i64;
2590         have_neg = true;
2591         break;
2592     case TCG_TYPE_V64:
2593     case TCG_TYPE_V128:
2594     case TCG_TYPE_V256:
2595         neg_op = INDEX_op_neg_vec;
2596         have_neg = (TCG_TARGET_HAS_neg_vec &&
2597                     tcg_can_emit_vec_op(neg_op, ctx->type, TCGOP_VECE(op)) > 0);
2598         break;
2599     default:
2600         g_assert_not_reached();
2601     }
2602     if (have_neg) {
2603         op->opc = neg_op;
2604         op->args[1] = op->args[2];
2605         return fold_neg_no_const(ctx, op);
2606     }
2607     return false;
2608 }
2609 
2610 /* We cannot as yet do_constant_folding with vectors. */
2611 static bool fold_sub_vec(OptContext *ctx, TCGOp *op)
2612 {
2613     if (fold_xx_to_i(ctx, op, 0) ||
2614         fold_xi_to_x(ctx, op, 0) ||
2615         fold_sub_to_neg(ctx, op)) {
2616         return true;
2617     }
2618     return finish_folding(ctx, op);
2619 }
2620 
2621 static bool fold_sub(OptContext *ctx, TCGOp *op)
2622 {
2623     if (fold_const2(ctx, op) ||
2624         fold_xx_to_i(ctx, op, 0) ||
2625         fold_xi_to_x(ctx, op, 0) ||
2626         fold_sub_to_neg(ctx, op)) {
2627         return true;
2628     }
2629 
2630     /* Fold sub r,x,i to add r,x,-i */
2631     if (arg_is_const(op->args[2])) {
2632         uint64_t val = arg_info(op->args[2])->val;
2633 
2634         op->opc = INDEX_op_add;
2635         op->args[2] = arg_new_constant(ctx, -val);
2636     }
2637     return finish_folding(ctx, op);
2638 }
2639 
2640 static bool fold_sub2(OptContext *ctx, TCGOp *op)
2641 {
2642     return fold_addsub2(ctx, op, false);
2643 }
2644 
2645 static bool fold_tcg_ld(OptContext *ctx, TCGOp *op)
2646 {
2647     uint64_t z_mask = -1, s_mask = 0;
2648 
2649     /* We can't do any folding with a load, but we can record bits. */
2650     switch (op->opc) {
2651     CASE_OP_32_64(ld8s):
2652         s_mask = INT8_MIN;
2653         break;
2654     CASE_OP_32_64(ld8u):
2655         z_mask = MAKE_64BIT_MASK(0, 8);
2656         break;
2657     CASE_OP_32_64(ld16s):
2658         s_mask = INT16_MIN;
2659         break;
2660     CASE_OP_32_64(ld16u):
2661         z_mask = MAKE_64BIT_MASK(0, 16);
2662         break;
2663     case INDEX_op_ld32s_i64:
2664         s_mask = INT32_MIN;
2665         break;
2666     case INDEX_op_ld32u_i64:
2667         z_mask = MAKE_64BIT_MASK(0, 32);
2668         break;
2669     default:
2670         g_assert_not_reached();
2671     }
2672     return fold_masks_zs(ctx, op, z_mask, s_mask);
2673 }
2674 
2675 static bool fold_tcg_ld_memcopy(OptContext *ctx, TCGOp *op)
2676 {
2677     TCGTemp *dst, *src;
2678     intptr_t ofs;
2679     TCGType type;
2680 
2681     if (op->args[1] != tcgv_ptr_arg(tcg_env)) {
2682         return finish_folding(ctx, op);
2683     }
2684 
2685     type = ctx->type;
2686     ofs = op->args[2];
2687     dst = arg_temp(op->args[0]);
2688     src = find_mem_copy_for(ctx, type, ofs);
2689     if (src && src->base_type == type) {
2690         return tcg_opt_gen_mov(ctx, op, temp_arg(dst), temp_arg(src));
2691     }
2692 
2693     reset_ts(ctx, dst);
2694     record_mem_copy(ctx, type, dst, ofs, ofs + tcg_type_size(type) - 1);
2695     return true;
2696 }
2697 
2698 static bool fold_tcg_st(OptContext *ctx, TCGOp *op)
2699 {
2700     intptr_t ofs = op->args[2];
2701     intptr_t lm1;
2702 
2703     if (op->args[1] != tcgv_ptr_arg(tcg_env)) {
2704         remove_mem_copy_all(ctx);
2705         return true;
2706     }
2707 
2708     switch (op->opc) {
2709     CASE_OP_32_64(st8):
2710         lm1 = 0;
2711         break;
2712     CASE_OP_32_64(st16):
2713         lm1 = 1;
2714         break;
2715     case INDEX_op_st32_i64:
2716     case INDEX_op_st_i32:
2717         lm1 = 3;
2718         break;
2719     case INDEX_op_st_i64:
2720         lm1 = 7;
2721         break;
2722     case INDEX_op_st_vec:
2723         lm1 = tcg_type_size(ctx->type) - 1;
2724         break;
2725     default:
2726         g_assert_not_reached();
2727     }
2728     remove_mem_copy_in(ctx, ofs, ofs + lm1);
2729     return true;
2730 }
2731 
2732 static bool fold_tcg_st_memcopy(OptContext *ctx, TCGOp *op)
2733 {
2734     TCGTemp *src;
2735     intptr_t ofs, last;
2736     TCGType type;
2737 
2738     if (op->args[1] != tcgv_ptr_arg(tcg_env)) {
2739         return fold_tcg_st(ctx, op);
2740     }
2741 
2742     src = arg_temp(op->args[0]);
2743     ofs = op->args[2];
2744     type = ctx->type;
2745 
2746     /*
2747      * Eliminate duplicate stores of a constant.
2748      * This happens frequently when the target ISA zero-extends.
2749      */
2750     if (ts_is_const(src)) {
2751         TCGTemp *prev = find_mem_copy_for(ctx, type, ofs);
2752         if (src == prev) {
2753             tcg_op_remove(ctx->tcg, op);
2754             return true;
2755         }
2756     }
2757 
2758     last = ofs + tcg_type_size(type) - 1;
2759     remove_mem_copy_in(ctx, ofs, last);
2760     record_mem_copy(ctx, type, src, ofs, last);
2761     return true;
2762 }
2763 
2764 static bool fold_xor(OptContext *ctx, TCGOp *op)
2765 {
2766     uint64_t z_mask, s_mask;
2767     TempOptInfo *t1, *t2;
2768 
2769     if (fold_const2_commutative(ctx, op) ||
2770         fold_xx_to_i(ctx, op, 0) ||
2771         fold_xi_to_x(ctx, op, 0) ||
2772         fold_xi_to_not(ctx, op, -1)) {
2773         return true;
2774     }
2775 
2776     t1 = arg_info(op->args[1]);
2777     t2 = arg_info(op->args[2]);
2778     z_mask = t1->z_mask | t2->z_mask;
2779     s_mask = t1->s_mask & t2->s_mask;
2780     return fold_masks_zs(ctx, op, z_mask, s_mask);
2781 }
2782 
2783 /* Propagate constants and copies, fold constant expressions. */
2784 void tcg_optimize(TCGContext *s)
2785 {
2786     int nb_temps, i;
2787     TCGOp *op, *op_next;
2788     OptContext ctx = { .tcg = s };
2789 
2790     QSIMPLEQ_INIT(&ctx.mem_free);
2791 
2792     /* Array VALS has an element for each temp.
2793        If this temp holds a constant then its value is kept in VALS' element.
2794        If this temp is a copy of other ones then the other copies are
2795        available through the doubly linked circular list. */
2796 
2797     nb_temps = s->nb_temps;
2798     for (i = 0; i < nb_temps; ++i) {
2799         s->temps[i].state_ptr = NULL;
2800     }
2801 
2802     QTAILQ_FOREACH_SAFE(op, &s->ops, link, op_next) {
2803         TCGOpcode opc = op->opc;
2804         const TCGOpDef *def;
2805         bool done = false;
2806 
2807         /* Calls are special. */
2808         if (opc == INDEX_op_call) {
2809             fold_call(&ctx, op);
2810             continue;
2811         }
2812 
2813         def = &tcg_op_defs[opc];
2814         init_arguments(&ctx, op, def->nb_oargs + def->nb_iargs);
2815         copy_propagate(&ctx, op, def->nb_oargs, def->nb_iargs);
2816 
2817         /* Pre-compute the type of the operation. */
2818         ctx.type = TCGOP_TYPE(op);
2819 
2820         /*
2821          * Process each opcode.
2822          * Sorted alphabetically by opcode as much as possible.
2823          */
2824         switch (opc) {
2825         case INDEX_op_add:
2826             done = fold_add(&ctx, op);
2827             break;
2828         case INDEX_op_add_vec:
2829             done = fold_add_vec(&ctx, op);
2830             break;
2831         CASE_OP_32_64(add2):
2832             done = fold_add2(&ctx, op);
2833             break;
2834         case INDEX_op_and:
2835         case INDEX_op_and_vec:
2836             done = fold_and(&ctx, op);
2837             break;
2838         CASE_OP_32_64_VEC(andc):
2839             done = fold_andc(&ctx, op);
2840             break;
2841         CASE_OP_32_64(brcond):
2842             done = fold_brcond(&ctx, op);
2843             break;
2844         case INDEX_op_brcond2_i32:
2845             done = fold_brcond2(&ctx, op);
2846             break;
2847         CASE_OP_32_64(bswap16):
2848         CASE_OP_32_64(bswap32):
2849         case INDEX_op_bswap64_i64:
2850             done = fold_bswap(&ctx, op);
2851             break;
2852         CASE_OP_32_64(clz):
2853         CASE_OP_32_64(ctz):
2854             done = fold_count_zeros(&ctx, op);
2855             break;
2856         CASE_OP_32_64(ctpop):
2857             done = fold_ctpop(&ctx, op);
2858             break;
2859         CASE_OP_32_64(deposit):
2860             done = fold_deposit(&ctx, op);
2861             break;
2862         CASE_OP_32_64(div):
2863         CASE_OP_32_64(divu):
2864             done = fold_divide(&ctx, op);
2865             break;
2866         case INDEX_op_dup_vec:
2867             done = fold_dup(&ctx, op);
2868             break;
2869         case INDEX_op_dup2_vec:
2870             done = fold_dup2(&ctx, op);
2871             break;
2872         CASE_OP_32_64_VEC(eqv):
2873             done = fold_eqv(&ctx, op);
2874             break;
2875         CASE_OP_32_64(extract):
2876             done = fold_extract(&ctx, op);
2877             break;
2878         CASE_OP_32_64(extract2):
2879             done = fold_extract2(&ctx, op);
2880             break;
2881         case INDEX_op_ext_i32_i64:
2882             done = fold_exts(&ctx, op);
2883             break;
2884         case INDEX_op_extu_i32_i64:
2885         case INDEX_op_extrl_i64_i32:
2886         case INDEX_op_extrh_i64_i32:
2887             done = fold_extu(&ctx, op);
2888             break;
2889         CASE_OP_32_64(ld8s):
2890         CASE_OP_32_64(ld8u):
2891         CASE_OP_32_64(ld16s):
2892         CASE_OP_32_64(ld16u):
2893         case INDEX_op_ld32s_i64:
2894         case INDEX_op_ld32u_i64:
2895             done = fold_tcg_ld(&ctx, op);
2896             break;
2897         case INDEX_op_ld_i32:
2898         case INDEX_op_ld_i64:
2899         case INDEX_op_ld_vec:
2900             done = fold_tcg_ld_memcopy(&ctx, op);
2901             break;
2902         CASE_OP_32_64(st8):
2903         CASE_OP_32_64(st16):
2904         case INDEX_op_st32_i64:
2905             done = fold_tcg_st(&ctx, op);
2906             break;
2907         case INDEX_op_st_i32:
2908         case INDEX_op_st_i64:
2909         case INDEX_op_st_vec:
2910             done = fold_tcg_st_memcopy(&ctx, op);
2911             break;
2912         case INDEX_op_mb:
2913             done = fold_mb(&ctx, op);
2914             break;
2915         case INDEX_op_mov:
2916         case INDEX_op_mov_vec:
2917             done = fold_mov(&ctx, op);
2918             break;
2919         CASE_OP_32_64(movcond):
2920             done = fold_movcond(&ctx, op);
2921             break;
2922         CASE_OP_32_64(mul):
2923             done = fold_mul(&ctx, op);
2924             break;
2925         CASE_OP_32_64(mulsh):
2926         CASE_OP_32_64(muluh):
2927             done = fold_mul_highpart(&ctx, op);
2928             break;
2929         CASE_OP_32_64(muls2):
2930         CASE_OP_32_64(mulu2):
2931             done = fold_multiply2(&ctx, op);
2932             break;
2933         CASE_OP_32_64_VEC(nand):
2934             done = fold_nand(&ctx, op);
2935             break;
2936         CASE_OP_32_64(neg):
2937             done = fold_neg(&ctx, op);
2938             break;
2939         CASE_OP_32_64_VEC(nor):
2940             done = fold_nor(&ctx, op);
2941             break;
2942         CASE_OP_32_64_VEC(not):
2943             done = fold_not(&ctx, op);
2944             break;
2945         CASE_OP_32_64_VEC(or):
2946             done = fold_or(&ctx, op);
2947             break;
2948         CASE_OP_32_64_VEC(orc):
2949             done = fold_orc(&ctx, op);
2950             break;
2951         case INDEX_op_qemu_ld_i32:
2952             done = fold_qemu_ld_1reg(&ctx, op);
2953             break;
2954         case INDEX_op_qemu_ld_i64:
2955             if (TCG_TARGET_REG_BITS == 64) {
2956                 done = fold_qemu_ld_1reg(&ctx, op);
2957                 break;
2958             }
2959             QEMU_FALLTHROUGH;
2960         case INDEX_op_qemu_ld_i128:
2961             done = fold_qemu_ld_2reg(&ctx, op);
2962             break;
2963         case INDEX_op_qemu_st8_i32:
2964         case INDEX_op_qemu_st_i32:
2965         case INDEX_op_qemu_st_i64:
2966         case INDEX_op_qemu_st_i128:
2967             done = fold_qemu_st(&ctx, op);
2968             break;
2969         CASE_OP_32_64(rem):
2970         CASE_OP_32_64(remu):
2971             done = fold_remainder(&ctx, op);
2972             break;
2973         CASE_OP_32_64(rotl):
2974         CASE_OP_32_64(rotr):
2975         CASE_OP_32_64(sar):
2976         CASE_OP_32_64(shl):
2977         CASE_OP_32_64(shr):
2978             done = fold_shift(&ctx, op);
2979             break;
2980         CASE_OP_32_64(setcond):
2981             done = fold_setcond(&ctx, op);
2982             break;
2983         CASE_OP_32_64(negsetcond):
2984             done = fold_negsetcond(&ctx, op);
2985             break;
2986         case INDEX_op_setcond2_i32:
2987             done = fold_setcond2(&ctx, op);
2988             break;
2989         case INDEX_op_cmp_vec:
2990             done = fold_cmp_vec(&ctx, op);
2991             break;
2992         case INDEX_op_cmpsel_vec:
2993             done = fold_cmpsel_vec(&ctx, op);
2994             break;
2995         case INDEX_op_bitsel_vec:
2996             done = fold_bitsel_vec(&ctx, op);
2997             break;
2998         CASE_OP_32_64(sextract):
2999             done = fold_sextract(&ctx, op);
3000             break;
3001         CASE_OP_32_64(sub):
3002             done = fold_sub(&ctx, op);
3003             break;
3004         case INDEX_op_sub_vec:
3005             done = fold_sub_vec(&ctx, op);
3006             break;
3007         CASE_OP_32_64(sub2):
3008             done = fold_sub2(&ctx, op);
3009             break;
3010         CASE_OP_32_64_VEC(xor):
3011             done = fold_xor(&ctx, op);
3012             break;
3013         case INDEX_op_set_label:
3014         case INDEX_op_br:
3015         case INDEX_op_exit_tb:
3016         case INDEX_op_goto_tb:
3017         case INDEX_op_goto_ptr:
3018             finish_ebb(&ctx);
3019             done = true;
3020             break;
3021         default:
3022             done = finish_folding(&ctx, op);
3023             break;
3024         }
3025         tcg_debug_assert(done);
3026     }
3027 }
3028