2 ** IR assembler (SSA IR -> machine code).
3 ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
22 #include "lj_ircall.h"
29 #include "lj_dispatch.h"
31 #include "lj_target.h"
33 /* -- Assembler state and common macros ----------------------------------- */
35 /* Assembler state. */
36 typedef struct ASMState
{
37 RegCost cost
[RID_MAX
]; /* Reference and blended allocation cost for regs. */
39 MCode
*mcp
; /* Current MCode pointer (grows down). */
40 MCode
*mclim
; /* Lower limit for MCode memory + red zone. */
42 IRIns
*ir
; /* Copy of pointer to IR instructions/constants. */
43 jit_State
*J
; /* JIT compiler state. */
45 #if LJ_TARGET_X86ORX64
46 x86ModRM mrm
; /* Fused x86 address operand. */
49 RegSet freeset
; /* Set of free registers. */
50 RegSet modset
; /* Set of registers modified inside the loop. */
51 RegSet weakset
; /* Set of weakly referenced registers. */
52 RegSet phiset
; /* Set of PHI registers. */
54 uint32_t flags
; /* Copy of JIT compiler flags. */
55 int loopinv
; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
57 int32_t evenspill
; /* Next even spill slot. */
58 int32_t oddspill
; /* Next odd spill slot (or 0). */
60 IRRef curins
; /* Reference of current instruction. */
61 IRRef stopins
; /* Stop assembly before hitting this instruction. */
62 IRRef orignins
; /* Original T->nins. */
64 IRRef snapref
; /* Current snapshot is active after this reference. */
65 IRRef snaprename
; /* Rename highwater mark for snapshot check. */
66 SnapNo snapno
; /* Current snapshot number. */
67 SnapNo loopsnapno
; /* Loop snapshot number. */
69 IRRef fuseref
; /* Fusion limit (loopref, 0 or FUSE_DISABLED). */
70 IRRef sectref
; /* Section base reference (loopref or 0). */
71 IRRef loopref
; /* Reference of LOOP instruction (or 0). */
73 BCReg topslot
; /* Number of slots for stack check (unless 0). */
74 MSize gcsteps
; /* Accumulated number of GC steps (per section). */
76 GCtrace
*T
; /* Trace to assemble. */
77 GCtrace
*parent
; /* Parent trace (or NULL). */
79 MCode
*mcbot
; /* Bottom of reserved MCode. */
80 MCode
*mctop
; /* Top of generated MCode. */
81 MCode
*mcloop
; /* Pointer to loop MCode (or NULL). */
82 MCode
*invmcp
; /* Points to invertible loop branch (or NULL). */
83 MCode
*flagmcp
; /* Pending opportunity to merge flag setting ins. */
84 MCode
*realign
; /* Realign loop if not NULL. */
87 int32_t krefk
[RID_NUM_KREF
];
89 IRRef1 phireg
[RID_MAX
]; /* PHI register references. */
90 uint16_t parentmap
[LJ_MAX_JSLOTS
]; /* Parent slot to RegSP map. */
92 uint16_t parentmaphi
[LJ_MAX_JSLOTS
]; /* Parent slot to hi RegSP map. */
96 #define IR(ref) (&as->ir[(ref)])
98 #define ASMREF_TMP1 REF_TRUE /* Temp. register. */
99 #define ASMREF_TMP2 REF_FALSE /* Temp. register. */
100 #define ASMREF_L REF_NIL /* Stores register for L. */
102 /* Check for variant to invariant references. */
103 #define iscrossref(as, ref) ((ref) < as->sectref)
105 /* Inhibit memory op fusion from variant to invariant references. */
106 #define FUSE_DISABLED (~(IRRef)0)
107 #define mayfuse(as, ref) ((ref) > as->fuseref)
108 #define neverfuse(as) (as->fuseref == FUSE_DISABLED)
109 #define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t))
110 #define opisfusableload(o) \
111 ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
112 (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
114 /* Sparse limit checks using a red zone before the actual limit. */
115 #define MCLIM_REDZONE 64
116 #define checkmclim(as) \
117 if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as)
119 static LJ_NORET LJ_NOINLINE
void asm_mclimit(ASMState
*as
)
121 lj_mcode_limiterr(as
->J
, (size_t)(as
->mctop
- as
->mcp
+ 4*MCLIM_REDZONE
));
125 #define ra_iskref(ref) ((ref) < RID_NUM_KREF)
126 #define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
127 #define ra_krefk(as, ref) (as->krefk[(ref)])
129 static LJ_AINLINE
void ra_setkref(ASMState
*as
, Reg r
, int32_t k
)
131 IRRef ref
= (IRRef
)(r
- RID_MIN_KREF
);
133 as
->cost
[r
] = REGCOST(ref
, ref
);
137 #define ra_iskref(ref) 0
138 #define ra_krefreg(ref) RID_MIN_GPR
139 #define ra_krefk(as, ref) 0
142 /* Arch-specific field offsets. */
143 static const uint8_t field_ofs
[IRFL__MAX
+1] = {
144 #define FLOFS(name, ofs) (uint8_t)(ofs),
150 /* -- Target-specific instruction emitter --------------------------------- */
152 #if LJ_TARGET_X86ORX64
153 #include "lj_emit_x86.h"
155 #include "lj_emit_arm.h"
157 #include "lj_emit_ppc.h"
159 #error "Missing instruction emitter for target CPU"
162 /* -- Register allocator debugging ---------------------------------------- */
164 /* #define LUAJIT_DEBUG_RA */
166 #ifdef LUAJIT_DEBUG_RA
171 #define RIDNAME(name) #name,
172 static const char *const ra_regname
[] = {
180 static char ra_dbg_buf
[65536];
181 static char *ra_dbg_p
;
182 static char *ra_dbg_merge
;
183 static MCode
*ra_dbg_mcp
;
185 static void ra_dstart(void)
187 ra_dbg_p
= ra_dbg_buf
;
192 static void ra_dflush(void)
194 fwrite(ra_dbg_buf
, 1, (size_t)(ra_dbg_p
-ra_dbg_buf
), stdout
);
198 static void ra_dprintf(ASMState
*as
, const char *fmt
, ...)
203 p
= ra_dbg_mcp
== as
->mcp
? ra_dbg_merge
: ra_dbg_p
;
205 p
+= sprintf(p
, "%08x \e[36m%04d ", (uintptr_t)as
->mcp
, as
->curins
-REF_BIAS
);
207 const char *e
= strchr(fmt
, '$');
208 if (e
== NULL
) break;
209 memcpy(p
, fmt
, (size_t)(e
-fmt
));
212 Reg r
= va_arg(argp
, Reg
) & RID_MASK
;
215 for (q
= ra_regname
[r
]; *q
; q
++)
216 *p
++ = *q
>= 'A' && *q
<= 'Z' ? *q
+ 0x20 : *q
;
221 } else if (e
[1] == 'f' || e
[1] == 'i') {
224 ref
= va_arg(argp
, IRRef
);
226 ref
= va_arg(argp
, IRIns
*) - as
->ir
;
228 p
+= sprintf(p
, "%04d", ref
- REF_BIAS
);
230 p
+= sprintf(p
, "K%03d", REF_BIAS
- ref
);
231 } else if (e
[1] == 's') {
232 uint32_t slot
= va_arg(argp
, uint32_t);
233 p
+= sprintf(p
, "[sp+0x%x]", sps_scale(slot
));
234 } else if (e
[1] == 'x') {
235 p
+= sprintf(p
, "%08x", va_arg(argp
, int32_t));
244 *p
++ = '\e'; *p
++ = '['; *p
++ = 'm'; *p
++ = '\n';
245 if (p
> ra_dbg_buf
+sizeof(ra_dbg_buf
)-256) {
246 fwrite(ra_dbg_buf
, 1, (size_t)(p
-ra_dbg_buf
), stdout
);
252 #define RA_DBG_START() ra_dstart()
253 #define RA_DBG_FLUSH() ra_dflush()
254 #define RA_DBG_REF() \
255 do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
256 ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
257 #define RA_DBGX(x) ra_dprintf x
260 #define RA_DBG_START() ((void)0)
261 #define RA_DBG_FLUSH() ((void)0)
262 #define RA_DBG_REF() ((void)0)
263 #define RA_DBGX(x) ((void)0)
266 /* -- Register allocator -------------------------------------------------- */
268 #define ra_free(as, r) rset_set(as->freeset, (r))
269 #define ra_modified(as, r) rset_set(as->modset, (r))
270 #define ra_weak(as, r) rset_set(as->weakset, (r))
271 #define ra_noweak(as, r) rset_clear(as->weakset, (r))
273 #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
275 /* Setup register allocator. */
276 static void ra_setup(ASMState
*as
)
279 /* Initially all regs (except the stack pointer) are free for use. */
280 as
->freeset
= RSET_INIT
;
281 as
->modset
= RSET_EMPTY
;
282 as
->weakset
= RSET_EMPTY
;
283 as
->phiset
= RSET_EMPTY
;
284 memset(as
->phireg
, 0, sizeof(as
->phireg
));
285 for (r
= RID_MIN_GPR
; r
< RID_MAX
; r
++)
286 as
->cost
[r
] = REGCOST(~0u, 0u);
289 /* Rematerialize constants. */
290 static Reg
ra_rematk(ASMState
*as
, IRRef ref
)
294 if (ra_iskref(ref
)) {
296 lua_assert(!rset_test(as
->freeset
, r
));
299 emit_loadi(as
, r
, ra_krefk(as
, ref
));
304 lua_assert(ra_hasreg(r
) && !ra_hasspill(ir
->s
));
307 ir
->r
= RID_INIT
; /* Do not keep any hint. */
308 RA_DBGX((as
, "remat $i $r", ir
, r
));
310 if (ir
->o
== IR_KNUM
) {
311 emit_loadn(as
, r
, ir_knum(ir
));
314 if (emit_canremat(REF_BASE
) && ir
->o
== IR_BASE
) {
315 ra_sethint(ir
->r
, RID_BASE
); /* Restore BASE register hint. */
316 emit_getgl(as
, r
, jit_base
);
317 } else if (emit_canremat(ASMREF_L
) && ir
->o
== IR_KPRI
) {
318 lua_assert(irt_isnil(ir
->t
)); /* REF_NIL stores ASMREF_L register. */
319 emit_getgl(as
, r
, jit_L
);
321 } else if (ir
->o
== IR_KINT64
) {
322 emit_loadu64(as
, r
, ir_kint64(ir
)->u64
);
325 lua_assert(ir
->o
== IR_KINT
|| ir
->o
== IR_KGC
||
326 ir
->o
== IR_KPTR
|| ir
->o
== IR_KKPTR
|| ir
->o
== IR_KNULL
);
327 emit_loadi(as
, r
, ir
->i
);
332 /* Force a spill. Allocate a new spill slot if needed. */
333 static int32_t ra_spill(ASMState
*as
, IRIns
*ir
)
335 int32_t slot
= ir
->s
;
336 if (!ra_hasspill(slot
)) {
337 if (irt_is64(ir
->t
)) {
338 slot
= as
->evenspill
;
340 } else if (as
->oddspill
) {
344 slot
= as
->evenspill
;
345 as
->oddspill
= slot
+1;
348 if (as
->evenspill
> 256)
349 lj_trace_err(as
->J
, LJ_TRERR_SPILLOV
);
350 ir
->s
= (uint8_t)slot
;
352 return sps_scale(slot
);
355 /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
356 static Reg
ra_releasetmp(ASMState
*as
, IRRef ref
)
360 lua_assert(ra_hasreg(r
) && !ra_hasspill(ir
->s
));
367 /* Restore a register (marked as free). Rematerialize or force a spill. */
368 static Reg
ra_restore(ASMState
*as
, IRRef ref
)
370 if (emit_canremat(ref
)) {
371 return ra_rematk(as
, ref
);
374 int32_t ofs
= ra_spill(as
, ir
); /* Force a spill slot. */
376 lua_assert(ra_hasreg(r
));
377 ra_sethint(ir
->r
, r
); /* Keep hint. */
379 if (!rset_test(as
->weakset
, r
)) { /* Only restore non-weak references. */
381 RA_DBGX((as
, "restore $i $r", ir
, r
));
382 emit_spload(as
, ir
, r
, ofs
);
388 /* Save a register to a spill slot. */
389 static void ra_save(ASMState
*as
, IRIns
*ir
, Reg r
)
391 RA_DBGX((as
, "save $i $r", ir
, r
));
392 emit_spstore(as
, ir
, r
, sps_scale(ir
->s
));
395 #define MINCOST(name) \
396 if (rset_test(RSET_ALL, RID_##name) && \
397 LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
398 cost = as->cost[RID_##name];
400 /* Evict the register with the lowest cost, forcing a restore. */
401 static Reg
ra_evict(ASMState
*as
, RegSet allow
)
404 RegCost cost
= ~(RegCost
)0;
405 lua_assert(allow
!= RSET_EMPTY
);
406 if (RID_NUM_FPR
== 0 || allow
< RID2RSET(RID_MAX_GPR
)) {
411 ref
= regcost_ref(cost
);
412 lua_assert(ra_iskref(ref
) || (ref
>= as
->T
->nk
&& ref
< as
->T
->nins
));
413 /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
414 if (!irref_isk(ref
) && (as
->weakset
& allow
)) {
416 if (!rset_test(as
->weakset
, ir
->r
))
417 ref
= regcost_ref(as
->cost
[rset_pickbot((as
->weakset
& allow
))]);
419 return ra_restore(as
, ref
);
422 /* Pick any register (marked as free). Evict on-demand. */
423 static Reg
ra_pick(ASMState
*as
, RegSet allow
)
425 RegSet pick
= as
->freeset
& allow
;
427 return ra_evict(as
, allow
);
429 return rset_picktop(pick
);
432 /* Get a scratch register (marked as free). */
433 static Reg
ra_scratch(ASMState
*as
, RegSet allow
)
435 Reg r
= ra_pick(as
, allow
);
437 RA_DBGX((as
, "scratch $r", r
));
441 /* Evict all registers from a set (if not free). */
442 static void ra_evictset(ASMState
*as
, RegSet drop
)
445 drop
&= ~as
->freeset
;
447 Reg r
= rset_pickbot(drop
);
448 ra_restore(as
, regcost_ref(as
->cost
[r
]));
454 /* Evict (rematerialize) all registers allocated to constants. */
455 static void ra_evictk(ASMState
*as
)
459 work
= ~as
->freeset
& RSET_FPR
;
461 Reg r
= rset_pickbot(work
);
462 IRRef ref
= regcost_ref(as
->cost
[r
]);
463 if (emit_canremat(ref
) && irref_isk(ref
)) {
470 work
= ~as
->freeset
& RSET_GPR
;
472 Reg r
= rset_pickbot(work
);
473 IRRef ref
= regcost_ref(as
->cost
[r
]);
474 if (emit_canremat(ref
) && irref_isk(ref
)) {
483 /* Allocate a register for a constant. */
484 static Reg
ra_allock(ASMState
*as
, int32_t k
, RegSet allow
)
486 /* First try to find a register which already holds the same constant. */
487 RegSet pick
, work
= ~as
->freeset
& RSET_GPR
;
491 r
= rset_pickbot(work
);
492 ref
= regcost_ref(as
->cost
[r
]);
493 if (ref
< ASMREF_L
&&
494 k
== (ra_iskref(ref
) ? ra_krefk(as
, ref
) : IR(ref
)->i
))
498 pick
= as
->freeset
& allow
;
500 /* Constants should preferably get unmodified registers. */
501 if ((pick
& ~as
->modset
))
503 r
= rset_pickbot(pick
); /* Reduce conflicts with inverse allocation. */
505 r
= ra_evict(as
, allow
);
507 RA_DBGX((as
, "allock $x $r", k
, r
));
508 ra_setkref(as
, r
, k
);
509 rset_clear(as
->freeset
, r
);
514 /* Allocate a specific register for a constant. */
515 static void ra_allockreg(ASMState
*as
, int32_t k
, Reg r
)
517 Reg kr
= ra_allock(as
, k
, RID2RSET(r
));
520 irdummy
.t
.irt
= IRT_INT
;
521 ra_scratch(as
, RID2RSET(r
));
522 emit_movrr(as
, &irdummy
, r
, kr
);
526 #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
529 /* Allocate a register for ref from the allowed set of registers.
530 ** Note: this function assumes the ref does NOT have a register yet!
531 ** Picks an optimal register, sets the cost and marks the register as non-free.
533 static Reg
ra_allocref(ASMState
*as
, IRRef ref
, RegSet allow
)
536 RegSet pick
= as
->freeset
& allow
;
538 lua_assert(ra_noreg(ir
->r
));
540 /* First check register hint from propagation or PHI. */
541 if (ra_hashint(ir
->r
)) {
542 r
= ra_gethint(ir
->r
);
543 if (rset_test(pick
, r
)) /* Use hint register if possible. */
545 /* Rematerialization is cheaper than missing a hint. */
546 if (rset_test(allow
, r
) && emit_canremat(regcost_ref(as
->cost
[r
]))) {
547 ra_rematk(as
, regcost_ref(as
->cost
[r
]));
550 RA_DBGX((as
, "hintmiss $f $r", ref
, r
));
552 /* Invariants should preferably get unmodified registers. */
553 if (ref
< as
->loopref
&& !irt_isphi(ir
->t
)) {
554 if ((pick
& ~as
->modset
))
556 r
= rset_pickbot(pick
); /* Reduce conflicts with inverse allocation. */
558 /* We've got plenty of regs, so get callee-save regs if possible. */
559 if (RID_NUM_GPR
> 8 && (pick
& ~RSET_SCRATCH
))
560 pick
&= ~RSET_SCRATCH
;
561 r
= rset_picktop(pick
);
564 r
= ra_evict(as
, allow
);
567 RA_DBGX((as
, "alloc $f $r", ref
, r
));
569 rset_clear(as
->freeset
, r
);
571 as
->cost
[r
] = REGCOST_REF_T(ref
, irt_t(ir
->t
));
575 /* Allocate a register on-demand. */
576 static Reg
ra_alloc1(ASMState
*as
, IRRef ref
, RegSet allow
)
579 /* Note: allow is ignored if the register is already allocated. */
580 if (ra_noreg(r
)) r
= ra_allocref(as
, ref
, allow
);
585 /* Rename register allocation and emit move. */
586 static void ra_rename(ASMState
*as
, Reg down
, Reg up
)
588 IRRef ren
, ref
= regcost_ref(as
->cost
[up
] = as
->cost
[down
]);
592 lua_assert((down
< RID_MAX_GPR
) == (up
< RID_MAX_GPR
));
593 lua_assert(!rset_test(as
->freeset
, down
) && rset_test(as
->freeset
, up
));
594 ra_free(as
, down
); /* 'down' is free ... */
595 ra_modified(as
, down
);
596 rset_clear(as
->freeset
, up
); /* ... and 'up' is now allocated. */
598 RA_DBGX((as
, "rename $f $r $r", regcost_ref(as
->cost
[up
]), down
, up
));
599 emit_movrr(as
, ir
, down
, up
); /* Backwards codegen needs inverse move. */
600 if (!ra_hasspill(IR(ref
)->s
)) { /* Add the rename to the IR. */
601 lj_ir_set(as
->J
, IRT(IR_RENAME
, IRT_NIL
), ref
, as
->snapno
);
602 ren
= tref_ref(lj_ir_emit(as
->J
));
603 as
->ir
= as
->T
->ir
; /* The IR may have been reallocated. */
604 IR(ren
)->r
= (uint8_t)down
;
605 IR(ren
)->s
= SPS_NONE
;
609 /* Pick a destination register (marked as free).
610 ** Caveat: allow is ignored if there's already a destination register.
611 ** Use ra_destreg() to get a specific register.
613 static Reg
ra_dest(ASMState
*as
, IRIns
*ir
, RegSet allow
)
616 if (ra_hasreg(dest
)) {
618 ra_modified(as
, dest
);
620 if (ra_hashint(dest
) && rset_test((as
->freeset
&allow
), ra_gethint(dest
))) {
621 dest
= ra_gethint(dest
);
622 ra_modified(as
, dest
);
623 RA_DBGX((as
, "dest $r", dest
));
625 dest
= ra_scratch(as
, allow
);
629 if (LJ_UNLIKELY(ra_hasspill(ir
->s
))) ra_save(as
, ir
, dest
);
633 /* Force a specific destination register (marked as free). */
634 static void ra_destreg(ASMState
*as
, IRIns
*ir
, Reg r
)
636 Reg dest
= ra_dest(as
, ir
, RID2RSET(r
));
638 ra_scratch(as
, RID2RSET(r
));
639 emit_movrr(as
, ir
, dest
, r
);
643 #if LJ_TARGET_X86ORX64
644 /* Propagate dest register to left reference. Emit moves as needed.
645 ** This is a required fixup step for all 2-operand machine instructions.
647 static void ra_left(ASMState
*as
, Reg dest
, IRRef lref
)
649 IRIns
*ir
= IR(lref
);
651 if (ra_noreg(left
)) {
652 if (irref_isk(lref
)) {
653 if (ir
->o
== IR_KNUM
) {
654 cTValue
*tv
= ir_knum(ir
);
655 /* FP remat needs a load except for +0. Still better than eviction. */
656 if (tvispzero(tv
) || !(as
->freeset
& RSET_FPR
)) {
657 emit_loadn(as
, dest
, tv
);
661 } else if (ir
->o
== IR_KINT64
) {
662 emit_loadu64(as
, dest
, ir_kint64(ir
)->u64
);
666 lua_assert(ir
->o
== IR_KINT
|| ir
->o
== IR_KGC
||
667 ir
->o
== IR_KPTR
|| ir
->o
== IR_KKPTR
|| ir
->o
== IR_KNULL
);
668 emit_loadi(as
, dest
, ir
->i
);
672 if (!ra_hashint(left
) && !iscrossref(as
, lref
))
673 ra_sethint(ir
->r
, dest
); /* Propagate register hint. */
674 left
= ra_allocref(as
, lref
, dest
< RID_MAX_GPR
? RSET_GPR
: RSET_FPR
);
677 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
679 /* Use register renaming if dest is the PHI reg. */
680 if (irt_isphi(ir
->t
) && as
->phireg
[dest
] == lref
) {
681 ra_modified(as
, left
);
682 ra_rename(as
, left
, dest
);
684 emit_movrr(as
, ir
, dest
, left
);
689 /* Similar to ra_left, except we override any hints. */
690 static void ra_leftov(ASMState
*as
, Reg dest
, IRRef lref
)
692 IRIns
*ir
= IR(lref
);
694 if (ra_noreg(left
)) {
695 ra_sethint(ir
->r
, dest
); /* Propagate register hint. */
696 left
= ra_allocref(as
, lref
,
697 (LJ_SOFTFP
|| dest
< RID_MAX_GPR
) ? RSET_GPR
: RSET_FPR
);
701 /* Use register renaming if dest is the PHI reg. */
702 if (irt_isphi(ir
->t
) && as
->phireg
[dest
] == lref
) {
703 ra_modified(as
, left
);
704 ra_rename(as
, left
, dest
);
706 emit_movrr(as
, ir
, dest
, left
);
712 #if !LJ_TARGET_X86ORX64
713 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
714 static void ra_destpair(ASMState
*as
, IRIns
*ir
)
716 Reg destlo
= ir
->r
, desthi
= (ir
+1)->r
;
717 /* First spill unrelated refs blocking the destination registers. */
718 if (!rset_test(as
->freeset
, RID_RETLO
) &&
719 destlo
!= RID_RETLO
&& desthi
!= RID_RETLO
)
720 ra_restore(as
, regcost_ref(as
->cost
[RID_RETLO
]));
721 if (!rset_test(as
->freeset
, RID_RETHI
) &&
722 destlo
!= RID_RETHI
&& desthi
!= RID_RETHI
)
723 ra_restore(as
, regcost_ref(as
->cost
[RID_RETHI
]));
724 /* Next free the destination registers (if any). */
725 if (ra_hasreg(destlo
)) {
727 ra_modified(as
, destlo
);
731 if (ra_hasreg(desthi
)) {
733 ra_modified(as
, desthi
);
737 /* Check for conflicts and shuffle the registers as needed. */
738 if (destlo
== RID_RETHI
) {
739 if (desthi
== RID_RETLO
) {
740 emit_movrr(as
, ir
, RID_RETHI
, RID_TMP
);
741 emit_movrr(as
, ir
, RID_RETLO
, RID_RETHI
);
742 emit_movrr(as
, ir
, RID_TMP
, RID_RETLO
);
744 emit_movrr(as
, ir
, RID_RETHI
, RID_RETLO
);
745 if (desthi
!= RID_RETHI
) emit_movrr(as
, ir
, desthi
, RID_RETHI
);
747 } else if (desthi
== RID_RETLO
) {
748 emit_movrr(as
, ir
, RID_RETLO
, RID_RETHI
);
749 if (destlo
!= RID_RETLO
) emit_movrr(as
, ir
, destlo
, RID_RETLO
);
751 if (desthi
!= RID_RETHI
) emit_movrr(as
, ir
, desthi
, RID_RETHI
);
752 if (destlo
!= RID_RETLO
) emit_movrr(as
, ir
, destlo
, RID_RETLO
);
754 /* Restore spill slots (if any). */
755 if (ra_hasspill((ir
+1)->s
)) ra_save(as
, ir
+1, RID_RETHI
);
756 if (ra_hasspill(ir
->s
)) ra_save(as
, ir
, RID_RETLO
);
760 /* -- Snapshot handling --------- ----------------------------------------- */
762 /* Can we rematerialize a KNUM instead of forcing a spill? */
763 static int asm_snap_canremat(ASMState
*as
)
766 for (r
= RID_MIN_FPR
; r
< RID_MAX_FPR
; r
++)
767 if (irref_isk(regcost_ref(as
->cost
[r
])))
772 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
773 static void asm_snap_alloc1(ASMState
*as
, IRRef ref
)
777 RegSet allow
= (!LJ_SOFTFP
&& irt_isnum(ir
->t
)) ? RSET_FPR
: RSET_GPR
;
778 /* Get a weak register if we have a free one or can rematerialize. */
779 if ((as
->freeset
& allow
) ||
780 (allow
== RSET_FPR
&& asm_snap_canremat(as
))) {
781 Reg r
= ra_allocref(as
, ref
, allow
); /* Allocate a register. */
782 if (!irt_isphi(ir
->t
))
783 ra_weak(as
, r
); /* But mark it as weakly referenced. */
785 RA_DBGX((as
, "snapreg $f $r", ref
, ir
->r
));
787 ra_spill(as
, ir
); /* Otherwise force a spill slot. */
788 RA_DBGX((as
, "snapspill $f $s", ref
, ir
->s
));
793 /* Allocate refs escaping to a snapshot. */
794 static void asm_snap_alloc(ASMState
*as
)
796 SnapShot
*snap
= &as
->T
->snap
[as
->snapno
];
797 SnapEntry
*map
= &as
->T
->snapmap
[snap
->mapofs
];
798 MSize n
, nent
= snap
->nent
;
799 for (n
= 0; n
< nent
; n
++) {
800 SnapEntry sn
= map
[n
];
801 IRRef ref
= snap_ref(sn
);
802 if (!irref_isk(ref
)) {
803 asm_snap_alloc1(as
, ref
);
804 if (LJ_SOFTFP
&& (sn
& SNAP_SOFTFPNUM
)) {
805 lua_assert(irt_type(IR(ref
+1)->t
) == IRT_SOFTFP
);
806 asm_snap_alloc1(as
, ref
+1);
812 /* All guards for a snapshot use the same exitno. This is currently the
813 ** same as the snapshot number. Since the exact origin of the exit cannot
814 ** be determined, all guards for the same snapshot must exit with the same
816 ** A renamed ref which has been used in a prior guard for the same snapshot
817 ** would cause an inconsistency. The easy way out is to force a spill slot.
819 static int asm_snap_checkrename(ASMState
*as
, IRRef ren
)
821 SnapShot
*snap
= &as
->T
->snap
[as
->snapno
];
822 SnapEntry
*map
= &as
->T
->snapmap
[snap
->mapofs
];
823 MSize n
, nent
= snap
->nent
;
824 for (n
= 0; n
< nent
; n
++) {
825 SnapEntry sn
= map
[n
];
826 IRRef ref
= snap_ref(sn
);
827 if (ref
== ren
|| (LJ_SOFTFP
&& (sn
& SNAP_SOFTFPNUM
) && ++ref
== ren
)) {
829 ra_spill(as
, ir
); /* Register renamed, so force a spill slot. */
830 RA_DBGX((as
, "snaprensp $f $s", ref
, ir
->s
));
831 return 1; /* Found. */
834 return 0; /* Not found. */
837 /* Prepare snapshot for next guard instruction. */
838 static void asm_snap_prep(ASMState
*as
)
840 if (as
->curins
< as
->snapref
) {
842 lua_assert(as
->snapno
!= 0);
844 as
->snapref
= as
->T
->snap
[as
->snapno
].ref
;
845 } while (as
->curins
< as
->snapref
);
847 as
->snaprename
= as
->T
->nins
;
849 /* Process any renames above the highwater mark. */
850 for (; as
->snaprename
< as
->T
->nins
; as
->snaprename
++) {
851 IRIns
*ir
= IR(as
->snaprename
);
852 if (asm_snap_checkrename(as
, ir
->op1
))
853 ir
->op2
= REF_BIAS
-1; /* Kill rename. */
858 /* -- Miscellaneous helpers ----------------------------------------------- */
860 /* Collect arguments from CALL* and CARG instructions. */
861 static void asm_collectargs(ASMState
*as
, IRIns
*ir
,
862 const CCallInfo
*ci
, IRRef
*args
)
864 uint32_t n
= CCI_NARGS(ci
);
865 lua_assert(n
<= CCI_NARGS_MAX
);
866 if ((ci
->flags
& CCI_L
)) { *args
++ = ASMREF_L
; n
--; }
869 lua_assert(ir
->o
== IR_CARG
);
870 args
[n
] = ir
->op2
== REF_NIL
? 0 : ir
->op2
;
872 args
[0] = ir
->op1
== REF_NIL
? 0 : ir
->op1
;
873 lua_assert(IR(ir
->op1
)->o
!= IR_CARG
);
876 /* Reconstruct CCallInfo flags for CALLX*. */
877 static uint32_t asm_callx_flags(ASMState
*as
, IRIns
*ir
)
880 if (ir
->op1
!= REF_NIL
) { /* Count number of arguments first. */
881 IRIns
*ira
= IR(ir
->op1
);
883 while (ira
->o
== IR_CARG
) { nargs
++; ira
= IR(ira
->op1
); }
886 if (IR(ir
->op2
)->o
== IR_CARG
) { /* Copy calling convention info. */
887 CTypeID id
= (CTypeID
)IR(IR(ir
->op2
)->op2
)->i
;
888 CType
*ct
= ctype_get(ctype_ctsG(J2G(as
->J
)), id
);
889 nargs
|= ((ct
->info
& CTF_VARARG
) ? CCI_VARARG
: 0);
891 nargs
|= (ctype_cconv(ct
->info
) << CCI_CC_SHIFT
);
895 return (nargs
| (ir
->t
.irt
<< CCI_OTSHIFT
));
898 /* Calculate stack adjustment. */
899 static int32_t asm_stack_adjust(ASMState
*as
)
901 if (as
->evenspill
<= SPS_FIXED
)
903 return sps_scale(sps_align(as
->evenspill
));
906 /* Must match with hash*() in lj_tab.c. */
907 static uint32_t ir_khash(IRIns
*ir
)
910 if (irt_isstr(ir
->t
)) {
911 return ir_kstr(ir
)->hash
;
912 } else if (irt_isnum(ir
->t
)) {
913 lo
= ir_knum(ir
)->u32
.lo
;
914 hi
= ir_knum(ir
)->u32
.hi
<< 1;
915 } else if (irt_ispri(ir
->t
)) {
916 lua_assert(!irt_isnil(ir
->t
));
917 return irt_type(ir
->t
)-IRT_FALSE
;
919 lua_assert(irt_isgcv(ir
->t
));
920 lo
= u32ptr(ir_kgc(ir
));
923 return hashrot(lo
, hi
);
926 /* -- Allocations --------------------------------------------------------- */
928 static void asm_gencall(ASMState
*as
, const CCallInfo
*ci
, IRRef
*args
);
929 static void asm_setupresult(ASMState
*as
, IRIns
*ir
, const CCallInfo
*ci
);
931 static void asm_snew(ASMState
*as
, IRIns
*ir
)
933 const CCallInfo
*ci
= &lj_ir_callinfo
[IRCALL_lj_str_new
];
935 args
[0] = ASMREF_L
; /* lua_State *L */
936 args
[1] = ir
->op1
; /* const char *str */
937 args
[2] = ir
->op2
; /* size_t len */
939 asm_setupresult(as
, ir
, ci
); /* GCstr * */
940 asm_gencall(as
, ci
, args
);
943 static void asm_tnew(ASMState
*as
, IRIns
*ir
)
945 const CCallInfo
*ci
= &lj_ir_callinfo
[IRCALL_lj_tab_new1
];
947 args
[0] = ASMREF_L
; /* lua_State *L */
948 args
[1] = ASMREF_TMP1
; /* uint32_t ahsize */
950 asm_setupresult(as
, ir
, ci
); /* GCtab * */
951 asm_gencall(as
, ci
, args
);
952 ra_allockreg(as
, ir
->op1
| (ir
->op2
<< 24), ra_releasetmp(as
, ASMREF_TMP1
));
955 static void asm_tdup(ASMState
*as
, IRIns
*ir
)
957 const CCallInfo
*ci
= &lj_ir_callinfo
[IRCALL_lj_tab_dup
];
959 args
[0] = ASMREF_L
; /* lua_State *L */
960 args
[1] = ir
->op1
; /* const GCtab *kt */
962 asm_setupresult(as
, ir
, ci
); /* GCtab * */
963 asm_gencall(as
, ci
, args
);
966 /* -- PHI and loop handling ----------------------------------------------- */
968 /* Break a PHI cycle by renaming to a free register (evict if needed). */
969 static void asm_phi_break(ASMState
*as
, RegSet blocked
, RegSet blockedby
,
972 RegSet candidates
= blocked
& allow
;
973 if (candidates
) { /* If this register file has candidates. */
974 /* Note: the set for ra_pick cannot be empty, since each register file
975 ** has some registers never allocated to PHIs.
977 Reg down
, up
= ra_pick(as
, ~blocked
& allow
); /* Get a free register. */
978 if (candidates
& ~blockedby
) /* Optimize shifts, else it's a cycle. */
979 candidates
= candidates
& ~blockedby
;
980 down
= rset_picktop(candidates
); /* Pick candidate PHI register. */
981 ra_rename(as
, down
, up
); /* And rename it to the free register. */
985 /* PHI register shuffling.
987 ** The allocator tries hard to preserve PHI register assignments across
988 ** the loop body. Most of the time this loop does nothing, since there
989 ** are no register mismatches.
991 ** If a register mismatch is detected and ...
992 ** - the register is currently free: rename it.
993 ** - the register is blocked by an invariant: restore/remat and rename it.
994 ** - Otherwise the register is used by another PHI, so mark it as blocked.
996 ** The renames are order-sensitive, so just retry the loop if a register
997 ** is marked as blocked, but has been freed in the meantime. A cycle is
998 ** detected if all of the blocked registers are allocated. To break the
999 ** cycle rename one of them to a free register and retry.
1001 ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1003 static void asm_phi_shuffle(ASMState
*as
)
1007 /* Find and resolve PHI register mismatches. */
1009 RegSet blocked
= RSET_EMPTY
;
1010 RegSet blockedby
= RSET_EMPTY
;
1011 RegSet phiset
= as
->phiset
;
1012 while (phiset
) { /* Check all left PHI operand registers. */
1013 Reg r
= rset_pickbot(phiset
);
1014 IRIns
*irl
= IR(as
->phireg
[r
]);
1016 if (r
!= left
) { /* Mismatch? */
1017 if (!rset_test(as
->freeset
, r
)) { /* PHI register blocked? */
1018 IRRef ref
= regcost_ref(as
->cost
[r
]);
1019 /* Blocked by other PHI (w/reg)? */
1020 if (!ra_iskref(ref
) && irt_ismarked(IR(ref
)->t
)) {
1021 rset_set(blocked
, r
);
1022 if (ra_hasreg(left
))
1023 rset_set(blockedby
, left
);
1025 } else { /* Otherwise grab register from invariant. */
1026 ra_restore(as
, ref
);
1030 if (ra_hasreg(left
)) {
1031 ra_rename(as
, left
, r
);
1035 rset_clear(phiset
, r
);
1037 if (!blocked
) break; /* Finished. */
1038 if (!(as
->freeset
& blocked
)) { /* Break cycles if none are free. */
1039 asm_phi_break(as
, blocked
, blockedby
, RSET_GPR
);
1040 if (!LJ_SOFTFP
) asm_phi_break(as
, blocked
, blockedby
, RSET_FPR
);
1042 } /* Else retry some more renames. */
1045 /* Restore/remat invariants whose registers are modified inside the loop. */
1046 work
= as
->modset
& ~(as
->freeset
| as
->phiset
);
1048 Reg r
= rset_pickbot(work
);
1049 ra_restore(as
, regcost_ref(as
->cost
[r
]));
1050 rset_clear(work
, r
);
1054 /* Allocate and save all unsaved PHI regs and clear marks. */
1057 Reg r
= rset_picktop(work
);
1058 IRRef lref
= as
->phireg
[r
];
1059 IRIns
*ir
= IR(lref
);
1060 if (ra_hasspill(ir
->s
)) { /* Left PHI gained a spill slot? */
1061 irt_clearmark(ir
->t
); /* Handled here, so clear marker now. */
1062 ra_alloc1(as
, lref
, RID2RSET(r
));
1063 ra_save(as
, ir
, r
); /* Save to spill slot inside the loop. */
1066 rset_clear(work
, r
);
1070 /* Emit renames for left PHIs which are only spilled outside the loop. */
1071 static void asm_phi_fixup(ASMState
*as
)
1073 RegSet work
= as
->phiset
;
1075 Reg r
= rset_picktop(work
);
1076 IRRef lref
= as
->phireg
[r
];
1077 IRIns
*ir
= IR(lref
);
1078 /* Left PHI gained a spill slot before the loop? */
1079 if (irt_ismarked(ir
->t
) && ra_hasspill(ir
->s
)) {
1081 lj_ir_set(as
->J
, IRT(IR_RENAME
, IRT_NIL
), lref
, as
->loopsnapno
);
1082 ren
= tref_ref(lj_ir_emit(as
->J
));
1083 as
->ir
= as
->T
->ir
; /* The IR may have been reallocated. */
1084 IR(ren
)->r
= (uint8_t)r
;
1085 IR(ren
)->s
= SPS_NONE
;
1087 irt_clearmark(ir
->t
); /* Always clear marker. */
1088 rset_clear(work
, r
);
1092 /* Setup right PHI reference. */
1093 static void asm_phi(ASMState
*as
, IRIns
*ir
)
1095 RegSet allow
= ((!LJ_SOFTFP
&& irt_isfp(ir
->t
)) ? RSET_FPR
: RSET_GPR
) &
1097 RegSet afree
= (as
->freeset
& allow
);
1098 IRIns
*irl
= IR(ir
->op1
);
1099 IRIns
*irr
= IR(ir
->op2
);
1100 /* Spill slot shuffling is not implemented yet (but rarely needed). */
1101 if (ra_hasspill(irl
->s
) || ra_hasspill(irr
->s
))
1102 lj_trace_err(as
->J
, LJ_TRERR_NYIPHI
);
1103 /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
1104 if ((afree
& (afree
-1))) { /* Two or more free registers? */
1106 if (ra_noreg(irr
->r
)) { /* Get a register for the right PHI. */
1107 r
= ra_allocref(as
, ir
->op2
, allow
);
1108 } else { /* Duplicate right PHI, need a copy (rare). */
1109 r
= ra_scratch(as
, allow
);
1110 emit_movrr(as
, irr
, r
, irr
->r
);
1113 rset_set(as
->phiset
, r
);
1114 as
->phireg
[r
] = (IRRef1
)ir
->op1
;
1115 irt_setmark(irl
->t
); /* Marks left PHIs _with_ register. */
1116 if (ra_noreg(irl
->r
))
1117 ra_sethint(irl
->r
, r
); /* Set register hint for left PHI. */
1118 } else { /* Otherwise allocate a spill slot. */
1119 /* This is overly restrictive, but it triggers only on synthetic code. */
1120 if (ra_hasreg(irl
->r
) || ra_hasreg(irr
->r
))
1121 lj_trace_err(as
->J
, LJ_TRERR_NYIPHI
);
1123 irl
->s
= irr
->s
= ir
->s
; /* Sync left/right PHI spill slots. */
1127 static void asm_gc_check(ASMState
*as
);
1128 static void asm_loop_fixup(ASMState
*as
);
1130 /* Middle part of a loop. */
1131 static void asm_loop(ASMState
*as
)
1133 /* LOOP is a guard, so the snapno is up to date. */
1134 as
->loopsnapno
= as
->snapno
;
1137 /* LOOP marks the transition from the variant to the invariant part. */
1138 as
->flagmcp
= as
->invmcp
= NULL
;
1140 if (!neverfuse(as
)) as
->fuseref
= 0;
1141 asm_phi_shuffle(as
);
1143 as
->mcloop
= as
->mcp
;
1144 RA_DBGX((as
, "===== LOOP ====="));
1145 if (!as
->realign
) RA_DBG_FLUSH();
1148 /* -- Target-specific assembler ------------------------------------------- */
1150 #if LJ_TARGET_X86ORX64
1151 #include "lj_asm_x86.h"
1153 #include "lj_asm_arm.h"
1155 #include "lj_asm_ppc.h"
1157 #error "Missing assembler for target CPU"
1160 /* -- Head of trace ------------------------------------------------------- */
1162 /* Head of a root trace. */
1163 static void asm_head_root(ASMState
*as
)
1166 asm_head_root_base(as
);
1167 emit_setvmstate(as
, (int32_t)as
->T
->traceno
);
1168 spadj
= asm_stack_adjust(as
);
1169 as
->T
->spadjust
= (uint16_t)spadj
;
1170 emit_spsub(as
, spadj
);
1171 /* Root traces assume a checked stack for the starting proto. */
1172 as
->T
->topslot
= gcref(as
->T
->startpt
)->pt
.framesize
;
1175 /* Get RegSP for parent slot. */
1176 static LJ_AINLINE RegSP
asm_head_parentrs(ASMState
*as
, IRIns
*ir
)
1179 if (ir
->o
== IR_HIOP
) return as
->parentmaphi
[(ir
-1)->op1
];
1181 return as
->parentmap
[ir
->op1
];
1184 /* Head of a side trace.
1186 ** The current simplistic algorithm requires that all slots inherited
1187 ** from the parent are live in a register between pass 2 and pass 3. This
1188 ** avoids the complexity of stack slot shuffling. But of course this may
1189 ** overflow the register set in some cases and cause the dreaded error:
1190 ** "NYI: register coalescing too complex". A refined algorithm is needed.
1192 static void asm_head_side(ASMState
*as
)
1194 IRRef1 sloadins
[RID_MAX
];
1195 RegSet allow
= RSET_ALL
; /* Inverse of all coalesced registers. */
1196 RegSet live
= RSET_EMPTY
; /* Live parent registers. */
1197 IRIns
*irp
= &as
->parent
->ir
[REF_BASE
]; /* Parent base. */
1198 int32_t spadj
, spdelta
;
1203 allow
= asm_head_side_base(as
, irp
, allow
);
1205 /* Scan all parent SLOADs and collect register dependencies. */
1206 for (i
= as
->stopins
; i
> REF_BASE
; i
--) {
1209 lua_assert((ir
->o
== IR_SLOAD
&& (ir
->op2
& IRSLOAD_PARENT
)) ||
1210 (LJ_SOFTFP
&& ir
->o
== IR_HIOP
));
1211 rs
= asm_head_parentrs(as
, ir
);
1212 if (ra_hasreg(ir
->r
)) {
1213 rset_clear(allow
, ir
->r
);
1214 if (ra_hasspill(ir
->s
)) {
1215 ra_save(as
, ir
, ir
->r
);
1218 } else if (ra_hasspill(ir
->s
)) {
1222 if (ir
->r
== rs
) { /* Coalesce matching registers right now. */
1224 } else if (ra_hasspill(regsp_spill(rs
))) {
1225 if (ra_hasreg(ir
->r
))
1227 } else if (ra_used(ir
)) {
1228 sloadins
[rs
] = (IRRef1
)i
;
1229 rset_set(live
, rs
); /* Block live parent register. */
1233 /* Calculate stack frame adjustment. */
1234 spadj
= asm_stack_adjust(as
);
1235 spdelta
= spadj
- (int32_t)as
->parent
->spadjust
;
1236 if (spdelta
< 0) { /* Don't shrink the stack frame. */
1237 spadj
= (int32_t)as
->parent
->spadjust
;
1240 as
->T
->spadjust
= (uint16_t)spadj
;
1242 /* Reload spilled target registers. */
1244 for (i
= as
->stopins
; i
> REF_BASE
; i
--) {
1246 if (irt_ismarked(ir
->t
)) {
1250 irt_clearmark(ir
->t
);
1251 rs
= asm_head_parentrs(as
, ir
);
1252 if (!ra_hasspill(regsp_spill(rs
)))
1253 ra_sethint(ir
->r
, rs
); /* Hint may be gone, set it again. */
1254 else if (sps_scale(regsp_spill(rs
))+spdelta
== sps_scale(ir
->s
))
1255 continue; /* Same spill slot, do nothing. */
1256 mask
= ((!LJ_SOFTFP
&& irt_isnum(ir
->t
)) ? RSET_FPR
: RSET_GPR
) & allow
;
1257 if (mask
== RSET_EMPTY
)
1258 lj_trace_err(as
->J
, LJ_TRERR_NYICOAL
);
1259 r
= ra_allocref(as
, i
, mask
);
1261 rset_clear(allow
, r
);
1262 if (r
== rs
) { /* Coalesce matching registers right now. */
1264 rset_clear(live
, r
);
1265 } else if (ra_hasspill(regsp_spill(rs
))) {
1273 /* Store trace number and adjust stack frame relative to the parent. */
1274 emit_setvmstate(as
, (int32_t)as
->T
->traceno
);
1275 emit_spsub(as
, spdelta
);
1277 #if !LJ_TARGET_X86ORX64
1278 /* Restore BASE register from parent spill slot. */
1279 if (ra_hasspill(irp
->s
))
1280 emit_spload(as
, IR(REF_BASE
), IR(REF_BASE
)->r
, sps_scale(irp
->s
));
1283 /* Restore target registers from parent spill slots. */
1285 RegSet work
= ~as
->freeset
& RSET_ALL
;
1287 Reg r
= rset_pickbot(work
);
1288 IRIns
*ir
= IR(regcost_ref(as
->cost
[r
]));
1289 RegSP rs
= asm_head_parentrs(as
, ir
);
1290 rset_clear(work
, r
);
1291 if (ra_hasspill(regsp_spill(rs
))) {
1292 int32_t ofs
= sps_scale(regsp_spill(rs
));
1294 emit_spload(as
, ir
, r
, ofs
);
1300 /* Shuffle registers to match up target regs with parent regs. */
1304 /* Repeatedly coalesce free live registers by moving to their target. */
1305 while ((work
= as
->freeset
& live
) != RSET_EMPTY
) {
1306 Reg rp
= rset_pickbot(work
);
1307 IRIns
*ir
= IR(sloadins
[rp
]);
1308 rset_clear(live
, rp
);
1309 rset_clear(allow
, rp
);
1311 emit_movrr(as
, ir
, ir
->r
, rp
);
1315 /* We're done if no live registers remain. */
1316 if (live
== RSET_EMPTY
)
1319 /* Break cycles by renaming one target to a temp. register. */
1320 if (live
& RSET_GPR
) {
1321 RegSet tmpset
= as
->freeset
& ~live
& allow
& RSET_GPR
;
1322 if (tmpset
== RSET_EMPTY
)
1323 lj_trace_err(as
->J
, LJ_TRERR_NYICOAL
);
1324 ra_rename(as
, rset_pickbot(live
& RSET_GPR
), rset_pickbot(tmpset
));
1326 if (!LJ_SOFTFP
&& (live
& RSET_FPR
)) {
1327 RegSet tmpset
= as
->freeset
& ~live
& allow
& RSET_FPR
;
1328 if (tmpset
== RSET_EMPTY
)
1329 lj_trace_err(as
->J
, LJ_TRERR_NYICOAL
);
1330 ra_rename(as
, rset_pickbot(live
& RSET_FPR
), rset_pickbot(tmpset
));
1333 /* Continue with coalescing to fix up the broken cycle(s). */
1336 /* Inherit top stack slot already checked by parent trace. */
1337 as
->T
->topslot
= as
->parent
->topslot
;
1338 if (as
->topslot
> as
->T
->topslot
) { /* Need to check for higher slot? */
1339 #ifdef EXITSTATE_CHECKEXIT
1340 /* Highest exit + 1 indicates stack check. */
1341 ExitNo exitno
= as
->T
->nsnap
;
1343 /* Reuse the parent exit in the context of the parent trace. */
1344 ExitNo exitno
= as
->J
->exitno
;
1346 as
->T
->topslot
= (uint8_t)as
->topslot
; /* Remember for child traces. */
1347 asm_stack_check(as
, as
->topslot
, irp
, allow
& RSET_GPR
, exitno
);
1351 /* -- Tail of trace ------------------------------------------------------- */
1353 /* Get base slot for a snapshot. */
1354 static BCReg
asm_baseslot(ASMState
*as
, SnapShot
*snap
, int *gotframe
)
1356 SnapEntry
*map
= &as
->T
->snapmap
[snap
->mapofs
];
1358 for (n
= snap
->nent
; n
> 0; n
--) {
1359 SnapEntry sn
= map
[n
-1];
1360 if ((sn
& SNAP_FRAME
)) {
1362 return snap_slot(sn
);
1368 /* Link to another trace. */
1369 static void asm_tail_link(ASMState
*as
)
1371 SnapNo snapno
= as
->T
->nsnap
-1; /* Last snapshot. */
1372 SnapShot
*snap
= &as
->T
->snap
[snapno
];
1374 BCReg baseslot
= asm_baseslot(as
, snap
, &gotframe
);
1376 as
->topslot
= snap
->topslot
;
1378 ra_allocref(as
, REF_BASE
, RID2RSET(RID_BASE
));
1380 if (as
->T
->link
== 0) {
1381 /* Setup fixed registers for exit to interpreter. */
1382 const BCIns
*pc
= snap_pc(as
->T
->snapmap
[snap
->mapofs
+ snap
->nent
]);
1384 if (bc_op(*pc
) == BC_JLOOP
) { /* NYI: find a better way to do this. */
1385 BCIns
*retpc
= &traceref(as
->J
, bc_d(*pc
))->startins
;
1386 if (bc_isret(bc_op(*retpc
)))
1389 ra_allockreg(as
, i32ptr(J2GG(as
->J
)->dispatch
), RID_DISPATCH
);
1390 ra_allockreg(as
, i32ptr(pc
), RID_LPC
);
1391 mres
= (int32_t)(snap
->nslots
- baseslot
);
1392 switch (bc_op(*pc
)) {
1393 case BC_CALLM
: case BC_CALLMT
:
1394 mres
-= (int32_t)(1 + bc_a(*pc
) + bc_c(*pc
)); break;
1395 case BC_RETM
: mres
-= (int32_t)(bc_a(*pc
) + bc_d(*pc
)); break;
1396 case BC_TSETM
: mres
-= (int32_t)bc_a(*pc
); break;
1397 default: if (bc_op(*pc
) < BC_FUNCF
) mres
= 0; break;
1399 ra_allockreg(as
, mres
, RID_RET
); /* Return MULTRES or 0. */
1400 } else if (baseslot
) {
1401 /* Save modified BASE for linking to trace with higher start frame. */
1402 emit_setgl(as
, RID_BASE
, jit_base
);
1404 emit_addptr(as
, RID_BASE
, 8*(int32_t)baseslot
);
1406 /* Sync the interpreter state with the on-trace state. */
1407 asm_stack_restore(as
, snap
);
1409 /* Root traces that add frames need to check the stack at the end. */
1410 if (!as
->parent
&& gotframe
)
1411 asm_stack_check(as
, as
->topslot
, NULL
, as
->freeset
& RSET_GPR
, snapno
);
1414 /* -- Trace setup --------------------------------------------------------- */
1416 /* Clear reg/sp for all instructions and add register hints. */
1417 static void asm_setup_regsp(ASMState
*as
)
1423 uint32_t rload
= 0xa6402a64;
1428 /* Clear reg/sp for constants. */
1429 for (i
= T
->nk
; i
< REF_BIAS
; i
++)
1430 IR(i
)->prev
= REGSP_INIT
;
1432 /* REF_BASE is used for implicit references to the BASE register. */
1433 IR(REF_BASE
)->prev
= REGSP_HINT(RID_BASE
);
1436 if (IR(nins
-1)->o
== IR_RENAME
) {
1437 do { nins
--; } while (IR(nins
-1)->o
== IR_RENAME
);
1438 T
->nins
= nins
; /* Remove any renames left over from ASM restart. */
1440 as
->snaprename
= nins
;
1442 as
->snapno
= T
->nsnap
;
1444 as
->stopins
= REF_BASE
;
1445 as
->orignins
= nins
;
1449 as
->evenspill
= SPS_FIRST
;
1450 for (i
= REF_FIRST
; i
< nins
; i
++) {
1456 /* Set hints for slot loads from a parent trace. */
1458 if ((ir
->op2
& IRSLOAD_PARENT
)) {
1459 RegSP rs
= as
->parentmap
[ir
->op1
];
1460 lua_assert(regsp_used(rs
));
1462 if (!ra_hasspill(regsp_spill(rs
)) && ra_hasreg(regsp_reg(rs
))) {
1463 ir
->prev
= (uint16_t)REGSP_HINT(regsp_reg(rs
));
1468 if ((ir
->op2
& IRSLOAD_TYPECHECK
) || (ir
+1)->o
== IR_HIOP
) {
1469 ir
->prev
= (uint16_t)REGSP_HINT((rload
& 15));
1470 rload
= lj_ror(rload
, 4);
1476 case IR_ALOAD
: case IR_HLOAD
: case IR_ULOAD
: case IR_VLOAD
:
1477 ir
->prev
= (uint16_t)REGSP_HINT((rload
& 15));
1478 rload
= lj_ror(rload
, 4);
1483 ci
.flags
= asm_callx_flags(as
, ir
);
1484 ir
->prev
= asm_setup_call_slots(as
, ir
, &ci
);
1486 as
->modset
|= RSET_SCRATCH
;
1489 case IR_CALLN
: case IR_CALLL
: case IR_CALLS
: {
1490 const CCallInfo
*ci
= &lj_ir_callinfo
[ir
->op2
];
1491 ir
->prev
= asm_setup_call_slots(as
, ir
, ci
);
1493 as
->modset
|= (ci
->flags
& CCI_NOFPRCLOBBER
) ?
1494 (RSET_SCRATCH
& ~RSET_FPR
) : RSET_SCRATCH
;
1497 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1499 switch ((ir
-1)->o
) {
1502 if (((ir
-1)->op2
& IRSLOAD_PARENT
)) {
1503 RegSP rs
= as
->parentmaphi
[(ir
-1)->op1
];
1504 lua_assert(regsp_used(rs
));
1506 if (!ra_hasspill(regsp_spill(rs
)) && ra_hasreg(regsp_reg(rs
))) {
1507 ir
->prev
= (uint16_t)REGSP_HINT(regsp_reg(rs
));
1513 case IR_ALOAD
: case IR_HLOAD
: case IR_ULOAD
: case IR_VLOAD
:
1514 if (ra_hashint((ir
-1)->r
)) {
1515 ir
->prev
= (ir
-1)->prev
+ 1;
1523 if (irt_isfp((ir
-1)->t
)) {
1524 ir
->prev
= REGSP_HINT(RID_FPRET
);
1529 case IR_CALLN
: case IR_CALLXS
:
1531 case IR_MIN
: case IR_MAX
:
1534 (ir
-1)->prev
= REGSP_HINT(RID_RETLO
);
1536 ir
->prev
= REGSP_HINT(RID_RETHI
);
1544 case IR_MIN
: case IR_MAX
:
1545 if ((ir
+1)->o
!= IR_HIOP
) break;
1548 /* C calls evict all scratch regs and return results in RID_RET. */
1549 case IR_SNEW
: case IR_XSNEW
: case IR_NEWREF
:
1550 if (REGARG_NUMGPR
< 3 && as
->evenspill
< 3)
1551 as
->evenspill
= 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1552 case IR_TNEW
: case IR_TDUP
: case IR_CNEW
: case IR_CNEWI
: case IR_TOSTR
:
1553 ir
->prev
= REGSP_HINT(RID_RET
);
1555 as
->modset
= RSET_SCRATCH
;
1557 case IR_STRTO
: case IR_OBAR
:
1559 as
->modset
= RSET_SCRATCH
;
1561 #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1562 case IR_ATAN2
: case IR_LDEXP
:
1565 if (!LJ_SOFTFP
&& irt_isnum(ir
->t
)) {
1566 #if LJ_TARGET_X86ORX64
1567 ir
->prev
= REGSP_HINT(RID_XMM0
);
1569 as
->modset
|= RSET_RANGE(RID_XMM0
, RID_XMM1
+1)|RID2RSET(RID_EAX
);
1571 ir
->prev
= REGSP_HINT(RID_FPRET
);
1573 as
->modset
|= RSET_SCRATCH
;
1577 /* fallthrough for integer POW */
1578 case IR_DIV
: case IR_MOD
:
1579 if (!irt_isnum(ir
->t
)) {
1580 ir
->prev
= REGSP_HINT(RID_RET
);
1582 as
->modset
|= (RSET_SCRATCH
& RSET_GPR
);
1587 #if LJ_TARGET_X86ORX64
1588 if (ir
->op2
== IRFPM_EXP2
) { /* May be joined to lj_vm_pow_sse. */
1589 ir
->prev
= REGSP_HINT(RID_XMM0
);
1591 if (as
->evenspill
< 4) /* Leave room for 16 byte scratch area. */
1595 as
->modset
|= RSET_RANGE(RID_XMM0
, RID_XMM2
+1)|RID2RSET(RID_EAX
);
1597 } else if (ir
->op2
<= IRFPM_TRUNC
&& !(as
->flags
& JIT_F_SSE4_1
)) {
1598 ir
->prev
= REGSP_HINT(RID_XMM0
);
1600 as
->modset
|= RSET_RANGE(RID_XMM0
, RID_XMM3
+1)|RID2RSET(RID_EAX
);
1605 ir
->prev
= REGSP_HINT(RID_FPRET
);
1607 as
->modset
|= RSET_SCRATCH
;
1610 #if LJ_TARGET_X86ORX64
1611 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1612 case IR_BSHL
: case IR_BSHR
: case IR_BSAR
: case IR_BROL
: case IR_BROR
:
1613 if (!irref_isk(ir
->op2
) && !ra_hashint(IR(ir
->op2
)->r
)) {
1614 IR(ir
->op2
)->r
= REGSP_HINT(RID_ECX
);
1616 rset_set(as
->modset
, RID_ECX
);
1620 /* Do not propagate hints across type conversions. */
1624 if (irt_isfp(ir
->t
) || (ir
->op2
& IRCONV_SRCMASK
) == IRT_NUM
||
1625 (ir
->op2
& IRCONV_SRCMASK
) == IRT_FLOAT
)
1629 /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
1630 if (irref_isk(ir
->op2
) && !irref_isk(ir
->op1
)) {
1631 ir
->prev
= IR(ir
->op1
)->prev
;
1636 ir
->prev
= REGSP_INIT
;
1638 if ((as
->evenspill
& 1))
1639 as
->oddspill
= as
->evenspill
++;
1644 /* -- Assembler core ------------------------------------------------------ */
1646 /* Assemble a trace. */
1647 void lj_asm_trace(jit_State
*J
, GCtrace
*T
)
1650 ASMState
*as
= &as_
;
1653 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1654 J
->cur
.nins
= lj_ir_nextins(J
);
1655 J
->cur
.ir
[J
->cur
.nins
].o
= IR_NOP
;
1657 /* Setup initial state. Copy some fields to reduce indirections. */
1661 as
->flags
= J
->flags
;
1662 as
->loopref
= J
->loopref
;
1666 as
->parent
= traceref(J
, J
->parent
);
1667 lj_snap_regspmap(as
->parentmap
, as
->parent
, J
->exitno
, 0);
1669 lj_snap_regspmap(as
->parentmaphi
, as
->parent
, J
->exitno
, 1);
1674 /* Reserve MCode memory. */
1675 as
->mctop
= origtop
= lj_mcode_reserve(J
, &as
->mcbot
);
1676 as
->mcp
= as
->mctop
;
1677 as
->mclim
= as
->mcbot
+ MCLIM_REDZONE
;
1678 asm_setup_target(as
);
1681 as
->mcp
= as
->mctop
;
1682 as
->curins
= T
->nins
;
1684 RA_DBGX((as
, "===== STOP ====="));
1686 /* General trace setup. Emit tail of trace. */
1692 as
->sectref
= as
->loopref
;
1693 as
->fuseref
= (as
->flags
& JIT_F_OPT_FUSE
) ? as
->loopref
: FUSE_DISABLED
;
1694 asm_setup_regsp(as
);
1698 /* Assemble a trace in linear backwards order. */
1699 for (as
->curins
--; as
->curins
> as
->stopins
; as
->curins
--) {
1700 IRIns
*ir
= IR(as
->curins
);
1701 lua_assert(!(LJ_32
&& irt_isint64(ir
->t
))); /* Handled by SPLIT. */
1702 if (!ra_used(ir
) && !ir_sideeff(ir
) && (as
->flags
& JIT_F_OPT_DCE
))
1703 continue; /* Dead-code elimination can be soooo easy. */
1704 if (irt_isguard(ir
->t
))
1710 } while (as
->realign
); /* Retry in case the MCode needs to be realigned. */
1712 /* Emit head of trace. */
1716 as
->curins
= as
->T
->snap
[0].ref
;
1717 asm_snap_prep(as
); /* The GC check is a guard. */
1727 RA_DBGX((as
, "===== START ===="));
1729 if (as
->freeset
!= RSET_ALL
)
1730 lj_trace_err(as
->J
, LJ_TRERR_BADRA
); /* Ouch! Should never happen. */
1732 /* Set trace entry point before fixing up tail to allow link to self. */
1734 T
->mcloop
= as
->mcloop
? (MSize
)((char *)as
->mcloop
- (char *)as
->mcp
) : 0;
1736 asm_tail_fixup(as
, T
->link
); /* Note: this may change as->mctop! */
1737 T
->szmcode
= (MSize
)((char *)as
->mctop
- (char *)as
->mcp
);
1738 lj_mcode_sync(T
->mcode
, origtop
);