• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tarantool / luajit / 7091447848

04 Dec 2023 07:16PM UTC coverage: 88.589% (-0.01%) from 88.599%
7091447848

push

github

fckxorg
fixup

5374 of 5986 branches covered (0.0%)

Branch coverage included in aggregate %.

20617 of 23353 relevant lines covered (88.28%)

2748253.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.13
/src/lj_record.c
1
/*
2
** Trace recorder (bytecode -> SSA IR).
3
** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4
*/
5

6
#define lj_record_c
7
#define LUA_CORE
8

9
#include "lj_obj.h"
10

11
#if LJ_HASJIT
12

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
#if LJ_HASPROFILE
24
#include "lj_debug.h"
25
#endif
26
#include "lj_ir.h"
27
#include "lj_jit.h"
28
#include "lj_ircall.h"
29
#include "lj_iropt.h"
30
#include "lj_trace.h"
31
#include "lj_record.h"
32
#include "lj_ffrecord.h"
33
#include "lj_snap.h"
34
#include "lj_dispatch.h"
35
#include "lj_vm.h"
36

37
/* Some local macros to save typing. Undef'd at the end. */
38
#define IR(ref)                        (&J->cur.ir[(ref)])
39

40
/* Pass IR on to next optimization in chain (FOLD). */
41
#define emitir(ot, a, b)        (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
42

43
/* Emit raw IR without passing through optimizations. */
44
#define emitir_raw(ot, a, b)        (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))
45

46
/* -- Sanity checks ------------------------------------------------------- */
47

48
#ifdef LUA_USE_ASSERT
49
/* Sanity check the whole IR -- sloooow. */
50
static void rec_check_ir(jit_State *J)
51
{
52
  IRRef i, nins = J->cur.nins, nk = J->cur.nk;
53
  lj_assertJ(nk <= REF_BIAS && nins >= REF_BIAS && nins < 65536,
54
             "inconsistent IR layout");
55
  for (i = nk; i < nins; i++) {
56
    IRIns *ir = IR(i);
57
    uint32_t mode = lj_ir_mode[ir->o];
58
    IRRef op1 = ir->op1;
59
    IRRef op2 = ir->op2;
60
    const char *err = NULL;
61
    switch (irm_op1(mode)) {
62
    case IRMnone:
63
      if (op1 != 0) err = "IRMnone op1 used";
64
      break;
65
    case IRMref:
66
      if (op1 < nk || (i >= REF_BIAS ? op1 >= i : op1 <= i))
67
        err = "IRMref op1 out of range";
68
      break;
69
    case IRMlit: break;
70
    case IRMcst:
71
      if (i >= REF_BIAS) { err = "constant in IR range"; break; }
72
      if (irt_is64(ir->t) && ir->o != IR_KNULL)
73
        i++;
74
      continue;
75
    }
76
    switch (irm_op2(mode)) {
77
    case IRMnone:
78
      if (op2) err = "IRMnone op2 used";
79
      break;
80
    case IRMref:
81
      if (op2 < nk || (i >= REF_BIAS ? op2 >= i : op2 <= i))
82
        err = "IRMref op2 out of range";
83
      break;
84
    case IRMlit: break;
85
    case IRMcst: err = "IRMcst op2"; break;
86
    }
87
    if (!err && ir->prev) {
88
      if (ir->prev < nk || (i >= REF_BIAS ? ir->prev >= i : ir->prev <= i))
89
        err = "chain out of range";
90
      else if (ir->o != IR_NOP && IR(ir->prev)->o != ir->o)
91
        err = "chain to different op";
92
    }
93
    lj_assertJ(!err, "bad IR %04d op %d(%04d,%04d): %s",
94
               i-REF_BIAS,
95
               ir->o,
96
               irm_op1(mode) == IRMref ? op1-REF_BIAS : op1,
97
               irm_op2(mode) == IRMref ? op2-REF_BIAS : op2,
98
               err);
99
  }
100
}
101

102
/* Compare stack slots and frames of the recorder and the VM. */
103
static void rec_check_slots(jit_State *J)
104
{
105
  BCReg s, nslots = J->baseslot + J->maxslot;
106
  int32_t depth = 0;
107
  cTValue *base = J->L->base - J->baseslot;
108
  lj_assertJ(J->baseslot >= 1+LJ_FR2, "bad baseslot");
109
  lj_assertJ(J->baseslot == 1+LJ_FR2 || (J->slot[J->baseslot-1] & TREF_FRAME),
110
             "baseslot does not point to frame");
111
  lj_assertJ(nslots <= LJ_MAX_JSLOTS, "slot overflow");
112
  for (s = 0; s < nslots; s++) {
113
    TRef tr = J->slot[s];
114
    if (tr) {
115
      cTValue *tv = &base[s];
116
      IRRef ref = tref_ref(tr);
117
      IRIns *ir = NULL;  /* Silence compiler. */
118
      lj_assertJ(tv < J->L->top, "slot %d above top of Lua stack", s);
119
      if (!LJ_FR2 || ref || !(tr & (TREF_FRAME | TREF_CONT))) {
120
        lj_assertJ(ref >= J->cur.nk && ref < J->cur.nins,
121
                   "slot %d ref %04d out of range", s, ref - REF_BIAS);
122
        ir = IR(ref);
123
        lj_assertJ(irt_t(ir->t) == tref_t(tr), "slot %d IR type mismatch", s);
124
      }
125
      if (s == 0) {
126
        lj_assertJ(tref_isfunc(tr), "frame slot 0 is not a function");
127
#if LJ_FR2
128
      } else if (s == 1) {
129
        lj_assertJ((tr & ~TREF_FRAME) == 0, "bad frame slot 1");
130
#endif
131
      } else if ((tr & TREF_FRAME)) {
132
        GCfunc *fn = gco2func(frame_gc(tv));
133
        BCReg delta = (BCReg)(tv - frame_prev(tv));
134
#if LJ_FR2
135
        lj_assertJ(!ref || ir_knum(ir)->u64 == tv->u64,
136
                   "frame slot %d PC mismatch", s);
137
        tr = J->slot[s-1];
138
        ir = IR(tref_ref(tr));
139
#endif
140
        lj_assertJ(tref_isfunc(tr),
141
                   "frame slot %d is not a function", s-LJ_FR2);
142
        lj_assertJ(!tref_isk(tr) || fn == ir_kfunc(ir),
143
                   "frame slot %d function mismatch", s-LJ_FR2);
144
        lj_assertJ(s > delta + LJ_FR2 ? (J->slot[s-delta] & TREF_FRAME)
145
                                      : (s == delta + LJ_FR2),
146
                   "frame slot %d broken chain", s-LJ_FR2);
147
        depth++;
148
      } else if ((tr & TREF_CONT)) {
149
#if LJ_FR2
150
        lj_assertJ(!ref || ir_knum(ir)->u64 == tv->u64,
151
                   "cont slot %d continuation mismatch", s);
152
#else
153
        lj_assertJ(ir_kptr(ir) == gcrefp(tv->gcr, void),
154
                   "cont slot %d continuation mismatch", s);
155
#endif
156
        lj_assertJ((J->slot[s+1+LJ_FR2] & TREF_FRAME),
157
                   "cont slot %d not followed by frame", s);
158
        depth++;
159
      } else {
160
        /* Number repr. may differ, but other types must be the same. */
161
        lj_assertJ(tvisnumber(tv) ? tref_isnumber(tr) :
162
                                    itype2irt(tv) == tref_type(tr),
163
                   "slot %d type mismatch: stack type %d vs IR type %d",
164
                   s, itypemap(tv), tref_type(tr));
165
        if (tref_isk(tr)) {  /* Compare constants. */
166
          TValue tvk;
167
          lj_ir_kvalue(J->L, &tvk, ir);
168
          lj_assertJ((tvisnum(&tvk) && tvisnan(&tvk)) ?
169
                     (tvisnum(tv) && tvisnan(tv)) :
170
                     lj_obj_equal(tv, &tvk),
171
                     "slot %d const mismatch: stack %016llx vs IR %016llx",
172
                     s, tv->u64, tvk.u64);
173
        }
174
      }
175
    }
176
  }
177
  lj_assertJ(J->framedepth == depth,
178
             "frame depth mismatch %d vs %d", J->framedepth, depth);
179
}
180
#endif
181

182
/* -- Type handling and specialization ------------------------------------ */
183

184
/* Note: these functions return tagged references (TRef). */
185

186
/* Specialize a slot to a specific type. Note: slot can be negative! */
187
static TRef sloadt(jit_State *J, int32_t slot, IRType t, int mode)
6,379✔
188
{
189
  /* Caller may set IRT_GUARD in t. */
190
  TRef ref = emitir_raw(IRT(IR_SLOAD, t), (int32_t)J->baseslot+slot, mode);
12,758✔
191
  J->base[slot] = ref;
6,379✔
192
  return ref;
6,379✔
193
}
194

195
/* Specialize a slot to the runtime type. Note: slot can be negative! */
196
static TRef sload(jit_State *J, int32_t slot)
13,296✔
197
{
198
  IRType t = itype2irt(&J->L->base[slot]);
13,296✔
199
  TRef ref = emitir_raw(IRTG(IR_SLOAD, t), (int32_t)J->baseslot+slot,
13,296✔
200
                        IRSLOAD_TYPECHECK);
201
  if (irtype_ispri(t)) ref = TREF_PRI(t);  /* Canonicalize primitive refs. */
13,296✔
202
  J->base[slot] = ref;
13,296✔
203
  return ref;
13,296✔
204
}
205

206
/* Get TRef from slot. Load slot and specialize if not done already. */
207
#define getslot(J, s)        (J->base[(s)] ? J->base[(s)] : sload(J, (int32_t)(s)))
208

209
/* Get TRef for current function. */
210
static TRef getcurrf(jit_State *J)
18,891✔
211
{
212
  if (J->base[-1-LJ_FR2])
18,891✔
213
    return J->base[-1-LJ_FR2];
214
  lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot");
3,809✔
215
  return sloadt(J, -1-LJ_FR2, IRT_FUNC, IRSLOAD_READONLY);
3,809✔
216
}
217

218
/* Compare for raw object equality.
219
** Returns 0 if the objects are the same.
220
** Returns 1 if they are different, but the same type.
221
** Returns 2 for two different types.
222
** Comparisons between primitives always return 1 -- no caller cares about it.
223
*/
224
int lj_record_objcmp(jit_State *J, TRef a, TRef b, cTValue *av, cTValue *bv)
7,540✔
225
{
226
  int diff = !lj_obj_equal(av, bv);
7,540✔
227
  if (!tref_isk2(a, b)) {  /* Shortcut, also handles primitives. */
7,540✔
228
    IRType ta = tref_isinteger(a) ? IRT_INT : tref_type(a);
7,540✔
229
    IRType tb = tref_isinteger(b) ? IRT_INT : tref_type(b);
7,540✔
230
    if (ta != tb) {
7,540✔
231
      /* Widen mixed number/int comparisons to number/number comparison. */
232
      if (ta == IRT_INT && tb == IRT_NUM) {
6,874✔
233
        a = emitir(IRTN(IR_CONV), a, IRCONV_NUM_INT);
2✔
234
        ta = IRT_NUM;
2✔
235
      } else if (ta == IRT_NUM && tb == IRT_INT) {
6,872✔
236
        b = emitir(IRTN(IR_CONV), b, IRCONV_NUM_INT);
223✔
237
      } else {
238
        return 2;  /* Two different types are never equal. */
239
      }
240
    }
241
    emitir(IRTG(diff ? IR_NE : IR_EQ, ta), a, b);
1,427✔
242
  }
243
  return diff;
244
}
245

246
/* Constify a value. Returns 0 for non-representable object types. */
247
TRef lj_record_constify(jit_State *J, cTValue *o)
15,398✔
248
{
249
  if (tvisgcv(o))
15,398✔
250
    return lj_ir_kgc(J, gcV(o), itype2irt(o));
15,123✔
251
  else if (tvisint(o))
275✔
252
    return lj_ir_kint(J, intV(o));
253
  else if (tvisnum(o))
275✔
254
    return lj_ir_knumint(J, numV(o));
275✔
255
  else if (tvisbool(o))
×
256
    return TREF_PRI(itype2irt(o));
×
257
  else
258
    return 0;  /* Can't represent lightuserdata (pointless). */
259
}
260

261
/* -- Record loop ops ----------------------------------------------------- */
262

263
/* Loop event. */
264
typedef enum {
265
  LOOPEV_LEAVE,                /* Loop is left or not entered. */
266
  LOOPEV_ENTERLO,        /* Loop is entered with a low iteration count left. */
267
  LOOPEV_ENTER                /* Loop is entered. */
268
} LoopEvent;
269

270
/* Canonicalize slots: convert integers to numbers. */
271
static void canonicalize_slots(jit_State *J)
3,911✔
272
{
273
  BCReg s;
3,911✔
274
  if (LJ_DUALNUM) return;
3,911✔
275
  for (s = J->baseslot+J->maxslot-1; s >= 1; s--) {
41,569✔
276
    TRef tr = J->slot[s];
37,658✔
277
    if (tref_isinteger(tr)) {
37,658✔
278
      IRIns *ir = IR(tref_ref(tr));
1,189✔
279
      if (!(ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_READONLY)))
1,189✔
280
        J->slot[s] = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
1,118✔
281
    }
282
  }
283
}
284

285
/* Stop recording. */
286
void lj_record_stop(jit_State *J, TraceLink linktype, TraceNo lnk)
5,197✔
287
{
288
#ifdef LUAJIT_ENABLE_TABLE_BUMP
289
  if (J->retryrec)
290
    lj_trace_err(J, LJ_TRERR_RETRY);
291
#endif
292
  lj_trace_end(J);
5,197✔
293
  J->cur.linktype = (uint8_t)linktype;
5,197✔
294
  J->cur.link = (uint16_t)lnk;
5,197✔
295
  /* Looping back at the same stack level? */
296
  if (lnk == J->cur.traceno && J->framedepth + J->retdepth == 0) {
5,197✔
297
    if ((J->flags & JIT_F_OPT_LOOP))  /* Shall we try to create a loop? */
2,000✔
298
      goto nocanon;  /* Do not canonicalize or we lose the narrowing. */
1,286✔
299
    if (J->cur.root)  /* Otherwise ensure we always link to the root trace. */
714✔
300
      J->cur.link = J->cur.root;
1✔
301
  }
302
  canonicalize_slots(J);
3,911✔
303
nocanon:
5,197✔
304
  /* Note: all loop ops must set J->pc to the following instruction! */
305
  lj_snap_add(J);  /* Add loop snapshot. */
5,197✔
306
  J->needsnap = 0;
5,197✔
307
  J->mergesnap = 1;  /* In case recording continues. */
5,197✔
308
}
5,197✔
309

310
/* Search bytecode backwards for a int/num constant slot initializer. */
311
static TRef find_kinit(jit_State *J, const BCIns *endpc, BCReg slot, IRType t)
7,681✔
312
{
313
  /* This algorithm is rather simplistic and assumes quite a bit about
314
  ** how the bytecode is generated. It works fine for FORI initializers,
315
  ** but it won't necessarily work in other cases (e.g. iterator arguments).
316
  ** It doesn't do anything fancy, either (like backpropagating MOVs).
317
  */
318
  const BCIns *pc, *startpc = proto_bc(J->pt);
7,681✔
319
  for (pc = endpc-1; pc > startpc; pc--) {
15,673✔
320
    BCIns ins = *pc;
15,673✔
321
    BCOp op = bc_op(ins);
15,673✔
322
    /* First try to find the last instruction that stores to this slot. */
323
    if (bcmode_a(op) == BCMbase && bc_a(ins) <= slot) {
15,673✔
324
      return 0;  /* Multiple results, e.g. from a CALL or KNIL. */
325
    } else if (bcmode_a(op) == BCMdst && bc_a(ins) == slot) {
15,658✔
326
      if (op == BC_KSHORT || op == BC_KNUM) {  /* Found const. initializer. */
7,666✔
327
        /* Now try to verify there's no forward jump across it. */
328
        const BCIns *kpc = pc;
462,123✔
329
        for (; pc > startpc; pc--)
462,123✔
330
          if (bc_op(*pc) == BC_JMP) {
454,756✔
331
            const BCIns *target = pc+bc_j(*pc)+1;
41,614✔
332
            if (target > kpc && target <= endpc)
41,614✔
333
              return 0;  /* Conditional assignment. */
334
          }
335
        if (op == BC_KSHORT) {
7,367✔
336
          int32_t k = (int32_t)(int16_t)bc_d(ins);
7,301✔
337
          return t == IRT_INT ? lj_ir_kint(J, k) : lj_ir_knum(J, (lua_Number)k);
7,301✔
338
        } else {
339
          cTValue *tv = proto_knumtv(J->pt, bc_d(ins));
66✔
340
          if (t == IRT_INT) {
66✔
341
            int32_t k = numberVint(tv);
50✔
342
            if (tvisint(tv) || numV(tv) == (lua_Number)k)  /* -0 is ok here. */
50✔
343
              return lj_ir_kint(J, k);
46✔
344
            return 0;  /* Type mismatch. */
345
          } else {
346
            return lj_ir_knum(J, numberVnum(tv));
16✔
347
          }
348
        }
349
      }
350
      return 0;  /* Non-constant initializer. */
351
    }
352
  }
353
  return 0;  /* No assignment to this slot found? */
354
}
355

356
/* Load and optionally convert a FORI argument from a slot. */
357
static TRef fori_load(jit_State *J, BCReg slot, IRType t, int mode)
2,570✔
358
{
359
  int conv = (tvisint(&J->L->base[slot]) != (t==IRT_INT)) ? IRSLOAD_CONVERT : 0;
2,570✔
360
  return sloadt(J, (int32_t)slot,
7,710✔
361
                t + (((mode & IRSLOAD_TYPECHECK) ||
2,570✔
362
                      (conv && t == IRT_INT && !(mode >> 16))) ?
2,570✔
363
                     IRT_GUARD : 0),
2,570✔
364
                mode + conv);
365
}
366

