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