xref: /openbmc/qemu/tcg/tcg.c (revision 74dbd36f1f87bd7fc4705644d63c5561a23b0567)
1 /*
2  * Tiny Code Generator for QEMU
3  *
4  * Copyright (c) 2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 /* Define to jump the ELF file used to communicate with GDB.  */
28 #undef DEBUG_JIT
29 
30 #include "qemu/error-report.h"
31 #include "qemu/cutils.h"
32 #include "qemu/host-utils.h"
33 #include "qemu/qemu-print.h"
34 #include "qemu/cacheflush.h"
35 #include "qemu/cacheinfo.h"
36 #include "qemu/timer.h"
37 #include "exec/translation-block.h"
38 #include "exec/tlb-common.h"
39 #include "tcg/startup.h"
40 #include "tcg/tcg-op-common.h"
41 
42 #if UINTPTR_MAX == UINT32_MAX
43 # define ELF_CLASS  ELFCLASS32
44 #else
45 # define ELF_CLASS  ELFCLASS64
46 #endif
47 #if HOST_BIG_ENDIAN
48 # define ELF_DATA   ELFDATA2MSB
49 #else
50 # define ELF_DATA   ELFDATA2LSB
51 #endif
52 
53 #include "elf.h"
54 #include "exec/log.h"
55 #include "tcg/tcg-ldst.h"
56 #include "tcg/tcg-temp-internal.h"
57 #include "tcg-internal.h"
58 #include "tcg/perf.h"
59 #include "tcg-has.h"
60 #ifdef CONFIG_USER_ONLY
61 #include "user/guest-base.h"
62 #endif
63 
64 /* Forward declarations for functions declared in tcg-target.c.inc and
65    used here. */
66 static void tcg_target_init(TCGContext *s);
67 static void tcg_target_qemu_prologue(TCGContext *s);
68 static bool patch_reloc(tcg_insn_unit *code_ptr, int type,
69                         intptr_t value, intptr_t addend);
70 static void tcg_out_nop_fill(tcg_insn_unit *p, int count);
71 
72 typedef struct TCGLabelQemuLdst TCGLabelQemuLdst;
73 static bool tcg_out_qemu_ld_slow_path(TCGContext *s, TCGLabelQemuLdst *l);
74 static bool tcg_out_qemu_st_slow_path(TCGContext *s, TCGLabelQemuLdst *l);
75 
76 /* The CIE and FDE header definitions will be common to all hosts.  */
77 typedef struct {
78     uint32_t len __attribute__((aligned((sizeof(void *)))));
79     uint32_t id;
80     uint8_t version;
81     char augmentation[1];
82     uint8_t code_align;
83     uint8_t data_align;
84     uint8_t return_column;
85 } DebugFrameCIE;
86 
87 typedef struct QEMU_PACKED {
88     uint32_t len __attribute__((aligned((sizeof(void *)))));
89     uint32_t cie_offset;
90     uintptr_t func_start;
91     uintptr_t func_len;
92 } DebugFrameFDEHeader;
93 
94 typedef struct QEMU_PACKED {
95     DebugFrameCIE cie;
96     DebugFrameFDEHeader fde;
97 } DebugFrameHeader;
98 
99 struct TCGLabelQemuLdst {
100     bool is_ld;             /* qemu_ld: true, qemu_st: false */
101     MemOpIdx oi;
102     TCGType type;           /* result type of a load */
103     TCGReg addr_reg;        /* reg index for guest virtual addr */
104     TCGReg datalo_reg;      /* reg index for low word to be loaded or stored */
105     TCGReg datahi_reg;      /* reg index for high word to be loaded or stored */
106     const tcg_insn_unit *raddr;   /* addr of the next IR of qemu_ld/st IR */
107     tcg_insn_unit *label_ptr[2]; /* label pointers to be updated */
108     QSIMPLEQ_ENTRY(TCGLabelQemuLdst) next;
109 };
110 
111 static void tcg_register_jit_int(const void *buf, size_t size,
112                                  const void *debug_frame,
113                                  size_t debug_frame_size)
114     __attribute__((unused));
115 
116 /* Forward declarations for functions declared and used in tcg-target.c.inc. */
117 static void tcg_out_tb_start(TCGContext *s);
118 static void tcg_out_ld(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg1,
119                        intptr_t arg2);
120 static bool tcg_out_mov(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg);
121 static void tcg_out_movi(TCGContext *s, TCGType type,
122                          TCGReg ret, tcg_target_long arg);
123 static void tcg_out_ext8s(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg);
124 static void tcg_out_ext16s(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg);
125 static void tcg_out_ext8u(TCGContext *s, TCGReg ret, TCGReg arg);
126 static void tcg_out_ext16u(TCGContext *s, TCGReg ret, TCGReg arg);
127 static void tcg_out_ext32s(TCGContext *s, TCGReg ret, TCGReg arg);
128 static void tcg_out_ext32u(TCGContext *s, TCGReg ret, TCGReg arg);
129 static void tcg_out_exts_i32_i64(TCGContext *s, TCGReg ret, TCGReg arg);
130 static void tcg_out_extu_i32_i64(TCGContext *s, TCGReg ret, TCGReg arg);
131 static void tcg_out_extrl_i64_i32(TCGContext *s, TCGReg ret, TCGReg arg);
132 static void tcg_out_addi_ptr(TCGContext *s, TCGReg, TCGReg, tcg_target_long);
133 static bool tcg_out_xchg(TCGContext *s, TCGType type, TCGReg r1, TCGReg r2);
134 static void tcg_out_exit_tb(TCGContext *s, uintptr_t arg);
135 static void tcg_out_goto_tb(TCGContext *s, int which);
136 static void tcg_out_op(TCGContext *s, TCGOpcode opc, TCGType type,
137                        const TCGArg args[TCG_MAX_OP_ARGS],
138                        const int const_args[TCG_MAX_OP_ARGS]);
139 #if TCG_TARGET_MAYBE_vec
140 static bool tcg_out_dup_vec(TCGContext *s, TCGType type, unsigned vece,
141                             TCGReg dst, TCGReg src);
142 static bool tcg_out_dupm_vec(TCGContext *s, TCGType type, unsigned vece,
143                              TCGReg dst, TCGReg base, intptr_t offset);
144 static void tcg_out_dupi_vec(TCGContext *s, TCGType type, unsigned vece,
145                              TCGReg dst, int64_t arg);
146 static void tcg_out_vec_op(TCGContext *s, TCGOpcode opc,
147                            unsigned vecl, unsigned vece,
148                            const TCGArg args[TCG_MAX_OP_ARGS],
149                            const int const_args[TCG_MAX_OP_ARGS]);
150 #else
151 static inline bool tcg_out_dup_vec(TCGContext *s, TCGType type, unsigned vece,
152                                    TCGReg dst, TCGReg src)
153 {
154     g_assert_not_reached();
155 }
156 static inline bool tcg_out_dupm_vec(TCGContext *s, TCGType type, unsigned vece,
157                                     TCGReg dst, TCGReg base, intptr_t offset)
158 {
159     g_assert_not_reached();
160 }
161 static inline void tcg_out_dupi_vec(TCGContext *s, TCGType type, unsigned vece,
162                                     TCGReg dst, int64_t arg)
163 {
164     g_assert_not_reached();
165 }
166 static inline void tcg_out_vec_op(TCGContext *s, TCGOpcode opc,
167                                   unsigned vecl, unsigned vece,
168                                   const TCGArg args[TCG_MAX_OP_ARGS],
169                                   const int const_args[TCG_MAX_OP_ARGS])
170 {
171     g_assert_not_reached();
172 }
173 int tcg_can_emit_vec_op(TCGOpcode o, TCGType t, unsigned ve)
174 {
175     return 0;
176 }
177 #endif
178 static void tcg_out_st(TCGContext *s, TCGType type, TCGReg arg, TCGReg arg1,
179                        intptr_t arg2);
180 static bool tcg_out_sti(TCGContext *s, TCGType type, TCGArg val,
181                         TCGReg base, intptr_t ofs);
182 static void tcg_out_call(TCGContext *s, const tcg_insn_unit *target,
183                          const TCGHelperInfo *info);
184 static TCGReg tcg_target_call_oarg_reg(TCGCallReturnKind kind, int slot);
185 static bool tcg_target_const_match(int64_t val, int ct,
186                                    TCGType type, TCGCond cond, int vece);
187 
188 #ifndef CONFIG_USER_ONLY
189 #define guest_base  ({ qemu_build_not_reached(); (uintptr_t)0; })
190 #endif
191 
192 typedef struct TCGLdstHelperParam {
193     TCGReg (*ra_gen)(TCGContext *s, const TCGLabelQemuLdst *l, int arg_reg);
194     unsigned ntmp;
195     int tmp[3];
196 } TCGLdstHelperParam;
197 
198 static void tcg_out_ld_helper_args(TCGContext *s, const TCGLabelQemuLdst *l,
199                                    const TCGLdstHelperParam *p)
200     __attribute__((unused));
201 static void tcg_out_ld_helper_ret(TCGContext *s, const TCGLabelQemuLdst *l,
202                                   bool load_sign, const TCGLdstHelperParam *p)
203     __attribute__((unused));
204 static void tcg_out_st_helper_args(TCGContext *s, const TCGLabelQemuLdst *l,
205                                    const TCGLdstHelperParam *p)
206     __attribute__((unused));
207 
208 static void * const qemu_ld_helpers[MO_SSIZE + 1] __attribute__((unused)) = {
209     [MO_UB] = helper_ldub_mmu,
210     [MO_SB] = helper_ldsb_mmu,
211     [MO_UW] = helper_lduw_mmu,
212     [MO_SW] = helper_ldsw_mmu,
213     [MO_UL] = helper_ldul_mmu,
214     [MO_UQ] = helper_ldq_mmu,
215 #if TCG_TARGET_REG_BITS == 64
216     [MO_SL] = helper_ldsl_mmu,
217     [MO_128] = helper_ld16_mmu,
218 #endif
219 };
220 
221 static void * const qemu_st_helpers[MO_SIZE + 1] __attribute__((unused)) = {
222     [MO_8]  = helper_stb_mmu,
223     [MO_16] = helper_stw_mmu,
224     [MO_32] = helper_stl_mmu,
225     [MO_64] = helper_stq_mmu,
226 #if TCG_TARGET_REG_BITS == 64
227     [MO_128] = helper_st16_mmu,
228 #endif
229 };
230 
231 typedef struct {
232     MemOp atom;   /* lg2 bits of atomicity required */
233     MemOp align;  /* lg2 bits of alignment to use */
234 } TCGAtomAlign;
235 
236 static TCGAtomAlign atom_and_align_for_opc(TCGContext *s, MemOp opc,
237                                            MemOp host_atom, bool allow_two_ops)
238     __attribute__((unused));
239 
240 #ifdef CONFIG_USER_ONLY
241 bool tcg_use_softmmu;
242 #endif
243 
244 TCGContext tcg_init_ctx;
245 __thread TCGContext *tcg_ctx;
246 
247 TCGContext **tcg_ctxs;
248 unsigned int tcg_cur_ctxs;
249 unsigned int tcg_max_ctxs;
250 TCGv_env tcg_env;
251 const void *tcg_code_gen_epilogue;
252 uintptr_t tcg_splitwx_diff;
253 
254 #ifndef CONFIG_TCG_INTERPRETER
255 tcg_prologue_fn *tcg_qemu_tb_exec;
256 #endif
257 
258 static TCGRegSet tcg_target_available_regs[TCG_TYPE_COUNT];
259 static TCGRegSet tcg_target_call_clobber_regs;
260 
261 #if TCG_TARGET_INSN_UNIT_SIZE == 1
262 static __attribute__((unused)) inline void tcg_out8(TCGContext *s, uint8_t v)
263 {
264     *s->code_ptr++ = v;
265 }
266 
267 static __attribute__((unused)) inline void tcg_patch8(tcg_insn_unit *p,
268                                                       uint8_t v)
269 {
270     *p = v;
271 }
272 #endif
273 
274 #if TCG_TARGET_INSN_UNIT_SIZE <= 2
275 static __attribute__((unused)) inline void tcg_out16(TCGContext *s, uint16_t v)
276 {
277     if (TCG_TARGET_INSN_UNIT_SIZE == 2) {
278         *s->code_ptr++ = v;
279     } else {
280         tcg_insn_unit *p = s->code_ptr;
281         memcpy(p, &v, sizeof(v));
282         s->code_ptr = p + (2 / TCG_TARGET_INSN_UNIT_SIZE);
283     }
284 }
285 
286 static __attribute__((unused)) inline void tcg_patch16(tcg_insn_unit *p,
287                                                        uint16_t v)
288 {
289     if (TCG_TARGET_INSN_UNIT_SIZE == 2) {
290         *p = v;
291     } else {
292         memcpy(p, &v, sizeof(v));
293     }
294 }
295 #endif
296 
297 #if TCG_TARGET_INSN_UNIT_SIZE <= 4
298 static __attribute__((unused)) inline void tcg_out32(TCGContext *s, uint32_t v)
299 {
300     if (TCG_TARGET_INSN_UNIT_SIZE == 4) {
301         *s->code_ptr++ = v;
302     } else {
303         tcg_insn_unit *p = s->code_ptr;
304         memcpy(p, &v, sizeof(v));
305         s->code_ptr = p + (4 / TCG_TARGET_INSN_UNIT_SIZE);
306     }
307 }
308 
309 static __attribute__((unused)) inline void tcg_patch32(tcg_insn_unit *p,
310                                                        uint32_t v)
311 {
312     if (TCG_TARGET_INSN_UNIT_SIZE == 4) {
313         *p = v;
314     } else {
315         memcpy(p, &v, sizeof(v));
316     }
317 }
318 #endif
319 
320 #if TCG_TARGET_INSN_UNIT_SIZE <= 8
321 static __attribute__((unused)) inline void tcg_out64(TCGContext *s, uint64_t v)
322 {
323     if (TCG_TARGET_INSN_UNIT_SIZE == 8) {
324         *s->code_ptr++ = v;
325     } else {
326         tcg_insn_unit *p = s->code_ptr;
327         memcpy(p, &v, sizeof(v));
328         s->code_ptr = p + (8 / TCG_TARGET_INSN_UNIT_SIZE);
329     }
330 }
331 
332 static __attribute__((unused)) inline void tcg_patch64(tcg_insn_unit *p,
333                                                        uint64_t v)
334 {
335     if (TCG_TARGET_INSN_UNIT_SIZE == 8) {
336         *p = v;
337     } else {
338         memcpy(p, &v, sizeof(v));
339     }
340 }
341 #endif
342 
343 /* label relocation processing */
344 
345 static void tcg_out_reloc(TCGContext *s, tcg_insn_unit *code_ptr, int type,
346                           TCGLabel *l, intptr_t addend)
347 {
348     TCGRelocation *r = tcg_malloc(sizeof(TCGRelocation));
349 
350     r->type = type;
351     r->ptr = code_ptr;
352     r->addend = addend;
353     QSIMPLEQ_INSERT_TAIL(&l->relocs, r, next);
354 }
355 
356 static void tcg_out_label(TCGContext *s, TCGLabel *l)
357 {
358     tcg_debug_assert(!l->has_value);
359     l->has_value = 1;
360     l->u.value_ptr = tcg_splitwx_to_rx(s->code_ptr);
361 }
362 
363 TCGLabel *gen_new_label(void)
364 {
365     TCGContext *s = tcg_ctx;
366     TCGLabel *l = tcg_malloc(sizeof(TCGLabel));
367 
368     memset(l, 0, sizeof(TCGLabel));
369     l->id = s->nb_labels++;
370     QSIMPLEQ_INIT(&l->branches);
371     QSIMPLEQ_INIT(&l->relocs);
372 
373     QSIMPLEQ_INSERT_TAIL(&s->labels, l, next);
374 
375     return l;
376 }
377 
378 static bool tcg_resolve_relocs(TCGContext *s)
379 {
380     TCGLabel *l;
381 
382     QSIMPLEQ_FOREACH(l, &s->labels, next) {
383         TCGRelocation *r;
384         uintptr_t value = l->u.value;
385 
386         QSIMPLEQ_FOREACH(r, &l->relocs, next) {
387             if (!patch_reloc(r->ptr, r->type, value, r->addend)) {
388                 return false;
389             }
390         }
391     }
392     return true;
393 }
394 
395 static void set_jmp_reset_offset(TCGContext *s, int which)
396 {
397     /*
398      * We will check for overflow at the end of the opcode loop in
399      * tcg_gen_code, where we bound tcg_current_code_size to UINT16_MAX.
400      */
401     s->gen_tb->jmp_reset_offset[which] = tcg_current_code_size(s);
402 }
403 
404 static void G_GNUC_UNUSED set_jmp_insn_offset(TCGContext *s, int which)
405 {
406     /*
407      * We will check for overflow at the end of the opcode loop in
408      * tcg_gen_code, where we bound tcg_current_code_size to UINT16_MAX.
409      */
410     s->gen_tb->jmp_insn_offset[which] = tcg_current_code_size(s);
411 }
412 
413 static uintptr_t G_GNUC_UNUSED get_jmp_target_addr(TCGContext *s, int which)
414 {
415     /*
416      * Return the read-execute version of the pointer, for the benefit
417      * of any pc-relative addressing mode.
418      */
419     return (uintptr_t)tcg_splitwx_to_rx(&s->gen_tb->jmp_target_addr[which]);
420 }
421 
422 static int __attribute__((unused))
423 tlb_mask_table_ofs(TCGContext *s, int which)
424 {
425     return (offsetof(CPUNegativeOffsetState, tlb.f[which]) -
426             sizeof(CPUNegativeOffsetState));
427 }
428 
429 /* Signal overflow, starting over with fewer guest insns. */
430 static G_NORETURN
431 void tcg_raise_tb_overflow(TCGContext *s)
432 {
433     siglongjmp(s->jmp_trans, -2);
434 }
435 
436 /*
437  * Used by tcg_out_movext{1,2} to hold the arguments for tcg_out_movext.
438  * By the time we arrive at tcg_out_movext1, @dst is always a TCGReg.
439  *
440  * However, tcg_out_helper_load_slots reuses this field to hold an
441  * argument slot number (which may designate a argument register or an
442  * argument stack slot), converting to TCGReg once all arguments that
443  * are destined for the stack are processed.
444  */
445 typedef struct TCGMovExtend {
446     unsigned dst;
447     TCGReg src;
448     TCGType dst_type;
449     TCGType src_type;
450     MemOp src_ext;
451 } TCGMovExtend;
452 
453 /**
454  * tcg_out_movext -- move and extend
455  * @s: tcg context
456  * @dst_type: integral type for destination
457  * @dst: destination register
458  * @src_type: integral type for source
459  * @src_ext: extension to apply to source
460  * @src: source register
461  *
462  * Move or extend @src into @dst, depending on @src_ext and the types.
463  */
464 static void tcg_out_movext(TCGContext *s, TCGType dst_type, TCGReg dst,
465                            TCGType src_type, MemOp src_ext, TCGReg src)
466 {
467     switch (src_ext) {
468     case MO_UB:
469         tcg_out_ext8u(s, dst, src);
470         break;
471     case MO_SB:
472         tcg_out_ext8s(s, dst_type, dst, src);
473         break;
474     case MO_UW:
475         tcg_out_ext16u(s, dst, src);
476         break;
477     case MO_SW:
478         tcg_out_ext16s(s, dst_type, dst, src);
479         break;
480     case MO_UL:
481     case MO_SL:
482         if (dst_type == TCG_TYPE_I32) {
483             if (src_type == TCG_TYPE_I32) {
484                 tcg_out_mov(s, TCG_TYPE_I32, dst, src);
485             } else {
486                 tcg_out_extrl_i64_i32(s, dst, src);
487             }
488         } else if (src_type == TCG_TYPE_I32) {
489             if (src_ext & MO_SIGN) {
490                 tcg_out_exts_i32_i64(s, dst, src);
491             } else {
492                 tcg_out_extu_i32_i64(s, dst, src);
493             }
494         } else {
495             if (src_ext & MO_SIGN) {
496                 tcg_out_ext32s(s, dst, src);
497             } else {
498                 tcg_out_ext32u(s, dst, src);
499             }
500         }
501         break;
502     case MO_UQ:
503         tcg_debug_assert(TCG_TARGET_REG_BITS == 64);
504         if (dst_type == TCG_TYPE_I32) {
505             tcg_out_extrl_i64_i32(s, dst, src);
506         } else {
507             tcg_out_mov(s, TCG_TYPE_I64, dst, src);
508         }
509         break;
510     default:
511         g_assert_not_reached();
512     }
513 }
514 
515 /* Minor variations on a theme, using a structure. */
516 static void tcg_out_movext1_new_src(TCGContext *s, const TCGMovExtend *i,
517                                     TCGReg src)
518 {
519     tcg_out_movext(s, i->dst_type, i->dst, i->src_type, i->src_ext, src);
520 }
521 
522 static void tcg_out_movext1(TCGContext *s, const TCGMovExtend *i)
523 {
524     tcg_out_movext1_new_src(s, i, i->src);
525 }
526 
527 /**
528  * tcg_out_movext2 -- move and extend two pair
529  * @s: tcg context
530  * @i1: first move description
531  * @i2: second move description
532  * @scratch: temporary register, or -1 for none
533  *
534  * As tcg_out_movext, for both @i1 and @i2, caring for overlap
535  * between the sources and destinations.
536  */
537 
538 static void tcg_out_movext2(TCGContext *s, const TCGMovExtend *i1,
539                             const TCGMovExtend *i2, int scratch)
540 {
541     TCGReg src1 = i1->src;
542     TCGReg src2 = i2->src;
543 
544     if (i1->dst != src2) {
545         tcg_out_movext1(s, i1);
546         tcg_out_movext1(s, i2);
547         return;
548     }
549     if (i2->dst == src1) {
550         TCGType src1_type = i1->src_type;
551         TCGType src2_type = i2->src_type;
552 
553         if (tcg_out_xchg(s, MAX(src1_type, src2_type), src1, src2)) {
554             /* The data is now in the correct registers, now extend. */
555             src1 = i2->src;
556             src2 = i1->src;
557         } else {
558             tcg_debug_assert(scratch >= 0);
559             tcg_out_mov(s, src1_type, scratch, src1);
560             src1 = scratch;
561         }
562     }
563     tcg_out_movext1_new_src(s, i2, src2);
564     tcg_out_movext1_new_src(s, i1, src1);
565 }
566 
567 /**
568  * tcg_out_movext3 -- move and extend three pair
569  * @s: tcg context
570  * @i1: first move description
571  * @i2: second move description
572  * @i3: third move description
573  * @scratch: temporary register, or -1 for none
574  *
575  * As tcg_out_movext, for all of @i1, @i2 and @i3, caring for overlap
576  * between the sources and destinations.
577  */
578 
579 static void tcg_out_movext3(TCGContext *s, const TCGMovExtend *i1,
580                             const TCGMovExtend *i2, const TCGMovExtend *i3,
581                             int scratch)
582 {
583     TCGReg src1 = i1->src;
584     TCGReg src2 = i2->src;
585     TCGReg src3 = i3->src;
586 
587     if (i1->dst != src2 && i1->dst != src3) {
588         tcg_out_movext1(s, i1);
589         tcg_out_movext2(s, i2, i3, scratch);
590         return;
591     }
592     if (i2->dst != src1 && i2->dst != src3) {
593         tcg_out_movext1(s, i2);
594         tcg_out_movext2(s, i1, i3, scratch);
595         return;
596     }
597     if (i3->dst != src1 && i3->dst != src2) {
598         tcg_out_movext1(s, i3);
599         tcg_out_movext2(s, i1, i2, scratch);
600         return;
601     }
602 
603     /*
604      * There is a cycle.  Since there are only 3 nodes, the cycle is
605      * either "clockwise" or "anti-clockwise", and can be solved with
606      * a single scratch or two xchg.
607      */
608     if (i1->dst == src2 && i2->dst == src3 && i3->dst == src1) {
609         /* "Clockwise" */
610         if (tcg_out_xchg(s, MAX(i1->src_type, i2->src_type), src1, src2)) {
611             tcg_out_xchg(s, MAX(i2->src_type, i3->src_type), src2, src3);
612             /* The data is now in the correct registers, now extend. */
613             tcg_out_movext1_new_src(s, i1, i1->dst);
614             tcg_out_movext1_new_src(s, i2, i2->dst);
615             tcg_out_movext1_new_src(s, i3, i3->dst);
616         } else {
617             tcg_debug_assert(scratch >= 0);
618             tcg_out_mov(s, i1->src_type, scratch, src1);
619             tcg_out_movext1(s, i3);
620             tcg_out_movext1(s, i2);
621             tcg_out_movext1_new_src(s, i1, scratch);
622         }
623     } else if (i1->dst == src3 && i2->dst == src1 && i3->dst == src2) {
624         /* "Anti-clockwise" */
625         if (tcg_out_xchg(s, MAX(i2->src_type, i3->src_type), src2, src3)) {
626             tcg_out_xchg(s, MAX(i1->src_type, i2->src_type), src1, src2);
627             /* The data is now in the correct registers, now extend. */
628             tcg_out_movext1_new_src(s, i1, i1->dst);
629             tcg_out_movext1_new_src(s, i2, i2->dst);
630             tcg_out_movext1_new_src(s, i3, i3->dst);
631         } else {
632             tcg_debug_assert(scratch >= 0);
633             tcg_out_mov(s, i1->src_type, scratch, src1);
634             tcg_out_movext1(s, i2);
635             tcg_out_movext1(s, i3);
636             tcg_out_movext1_new_src(s, i1, scratch);
637         }
638     } else {
639         g_assert_not_reached();
640     }
641 }
642 
643 /*
644  * Allocate a new TCGLabelQemuLdst entry.
645  */
646 
647 __attribute__((unused))
648 static TCGLabelQemuLdst *new_ldst_label(TCGContext *s)
649 {
650     TCGLabelQemuLdst *l = tcg_malloc(sizeof(*l));
651 
652     memset(l, 0, sizeof(*l));
653     QSIMPLEQ_INSERT_TAIL(&s->ldst_labels, l, next);
654 
655     return l;
656 }
657 
658 /*
659  * Allocate new constant pool entries.
660  */
661 
662 typedef struct TCGLabelPoolData {
663     struct TCGLabelPoolData *next;
664     tcg_insn_unit *label;
665     intptr_t addend;
666     int rtype;
667     unsigned nlong;
668     tcg_target_ulong data[];
669 } TCGLabelPoolData;
670 
671 static TCGLabelPoolData *new_pool_alloc(TCGContext *s, int nlong, int rtype,
672                                         tcg_insn_unit *label, intptr_t addend)
673 {
674     TCGLabelPoolData *n = tcg_malloc(sizeof(TCGLabelPoolData)
675                                      + sizeof(tcg_target_ulong) * nlong);
676 
677     n->label = label;
678     n->addend = addend;
679     n->rtype = rtype;
680     n->nlong = nlong;
681     return n;
682 }
683 
684 static void new_pool_insert(TCGContext *s, TCGLabelPoolData *n)
685 {
686     TCGLabelPoolData *i, **pp;
687     int nlong = n->nlong;
688 
689     /* Insertion sort on the pool.  */
690     for (pp = &s->pool_labels; (i = *pp) != NULL; pp = &i->next) {
691         if (nlong > i->nlong) {
692             break;
693         }
694         if (nlong < i->nlong) {
695             continue;
696         }
697         if (memcmp(n->data, i->data, sizeof(tcg_target_ulong) * nlong) >= 0) {
698             break;
699         }
700     }
701     n->next = *pp;
702     *pp = n;
703 }
704 
705 /* The "usual" for generic integer code.  */
706 __attribute__((unused))
707 static void new_pool_label(TCGContext *s, tcg_target_ulong d, int rtype,
708                            tcg_insn_unit *label, intptr_t addend)
709 {
710     TCGLabelPoolData *n = new_pool_alloc(s, 1, rtype, label, addend);
711     n->data[0] = d;
712     new_pool_insert(s, n);
713 }
714 
715 /* For v64 or v128, depending on the host.  */
716 __attribute__((unused))
717 static void new_pool_l2(TCGContext *s, int rtype, tcg_insn_unit *label,
718                         intptr_t addend, tcg_target_ulong d0,
719                         tcg_target_ulong d1)
720 {
721     TCGLabelPoolData *n = new_pool_alloc(s, 2, rtype, label, addend);
722     n->data[0] = d0;
723     n->data[1] = d1;
724     new_pool_insert(s, n);
725 }
726 
727 /* For v128 or v256, depending on the host.  */
728 __attribute__((unused))
729 static void new_pool_l4(TCGContext *s, int rtype, tcg_insn_unit *label,
730                         intptr_t addend, tcg_target_ulong d0,
731                         tcg_target_ulong d1, tcg_target_ulong d2,
732                         tcg_target_ulong d3)
733 {
734     TCGLabelPoolData *n = new_pool_alloc(s, 4, rtype, label, addend);
735     n->data[0] = d0;
736     n->data[1] = d1;
737     n->data[2] = d2;
738     n->data[3] = d3;
739     new_pool_insert(s, n);
740 }
741 
742 /* For v256, for 32-bit host.  */
743 __attribute__((unused))
744 static void new_pool_l8(TCGContext *s, int rtype, tcg_insn_unit *label,
745                         intptr_t addend, tcg_target_ulong d0,
746                         tcg_target_ulong d1, tcg_target_ulong d2,
747                         tcg_target_ulong d3, tcg_target_ulong d4,
748                         tcg_target_ulong d5, tcg_target_ulong d6,
749                         tcg_target_ulong d7)
750 {
751     TCGLabelPoolData *n = new_pool_alloc(s, 8, rtype, label, addend);
752     n->data[0] = d0;
753     n->data[1] = d1;
754     n->data[2] = d2;
755     n->data[3] = d3;
756     n->data[4] = d4;
757     n->data[5] = d5;
758     n->data[6] = d6;
759     n->data[7] = d7;
760     new_pool_insert(s, n);
761 }
762 
763 /*
764  * Generate TB finalization at the end of block
765  */
766 
767 static int tcg_out_ldst_finalize(TCGContext *s)
768 {
769     TCGLabelQemuLdst *lb;
770 
771     /* qemu_ld/st slow paths */
772     QSIMPLEQ_FOREACH(lb, &s->ldst_labels, next) {
773         if (lb->is_ld
774             ? !tcg_out_qemu_ld_slow_path(s, lb)
775             : !tcg_out_qemu_st_slow_path(s, lb)) {
776             return -2;
777         }
778 
779         /*
780          * Test for (pending) buffer overflow.  The assumption is that any
781          * one operation beginning below the high water mark cannot overrun
782          * the buffer completely.  Thus we can test for overflow after
783          * generating code without having to check during generation.
784          */
785         if (unlikely((void *)s->code_ptr > s->code_gen_highwater)) {
786             return -1;
787         }
788     }
789     return 0;
790 }
791 
792 static int tcg_out_pool_finalize(TCGContext *s)
793 {
794     TCGLabelPoolData *p = s->pool_labels;
795     TCGLabelPoolData *l = NULL;
796     void *a;
797 
798     if (p == NULL) {
799         return 0;
800     }
801 
802     /*
803      * ??? Round up to qemu_icache_linesize, but then do not round
804      * again when allocating the next TranslationBlock structure.
805      */
806     a = (void *)ROUND_UP((uintptr_t)s->code_ptr,
807                          sizeof(tcg_target_ulong) * p->nlong);
808     tcg_out_nop_fill(s->code_ptr, (tcg_insn_unit *)a - s->code_ptr);
809     s->data_gen_ptr = a;
810 
811     for (; p != NULL; p = p->next) {
812         size_t size = sizeof(tcg_target_ulong) * p->nlong;
813         uintptr_t value;
814 
815         if (!l || l->nlong != p->nlong || memcmp(l->data, p->data, size)) {
816             if (unlikely(a > s->code_gen_highwater)) {
817                 return -1;
818             }
819             memcpy(a, p->data, size);
820             a += size;
821             l = p;
822         }
823 
824         value = (uintptr_t)tcg_splitwx_to_rx(a) - size;
825         if (!patch_reloc(p->label, p->rtype, value, p->addend)) {
826             return -2;
827         }
828     }
829 
830     s->code_ptr = a;
831     return 0;
832 }
833 
834 #define C_PFX1(P, A)                    P##A
835 #define C_PFX2(P, A, B)                 P##A##_##B
836 #define C_PFX3(P, A, B, C)              P##A##_##B##_##C
837 #define C_PFX4(P, A, B, C, D)           P##A##_##B##_##C##_##D
838 #define C_PFX5(P, A, B, C, D, E)        P##A##_##B##_##C##_##D##_##E
839 #define C_PFX6(P, A, B, C, D, E, F)     P##A##_##B##_##C##_##D##_##E##_##F
840 
841 /* Define an enumeration for the various combinations. */
842 
843 #define C_O0_I1(I1)                     C_PFX1(c_o0_i1_, I1),
844 #define C_O0_I2(I1, I2)                 C_PFX2(c_o0_i2_, I1, I2),
845 #define C_O0_I3(I1, I2, I3)             C_PFX3(c_o0_i3_, I1, I2, I3),
846 #define C_O0_I4(I1, I2, I3, I4)         C_PFX4(c_o0_i4_, I1, I2, I3, I4),
847 
848 #define C_O1_I1(O1, I1)                 C_PFX2(c_o1_i1_, O1, I1),
849 #define C_O1_I2(O1, I1, I2)             C_PFX3(c_o1_i2_, O1, I1, I2),
850 #define C_O1_I3(O1, I1, I2, I3)         C_PFX4(c_o1_i3_, O1, I1, I2, I3),
851 #define C_O1_I4(O1, I1, I2, I3, I4)     C_PFX5(c_o1_i4_, O1, I1, I2, I3, I4),
852 
853 #define C_N1_I2(O1, I1, I2)             C_PFX3(c_n1_i2_, O1, I1, I2),
854 #define C_N1O1_I1(O1, O2, I1)           C_PFX3(c_n1o1_i1_, O1, O2, I1),
855 #define C_N2_I1(O1, O2, I1)             C_PFX3(c_n2_i1_, O1, O2, I1),
856 
857 #define C_O2_I1(O1, O2, I1)             C_PFX3(c_o2_i1_, O1, O2, I1),
858 #define C_O2_I2(O1, O2, I1, I2)         C_PFX4(c_o2_i2_, O1, O2, I1, I2),
859 #define C_O2_I3(O1, O2, I1, I2, I3)     C_PFX5(c_o2_i3_, O1, O2, I1, I2, I3),
860 #define C_O2_I4(O1, O2, I1, I2, I3, I4) C_PFX6(c_o2_i4_, O1, O2, I1, I2, I3, I4),
861 #define C_N1_O1_I4(O1, O2, I1, I2, I3, I4) C_PFX6(c_n1_o1_i4_, O1, O2, I1, I2, I3, I4),
862 
863 typedef enum {
864     C_Dynamic = -2,
865     C_NotImplemented = -1,
866 #include "tcg-target-con-set.h"
867 } TCGConstraintSetIndex;
868 
869 static TCGConstraintSetIndex tcg_target_op_def(TCGOpcode, TCGType, unsigned);
870 
871 #undef C_O0_I1
872 #undef C_O0_I2
873 #undef C_O0_I3
874 #undef C_O0_I4
875 #undef C_O1_I1
876 #undef C_O1_I2
877 #undef C_O1_I3
878 #undef C_O1_I4
879 #undef C_N1_I2
880 #undef C_N1O1_I1
881 #undef C_N2_I1
882 #undef C_O2_I1
883 #undef C_O2_I2
884 #undef C_O2_I3
885 #undef C_O2_I4
886 #undef C_N1_O1_I4
887 
888 /* Put all of the constraint sets into an array, indexed by the enum. */
889 
890 typedef struct TCGConstraintSet {
891     uint8_t nb_oargs, nb_iargs;
892     const char *args_ct_str[TCG_MAX_OP_ARGS];
893 } TCGConstraintSet;
894 
895 #define C_O0_I1(I1)                     { 0, 1, { #I1 } },
896 #define C_O0_I2(I1, I2)                 { 0, 2, { #I1, #I2 } },
897 #define C_O0_I3(I1, I2, I3)             { 0, 3, { #I1, #I2, #I3 } },
898 #define C_O0_I4(I1, I2, I3, I4)         { 0, 4, { #I1, #I2, #I3, #I4 } },
899 
900 #define C_O1_I1(O1, I1)                 { 1, 1, { #O1, #I1 } },
901 #define C_O1_I2(O1, I1, I2)             { 1, 2, { #O1, #I1, #I2 } },
902 #define C_O1_I3(O1, I1, I2, I3)         { 1, 3, { #O1, #I1, #I2, #I3 } },
903 #define C_O1_I4(O1, I1, I2, I3, I4)     { 1, 4, { #O1, #I1, #I2, #I3, #I4 } },
904 
905 #define C_N1_I2(O1, I1, I2)             { 1, 2, { "&" #O1, #I1, #I2 } },
906 #define C_N1O1_I1(O1, O2, I1)           { 2, 1, { "&" #O1, #O2, #I1 } },
907 #define C_N2_I1(O1, O2, I1)             { 2, 1, { "&" #O1, "&" #O2, #I1 } },
908 
909 #define C_O2_I1(O1, O2, I1)             { 2, 1, { #O1, #O2, #I1 } },
910 #define C_O2_I2(O1, O2, I1, I2)         { 2, 2, { #O1, #O2, #I1, #I2 } },
911 #define C_O2_I3(O1, O2, I1, I2, I3)     { 2, 3, { #O1, #O2, #I1, #I2, #I3 } },
912 #define C_O2_I4(O1, O2, I1, I2, I3, I4) { 2, 4, { #O1, #O2, #I1, #I2, #I3, #I4 } },
913 #define C_N1_O1_I4(O1, O2, I1, I2, I3, I4) { 2, 4, { "&" #O1, #O2, #I1, #I2, #I3, #I4 } },
914 
915 static const TCGConstraintSet constraint_sets[] = {
916 #include "tcg-target-con-set.h"
917 };
918 
919 #undef C_O0_I1
920 #undef C_O0_I2
921 #undef C_O0_I3
922 #undef C_O0_I4
923 #undef C_O1_I1
924 #undef C_O1_I2
925 #undef C_O1_I3
926 #undef C_O1_I4
927 #undef C_N1_I2
928 #undef C_N1O1_I1
929 #undef C_N2_I1
930 #undef C_O2_I1
931 #undef C_O2_I2
932 #undef C_O2_I3
933 #undef C_O2_I4
934 #undef C_N1_O1_I4
935 
936 /* Expand the enumerator to be returned from tcg_target_op_def(). */
937 
938 #define C_O0_I1(I1)                     C_PFX1(c_o0_i1_, I1)
939 #define C_O0_I2(I1, I2)                 C_PFX2(c_o0_i2_, I1, I2)
940 #define C_O0_I3(I1, I2, I3)             C_PFX3(c_o0_i3_, I1, I2, I3)
941 #define C_O0_I4(I1, I2, I3, I4)         C_PFX4(c_o0_i4_, I1, I2, I3, I4)
942 
943 #define C_O1_I1(O1, I1)                 C_PFX2(c_o1_i1_, O1, I1)
944 #define C_O1_I2(O1, I1, I2)             C_PFX3(c_o1_i2_, O1, I1, I2)
945 #define C_O1_I3(O1, I1, I2, I3)         C_PFX4(c_o1_i3_, O1, I1, I2, I3)
946 #define C_O1_I4(O1, I1, I2, I3, I4)     C_PFX5(c_o1_i4_, O1, I1, I2, I3, I4)
947 
948 #define C_N1_I2(O1, I1, I2)             C_PFX3(c_n1_i2_, O1, I1, I2)
949 #define C_N1O1_I1(O1, O2, I1)           C_PFX3(c_n1o1_i1_, O1, O2, I1)
950 #define C_N2_I1(O1, O2, I1)             C_PFX3(c_n2_i1_, O1, O2, I1)
951 
952 #define C_O2_I1(O1, O2, I1)             C_PFX3(c_o2_i1_, O1, O2, I1)
953 #define C_O2_I2(O1, O2, I1, I2)         C_PFX4(c_o2_i2_, O1, O2, I1, I2)
954 #define C_O2_I3(O1, O2, I1, I2, I3)     C_PFX5(c_o2_i3_, O1, O2, I1, I2, I3)
955 #define C_O2_I4(O1, O2, I1, I2, I3, I4) C_PFX6(c_o2_i4_, O1, O2, I1, I2, I3, I4)
956 #define C_N1_O1_I4(O1, O2, I1, I2, I3, I4) C_PFX6(c_n1_o1_i4_, O1, O2, I1, I2, I3, I4)
957 
958 /*
959  * TCGOutOp is the base class for a set of structures that describe how
960  * to generate code for a given TCGOpcode.
961  *
962  * @static_constraint:
963  *   C_NotImplemented: The TCGOpcode is not supported by the backend.
964  *   C_Dynamic:        Use @dynamic_constraint to select a constraint set
965  *                     based on any of @type, @flags, or host isa.
966  *   Otherwise:        The register allocation constrains for the TCGOpcode.
967  *
968  * Subclasses of TCGOutOp will define a set of output routines that may
969  * be used.  Such routines will often be selected by the set of registers
970  * and constants that come out of register allocation.  The set of
971  * routines that are provided will guide the set of constraints that are
972  * legal.  In particular, assume that tcg_optimize() has done its job in
973  * swapping commutative operands and folding operations for which all
974  * operands are constant.
975  */
976 typedef struct TCGOutOp {
977     TCGConstraintSetIndex static_constraint;
978     TCGConstraintSetIndex (*dynamic_constraint)(TCGType type, unsigned flags);
979 } TCGOutOp;
980 
981 typedef struct TCGOutOpBinary {
982     TCGOutOp base;
983     void (*out_rrr)(TCGContext *s, TCGType type,
984                     TCGReg a0, TCGReg a1, TCGReg a2);
985     void (*out_rri)(TCGContext *s, TCGType type,
986                     TCGReg a0, TCGReg a1, tcg_target_long a2);
987 } TCGOutOpBinary;
988 
989 typedef struct TCGOutOpDivRem {
990     TCGOutOp base;
991     void (*out_rr01r)(TCGContext *s, TCGType type,
992                       TCGReg a0, TCGReg a1, TCGReg a4);
993 } TCGOutOpDivRem;
994 
995 typedef struct TCGOutOpUnary {
996     TCGOutOp base;
997     void (*out_rr)(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1);
998 } TCGOutOpUnary;
999 
1000 typedef struct TCGOutOpSubtract {
1001     TCGOutOp base;
1002     void (*out_rrr)(TCGContext *s, TCGType type,
1003                     TCGReg a0, TCGReg a1, TCGReg a2);
1004     void (*out_rir)(TCGContext *s, TCGType type,
1005                     TCGReg a0, tcg_target_long a1, TCGReg a2);
1006 } TCGOutOpSubtract;
1007 
1008 #include "tcg-target.c.inc"
1009 
1010 #ifndef CONFIG_TCG_INTERPRETER
1011 /* Validate CPUTLBDescFast placement. */
1012 QEMU_BUILD_BUG_ON((int)(offsetof(CPUNegativeOffsetState, tlb.f[0]) -
1013                         sizeof(CPUNegativeOffsetState))
1014                   < MIN_TLB_MASK_TABLE_OFS);
1015 #endif
1016 
1017 /*
1018  * Register V as the TCGOutOp for O.
1019  * This verifies that V is of type T, otherwise give a nice compiler error.
1020  * This prevents trivial mistakes within each arch/tcg-target.c.inc.
1021  */
1022 #define OUTOP(O, T, V)  [O] = _Generic(V, T: &V.base)
1023 
1024 /* Register allocation descriptions for every TCGOpcode. */
1025 static const TCGOutOp * const all_outop[NB_OPS] = {
1026     OUTOP(INDEX_op_add, TCGOutOpBinary, outop_add),
1027     OUTOP(INDEX_op_and, TCGOutOpBinary, outop_and),
1028     OUTOP(INDEX_op_andc, TCGOutOpBinary, outop_andc),
1029     OUTOP(INDEX_op_divs, TCGOutOpBinary, outop_divs),
1030     OUTOP(INDEX_op_divu, TCGOutOpBinary, outop_divu),
1031     OUTOP(INDEX_op_divs2, TCGOutOpDivRem, outop_divs2),
1032     OUTOP(INDEX_op_divu2, TCGOutOpDivRem, outop_divu2),
1033     OUTOP(INDEX_op_eqv, TCGOutOpBinary, outop_eqv),
1034     OUTOP(INDEX_op_mul, TCGOutOpBinary, outop_mul),
1035     OUTOP(INDEX_op_mulsh, TCGOutOpBinary, outop_mulsh),
1036     OUTOP(INDEX_op_muluh, TCGOutOpBinary, outop_muluh),
1037     OUTOP(INDEX_op_nand, TCGOutOpBinary, outop_nand),
1038     OUTOP(INDEX_op_neg, TCGOutOpUnary, outop_neg),
1039     OUTOP(INDEX_op_nor, TCGOutOpBinary, outop_nor),
1040     OUTOP(INDEX_op_not, TCGOutOpUnary, outop_not),
1041     OUTOP(INDEX_op_or, TCGOutOpBinary, outop_or),
1042     OUTOP(INDEX_op_orc, TCGOutOpBinary, outop_orc),
1043     OUTOP(INDEX_op_rems, TCGOutOpBinary, outop_rems),
1044     OUTOP(INDEX_op_remu, TCGOutOpBinary, outop_remu),
1045     OUTOP(INDEX_op_shl, TCGOutOpBinary, outop_shl),
1046     OUTOP(INDEX_op_shr, TCGOutOpBinary, outop_shr),
1047     OUTOP(INDEX_op_sub, TCGOutOpSubtract, outop_sub),
1048     OUTOP(INDEX_op_xor, TCGOutOpBinary, outop_xor),
1049 };
1050 
1051 #undef OUTOP
1052 
1053 /*
1054  * All TCG threads except the parent (i.e. the one that called tcg_context_init
1055  * and registered the target's TCG globals) must register with this function
1056  * before initiating translation.
1057  *
1058  * In user-mode we just point tcg_ctx to tcg_init_ctx. See the documentation
1059  * of tcg_region_init() for the reasoning behind this.
1060  *
1061  * In system-mode each caller registers its context in tcg_ctxs[]. Note that in
1062  * system-mode tcg_ctxs[] does not track tcg_ctx_init, since the initial context
1063  * is not used anymore for translation once this function is called.
1064  *
1065  * Not tracking tcg_init_ctx in tcg_ctxs[] in system-mode keeps code that
1066  * iterates over the array (e.g. tcg_code_size() the same for both system/user
1067  * modes.
1068  */
1069 #ifdef CONFIG_USER_ONLY
1070 void tcg_register_thread(void)
1071 {
1072     tcg_ctx = &tcg_init_ctx;
1073 }
1074 #else
1075 void tcg_register_thread(void)
1076 {
1077     TCGContext *s = g_malloc(sizeof(*s));
1078     unsigned int i, n;
1079 
1080     *s = tcg_init_ctx;
1081 
1082     /* Relink mem_base.  */
1083     for (i = 0, n = tcg_init_ctx.nb_globals; i < n; ++i) {
1084         if (tcg_init_ctx.temps[i].mem_base) {
1085             ptrdiff_t b = tcg_init_ctx.temps[i].mem_base - tcg_init_ctx.temps;
1086             tcg_debug_assert(b >= 0 && b < n);
1087             s->temps[i].mem_base = &s->temps[b];
1088         }
1089     }
1090 
1091     /* Claim an entry in tcg_ctxs */
1092     n = qatomic_fetch_inc(&tcg_cur_ctxs);
1093     g_assert(n < tcg_max_ctxs);
1094     qatomic_set(&tcg_ctxs[n], s);
1095 
1096     if (n > 0) {
1097         tcg_region_initial_alloc(s);
1098     }
1099 
1100     tcg_ctx = s;
1101 }
1102 #endif /* !CONFIG_USER_ONLY */
1103 
1104 /* pool based memory allocation */
1105 void *tcg_malloc_internal(TCGContext *s, int size)
1106 {
1107     TCGPool *p;
1108     int pool_size;
1109 
1110     if (size > TCG_POOL_CHUNK_SIZE) {
1111         /* big malloc: insert a new pool (XXX: could optimize) */
1112         p = g_malloc(sizeof(TCGPool) + size);
1113         p->size = size;
1114         p->next = s->pool_first_large;
1115         s->pool_first_large = p;
1116         return p->data;
1117     } else {
1118         p = s->pool_current;
1119         if (!p) {
1120             p = s->pool_first;
1121             if (!p)
1122                 goto new_pool;
1123         } else {
1124             if (!p->next) {
1125             new_pool:
1126                 pool_size = TCG_POOL_CHUNK_SIZE;
1127                 p = g_malloc(sizeof(TCGPool) + pool_size);
1128                 p->size = pool_size;
1129                 p->next = NULL;
1130                 if (s->pool_current) {
1131                     s->pool_current->next = p;
1132                 } else {
1133                     s->pool_first = p;
1134                 }
1135             } else {
1136                 p = p->next;
1137             }
1138         }
1139     }
1140     s->pool_current = p;
1141     s->pool_cur = p->data + size;
1142     s->pool_end = p->data + p->size;
1143     return p->data;
1144 }
1145 
1146 void tcg_pool_reset(TCGContext *s)
1147 {
1148     TCGPool *p, *t;
1149     for (p = s->pool_first_large; p; p = t) {
1150         t = p->next;
1151         g_free(p);
1152     }
1153     s->pool_first_large = NULL;
1154     s->pool_cur = s->pool_end = NULL;
1155     s->pool_current = NULL;
1156 }
1157 
1158 /*
1159  * Create TCGHelperInfo structures for "tcg/tcg-ldst.h" functions,
1160  * akin to what "exec/helper-tcg.h" does with DEF_HELPER_FLAGS_N.
1161  * We only use these for layout in tcg_out_ld_helper_ret and
1162  * tcg_out_st_helper_args, and share them between several of
1163  * the helpers, with the end result that it's easier to build manually.
1164  */
1165 
1166 #if TCG_TARGET_REG_BITS == 32
1167 # define dh_typecode_ttl  dh_typecode_i32
1168 #else
1169 # define dh_typecode_ttl  dh_typecode_i64
1170 #endif
1171 
1172 static TCGHelperInfo info_helper_ld32_mmu = {
1173     .flags = TCG_CALL_NO_WG,
1174     .typemask = dh_typemask(ttl, 0)  /* return tcg_target_ulong */
1175               | dh_typemask(env, 1)
1176               | dh_typemask(i64, 2)  /* uint64_t addr */
1177               | dh_typemask(i32, 3)  /* unsigned oi */
1178               | dh_typemask(ptr, 4)  /* uintptr_t ra */
1179 };
1180 
1181 static TCGHelperInfo info_helper_ld64_mmu = {
1182     .flags = TCG_CALL_NO_WG,
1183     .typemask = dh_typemask(i64, 0)  /* return uint64_t */
1184               | dh_typemask(env, 1)
1185               | dh_typemask(i64, 2)  /* uint64_t addr */
1186               | dh_typemask(i32, 3)  /* unsigned oi */
1187               | dh_typemask(ptr, 4)  /* uintptr_t ra */
1188 };
1189 
1190 static TCGHelperInfo info_helper_ld128_mmu = {
1191     .flags = TCG_CALL_NO_WG,
1192     .typemask = dh_typemask(i128, 0) /* return Int128 */
1193               | dh_typemask(env, 1)
1194               | dh_typemask(i64, 2)  /* uint64_t addr */
1195               | dh_typemask(i32, 3)  /* unsigned oi */
1196               | dh_typemask(ptr, 4)  /* uintptr_t ra */
1197 };
1198 
1199 static TCGHelperInfo info_helper_st32_mmu = {
1200     .flags = TCG_CALL_NO_WG,
1201     .typemask = dh_typemask(void, 0)
1202               | dh_typemask(env, 1)
1203               | dh_typemask(i64, 2)  /* uint64_t addr */
1204               | dh_typemask(i32, 3)  /* uint32_t data */
1205               | dh_typemask(i32, 4)  /* unsigned oi */
1206               | dh_typemask(ptr, 5)  /* uintptr_t ra */
1207 };
1208 
1209 static TCGHelperInfo info_helper_st64_mmu = {
1210     .flags = TCG_CALL_NO_WG,
1211     .typemask = dh_typemask(void, 0)
1212               | dh_typemask(env, 1)
1213               | dh_typemask(i64, 2)  /* uint64_t addr */
1214               | dh_typemask(i64, 3)  /* uint64_t data */
1215               | dh_typemask(i32, 4)  /* unsigned oi */
1216               | dh_typemask(ptr, 5)  /* uintptr_t ra */
1217 };
1218 
1219 static TCGHelperInfo info_helper_st128_mmu = {
1220     .flags = TCG_CALL_NO_WG,
1221     .typemask = dh_typemask(void, 0)
1222               | dh_typemask(env, 1)
1223               | dh_typemask(i64, 2)  /* uint64_t addr */
1224               | dh_typemask(i128, 3) /* Int128 data */
1225               | dh_typemask(i32, 4)  /* unsigned oi */
1226               | dh_typemask(ptr, 5)  /* uintptr_t ra */
1227 };
1228 
1229 #ifdef CONFIG_TCG_INTERPRETER
1230 static ffi_type *typecode_to_ffi(int argmask)
1231 {
1232     /*
1233      * libffi does not support __int128_t, so we have forced Int128
1234      * to use the structure definition instead of the builtin type.
1235      */
1236     static ffi_type *ffi_type_i128_elements[3] = {
1237         &ffi_type_uint64,
1238         &ffi_type_uint64,
1239         NULL
1240     };
1241     static ffi_type ffi_type_i128 = {
1242         .size = 16,
1243         .alignment = __alignof__(Int128),
1244         .type = FFI_TYPE_STRUCT,
1245         .elements = ffi_type_i128_elements,
1246     };
1247 
1248     switch (argmask) {
1249     case dh_typecode_void:
1250         return &ffi_type_void;
1251     case dh_typecode_i32:
1252         return &ffi_type_uint32;
1253     case dh_typecode_s32:
1254         return &ffi_type_sint32;
1255     case dh_typecode_i64:
1256         return &ffi_type_uint64;
1257     case dh_typecode_s64:
1258         return &ffi_type_sint64;
1259     case dh_typecode_ptr:
1260         return &ffi_type_pointer;
1261     case dh_typecode_i128:
1262         return &ffi_type_i128;
1263     }
1264     g_assert_not_reached();
1265 }
1266 
1267 static ffi_cif *init_ffi_layout(TCGHelperInfo *info)
1268 {
1269     unsigned typemask = info->typemask;
1270     struct {
1271         ffi_cif cif;
1272         ffi_type *args[];
1273     } *ca;
1274     ffi_status status;
1275     int nargs;
1276 
1277     /* Ignoring the return type, find the last non-zero field. */
1278     nargs = 32 - clz32(typemask >> 3);
1279     nargs = DIV_ROUND_UP(nargs, 3);
1280     assert(nargs <= MAX_CALL_IARGS);
1281 
1282     ca = g_malloc0(sizeof(*ca) + nargs * sizeof(ffi_type *));
1283     ca->cif.rtype = typecode_to_ffi(typemask & 7);
1284     ca->cif.nargs = nargs;
1285 
1286     if (nargs != 0) {
1287         ca->cif.arg_types = ca->args;
1288         for (int j = 0; j < nargs; ++j) {
1289             int typecode = extract32(typemask, (j + 1) * 3, 3);
1290             ca->args[j] = typecode_to_ffi(typecode);
1291         }
1292     }
1293 
1294     status = ffi_prep_cif(&ca->cif, FFI_DEFAULT_ABI, nargs,
1295                           ca->cif.rtype, ca->cif.arg_types);
1296     assert(status == FFI_OK);
1297 
1298     return &ca->cif;
1299 }
1300 
1301 #define HELPER_INFO_INIT(I)      (&(I)->cif)
1302 #define HELPER_INFO_INIT_VAL(I)  init_ffi_layout(I)
1303 #else
1304 #define HELPER_INFO_INIT(I)      (&(I)->init)
1305 #define HELPER_INFO_INIT_VAL(I)  1
1306 #endif /* CONFIG_TCG_INTERPRETER */
1307 
1308 static inline bool arg_slot_reg_p(unsigned arg_slot)
1309 {
1310     /*
1311      * Split the sizeof away from the comparison to avoid Werror from
1312      * "unsigned < 0 is always false", when iarg_regs is empty.
1313      */
1314     unsigned nreg = ARRAY_SIZE(tcg_target_call_iarg_regs);
1315     return arg_slot < nreg;
1316 }
1317 
1318 static inline int arg_slot_stk_ofs(unsigned arg_slot)
1319 {
1320     unsigned max = TCG_STATIC_CALL_ARGS_SIZE / sizeof(tcg_target_long);
1321     unsigned stk_slot = arg_slot - ARRAY_SIZE(tcg_target_call_iarg_regs);
1322 
1323     tcg_debug_assert(stk_slot < max);
1324     return TCG_TARGET_CALL_STACK_OFFSET + stk_slot * sizeof(tcg_target_long);
1325 }
1326 
1327 typedef struct TCGCumulativeArgs {
1328     int arg_idx;                /* tcg_gen_callN args[] */
1329     int info_in_idx;            /* TCGHelperInfo in[] */
1330     int arg_slot;               /* regs+stack slot */
1331     int ref_slot;               /* stack slots for references */
1332 } TCGCumulativeArgs;
1333 
1334 static void layout_arg_even(TCGCumulativeArgs *cum)
1335 {
1336     cum->arg_slot += cum->arg_slot & 1;
1337 }
1338 
1339 static void layout_arg_1(TCGCumulativeArgs *cum, TCGHelperInfo *info,
1340                          TCGCallArgumentKind kind)
1341 {
1342     TCGCallArgumentLoc *loc = &info->in[cum->info_in_idx];
1343 
1344     *loc = (TCGCallArgumentLoc){
1345         .kind = kind,
1346         .arg_idx = cum->arg_idx,
1347         .arg_slot = cum->arg_slot,
1348     };
1349     cum->info_in_idx++;
1350     cum->arg_slot++;
1351 }
1352 
1353 static void layout_arg_normal_n(TCGCumulativeArgs *cum,
1354                                 TCGHelperInfo *info, int n)
1355 {
1356     TCGCallArgumentLoc *loc = &info->in[cum->info_in_idx];
1357 
1358     for (int i = 0; i < n; ++i) {
1359         /* Layout all using the same arg_idx, adjusting the subindex. */
1360         loc[i] = (TCGCallArgumentLoc){
1361             .kind = TCG_CALL_ARG_NORMAL,
1362             .arg_idx = cum->arg_idx,
1363             .tmp_subindex = i,
1364             .arg_slot = cum->arg_slot + i,
1365         };
1366     }
1367     cum->info_in_idx += n;
1368     cum->arg_slot += n;
1369 }
1370 
1371 static void layout_arg_by_ref(TCGCumulativeArgs *cum, TCGHelperInfo *info)
1372 {
1373     TCGCallArgumentLoc *loc = &info->in[cum->info_in_idx];
1374     int n = 128 / TCG_TARGET_REG_BITS;
1375 
1376     /* The first subindex carries the pointer. */
1377     layout_arg_1(cum, info, TCG_CALL_ARG_BY_REF);
1378 
1379     /*
1380      * The callee is allowed to clobber memory associated with
1381      * structure pass by-reference.  Therefore we must make copies.
1382      * Allocate space from "ref_slot", which will be adjusted to
1383      * follow the parameters on the stack.
1384      */
1385     loc[0].ref_slot = cum->ref_slot;
1386 
1387     /*
1388      * Subsequent words also go into the reference slot, but
1389      * do not accumulate into the regular arguments.
1390      */
1391     for (int i = 1; i < n; ++i) {
1392         loc[i] = (TCGCallArgumentLoc){
1393             .kind = TCG_CALL_ARG_BY_REF_N,
1394             .arg_idx = cum->arg_idx,
1395             .tmp_subindex = i,
1396             .ref_slot = cum->ref_slot + i,
1397         };
1398     }
1399     cum->info_in_idx += n - 1;  /* i=0 accounted for in layout_arg_1 */
1400     cum->ref_slot += n;
1401 }
1402 
1403 static void init_call_layout(TCGHelperInfo *info)
1404 {
1405     int max_reg_slots = ARRAY_SIZE(tcg_target_call_iarg_regs);
1406     int max_stk_slots = TCG_STATIC_CALL_ARGS_SIZE / sizeof(tcg_target_long);
1407     unsigned typemask = info->typemask;
1408     unsigned typecode;
1409     TCGCumulativeArgs cum = { };
1410 
1411     /*
1412      * Parse and place any function return value.
1413      */
1414     typecode = typemask & 7;
1415     switch (typecode) {
1416     case dh_typecode_void:
1417         info->nr_out = 0;
1418         break;
1419     case dh_typecode_i32:
1420     case dh_typecode_s32:
1421     case dh_typecode_ptr:
1422         info->nr_out = 1;
1423         info->out_kind = TCG_CALL_RET_NORMAL;
1424         break;
1425     case dh_typecode_i64:
1426     case dh_typecode_s64:
1427         info->nr_out = 64 / TCG_TARGET_REG_BITS;
1428         info->out_kind = TCG_CALL_RET_NORMAL;
1429         /* Query the last register now to trigger any assert early. */
1430         tcg_target_call_oarg_reg(info->out_kind, info->nr_out - 1);
1431         break;
1432     case dh_typecode_i128:
1433         info->nr_out = 128 / TCG_TARGET_REG_BITS;
1434         info->out_kind = TCG_TARGET_CALL_RET_I128;
1435         switch (TCG_TARGET_CALL_RET_I128) {
1436         case TCG_CALL_RET_NORMAL:
1437             /* Query the last register now to trigger any assert early. */
1438             tcg_target_call_oarg_reg(info->out_kind, info->nr_out - 1);
1439             break;
1440         case TCG_CALL_RET_BY_VEC:
1441             /* Query the single register now to trigger any assert early. */
1442             tcg_target_call_oarg_reg(TCG_CALL_RET_BY_VEC, 0);
1443             break;
1444         case TCG_CALL_RET_BY_REF:
1445             /*
1446              * Allocate the first argument to the output.
1447              * We don't need to store this anywhere, just make it
1448              * unavailable for use in the input loop below.
1449              */
1450             cum.arg_slot = 1;
1451             break;
1452         default:
1453             qemu_build_not_reached();
1454         }
1455         break;
1456     default:
1457         g_assert_not_reached();
1458     }
1459 
1460     /*
1461      * Parse and place function arguments.
1462      */
1463     for (typemask >>= 3; typemask; typemask >>= 3, cum.arg_idx++) {
1464         TCGCallArgumentKind kind;
1465         TCGType type;
1466 
1467         typecode = typemask & 7;
1468         switch (typecode) {
1469         case dh_typecode_i32:
1470         case dh_typecode_s32:
1471             type = TCG_TYPE_I32;
1472             break;
1473         case dh_typecode_i64:
1474         case dh_typecode_s64:
1475             type = TCG_TYPE_I64;
1476             break;
1477         case dh_typecode_ptr:
1478             type = TCG_TYPE_PTR;
1479             break;
1480         case dh_typecode_i128:
1481             type = TCG_TYPE_I128;
1482             break;
1483         default:
1484             g_assert_not_reached();
1485         }
1486 
1487         switch (type) {
1488         case TCG_TYPE_I32:
1489             switch (TCG_TARGET_CALL_ARG_I32) {
1490             case TCG_CALL_ARG_EVEN:
1491                 layout_arg_even(&cum);
1492                 /* fall through */
1493             case TCG_CALL_ARG_NORMAL:
1494                 layout_arg_1(&cum, info, TCG_CALL_ARG_NORMAL);
1495                 break;
1496             case TCG_CALL_ARG_EXTEND:
1497                 kind = TCG_CALL_ARG_EXTEND_U + (typecode & 1);
1498                 layout_arg_1(&cum, info, kind);
1499                 break;
1500             default:
1501                 qemu_build_not_reached();
1502             }
1503             break;
1504 
1505         case TCG_TYPE_I64:
1506             switch (TCG_TARGET_CALL_ARG_I64) {
1507             case TCG_CALL_ARG_EVEN:
1508                 layout_arg_even(&cum);
1509                 /* fall through */
1510             case TCG_CALL_ARG_NORMAL:
1511                 if (TCG_TARGET_REG_BITS == 32) {
1512                     layout_arg_normal_n(&cum, info, 2);
1513                 } else {
1514                     layout_arg_1(&cum, info, TCG_CALL_ARG_NORMAL);
1515                 }
1516                 break;
1517             default:
1518                 qemu_build_not_reached();
1519             }
1520             break;
1521 
1522         case TCG_TYPE_I128:
1523             switch (TCG_TARGET_CALL_ARG_I128) {
1524             case TCG_CALL_ARG_EVEN:
1525                 layout_arg_even(&cum);
1526                 /* fall through */
1527             case TCG_CALL_ARG_NORMAL:
1528                 layout_arg_normal_n(&cum, info, 128 / TCG_TARGET_REG_BITS);
1529                 break;
1530             case TCG_CALL_ARG_BY_REF:
1531                 layout_arg_by_ref(&cum, info);
1532                 break;
1533             default:
1534                 qemu_build_not_reached();
1535             }
1536             break;
1537 
1538         default:
1539             g_assert_not_reached();
1540         }
1541     }
1542     info->nr_in = cum.info_in_idx;
1543 
1544     /* Validate that we didn't overrun the input array. */
1545     assert(cum.info_in_idx <= ARRAY_SIZE(info->in));
1546     /* Validate the backend has enough argument space. */
1547     assert(cum.arg_slot <= max_reg_slots + max_stk_slots);
1548 
1549     /*
1550      * Relocate the "ref_slot" area to the end of the parameters.
1551      * Minimizing this stack offset helps code size for x86,
1552      * which has a signed 8-bit offset encoding.
1553      */
1554     if (cum.ref_slot != 0) {
1555         int ref_base = 0;
1556 
1557         if (cum.arg_slot > max_reg_slots) {
1558             int align = __alignof(Int128) / sizeof(tcg_target_long);
1559 
1560             ref_base = cum.arg_slot - max_reg_slots;
1561             if (align > 1) {
1562                 ref_base = ROUND_UP(ref_base, align);
1563             }
1564         }
1565         assert(ref_base + cum.ref_slot <= max_stk_slots);
1566         ref_base += max_reg_slots;
1567 
1568         if (ref_base != 0) {
1569             for (int i = cum.info_in_idx - 1; i >= 0; --i) {
1570                 TCGCallArgumentLoc *loc = &info->in[i];
1571                 switch (loc->kind) {
1572                 case TCG_CALL_ARG_BY_REF:
1573                 case TCG_CALL_ARG_BY_REF_N:
1574                     loc->ref_slot += ref_base;
1575                     break;
1576                 default:
1577                     break;
1578                 }
1579             }
1580         }
1581     }
1582 }
1583 
1584 static int indirect_reg_alloc_order[ARRAY_SIZE(tcg_target_reg_alloc_order)];
1585 static void process_constraint_sets(void);
1586 static TCGTemp *tcg_global_reg_new_internal(TCGContext *s, TCGType type,
1587                                             TCGReg reg, const char *name);
1588 
1589 static void tcg_context_init(unsigned max_threads)
1590 {
1591     TCGContext *s = &tcg_init_ctx;
1592     int n, i;
1593     TCGTemp *ts;
1594 
1595     memset(s, 0, sizeof(*s));
1596     s->nb_globals = 0;
1597 
1598     init_call_layout(&info_helper_ld32_mmu);
1599     init_call_layout(&info_helper_ld64_mmu);
1600     init_call_layout(&info_helper_ld128_mmu);
1601     init_call_layout(&info_helper_st32_mmu);
1602     init_call_layout(&info_helper_st64_mmu);
1603     init_call_layout(&info_helper_st128_mmu);
1604 
1605     tcg_target_init(s);
1606     process_constraint_sets();
1607 
1608     /* Reverse the order of the saved registers, assuming they're all at
1609        the start of tcg_target_reg_alloc_order.  */
1610     for (n = 0; n < ARRAY_SIZE(tcg_target_reg_alloc_order); ++n) {
1611         int r = tcg_target_reg_alloc_order[n];
1612         if (tcg_regset_test_reg(tcg_target_call_clobber_regs, r)) {
1613             break;
1614         }
1615     }
1616     for (i = 0; i < n; ++i) {
1617         indirect_reg_alloc_order[i] = tcg_target_reg_alloc_order[n - 1 - i];
1618     }
1619     for (; i < ARRAY_SIZE(tcg_target_reg_alloc_order); ++i) {
1620         indirect_reg_alloc_order[i] = tcg_target_reg_alloc_order[i];
1621     }
1622 
1623     tcg_ctx = s;
1624     /*
1625      * In user-mode we simply share the init context among threads, since we
1626      * use a single region. See the documentation tcg_region_init() for the
1627      * reasoning behind this.
1628      * In system-mode we will have at most max_threads TCG threads.
1629      */
1630 #ifdef CONFIG_USER_ONLY
1631     tcg_ctxs = &tcg_ctx;
1632     tcg_cur_ctxs = 1;
1633     tcg_max_ctxs = 1;
1634 #else
1635     tcg_max_ctxs = max_threads;
1636     tcg_ctxs = g_new0(TCGContext *, max_threads);
1637 #endif
1638 
1639     tcg_debug_assert(!tcg_regset_test_reg(s->reserved_regs, TCG_AREG0));
1640     ts = tcg_global_reg_new_internal(s, TCG_TYPE_PTR, TCG_AREG0, "env");
1641     tcg_env = temp_tcgv_ptr(ts);
1642 }
1643 
1644 void tcg_init(size_t tb_size, int splitwx, unsigned max_threads)
1645 {
1646     tcg_context_init(max_threads);
1647     tcg_region_init(tb_size, splitwx, max_threads);
1648 }
1649 
1650 /*
1651  * Allocate TBs right before their corresponding translated code, making
1652  * sure that TBs and code are on different cache lines.
1653  */
1654 TranslationBlock *tcg_tb_alloc(TCGContext *s)
1655 {
1656     uintptr_t align = qemu_icache_linesize;
1657     TranslationBlock *tb;
1658     void *next;
1659 
1660  retry:
1661     tb = (void *)ROUND_UP((uintptr_t)s->code_gen_ptr, align);
1662     next = (void *)ROUND_UP((uintptr_t)(tb + 1), align);
1663 
1664     if (unlikely(next > s->code_gen_highwater)) {
1665         if (tcg_region_alloc(s)) {
1666             return NULL;
1667         }
1668         goto retry;
1669     }
1670     qatomic_set(&s->code_gen_ptr, next);
1671     return tb;
1672 }
1673 
1674 void tcg_prologue_init(void)
1675 {
1676     TCGContext *s = tcg_ctx;
1677     size_t prologue_size;
1678 
1679     s->code_ptr = s->code_gen_ptr;
1680     s->code_buf = s->code_gen_ptr;
1681     s->data_gen_ptr = NULL;
1682 
1683 #ifndef CONFIG_TCG_INTERPRETER
1684     tcg_qemu_tb_exec = (tcg_prologue_fn *)tcg_splitwx_to_rx(s->code_ptr);
1685 #endif
1686 
1687     s->pool_labels = NULL;
1688 
1689     qemu_thread_jit_write();
1690     /* Generate the prologue.  */
1691     tcg_target_qemu_prologue(s);
1692 
1693     /* Allow the prologue to put e.g. guest_base into a pool entry.  */
1694     {
1695         int result = tcg_out_pool_finalize(s);
1696         tcg_debug_assert(result == 0);
1697     }
1698 
1699     prologue_size = tcg_current_code_size(s);
1700     perf_report_prologue(s->code_gen_ptr, prologue_size);
1701 
1702 #ifndef CONFIG_TCG_INTERPRETER
1703     flush_idcache_range((uintptr_t)tcg_splitwx_to_rx(s->code_buf),
1704                         (uintptr_t)s->code_buf, prologue_size);
1705 #endif
1706 
1707     if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM)) {
1708         FILE *logfile = qemu_log_trylock();
1709         if (logfile) {
1710             fprintf(logfile, "PROLOGUE: [size=%zu]\n", prologue_size);
1711             if (s->data_gen_ptr) {
1712                 size_t code_size = s->data_gen_ptr - s->code_gen_ptr;
1713                 size_t data_size = prologue_size - code_size;
1714                 size_t i;
1715 
1716                 disas(logfile, s->code_gen_ptr, code_size);
1717 
1718                 for (i = 0; i < data_size; i += sizeof(tcg_target_ulong)) {
1719                     if (sizeof(tcg_target_ulong) == 8) {
1720                         fprintf(logfile,
1721                                 "0x%08" PRIxPTR ":  .quad  0x%016" PRIx64 "\n",
1722                                 (uintptr_t)s->data_gen_ptr + i,
1723                                 *(uint64_t *)(s->data_gen_ptr + i));
1724                     } else {
1725                         fprintf(logfile,
1726                                 "0x%08" PRIxPTR ":  .long  0x%08x\n",
1727                                 (uintptr_t)s->data_gen_ptr + i,
1728                                 *(uint32_t *)(s->data_gen_ptr + i));
1729                     }
1730                 }
1731             } else {
1732                 disas(logfile, s->code_gen_ptr, prologue_size);
1733             }
1734             fprintf(logfile, "\n");
1735             qemu_log_unlock(logfile);
1736         }
1737     }
1738 
1739 #ifndef CONFIG_TCG_INTERPRETER
1740     /*
1741      * Assert that goto_ptr is implemented completely, setting an epilogue.
1742      * For tci, we use NULL as the signal to return from the interpreter,
1743      * so skip this check.
1744      */
1745     tcg_debug_assert(tcg_code_gen_epilogue != NULL);
1746 #endif
1747 
1748     tcg_region_prologue_set(s);
1749 }
1750 
1751 void tcg_func_start(TCGContext *s)
1752 {
1753     tcg_pool_reset(s);
1754     s->nb_temps = s->nb_globals;
1755 
1756     /* No temps have been previously allocated for size or locality.  */
1757     tcg_temp_ebb_reset_freed(s);
1758 
1759     /* No constant temps have been previously allocated. */
1760     for (int i = 0; i < TCG_TYPE_COUNT; ++i) {
1761         if (s->const_table[i]) {
1762             g_hash_table_remove_all(s->const_table[i]);
1763         }
1764     }
1765 
1766     s->nb_ops = 0;
1767     s->nb_labels = 0;
1768     s->current_frame_offset = s->frame_start;
1769 
1770 #ifdef CONFIG_DEBUG_TCG
1771     s->goto_tb_issue_mask = 0;
1772 #endif
1773 
1774     QTAILQ_INIT(&s->ops);
1775     QTAILQ_INIT(&s->free_ops);
1776     s->emit_before_op = NULL;
1777     QSIMPLEQ_INIT(&s->labels);
1778 
1779     tcg_debug_assert(s->addr_type <= TCG_TYPE_REG);
1780     tcg_debug_assert(s->insn_start_words > 0);
1781 }
1782 
1783 static TCGTemp *tcg_temp_alloc(TCGContext *s)
1784 {
1785     int n = s->nb_temps++;
1786 
1787     if (n >= TCG_MAX_TEMPS) {
1788         tcg_raise_tb_overflow(s);
1789     }
1790     return memset(&s->temps[n], 0, sizeof(TCGTemp));
1791 }
1792 
1793 static TCGTemp *tcg_global_alloc(TCGContext *s)
1794 {
1795     TCGTemp *ts;
1796 
1797     tcg_debug_assert(s->nb_globals == s->nb_temps);
1798     tcg_debug_assert(s->nb_globals < TCG_MAX_TEMPS);
1799     s->nb_globals++;
1800     ts = tcg_temp_alloc(s);
1801     ts->kind = TEMP_GLOBAL;
1802 
1803     return ts;
1804 }
1805 
1806 static TCGTemp *tcg_global_reg_new_internal(TCGContext *s, TCGType type,
1807                                             TCGReg reg, const char *name)
1808 {
1809     TCGTemp *ts;
1810 
1811     tcg_debug_assert(TCG_TARGET_REG_BITS == 64 || type == TCG_TYPE_I32);
1812 
1813     ts = tcg_global_alloc(s);
1814     ts->base_type = type;
1815     ts->type = type;
1816     ts->kind = TEMP_FIXED;
1817     ts->reg = reg;
1818     ts->name = name;
1819     tcg_regset_set_reg(s->reserved_regs, reg);
1820 
1821     return ts;
1822 }
1823 
1824 void tcg_set_frame(TCGContext *s, TCGReg reg, intptr_t start, intptr_t size)
1825 {
1826     s->frame_start = start;
1827     s->frame_end = start + size;
1828     s->frame_temp
1829         = tcg_global_reg_new_internal(s, TCG_TYPE_PTR, reg, "_frame");
1830 }
1831 
1832 static TCGTemp *tcg_global_mem_new_internal(TCGv_ptr base, intptr_t offset,
1833                                             const char *name, TCGType type)
1834 {
1835     TCGContext *s = tcg_ctx;
1836     TCGTemp *base_ts = tcgv_ptr_temp(base);
1837     TCGTemp *ts = tcg_global_alloc(s);
1838     int indirect_reg = 0;
1839 
1840     switch (base_ts->kind) {
1841     case TEMP_FIXED:
1842         break;
1843     case TEMP_GLOBAL:
1844         /* We do not support double-indirect registers.  */
1845         tcg_debug_assert(!base_ts->indirect_reg);
1846         base_ts->indirect_base = 1;
1847         s->nb_indirects += (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64
1848                             ? 2 : 1);
1849         indirect_reg = 1;
1850         break;
1851     default:
1852         g_assert_not_reached();
1853     }
1854 
1855     if (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64) {
1856         TCGTemp *ts2 = tcg_global_alloc(s);
1857         char buf[64];
1858 
1859         ts->base_type = TCG_TYPE_I64;
1860         ts->type = TCG_TYPE_I32;
1861         ts->indirect_reg = indirect_reg;
1862         ts->mem_allocated = 1;
1863         ts->mem_base = base_ts;
1864         ts->mem_offset = offset;
1865         pstrcpy(buf, sizeof(buf), name);
1866         pstrcat(buf, sizeof(buf), "_0");
1867         ts->name = strdup(buf);
1868 
1869         tcg_debug_assert(ts2 == ts + 1);
1870         ts2->base_type = TCG_TYPE_I64;
1871         ts2->type = TCG_TYPE_I32;
1872         ts2->indirect_reg = indirect_reg;
1873         ts2->mem_allocated = 1;
1874         ts2->mem_base = base_ts;
1875         ts2->mem_offset = offset + 4;
1876         ts2->temp_subindex = 1;
1877         pstrcpy(buf, sizeof(buf), name);
1878         pstrcat(buf, sizeof(buf), "_1");
1879         ts2->name = strdup(buf);
1880     } else {
1881         ts->base_type = type;
1882         ts->type = type;
1883         ts->indirect_reg = indirect_reg;
1884         ts->mem_allocated = 1;
1885         ts->mem_base = base_ts;
1886         ts->mem_offset = offset;
1887         ts->name = name;
1888     }
1889     return ts;
1890 }
1891 
1892 TCGv_i32 tcg_global_mem_new_i32(TCGv_ptr reg, intptr_t off, const char *name)
1893 {
1894     TCGTemp *ts = tcg_global_mem_new_internal(reg, off, name, TCG_TYPE_I32);
1895     return temp_tcgv_i32(ts);
1896 }
1897 
1898 TCGv_i64 tcg_global_mem_new_i64(TCGv_ptr reg, intptr_t off, const char *name)
1899 {
1900     TCGTemp *ts = tcg_global_mem_new_internal(reg, off, name, TCG_TYPE_I64);
1901     return temp_tcgv_i64(ts);
1902 }
1903 
1904 TCGv_ptr tcg_global_mem_new_ptr(TCGv_ptr reg, intptr_t off, const char *name)
1905 {
1906     TCGTemp *ts = tcg_global_mem_new_internal(reg, off, name, TCG_TYPE_PTR);
1907     return temp_tcgv_ptr(ts);
1908 }
1909 
1910 TCGTemp *tcg_temp_new_internal(TCGType type, TCGTempKind kind)
1911 {
1912     TCGContext *s = tcg_ctx;
1913     TCGTemp *ts;
1914     int n;
1915 
1916     if (kind == TEMP_EBB) {
1917         int idx = find_first_bit(s->free_temps[type].l, TCG_MAX_TEMPS);
1918 
1919         if (idx < TCG_MAX_TEMPS) {
1920             /* There is already an available temp with the right type.  */
1921             clear_bit(idx, s->free_temps[type].l);
1922 
1923             ts = &s->temps[idx];
1924             ts->temp_allocated = 1;
1925             tcg_debug_assert(ts->base_type == type);
1926             tcg_debug_assert(ts->kind == kind);
1927             return ts;
1928         }
1929     } else {
1930         tcg_debug_assert(kind == TEMP_TB);
1931     }
1932 
1933     switch (type) {
1934     case TCG_TYPE_I32:
1935     case TCG_TYPE_V64:
1936     case TCG_TYPE_V128:
1937     case TCG_TYPE_V256:
1938         n = 1;
1939         break;
1940     case TCG_TYPE_I64:
1941         n = 64 / TCG_TARGET_REG_BITS;
1942         break;
1943     case TCG_TYPE_I128:
1944         n = 128 / TCG_TARGET_REG_BITS;
1945         break;
1946     default:
1947         g_assert_not_reached();
1948     }
1949 
1950     ts = tcg_temp_alloc(s);
1951     ts->base_type = type;
1952     ts->temp_allocated = 1;
1953     ts->kind = kind;
1954 
1955     if (n == 1) {
1956         ts->type = type;
1957     } else {
1958         ts->type = TCG_TYPE_REG;
1959 
1960         for (int i = 1; i < n; ++i) {
1961             TCGTemp *ts2 = tcg_temp_alloc(s);
1962 
1963             tcg_debug_assert(ts2 == ts + i);
1964             ts2->base_type = type;
1965             ts2->type = TCG_TYPE_REG;
1966             ts2->temp_allocated = 1;
1967             ts2->temp_subindex = i;
1968             ts2->kind = kind;
1969         }
1970     }
1971     return ts;
1972 }
1973 
1974 TCGv_i32 tcg_temp_new_i32(void)
1975 {
1976     return temp_tcgv_i32(tcg_temp_new_internal(TCG_TYPE_I32, TEMP_TB));
1977 }
1978 
1979 TCGv_i32 tcg_temp_ebb_new_i32(void)
1980 {
1981     return temp_tcgv_i32(tcg_temp_new_internal(TCG_TYPE_I32, TEMP_EBB));
1982 }
1983 
1984 TCGv_i64 tcg_temp_new_i64(void)
1985 {
1986     return temp_tcgv_i64(tcg_temp_new_internal(TCG_TYPE_I64, TEMP_TB));
1987 }
1988 
1989 TCGv_i64 tcg_temp_ebb_new_i64(void)
1990 {
1991     return temp_tcgv_i64(tcg_temp_new_internal(TCG_TYPE_I64, TEMP_EBB));
1992 }
1993 
1994 TCGv_ptr tcg_temp_new_ptr(void)
1995 {
1996     return temp_tcgv_ptr(tcg_temp_new_internal(TCG_TYPE_PTR, TEMP_TB));
1997 }
1998 
1999 TCGv_ptr tcg_temp_ebb_new_ptr(void)
2000 {
2001     return temp_tcgv_ptr(tcg_temp_new_internal(TCG_TYPE_PTR, TEMP_EBB));
2002 }
2003 
2004 TCGv_i128 tcg_temp_new_i128(void)
2005 {
2006     return temp_tcgv_i128(tcg_temp_new_internal(TCG_TYPE_I128, TEMP_TB));
2007 }
2008 
2009 TCGv_i128 tcg_temp_ebb_new_i128(void)
2010 {
2011     return temp_tcgv_i128(tcg_temp_new_internal(TCG_TYPE_I128, TEMP_EBB));
2012 }
2013 
2014 TCGv_vec tcg_temp_new_vec(TCGType type)
2015 {
2016     TCGTemp *t;
2017 
2018 #ifdef CONFIG_DEBUG_TCG
2019     switch (type) {
2020     case TCG_TYPE_V64:
2021         assert(TCG_TARGET_HAS_v64);
2022         break;
2023     case TCG_TYPE_V128:
2024         assert(TCG_TARGET_HAS_v128);
2025         break;
2026     case TCG_TYPE_V256:
2027         assert(TCG_TARGET_HAS_v256);
2028         break;
2029     default:
2030         g_assert_not_reached();
2031     }
2032 #endif
2033 
2034     t = tcg_temp_new_internal(type, TEMP_EBB);
2035     return temp_tcgv_vec(t);
2036 }
2037 
2038 /* Create a new temp of the same type as an existing temp.  */
2039 TCGv_vec tcg_temp_new_vec_matching(TCGv_vec match)
2040 {
2041     TCGTemp *t = tcgv_vec_temp(match);
2042 
2043     tcg_debug_assert(t->temp_allocated != 0);
2044 
2045     t = tcg_temp_new_internal(t->base_type, TEMP_EBB);
2046     return temp_tcgv_vec(t);
2047 }
2048 
2049 void tcg_temp_free_internal(TCGTemp *ts)
2050 {
2051     TCGContext *s = tcg_ctx;
2052 
2053     switch (ts->kind) {
2054     case TEMP_CONST:
2055     case TEMP_TB:
2056         /* Silently ignore free. */
2057         break;
2058     case TEMP_EBB:
2059         tcg_debug_assert(ts->temp_allocated != 0);
2060         ts->temp_allocated = 0;
2061         set_bit(temp_idx(ts), s->free_temps[ts->base_type].l);
2062         break;
2063     default:
2064         /* It never made sense to free TEMP_FIXED or TEMP_GLOBAL. */
2065         g_assert_not_reached();
2066     }
2067 }
2068 
2069 void tcg_temp_free_i32(TCGv_i32 arg)
2070 {
2071     tcg_temp_free_internal(tcgv_i32_temp(arg));
2072 }
2073 
2074 void tcg_temp_free_i64(TCGv_i64 arg)
2075 {
2076     tcg_temp_free_internal(tcgv_i64_temp(arg));
2077 }
2078 
2079 void tcg_temp_free_i128(TCGv_i128 arg)
2080 {
2081     tcg_temp_free_internal(tcgv_i128_temp(arg));
2082 }
2083 
2084 void tcg_temp_free_ptr(TCGv_ptr arg)
2085 {
2086     tcg_temp_free_internal(tcgv_ptr_temp(arg));
2087 }
2088 
2089 void tcg_temp_free_vec(TCGv_vec arg)
2090 {
2091     tcg_temp_free_internal(tcgv_vec_temp(arg));
2092 }
2093 
2094 TCGTemp *tcg_constant_internal(TCGType type, int64_t val)
2095 {
2096     TCGContext *s = tcg_ctx;
2097     GHashTable *h = s->const_table[type];
2098     TCGTemp *ts;
2099 
2100     if (h == NULL) {
2101         h = g_hash_table_new(g_int64_hash, g_int64_equal);
2102         s->const_table[type] = h;
2103     }
2104 
2105     ts = g_hash_table_lookup(h, &val);
2106     if (ts == NULL) {
2107         int64_t *val_ptr;
2108 
2109         ts = tcg_temp_alloc(s);
2110 
2111         if (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64) {
2112             TCGTemp *ts2 = tcg_temp_alloc(s);
2113 
2114             tcg_debug_assert(ts2 == ts + 1);
2115 
2116             ts->base_type = TCG_TYPE_I64;
2117             ts->type = TCG_TYPE_I32;
2118             ts->kind = TEMP_CONST;
2119             ts->temp_allocated = 1;
2120 
2121             ts2->base_type = TCG_TYPE_I64;
2122             ts2->type = TCG_TYPE_I32;
2123             ts2->kind = TEMP_CONST;
2124             ts2->temp_allocated = 1;
2125             ts2->temp_subindex = 1;
2126 
2127             /*
2128              * Retain the full value of the 64-bit constant in the low
2129              * part, so that the hash table works.  Actual uses will
2130              * truncate the value to the low part.
2131              */
2132             ts[HOST_BIG_ENDIAN].val = val;
2133             ts[!HOST_BIG_ENDIAN].val = val >> 32;
2134             val_ptr = &ts[HOST_BIG_ENDIAN].val;
2135         } else {
2136             ts->base_type = type;
2137             ts->type = type;
2138             ts->kind = TEMP_CONST;
2139             ts->temp_allocated = 1;
2140             ts->val = val;
2141             val_ptr = &ts->val;
2142         }
2143         g_hash_table_insert(h, val_ptr, ts);
2144     }
2145 
2146     return ts;
2147 }
2148 
2149 TCGv_i32 tcg_constant_i32(int32_t val)
2150 {
2151     return temp_tcgv_i32(tcg_constant_internal(TCG_TYPE_I32, val));
2152 }
2153 
2154 TCGv_i64 tcg_constant_i64(int64_t val)
2155 {
2156     return temp_tcgv_i64(tcg_constant_internal(TCG_TYPE_I64, val));
2157 }
2158 
2159 TCGv_ptr tcg_constant_ptr_int(intptr_t val)
2160 {
2161     return temp_tcgv_ptr(tcg_constant_internal(TCG_TYPE_PTR, val));
2162 }
2163 
2164 TCGv_vec tcg_constant_vec(TCGType type, unsigned vece, int64_t val)
2165 {
2166     val = dup_const(vece, val);
2167     return temp_tcgv_vec(tcg_constant_internal(type, val));
2168 }
2169 
2170 TCGv_vec tcg_constant_vec_matching(TCGv_vec match, unsigned vece, int64_t val)
2171 {
2172     TCGTemp *t = tcgv_vec_temp(match);
2173 
2174     tcg_debug_assert(t->temp_allocated != 0);
2175     return tcg_constant_vec(t->base_type, vece, val);
2176 }
2177 
2178 #ifdef CONFIG_DEBUG_TCG
2179 size_t temp_idx(TCGTemp *ts)
2180 {
2181     ptrdiff_t n = ts - tcg_ctx->temps;
2182     assert(n >= 0 && n < tcg_ctx->nb_temps);
2183     return n;
2184 }
2185 
2186 TCGTemp *tcgv_i32_temp(TCGv_i32 v)
2187 {
2188     uintptr_t o = (uintptr_t)v - offsetof(TCGContext, temps);
2189 
2190     assert(o < sizeof(TCGTemp) * tcg_ctx->nb_temps);
2191     assert(o % sizeof(TCGTemp) == 0);
2192 
2193     return (void *)tcg_ctx + (uintptr_t)v;
2194 }
2195 #endif /* CONFIG_DEBUG_TCG */
2196 
2197 /*
2198  * Return true if OP may appear in the opcode stream with TYPE.
2199  * Test the runtime variable that controls each opcode.
2200  */
2201 bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags)
2202 {
2203     bool has_type;
2204 
2205     switch (type) {
2206     case TCG_TYPE_I32:
2207         has_type = true;
2208         break;
2209     case TCG_TYPE_I64:
2210         has_type = TCG_TARGET_REG_BITS == 64;
2211         break;
2212     case TCG_TYPE_V64:
2213         has_type = TCG_TARGET_HAS_v64;
2214         break;
2215     case TCG_TYPE_V128:
2216         has_type = TCG_TARGET_HAS_v128;
2217         break;
2218     case TCG_TYPE_V256:
2219         has_type = TCG_TARGET_HAS_v256;
2220         break;
2221     default:
2222         has_type = false;
2223         break;
2224     }
2225 
2226     switch (op) {
2227     case INDEX_op_discard:
2228     case INDEX_op_set_label:
2229     case INDEX_op_call:
2230     case INDEX_op_br:
2231     case INDEX_op_mb:
2232     case INDEX_op_insn_start:
2233     case INDEX_op_exit_tb:
2234     case INDEX_op_goto_tb:
2235     case INDEX_op_goto_ptr:
2236     case INDEX_op_qemu_ld_i32:
2237     case INDEX_op_qemu_st_i32:
2238     case INDEX_op_qemu_ld_i64:
2239     case INDEX_op_qemu_st_i64:
2240         return true;
2241 
2242     case INDEX_op_qemu_st8_i32:
2243         return TCG_TARGET_HAS_qemu_st8_i32;
2244 
2245     case INDEX_op_qemu_ld_i128:
2246     case INDEX_op_qemu_st_i128:
2247         return TCG_TARGET_HAS_qemu_ldst_i128;
2248 
2249     case INDEX_op_add:
2250     case INDEX_op_and:
2251     case INDEX_op_mov:
2252     case INDEX_op_or:
2253     case INDEX_op_xor:
2254         return has_type;
2255 
2256     case INDEX_op_setcond_i32:
2257     case INDEX_op_brcond_i32:
2258     case INDEX_op_movcond_i32:
2259     case INDEX_op_ld8u_i32:
2260     case INDEX_op_ld8s_i32:
2261     case INDEX_op_ld16u_i32:
2262     case INDEX_op_ld16s_i32:
2263     case INDEX_op_ld_i32:
2264     case INDEX_op_st8_i32:
2265     case INDEX_op_st16_i32:
2266     case INDEX_op_st_i32:
2267     case INDEX_op_sar_i32:
2268     case INDEX_op_extract_i32:
2269     case INDEX_op_sextract_i32:
2270     case INDEX_op_deposit_i32:
2271         return true;
2272 
2273     case INDEX_op_negsetcond_i32:
2274         return TCG_TARGET_HAS_negsetcond_i32;
2275     case INDEX_op_rotl_i32:
2276     case INDEX_op_rotr_i32:
2277         return TCG_TARGET_HAS_rot_i32;
2278     case INDEX_op_extract2_i32:
2279         return TCG_TARGET_HAS_extract2_i32;
2280     case INDEX_op_add2_i32:
2281         return TCG_TARGET_HAS_add2_i32;
2282     case INDEX_op_sub2_i32:
2283         return TCG_TARGET_HAS_sub2_i32;
2284     case INDEX_op_mulu2_i32:
2285         return TCG_TARGET_HAS_mulu2_i32;
2286     case INDEX_op_muls2_i32:
2287         return TCG_TARGET_HAS_muls2_i32;
2288     case INDEX_op_bswap16_i32:
2289         return TCG_TARGET_HAS_bswap16_i32;
2290     case INDEX_op_bswap32_i32:
2291         return TCG_TARGET_HAS_bswap32_i32;
2292     case INDEX_op_clz_i32:
2293         return TCG_TARGET_HAS_clz_i32;
2294     case INDEX_op_ctz_i32:
2295         return TCG_TARGET_HAS_ctz_i32;
2296     case INDEX_op_ctpop_i32:
2297         return TCG_TARGET_HAS_ctpop_i32;
2298 
2299     case INDEX_op_brcond2_i32:
2300     case INDEX_op_setcond2_i32:
2301         return TCG_TARGET_REG_BITS == 32;
2302 
2303     case INDEX_op_setcond_i64:
2304     case INDEX_op_brcond_i64:
2305     case INDEX_op_movcond_i64:
2306     case INDEX_op_ld8u_i64:
2307     case INDEX_op_ld8s_i64:
2308     case INDEX_op_ld16u_i64:
2309     case INDEX_op_ld16s_i64:
2310     case INDEX_op_ld32u_i64:
2311     case INDEX_op_ld32s_i64:
2312     case INDEX_op_ld_i64:
2313     case INDEX_op_st8_i64:
2314     case INDEX_op_st16_i64:
2315     case INDEX_op_st32_i64:
2316     case INDEX_op_st_i64:
2317     case INDEX_op_sar_i64:
2318     case INDEX_op_ext_i32_i64:
2319     case INDEX_op_extu_i32_i64:
2320     case INDEX_op_extract_i64:
2321     case INDEX_op_sextract_i64:
2322     case INDEX_op_deposit_i64:
2323         return TCG_TARGET_REG_BITS == 64;
2324 
2325     case INDEX_op_negsetcond_i64:
2326         return TCG_TARGET_HAS_negsetcond_i64;
2327     case INDEX_op_rotl_i64:
2328     case INDEX_op_rotr_i64:
2329         return TCG_TARGET_HAS_rot_i64;
2330     case INDEX_op_extract2_i64:
2331         return TCG_TARGET_HAS_extract2_i64;
2332     case INDEX_op_extrl_i64_i32:
2333     case INDEX_op_extrh_i64_i32:
2334         return TCG_TARGET_HAS_extr_i64_i32;
2335     case INDEX_op_bswap16_i64:
2336         return TCG_TARGET_HAS_bswap16_i64;
2337     case INDEX_op_bswap32_i64:
2338         return TCG_TARGET_HAS_bswap32_i64;
2339     case INDEX_op_bswap64_i64:
2340         return TCG_TARGET_HAS_bswap64_i64;
2341     case INDEX_op_clz_i64:
2342         return TCG_TARGET_HAS_clz_i64;
2343     case INDEX_op_ctz_i64:
2344         return TCG_TARGET_HAS_ctz_i64;
2345     case INDEX_op_ctpop_i64:
2346         return TCG_TARGET_HAS_ctpop_i64;
2347     case INDEX_op_add2_i64:
2348         return TCG_TARGET_HAS_add2_i64;
2349     case INDEX_op_sub2_i64:
2350         return TCG_TARGET_HAS_sub2_i64;
2351     case INDEX_op_mulu2_i64:
2352         return TCG_TARGET_HAS_mulu2_i64;
2353     case INDEX_op_muls2_i64:
2354         return TCG_TARGET_HAS_muls2_i64;
2355 
2356     case INDEX_op_mov_vec:
2357     case INDEX_op_dup_vec:
2358     case INDEX_op_dupm_vec:
2359     case INDEX_op_ld_vec:
2360     case INDEX_op_st_vec:
2361     case INDEX_op_add_vec:
2362     case INDEX_op_sub_vec:
2363     case INDEX_op_and_vec:
2364     case INDEX_op_or_vec:
2365     case INDEX_op_xor_vec:
2366     case INDEX_op_cmp_vec:
2367         return has_type;
2368     case INDEX_op_dup2_vec:
2369         return has_type && TCG_TARGET_REG_BITS == 32;
2370     case INDEX_op_not_vec:
2371         return has_type && TCG_TARGET_HAS_not_vec;
2372     case INDEX_op_neg_vec:
2373         return has_type && TCG_TARGET_HAS_neg_vec;
2374     case INDEX_op_abs_vec:
2375         return has_type && TCG_TARGET_HAS_abs_vec;
2376     case INDEX_op_andc_vec:
2377         return has_type && TCG_TARGET_HAS_andc_vec;
2378     case INDEX_op_orc_vec:
2379         return has_type && TCG_TARGET_HAS_orc_vec;
2380     case INDEX_op_nand_vec:
2381         return has_type && TCG_TARGET_HAS_nand_vec;
2382     case INDEX_op_nor_vec:
2383         return has_type && TCG_TARGET_HAS_nor_vec;
2384     case INDEX_op_eqv_vec:
2385         return has_type && TCG_TARGET_HAS_eqv_vec;
2386     case INDEX_op_mul_vec:
2387         return has_type && TCG_TARGET_HAS_mul_vec;
2388     case INDEX_op_shli_vec:
2389     case INDEX_op_shri_vec:
2390     case INDEX_op_sari_vec:
2391         return has_type && TCG_TARGET_HAS_shi_vec;
2392     case INDEX_op_shls_vec:
2393     case INDEX_op_shrs_vec:
2394     case INDEX_op_sars_vec:
2395         return has_type && TCG_TARGET_HAS_shs_vec;
2396     case INDEX_op_shlv_vec:
2397     case INDEX_op_shrv_vec:
2398     case INDEX_op_sarv_vec:
2399         return has_type && TCG_TARGET_HAS_shv_vec;
2400     case INDEX_op_rotli_vec:
2401         return has_type && TCG_TARGET_HAS_roti_vec;
2402     case INDEX_op_rotls_vec:
2403         return has_type && TCG_TARGET_HAS_rots_vec;
2404     case INDEX_op_rotlv_vec:
2405     case INDEX_op_rotrv_vec:
2406         return has_type && TCG_TARGET_HAS_rotv_vec;
2407     case INDEX_op_ssadd_vec:
2408     case INDEX_op_usadd_vec:
2409     case INDEX_op_sssub_vec:
2410     case INDEX_op_ussub_vec:
2411         return has_type && TCG_TARGET_HAS_sat_vec;
2412     case INDEX_op_smin_vec:
2413     case INDEX_op_umin_vec:
2414     case INDEX_op_smax_vec:
2415     case INDEX_op_umax_vec:
2416         return has_type && TCG_TARGET_HAS_minmax_vec;
2417     case INDEX_op_bitsel_vec:
2418         return has_type && TCG_TARGET_HAS_bitsel_vec;
2419     case INDEX_op_cmpsel_vec:
2420         return has_type && TCG_TARGET_HAS_cmpsel_vec;
2421 
2422     default:
2423         if (op < INDEX_op_last_generic) {
2424             const TCGOutOp *outop;
2425             TCGConstraintSetIndex con_set;
2426 
2427             if (!has_type) {
2428                 return false;
2429             }
2430 
2431             outop = all_outop[op];
2432             tcg_debug_assert(outop != NULL);
2433 
2434             con_set = outop->static_constraint;
2435             if (con_set == C_Dynamic) {
2436                 con_set = outop->dynamic_constraint(type, flags);
2437             }
2438             if (con_set >= 0) {
2439                 return true;
2440             }
2441             tcg_debug_assert(con_set == C_NotImplemented);
2442             return false;
2443         }
2444         tcg_debug_assert(op < NB_OPS);
2445         return true;
2446 
2447     case INDEX_op_last_generic:
2448         g_assert_not_reached();
2449     }
2450 }
2451 
2452 bool tcg_op_deposit_valid(TCGType type, unsigned ofs, unsigned len)
2453 {
2454     unsigned width;
2455 
2456     tcg_debug_assert(type == TCG_TYPE_I32 || type == TCG_TYPE_I64);
2457     width = (type == TCG_TYPE_I32 ? 32 : 64);
2458 
2459     tcg_debug_assert(ofs < width);
2460     tcg_debug_assert(len > 0);
2461     tcg_debug_assert(len <= width - ofs);
2462 
2463     return TCG_TARGET_deposit_valid(type, ofs, len);
2464 }
2465 
2466 static TCGOp *tcg_op_alloc(TCGOpcode opc, unsigned nargs);
2467 
2468 static void tcg_gen_callN(void *func, TCGHelperInfo *info,
2469                           TCGTemp *ret, TCGTemp **args)
2470 {
2471     TCGv_i64 extend_free[MAX_CALL_IARGS];
2472     int n_extend = 0;
2473     TCGOp *op;
2474     int i, n, pi = 0, total_args;
2475 
2476     if (unlikely(g_once_init_enter(HELPER_INFO_INIT(info)))) {
2477         init_call_layout(info);
2478         g_once_init_leave(HELPER_INFO_INIT(info), HELPER_INFO_INIT_VAL(info));
2479     }
2480 
2481     total_args = info->nr_out + info->nr_in + 2;
2482     op = tcg_op_alloc(INDEX_op_call, total_args);
2483 
2484 #ifdef CONFIG_PLUGIN
2485     /* Flag helpers that may affect guest state */
2486     if (tcg_ctx->plugin_insn && !(info->flags & TCG_CALL_NO_SIDE_EFFECTS)) {
2487         tcg_ctx->plugin_insn->calls_helpers = true;
2488     }
2489 #endif
2490 
2491     TCGOP_CALLO(op) = n = info->nr_out;
2492     switch (n) {
2493     case 0:
2494         tcg_debug_assert(ret == NULL);
2495         break;
2496     case 1:
2497         tcg_debug_assert(ret != NULL);
2498         op->args[pi++] = temp_arg(ret);
2499         break;
2500     case 2:
2501     case 4:
2502         tcg_debug_assert(ret != NULL);
2503         tcg_debug_assert(ret->base_type == ret->type + ctz32(n));
2504         tcg_debug_assert(ret->temp_subindex == 0);
2505         for (i = 0; i < n; ++i) {
2506             op->args[pi++] = temp_arg(ret + i);
2507         }
2508         break;
2509     default:
2510         g_assert_not_reached();
2511     }
2512 
2513     TCGOP_CALLI(op) = n = info->nr_in;
2514     for (i = 0; i < n; i++) {
2515         const TCGCallArgumentLoc *loc = &info->in[i];
2516         TCGTemp *ts = args[loc->arg_idx] + loc->tmp_subindex;
2517 
2518         switch (loc->kind) {
2519         case TCG_CALL_ARG_NORMAL:
2520         case TCG_CALL_ARG_BY_REF:
2521         case TCG_CALL_ARG_BY_REF_N:
2522             op->args[pi++] = temp_arg(ts);
2523             break;
2524 
2525         case TCG_CALL_ARG_EXTEND_U:
2526         case TCG_CALL_ARG_EXTEND_S:
2527             {
2528                 TCGv_i64 temp = tcg_temp_ebb_new_i64();
2529                 TCGv_i32 orig = temp_tcgv_i32(ts);
2530 
2531                 if (loc->kind == TCG_CALL_ARG_EXTEND_S) {
2532                     tcg_gen_ext_i32_i64(temp, orig);
2533                 } else {
2534                     tcg_gen_extu_i32_i64(temp, orig);
2535                 }
2536                 op->args[pi++] = tcgv_i64_arg(temp);
2537                 extend_free[n_extend++] = temp;
2538             }
2539             break;
2540 
2541         default:
2542             g_assert_not_reached();
2543         }
2544     }
2545     op->args[pi++] = (uintptr_t)func;
2546     op->args[pi++] = (uintptr_t)info;
2547     tcg_debug_assert(pi == total_args);
2548 
2549     if (tcg_ctx->emit_before_op) {
2550         QTAILQ_INSERT_BEFORE(tcg_ctx->emit_before_op, op, link);
2551     } else {
2552         QTAILQ_INSERT_TAIL(&tcg_ctx->ops, op, link);
2553     }
2554 
2555     tcg_debug_assert(n_extend < ARRAY_SIZE(extend_free));
2556     for (i = 0; i < n_extend; ++i) {
2557         tcg_temp_free_i64(extend_free[i]);
2558     }
2559 }
2560 
2561 void tcg_gen_call0(void *func, TCGHelperInfo *info, TCGTemp *ret)
2562 {
2563     tcg_gen_callN(func, info, ret, NULL);
2564 }
2565 
2566 void tcg_gen_call1(void *func, TCGHelperInfo *info, TCGTemp *ret, TCGTemp *t1)
2567 {
2568     tcg_gen_callN(func, info, ret, &t1);
2569 }
2570 
2571 void tcg_gen_call2(void *func, TCGHelperInfo *info, TCGTemp *ret,
2572                    TCGTemp *t1, TCGTemp *t2)
2573 {
2574     TCGTemp *args[2] = { t1, t2 };
2575     tcg_gen_callN(func, info, ret, args);
2576 }
2577 
2578 void tcg_gen_call3(void *func, TCGHelperInfo *info, TCGTemp *ret,
2579                    TCGTemp *t1, TCGTemp *t2, TCGTemp *t3)
2580 {
2581     TCGTemp *args[3] = { t1, t2, t3 };
2582     tcg_gen_callN(func, info, ret, args);
2583 }
2584 
2585 void tcg_gen_call4(void *func, TCGHelperInfo *info, TCGTemp *ret,
2586                    TCGTemp *t1, TCGTemp *t2, TCGTemp *t3, TCGTemp *t4)
2587 {
2588     TCGTemp *args[4] = { t1, t2, t3, t4 };
2589     tcg_gen_callN(func, info, ret, args);
2590 }
2591 
2592 void tcg_gen_call5(void *func, TCGHelperInfo *info, TCGTemp *ret, TCGTemp *t1,
2593                    TCGTemp *t2, TCGTemp *t3, TCGTemp *t4, TCGTemp *t5)
2594 {
2595     TCGTemp *args[5] = { t1, t2, t3, t4, t5 };
2596     tcg_gen_callN(func, info, ret, args);
2597 }
2598 
2599 void tcg_gen_call6(void *func, TCGHelperInfo *info, TCGTemp *ret,
2600                    TCGTemp *t1, TCGTemp *t2, TCGTemp *t3,
2601                    TCGTemp *t4, TCGTemp *t5, TCGTemp *t6)
2602 {
2603     TCGTemp *args[6] = { t1, t2, t3, t4, t5, t6 };
2604     tcg_gen_callN(func, info, ret, args);
2605 }
2606 
2607 void tcg_gen_call7(void *func, TCGHelperInfo *info, TCGTemp *ret, TCGTemp *t1,
2608                    TCGTemp *t2, TCGTemp *t3, TCGTemp *t4,
2609                    TCGTemp *t5, TCGTemp *t6, TCGTemp *t7)
2610 {
2611     TCGTemp *args[7] = { t1, t2, t3, t4, t5, t6, t7 };
2612     tcg_gen_callN(func, info, ret, args);
2613 }
2614 
2615 static void tcg_reg_alloc_start(TCGContext *s)
2616 {
2617     int i, n;
2618 
2619     for (i = 0, n = s->nb_temps; i < n; i++) {
2620         TCGTemp *ts = &s->temps[i];
2621         TCGTempVal val = TEMP_VAL_MEM;
2622 
2623         switch (ts->kind) {
2624         case TEMP_CONST:
2625             val = TEMP_VAL_CONST;
2626             break;
2627         case TEMP_FIXED:
2628             val = TEMP_VAL_REG;
2629             break;
2630         case TEMP_GLOBAL:
2631             break;
2632         case TEMP_EBB:
2633             val = TEMP_VAL_DEAD;
2634             /* fall through */
2635         case TEMP_TB:
2636             ts->mem_allocated = 0;
2637             break;
2638         default:
2639             g_assert_not_reached();
2640         }
2641         ts->val_type = val;
2642     }
2643 
2644     memset(s->reg_to_temp, 0, sizeof(s->reg_to_temp));
2645 }
2646 
2647 static char *tcg_get_arg_str_ptr(TCGContext *s, char *buf, int buf_size,
2648                                  TCGTemp *ts)
2649 {
2650     int idx = temp_idx(ts);
2651 
2652     switch (ts->kind) {
2653     case TEMP_FIXED:
2654     case TEMP_GLOBAL:
2655         pstrcpy(buf, buf_size, ts->name);
2656         break;
2657     case TEMP_TB:
2658         snprintf(buf, buf_size, "loc%d", idx - s->nb_globals);
2659         break;
2660     case TEMP_EBB:
2661         snprintf(buf, buf_size, "tmp%d", idx - s->nb_globals);
2662         break;
2663     case TEMP_CONST:
2664         switch (ts->type) {
2665         case TCG_TYPE_I32:
2666             snprintf(buf, buf_size, "$0x%x", (int32_t)ts->val);
2667             break;
2668 #if TCG_TARGET_REG_BITS > 32
2669         case TCG_TYPE_I64:
2670             snprintf(buf, buf_size, "$0x%" PRIx64, ts->val);
2671             break;
2672 #endif
2673         case TCG_TYPE_V64:
2674         case TCG_TYPE_V128:
2675         case TCG_TYPE_V256:
2676             snprintf(buf, buf_size, "v%d$0x%" PRIx64,
2677                      64 << (ts->type - TCG_TYPE_V64), ts->val);
2678             break;
2679         default:
2680             g_assert_not_reached();
2681         }
2682         break;
2683     }
2684     return buf;
2685 }
2686 
2687 static char *tcg_get_arg_str(TCGContext *s, char *buf,
2688                              int buf_size, TCGArg arg)
2689 {
2690     return tcg_get_arg_str_ptr(s, buf, buf_size, arg_temp(arg));
2691 }
2692 
2693 static const char * const cond_name[] =
2694 {
2695     [TCG_COND_NEVER] = "never",
2696     [TCG_COND_ALWAYS] = "always",
2697     [TCG_COND_EQ] = "eq",
2698     [TCG_COND_NE] = "ne",
2699     [TCG_COND_LT] = "lt",
2700     [TCG_COND_GE] = "ge",
2701     [TCG_COND_LE] = "le",
2702     [TCG_COND_GT] = "gt",
2703     [TCG_COND_LTU] = "ltu",
2704     [TCG_COND_GEU] = "geu",
2705     [TCG_COND_LEU] = "leu",
2706     [TCG_COND_GTU] = "gtu",
2707     [TCG_COND_TSTEQ] = "tsteq",
2708     [TCG_COND_TSTNE] = "tstne",
2709 };
2710 
2711 static const char * const ldst_name[(MO_BSWAP | MO_SSIZE) + 1] =
2712 {
2713     [MO_UB]   = "ub",
2714     [MO_SB]   = "sb",
2715     [MO_LEUW] = "leuw",
2716     [MO_LESW] = "lesw",
2717     [MO_LEUL] = "leul",
2718     [MO_LESL] = "lesl",
2719     [MO_LEUQ] = "leq",
2720     [MO_BEUW] = "beuw",
2721     [MO_BESW] = "besw",
2722     [MO_BEUL] = "beul",
2723     [MO_BESL] = "besl",
2724     [MO_BEUQ] = "beq",
2725     [MO_128 + MO_BE] = "beo",
2726     [MO_128 + MO_LE] = "leo",
2727 };
2728 
2729 static const char * const alignment_name[(MO_AMASK >> MO_ASHIFT) + 1] = {
2730     [MO_UNALN >> MO_ASHIFT]    = "un+",
2731     [MO_ALIGN >> MO_ASHIFT]    = "al+",
2732     [MO_ALIGN_2 >> MO_ASHIFT]  = "al2+",
2733     [MO_ALIGN_4 >> MO_ASHIFT]  = "al4+",
2734     [MO_ALIGN_8 >> MO_ASHIFT]  = "al8+",
2735     [MO_ALIGN_16 >> MO_ASHIFT] = "al16+",
2736     [MO_ALIGN_32 >> MO_ASHIFT] = "al32+",
2737     [MO_ALIGN_64 >> MO_ASHIFT] = "al64+",
2738 };
2739 
2740 static const char * const atom_name[(MO_ATOM_MASK >> MO_ATOM_SHIFT) + 1] = {
2741     [MO_ATOM_IFALIGN >> MO_ATOM_SHIFT] = "",
2742     [MO_ATOM_IFALIGN_PAIR >> MO_ATOM_SHIFT] = "pair+",
2743     [MO_ATOM_WITHIN16 >> MO_ATOM_SHIFT] = "w16+",
2744     [MO_ATOM_WITHIN16_PAIR >> MO_ATOM_SHIFT] = "w16p+",
2745     [MO_ATOM_SUBALIGN >> MO_ATOM_SHIFT] = "sub+",
2746     [MO_ATOM_NONE >> MO_ATOM_SHIFT] = "noat+",
2747 };
2748 
2749 static const char bswap_flag_name[][6] = {
2750     [TCG_BSWAP_IZ] = "iz",
2751     [TCG_BSWAP_OZ] = "oz",
2752     [TCG_BSWAP_OS] = "os",
2753     [TCG_BSWAP_IZ | TCG_BSWAP_OZ] = "iz,oz",
2754     [TCG_BSWAP_IZ | TCG_BSWAP_OS] = "iz,os",
2755 };
2756 
2757 #ifdef CONFIG_PLUGIN
2758 static const char * const plugin_from_name[] = {
2759     "from-tb",
2760     "from-insn",
2761     "after-insn",
2762     "after-tb",
2763 };
2764 #endif
2765 
2766 static inline bool tcg_regset_single(TCGRegSet d)
2767 {
2768     return (d & (d - 1)) == 0;
2769 }
2770 
2771 static inline TCGReg tcg_regset_first(TCGRegSet d)
2772 {
2773     if (TCG_TARGET_NB_REGS <= 32) {
2774         return ctz32(d);
2775     } else {
2776         return ctz64(d);
2777     }
2778 }
2779 
2780 /* Return only the number of characters output -- no error return. */
2781 #define ne_fprintf(...) \
2782     ({ int ret_ = fprintf(__VA_ARGS__); ret_ >= 0 ? ret_ : 0; })
2783 
2784 void tcg_dump_ops(TCGContext *s, FILE *f, bool have_prefs)
2785 {
2786     char buf[128];
2787     TCGOp *op;
2788 
2789     QTAILQ_FOREACH(op, &s->ops, link) {
2790         int i, k, nb_oargs, nb_iargs, nb_cargs;
2791         const TCGOpDef *def;
2792         TCGOpcode c;
2793         int col = 0;
2794 
2795         c = op->opc;
2796         def = &tcg_op_defs[c];
2797 
2798         if (c == INDEX_op_insn_start) {
2799             nb_oargs = 0;
2800             col += ne_fprintf(f, "\n ----");
2801 
2802             for (i = 0, k = s->insn_start_words; i < k; ++i) {
2803                 col += ne_fprintf(f, " %016" PRIx64,
2804                                   tcg_get_insn_start_param(op, i));
2805             }
2806         } else if (c == INDEX_op_call) {
2807             const TCGHelperInfo *info = tcg_call_info(op);
2808             void *func = tcg_call_func(op);
2809 
2810             /* variable number of arguments */
2811             nb_oargs = TCGOP_CALLO(op);
2812             nb_iargs = TCGOP_CALLI(op);
2813             nb_cargs = def->nb_cargs;
2814 
2815             col += ne_fprintf(f, " %s ", def->name);
2816 
2817             /*
2818              * Print the function name from TCGHelperInfo, if available.
2819              * Note that plugins have a template function for the info,
2820              * but the actual function pointer comes from the plugin.
2821              */
2822             if (func == info->func) {
2823                 col += ne_fprintf(f, "%s", info->name);
2824             } else {
2825                 col += ne_fprintf(f, "plugin(%p)", func);
2826             }
2827 
2828             col += ne_fprintf(f, ",$0x%x,$%d", info->flags, nb_oargs);
2829             for (i = 0; i < nb_oargs; i++) {
2830                 col += ne_fprintf(f, ",%s", tcg_get_arg_str(s, buf, sizeof(buf),
2831                                                             op->args[i]));
2832             }
2833             for (i = 0; i < nb_iargs; i++) {
2834                 TCGArg arg = op->args[nb_oargs + i];
2835                 const char *t = tcg_get_arg_str(s, buf, sizeof(buf), arg);
2836                 col += ne_fprintf(f, ",%s", t);
2837             }
2838         } else {
2839             if (def->flags & TCG_OPF_INT) {
2840                 col += ne_fprintf(f, " %s_i%d ",
2841                                   def->name,
2842                                   8 * tcg_type_size(TCGOP_TYPE(op)));
2843             } else if (def->flags & TCG_OPF_VECTOR) {
2844                 col += ne_fprintf(f, "%s v%d,e%d,",
2845                                   def->name,
2846                                   8 * tcg_type_size(TCGOP_TYPE(op)),
2847                                   8 << TCGOP_VECE(op));
2848             } else {
2849                 col += ne_fprintf(f, " %s ", def->name);
2850             }
2851 
2852             nb_oargs = def->nb_oargs;
2853             nb_iargs = def->nb_iargs;
2854             nb_cargs = def->nb_cargs;
2855 
2856             k = 0;
2857             for (i = 0; i < nb_oargs; i++) {
2858                 const char *sep =  k ? "," : "";
2859                 col += ne_fprintf(f, "%s%s", sep,
2860                                   tcg_get_arg_str(s, buf, sizeof(buf),
2861                                                   op->args[k++]));
2862             }
2863             for (i = 0; i < nb_iargs; i++) {
2864                 const char *sep =  k ? "," : "";
2865                 col += ne_fprintf(f, "%s%s", sep,
2866                                   tcg_get_arg_str(s, buf, sizeof(buf),
2867                                                   op->args[k++]));
2868             }
2869             switch (c) {
2870             case INDEX_op_brcond_i32:
2871             case INDEX_op_setcond_i32:
2872             case INDEX_op_negsetcond_i32:
2873             case INDEX_op_movcond_i32:
2874             case INDEX_op_brcond2_i32:
2875             case INDEX_op_setcond2_i32:
2876             case INDEX_op_brcond_i64:
2877             case INDEX_op_setcond_i64:
2878             case INDEX_op_negsetcond_i64:
2879             case INDEX_op_movcond_i64:
2880             case INDEX_op_cmp_vec:
2881             case INDEX_op_cmpsel_vec:
2882                 if (op->args[k] < ARRAY_SIZE(cond_name)
2883                     && cond_name[op->args[k]]) {
2884                     col += ne_fprintf(f, ",%s", cond_name[op->args[k++]]);
2885                 } else {
2886                     col += ne_fprintf(f, ",$0x%" TCG_PRIlx, op->args[k++]);
2887                 }
2888                 i = 1;
2889                 break;
2890             case INDEX_op_qemu_ld_i32:
2891             case INDEX_op_qemu_st_i32:
2892             case INDEX_op_qemu_st8_i32:
2893             case INDEX_op_qemu_ld_i64:
2894             case INDEX_op_qemu_st_i64:
2895             case INDEX_op_qemu_ld_i128:
2896             case INDEX_op_qemu_st_i128:
2897                 {
2898                     const char *s_al, *s_op, *s_at;
2899                     MemOpIdx oi = op->args[k++];
2900                     MemOp mop = get_memop(oi);
2901                     unsigned ix = get_mmuidx(oi);
2902 
2903                     s_al = alignment_name[(mop & MO_AMASK) >> MO_ASHIFT];
2904                     s_op = ldst_name[mop & (MO_BSWAP | MO_SSIZE)];
2905                     s_at = atom_name[(mop & MO_ATOM_MASK) >> MO_ATOM_SHIFT];
2906                     mop &= ~(MO_AMASK | MO_BSWAP | MO_SSIZE | MO_ATOM_MASK);
2907 
2908                     /* If all fields are accounted for, print symbolically. */
2909                     if (!mop && s_al && s_op && s_at) {
2910                         col += ne_fprintf(f, ",%s%s%s,%u",
2911                                           s_at, s_al, s_op, ix);
2912                     } else {
2913                         mop = get_memop(oi);
2914                         col += ne_fprintf(f, ",$0x%x,%u", mop, ix);
2915                     }
2916                     i = 1;
2917                 }
2918                 break;
2919             case INDEX_op_bswap16_i32:
2920             case INDEX_op_bswap16_i64:
2921             case INDEX_op_bswap32_i32:
2922             case INDEX_op_bswap32_i64:
2923             case INDEX_op_bswap64_i64:
2924                 {
2925                     TCGArg flags = op->args[k];
2926                     const char *name = NULL;
2927 
2928                     if (flags < ARRAY_SIZE(bswap_flag_name)) {
2929                         name = bswap_flag_name[flags];
2930                     }
2931                     if (name) {
2932                         col += ne_fprintf(f, ",%s", name);
2933                     } else {
2934                         col += ne_fprintf(f, ",$0x%" TCG_PRIlx, flags);
2935                     }
2936                     i = k = 1;
2937                 }
2938                 break;
2939 #ifdef CONFIG_PLUGIN
2940             case INDEX_op_plugin_cb:
2941                 {
2942                     TCGArg from = op->args[k++];
2943                     const char *name = NULL;
2944 
2945                     if (from < ARRAY_SIZE(plugin_from_name)) {
2946                         name = plugin_from_name[from];
2947                     }
2948                     if (name) {
2949                         col += ne_fprintf(f, "%s", name);
2950                     } else {
2951                         col += ne_fprintf(f, "$0x%" TCG_PRIlx, from);
2952                     }
2953                     i = 1;
2954                 }
2955                 break;
2956 #endif
2957             default:
2958                 i = 0;
2959                 break;
2960             }
2961             switch (c) {
2962             case INDEX_op_set_label:
2963             case INDEX_op_br:
2964             case INDEX_op_brcond_i32:
2965             case INDEX_op_brcond_i64:
2966             case INDEX_op_brcond2_i32:
2967                 col += ne_fprintf(f, "%s$L%d", k ? "," : "",
2968                                   arg_label(op->args[k])->id);
2969                 i++, k++;
2970                 break;
2971             case INDEX_op_mb:
2972                 {
2973                     TCGBar membar = op->args[k];
2974                     const char *b_op, *m_op;
2975 
2976                     switch (membar & TCG_BAR_SC) {
2977                     case 0:
2978                         b_op = "none";
2979                         break;
2980                     case TCG_BAR_LDAQ:
2981                         b_op = "acq";
2982                         break;
2983                     case TCG_BAR_STRL:
2984                         b_op = "rel";
2985                         break;
2986                     case TCG_BAR_SC:
2987                         b_op = "seq";
2988                         break;
2989                     default:
2990                         g_assert_not_reached();
2991                     }
2992 
2993                     switch (membar & TCG_MO_ALL) {
2994                     case 0:
2995                         m_op = "none";
2996                         break;
2997                     case TCG_MO_LD_LD:
2998                         m_op = "rr";
2999                         break;
3000                     case TCG_MO_LD_ST:
3001                         m_op = "rw";
3002                         break;
3003                     case TCG_MO_ST_LD:
3004                         m_op = "wr";
3005                         break;
3006                     case TCG_MO_ST_ST:
3007                         m_op = "ww";
3008                         break;
3009                     case TCG_MO_LD_LD | TCG_MO_LD_ST:
3010                         m_op = "rr+rw";
3011                         break;
3012                     case TCG_MO_LD_LD | TCG_MO_ST_LD:
3013                         m_op = "rr+wr";
3014                         break;
3015                     case TCG_MO_LD_LD | TCG_MO_ST_ST:
3016                         m_op = "rr+ww";
3017                         break;
3018                     case TCG_MO_LD_ST | TCG_MO_ST_LD:
3019                         m_op = "rw+wr";
3020                         break;
3021                     case TCG_MO_LD_ST | TCG_MO_ST_ST:
3022                         m_op = "rw+ww";
3023                         break;
3024                     case TCG_MO_ST_LD | TCG_MO_ST_ST:
3025                         m_op = "wr+ww";
3026                         break;
3027                     case TCG_MO_LD_LD | TCG_MO_LD_ST | TCG_MO_ST_LD:
3028                         m_op = "rr+rw+wr";
3029                         break;
3030                     case TCG_MO_LD_LD | TCG_MO_LD_ST | TCG_MO_ST_ST:
3031                         m_op = "rr+rw+ww";
3032                         break;
3033                     case TCG_MO_LD_LD | TCG_MO_ST_LD | TCG_MO_ST_ST:
3034                         m_op = "rr+wr+ww";
3035                         break;
3036                     case TCG_MO_LD_ST | TCG_MO_ST_LD | TCG_MO_ST_ST:
3037                         m_op = "rw+wr+ww";
3038                         break;
3039                     case TCG_MO_ALL:
3040                         m_op = "all";
3041                         break;
3042                     default:
3043                         g_assert_not_reached();
3044                     }
3045 
3046                     col += ne_fprintf(f, "%s%s:%s", (k ? "," : ""), b_op, m_op);
3047                     i++, k++;
3048                 }
3049                 break;
3050             default:
3051                 break;
3052             }
3053             for (; i < nb_cargs; i++, k++) {
3054                 col += ne_fprintf(f, "%s$0x%" TCG_PRIlx, k ? "," : "",
3055                                   op->args[k]);
3056             }
3057         }
3058 
3059         if (have_prefs || op->life) {
3060             for (; col < 40; ++col) {
3061                 putc(' ', f);
3062             }
3063         }
3064 
3065         if (op->life) {
3066             unsigned life = op->life;
3067 
3068             if (life & (SYNC_ARG * 3)) {
3069                 ne_fprintf(f, "  sync:");
3070                 for (i = 0; i < 2; ++i) {
3071                     if (life & (SYNC_ARG << i)) {
3072                         ne_fprintf(f, " %d", i);
3073                     }
3074                 }
3075             }
3076             life /= DEAD_ARG;
3077             if (life) {
3078                 ne_fprintf(f, "  dead:");
3079                 for (i = 0; life; ++i, life >>= 1) {
3080                     if (life & 1) {
3081                         ne_fprintf(f, " %d", i);
3082                     }
3083                 }
3084             }
3085         }
3086 
3087         if (have_prefs) {
3088             for (i = 0; i < nb_oargs; ++i) {
3089                 TCGRegSet set = output_pref(op, i);
3090 
3091                 if (i == 0) {
3092                     ne_fprintf(f, "  pref=");
3093                 } else {
3094                     ne_fprintf(f, ",");
3095                 }
3096                 if (set == 0) {
3097                     ne_fprintf(f, "none");
3098                 } else if (set == MAKE_64BIT_MASK(0, TCG_TARGET_NB_REGS)) {
3099                     ne_fprintf(f, "all");
3100 #ifdef CONFIG_DEBUG_TCG
3101                 } else if (tcg_regset_single(set)) {
3102                     TCGReg reg = tcg_regset_first(set);
3103                     ne_fprintf(f, "%s", tcg_target_reg_names[reg]);
3104 #endif
3105                 } else if (TCG_TARGET_NB_REGS <= 32) {
3106                     ne_fprintf(f, "0x%x", (uint32_t)set);
3107                 } else {
3108                     ne_fprintf(f, "0x%" PRIx64, (uint64_t)set);
3109                 }
3110             }
3111         }
3112 
3113         putc('\n', f);
3114     }
3115 }
3116 
3117 /* we give more priority to constraints with less registers */
3118 static int get_constraint_priority(const TCGArgConstraint *arg_ct, int k)
3119 {
3120     int n;
3121 
3122     arg_ct += k;
3123     n = ctpop64(arg_ct->regs);
3124 
3125     /*
3126      * Sort constraints of a single register first, which includes output
3127      * aliases (which must exactly match the input already allocated).
3128      */
3129     if (n == 1 || arg_ct->oalias) {
3130         return INT_MAX;
3131     }
3132 
3133     /*
3134      * Sort register pairs next, first then second immediately after.
3135      * Arbitrarily sort multiple pairs by the index of the first reg;
3136      * there shouldn't be many pairs.
3137      */
3138     switch (arg_ct->pair) {
3139     case 1:
3140     case 3:
3141         return (k + 1) * 2;
3142     case 2:
3143         return (arg_ct->pair_index + 1) * 2 - 1;
3144     }
3145 
3146     /* Finally, sort by decreasing register count. */
3147     assert(n > 1);
3148     return -n;
3149 }
3150 
3151 /* sort from highest priority to lowest */
3152 static void sort_constraints(TCGArgConstraint *a, int start, int n)
3153 {
3154     int i, j;
3155 
3156     for (i = 0; i < n; i++) {
3157         a[start + i].sort_index = start + i;
3158     }
3159     if (n <= 1) {
3160         return;
3161     }
3162     for (i = 0; i < n - 1; i++) {
3163         for (j = i + 1; j < n; j++) {
3164             int p1 = get_constraint_priority(a, a[start + i].sort_index);
3165             int p2 = get_constraint_priority(a, a[start + j].sort_index);
3166             if (p1 < p2) {
3167                 int tmp = a[start + i].sort_index;
3168                 a[start + i].sort_index = a[start + j].sort_index;
3169                 a[start + j].sort_index = tmp;
3170             }
3171         }
3172     }
3173 }
3174 
3175 static const TCGArgConstraint empty_cts[TCG_MAX_OP_ARGS];
3176 static TCGArgConstraint all_cts[ARRAY_SIZE(constraint_sets)][TCG_MAX_OP_ARGS];
3177 
3178 static void process_constraint_sets(void)
3179 {
3180     for (size_t c = 0; c < ARRAY_SIZE(constraint_sets); ++c) {
3181         const TCGConstraintSet *tdefs = &constraint_sets[c];
3182         TCGArgConstraint *args_ct = all_cts[c];
3183         int nb_oargs = tdefs->nb_oargs;
3184         int nb_iargs = tdefs->nb_iargs;
3185         int nb_args = nb_oargs + nb_iargs;
3186         bool saw_alias_pair = false;
3187 
3188         for (int i = 0; i < nb_args; i++) {
3189             const char *ct_str = tdefs->args_ct_str[i];
3190             bool input_p = i >= nb_oargs;
3191             int o;
3192 
3193             switch (*ct_str) {
3194             case '0' ... '9':
3195                 o = *ct_str - '0';
3196                 tcg_debug_assert(input_p);
3197                 tcg_debug_assert(o < nb_oargs);
3198                 tcg_debug_assert(args_ct[o].regs != 0);
3199                 tcg_debug_assert(!args_ct[o].oalias);
3200                 args_ct[i] = args_ct[o];
3201                 /* The output sets oalias.  */
3202                 args_ct[o].oalias = 1;
3203                 args_ct[o].alias_index = i;
3204                 /* The input sets ialias. */
3205                 args_ct[i].ialias = 1;
3206                 args_ct[i].alias_index = o;
3207                 if (args_ct[i].pair) {
3208                     saw_alias_pair = true;
3209                 }
3210                 tcg_debug_assert(ct_str[1] == '\0');
3211                 continue;
3212 
3213             case '&':
3214                 tcg_debug_assert(!input_p);
3215                 args_ct[i].newreg = true;
3216                 ct_str++;
3217                 break;
3218 
3219             case 'p': /* plus */
3220                 /* Allocate to the register after the previous. */
3221                 tcg_debug_assert(i > (input_p ? nb_oargs : 0));
3222                 o = i - 1;
3223                 tcg_debug_assert(!args_ct[o].pair);
3224                 tcg_debug_assert(!args_ct[o].ct);
3225                 args_ct[i] = (TCGArgConstraint){
3226                     .pair = 2,
3227                     .pair_index = o,
3228                     .regs = args_ct[o].regs << 1,
3229                     .newreg = args_ct[o].newreg,
3230                 };
3231                 args_ct[o].pair = 1;
3232                 args_ct[o].pair_index = i;
3233                 tcg_debug_assert(ct_str[1] == '\0');
3234                 continue;
3235 
3236             case 'm': /* minus */
3237                 /* Allocate to the register before the previous. */
3238                 tcg_debug_assert(i > (input_p ? nb_oargs : 0));
3239                 o = i - 1;
3240                 tcg_debug_assert(!args_ct[o].pair);
3241                 tcg_debug_assert(!args_ct[o].ct);
3242                 args_ct[i] = (TCGArgConstraint){
3243                     .pair = 1,
3244                     .pair_index = o,
3245                     .regs = args_ct[o].regs >> 1,
3246                     .newreg = args_ct[o].newreg,
3247                 };
3248                 args_ct[o].pair = 2;
3249                 args_ct[o].pair_index = i;
3250                 tcg_debug_assert(ct_str[1] == '\0');
3251                 continue;
3252             }
3253 
3254             do {
3255                 switch (*ct_str) {
3256                 case 'i':
3257                     args_ct[i].ct |= TCG_CT_CONST;
3258                     break;
3259 #ifdef TCG_REG_ZERO
3260                 case 'z':
3261                     args_ct[i].ct |= TCG_CT_REG_ZERO;
3262                     break;
3263 #endif
3264 
3265                 /* Include all of the target-specific constraints. */
3266 
3267 #undef CONST
3268 #define CONST(CASE, MASK) \
3269     case CASE: args_ct[i].ct |= MASK; break;
3270 #define REGS(CASE, MASK) \
3271     case CASE: args_ct[i].regs |= MASK; break;
3272 
3273 #include "tcg-target-con-str.h"
3274 
3275 #undef REGS
3276 #undef CONST
3277                 default:
3278                 case '0' ... '9':
3279                 case '&':
3280                 case 'p':
3281                 case 'm':
3282                     /* Typo in TCGConstraintSet constraint. */
3283                     g_assert_not_reached();
3284                 }
3285             } while (*++ct_str != '\0');
3286         }
3287 
3288         /*
3289          * Fix up output pairs that are aliased with inputs.
3290          * When we created the alias, we copied pair from the output.
3291          * There are three cases:
3292          *    (1a) Pairs of inputs alias pairs of outputs.
3293          *    (1b) One input aliases the first of a pair of outputs.
3294          *    (2)  One input aliases the second of a pair of outputs.
3295          *
3296          * Case 1a is handled by making sure that the pair_index'es are
3297          * properly updated so that they appear the same as a pair of inputs.
3298          *
3299          * Case 1b is handled by setting the pair_index of the input to
3300          * itself, simply so it doesn't point to an unrelated argument.
3301          * Since we don't encounter the "second" during the input allocation
3302          * phase, nothing happens with the second half of the input pair.
3303          *
3304          * Case 2 is handled by setting the second input to pair=3, the
3305          * first output to pair=3, and the pair_index'es to match.
3306          */
3307         if (saw_alias_pair) {
3308             for (int i = nb_oargs; i < nb_args; i++) {
3309                 int o, o2, i2;
3310 
3311                 /*
3312                  * Since [0-9pm] must be alone in the constraint string,
3313                  * the only way they can both be set is if the pair comes
3314                  * from the output alias.
3315                  */
3316                 if (!args_ct[i].ialias) {
3317                     continue;
3318                 }
3319                 switch (args_ct[i].pair) {
3320                 case 0:
3321                     break;
3322                 case 1:
3323                     o = args_ct[i].alias_index;
3324                     o2 = args_ct[o].pair_index;
3325                     tcg_debug_assert(args_ct[o].pair == 1);
3326                     tcg_debug_assert(args_ct[o2].pair == 2);
3327                     if (args_ct[o2].oalias) {
3328                         /* Case 1a */
3329                         i2 = args_ct[o2].alias_index;
3330                         tcg_debug_assert(args_ct[i2].pair == 2);
3331                         args_ct[i2].pair_index = i;
3332                         args_ct[i].pair_index = i2;
3333                     } else {
3334                         /* Case 1b */
3335                         args_ct[i].pair_index = i;
3336                     }
3337                     break;
3338                 case 2:
3339                     o = args_ct[i].alias_index;
3340                     o2 = args_ct[o].pair_index;
3341                     tcg_debug_assert(args_ct[o].pair == 2);
3342                     tcg_debug_assert(args_ct[o2].pair == 1);
3343                     if (args_ct[o2].oalias) {
3344                         /* Case 1a */
3345                         i2 = args_ct[o2].alias_index;
3346                         tcg_debug_assert(args_ct[i2].pair == 1);
3347                         args_ct[i2].pair_index = i;
3348                         args_ct[i].pair_index = i2;
3349                     } else {
3350                         /* Case 2 */
3351                         args_ct[i].pair = 3;
3352                         args_ct[o2].pair = 3;
3353                         args_ct[i].pair_index = o2;
3354                         args_ct[o2].pair_index = i;
3355                     }
3356                     break;
3357                 default:
3358                     g_assert_not_reached();
3359                 }
3360             }
3361         }
3362 
3363         /* sort the constraints (XXX: this is just an heuristic) */
3364         sort_constraints(args_ct, 0, nb_oargs);
3365         sort_constraints(args_ct, nb_oargs, nb_iargs);
3366     }
3367 }
3368 
3369 static const TCGArgConstraint *opcode_args_ct(const TCGOp *op)
3370 {
3371     TCGOpcode opc = op->opc;
3372     TCGType type = TCGOP_TYPE(op);
3373     unsigned flags = TCGOP_FLAGS(op);
3374     const TCGOpDef *def = &tcg_op_defs[opc];
3375     const TCGOutOp *outop = all_outop[opc];
3376     TCGConstraintSetIndex con_set;
3377 
3378     if (def->flags & TCG_OPF_NOT_PRESENT) {
3379         return empty_cts;
3380     }
3381 
3382     if (outop) {
3383         con_set = outop->static_constraint;
3384         if (con_set == C_Dynamic) {
3385             con_set = outop->dynamic_constraint(type, flags);
3386         }
3387     } else {
3388         con_set = tcg_target_op_def(opc, type, flags);
3389     }
3390     tcg_debug_assert(con_set >= 0);
3391     tcg_debug_assert(con_set < ARRAY_SIZE(constraint_sets));
3392 
3393     /* The constraint arguments must match TCGOpcode arguments. */
3394     tcg_debug_assert(constraint_sets[con_set].nb_oargs == def->nb_oargs);
3395     tcg_debug_assert(constraint_sets[con_set].nb_iargs == def->nb_iargs);
3396 
3397     return all_cts[con_set];
3398 }
3399 
3400 static void remove_label_use(TCGOp *op, int idx)
3401 {
3402     TCGLabel *label = arg_label(op->args[idx]);
3403     TCGLabelUse *use;
3404 
3405     QSIMPLEQ_FOREACH(use, &label->branches, next) {
3406         if (use->op == op) {
3407             QSIMPLEQ_REMOVE(&label->branches, use, TCGLabelUse, next);
3408             return;
3409         }
3410     }
3411     g_assert_not_reached();
3412 }
3413 
3414 void tcg_op_remove(TCGContext *s, TCGOp *op)
3415 {
3416     switch (op->opc) {
3417     case INDEX_op_br:
3418         remove_label_use(op, 0);
3419         break;
3420     case INDEX_op_brcond_i32:
3421     case INDEX_op_brcond_i64:
3422         remove_label_use(op, 3);
3423         break;
3424     case INDEX_op_brcond2_i32:
3425         remove_label_use(op, 5);
3426         break;
3427     default:
3428         break;
3429     }
3430 
3431     QTAILQ_REMOVE(&s->ops, op, link);
3432     QTAILQ_INSERT_TAIL(&s->free_ops, op, link);
3433     s->nb_ops--;
3434 }
3435 
3436 void tcg_remove_ops_after(TCGOp *op)
3437 {
3438     TCGContext *s = tcg_ctx;
3439 
3440     while (true) {
3441         TCGOp *last = tcg_last_op();
3442         if (last == op) {
3443             return;
3444         }
3445         tcg_op_remove(s, last);
3446     }
3447 }
3448 
3449 static TCGOp *tcg_op_alloc(TCGOpcode opc, unsigned nargs)
3450 {
3451     TCGContext *s = tcg_ctx;
3452     TCGOp *op = NULL;
3453 
3454     if (unlikely(!QTAILQ_EMPTY(&s->free_ops))) {
3455         QTAILQ_FOREACH(op, &s->free_ops, link) {
3456             if (nargs <= op->nargs) {
3457                 QTAILQ_REMOVE(&s->free_ops, op, link);
3458                 nargs = op->nargs;
3459                 goto found;
3460             }
3461         }
3462     }
3463 
3464     /* Most opcodes have 3 or 4 operands: reduce fragmentation. */
3465     nargs = MAX(4, nargs);
3466     op = tcg_malloc(sizeof(TCGOp) + sizeof(TCGArg) * nargs);
3467 
3468  found:
3469     memset(op, 0, offsetof(TCGOp, link));
3470     op->opc = opc;
3471     op->nargs = nargs;
3472 
3473     /* Check for bitfield overflow. */
3474     tcg_debug_assert(op->nargs == nargs);
3475 
3476     s->nb_ops++;
3477     return op;
3478 }
3479 
3480 TCGOp *tcg_emit_op(TCGOpcode opc, unsigned nargs)
3481 {
3482     TCGOp *op = tcg_op_alloc(opc, nargs);
3483 
3484     if (tcg_ctx->emit_before_op) {
3485         QTAILQ_INSERT_BEFORE(tcg_ctx->emit_before_op, op, link);
3486     } else {
3487         QTAILQ_INSERT_TAIL(&tcg_ctx->ops, op, link);
3488     }
3489     return op;
3490 }
3491 
3492 TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *old_op,
3493                             TCGOpcode opc, TCGType type, unsigned nargs)
3494 {
3495     TCGOp *new_op = tcg_op_alloc(opc, nargs);
3496 
3497     TCGOP_TYPE(new_op) = type;
3498     QTAILQ_INSERT_BEFORE(old_op, new_op, link);
3499     return new_op;
3500 }
3501 
3502 TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *old_op,
3503                            TCGOpcode opc, TCGType type, unsigned nargs)
3504 {
3505     TCGOp *new_op = tcg_op_alloc(opc, nargs);
3506 
3507     TCGOP_TYPE(new_op) = type;
3508     QTAILQ_INSERT_AFTER(&s->ops, old_op, new_op, link);
3509     return new_op;
3510 }
3511 
3512 static void move_label_uses(TCGLabel *to, TCGLabel *from)
3513 {
3514     TCGLabelUse *u;
3515 
3516     QSIMPLEQ_FOREACH(u, &from->branches, next) {
3517         TCGOp *op = u->op;
3518         switch (op->opc) {
3519         case INDEX_op_br:
3520             op->args[0] = label_arg(to);
3521             break;
3522         case INDEX_op_brcond_i32:
3523         case INDEX_op_brcond_i64:
3524             op->args[3] = label_arg(to);
3525             break;
3526         case INDEX_op_brcond2_i32:
3527             op->args[5] = label_arg(to);
3528             break;
3529         default:
3530             g_assert_not_reached();
3531         }
3532     }
3533 
3534     QSIMPLEQ_CONCAT(&to->branches, &from->branches);
3535 }
3536 
3537 /* Reachable analysis : remove unreachable code.  */
3538 static void __attribute__((noinline))
3539 reachable_code_pass(TCGContext *s)
3540 {
3541     TCGOp *op, *op_next, *op_prev;
3542     bool dead = false;
3543 
3544     QTAILQ_FOREACH_SAFE(op, &s->ops, link, op_next) {
3545         bool remove = dead;
3546         TCGLabel *label;
3547 
3548         switch (op->opc) {
3549         case INDEX_op_set_label:
3550             label = arg_label(op->args[0]);
3551 
3552             /*
3553              * Note that the first op in the TB is always a load,
3554              * so there is always something before a label.
3555              */
3556             op_prev = QTAILQ_PREV(op, link);
3557 
3558             /*
3559              * If we find two sequential labels, move all branches to
3560              * reference the second label and remove the first label.
3561              * Do this before branch to next optimization, so that the
3562              * middle label is out of the way.
3563              */
3564             if (op_prev->opc == INDEX_op_set_label) {
3565                 move_label_uses(label, arg_label(op_prev->args[0]));
3566                 tcg_op_remove(s, op_prev);
3567                 op_prev = QTAILQ_PREV(op, link);
3568             }
3569 
3570             /*
3571              * Optimization can fold conditional branches to unconditional.
3572              * If we find a label which is preceded by an unconditional
3573              * branch to next, remove the branch.  We couldn't do this when
3574              * processing the branch because any dead code between the branch
3575              * and label had not yet been removed.
3576              */
3577             if (op_prev->opc == INDEX_op_br &&
3578                 label == arg_label(op_prev->args[0])) {
3579                 tcg_op_remove(s, op_prev);
3580                 /* Fall through means insns become live again.  */
3581                 dead = false;
3582             }
3583 
3584             if (QSIMPLEQ_EMPTY(&label->branches)) {
3585                 /*
3586                  * While there is an occasional backward branch, virtually
3587                  * all branches generated by the translators are forward.
3588                  * Which means that generally we will have already removed
3589                  * all references to the label that will be, and there is
3590                  * little to be gained by iterating.
3591                  */
3592                 remove = true;
3593             } else {
3594                 /* Once we see a label, insns become live again.  */
3595                 dead = false;
3596                 remove = false;
3597             }
3598             break;
3599 
3600         case INDEX_op_br:
3601         case INDEX_op_exit_tb:
3602         case INDEX_op_goto_ptr:
3603             /* Unconditional branches; everything following is dead.  */
3604             dead = true;
3605             break;
3606 
3607         case INDEX_op_call:
3608             /* Notice noreturn helper calls, raising exceptions.  */
3609             if (tcg_call_flags(op) & TCG_CALL_NO_RETURN) {
3610                 dead = true;
3611             }
3612             break;
3613 
3614         case INDEX_op_insn_start:
3615             /* Never remove -- we need to keep these for unwind.  */
3616             remove = false;
3617             break;
3618 
3619         default:
3620             break;
3621         }
3622 
3623         if (remove) {
3624             tcg_op_remove(s, op);
3625         }
3626     }
3627 }
3628 
3629 #define TS_DEAD  1
3630 #define TS_MEM   2
3631 
3632 #define IS_DEAD_ARG(n)   (arg_life & (DEAD_ARG << (n)))
3633 #define NEED_SYNC_ARG(n) (arg_life & (SYNC_ARG << (n)))
3634 
3635 /* For liveness_pass_1, the register preferences for a given temp.  */
3636 static inline TCGRegSet *la_temp_pref(TCGTemp *ts)
3637 {
3638     return ts->state_ptr;
3639 }
3640 
3641 /* For liveness_pass_1, reset the preferences for a given temp to the
3642  * maximal regset for its type.
3643  */
3644 static inline void la_reset_pref(TCGTemp *ts)
3645 {
3646     *la_temp_pref(ts)
3647         = (ts->state == TS_DEAD ? 0 : tcg_target_available_regs[ts->type]);
3648 }
3649 
3650 /* liveness analysis: end of function: all temps are dead, and globals
3651    should be in memory. */
3652 static void la_func_end(TCGContext *s, int ng, int nt)
3653 {
3654     int i;
3655 
3656     for (i = 0; i < ng; ++i) {
3657         s->temps[i].state = TS_DEAD | TS_MEM;
3658         la_reset_pref(&s->temps[i]);
3659     }
3660     for (i = ng; i < nt; ++i) {
3661         s->temps[i].state = TS_DEAD;
3662         la_reset_pref(&s->temps[i]);
3663     }
3664 }
3665 
3666 /* liveness analysis: end of basic block: all temps are dead, globals
3667    and local temps should be in memory. */
3668 static void la_bb_end(TCGContext *s, int ng, int nt)
3669 {
3670     int i;
3671 
3672     for (i = 0; i < nt; ++i) {
3673         TCGTemp *ts = &s->temps[i];
3674         int state;
3675 
3676         switch (ts->kind) {
3677         case TEMP_FIXED:
3678         case TEMP_GLOBAL:
3679         case TEMP_TB:
3680             state = TS_DEAD | TS_MEM;
3681             break;
3682         case TEMP_EBB:
3683         case TEMP_CONST:
3684             state = TS_DEAD;
3685             break;
3686         default:
3687             g_assert_not_reached();
3688         }
3689         ts->state = state;
3690         la_reset_pref(ts);
3691     }
3692 }
3693 
3694 /* liveness analysis: sync globals back to memory.  */
3695 static void la_global_sync(TCGContext *s, int ng)
3696 {
3697     int i;
3698 
3699     for (i = 0; i < ng; ++i) {
3700         int state = s->temps[i].state;
3701         s->temps[i].state = state | TS_MEM;
3702         if (state == TS_DEAD) {
3703             /* If the global was previously dead, reset prefs.  */
3704             la_reset_pref(&s->temps[i]);
3705         }
3706     }
3707 }
3708 
3709 /*
3710  * liveness analysis: conditional branch: all temps are dead unless
3711  * explicitly live-across-conditional-branch, globals and local temps
3712  * should be synced.
3713  */
3714 static void la_bb_sync(TCGContext *s, int ng, int nt)
3715 {
3716     la_global_sync(s, ng);
3717 
3718     for (int i = ng; i < nt; ++i) {
3719         TCGTemp *ts = &s->temps[i];
3720         int state;
3721 
3722         switch (ts->kind) {
3723         case TEMP_TB:
3724             state = ts->state;
3725             ts->state = state | TS_MEM;
3726             if (state != TS_DEAD) {
3727                 continue;
3728             }
3729             break;
3730         case TEMP_EBB:
3731         case TEMP_CONST:
3732             continue;
3733         default:
3734             g_assert_not_reached();
3735         }
3736         la_reset_pref(&s->temps[i]);
3737     }
3738 }
3739 
3740 /* liveness analysis: sync globals back to memory and kill.  */
3741 static void la_global_kill(TCGContext *s, int ng)
3742 {
3743     int i;
3744 
3745     for (i = 0; i < ng; i++) {
3746         s->temps[i].state = TS_DEAD | TS_MEM;
3747         la_reset_pref(&s->temps[i]);
3748     }
3749 }
3750 
3751 /* liveness analysis: note live globals crossing calls.  */
3752 static void la_cross_call(TCGContext *s, int nt)
3753 {
3754     TCGRegSet mask = ~tcg_target_call_clobber_regs;
3755     int i;
3756 
3757     for (i = 0; i < nt; i++) {
3758         TCGTemp *ts = &s->temps[i];
3759         if (!(ts->state & TS_DEAD)) {
3760             TCGRegSet *pset = la_temp_pref(ts);
3761             TCGRegSet set = *pset;
3762 
3763             set &= mask;
3764             /* If the combination is not possible, restart.  */
3765             if (set == 0) {
3766                 set = tcg_target_available_regs[ts->type] & mask;
3767             }
3768             *pset = set;
3769         }
3770     }
3771 }
3772 
3773 /*
3774  * Liveness analysis: Verify the lifetime of TEMP_TB, and reduce
3775  * to TEMP_EBB, if possible.
3776  */
3777 static void __attribute__((noinline))
3778 liveness_pass_0(TCGContext *s)
3779 {
3780     void * const multiple_ebb = (void *)(uintptr_t)-1;
3781     int nb_temps = s->nb_temps;
3782     TCGOp *op, *ebb;
3783 
3784     for (int i = s->nb_globals; i < nb_temps; ++i) {
3785         s->temps[i].state_ptr = NULL;
3786     }
3787 
3788     /*
3789      * Represent each EBB by the op at which it begins.  In the case of
3790      * the first EBB, this is the first op, otherwise it is a label.
3791      * Collect the uses of each TEMP_TB: NULL for unused, EBB for use
3792      * within a single EBB, else MULTIPLE_EBB.
3793      */
3794     ebb = QTAILQ_FIRST(&s->ops);
3795     QTAILQ_FOREACH(op, &s->ops, link) {
3796         const TCGOpDef *def;
3797         int nb_oargs, nb_iargs;
3798 
3799         switch (op->opc) {
3800         case INDEX_op_set_label:
3801             ebb = op;
3802             continue;
3803         case INDEX_op_discard:
3804             continue;
3805         case INDEX_op_call:
3806             nb_oargs = TCGOP_CALLO(op);
3807             nb_iargs = TCGOP_CALLI(op);
3808             break;
3809         default:
3810             def = &tcg_op_defs[op->opc];
3811             nb_oargs = def->nb_oargs;
3812             nb_iargs = def->nb_iargs;
3813             break;
3814         }
3815 
3816         for (int i = 0; i < nb_oargs + nb_iargs; ++i) {
3817             TCGTemp *ts = arg_temp(op->args[i]);
3818 
3819             if (ts->kind != TEMP_TB) {
3820                 continue;
3821             }
3822             if (ts->state_ptr == NULL) {
3823                 ts->state_ptr = ebb;
3824             } else if (ts->state_ptr != ebb) {
3825                 ts->state_ptr = multiple_ebb;
3826             }
3827         }
3828     }
3829 
3830     /*
3831      * For TEMP_TB that turned out not to be used beyond one EBB,
3832      * reduce the liveness to TEMP_EBB.
3833      */
3834     for (int i = s->nb_globals; i < nb_temps; ++i) {
3835         TCGTemp *ts = &s->temps[i];
3836         if (ts->kind == TEMP_TB && ts->state_ptr != multiple_ebb) {
3837             ts->kind = TEMP_EBB;
3838         }
3839     }
3840 }
3841 
3842 /* Liveness analysis : update the opc_arg_life array to tell if a
3843    given input arguments is dead. Instructions updating dead
3844    temporaries are removed. */
3845 static void __attribute__((noinline))
3846 liveness_pass_1(TCGContext *s)
3847 {
3848     int nb_globals = s->nb_globals;
3849     int nb_temps = s->nb_temps;
3850     TCGOp *op, *op_prev;
3851     TCGRegSet *prefs;
3852     int i;
3853 
3854     prefs = tcg_malloc(sizeof(TCGRegSet) * nb_temps);
3855     for (i = 0; i < nb_temps; ++i) {
3856         s->temps[i].state_ptr = prefs + i;
3857     }
3858 
3859     /* ??? Should be redundant with the exit_tb that ends the TB.  */
3860     la_func_end(s, nb_globals, nb_temps);
3861 
3862     QTAILQ_FOREACH_REVERSE_SAFE(op, &s->ops, link, op_prev) {
3863         int nb_iargs, nb_oargs;
3864         TCGOpcode opc_new, opc_new2;
3865         TCGLifeData arg_life = 0;
3866         TCGTemp *ts;
3867         TCGOpcode opc = op->opc;
3868         const TCGOpDef *def = &tcg_op_defs[opc];
3869         const TCGArgConstraint *args_ct;
3870 
3871         switch (opc) {
3872         case INDEX_op_call:
3873             {
3874                 const TCGHelperInfo *info = tcg_call_info(op);
3875                 int call_flags = tcg_call_flags(op);
3876 
3877                 nb_oargs = TCGOP_CALLO(op);
3878                 nb_iargs = TCGOP_CALLI(op);
3879 
3880                 /* pure functions can be removed if their result is unused */
3881                 if (call_flags & TCG_CALL_NO_SIDE_EFFECTS) {
3882                     for (i = 0; i < nb_oargs; i++) {
3883                         ts = arg_temp(op->args[i]);
3884                         if (ts->state != TS_DEAD) {
3885                             goto do_not_remove_call;
3886                         }
3887                     }
3888                     goto do_remove;
3889                 }
3890             do_not_remove_call:
3891 
3892                 /* Output args are dead.  */
3893                 for (i = 0; i < nb_oargs; i++) {
3894                     ts = arg_temp(op->args[i]);
3895                     if (ts->state & TS_DEAD) {
3896                         arg_life |= DEAD_ARG << i;
3897                     }
3898                     if (ts->state & TS_MEM) {
3899                         arg_life |= SYNC_ARG << i;
3900                     }
3901                     ts->state = TS_DEAD;
3902                     la_reset_pref(ts);
3903                 }
3904 
3905                 /* Not used -- it will be tcg_target_call_oarg_reg().  */
3906                 memset(op->output_pref, 0, sizeof(op->output_pref));
3907 
3908                 if (!(call_flags & (TCG_CALL_NO_WRITE_GLOBALS |
3909                                     TCG_CALL_NO_READ_GLOBALS))) {
3910                     la_global_kill(s, nb_globals);
3911                 } else if (!(call_flags & TCG_CALL_NO_READ_GLOBALS)) {
3912                     la_global_sync(s, nb_globals);
3913                 }
3914 
3915                 /* Record arguments that die in this helper.  */
3916                 for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
3917                     ts = arg_temp(op->args[i]);
3918                     if (ts->state & TS_DEAD) {
3919                         arg_life |= DEAD_ARG << i;
3920                     }
3921                 }
3922 
3923                 /* For all live registers, remove call-clobbered prefs.  */
3924                 la_cross_call(s, nb_temps);
3925 
3926                 /*
3927                  * Input arguments are live for preceding opcodes.
3928                  *
3929                  * For those arguments that die, and will be allocated in
3930                  * registers, clear the register set for that arg, to be
3931                  * filled in below.  For args that will be on the stack,
3932                  * reset to any available reg.  Process arguments in reverse
3933                  * order so that if a temp is used more than once, the stack
3934                  * reset to max happens before the register reset to 0.
3935                  */
3936                 for (i = nb_iargs - 1; i >= 0; i--) {
3937                     const TCGCallArgumentLoc *loc = &info->in[i];
3938                     ts = arg_temp(op->args[nb_oargs + i]);
3939 
3940                     if (ts->state & TS_DEAD) {
3941                         switch (loc->kind) {
3942                         case TCG_CALL_ARG_NORMAL:
3943                         case TCG_CALL_ARG_EXTEND_U:
3944                         case TCG_CALL_ARG_EXTEND_S:
3945                             if (arg_slot_reg_p(loc->arg_slot)) {
3946                                 *la_temp_pref(ts) = 0;
3947                                 break;
3948                             }
3949                             /* fall through */
3950                         default:
3951                             *la_temp_pref(ts) =
3952                                 tcg_target_available_regs[ts->type];
3953                             break;
3954                         }
3955                         ts->state &= ~TS_DEAD;
3956                     }
3957                 }
3958 
3959                 /*
3960                  * For each input argument, add its input register to prefs.
3961                  * If a temp is used once, this produces a single set bit;
3962                  * if a temp is used multiple times, this produces a set.
3963                  */
3964                 for (i = 0; i < nb_iargs; i++) {
3965                     const TCGCallArgumentLoc *loc = &info->in[i];
3966                     ts = arg_temp(op->args[nb_oargs + i]);
3967 
3968                     switch (loc->kind) {
3969                     case TCG_CALL_ARG_NORMAL:
3970                     case TCG_CALL_ARG_EXTEND_U:
3971                     case TCG_CALL_ARG_EXTEND_S:
3972                         if (arg_slot_reg_p(loc->arg_slot)) {
3973                             tcg_regset_set_reg(*la_temp_pref(ts),
3974                                 tcg_target_call_iarg_regs[loc->arg_slot]);
3975                         }
3976                         break;
3977                     default:
3978                         break;
3979                     }
3980                 }
3981             }
3982             break;
3983         case INDEX_op_insn_start:
3984             break;
3985         case INDEX_op_discard:
3986             /* mark the temporary as dead */
3987             ts = arg_temp(op->args[0]);
3988             ts->state = TS_DEAD;
3989             la_reset_pref(ts);
3990             break;
3991 
3992         case INDEX_op_add2_i32:
3993         case INDEX_op_add2_i64:
3994             opc_new = INDEX_op_add;
3995             goto do_addsub2;
3996         case INDEX_op_sub2_i32:
3997         case INDEX_op_sub2_i64:
3998             opc_new = INDEX_op_sub;
3999         do_addsub2:
4000             nb_iargs = 4;
4001             nb_oargs = 2;
4002             /* Test if the high part of the operation is dead, but not
4003                the low part.  The result can be optimized to a simple
4004                add or sub.  This happens often for x86_64 guest when the
4005                cpu mode is set to 32 bit.  */
4006             if (arg_temp(op->args[1])->state == TS_DEAD) {
4007                 if (arg_temp(op->args[0])->state == TS_DEAD) {
4008                     goto do_remove;
4009                 }
4010                 /* Replace the opcode and adjust the args in place,
4011                    leaving 3 unused args at the end.  */
4012                 op->opc = opc = opc_new;
4013                 op->args[1] = op->args[2];
4014                 op->args[2] = op->args[4];
4015                 /* Fall through and mark the single-word operation live.  */
4016                 nb_iargs = 2;
4017                 nb_oargs = 1;
4018             }
4019             goto do_not_remove;
4020 
4021         case INDEX_op_muls2_i32:
4022         case INDEX_op_muls2_i64:
4023             opc_new = INDEX_op_mul;
4024             opc_new2 = INDEX_op_mulsh;
4025             goto do_mul2;
4026         case INDEX_op_mulu2_i32:
4027         case INDEX_op_mulu2_i64:
4028             opc_new = INDEX_op_mul;
4029             opc_new2 = INDEX_op_muluh;
4030         do_mul2:
4031             nb_iargs = 2;
4032             nb_oargs = 2;
4033             if (arg_temp(op->args[1])->state == TS_DEAD) {
4034                 if (arg_temp(op->args[0])->state == TS_DEAD) {
4035                     /* Both parts of the operation are dead.  */
4036                     goto do_remove;
4037                 }
4038                 /* The high part of the operation is dead; generate the low. */
4039                 op->opc = opc = opc_new;
4040                 op->args[1] = op->args[2];
4041                 op->args[2] = op->args[3];
4042             } else if (arg_temp(op->args[0])->state == TS_DEAD &&
4043                        tcg_op_supported(opc_new2, TCGOP_TYPE(op), 0)) {
4044                 /* The low part of the operation is dead; generate the high. */
4045                 op->opc = opc = opc_new2;
4046                 op->args[0] = op->args[1];
4047                 op->args[1] = op->args[2];
4048                 op->args[2] = op->args[3];
4049             } else {
4050                 goto do_not_remove;
4051             }
4052             /* Mark the single-word operation live.  */
4053             nb_oargs = 1;
4054             goto do_not_remove;
4055 
4056         default:
4057             /* XXX: optimize by hardcoding common cases (e.g. triadic ops) */
4058             nb_iargs = def->nb_iargs;
4059             nb_oargs = def->nb_oargs;
4060 
4061             /* Test if the operation can be removed because all
4062                its outputs are dead. We assume that nb_oargs == 0
4063                implies side effects */
4064             if (!(def->flags & TCG_OPF_SIDE_EFFECTS) && nb_oargs != 0) {
4065                 for (i = 0; i < nb_oargs; i++) {
4066                     if (arg_temp(op->args[i])->state != TS_DEAD) {
4067                         goto do_not_remove;
4068                     }
4069                 }
4070                 goto do_remove;
4071             }
4072             goto do_not_remove;
4073 
4074         do_remove:
4075             tcg_op_remove(s, op);
4076             break;
4077 
4078         do_not_remove:
4079             for (i = 0; i < nb_oargs; i++) {
4080                 ts = arg_temp(op->args[i]);
4081 
4082                 /* Remember the preference of the uses that followed.  */
4083                 if (i < ARRAY_SIZE(op->output_pref)) {
4084                     op->output_pref[i] = *la_temp_pref(ts);
4085                 }
4086 
4087                 /* Output args are dead.  */
4088                 if (ts->state & TS_DEAD) {
4089                     arg_life |= DEAD_ARG << i;
4090                 }
4091                 if (ts->state & TS_MEM) {
4092                     arg_life |= SYNC_ARG << i;
4093                 }
4094                 ts->state = TS_DEAD;
4095                 la_reset_pref(ts);
4096             }
4097 
4098             /* If end of basic block, update.  */
4099             if (def->flags & TCG_OPF_BB_EXIT) {
4100                 la_func_end(s, nb_globals, nb_temps);
4101             } else if (def->flags & TCG_OPF_COND_BRANCH) {
4102                 la_bb_sync(s, nb_globals, nb_temps);
4103             } else if (def->flags & TCG_OPF_BB_END) {
4104                 la_bb_end(s, nb_globals, nb_temps);
4105             } else if (def->flags & TCG_OPF_SIDE_EFFECTS) {
4106                 la_global_sync(s, nb_globals);
4107                 if (def->flags & TCG_OPF_CALL_CLOBBER) {
4108                     la_cross_call(s, nb_temps);
4109                 }
4110             }
4111 
4112             /* Record arguments that die in this opcode.  */
4113             for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
4114                 ts = arg_temp(op->args[i]);
4115                 if (ts->state & TS_DEAD) {
4116                     arg_life |= DEAD_ARG << i;
4117                 }
4118             }
4119 
4120             /* Input arguments are live for preceding opcodes.  */
4121             for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
4122                 ts = arg_temp(op->args[i]);
4123                 if (ts->state & TS_DEAD) {
4124                     /* For operands that were dead, initially allow
4125                        all regs for the type.  */
4126                     *la_temp_pref(ts) = tcg_target_available_regs[ts->type];
4127                     ts->state &= ~TS_DEAD;
4128                 }
4129             }
4130 
4131             /* Incorporate constraints for this operand.  */
4132             switch (opc) {
4133             case INDEX_op_mov:
4134                 /* Note that these are TCG_OPF_NOT_PRESENT and do not
4135                    have proper constraints.  That said, special case
4136                    moves to propagate preferences backward.  */
4137                 if (IS_DEAD_ARG(1)) {
4138                     *la_temp_pref(arg_temp(op->args[0]))
4139                         = *la_temp_pref(arg_temp(op->args[1]));
4140                 }
4141                 break;
4142 
4143             default:
4144                 args_ct = opcode_args_ct(op);
4145                 for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
4146                     const TCGArgConstraint *ct = &args_ct[i];
4147                     TCGRegSet set, *pset;
4148 
4149                     ts = arg_temp(op->args[i]);
4150                     pset = la_temp_pref(ts);
4151                     set = *pset;
4152 
4153                     set &= ct->regs;
4154                     if (ct->ialias) {
4155                         set &= output_pref(op, ct->alias_index);
4156                     }
4157                     /* If the combination is not possible, restart.  */
4158                     if (set == 0) {
4159                         set = ct->regs;
4160                     }
4161                     *pset = set;
4162                 }
4163                 break;
4164             }
4165             break;
4166         }
4167         op->life = arg_life;
4168     }
4169 }
4170 
4171 /* Liveness analysis: Convert indirect regs to direct temporaries.  */
4172 static bool __attribute__((noinline))
4173 liveness_pass_2(TCGContext *s)
4174 {
4175     int nb_globals = s->nb_globals;
4176     int nb_temps, i;
4177     bool changes = false;
4178     TCGOp *op, *op_next;
4179 
4180     /* Create a temporary for each indirect global.  */
4181     for (i = 0; i < nb_globals; ++i) {
4182         TCGTemp *its = &s->temps[i];
4183         if (its->indirect_reg) {
4184             TCGTemp *dts = tcg_temp_alloc(s);
4185             dts->type = its->type;
4186             dts->base_type = its->base_type;
4187             dts->temp_subindex = its->temp_subindex;
4188             dts->kind = TEMP_EBB;
4189             its->state_ptr = dts;
4190         } else {
4191             its->state_ptr = NULL;
4192         }
4193         /* All globals begin dead.  */
4194         its->state = TS_DEAD;
4195     }
4196     for (nb_temps = s->nb_temps; i < nb_temps; ++i) {
4197         TCGTemp *its = &s->temps[i];
4198         its->state_ptr = NULL;
4199         its->state = TS_DEAD;
4200     }
4201 
4202     QTAILQ_FOREACH_SAFE(op, &s->ops, link, op_next) {
4203         TCGOpcode opc = op->opc;
4204         const TCGOpDef *def = &tcg_op_defs[opc];
4205         TCGLifeData arg_life = op->life;
4206         int nb_iargs, nb_oargs, call_flags;
4207         TCGTemp *arg_ts, *dir_ts;
4208 
4209         if (opc == INDEX_op_call) {
4210             nb_oargs = TCGOP_CALLO(op);
4211             nb_iargs = TCGOP_CALLI(op);
4212             call_flags = tcg_call_flags(op);
4213         } else {
4214             nb_iargs = def->nb_iargs;
4215             nb_oargs = def->nb_oargs;
4216 
4217             /* Set flags similar to how calls require.  */
4218             if (def->flags & TCG_OPF_COND_BRANCH) {
4219                 /* Like reading globals: sync_globals */
4220                 call_flags = TCG_CALL_NO_WRITE_GLOBALS;
4221             } else if (def->flags & TCG_OPF_BB_END) {
4222                 /* Like writing globals: save_globals */
4223                 call_flags = 0;
4224             } else if (def->flags & TCG_OPF_SIDE_EFFECTS) {
4225                 /* Like reading globals: sync_globals */
4226                 call_flags = TCG_CALL_NO_WRITE_GLOBALS;
4227             } else {
4228                 /* No effect on globals.  */
4229                 call_flags = (TCG_CALL_NO_READ_GLOBALS |
4230                               TCG_CALL_NO_WRITE_GLOBALS);
4231             }
4232         }
4233 
4234         /* Make sure that input arguments are available.  */
4235         for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
4236             arg_ts = arg_temp(op->args[i]);
4237             dir_ts = arg_ts->state_ptr;
4238             if (dir_ts && arg_ts->state == TS_DEAD) {
4239                 TCGOpcode lopc = (arg_ts->type == TCG_TYPE_I32
4240                                   ? INDEX_op_ld_i32
4241                                   : INDEX_op_ld_i64);
4242                 TCGOp *lop = tcg_op_insert_before(s, op, lopc,
4243                                                   arg_ts->type, 3);
4244 
4245                 lop->args[0] = temp_arg(dir_ts);
4246                 lop->args[1] = temp_arg(arg_ts->mem_base);
4247                 lop->args[2] = arg_ts->mem_offset;
4248 
4249                 /* Loaded, but synced with memory.  */
4250                 arg_ts->state = TS_MEM;
4251             }
4252         }
4253 
4254         /* Perform input replacement, and mark inputs that became dead.
4255            No action is required except keeping temp_state up to date
4256            so that we reload when needed.  */
4257         for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
4258             arg_ts = arg_temp(op->args[i]);
4259             dir_ts = arg_ts->state_ptr;
4260             if (dir_ts) {
4261                 op->args[i] = temp_arg(dir_ts);
4262                 changes = true;
4263                 if (IS_DEAD_ARG(i)) {
4264                     arg_ts->state = TS_DEAD;
4265                 }
4266             }
4267         }
4268 
4269         /* Liveness analysis should ensure that the following are
4270            all correct, for call sites and basic block end points.  */
4271         if (call_flags & TCG_CALL_NO_READ_GLOBALS) {
4272             /* Nothing to do */
4273         } else if (call_flags & TCG_CALL_NO_WRITE_GLOBALS) {
4274             for (i = 0; i < nb_globals; ++i) {
4275                 /* Liveness should see that globals are synced back,
4276                    that is, either TS_DEAD or TS_MEM.  */
4277                 arg_ts = &s->temps[i];
4278                 tcg_debug_assert(arg_ts->state_ptr == 0
4279                                  || arg_ts->state != 0);
4280             }
4281         } else {
4282             for (i = 0; i < nb_globals; ++i) {
4283                 /* Liveness should see that globals are saved back,
4284                    that is, TS_DEAD, waiting to be reloaded.  */
4285                 arg_ts = &s->temps[i];
4286                 tcg_debug_assert(arg_ts->state_ptr == 0
4287                                  || arg_ts->state == TS_DEAD);
4288             }
4289         }
4290 
4291         /* Outputs become available.  */
4292         if (opc == INDEX_op_mov) {
4293             arg_ts = arg_temp(op->args[0]);
4294             dir_ts = arg_ts->state_ptr;
4295             if (dir_ts) {
4296                 op->args[0] = temp_arg(dir_ts);
4297                 changes = true;
4298 
4299                 /* The output is now live and modified.  */
4300                 arg_ts->state = 0;
4301 
4302                 if (NEED_SYNC_ARG(0)) {
4303                     TCGOpcode sopc = (arg_ts->type == TCG_TYPE_I32
4304                                       ? INDEX_op_st_i32
4305                                       : INDEX_op_st_i64);
4306                     TCGOp *sop = tcg_op_insert_after(s, op, sopc,
4307                                                      arg_ts->type, 3);
4308                     TCGTemp *out_ts = dir_ts;
4309 
4310                     if (IS_DEAD_ARG(0)) {
4311                         out_ts = arg_temp(op->args[1]);
4312                         arg_ts->state = TS_DEAD;
4313                         tcg_op_remove(s, op);
4314                     } else {
4315                         arg_ts->state = TS_MEM;
4316                     }
4317 
4318                     sop->args[0] = temp_arg(out_ts);
4319                     sop->args[1] = temp_arg(arg_ts->mem_base);
4320                     sop->args[2] = arg_ts->mem_offset;
4321                 } else {
4322                     tcg_debug_assert(!IS_DEAD_ARG(0));
4323                 }
4324             }
4325         } else {
4326             for (i = 0; i < nb_oargs; i++) {
4327                 arg_ts = arg_temp(op->args[i]);
4328                 dir_ts = arg_ts->state_ptr;
4329                 if (!dir_ts) {
4330                     continue;
4331                 }
4332                 op->args[i] = temp_arg(dir_ts);
4333                 changes = true;
4334 
4335                 /* The output is now live and modified.  */
4336                 arg_ts->state = 0;
4337 
4338                 /* Sync outputs upon their last write.  */
4339                 if (NEED_SYNC_ARG(i)) {
4340                     TCGOpcode sopc = (arg_ts->type == TCG_TYPE_I32
4341                                       ? INDEX_op_st_i32
4342                                       : INDEX_op_st_i64);
4343                     TCGOp *sop = tcg_op_insert_after(s, op, sopc,
4344                                                      arg_ts->type, 3);
4345 
4346                     sop->args[0] = temp_arg(dir_ts);
4347                     sop->args[1] = temp_arg(arg_ts->mem_base);
4348                     sop->args[2] = arg_ts->mem_offset;
4349 
4350                     arg_ts->state = TS_MEM;
4351                 }
4352                 /* Drop outputs that are dead.  */
4353                 if (IS_DEAD_ARG(i)) {
4354                     arg_ts->state = TS_DEAD;
4355                 }
4356             }
4357         }
4358     }
4359 
4360     return changes;
4361 }
4362 
4363 static void temp_allocate_frame(TCGContext *s, TCGTemp *ts)
4364 {
4365     intptr_t off;
4366     int size, align;
4367 
4368     /* When allocating an object, look at the full type. */
4369     size = tcg_type_size(ts->base_type);
4370     switch (ts->base_type) {
4371     case TCG_TYPE_I32:
4372         align = 4;
4373         break;
4374     case TCG_TYPE_I64:
4375     case TCG_TYPE_V64:
4376         align = 8;
4377         break;
4378     case TCG_TYPE_I128:
4379     case TCG_TYPE_V128:
4380     case TCG_TYPE_V256:
4381         /*
4382          * Note that we do not require aligned storage for V256,
4383          * and that we provide alignment for I128 to match V128,
4384          * even if that's above what the host ABI requires.
4385          */
4386         align = 16;
4387         break;
4388     default:
4389         g_assert_not_reached();
4390     }
4391 
4392     /*
4393      * Assume the stack is sufficiently aligned.
4394      * This affects e.g. ARM NEON, where we have 8 byte stack alignment
4395      * and do not require 16 byte vector alignment.  This seems slightly
4396      * easier than fully parameterizing the above switch statement.
4397      */
4398     align = MIN(TCG_TARGET_STACK_ALIGN, align);
4399     off = ROUND_UP(s->current_frame_offset, align);
4400 
4401     /* If we've exhausted the stack frame, restart with a smaller TB. */
4402     if (off + size > s->frame_end) {
4403         tcg_raise_tb_overflow(s);
4404     }
4405     s->current_frame_offset = off + size;
4406 #if defined(__sparc__)
4407     off += TCG_TARGET_STACK_BIAS;
4408 #endif
4409 
4410     /* If the object was subdivided, assign memory to all the parts. */
4411     if (ts->base_type != ts->type) {
4412         int part_size = tcg_type_size(ts->type);
4413         int part_count = size / part_size;
4414 
4415         /*
4416          * Each part is allocated sequentially in tcg_temp_new_internal.
4417          * Jump back to the first part by subtracting the current index.
4418          */
4419         ts -= ts->temp_subindex;
4420         for (int i = 0; i < part_count; ++i) {
4421             ts[i].mem_offset = off + i * part_size;
4422             ts[i].mem_base = s->frame_temp;
4423             ts[i].mem_allocated = 1;
4424         }
4425     } else {
4426         ts->mem_offset = off;
4427         ts->mem_base = s->frame_temp;
4428         ts->mem_allocated = 1;
4429     }
4430 }
4431 
4432 /* Assign @reg to @ts, and update reg_to_temp[]. */
4433 static void set_temp_val_reg(TCGContext *s, TCGTemp *ts, TCGReg reg)
4434 {
4435     if (ts->val_type == TEMP_VAL_REG) {
4436         TCGReg old = ts->reg;
4437         tcg_debug_assert(s->reg_to_temp[old] == ts);
4438         if (old == reg) {
4439             return;
4440         }
4441         s->reg_to_temp[old] = NULL;
4442     }
4443     tcg_debug_assert(s->reg_to_temp[reg] == NULL);
4444     s->reg_to_temp[reg] = ts;
4445     ts->val_type = TEMP_VAL_REG;
4446     ts->reg = reg;
4447 }
4448 
4449 /* Assign a non-register value type to @ts, and update reg_to_temp[]. */
4450 static void set_temp_val_nonreg(TCGContext *s, TCGTemp *ts, TCGTempVal type)
4451 {
4452     tcg_debug_assert(type != TEMP_VAL_REG);
4453     if (ts->val_type == TEMP_VAL_REG) {
4454         TCGReg reg = ts->reg;
4455         tcg_debug_assert(s->reg_to_temp[reg] == ts);
4456         s->reg_to_temp[reg] = NULL;
4457     }
4458     ts->val_type = type;
4459 }
4460 
4461 static void temp_load(TCGContext *, TCGTemp *, TCGRegSet, TCGRegSet, TCGRegSet);
4462 
4463 /* Mark a temporary as free or dead.  If 'free_or_dead' is negative,
4464    mark it free; otherwise mark it dead.  */
4465 static void temp_free_or_dead(TCGContext *s, TCGTemp *ts, int free_or_dead)
4466 {
4467     TCGTempVal new_type;
4468 
4469     switch (ts->kind) {
4470     case TEMP_FIXED:
4471         return;
4472     case TEMP_GLOBAL:
4473     case TEMP_TB:
4474         new_type = TEMP_VAL_MEM;
4475         break;
4476     case TEMP_EBB:
4477         new_type = free_or_dead < 0 ? TEMP_VAL_MEM : TEMP_VAL_DEAD;
4478         break;
4479     case TEMP_CONST:
4480         new_type = TEMP_VAL_CONST;
4481         break;
4482     default:
4483         g_assert_not_reached();
4484     }
4485     set_temp_val_nonreg(s, ts, new_type);
4486 }
4487 
4488 /* Mark a temporary as dead.  */
4489 static inline void temp_dead(TCGContext *s, TCGTemp *ts)
4490 {
4491     temp_free_or_dead(s, ts, 1);
4492 }
4493 
4494 /* Sync a temporary to memory. 'allocated_regs' is used in case a temporary
4495    registers needs to be allocated to store a constant.  If 'free_or_dead'
4496    is non-zero, subsequently release the temporary; if it is positive, the
4497    temp is dead; if it is negative, the temp is free.  */
4498 static void temp_sync(TCGContext *s, TCGTemp *ts, TCGRegSet allocated_regs,
4499                       TCGRegSet preferred_regs, int free_or_dead)
4500 {
4501     if (!temp_readonly(ts) && !ts->mem_coherent) {
4502         if (!ts->mem_allocated) {
4503             temp_allocate_frame(s, ts);
4504         }
4505         switch (ts->val_type) {
4506         case TEMP_VAL_CONST:
4507             /* If we're going to free the temp immediately, then we won't
4508                require it later in a register, so attempt to store the
4509                constant to memory directly.  */
4510             if (free_or_dead
4511                 && tcg_out_sti(s, ts->type, ts->val,
4512                                ts->mem_base->reg, ts->mem_offset)) {
4513                 break;
4514             }
4515             temp_load(s, ts, tcg_target_available_regs[ts->type],
4516                       allocated_regs, preferred_regs);
4517             /* fallthrough */
4518 
4519         case TEMP_VAL_REG:
4520             tcg_out_st(s, ts->type, ts->reg,
4521                        ts->mem_base->reg, ts->mem_offset);
4522             break;
4523 
4524         case TEMP_VAL_MEM:
4525             break;
4526 
4527         case TEMP_VAL_DEAD:
4528         default:
4529             g_assert_not_reached();
4530         }
4531         ts->mem_coherent = 1;
4532     }
4533     if (free_or_dead) {
4534         temp_free_or_dead(s, ts, free_or_dead);
4535     }
4536 }
4537 
4538 /* free register 'reg' by spilling the corresponding temporary if necessary */
4539 static void tcg_reg_free(TCGContext *s, TCGReg reg, TCGRegSet allocated_regs)
4540 {
4541     TCGTemp *ts = s->reg_to_temp[reg];
4542     if (ts != NULL) {
4543         temp_sync(s, ts, allocated_regs, 0, -1);
4544     }
4545 }
4546 
4547 /**
4548  * tcg_reg_alloc:
4549  * @required_regs: Set of registers in which we must allocate.
4550  * @allocated_regs: Set of registers which must be avoided.
4551  * @preferred_regs: Set of registers we should prefer.
4552  * @rev: True if we search the registers in "indirect" order.
4553  *
4554  * The allocated register must be in @required_regs & ~@allocated_regs,
4555  * but if we can put it in @preferred_regs we may save a move later.
4556  */
4557 static TCGReg tcg_reg_alloc(TCGContext *s, TCGRegSet required_regs,
4558                             TCGRegSet allocated_regs,
4559                             TCGRegSet preferred_regs, bool rev)
4560 {
4561     int i, j, f, n = ARRAY_SIZE(tcg_target_reg_alloc_order);
4562     TCGRegSet reg_ct[2];
4563     const int *order;
4564 
4565     reg_ct[1] = required_regs & ~allocated_regs;
4566     tcg_debug_assert(reg_ct[1] != 0);
4567     reg_ct[0] = reg_ct[1] & preferred_regs;
4568 
4569     /* Skip the preferred_regs option if it cannot be satisfied,
4570        or if the preference made no difference.  */
4571     f = reg_ct[0] == 0 || reg_ct[0] == reg_ct[1];
4572 
4573     order = rev ? indirect_reg_alloc_order : tcg_target_reg_alloc_order;
4574 
4575     /* Try free registers, preferences first.  */
4576     for (j = f; j < 2; j++) {
4577         TCGRegSet set = reg_ct[j];
4578 
4579         if (tcg_regset_single(set)) {
4580             /* One register in the set.  */
4581             TCGReg reg = tcg_regset_first(set);
4582             if (s->reg_to_temp[reg] == NULL) {
4583                 return reg;
4584             }
4585         } else {
4586             for (i = 0; i < n; i++) {
4587                 TCGReg reg = order[i];
4588                 if (s->reg_to_temp[reg] == NULL &&
4589                     tcg_regset_test_reg(set, reg)) {
4590                     return reg;
4591                 }
4592             }
4593         }
4594     }
4595 
4596     /* We must spill something.  */
4597     for (j = f; j < 2; j++) {
4598         TCGRegSet set = reg_ct[j];
4599 
4600         if (tcg_regset_single(set)) {
4601             /* One register in the set.  */
4602             TCGReg reg = tcg_regset_first(set);
4603             tcg_reg_free(s, reg, allocated_regs);
4604             return reg;
4605         } else {
4606             for (i = 0; i < n; i++) {
4607                 TCGReg reg = order[i];
4608                 if (tcg_regset_test_reg(set, reg)) {
4609                     tcg_reg_free(s, reg, allocated_regs);
4610                     return reg;
4611                 }
4612             }
4613         }
4614     }
4615 
4616     g_assert_not_reached();
4617 }
4618 
4619 static TCGReg tcg_reg_alloc_pair(TCGContext *s, TCGRegSet required_regs,
4620                                  TCGRegSet allocated_regs,
4621                                  TCGRegSet preferred_regs, bool rev)
4622 {
4623     int i, j, k, fmin, n = ARRAY_SIZE(tcg_target_reg_alloc_order);
4624     TCGRegSet reg_ct[2];
4625     const int *order;
4626 
4627     /* Ensure that if I is not in allocated_regs, I+1 is not either. */
4628     reg_ct[1] = required_regs & ~(allocated_regs | (allocated_regs >> 1));
4629     tcg_debug_assert(reg_ct[1] != 0);
4630     reg_ct[0] = reg_ct[1] & preferred_regs;
4631 
4632     order = rev ? indirect_reg_alloc_order : tcg_target_reg_alloc_order;
4633 
4634     /*
4635      * Skip the preferred_regs option if it cannot be satisfied,
4636      * or if the preference made no difference.
4637      */
4638     k = reg_ct[0] == 0 || reg_ct[0] == reg_ct[1];
4639 
4640     /*
4641      * Minimize the number of flushes by looking for 2 free registers first,
4642      * then a single flush, then two flushes.
4643      */
4644     for (fmin = 2; fmin >= 0; fmin--) {
4645         for (j = k; j < 2; j++) {
4646             TCGRegSet set = reg_ct[j];
4647 
4648             for (i = 0; i < n; i++) {
4649                 TCGReg reg = order[i];
4650 
4651                 if (tcg_regset_test_reg(set, reg)) {
4652                     int f = !s->reg_to_temp[reg] + !s->reg_to_temp[reg + 1];
4653                     if (f >= fmin) {
4654                         tcg_reg_free(s, reg, allocated_regs);
4655                         tcg_reg_free(s, reg + 1, allocated_regs);
4656                         return reg;
4657                     }
4658                 }
4659             }
4660         }
4661     }
4662     g_assert_not_reached();
4663 }
4664 
4665 /* Make sure the temporary is in a register.  If needed, allocate the register
4666    from DESIRED while avoiding ALLOCATED.  */
4667 static void temp_load(TCGContext *s, TCGTemp *ts, TCGRegSet desired_regs,
4668                       TCGRegSet allocated_regs, TCGRegSet preferred_regs)
4669 {
4670     TCGReg reg;
4671 
4672     switch (ts->val_type) {
4673     case TEMP_VAL_REG:
4674         return;
4675     case TEMP_VAL_CONST:
4676         reg = tcg_reg_alloc(s, desired_regs, allocated_regs,
4677                             preferred_regs, ts->indirect_base);
4678         if (ts->type <= TCG_TYPE_I64) {
4679             tcg_out_movi(s, ts->type, reg, ts->val);
4680         } else {
4681             uint64_t val = ts->val;
4682             MemOp vece = MO_64;
4683 
4684             /*
4685              * Find the minimal vector element that matches the constant.
4686              * The targets will, in general, have to do this search anyway,
4687              * do this generically.
4688              */
4689             if (val == dup_const(MO_8, val)) {
4690                 vece = MO_8;
4691             } else if (val == dup_const(MO_16, val)) {
4692                 vece = MO_16;
4693             } else if (val == dup_const(MO_32, val)) {
4694                 vece = MO_32;
4695             }
4696 
4697             tcg_out_dupi_vec(s, ts->type, vece, reg, ts->val);
4698         }
4699         ts->mem_coherent = 0;
4700         break;
4701     case TEMP_VAL_MEM:
4702         if (!ts->mem_allocated) {
4703             temp_allocate_frame(s, ts);
4704         }
4705         reg = tcg_reg_alloc(s, desired_regs, allocated_regs,
4706                             preferred_regs, ts->indirect_base);
4707         tcg_out_ld(s, ts->type, reg, ts->mem_base->reg, ts->mem_offset);
4708         ts->mem_coherent = 1;
4709         break;
4710     case TEMP_VAL_DEAD:
4711     default:
4712         g_assert_not_reached();
4713     }
4714     set_temp_val_reg(s, ts, reg);
4715 }
4716 
4717 /* Save a temporary to memory. 'allocated_regs' is used in case a
4718    temporary registers needs to be allocated to store a constant.  */
4719 static void temp_save(TCGContext *s, TCGTemp *ts, TCGRegSet allocated_regs)
4720 {
4721     /* The liveness analysis already ensures that globals are back
4722        in memory. Keep an tcg_debug_assert for safety. */
4723     tcg_debug_assert(ts->val_type == TEMP_VAL_MEM || temp_readonly(ts));
4724 }
4725 
4726 /* save globals to their canonical location and assume they can be
4727    modified be the following code. 'allocated_regs' is used in case a
4728    temporary registers needs to be allocated to store a constant. */
4729 static void save_globals(TCGContext *s, TCGRegSet allocated_regs)
4730 {
4731     int i, n;
4732 
4733     for (i = 0, n = s->nb_globals; i < n; i++) {
4734         temp_save(s, &s->temps[i], allocated_regs);
4735     }
4736 }
4737 
4738 /* sync globals to their canonical location and assume they can be
4739    read by the following code. 'allocated_regs' is used in case a
4740    temporary registers needs to be allocated to store a constant. */
4741 static void sync_globals(TCGContext *s, TCGRegSet allocated_regs)
4742 {
4743     int i, n;
4744 
4745     for (i = 0, n = s->nb_globals; i < n; i++) {
4746         TCGTemp *ts = &s->temps[i];
4747         tcg_debug_assert(ts->val_type != TEMP_VAL_REG
4748                          || ts->kind == TEMP_FIXED
4749                          || ts->mem_coherent);
4750     }
4751 }
4752 
4753 /* at the end of a basic block, we assume all temporaries are dead and
4754    all globals are stored at their canonical location. */
4755 static void tcg_reg_alloc_bb_end(TCGContext *s, TCGRegSet allocated_regs)
4756 {
4757     int i;
4758 
4759     for (i = s->nb_globals; i < s->nb_temps; i++) {
4760         TCGTemp *ts = &s->temps[i];
4761 
4762         switch (ts->kind) {
4763         case TEMP_TB:
4764             temp_save(s, ts, allocated_regs);
4765             break;
4766         case TEMP_EBB:
4767             /* The liveness analysis already ensures that temps are dead.
4768                Keep an tcg_debug_assert for safety. */
4769             tcg_debug_assert(ts->val_type == TEMP_VAL_DEAD);
4770             break;
4771         case TEMP_CONST:
4772             /* Similarly, we should have freed any allocated register. */
4773             tcg_debug_assert(ts->val_type == TEMP_VAL_CONST);
4774             break;
4775         default:
4776             g_assert_not_reached();
4777         }
4778     }
4779 
4780     save_globals(s, allocated_regs);
4781 }
4782 
4783 /*
4784  * At a conditional branch, we assume all temporaries are dead unless
4785  * explicitly live-across-conditional-branch; all globals and local
4786  * temps are synced to their location.
4787  */
4788 static void tcg_reg_alloc_cbranch(TCGContext *s, TCGRegSet allocated_regs)
4789 {
4790     sync_globals(s, allocated_regs);
4791 
4792     for (int i = s->nb_globals; i < s->nb_temps; i++) {
4793         TCGTemp *ts = &s->temps[i];
4794         /*
4795          * The liveness analysis already ensures that temps are dead.
4796          * Keep tcg_debug_asserts for safety.
4797          */
4798         switch (ts->kind) {
4799         case TEMP_TB:
4800             tcg_debug_assert(ts->val_type != TEMP_VAL_REG || ts->mem_coherent);
4801             break;
4802         case TEMP_EBB:
4803         case TEMP_CONST:
4804             break;
4805         default:
4806             g_assert_not_reached();
4807         }
4808     }
4809 }
4810 
4811 /*
4812  * Specialized code generation for INDEX_op_mov_* with a constant.
4813  */
4814 static void tcg_reg_alloc_do_movi(TCGContext *s, TCGTemp *ots,
4815                                   tcg_target_ulong val, TCGLifeData arg_life,
4816                                   TCGRegSet preferred_regs)
4817 {
4818     /* ENV should not be modified.  */
4819     tcg_debug_assert(!temp_readonly(ots));
4820 
4821     /* The movi is not explicitly generated here.  */
4822     set_temp_val_nonreg(s, ots, TEMP_VAL_CONST);
4823     ots->val = val;
4824     ots->mem_coherent = 0;
4825     if (NEED_SYNC_ARG(0)) {
4826         temp_sync(s, ots, s->reserved_regs, preferred_regs, IS_DEAD_ARG(0));
4827     } else if (IS_DEAD_ARG(0)) {
4828         temp_dead(s, ots);
4829     }
4830 }
4831 
4832 /*
4833  * Specialized code generation for INDEX_op_mov_*.
4834  */
4835 static void tcg_reg_alloc_mov(TCGContext *s, const TCGOp *op)
4836 {
4837     const TCGLifeData arg_life = op->life;
4838     TCGRegSet allocated_regs, preferred_regs;
4839     TCGTemp *ts, *ots;
4840     TCGType otype, itype;
4841     TCGReg oreg, ireg;
4842 
4843     allocated_regs = s->reserved_regs;
4844     preferred_regs = output_pref(op, 0);
4845     ots = arg_temp(op->args[0]);
4846     ts = arg_temp(op->args[1]);
4847 
4848     /* ENV should not be modified.  */
4849     tcg_debug_assert(!temp_readonly(ots));
4850 
4851     /* Note that otype != itype for no-op truncation.  */
4852     otype = ots->type;
4853     itype = ts->type;
4854 
4855     if (ts->val_type == TEMP_VAL_CONST) {
4856         /* propagate constant or generate sti */
4857         tcg_target_ulong val = ts->val;
4858         if (IS_DEAD_ARG(1)) {
4859             temp_dead(s, ts);
4860         }
4861         tcg_reg_alloc_do_movi(s, ots, val, arg_life, preferred_regs);
4862         return;
4863     }
4864 
4865     /* If the source value is in memory we're going to be forced
4866        to have it in a register in order to perform the copy.  Copy
4867        the SOURCE value into its own register first, that way we
4868        don't have to reload SOURCE the next time it is used. */
4869     if (ts->val_type == TEMP_VAL_MEM) {
4870         temp_load(s, ts, tcg_target_available_regs[itype],
4871                   allocated_regs, preferred_regs);
4872     }
4873     tcg_debug_assert(ts->val_type == TEMP_VAL_REG);
4874     ireg = ts->reg;
4875 
4876     if (IS_DEAD_ARG(0)) {
4877         /* mov to a non-saved dead register makes no sense (even with
4878            liveness analysis disabled). */
4879         tcg_debug_assert(NEED_SYNC_ARG(0));
4880         if (!ots->mem_allocated) {
4881             temp_allocate_frame(s, ots);
4882         }
4883         tcg_out_st(s, otype, ireg, ots->mem_base->reg, ots->mem_offset);
4884         if (IS_DEAD_ARG(1)) {
4885             temp_dead(s, ts);
4886         }
4887         temp_dead(s, ots);
4888         return;
4889     }
4890 
4891     if (IS_DEAD_ARG(1) && ts->kind != TEMP_FIXED) {
4892         /*
4893          * The mov can be suppressed.  Kill input first, so that it
4894          * is unlinked from reg_to_temp, then set the output to the
4895          * reg that we saved from the input.
4896          */
4897         temp_dead(s, ts);
4898         oreg = ireg;
4899     } else {
4900         if (ots->val_type == TEMP_VAL_REG) {
4901             oreg = ots->reg;
4902         } else {
4903             /* Make sure to not spill the input register during allocation. */
4904             oreg = tcg_reg_alloc(s, tcg_target_available_regs[otype],
4905                                  allocated_regs | ((TCGRegSet)1 << ireg),
4906                                  preferred_regs, ots->indirect_base);
4907         }
4908         if (!tcg_out_mov(s, otype, oreg, ireg)) {
4909             /*
4910              * Cross register class move not supported.
4911              * Store the source register into the destination slot
4912              * and leave the destination temp as TEMP_VAL_MEM.
4913              */
4914             assert(!temp_readonly(ots));
4915             if (!ts->mem_allocated) {
4916                 temp_allocate_frame(s, ots);
4917             }
4918             tcg_out_st(s, ts->type, ireg, ots->mem_base->reg, ots->mem_offset);
4919             set_temp_val_nonreg(s, ts, TEMP_VAL_MEM);
4920             ots->mem_coherent = 1;
4921             return;
4922         }
4923     }
4924     set_temp_val_reg(s, ots, oreg);
4925     ots->mem_coherent = 0;
4926 
4927     if (NEED_SYNC_ARG(0)) {
4928         temp_sync(s, ots, allocated_regs, 0, 0);
4929     }
4930 }
4931 
4932 /*
4933  * Specialized code generation for INDEX_op_dup_vec.
4934  */
4935 static void tcg_reg_alloc_dup(TCGContext *s, const TCGOp *op)
4936 {
4937     const TCGLifeData arg_life = op->life;
4938     TCGRegSet dup_out_regs, dup_in_regs;
4939     const TCGArgConstraint *dup_args_ct;
4940     TCGTemp *its, *ots;
4941     TCGType itype, vtype;
4942     unsigned vece;
4943     int lowpart_ofs;
4944     bool ok;
4945 
4946     ots = arg_temp(op->args[0]);
4947     its = arg_temp(op->args[1]);
4948 
4949     /* ENV should not be modified.  */
4950     tcg_debug_assert(!temp_readonly(ots));
4951 
4952     itype = its->type;
4953     vece = TCGOP_VECE(op);
4954     vtype = TCGOP_TYPE(op);
4955 
4956     if (its->val_type == TEMP_VAL_CONST) {
4957         /* Propagate constant via movi -> dupi.  */
4958         tcg_target_ulong val = its->val;
4959         if (IS_DEAD_ARG(1)) {
4960             temp_dead(s, its);
4961         }
4962         tcg_reg_alloc_do_movi(s, ots, val, arg_life, output_pref(op, 0));
4963         return;
4964     }
4965 
4966     dup_args_ct = opcode_args_ct(op);
4967     dup_out_regs = dup_args_ct[0].regs;
4968     dup_in_regs = dup_args_ct[1].regs;
4969 
4970     /* Allocate the output register now.  */
4971     if (ots->val_type != TEMP_VAL_REG) {
4972         TCGRegSet allocated_regs = s->reserved_regs;
4973         TCGReg oreg;
4974 
4975         if (!IS_DEAD_ARG(1) && its->val_type == TEMP_VAL_REG) {
4976             /* Make sure to not spill the input register. */
4977             tcg_regset_set_reg(allocated_regs, its->reg);
4978         }
4979         oreg = tcg_reg_alloc(s, dup_out_regs, allocated_regs,
4980                              output_pref(op, 0), ots->indirect_base);
4981         set_temp_val_reg(s, ots, oreg);
4982     }
4983 
4984     switch (its->val_type) {
4985     case TEMP_VAL_REG:
4986         /*
4987          * The dup constriaints must be broad, covering all possible VECE.
4988          * However, tcg_op_dup_vec() gets to see the VECE and we allow it
4989          * to fail, indicating that extra moves are required for that case.
4990          */
4991         if (tcg_regset_test_reg(dup_in_regs, its->reg)) {
4992             if (tcg_out_dup_vec(s, vtype, vece, ots->reg, its->reg)) {
4993                 goto done;
4994             }
4995             /* Try again from memory or a vector input register.  */
4996         }
4997         if (!its->mem_coherent) {
4998             /*
4999              * The input register is not synced, and so an extra store
5000              * would be required to use memory.  Attempt an integer-vector
5001              * register move first.  We do not have a TCGRegSet for this.
5002              */
5003             if (tcg_out_mov(s, itype, ots->reg, its->reg)) {
5004                 break;
5005             }
5006             /* Sync the temp back to its slot and load from there.  */
5007             temp_sync(s, its, s->reserved_regs, 0, 0);
5008         }
5009         /* fall through */
5010 
5011     case TEMP_VAL_MEM:
5012         lowpart_ofs = 0;
5013         if (HOST_BIG_ENDIAN) {
5014             lowpart_ofs = tcg_type_size(itype) - (1 << vece);
5015         }
5016         if (tcg_out_dupm_vec(s, vtype, vece, ots->reg, its->mem_base->reg,
5017                              its->mem_offset + lowpart_ofs)) {
5018             goto done;
5019         }
5020         /* Load the input into the destination vector register. */
5021         tcg_out_ld(s, itype, ots->reg, its->mem_base->reg, its->mem_offset);
5022         break;
5023 
5024     default:
5025         g_assert_not_reached();
5026     }
5027 
5028     /* We now have a vector input register, so dup must succeed. */
5029     ok = tcg_out_dup_vec(s, vtype, vece, ots->reg, ots->reg);
5030     tcg_debug_assert(ok);
5031 
5032  done:
5033     ots->mem_coherent = 0;
5034     if (IS_DEAD_ARG(1)) {
5035         temp_dead(s, its);
5036     }
5037     if (NEED_SYNC_ARG(0)) {
5038         temp_sync(s, ots, s->reserved_regs, 0, 0);
5039     }
5040     if (IS_DEAD_ARG(0)) {
5041         temp_dead(s, ots);
5042     }
5043 }
5044 
5045 static void tcg_reg_alloc_op(TCGContext *s, const TCGOp *op)
5046 {
5047     const TCGLifeData arg_life = op->life;
5048     const TCGOpDef * const def = &tcg_op_defs[op->opc];
5049     TCGRegSet i_allocated_regs;
5050     TCGRegSet o_allocated_regs;
5051     int i, k, nb_iargs, nb_oargs;
5052     TCGReg reg;
5053     TCGArg arg;
5054     const TCGArgConstraint *args_ct;
5055     const TCGArgConstraint *arg_ct;
5056     TCGTemp *ts;
5057     TCGArg new_args[TCG_MAX_OP_ARGS];
5058     int const_args[TCG_MAX_OP_ARGS];
5059     TCGCond op_cond;
5060 
5061     nb_oargs = def->nb_oargs;
5062     nb_iargs = def->nb_iargs;
5063 
5064     /* copy constants */
5065     memcpy(new_args + nb_oargs + nb_iargs,
5066            op->args + nb_oargs + nb_iargs,
5067            sizeof(TCGArg) * def->nb_cargs);
5068 
5069     i_allocated_regs = s->reserved_regs;
5070     o_allocated_regs = s->reserved_regs;
5071 
5072     switch (op->opc) {
5073     case INDEX_op_brcond_i32:
5074     case INDEX_op_brcond_i64:
5075         op_cond = op->args[2];
5076         break;
5077     case INDEX_op_setcond_i32:
5078     case INDEX_op_setcond_i64:
5079     case INDEX_op_negsetcond_i32:
5080     case INDEX_op_negsetcond_i64:
5081     case INDEX_op_cmp_vec:
5082         op_cond = op->args[3];
5083         break;
5084     case INDEX_op_brcond2_i32:
5085         op_cond = op->args[4];
5086         break;
5087     case INDEX_op_movcond_i32:
5088     case INDEX_op_movcond_i64:
5089     case INDEX_op_setcond2_i32:
5090     case INDEX_op_cmpsel_vec:
5091         op_cond = op->args[5];
5092         break;
5093     default:
5094         /* No condition within opcode. */
5095         op_cond = TCG_COND_ALWAYS;
5096         break;
5097     }
5098 
5099     args_ct = opcode_args_ct(op);
5100 
5101     /* satisfy input constraints */
5102     for (k = 0; k < nb_iargs; k++) {
5103         TCGRegSet i_preferred_regs, i_required_regs;
5104         bool allocate_new_reg, copyto_new_reg;
5105         TCGTemp *ts2;
5106         int i1, i2;
5107 
5108         i = args_ct[nb_oargs + k].sort_index;
5109         arg = op->args[i];
5110         arg_ct = &args_ct[i];
5111         ts = arg_temp(arg);
5112 
5113         if (ts->val_type == TEMP_VAL_CONST) {
5114 #ifdef TCG_REG_ZERO
5115             if (ts->val == 0 && (arg_ct->ct & TCG_CT_REG_ZERO)) {
5116                 /* Hardware zero register: indicate register via non-const. */
5117                 const_args[i] = 0;
5118                 new_args[i] = TCG_REG_ZERO;
5119                 continue;
5120             }
5121 #endif
5122 
5123             if (tcg_target_const_match(ts->val, arg_ct->ct, ts->type,
5124                                        op_cond, TCGOP_VECE(op))) {
5125                 /* constant is OK for instruction */
5126                 const_args[i] = 1;
5127                 new_args[i] = ts->val;
5128                 continue;
5129             }
5130         }
5131 
5132         reg = ts->reg;
5133         i_preferred_regs = 0;
5134         i_required_regs = arg_ct->regs;
5135         allocate_new_reg = false;
5136         copyto_new_reg = false;
5137 
5138         switch (arg_ct->pair) {
5139         case 0: /* not paired */
5140             if (arg_ct->ialias) {
5141                 i_preferred_regs = output_pref(op, arg_ct->alias_index);
5142 
5143                 /*
5144                  * If the input is readonly, then it cannot also be an
5145                  * output and aliased to itself.  If the input is not
5146                  * dead after the instruction, we must allocate a new
5147                  * register and move it.
5148                  */
5149                 if (temp_readonly(ts) || !IS_DEAD_ARG(i)
5150                     || args_ct[arg_ct->alias_index].newreg) {
5151                     allocate_new_reg = true;
5152                 } else if (ts->val_type == TEMP_VAL_REG) {
5153                     /*
5154                      * Check if the current register has already been
5155                      * allocated for another input.
5156                      */
5157                     allocate_new_reg =
5158                         tcg_regset_test_reg(i_allocated_regs, reg);
5159                 }
5160             }
5161             if (!allocate_new_reg) {
5162                 temp_load(s, ts, i_required_regs, i_allocated_regs,
5163                           i_preferred_regs);
5164                 reg = ts->reg;
5165                 allocate_new_reg = !tcg_regset_test_reg(i_required_regs, reg);
5166             }
5167             if (allocate_new_reg) {
5168                 /*
5169                  * Allocate a new register matching the constraint
5170                  * and move the temporary register into it.
5171                  */
5172                 temp_load(s, ts, tcg_target_available_regs[ts->type],
5173                           i_allocated_regs, 0);
5174                 reg = tcg_reg_alloc(s, i_required_regs, i_allocated_regs,
5175                                     i_preferred_regs, ts->indirect_base);
5176                 copyto_new_reg = true;
5177             }
5178             break;
5179 
5180         case 1:
5181             /* First of an input pair; if i1 == i2, the second is an output. */
5182             i1 = i;
5183             i2 = arg_ct->pair_index;
5184             ts2 = i1 != i2 ? arg_temp(op->args[i2]) : NULL;
5185 
5186             /*
5187              * It is easier to default to allocating a new pair
5188              * and to identify a few cases where it's not required.
5189              */
5190             if (arg_ct->ialias) {
5191                 i_preferred_regs = output_pref(op, arg_ct->alias_index);
5192                 if (IS_DEAD_ARG(i1) &&
5193                     IS_DEAD_ARG(i2) &&
5194                     !temp_readonly(ts) &&
5195                     ts->val_type == TEMP_VAL_REG &&
5196                     ts->reg < TCG_TARGET_NB_REGS - 1 &&
5197                     tcg_regset_test_reg(i_required_regs, reg) &&
5198                     !tcg_regset_test_reg(i_allocated_regs, reg) &&
5199                     !tcg_regset_test_reg(i_allocated_regs, reg + 1) &&
5200                     (ts2
5201                      ? ts2->val_type == TEMP_VAL_REG &&
5202                        ts2->reg == reg + 1 &&
5203                        !temp_readonly(ts2)
5204                      : s->reg_to_temp[reg + 1] == NULL)) {
5205                     break;
5206                 }
5207             } else {
5208                 /* Without aliasing, the pair must also be an input. */
5209                 tcg_debug_assert(ts2);
5210                 if (ts->val_type == TEMP_VAL_REG &&
5211                     ts2->val_type == TEMP_VAL_REG &&
5212                     ts2->reg == reg + 1 &&
5213                     tcg_regset_test_reg(i_required_regs, reg)) {
5214                     break;
5215                 }
5216             }
5217             reg = tcg_reg_alloc_pair(s, i_required_regs, i_allocated_regs,
5218                                      0, ts->indirect_base);
5219             goto do_pair;
5220 
5221         case 2: /* pair second */
5222             reg = new_args[arg_ct->pair_index] + 1;
5223             goto do_pair;
5224 
5225         case 3: /* ialias with second output, no first input */
5226             tcg_debug_assert(arg_ct->ialias);
5227             i_preferred_regs = output_pref(op, arg_ct->alias_index);
5228 
5229             if (IS_DEAD_ARG(i) &&
5230                 !temp_readonly(ts) &&
5231                 ts->val_type == TEMP_VAL_REG &&
5232                 reg > 0 &&
5233                 s->reg_to_temp[reg - 1] == NULL &&
5234                 tcg_regset_test_reg(i_required_regs, reg) &&
5235                 !tcg_regset_test_reg(i_allocated_regs, reg) &&
5236                 !tcg_regset_test_reg(i_allocated_regs, reg - 1)) {
5237                 tcg_regset_set_reg(i_allocated_regs, reg - 1);
5238                 break;
5239             }
5240             reg = tcg_reg_alloc_pair(s, i_required_regs >> 1,
5241                                      i_allocated_regs, 0,
5242                                      ts->indirect_base);
5243             tcg_regset_set_reg(i_allocated_regs, reg);
5244             reg += 1;
5245             goto do_pair;
5246 
5247         do_pair:
5248             /*
5249              * If an aliased input is not dead after the instruction,
5250              * we must allocate a new register and move it.
5251              */
5252             if (arg_ct->ialias && (!IS_DEAD_ARG(i) || temp_readonly(ts))) {
5253                 TCGRegSet t_allocated_regs = i_allocated_regs;
5254 
5255                 /*
5256                  * Because of the alias, and the continued life, make sure
5257                  * that the temp is somewhere *other* than the reg pair,
5258                  * and we get a copy in reg.
5259                  */
5260                 tcg_regset_set_reg(t_allocated_regs, reg);
5261                 tcg_regset_set_reg(t_allocated_regs, reg + 1);
5262                 if (ts->val_type == TEMP_VAL_REG && ts->reg == reg) {
5263                     /* If ts was already in reg, copy it somewhere else. */
5264                     TCGReg nr;
5265                     bool ok;
5266 
5267                     tcg_debug_assert(ts->kind != TEMP_FIXED);
5268                     nr = tcg_reg_alloc(s, tcg_target_available_regs[ts->type],
5269                                        t_allocated_regs, 0, ts->indirect_base);
5270                     ok = tcg_out_mov(s, ts->type, nr, reg);
5271                     tcg_debug_assert(ok);
5272 
5273                     set_temp_val_reg(s, ts, nr);
5274                 } else {
5275                     temp_load(s, ts, tcg_target_available_regs[ts->type],
5276                               t_allocated_regs, 0);
5277                     copyto_new_reg = true;
5278                 }
5279             } else {
5280                 /* Preferably allocate to reg, otherwise copy. */
5281                 i_required_regs = (TCGRegSet)1 << reg;
5282                 temp_load(s, ts, i_required_regs, i_allocated_regs,
5283                           i_preferred_regs);
5284                 copyto_new_reg = ts->reg != reg;
5285             }
5286             break;
5287 
5288         default:
5289             g_assert_not_reached();
5290         }
5291 
5292         if (copyto_new_reg) {
5293             if (!tcg_out_mov(s, ts->type, reg, ts->reg)) {
5294                 /*
5295                  * Cross register class move not supported.  Sync the
5296                  * temp back to its slot and load from there.
5297                  */
5298                 temp_sync(s, ts, i_allocated_regs, 0, 0);
5299                 tcg_out_ld(s, ts->type, reg,
5300                            ts->mem_base->reg, ts->mem_offset);
5301             }
5302         }
5303         new_args[i] = reg;
5304         const_args[i] = 0;
5305         tcg_regset_set_reg(i_allocated_regs, reg);
5306     }
5307 
5308     /* mark dead temporaries and free the associated registers */
5309     for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
5310         if (IS_DEAD_ARG(i)) {
5311             temp_dead(s, arg_temp(op->args[i]));
5312         }
5313     }
5314 
5315     if (def->flags & TCG_OPF_COND_BRANCH) {
5316         tcg_reg_alloc_cbranch(s, i_allocated_regs);
5317     } else if (def->flags & TCG_OPF_BB_END) {
5318         tcg_reg_alloc_bb_end(s, i_allocated_regs);
5319     } else {
5320         if (def->flags & TCG_OPF_CALL_CLOBBER) {
5321             /* XXX: permit generic clobber register list ? */
5322             for (i = 0; i < TCG_TARGET_NB_REGS; i++) {
5323                 if (tcg_regset_test_reg(tcg_target_call_clobber_regs, i)) {
5324                     tcg_reg_free(s, i, i_allocated_regs);
5325                 }
5326             }
5327         }
5328         if (def->flags & TCG_OPF_SIDE_EFFECTS) {
5329             /* sync globals if the op has side effects and might trigger
5330                an exception. */
5331             sync_globals(s, i_allocated_regs);
5332         }
5333 
5334         /* satisfy the output constraints */
5335         for (k = 0; k < nb_oargs; k++) {
5336             i = args_ct[k].sort_index;
5337             arg = op->args[i];
5338             arg_ct = &args_ct[i];
5339             ts = arg_temp(arg);
5340 
5341             /* ENV should not be modified.  */
5342             tcg_debug_assert(!temp_readonly(ts));
5343 
5344             switch (arg_ct->pair) {
5345             case 0: /* not paired */
5346                 if (arg_ct->oalias && !const_args[arg_ct->alias_index]) {
5347                     reg = new_args[arg_ct->alias_index];
5348                 } else if (arg_ct->newreg) {
5349                     reg = tcg_reg_alloc(s, arg_ct->regs,
5350                                         i_allocated_regs | o_allocated_regs,
5351                                         output_pref(op, k), ts->indirect_base);
5352                 } else {
5353                     reg = tcg_reg_alloc(s, arg_ct->regs, o_allocated_regs,
5354                                         output_pref(op, k), ts->indirect_base);
5355                 }
5356                 break;
5357 
5358             case 1: /* first of pair */
5359                 if (arg_ct->oalias) {
5360                     reg = new_args[arg_ct->alias_index];
5361                 } else if (arg_ct->newreg) {
5362                     reg = tcg_reg_alloc_pair(s, arg_ct->regs,
5363                                              i_allocated_regs | o_allocated_regs,
5364                                              output_pref(op, k),
5365                                              ts->indirect_base);
5366                 } else {
5367                     reg = tcg_reg_alloc_pair(s, arg_ct->regs, o_allocated_regs,
5368                                              output_pref(op, k),
5369                                              ts->indirect_base);
5370                 }
5371                 break;
5372 
5373             case 2: /* second of pair */
5374                 if (arg_ct->oalias) {
5375                     reg = new_args[arg_ct->alias_index];
5376                 } else {
5377                     reg = new_args[arg_ct->pair_index] + 1;
5378                 }
5379                 break;
5380 
5381             case 3: /* first of pair, aliasing with a second input */
5382                 tcg_debug_assert(!arg_ct->newreg);
5383                 reg = new_args[arg_ct->pair_index] - 1;
5384                 break;
5385 
5386             default:
5387                 g_assert_not_reached();
5388             }
5389             tcg_regset_set_reg(o_allocated_regs, reg);
5390             set_temp_val_reg(s, ts, reg);
5391             ts->mem_coherent = 0;
5392             new_args[i] = reg;
5393         }
5394     }
5395 
5396     /* emit instruction */
5397     TCGType type = TCGOP_TYPE(op);
5398     switch (op->opc) {
5399     case INDEX_op_ext_i32_i64:
5400         tcg_out_exts_i32_i64(s, new_args[0], new_args[1]);
5401         break;
5402     case INDEX_op_extu_i32_i64:
5403         tcg_out_extu_i32_i64(s, new_args[0], new_args[1]);
5404         break;
5405     case INDEX_op_extrl_i64_i32:
5406         tcg_out_extrl_i64_i32(s, new_args[0], new_args[1]);
5407         break;
5408 
5409     case INDEX_op_add:
5410     case INDEX_op_and:
5411     case INDEX_op_andc:
5412     case INDEX_op_divs:
5413     case INDEX_op_divu:
5414     case INDEX_op_eqv:
5415     case INDEX_op_mul:
5416     case INDEX_op_mulsh:
5417     case INDEX_op_muluh:
5418     case INDEX_op_nand:
5419     case INDEX_op_nor:
5420     case INDEX_op_or:
5421     case INDEX_op_orc:
5422     case INDEX_op_rems:
5423     case INDEX_op_remu:
5424     case INDEX_op_shl:
5425     case INDEX_op_shr:
5426     case INDEX_op_xor:
5427         {
5428             const TCGOutOpBinary *out =
5429                 container_of(all_outop[op->opc], TCGOutOpBinary, base);
5430 
5431             /* Constants should never appear in the first source operand. */
5432             tcg_debug_assert(!const_args[1]);
5433             if (const_args[2]) {
5434                 out->out_rri(s, type, new_args[0], new_args[1], new_args[2]);
5435             } else {
5436                 out->out_rrr(s, type, new_args[0], new_args[1], new_args[2]);
5437             }
5438         }
5439         break;
5440 
5441     case INDEX_op_sub:
5442         {
5443             const TCGOutOpSubtract *out = &outop_sub;
5444 
5445             /*
5446              * Constants should never appear in the second source operand.
5447              * These are folded to add with negative constant.
5448              */
5449             tcg_debug_assert(!const_args[2]);
5450             if (const_args[1]) {
5451                 out->out_rir(s, type, new_args[0], new_args[1], new_args[2]);
5452             } else {
5453                 out->out_rrr(s, type, new_args[0], new_args[1], new_args[2]);
5454             }
5455         }
5456         break;
5457 
5458     case INDEX_op_neg:
5459     case INDEX_op_not:
5460         {
5461             const TCGOutOpUnary *out =
5462                 container_of(all_outop[op->opc], TCGOutOpUnary, base);
5463 
5464             /* Constants should have been folded. */
5465             tcg_debug_assert(!const_args[1]);
5466             out->out_rr(s, type, new_args[0], new_args[1]);
5467         }
5468         break;
5469 
5470     case INDEX_op_divs2:
5471     case INDEX_op_divu2:
5472         {
5473             const TCGOutOpDivRem *out =
5474                 container_of(all_outop[op->opc], TCGOutOpDivRem, base);
5475 
5476             /* Only used by x86 and s390x, which use matching constraints. */
5477             tcg_debug_assert(new_args[0] == new_args[2]);
5478             tcg_debug_assert(new_args[1] == new_args[3]);
5479             tcg_debug_assert(!const_args[4]);
5480             out->out_rr01r(s, type, new_args[0], new_args[1], new_args[4]);
5481         }
5482         break;
5483 
5484     default:
5485         if (def->flags & TCG_OPF_VECTOR) {
5486             tcg_out_vec_op(s, op->opc, type - TCG_TYPE_V64,
5487                            TCGOP_VECE(op), new_args, const_args);
5488         } else {
5489             tcg_out_op(s, op->opc, type, new_args, const_args);
5490         }
5491         break;
5492     }
5493 
5494     /* move the outputs in the correct register if needed */
5495     for(i = 0; i < nb_oargs; i++) {
5496         ts = arg_temp(op->args[i]);
5497 
5498         /* ENV should not be modified.  */
5499         tcg_debug_assert(!temp_readonly(ts));
5500 
5501         if (NEED_SYNC_ARG(i)) {
5502             temp_sync(s, ts, o_allocated_regs, 0, IS_DEAD_ARG(i));
5503         } else if (IS_DEAD_ARG(i)) {
5504             temp_dead(s, ts);
5505         }
5506     }
5507 }
5508 
5509 static bool tcg_reg_alloc_dup2(TCGContext *s, const TCGOp *op)
5510 {
5511     const TCGLifeData arg_life = op->life;
5512     TCGTemp *ots, *itsl, *itsh;
5513     TCGType vtype = TCGOP_TYPE(op);
5514 
5515     /* This opcode is only valid for 32-bit hosts, for 64-bit elements. */
5516     tcg_debug_assert(TCG_TARGET_REG_BITS == 32);
5517     tcg_debug_assert(TCGOP_VECE(op) == MO_64);
5518 
5519     ots = arg_temp(op->args[0]);
5520     itsl = arg_temp(op->args[1]);
5521     itsh = arg_temp(op->args[2]);
5522 
5523     /* ENV should not be modified.  */
5524     tcg_debug_assert(!temp_readonly(ots));
5525 
5526     /* Allocate the output register now.  */
5527     if (ots->val_type != TEMP_VAL_REG) {
5528         TCGRegSet allocated_regs = s->reserved_regs;
5529         TCGRegSet dup_out_regs = opcode_args_ct(op)[0].regs;
5530         TCGReg oreg;
5531 
5532         /* Make sure to not spill the input registers. */
5533         if (!IS_DEAD_ARG(1) && itsl->val_type == TEMP_VAL_REG) {
5534             tcg_regset_set_reg(allocated_regs, itsl->reg);
5535         }
5536         if (!IS_DEAD_ARG(2) && itsh->val_type == TEMP_VAL_REG) {
5537             tcg_regset_set_reg(allocated_regs, itsh->reg);
5538         }
5539 
5540         oreg = tcg_reg_alloc(s, dup_out_regs, allocated_regs,
5541                              output_pref(op, 0), ots->indirect_base);
5542         set_temp_val_reg(s, ots, oreg);
5543     }
5544 
5545     /* Promote dup2 of immediates to dupi_vec. */
5546     if (itsl->val_type == TEMP_VAL_CONST && itsh->val_type == TEMP_VAL_CONST) {
5547         uint64_t val = deposit64(itsl->val, 32, 32, itsh->val);
5548         MemOp vece = MO_64;
5549 
5550         if (val == dup_const(MO_8, val)) {
5551             vece = MO_8;
5552         } else if (val == dup_const(MO_16, val)) {
5553             vece = MO_16;
5554         } else if (val == dup_const(MO_32, val)) {
5555             vece = MO_32;
5556         }
5557 
5558         tcg_out_dupi_vec(s, vtype, vece, ots->reg, val);
5559         goto done;
5560     }
5561 
5562     /* If the two inputs form one 64-bit value, try dupm_vec. */
5563     if (itsl->temp_subindex == HOST_BIG_ENDIAN &&
5564         itsh->temp_subindex == !HOST_BIG_ENDIAN &&
5565         itsl == itsh + (HOST_BIG_ENDIAN ? 1 : -1)) {
5566         TCGTemp *its = itsl - HOST_BIG_ENDIAN;
5567 
5568         temp_sync(s, its + 0, s->reserved_regs, 0, 0);
5569         temp_sync(s, its + 1, s->reserved_regs, 0, 0);
5570 
5571         if (tcg_out_dupm_vec(s, vtype, MO_64, ots->reg,
5572                              its->mem_base->reg, its->mem_offset)) {
5573             goto done;
5574         }
5575     }
5576 
5577     /* Fall back to generic expansion. */
5578     return false;
5579 
5580  done:
5581     ots->mem_coherent = 0;
5582     if (IS_DEAD_ARG(1)) {
5583         temp_dead(s, itsl);
5584     }
5585     if (IS_DEAD_ARG(2)) {
5586         temp_dead(s, itsh);
5587     }
5588     if (NEED_SYNC_ARG(0)) {
5589         temp_sync(s, ots, s->reserved_regs, 0, IS_DEAD_ARG(0));
5590     } else if (IS_DEAD_ARG(0)) {
5591         temp_dead(s, ots);
5592     }
5593     return true;
5594 }
5595 
5596 static void load_arg_reg(TCGContext *s, TCGReg reg, TCGTemp *ts,
5597                          TCGRegSet allocated_regs)
5598 {
5599     if (ts->val_type == TEMP_VAL_REG) {
5600         if (ts->reg != reg) {
5601             tcg_reg_free(s, reg, allocated_regs);
5602             if (!tcg_out_mov(s, ts->type, reg, ts->reg)) {
5603                 /*
5604                  * Cross register class move not supported.  Sync the
5605                  * temp back to its slot and load from there.
5606                  */
5607                 temp_sync(s, ts, allocated_regs, 0, 0);
5608                 tcg_out_ld(s, ts->type, reg,
5609                            ts->mem_base->reg, ts->mem_offset);
5610             }
5611         }
5612     } else {
5613         TCGRegSet arg_set = 0;
5614 
5615         tcg_reg_free(s, reg, allocated_regs);
5616         tcg_regset_set_reg(arg_set, reg);
5617         temp_load(s, ts, arg_set, allocated_regs, 0);
5618     }
5619 }
5620 
5621 static void load_arg_stk(TCGContext *s, unsigned arg_slot, TCGTemp *ts,
5622                          TCGRegSet allocated_regs)
5623 {
5624     /*
5625      * When the destination is on the stack, load up the temp and store.
5626      * If there are many call-saved registers, the temp might live to
5627      * see another use; otherwise it'll be discarded.
5628      */
5629     temp_load(s, ts, tcg_target_available_regs[ts->type], allocated_regs, 0);
5630     tcg_out_st(s, ts->type, ts->reg, TCG_REG_CALL_STACK,
5631                arg_slot_stk_ofs(arg_slot));
5632 }
5633 
5634 static void load_arg_normal(TCGContext *s, const TCGCallArgumentLoc *l,
5635                             TCGTemp *ts, TCGRegSet *allocated_regs)
5636 {
5637     if (arg_slot_reg_p(l->arg_slot)) {
5638         TCGReg reg = tcg_target_call_iarg_regs[l->arg_slot];
5639         load_arg_reg(s, reg, ts, *allocated_regs);
5640         tcg_regset_set_reg(*allocated_regs, reg);
5641     } else {
5642         load_arg_stk(s, l->arg_slot, ts, *allocated_regs);
5643     }
5644 }
5645 
5646 static void load_arg_ref(TCGContext *s, unsigned arg_slot, TCGReg ref_base,
5647                          intptr_t ref_off, TCGRegSet *allocated_regs)
5648 {
5649     TCGReg reg;
5650 
5651     if (arg_slot_reg_p(arg_slot)) {
5652         reg = tcg_target_call_iarg_regs[arg_slot];
5653         tcg_reg_free(s, reg, *allocated_regs);
5654         tcg_out_addi_ptr(s, reg, ref_base, ref_off);
5655         tcg_regset_set_reg(*allocated_regs, reg);
5656     } else {
5657         reg = tcg_reg_alloc(s, tcg_target_available_regs[TCG_TYPE_PTR],
5658                             *allocated_regs, 0, false);
5659         tcg_out_addi_ptr(s, reg, ref_base, ref_off);
5660         tcg_out_st(s, TCG_TYPE_PTR, reg, TCG_REG_CALL_STACK,
5661                    arg_slot_stk_ofs(arg_slot));
5662     }
5663 }
5664 
5665 static void tcg_reg_alloc_call(TCGContext *s, TCGOp *op)
5666 {
5667     const int nb_oargs = TCGOP_CALLO(op);
5668     const int nb_iargs = TCGOP_CALLI(op);
5669     const TCGLifeData arg_life = op->life;
5670     const TCGHelperInfo *info = tcg_call_info(op);
5671     TCGRegSet allocated_regs = s->reserved_regs;
5672     int i;
5673 
5674     /*
5675      * Move inputs into place in reverse order,
5676      * so that we place stacked arguments first.
5677      */
5678     for (i = nb_iargs - 1; i >= 0; --i) {
5679         const TCGCallArgumentLoc *loc = &info->in[i];
5680         TCGTemp *ts = arg_temp(op->args[nb_oargs + i]);
5681 
5682         switch (loc->kind) {
5683         case TCG_CALL_ARG_NORMAL:
5684         case TCG_CALL_ARG_EXTEND_U:
5685         case TCG_CALL_ARG_EXTEND_S:
5686             load_arg_normal(s, loc, ts, &allocated_regs);
5687             break;
5688         case TCG_CALL_ARG_BY_REF:
5689             load_arg_stk(s, loc->ref_slot, ts, allocated_regs);
5690             load_arg_ref(s, loc->arg_slot, TCG_REG_CALL_STACK,
5691                          arg_slot_stk_ofs(loc->ref_slot),
5692                          &allocated_regs);
5693             break;
5694         case TCG_CALL_ARG_BY_REF_N:
5695             load_arg_stk(s, loc->ref_slot, ts, allocated_regs);
5696             break;
5697         default:
5698             g_assert_not_reached();
5699         }
5700     }
5701 
5702     /* Mark dead temporaries and free the associated registers.  */
5703     for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
5704         if (IS_DEAD_ARG(i)) {
5705             temp_dead(s, arg_temp(op->args[i]));
5706         }
5707     }
5708 
5709     /* Clobber call registers.  */
5710     for (i = 0; i < TCG_TARGET_NB_REGS; i++) {
5711         if (tcg_regset_test_reg(tcg_target_call_clobber_regs, i)) {
5712             tcg_reg_free(s, i, allocated_regs);
5713         }
5714     }
5715 
5716     /*
5717      * Save globals if they might be written by the helper,
5718      * sync them if they might be read.
5719      */
5720     if (info->flags & TCG_CALL_NO_READ_GLOBALS) {
5721         /* Nothing to do */
5722     } else if (info->flags & TCG_CALL_NO_WRITE_GLOBALS) {
5723         sync_globals(s, allocated_regs);
5724     } else {
5725         save_globals(s, allocated_regs);
5726     }
5727 
5728     /*
5729      * If the ABI passes a pointer to the returned struct as the first
5730      * argument, load that now.  Pass a pointer to the output home slot.
5731      */
5732     if (info->out_kind == TCG_CALL_RET_BY_REF) {
5733         TCGTemp *ts = arg_temp(op->args[0]);
5734 
5735         if (!ts->mem_allocated) {
5736             temp_allocate_frame(s, ts);
5737         }
5738         load_arg_ref(s, 0, ts->mem_base->reg, ts->mem_offset, &allocated_regs);
5739     }
5740 
5741     tcg_out_call(s, tcg_call_func(op), info);
5742 
5743     /* Assign output registers and emit moves if needed.  */
5744     switch (info->out_kind) {
5745     case TCG_CALL_RET_NORMAL:
5746         for (i = 0; i < nb_oargs; i++) {
5747             TCGTemp *ts = arg_temp(op->args[i]);
5748             TCGReg reg = tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, i);
5749 
5750             /* ENV should not be modified.  */
5751             tcg_debug_assert(!temp_readonly(ts));
5752 
5753             set_temp_val_reg(s, ts, reg);
5754             ts->mem_coherent = 0;
5755         }
5756         break;
5757 
5758     case TCG_CALL_RET_BY_VEC:
5759         {
5760             TCGTemp *ts = arg_temp(op->args[0]);
5761 
5762             tcg_debug_assert(ts->base_type == TCG_TYPE_I128);
5763             tcg_debug_assert(ts->temp_subindex == 0);
5764             if (!ts->mem_allocated) {
5765                 temp_allocate_frame(s, ts);
5766             }
5767             tcg_out_st(s, TCG_TYPE_V128,
5768                        tcg_target_call_oarg_reg(TCG_CALL_RET_BY_VEC, 0),
5769                        ts->mem_base->reg, ts->mem_offset);
5770         }
5771         /* fall through to mark all parts in memory */
5772 
5773     case TCG_CALL_RET_BY_REF:
5774         /* The callee has performed a write through the reference. */
5775         for (i = 0; i < nb_oargs; i++) {
5776             TCGTemp *ts = arg_temp(op->args[i]);
5777             ts->val_type = TEMP_VAL_MEM;
5778         }
5779         break;
5780 
5781     default:
5782         g_assert_not_reached();
5783     }
5784 
5785     /* Flush or discard output registers as needed. */
5786     for (i = 0; i < nb_oargs; i++) {
5787         TCGTemp *ts = arg_temp(op->args[i]);
5788         if (NEED_SYNC_ARG(i)) {
5789             temp_sync(s, ts, s->reserved_regs, 0, IS_DEAD_ARG(i));
5790         } else if (IS_DEAD_ARG(i)) {
5791             temp_dead(s, ts);
5792         }
5793     }
5794 }
5795 
5796 /**
5797  * atom_and_align_for_opc:
5798  * @s: tcg context
5799  * @opc: memory operation code
5800  * @host_atom: MO_ATOM_{IFALIGN,WITHIN16,SUBALIGN} for host operations
5801  * @allow_two_ops: true if we are prepared to issue two operations
5802  *
5803  * Return the alignment and atomicity to use for the inline fast path
5804  * for the given memory operation.  The alignment may be larger than
5805  * that specified in @opc, and the correct alignment will be diagnosed
5806  * by the slow path helper.
5807  *
5808  * If @allow_two_ops, the host is prepared to test for 2x alignment,
5809  * and issue two loads or stores for subalignment.
5810  */
5811 static TCGAtomAlign atom_and_align_for_opc(TCGContext *s, MemOp opc,
5812                                            MemOp host_atom, bool allow_two_ops)
5813 {
5814     MemOp align = memop_alignment_bits(opc);
5815     MemOp size = opc & MO_SIZE;
5816     MemOp half = size ? size - 1 : 0;
5817     MemOp atom = opc & MO_ATOM_MASK;
5818     MemOp atmax;
5819 
5820     switch (atom) {
5821     case MO_ATOM_NONE:
5822         /* The operation requires no specific atomicity. */
5823         atmax = MO_8;
5824         break;
5825 
5826     case MO_ATOM_IFALIGN:
5827         atmax = size;
5828         break;
5829 
5830     case MO_ATOM_IFALIGN_PAIR:
5831         atmax = half;
5832         break;
5833 
5834     case MO_ATOM_WITHIN16:
5835         atmax = size;
5836         if (size == MO_128) {
5837             /* Misalignment implies !within16, and therefore no atomicity. */
5838         } else if (host_atom != MO_ATOM_WITHIN16) {
5839             /* The host does not implement within16, so require alignment. */
5840             align = MAX(align, size);
5841         }
5842         break;
5843 
5844     case MO_ATOM_WITHIN16_PAIR:
5845         atmax = size;
5846         /*
5847          * Misalignment implies !within16, and therefore half atomicity.
5848          * Any host prepared for two operations can implement this with
5849          * half alignment.
5850          */
5851         if (host_atom != MO_ATOM_WITHIN16 && allow_two_ops) {
5852             align = MAX(align, half);
5853         }
5854         break;
5855 
5856     case MO_ATOM_SUBALIGN:
5857         atmax = size;
5858         if (host_atom != MO_ATOM_SUBALIGN) {
5859             /* If unaligned but not odd, there are subobjects up to half. */
5860             if (allow_two_ops) {
5861                 align = MAX(align, half);
5862             } else {
5863                 align = MAX(align, size);
5864             }
5865         }
5866         break;
5867 
5868     default:
5869         g_assert_not_reached();
5870     }
5871 
5872     return (TCGAtomAlign){ .atom = atmax, .align = align };
5873 }
5874 
5875 /*
5876  * Similarly for qemu_ld/st slow path helpers.
5877  * We must re-implement tcg_gen_callN and tcg_reg_alloc_call simultaneously,
5878  * using only the provided backend tcg_out_* functions.
5879  */
5880 
5881 static int tcg_out_helper_stk_ofs(TCGType type, unsigned slot)
5882 {
5883     int ofs = arg_slot_stk_ofs(slot);
5884 
5885     /*
5886      * Each stack slot is TCG_TARGET_LONG_BITS.  If the host does not
5887      * require extension to uint64_t, adjust the address for uint32_t.
5888      */
5889     if (HOST_BIG_ENDIAN &&
5890         TCG_TARGET_REG_BITS == 64 &&
5891         type == TCG_TYPE_I32) {
5892         ofs += 4;
5893     }
5894     return ofs;
5895 }
5896 
5897 static void tcg_out_helper_load_slots(TCGContext *s,
5898                                       unsigned nmov, TCGMovExtend *mov,
5899                                       const TCGLdstHelperParam *parm)
5900 {
5901     unsigned i;
5902     TCGReg dst3;
5903 
5904     /*
5905      * Start from the end, storing to the stack first.
5906      * This frees those registers, so we need not consider overlap.
5907      */
5908     for (i = nmov; i-- > 0; ) {
5909         unsigned slot = mov[i].dst;
5910 
5911         if (arg_slot_reg_p(slot)) {
5912             goto found_reg;
5913         }
5914 
5915         TCGReg src = mov[i].src;
5916         TCGType dst_type = mov[i].dst_type;
5917         MemOp dst_mo = dst_type == TCG_TYPE_I32 ? MO_32 : MO_64;
5918 
5919         /* The argument is going onto the stack; extend into scratch. */
5920         if ((mov[i].src_ext & MO_SIZE) != dst_mo) {
5921             tcg_debug_assert(parm->ntmp != 0);
5922             mov[i].dst = src = parm->tmp[0];
5923             tcg_out_movext1(s, &mov[i]);
5924         }
5925 
5926         tcg_out_st(s, dst_type, src, TCG_REG_CALL_STACK,
5927                    tcg_out_helper_stk_ofs(dst_type, slot));
5928     }
5929     return;
5930 
5931  found_reg:
5932     /*
5933      * The remaining arguments are in registers.
5934      * Convert slot numbers to argument registers.
5935      */
5936     nmov = i + 1;
5937     for (i = 0; i < nmov; ++i) {
5938         mov[i].dst = tcg_target_call_iarg_regs[mov[i].dst];
5939     }
5940 
5941     switch (nmov) {
5942     case 4:
5943         /* The backend must have provided enough temps for the worst case. */
5944         tcg_debug_assert(parm->ntmp >= 2);
5945 
5946         dst3 = mov[3].dst;
5947         for (unsigned j = 0; j < 3; ++j) {
5948             if (dst3 == mov[j].src) {
5949                 /*
5950                  * Conflict. Copy the source to a temporary, perform the
5951                  * remaining moves, then the extension from our scratch
5952                  * on the way out.
5953                  */
5954                 TCGReg scratch = parm->tmp[1];
5955 
5956                 tcg_out_mov(s, mov[3].src_type, scratch, mov[3].src);
5957                 tcg_out_movext3(s, mov, mov + 1, mov + 2, parm->tmp[0]);
5958                 tcg_out_movext1_new_src(s, &mov[3], scratch);
5959                 break;
5960             }
5961         }
5962 
5963         /* No conflicts: perform this move and continue. */
5964         tcg_out_movext1(s, &mov[3]);
5965         /* fall through */
5966 
5967     case 3:
5968         tcg_out_movext3(s, mov, mov + 1, mov + 2,
5969                         parm->ntmp ? parm->tmp[0] : -1);
5970         break;
5971     case 2:
5972         tcg_out_movext2(s, mov, mov + 1,
5973                         parm->ntmp ? parm->tmp[0] : -1);
5974         break;
5975     case 1:
5976         tcg_out_movext1(s, mov);
5977         break;
5978     default:
5979         g_assert_not_reached();
5980     }
5981 }
5982 
5983 static void tcg_out_helper_load_imm(TCGContext *s, unsigned slot,
5984                                     TCGType type, tcg_target_long imm,
5985                                     const TCGLdstHelperParam *parm)
5986 {
5987     if (arg_slot_reg_p(slot)) {
5988         tcg_out_movi(s, type, tcg_target_call_iarg_regs[slot], imm);
5989     } else {
5990         int ofs = tcg_out_helper_stk_ofs(type, slot);
5991         if (!tcg_out_sti(s, type, imm, TCG_REG_CALL_STACK, ofs)) {
5992             tcg_debug_assert(parm->ntmp != 0);
5993             tcg_out_movi(s, type, parm->tmp[0], imm);
5994             tcg_out_st(s, type, parm->tmp[0], TCG_REG_CALL_STACK, ofs);
5995         }
5996     }
5997 }
5998 
5999 static void tcg_out_helper_load_common_args(TCGContext *s,
6000                                             const TCGLabelQemuLdst *ldst,
6001                                             const TCGLdstHelperParam *parm,
6002                                             const TCGHelperInfo *info,
6003                                             unsigned next_arg)
6004 {
6005     TCGMovExtend ptr_mov = {
6006         .dst_type = TCG_TYPE_PTR,
6007         .src_type = TCG_TYPE_PTR,
6008         .src_ext = sizeof(void *) == 4 ? MO_32 : MO_64
6009     };
6010     const TCGCallArgumentLoc *loc = &info->in[0];
6011     TCGType type;
6012     unsigned slot;
6013     tcg_target_ulong imm;
6014 
6015     /*
6016      * Handle env, which is always first.
6017      */
6018     ptr_mov.dst = loc->arg_slot;
6019     ptr_mov.src = TCG_AREG0;
6020     tcg_out_helper_load_slots(s, 1, &ptr_mov, parm);
6021 
6022     /*
6023      * Handle oi.
6024      */
6025     imm = ldst->oi;
6026     loc = &info->in[next_arg];
6027     type = TCG_TYPE_I32;
6028     switch (loc->kind) {
6029     case TCG_CALL_ARG_NORMAL:
6030         break;
6031     case TCG_CALL_ARG_EXTEND_U:
6032     case TCG_CALL_ARG_EXTEND_S:
6033         /* No extension required for MemOpIdx. */
6034         tcg_debug_assert(imm <= INT32_MAX);
6035         type = TCG_TYPE_REG;
6036         break;
6037     default:
6038         g_assert_not_reached();
6039     }
6040     tcg_out_helper_load_imm(s, loc->arg_slot, type, imm, parm);
6041     next_arg++;
6042 
6043     /*
6044      * Handle ra.
6045      */
6046     loc = &info->in[next_arg];
6047     slot = loc->arg_slot;
6048     if (parm->ra_gen) {
6049         int arg_reg = -1;
6050         TCGReg ra_reg;
6051 
6052         if (arg_slot_reg_p(slot)) {
6053             arg_reg = tcg_target_call_iarg_regs[slot];
6054         }
6055         ra_reg = parm->ra_gen(s, ldst, arg_reg);
6056 
6057         ptr_mov.dst = slot;
6058         ptr_mov.src = ra_reg;
6059         tcg_out_helper_load_slots(s, 1, &ptr_mov, parm);
6060     } else {
6061         imm = (uintptr_t)ldst->raddr;
6062         tcg_out_helper_load_imm(s, slot, TCG_TYPE_PTR, imm, parm);
6063     }
6064 }
6065 
6066 static unsigned tcg_out_helper_add_mov(TCGMovExtend *mov,
6067                                        const TCGCallArgumentLoc *loc,
6068                                        TCGType dst_type, TCGType src_type,
6069                                        TCGReg lo, TCGReg hi)
6070 {
6071     MemOp reg_mo;
6072 
6073     if (dst_type <= TCG_TYPE_REG) {
6074         MemOp src_ext;
6075 
6076         switch (loc->kind) {
6077         case TCG_CALL_ARG_NORMAL:
6078             src_ext = src_type == TCG_TYPE_I32 ? MO_32 : MO_64;
6079             break;
6080         case TCG_CALL_ARG_EXTEND_U:
6081             dst_type = TCG_TYPE_REG;
6082             src_ext = MO_UL;
6083             break;
6084         case TCG_CALL_ARG_EXTEND_S:
6085             dst_type = TCG_TYPE_REG;
6086             src_ext = MO_SL;
6087             break;
6088         default:
6089             g_assert_not_reached();
6090         }
6091 
6092         mov[0].dst = loc->arg_slot;
6093         mov[0].dst_type = dst_type;
6094         mov[0].src = lo;
6095         mov[0].src_type = src_type;
6096         mov[0].src_ext = src_ext;
6097         return 1;
6098     }
6099 
6100     if (TCG_TARGET_REG_BITS == 32) {
6101         assert(dst_type == TCG_TYPE_I64);
6102         reg_mo = MO_32;
6103     } else {
6104         assert(dst_type == TCG_TYPE_I128);
6105         reg_mo = MO_64;
6106     }
6107 
6108     mov[0].dst = loc[HOST_BIG_ENDIAN].arg_slot;
6109     mov[0].src = lo;
6110     mov[0].dst_type = TCG_TYPE_REG;
6111     mov[0].src_type = TCG_TYPE_REG;
6112     mov[0].src_ext = reg_mo;
6113 
6114     mov[1].dst = loc[!HOST_BIG_ENDIAN].arg_slot;
6115     mov[1].src = hi;
6116     mov[1].dst_type = TCG_TYPE_REG;
6117     mov[1].src_type = TCG_TYPE_REG;
6118     mov[1].src_ext = reg_mo;
6119 
6120     return 2;
6121 }
6122 
6123 static void tcg_out_ld_helper_args(TCGContext *s, const TCGLabelQemuLdst *ldst,
6124                                    const TCGLdstHelperParam *parm)
6125 {
6126     const TCGHelperInfo *info;
6127     const TCGCallArgumentLoc *loc;
6128     TCGMovExtend mov[2];
6129     unsigned next_arg, nmov;
6130     MemOp mop = get_memop(ldst->oi);
6131 
6132     switch (mop & MO_SIZE) {
6133     case MO_8:
6134     case MO_16:
6135     case MO_32:
6136         info = &info_helper_ld32_mmu;
6137         break;
6138     case MO_64:
6139         info = &info_helper_ld64_mmu;
6140         break;
6141     case MO_128:
6142         info = &info_helper_ld128_mmu;
6143         break;
6144     default:
6145         g_assert_not_reached();
6146     }
6147 
6148     /* Defer env argument. */
6149     next_arg = 1;
6150 
6151     loc = &info->in[next_arg];
6152     if (TCG_TARGET_REG_BITS == 32 && s->addr_type == TCG_TYPE_I32) {
6153         /*
6154          * 32-bit host with 32-bit guest: zero-extend the guest address
6155          * to 64-bits for the helper by storing the low part, then
6156          * load a zero for the high part.
6157          */
6158         tcg_out_helper_add_mov(mov, loc + HOST_BIG_ENDIAN,
6159                                TCG_TYPE_I32, TCG_TYPE_I32,
6160                                ldst->addr_reg, -1);
6161         tcg_out_helper_load_slots(s, 1, mov, parm);
6162 
6163         tcg_out_helper_load_imm(s, loc[!HOST_BIG_ENDIAN].arg_slot,
6164                                 TCG_TYPE_I32, 0, parm);
6165         next_arg += 2;
6166     } else {
6167         nmov = tcg_out_helper_add_mov(mov, loc, TCG_TYPE_I64, s->addr_type,
6168                                       ldst->addr_reg, -1);
6169         tcg_out_helper_load_slots(s, nmov, mov, parm);
6170         next_arg += nmov;
6171     }
6172 
6173     switch (info->out_kind) {
6174     case TCG_CALL_RET_NORMAL:
6175     case TCG_CALL_RET_BY_VEC:
6176         break;
6177     case TCG_CALL_RET_BY_REF:
6178         /*
6179          * The return reference is in the first argument slot.
6180          * We need memory in which to return: re-use the top of stack.
6181          */
6182         {
6183             int ofs_slot0 = TCG_TARGET_CALL_STACK_OFFSET;
6184 
6185             if (arg_slot_reg_p(0)) {
6186                 tcg_out_addi_ptr(s, tcg_target_call_iarg_regs[0],
6187                                  TCG_REG_CALL_STACK, ofs_slot0);
6188             } else {
6189                 tcg_debug_assert(parm->ntmp != 0);
6190                 tcg_out_addi_ptr(s, parm->tmp[0],
6191                                  TCG_REG_CALL_STACK, ofs_slot0);
6192                 tcg_out_st(s, TCG_TYPE_PTR, parm->tmp[0],
6193                            TCG_REG_CALL_STACK, ofs_slot0);
6194             }
6195         }
6196         break;
6197     default:
6198         g_assert_not_reached();
6199     }
6200 
6201     tcg_out_helper_load_common_args(s, ldst, parm, info, next_arg);
6202 }
6203 
6204 static void tcg_out_ld_helper_ret(TCGContext *s, const TCGLabelQemuLdst *ldst,
6205                                   bool load_sign,
6206                                   const TCGLdstHelperParam *parm)
6207 {
6208     MemOp mop = get_memop(ldst->oi);
6209     TCGMovExtend mov[2];
6210     int ofs_slot0;
6211 
6212     switch (ldst->type) {
6213     case TCG_TYPE_I64:
6214         if (TCG_TARGET_REG_BITS == 32) {
6215             break;
6216         }
6217         /* fall through */
6218 
6219     case TCG_TYPE_I32:
6220         mov[0].dst = ldst->datalo_reg;
6221         mov[0].src = tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, 0);
6222         mov[0].dst_type = ldst->type;
6223         mov[0].src_type = TCG_TYPE_REG;
6224 
6225         /*
6226          * If load_sign, then we allowed the helper to perform the
6227          * appropriate sign extension to tcg_target_ulong, and all
6228          * we need now is a plain move.
6229          *
6230          * If they do not, then we expect the relevant extension
6231          * instruction to be no more expensive than a move, and
6232          * we thus save the icache etc by only using one of two
6233          * helper functions.
6234          */
6235         if (load_sign || !(mop & MO_SIGN)) {
6236             if (TCG_TARGET_REG_BITS == 32 || ldst->type == TCG_TYPE_I32) {
6237                 mov[0].src_ext = MO_32;
6238             } else {
6239                 mov[0].src_ext = MO_64;
6240             }
6241         } else {
6242             mov[0].src_ext = mop & MO_SSIZE;
6243         }
6244         tcg_out_movext1(s, mov);
6245         return;
6246 
6247     case TCG_TYPE_I128:
6248         tcg_debug_assert(TCG_TARGET_REG_BITS == 64);
6249         ofs_slot0 = TCG_TARGET_CALL_STACK_OFFSET;
6250         switch (TCG_TARGET_CALL_RET_I128) {
6251         case TCG_CALL_RET_NORMAL:
6252             break;
6253         case TCG_CALL_RET_BY_VEC:
6254             tcg_out_st(s, TCG_TYPE_V128,
6255                        tcg_target_call_oarg_reg(TCG_CALL_RET_BY_VEC, 0),
6256                        TCG_REG_CALL_STACK, ofs_slot0);
6257             /* fall through */
6258         case TCG_CALL_RET_BY_REF:
6259             tcg_out_ld(s, TCG_TYPE_I64, ldst->datalo_reg,
6260                        TCG_REG_CALL_STACK, ofs_slot0 + 8 * HOST_BIG_ENDIAN);
6261             tcg_out_ld(s, TCG_TYPE_I64, ldst->datahi_reg,
6262                        TCG_REG_CALL_STACK, ofs_slot0 + 8 * !HOST_BIG_ENDIAN);
6263             return;
6264         default:
6265             g_assert_not_reached();
6266         }
6267         break;
6268 
6269     default:
6270         g_assert_not_reached();
6271     }
6272 
6273     mov[0].dst = ldst->datalo_reg;
6274     mov[0].src =
6275         tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, HOST_BIG_ENDIAN);
6276     mov[0].dst_type = TCG_TYPE_REG;
6277     mov[0].src_type = TCG_TYPE_REG;
6278     mov[0].src_ext = TCG_TARGET_REG_BITS == 32 ? MO_32 : MO_64;
6279 
6280     mov[1].dst = ldst->datahi_reg;
6281     mov[1].src =
6282         tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, !HOST_BIG_ENDIAN);
6283     mov[1].dst_type = TCG_TYPE_REG;
6284     mov[1].src_type = TCG_TYPE_REG;
6285     mov[1].src_ext = TCG_TARGET_REG_BITS == 32 ? MO_32 : MO_64;
6286 
6287     tcg_out_movext2(s, mov, mov + 1, parm->ntmp ? parm->tmp[0] : -1);
6288 }
6289 
6290 static void tcg_out_st_helper_args(TCGContext *s, const TCGLabelQemuLdst *ldst,
6291                                    const TCGLdstHelperParam *parm)
6292 {
6293     const TCGHelperInfo *info;
6294     const TCGCallArgumentLoc *loc;
6295     TCGMovExtend mov[4];
6296     TCGType data_type;
6297     unsigned next_arg, nmov, n;
6298     MemOp mop = get_memop(ldst->oi);
6299 
6300     switch (mop & MO_SIZE) {
6301     case MO_8:
6302     case MO_16:
6303     case MO_32:
6304         info = &info_helper_st32_mmu;
6305         data_type = TCG_TYPE_I32;
6306         break;
6307     case MO_64:
6308         info = &info_helper_st64_mmu;
6309         data_type = TCG_TYPE_I64;
6310         break;
6311     case MO_128:
6312         info = &info_helper_st128_mmu;
6313         data_type = TCG_TYPE_I128;
6314         break;
6315     default:
6316         g_assert_not_reached();
6317     }
6318 
6319     /* Defer env argument. */
6320     next_arg = 1;
6321     nmov = 0;
6322 
6323     /* Handle addr argument. */
6324     loc = &info->in[next_arg];
6325     tcg_debug_assert(s->addr_type <= TCG_TYPE_REG);
6326     if (TCG_TARGET_REG_BITS == 32) {
6327         /*
6328          * 32-bit host (and thus 32-bit guest): zero-extend the guest address
6329          * to 64-bits for the helper by storing the low part.  Later,
6330          * after we have processed the register inputs, we will load a
6331          * zero for the high part.
6332          */
6333         tcg_out_helper_add_mov(mov, loc + HOST_BIG_ENDIAN,
6334                                TCG_TYPE_I32, TCG_TYPE_I32,
6335                                ldst->addr_reg, -1);
6336         next_arg += 2;
6337         nmov += 1;
6338     } else {
6339         n = tcg_out_helper_add_mov(mov, loc, TCG_TYPE_I64, s->addr_type,
6340                                    ldst->addr_reg, -1);
6341         next_arg += n;
6342         nmov += n;
6343     }
6344 
6345     /* Handle data argument. */
6346     loc = &info->in[next_arg];
6347     switch (loc->kind) {
6348     case TCG_CALL_ARG_NORMAL:
6349     case TCG_CALL_ARG_EXTEND_U:
6350     case TCG_CALL_ARG_EXTEND_S:
6351         n = tcg_out_helper_add_mov(mov + nmov, loc, data_type, ldst->type,
6352                                    ldst->datalo_reg, ldst->datahi_reg);
6353         next_arg += n;
6354         nmov += n;
6355         tcg_out_helper_load_slots(s, nmov, mov, parm);
6356         break;
6357 
6358     case TCG_CALL_ARG_BY_REF:
6359         tcg_debug_assert(TCG_TARGET_REG_BITS == 64);
6360         tcg_debug_assert(data_type == TCG_TYPE_I128);
6361         tcg_out_st(s, TCG_TYPE_I64,
6362                    HOST_BIG_ENDIAN ? ldst->datahi_reg : ldst->datalo_reg,
6363                    TCG_REG_CALL_STACK, arg_slot_stk_ofs(loc[0].ref_slot));
6364         tcg_out_st(s, TCG_TYPE_I64,
6365                    HOST_BIG_ENDIAN ? ldst->datalo_reg : ldst->datahi_reg,
6366                    TCG_REG_CALL_STACK, arg_slot_stk_ofs(loc[1].ref_slot));
6367 
6368         tcg_out_helper_load_slots(s, nmov, mov, parm);
6369 
6370         if (arg_slot_reg_p(loc->arg_slot)) {
6371             tcg_out_addi_ptr(s, tcg_target_call_iarg_regs[loc->arg_slot],
6372                              TCG_REG_CALL_STACK,
6373                              arg_slot_stk_ofs(loc->ref_slot));
6374         } else {
6375             tcg_debug_assert(parm->ntmp != 0);
6376             tcg_out_addi_ptr(s, parm->tmp[0], TCG_REG_CALL_STACK,
6377                              arg_slot_stk_ofs(loc->ref_slot));
6378             tcg_out_st(s, TCG_TYPE_PTR, parm->tmp[0],
6379                        TCG_REG_CALL_STACK, arg_slot_stk_ofs(loc->arg_slot));
6380         }
6381         next_arg += 2;
6382         break;
6383 
6384     default:
6385         g_assert_not_reached();
6386     }
6387 
6388     if (TCG_TARGET_REG_BITS == 32) {
6389         /* Zero extend the address by loading a zero for the high part. */
6390         loc = &info->in[1 + !HOST_BIG_ENDIAN];
6391         tcg_out_helper_load_imm(s, loc->arg_slot, TCG_TYPE_I32, 0, parm);
6392     }
6393 
6394     tcg_out_helper_load_common_args(s, ldst, parm, info, next_arg);
6395 }
6396 
6397 int tcg_gen_code(TCGContext *s, TranslationBlock *tb, uint64_t pc_start)
6398 {
6399     int i, start_words, num_insns;
6400     TCGOp *op;
6401 
6402     if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP)
6403                  && qemu_log_in_addr_range(pc_start))) {
6404         FILE *logfile = qemu_log_trylock();
6405         if (logfile) {
6406             fprintf(logfile, "OP:\n");
6407             tcg_dump_ops(s, logfile, false);
6408             fprintf(logfile, "\n");
6409             qemu_log_unlock(logfile);
6410         }
6411     }
6412 
6413 #ifdef CONFIG_DEBUG_TCG
6414     /* Ensure all labels referenced have been emitted.  */
6415     {
6416         TCGLabel *l;
6417         bool error = false;
6418 
6419         QSIMPLEQ_FOREACH(l, &s->labels, next) {
6420             if (unlikely(!l->present) && !QSIMPLEQ_EMPTY(&l->branches)) {
6421                 qemu_log_mask(CPU_LOG_TB_OP,
6422                               "$L%d referenced but not present.\n", l->id);
6423                 error = true;
6424             }
6425         }
6426         assert(!error);
6427     }
6428 #endif
6429 
6430     /* Do not reuse any EBB that may be allocated within the TB. */
6431     tcg_temp_ebb_reset_freed(s);
6432 
6433     tcg_optimize(s);
6434 
6435     reachable_code_pass(s);
6436     liveness_pass_0(s);
6437     liveness_pass_1(s);
6438 
6439     if (s->nb_indirects > 0) {
6440         if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_IND)
6441                      && qemu_log_in_addr_range(pc_start))) {
6442             FILE *logfile = qemu_log_trylock();
6443             if (logfile) {
6444                 fprintf(logfile, "OP before indirect lowering:\n");
6445                 tcg_dump_ops(s, logfile, false);
6446                 fprintf(logfile, "\n");
6447                 qemu_log_unlock(logfile);
6448             }
6449         }
6450 
6451         /* Replace indirect temps with direct temps.  */
6452         if (liveness_pass_2(s)) {
6453             /* If changes were made, re-run liveness.  */
6454             liveness_pass_1(s);
6455         }
6456     }
6457 
6458     if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT)
6459                  && qemu_log_in_addr_range(pc_start))) {
6460         FILE *logfile = qemu_log_trylock();
6461         if (logfile) {
6462             fprintf(logfile, "OP after optimization and liveness analysis:\n");
6463             tcg_dump_ops(s, logfile, true);
6464             fprintf(logfile, "\n");
6465             qemu_log_unlock(logfile);
6466         }
6467     }
6468 
6469     /* Initialize goto_tb jump offsets. */
6470     tb->jmp_reset_offset[0] = TB_JMP_OFFSET_INVALID;
6471     tb->jmp_reset_offset[1] = TB_JMP_OFFSET_INVALID;
6472     tb->jmp_insn_offset[0] = TB_JMP_OFFSET_INVALID;
6473     tb->jmp_insn_offset[1] = TB_JMP_OFFSET_INVALID;
6474 
6475     tcg_reg_alloc_start(s);
6476 
6477     /*
6478      * Reset the buffer pointers when restarting after overflow.
6479      * TODO: Move this into translate-all.c with the rest of the
6480      * buffer management.  Having only this done here is confusing.
6481      */
6482     s->code_buf = tcg_splitwx_to_rw(tb->tc.ptr);
6483     s->code_ptr = s->code_buf;
6484     s->data_gen_ptr = NULL;
6485 
6486     QSIMPLEQ_INIT(&s->ldst_labels);
6487     s->pool_labels = NULL;
6488 
6489     start_words = s->insn_start_words;
6490     s->gen_insn_data =
6491         tcg_malloc(sizeof(uint64_t) * s->gen_tb->icount * start_words);
6492 
6493     tcg_out_tb_start(s);
6494 
6495     num_insns = -1;
6496     QTAILQ_FOREACH(op, &s->ops, link) {
6497         TCGOpcode opc = op->opc;
6498 
6499         switch (opc) {
6500         case INDEX_op_mov:
6501         case INDEX_op_mov_vec:
6502             tcg_reg_alloc_mov(s, op);
6503             break;
6504         case INDEX_op_dup_vec:
6505             tcg_reg_alloc_dup(s, op);
6506             break;
6507         case INDEX_op_insn_start:
6508             if (num_insns >= 0) {
6509                 size_t off = tcg_current_code_size(s);
6510                 s->gen_insn_end_off[num_insns] = off;
6511                 /* Assert that we do not overflow our stored offset.  */
6512                 assert(s->gen_insn_end_off[num_insns] == off);
6513             }
6514             num_insns++;
6515             for (i = 0; i < start_words; ++i) {
6516                 s->gen_insn_data[num_insns * start_words + i] =
6517                     tcg_get_insn_start_param(op, i);
6518             }
6519             break;
6520         case INDEX_op_discard:
6521             temp_dead(s, arg_temp(op->args[0]));
6522             break;
6523         case INDEX_op_set_label:
6524             tcg_reg_alloc_bb_end(s, s->reserved_regs);
6525             tcg_out_label(s, arg_label(op->args[0]));
6526             break;
6527         case INDEX_op_call:
6528             tcg_reg_alloc_call(s, op);
6529             break;
6530         case INDEX_op_exit_tb:
6531             tcg_out_exit_tb(s, op->args[0]);
6532             break;
6533         case INDEX_op_goto_tb:
6534             tcg_out_goto_tb(s, op->args[0]);
6535             break;
6536         case INDEX_op_dup2_vec:
6537             if (tcg_reg_alloc_dup2(s, op)) {
6538                 break;
6539             }
6540             /* fall through */
6541         default:
6542             /* Sanity check that we've not introduced any unhandled opcodes. */
6543             tcg_debug_assert(tcg_op_supported(opc, TCGOP_TYPE(op),
6544                                               TCGOP_FLAGS(op)));
6545             /* Note: in order to speed up the code, it would be much
6546                faster to have specialized register allocator functions for
6547                some common argument patterns */
6548             tcg_reg_alloc_op(s, op);
6549             break;
6550         }
6551         /* Test for (pending) buffer overflow.  The assumption is that any
6552            one operation beginning below the high water mark cannot overrun
6553            the buffer completely.  Thus we can test for overflow after
6554            generating code without having to check during generation.  */
6555         if (unlikely((void *)s->code_ptr > s->code_gen_highwater)) {
6556             return -1;
6557         }
6558         /* Test for TB overflow, as seen by gen_insn_end_off.  */
6559         if (unlikely(tcg_current_code_size(s) > UINT16_MAX)) {
6560             return -2;
6561         }
6562     }
6563     tcg_debug_assert(num_insns + 1 == s->gen_tb->icount);
6564     s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);
6565 
6566     /* Generate TB finalization at the end of block */
6567     i = tcg_out_ldst_finalize(s);
6568     if (i < 0) {
6569         return i;
6570     }
6571     i = tcg_out_pool_finalize(s);
6572     if (i < 0) {
6573         return i;
6574     }
6575     if (!tcg_resolve_relocs(s)) {
6576         return -2;
6577     }
6578 
6579 #ifndef CONFIG_TCG_INTERPRETER
6580     /* flush instruction cache */
6581     flush_idcache_range((uintptr_t)tcg_splitwx_to_rx(s->code_buf),
6582                         (uintptr_t)s->code_buf,
6583                         tcg_ptr_byte_diff(s->code_ptr, s->code_buf));
6584 #endif
6585 
6586     return tcg_current_code_size(s);
6587 }
6588 
6589 #ifdef ELF_HOST_MACHINE
6590 /* In order to use this feature, the backend needs to do three things:
6591 
6592    (1) Define ELF_HOST_MACHINE to indicate both what value to
6593        put into the ELF image and to indicate support for the feature.
6594 
6595    (2) Define tcg_register_jit.  This should create a buffer containing
6596        the contents of a .debug_frame section that describes the post-
6597        prologue unwind info for the tcg machine.
6598 
6599    (3) Call tcg_register_jit_int, with the constructed .debug_frame.
6600 */
6601 
6602 /* Begin GDB interface.  THE FOLLOWING MUST MATCH GDB DOCS.  */
6603 typedef enum {
6604     JIT_NOACTION = 0,
6605     JIT_REGISTER_FN,
6606     JIT_UNREGISTER_FN
6607 } jit_actions_t;
6608 
6609 struct jit_code_entry {
6610     struct jit_code_entry *next_entry;
6611     struct jit_code_entry *prev_entry;
6612     const void *symfile_addr;
6613     uint64_t symfile_size;
6614 };
6615 
6616 struct jit_descriptor {
6617     uint32_t version;
6618     uint32_t action_flag;
6619     struct jit_code_entry *relevant_entry;
6620     struct jit_code_entry *first_entry;
6621 };
6622 
6623 void __jit_debug_register_code(void) __attribute__((noinline));
6624 void __jit_debug_register_code(void)
6625 {
6626     asm("");
6627 }
6628 
6629 /* Must statically initialize the version, because GDB may check
6630    the version before we can set it.  */
6631 struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
6632 
6633 /* End GDB interface.  */
6634 
6635 static int find_string(const char *strtab, const char *str)
6636 {
6637     const char *p = strtab + 1;
6638 
6639     while (1) {
6640         if (strcmp(p, str) == 0) {
6641             return p - strtab;
6642         }
6643         p += strlen(p) + 1;
6644     }
6645 }
6646 
6647 static void tcg_register_jit_int(const void *buf_ptr, size_t buf_size,
6648                                  const void *debug_frame,
6649                                  size_t debug_frame_size)
6650 {
6651     struct __attribute__((packed)) DebugInfo {
6652         uint32_t  len;
6653         uint16_t  version;
6654         uint32_t  abbrev;
6655         uint8_t   ptr_size;
6656         uint8_t   cu_die;
6657         uint16_t  cu_lang;
6658         uintptr_t cu_low_pc;
6659         uintptr_t cu_high_pc;
6660         uint8_t   fn_die;
6661         char      fn_name[16];
6662         uintptr_t fn_low_pc;
6663         uintptr_t fn_high_pc;
6664         uint8_t   cu_eoc;
6665     };
6666 
6667     struct ElfImage {
6668         ElfW(Ehdr) ehdr;
6669         ElfW(Phdr) phdr;
6670         ElfW(Shdr) shdr[7];
6671         ElfW(Sym)  sym[2];
6672         struct DebugInfo di;
6673         uint8_t    da[24];
6674         char       str[80];
6675     };
6676 
6677     struct ElfImage *img;
6678 
6679     static const struct ElfImage img_template = {
6680         .ehdr = {
6681             .e_ident[EI_MAG0] = ELFMAG0,
6682             .e_ident[EI_MAG1] = ELFMAG1,
6683             .e_ident[EI_MAG2] = ELFMAG2,
6684             .e_ident[EI_MAG3] = ELFMAG3,
6685             .e_ident[EI_CLASS] = ELF_CLASS,
6686             .e_ident[EI_DATA] = ELF_DATA,
6687             .e_ident[EI_VERSION] = EV_CURRENT,
6688             .e_type = ET_EXEC,
6689             .e_machine = ELF_HOST_MACHINE,
6690             .e_version = EV_CURRENT,
6691             .e_phoff = offsetof(struct ElfImage, phdr),
6692             .e_shoff = offsetof(struct ElfImage, shdr),
6693             .e_ehsize = sizeof(ElfW(Shdr)),
6694             .e_phentsize = sizeof(ElfW(Phdr)),
6695             .e_phnum = 1,
6696             .e_shentsize = sizeof(ElfW(Shdr)),
6697             .e_shnum = ARRAY_SIZE(img->shdr),
6698             .e_shstrndx = ARRAY_SIZE(img->shdr) - 1,
6699 #ifdef ELF_HOST_FLAGS
6700             .e_flags = ELF_HOST_FLAGS,
6701 #endif
6702 #ifdef ELF_OSABI
6703             .e_ident[EI_OSABI] = ELF_OSABI,
6704 #endif
6705         },
6706         .phdr = {
6707             .p_type = PT_LOAD,
6708             .p_flags = PF_X,
6709         },
6710         .shdr = {
6711             [0] = { .sh_type = SHT_NULL },
6712             /* Trick: The contents of code_gen_buffer are not present in
6713                this fake ELF file; that got allocated elsewhere.  Therefore
6714                we mark .text as SHT_NOBITS (similar to .bss) so that readers
6715                will not look for contents.  We can record any address.  */
6716             [1] = { /* .text */
6717                 .sh_type = SHT_NOBITS,
6718                 .sh_flags = SHF_EXECINSTR | SHF_ALLOC,
6719             },
6720             [2] = { /* .debug_info */
6721                 .sh_type = SHT_PROGBITS,
6722                 .sh_offset = offsetof(struct ElfImage, di),
6723                 .sh_size = sizeof(struct DebugInfo),
6724             },
6725             [3] = { /* .debug_abbrev */
6726                 .sh_type = SHT_PROGBITS,
6727                 .sh_offset = offsetof(struct ElfImage, da),
6728                 .sh_size = sizeof(img->da),
6729             },
6730             [4] = { /* .debug_frame */
6731                 .sh_type = SHT_PROGBITS,
6732                 .sh_offset = sizeof(struct ElfImage),
6733             },
6734             [5] = { /* .symtab */
6735                 .sh_type = SHT_SYMTAB,
6736                 .sh_offset = offsetof(struct ElfImage, sym),
6737                 .sh_size = sizeof(img->sym),
6738                 .sh_info = 1,
6739                 .sh_link = ARRAY_SIZE(img->shdr) - 1,
6740                 .sh_entsize = sizeof(ElfW(Sym)),
6741             },
6742             [6] = { /* .strtab */
6743                 .sh_type = SHT_STRTAB,
6744                 .sh_offset = offsetof(struct ElfImage, str),
6745                 .sh_size = sizeof(img->str),
6746             }
6747         },
6748         .sym = {
6749             [1] = { /* code_gen_buffer */
6750                 .st_info = ELF_ST_INFO(STB_GLOBAL, STT_FUNC),
6751                 .st_shndx = 1,
6752             }
6753         },
6754         .di = {
6755             .len = sizeof(struct DebugInfo) - 4,
6756             .version = 2,
6757             .ptr_size = sizeof(void *),
6758             .cu_die = 1,
6759             .cu_lang = 0x8001,  /* DW_LANG_Mips_Assembler */
6760             .fn_die = 2,
6761             .fn_name = "code_gen_buffer"
6762         },
6763         .da = {
6764             1,          /* abbrev number (the cu) */
6765             0x11, 1,    /* DW_TAG_compile_unit, has children */
6766             0x13, 0x5,  /* DW_AT_language, DW_FORM_data2 */
6767             0x11, 0x1,  /* DW_AT_low_pc, DW_FORM_addr */
6768             0x12, 0x1,  /* DW_AT_high_pc, DW_FORM_addr */
6769             0, 0,       /* end of abbrev */
6770             2,          /* abbrev number (the fn) */
6771             0x2e, 0,    /* DW_TAG_subprogram, no children */
6772             0x3, 0x8,   /* DW_AT_name, DW_FORM_string */
6773             0x11, 0x1,  /* DW_AT_low_pc, DW_FORM_addr */
6774             0x12, 0x1,  /* DW_AT_high_pc, DW_FORM_addr */
6775             0, 0,       /* end of abbrev */
6776             0           /* no more abbrev */
6777         },
6778         .str = "\0" ".text\0" ".debug_info\0" ".debug_abbrev\0"
6779                ".debug_frame\0" ".symtab\0" ".strtab\0" "code_gen_buffer",
6780     };
6781 
6782     /* We only need a single jit entry; statically allocate it.  */
6783     static struct jit_code_entry one_entry;
6784 
6785     uintptr_t buf = (uintptr_t)buf_ptr;
6786     size_t img_size = sizeof(struct ElfImage) + debug_frame_size;
6787     DebugFrameHeader *dfh;
6788 
6789     img = g_malloc(img_size);
6790     *img = img_template;
6791 
6792     img->phdr.p_vaddr = buf;
6793     img->phdr.p_paddr = buf;
6794     img->phdr.p_memsz = buf_size;
6795 
6796     img->shdr[1].sh_name = find_string(img->str, ".text");
6797     img->shdr[1].sh_addr = buf;
6798     img->shdr[1].sh_size = buf_size;
6799 
6800     img->shdr[2].sh_name = find_string(img->str, ".debug_info");
6801     img->shdr[3].sh_name = find_string(img->str, ".debug_abbrev");
6802 
6803     img->shdr[4].sh_name = find_string(img->str, ".debug_frame");
6804     img->shdr[4].sh_size = debug_frame_size;
6805 
6806     img->shdr[5].sh_name = find_string(img->str, ".symtab");
6807     img->shdr[6].sh_name = find_string(img->str, ".strtab");
6808 
6809     img->sym[1].st_name = find_string(img->str, "code_gen_buffer");
6810     img->sym[1].st_value = buf;
6811     img->sym[1].st_size = buf_size;
6812 
6813     img->di.cu_low_pc = buf;
6814     img->di.cu_high_pc = buf + buf_size;
6815     img->di.fn_low_pc = buf;
6816     img->di.fn_high_pc = buf + buf_size;
6817 
6818     dfh = (DebugFrameHeader *)(img + 1);
6819     memcpy(dfh, debug_frame, debug_frame_size);
6820     dfh->fde.func_start = buf;
6821     dfh->fde.func_len = buf_size;
6822 
6823 #ifdef DEBUG_JIT
6824     /* Enable this block to be able to debug the ELF image file creation.
6825        One can use readelf, objdump, or other inspection utilities.  */
6826     {
6827         g_autofree char *jit = g_strdup_printf("%s/qemu.jit", g_get_tmp_dir());
6828         FILE *f = fopen(jit, "w+b");
6829         if (f) {
6830             if (fwrite(img, img_size, 1, f) != img_size) {
6831                 /* Avoid stupid unused return value warning for fwrite.  */
6832             }
6833             fclose(f);
6834         }
6835     }
6836 #endif
6837 
6838     one_entry.symfile_addr = img;
6839     one_entry.symfile_size = img_size;
6840 
6841     __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
6842     __jit_debug_descriptor.relevant_entry = &one_entry;
6843     __jit_debug_descriptor.first_entry = &one_entry;
6844     __jit_debug_register_code();
6845 }
6846 #else
6847 /* No support for the feature.  Provide the entry point expected by exec.c,
6848    and implement the internal function we declared earlier.  */
6849 
6850 static void tcg_register_jit_int(const void *buf, size_t size,
6851                                  const void *debug_frame,
6852                                  size_t debug_frame_size)
6853 {
6854 }
6855 
6856 void tcg_register_jit(const void *buf, size_t buf_size)
6857 {
6858 }
6859 #endif /* ELF_HOST_MACHINE */
6860 
6861 #if !TCG_TARGET_MAYBE_vec
6862 void tcg_expand_vec_op(TCGOpcode o, TCGType t, unsigned e, TCGArg a0, ...)
6863 {
6864     g_assert_not_reached();
6865 }
6866 #endif
6867