367
/* Peek before FORI to find a const initializer. Otherwise load from slot. */
368
static TRef fori_arg(jit_State *J, const BCIns *fori, BCReg slot,
5,526✔
369
                     IRType t, int mode)
370
{
371
  TRef tr = J->base[slot];
5,526✔
372
  if (!tr) {
5,526✔
373
    tr = find_kinit(J, fori, slot, t);
4,918✔
374
    if (!tr)
4,918✔
375
      tr = fori_load(J, slot, t, mode);
239✔
376
  }
377
  return tr;
5,526✔
378
}
379

380
/* Return the direction of the FOR loop iterator.
381
** It's important to exactly reproduce the semantics of the interpreter.
382
*/
383
static int rec_for_direction(cTValue *o)
5,703✔
384
{
385
  return (tvisint(o) ? intV(o) : (int32_t)o->u32.hi) >= 0;
5,703✔
386
}
387

388
/* Simulate the runtime behavior of the FOR loop iterator. */
389
static LoopEvent rec_for_iter(IROp *op, cTValue *o, int isforl)
2,709✔
390
{
391
  lua_Number stopv = numberVnum(&o[FORL_STOP]);
2,709✔
392
  lua_Number idxv = numberVnum(&o[FORL_IDX]);
2,709✔
393
  lua_Number stepv = numberVnum(&o[FORL_STEP]);
2,709✔
394
  if (isforl)
2,709✔
395
    idxv += stepv;
2,478✔
396
  if (rec_for_direction(&o[FORL_STEP])) {
2,709✔
397
    if (idxv <= stopv) {
2,646✔
398
      *op = IR_LE;
2,594✔
399
      return idxv + 2*stepv > stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
2,594✔
400
    }
401
    *op = IR_GT; return LOOPEV_LEAVE;
52✔
402
  } else {
403
    if (stopv <= idxv) {
63✔
404
      *op = IR_GE;
63✔
405
      return idxv + 2*stepv < stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
63✔
406
    }
407
    *op = IR_LT; return LOOPEV_LEAVE;
×
408
  }
409
}
410

411
/* Record checks for FOR loop overflow and step direction. */
412
static void rec_for_check(jit_State *J, IRType t, int dir,
2,994✔
413
                          TRef stop, TRef step, int init)
414
{
415
  if (!tref_isk(step)) {
2,994✔
416
    /* Non-constant step: need a guard for the direction. */
417
    TRef zero = (t == IRT_INT) ? lj_ir_kint(J, 0) : lj_ir_knum_zero(J);
249✔
418
    emitir(IRTG(dir ? IR_GE : IR_LT, t), step, zero);
250✔
419
    /* Add hoistable overflow checks for a narrowed FORL index. */
420
    if (init && t == IRT_INT) {
249✔
421
      if (tref_isk(stop)) {
8✔
422
        /* Constant stop: optimize check away or to a range check for step. */
423
        int32_t k = IR(tref_ref(stop))->i;
2✔
424
        if (dir) {
2✔
425
          if (k > 0)
2✔
426
            emitir(IRTGI(IR_LE), step, lj_ir_kint(J, (int32_t)0x7fffffff-k));
2✔
427
        } else {
428
          if (k < 0)
×
429
            emitir(IRTGI(IR_GE), step, lj_ir_kint(J, (int32_t)0x80000000-k));
×
430
        }
431
      } else {
432
        /* Stop+step variable: need full overflow check. */
433
        TRef tr = emitir(IRTGI(IR_ADDOV), step, stop);
6✔
434
        emitir(IRTI(IR_USE), tr, 0);  /* ADDOV is weak. Avoid dead result. */
6✔
435
      }
436
    }
437
  } else if (init && t == IRT_INT && !tref_isk(stop)) {
2,745✔
438
    /* Constant step: optimize overflow check to a range check for stop. */
439
    int32_t k = IR(tref_ref(step))->i;
212✔
440
    k = (int32_t)(dir ? 0x7fffffff : 0x80000000) - k;
212✔
441
    emitir(IRTGI(dir ? IR_LE : IR_GE), stop, lj_ir_kint(J, k));
244✔
442
  }
443
}
2,994✔
444

445
/* Record a FORL instruction. */
446
static void rec_for_loop(jit_State *J, const BCIns *fori, ScEvEntry *scev,
2,763✔
447
                         int init)
448
{
449
  BCReg ra = bc_a(*fori);
2,763✔
450
  cTValue *tv = &J->L->base[ra];
2,763✔
451
  TRef idx = J->base[ra+FORL_IDX];
2,763✔
452
  IRType t = idx ? tref_type(idx) :
2,763✔
453
             (init || LJ_DUALNUM) ? lj_opt_narrow_forl(J, tv) : IRT_NUM;
2,331✔
454
  int mode = IRSLOAD_INHERIT +
2,763✔
455
    ((!LJ_DUALNUM || tvisint(tv) == (t == IRT_INT)) ? IRSLOAD_READONLY : 0);
456
  TRef stop = fori_arg(J, fori, ra+FORL_STOP, t, mode);
2,763✔
457
  TRef step = fori_arg(J, fori, ra+FORL_STEP, t, mode);
2,763✔
458
  int tc, dir = rec_for_direction(&tv[FORL_STEP]);
2,763✔
459
  lj_assertJ(bc_op(*fori) == BC_FORI || bc_op(*fori) == BC_JFORI,
2,763✔
460
             "bad bytecode %d instead of FORI/JFORI", bc_op(*fori));
461
  scev->t.irt = t;
2,763✔
462
  scev->dir = dir;
2,763✔
463
  scev->stop = tref_ref(stop);
2,763✔
464
  scev->step = tref_ref(step);
2,763✔
465
  rec_for_check(J, t, dir, stop, step, init);
2,763✔
466
  scev->start = tref_ref(find_kinit(J, fori, ra+FORL_IDX, IRT_INT));
2,763✔
467
  tc = (LJ_DUALNUM &&
2,763✔
468
        !(scev->start && irref_isk(scev->stop) && irref_isk(scev->step) &&
469
          tvisint(&tv[FORL_IDX]) == (t == IRT_INT))) ?
470
        IRSLOAD_TYPECHECK : 0;
471
  if (tc) {
2,763✔
472
    J->base[ra+FORL_STOP] = stop;
473
    J->base[ra+FORL_STEP] = step;
474
  }
475
  if (!idx)
2,763✔
476
    idx = fori_load(J, ra+FORL_IDX, t,
2,331✔
477
                    IRSLOAD_INHERIT + tc + (J->scev.start << 16));
2,331✔
478
  if (!init)
2,763✔
479
    J->base[ra+FORL_IDX] = idx = emitir(IRT(IR_ADD, t), idx, step);
504✔
480
  J->base[ra+FORL_EXT] = idx;
2,763✔
481
  scev->idx = tref_ref(idx);
2,763✔
482
  setmref(scev->pc, fori);
2,763✔
483
  J->maxslot = ra+FORL_EXT+1;
2,763✔
484
}
2,763✔
485

486
/* Record FORL/JFORL or FORI/JFORI. */
487
static LoopEvent rec_for(jit_State *J, const BCIns *fori, int isforl)
2,710✔
488
{
489
  BCReg ra = bc_a(*fori);
2,710✔
490
  TValue *tv = &J->L->base[ra];
2,710✔
491
  TRef *tr = &J->base[ra];
2,710✔
492
  IROp op;
2,710✔
493
  LoopEvent ev;
2,710✔
494
  TRef stop;
2,710✔
495
  IRType t;
2,710✔
496
  if (isforl) {  /* Handle FORL/JFORL opcodes. */
2,710✔
497
    TRef idx = tr[FORL_IDX];
2,478✔
498
    if (mref(J->scev.pc, const BCIns) == fori && tref_ref(idx) == J->scev.idx) {
2,478✔
499
      t = J->scev.t.irt;
1,974✔
500
      stop = J->scev.stop;
1,974✔
501
      idx = emitir(IRT(IR_ADD, t), idx, J->scev.step);
1,974✔
502
      tr[FORL_EXT] = tr[FORL_IDX] = idx;
1,974✔
503
    } else {
504
      ScEvEntry scev;
504✔
505
      rec_for_loop(J, fori, &scev, 0);
504✔
506
      t = scev.t.irt;
504✔
507
      stop = scev.stop;
504✔
508
    }
509
  } else {  /* Handle FORI/JFORI opcodes. */
510
    BCReg i;
232✔
511
    lj_meta_for(J->L, tv);
232✔
512
    t = (LJ_DUALNUM || tref_isint(tr[FORL_IDX])) ? lj_opt_narrow_forl(J, tv) :
231✔
513
                                                   IRT_NUM;
514
    for (i = FORL_IDX; i <= FORL_STEP; i++) {
924✔
515
      if (!tr[i]) sload(J, ra+i);
693✔
516
      lj_assertJ(tref_isnumber_str(tr[i]), "bad FORI argument type");
693✔
517
      if (tref_isstr(tr[i]))
693✔
518
        tr[i] = emitir(IRTG(IR_STRTO, IRT_NUM), tr[i], 0);
1✔
519
      if (t == IRT_INT) {
693✔
520
        if (!tref_isinteger(tr[i]))
294✔
521
          tr[i] = emitir(IRTGI(IR_CONV), tr[i], IRCONV_INT_NUM|IRCONV_CHECK);
10✔
522
      } else {
523
        if (!tref_isnum(tr[i]))
399✔
524
          tr[i] = emitir(IRTN(IR_CONV), tr[i], IRCONV_NUM_INT);
372✔
525
      }
526
    }
527
    tr[FORL_EXT] = tr[FORL_IDX];
231✔
528
    stop = tr[FORL_STOP];
231✔
529
    rec_for_check(J, t, rec_for_direction(&tv[FORL_STEP]),
231✔
530
                  stop, tr[FORL_STEP], 1);
531
  }
532

533
  ev = rec_for_iter(&op, tv, isforl);
2,709✔
534
  if (ev == LOOPEV_LEAVE) {
2,709✔
535
    J->maxslot = ra+FORL_EXT+1;
52✔
536
    J->pc = fori+1;
52✔
537
  } else {
538
    J->maxslot = ra;
2,657✔
539
    J->pc = fori+bc_j(*fori)+1;
2,657✔
540
  }
541
  lj_snap_add(J);
2,709✔
542

543
  emitir(IRTG(op, t), tr[FORL_IDX], stop);
2,709✔
544

545
  if (ev == LOOPEV_LEAVE) {
2,709✔
546
    J->maxslot = ra;
52✔
547
    J->pc = fori+bc_j(*fori)+1;
52✔
548
  } else {
549
    J->maxslot = ra+FORL_EXT+1;
2,657✔
550
    J->pc = fori+1;
2,657✔
551
  }
552
  J->needsnap = 1;
2,709✔
553
  return ev;
2,709✔
554
}
555

556
/* Record ITERL/JITERL. */
557
static LoopEvent rec_iterl(jit_State *J, const BCIns iterins)
108✔
558
{
559
  BCReg ra = bc_a(iterins);
108✔
560
  if (!tref_isnil(getslot(J, ra))) {  /* Looping back? */
108✔
561
    J->base[ra-1] = J->base[ra];  /* Copy result of ITERC to control var. */
81✔
562
    J->maxslot = ra-1+bc_b(J->pc[-1]);
81✔
563
    J->pc += bc_j(iterins)+1;
81✔
564
    return LOOPEV_ENTER;
81✔
565
  } else {
566
    J->maxslot = ra-3;
27✔
567
    J->pc++;
27✔
568
    return LOOPEV_LEAVE;
27✔
569
  }
570
}
571

572
/* Record LOOP/JLOOP. Now, that was easy. */
573
static LoopEvent rec_loop(jit_State *J, BCReg ra)
1,554✔
574
{
575
  if (ra < J->maxslot) J->maxslot = ra;
86✔
576
  J->pc++;
1,554✔
577
  return LOOPEV_ENTER;
1,554✔
578
}
579

580
/* Check if a loop repeatedly failed to trace because it didn't loop back. */
581
static int innerloopleft(jit_State *J, const BCIns *pc)
582
{
583
  ptrdiff_t i;
584
  for (i = 0; i < PENALTY_SLOTS; i++)
10,315✔
585
    if (mref(J->penalty[i].pc, const BCIns) == pc) {
10,158✔
586
      if ((J->penalty[i].reason == LJ_TRERR_LLEAVE ||
11✔
587
           J->penalty[i].reason == LJ_TRERR_LINNER) &&
10✔
588
          J->penalty[i].val >= 2*PENALTY_MIN)
10✔
589
        return 1;
590
      break;
591
    }
592
  return 0;
593
}
594

595
/* Handle the case when an interpreted loop op is hit. */
596
static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev)
2,318✔
597
{
598
  if (J->parent == 0 && J->exitno == 0) {
2,318✔
599
    if (pc == J->startpc && J->framedepth + J->retdepth == 0) {
2,033✔
600
      /* Same loop? */
601
      if (ev == LOOPEV_LEAVE)  /* Must loop back to form a root trace. */
1,861✔
602
        lj_trace_err(J, LJ_TRERR_LLEAVE);
30✔
603
      lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno);  /* Looping trace. */
1,831✔
604
    } else if (ev != LOOPEV_LEAVE) {  /* Entering inner loop? */
172✔
605
      /* It's usually better to abort here and wait until the inner loop
606
      ** is traced. But if the inner loop repeatedly didn't loop back,
607
      ** this indicates a low trip count. In this case try unrolling
608
      ** an inner loop even in a root trace. But it's better to be a bit
609
      ** more conservative here and only do it for very short loops.
610
      */
611
      if (bc_j(*pc) != -1 && !innerloopleft(J, pc))
169✔
612
        lj_trace_err(J, LJ_TRERR_LINNER);  /* Root trace hit an inner loop. */
165✔
613
      if ((ev != LOOPEV_ENTERLO &&
4✔
614
           J->loopref && J->cur.nins - J->loopref > 24) || --J->loopunroll < 0)
4✔
615
        lj_trace_err(J, LJ_TRERR_LUNROLL);  /* Limit loop unrolling. */
×
616
      J->loopref = J->cur.nins;
4✔
617
    }
618
  } else if (ev != LOOPEV_LEAVE) {  /* Side trace enters an inner loop. */
285✔
619
    J->loopref = J->cur.nins;
263✔
620
    if (--J->loopunroll < 0)
263✔
621
      lj_trace_err(J, LJ_TRERR_LUNROLL);  /* Limit loop unrolling. */
9✔
622
  }  /* Side trace continues across a loop that's left or not entered. */
623
}
2,114✔
624

625
/* Handle the case when an already compiled loop op is hit. */
626
static void rec_loop_jit(jit_State *J, TraceNo lnk, LoopEvent ev)
1,822✔
627
{
628
  if (J->parent == 0 && J->exitno == 0) {  /* Root trace hit an inner loop. */
1,822✔
629
    /* Better let the inner loop spawn a side trace back here. */
630
    lj_trace_err(J, LJ_TRERR_LINNER);
96✔
631
  } else if (ev != LOOPEV_LEAVE) {  /* Side trace enters a compiled loop. */
1,726✔
632
    J->instunroll = 0;  /* Cannot continue across a compiled loop op. */
1,704✔
633
    if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
1,704✔
634
      lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno);  /* Form extra loop. */
165✔
635
    else
636
      lj_record_stop(J, LJ_TRLINK_ROOT, lnk);  /* Link to the loop. */
1,539✔
637
  }  /* Side trace continues across a loop that's left or not entered. */
638
}
1,726✔
639

640
/* -- Record profiler hook checks ----------------------------------------- */
641

642
#if LJ_HASPROFILE
643

644
/* Need to insert profiler hook check? */
645
static int rec_profile_need(jit_State *J, GCproto *pt, const BCIns *pc)
7✔
646
{
647
  GCproto *ppt;
7✔
648
  lj_assertJ(J->prof_mode == 'f' || J->prof_mode == 'l',
7✔
649
             "bad profiler mode %c", J->prof_mode);
650
  if (!pt)
7✔
651
    return 0;
652
  ppt = J->prev_pt;
6✔
653
  J->prev_pt = pt;
6✔
654
  if (pt != ppt && ppt) {
6✔
655
    J->prev_line = -1;
×
656
    return 1;
×
657
  }
658
  if (J->prof_mode == 'l') {
6✔
659
    BCLine line = lj_debug_line(pt, proto_bcpos(pt, pc));
4✔
660
    BCLine pline = J->prev_line;
4✔
661
    J->prev_line = line;
4✔
662
    if (pline != line)
4✔
663
      return 1;
1✔
664
  }
665
  return 0;
666
}
667

668
static void rec_profile_ins(jit_State *J, const BCIns *pc)
280,559✔
669
{
670
  if (J->prof_mode && rec_profile_need(J, J->pt, pc)) {
280,559✔
671
    emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
1✔
672
    lj_snap_add(J);
1✔
673
  }
674
}
280,559✔
675

676
static void rec_profile_ret(jit_State *J)
13,764✔
677
{
678
  if (J->prof_mode == 'f') {
13,764✔
679
    emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
×
680
    J->prev_pt = NULL;
×
681
    lj_snap_add(J);
×
682
  }
683
}
13,764✔
684

685
#endif
686

687
/* -- Record calls and returns -------------------------------------------- */
688

