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