xref: /qemu/include/tcg/tcg.h (revision dfd1b812)
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 #ifndef TCG_H
26 #define TCG_H
27 
28 #include "cpu.h"
29 #include "exec/memop.h"
30 #include "exec/memopidx.h"
31 #include "qemu/bitops.h"
32 #include "qemu/plugin.h"
33 #include "qemu/queue.h"
34 #include "tcg/tcg-mo.h"
35 #include "tcg-target-reg-bits.h"
36 #include "tcg-target.h"
37 #include "tcg/tcg-cond.h"
38 #include "tcg/debug-assert.h"
39 
40 /* XXX: make safe guess about sizes */
41 #define MAX_OP_PER_INSTR 266
42 
43 #define MAX_CALL_IARGS  7
44 
45 #define CPU_TEMP_BUF_NLONGS 128
46 #define TCG_STATIC_FRAME_SIZE  (CPU_TEMP_BUF_NLONGS * sizeof(long))
47 
48 #if TCG_TARGET_REG_BITS == 32
49 typedef int32_t tcg_target_long;
50 typedef uint32_t tcg_target_ulong;
51 #define TCG_PRIlx PRIx32
52 #define TCG_PRIld PRId32
53 #elif TCG_TARGET_REG_BITS == 64
54 typedef int64_t tcg_target_long;
55 typedef uint64_t tcg_target_ulong;
56 #define TCG_PRIlx PRIx64
57 #define TCG_PRIld PRId64
58 #else
59 #error unsupported
60 #endif
61 
62 #if TCG_TARGET_NB_REGS <= 32
63 typedef uint32_t TCGRegSet;
64 #elif TCG_TARGET_NB_REGS <= 64
65 typedef uint64_t TCGRegSet;
66 #else
67 #error unsupported
68 #endif
69 
70 #if TCG_TARGET_REG_BITS == 32
71 /* Turn some undef macros into false macros.  */
72 #define TCG_TARGET_HAS_extrl_i64_i32    0
73 #define TCG_TARGET_HAS_extrh_i64_i32    0
74 #define TCG_TARGET_HAS_div_i64          0
75 #define TCG_TARGET_HAS_rem_i64          0
76 #define TCG_TARGET_HAS_div2_i64         0
77 #define TCG_TARGET_HAS_rot_i64          0
78 #define TCG_TARGET_HAS_ext8s_i64        0
79 #define TCG_TARGET_HAS_ext16s_i64       0
80 #define TCG_TARGET_HAS_ext32s_i64       0
81 #define TCG_TARGET_HAS_ext8u_i64        0
82 #define TCG_TARGET_HAS_ext16u_i64       0
83 #define TCG_TARGET_HAS_ext32u_i64       0
84 #define TCG_TARGET_HAS_bswap16_i64      0
85 #define TCG_TARGET_HAS_bswap32_i64      0
86 #define TCG_TARGET_HAS_bswap64_i64      0
87 #define TCG_TARGET_HAS_neg_i64          0
88 #define TCG_TARGET_HAS_not_i64          0
89 #define TCG_TARGET_HAS_andc_i64         0
90 #define TCG_TARGET_HAS_orc_i64          0
91 #define TCG_TARGET_HAS_eqv_i64          0
92 #define TCG_TARGET_HAS_nand_i64         0
93 #define TCG_TARGET_HAS_nor_i64          0
94 #define TCG_TARGET_HAS_clz_i64          0
95 #define TCG_TARGET_HAS_ctz_i64          0
96 #define TCG_TARGET_HAS_ctpop_i64        0
97 #define TCG_TARGET_HAS_deposit_i64      0
98 #define TCG_TARGET_HAS_extract_i64      0
99 #define TCG_TARGET_HAS_sextract_i64     0
100 #define TCG_TARGET_HAS_extract2_i64     0
101 #define TCG_TARGET_HAS_movcond_i64      0
102 #define TCG_TARGET_HAS_add2_i64         0
103 #define TCG_TARGET_HAS_sub2_i64         0
104 #define TCG_TARGET_HAS_mulu2_i64        0
105 #define TCG_TARGET_HAS_muls2_i64        0
106 #define TCG_TARGET_HAS_muluh_i64        0
107 #define TCG_TARGET_HAS_mulsh_i64        0
108 /* Turn some undef macros into true macros.  */
109 #define TCG_TARGET_HAS_add2_i32         1
110 #define TCG_TARGET_HAS_sub2_i32         1
111 #endif
112 
113 #ifndef TCG_TARGET_deposit_i32_valid
114 #define TCG_TARGET_deposit_i32_valid(ofs, len) 1
115 #endif
116 #ifndef TCG_TARGET_deposit_i64_valid
117 #define TCG_TARGET_deposit_i64_valid(ofs, len) 1
118 #endif
119 #ifndef TCG_TARGET_extract_i32_valid
120 #define TCG_TARGET_extract_i32_valid(ofs, len) 1
121 #endif
122 #ifndef TCG_TARGET_extract_i64_valid
123 #define TCG_TARGET_extract_i64_valid(ofs, len) 1
124 #endif
125 
126 /* Only one of DIV or DIV2 should be defined.  */
127 #if defined(TCG_TARGET_HAS_div_i32)
128 #define TCG_TARGET_HAS_div2_i32         0
129 #elif defined(TCG_TARGET_HAS_div2_i32)
130 #define TCG_TARGET_HAS_div_i32          0
131 #define TCG_TARGET_HAS_rem_i32          0
132 #endif
133 #if defined(TCG_TARGET_HAS_div_i64)
134 #define TCG_TARGET_HAS_div2_i64         0
135 #elif defined(TCG_TARGET_HAS_div2_i64)
136 #define TCG_TARGET_HAS_div_i64          0
137 #define TCG_TARGET_HAS_rem_i64          0
138 #endif
139 
140 #if !defined(TCG_TARGET_HAS_v64) \
141     && !defined(TCG_TARGET_HAS_v128) \
142     && !defined(TCG_TARGET_HAS_v256)
143 #define TCG_TARGET_MAYBE_vec            0
144 #define TCG_TARGET_HAS_abs_vec          0
145 #define TCG_TARGET_HAS_neg_vec          0
146 #define TCG_TARGET_HAS_not_vec          0
147 #define TCG_TARGET_HAS_andc_vec         0
148 #define TCG_TARGET_HAS_orc_vec          0
149 #define TCG_TARGET_HAS_nand_vec         0
150 #define TCG_TARGET_HAS_nor_vec          0
151 #define TCG_TARGET_HAS_eqv_vec          0
152 #define TCG_TARGET_HAS_roti_vec         0
153 #define TCG_TARGET_HAS_rots_vec         0
154 #define TCG_TARGET_HAS_rotv_vec         0
155 #define TCG_TARGET_HAS_shi_vec          0
156 #define TCG_TARGET_HAS_shs_vec          0
157 #define TCG_TARGET_HAS_shv_vec          0
158 #define TCG_TARGET_HAS_mul_vec          0
159 #define TCG_TARGET_HAS_sat_vec          0
160 #define TCG_TARGET_HAS_minmax_vec       0
161 #define TCG_TARGET_HAS_bitsel_vec       0
162 #define TCG_TARGET_HAS_cmpsel_vec       0
163 #else
164 #define TCG_TARGET_MAYBE_vec            1
165 #endif
166 #ifndef TCG_TARGET_HAS_v64
167 #define TCG_TARGET_HAS_v64              0
168 #endif
169 #ifndef TCG_TARGET_HAS_v128
170 #define TCG_TARGET_HAS_v128             0
171 #endif
172 #ifndef TCG_TARGET_HAS_v256
173 #define TCG_TARGET_HAS_v256             0
174 #endif
175 
176 typedef enum TCGOpcode {
177 #define DEF(name, oargs, iargs, cargs, flags) INDEX_op_ ## name,
178 #include "tcg/tcg-opc.h"
179 #undef DEF
180     NB_OPS,
181 } TCGOpcode;
182 
183 #define tcg_regset_set_reg(d, r)   ((d) |= (TCGRegSet)1 << (r))
184 #define tcg_regset_reset_reg(d, r) ((d) &= ~((TCGRegSet)1 << (r)))
185 #define tcg_regset_test_reg(d, r)  (((d) >> (r)) & 1)
186 
187 #ifndef TCG_TARGET_INSN_UNIT_SIZE
188 # error "Missing TCG_TARGET_INSN_UNIT_SIZE"
189 #elif TCG_TARGET_INSN_UNIT_SIZE == 1
190 typedef uint8_t tcg_insn_unit;
191 #elif TCG_TARGET_INSN_UNIT_SIZE == 2
192 typedef uint16_t tcg_insn_unit;
193 #elif TCG_TARGET_INSN_UNIT_SIZE == 4
194 typedef uint32_t tcg_insn_unit;
195 #elif TCG_TARGET_INSN_UNIT_SIZE == 8
196 typedef uint64_t tcg_insn_unit;
197 #else
198 /* The port better have done this.  */
199 #endif
200 
201 typedef struct TCGRelocation TCGRelocation;
202 struct TCGRelocation {
203     QSIMPLEQ_ENTRY(TCGRelocation) next;
204     tcg_insn_unit *ptr;
205     intptr_t addend;
206     int type;
207 };
208 
209 typedef struct TCGOp TCGOp;
210 typedef struct TCGLabelUse TCGLabelUse;
211 struct TCGLabelUse {
212     QSIMPLEQ_ENTRY(TCGLabelUse) next;
213     TCGOp *op;
214 };
215 
216 typedef struct TCGLabel TCGLabel;
217 struct TCGLabel {
218     bool present;
219     bool has_value;
220     uint16_t id;
221     union {
222         uintptr_t value;
223         const tcg_insn_unit *value_ptr;
224     } u;
225     QSIMPLEQ_HEAD(, TCGLabelUse) branches;
226     QSIMPLEQ_HEAD(, TCGRelocation) relocs;
227     QSIMPLEQ_ENTRY(TCGLabel) next;
228 };
229 
230 typedef struct TCGPool {
231     struct TCGPool *next;
232     int size;
233     uint8_t data[] __attribute__ ((aligned));
234 } TCGPool;
235 
236 #define TCG_POOL_CHUNK_SIZE 32768
237 
238 #define TCG_MAX_TEMPS 512
239 #define TCG_MAX_INSNS 512
240 
241 /* when the size of the arguments of a called function is smaller than
242    this value, they are statically allocated in the TB stack frame */
243 #define TCG_STATIC_CALL_ARGS_SIZE 128
244 
245 typedef enum TCGType {
246     TCG_TYPE_I32,
247     TCG_TYPE_I64,
248     TCG_TYPE_I128,
249 
250     TCG_TYPE_V64,
251     TCG_TYPE_V128,
252     TCG_TYPE_V256,
253 
254     /* Number of different types (integer not enum) */
255 #define TCG_TYPE_COUNT  (TCG_TYPE_V256 + 1)
256 
257     /* An alias for the size of the host register.  */
258 #if TCG_TARGET_REG_BITS == 32
259     TCG_TYPE_REG = TCG_TYPE_I32,
260 #else
261     TCG_TYPE_REG = TCG_TYPE_I64,
262 #endif
263 
264     /* An alias for the size of the native pointer.  */
265 #if UINTPTR_MAX == UINT32_MAX
266     TCG_TYPE_PTR = TCG_TYPE_I32,
267 #else
268     TCG_TYPE_PTR = TCG_TYPE_I64,
269 #endif
270 } TCGType;
271 
272 /**
273  * tcg_type_size
274  * @t: type
275  *
276  * Return the size of the type in bytes.
277  */
278 static inline int tcg_type_size(TCGType t)
279 {
280     unsigned i = t;
281     if (i >= TCG_TYPE_V64) {
282         tcg_debug_assert(i < TCG_TYPE_COUNT);
283         i -= TCG_TYPE_V64 - 1;
284     }
285     return 4 << i;
286 }
287 
288 /**
289  * get_alignment_bits
290  * @memop: MemOp value
291  *
292  * Extract the alignment size from the memop.
293  */
294 static inline unsigned get_alignment_bits(MemOp memop)
295 {
296     unsigned a = memop & MO_AMASK;
297 
298     if (a == MO_UNALN) {
299         /* No alignment required.  */
300         a = 0;
301     } else if (a == MO_ALIGN) {
302         /* A natural alignment requirement.  */
303         a = memop & MO_SIZE;
304     } else {
305         /* A specific alignment requirement.  */
306         a = a >> MO_ASHIFT;
307     }
308     return a;
309 }
310 
311 typedef tcg_target_ulong TCGArg;
312 
313 /* Define type and accessor macros for TCG variables.
314 
315    TCG variables are the inputs and outputs of TCG ops, as described
316    in tcg/README. Target CPU front-end code uses these types to deal
317    with TCG variables as it emits TCG code via the tcg_gen_* functions.
318    They come in several flavours:
319     * TCGv_i32  : 32 bit integer type
320     * TCGv_i64  : 64 bit integer type
321     * TCGv_i128 : 128 bit integer type
322     * TCGv_ptr  : a host pointer type
323     * TCGv_vec  : a host vector type; the exact size is not exposed
324                   to the CPU front-end code.
325     * TCGv      : an integer type the same size as target_ulong
326                   (an alias for either TCGv_i32 or TCGv_i64)
327    The compiler's type checking will complain if you mix them
328    up and pass the wrong sized TCGv to a function.
329 
330    Users of tcg_gen_* don't need to know about any of the internal
331    details of these, and should treat them as opaque types.
332    You won't be able to look inside them in a debugger either.
333 
334    Internal implementation details follow:
335 
336    Note that there is no definition of the structs TCGv_i32_d etc anywhere.
337    This is deliberate, because the values we store in variables of type
338    TCGv_i32 are not really pointers-to-structures. They're just small
339    integers, but keeping them in pointer types like this means that the
340    compiler will complain if you accidentally pass a TCGv_i32 to a
341    function which takes a TCGv_i64, and so on. Only the internals of
342    TCG need to care about the actual contents of the types.  */
343 
344 typedef struct TCGv_i32_d *TCGv_i32;
345 typedef struct TCGv_i64_d *TCGv_i64;
346 typedef struct TCGv_i128_d *TCGv_i128;
347 typedef struct TCGv_ptr_d *TCGv_ptr;
348 typedef struct TCGv_vec_d *TCGv_vec;
349 typedef TCGv_ptr TCGv_env;
350 
351 /* call flags */
352 /* Helper does not read globals (either directly or through an exception). It
353    implies TCG_CALL_NO_WRITE_GLOBALS. */
354 #define TCG_CALL_NO_READ_GLOBALS    0x0001
355 /* Helper does not write globals */
356 #define TCG_CALL_NO_WRITE_GLOBALS   0x0002
357 /* Helper can be safely suppressed if the return value is not used. */
358 #define TCG_CALL_NO_SIDE_EFFECTS    0x0004
359 /* Helper is G_NORETURN.  */
360 #define TCG_CALL_NO_RETURN          0x0008
361 /* Helper is part of Plugins.  */
362 #define TCG_CALL_PLUGIN             0x0010
363 
364 /* convenience version of most used call flags */
365 #define TCG_CALL_NO_RWG         TCG_CALL_NO_READ_GLOBALS
366 #define TCG_CALL_NO_WG          TCG_CALL_NO_WRITE_GLOBALS
367 #define TCG_CALL_NO_SE          TCG_CALL_NO_SIDE_EFFECTS
368 #define TCG_CALL_NO_RWG_SE      (TCG_CALL_NO_RWG | TCG_CALL_NO_SE)
369 #define TCG_CALL_NO_WG_SE       (TCG_CALL_NO_WG | TCG_CALL_NO_SE)
370 
371 /*
372  * Flags for the bswap opcodes.
373  * If IZ, the input is zero-extended, otherwise unknown.
374  * If OZ or OS, the output is zero- or sign-extended respectively,
375  * otherwise the high bits are undefined.
376  */
377 enum {
378     TCG_BSWAP_IZ = 1,
379     TCG_BSWAP_OZ = 2,
380     TCG_BSWAP_OS = 4,
381 };
382 
383 typedef enum TCGTempVal {
384     TEMP_VAL_DEAD,
385     TEMP_VAL_REG,
386     TEMP_VAL_MEM,
387     TEMP_VAL_CONST,
388 } TCGTempVal;
389 
390 typedef enum TCGTempKind {
391     /*
392      * Temp is dead at the end of the extended basic block (EBB),
393      * the single-entry multiple-exit region that falls through
394      * conditional branches.
395      */
396     TEMP_EBB,
397     /* Temp is live across the entire translation block, but dead at end. */
398     TEMP_TB,
399     /* Temp is live across the entire translation block, and between them. */
400     TEMP_GLOBAL,
401     /* Temp is in a fixed register. */
402     TEMP_FIXED,
403     /* Temp is a fixed constant. */
404     TEMP_CONST,
405 } TCGTempKind;
406 
407 typedef struct TCGTemp {
408     TCGReg reg:8;
409     TCGTempVal val_type:8;
410     TCGType base_type:8;
411     TCGType type:8;
412     TCGTempKind kind:3;
413     unsigned int indirect_reg:1;
414     unsigned int indirect_base:1;
415     unsigned int mem_coherent:1;
416     unsigned int mem_allocated:1;
417     unsigned int temp_allocated:1;
418     unsigned int temp_subindex:1;
419 
420     int64_t val;
421     struct TCGTemp *mem_base;
422     intptr_t mem_offset;
423     const char *name;
424 
425     /* Pass-specific information that can be stored for a temporary.
426        One word worth of integer data, and one pointer to data
427        allocated separately.  */
428     uintptr_t state;
429     void *state_ptr;
430 } TCGTemp;
431 
432 typedef struct TCGContext TCGContext;
433 
434 typedef struct TCGTempSet {
435     unsigned long l[BITS_TO_LONGS(TCG_MAX_TEMPS)];
436 } TCGTempSet;
437 
438 /*
439  * With 1 128-bit output, a 32-bit host requires 4 output parameters,
440  * which leaves a maximum of 28 other slots.  Which is enough for 7
441  * 128-bit operands.
442  */
443 #define DEAD_ARG  (1 << 4)
444 #define SYNC_ARG  (1 << 0)
445 typedef uint32_t TCGLifeData;
446 
447 struct TCGOp {
448     TCGOpcode opc   : 8;
449     unsigned nargs  : 8;
450 
451     /* Parameters for this opcode.  See below.  */
452     unsigned param1 : 8;
453     unsigned param2 : 8;
454 
455     /* Lifetime data of the operands.  */
456     TCGLifeData life;
457 
458     /* Next and previous opcodes.  */
459     QTAILQ_ENTRY(TCGOp) link;
460 
461     /* Register preferences for the output(s).  */
462     TCGRegSet output_pref[2];
463 
464     /* Arguments for the opcode.  */
465     TCGArg args[];
466 };
467 
468 #define TCGOP_CALLI(X)    (X)->param1
469 #define TCGOP_CALLO(X)    (X)->param2
470 
471 #define TCGOP_VECL(X)     (X)->param1
472 #define TCGOP_VECE(X)     (X)->param2
473 
474 /* Make sure operands fit in the bitfields above.  */
475 QEMU_BUILD_BUG_ON(NB_OPS > (1 << 8));
476 
477 static inline TCGRegSet output_pref(const TCGOp *op, unsigned i)
478 {
479     return i < ARRAY_SIZE(op->output_pref) ? op->output_pref[i] : 0;
480 }
481 
482 typedef struct TCGProfile {
483     int64_t cpu_exec_time;
484     int64_t tb_count1;
485     int64_t tb_count;
486     int64_t op_count; /* total insn count */
487     int op_count_max; /* max insn per TB */
488     int temp_count_max;
489     int64_t temp_count;
490     int64_t del_op_count;
491     int64_t code_in_len;
492     int64_t code_out_len;
493     int64_t search_out_len;
494     int64_t interm_time;
495     int64_t code_time;
496     int64_t la_time;
497     int64_t opt_time;
498     int64_t restore_count;
499     int64_t restore_time;
500     int64_t table_op_count[NB_OPS];
501 } TCGProfile;
502 
503 struct TCGContext {
504     uint8_t *pool_cur, *pool_end;
505     TCGPool *pool_first, *pool_current, *pool_first_large;
506     int nb_labels;
507     int nb_globals;
508     int nb_temps;
509     int nb_indirects;
510     int nb_ops;
511     TCGType addr_type;            /* TCG_TYPE_I32 or TCG_TYPE_I64 */
512 
513 #ifdef CONFIG_SOFTMMU
514     int tlb_fast_offset;
515     int page_mask;
516     uint8_t page_bits;
517     uint8_t tlb_dyn_max_bits;
518 #endif
519     uint8_t insn_start_words;
520     TCGBar guest_mo;
521 
522     TCGRegSet reserved_regs;
523     intptr_t current_frame_offset;
524     intptr_t frame_start;
525     intptr_t frame_end;
526     TCGTemp *frame_temp;
527 
528     TranslationBlock *gen_tb;     /* tb for which code is being generated */
529     tcg_insn_unit *code_buf;      /* pointer for start of tb */
530     tcg_insn_unit *code_ptr;      /* pointer for running end of tb */
531 
532 #ifdef CONFIG_PROFILER
533     TCGProfile prof;
534 #endif
535 
536 #ifdef CONFIG_DEBUG_TCG
537     int goto_tb_issue_mask;
538     const TCGOpcode *vecop_list;
539 #endif
540 
541     /* Code generation.  Note that we specifically do not use tcg_insn_unit
542        here, because there's too much arithmetic throughout that relies
543        on addition and subtraction working on bytes.  Rely on the GCC
544        extension that allows arithmetic on void*.  */
545     void *code_gen_buffer;
546     size_t code_gen_buffer_size;
547     void *code_gen_ptr;
548     void *data_gen_ptr;
549 
550     /* Threshold to flush the translated code buffer.  */
551     void *code_gen_highwater;
552 
553     /* Track which vCPU triggers events */
554     CPUState *cpu;                      /* *_trans */
555 
556     /* These structures are private to tcg-target.c.inc.  */
557 #ifdef TCG_TARGET_NEED_LDST_LABELS
558     QSIMPLEQ_HEAD(, TCGLabelQemuLdst) ldst_labels;
559 #endif
560 #ifdef TCG_TARGET_NEED_POOL_LABELS
561     struct TCGLabelPoolData *pool_labels;
562 #endif
563 
564     TCGLabel *exitreq_label;
565 
566 #ifdef CONFIG_PLUGIN
567     /*
568      * We keep one plugin_tb struct per TCGContext. Note that on every TB
569      * translation we clear but do not free its contents; this way we
570      * avoid a lot of malloc/free churn, since after a few TB's it's
571      * unlikely that we'll need to allocate either more instructions or more
572      * space for instructions (for variable-instruction-length ISAs).
573      */
574     struct qemu_plugin_tb *plugin_tb;
575 
576     /* descriptor of the instruction being translated */
577     struct qemu_plugin_insn *plugin_insn;
578 #endif
579 
580     GHashTable *const_table[TCG_TYPE_COUNT];
581     TCGTempSet free_temps[TCG_TYPE_COUNT];
582     TCGTemp temps[TCG_MAX_TEMPS]; /* globals first, temps after */
583 
584     QTAILQ_HEAD(, TCGOp) ops, free_ops;
585     QSIMPLEQ_HEAD(, TCGLabel) labels;
586 
587     /* Tells which temporary holds a given register.
588        It does not take into account fixed registers */
589     TCGTemp *reg_to_temp[TCG_TARGET_NB_REGS];
590 
591     uint16_t gen_insn_end_off[TCG_MAX_INSNS];
592     uint64_t *gen_insn_data;
593 
594     /* Exit to translator on overflow. */
595     sigjmp_buf jmp_trans;
596 };
597 
598 static inline bool temp_readonly(TCGTemp *ts)
599 {
600     return ts->kind >= TEMP_FIXED;
601 }
602 
603 extern __thread TCGContext *tcg_ctx;
604 extern const void *tcg_code_gen_epilogue;
605 extern uintptr_t tcg_splitwx_diff;
606 extern TCGv_env cpu_env;
607 
608 bool in_code_gen_buffer(const void *p);
609 
610 #ifdef CONFIG_DEBUG_TCG
611 const void *tcg_splitwx_to_rx(void *rw);
612 void *tcg_splitwx_to_rw(const void *rx);
613 #else
614 static inline const void *tcg_splitwx_to_rx(void *rw)
615 {
616     return rw ? rw + tcg_splitwx_diff : NULL;
617 }
618 
619 static inline void *tcg_splitwx_to_rw(const void *rx)
620 {
621     return rx ? (void *)rx - tcg_splitwx_diff : NULL;
622 }
623 #endif
624 
625 static inline TCGArg temp_arg(TCGTemp *ts)
626 {
627     return (uintptr_t)ts;
628 }
629 
630 static inline TCGTemp *arg_temp(TCGArg a)
631 {
632     return (TCGTemp *)(uintptr_t)a;
633 }
634 
635 #ifdef CONFIG_DEBUG_TCG
636 size_t temp_idx(TCGTemp *ts);
637 TCGTemp *tcgv_i32_temp(TCGv_i32 v);
638 #else
639 static inline size_t temp_idx(TCGTemp *ts)
640 {
641     return ts - tcg_ctx->temps;
642 }
643 
644 /*
645  * Using the offset of a temporary, relative to TCGContext, rather than
646  * its index means that we don't use 0.  That leaves offset 0 free for
647  * a NULL representation without having to leave index 0 unused.
648  */
649 static inline TCGTemp *tcgv_i32_temp(TCGv_i32 v)
650 {
651     return (void *)tcg_ctx + (uintptr_t)v;
652 }
653 #endif
654 
655 static inline TCGTemp *tcgv_i64_temp(TCGv_i64 v)
656 {
657     return tcgv_i32_temp((TCGv_i32)v);
658 }
659 
660 static inline TCGTemp *tcgv_i128_temp(TCGv_i128 v)
661 {
662     return tcgv_i32_temp((TCGv_i32)v);
663 }
664 
665 static inline TCGTemp *tcgv_ptr_temp(TCGv_ptr v)
666 {
667     return tcgv_i32_temp((TCGv_i32)v);
668 }
669 
670 static inline TCGTemp *tcgv_vec_temp(TCGv_vec v)
671 {
672     return tcgv_i32_temp((TCGv_i32)v);
673 }
674 
675 static inline TCGArg tcgv_i32_arg(TCGv_i32 v)
676 {
677     return temp_arg(tcgv_i32_temp(v));
678 }
679 
680 static inline TCGArg tcgv_i64_arg(TCGv_i64 v)
681 {
682     return temp_arg(tcgv_i64_temp(v));
683 }
684 
685 static inline TCGArg tcgv_i128_arg(TCGv_i128 v)
686 {
687     return temp_arg(tcgv_i128_temp(v));
688 }
689 
690 static inline TCGArg tcgv_ptr_arg(TCGv_ptr v)
691 {
692     return temp_arg(tcgv_ptr_temp(v));
693 }
694 
695 static inline TCGArg tcgv_vec_arg(TCGv_vec v)
696 {
697     return temp_arg(tcgv_vec_temp(v));
698 }
699 
700 static inline TCGv_i32 temp_tcgv_i32(TCGTemp *t)
701 {
702     (void)temp_idx(t); /* trigger embedded assert */
703     return (TCGv_i32)((void *)t - (void *)tcg_ctx);
704 }
705 
706 static inline TCGv_i64 temp_tcgv_i64(TCGTemp *t)
707 {
708     return (TCGv_i64)temp_tcgv_i32(t);
709 }
710 
711 static inline TCGv_i128 temp_tcgv_i128(TCGTemp *t)
712 {
713     return (TCGv_i128)temp_tcgv_i32(t);
714 }
715 
716 static inline TCGv_ptr temp_tcgv_ptr(TCGTemp *t)
717 {
718     return (TCGv_ptr)temp_tcgv_i32(t);
719 }
720 
721 static inline TCGv_vec temp_tcgv_vec(TCGTemp *t)
722 {
723     return (TCGv_vec)temp_tcgv_i32(t);
724 }
725 
726 static inline TCGArg tcg_get_insn_param(TCGOp *op, int arg)
727 {
728     return op->args[arg];
729 }
730 
731 static inline void tcg_set_insn_param(TCGOp *op, int arg, TCGArg v)
732 {
733     op->args[arg] = v;
734 }
735 
736 static inline uint64_t tcg_get_insn_start_param(TCGOp *op, int arg)
737 {
738     if (TCG_TARGET_REG_BITS == 64) {
739         return tcg_get_insn_param(op, arg);
740     } else {
741         return deposit64(tcg_get_insn_param(op, arg * 2), 32, 32,
742                          tcg_get_insn_param(op, arg * 2 + 1));
743     }
744 }
745 
746 static inline void tcg_set_insn_start_param(TCGOp *op, int arg, uint64_t v)
747 {
748     if (TCG_TARGET_REG_BITS == 64) {
749         tcg_set_insn_param(op, arg, v);
750     } else {
751         tcg_set_insn_param(op, arg * 2, v);
752         tcg_set_insn_param(op, arg * 2 + 1, v >> 32);
753     }
754 }
755 
756 /* The last op that was emitted.  */
757 static inline TCGOp *tcg_last_op(void)
758 {
759     return QTAILQ_LAST(&tcg_ctx->ops);
760 }
761 
762 /* Test for whether to terminate the TB for using too many opcodes.  */
763 static inline bool tcg_op_buf_full(void)
764 {
765     /* This is not a hard limit, it merely stops translation when
766      * we have produced "enough" opcodes.  We want to limit TB size
767      * such that a RISC host can reasonably use a 16-bit signed
768      * branch within the TB.  We also need to be mindful of the
769      * 16-bit unsigned offsets, TranslationBlock.jmp_reset_offset[]
770      * and TCGContext.gen_insn_end_off[].
771      */
772     return tcg_ctx->nb_ops >= 4000;
773 }
774 
775 /* pool based memory allocation */
776 
777 /* user-mode: mmap_lock must be held for tcg_malloc_internal. */
778 void *tcg_malloc_internal(TCGContext *s, int size);
779 void tcg_pool_reset(TCGContext *s);
780 TranslationBlock *tcg_tb_alloc(TCGContext *s);
781 
782 void tcg_region_reset_all(void);
783 
784 size_t tcg_code_size(void);
785 size_t tcg_code_capacity(void);
786 
787 void tcg_tb_insert(TranslationBlock *tb);
788 void tcg_tb_remove(TranslationBlock *tb);
789 TranslationBlock *tcg_tb_lookup(uintptr_t tc_ptr);
790 void tcg_tb_foreach(GTraverseFunc func, gpointer user_data);
791 size_t tcg_nb_tbs(void);
792 
793 /* user-mode: Called with mmap_lock held.  */
794 static inline void *tcg_malloc(int size)
795 {
796     TCGContext *s = tcg_ctx;
797     uint8_t *ptr, *ptr_end;
798 
799     /* ??? This is a weak placeholder for minimum malloc alignment.  */
800     size = QEMU_ALIGN_UP(size, 8);
801 
802     ptr = s->pool_cur;
803     ptr_end = ptr + size;
804     if (unlikely(ptr_end > s->pool_end)) {
805         return tcg_malloc_internal(tcg_ctx, size);
806     } else {
807         s->pool_cur = ptr_end;
808         return ptr;
809     }
810 }
811 
812 void tcg_init(size_t tb_size, int splitwx, unsigned max_cpus);
813 void tcg_register_thread(void);
814 void tcg_prologue_init(TCGContext *s);
815 void tcg_func_start(TCGContext *s);
816 
817 int tcg_gen_code(TCGContext *s, TranslationBlock *tb, uint64_t pc_start);
818 
819 void tb_target_set_jmp_target(const TranslationBlock *, int,
820                               uintptr_t, uintptr_t);
821 
822 void tcg_set_frame(TCGContext *s, TCGReg reg, intptr_t start, intptr_t size);
823 
824 TCGTemp *tcg_global_mem_new_internal(TCGType, TCGv_ptr,
825                                      intptr_t, const char *);
826 TCGTemp *tcg_temp_new_internal(TCGType, TCGTempKind);
827 TCGv_vec tcg_temp_new_vec(TCGType type);
828 TCGv_vec tcg_temp_new_vec_matching(TCGv_vec match);
829 
830 static inline TCGv_i32 tcg_global_mem_new_i32(TCGv_ptr reg, intptr_t offset,
831                                               const char *name)
832 {
833     TCGTemp *t = tcg_global_mem_new_internal(TCG_TYPE_I32, reg, offset, name);
834     return temp_tcgv_i32(t);
835 }
836 
837 static inline TCGv_i32 tcg_temp_new_i32(void)
838 {
839     TCGTemp *t = tcg_temp_new_internal(TCG_TYPE_I32, TEMP_TB);
840     return temp_tcgv_i32(t);
841 }
842 
843 static inline TCGv_i64 tcg_global_mem_new_i64(TCGv_ptr reg, intptr_t offset,
844                                               const char *name)
845 {
846     TCGTemp *t = tcg_global_mem_new_internal(TCG_TYPE_I64, reg, offset, name);
847     return temp_tcgv_i64(t);
848 }
849 
850 static inline TCGv_i64 tcg_temp_new_i64(void)
851 {
852     TCGTemp *t = tcg_temp_new_internal(TCG_TYPE_I64, TEMP_TB);
853     return temp_tcgv_i64(t);
854 }
855 
856 static inline TCGv_i128 tcg_temp_new_i128(void)
857 {
858     TCGTemp *t = tcg_temp_new_internal(TCG_TYPE_I128, TEMP_TB);
859     return temp_tcgv_i128(t);
860 }
861 
862 static inline TCGv_ptr tcg_global_mem_new_ptr(TCGv_ptr reg, intptr_t offset,
863                                               const char *name)
864 {
865     TCGTemp *t = tcg_global_mem_new_internal(TCG_TYPE_PTR, reg, offset, name);
866     return temp_tcgv_ptr(t);
867 }
868 
869 static inline TCGv_ptr tcg_temp_new_ptr(void)
870 {
871     TCGTemp *t = tcg_temp_new_internal(TCG_TYPE_PTR, TEMP_TB);
872     return temp_tcgv_ptr(t);
873 }
874 
875 int64_t tcg_cpu_exec_time(void);
876 void tcg_dump_info(GString *buf);
877 void tcg_dump_op_count(GString *buf);
878 
879 #define TCG_CT_CONST  1 /* any constant of register size */
880 
881 typedef struct TCGArgConstraint {
882     unsigned ct : 16;
883     unsigned alias_index : 4;
884     unsigned sort_index : 4;
885     unsigned pair_index : 4;
886     unsigned pair : 2;  /* 0: none, 1: first, 2: second, 3: second alias */
887     bool oalias : 1;
888     bool ialias : 1;
889     bool newreg : 1;
890     TCGRegSet regs;
891 } TCGArgConstraint;
892 
893 #define TCG_MAX_OP_ARGS 16
894 
895 /* Bits for TCGOpDef->flags, 8 bits available, all used.  */
896 enum {
897     /* Instruction exits the translation block.  */
898     TCG_OPF_BB_EXIT      = 0x01,
899     /* Instruction defines the end of a basic block.  */
900     TCG_OPF_BB_END       = 0x02,
901     /* Instruction clobbers call registers and potentially update globals.  */
902     TCG_OPF_CALL_CLOBBER = 0x04,
903     /* Instruction has side effects: it cannot be removed if its outputs
904        are not used, and might trigger exceptions.  */
905     TCG_OPF_SIDE_EFFECTS = 0x08,
906     /* Instruction operands are 64-bits (otherwise 32-bits).  */
907     TCG_OPF_64BIT        = 0x10,
908     /* Instruction is optional and not implemented by the host, or insn
909        is generic and should not be implemened by the host.  */
910     TCG_OPF_NOT_PRESENT  = 0x20,
911     /* Instruction operands are vectors.  */
912     TCG_OPF_VECTOR       = 0x40,
913     /* Instruction is a conditional branch. */
914     TCG_OPF_COND_BRANCH  = 0x80
915 };
916 
917 typedef struct TCGOpDef {
918     const char *name;
919     uint8_t nb_oargs, nb_iargs, nb_cargs, nb_args;
920     uint8_t flags;
921     TCGArgConstraint *args_ct;
922 } TCGOpDef;
923 
924 extern TCGOpDef tcg_op_defs[];
925 extern const size_t tcg_op_defs_max;
926 
927 typedef struct TCGTargetOpDef {
928     TCGOpcode op;
929     const char *args_ct_str[TCG_MAX_OP_ARGS];
930 } TCGTargetOpDef;
931 
932 bool tcg_op_supported(TCGOpcode op);
933 
934 void tcg_gen_call0(TCGHelperInfo *, TCGTemp *ret);
935 void tcg_gen_call1(TCGHelperInfo *, TCGTemp *ret, TCGTemp *);
936 void tcg_gen_call2(TCGHelperInfo *, TCGTemp *ret, TCGTemp *, TCGTemp *);
937 void tcg_gen_call3(TCGHelperInfo *, TCGTemp *ret, TCGTemp *,
938                    TCGTemp *, TCGTemp *);
939 void tcg_gen_call4(TCGHelperInfo *, TCGTemp *ret, TCGTemp *, TCGTemp *,
940                    TCGTemp *, TCGTemp *);
941 void tcg_gen_call5(TCGHelperInfo *, TCGTemp *ret, TCGTemp *, TCGTemp *,
942                    TCGTemp *, TCGTemp *, TCGTemp *);
943 void tcg_gen_call6(TCGHelperInfo *, TCGTemp *ret, TCGTemp *, TCGTemp *,
944                    TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *);
945 void tcg_gen_call7(TCGHelperInfo *, TCGTemp *ret, TCGTemp *, TCGTemp *,
946                    TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *, TCGTemp *);
947 
948 TCGOp *tcg_emit_op(TCGOpcode opc, unsigned nargs);
949 void tcg_op_remove(TCGContext *s, TCGOp *op);
950 TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *op,
951                             TCGOpcode opc, unsigned nargs);
952 TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *op,
953                            TCGOpcode opc, unsigned nargs);
954 
955 /**
956  * tcg_remove_ops_after:
957  * @op: target operation
958  *
959  * Discard any opcodes emitted since @op.  Expected usage is to save
960  * a starting point with tcg_last_op(), speculatively emit opcodes,
961  * then decide whether or not to keep those opcodes after the fact.
962  */
963 void tcg_remove_ops_after(TCGOp *op);
964 
965 void tcg_optimize(TCGContext *s);
966 
967 /*
968  * Locate or create a read-only temporary that is a constant.
969  * This kind of temporary need not be freed, but for convenience
970  * will be silently ignored by tcg_temp_free_*.
971  */
972 TCGTemp *tcg_constant_internal(TCGType type, int64_t val);
973 
974 static inline TCGv_i32 tcg_constant_i32(int32_t val)
975 {
976     return temp_tcgv_i32(tcg_constant_internal(TCG_TYPE_I32, val));
977 }
978 
979 static inline TCGv_i64 tcg_constant_i64(int64_t val)
980 {
981     return temp_tcgv_i64(tcg_constant_internal(TCG_TYPE_I64, val));
982 }
983 
984 TCGv_vec tcg_constant_vec(TCGType type, unsigned vece, int64_t val);
985 TCGv_vec tcg_constant_vec_matching(TCGv_vec match, unsigned vece, int64_t val);
986 
987 #if UINTPTR_MAX == UINT32_MAX
988 # define tcg_constant_ptr(x)     ((TCGv_ptr)tcg_constant_i32((intptr_t)(x)))
989 #else
990 # define tcg_constant_ptr(x)     ((TCGv_ptr)tcg_constant_i64((intptr_t)(x)))
991 #endif
992 
993 TCGLabel *gen_new_label(void);
994 
995 /**
996  * label_arg
997  * @l: label
998  *
999  * Encode a label for storage in the TCG opcode stream.
1000  */
1001 
1002 static inline TCGArg label_arg(TCGLabel *l)
1003 {
1004     return (uintptr_t)l;
1005 }
1006 
1007 /**
1008  * arg_label
1009  * @i: value
1010  *
1011  * The opposite of label_arg.  Retrieve a label from the
1012  * encoding of the TCG opcode stream.
1013  */
1014 
1015 static inline TCGLabel *arg_label(TCGArg i)
1016 {
1017     return (TCGLabel *)(uintptr_t)i;
1018 }
1019 
1020 /**
1021  * tcg_ptr_byte_diff
1022  * @a, @b: addresses to be differenced
1023  *
1024  * There are many places within the TCG backends where we need a byte
1025  * difference between two pointers.  While this can be accomplished
1026  * with local casting, it's easy to get wrong -- especially if one is
1027  * concerned with the signedness of the result.
1028  *
1029  * This version relies on GCC's void pointer arithmetic to get the
1030  * correct result.
1031  */
1032 
1033 static inline ptrdiff_t tcg_ptr_byte_diff(const void *a, const void *b)
1034 {
1035     return a - b;
1036 }
1037 
1038 /**
1039  * tcg_pcrel_diff
1040  * @s: the tcg context
1041  * @target: address of the target
1042  *
1043  * Produce a pc-relative difference, from the current code_ptr
1044  * to the destination address.
1045  */
1046 
1047 static inline ptrdiff_t tcg_pcrel_diff(TCGContext *s, const void *target)
1048 {
1049     return tcg_ptr_byte_diff(target, tcg_splitwx_to_rx(s->code_ptr));
1050 }
1051 
1052 /**
1053  * tcg_tbrel_diff
1054  * @s: the tcg context
1055  * @target: address of the target
1056  *
1057  * Produce a difference, from the beginning of the current TB code
1058  * to the destination address.
1059  */
1060 static inline ptrdiff_t tcg_tbrel_diff(TCGContext *s, const void *target)
1061 {
1062     return tcg_ptr_byte_diff(target, tcg_splitwx_to_rx(s->code_buf));
1063 }
1064 
1065 /**
1066  * tcg_current_code_size
1067  * @s: the tcg context
1068  *
1069  * Compute the current code size within the translation block.
1070  * This is used to fill in qemu's data structures for goto_tb.
1071  */
1072 
1073 static inline size_t tcg_current_code_size(TCGContext *s)
1074 {
1075     return tcg_ptr_byte_diff(s->code_ptr, s->code_buf);
1076 }
1077 
1078 /**
1079  * tcg_qemu_tb_exec:
1080  * @env: pointer to CPUArchState for the CPU
1081  * @tb_ptr: address of generated code for the TB to execute
1082  *
1083  * Start executing code from a given translation block.
1084  * Where translation blocks have been linked, execution
1085  * may proceed from the given TB into successive ones.
1086  * Control eventually returns only when some action is needed
1087  * from the top-level loop: either control must pass to a TB
1088  * which has not yet been directly linked, or an asynchronous
1089  * event such as an interrupt needs handling.
1090  *
1091  * Return: The return value is the value passed to the corresponding
1092  * tcg_gen_exit_tb() at translation time of the last TB attempted to execute.
1093  * The value is either zero or a 4-byte aligned pointer to that TB combined
1094  * with additional information in its two least significant bits. The
1095  * additional information is encoded as follows:
1096  *  0, 1: the link between this TB and the next is via the specified
1097  *        TB index (0 or 1). That is, we left the TB via (the equivalent
1098  *        of) "goto_tb <index>". The main loop uses this to determine
1099  *        how to link the TB just executed to the next.
1100  *  2:    we are using instruction counting code generation, and we
1101  *        did not start executing this TB because the instruction counter
1102  *        would hit zero midway through it. In this case the pointer
1103  *        returned is the TB we were about to execute, and the caller must
1104  *        arrange to execute the remaining count of instructions.
1105  *  3:    we stopped because the CPU's exit_request flag was set
1106  *        (usually meaning that there is an interrupt that needs to be
1107  *        handled). The pointer returned is the TB we were about to execute
1108  *        when we noticed the pending exit request.
1109  *
1110  * If the bottom two bits indicate an exit-via-index then the CPU
1111  * state is correctly synchronised and ready for execution of the next
1112  * TB (and in particular the guest PC is the address to execute next).
1113  * Otherwise, we gave up on execution of this TB before it started, and
1114  * the caller must fix up the CPU state by calling the CPU's
1115  * synchronize_from_tb() method with the TB pointer we return (falling
1116  * back to calling the CPU's set_pc method with tb->pb if no
1117  * synchronize_from_tb() method exists).
1118  *
1119  * Note that TCG targets may use a different definition of tcg_qemu_tb_exec
1120  * to this default (which just calls the prologue.code emitted by
1121  * tcg_target_qemu_prologue()).
1122  */
1123 #define TB_EXIT_MASK      3
1124 #define TB_EXIT_IDX0      0
1125 #define TB_EXIT_IDX1      1
1126 #define TB_EXIT_IDXMAX    1
1127 #define TB_EXIT_REQUESTED 3
1128 
1129 #ifdef CONFIG_TCG_INTERPRETER
1130 uintptr_t tcg_qemu_tb_exec(CPUArchState *env, const void *tb_ptr);
1131 #else
1132 typedef uintptr_t tcg_prologue_fn(CPUArchState *env, const void *tb_ptr);
1133 extern tcg_prologue_fn *tcg_qemu_tb_exec;
1134 #endif
1135 
1136 void tcg_register_jit(const void *buf, size_t buf_size);
1137 
1138 #if TCG_TARGET_MAYBE_vec
1139 /* Return zero if the tuple (opc, type, vece) is unsupportable;
1140    return > 0 if it is directly supportable;
1141    return < 0 if we must call tcg_expand_vec_op.  */
1142 int tcg_can_emit_vec_op(TCGOpcode, TCGType, unsigned);
1143 #else
1144 static inline int tcg_can_emit_vec_op(TCGOpcode o, TCGType t, unsigned ve)
1145 {
1146     return 0;
1147 }
1148 #endif
1149 
1150 /* Expand the tuple (opc, type, vece) on the given arguments.  */
1151 void tcg_expand_vec_op(TCGOpcode, TCGType, unsigned, TCGArg, ...);
1152 
1153 /* Replicate a constant C accoring to the log2 of the element size.  */
1154 uint64_t dup_const(unsigned vece, uint64_t c);
1155 
1156 #define dup_const(VECE, C)                                         \
1157     (__builtin_constant_p(VECE)                                    \
1158      ? (  (VECE) == MO_8  ? 0x0101010101010101ull * (uint8_t)(C)   \
1159         : (VECE) == MO_16 ? 0x0001000100010001ull * (uint16_t)(C)  \
1160         : (VECE) == MO_32 ? 0x0000000100000001ull * (uint32_t)(C)  \
1161         : (VECE) == MO_64 ? (uint64_t)(C)                          \
1162         : (qemu_build_not_reached_always(), 0))                    \
1163      : dup_const(VECE, C))
1164 
1165 #ifdef CONFIG_DEBUG_TCG
1166 void tcg_assert_listed_vecop(TCGOpcode);
1167 #else
1168 static inline void tcg_assert_listed_vecop(TCGOpcode op) { }
1169 #endif
1170 
1171 static inline const TCGOpcode *tcg_swap_vecop_list(const TCGOpcode *n)
1172 {
1173 #ifdef CONFIG_DEBUG_TCG
1174     const TCGOpcode *o = tcg_ctx->vecop_list;
1175     tcg_ctx->vecop_list = n;
1176     return o;
1177 #else
1178     return NULL;
1179 #endif
1180 }
1181 
1182 bool tcg_can_emit_vecop_list(const TCGOpcode *, TCGType, unsigned);
1183 
1184 #endif /* TCG_H */
1185