689
/* Specialize to the runtime value of the called function or its prototype. */
690
static TRef rec_call_specialize(jit_State *J, GCfunc *fn, TRef tr)
19,623✔
691
{
692
  TRef kfunc;
19,623✔
693
  if (isluafunc(fn)) {
19,623✔
694
    GCproto *pt = funcproto(fn);
13,390✔
695
    /* Too many closures created? Probably not a monomorphic function. */
696
    if (pt->flags >= PROTO_CLC_POLY) {  /* Specialize to prototype instead. */
13,390✔
697
      TRef trpt = emitir(IRT(IR_FLOAD, IRT_PGC), tr, IRFL_FUNC_PC);
20✔
698
      emitir(IRTG(IR_EQ, IRT_PGC), trpt, lj_ir_kptr(J, proto_bc(pt)));
20✔
699
      (void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);  /* Prevent GC of proto. */
20✔
700
      return tr;
20✔
701
    }
702
  } else {
703
    /* Don't specialize to non-monomorphic builtins. */
704
    switch (fn->c.ffid) {
6,233✔
705
    case FF_coroutine_wrap_aux:
6✔
706
    case FF_string_gmatch_aux:
707
      /* NYI: io_file_iter doesn't have an ffid, yet. */
708
      {  /* Specialize to the ffid. */
709
        TRef trid = emitir(IRT(IR_FLOAD, IRT_U8), tr, IRFL_FUNC_FFID);
6✔
710
        emitir(IRTG(IR_EQ, IRT_INT), trid, lj_ir_kint(J, fn->c.ffid));
6✔
711
      }
712
      return tr;
6✔
713
    default:
714
      /* NYI: don't specialize to non-monomorphic C functions. */
715
      break;
716
    }
717
  }
718
  /* Otherwise specialize to the function (closure) value itself. */
719
  kfunc = lj_ir_kfunc(J, fn);
19,597✔
720
  emitir(IRTG(IR_EQ, IRT_FUNC), tr, kfunc);
19,597✔
721
  return kfunc;
19,597✔
722
}
723

724
/* Record call setup. */
725
static void rec_call_setup(jit_State *J, BCReg func, ptrdiff_t nargs)
19,623✔
726
{
727
  RecordIndex ix;
19,623✔
728
  TValue *functv = &J->L->base[func];
19,623✔
729
  TRef kfunc, *fbase = &J->base[func];
19,623✔
730
  ptrdiff_t i;
19,623✔
731
  (void)getslot(J, func); /* Ensure func has a reference. */
19,623✔
732
  for (i = 1; i <= nargs; i++)
46,375✔
733
    (void)getslot(J, func+LJ_FR2+i);  /* Ensure all args have a reference. */
26,752✔
734
  if (!tref_isfunc(fbase[0])) {  /* Resolve __call metamethod. */
19,623✔
735
    ix.tab = fbase[0];
73✔
736
    copyTV(J->L, &ix.tabv, functv);
73✔
737
    if (!lj_record_mm_lookup(J, &ix, MM_call) || !tref_isfunc(ix.mobj))
73✔
738
      lj_trace_err(J, LJ_TRERR_NOMM);
×
739
    for (i = ++nargs; i > LJ_FR2; i--)  /* Shift arguments up. */
183✔
740
      fbase[i+LJ_FR2] = fbase[i+LJ_FR2-1];
110✔
741
#if LJ_FR2
742
    fbase[2] = fbase[0];
73✔
743
#endif
744
    fbase[0] = ix.mobj;  /* Replace function. */
73✔
745
    functv = &ix.mobjv;
73✔
746
  }
747
  kfunc = rec_call_specialize(J, funcV(functv), fbase[0]);
19,623✔
748
#if LJ_FR2
749
  fbase[0] = kfunc;
19,623✔
750
  fbase[1] = TREF_FRAME;
19,623✔
751
#else
752
  fbase[0] = kfunc | TREF_FRAME;
753
#endif
754
  J->maxslot = (BCReg)nargs;
19,623✔
755
}
19,623✔
756

757
/* Record call. */
758
void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs)
17,686✔
759
{
760
  rec_call_setup(J, func, nargs);
17,686✔
761
  /* Bump frame. */
762
  J->framedepth++;
17,686✔
763
  J->base += func+1+LJ_FR2;
17,686✔
764
  J->baseslot += func+1+LJ_FR2;
17,686✔
765
  if (J->baseslot + J->maxslot >= LJ_MAX_JSLOTS)
17,686✔
766
    lj_trace_err(J, LJ_TRERR_STACKOV);
1✔
767
}
17,685✔
768

769
/* Record tail call. */
770
void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs)
1,937✔
771
{
772
  rec_call_setup(J, func, nargs);
1,937✔
773
  if (frame_isvarg(J->L->base - 1)) {
1,937✔
774
    BCReg cbase = (BCReg)frame_delta(J->L->base - 1);
4✔
775
    if (--J->framedepth < 0)
4✔
776
      lj_trace_err(J, LJ_TRERR_NYIRETL);
×
777
    J->baseslot -= (BCReg)cbase;
4✔
778
    J->base -= cbase;
4✔
779
    func += cbase;
4✔
780
  }
781
  /* Move func + args down. */
782
  if (LJ_FR2 && J->baseslot == 2)
1,937✔
783
    J->base[func+1] = TREF_FRAME;
1,775✔
784
  memmove(&J->base[-1-LJ_FR2], &J->base[func], sizeof(TRef)*(J->maxslot+1+LJ_FR2));
1,937✔
785
  /* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */
786
  /* Tailcalls can form a loop, so count towards the loop unroll limit. */
787
  if (++J->tailcalled > J->loopunroll)
1,937✔
788
    lj_trace_err(J, LJ_TRERR_LUNROLL);
12✔
789
}
1,925✔
790

791
/* Check unroll limits for down-recursion. */
792
static int check_downrec_unroll(jit_State *J, GCproto *pt)
2,183✔
793
{
794
  IRRef ptref;
2,183✔
795
  for (ptref = J->chain[IR_KGC]; ptref; ptref = IR(ptref)->prev)
10,331✔
796
    if (ir_kgc(IR(ptref)) == obj2gco(pt)) {
8,223✔
797
      int count = 0;
98✔
798
      IRRef ref;
98✔
799
      for (ref = J->chain[IR_RETF]; ref; ref = IR(ref)->prev)
241✔
800
        if (IR(ref)->op1 == ptref)
143✔
801
          count++;
121✔
802
      if (count) {
98✔
803
        if (J->pc == J->startpc) {
98✔
804
          if (count + J->tailcalled > J->param[JIT_P_recunroll])
34✔
805
            return 1;
806
        } else {
807
          lj_trace_err(J, LJ_TRERR_DOWNREC);
64✔
808
        }
809
      }
810
    }
811
  return 0;
812
}
813

814
static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot);
815

816
/* Record return. */
817
void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
19,754✔
818
{
819
  TValue *frame = J->L->base - 1;
19,754✔
820
  ptrdiff_t i;
19,754✔
821
  for (i = 0; i < gotresults; i++)
36,943✔
822
    (void)getslot(J, rbase+i);  /* Ensure all results have a reference. */
17,189✔
823
  while (frame_ispcall(frame)) {  /* Immediately resolve pcall() returns. */
19,782✔
824
    BCReg cbase = (BCReg)frame_delta(frame);
36✔
825
    if (--J->framedepth <= 0)
36✔
826
      lj_trace_err(J, LJ_TRERR_NYIRETL);
8✔
827
    lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
28✔
828
    gotresults++;
28✔
829
    rbase += cbase;
28✔
830
    J->baseslot -= (BCReg)cbase;
28✔
831
    J->base -= cbase;
28✔
832
    J->base[--rbase] = TREF_TRUE;  /* Prepend true to results. */
28✔
833
    frame = frame_prevd(frame);
28✔
834
    J->needsnap = 1;  /* Stop catching on-trace errors. */
28✔
835
  }
836
  /* Return to lower frame via interpreter for unhandled cases. */
837
  if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) &&
19,746✔
838
       (!frame_islua(frame) ||
2,366✔
839
        (J->parent == 0 && J->exitno == 0 &&
2,324✔
840
         !bc_isret(bc_op(J->cur.startins))))) {
295✔
841
    /* NYI: specialize to frame type and return directly, not via RET*. */
842
    for (i = 0; i < (ptrdiff_t)rbase; i++)
397✔
843
      J->base[i] = 0;  /* Purge dead slots. */
214✔
844
    J->maxslot = rbase + (BCReg)gotresults;
183✔
845
    lj_record_stop(J, LJ_TRLINK_RETURN, 0);  /* Return to interpreter. */
183✔
846
    return;
183✔
847
  }
848
  if (frame_isvarg(frame)) {
19,563✔
849
    BCReg cbase = (BCReg)frame_delta(frame);
25✔
850
    if (--J->framedepth < 0)  /* NYI: return of vararg func to lower frame. */
25✔
851
      lj_trace_err(J, LJ_TRERR_NYIRETL);
×
852
    lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
25✔
853
    rbase += cbase;
25✔
854
    J->baseslot -= (BCReg)cbase;
25✔
855
    J->base -= cbase;
25✔
856
    frame = frame_prevd(frame);
25✔
857
  }
858
  if (frame_islua(frame)) {  /* Return to Lua frame. */
19,563✔
859
    BCIns callins = *(frame_pc(frame)-1);
18,830✔
860
    ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
18,830✔
861
    BCReg cbase = bc_a(callins);
18,830✔
862
    GCproto *pt = funcproto(frame_func(frame - (cbase+1+LJ_FR2)));
18,830✔
863
    if ((pt->flags & PROTO_NOJIT))
18,830✔
864
      lj_trace_err(J, LJ_TRERR_CJITOFF);
×
865
    if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
18,830✔
866
      if (check_downrec_unroll(J, pt)) {
2,183✔
867
        J->maxslot = (BCReg)(rbase + gotresults);
11✔
868
        lj_snap_purge(J);
11✔
869
        lj_record_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno);  /* Down-rec. */
11✔
870
        return;
11✔
871
      }
872
      lj_snap_add(J);
2,108✔
873
    }
874
    for (i = 0; i < nresults; i++)  /* Adjust results. */
33,784✔
875
      J->base[i-1-LJ_FR2] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
15,029✔
876
    J->maxslot = cbase+(BCReg)nresults;
18,755✔
877
    if (J->framedepth > 0) {  /* Return to a frame that is part of the trace. */
18,755✔
878
      J->framedepth--;
16,418✔
879
      lj_assertJ(J->baseslot > cbase+1+LJ_FR2, "bad baseslot for return");
16,418✔
880
      J->baseslot -= cbase+1+LJ_FR2;
16,418✔
881
      J->base -= cbase+1+LJ_FR2;
16,418✔
882
    } else if (J->parent == 0 && J->exitno == 0 &&
2,337✔
883
               !bc_isret(bc_op(J->cur.startins))) {
136✔
884
      /* Return to lower frame would leave the loop in a root trace. */
885
      lj_trace_err(J, LJ_TRERR_LLEAVE);
11✔
886
    } else if (J->needsnap) {  /* Tailcalled to ff with side-effects. */
2,326✔
887
      lj_trace_err(J, LJ_TRERR_NYIRETL);  /* No way to insert snapshot here. */
×
888
    } else {  /* Return to lower frame. Guard for the target we return to. */
889
      TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
2,326✔
890
      TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
2,326✔
891
      emitir(IRTG(IR_RETF, IRT_PGC), trpt, trpc);
2,326✔
892
      J->retdepth++;
2,326✔
893
      J->needsnap = 1;
2,326✔
894
      lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot for return");
2,326✔
895
      /* Shift result slots up and clear the slots of the new frame below. */
896
      memmove(J->base + cbase, J->base-1-LJ_FR2, sizeof(TRef)*nresults);
2,326✔
897
      memset(J->base-1-LJ_FR2, 0, sizeof(TRef)*(cbase+1+LJ_FR2));
2,326✔
898
    }
899
  } else if (frame_iscont(frame)) {  /* Return to continuation frame. */
733✔
900
    ASMFunction cont = frame_contf(frame);
733✔
901
    BCReg cbase = (BCReg)frame_delta(frame);
733✔
902
    if ((J->framedepth -= 2) < 0)
733✔
903
      lj_trace_err(J, LJ_TRERR_NYIRETL);
5✔
904
    J->baseslot -= (BCReg)cbase;
728✔
905
    J->base -= cbase;
728✔
906
    J->maxslot = cbase-(2<<LJ_FR2);
728✔
907
    if (cont == lj_cont_ra) {
728✔
908
      /* Copy result to destination slot. */
909
      BCReg dst = bc_a(*(frame_contpc(frame)-1));
451✔
910
      J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
451✔
911
      if (dst >= J->maxslot) {
451✔
912
        J->maxslot = dst+1;
×
913
      }
914
    } else if (cont == lj_cont_nop) {
277✔
915
      /* Nothing to do here. */
916
    } else if (cont == lj_cont_cat) {
170✔
917
      BCReg bslot = bc_b(*(frame_contpc(frame)-1));
6✔
918
      TRef tr = gotresults ? J->base[cbase+rbase] : TREF_NIL;
6✔
919
      if (bslot != J->maxslot) {  /* Concatenate the remainder. */
6✔
920
        TValue *b = J->L->base, save;  /* Simulate lower frame and result. */
3✔
921
        /* Can't handle MM_concat + CALLT + fast func side-effects. */
922
        if (J->postproc != LJ_POST_NONE)
3✔
923
          lj_trace_err(J, LJ_TRERR_NYIRETL);
1✔
924
        J->base[J->maxslot] = tr;
2✔
925
        copyTV(J->L, &save, b-(2<<LJ_FR2));
2✔
926
        if (gotresults)
927
          copyTV(J->L, b-(2<<LJ_FR2), b+rbase);
2✔
928
        else
929
          setnilV(b-(2<<LJ_FR2));
×
930
        J->L->base = b - cbase;
2✔
931
        tr = rec_cat(J, bslot, cbase-(2<<LJ_FR2));
2✔
932
        b = J->L->base + cbase;  /* Undo. */
2✔
933
        J->L->base = b;
2✔
934
        copyTV(J->L, b-(2<<LJ_FR2), &save);
2✔
935
      }
936
      if (tr) {  /* Store final result. */
5✔
937
        BCReg dst = bc_a(*(frame_contpc(frame)-1));
3✔
938
        J->base[dst] = tr;
3✔
939
        if (dst >= J->maxslot) {
3✔
940
          J->maxslot = dst+1;
×
941
        }
942
      }  /* Otherwise continue with another __concat call. */
943
    } else {
944
      /* Result type already specialized. */
945
      lj_assertJ(cont == lj_cont_condf || cont == lj_cont_condt,
946
                 "bad continuation type");
947
    }
948
  } else {
949
    lj_trace_err(J, LJ_TRERR_NYIRETL);  /* NYI: handle return to C frame. */
×
950
  }
951
  lj_assertJ(J->baseslot >= 1+LJ_FR2, "bad baseslot for return");
19,665✔
952
}
953

954
/* -- Metamethod handling ------------------------------------------------- */
955

956
/* Prepare to record call to metamethod. */
957
static BCReg rec_mm_prep(jit_State *J, ASMFunction cont)
733✔
958
{
959
  BCReg s, top = cont == lj_cont_cat ? J->maxslot : curr_proto(J->L)->framesize;
733✔
960
#if LJ_FR2
961
  J->base[top] = lj_ir_k64(J, IR_KNUM, u64ptr(contptr(cont)));
733✔
962
  J->base[top+1] = TREF_CONT;
733✔
963
#else
964
  J->base[top] = lj_ir_kptr(J, contptr(cont)) | TREF_CONT;
965
#endif
966
  J->framedepth++;
733✔
967
  for (s = J->maxslot; s < top; s++)
2,373✔
968
    J->base[s] = 0;  /* Clear frame gap to avoid resurrecting previous refs. */
1,640✔
969
  return top+1+LJ_FR2;
733✔
970
}
971

972
/* Record metamethod lookup. */
973
int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
11,206✔
974
{
975
  RecordIndex mix;
11,206✔
976
  GCtab *mt;
11,206✔
977
  if (tref_istab(ix->tab)) {
11,206✔
978
    mt = tabref(tabV(&ix->tabv)->metatable);
10,296✔
979
    mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
10,296✔
980
  } else if (tref_isudata(ix->tab)) {
910✔
981
    int udtype = udataV(&ix->tabv)->udtype;
49✔
982
    mt = tabref(udataV(&ix->tabv)->metatable);
49✔
983
    /* The metatables of special userdata objects are treated as immutable. */
984
    if (udtype != UDTYPE_USERDATA) {
49✔
985
      cTValue *mo;
44✔
986
      if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) {
44✔
987
        /* Specialize to the C library namespace object. */
988
        emitir(IRTG(IR_EQ, IRT_PGC), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv)));
44✔
989
      } else {
990
        /* Specialize to the type of userdata. */
991
        TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE);
×
992
        emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, udtype));
×
993
      }
994
  immutable_mt:
690✔
995
      mo = lj_tab_getstr(mt, mmname_str(J2G(J), mm));
690✔
996
      if (!mo || tvisnil(mo))
690✔
997
        return 0;  /* No metamethod. */
998
      /* Treat metamethod or index table as immutable, too. */
999
      if (!(tvisfunc(mo) || tvistab(mo)))
690✔
1000
        lj_trace_err(J, LJ_TRERR_BADTYPE);
×
1001
      copyTV(J->L, &ix->mobjv, mo);
690✔
1002
      ix->mobj = lj_ir_kgc(J, gcV(mo), tvisfunc(mo) ? IRT_FUNC : IRT_TAB);
690✔
1003
      ix->mtv = mt;
690✔
1004
      ix->mt = TREF_NIL;  /* Dummy value for comparison semantics. */
690✔
1005
      return 1;  /* Got metamethod or index table. */
690✔
1006
    }
1007
    mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_UDATA_META);
5✔
1008
  } else {
1009
    /* Specialize to base metatable. Must flush mcode in lua_setmetatable(). */
1010
    mt = tabref(basemt_obj(J2G(J), &ix->tabv));
861✔
1011
    if (mt == NULL) {
861✔
1012
      ix->mt = TREF_NIL;
50✔
1013
      return 0;  /* No metamethod. */
50✔
1014
    }
1015
    /* The cdata metatable is treated as immutable. */
1016
    if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt;
811✔
1017
#if LJ_GC64
1018
    /* TODO: fix ARM32 asm_fload(), so we can use this for all archs. */
1019
    ix->mt = mix.tab = lj_ir_ggfload(J, IRT_TAB,
329✔
1020
      GG_OFS(g.gcroot[GCROOT_BASEMT+itypemap(&ix->tabv)]));
164✔
1021
#else
1022
    ix->mt = mix.tab = lj_ir_ktab(J, mt);
1023
#endif
1024
    goto nocheck;
165✔
1025
  }
1026
  ix->mt = mt ? mix.tab : TREF_NIL;
10,301✔
1027
  emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mix.tab, lj_ir_knull(J, IRT_TAB));
