RELEASE LuaJIT-2.0.0-beta11
[luajit-2.0/celess22.git] / src / lj_record.c
blobea391bf18864780b67fd6947a9ccef3c72031f62
1 /*
2 ** Trace recorder (bytecode -> SSA IR).
3 ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #define lj_record_c
7 #define LUA_CORE
9 #include "lj_obj.h"
11 #if LJ_HASJIT
13 #include "lj_err.h"
14 #include "lj_str.h"
15 #include "lj_tab.h"
16 #include "lj_meta.h"
17 #include "lj_frame.h"
18 #if LJ_HASFFI
19 #include "lj_ctype.h"
20 #endif
21 #include "lj_bc.h"
22 #include "lj_ff.h"
23 #include "lj_ir.h"
24 #include "lj_jit.h"
25 #include "lj_ircall.h"
26 #include "lj_iropt.h"
27 #include "lj_trace.h"
28 #include "lj_record.h"
29 #include "lj_ffrecord.h"
30 #include "lj_snap.h"
31 #include "lj_dispatch.h"
32 #include "lj_vm.h"
34 /* Some local macros to save typing. Undef'd at the end. */
35 #define IR(ref) (&J->cur.ir[(ref)])
37 /* Pass IR on to next optimization in chain (FOLD). */
38 #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
40 /* Emit raw IR without passing through optimizations. */
41 #define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))
43 /* -- Sanity checks ------------------------------------------------------- */
45 #ifdef LUA_USE_ASSERT
46 /* Sanity check the whole IR -- sloooow. */
47 static void rec_check_ir(jit_State *J)
49 IRRef i, nins = J->cur.nins, nk = J->cur.nk;
50 lua_assert(nk <= REF_BIAS && nins >= REF_BIAS && nins < 65536);
51 for (i = nins-1; i >= nk; i--) {
52 IRIns *ir = IR(i);
53 uint32_t mode = lj_ir_mode[ir->o];
54 IRRef op1 = ir->op1;
55 IRRef op2 = ir->op2;
56 switch (irm_op1(mode)) {
57 case IRMnone: lua_assert(op1 == 0); break;
58 case IRMref: lua_assert(op1 >= nk);
59 lua_assert(i >= REF_BIAS ? op1 < i : op1 > i); break;
60 case IRMlit: break;
61 case IRMcst: lua_assert(i < REF_BIAS); continue;
63 switch (irm_op2(mode)) {
64 case IRMnone: lua_assert(op2 == 0); break;
65 case IRMref: lua_assert(op2 >= nk);
66 lua_assert(i >= REF_BIAS ? op2 < i : op2 > i); break;
67 case IRMlit: break;
68 case IRMcst: lua_assert(0); break;
70 if (ir->prev) {
71 lua_assert(ir->prev >= nk);
72 lua_assert(i >= REF_BIAS ? ir->prev < i : ir->prev > i);
73 lua_assert(ir->o == IR_NOP || IR(ir->prev)->o == ir->o);
78 /* Compare stack slots and frames of the recorder and the VM. */
79 static void rec_check_slots(jit_State *J)
81 BCReg s, nslots = J->baseslot + J->maxslot;
82 int32_t depth = 0;
83 cTValue *base = J->L->base - J->baseslot;
84 lua_assert(J->baseslot >= 1 && J->baseslot < LJ_MAX_JSLOTS);
85 lua_assert(J->baseslot == 1 || (J->slot[J->baseslot-1] & TREF_FRAME));
86 lua_assert(nslots < LJ_MAX_JSLOTS);
87 for (s = 0; s < nslots; s++) {
88 TRef tr = J->slot[s];
89 if (tr) {
90 cTValue *tv = &base[s];
91 IRRef ref = tref_ref(tr);
92 IRIns *ir;
93 lua_assert(ref >= J->cur.nk && ref < J->cur.nins);
94 ir = IR(ref);
95 lua_assert(irt_t(ir->t) == tref_t(tr));
96 if (s == 0) {
97 lua_assert(tref_isfunc(tr));
98 } else if ((tr & TREF_FRAME)) {
99 GCfunc *fn = gco2func(frame_gc(tv));
100 BCReg delta = (BCReg)(tv - frame_prev(tv));
101 lua_assert(tref_isfunc(tr));
102 if (tref_isk(tr)) lua_assert(fn == ir_kfunc(ir));
103 lua_assert(s > delta ? (J->slot[s-delta] & TREF_FRAME) : (s == delta));
104 depth++;
105 } else if ((tr & TREF_CONT)) {
106 lua_assert(ir_kptr(ir) == gcrefp(tv->gcr, void));
107 lua_assert((J->slot[s+1] & TREF_FRAME));
108 depth++;
109 } else {
110 if (tvisnumber(tv))
111 lua_assert(tref_isnumber(tr)); /* Could be IRT_INT etc., too. */
112 else
113 lua_assert(itype2irt(tv) == tref_type(tr));
114 if (tref_isk(tr)) { /* Compare constants. */
115 TValue tvk;
116 lj_ir_kvalue(J->L, &tvk, ir);
117 if (!(tvisnum(&tvk) && tvisnan(&tvk)))
118 lua_assert(lj_obj_equal(tv, &tvk));
119 else
120 lua_assert(tvisnum(tv) && tvisnan(tv));
125 lua_assert(J->framedepth == depth);
127 #endif
129 /* -- Type handling and specialization ------------------------------------ */
131 /* Note: these functions return tagged references (TRef). */
133 /* Specialize a slot to a specific type. Note: slot can be negative! */
134 static TRef sloadt(jit_State *J, int32_t slot, IRType t, int mode)
136 /* Caller may set IRT_GUARD in t. */
137 TRef ref = emitir_raw(IRT(IR_SLOAD, t), (int32_t)J->baseslot+slot, mode);
138 J->base[slot] = ref;
139 return ref;
142 /* Specialize a slot to the runtime type. Note: slot can be negative! */
143 static TRef sload(jit_State *J, int32_t slot)
145 IRType t = itype2irt(&J->L->base[slot]);
146 TRef ref = emitir_raw(IRTG(IR_SLOAD, t), (int32_t)J->baseslot+slot,
147 IRSLOAD_TYPECHECK);
148 if (irtype_ispri(t)) ref = TREF_PRI(t); /* Canonicalize primitive refs. */
149 J->base[slot] = ref;
150 return ref;
153 /* Get TRef from slot. Load slot and specialize if not done already. */
154 #define getslot(J, s) (J->base[(s)] ? J->base[(s)] : sload(J, (int32_t)(s)))
156 /* Get TRef for current function. */
157 static TRef getcurrf(jit_State *J)
159 if (J->base[-1])
160 return J->base[-1];
161 lua_assert(J->baseslot == 1);
162 return sloadt(J, -1, IRT_FUNC, IRSLOAD_READONLY);
165 /* Compare for raw object equality.
166 ** Returns 0 if the objects are the same.
167 ** Returns 1 if they are different, but the same type.
168 ** Returns 2 for two different types.
169 ** Comparisons between primitives always return 1 -- no caller cares about it.
171 int lj_record_objcmp(jit_State *J, TRef a, TRef b, cTValue *av, cTValue *bv)
173 int diff = !lj_obj_equal(av, bv);
174 if (!tref_isk2(a, b)) { /* Shortcut, also handles primitives. */
175 IRType ta = tref_isinteger(a) ? IRT_INT : tref_type(a);
176 IRType tb = tref_isinteger(b) ? IRT_INT : tref_type(b);
177 if (ta != tb) {
178 /* Widen mixed number/int comparisons to number/number comparison. */
179 if (ta == IRT_INT && tb == IRT_NUM) {
180 a = emitir(IRTN(IR_CONV), a, IRCONV_NUM_INT);
181 ta = IRT_NUM;
182 } else if (ta == IRT_NUM && tb == IRT_INT) {
183 b = emitir(IRTN(IR_CONV), b, IRCONV_NUM_INT);
184 } else {
185 return 2; /* Two different types are never equal. */
188 emitir(IRTG(diff ? IR_NE : IR_EQ, ta), a, b);
190 return diff;
193 /* Constify a value. Returns 0 for non-representable object types. */
194 TRef lj_record_constify(jit_State *J, cTValue *o)
196 if (tvisgcv(o))
197 return lj_ir_kgc(J, gcV(o), itype2irt(o));
198 else if (tvisint(o))
199 return lj_ir_kint(J, intV(o));
200 else if (tvisnum(o))
201 return lj_ir_knumint(J, numV(o));
202 else if (tvisbool(o))
203 return TREF_PRI(itype2irt(o));
204 else
205 return 0; /* Can't represent lightuserdata (pointless). */
208 /* -- Record loop ops ----------------------------------------------------- */
210 /* Loop event. */
211 typedef enum {
212 LOOPEV_LEAVE, /* Loop is left or not entered. */
213 LOOPEV_ENTERLO, /* Loop is entered with a low iteration count left. */
214 LOOPEV_ENTER /* Loop is entered. */
215 } LoopEvent;
217 /* Canonicalize slots: convert integers to numbers. */
218 static void canonicalize_slots(jit_State *J)
220 BCReg s;
221 if (LJ_DUALNUM) return;
222 for (s = J->baseslot+J->maxslot-1; s >= 1; s--) {
223 TRef tr = J->slot[s];
224 if (tref_isinteger(tr)) {
225 IRIns *ir = IR(tref_ref(tr));
226 if (!(ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_READONLY)))
227 J->slot[s] = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
232 /* Stop recording. */
233 static void rec_stop(jit_State *J, TraceLink linktype, TraceNo lnk)
235 lj_trace_end(J);
236 J->cur.linktype = (uint8_t)linktype;
237 J->cur.link = (uint16_t)lnk;
238 /* Looping back at the same stack level? */
239 if (lnk == J->cur.traceno && J->framedepth + J->retdepth == 0) {
240 if ((J->flags & JIT_F_OPT_LOOP)) /* Shall we try to create a loop? */
241 goto nocanon; /* Do not canonicalize or we lose the narrowing. */
242 if (J->cur.root) /* Otherwise ensure we always link to the root trace. */
243 J->cur.link = J->cur.root;
245 canonicalize_slots(J);
246 nocanon:
247 /* Note: all loop ops must set J->pc to the following instruction! */
248 lj_snap_add(J); /* Add loop snapshot. */
249 J->needsnap = 0;
250 J->mergesnap = 1; /* In case recording continues. */
253 /* Search bytecode backwards for a int/num constant slot initializer. */
254 static TRef find_kinit(jit_State *J, const BCIns *endpc, BCReg slot, IRType t)
256 /* This algorithm is rather simplistic and assumes quite a bit about
257 ** how the bytecode is generated. It works fine for FORI initializers,
258 ** but it won't necessarily work in other cases (e.g. iterator arguments).
259 ** It doesn't do anything fancy, either (like backpropagating MOVs).
261 const BCIns *pc, *startpc = proto_bc(J->pt);
262 for (pc = endpc-1; pc > startpc; pc--) {
263 BCIns ins = *pc;
264 BCOp op = bc_op(ins);
265 /* First try to find the last instruction that stores to this slot. */
266 if (bcmode_a(op) == BCMbase && bc_a(ins) <= slot) {
267 return 0; /* Multiple results, e.g. from a CALL or KNIL. */
268 } else if (bcmode_a(op) == BCMdst && bc_a(ins) == slot) {
269 if (op == BC_KSHORT || op == BC_KNUM) { /* Found const. initializer. */
270 /* Now try to verify there's no forward jump across it. */
271 const BCIns *kpc = pc;
272 for (; pc > startpc; pc--)
273 if (bc_op(*pc) == BC_JMP) {
274 const BCIns *target = pc+bc_j(*pc)+1;
275 if (target > kpc && target <= endpc)
276 return 0; /* Conditional assignment. */
278 if (op == BC_KSHORT) {
279 int32_t k = (int32_t)(int16_t)bc_d(ins);
280 return t == IRT_INT ? lj_ir_kint(J, k) : lj_ir_knum(J, (lua_Number)k);
281 } else {
282 cTValue *tv = proto_knumtv(J->pt, bc_d(ins));
283 if (t == IRT_INT) {
284 int32_t k = numberVint(tv);
285 if (tvisint(tv) || numV(tv) == (lua_Number)k) /* -0 is ok here. */
286 return lj_ir_kint(J, k);
287 return 0; /* Type mismatch. */
288 } else {
289 return lj_ir_knum(J, numberVnum(tv));
293 return 0; /* Non-constant initializer. */
296 return 0; /* No assignment to this slot found? */
299 /* Load and optionally convert a FORI argument from a slot. */
300 static TRef fori_load(jit_State *J, BCReg slot, IRType t, int mode)
302 int conv = (tvisint(&J->L->base[slot]) != (t==IRT_INT)) ? IRSLOAD_CONVERT : 0;
303 return sloadt(J, (int32_t)slot,
304 t + (((mode & IRSLOAD_TYPECHECK) ||
305 (conv && t == IRT_INT && !(mode >> 16))) ?
306 IRT_GUARD : 0),
307 mode + conv);
310 /* Peek before FORI to find a const initializer. Otherwise load from slot. */
311 static TRef fori_arg(jit_State *J, const BCIns *fori, BCReg slot,
312 IRType t, int mode)
314 TRef tr = J->base[slot];
315 if (!tr) {
316 tr = find_kinit(J, fori, slot, t);
317 if (!tr)
318 tr = fori_load(J, slot, t, mode);
320 return tr;
323 /* Return the direction of the FOR loop iterator.
324 ** It's important to exactly reproduce the semantics of the interpreter.
326 static int rec_for_direction(cTValue *o)
328 return (tvisint(o) ? intV(o) : (int32_t)o->u32.hi) >= 0;
331 /* Simulate the runtime behavior of the FOR loop iterator. */
332 static LoopEvent rec_for_iter(IROp *op, cTValue *o, int isforl)
334 lua_Number stopv = numberVnum(&o[FORL_STOP]);
335 lua_Number idxv = numberVnum(&o[FORL_IDX]);
336 lua_Number stepv = numberVnum(&o[FORL_STEP]);
337 if (isforl)
338 idxv += stepv;
339 if (rec_for_direction(&o[FORL_STEP])) {
340 if (idxv <= stopv) {
341 *op = IR_LE;
342 return idxv + 2*stepv > stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
344 *op = IR_GT; return LOOPEV_LEAVE;
345 } else {
346 if (stopv <= idxv) {
347 *op = IR_GE;
348 return idxv + 2*stepv < stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
350 *op = IR_LT; return LOOPEV_LEAVE;
354 /* Record checks for FOR loop overflow and step direction. */
355 static void rec_for_check(jit_State *J, IRType t, int dir,
356 TRef stop, TRef step, int init)
358 if (!tref_isk(step)) {
359 /* Non-constant step: need a guard for the direction. */
360 TRef zero = (t == IRT_INT) ? lj_ir_kint(J, 0) : lj_ir_knum_zero(J);
361 emitir(IRTG(dir ? IR_GE : IR_LT, t), step, zero);
362 /* Add hoistable overflow checks for a narrowed FORL index. */
363 if (init && t == IRT_INT) {
364 if (tref_isk(stop)) {
365 /* Constant stop: optimize check away or to a range check for step. */
366 int32_t k = IR(tref_ref(stop))->i;
367 if (dir) {
368 if (k > 0)
369 emitir(IRTGI(IR_LE), step, lj_ir_kint(J, (int32_t)0x7fffffff-k));
370 } else {
371 if (k < 0)
372 emitir(IRTGI(IR_GE), step, lj_ir_kint(J, (int32_t)0x80000000-k));
374 } else {
375 /* Stop+step variable: need full overflow check. */
376 TRef tr = emitir(IRTGI(IR_ADDOV), step, stop);
377 emitir(IRTI(IR_USE), tr, 0); /* ADDOV is weak. Avoid dead result. */
380 } else if (init && t == IRT_INT && !tref_isk(stop)) {
381 /* Constant step: optimize overflow check to a range check for stop. */
382 int32_t k = IR(tref_ref(step))->i;
383 k = (int32_t)(dir ? 0x7fffffff : 0x80000000) - k;
384 emitir(IRTGI(dir ? IR_LE : IR_GE), stop, lj_ir_kint(J, k));
388 /* Record a FORL instruction. */
389 static void rec_for_loop(jit_State *J, const BCIns *fori, ScEvEntry *scev,
390 int init)
392 BCReg ra = bc_a(*fori);
393 cTValue *tv = &J->L->base[ra];
394 TRef idx = J->base[ra+FORL_IDX];
395 IRType t = idx ? tref_type(idx) :
396 (init || LJ_DUALNUM) ? lj_opt_narrow_forl(J, tv) : IRT_NUM;
397 int mode = IRSLOAD_INHERIT +
398 ((!LJ_DUALNUM || tvisint(tv) == (t == IRT_INT)) ? IRSLOAD_READONLY : 0);
399 TRef stop = fori_arg(J, fori, ra+FORL_STOP, t, mode);
400 TRef step = fori_arg(J, fori, ra+FORL_STEP, t, mode);
401 int tc, dir = rec_for_direction(&tv[FORL_STEP]);
402 lua_assert(bc_op(*fori) == BC_FORI || bc_op(*fori) == BC_JFORI);
403 scev->t.irt = t;
404 scev->dir = dir;
405 scev->stop = tref_ref(stop);
406 scev->step = tref_ref(step);
407 rec_for_check(J, t, dir, stop, step, init);
408 scev->start = tref_ref(find_kinit(J, fori, ra+FORL_IDX, IRT_INT));
409 tc = (LJ_DUALNUM &&
410 !(scev->start && irref_isk(scev->stop) && irref_isk(scev->step) &&
411 tvisint(&tv[FORL_IDX]) == (t == IRT_INT))) ?
412 IRSLOAD_TYPECHECK : 0;
413 if (tc) {
414 J->base[ra+FORL_STOP] = stop;
415 J->base[ra+FORL_STEP] = step;
417 if (!idx)
418 idx = fori_load(J, ra+FORL_IDX, t,
419 IRSLOAD_INHERIT + tc + (J->scev.start << 16));
420 if (!init)
421 J->base[ra+FORL_IDX] = idx = emitir(IRT(IR_ADD, t), idx, step);
422 J->base[ra+FORL_EXT] = idx;
423 scev->idx = tref_ref(idx);
424 J->maxslot = ra+FORL_EXT+1;
427 /* Record FORL/JFORL or FORI/JFORI. */
428 static LoopEvent rec_for(jit_State *J, const BCIns *fori, int isforl)
430 BCReg ra = bc_a(*fori);
431 TValue *tv = &J->L->base[ra];
432 TRef *tr = &J->base[ra];
433 IROp op;
434 LoopEvent ev;
435 TRef stop;
436 IRType t;
437 if (isforl) { /* Handle FORL/JFORL opcodes. */
438 TRef idx = tr[FORL_IDX];
439 if (tref_ref(idx) == J->scev.idx) {
440 t = J->scev.t.irt;
441 stop = J->scev.stop;
442 idx = emitir(IRT(IR_ADD, t), idx, J->scev.step);
443 tr[FORL_EXT] = tr[FORL_IDX] = idx;
444 } else {
445 ScEvEntry scev;
446 rec_for_loop(J, fori, &scev, 0);
447 t = scev.t.irt;
448 stop = scev.stop;
450 } else { /* Handle FORI/JFORI opcodes. */
451 BCReg i;
452 lj_meta_for(J->L, tv);
453 t = (LJ_DUALNUM || tref_isint(tr[FORL_IDX])) ? lj_opt_narrow_forl(J, tv) :
454 IRT_NUM;
455 for (i = FORL_IDX; i <= FORL_STEP; i++) {
456 if (!tr[i]) sload(J, ra+i);
457 lua_assert(tref_isnumber_str(tr[i]));
458 if (tref_isstr(tr[i]))
459 tr[i] = emitir(IRTG(IR_STRTO, IRT_NUM), tr[i], 0);
460 if (t == IRT_INT) {
461 if (!tref_isinteger(tr[i]))
462 tr[i] = emitir(IRTGI(IR_CONV), tr[i], IRCONV_INT_NUM|IRCONV_CHECK);
463 } else {
464 if (!tref_isnum(tr[i]))
465 tr[i] = emitir(IRTN(IR_CONV), tr[i], IRCONV_NUM_INT);
468 tr[FORL_EXT] = tr[FORL_IDX];
469 stop = tr[FORL_STOP];
470 rec_for_check(J, t, rec_for_direction(&tv[FORL_STEP]),
471 stop, tr[FORL_STEP], 1);
474 ev = rec_for_iter(&op, tv, isforl);
475 if (ev == LOOPEV_LEAVE) {
476 J->maxslot = ra+FORL_EXT+1;
477 J->pc = fori+1;
478 } else {
479 J->maxslot = ra;
480 J->pc = fori+bc_j(*fori)+1;
482 lj_snap_add(J);
484 emitir(IRTG(op, t), tr[FORL_IDX], stop);
486 if (ev == LOOPEV_LEAVE) {
487 J->maxslot = ra;
488 J->pc = fori+bc_j(*fori)+1;
489 } else {
490 J->maxslot = ra+FORL_EXT+1;
491 J->pc = fori+1;
493 J->needsnap = 1;
494 return ev;
497 /* Record ITERL/JITERL. */
498 static LoopEvent rec_iterl(jit_State *J, const BCIns iterins)
500 BCReg ra = bc_a(iterins);
501 lua_assert(J->base[ra] != 0);
502 if (!tref_isnil(J->base[ra])) { /* Looping back? */
503 J->base[ra-1] = J->base[ra]; /* Copy result of ITERC to control var. */
504 J->maxslot = ra-1+bc_b(J->pc[-1]);
505 J->pc += bc_j(iterins)+1;
506 return LOOPEV_ENTER;
507 } else {
508 J->maxslot = ra-3;
509 J->pc++;
510 return LOOPEV_LEAVE;
514 /* Record LOOP/JLOOP. Now, that was easy. */
515 static LoopEvent rec_loop(jit_State *J, BCReg ra)
517 if (ra < J->maxslot) J->maxslot = ra;
518 J->pc++;
519 return LOOPEV_ENTER;
522 /* Check if a loop repeatedly failed to trace because it didn't loop back. */
523 static int innerloopleft(jit_State *J, const BCIns *pc)
525 ptrdiff_t i;
526 for (i = 0; i < PENALTY_SLOTS; i++)
527 if (mref(J->penalty[i].pc, const BCIns) == pc) {
528 if ((J->penalty[i].reason == LJ_TRERR_LLEAVE ||
529 J->penalty[i].reason == LJ_TRERR_LINNER) &&
530 J->penalty[i].val >= 2*PENALTY_MIN)
531 return 1;
532 break;
534 return 0;
537 /* Handle the case when an interpreted loop op is hit. */
538 static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev)
540 if (J->parent == 0) {
541 if (pc == J->startpc && J->framedepth + J->retdepth == 0) {
542 /* Same loop? */
543 if (ev == LOOPEV_LEAVE) /* Must loop back to form a root trace. */
544 lj_trace_err(J, LJ_TRERR_LLEAVE);
545 rec_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Looping root trace. */
546 } else if (ev != LOOPEV_LEAVE) { /* Entering inner loop? */
547 /* It's usually better to abort here and wait until the inner loop
548 ** is traced. But if the inner loop repeatedly didn't loop back,
549 ** this indicates a low trip count. In this case try unrolling
550 ** an inner loop even in a root trace. But it's better to be a bit
551 ** more conservative here and only do it for very short loops.
553 if (bc_j(*pc) != -1 && !innerloopleft(J, pc))
554 lj_trace_err(J, LJ_TRERR_LINNER); /* Root trace hit an inner loop. */
555 if ((ev != LOOPEV_ENTERLO &&
556 J->loopref && J->cur.nins - J->loopref > 24) || --J->loopunroll < 0)
557 lj_trace_err(J, LJ_TRERR_LUNROLL); /* Limit loop unrolling. */
558 J->loopref = J->cur.nins;
560 } else if (ev != LOOPEV_LEAVE) { /* Side trace enters an inner loop. */
561 J->loopref = J->cur.nins;
562 if (--J->loopunroll < 0)
563 lj_trace_err(J, LJ_TRERR_LUNROLL); /* Limit loop unrolling. */
564 } /* Side trace continues across a loop that's left or not entered. */
567 /* Handle the case when an already compiled loop op is hit. */
568 static void rec_loop_jit(jit_State *J, TraceNo lnk, LoopEvent ev)
570 if (J->parent == 0) { /* Root trace hit an inner loop. */
571 /* Better let the inner loop spawn a side trace back here. */
572 lj_trace_err(J, LJ_TRERR_LINNER);
573 } else if (ev != LOOPEV_LEAVE) { /* Side trace enters a compiled loop. */
574 J->instunroll = 0; /* Cannot continue across a compiled loop op. */
575 if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
576 rec_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Form an extra loop. */
577 else
578 rec_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the loop. */
579 } /* Side trace continues across a loop that's left or not entered. */
582 /* -- Record calls and returns -------------------------------------------- */
584 /* Specialize to the runtime value of the called function or its prototype. */
585 static TRef rec_call_specialize(jit_State *J, GCfunc *fn, TRef tr)
587 TRef kfunc;
588 if (isluafunc(fn)) {
589 GCproto *pt = funcproto(fn);
590 /* Too many closures created? Probably not a monomorphic function. */
591 if (pt->flags >= PROTO_CLC_POLY) { /* Specialize to prototype instead. */
592 TRef trpt = emitir(IRT(IR_FLOAD, IRT_P32), tr, IRFL_FUNC_PC);
593 emitir(IRTG(IR_EQ, IRT_P32), trpt, lj_ir_kptr(J, proto_bc(pt)));
594 (void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO); /* Prevent GC of proto. */
595 return tr;
598 /* Otherwise specialize to the function (closure) value itself. */
599 kfunc = lj_ir_kfunc(J, fn);
600 emitir(IRTG(IR_EQ, IRT_FUNC), tr, kfunc);
601 return kfunc;
604 /* Record call setup. */
605 static void rec_call_setup(jit_State *J, BCReg func, ptrdiff_t nargs)
607 RecordIndex ix;
608 TValue *functv = &J->L->base[func];
609 TRef *fbase = &J->base[func];
610 ptrdiff_t i;
611 for (i = 0; i <= nargs; i++)
612 (void)getslot(J, func+i); /* Ensure func and all args have a reference. */
613 if (!tref_isfunc(fbase[0])) { /* Resolve __call metamethod. */
614 ix.tab = fbase[0];
615 copyTV(J->L, &ix.tabv, functv);
616 if (!lj_record_mm_lookup(J, &ix, MM_call) || !tref_isfunc(ix.mobj))
617 lj_trace_err(J, LJ_TRERR_NOMM);
618 for (i = ++nargs; i > 0; i--) /* Shift arguments up. */
619 fbase[i] = fbase[i-1];
620 fbase[0] = ix.mobj; /* Replace function. */
621 functv = &ix.mobjv;
623 fbase[0] = TREF_FRAME | rec_call_specialize(J, funcV(functv), fbase[0]);
624 J->maxslot = (BCReg)nargs;
627 /* Record call. */
628 void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs)
630 rec_call_setup(J, func, nargs);
631 /* Bump frame. */
632 J->framedepth++;
633 J->base += func+1;
634 J->baseslot += func+1;
637 /* Record tail call. */
638 void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs)
640 rec_call_setup(J, func, nargs);
641 if (frame_isvarg(J->L->base - 1)) {
642 BCReg cbase = (BCReg)frame_delta(J->L->base - 1);
643 if (--J->framedepth < 0)
644 lj_trace_err(J, LJ_TRERR_NYIRETL);
645 J->baseslot -= (BCReg)cbase;
646 J->base -= cbase;
647 func += cbase;
649 /* Move func + args down. */
650 memmove(&J->base[-1], &J->base[func], sizeof(TRef)*(J->maxslot+1));
651 /* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */
652 /* Tailcalls can form a loop, so count towards the loop unroll limit. */
653 if (++J->tailcalled > J->loopunroll)
654 lj_trace_err(J, LJ_TRERR_LUNROLL);
657 /* Check unroll limits for down-recursion. */
658 static int check_downrec_unroll(jit_State *J, GCproto *pt)
660 IRRef ptref;
661 for (ptref = J->chain[IR_KGC]; ptref; ptref = IR(ptref)->prev)
662 if (ir_kgc(IR(ptref)) == obj2gco(pt)) {
663 int count = 0;
664 IRRef ref;
665 for (ref = J->chain[IR_RETF]; ref; ref = IR(ref)->prev)
666 if (IR(ref)->op1 == ptref)
667 count++;
668 if (count) {
669 if (J->pc == J->startpc) {
670 if (count + J->tailcalled > J->param[JIT_P_recunroll])
671 return 1;
672 } else {
673 lj_trace_err(J, LJ_TRERR_DOWNREC);
677 return 0;
680 /* Record return. */
681 void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
683 TValue *frame = J->L->base - 1;
684 ptrdiff_t i;
685 for (i = 0; i < gotresults; i++)
686 (void)getslot(J, rbase+i); /* Ensure all results have a reference. */
687 while (frame_ispcall(frame)) { /* Immediately resolve pcall() returns. */
688 BCReg cbase = (BCReg)frame_delta(frame);
689 if (--J->framedepth < 0)
690 lj_trace_err(J, LJ_TRERR_NYIRETL);
691 lua_assert(J->baseslot > 1);
692 gotresults++;
693 rbase += cbase;
694 J->baseslot -= (BCReg)cbase;
695 J->base -= cbase;
696 J->base[--rbase] = TREF_TRUE; /* Prepend true to results. */
697 frame = frame_prevd(frame);
699 /* Return to lower frame via interpreter for unhandled cases. */
700 if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) &&
701 (!frame_islua(frame) ||
702 (J->parent == 0 && !bc_isret(bc_op(J->cur.startins))))) {
703 /* NYI: specialize to frame type and return directly, not via RET*. */
704 for (i = -1; i < (ptrdiff_t)rbase; i++)
705 J->base[i] = 0; /* Purge dead slots. */
706 J->maxslot = rbase + (BCReg)gotresults;
707 rec_stop(J, LJ_TRLINK_RETURN, 0); /* Return to interpreter. */
708 return;
710 if (frame_isvarg(frame)) {
711 BCReg cbase = (BCReg)frame_delta(frame);
712 if (--J->framedepth < 0) /* NYI: return of vararg func to lower frame. */
713 lj_trace_err(J, LJ_TRERR_NYIRETL);
714 lua_assert(J->baseslot > 1);
715 rbase += cbase;
716 J->baseslot -= (BCReg)cbase;
717 J->base -= cbase;
718 frame = frame_prevd(frame);
720 if (frame_islua(frame)) { /* Return to Lua frame. */
721 BCIns callins = *(frame_pc(frame)-1);
722 ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
723 BCReg cbase = bc_a(callins);
724 GCproto *pt = funcproto(frame_func(frame - (cbase+1)));
725 if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
726 if (check_downrec_unroll(J, pt)) {
727 J->maxslot = (BCReg)(rbase + gotresults);
728 lj_snap_purge(J);
729 rec_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno); /* Down-recursion. */
730 return;
732 lj_snap_add(J);
734 for (i = 0; i < nresults; i++) /* Adjust results. */
735 J->base[i-1] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
736 J->maxslot = cbase+(BCReg)nresults;
737 if (J->framedepth > 0) { /* Return to a frame that is part of the trace. */
738 J->framedepth--;
739 lua_assert(J->baseslot > cbase+1);
740 J->baseslot -= cbase+1;
741 J->base -= cbase+1;
742 } else if (J->parent == 0 && !bc_isret(bc_op(J->cur.startins))) {
743 /* Return to lower frame would leave the loop in a root trace. */
744 lj_trace_err(J, LJ_TRERR_LLEAVE);
745 } else { /* Return to lower frame. Guard for the target we return to. */
746 TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
747 TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
748 emitir(IRTG(IR_RETF, IRT_P32), trpt, trpc);
749 J->retdepth++;
750 J->needsnap = 1;
751 lua_assert(J->baseslot == 1);
752 /* Shift result slots up and clear the slots of the new frame below. */
753 memmove(J->base + cbase, J->base-1, sizeof(TRef)*nresults);
754 memset(J->base-1, 0, sizeof(TRef)*(cbase+1));
756 } else if (frame_iscont(frame)) { /* Return to continuation frame. */
757 ASMFunction cont = frame_contf(frame);
758 BCReg cbase = (BCReg)frame_delta(frame);
759 if ((J->framedepth -= 2) < 0)
760 lj_trace_err(J, LJ_TRERR_NYIRETL);
761 J->baseslot -= (BCReg)cbase;
762 J->base -= cbase;
763 J->maxslot = cbase-2;
764 if (cont == lj_cont_ra) {
765 /* Copy result to destination slot. */
766 BCReg dst = bc_a(*(frame_contpc(frame)-1));
767 J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
768 if (dst >= J->maxslot) J->maxslot = dst+1;
769 } else if (cont == lj_cont_nop) {
770 /* Nothing to do here. */
771 } else if (cont == lj_cont_cat) {
772 lua_assert(0);
773 } else {
774 /* Result type already specialized. */
775 lua_assert(cont == lj_cont_condf || cont == lj_cont_condt);
777 } else {
778 lj_trace_err(J, LJ_TRERR_NYIRETL); /* NYI: handle return to C frame. */
780 lua_assert(J->baseslot >= 1);
783 /* -- Metamethod handling ------------------------------------------------- */
785 /* Prepare to record call to metamethod. */
786 static BCReg rec_mm_prep(jit_State *J, ASMFunction cont)
788 BCReg s, top = curr_proto(J->L)->framesize;
789 TRef trcont;
790 setcont(&J->L->base[top], cont);
791 #if LJ_64
792 trcont = lj_ir_kptr(J, (void *)((int64_t)cont - (int64_t)lj_vm_asm_begin));
793 #else
794 trcont = lj_ir_kptr(J, (void *)cont);
795 #endif
796 J->base[top] = trcont | TREF_CONT;
797 J->framedepth++;
798 for (s = J->maxslot; s < top; s++)
799 J->base[s] = 0; /* Clear frame gap to avoid resurrecting previous refs. */
800 return top+1;
803 /* Record metamethod lookup. */
804 int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
806 RecordIndex mix;
807 GCtab *mt;
808 if (tref_istab(ix->tab)) {
809 mt = tabref(tabV(&ix->tabv)->metatable);
810 mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
811 } else if (tref_isudata(ix->tab)) {
812 int udtype = udataV(&ix->tabv)->udtype;
813 mt = tabref(udataV(&ix->tabv)->metatable);
814 /* The metatables of special userdata objects are treated as immutable. */
815 if (udtype != UDTYPE_USERDATA) {
816 cTValue *mo;
817 if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) {
818 /* Specialize to the C library namespace object. */
819 emitir(IRTG(IR_EQ, IRT_P32), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv)));
820 } else {
821 /* Specialize to the type of userdata. */
822 TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE);
823 emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, udtype));
825 immutable_mt:
826 mo = lj_tab_getstr(mt, mmname_str(J2G(J), mm));
827 if (!mo || tvisnil(mo))
828 return 0; /* No metamethod. */
829 /* Treat metamethod or index table as immutable, too. */
830 if (!(tvisfunc(mo) || tvistab(mo)))
831 lj_trace_err(J, LJ_TRERR_BADTYPE);
832 copyTV(J->L, &ix->mobjv, mo);
833 ix->mobj = lj_ir_kgc(J, gcV(mo), tvisfunc(mo) ? IRT_FUNC : IRT_TAB);
834 ix->mtv = mt;
835 ix->mt = TREF_NIL; /* Dummy value for comparison semantics. */
836 return 1; /* Got metamethod or index table. */
838 mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_UDATA_META);
839 } else {
840 /* Specialize to base metatable. Must flush mcode in lua_setmetatable(). */
841 mt = tabref(basemt_obj(J2G(J), &ix->tabv));
842 if (mt == NULL) {
843 ix->mt = TREF_NIL;
844 return 0; /* No metamethod. */
846 /* The cdata metatable is treated as immutable. */
847 if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt;
848 ix->mt = mix.tab = lj_ir_ktab(J, mt);
849 goto nocheck;
851 ix->mt = mt ? mix.tab : TREF_NIL;
852 emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mix.tab, lj_ir_knull(J, IRT_TAB));
853 nocheck:
854 if (mt) {
855 GCstr *mmstr = mmname_str(J2G(J), mm);
856 cTValue *mo = lj_tab_getstr(mt, mmstr);
857 if (mo && !tvisnil(mo))
858 copyTV(J->L, &ix->mobjv, mo);
859 ix->mtv = mt;
860 settabV(J->L, &mix.tabv, mt);
861 setstrV(J->L, &mix.keyv, mmstr);
862 mix.key = lj_ir_kstr(J, mmstr);
863 mix.val = 0;
864 mix.idxchain = 0;
865 ix->mobj = lj_record_idx(J, &mix);
866 return !tref_isnil(ix->mobj); /* 1 if metamethod found, 0 if not. */
868 return 0; /* No metamethod. */
871 /* Record call to arithmetic metamethod. */
872 static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
874 /* Set up metamethod call first to save ix->tab and ix->tabv. */
875 BCReg func = rec_mm_prep(J, lj_cont_ra);
876 TRef *base = J->base + func;
877 TValue *basev = J->L->base + func;
878 base[1] = ix->tab; base[2] = ix->key;
879 copyTV(J->L, basev+1, &ix->tabv);
880 copyTV(J->L, basev+2, &ix->keyv);
881 if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
882 if (mm != MM_unm) {
883 ix->tab = ix->key;
884 copyTV(J->L, &ix->tabv, &ix->keyv);
885 if (lj_record_mm_lookup(J, ix, mm)) /* Lookup mm on 2nd operand. */
886 goto ok;
888 lj_trace_err(J, LJ_TRERR_NOMM);
891 base[0] = ix->mobj;
892 copyTV(J->L, basev+0, &ix->mobjv);
893 lj_record_call(J, func, 2);
894 return 0; /* No result yet. */
897 /* Record call to __len metamethod. */
898 static TRef rec_mm_len(jit_State *J, TRef tr, TValue *tv)
900 RecordIndex ix;
901 ix.tab = tr;
902 copyTV(J->L, &ix.tabv, tv);
903 if (lj_record_mm_lookup(J, &ix, MM_len)) {
904 BCReg func = rec_mm_prep(J, lj_cont_ra);
905 TRef *base = J->base + func;
906 TValue *basev = J->L->base + func;
907 base[0] = ix.mobj; copyTV(J->L, basev+0, &ix.mobjv);
908 base[1] = tr; copyTV(J->L, basev+1, tv);
909 #if LJ_52
910 base[2] = tr; copyTV(J->L, basev+2, tv);
911 #else
912 base[2] = TREF_NIL; setnilV(basev+2);
913 #endif
914 lj_record_call(J, func, 2);
915 } else {
916 if (LJ_52 && tref_istab(tr))
917 return lj_ir_call(J, IRCALL_lj_tab_len, tr);
918 lj_trace_err(J, LJ_TRERR_NOMM);
920 return 0; /* No result yet. */
923 /* Call a comparison metamethod. */
924 static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op)
926 BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt);
927 TRef *base = J->base + func;
928 TValue *tv = J->L->base + func;
929 base[0] = ix->mobj; base[1] = ix->val; base[2] = ix->key;
930 copyTV(J->L, tv+0, &ix->mobjv);
931 copyTV(J->L, tv+1, &ix->valv);
932 copyTV(J->L, tv+2, &ix->keyv);
933 lj_record_call(J, func, 2);
936 /* Record call to equality comparison metamethod (for tab and udata only). */
937 static void rec_mm_equal(jit_State *J, RecordIndex *ix, int op)
939 ix->tab = ix->val;
940 copyTV(J->L, &ix->tabv, &ix->valv);
941 if (lj_record_mm_lookup(J, ix, MM_eq)) { /* Lookup mm on 1st operand. */
942 cTValue *bv;
943 TRef mo1 = ix->mobj;
944 TValue mo1v;
945 copyTV(J->L, &mo1v, &ix->mobjv);
946 /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
947 bv = &ix->keyv;
948 if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
949 TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
950 emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
951 } else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
952 TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
953 emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
954 } else { /* Lookup metamethod on 2nd operand and compare both. */
955 ix->tab = ix->key;
956 copyTV(J->L, &ix->tabv, bv);
957 if (!lj_record_mm_lookup(J, ix, MM_eq) ||
958 lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
959 return;
961 rec_mm_callcomp(J, ix, op);
965 /* Record call to ordered comparison metamethods (for arbitrary objects). */
966 static void rec_mm_comp(jit_State *J, RecordIndex *ix, int op)
968 ix->tab = ix->val;
969 copyTV(J->L, &ix->tabv, &ix->valv);
970 while (1) {
971 MMS mm = (op & 2) ? MM_le : MM_lt; /* Try __le + __lt or only __lt. */
972 #if LJ_52
973 if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
974 ix->tab = ix->key;
975 copyTV(J->L, &ix->tabv, &ix->keyv);
976 if (!lj_record_mm_lookup(J, ix, mm)) /* Lookup mm on 2nd operand. */
977 goto nomatch;
979 rec_mm_callcomp(J, ix, op);
980 return;
981 #else
982 if (lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
983 cTValue *bv;
984 TRef mo1 = ix->mobj;
985 TValue mo1v;
986 copyTV(J->L, &mo1v, &ix->mobjv);
987 /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
988 bv = &ix->keyv;
989 if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
990 TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
991 emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
992 } else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
993 TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
994 emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
995 } else { /* Lookup metamethod on 2nd operand and compare both. */
996 ix->tab = ix->key;
997 copyTV(J->L, &ix->tabv, bv);
998 if (!lj_record_mm_lookup(J, ix, mm) ||
999 lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
1000 goto nomatch;
1002 rec_mm_callcomp(J, ix, op);
1003 return;
1005 #endif
1006 nomatch:
1007 /* Lookup failed. Retry with __lt and swapped operands. */
1008 if (!(op & 2)) break; /* Already at __lt. Interpreter will throw. */
1009 ix->tab = ix->key; ix->key = ix->val; ix->val = ix->tab;
1010 copyTV(J->L, &ix->tabv, &ix->keyv);
1011 copyTV(J->L, &ix->keyv, &ix->valv);
1012 copyTV(J->L, &ix->valv, &ix->tabv);
1013 op ^= 3;
1017 #if LJ_HASFFI
1018 /* Setup call to cdata comparison metamethod. */
1019 static void rec_mm_comp_cdata(jit_State *J, RecordIndex *ix, int op, MMS mm)
1021 lj_snap_add(J);
1022 if (tref_iscdata(ix->val)) {
1023 ix->tab = ix->val;
1024 copyTV(J->L, &ix->tabv, &ix->valv);
1025 } else {
1026 lua_assert(tref_iscdata(ix->key));
1027 ix->tab = ix->key;
1028 copyTV(J->L, &ix->tabv, &ix->keyv);
1030 lj_record_mm_lookup(J, ix, mm);
1031 rec_mm_callcomp(J, ix, op);
1033 #endif
1035 /* -- Indexed access ------------------------------------------------------ */
1037 /* Record bounds-check. */
1038 static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize)
1040 /* Try to emit invariant bounds checks. */
1041 if ((J->flags & (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) ==
1042 (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) {
1043 IRRef ref = tref_ref(ikey);
1044 IRIns *ir = IR(ref);
1045 int32_t ofs = 0;
1046 IRRef ofsref = 0;
1047 /* Handle constant offsets. */
1048 if (ir->o == IR_ADD && irref_isk(ir->op2)) {
1049 ofsref = ir->op2;
1050 ofs = IR(ofsref)->i;
1051 ref = ir->op1;
1052 ir = IR(ref);
1054 /* Got scalar evolution analysis results for this reference? */
1055 if (ref == J->scev.idx) {
1056 int32_t stop;
1057 lua_assert(irt_isint(J->scev.t) && ir->o == IR_SLOAD);
1058 stop = numberVint(&(J->L->base - J->baseslot)[ir->op1 + FORL_STOP]);
1059 /* Runtime value for stop of loop is within bounds? */
1060 if ((int64_t)stop + ofs < (int64_t)asize) {
1061 /* Emit invariant bounds check for stop. */
1062 emitir(IRTG(IR_ABC, IRT_P32), asizeref, ofs == 0 ? J->scev.stop :
1063 emitir(IRTI(IR_ADD), J->scev.stop, ofsref));
1064 /* Emit invariant bounds check for start, if not const or negative. */
1065 if (!(J->scev.dir && J->scev.start &&
1066 (int64_t)IR(J->scev.start)->i + ofs >= 0))
1067 emitir(IRTG(IR_ABC, IRT_P32), asizeref, ikey);
1068 return;
1072 emitir(IRTGI(IR_ABC), asizeref, ikey); /* Emit regular bounds check. */
1075 /* Record indexed key lookup. */
1076 static TRef rec_idx_key(jit_State *J, RecordIndex *ix)
1078 TRef key;
1079 GCtab *t = tabV(&ix->tabv);
1080 ix->oldv = lj_tab_get(J->L, t, &ix->keyv); /* Lookup previous value. */
1082 /* Integer keys are looked up in the array part first. */
1083 key = ix->key;
1084 if (tref_isnumber(key)) {
1085 int32_t k = numberVint(&ix->keyv);
1086 if (!tvisint(&ix->keyv) && numV(&ix->keyv) != (lua_Number)k)
1087 k = LJ_MAX_ASIZE;
1088 if ((MSize)k < LJ_MAX_ASIZE) { /* Potential array key? */
1089 TRef ikey = lj_opt_narrow_index(J, key);
1090 TRef asizeref = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
1091 if ((MSize)k < t->asize) { /* Currently an array key? */
1092 TRef arrayref;
1093 rec_idx_abc(J, asizeref, ikey, t->asize);
1094 arrayref = emitir(IRT(IR_FLOAD, IRT_P32), ix->tab, IRFL_TAB_ARRAY);
1095 return emitir(IRT(IR_AREF, IRT_P32), arrayref, ikey);
1096 } else { /* Currently not in array (may be an array extension)? */
1097 emitir(IRTGI(IR_ULE), asizeref, ikey); /* Inv. bounds check. */
1098 if (k == 0 && tref_isk(key))
1099 key = lj_ir_knum_zero(J); /* Canonicalize 0 or +-0.0 to +0.0. */
1100 /* And continue with the hash lookup. */
1102 } else if (!tref_isk(key)) {
1103 /* We can rule out const numbers which failed the integerness test
1104 ** above. But all other numbers are potential array keys.
1106 if (t->asize == 0) { /* True sparse tables have an empty array part. */
1107 /* Guard that the array part stays empty. */
1108 TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
1109 emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
1110 } else {
1111 lj_trace_err(J, LJ_TRERR_NYITMIX);
1116 /* Otherwise the key is located in the hash part. */
1117 if (t->hmask == 0) { /* Shortcut for empty hash part. */
1118 /* Guard that the hash part stays empty. */
1119 TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
1120 emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
1121 return lj_ir_kkptr(J, niltvg(J2G(J)));
1123 if (tref_isinteger(key)) /* Hash keys are based on numbers, not ints. */
1124 ix->key = key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
1125 if (tref_isk(key)) {
1126 /* Optimize lookup of constant hash keys. */
1127 MSize hslot = (MSize)((char *)ix->oldv - (char *)&noderef(t->node)[0].val);
1128 if (t->hmask > 0 && hslot <= t->hmask*(MSize)sizeof(Node) &&
1129 hslot <= 65535*(MSize)sizeof(Node)) {
1130 TRef node, kslot;
1131 TRef hm = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
1132 emitir(IRTGI(IR_EQ), hm, lj_ir_kint(J, (int32_t)t->hmask));
1133 node = emitir(IRT(IR_FLOAD, IRT_P32), ix->tab, IRFL_TAB_NODE);
1134 kslot = lj_ir_kslot(J, key, hslot / sizeof(Node));
1135 return emitir(IRTG(IR_HREFK, IRT_P32), node, kslot);
1138 /* Fall back to a regular hash lookup. */
1139 return emitir(IRT(IR_HREF, IRT_P32), ix->tab, key);
1142 /* Determine whether a key is NOT one of the fast metamethod names. */
1143 static int nommstr(jit_State *J, TRef key)
1145 if (tref_isstr(key)) {
1146 if (tref_isk(key)) {
1147 GCstr *str = ir_kstr(IR(tref_ref(key)));
1148 uint32_t mm;
1149 for (mm = 0; mm <= MM_FAST; mm++)
1150 if (mmname_str(J2G(J), mm) == str)
1151 return 0; /* MUST be one the fast metamethod names. */
1152 } else {
1153 return 0; /* Variable string key MAY be a metamethod name. */
1156 return 1; /* CANNOT be a metamethod name. */
1159 /* Record indexed load/store. */
1160 TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1162 TRef xref;
1163 IROp xrefop, loadop;
1164 cTValue *oldv;
1166 while (!tref_istab(ix->tab)) { /* Handle non-table lookup. */
1167 /* Never call raw lj_record_idx() on non-table. */
1168 lua_assert(ix->idxchain != 0);
1169 if (!lj_record_mm_lookup(J, ix, ix->val ? MM_newindex : MM_index))
1170 lj_trace_err(J, LJ_TRERR_NOMM);
1171 handlemm:
1172 if (tref_isfunc(ix->mobj)) { /* Handle metamethod call. */
1173 BCReg func = rec_mm_prep(J, ix->val ? lj_cont_nop : lj_cont_ra);
1174 TRef *base = J->base + func;
1175 TValue *tv = J->L->base + func;
1176 base[0] = ix->mobj; base[1] = ix->tab; base[2] = ix->key;
1177 setfuncV(J->L, tv+0, funcV(&ix->mobjv));
1178 copyTV(J->L, tv+1, &ix->tabv);
1179 copyTV(J->L, tv+2, &ix->keyv);
1180 if (ix->val) {
1181 base[3] = ix->val;
1182 copyTV(J->L, tv+3, &ix->valv);
1183 lj_record_call(J, func, 3); /* mobj(tab, key, val) */
1184 return 0;
1185 } else {
1186 lj_record_call(J, func, 2); /* res = mobj(tab, key) */
1187 return 0; /* No result yet. */
1190 /* Otherwise retry lookup with metaobject. */
1191 ix->tab = ix->mobj;
1192 copyTV(J->L, &ix->tabv, &ix->mobjv);
1193 if (--ix->idxchain == 0)
1194 lj_trace_err(J, LJ_TRERR_IDXLOOP);
1197 /* First catch nil and NaN keys for tables. */
1198 if (tvisnil(&ix->keyv) || (tvisnum(&ix->keyv) && tvisnan(&ix->keyv))) {
1199 if (ix->val) /* Better fail early. */
1200 lj_trace_err(J, LJ_TRERR_STORENN);
1201 if (tref_isk(ix->key)) {
1202 if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
1203 goto handlemm;
1204 return TREF_NIL;
1208 /* Record the key lookup. */
1209 xref = rec_idx_key(J, ix);
1210 xrefop = IR(tref_ref(xref))->o;
1211 loadop = xrefop == IR_AREF ? IR_ALOAD : IR_HLOAD;
1212 /* The lj_meta_tset() inconsistency is gone, but better play safe. */
1213 oldv = xrefop == IR_KKPTR ? (cTValue *)ir_kptr(IR(tref_ref(xref))) : ix->oldv;
1215 if (ix->val == 0) { /* Indexed load */
1216 IRType t = itype2irt(oldv);
1217 TRef res;
1218 if (oldv == niltvg(J2G(J))) {
1219 emitir(IRTG(IR_EQ, IRT_P32), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1220 res = TREF_NIL;
1221 } else {
1222 res = emitir(IRTG(loadop, t), xref, 0);
1224 if (t == IRT_NIL && ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
1225 goto handlemm;
1226 if (irtype_ispri(t)) res = TREF_PRI(t); /* Canonicalize primitives. */
1227 return res;
1228 } else { /* Indexed store. */
1229 GCtab *mt = tabref(tabV(&ix->tabv)->metatable);
1230 int keybarrier = tref_isgcv(ix->key) && !tref_isnil(ix->val);
1231 if (tvisnil(oldv)) { /* Previous value was nil? */
1232 /* Need to duplicate the hasmm check for the early guards. */
1233 int hasmm = 0;
1234 if (ix->idxchain && mt) {
1235 cTValue *mo = lj_tab_getstr(mt, mmname_str(J2G(J), MM_newindex));
1236 hasmm = mo && !tvisnil(mo);
1238 if (hasmm)
1239 emitir(IRTG(loadop, IRT_NIL), xref, 0); /* Guard for nil value. */
1240 else if (xrefop == IR_HREF)
1241 emitir(IRTG(oldv == niltvg(J2G(J)) ? IR_EQ : IR_NE, IRT_P32),
1242 xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1243 if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_newindex)) {
1244 lua_assert(hasmm);
1245 goto handlemm;
1247 lua_assert(!hasmm);
1248 if (oldv == niltvg(J2G(J))) { /* Need to insert a new key. */
1249 TRef key = ix->key;
1250 if (tref_isinteger(key)) /* NEWREF needs a TValue as a key. */
1251 key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
1252 xref = emitir(IRT(IR_NEWREF, IRT_P32), ix->tab, key);
1253 keybarrier = 0; /* NEWREF already takes care of the key barrier. */
1255 } else if (!lj_opt_fwd_wasnonnil(J, loadop, tref_ref(xref))) {
1256 /* Cannot derive that the previous value was non-nil, must do checks. */
1257 if (xrefop == IR_HREF) /* Guard against store to niltv. */
1258 emitir(IRTG(IR_NE, IRT_P32), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1259 if (ix->idxchain) { /* Metamethod lookup required? */
1260 /* A check for NULL metatable is cheaper (hoistable) than a load. */
1261 if (!mt) {
1262 TRef mtref = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
1263 emitir(IRTG(IR_EQ, IRT_TAB), mtref, lj_ir_knull(J, IRT_TAB));
1264 } else {
1265 IRType t = itype2irt(oldv);
1266 emitir(IRTG(loadop, t), xref, 0); /* Guard for non-nil value. */
1269 } else {
1270 keybarrier = 0; /* Previous non-nil value kept the key alive. */
1272 /* Convert int to number before storing. */
1273 if (!LJ_DUALNUM && tref_isinteger(ix->val))
1274 ix->val = emitir(IRTN(IR_CONV), ix->val, IRCONV_NUM_INT);
1275 emitir(IRT(loadop+IRDELTA_L2S, tref_type(ix->val)), xref, ix->val);
1276 if (keybarrier || tref_isgcv(ix->val))
1277 emitir(IRT(IR_TBAR, IRT_NIL), ix->tab, 0);
1278 /* Invalidate neg. metamethod cache for stores with certain string keys. */
1279 if (!nommstr(J, ix->key)) {
1280 TRef fref = emitir(IRT(IR_FREF, IRT_P32), ix->tab, IRFL_TAB_NOMM);
1281 emitir(IRT(IR_FSTORE, IRT_U8), fref, lj_ir_kint(J, 0));
1283 J->needsnap = 1;
1284 return 0;
1288 /* -- Upvalue access ------------------------------------------------------ */
1290 /* Check whether upvalue is immutable and ok to constify. */
1291 static int rec_upvalue_constify(jit_State *J, GCupval *uvp)
1293 if (uvp->immutable) {
1294 cTValue *o = uvval(uvp);
1295 /* Don't constify objects that may retain large amounts of memory. */
1296 #if LJ_HASFFI
1297 if (tviscdata(o)) {
1298 GCcdata *cd = cdataV(o);
1299 if (!cdataisv(cd) && !(cd->marked & LJ_GC_CDATA_FIN)) {
1300 CType *ct = ctype_raw(ctype_ctsG(J2G(J)), cd->ctypeid);
1301 if (!ctype_hassize(ct->info) || ct->size <= 16)
1302 return 1;
1304 return 0;
1306 #else
1307 UNUSED(J);
1308 #endif
1309 if (!(tvistab(o) || tvisudata(o) || tvisthread(o)))
1310 return 1;
1312 return 0;
1315 /* Record upvalue load/store. */
1316 static TRef rec_upvalue(jit_State *J, uint32_t uv, TRef val)
1318 GCupval *uvp = &gcref(J->fn->l.uvptr[uv])->uv;
1319 TRef fn = getcurrf(J);
1320 IRRef uref;
1321 int needbarrier = 0;
1322 if (rec_upvalue_constify(J, uvp)) { /* Try to constify immutable upvalue. */
1323 TRef tr, kfunc;
1324 lua_assert(val == 0);
1325 if (!tref_isk(fn)) { /* Late specialization of current function. */
1326 if (J->pt->flags >= PROTO_CLC_POLY)
1327 goto noconstify;
1328 kfunc = lj_ir_kfunc(J, J->fn);
1329 emitir(IRTG(IR_EQ, IRT_FUNC), fn, kfunc);
1330 J->base[-1] = TREF_FRAME | kfunc;
1331 fn = kfunc;
1333 tr = lj_record_constify(J, uvval(uvp));
1334 if (tr)
1335 return tr;
1337 noconstify:
1338 /* Note: this effectively limits LJ_MAX_UPVAL to 127. */
1339 uv = (uv << 8) | (hashrot(uvp->dhash, uvp->dhash + HASH_BIAS) & 0xff);
1340 if (!uvp->closed) {
1341 /* In current stack? */
1342 if (uvval(uvp) >= tvref(J->L->stack) &&
1343 uvval(uvp) < tvref(J->L->maxstack)) {
1344 int32_t slot = (int32_t)(uvval(uvp) - (J->L->base - J->baseslot));
1345 if (slot >= 0) { /* Aliases an SSA slot? */
1346 slot -= (int32_t)J->baseslot; /* Note: slot number may be negative! */
1347 /* NYI: add IR to guard that it's still aliasing the same slot. */
1348 if (val == 0) {
1349 return getslot(J, slot);
1350 } else {
1351 J->base[slot] = val;
1352 if (slot >= (int32_t)J->maxslot) J->maxslot = (BCReg)(slot+1);
1353 return 0;
1357 uref = tref_ref(emitir(IRTG(IR_UREFO, IRT_P32), fn, uv));
1358 } else {
1359 needbarrier = 1;
1360 uref = tref_ref(emitir(IRTG(IR_UREFC, IRT_P32), fn, uv));
1362 if (val == 0) { /* Upvalue load */
1363 IRType t = itype2irt(uvval(uvp));
1364 TRef res = emitir(IRTG(IR_ULOAD, t), uref, 0);
1365 if (irtype_ispri(t)) res = TREF_PRI(t); /* Canonicalize primitive refs. */
1366 return res;
1367 } else { /* Upvalue store. */
1368 /* Convert int to number before storing. */
1369 if (!LJ_DUALNUM && tref_isinteger(val))
1370 val = emitir(IRTN(IR_CONV), val, IRCONV_NUM_INT);
1371 emitir(IRT(IR_USTORE, tref_type(val)), uref, val);
1372 if (needbarrier && tref_isgcv(val))
1373 emitir(IRT(IR_OBAR, IRT_NIL), uref, val);
1374 J->needsnap = 1;
1375 return 0;
1379 /* -- Record calls to Lua functions --------------------------------------- */
1381 /* Check unroll limits for calls. */
1382 static void check_call_unroll(jit_State *J, TraceNo lnk)
1384 cTValue *frame = J->L->base - 1;
1385 void *pc = mref(frame_func(frame)->l.pc, void);
1386 int32_t depth = J->framedepth;
1387 int32_t count = 0;
1388 if ((J->pt->flags & PROTO_VARARG)) depth--; /* Vararg frame still missing. */
1389 for (; depth > 0; depth--) { /* Count frames with same prototype. */
1390 frame = frame_prev(frame);
1391 if (mref(frame_func(frame)->l.pc, void) == pc)
1392 count++;
1394 if (J->pc == J->startpc) {
1395 if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
1396 J->pc++;
1397 if (J->framedepth + J->retdepth == 0)
1398 rec_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Tail-recursion. */
1399 else
1400 rec_stop(J, LJ_TRLINK_UPREC, J->cur.traceno); /* Up-recursion. */
1402 } else {
1403 if (count > J->param[JIT_P_callunroll]) {
1404 if (lnk) { /* Possible tail- or up-recursion. */
1405 lj_trace_flush(J, lnk); /* Flush trace that only returns. */
1406 /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
1407 hotcount_set(J2GG(J), J->pc+1, LJ_PRNG_BITS(J, 4));
1409 lj_trace_err(J, LJ_TRERR_CUNROLL);
1414 /* Record Lua function setup. */
1415 static void rec_func_setup(jit_State *J)
1417 GCproto *pt = J->pt;
1418 BCReg s, numparams = pt->numparams;
1419 if ((pt->flags & PROTO_NOJIT))
1420 lj_trace_err(J, LJ_TRERR_CJITOFF);
1421 if (J->baseslot + pt->framesize >= LJ_MAX_JSLOTS)
1422 lj_trace_err(J, LJ_TRERR_STACKOV);
1423 /* Fill up missing parameters with nil. */
1424 for (s = J->maxslot; s < numparams; s++)
1425 J->base[s] = TREF_NIL;
1426 /* The remaining slots should never be read before they are written. */
1427 J->maxslot = numparams;
1430 /* Record Lua vararg function setup. */
1431 static void rec_func_vararg(jit_State *J)
1433 GCproto *pt = J->pt;
1434 BCReg s, fixargs, vframe = J->maxslot+1;
1435 lua_assert((pt->flags & PROTO_VARARG));
1436 if (J->baseslot + vframe + pt->framesize >= LJ_MAX_JSLOTS)
1437 lj_trace_err(J, LJ_TRERR_STACKOV);
1438 J->base[vframe-1] = J->base[-1]; /* Copy function up. */
1439 /* Copy fixarg slots up and set their original slots to nil. */
1440 fixargs = pt->numparams < J->maxslot ? pt->numparams : J->maxslot;
1441 for (s = 0; s < fixargs; s++) {
1442 J->base[vframe+s] = J->base[s];
1443 J->base[s] = TREF_NIL;
1445 J->maxslot = fixargs;
1446 J->framedepth++;
1447 J->base += vframe;
1448 J->baseslot += vframe;
1451 /* Record entry to a Lua function. */
1452 static void rec_func_lua(jit_State *J)
1454 rec_func_setup(J);
1455 check_call_unroll(J, 0);
1458 /* Record entry to an already compiled function. */
1459 static void rec_func_jit(jit_State *J, TraceNo lnk)
1461 GCtrace *T;
1462 rec_func_setup(J);
1463 T = traceref(J, lnk);
1464 if (T->linktype == LJ_TRLINK_RETURN) { /* Trace returns to interpreter? */
1465 check_call_unroll(J, lnk);
1466 /* Temporarily unpatch JFUNC* to continue recording across function. */
1467 J->patchins = *J->pc;
1468 J->patchpc = (BCIns *)J->pc;
1469 *J->patchpc = T->startins;
1470 return;
1472 J->instunroll = 0; /* Cannot continue across a compiled function. */
1473 if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
1474 rec_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Extra tail-recursion. */
1475 else
1476 rec_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the function. */
1479 /* -- Vararg handling ----------------------------------------------------- */
1481 /* Detect y = select(x, ...) idiom. */
1482 static int select_detect(jit_State *J)
1484 BCIns ins = J->pc[1];
1485 if (bc_op(ins) == BC_CALLM && bc_b(ins) == 2 && bc_c(ins) == 1) {
1486 cTValue *func = &J->L->base[bc_a(ins)];
1487 if (tvisfunc(func) && funcV(func)->c.ffid == FF_select)
1488 return 1;
1490 return 0;
1493 /* Record vararg instruction. */
1494 static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
1496 int32_t numparams = J->pt->numparams;
1497 ptrdiff_t nvararg = frame_delta(J->L->base-1) - numparams - 1;
1498 lua_assert(frame_isvarg(J->L->base-1));
1499 if (J->framedepth > 0) { /* Simple case: varargs defined on-trace. */
1500 ptrdiff_t i;
1501 if (nvararg < 0) nvararg = 0;
1502 if (nresults == -1) {
1503 nresults = nvararg;
1504 J->maxslot = dst + (BCReg)nvararg;
1505 } else if (dst + nresults > J->maxslot) {
1506 J->maxslot = dst + (BCReg)nresults;
1508 for (i = 0; i < nresults; i++) {
1509 J->base[dst+i] = i < nvararg ? J->base[i - nvararg - 1] : TREF_NIL;
1510 lua_assert(J->base[dst+i] != 0);
1512 } else { /* Unknown number of varargs passed to trace. */
1513 TRef fr = emitir(IRTI(IR_SLOAD), 0, IRSLOAD_READONLY|IRSLOAD_FRAME);
1514 int32_t frofs = 8*(1+numparams)+FRAME_VARG;
1515 if (nresults >= 0) { /* Known fixed number of results. */
1516 ptrdiff_t i;
1517 if (nvararg > 0) {
1518 ptrdiff_t nload = nvararg >= nresults ? nresults : nvararg;
1519 TRef vbase;
1520 if (nvararg >= nresults)
1521 emitir(IRTGI(IR_GE), fr, lj_ir_kint(J, frofs+8*(int32_t)nresults));
1522 else
1523 emitir(IRTGI(IR_EQ), fr, lj_ir_kint(J, frame_ftsz(J->L->base-1)));
1524 vbase = emitir(IRTI(IR_SUB), REF_BASE, fr);
1525 vbase = emitir(IRT(IR_ADD, IRT_P32), vbase, lj_ir_kint(J, frofs-8));
1526 for (i = 0; i < nload; i++) {
1527 IRType t = itype2irt(&J->L->base[i-1-nvararg]);
1528 TRef aref = emitir(IRT(IR_AREF, IRT_P32),
1529 vbase, lj_ir_kint(J, (int32_t)i));
1530 TRef tr = emitir(IRTG(IR_VLOAD, t), aref, 0);
1531 if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */
1532 J->base[dst+i] = tr;
1534 } else {
1535 emitir(IRTGI(IR_LE), fr, lj_ir_kint(J, frofs));
1536 nvararg = 0;
1538 for (i = nvararg; i < nresults; i++)
1539 J->base[dst+i] = TREF_NIL;
1540 if (dst + (BCReg)nresults > J->maxslot)
1541 J->maxslot = dst + (BCReg)nresults;
1542 } else if (select_detect(J)) { /* y = select(x, ...) */
1543 TRef tridx = J->base[dst-1];
1544 TRef tr = TREF_NIL;
1545 ptrdiff_t idx = lj_ffrecord_select_mode(J, tridx, &J->L->base[dst-1]);
1546 if (idx < 0) goto nyivarg;
1547 if (idx != 0 && !tref_isinteger(tridx))
1548 tridx = emitir(IRTGI(IR_CONV), tridx, IRCONV_INT_NUM|IRCONV_INDEX);
1549 if (idx != 0 && tref_isk(tridx)) {
1550 emitir(IRTGI(idx <= nvararg ? IR_GE : IR_LT),
1551 fr, lj_ir_kint(J, frofs+8*(int32_t)idx));
1552 frofs -= 8; /* Bias for 1-based index. */
1553 } else if (idx <= nvararg) { /* Compute size. */
1554 TRef tmp = emitir(IRTI(IR_ADD), fr, lj_ir_kint(J, -frofs));
1555 if (numparams)
1556 emitir(IRTGI(IR_GE), tmp, lj_ir_kint(J, 0));
1557 tr = emitir(IRTI(IR_BSHR), tmp, lj_ir_kint(J, 3));
1558 if (idx != 0) {
1559 tridx = emitir(IRTI(IR_ADD), tridx, lj_ir_kint(J, -1));
1560 rec_idx_abc(J, tr, tridx, (uint32_t)nvararg);
1562 } else {
1563 TRef tmp = lj_ir_kint(J, frofs);
1564 if (idx != 0) {
1565 TRef tmp2 = emitir(IRTI(IR_BSHL), tridx, lj_ir_kint(J, 3));
1566 tmp = emitir(IRTI(IR_ADD), tmp2, tmp);
1567 } else {
1568 tr = lj_ir_kint(J, 0);
1570 emitir(IRTGI(IR_LT), fr, tmp);
1572 if (idx != 0 && idx <= nvararg) {
1573 IRType t;
1574 TRef aref, vbase = emitir(IRTI(IR_SUB), REF_BASE, fr);
1575 vbase = emitir(IRT(IR_ADD, IRT_P32), vbase, lj_ir_kint(J, frofs-8));
1576 t = itype2irt(&J->L->base[idx-2-nvararg]);
1577 aref = emitir(IRT(IR_AREF, IRT_P32), vbase, tridx);
1578 tr = emitir(IRTG(IR_VLOAD, t), aref, 0);
1579 if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */
1581 J->base[dst-2] = tr;
1582 J->maxslot = dst-1;
1583 J->bcskip = 2; /* Skip CALLM + select. */
1584 } else {
1585 nyivarg:
1586 setintV(&J->errinfo, BC_VARG);
1587 lj_trace_err_info(J, LJ_TRERR_NYIBC);
1592 /* -- Record allocations -------------------------------------------------- */
1594 static TRef rec_tnew(jit_State *J, uint32_t ah)
1596 uint32_t asize = ah & 0x7ff;
1597 uint32_t hbits = ah >> 11;
1598 if (asize == 0x7ff) asize = 0x801;
1599 return emitir(IRTG(IR_TNEW, IRT_TAB), asize, hbits);
1602 /* -- Record bytecode ops ------------------------------------------------- */
1604 /* Prepare for comparison. */
1605 static void rec_comp_prep(jit_State *J)
1607 /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
1608 if (J->cur.nsnap == 1 && J->cur.snap[0].ref == J->cur.nins)
1609 emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
1610 lj_snap_add(J);
1613 /* Fixup comparison. */
1614 static void rec_comp_fixup(jit_State *J, const BCIns *pc, int cond)
1616 BCIns jmpins = pc[1];
1617 const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0);
1618 SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
1619 /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
1620 J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc);
1621 J->needsnap = 1;
1622 if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins);
1623 lj_snap_shrink(J); /* Shrink last snapshot if possible. */
1626 /* Record the next bytecode instruction (_before_ it's executed). */
1627 void lj_record_ins(jit_State *J)
1629 cTValue *lbase;
1630 RecordIndex ix;
1631 const BCIns *pc;
1632 BCIns ins;
1633 BCOp op;
1634 TRef ra, rb, rc;
1636 /* Perform post-processing action before recording the next instruction. */
1637 if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) {
1638 switch (J->postproc) {
1639 case LJ_POST_FIXCOMP: /* Fixup comparison. */
1640 pc = frame_pc(&J2G(J)->tmptv);
1641 rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1)));
1642 /* fallthrough */
1643 case LJ_POST_FIXGUARD: /* Fixup and emit pending guard. */
1644 case LJ_POST_FIXGUARDSNAP: /* Fixup and emit pending guard and snapshot. */
1645 if (!tvistruecond(&J2G(J)->tmptv2)) {
1646 J->fold.ins.o ^= 1; /* Flip guard to opposite. */
1647 if (J->postproc == LJ_POST_FIXGUARDSNAP) {
1648 SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
1649 J->cur.snapmap[snap->mapofs+snap->nent-1]--; /* False -> true. */
1652 lj_opt_fold(J); /* Emit pending guard. */
1653 /* fallthrough */
1654 case LJ_POST_FIXBOOL:
1655 if (!tvistruecond(&J2G(J)->tmptv2)) {
1656 BCReg s;
1657 TValue *tv = J->L->base;
1658 for (s = 0; s < J->maxslot; s++) /* Fixup stack slot (if any). */
1659 if (J->base[s] == TREF_TRUE && tvisfalse(&tv[s])) {
1660 J->base[s] = TREF_FALSE;
1661 break;
1664 break;
1665 case LJ_POST_FIXCONST:
1667 BCReg s;
1668 TValue *tv = J->L->base;
1669 for (s = 0; s < J->maxslot; s++) /* Constify stack slots (if any). */
1670 if (J->base[s] == TREF_NIL && !tvisnil(&tv[s]))
1671 J->base[s] = lj_record_constify(J, &tv[s]);
1673 break;
1674 case LJ_POST_FFRETRY: /* Suppress recording of retried fast function. */
1675 if (bc_op(*J->pc) >= BC__MAX)
1676 return;
1677 break;
1678 default: lua_assert(0); break;
1680 J->postproc = LJ_POST_NONE;
1683 /* Need snapshot before recording next bytecode (e.g. after a store). */
1684 if (J->needsnap) {
1685 J->needsnap = 0;
1686 lj_snap_purge(J);
1687 lj_snap_add(J);
1688 J->mergesnap = 1;
1691 /* Skip some bytecodes. */
1692 if (LJ_UNLIKELY(J->bcskip > 0)) {
1693 J->bcskip--;
1694 return;
1697 /* Record only closed loops for root traces. */
1698 pc = J->pc;
1699 if (J->framedepth == 0 &&
1700 (MSize)((char *)pc - (char *)J->bc_min) >= J->bc_extent)
1701 lj_trace_err(J, LJ_TRERR_LLEAVE);
1703 #ifdef LUA_USE_ASSERT
1704 rec_check_slots(J);
1705 rec_check_ir(J);
1706 #endif
1708 /* Keep a copy of the runtime values of var/num/str operands. */
1709 #define rav (&ix.valv)
1710 #define rbv (&ix.tabv)
1711 #define rcv (&ix.keyv)
1713 lbase = J->L->base;
1714 ins = *pc;
1715 op = bc_op(ins);
1716 ra = bc_a(ins);
1717 ix.val = 0;
1718 switch (bcmode_a(op)) {
1719 case BCMvar:
1720 copyTV(J->L, rav, &lbase[ra]); ix.val = ra = getslot(J, ra); break;
1721 default: break; /* Handled later. */
1723 rb = bc_b(ins);
1724 rc = bc_c(ins);
1725 switch (bcmode_b(op)) {
1726 case BCMnone: rb = 0; rc = bc_d(ins); break; /* Upgrade rc to 'rd'. */
1727 case BCMvar:
1728 copyTV(J->L, rbv, &lbase[rb]); ix.tab = rb = getslot(J, rb); break;
1729 default: break; /* Handled later. */
1731 switch (bcmode_c(op)) {
1732 case BCMvar:
1733 copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
1734 case BCMpri: setitype(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
1735 case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
1736 copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
1737 lj_ir_knumint(J, numV(tv)); } break;
1738 case BCMstr: { GCstr *s = gco2str(proto_kgc(J->pt, ~(ptrdiff_t)rc));
1739 setstrV(J->L, rcv, s); ix.key = rc = lj_ir_kstr(J, s); } break;
1740 default: break; /* Handled later. */
1743 switch (op) {
1745 /* -- Comparison ops ---------------------------------------------------- */
1747 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
1748 #if LJ_HASFFI
1749 if (tref_iscdata(ra) || tref_iscdata(rc)) {
1750 rec_mm_comp_cdata(J, &ix, op, ((int)op & 2) ? MM_le : MM_lt);
1751 break;
1753 #endif
1754 /* Emit nothing for two numeric or string consts. */
1755 if (!(tref_isk2(ra,rc) && tref_isnumber_str(ra) && tref_isnumber_str(rc))) {
1756 IRType ta = tref_isinteger(ra) ? IRT_INT : tref_type(ra);
1757 IRType tc = tref_isinteger(rc) ? IRT_INT : tref_type(rc);
1758 int irop;
1759 if (ta != tc) {
1760 /* Widen mixed number/int comparisons to number/number comparison. */
1761 if (ta == IRT_INT && tc == IRT_NUM) {
1762 ra = emitir(IRTN(IR_CONV), ra, IRCONV_NUM_INT);
1763 ta = IRT_NUM;
1764 } else if (ta == IRT_NUM && tc == IRT_INT) {
1765 rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
1766 } else if (LJ_52) {
1767 ta = IRT_NIL; /* Force metamethod for different types. */
1768 } else if (!((ta == IRT_FALSE || ta == IRT_TRUE) &&
1769 (tc == IRT_FALSE || tc == IRT_TRUE))) {
1770 break; /* Interpreter will throw for two different types. */
1773 rec_comp_prep(J);
1774 irop = (int)op - (int)BC_ISLT + (int)IR_LT;
1775 if (ta == IRT_NUM) {
1776 if ((irop & 1)) irop ^= 4; /* ISGE/ISGT are unordered. */
1777 if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
1778 irop ^= 5;
1779 } else if (ta == IRT_INT) {
1780 if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
1781 irop ^= 1;
1782 } else if (ta == IRT_STR) {
1783 if (!lj_ir_strcmp(strV(rav), strV(rcv), (IROp)irop)) irop ^= 1;
1784 ra = lj_ir_call(J, IRCALL_lj_str_cmp, ra, rc);
1785 rc = lj_ir_kint(J, 0);
1786 ta = IRT_INT;
1787 } else {
1788 rec_mm_comp(J, &ix, (int)op);
1789 break;
1791 emitir(IRTG(irop, ta), ra, rc);
1792 rec_comp_fixup(J, J->pc, ((int)op ^ irop) & 1);
1794 break;
1796 case BC_ISEQV: case BC_ISNEV:
1797 case BC_ISEQS: case BC_ISNES:
1798 case BC_ISEQN: case BC_ISNEN:
1799 case BC_ISEQP: case BC_ISNEP:
1800 #if LJ_HASFFI
1801 if (tref_iscdata(ra) || tref_iscdata(rc)) {
1802 rec_mm_comp_cdata(J, &ix, op, MM_eq);
1803 break;
1805 #endif
1806 /* Emit nothing for two non-table, non-udata consts. */
1807 if (!(tref_isk2(ra, rc) && !(tref_istab(ra) || tref_isudata(ra)))) {
1808 int diff;
1809 rec_comp_prep(J);
1810 diff = lj_record_objcmp(J, ra, rc, rav, rcv);
1811 if (diff == 1 && (tref_istab(ra) || tref_isudata(ra))) {
1812 /* Only check __eq if different, but the same type (table or udata). */
1813 rec_mm_equal(J, &ix, (int)op);
1814 break;
1816 rec_comp_fixup(J, J->pc, ((int)op & 1) == !diff);
1818 break;
1820 /* -- Unary test and copy ops ------------------------------------------- */
1822 case BC_ISTC: case BC_ISFC:
1823 if ((op & 1) == tref_istruecond(rc))
1824 rc = 0; /* Don't store if condition is not true. */
1825 /* fallthrough */
1826 case BC_IST: case BC_ISF: /* Type specialization suffices. */
1827 if (bc_a(pc[1]) < J->maxslot)
1828 J->maxslot = bc_a(pc[1]); /* Shrink used slots. */
1829 break;
1831 /* -- Unary ops --------------------------------------------------------- */
1833 case BC_NOT:
1834 /* Type specialization already forces const result. */
1835 rc = tref_istruecond(rc) ? TREF_FALSE : TREF_TRUE;
1836 break;
1838 case BC_LEN:
1839 if (tref_isstr(rc))
1840 rc = emitir(IRTI(IR_FLOAD), rc, IRFL_STR_LEN);
1841 else if (!LJ_52 && tref_istab(rc))
1842 rc = lj_ir_call(J, IRCALL_lj_tab_len, rc);
1843 else
1844 rc = rec_mm_len(J, rc, rcv);
1845 break;
1847 /* -- Arithmetic ops ---------------------------------------------------- */
1849 case BC_UNM:
1850 if (tref_isnumber_str(rc)) {
1851 rc = lj_opt_narrow_unm(J, rc, rcv);
1852 } else {
1853 ix.tab = rc;
1854 copyTV(J->L, &ix.tabv, rcv);
1855 rc = rec_mm_arith(J, &ix, MM_unm);
1857 break;
1859 case BC_ADDNV: case BC_SUBNV: case BC_MULNV: case BC_DIVNV: case BC_MODNV:
1860 /* Swap rb/rc and rbv/rcv. rav is temp. */
1861 ix.tab = rc; ix.key = rc = rb; rb = ix.tab;
1862 copyTV(J->L, rav, rbv);
1863 copyTV(J->L, rbv, rcv);
1864 copyTV(J->L, rcv, rav);
1865 if (op == BC_MODNV)
1866 goto recmod;
1867 /* fallthrough */
1868 case BC_ADDVN: case BC_SUBVN: case BC_MULVN: case BC_DIVVN:
1869 case BC_ADDVV: case BC_SUBVV: case BC_MULVV: case BC_DIVVV: {
1870 MMS mm = bcmode_mm(op);
1871 if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
1872 rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv,
1873 (int)mm - (int)MM_add + (int)IR_ADD);
1874 else
1875 rc = rec_mm_arith(J, &ix, mm);
1876 break;
1879 case BC_MODVN: case BC_MODVV:
1880 recmod:
1881 if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
1882 rc = lj_opt_narrow_mod(J, rb, rc, rcv);
1883 else
1884 rc = rec_mm_arith(J, &ix, MM_mod);
1885 break;
1887 case BC_POW:
1888 if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
1889 rc = lj_opt_narrow_pow(J, lj_ir_tonum(J, rb), rc, rcv);
1890 else
1891 rc = rec_mm_arith(J, &ix, MM_pow);
1892 break;
1894 /* -- Constant and move ops --------------------------------------------- */
1896 case BC_MOV:
1897 /* Clear gap of method call to avoid resurrecting previous refs. */
1898 if (ra > J->maxslot) J->base[ra-1] = 0;
1899 break;
1900 case BC_KSTR: case BC_KNUM: case BC_KPRI:
1901 break;
1902 case BC_KSHORT:
1903 rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
1904 break;
1905 case BC_KNIL:
1906 while (ra <= rc)
1907 J->base[ra++] = TREF_NIL;
1908 if (rc >= J->maxslot) J->maxslot = rc+1;
1909 break;
1910 #if LJ_HASFFI
1911 case BC_KCDATA:
1912 rc = lj_ir_kgc(J, proto_kgc(J->pt, ~(ptrdiff_t)rc), IRT_CDATA);
1913 break;
1914 #endif
1916 /* -- Upvalue and function ops ------------------------------------------ */
1918 case BC_UGET:
1919 rc = rec_upvalue(J, rc, 0);
1920 break;
1921 case BC_USETV: case BC_USETS: case BC_USETN: case BC_USETP:
1922 rec_upvalue(J, ra, rc);
1923 break;
1925 /* -- Table ops --------------------------------------------------------- */
1927 case BC_GGET: case BC_GSET:
1928 settabV(J->L, &ix.tabv, tabref(J->fn->l.env));
1929 ix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), getcurrf(J), IRFL_FUNC_ENV);
1930 ix.idxchain = LJ_MAX_IDXCHAIN;
1931 rc = lj_record_idx(J, &ix);
1932 break;
1934 case BC_TGETB: case BC_TSETB:
1935 setintV(&ix.keyv, (int32_t)rc);
1936 ix.key = lj_ir_kint(J, (int32_t)rc);
1937 /* fallthrough */
1938 case BC_TGETV: case BC_TGETS: case BC_TSETV: case BC_TSETS:
1939 ix.idxchain = LJ_MAX_IDXCHAIN;
1940 rc = lj_record_idx(J, &ix);
1941 break;
1943 case BC_TNEW:
1944 rc = rec_tnew(J, rc);
1945 break;
1946 case BC_TDUP:
1947 rc = emitir(IRTG(IR_TDUP, IRT_TAB),
1948 lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
1949 break;
1951 /* -- Calls and vararg handling ----------------------------------------- */
1953 case BC_ITERC:
1954 J->base[ra] = getslot(J, ra-3);
1955 J->base[ra+1] = getslot(J, ra-2);
1956 J->base[ra+2] = getslot(J, ra-1);
1957 { /* Do the actual copy now because lj_record_call needs the values. */
1958 TValue *b = &J->L->base[ra];
1959 copyTV(J->L, b, b-3);
1960 copyTV(J->L, b+1, b-2);
1961 copyTV(J->L, b+2, b-1);
1963 lj_record_call(J, ra, (ptrdiff_t)rc-1);
1964 break;
1966 /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
1967 case BC_CALLM:
1968 rc = (BCReg)(J->L->top - J->L->base) - ra;
1969 /* fallthrough */
1970 case BC_CALL:
1971 lj_record_call(J, ra, (ptrdiff_t)rc-1);
1972 break;
1974 case BC_CALLMT:
1975 rc = (BCReg)(J->L->top - J->L->base) - ra;
1976 /* fallthrough */
1977 case BC_CALLT:
1978 lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
1979 break;
1981 case BC_VARG:
1982 rec_varg(J, ra, (ptrdiff_t)rb-1);
1983 break;
1985 /* -- Returns ----------------------------------------------------------- */
1987 case BC_RETM:
1988 /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
1989 rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
1990 /* fallthrough */
1991 case BC_RET: case BC_RET0: case BC_RET1:
1992 lj_record_ret(J, ra, (ptrdiff_t)rc-1);
1993 break;
1995 /* -- Loops and branches ------------------------------------------------ */
1997 case BC_FORI:
1998 if (rec_for(J, pc, 0) != LOOPEV_LEAVE)
1999 J->loopref = J->cur.nins;
2000 break;
2001 case BC_JFORI:
2002 lua_assert(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL);
2003 if (rec_for(J, pc, 0) != LOOPEV_LEAVE) /* Link to existing loop. */
2004 rec_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
2005 /* Continue tracing if the loop is not entered. */
2006 break;
2008 case BC_FORL:
2009 rec_loop_interp(J, pc, rec_for(J, pc+((ptrdiff_t)rc-BCBIAS_J), 1));
2010 break;
2011 case BC_ITERL:
2012 rec_loop_interp(J, pc, rec_iterl(J, *pc));
2013 break;
2014 case BC_LOOP:
2015 rec_loop_interp(J, pc, rec_loop(J, ra));
2016 break;
2018 case BC_JFORL:
2019 rec_loop_jit(J, rc, rec_for(J, pc+bc_j(traceref(J, rc)->startins), 1));
2020 break;
2021 case BC_JITERL:
2022 rec_loop_jit(J, rc, rec_iterl(J, traceref(J, rc)->startins));
2023 break;
2024 case BC_JLOOP:
2025 rec_loop_jit(J, rc, rec_loop(J, ra));
2026 break;
2028 case BC_IFORL:
2029 case BC_IITERL:
2030 case BC_ILOOP:
2031 case BC_IFUNCF:
2032 case BC_IFUNCV:
2033 lj_trace_err(J, LJ_TRERR_BLACKL);
2034 break;
2036 case BC_JMP:
2037 if (ra < J->maxslot)
2038 J->maxslot = ra; /* Shrink used slots. */
2039 break;
2041 /* -- Function headers -------------------------------------------------- */
2043 case BC_FUNCF:
2044 rec_func_lua(J);
2045 break;
2046 case BC_JFUNCF:
2047 rec_func_jit(J, rc);
2048 break;
2050 case BC_FUNCV:
2051 rec_func_vararg(J);
2052 rec_func_lua(J);
2053 break;
2054 case BC_JFUNCV:
2055 lua_assert(0); /* Cannot happen. No hotcall counting for varag funcs. */
2056 break;
2058 case BC_FUNCC:
2059 case BC_FUNCCW:
2060 lj_ffrecord_func(J);
2061 break;
2063 default:
2064 if (op >= BC__MAX) {
2065 lj_ffrecord_func(J);
2066 break;
2068 /* fallthrough */
2069 case BC_ITERN:
2070 case BC_ISNEXT:
2071 case BC_CAT:
2072 case BC_UCLO:
2073 case BC_FNEW:
2074 case BC_TSETM:
2075 setintV(&J->errinfo, (int32_t)op);
2076 lj_trace_err_info(J, LJ_TRERR_NYIBC);
2077 break;
2080 /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
2081 if (bcmode_a(op) == BCMdst && rc) {
2082 J->base[ra] = rc;
2083 if (ra >= J->maxslot) J->maxslot = ra+1;
2086 #undef rav
2087 #undef rbv
2088 #undef rcv
2090 /* Limit the number of recorded IR instructions. */
2091 if (J->cur.nins > REF_FIRST+(IRRef)J->param[JIT_P_maxrecord])
2092 lj_trace_err(J, LJ_TRERR_TRACEOV);
2095 /* -- Recording setup ----------------------------------------------------- */
2097 /* Setup recording for a root trace started by a hot loop. */
2098 static const BCIns *rec_setup_root(jit_State *J)
2100 /* Determine the next PC and the bytecode range for the loop. */
2101 const BCIns *pcj, *pc = J->pc;
2102 BCIns ins = *pc;
2103 BCReg ra = bc_a(ins);
2104 switch (bc_op(ins)) {
2105 case BC_FORL:
2106 J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
2107 pc += 1+bc_j(ins);
2108 J->bc_min = pc;
2109 break;
2110 case BC_ITERL:
2111 lua_assert(bc_op(pc[-1]) == BC_ITERC);
2112 J->maxslot = ra + bc_b(pc[-1]) - 1;
2113 J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
2114 pc += 1+bc_j(ins);
2115 lua_assert(bc_op(pc[-1]) == BC_JMP);
2116 J->bc_min = pc;
2117 break;
2118 case BC_LOOP:
2119 /* Only check BC range for real loops, but not for "repeat until true". */
2120 pcj = pc + bc_j(ins);
2121 ins = *pcj;
2122 if (bc_op(ins) == BC_JMP && bc_j(ins) < 0) {
2123 J->bc_min = pcj+1 + bc_j(ins);
2124 J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
2126 J->maxslot = ra;
2127 pc++;
2128 break;
2129 case BC_RET:
2130 case BC_RET0:
2131 case BC_RET1:
2132 /* No bytecode range check for down-recursive root traces. */
2133 J->maxslot = ra + bc_d(ins);
2134 break;
2135 case BC_FUNCF:
2136 /* No bytecode range check for root traces started by a hot call. */
2137 J->maxslot = J->pt->numparams;
2138 pc++;
2139 break;
2140 default:
2141 lua_assert(0);
2142 break;
2144 return pc;
2147 /* Setup for recording a new trace. */
2148 void lj_record_setup(jit_State *J)
2150 uint32_t i;
2152 /* Initialize state related to current trace. */
2153 memset(J->slot, 0, sizeof(J->slot));
2154 memset(J->chain, 0, sizeof(J->chain));
2155 memset(J->bpropcache, 0, sizeof(J->bpropcache));
2156 J->scev.idx = REF_NIL;
2158 J->baseslot = 1; /* Invoking function is at base[-1]. */
2159 J->base = J->slot + J->baseslot;
2160 J->maxslot = 0;
2161 J->framedepth = 0;
2162 J->retdepth = 0;
2164 J->instunroll = J->param[JIT_P_instunroll];
2165 J->loopunroll = J->param[JIT_P_loopunroll];
2166 J->tailcalled = 0;
2167 J->loopref = 0;
2169 J->bc_min = NULL; /* Means no limit. */
2170 J->bc_extent = ~(MSize)0;
2172 /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2173 emitir_raw(IRT(IR_BASE, IRT_P32), J->parent, J->exitno);
2174 for (i = 0; i <= 2; i++) {
2175 IRIns *ir = IR(REF_NIL-i);
2176 ir->i = 0;
2177 ir->t.irt = (uint8_t)(IRT_NIL+i);
2178 ir->o = IR_KPRI;
2179 ir->prev = 0;
2181 J->cur.nk = REF_TRUE;
2183 J->startpc = J->pc;
2184 setmref(J->cur.startpc, J->pc);
2185 if (J->parent) { /* Side trace. */
2186 GCtrace *T = traceref(J, J->parent);
2187 TraceNo root = T->root ? T->root : J->parent;
2188 J->cur.root = (uint16_t)root;
2189 J->cur.startins = BCINS_AD(BC_JMP, 0, 0);
2190 /* Check whether we could at least potentially form an extra loop. */
2191 if (J->exitno == 0 && T->snap[0].nent == 0) {
2192 /* We can narrow a FORL for some side traces, too. */
2193 if (J->pc > proto_bc(J->pt) && bc_op(J->pc[-1]) == BC_JFORI &&
2194 bc_d(J->pc[bc_j(J->pc[-1])-1]) == root) {
2195 lj_snap_add(J);
2196 rec_for_loop(J, J->pc-1, &J->scev, 1);
2197 goto sidecheck;
2199 } else {
2200 J->startpc = NULL; /* Prevent forming an extra loop. */
2202 lj_snap_replay(J, T);
2203 sidecheck:
2204 if (traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] ||
2205 T->snap[J->exitno].count >= J->param[JIT_P_hotexit] +
2206 J->param[JIT_P_tryside]) {
2207 rec_stop(J, LJ_TRLINK_INTERP, 0);
2209 } else { /* Root trace. */
2210 J->cur.root = 0;
2211 J->cur.startins = *J->pc;
2212 J->pc = rec_setup_root(J);
2213 /* Note: the loop instruction itself is recorded at the end and not
2214 ** at the start! So snapshot #0 needs to point to the *next* instruction.
2216 lj_snap_add(J);
2217 if (bc_op(J->cur.startins) == BC_FORL)
2218 rec_for_loop(J, J->pc-1, &J->scev, 1);
2219 if (1 + J->pt->framesize >= LJ_MAX_JSLOTS)
2220 lj_trace_err(J, LJ_TRERR_STACKOV);
2222 #ifdef LUAJIT_ENABLE_CHECKHOOK
2223 /* Regularly check for instruction/line hooks from compiled code and
2224 ** exit to the interpreter if the hooks are set.
2226 ** This is a compile-time option and disabled by default, since the
2227 ** hook checks may be quite expensive in tight loops.
2229 ** Note this is only useful if hooks are *not* set most of the time.
2230 ** Use this only if you want to *asynchronously* interrupt the execution.
2232 ** You can set the instruction hook via lua_sethook() with a count of 1
2233 ** from a signal handler or another native thread. Please have a look
2234 ** at the first few functions in luajit.c for an example (Ctrl-C handler).
2237 TRef tr = emitir(IRT(IR_XLOAD, IRT_U8),
2238 lj_ir_kptr(J, &J2G(J)->hookmask), IRXLOAD_VOLATILE);
2239 tr = emitir(IRTI(IR_BAND), tr, lj_ir_kint(J, (LUA_MASKLINE|LUA_MASKCOUNT)));
2240 emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, 0));
2242 #endif
2245 #undef IR
2246 #undef emitir_raw
2247 #undef emitir
2249 #endif