aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/libraries/luajit-2.0/src/lj_asm.c
diff options
context:
space:
mode:
Diffstat (limited to 'libraries/luajit-2.0/src/lj_asm.c')
-rw-r--r--libraries/luajit-2.0/src/lj_asm.c1741
1 files changed, 1741 insertions, 0 deletions
diff --git a/libraries/luajit-2.0/src/lj_asm.c b/libraries/luajit-2.0/src/lj_asm.c
new file mode 100644
index 0000000..1103e99
--- /dev/null
+++ b/libraries/luajit-2.0/src/lj_asm.c
@@ -0,0 +1,1741 @@
1/*
2** IR assembler (SSA IR -> machine code).
3** Copyright (C) 2005-2011 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#define lj_asm_c
7#define LUA_CORE
8
9#include "lj_obj.h"
10
11#if LJ_HASJIT
12
13#include "lj_gc.h"
14#include "lj_str.h"
15#include "lj_tab.h"
16#include "lj_frame.h"
17#if LJ_HASFFI
18#include "lj_ctype.h"
19#endif
20#include "lj_ir.h"
21#include "lj_jit.h"
22#include "lj_ircall.h"
23#include "lj_iropt.h"
24#include "lj_mcode.h"
25#include "lj_iropt.h"
26#include "lj_trace.h"
27#include "lj_snap.h"
28#include "lj_asm.h"
29#include "lj_dispatch.h"
30#include "lj_vm.h"
31#include "lj_target.h"
32
33/* -- Assembler state and common macros ----------------------------------- */
34
35/* Assembler state. */
36typedef struct ASMState {
37 RegCost cost[RID_MAX]; /* Reference and blended allocation cost for regs. */
38
39 MCode *mcp; /* Current MCode pointer (grows down). */
40 MCode *mclim; /* Lower limit for MCode memory + red zone. */
41
42 IRIns *ir; /* Copy of pointer to IR instructions/constants. */
43 jit_State *J; /* JIT compiler state. */
44
45#if LJ_TARGET_X86ORX64
46 x86ModRM mrm; /* Fused x86 address operand. */
47#endif
48
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. */
53
54 uint32_t flags; /* Copy of JIT compiler flags. */
55 int loopinv; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
56
57 int32_t evenspill; /* Next even spill slot. */
58 int32_t oddspill; /* Next odd spill slot (or 0). */
59
60 IRRef curins; /* Reference of current instruction. */
61 IRRef stopins; /* Stop assembly before hitting this instruction. */
62 IRRef orignins; /* Original T->nins. */
63
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. */
68
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). */
72
73 BCReg topslot; /* Number of slots for stack check (unless 0). */
74 MSize gcsteps; /* Accumulated number of GC steps (per section). */
75
76 GCtrace *T; /* Trace to assemble. */
77 GCtrace *parent; /* Parent trace (or NULL). */
78
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. */
85
86#ifdef RID_NUM_KREF
87 int32_t krefk[RID_NUM_KREF];
88#endif
89 IRRef1 phireg[RID_MAX]; /* PHI register references. */
90 uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent slot to RegSP map. */
91#if LJ_SOFTFP
92 uint16_t parentmaphi[LJ_MAX_JSLOTS]; /* Parent slot to hi RegSP map. */
93#endif
94} ASMState;
95
96#define IR(ref) (&as->ir[(ref)])
97
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. */
101
102/* Check for variant to invariant references. */
103#define iscrossref(as, ref) ((ref) < as->sectref)
104
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)
113
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)
118
119static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
120{
121 lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
122}
123
124#ifdef RID_NUM_KREF
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)])
128
129static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k)
130{
131 IRRef ref = (IRRef)(r - RID_MIN_KREF);
132 as->krefk[ref] = k;
133 as->cost[r] = REGCOST(ref, ref);
134}
135
136#else
137#define ra_iskref(ref) 0
138#define ra_krefreg(ref) RID_MIN_GPR
139#define ra_krefk(as, ref) 0
140#endif
141
142/* Arch-specific field offsets. */
143static const uint8_t field_ofs[IRFL__MAX+1] = {
144#define FLOFS(name, ofs) (uint8_t)(ofs),
145IRFLDEF(FLOFS)
146#undef FLOFS
147 0
148};
149
150/* -- Target-specific instruction emitter --------------------------------- */
151
152#if LJ_TARGET_X86ORX64
153#include "lj_emit_x86.h"
154#elif LJ_TARGET_ARM
155#include "lj_emit_arm.h"
156#elif LJ_TARGET_PPC
157#include "lj_emit_ppc.h"
158#else
159#error "Missing instruction emitter for target CPU"
160#endif
161
162/* -- Register allocator debugging ---------------------------------------- */
163
164/* #define LUAJIT_DEBUG_RA */
165
166#ifdef LUAJIT_DEBUG_RA
167
168#include <stdio.h>
169#include <stdarg.h>
170
171#define RIDNAME(name) #name,
172static const char *const ra_regname[] = {
173 GPRDEF(RIDNAME)
174 FPRDEF(RIDNAME)
175 VRIDDEF(RIDNAME)
176 NULL
177};
178#undef RIDNAME
179
180static char ra_dbg_buf[65536];
181static char *ra_dbg_p;
182static char *ra_dbg_merge;
183static MCode *ra_dbg_mcp;
184
185static void ra_dstart(void)
186{
187 ra_dbg_p = ra_dbg_buf;
188 ra_dbg_merge = NULL;
189 ra_dbg_mcp = NULL;
190}
191
192static void ra_dflush(void)
193{
194 fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
195 ra_dstart();
196}
197
198static void ra_dprintf(ASMState *as, const char *fmt, ...)
199{
200 char *p;
201 va_list argp;
202 va_start(argp, fmt);
203 p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
204 ra_dbg_mcp = NULL;
205 p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
206 for (;;) {
207 const char *e = strchr(fmt, '$');
208 if (e == NULL) break;
209 memcpy(p, fmt, (size_t)(e-fmt));
210 p += e-fmt;
211 if (e[1] == 'r') {
212 Reg r = va_arg(argp, Reg) & RID_MASK;
213 if (r <= RID_MAX) {
214 const char *q;
215 for (q = ra_regname[r]; *q; q++)
216 *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
217 } else {
218 *p++ = '?';
219 lua_assert(0);
220 }
221 } else if (e[1] == 'f' || e[1] == 'i') {
222 IRRef ref;
223 if (e[1] == 'f')
224 ref = va_arg(argp, IRRef);
225 else
226 ref = va_arg(argp, IRIns *) - as->ir;
227 if (ref >= REF_BIAS)
228 p += sprintf(p, "%04d", ref - REF_BIAS);
229 else
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));
236 } else {
237 lua_assert(0);
238 }
239 fmt = e+2;
240 }
241 va_end(argp);
242 while (*fmt)
243 *p++ = *fmt++;
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);
247 p = ra_dbg_buf;
248 }
249 ra_dbg_p = p;
250}
251
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
258
259#else
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)
264#endif
265
266/* -- Register allocator -------------------------------------------------- */
267
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))
272
273#define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
274
275/* Setup register allocator. */
276static void ra_setup(ASMState *as)
277{
278 Reg r;
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);
287}
288
289/* Rematerialize constants. */
290static Reg ra_rematk(ASMState *as, IRRef ref)
291{
292 IRIns *ir;
293 Reg r;
294 if (ra_iskref(ref)) {
295 r = ra_krefreg(ref);
296 lua_assert(!rset_test(as->freeset, r));
297 ra_free(as, r);
298 ra_modified(as, r);
299 emit_loadi(as, r, ra_krefk(as, ref));
300 return r;
301 }
302 ir = IR(ref);
303 r = ir->r;
304 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
305 ra_free(as, r);
306 ra_modified(as, r);
307 ir->r = RID_INIT; /* Do not keep any hint. */
308 RA_DBGX((as, "remat $i $r", ir, r));
309#if !LJ_SOFTFP
310 if (ir->o == IR_KNUM) {
311 emit_loadn(as, r, ir_knum(ir));
312 } else
313#endif
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);
320#if LJ_64
321 } else if (ir->o == IR_KINT64) {
322 emit_loadu64(as, r, ir_kint64(ir)->u64);
323#endif
324 } else {
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);
328 }
329 return r;
330}
331
332/* Force a spill. Allocate a new spill slot if needed. */
333static int32_t ra_spill(ASMState *as, IRIns *ir)
334{
335 int32_t slot = ir->s;
336 if (!ra_hasspill(slot)) {
337 if (irt_is64(ir->t)) {
338 slot = as->evenspill;
339 as->evenspill += 2;
340 } else if (as->oddspill) {
341 slot = as->oddspill;
342 as->oddspill = 0;
343 } else {
344 slot = as->evenspill;
345 as->oddspill = slot+1;
346 as->evenspill += 2;
347 }
348 if (as->evenspill > 256)
349 lj_trace_err(as->J, LJ_TRERR_SPILLOV);
350 ir->s = (uint8_t)slot;
351 }
352 return sps_scale(slot);
353}
354
355/* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
356static Reg ra_releasetmp(ASMState *as, IRRef ref)
357{
358 IRIns *ir = IR(ref);
359 Reg r = ir->r;
360 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
361 ra_free(as, r);
362 ra_modified(as, r);
363 ir->r = RID_INIT;
364 return r;
365}
366
367/* Restore a register (marked as free). Rematerialize or force a spill. */
368static Reg ra_restore(ASMState *as, IRRef ref)
369{
370 if (emit_canremat(ref)) {
371 return ra_rematk(as, ref);
372 } else {
373 IRIns *ir = IR(ref);
374 int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
375 Reg r = ir->r;
376 lua_assert(ra_hasreg(r));
377 ra_sethint(ir->r, r); /* Keep hint. */
378 ra_free(as, r);
379 if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
380 ra_modified(as, r);
381 RA_DBGX((as, "restore $i $r", ir, r));
382 emit_spload(as, ir, r, ofs);
383 }
384 return r;
385 }
386}
387
388/* Save a register to a spill slot. */
389static void ra_save(ASMState *as, IRIns *ir, Reg r)
390{
391 RA_DBGX((as, "save $i $r", ir, r));
392 emit_spstore(as, ir, r, sps_scale(ir->s));
393}
394
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];
399
400/* Evict the register with the lowest cost, forcing a restore. */
401static Reg ra_evict(ASMState *as, RegSet allow)
402{
403 IRRef ref;
404 RegCost cost = ~(RegCost)0;
405 lua_assert(allow != RSET_EMPTY);
406 if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
407 GPRDEF(MINCOST)
408 } else {
409 FPRDEF(MINCOST)
410 }
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)) {
415 IRIns *ir = IR(ref);
416 if (!rset_test(as->weakset, ir->r))
417 ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
418 }
419 return ra_restore(as, ref);
420}
421
422/* Pick any register (marked as free). Evict on-demand. */
423static Reg ra_pick(ASMState *as, RegSet allow)
424{
425 RegSet pick = as->freeset & allow;
426 if (!pick)
427 return ra_evict(as, allow);
428 else
429 return rset_picktop(pick);
430}
431
432/* Get a scratch register (marked as free). */
433static Reg ra_scratch(ASMState *as, RegSet allow)
434{
435 Reg r = ra_pick(as, allow);
436 ra_modified(as, r);
437 RA_DBGX((as, "scratch $r", r));
438 return r;
439}
440
441/* Evict all registers from a set (if not free). */
442static void ra_evictset(ASMState *as, RegSet drop)
443{
444 as->modset |= drop;
445 drop &= ~as->freeset;
446 while (drop) {
447 Reg r = rset_pickbot(drop);
448 ra_restore(as, regcost_ref(as->cost[r]));
449 rset_clear(drop, r);
450 checkmclim(as);
451 }
452}
453
454/* Evict (rematerialize) all registers allocated to constants. */
455static void ra_evictk(ASMState *as)
456{
457 RegSet work;
458#if !LJ_SOFTFP
459 work = ~as->freeset & RSET_FPR;
460 while (work) {
461 Reg r = rset_pickbot(work);
462 IRRef ref = regcost_ref(as->cost[r]);
463 if (emit_canremat(ref) && irref_isk(ref)) {
464 ra_rematk(as, ref);
465 checkmclim(as);
466 }
467 rset_clear(work, r);
468 }
469#endif
470 work = ~as->freeset & RSET_GPR;
471 while (work) {
472 Reg r = rset_pickbot(work);
473 IRRef ref = regcost_ref(as->cost[r]);
474 if (emit_canremat(ref) && irref_isk(ref)) {
475 ra_rematk(as, ref);
476 checkmclim(as);
477 }
478 rset_clear(work, r);
479 }
480}
481
482#ifdef RID_NUM_KREF
483/* Allocate a register for a constant. */
484static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
485{
486 /* First try to find a register which already holds the same constant. */
487 RegSet pick, work = ~as->freeset & RSET_GPR;
488 Reg r;
489 while (work) {
490 IRRef ref;
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))
495 return r;
496 rset_clear(work, r);
497 }
498 pick = as->freeset & allow;
499 if (pick) {
500 /* Constants should preferably get unmodified registers. */
501 if ((pick & ~as->modset))
502 pick &= ~as->modset;
503 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
504 } else {
505 r = ra_evict(as, allow);
506 }
507 RA_DBGX((as, "allock $x $r", k, r));
508 ra_setkref(as, r, k);
509 rset_clear(as->freeset, r);
510 ra_noweak(as, r);
511 return r;
512}
513
514/* Allocate a specific register for a constant. */
515static void ra_allockreg(ASMState *as, int32_t k, Reg r)
516{
517 Reg kr = ra_allock(as, k, RID2RSET(r));
518 if (kr != r) {
519 IRIns irdummy;
520 irdummy.t.irt = IRT_INT;
521 ra_scratch(as, RID2RSET(r));
522 emit_movrr(as, &irdummy, r, kr);
523 }
524}
525#else
526#define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
527#endif
528
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.
532*/
533static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
534{
535 IRIns *ir = IR(ref);
536 RegSet pick = as->freeset & allow;
537 Reg r;
538 lua_assert(ra_noreg(ir->r));
539 if (pick) {
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. */
544 goto found;
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]));
548 goto found;
549 }
550 RA_DBGX((as, "hintmiss $f $r", ref, r));
551 }
552 /* Invariants should preferably get unmodified registers. */
553 if (ref < as->loopref && !irt_isphi(ir->t)) {
554 if ((pick & ~as->modset))
555 pick &= ~as->modset;
556 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
557 } else {
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);
562 }
563 } else {
564 r = ra_evict(as, allow);
565 }
566found:
567 RA_DBGX((as, "alloc $f $r", ref, r));
568 ir->r = (uint8_t)r;
569 rset_clear(as->freeset, r);
570 ra_noweak(as, r);
571 as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
572 return r;
573}
574
575/* Allocate a register on-demand. */
576static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
577{
578 Reg r = IR(ref)->r;
579 /* Note: allow is ignored if the register is already allocated. */
580 if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
581 ra_noweak(as, r);
582 return r;
583}
584
585/* Rename register allocation and emit move. */
586static void ra_rename(ASMState *as, Reg down, Reg up)
587{
588 IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
589 IRIns *ir = IR(ref);
590 ir->r = (uint8_t)up;
591 as->cost[down] = 0;
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. */
597 ra_noweak(as, up);
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;
606 }
607}
608
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.
612*/
613static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
614{
615 Reg dest = ir->r;
616 if (ra_hasreg(dest)) {
617 ra_free(as, dest);
618 ra_modified(as, dest);
619 } else {
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));
624 } else {
625 dest = ra_scratch(as, allow);
626 }
627 ir->r = dest;
628 }
629 if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
630 return dest;
631}
632
633/* Force a specific destination register (marked as free). */
634static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
635{
636 Reg dest = ra_dest(as, ir, RID2RSET(r));
637 if (dest != r) {
638 ra_scratch(as, RID2RSET(r));
639 emit_movrr(as, ir, dest, r);
640 }
641}
642
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.
646*/
647static void ra_left(ASMState *as, Reg dest, IRRef lref)
648{
649 IRIns *ir = IR(lref);
650 Reg left = ir->r;
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);
658 return;
659 }
660#if LJ_64
661 } else if (ir->o == IR_KINT64) {
662 emit_loadu64(as, dest, ir_kint64(ir)->u64);
663 return;
664#endif
665 } else {
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);
669 return;
670 }
671 }
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);
675 }
676 ra_noweak(as, left);
677 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
678 if (dest != left) {
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);
683 } else {
684 emit_movrr(as, ir, dest, left);
685 }
686 }
687}
688#else
689/* Similar to ra_left, except we override any hints. */
690static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
691{
692 IRIns *ir = IR(lref);
693 Reg left = ir->r;
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);
698 }
699 ra_noweak(as, left);
700 if (dest != left) {
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);
705 } else {
706 emit_movrr(as, ir, dest, left);
707 }
708 }
709}
710#endif
711
712#if !LJ_TARGET_X86ORX64
713/* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
714static void ra_destpair(ASMState *as, IRIns *ir)
715{
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)) {
726 ra_free(as, destlo);
727 ra_modified(as, destlo);
728 } else {
729 destlo = RID_RETLO;
730 }
731 if (ra_hasreg(desthi)) {
732 ra_free(as, desthi);
733 ra_modified(as, desthi);
734 } else {
735 desthi = RID_RETHI;
736 }
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);
743 } else {
744 emit_movrr(as, ir, RID_RETHI, RID_RETLO);
745 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
746 }
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);
750 } else {
751 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
752 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
753 }
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);
757}
758#endif
759
760/* -- Snapshot handling --------- ----------------------------------------- */
761
762/* Can we rematerialize a KNUM instead of forcing a spill? */
763static int asm_snap_canremat(ASMState *as)
764{
765 Reg r;
766 for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
767 if (irref_isk(regcost_ref(as->cost[r])))
768 return 1;
769 return 0;
770}
771
772/* Allocate register or spill slot for a ref that escapes to a snapshot. */
773static void asm_snap_alloc1(ASMState *as, IRRef ref)
774{
775 IRIns *ir = IR(ref);
776 if (!ra_used(ir)) {
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. */
784 checkmclim(as);
785 RA_DBGX((as, "snapreg $f $r", ref, ir->r));
786 } else {
787 ra_spill(as, ir); /* Otherwise force a spill slot. */
788 RA_DBGX((as, "snapspill $f $s", ref, ir->s));
789 }
790 }
791}
792
793/* Allocate refs escaping to a snapshot. */
794static void asm_snap_alloc(ASMState *as)
795{
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);
807 }
808 }
809 }
810}
811
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
815** RegSP mapping.
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.
818*/
819static int asm_snap_checkrename(ASMState *as, IRRef ren)
820{
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)) {
828 IRIns *ir = IR(ref);
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. */
832 }
833 }
834 return 0; /* Not found. */
835}
836
837/* Prepare snapshot for next guard instruction. */
838static void asm_snap_prep(ASMState *as)
839{
840 if (as->curins < as->snapref) {
841 do {
842 lua_assert(as->snapno != 0);
843 as->snapno--;
844 as->snapref = as->T->snap[as->snapno].ref;
845 } while (as->curins < as->snapref);
846 asm_snap_alloc(as);
847 as->snaprename = as->T->nins;
848 } else {
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. */
854 }
855 }
856}
857
858/* -- Miscellaneous helpers ----------------------------------------------- */
859
860/* Collect arguments from CALL* and CARG instructions. */
861static void asm_collectargs(ASMState *as, IRIns *ir,
862 const CCallInfo *ci, IRRef *args)
863{
864 uint32_t n = CCI_NARGS(ci);
865 lua_assert(n <= CCI_NARGS_MAX);
866 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
867 while (n-- > 1) {
868 ir = IR(ir->op1);
869 lua_assert(ir->o == IR_CARG);
870 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
871 }
872 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
873 lua_assert(IR(ir->op1)->o != IR_CARG);
874}
875
876/* Reconstruct CCallInfo flags for CALLX*. */
877static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
878{
879 uint32_t nargs = 0;
880 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
881 IRIns *ira = IR(ir->op1);
882 nargs++;
883 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
884 }
885#if LJ_HASFFI
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);
890#if LJ_TARGET_X86
891 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
892#endif
893 }
894#endif
895 return (nargs | (ir->t.irt << CCI_OTSHIFT));
896}
897
898/* Calculate stack adjustment. */
899static int32_t asm_stack_adjust(ASMState *as)
900{
901 if (as->evenspill <= SPS_FIXED)
902 return 0;
903 return sps_scale(sps_align(as->evenspill));
904}
905
906/* Must match with hash*() in lj_tab.c. */
907static uint32_t ir_khash(IRIns *ir)
908{
909 uint32_t lo, hi;
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;
918 } else {
919 lua_assert(irt_isgcv(ir->t));
920 lo = u32ptr(ir_kgc(ir));
921 hi = lo + HASH_BIAS;
922 }
923 return hashrot(lo, hi);
924}
925
926/* -- Allocations --------------------------------------------------------- */
927
928static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
929static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
930
931static void asm_snew(ASMState *as, IRIns *ir)
932{
933 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
934 IRRef args[3];
935 args[0] = ASMREF_L; /* lua_State *L */
936 args[1] = ir->op1; /* const char *str */
937 args[2] = ir->op2; /* size_t len */
938 as->gcsteps++;
939 asm_setupresult(as, ir, ci); /* GCstr * */
940 asm_gencall(as, ci, args);
941}
942
943static void asm_tnew(ASMState *as, IRIns *ir)
944{
945 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
946 IRRef args[2];
947 args[0] = ASMREF_L; /* lua_State *L */
948 args[1] = ASMREF_TMP1; /* uint32_t ahsize */
949 as->gcsteps++;
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));
953}
954
955static void asm_tdup(ASMState *as, IRIns *ir)
956{
957 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
958 IRRef args[2];
959 args[0] = ASMREF_L; /* lua_State *L */
960 args[1] = ir->op1; /* const GCtab *kt */
961 as->gcsteps++;
962 asm_setupresult(as, ir, ci); /* GCtab * */
963 asm_gencall(as, ci, args);
964}
965
966/* -- PHI and loop handling ----------------------------------------------- */
967
968/* Break a PHI cycle by renaming to a free register (evict if needed). */
969static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
970 RegSet allow)
971{
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.
976 */
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. */
982 }
983}
984
985/* PHI register shuffling.
986**
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.
990**
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.
995**
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.
1000**
1001** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1002*/
1003static void asm_phi_shuffle(ASMState *as)
1004{
1005 RegSet work;
1006
1007 /* Find and resolve PHI register mismatches. */
1008 for (;;) {
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]);
1015 Reg left = irl->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);
1024 left = RID_NONE;
1025 } else { /* Otherwise grab register from invariant. */
1026 ra_restore(as, ref);
1027 checkmclim(as);
1028 }
1029 }
1030 if (ra_hasreg(left)) {
1031 ra_rename(as, left, r);
1032 checkmclim(as);
1033 }
1034 }
1035 rset_clear(phiset, r);
1036 }
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);
1041 checkmclim(as);
1042 } /* Else retry some more renames. */
1043 }
1044
1045 /* Restore/remat invariants whose registers are modified inside the loop. */
1046 work = as->modset & ~(as->freeset | as->phiset);
1047 while (work) {
1048 Reg r = rset_pickbot(work);
1049 ra_restore(as, regcost_ref(as->cost[r]));
1050 rset_clear(work, r);
1051 checkmclim(as);
1052 }
1053
1054 /* Allocate and save all unsaved PHI regs and clear marks. */
1055 work = as->phiset;
1056 while (work) {
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. */
1064 checkmclim(as);
1065 }
1066 rset_clear(work, r);
1067 }
1068}
1069
1070/* Emit renames for left PHIs which are only spilled outside the loop. */
1071static void asm_phi_fixup(ASMState *as)
1072{
1073 RegSet work = as->phiset;
1074 while (work) {
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)) {
1080 IRRef ren;
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;
1086 }
1087 irt_clearmark(ir->t); /* Always clear marker. */
1088 rset_clear(work, r);
1089 }
1090}
1091
1092/* Setup right PHI reference. */
1093static void asm_phi(ASMState *as, IRIns *ir)
1094{
1095 RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
1096 ~as->phiset;
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? */
1105 Reg r;
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);
1111 }
1112 ir->r = (uint8_t)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);
1122 ra_spill(as, ir);
1123 irl->s = irr->s = ir->s; /* Sync left/right PHI spill slots. */
1124 }
1125}
1126
1127static void asm_gc_check(ASMState *as);
1128static void asm_loop_fixup(ASMState *as);
1129
1130/* Middle part of a loop. */
1131static void asm_loop(ASMState *as)
1132{
1133 /* LOOP is a guard, so the snapno is up to date. */
1134 as->loopsnapno = as->snapno;
1135 if (as->gcsteps)
1136 asm_gc_check(as);
1137 /* LOOP marks the transition from the variant to the invariant part. */
1138 as->flagmcp = as->invmcp = NULL;
1139 as->sectref = 0;
1140 if (!neverfuse(as)) as->fuseref = 0;
1141 asm_phi_shuffle(as);
1142 asm_loop_fixup(as);
1143 as->mcloop = as->mcp;
1144 RA_DBGX((as, "===== LOOP ====="));
1145 if (!as->realign) RA_DBG_FLUSH();
1146}
1147
1148/* -- Target-specific assembler ------------------------------------------- */
1149
1150#if LJ_TARGET_X86ORX64
1151#include "lj_asm_x86.h"
1152#elif LJ_TARGET_ARM
1153#include "lj_asm_arm.h"
1154#elif LJ_TARGET_PPC
1155#include "lj_asm_ppc.h"
1156#else
1157#error "Missing assembler for target CPU"
1158#endif
1159
1160/* -- Head of trace ------------------------------------------------------- */
1161
1162/* Head of a root trace. */
1163static void asm_head_root(ASMState *as)
1164{
1165 int32_t spadj;
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;
1173}
1174
1175/* Get RegSP for parent slot. */
1176static LJ_AINLINE RegSP asm_head_parentrs(ASMState *as, IRIns *ir)
1177{
1178#if LJ_SOFTFP
1179 if (ir->o == IR_HIOP) return as->parentmaphi[(ir-1)->op1];
1180#endif
1181 return as->parentmap[ir->op1];
1182}
1183
1184/* Head of a side trace.
1185**
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.
1191*/
1192static void asm_head_side(ASMState *as)
1193{
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;
1199 int pass2 = 0;
1200 int pass3 = 0;
1201 IRRef i;
1202
1203 allow = asm_head_side_base(as, irp, allow);
1204
1205 /* Scan all parent SLOADs and collect register dependencies. */
1206 for (i = as->stopins; i > REF_BASE; i--) {
1207 IRIns *ir = IR(i);
1208 RegSP rs;
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);
1216 } else if (ra_hasspill(ir->s)) {
1217 irt_setmark(ir->t);
1218 pass2 = 1;
1219 }
1220 if (ir->r == rs) { /* Coalesce matching registers right now. */
1221 ra_free(as, ir->r);
1222 } else if (ra_hasspill(regsp_spill(rs))) {
1223 if (ra_hasreg(ir->r))
1224 pass3 = 1;
1225 } else if (ra_used(ir)) {
1226 sloadins[rs] = (IRRef1)i;
1227 rset_set(live, rs); /* Block live parent register. */
1228 }
1229 }
1230
1231 /* Calculate stack frame adjustment. */
1232 spadj = asm_stack_adjust(as);
1233 spdelta = spadj - (int32_t)as->parent->spadjust;
1234 if (spdelta < 0) { /* Don't shrink the stack frame. */
1235 spadj = (int32_t)as->parent->spadjust;
1236 spdelta = 0;
1237 }
1238 as->T->spadjust = (uint16_t)spadj;
1239
1240 /* Reload spilled target registers. */
1241 if (pass2) {
1242 for (i = as->stopins; i > REF_BASE; i--) {
1243 IRIns *ir = IR(i);
1244 if (irt_ismarked(ir->t)) {
1245 RegSet mask;
1246 Reg r;
1247 RegSP rs;
1248 irt_clearmark(ir->t);
1249 rs = asm_head_parentrs(as, ir);
1250 if (!ra_hasspill(regsp_spill(rs)))
1251 ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
1252 else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
1253 continue; /* Same spill slot, do nothing. */
1254 mask = ((!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
1255 if (mask == RSET_EMPTY)
1256 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1257 r = ra_allocref(as, i, mask);
1258 ra_save(as, ir, r);
1259 rset_clear(allow, r);
1260 if (r == rs) { /* Coalesce matching registers right now. */
1261 ra_free(as, r);
1262 rset_clear(live, r);
1263 } else if (ra_hasspill(regsp_spill(rs))) {
1264 pass3 = 1;
1265 }
1266 checkmclim(as);
1267 }
1268 }
1269 }
1270
1271 /* Store trace number and adjust stack frame relative to the parent. */
1272 emit_setvmstate(as, (int32_t)as->T->traceno);
1273 emit_spsub(as, spdelta);
1274
1275#if !LJ_TARGET_X86ORX64
1276 /* Restore BASE register from parent spill slot. */
1277 if (ra_hasspill(irp->s))
1278 emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
1279#endif
1280
1281 /* Restore target registers from parent spill slots. */
1282 if (pass3) {
1283 RegSet work = ~as->freeset & RSET_ALL;
1284 while (work) {
1285 Reg r = rset_pickbot(work);
1286 IRIns *ir = IR(regcost_ref(as->cost[r]));
1287 RegSP rs = asm_head_parentrs(as, ir);
1288 rset_clear(work, r);
1289 if (ra_hasspill(regsp_spill(rs))) {
1290 int32_t ofs = sps_scale(regsp_spill(rs));
1291 ra_free(as, r);
1292 emit_spload(as, ir, r, ofs);
1293 checkmclim(as);
1294 }
1295 }
1296 }
1297
1298 /* Shuffle registers to match up target regs with parent regs. */
1299 for (;;) {
1300 RegSet work;
1301
1302 /* Repeatedly coalesce free live registers by moving to their target. */
1303 while ((work = as->freeset & live) != RSET_EMPTY) {
1304 Reg rp = rset_pickbot(work);
1305 IRIns *ir = IR(sloadins[rp]);
1306 rset_clear(live, rp);
1307 rset_clear(allow, rp);
1308 ra_free(as, ir->r);
1309 emit_movrr(as, ir, ir->r, rp);
1310 checkmclim(as);
1311 }
1312
1313 /* We're done if no live registers remain. */
1314 if (live == RSET_EMPTY)
1315 break;
1316
1317 /* Break cycles by renaming one target to a temp. register. */
1318 if (live & RSET_GPR) {
1319 RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
1320 if (tmpset == RSET_EMPTY)
1321 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1322 ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
1323 }
1324 if (!LJ_SOFTFP && (live & RSET_FPR)) {
1325 RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
1326 if (tmpset == RSET_EMPTY)
1327 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1328 ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
1329 }
1330 checkmclim(as);
1331 /* Continue with coalescing to fix up the broken cycle(s). */
1332 }
1333
1334 /* Inherit top stack slot already checked by parent trace. */
1335 as->T->topslot = as->parent->topslot;
1336 if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
1337#ifdef EXITSTATE_CHECKEXIT
1338 /* Highest exit + 1 indicates stack check. */
1339 ExitNo exitno = as->T->nsnap;
1340#else
1341 /* Reuse the parent exit in the context of the parent trace. */
1342 ExitNo exitno = as->J->exitno;
1343#endif
1344 as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
1345 asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
1346 }
1347}
1348
1349/* -- Tail of trace ------------------------------------------------------- */
1350
1351/* Get base slot for a snapshot. */
1352static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
1353{
1354 SnapEntry *map = &as->T->snapmap[snap->mapofs];
1355 MSize n;
1356 for (n = snap->nent; n > 0; n--) {
1357 SnapEntry sn = map[n-1];
1358 if ((sn & SNAP_FRAME)) {
1359 *gotframe = 1;
1360 return snap_slot(sn);
1361 }
1362 }
1363 return 0;
1364}
1365
1366/* Link to another trace. */
1367static void asm_tail_link(ASMState *as)
1368{
1369 SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
1370 SnapShot *snap = &as->T->snap[snapno];
1371 int gotframe = 0;
1372 BCReg baseslot = asm_baseslot(as, snap, &gotframe);
1373
1374 as->topslot = snap->topslot;
1375 checkmclim(as);
1376 ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
1377
1378 if (as->T->link == 0) {
1379 /* Setup fixed registers for exit to interpreter. */
1380 const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
1381 int32_t mres;
1382 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
1383 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1384 if (bc_isret(bc_op(*retpc)))
1385 pc = retpc;
1386 }
1387 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1388 ra_allockreg(as, i32ptr(pc), RID_LPC);
1389 mres = (int32_t)(snap->nslots - baseslot);
1390 switch (bc_op(*pc)) {
1391 case BC_CALLM: case BC_CALLMT:
1392 mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
1393 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1394 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1395 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
1396 }
1397 ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
1398 } else if (baseslot) {
1399 /* Save modified BASE for linking to trace with higher start frame. */
1400 emit_setgl(as, RID_BASE, jit_base);
1401 }
1402 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1403
1404 /* Sync the interpreter state with the on-trace state. */
1405 asm_stack_restore(as, snap);
1406
1407 /* Root traces that add frames need to check the stack at the end. */
1408 if (!as->parent && gotframe)
1409 asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
1410}
1411
1412/* -- Trace setup --------------------------------------------------------- */
1413
1414/* Clear reg/sp for all instructions and add register hints. */
1415static void asm_setup_regsp(ASMState *as)
1416{
1417 GCtrace *T = as->T;
1418 IRRef i, nins;
1419 int inloop;
1420#if LJ_TARGET_ARM
1421 uint32_t rload = 0xa6402a64;
1422#endif
1423
1424 ra_setup(as);
1425
1426 /* Clear reg/sp for constants. */
1427 for (i = T->nk; i < REF_BIAS; i++)
1428 IR(i)->prev = REGSP_INIT;
1429
1430 /* REF_BASE is used for implicit references to the BASE register. */
1431 IR(REF_BASE)->prev = REGSP_HINT(RID_BASE);
1432
1433 nins = T->nins;
1434 if (IR(nins-1)->o == IR_RENAME) {
1435 do { nins--; } while (IR(nins-1)->o == IR_RENAME);
1436 T->nins = nins; /* Remove any renames left over from ASM restart. */
1437 }
1438 as->snaprename = nins;
1439 as->snapref = nins;
1440 as->snapno = T->nsnap;
1441
1442 as->stopins = REF_BASE;
1443 as->orignins = nins;
1444 as->curins = nins;
1445
1446 inloop = 0;
1447 as->evenspill = SPS_FIRST;
1448 for (i = REF_FIRST; i < nins; i++) {
1449 IRIns *ir = IR(i);
1450 switch (ir->o) {
1451 case IR_LOOP:
1452 inloop = 1;
1453 break;
1454 /* Set hints for slot loads from a parent trace. */
1455 case IR_SLOAD:
1456 if ((ir->op2 & IRSLOAD_PARENT)) {
1457 RegSP rs = as->parentmap[ir->op1];
1458 lua_assert(regsp_used(rs));
1459 as->stopins = i;
1460 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1461 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1462 continue;
1463 }
1464 }
1465#if LJ_TARGET_ARM
1466 if ((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP) {
1467 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1468 rload = lj_ror(rload, 4);
1469 continue;
1470 }
1471#endif
1472 break;
1473#if LJ_TARGET_ARM
1474 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1475 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1476 rload = lj_ror(rload, 4);
1477 continue;
1478#endif
1479 case IR_CALLXS: {
1480 CCallInfo ci;
1481 ci.flags = asm_callx_flags(as, ir);
1482 ir->prev = asm_setup_call_slots(as, ir, &ci);
1483 if (inloop)
1484 as->modset |= RSET_SCRATCH;
1485 continue;
1486 }
1487 case IR_CALLN: case IR_CALLL: case IR_CALLS: {
1488 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1489 ir->prev = asm_setup_call_slots(as, ir, ci);
1490 if (inloop)
1491 as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
1492 (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
1493 continue;
1494 }
1495#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1496 case IR_HIOP:
1497 switch ((ir-1)->o) {
1498#if LJ_SOFTFP
1499 case IR_SLOAD:
1500 if (((ir-1)->op2 & IRSLOAD_PARENT)) {
1501 RegSP rs = as->parentmaphi[(ir-1)->op1];
1502 lua_assert(regsp_used(rs));
1503 as->stopins = i;
1504 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1505 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1506 continue;
1507 }
1508 }
1509#if LJ_TARGET_ARM
1510 /* fallthrough */
1511 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1512 if (ra_hashint((ir-1)->r)) {
1513 ir->prev = (ir-1)->prev + 1;
1514 continue;
1515 }
1516#endif
1517 break;
1518#endif
1519#if LJ_NEED_FP64
1520 case IR_CONV:
1521 if (irt_isfp((ir-1)->t)) {
1522 ir->prev = REGSP_HINT(RID_FPRET);
1523 continue;
1524 }
1525 /* fallthrough */
1526#endif
1527 case IR_CALLN: case IR_CALLXS:
1528#if LJ_SOFTFP
1529 case IR_MIN: case IR_MAX:
1530#endif
1531#if LJ_BE
1532 (ir-1)->prev = REGSP_HINT(RID_RETLO);
1533#endif
1534 ir->prev = REGSP_HINT(RID_RETHI);
1535 continue;
1536 default:
1537 break;
1538 }
1539 break;
1540#endif
1541#if LJ_SOFTFP
1542 case IR_MIN: case IR_MAX:
1543 if ((ir+1)->o != IR_HIOP) break;
1544 /* fallthrough */
1545#endif
1546 /* C calls evict all scratch regs and return results in RID_RET. */
1547 case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
1548 if (REGARG_NUMGPR < 3 && as->evenspill < 3)
1549 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1550 case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
1551 ir->prev = REGSP_HINT(RID_RET);
1552 if (inloop)
1553 as->modset = RSET_SCRATCH;
1554 continue;
1555 case IR_STRTO: case IR_OBAR:
1556 if (inloop)
1557 as->modset = RSET_SCRATCH;
1558 break;
1559#if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1560 case IR_ATAN2: case IR_LDEXP:
1561#endif
1562 case IR_POW:
1563 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1564#if LJ_TARGET_X86ORX64
1565 ir->prev = REGSP_HINT(RID_XMM0);
1566 if (inloop)
1567 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1568#else
1569 ir->prev = REGSP_HINT(RID_FPRET);
1570 if (inloop)
1571 as->modset |= RSET_SCRATCH;
1572#endif
1573 continue;
1574 }
1575 /* fallthrough for integer POW */
1576 case IR_DIV: case IR_MOD:
1577 if (!irt_isnum(ir->t)) {
1578 ir->prev = REGSP_HINT(RID_RET);
1579 if (inloop)
1580 as->modset |= (RSET_SCRATCH & RSET_GPR);
1581 continue;
1582 }
1583 break;
1584 case IR_FPMATH:
1585#if LJ_TARGET_X86ORX64
1586 if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
1587 ir->prev = REGSP_HINT(RID_XMM0);
1588#if !LJ_64
1589 if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
1590 as->evenspill = 4;
1591#endif
1592 if (inloop)
1593 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1594 continue;
1595 } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
1596 ir->prev = REGSP_HINT(RID_XMM0);
1597 if (inloop)
1598 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1599 continue;
1600 }
1601 break;
1602#else
1603 ir->prev = REGSP_HINT(RID_FPRET);
1604 if (inloop)
1605 as->modset |= RSET_SCRATCH;
1606 continue;
1607#endif
1608#if LJ_TARGET_X86ORX64
1609 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1610 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
1611 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
1612 IR(ir->op2)->r = REGSP_HINT(RID_ECX);
1613 if (inloop)
1614 rset_set(as->modset, RID_ECX);
1615 }
1616 break;
1617#endif
1618 /* Do not propagate hints across type conversions. */
1619 case IR_TOBIT:
1620 break;
1621 case IR_CONV:
1622 if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
1623 (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
1624 break;
1625 /* fallthrough */
1626 default:
1627 /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
1628 if (irref_isk(ir->op2) && !irref_isk(ir->op1)) {
1629 ir->prev = IR(ir->op1)->prev;
1630 continue;
1631 }
1632 break;
1633 }
1634 ir->prev = REGSP_INIT;
1635 }
1636 if ((as->evenspill & 1))
1637 as->oddspill = as->evenspill++;
1638 else
1639 as->oddspill = 0;
1640}
1641
1642/* -- Assembler core ------------------------------------------------------ */
1643
1644/* Assemble a trace. */
1645void lj_asm_trace(jit_State *J, GCtrace *T)
1646{
1647 ASMState as_;
1648 ASMState *as = &as_;
1649 MCode *origtop;
1650
1651 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1652 J->cur.nins = lj_ir_nextins(J);
1653 J->cur.ir[J->cur.nins].o = IR_NOP;
1654
1655 /* Setup initial state. Copy some fields to reduce indirections. */
1656 as->J = J;
1657 as->T = T;
1658 as->ir = T->ir;
1659 as->flags = J->flags;
1660 as->loopref = J->loopref;
1661 as->realign = NULL;
1662 as->loopinv = 0;
1663 if (J->parent) {
1664 as->parent = traceref(J, J->parent);
1665 lj_snap_regspmap(as->parentmap, as->parent, J->exitno, 0);
1666#if LJ_SOFTFP
1667 lj_snap_regspmap(as->parentmaphi, as->parent, J->exitno, 1);
1668#endif
1669 } else {
1670 as->parent = NULL;
1671 }
1672 /* Reserve MCode memory. */
1673 as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
1674 as->mcp = as->mctop;
1675 as->mclim = as->mcbot + MCLIM_REDZONE;
1676 asm_setup_target(as);
1677
1678 do {
1679 as->mcp = as->mctop;
1680 as->curins = T->nins;
1681 RA_DBG_START();
1682 RA_DBGX((as, "===== STOP ====="));
1683
1684 /* General trace setup. Emit tail of trace. */
1685 asm_tail_prep(as);
1686 as->mcloop = NULL;
1687 as->flagmcp = NULL;
1688 as->topslot = 0;
1689 as->gcsteps = 0;
1690 as->sectref = as->loopref;
1691 as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
1692 asm_setup_regsp(as);
1693 if (!as->loopref)
1694 asm_tail_link(as);
1695
1696 /* Assemble a trace in linear backwards order. */
1697 for (as->curins--; as->curins > as->stopins; as->curins--) {
1698 IRIns *ir = IR(as->curins);
1699 lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
1700 if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
1701 continue; /* Dead-code elimination can be soooo easy. */
1702 if (irt_isguard(ir->t))
1703 asm_snap_prep(as);
1704 RA_DBG_REF();
1705 checkmclim(as);
1706 asm_ir(as, ir);
1707 }
1708 } while (as->realign); /* Retry in case the MCode needs to be realigned. */
1709
1710 /* Emit head of trace. */
1711 RA_DBG_REF();
1712 checkmclim(as);
1713 if (as->gcsteps) {
1714 as->curins = as->T->snap[0].ref;
1715 asm_snap_prep(as); /* The GC check is a guard. */
1716 asm_gc_check(as);
1717 }
1718 ra_evictk(as);
1719 if (as->parent)
1720 asm_head_side(as);
1721 else
1722 asm_head_root(as);
1723 asm_phi_fixup(as);
1724
1725 RA_DBGX((as, "===== START ===="));
1726 RA_DBG_FLUSH();
1727 if (as->freeset != RSET_ALL)
1728 lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
1729
1730 /* Set trace entry point before fixing up tail to allow link to self. */
1731 T->mcode = as->mcp;
1732 T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
1733 if (!as->loopref)
1734 asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
1735 T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
1736 lj_mcode_sync(T->mcode, origtop);
1737}
1738
1739#undef IR
1740
1741#endif