20,208✔
1028
nocheck:
10,466✔
1029
  if (mt) {
10,466✔
1030
    GCstr *mmstr = mmname_str(J2G(J), mm);
559✔
1031
    cTValue *mo = lj_tab_getstr(mt, mmstr);
559✔
1032
    if (mo && !tvisnil(mo))
559✔
1033
      copyTV(J->L, &ix->mobjv, mo);
499✔
1034
    ix->mtv = mt;
559✔
1035
    settabV(J->L, &mix.tabv, mt);
559✔
1036
    setstrV(J->L, &mix.keyv, mmstr);
559✔
1037
    mix.key = lj_ir_kstr(J, mmstr);
559✔
1038
    mix.val = 0;
559✔
1039
    mix.idxchain = 0;
559✔
1040
    ix->mobj = lj_record_idx(J, &mix);
559✔
1041
    return !tref_isnil(ix->mobj);  /* 1 if metamethod found, 0 if not. */
559✔
1042
  }
1043
  return 0;  /* No metamethod. */
1044
}
1045

1046
/* Record call to arithmetic metamethod. */
1047
static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
156✔
1048
{
1049
  /* Set up metamethod call first to save ix->tab and ix->tabv. */
1050
  BCReg func = rec_mm_prep(J, mm == MM_concat ? lj_cont_cat : lj_cont_ra);
306✔
1051
  TRef *base = J->base + func;
156✔
1052
  TValue *basev = J->L->base + func;
156✔
1053
  base[1+LJ_FR2] = ix->tab; base[2+LJ_FR2] = ix->key;
156✔
1054
  copyTV(J->L, basev+1+LJ_FR2, &ix->tabv);
156✔
1055
  copyTV(J->L, basev+2+LJ_FR2, &ix->keyv);
156✔
1056
  if (!lj_record_mm_lookup(J, ix, mm)) {  /* Lookup mm on 1st operand. */
156✔
1057
    if (mm != MM_unm) {
9✔
1058
      ix->tab = ix->key;
9✔
1059
      copyTV(J->L, &ix->tabv, &ix->keyv);
9✔
1060
      if (lj_record_mm_lookup(J, ix, mm))  /* Lookup mm on 2nd operand. */
9✔
1061
        goto ok;
9✔
1062
    }
1063
    lj_trace_err(J, LJ_TRERR_NOMM);
×
1064
  }
1065
ok:
147✔
1066
  base[0] = ix->mobj;
156✔
1067
#if LJ_FR2
1068
  base[1] = 0;
156✔
1069
#endif
1070
  copyTV(J->L, basev+0, &ix->mobjv);
156✔
1071
  lj_record_call(J, func, 2);
156✔
1072
  return 0;  /* No result yet. */
155✔
1073
}
1074

1075
/* Record call to __len metamethod. */
1076
static TRef rec_mm_len(jit_State *J, TRef tr, TValue *tv)
1077
{
1078
  RecordIndex ix;
1079
  ix.tab = tr;
1080
  copyTV(J->L, &ix.tabv, tv);
1081
  if (lj_record_mm_lookup(J, &ix, MM_len)) {
1082
    BCReg func = rec_mm_prep(J, lj_cont_ra);
1083
    TRef *base = J->base + func;
1084
    TValue *basev = J->L->base + func;
1085
    base[0] = ix.mobj; copyTV(J->L, basev+0, &ix.mobjv);
1086
    base += LJ_FR2;
1087
    basev += LJ_FR2;
1088
    base[1] = tr; copyTV(J->L, basev+1, tv);
1089
#if LJ_52
1090
    base[2] = tr; copyTV(J->L, basev+2, tv);
1091
#else
1092
    base[2] = TREF_NIL; setnilV(basev+2);
1093
#endif
1094
    lj_record_call(J, func, 2);
1095
  } else {
1096
    if (LJ_52 && tref_istab(tr))
1097
      return lj_ir_call(J, IRCALL_lj_tab_len, tr);
1098
    lj_trace_err(J, LJ_TRERR_NOMM);
1099
  }
1100
  return 0;  /* No result yet. */
1101
}
1102

1103
/* Call a comparison metamethod. */
1104
static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op)
164✔
1105
{
1106
  BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt);
242✔
1107
  TRef *base = J->base + func + LJ_FR2;
164✔
1108
  TValue *tv = J->L->base + func + LJ_FR2;
164✔
1109
  base[-LJ_FR2] = ix->mobj; base[1] = ix->val; base[2] = ix->key;
164✔
1110
  copyTV(J->L, tv-LJ_FR2, &ix->mobjv);
164✔
1111
  copyTV(J->L, tv+1, &ix->valv);
164✔
1112
  copyTV(J->L, tv+2, &ix->keyv);
164✔
1113
  lj_record_call(J, func, 2);
164✔
1114
}
164✔
1115

1116
/* Record call to equality comparison metamethod (for tab and udata only). */
1117
static void rec_mm_equal(jit_State *J, RecordIndex *ix, int op)
10✔
1118
{
1119
  ix->tab = ix->val;
10✔
1120
  copyTV(J->L, &ix->tabv, &ix->valv);
10✔
1121
  if (lj_record_mm_lookup(J, ix, MM_eq)) {  /* Lookup mm on 1st operand. */
10✔
1122
    cTValue *bv;
9✔
1123
    TRef mo1 = ix->mobj;
9✔
1124
    TValue mo1v;
9✔
1125
    copyTV(J->L, &mo1v, &ix->mobjv);
9✔
1126
    /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
1127
    bv = &ix->keyv;
9✔
1128
    if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
18✔
1129
      TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
9✔
1130
      emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
9✔
1131
    } else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
×
1132
      TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
×
1133
      emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
×
1134
    } else {  /* Lookup metamethod on 2nd operand and compare both. */
1135
      ix->tab = ix->key;
×
1136
      copyTV(J->L, &ix->tabv, bv);
×
1137
      if (!lj_record_mm_lookup(J, ix, MM_eq) ||
×
1138
          lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
×
1139
        return;
×
1140
    }
1141
    rec_mm_callcomp(J, ix, op);
9✔
1142
  }
1143
}
1144

1145
/* Record call to ordered comparison metamethods (for arbitrary objects). */
1146
static void rec_mm_comp(jit_State *J, RecordIndex *ix, int op)
49✔
1147
{
1148
  ix->tab = ix->val;
49✔
1149
  copyTV(J->L, &ix->tabv, &ix->valv);
49✔
1150
  while (1) {
67✔
1151
    MMS mm = (op & 2) ? MM_le : MM_lt;  /* Try __le + __lt or only __lt. */
58✔
1152
#if LJ_52
1153
    if (!lj_record_mm_lookup(J, ix, mm)) {  /* Lookup mm on 1st operand. */
1154
      ix->tab = ix->key;
1155
      copyTV(J->L, &ix->tabv, &ix->keyv);
1156
      if (!lj_record_mm_lookup(J, ix, mm))  /* Lookup mm on 2nd operand. */
1157
        goto nomatch;
1158
    }
1159
    rec_mm_callcomp(J, ix, op);
1160
    return;
1161
#else
1162
    if (lj_record_mm_lookup(J, ix, mm)) {  /* Lookup mm on 1st operand. */
58✔
1163
      cTValue *bv;
49✔
1164
      TRef mo1 = ix->mobj;
49✔
1165
      TValue mo1v;
49✔
1166
      copyTV(J->L, &mo1v, &ix->mobjv);
49✔
1167
      /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
1168
      bv = &ix->keyv;
49✔
1169
      if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
98✔
1170
        TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
49✔
1171
        emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
49✔
1172
      } else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
×
1173
        TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
×
1174
        emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
×
1175
      } else {  /* Lookup metamethod on 2nd operand and compare both. */
1176
        ix->tab = ix->key;
×
1177
        copyTV(J->L, &ix->tabv, bv);
×
1178
        if (!lj_record_mm_lookup(J, ix, mm) ||
×
1179
            lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
×
1180
          goto nomatch;
×
1181
      }
1182
      rec_mm_callcomp(J, ix, op);
49✔
1183
      return;
49✔
1184
    }
1185
#endif
1186
  nomatch:
9✔
1187
    /* Lookup failed. Retry with  __lt and swapped operands. */
1188
    if (!(op & 2)) break;  /* Already at __lt. Interpreter will throw. */
9✔
1189
    ix->tab = ix->key; ix->key = ix->val; ix->val = ix->tab;
9✔
1190
    copyTV(J->L, &ix->tabv, &ix->keyv);
9✔
1191
    copyTV(J->L, &ix->keyv, &ix->valv);
9✔
1192
    copyTV(J->L, &ix->valv, &ix->tabv);
9✔
1193
    op ^= 3;
9✔
1194
  }
1195
}
1196

1197
#if LJ_HASFFI
1198
/* Setup call to cdata comparison metamethod. */
1199
static void rec_mm_comp_cdata(jit_State *J, RecordIndex *ix, int op, MMS mm)
106✔
1200
{
1201
  lj_snap_add(J);
106✔
1202
  if (tref_iscdata(ix->val)) {
106✔
1203
    ix->tab = ix->val;
13✔
1204
    copyTV(J->L, &ix->tabv, &ix->valv);
13✔
1205
  } else {
1206
    lj_assertJ(tref_iscdata(ix->key), "cdata expected");
93✔
1207
    ix->tab = ix->key;
93✔
1208
    copyTV(J->L, &ix->tabv, &ix->keyv);
93✔
1209
  }
1210
  lj_record_mm_lookup(J, ix, mm);
106✔
1211
  rec_mm_callcomp(J, ix, op);
106✔
1212
}
106✔
1213
#endif
1214

1215
/* -- Indexed access ------------------------------------------------------ */
1216

1217
#ifdef LUAJIT_ENABLE_TABLE_BUMP
1218
/* Bump table allocations in bytecode when they grow during recording. */
1219
static void rec_idx_bump(jit_State *J, RecordIndex *ix)
1220
{
1221
  RBCHashEntry *rbc = &J->rbchash[(ix->tab & (RBCHASH_SLOTS-1))];
1222
  if (tref_ref(ix->tab) == rbc->ref) {
1223
    const BCIns *pc = mref(rbc->pc, const BCIns);
1224
    GCtab *tb = tabV(&ix->tabv);
1225
    uint32_t nhbits;
1226
    IRIns *ir;
1227
    if (!tvisnil(&ix->keyv))
1228
      (void)lj_tab_set(J->L, tb, &ix->keyv);  /* Grow table right now. */
1229
    nhbits = tb->hmask > 0 ? lj_fls(tb->hmask)+1 : 0;
1230
    ir = IR(tref_ref(ix->tab));
1231
    if (ir->o == IR_TNEW) {
1232
      uint32_t ah = bc_d(*pc);
1233
      uint32_t asize = ah & 0x7ff, hbits = ah >> 11;
1234
      if (nhbits > hbits) hbits = nhbits;
1235
      if (tb->asize > asize) {
1236
        asize = tb->asize <= 0x7ff ? tb->asize : 0x7ff;
1237
      }
1238
      if ((asize | (hbits<<11)) != ah) {  /* Has the size changed? */
1239
        /* Patch bytecode, but continue recording (for more patching). */
1240
        setbc_d(pc, (asize | (hbits<<11)));
1241
        /* Patching TNEW operands is only safe if the trace is aborted. */
1242
        ir->op1 = asize; ir->op2 = hbits;
1243
        J->retryrec = 1;  /* Abort the trace at the end of recording. */
1244
      }
1245
    } else if (ir->o == IR_TDUP) {
1246
      GCtab *tpl = gco2tab(proto_kgc(&gcref(rbc->pt)->pt, ~(ptrdiff_t)bc_d(*pc)));
1247
      /* Grow template table, but preserve keys with nil values. */
1248
      if ((tb->asize > tpl->asize && (1u << nhbits)-1 == tpl->hmask) ||
1249
          (tb->asize == tpl->asize && (1u << nhbits)-1 > tpl->hmask)) {
1250
        Node *node = noderef(tpl->node);
1251
        uint32_t i, hmask = tpl->hmask, asize;
1252
        TValue *array;
1253
        for (i = 0; i <= hmask; i++) {
1254
          if (!tvisnil(&node[i].key) && tvisnil(&node[i].val))
1255
            settabV(J->L, &node[i].val, tpl);
1256
        }
1257
        if (!tvisnil(&ix->keyv) && tref_isk(ix->key)) {
1258
          TValue *o = lj_tab_set(J->L, tpl, &ix->keyv);
1259
          if (tvisnil(o)) settabV(J->L, o, tpl);
1260
        }
1261
        lj_tab_resize(J->L, tpl, tb->asize, nhbits);
1262
        node = noderef(tpl->node);
1263
        hmask = tpl->hmask;
1264
        for (i = 0; i <= hmask; i++) {
1265
          /* This is safe, since template tables only hold immutable values. */
1266
          if (tvistab(&node[i].val))
1267
            setnilV(&node[i].val);
1268
        }
1269
        /* The shape of the table may have changed. Clean up array part, too. */
1270
        asize = tpl->asize;
1271
        array = tvref(tpl->array);
1272
        for (i = 0; i < asize; i++) {
1273
          if (tvistab(&array[i]))
1274
            setnilV(&array[i]);
1275
        }
1276
        J->retryrec = 1;  /* Abort the trace at the end of recording. */
1277
      }
1278
    }
1279
  }
1280
}
1281
#endif
1282

1283
/* Record bounds-check. */
1284
static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize)
4,894✔
1285
{
1286
  /* Try to emit invariant bounds checks. */
1287
  if ((J->flags & (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) ==
4,894✔
1288
      (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) {
1289
    IRRef ref = tref_ref(ikey);
4,883✔
1290
    IRIns *ir = IR(ref);
4,883✔
1291
    int32_t ofs = 0;
4,883✔
1292
    IRRef ofsref = 0;
4,883✔
1293
    /* Handle constant offsets. */
1294
    if (ir->o == IR_ADD && irref_isk(ir->op2)) {
4,883✔
1295
      ofsref = ir->op2;
144✔
1296
      ofs = IR(ofsref)->i;
144✔
1297
      ref = ir->op1;
144✔
1298
      ir = IR(ref);
144✔
1299
    }
1300
    /* Got scalar evolution analysis results for this reference? */
1301
    if (ref == J->scev.idx) {
4,883✔
1302
      int32_t stop;
3,665✔
1303
      lj_assertJ(irt_isint(J->scev.t) && ir->o == IR_SLOAD,
3,665✔
1304
                 "only int SCEV supported");
1305
      stop = numberVint(&(J->L->base - J->baseslot)[ir->op1 + FORL_STOP]);
3,665✔
1306
      /* Runtime value for stop of loop is within bounds? */
1307
      if ((uint64_t)stop + ofs < (uint64_t)asize) {
3,665✔
1308
        /* Emit invariant bounds check for stop. */
1309
        emitir(IRTG(IR_ABC, IRT_P32), asizeref, ofs == 0 ? J->scev.stop :
114✔
1310
               emitir(IRTI(IR_ADD), J->scev.stop, ofsref));
1311
        /* Emit invariant bounds check for start, if not const or negative. */
1312
        if (!(J->scev.dir && J->scev.start &&
114✔
1313
              (int64_t)IR(J->scev.start)->i + ofs >= 0))
104✔
1314
          emitir(IRTG(IR_ABC, IRT_P32), asizeref, ikey);
10✔
1315
        return;
114✔
1316
      }
1317
    }
1318
  }
1319
  emitir(IRTGI(IR_ABC), asizeref, ikey);  /* Emit regular bounds check. */
4,780✔
1320
}
1321

1322
/* Record indexed key lookup. */
1323
static TRef rec_idx_key(jit_State *J, RecordIndex *ix, IRRef *rbref,
117,351✔
1324
                        IRType1 *rbguard)
1325
{
1326
  TRef key;
117,351✔
1327
  GCtab *t = tabV(&ix->tabv);
117,351✔
1328
  ix->oldv = lj_tab_get(J->L, t, &ix->keyv);  /* Lookup previous value. */
117,351✔
1329
  *rbref = 0;
117,351✔
1330
  rbguard->irt = 0;
117,351✔
1331

1332
  /* Integer keys are looked up in the array part first. */
1333
  key = ix->key;
117,351✔
1334
  if (tref_isnumber(key)) {
117,351✔
1335
    int32_t k = numberVint(&ix->keyv);
5,166✔
1336
    if (!tvisint(&ix->keyv) && numV(&ix->keyv) != (lua_Number)k)
5,166✔
1337
      k = LJ_MAX_ASIZE;
47✔
1338
    if ((MSize)k < LJ_MAX_ASIZE) {  /* Potential array key? */
5,166✔
1339
      TRef ikey = lj_opt_narrow_index(J, key);
5,089✔
1340
      TRef asizeref = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
5,089✔
1341
      if ((MSize)k < t->asize) {  /* Currently an array key? */
5,089✔
1342
        TRef arrayref;
4,891✔
1343
        rec_idx_abc(J, asizeref, ikey, t->asize);
4,891✔
1344
        arrayref = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_ARRAY);
4,891✔
1345
        return emitir(IRT(IR_AREF, IRT_PGC), arrayref, ikey);
4,891✔
1346
      } else {  /* Currently not in array (may be an array extension)? */
1347
        emitir(IRTGI(IR_ULE), asizeref, ikey);  /* Inv. bounds check. */
198✔
1348
        if (k == 0 && tref_isk(key))
198✔
1349
          key = lj_ir_knum_zero(J);  /* Canonicalize 0 or +-0.0 to +0.0. */
4✔
1350
        /* And continue with the hash lookup. */
1351
      }
1352
    } else if (!tref_isk(key)) {
77✔
1353
      /* We can rule out const numbers which failed the integerness test
1354
      ** above. But all other numbers are potential array keys.
1355
      */
1356
      if (t->asize == 0) {  /* True sparse tables have an empty array part. */
77✔
1357
        /* Guard that the array part stays empty. */
1358
        TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
69✔
1359
        emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
69✔
1360
      } else {
1361
        lj_trace_err(J, LJ_TRERR_NYITMIX);
8✔
1362
      }
1363
    }
1364
  }
1365

1366
  /* Otherwise the key is located in the hash part. */
1367
  if (t->hmask == 0) {  /* Shortcut for empty hash part. */
112,452✔
1368
    /* Guard that the hash part stays empty. */
1369
    TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
437✔
1370
    emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
437✔
1371
    return lj_ir_kkptr(J, niltvg(J2G(J)));
437✔
1372
  }
1373
  if (tref_isinteger(key))  /* Hash keys are based on numbers, not ints. */
112,015✔
1374
    key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
67✔
1375
  if (tref_isk(key)) {
112,015✔
1376
    /* Optimize lookup of constant hash keys. */
1377
    MSize hslot = (MSize)((char *)ix->oldv - (char *)&noderef(t->node)[0].val);
111,806✔
1378
    if (t->hmask > 0 && hslot <= t->hmask*(MSize)sizeof(Node) &&
111,806✔
1379
        hslot <= 65535*(MSize)sizeof(Node)) {
1380
      TRef node, kslot, hm;
103,853✔
1381
      *rbref = J->cur.nins;  /* Mark possible rollback point. */
103,853✔
1382
      *rbguard = J->guardemit;
103,853✔
1383
      hm = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
103,853✔
1384
      emitir(IRTGI(IR_EQ), hm, lj_ir_kint(J, (int32_t)t->hmask));
103,853✔
1385
      node = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_NODE);
103,853✔
1386
      kslot = lj_ir_kslot(J, key, hslot / sizeof(Node));
103,853✔
1387
      return emitir(IRTG(IR_HREFK, IRT_PGC), node, kslot);
103,853✔
1388
    }
1389
  }
1390
  /* Fall back to a regular hash lookup. */
1391
  return emitir(IRT(IR_HREF, IRT_PGC), ix->tab, key);
8,162✔
1392
}
1393

