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