1394
/* Determine whether a key is NOT one of the fast metamethod names. */
1395
static int nommstr(jit_State *J, TRef key)
51,946✔
1396
{
1397
  if (tref_isstr(key)) {
51,946✔
1398
    if (tref_isk(key)) {
49,194✔
1399
      GCstr *str = ir_kstr(IR(tref_ref(key)));
49,182✔
1400
      uint32_t mm;
49,182✔
1401
      for (mm = 0; mm <= MM_FAST; mm++)
344,274✔
1402
        if (mmname_str(J2G(J), mm) == str)
295,092✔
1403
          return 0;  /* MUST be one the fast metamethod names. */
1404
    } else {
1405
      return 0;  /* Variable string key MAY be a metamethod name. */
1406
    }
1407
  }
1408
  return 1;  /* CANNOT be a metamethod name. */
1409
}
1410

1411
/* Record indexed load/store. */
1412
TRef lj_record_idx(jit_State *J, RecordIndex *ix)
117,536✔
1413
{
1414
  TRef xref;
117,536✔
1415
  IROp xrefop, loadop;
117,536✔
1416
  IRRef rbref;
117,536✔
1417
  IRType1 rbguard;
117,536✔
1418
  cTValue *oldv;
117,536✔
1419

1420
  while (!tref_istab(ix->tab)) { /* Handle non-table lookup. */
117,915✔
1421
    /* Never call raw lj_record_idx() on non-table. */
1422
    lj_assertJ(ix->idxchain != 0, "bad usage");
562✔
1423
    if (!lj_record_mm_lookup(J, ix, ix->val ? MM_newindex : MM_index))
562✔
1424
      lj_trace_err(J, LJ_TRERR_NOMM);
×
1425
  handlemm:
562✔
1426
    if (tref_isfunc(ix->mobj)) {  /* Handle metamethod call. */
791✔
1427
      BCReg func = rec_mm_prep(J, ix->val ? lj_cont_nop : lj_cont_ra);
716✔
1428
      TRef *base = J->base + func + LJ_FR2;
412✔
1429
      TValue *tv = J->L->base + func + LJ_FR2;
412✔
1430
      base[-LJ_FR2] = ix->mobj; base[1] = ix->tab; base[2] = ix->key;
412✔
1431
      setfuncV(J->L, tv-LJ_FR2, funcV(&ix->mobjv));
412✔
1432
      copyTV(J->L, tv+1, &ix->tabv);
412✔
1433
      copyTV(J->L, tv+2, &ix->keyv);
412✔
1434
      if (ix->val) {
412✔
1435
        base[3] = ix->val;
108✔
1436
        copyTV(J->L, tv+3, &ix->valv);
108✔
1437
        lj_record_call(J, func, 3);  /* mobj(tab, key, val) */
108✔
1438
        return 0;
108✔
1439
      } else {
1440
        lj_record_call(J, func, 2);  /* res = mobj(tab, key) */
304✔
1441
        return 0;  /* No result yet. */
304✔
1442
      }
1443
    }
1444
    /* Otherwise retry lookup with metaobject. */
1445
    ix->tab = ix->mobj;
379✔
1446
    copyTV(J->L, &ix->tabv, &ix->mobjv);
379✔
1447
    if (--ix->idxchain == 0)
379✔
1448
      lj_trace_err(J, LJ_TRERR_IDXLOOP);
×
1449
  }
1450

1451
  /* First catch nil and NaN keys for tables. */
1452
  if (tvisnil(&ix->keyv) || (tvisnum(&ix->keyv) && tvisnan(&ix->keyv))) {
117,353✔
1453
    if (ix->val)  /* Better fail early. */
2✔
1454
      lj_trace_err(J, LJ_TRERR_STORENN);
2✔
1455
    if (tref_isk(ix->key)) {
×
1456
      if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
×
1457
        goto handlemm;
×
1458
      return TREF_NIL;
×
1459
    }
1460
  }
1461

1462
  /* Record the key lookup. */
1463
  xref = rec_idx_key(J, ix, &rbref, &rbguard);
117,351✔
1464
  xrefop = IR(tref_ref(xref))->o;
117,343✔
1465
  loadop = xrefop == IR_AREF ? IR_ALOAD : IR_HLOAD;
117,343✔
1466
  /* The lj_meta_tset() inconsistency is gone, but better play safe. */
1467
  oldv = xrefop == IR_KKPTR ? (cTValue *)ir_kptr(IR(tref_ref(xref))) : ix->oldv;
117,343✔
1468

1469
  if (ix->val == 0) {  /* Indexed load */
117,343✔
1470
    IRType t = itype2irt(oldv);
65,386✔
1471
    TRef res;
65,386✔
1472
    if (oldv == niltvg(J2G(J))) {
65,386✔
1473
      emitir(IRTG(IR_EQ, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1,205✔
1474
      res = TREF_NIL;
1,205✔
1475
    } else {
1476
      res = emitir(IRTG(loadop, t), xref, 0);
64,181✔
1477
    }
1478
    if (tref_ref(res) < rbref) {  /* HREFK + load forwarded? */
65,386✔
1479
      lj_ir_rollback(J, rbref);  /* Rollback to eliminate hmask guard. */
5,253✔
1480
      J->guardemit = rbguard;
5,253✔
1481
    }
1482
    if (t == IRT_NIL && ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
65,386✔
1483
      goto handlemm;
218✔
1484
    if (irtype_ispri(t)) res = TREF_PRI(t);  /* Canonicalize primitives. */
65,168✔
1485
    return res;
65,168✔
1486
  } else {  /* Indexed store. */
1487
    GCtab *mt = tabref(tabV(&ix->tabv)->metatable);
51,957✔
1488
    int keybarrier = tref_isgcv(ix->key) && !tref_isnil(ix->val);
51,957✔
1489
    if (tref_ref(xref) < rbref) {  /* HREFK forwarded? */
51,957✔
1490
      lj_ir_rollback(J, rbref);  /* Rollback to eliminate hmask guard. */
641✔
1491
      J->guardemit = rbguard;
641✔
1492
    }
1493
    if (tvisnil(oldv)) {  /* Previous value was nil? */
51,957✔
1494
      /* Need to duplicate the hasmm check for the early guards. */
1495
      int hasmm = 0;
8,488✔
1496
      if (ix->idxchain && mt) {
8,488✔
1497
        cTValue *mo = lj_tab_getstr(mt, mmname_str(J2G(J), MM_newindex));
27✔
1498
        hasmm = mo && !tvisnil(mo);
27✔
1499
      }
1500
      if (hasmm)
11✔
1501
        emitir(IRTG(loadop, IRT_NIL), xref, 0);  /* Guard for nil value. */
11✔
1502
      else if (xrefop == IR_HREF)
8,477✔
1503
        emitir(IRTG(oldv == niltvg(J2G(J)) ? IR_EQ : IR_NE, IRT_PGC),
6,903✔
1504
               xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1505
      if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_newindex)) {
8,488✔
1506
        lj_assertJ(hasmm, "inconsistent metamethod handling");
11✔
1507
        goto handlemm;
11✔
1508
      }
1509
      lj_assertJ(!hasmm, "inconsistent metamethod handling");
8,477✔
1510
      if (oldv == niltvg(J2G(J))) {  /* Need to insert a new key. */
8,477✔
1511
        TRef key = ix->key;
7,280✔
1512
        if (tref_isinteger(key)) {  /* NEWREF needs a TValue as a key. */
7,280✔
1513
          key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
116✔
1514
        } else if (tref_isnum(key)) {
7,164✔
1515
          if (tref_isk(key)) {
51✔
1516
            if (tvismzero(&ix->keyv))
2✔
1517
              key = lj_ir_knum_zero(J);  /* Canonicalize -0.0 to +0.0. */
2✔
1518
          } else {
1519
            emitir(IRTG(IR_EQ, IRT_NUM), key, key);  /* Check for !NaN. */
49✔
1520
          }
1521
        }
1522
        xref = emitir(IRT(IR_NEWREF, IRT_PGC), ix->tab, key);
7,280✔
1523
        keybarrier = 0;  /* NEWREF already takes care of the key barrier. */
7,280✔
1524
#ifdef LUAJIT_ENABLE_TABLE_BUMP
1525
        if ((J->flags & JIT_F_OPT_SINK))  /* Avoid a separate flag. */
1526
          rec_idx_bump(J, ix);
1527
#endif
1528
      }
1529
    } else if (!lj_opt_fwd_wasnonnil(J, loadop, tref_ref(xref))) {
43,469✔
1530
      /* Cannot derive that the previous value was non-nil, must do checks. */
1531
      if (xrefop == IR_HREF)  /* Guard against store to niltv. */
40,941✔
1532
        emitir(IRTG(IR_NE, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
13✔
1533
      if (ix->idxchain) {  /* Metamethod lookup required? */
40,941✔
1534
        /* A check for NULL metatable is cheaper (hoistable) than a load. */
1535
        if (!mt) {
40,933✔
1536
          TRef mtref = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
40,919✔
1537
          emitir(IRTG(IR_EQ, IRT_TAB), mtref, lj_ir_knull(J, IRT_TAB));
40,919✔
1538
        } else {
1539
          IRType t = itype2irt(oldv);
14✔
1540
          emitir(IRTG(loadop, t), xref, 0);  /* Guard for non-nil value. */
14✔
1541
        }
1542
      }
1543
    } else {
1544
      keybarrier = 0;  /* Previous non-nil value kept the key alive. */
1545
    }
1546
    /* Convert int to number before storing. */
1547
    if (!LJ_DUALNUM && tref_isinteger(ix->val))
51,946✔
1548
      ix->val = emitir(IRTN(IR_CONV), ix->val, IRCONV_NUM_INT);
560✔
1549
    emitir(IRT(loadop+IRDELTA_L2S, tref_type(ix->val)), xref, ix->val);
51,946✔
1550
    if (keybarrier || tref_isgcv(ix->val))
51,946✔
1551
      emitir(IRT(IR_TBAR, IRT_NIL), ix->tab, 0);
42,796✔
1552
    /* Invalidate neg. metamethod cache for stores with certain string keys. */
1553
    if (!nommstr(J, ix->key)) {
101,128✔
1554
      TRef fref = emitir(IRT(IR_FREF, IRT_PGC), ix->tab, IRFL_TAB_NOMM);
12✔
1555
      emitir(IRT(IR_FSTORE, IRT_U8), fref, lj_ir_kint(J, 0));
12✔
1556
    }
1557
    J->needsnap = 1;
51,946✔
1558
    return 0;
51,946✔
1559
  }
1560
}
1561

1562
static void rec_tsetm(jit_State *J, BCReg ra, BCReg rn, int32_t i)
5✔
1563
{
1564
  RecordIndex ix;
5✔
1565
  cTValue *basev = J->L->base;
5✔
1566
  GCtab *t = tabV(&basev[ra-1]);
5✔
1567
  settabV(J->L, &ix.tabv, t);
5✔
1568
  ix.tab = getslot(J, ra-1);
5✔
1569
  ix.idxchain = 0;
5✔
1570
#ifdef LUAJIT_ENABLE_TABLE_BUMP
1571
  if ((J->flags & JIT_F_OPT_SINK)) {
1572
    if (t->asize < i+rn-ra)
1573
      lj_tab_reasize(J->L, t, i+rn-ra);
1574
    setnilV(&ix.keyv);
1575
    rec_idx_bump(J, &ix);
1576
  }
1577
#endif
1578
  for (; ra < rn; i++, ra++) {
14✔
1579
    setintV(&ix.keyv, i);
9✔
1580
    ix.key = lj_ir_kint(J, i);
9✔
1581
    copyTV(J->L, &ix.valv, &basev[ra]);
9✔
1582
    ix.val = getslot(J, ra);
9✔
1583
    lj_record_idx(J, &ix);
9✔
1584
  }
1585
}
5✔
1586

1587
/* -- Upvalue access ------------------------------------------------------ */
1588

1589
/* Check whether upvalue is immutable and ok to constify. */
1590
static int rec_upvalue_constify(jit_State *J, GCupval *uvp)
1591
{
1592
  if (uvp->immutable) {
1593
    cTValue *o = uvval(uvp);
1594
    /* Don't constify objects that may retain large amounts of memory. */
1595
#if LJ_HASFFI
1596
    if (tviscdata(o)) {
1597
      GCcdata *cd = cdataV(o);
1598
      if (!cdataisv(cd) && !(cd->marked & LJ_GC_CDATA_FIN)) {
1599
        CType *ct = ctype_raw(ctype_ctsG(J2G(J)), cd->ctypeid);
1600
        if (!ctype_hassize(ct->info) || ct->size <= 16)
1601
          return 1;
1602
      }
1603
      return 0;
1604
    }
1605
#else
1606
    UNUSED(J);
1607
#endif
1608
    if (!(tvistab(o) || tvisudata(o) || tvisthread(o)))
1609
      return 1;
1610
  }
1611
  return 0;
1612
}
1613

1614
/* Record upvalue load/store. */
1615
static TRef rec_upvalue(jit_State *J, uint32_t uv, TRef val)
16,538✔
1616
{
1617
  GCupval *uvp = &gcref(J->fn->l.uvptr[uv])->uv;
16,538✔
1618
  TRef fn = getcurrf(J);
16,538✔
1619
  IRRef uref;
16,538✔
1620
  int needbarrier = 0;
16,538✔
1621
  if (rec_upvalue_constify(J, uvp)) {  /* Try to constify immutable upvalue. */
16,538✔
1622
    TRef tr, kfunc;
15,486✔
1623
    lj_assertJ(val == 0, "bad usage");
15,486✔
1624
    if (!tref_isk(fn)) {  /* Late specialization of current function. */
15,486✔
1625
      if (J->pt->flags >= PROTO_CLC_POLY)
2,379✔
1626
        goto noconstify;
89✔
1627
      kfunc = lj_ir_kfunc(J, J->fn);
2,290✔
1628
      emitir(IRTG(IR_EQ, IRT_FUNC), fn, kfunc);
2,290✔
1629
#if LJ_FR2
1630
      J->base[-2] = kfunc;
2,290✔
1631
#else
1632
      J->base[-1] = kfunc | TREF_FRAME;
1633
#endif
1634
      fn = kfunc;
2,290✔
1635
    }
1636
    tr = lj_record_constify(J, uvval(uvp));
15,397✔
1637
    if (tr)
15,397✔
1638
      return tr;
1639
  }
1640
noconstify:
1,052✔
1641
  /* Note: this effectively limits LJ_MAX_UPVAL to 127. */
1642
  uv = (uv << 8) | (hashrot(uvp->dhash, uvp->dhash + HASH_BIAS) & 0xff);
1,141✔
1643
  if (!uvp->closed) {
1,141✔
1644
    uref = tref_ref(emitir(IRTG(IR_UREFO, IRT_PGC), fn, uv));
383✔
1645
    /* In current stack? */
1646
    if (uvval(uvp) >= tvref(J->L->stack) &&
383✔
1647
        uvval(uvp) < tvref(J->L->maxstack)) {
383✔
1648
      int32_t slot = (int32_t)(uvval(uvp) - (J->L->base - J->baseslot));
374✔
1649
      if (slot >= 0) {  /* Aliases an SSA slot? */
374✔
1650
        emitir(IRTG(IR_EQ, IRT_PGC),
210✔
1651
               REF_BASE,
1652
               emitir(IRT(IR_ADD, IRT_PGC), uref,
1653
                      lj_ir_kint(J, (slot - 1 - LJ_FR2) * -8)));
1654
        slot -= (int32_t)J->baseslot;  /* Note: slot number may be negative! */
210✔
1655
        if (val == 0) {
210✔
1656
          return getslot(J, slot);
93✔
1657
        } else {
1658
          J->base[slot] = val;
117✔
1659
          if (slot >= (int32_t)J->maxslot) J->maxslot = (BCReg)(slot+1);
117✔
1660
          return 0;
117✔
1661
        }
1662
      }
1663
    }
1664
    emitir(IRTG(IR_UGT, IRT_PGC),
173✔
1665
           emitir(IRT(IR_SUB, IRT_PGC), uref, REF_BASE),
1666
           lj_ir_kint(J, (J->baseslot + J->maxslot) * 8));
1667
  } else {
1668
    needbarrier = 1;
758✔
1669
    uref = tref_ref(emitir(IRTG(IR_UREFC, IRT_PGC), fn, uv));
758✔
1670
  }
1671
  if (val == 0) {  /* Upvalue load */
931✔
1672
    IRType t = itype2irt(uvval(uvp));
880✔
1673
    TRef res = emitir(IRTG(IR_ULOAD, t), uref, 0);
880✔
1674
    if (irtype_ispri(t)) res = TREF_PRI(t);  /* Canonicalize primitive refs. */
880✔
1675
    return res;
880✔
1676
  } else {  /* Upvalue store. */
1677
    /* Convert int to number before storing. */
1678
    if (!LJ_DUALNUM && tref_isinteger(val))
51✔
1679
      val = emitir(IRTN(IR_CONV), val, IRCONV_NUM_INT);
1✔
1680
    emitir(IRT(IR_USTORE, tref_type(val)), uref, val);
51✔
1681
    if (needbarrier && tref_isgcv(val))
51✔
1682
      emitir(IRT(IR_OBAR, IRT_NIL), uref, val);
2✔
1683
    J->needsnap = 1;
51✔
1684
    return 0;
51✔
1685
  }
1686
}
1687

1688
/* -- Record calls to Lua functions --------------------------------------- */
1689

1690
/* Check unroll limits for calls. */
1691
static void check_call_unroll(jit_State *J, TraceNo lnk)
12,522✔
1692
{
1693
  cTValue *frame = J->L->base - 1;
12,522✔
1694
  void *pc = mref(frame_func(frame)->l.pc, void);
12,522✔
1695
  int32_t depth = J->framedepth;
12,522✔
1696
  int32_t count = 0;
12,522✔
1697
  if ((J->pt->flags & PROTO_VARARG)) depth--;  /* Vararg frame still missing. */
12,522✔
1698
  for (; depth > 0; depth--) {  /* Count frames with same prototype. */
35,201✔
1699
    if (frame_iscont(frame)) depth--;
22,679✔
1700
    frame = frame_prev(frame);
22,679✔
1701
    if (mref(frame_func(frame)->l.pc, void) == pc)
22,679✔
1702
      count++;
893✔
1703
  }
1704
  if (J->pc == J->startpc) {
12,522✔
1705
    if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
86✔
1706
      J->pc++;
19✔
1707
      if (J->framedepth + J->retdepth == 0)
19✔
1708
        lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno);  /* Tail-rec. */
4✔
1709
      else
1710
        lj_record_stop(J, LJ_TRLINK_UPREC, J->cur.traceno);  /* Up-recursion. */
15✔
1711
    }
1712
  } else {
1713
    if (count > J->param[JIT_P_callunroll]) {
12,436✔
1714
      if (lnk) {  /* Possible tail- or up-recursion. */
72✔
1715
        lj_trace_flush(J, lnk);  /* Flush trace that only returns. */
18✔
1716
        /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
1717
        hotcount_set(J2GG(J), J->pc+1, LJ_PRNG_BITS(J, 4));
18✔
1718
      }
1719
      lj_trace_err(J, LJ_TRERR_CUNROLL);
72✔
1720
    }
1721
  }
1722
}
12,450✔
1723

1724
/* Record Lua function setup. */
1725
static void rec_func_setup(jit_State *J)
13,388✔
1726
{
1727
  GCproto *pt = J->pt;
13,388✔
1728
  BCReg s, numparams = pt->numparams;
13,388✔
1729
  if ((pt->flags & PROTO_NOJIT))
13,388✔
1730
    lj_trace_err(J, LJ_TRERR_CJITOFF);
×
1731
  if (J->baseslot + pt->framesize >= LJ_MAX_JSLOTS)
13,388✔
1732
    lj_trace_err(J, LJ_TRERR_STACKOV);
×
1733
  /* Fill up missing parameters with nil. */
1734
  for (s = J->maxslot; s < numparams; s++)
13,814✔
1735
    J->base[s] = TREF_NIL;
426✔
1736
  /* The remaining slots should never be read before they are written. */
1737
  J->maxslot = numparams;
13,388✔
1738
}
13,388✔
1739

1740
/* Record Lua vararg function setup. */
1741
static void rec_func_vararg(jit_State *J)
101✔
1742
{
1743
  GCproto *pt = J->pt;
101✔
1744
  BCReg s, fixargs, vframe = J->maxslot+1+LJ_FR2;
101✔
1745
  lj_assertJ((pt->flags & PROTO_VARARG), "FUNCV in non-vararg function");
101✔
1746
  if (J->baseslot + vframe + pt->framesize >= LJ_MAX_JSLOTS)
101✔
1747
    lj_trace_err(J, LJ_TRERR_STACKOV);
×
1748
  J->base[vframe-1-LJ_FR2] = J->base[-1-LJ_FR2];  /* Copy function up. */
101✔
1749
#if LJ_FR2
1750
  J->base[vframe-1] = TREF_FRAME;
101✔
1751
#endif
1752
  /* Copy fixarg slots up and set their original slots to nil. */
1753
  fixargs = pt->numparams < J->maxslot ? pt->numparams : J->maxslot;
101✔
1754
  for (s = 0; s < fixargs; s++) {
128✔
1755
    J->base[vframe+s] = J->base[s];
27✔
1756
    J->base[s] = TREF_NIL;
27✔
1757
  }
1758
  J->maxslot = fixargs;
101✔
1759
  J->framedepth++;
101✔
1760
  J->base += vframe;
101✔
1761
  J->baseslot += vframe;
101✔
1762
}
101✔
1763

1764
/* Record entry to a Lua function. */
1765
static void rec_func_lua(jit_State *J)
2,713✔
1766
{
1767
  rec_func_setup(J);
2,713✔
1768
  check_call_unroll(J, 0);
2,713✔
1769
}
2,659✔
1770

1771
/* Record entry to an already compiled function. */
1772
static void rec_func_jit(jit_State *J, TraceNo lnk)
10,675✔
1773
{
1774
  GCtrace *T;
10,675✔
1775
  rec_func_setup(J);
10,675✔
1776
  T = traceref(J, lnk);
10,675✔
1777
  if (T->linktype == LJ_TRLINK_RETURN) {  /* Trace returns to interpreter? */
10,675✔
1778
    check_call_unroll(J, lnk);
9,809✔
1779
    /* Temporarily unpatch JFUNC* to continue recording across function. */
1780
    J->patchins = *J->pc;
9,791✔
1781
    J->patchpc = (BCIns *)J->pc;
9,791✔
1782
    *J->patchpc = T->startins;
9,791✔
1783
    return;
9,791✔
1784
  }
1785
  J->instunroll = 0;  /* Cannot continue across a compiled function. */
866✔
1786
  if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
866✔
1787
    lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno);  /* Extra tail-rec. */
×
1788
  else
1789
    lj_record_stop(J, LJ_TRLINK_ROOT, lnk);  /* Link to the function. */
866✔
1790
}
1791

1792
/* -- Vararg handling ----------------------------------------------------- */
1793

1794
/* Detect y = select(x, ...) idiom. */
1795
static int select_detect(jit_State *J)
13✔
1796
{
1797
  BCIns ins = J->pc[1];
13✔
1798
  if (bc_op(ins) == BC_CALLM && bc_b(ins) == 2 && bc_c(ins) == 1) {
13✔
1799
    cTValue *func = &J->L->base[bc_a(ins)];
12✔
1800
    if (tvisfunc(func) && funcV(func)->c.ffid == FF_select) {
12✔
1801
      TRef kfunc = lj_ir_kfunc(J, funcV(func));
8✔
1802
      emitir(IRTG(IR_EQ, IRT_FUNC), getslot(J, bc_a(ins)), kfunc);
8✔
1803
      return 1;
8✔
1804
    }
1805
  }
1806
  return 0;
1807
}
1808

1809
/* Record vararg instruction. */
1810
static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
38✔
1811
{
1812
  int32_t numparams = J->pt->numparams;
38✔
1813
  ptrdiff_t nvararg = frame_delta(J->L->base-1) - numparams - 1 - LJ_FR2;
38✔
1814
  lj_assertJ(frame_isvarg(J->L->base-1), "VARG in non-vararg frame");
38✔
1815
  if (LJ_FR2 && dst > J->maxslot)
38✔
1816
    J->base[dst-1] = 0;  /* Prevent resurrection of unrelated slot. */
2✔
1817
  if (J->framedepth > 0) {  /* Simple case: varargs defined on-trace. */
38✔
1818
    ptrdiff_t i;
15✔
1819
    if (nvararg < 0) nvararg = 0;
15✔
1820
    if (nresults != 1) {
15✔
1821
      if (nresults == -1) nresults = nvararg;
14✔
1822
      J->maxslot = dst + (BCReg)nresults;
14✔
1823
    } else if (dst >= J->maxslot) {
1✔
1824
      J->maxslot = dst + 1;
×
1825
    }
1826
    for (i = 0; i < nresults; i++)
28✔
1827
      J->base[dst+i] = i < nvararg ? getslot(J, i - nvararg - 1 - LJ_FR2) : TREF_NIL;
13✔
1828
  } else {  /* Unknown number of varargs passed to trace. */
1829
    TRef fr = emitir(IRTI(IR_SLOAD), LJ_FR2, IRSLOAD_READONLY|IRSLOAD_FRAME);
23✔
1830
    int32_t frofs = 8*(1+LJ_FR2+numparams)+FRAME_VARG;
23✔
1831
    if (nresults >= 0) {  /* Known fixed number of results. */
23✔
1832
      ptrdiff_t i;
10✔
1833
      if (nvararg > 0) {
10✔
1834
        ptrdiff_t nload = nvararg >= nresults ? nresults : nvararg;
7✔
1835
        TRef vbase;
7✔
1836
        if (nvararg >= nresults)
7✔
1837
          emitir(IRTGI(IR_GE), fr, lj_ir_kint(J, frofs+8*(int32_t)nresults));
6✔
1838
        else
1839
          emitir(IRTGI(IR_EQ), fr,
1✔
1840
                 lj_ir_kint(J, (int32_t)frame_ftsz(J->L->base-1)));
1841
        vbase = emitir(IRT(IR_SUB, IRT_IGC), REF_BASE, fr);
7✔
1842
        vbase = emitir(IRT(IR_ADD, IRT_PGC), vbase, lj_ir_kint(J, frofs-8*(1+LJ_FR2)));
7✔
1843
        for (i = 0; i < nload; i++) {
25✔
1844
          IRType t = itype2irt(&J->L->base[i-1-LJ_FR2-nvararg]);
11✔
1845
          TRef aref = emitir(IRT(IR_AREF, IRT_PGC),
11✔
1846
                             vbase, lj_ir_kint(J, (int32_t)i));
1847
          TRef tr = emitir(IRTG(IR_VLOAD, t), aref, 0);
11✔
1848
          if (irtype_ispri(t)) tr = TREF_PRI(t);  /* Canonicalize primitives. */
11✔
1849
          J->base[dst+i] = tr;
11✔
1850
        }
1851
      } else {
1852
        emitir(IRTGI(IR_LE), fr, lj_ir_kint(J, frofs));
3✔
1853
        nvararg = 0;
3✔
1854
      }
1855
      for (i = nvararg; i < nresults; i++)
14✔
1856
        J->base[dst+i] = TREF_NIL;
4✔
1857
      if (nresults != 1 || dst >= J->maxslot) {
10✔
1858
        J->maxslot = dst + (BCReg)nresults;
7✔
1859
      }
1860
    } else if (select_detect(J)) {  /* y = select(x, ...) */
13✔
1861
      TRef tridx = J->base[dst-1];
8✔
1862
      TRef tr = TREF_NIL;
8✔
1863
      ptrdiff_t idx = lj_ffrecord_select_mode(J, tridx, &J->L->base[dst-1]);
8✔
1864
      if (idx < 0) goto nyivarg;
8✔
1865
      if (idx != 0 && !tref_isinteger(tridx))
8✔
1866
        tridx = emitir(IRTGI(IR_CONV), tridx, IRCONV_INT_NUM|IRCONV_INDEX);
×
1867
      if (idx != 0 && tref_isk(tridx)) {
8✔
1868
        emitir(IRTGI(idx <= nvararg ? IR_GE : IR_LT),
3✔
1869
               fr, lj_ir_kint(J, frofs+8*(int32_t)idx));
1870
        frofs -= 8;  /* Bias for 1-based index. */
2✔
1871
      } else if (idx <= nvararg) {  /* Compute size. */
6✔
1872
        TRef tmp = emitir(IRTI(IR_ADD), fr, lj_ir_kint(J, -frofs));
4✔
1873
        if (numparams)
4✔
1874
          emitir(IRTGI(IR_GE), tmp, lj_ir_kint(J, 0));
3✔
1875
        tr = emitir(IRTI(IR_BSHR), tmp, lj_ir_kint(J, 3));
4✔
1876
        if (idx != 0) {
4✔
1877
          tridx = emitir(IRTI(IR_ADD), tridx, lj_ir_kint(J, -1));
3✔
1878
          rec_idx_abc(J, tr, tridx, (uint32_t)nvararg);
3✔
1879
        }
1880
      } else {
1881
        TRef tmp = lj_ir_kint(J, frofs);
2✔
1882
        if (idx != 0) {
2✔
1883
          TRef tmp2 = emitir(IRTI(IR_BSHL), tridx, lj_ir_kint(J, 3));
2✔
1884
          tmp = emitir(IRTI(IR_ADD), tmp2, tmp);
2✔
1885
        } else {
1886
          tr = lj_ir_kint(J, 0);
×
1887
        }
1888
        emitir(IRTGI(IR_LT), fr, tmp);
2✔
1889
      }
1890
      if (idx != 0 && idx <= nvararg) {
8✔
1891
        IRType t;
4✔
1892
        TRef aref, vbase = emitir(IRT(IR_SUB, IRT_IGC), REF_BASE, fr);
4✔
1893
        vbase = emitir(IRT(IR_ADD, IRT_PGC), vbase,
4✔
1894
                       lj_ir_kint(J, frofs-(8<<LJ_FR2)));
1895
        t = itype2irt(&J->L->base[idx-2-LJ_FR2-nvararg]);
4✔
1896
        aref = emitir(IRT(IR_AREF, IRT_PGC), vbase, tridx);
4✔
1897
        tr = emitir(IRTG(IR_VLOAD, t), aref, 0);
4✔
1898
        if (irtype_ispri(t)) tr = TREF_PRI(t);  /* Canonicalize primitives. */
4✔
1899
      }
1900
      J->base[dst-2-LJ_FR2] = tr;
8✔
1901
      J->maxslot = dst-1-LJ_FR2;
8✔
1902
      J->bcskip = 2;  /* Skip CALLM + select. */
8✔
1903
    } else {
1904
    nyivarg:
5✔
1905
      setintV(&J->errinfo, BC_VARG);
5✔
1906
      lj_trace_err_info(J, LJ_TRERR_NYIBC);
5✔
1907
    }
1908
  }
1909
  if (J->baseslot + J->maxslot >= LJ_MAX_JSLOTS)
33✔
1910
    lj_trace_err(J, LJ_TRERR_STACKOV);
×
1911
}
33✔
1912

1913
/* -- Record allocations -------------------------------------------------- */
1914

1915
static TRef rec_tnew(jit_State *J, uint32_t ah)
483✔
1916
{
1917
  uint32_t asize = ah & 0x7ff;
483✔
1918
  uint32_t hbits = ah >> 11;
483✔
1919
  TRef tr;
483✔
1920
  if (asize == 0x7ff) asize = 0x801;
×
1921
  tr = emitir(IRTG(IR_TNEW, IRT_TAB), asize, hbits);
483✔
1922
#ifdef LUAJIT_ENABLE_TABLE_BUMP
1923
  J->rbchash[(tr & (RBCHASH_SLOTS-1))].ref = tref_ref(tr);
1924
  setmref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pc, J->pc);
1925
  setgcref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
1926
#endif
1927
  return tr;
483✔
1928
}
1929

1930
/* -- Concatenation ------------------------------------------------------- */
1931

1932
static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot)
536✔
1933
{
1934
  TRef *top = &J->base[topslot];
536✔
1935
  TValue savetv[5];
536✔
1936
  BCReg s;
536✔
1937
  RecordIndex ix;
536✔
1938
  lj_assertJ(baseslot < topslot, "bad CAT arg");
536✔
1939
  for (s = baseslot; s <= topslot; s++)
1,888✔
1940
    (void)getslot(J, s);  /* Ensure all arguments have a reference. */
1,352✔
1941
  if (tref_isnumber_str(top[0]) && tref_isnumber_str(top[-1])) {
536✔
1942
    TRef tr, hdr, *trp, *xbase, *base = &J->base[baseslot];
531✔
1943
    /* First convert numbers to strings. */
1944
    for (trp = top; trp >= base; trp--) {
1,869✔
1945
      if (tref_isnumber(*trp))
1,339✔
1946
        *trp = emitir(IRT(IR_TOSTR, IRT_STR), *trp,
41✔
1947
                      tref_isnum(*trp) ? IRTOSTR_NUM : IRTOSTR_INT);
1948
      else if (!tref_isstr(*trp))
1,298✔
1949
        break;
1950
    }
1951
    xbase = ++trp;
531✔
1952
    tr = hdr = emitir(IRT(IR_BUFHDR, IRT_PGC),
531✔
1953
                      lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
1954
    do {
1,338✔
1955
      tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, *trp++);
1,338✔
1956
    } while (trp <= top);
1,338✔
1957
    tr = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
531✔
1958
    J->maxslot = (BCReg)(xbase - J->base);
531✔
1959
    if (xbase == base) return tr;  /* Return simple concatenation result. */
531✔
1960
    /* Pass partial result. */
1961
    topslot = J->maxslot--;
1✔
1962
    *xbase = tr;
1✔
1963
    top = xbase;
1✔
1964
    setstrV(J->L, &ix.keyv, &J2G(J)->strempty);  /* Simulate string result. */
1✔
1965
  } else {
1966
    J->maxslot = topslot-1;
5✔
1967
    copyTV(J->L, &ix.keyv, &J->L->base[topslot]);
5✔
1968
  }
1969
  copyTV(J->L, &ix.tabv, &J->L->base[topslot-1]);
6✔
1970
  ix.tab = top[-1];
6✔
1971
  ix.key = top[0];
6✔
1972
  memcpy(savetv, &J->L->base[topslot-1], sizeof(savetv));  /* Save slots. */
6✔
1973
  rec_mm_arith(J, &ix, MM_concat);  /* Call __concat metamethod. */
6✔
1974
  memcpy(&J->L->base[topslot-1], savetv, sizeof(savetv));  /* Restore slots. */
6✔
1975
  return 0;  /* No result yet. */
6✔
1976
}
1977

1978
/* -- Record bytecode ops ------------------------------------------------- */
1979

1980
/* Prepare for comparison. */
1981
static void rec_comp_prep(jit_State *J)
11,586✔
1982
{
1983
  /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
1984
  if (J->cur.nsnap == 1 && J->cur.snap[0].ref == J->cur.nins)
11,586✔
1985
    emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
67✔
1986
  lj_snap_add(J);
11,586✔
1987
}
11,586✔
1988

1989
/* Fixup comparison. */
1990
static void rec_comp_fixup(jit_State *J, const BCIns *pc, int cond)
11,540✔
1991
{
1992
  BCIns jmpins = pc[1];
11,540✔
1993
  const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0);
11,540✔
1994
  SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
11,540✔
1995
  /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
1996
#if LJ_FR2
1997
  SnapEntry *flink = &J->cur.snapmap[snap->mapofs + snap->nent];
11,540✔
1998
  uint64_t pcbase;
11,540✔
1999
  memcpy(&pcbase, flink, sizeof(uint64_t));
11,540✔
2000
  pcbase = (pcbase & 0xff) | (u64ptr(npc) << 8);
11,540✔
2001
  memcpy(flink, &pcbase, sizeof(uint64_t));
11,540✔
2002
#else
2003
  J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc);
2004
#endif
2005
  J->needsnap = 1;
11,540✔
2006
  if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins);
11,540✔
2007
  lj_snap_shrink(J);  /* Shrink last snapshot if possible. */
11,540✔
2008
}
11,540✔
2009

2010
/* Record the next bytecode instruction (_before_ it's executed). */
2011
void lj_record_ins(jit_State *J)
281,056✔
2012
{
2013
  cTValue *lbase;
281,056✔
2014
  RecordIndex ix;
281,056✔
2015
  const BCIns *pc;
281,056✔
2016
  BCIns ins;
281,056✔
2017
  BCOp op;
281,056✔
2018
  TRef ra, rb, rc;
281,056✔
2019

2020
  /* Perform post-processing action before recording the next instruction. */
2021
  if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) {
281,056✔
2022
    switch (J->postproc) {
5,974✔
2023
    case LJ_POST_FIXCOMP:  /* Fixup comparison. */
61✔
2024
      pc = (const BCIns *)(uintptr_t)J2G(J)->tmptv.u64;
61✔
2025
      rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1)));
61✔
2026
      /* fallthrough */
2027
    case LJ_POST_FIXGUARD:  /* Fixup and emit pending guard. */
106✔
2028
    case LJ_POST_FIXGUARDSNAP:  /* Fixup and emit pending guard and snapshot. */
2029
      if (!tvistruecond(&J2G(J)->tmptv2)) {
106✔
2030
        J->fold.ins.o ^= 1;  /* Flip guard to opposite. */
39✔
2031
        if (J->postproc == LJ_POST_FIXGUARDSNAP) {
39✔
2032
          SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
×
2033
          J->cur.snapmap[snap->mapofs+snap->nent-1]--;  /* False -> true. */
×
2034
        }
2035
      }
2036
      lj_opt_fold(J);  /* Emit pending guard. */
106✔
2037
      /* fallthrough */
2038
    case LJ_POST_FIXBOOL:
120✔
2039
      if (!tvistruecond(&J2G(J)->tmptv2)) {
120✔
2040
        BCReg s;
45✔
2041
        TValue *tv = J->L->base;
45✔
2042
        for (s = 0; s < J->maxslot; s++)  /* Fixup stack slot (if any). */
283✔
2043
          if (J->base[s] == TREF_TRUE && tvisfalse(&tv[s])) {
244✔
2044
            J->base[s] = TREF_FALSE;
6✔
2045
            break;
6✔
2046
          }
2047
      }
2048
      break;
2049
    case LJ_POST_FIXCONST:
1✔
2050
      {
2051
        BCReg s;
1✔
2052
        TValue *tv = J->L->base;
1✔
2053
        for (s = 0; s < J->maxslot; s++)  /* Constify stack slots (if any). */
13✔
2054
          if (J->base[s] == TREF_NIL && !tvisnil(&tv[s]))
12✔
2055
            J->base[s] = lj_record_constify(J, &tv[s]);
1✔
2056
      }
2057
      break;
2058
    case LJ_POST_FFRETRY:  /* Suppress recording of retried fast function. */
5,853✔
2059
      if (bc_op(*J->pc) >= BC__MAX)
5,853✔
2060
        return;
19✔
2061
      break;
2062
    default: lj_assertJ(0, "bad post-processing mode"); break;
2063
    }
2064
    J->postproc = LJ_POST_NONE;
5,971✔
2065
  }
2066

2067
  /* Need snapshot before recording next bytecode (e.g. after a store). */
2068
  if (J->needsnap) {
281,053✔
2069
    J->needsnap = 0;
66,470✔
2070
    if (J->pt) lj_snap_purge(J);
66,470✔
2071
    lj_snap_add(J);
66,470✔
2072
    J->mergesnap = 1;
66,470✔
2073
  }
2074

2075
  /* Skip some bytecodes. */
2076
  if (LJ_UNLIKELY(J->bcskip > 0)) {
281,053✔
2077
    J->bcskip--;
16✔
2078
    return;
16✔
2079
  }
2080

2081
  /* Record only closed loops for root traces. */
2082
  pc = J->pc;
281,037✔
2083
  if (J->framedepth == 0 &&
281,037✔
2084
     (MSize)((char *)pc - (char *)J->bc_min) >= J->bc_extent)
195,600✔
2085
    lj_trace_err(J, LJ_TRERR_LLEAVE);
478✔
2086

2087
#ifdef LUA_USE_ASSERT
2088
  rec_check_slots(J);
2089
  rec_check_ir(J);
2090
#endif
2091

2092
#if LJ_HASPROFILE
2093
  rec_profile_ins(J, pc);
280,559✔
2094
#endif
2095

2096
  /* Keep a copy of the runtime values of var/num/str operands. */
2097
#define rav        (&ix.valv)
2098
#define rbv        (&ix.tabv)
2099
#define rcv        (&ix.keyv)
2100

2101
  lbase = J->L->base;
280,559✔
2102
  ins = *pc;
280,559✔
2103
  op = bc_op(ins);
280,559✔
2104
  ra = bc_a(ins);
280,559✔
2105
  ix.val = 0;
280,559✔
2106
  switch (bcmode_a(op)) {
280,559✔
2107
  case BCMvar:
65,635✔
2108
    copyTV(J->L, rav, &lbase[ra]); ix.val = ra = getslot(J, ra); break;
65,635✔
2109
  default: break;  /* Handled later. */
2110
  }
2111
  rb = bc_b(ins);
280,559✔
2112
  rc = bc_c(ins);
280,559✔
2113
  switch (bcmode_b(op)) {
280,559✔
2114
  case BCMnone: rb = 0; rc = bc_d(ins); break;  /* Upgrade rc to 'rd'. */
96,772✔
2115
  case BCMvar:
166,301✔
2116
    copyTV(J->L, rbv, &lbase[rb]); ix.tab = rb = getslot(J, rb); break;
166,301✔
2117
  default: break;  /* Handled later. */
2118
  }
2119
  switch (bcmode_c(op)) {
280,559✔
2120
  case BCMvar:
69,541✔
2121
    copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
69,541✔
2122
  case BCMpri: setpriV(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
8,678✔
2123
  case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
5,808✔
2124
    copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
5,808✔
2125
    lj_ir_knumint(J, numV(tv)); } break;
5,808✔
2126
  case BCMstr: { GCstr *s = gco2str(proto_kgc(J->pt, ~(ptrdiff_t)rc));
112,961✔
2127
    setstrV(J->L, rcv, s); ix.key = rc = lj_ir_kstr(J, s); } break;
112,961✔
2128
  default: break;  /* Handled later. */
2129
  }
2130

2131
  switch (op) {
280,559✔
2132

2133
  /* -- Comparison ops ---------------------------------------------------- */
2134

2135
  case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
4,677✔
2136
#if LJ_HASFFI
2137
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
4,677✔
2138
      rec_mm_comp_cdata(J, &ix, op, ((int)op & 2) ? MM_le : MM_lt);
61✔
2139
      break;
61✔
2140
    }
2141
#endif
2142
    /* Emit nothing for two numeric or string consts. */
2143
    if (!(tref_isk2(ra,rc) && tref_isnumber_str(ra) && tref_isnumber_str(rc))) {
4,616✔
2144
      IRType ta = tref_isinteger(ra) ? IRT_INT : tref_type(ra);
4,048✔
2145
      IRType tc = tref_isinteger(rc) ? IRT_INT : tref_type(rc);
4,048✔
2146
      int irop;
4,048✔
2147
      if (ta != tc) {
4,048✔
2148
        /* Widen mixed number/int comparisons to number/number comparison. */
2149
        if (ta == IRT_INT && tc == IRT_NUM) {
3,294✔
2150
          ra = emitir(IRTN(IR_CONV), ra, IRCONV_NUM_INT);
1,667✔
2151
          ta = IRT_NUM;
1,667✔
2152
        } else if (ta == IRT_NUM && tc == IRT_INT) {
1,627✔
2153
          rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
1,627✔
2154
        } else if (LJ_52) {
×
2155
          ta = IRT_NIL;  /* Force metamethod for different types. */
2156
        } else if (!((ta == IRT_FALSE || ta == IRT_TRUE) &&
×
2157
                     (tc == IRT_FALSE || tc == IRT_TRUE))) {
×
2158
          break;  /* Interpreter will throw for two different types. */
2159
        }
2160
      }
2161
      rec_comp_prep(J);
4,048✔
2162
      irop = (int)op - (int)BC_ISLT + (int)IR_LT;
4,048✔
2163
      if (ta == IRT_NUM) {
4,048✔
2164
        if ((irop & 1)) irop ^= 4;  /* ISGE/ISGT are unordered. */
3,912✔
2165
        if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
3,912✔
2166
          irop ^= 5;
3,323✔
2167
      } else if (ta == IRT_INT) {
136✔
2168
        if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
86✔
2169
          irop ^= 1;
40✔
2170
      } else if (ta == IRT_STR) {
50✔
2171
        if (!lj_ir_strcmp(strV(rav), strV(rcv), (IROp)irop)) irop ^= 1;
1✔
2172
        ra = lj_ir_call(J, IRCALL_lj_str_cmp, ra, rc);
1✔
2173
        rc = lj_ir_kint(J, 0);
1✔
2174
        ta = IRT_INT;
1✔
2175
      } else {
2176
        rec_mm_comp(J, &ix, (int)op);
49✔
2177
        break;
49✔
2178
      }
2179
      emitir(IRTG(irop, ta), ra, rc);
3,999✔
2180
      rec_comp_fixup(J, J->pc, ((int)op ^ irop) & 1);
3,999✔
2181
    }
2182
    break;
2183

2184
  case BC_ISEQV: case BC_ISNEV:
8,913✔
2185
  case BC_ISEQS: case BC_ISNES:
2186
  case BC_ISEQN: case BC_ISNEN:
2187
  case BC_ISEQP: case BC_ISNEP:
2188
#if LJ_HASFFI
2189
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
8,913✔
2190
      rec_mm_comp_cdata(J, &ix, op, MM_eq);
45✔
2191
      break;
45✔
2192
    }
2193
#endif
2194
    /* Emit nothing for two non-table, non-udata consts. */
2195
    if (!(tref_isk2(ra, rc) && !(tref_istab(ra) || tref_isudata(ra)))) {
8,868✔
2196
      int diff;
7,538✔
2197
      rec_comp_prep(J);
7,538✔
2198
      diff = lj_record_objcmp(J, ra, rc, rav, rcv);
7,538✔
2199
      if (diff == 2 || !(tref_istab(ra) || tref_isudata(ra)))
7,538✔
2200
        rec_comp_fixup(J, J->pc, ((int)op & 1) == !diff);
7,480✔
2201
      else if (diff == 1)  /* Only check __eq if different, but same type. */
58✔
2202
        rec_mm_equal(J, &ix, (int)op);
10✔
2203
    }
2204
    break;
2205

2206
  /* -- Unary test and copy ops ------------------------------------------- */
2207

2208
  case BC_ISTC: case BC_ISFC:
244✔
2209
    if ((op & 1) == tref_istruecond(rc))
244✔
2210
      rc = 0;  /* Don't store if condition is not true. */
225✔
2211
    /* fallthrough */
2212
  case BC_IST: case BC_ISF:  /* Type specialization suffices. */
2213
    if (bc_a(pc[1]) < J->maxslot)
744✔
2214
      J->maxslot = bc_a(pc[1]);  /* Shrink used slots. */
157✔
2215
    break;
2216

2217
  case BC_ISTYPE: case BC_ISNUM:
2218
    /* These coercions need to correspond with lj_meta_istype(). */
2219
    if (LJ_DUALNUM && rc == ~LJ_TNUMX+1)
14✔
2220
      ra = lj_opt_narrow_toint(J, ra);
2221
    else if (rc == ~LJ_TNUMX+2)
14✔
2222
      ra = lj_ir_tonum(J, ra);
2✔
2223
    else if (rc == ~LJ_TSTR+1)
12✔
2224
      ra = lj_ir_tostr(J, ra);
6✔
2225
    /* else: type specialization suffices. */
2226
    J->base[bc_a(ins)] = ra;
14✔
2227
    break;
14✔
2228

2229
  /* -- Unary ops --------------------------------------------------------- */
2230

2231
  case BC_NOT:
5✔
2232
    /* Type specialization already forces const result. */
2233
    rc = tref_istruecond(rc) ? TREF_FALSE : TREF_TRUE;
5✔
2234
    break;
2235

2236
  case BC_LEN:
48✔
2237
    if (tref_isstr(rc))
48✔
2238
      rc = emitir(IRTI(IR_FLOAD), rc, IRFL_STR_LEN);
8✔
2239
    else if (!LJ_52 && tref_istab(rc))
40✔
2240
      rc = lj_ir_call(J, IRCALL_lj_tab_len, rc);
39✔
2241
    else
2242
      rc = rec_mm_len(J, rc, rcv);
1✔
2243
    break;
2244

2245
  /* -- Arithmetic ops ---------------------------------------------------- */
2246

2247
  case BC_UNM:
13✔
2248
    if (tref_isnumber_str(rc)) {
13✔
2249
      rc = lj_opt_narrow_unm(J, rc, rcv);
12✔
2250
    } else {
2251
      ix.tab = rc;
1✔
2252
      copyTV(J->L, &ix.tabv, rcv);
1✔
2253
      rc = rec_mm_arith(J, &ix, MM_unm);
1✔
2254
    }
2255
    break;
2256

2257
  case BC_ADDNV: case BC_SUBNV: case BC_MULNV: case BC_DIVNV: case BC_MODNV:
2,450✔
2258
    /* Swap rb/rc and rbv/rcv. rav is temp. */
2259
    ix.tab = rc; ix.key = rc = rb; rb = ix.tab;
2,450✔
2260
    copyTV(J->L, rav, rbv);
2,450✔
2261
    copyTV(J->L, rbv, rcv);
2,450✔
2262
    copyTV(J->L, rcv, rav);
2,450✔
2263
    if (op == BC_MODNV)
2,450✔
2264
      goto recmod;
17✔
2265
    /* fallthrough */
2266
  case BC_ADDVN: case BC_SUBVN: case BC_MULVN: case BC_DIVVN:
2267
  case BC_ADDVV: case BC_SUBVV: case BC_MULVV: case BC_DIVVV: {
2268
    MMS mm = bcmode_mm(op);
51,418✔
2269
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
51,418✔
2270
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv,
51,275✔
2271
                               (int)mm - (int)MM_add + (int)IR_ADD);
51,275✔
2272
    else
2273
      rc = rec_mm_arith(J, &ix, mm);
143✔
2274
    break;
2275
    }
2276

2277
  case BC_MODVN: case BC_MODVV:
2278
  recmod:
157✔
2279
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
157✔
2280
      rc = lj_opt_narrow_mod(J, rb, rc, rbv, rcv);
154✔
2281
    else
2282
      rc = rec_mm_arith(J, &ix, MM_mod);
3✔
2283
    break;
2284

2285
  case BC_POW:
243✔
2286
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
243✔
2287
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv, IR_POW);
240✔
2288
    else
2289
      rc = rec_mm_arith(J, &ix, MM_pow);
3✔
2290
    break;
2291

2292
  /* -- Miscellaneous ops ------------------------------------------------- */
2293

2294
  case BC_CAT:
534✔
2295
    rc = rec_cat(J, rb, rc);
534✔
2296
    break;
534✔
2297

2298
  /* -- Constant and move ops --------------------------------------------- */
2299

2300
  case BC_MOV:
11,850✔
2301
    /* Clear gap of method call to avoid resurrecting previous refs. */
2302
    if (ra > J->maxslot) {
11,850✔
2303
#if LJ_FR2
2304
      memset(J->base + J->maxslot, 0, (ra - J->maxslot) * sizeof(TRef));
6,564✔
2305
#else
2306
      J->base[ra-1] = 0;
2307
#endif
2308
    }
2309
    break;
2310
  case BC_KSTR: case BC_KNUM: case BC_KPRI:
2311
    break;
2312
  case BC_KSHORT:
7,317✔
2313
    rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
7,317✔
2314
    break;
7,317✔
2315
  case BC_KNIL:
12✔
2316
    if (LJ_FR2 && ra > J->maxslot)
12✔
2317
      J->base[ra-1] = 0;
1✔
2318
    while (ra <= rc)
704✔
2319
      J->base[ra++] = TREF_NIL;
692✔
2320
    if (rc >= J->maxslot) J->maxslot = rc+1;
12✔
2321
    break;
2322
#if LJ_HASFFI
2323
  case BC_KCDATA:
30✔
2324
    rc = lj_ir_kgc(J, proto_kgc(J->pt, ~(ptrdiff_t)rc), IRT_CDATA);
30✔
2325
    break;
30✔
2326
#endif
2327

2328
  /* -- Upvalue and function ops ------------------------------------------ */
2329

2330
  case BC_UGET:
16,370✔
2331
    rc = rec_upvalue(J, rc, 0);
16,370✔
2332
    break;
16,370✔
2333
  case BC_USETV: case BC_USETS: case BC_USETN: case BC_USETP:
168✔
2334
    rec_upvalue(J, ra, rc);
168✔
2335
    break;
168✔
2336

2337
  /* -- Table ops --------------------------------------------------------- */
2338

2339
  case BC_GGET: case BC_GSET:
2,353✔
2340
    settabV(J->L, &ix.tabv, tabref(J->fn->l.env));
2,353✔
2341
    ix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), getcurrf(J), IRFL_FUNC_ENV);
2,353✔
2342
    ix.idxchain = LJ_MAX_IDXCHAIN;
2,353✔
2343
    rc = lj_record_idx(J, &ix);
2,353✔
2344
    break;
2,353✔
2345

2346
  case BC_TGETB: case BC_TSETB:
455✔
2347
    setintV(&ix.keyv, (int32_t)rc);
455✔
2348
    ix.key = lj_ir_kint(J, (int32_t)rc);
455✔
2349
    /* fallthrough */
2350
  case BC_TGETV: case BC_TGETS: case BC_TSETV: case BC_TSETS:
114,463✔
2351
    ix.idxchain = LJ_MAX_IDXCHAIN;
114,463✔
2352
    rc = lj_record_idx(J, &ix);
114,463✔
2353
    break;
114,463✔
2354
  case BC_TGETR: case BC_TSETR:
20✔
2355
    ix.idxchain = 0;
20✔
2356
    rc = lj_record_idx(J, &ix);
20✔
2357
    break;
20✔
2358

2359
  case BC_TSETM:
5✔
2360
    rec_tsetm(J, ra, (BCReg)(J->L->top - J->L->base), (int32_t)rcv->u32.lo);
5✔
2361
    J->maxslot = ra;  /* The table slot at ra-1 is the highest used slot. */
5✔
2362
    break;
5✔
2363

2364
  case BC_TNEW:
2365
    rc = rec_tnew(J, rc);
483✔
2366
    break;
483✔
2367
  case BC_TDUP:
170✔
2368
    rc = emitir(IRTG(IR_TDUP, IRT_TAB),
170✔
2369
                lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
2370
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2371
    J->rbchash[(rc & (RBCHASH_SLOTS-1))].ref = tref_ref(rc);
2372
    setmref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pc, pc);
2373
    setgcref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
2374
#endif
2375
    break;
170✔
2376

2377
  /* -- Calls and vararg handling ----------------------------------------- */
2378

2379
  case BC_ITERC:
110✔
2380
    J->base[ra] = getslot(J, ra-3);
110✔
2381
    J->base[ra+1+LJ_FR2] = getslot(J, ra-2);
110✔
2382
    J->base[ra+2+LJ_FR2] = getslot(J, ra-1);
110✔
2383
    { /* Do the actual copy now because lj_record_call needs the values. */
2384
      TValue *b = &J->L->base[ra];
110✔
2385
      copyTV(J->L, b, b-3);
110✔
2386
      copyTV(J->L, b+1+LJ_FR2, b-2);
110✔
2387
      copyTV(J->L, b+2+LJ_FR2, b-1);
110✔
2388
    }
2389
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
110✔
2390
    break;
110✔
2391

2392
  /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
2393
  case BC_CALLM:
2,558✔
2394
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
2,558✔
2395
    /* fallthrough */
2396
  case BC_CALL:
16,804✔
2397
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
16,804✔
2398
    break;
16,804✔
2399

2400
  case BC_CALLMT:
7✔
2401
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
7✔
2402
    /* fallthrough */
2403
  case BC_CALLT:
1,934✔
2404
    lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
1,934✔
2405
    break;
1,934✔
2406

2407
  case BC_VARG:
38✔
2408
    rec_varg(J, ra, (ptrdiff_t)rb-1);
38✔
2409
    break;
38✔
2410

2411
  /* -- Returns ----------------------------------------------------------- */
2412

2413
  case BC_RETM:
25✔
2414
    /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
2415
    rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
25✔
2416
    /* fallthrough */
2417
  case BC_RET: case BC_RET0: case BC_RET1:
13,764✔
2418
#if LJ_HASPROFILE
2419
    rec_profile_ret(J);
13,764✔
2420
#endif
2421
    lj_record_ret(J, ra, (ptrdiff_t)rc-1);
13,764✔
2422
    break;
13,764✔
2423

2424
  /* -- Loops and branches ------------------------------------------------ */
2425

2426
  case BC_FORI:
159✔
2427
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)
159✔
2428
      J->loopref = J->cur.nins;
159✔
2429
    break;
2430
  case BC_JFORI:
73✔
2431
    lj_assertJ(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL,
73✔
2432
               "JFORI does not point to JFORL");
2433
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)  /* Link to existing loop. */
73✔
2434
      lj_record_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
70✔
2435
    /* Continue tracing if the loop is not entered. */
2436
    break;
2437

2438
  case BC_FORL:
2,179✔
2439
    rec_loop_interp(J, pc, rec_for(J, pc+((ptrdiff_t)rc-BCBIAS_J), 1));
2,179✔
2440
    break;
2,179✔
2441
  case BC_ITERL:
44✔
2442
    rec_loop_interp(J, pc, rec_iterl(J, *pc));
44✔
2443
    break;
44✔
2444
  case BC_LOOP:
95✔
2445
    rec_loop_interp(J, pc, rec_loop(J, ra));
95✔
2446
    break;
95✔
2447

2448
  case BC_JFORL:
299✔
2449
    rec_loop_jit(J, rc, rec_for(J, pc+bc_j(traceref(J, rc)->startins), 1));
299✔
2450
    break;
299✔
2451
  case BC_JITERL:
64✔
2452
    rec_loop_jit(J, rc, rec_iterl(J, traceref(J, rc)->startins));
64✔
2453
    break;
64✔
2454
  case BC_JLOOP:
1,459✔
2455
    rec_loop_jit(J, rc, rec_loop(J, ra));
1,459✔
2456
    break;
1,459✔
2457

2458
  case BC_IFORL:
×
2459
  case BC_IITERL:
2460
  case BC_ILOOP:
2461
  case BC_IFUNCF:
2462
  case BC_IFUNCV:
2463
    lj_trace_err(J, LJ_TRERR_BLACKL);
×
2464
    break;
1,511✔
2465

2466
  case BC_JMP:
1,511✔
2467
    if (ra < J->maxslot)
1,511✔
2468
      J->maxslot = ra;  /* Shrink used slots. */
989✔
2469
    break;
2470

2471
  /* -- Function headers -------------------------------------------------- */
2472

2473
  case BC_FUNCF:
2474
    rec_func_lua(J);
2,612✔
2475
    break;
2476
  case BC_JFUNCF:
10,675✔
2477
    rec_func_jit(J, rc);
10,675✔
2478
    break;
10,675✔
2479

2480
  case BC_FUNCV:
101✔
2481
    rec_func_vararg(J);
101✔
2482
    rec_func_lua(J);
101✔
2483
    break;
2484
  case BC_JFUNCV:
2485
    /* Cannot happen. No hotcall counting for varag funcs. */
2486
    lj_assertJ(0, "unsupported vararg hotcall");
2487
    break;
2488

2489
  case BC_FUNCC:
1,538✔
2490
  case BC_FUNCCW:
2491
    lj_ffrecord_func(J);
1,538✔
2492
    break;
1,538✔
2493

2494
  default:
4,683✔
2495
    if (op >= BC__MAX) {
4,683✔
2496
      lj_ffrecord_func(J);
4,683✔
2497
      break;
4,683✔
2498
    }
2499
    /* fallthrough */
2500
  case BC_ITERN:
2501
  case BC_ISNEXT:
2502
  case BC_UCLO:
2503
  case BC_FNEW:
2504
    setintV(&J->errinfo, (int32_t)op);
44✔
2505
    lj_trace_err_info(J, LJ_TRERR_NYIBC);
44✔
2506
    break;
280,008✔
2507
  }
2508

2509
  /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
2510
  if (bcmode_a(op) == BCMdst && rc) {
280,008✔
2511
    J->base[ra] = rc;
155,369✔
2512
    if (ra >= J->maxslot) {
155,369✔
2513
#if LJ_FR2
2514
      if (ra > J->maxslot) J->base[ra-1] = 0;
55,012✔
2515
#endif
2516
      J->maxslot = ra+1;
55,012✔
2517
    }
2518
  }
2519

2520
#undef rav
2521
#undef rbv
2522
#undef rcv
2523

2524
  /* Limit the number of recorded IR instructions and constants. */
2525
  if (J->cur.nins > REF_FIRST+(IRRef)J->param[JIT_P_maxrecord] ||
280,008✔
2526
      J->cur.nk < REF_BIAS-(IRRef)J->param[JIT_P_maxirconst])
280,008✔
2527
    lj_trace_err(J, LJ_TRERR_TRACEOV);
1✔
2528
}
2529

2530
/* -- Recording setup ----------------------------------------------------- */
2531

2532
/* Setup recording for a root trace started by a hot loop. */
2533
static const BCIns *rec_setup_root(jit_State *J)
3,849✔
2534
{
2535
  /* Determine the next PC and the bytecode range for the loop. */
2536
  const BCIns *pcj, *pc = J->pc;
3,849✔
2537
  BCIns ins = *pc;
3,849✔
2538
  BCReg ra = bc_a(ins);
3,849✔
2539
  switch (bc_op(ins)) {
3,849✔
2540
  case BC_FORL:
2,088✔
2541
    J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
2,088✔
2542
    pc += 1+bc_j(ins);
2,088✔
2543
    J->bc_min = pc;
2,088✔
2544
    break;
2,088✔
2545
  case BC_ITERL:
40✔
2546
    lj_assertJ(bc_op(pc[-1]) == BC_ITERC, "no ITERC before ITERL");
40✔
2547
    J->maxslot = ra + bc_b(pc[-1]) - 1;
40✔
2548
    J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
40✔
2549
    pc += 1+bc_j(ins);
40✔
2550
    lj_assertJ(bc_op(pc[-1]) == BC_JMP, "ITERL does not point to JMP+1");
40✔
2551
    J->bc_min = pc;
40✔
2552
    break;
40✔
2553
  case BC_LOOP:
869✔
2554
    /* Only check BC range for real loops, but not for "repeat until true". */
2555
    pcj = pc + bc_j(ins);
869✔
2556
    ins = *pcj;
869✔
2557
    if (bc_op(ins) == BC_JMP && bc_j(ins) < 0) {
869✔
2558
      J->bc_min = pcj+1 + bc_j(ins);
864✔
2559
      J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
864✔
2560
    }
2561
    J->maxslot = ra;
869✔
2562
    pc++;
869✔
2563
    break;
869✔
2564
  case BC_RET:
64✔
2565
  case BC_RET0:
2566
  case BC_RET1:
2567
    /* No bytecode range check for down-recursive root traces. */
2568
    J->maxslot = ra + bc_d(ins) - 1;
64✔
2569
    break;
64✔
2570
  case BC_FUNCF:
712✔
2571
    /* No bytecode range check for root traces started by a hot call. */
2572
    J->maxslot = J->pt->numparams;
712✔
2573
    pc++;
712✔
2574
    break;
712✔
2575
  case BC_CALLM:
76✔
2576
  case BC_CALL:
2577
  case BC_ITERC:
2578
    /* No bytecode range check for stitched traces. */
2579
    pc++;
76✔
2580
    break;
76✔
2581
  default:
2582
    lj_assertJ(0, "bad root trace start bytecode %d", bc_op(ins));
2583
    break;
2584
  }
2585
  return pc;
3,849✔
2586
}
2587

2588
/* Setup for recording a new trace. */
2589
void lj_record_setup(jit_State *J)
7,046✔
2590
{
2591
  uint32_t i;
7,046✔
2592

2593
  /* Initialize state related to current trace. */
2594
  memset(J->slot, 0, sizeof(J->slot));
7,046✔
2595
  memset(J->chain, 0, sizeof(J->chain));
7,046✔
2596
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2597
  memset(J->rbchash, 0, sizeof(J->rbchash));
2598
#endif
2599
  memset(J->bpropcache, 0, sizeof(J->bpropcache));
7,046✔
2600
  J->scev.idx = REF_NIL;
7,046✔
2601
  setmref(J->scev.pc, NULL);
7,046✔
2602

2603
  J->baseslot = 1+LJ_FR2;  /* Invoking function is at base[-1-LJ_FR2]. */
7,046✔
2604
  J->base = J->slot + J->baseslot;
7,046✔
2605
  J->maxslot = 0;
7,046✔
2606
  J->framedepth = 0;
7,046✔
2607
  J->retdepth = 0;
7,046✔
2608

2609
  J->instunroll = J->param[JIT_P_instunroll];
7,046✔
2610
  J->loopunroll = J->param[JIT_P_loopunroll];
7,046✔
2611
  J->tailcalled = 0;
7,046✔
2612
  J->loopref = 0;
7,046✔
2613

2614
  J->bc_min = NULL;  /* Means no limit. */
7,046✔
2615
  J->bc_extent = ~(MSize)0;
7,046✔
2616

2617
  /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2618
  emitir_raw(IRT(IR_BASE, IRT_PGC), J->parent, J->exitno);
7,046✔
2619
  for (i = 0; i <= 2; i++) {
35,230✔
2620
    IRIns *ir = IR(REF_NIL-i);
21,138✔
2621
    ir->i = 0;
21,138✔
2622
    ir->t.irt = (uint8_t)(IRT_NIL+i);
21,138✔
2623
    ir->o = IR_KPRI;
21,138✔
2624
    ir->prev = 0;
21,138✔
2625
  }
2626
  J->cur.nk = REF_TRUE;
7,046✔
2627

2628
  J->startpc = J->pc;
7,046✔
2629
  setmref(J->cur.startpc, J->pc);
7,046✔
2630
  if (J->parent) {  /* Side trace. */
7,046✔
2631
    GCtrace *T = traceref(J, J->parent);
3,197✔
2632
    TraceNo root = T->root ? T->root : J->parent;
3,197✔
2633
    J->cur.root = (uint16_t)root;
3,197✔
2634
    J->cur.startins = BCINS_AD(BC_JMP, 0, 0);
3,197✔
2635
    /* Check whether we could at least potentially form an extra loop. */
2636
    if (J->exitno == 0 && T->snap[0].nent == 0) {
3,197✔
2637
      /* We can narrow a FORL for some side traces, too. */
2638
      if (J->pc > proto_bc(J->pt) && bc_op(J->pc[-1]) == BC_JFORI &&
357✔
2639
          bc_d(J->pc[bc_j(J->pc[-1])-1]) == root) {
171✔
2640
        lj_snap_add(J);
171✔
2641
        rec_for_loop(J, J->pc-1, &J->scev, 1);
171✔
2642
        goto sidecheck;
171✔
2643
      }
2644
    } else {
2645
      J->startpc = NULL;  /* Prevent forming an extra loop. */
2,840✔
2646
    }
2647
    lj_snap_replay(J, T);
3,026✔
2648
  sidecheck:
3,197✔
2649
    if (traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] ||
3,197✔
2650
        T->snap[J->exitno].count >= J->param[JIT_P_hotexit] +
2,953✔
2651
                                    J->param[JIT_P_tryside]) {
2,953✔
2652
      lj_record_stop(J, LJ_TRLINK_INTERP, 0);
341✔
2653
    }
2654
  } else {  /* Root trace. */
2655
    J->cur.root = 0;
3,849✔
2656
    J->cur.startins = *J->pc;
3,849✔
2657
    J->pc = rec_setup_root(J);
3,849✔
2658
    /* Note: the loop instruction itself is recorded at the end and not
2659
    ** at the start! So snapshot #0 needs to point to the *next* instruction.
2660
    */
2661
    lj_snap_add(J);
3,849✔
2662
    if (bc_op(J->cur.startins) == BC_FORL)
3,849✔
2663
      rec_for_loop(J, J->pc-1, &J->scev, 1);
2,088✔
2664
    else if (bc_op(J->cur.startins) == BC_ITERC)
1,761✔
2665
      J->startpc = NULL;
2✔
2666
    if (1 + J->pt->framesize >= LJ_MAX_JSLOTS)
3,849✔
2667
      lj_trace_err(J, LJ_TRERR_STACKOV);
×
2668
  }
2669
#if LJ_HASPROFILE
2670
  J->prev_pt = NULL;
7,046✔
2671
  J->prev_line = -1;
7,046✔
2672
#endif
2673
#ifdef LUAJIT_ENABLE_CHECKHOOK
2674
  /* Regularly check for instruction/line hooks from compiled code and
2675
  ** exit to the interpreter if the hooks are set.
2676
  **
2677
  ** This is a compile-time option and disabled by default, since the
2678
  ** hook checks may be quite expensive in tight loops.
2679
  **
2680
  ** Note this is only useful if hooks are *not* set most of the time.
2681
  ** Use this only if you want to *asynchronously* interrupt the execution.
2682
  **
2683
  ** You can set the instruction hook via lua_sethook() with a count of 1
2684
  ** from a signal handler or another native thread. Please have a look
2685
  ** at the first few functions in luajit.c for an example (Ctrl-C handler).
2686
  */
2687
  {
2688
    TRef tr = emitir(IRT(IR_XLOAD, IRT_U8),
2689
                     lj_ir_kptr(J, &J2G(J)->hookmask), IRXLOAD_VOLATILE);
2690
    tr = emitir(IRTI(IR_BAND), tr, lj_ir_kint(J, (LUA_MASKLINE|LUA_MASKCOUNT)));
2691
    emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, 0));
2692
  }
2693
#endif
2694
}
7,046✔
2695

2696
#undef IR
2697
#undef emitir_raw
2698
#undef emitir
2699

2700
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc