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

tarantool / luajit / 13940950676

19 Mar 2025 07:17AM UTC coverage: 93.013% (+0.05%) from 92.966%
13940950676

push

github

Buristan
ci: disable integration-tarantool-ecosystem.yml

This patch prevents runs of the aforementioned workflow until the
corresponding workflow in the Tarantool is fixed.

Relates to tarantool/tarantool#11220

5702 of 6038 branches covered (94.44%)

Branch coverage included in aggregate %.

21723 of 23447 relevant lines covered (92.65%)

2959970.97 hits per line

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

96.5
/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)
130,437✔
188
{
189
  /* Caller may set IRT_GUARD in t. */
190
  TRef ref = emitir_raw(IRT(IR_SLOAD, t), (int32_t)J->baseslot+slot, mode);
260,874✔
191
  J->base[slot] = ref;
130,437✔
192
  return ref;
130,437✔
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)
283,805✔
197
{
198
  IRType t = itype2irt(&J->L->base[slot]);
283,805✔
199
  TRef ref = emitir_raw(IRTG(IR_SLOAD, t), (int32_t)J->baseslot+slot,
283,805✔
200
                        IRSLOAD_TYPECHECK);
201
  if (irtype_ispri(t)) ref = TREF_PRI(t);  /* Canonicalize primitive refs. */
283,805✔
202
  J->base[slot] = ref;
283,805✔
203
  return ref;
283,805✔
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)
1,145,262✔
211
{
212
  if (J->base[-1-LJ_FR2])
1,145,262✔
213
    return J->base[-1-LJ_FR2];
214
  /* Non-base frame functions ought to be loaded already. */
215
  lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot");
127,366✔
216
  return sloadt(J, -1-LJ_FR2, IRT_FUNC, IRSLOAD_READONLY);
127,366✔
217
}
218

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

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

262
/* -- Record loop ops ----------------------------------------------------- */
263

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

271
/* Canonicalize slots: convert integers to numbers. */
272
static void canonicalize_slots(jit_State *J)
17,448✔
273
{
274
  BCReg s;
17,448✔
275
  if (LJ_DUALNUM) return;
17,448✔
276
  for (s = J->baseslot+J->maxslot-1; s >= 1; s--) {
285,486✔
277
    TRef tr = J->slot[s];
268,039✔
278
    if (tref_isinteger(tr)) {
268,039✔
279
      IRIns *ir = IR(tref_ref(tr));
34,903✔
280
      if (!(ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_READONLY)))
34,903✔
281
        J->slot[s] = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
34,825✔
282
    }
283
  }
284
}
285

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

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

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

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

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

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

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

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

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

534
  ev = rec_for_iter(&op, tv, isforl);
3,169✔
535
  if (ev == LOOPEV_LEAVE) {
3,169✔
536
    J->maxslot = ra+FORL_EXT+1;
64✔
537
    J->pc = fori+1;
64✔
538
  } else {
539
    J->maxslot = ra;
3,105✔
540
    J->pc = fori+bc_j(*fori)+1;
3,105✔
541
  }
542
  lj_snap_add(J);
3,169✔
543

544
  emitir(IRTG(op, t), tr[FORL_IDX], stop);
3,169✔
545

546
  if (ev == LOOPEV_LEAVE) {
3,169✔
547
    J->maxslot = ra;
64✔
548
    J->pc = fori+bc_j(*fori)+1;
64✔
549
  } else {
550
    J->maxslot = ra+FORL_EXT+1;
3,105✔
551
    J->pc = fori+1;
3,105✔
552
  }
553
  J->needsnap = 1;
3,169✔
554
  return ev;
3,169✔
555
}
556

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

573
/* Record LOOP/JLOOP. Now, that was easy. */
574
static LoopEvent rec_loop(jit_State *J, BCReg ra, int skip)
33,293✔
575
{
576
  if (ra < J->maxslot) J->maxslot = ra;
19,499✔
577
  J->pc += skip;
33,293✔
578
  return LOOPEV_ENTER;
33,293✔
579
}
580

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

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

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

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

643
#if LJ_HASPROFILE
644

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

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

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

686
#endif
687

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

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

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

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

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

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

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

817
/* Record return. */
818
void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
1,209,534✔
819
{
820
  TValue *frame = J->L->base - 1;
1,209,534✔
821
  ptrdiff_t i;
1,209,534✔
822
  BCReg baseadj = 0;
1,209,534✔
823
  for (i = 0; i < gotresults; i++)
2,309,329✔
824
    (void)getslot(J, rbase+i);  /* Ensure all results have a reference. */
1,099,795✔
825
  while (frame_ispcall(frame)) {  /* Immediately resolve pcall() returns. */
1,209,564✔
826
    BCReg cbase = (BCReg)frame_delta(frame);
42✔
827
    if (--J->framedepth <= 0)
42✔
828
      lj_trace_err(J, LJ_TRERR_NYIRETL);
12✔
829
    lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
30✔
830
    gotresults++;
30✔
831
    baseadj += cbase;
30✔
832
    rbase += cbase;
30✔
833
    J->baseslot -= (BCReg)cbase;
30✔
834
    J->base -= cbase;
30✔
835
    J->base[--rbase] = TREF_TRUE;  /* Prepend true to results. */
30✔
836
    frame = frame_prevd(frame);
30✔
837
    J->needsnap = 1;  /* Stop catching on-trace errors. */
30✔
838
  }
839
  /* Return to lower frame via interpreter for unhandled cases. */
840
  if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) &&
1,209,522✔
841
       (!frame_islua(frame) ||
135,349✔
842
        (J->parent == 0 && J->exitno == 0 &&
135,296✔
843
         !bc_isret(bc_op(J->cur.startins))))) {
1,076✔
844
    /* NYI: specialize to frame type and return directly, not via RET*. */
845
    for (i = 0; i < (ptrdiff_t)rbase; i++)
2,649✔
846
      J->base[i] = 0;  /* Purge dead slots. */
1,521✔
847
    J->maxslot = rbase + (BCReg)gotresults;
1,128✔
848
    lj_record_stop(J, LJ_TRLINK_RETURN, 0);  /* Return to interpreter. */
1,128✔
849
    return;
1,128✔
850
  }
851
  if (frame_isvarg(frame)) {
1,208,394✔
852
    BCReg cbase = (BCReg)frame_delta(frame);
29✔
853
    if (--J->framedepth < 0)  /* NYI: return of vararg func to lower frame. */
29✔
854
      lj_trace_err(J, LJ_TRERR_NYIRETL);
×
855
    lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
29✔
856
    baseadj += cbase;
29✔
857
    rbase += cbase;
29✔
858
    J->baseslot -= (BCReg)cbase;
29✔
859
    J->base -= cbase;
29✔
860
    frame = frame_prevd(frame);
29✔
861
  }
862
  if (frame_islua(frame)) {  /* Return to Lua frame. */
1,208,394✔
863
    BCIns callins = *(frame_pc(frame)-1);
1,098,541✔
864
    ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
1,098,541✔
865
    BCReg cbase = bc_a(callins);
1,098,541✔
866
    GCproto *pt = funcproto(frame_func(frame - (cbase+1+LJ_FR2)));
1,098,541✔
867
    if ((pt->flags & PROTO_NOJIT))
1,098,541✔
868
      lj_trace_err(J, LJ_TRERR_CJITOFF);
×
869
    if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
1,098,541✔
870
      if (!J->cur.root && check_downrec_unroll(J, pt)) {
134,221✔
871
        J->maxslot = (BCReg)(rbase + gotresults);
×
872
        lj_snap_purge(J);
×
873
        lj_record_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno);  /* Down-rec. */
×
874
        return;
×
875
      }
876
      lj_snap_add(J);
134,220✔
877
    }
878
    for (i = 0; i < nresults; i++)  /* Adjust results. */
2,040,366✔
879
      J->base[i-1-LJ_FR2] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
941,826✔
880
    J->maxslot = cbase+(BCReg)nresults;
1,098,540✔
881
    if (J->framedepth > 0) {  /* Return to a frame that is part of the trace. */
1,098,540✔
882
      J->framedepth--;
963,805✔
883
      lj_assertJ(J->baseslot > cbase+1+LJ_FR2, "bad baseslot for return");
963,805✔
884
      J->baseslot -= cbase+1+LJ_FR2;
963,805✔
885
      J->base -= cbase+1+LJ_FR2;
963,805✔
886
    } else if (J->parent == 0 && J->exitno == 0 &&
134,735✔
887
               !bc_isret(bc_op(J->cur.startins))) {
24✔
888
      /* Return to lower frame would leave the loop in a root trace. */
889
      lj_trace_err(J, LJ_TRERR_LLEAVE);
23✔
890
    } else if (J->needsnap) {  /* Tailcalled to ff with side-effects. */
134,712✔
891
      lj_trace_err(J, LJ_TRERR_NYIRETL);  /* No way to insert snapshot here. */
×
892
    } else if (1 + pt->framesize >= LJ_MAX_JSLOTS) {
134,712✔
893
      lj_trace_err(J, LJ_TRERR_STACKOV);
1✔
894
    } else {  /* Return to lower frame. Guard for the target we return to. */
895
      TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
134,711✔
896
      TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
134,711✔
897
      emitir(IRTG(IR_RETF, IRT_PGC), trpt, trpc);
134,711✔
898
      J->retdepth++;
134,711✔
899
      J->needsnap = 1;
134,711✔
900
      lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot for return");
134,711✔
901
      /* Shift result slots up and clear the slots of the new frame below. */
902
      memmove(J->base + cbase, J->base-1-LJ_FR2, sizeof(TRef)*nresults);
134,711✔
903
      memset(J->base-1-LJ_FR2, 0, sizeof(TRef)*(cbase+1+LJ_FR2));
134,711✔
904
    }
905
  } else if (frame_iscont(frame)) {  /* Return to continuation frame. */
109,853✔
906
    ASMFunction cont = frame_contf(frame);
109,853✔
907
    BCReg cbase = (BCReg)frame_delta(frame);
109,853✔
908
    if ((J->framedepth -= 2) < 0)
109,853✔
909
      lj_trace_err(J, LJ_TRERR_NYIRETL);
5✔
910
    J->baseslot -= (BCReg)cbase;
109,848✔
911
    J->base -= cbase;
109,848✔
912
    J->maxslot = cbase-(2<<LJ_FR2);
109,848✔
913
    if (cont == lj_cont_ra) {
109,848✔
914
      /* Copy result to destination slot. */
915
      BCReg dst = bc_a(*(frame_contpc(frame)-1));
75,105✔
916
      J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
75,105✔
917
      if (dst >= J->maxslot) {
75,105✔
918
        J->maxslot = dst+1;
×
919
      }
920
    } else if (cont == lj_cont_nop) {
34,743✔
921
      /* Nothing to do here. */
922
    } else if (cont == lj_cont_cat) {
34,591✔
923
      BCReg bslot = bc_b(*(frame_contpc(frame)-1));
12✔
924
      TRef tr = gotresults ? J->base[cbase+rbase] : TREF_NIL;
12✔
925
      if (bslot != J->maxslot) {  /* Concatenate the remainder. */
12✔
926
        /* Simulate lower frame and result. */
927
        TValue *b = J->L->base - baseadj, save;
6✔
928
        /* Can't handle MM_concat + CALLT + fast func side-effects. */
929
        if (J->postproc != LJ_POST_NONE)
6✔
930
          lj_trace_err(J, LJ_TRERR_NYIRETL);
1✔
931
        J->base[J->maxslot] = tr;
5✔
932
        copyTV(J->L, &save, b-(2<<LJ_FR2));
5✔
933
        if (gotresults)
5✔
934
          copyTV(J->L, b-(2<<LJ_FR2), b+rbase);
5✔
935
        else
936
          setnilV(b-(2<<LJ_FR2));
×
937
        J->L->base = b - cbase;
5✔
938
        tr = rec_cat(J, bslot, cbase-(2<<LJ_FR2));
5✔
939
        b = J->L->base + cbase;  /* Undo. */
5✔
940
        J->L->base = b + baseadj;
5✔
941
        copyTV(J->L, b-(2<<LJ_FR2), &save);
5✔
942
      }
943
      if (tr >= 0xffffff00) {
11✔
944
        lj_err_throw(J->L, -(int32_t)tr);  /* Propagate errors. */
1✔
945
      } else if (tr) {  /* Store final result. */
10✔
946
        BCReg dst = bc_a(*(frame_contpc(frame)-1));
6✔
947
        J->base[dst] = tr;
6✔
948
        if (dst >= J->maxslot) {
6✔
949
          J->maxslot = dst+1;
×
950
        }
951
      }  /* Otherwise continue with another __concat call. */
952
    } else {
953
      /* Result type already specialized. */
954
      lj_assertJ(cont == lj_cont_condf || cont == lj_cont_condt,
955
                 "bad continuation type");
956
    }
957
  } else {
958
    lj_trace_err(J, LJ_TRERR_NYIRETL);  /* NYI: handle return to C frame. */
×
959
  }
960
  lj_assertJ(J->baseslot >= 1+LJ_FR2, "bad baseslot for return");
1,209,490✔
961
}
962

963
/* -- Metamethod handling ------------------------------------------------- */
964

965
/* Prepare to record call to metamethod. */
966
static BCReg rec_mm_prep(jit_State *J, ASMFunction cont)
109,859✔
967
{
968
  BCReg s, top = cont == lj_cont_cat ? J->maxslot : curr_proto(J->L)->framesize;
109,859✔
969
#if LJ_FR2
970
  J->base[top] = lj_ir_k64(J, IR_KNUM, u64ptr(contptr(cont)));
109,859✔
971
  J->base[top+1] = TREF_CONT;
109,859✔
972
#else
973
  J->base[top] = lj_ir_kptr(J, contptr(cont)) | TREF_CONT;
974
#endif
975
  J->framedepth++;
109,859✔
976
  for (s = J->maxslot; s < top; s++)
511,635✔
977
    J->base[s] = 0;  /* Clear frame gap to avoid resurrecting previous refs. */
401,776✔
978
  return top+1+LJ_FR2;
109,859✔
979
}
980

981
/* Record metamethod lookup. */
982
int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
189,169✔
983
{
984
  RecordIndex mix;
189,169✔
985
  GCtab *mt;
189,169✔
986
  if (tref_istab(ix->tab)) {
189,169✔
987
    mt = tabref(tabV(&ix->tabv)->metatable);
66,512✔
988
    mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
66,512✔
989
  } else if (tref_isudata(ix->tab)) {
122,657✔
990
    int udtype = udataV(&ix->tabv)->udtype;
12,449✔
991
    mt = tabref(udataV(&ix->tabv)->metatable);
12,449✔
992
    /* The metatables of special userdata objects are treated as immutable. */
993
    if (udtype > UDTYPE_IO_FILE) {
12,449✔
994
      cTValue *mo;
12,441✔
995
      if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) {
12,441✔
996
        /* Specialize to the C library namespace object. */
997
        emitir(IRTG(IR_EQ, IRT_PGC), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv)));
12,441✔
998
      } else {
999
        /* Specialize to the type of userdata. */
1000
        TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE);
×
1001
        emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, udtype));
×
1002
      }
1003
  immutable_mt:
122,243✔
1004
      mo = lj_tab_getstr(mt, mmname_str(J2G(J), mm));
122,243✔
1005
      if (!mo || tvisnil(mo))
122,243✔
1006
        return 0;  /* No metamethod. */
1007
      /* Treat metamethod or index table as immutable, too. */
1008
      if (!(tvisfunc(mo) || tvistab(mo)))
122,243✔
1009
        lj_trace_err(J, LJ_TRERR_BADTYPE);
×
1010
      copyTV(J->L, &ix->mobjv, mo);
122,243✔
1011
      ix->mobj = lj_ir_kgc(J, gcV(mo), tvisfunc(mo) ? IRT_FUNC : IRT_TAB);
122,243✔
1012
      ix->mtv = mt;
122,243✔
1013
      ix->mt = TREF_NIL;  /* Dummy value for comparison semantics. */
122,243✔
1014
      return 1;  /* Got metamethod or index table. */
122,243✔
1015
    }
1016
    mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_UDATA_META);
8✔
1017
  } else {
1018
    /* Specialize to base metatable. Must flush mcode in lua_setmetatable(). */
1019
    mt = tabref(basemt_obj(J2G(J), &ix->tabv));
110,208✔
1020
    if (mt == NULL) {
110,208✔
1021
      ix->mt = TREF_NIL;
159✔
1022
      return 0;  /* No metamethod. */
159✔
1023
    }
1024
    /* The cdata metatable is treated as immutable. */
1025
    if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt;
110,049✔
1026
#if LJ_GC64
1027
    /* TODO: fix ARM32 asm_fload(), so we can use this for all archs. */
1028
    ix->mt = mix.tab = lj_ir_ggfload(J, IRT_TAB,
490✔
1029
      GG_OFS(g.gcroot[GCROOT_BASEMT+itypemap(&ix->tabv)]));
243✔
1030
#else
1031
    ix->mt = mix.tab = lj_ir_ktab(J, mt);
1032
#endif
1033
    goto nocheck;
247✔
1034
  }
1035
  ix->mt = mt ? mix.tab : TREF_NIL;
66,520✔
1036
  emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mix.tab, lj_ir_knull(J, IRT_TAB));
94,864✔
1037
nocheck:
66,767✔
1038
  if (mt) {
66,767✔
1039
    GCstr *mmstr = mmname_str(J2G(J), mm);
38,423✔
1040
    cTValue *mo = lj_tab_getstr(mt, mmstr);
38,423✔
1041
    if (mo && !tvisnil(mo))
38,423✔
1042
      copyTV(J->L, &ix->mobjv, mo);
38,348✔
1043
    ix->mtv = mt;
38,423✔
1044
    settabV(J->L, &mix.tabv, mt);
38,423✔
1045
    setstrV(J->L, &mix.keyv, mmstr);
38,423✔
1046
    mix.key = lj_ir_kstr(J, mmstr);
38,423✔
1047
    mix.val = 0;
38,423✔
1048
    mix.idxchain = 0;
38,423✔
1049
    ix->mobj = lj_record_idx(J, &mix);
38,423✔
1050
    return !tref_isnil(ix->mobj);  /* 1 if metamethod found, 0 if not. */
38,423✔
1051
  }
1052
  return 0;  /* No metamethod. */
1053
}
1054

1055
/* Record call to arithmetic metamethod. */
1056
static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
40,581✔
1057
{
1058
  /* Set up metamethod call first to save ix->tab and ix->tabv. */
1059
  BCReg func = rec_mm_prep(J, mm == MM_concat ? lj_cont_cat : lj_cont_ra);
81,149✔
1060
  TRef *base = J->base + func;
40,581✔
1061
  TValue *basev = J->L->base + func;
40,581✔
1062
  base[1+LJ_FR2] = ix->tab; base[2+LJ_FR2] = ix->key;
40,581✔
1063
  copyTV(J->L, basev+1+LJ_FR2, &ix->tabv);
40,581✔
1064
  copyTV(J->L, basev+2+LJ_FR2, &ix->keyv);
40,581✔
1065
  if (!lj_record_mm_lookup(J, ix, mm)) {  /* Lookup mm on 1st operand. */
40,581✔
1066
    if (mm != MM_unm) {
19✔
1067
      ix->tab = ix->key;
19✔
1068
      copyTV(J->L, &ix->tabv, &ix->keyv);
19✔
1069
      if (lj_record_mm_lookup(J, ix, mm))  /* Lookup mm on 2nd operand. */
19✔
1070
        goto ok;
18✔
1071
    }
1072
    lj_trace_err(J, LJ_TRERR_NOMM);
1✔
1073
  }
1074
ok:
40,562✔
1075
  base[0] = ix->mobj;
40,580✔
1076
#if LJ_FR2
1077
  base[1] = 0;
40,580✔
1078
#endif
1079
  copyTV(J->L, basev+0, &ix->mobjv);
40,580✔
1080
  lj_record_call(J, func, 2);
40,580✔
1081
  return 0;  /* No result yet. */
40,579✔
1082
}
1083

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

1112
/* Call a comparison metamethod. */
1113
static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op)
34,581✔
1114
{
1115
  BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt);
47,066✔
1116
  TRef *base = J->base + func + LJ_FR2;
34,581✔
1117
  TValue *tv = J->L->base + func + LJ_FR2;
34,581✔
1118
  base[-LJ_FR2] = ix->mobj; base[1] = ix->val; base[2] = ix->key;
34,581✔
1119
  copyTV(J->L, tv-LJ_FR2, &ix->mobjv);
34,581✔
1120
  copyTV(J->L, tv+1, &ix->valv);
34,581✔
1121
  copyTV(J->L, tv+2, &ix->keyv);
34,581✔
1122
  lj_record_call(J, func, 2);
34,581✔
1123
}
34,581✔
1124

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

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

1206
#if LJ_HASFFI
1207
/* Setup call to cdata comparison metamethod. */
1208
static void rec_mm_comp_cdata(jit_State *J, RecordIndex *ix, int op, MMS mm)
34,523✔
1209
{
1210
  lj_snap_add(J);
34,523✔
1211
  if (tref_iscdata(ix->val)) {
34,523✔
1212
    ix->tab = ix->val;
51✔
1213
    copyTV(J->L, &ix->tabv, &ix->valv);
51✔
1214
  } else {
1215
    lj_assertJ(tref_iscdata(ix->key), "cdata expected");
34,472✔
1216
    ix->tab = ix->key;
34,472✔
1217
    copyTV(J->L, &ix->tabv, &ix->keyv);
34,472✔
1218
  }
1219
  lj_record_mm_lookup(J, ix, mm);
34,523✔
1220
  rec_mm_callcomp(J, ix, op);
34,523✔
1221
}
34,523✔
1222
#endif
1223

1224
/* -- Indexed access ------------------------------------------------------ */
1225

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

1292
/* Record bounds-check. */
1293
static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize)
5,361✔
1294
{
1295
  /* Try to emit invariant bounds checks. */
1296
  if ((J->flags & (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) ==
5,361✔
1297
      (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) {
1298
    IRRef ref = tref_ref(ikey);
5,350✔
1299
    IRIns *ir = IR(ref);
5,350✔
1300
    int32_t ofs = 0;
5,350✔
1301
    IRRef ofsref = 0;
5,350✔
1302
    /* Handle constant offsets. */
1303
    if (ir->o == IR_ADD && irref_isk(ir->op2)) {
5,350✔
1304
      ofsref = ir->op2;
176✔
1305
      ofs = IR(ofsref)->i;
176✔
1306
      ref = ir->op1;
176✔
1307
      ir = IR(ref);
176✔
1308
    }
1309
    /* Got scalar evolution analysis results for this reference? */
1310
    if (ref == J->scev.idx) {
5,350✔
1311
      int32_t stop;
3,732✔
1312
      lj_assertJ(irt_isint(J->scev.t) && ir->o == IR_SLOAD,
3,732✔
1313
                 "only int SCEV supported");
1314
      stop = numberVint(&(J->L->base - J->baseslot)[ir->op1 + FORL_STOP]);
3,732✔
1315
      /* Runtime value for stop of loop is within bounds? */
1316
      if ((uint64_t)stop + ofs < (uint64_t)asize) {
3,732✔
1317
        /* Emit invariant bounds check for stop. */
1318
        emitir(IRTG(IR_ABC, IRT_P32), asizeref, ofs == 0 ? J->scev.stop :
149✔
1319
               emitir(IRTI(IR_ADD), J->scev.stop, ofsref));
1320
        /* Emit invariant bounds check for start, if not const or negative. */
1321
        if (!(J->scev.dir && J->scev.start &&
149✔
1322
              (int64_t)IR(J->scev.start)->i + ofs >= 0))
138✔
1323
          emitir(IRTG(IR_ABC, IRT_P32), asizeref, ikey);
11✔
1324
        return;
149✔
1325
      }
1326
    }
1327
  }
1328
  emitir(IRTGI(IR_ABC), asizeref, ikey);  /* Emit regular bounds check. */
5,212✔
1329
}
1330

1331
/* Record indexed key lookup. */
1332
static TRef rec_idx_key(jit_State *J, RecordIndex *ix, IRRef *rbref,
1,610,985✔
1333
                        IRType1 *rbguard)
1334
{
1335
  TRef key;
1,610,985✔
1336
  GCtab *t = tabV(&ix->tabv);
1,610,985✔
1337
  ix->oldv = lj_tab_get(J->L, t, &ix->keyv);  /* Lookup previous value. */
1,610,985✔
1338
  *rbref = 0;
1,610,985✔
1339
  rbguard->irt = 0;
1,610,985✔
1340

1341
  /* Integer keys are looked up in the array part first. */
1342
  key = ix->key;
1,610,985✔
1343
  if (tref_isnumber(key)) {
1,610,985✔
1344
    int32_t k = numberVint(&ix->keyv);
30,795✔
1345
    if (!tvisint(&ix->keyv) && numV(&ix->keyv) != (lua_Number)k)
30,795✔
1346
      k = LJ_MAX_ASIZE;
94✔
1347
    if ((MSize)k < LJ_MAX_ASIZE) {  /* Potential array key? */
30,795✔
1348
      TRef ikey = lj_opt_narrow_index(J, key);
30,666✔
1349
      TRef asizeref = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
30,666✔
1350
      if ((MSize)k < t->asize) {  /* Currently an array key? */
30,666✔
1351
        TRef arrayref;
5,357✔
1352
        rec_idx_abc(J, asizeref, ikey, t->asize);
5,357✔
1353
        arrayref = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_ARRAY);
5,357✔
1354
        return emitir(IRT(IR_AREF, IRT_PGC), arrayref, ikey);
5,357✔
1355
      } else {  /* Currently not in array (may be an array extension)? */
1356
        emitir(IRTGI(IR_ULE), asizeref, ikey);  /* Inv. bounds check. */
25,309✔
1357
        if (k == 0 && tref_isk(key))
25,309✔
1358
          key = lj_ir_knum_zero(J);  /* Canonicalize 0 or +-0.0 to +0.0. */
4✔
1359
        /* And continue with the hash lookup. */
1360
      }
1361
    } else if (!tref_isk(key)) {
129✔
1362
      /* We can rule out const numbers which failed the integerness test
1363
      ** above. But all other numbers are potential array keys.
1364
      */
1365
      if (t->asize == 0) {  /* True sparse tables have an empty array part. */
129✔
1366
        /* Guard that the array part stays empty. */
1367
        TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
117✔
1368
        emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
117✔
1369
      } else {
1370
        lj_trace_err(J, LJ_TRERR_NYITMIX);
12✔
1371
      }
1372
    }
1373
  }
1374

1375
  /* Otherwise the key is located in the hash part. */
1376
  if (t->hmask == 0) {  /* Shortcut for empty hash part. */
1,605,616✔
1377
    /* Guard that the hash part stays empty. */
1378
    TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
409✔
1379
    emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
409✔
1380
    return lj_ir_kkptr(J, niltvg(J2G(J)));
409✔
1381
  }
1382
  if (tref_isinteger(key))  /* Hash keys are based on numbers, not ints. */
1,605,207✔
1383
    key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
25,163✔
1384
  if (tref_isk(key)) {
1,605,207✔
1385
    /* Optimize lookup of constant hash keys. */
1386
    GCSize hslot = (GCSize)((char *)ix->oldv-(char *)&noderef(t->node)[0].val);
1,579,876✔
1387
    if (hslot <= t->hmask*(GCSize)sizeof(Node) &&
1,579,876✔
1388
        hslot <= 65535*(GCSize)sizeof(Node)) {
1389
      TRef node, kslot, hm;
1,520,532✔
1390
      *rbref = J->cur.nins;  /* Mark possible rollback point. */
1,520,532✔
1391
      *rbguard = J->guardemit;
1,520,532✔
1392
      hm = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
1,520,532✔
1393
      emitir(IRTGI(IR_EQ), hm, lj_ir_kint(J, (int32_t)t->hmask));
1,520,532✔
1394
      node = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_NODE);
1,520,532✔
1395
      kslot = lj_ir_kslot(J, key, (IRRef)(hslot / sizeof(Node)));
1,520,532✔
1396
      return emitir(IRTG(IR_HREFK, IRT_PGC), node, kslot);
1,520,532✔
1397
    }
1398
  }
1399
  /* Fall back to a regular hash lookup. */
1400
  return emitir(IRT(IR_HREF, IRT_PGC), ix->tab, key);
84,675✔
1401
}
1402

1403
/* Determine whether a key is NOT one of the fast metamethod names. */
1404
static int nommstr(jit_State *J, TRef key)
317,286✔
1405
{
1406
  if (tref_isstr(key)) {
317,286✔
1407
    if (tref_isk(key)) {
314,169✔
1408
      GCstr *str = ir_kstr(IR(tref_ref(key)));
314,158✔
1409
      uint32_t mm;
314,158✔
1410
      for (mm = 0; mm <= MM_FAST; mm++)
2,199,106✔
1411
        if (mmname_str(J2G(J), mm) == str)
1,884,948✔
1412
          return 0;  /* MUST be one the fast metamethod names. */
1413
    } else {
1414
      return 0;  /* Variable string key MAY be a metamethod name. */
1415
    }
1416
  }
1417
  return 1;  /* CANNOT be a metamethod name. */
1418
}
1419

1420
/* Record indexed load/store. */
1421
TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1,607,696✔
1422
{
1423
  TRef xref;
1,607,696✔
1424
  IROp xrefop, loadop;
1,607,696✔
1425
  IRRef rbref;
1,607,696✔
1426
  IRType1 rbguard;
1,607,696✔
1427
  cTValue *oldv;
1,607,696✔
1428

1429
  while (!tref_istab(ix->tab)) { /* Handle non-table lookup. */
1,645,908✔
1430
    /* Never call raw lj_record_idx() on non-table. */
1431
    lj_assertJ(ix->idxchain != 0, "bad usage");
34,921✔
1432
    if (!lj_record_mm_lookup(J, ix, ix->val ? MM_newindex : MM_index))
34,921✔
1433
      lj_trace_err(J, LJ_TRERR_NOMM);
×
1434
  handlemm:
34,921✔
1435
    if (tref_isfunc(ix->mobj)) {  /* Handle metamethod call. */
72,907✔
1436
      BCReg func = rec_mm_prep(J, ix->val ? lj_cont_nop : lj_cont_ra);
69,237✔
1437
      TRef *base = J->base + func + LJ_FR2;
34,695✔
1438
      TValue *tv = J->L->base + func + LJ_FR2;
34,695✔
1439
      base[-LJ_FR2] = ix->mobj; base[1] = ix->tab; base[2] = ix->key;
34,695✔
1440
      setfuncV(J->L, tv-LJ_FR2, funcV(&ix->mobjv));
34,695✔
1441
      copyTV(J->L, tv+1, &ix->tabv);
34,695✔
1442
      copyTV(J->L, tv+2, &ix->keyv);
34,695✔
1443
      if (ix->val) {
34,695✔
1444
        base[3] = ix->val;
153✔
1445
        copyTV(J->L, tv+3, &ix->valv);
153✔
1446
        lj_record_call(J, func, 3);  /* mobj(tab, key, val) */
153✔
1447
        return 0;
153✔
1448
      } else {
1449
        lj_record_call(J, func, 2);  /* res = mobj(tab, key) */
34,542✔
1450
        return 0;  /* No result yet. */
34,542✔
1451
      }
1452
    }
1453
    /* Otherwise retry lookup with metaobject. */
1454
    ix->tab = ix->mobj;
38,212✔
1455
    copyTV(J->L, &ix->tabv, &ix->mobjv);
38,212✔
1456
    if (--ix->idxchain == 0)
38,212✔
1457
      lj_trace_err(J, LJ_TRERR_IDXLOOP);
×
1458
  }
1459

1460
  /* First catch nil and NaN keys for tables. */
1461
  if (tvisnil(&ix->keyv) || (tvisnum(&ix->keyv) && tvisnan(&ix->keyv))) {
1,610,987✔
1462
    if (ix->val)  /* Better fail early. */
2✔
1463
      lj_trace_err(J, LJ_TRERR_STORENN);
2✔
1464
    if (tref_isk(ix->key)) {
×
1465
      if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
×
1466
        goto handlemm;
×
1467
      return TREF_NIL;
×
1468
    }
1469
  }
1470

1471
  /* Record the key lookup. */
1472
  xref = rec_idx_key(J, ix, &rbref, &rbguard);
1,610,985✔
1473
  xrefop = IR(tref_ref(xref))->o;
1,610,973✔
1474
  loadop = xrefop == IR_AREF ? IR_ALOAD : IR_HLOAD;
1,610,973✔
1475
  /* The lj_meta_tset() inconsistency is gone, but better play safe. */
1476
  oldv = xrefop == IR_KKPTR ? (cTValue *)ir_kptr(IR(tref_ref(xref))) : ix->oldv;
1,610,973✔
1477

1478
  if (ix->val == 0) {  /* Indexed load */
1,610,973✔
1479
    IRType t = itype2irt(oldv);
1,293,675✔
1480
    TRef res;
1,293,675✔
1481
    if (oldv == niltvg(J2G(J))) {
1,293,675✔
1482
      emitir(IRTG(IR_EQ, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
51,118✔
1483
      res = TREF_NIL;
51,118✔
1484
    } else {
1485
      res = emitir(IRTG(loadop, t), xref, 0);
1,242,557✔
1486
    }
1487
    if (tref_ref(res) < rbref) {  /* HREFK + load forwarded? */
1,293,675✔
1488
      lj_ir_rollback(J, rbref);  /* Rollback to eliminate hmask guard. */
570,373✔
1489
      J->guardemit = rbguard;
570,373✔
1490
    }
1491
    if (t == IRT_NIL && ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
1,293,675✔
1492
      goto handlemm;
37,974✔
1493
    if (irtype_ispri(t)) res = TREF_PRI(t);  /* Canonicalize primitives. */
1,255,701✔
1494
    return res;
1,255,701✔
1495
  } else {  /* Indexed store. */
1496
    GCtab *mt = tabref(tabV(&ix->tabv)->metatable);
317,298✔
1497
    int keybarrier = tref_isgcv(ix->key) && !tref_isnil(ix->val);
317,298✔
1498
    if (tref_ref(xref) < rbref) {  /* HREFK forwarded? */
317,298✔
1499
      lj_ir_rollback(J, rbref);  /* Rollback to eliminate hmask guard. */
31,221✔
1500
      J->guardemit = rbguard;
31,221✔
1501
    }
1502
    if (tvisnil(oldv)) {  /* Previous value was nil? */
317,298✔
1503
      /* Need to duplicate the hasmm check for the early guards. */
1504
      int hasmm = 0;
10,945✔
1505
      if (ix->idxchain && mt) {
10,945✔
1506
        cTValue *mo = lj_tab_getstr(mt, mmname_str(J2G(J), MM_newindex));
36✔
1507
        hasmm = mo && !tvisnil(mo);
36✔
1508
      }
1509
      if (hasmm)
12✔
1510
        emitir(IRTG(loadop, IRT_NIL), xref, 0);  /* Guard for nil value. */
12✔
1511
      else if (xrefop == IR_HREF)
10,933✔
1512
        emitir(IRTG(oldv == niltvg(J2G(J)) ? IR_EQ : IR_NE, IRT_PGC),
8,345✔
1513
               xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1514
      if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_newindex)) {
10,945✔
1515
        lj_assertJ(hasmm, "inconsistent metamethod handling");
12✔
1516
        goto handlemm;
12✔
1517
      }
1518
      lj_assertJ(!hasmm, "inconsistent metamethod handling");
10,933✔
1519
      if (oldv == niltvg(J2G(J))) {  /* Need to insert a new key. */
10,933✔
1520
        TRef key = ix->key;
8,748✔
1521
        if (tref_isinteger(key)) {  /* NEWREF needs a TValue as a key. */
8,748✔
1522
          key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
131✔
1523
        } else if (tref_isnum(key)) {
8,617✔
1524
          if (tref_isk(key)) {
71✔
1525
            if (tvismzero(&ix->keyv))
2✔
1526
              key = lj_ir_knum_zero(J);  /* Canonicalize -0.0 to +0.0. */
2✔
1527
          } else {
1528
            emitir(IRTG(IR_EQ, IRT_NUM), key, key);  /* Check for !NaN. */
69✔
1529
          }
1530
        }
1531
        xref = emitir(IRT(IR_NEWREF, IRT_PGC), ix->tab, key);
8,748✔
1532
        keybarrier = 0;  /* NEWREF already takes care of the key barrier. */
8,748✔
1533
#ifdef LUAJIT_ENABLE_TABLE_BUMP
1534
        if ((J->flags & JIT_F_OPT_SINK))  /* Avoid a separate flag. */
1535
          rec_idx_bump(J, ix);
1536
#endif
1537
      }
1538
    } else if (!lj_opt_fwd_wasnonnil(J, loadop, tref_ref(xref))) {
306,353✔
1539
      /* Cannot derive that the previous value was non-nil, must do checks. */
1540
      if (xrefop == IR_HREF)  /* Guard against store to niltv. */
273,293✔
1541
        emitir(IRTG(IR_NE, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
29✔
1542
      if (ix->idxchain) {  /* Metamethod lookup required? */
273,293✔
1543
        /* A check for NULL metatable is cheaper (hoistable) than a load. */
1544
        if (!mt) {
273,284✔
1545
          TRef mtref = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
273,266✔
1546
          emitir(IRTG(IR_EQ, IRT_TAB), mtref, lj_ir_knull(J, IRT_TAB));
273,266✔
1547
        } else {
1548
          IRType t = itype2irt(oldv);
18✔
1549
          emitir(IRTG(loadop, t), xref, 0);  /* Guard for non-nil value. */
18✔
1550
        }
1551
      }
1552
    } else {
1553
      keybarrier = 0;  /* Previous non-nil value kept the key alive. */
1554
    }
1555
    /* Convert int to number before storing. */
1556
    if (!LJ_DUALNUM && tref_isinteger(ix->val))
317,286✔
1557
      ix->val = emitir(IRTN(IR_CONV), ix->val, IRCONV_NUM_INT);
3,313✔
1558
    emitir(IRT(loadop+IRDELTA_L2S, tref_type(ix->val)), xref, ix->val);
317,286✔
1559
    if (keybarrier || tref_isgcv(ix->val))
317,286✔
1560
      emitir(IRT(IR_TBAR, IRT_NIL), ix->tab, 0);
281,399✔
1561
    /* Invalidate neg. metamethod cache for stores with certain string keys. */
1562
    if (!nommstr(J, ix->key)) {
631,444✔
1563
      TRef fref = emitir(IRT(IR_FREF, IRT_PGC), ix->tab, IRFL_TAB_NOMM);
11✔
1564
      emitir(IRT(IR_FSTORE, IRT_U8), fref, lj_ir_kint(J, 0));
11✔
1565
    }
1566
    J->needsnap = 1;
317,286✔
1567
    return 0;
317,286✔
1568
  }
1569
}
1570

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

1596
/* -- Upvalue access ------------------------------------------------------ */
1597

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

1623
/* Record upvalue load/store. */
1624
static TRef rec_upvalue(jit_State *J, uint32_t uv, TRef val)
1,139,976✔
1625
{
1626
  GCupval *uvp = &gcref(J->fn->l.uvptr[uv])->uv;
1,139,976✔
1627
  TRef fn = getcurrf(J);
1,139,976✔
1628
  IRRef uref;
1,139,976✔
1629
  int needbarrier = 0;
1,139,976✔
1630
  if (rec_upvalue_constify(J, uvp)) {  /* Try to constify immutable upvalue. */
1,139,976✔
1631
    TRef tr, kfunc;
1,066,148✔
1632
    lj_assertJ(val == 0, "bad usage");
1,066,148✔
1633
    if (!tref_isk(fn)) {  /* Late specialization of current function. */
1,066,148✔
1634
      if (J->pt->flags >= PROTO_CLC_POLY)
123,984✔
1635
        goto noconstify;
86✔
1636
      kfunc = lj_ir_kfunc(J, J->fn);
123,898✔
1637
      emitir(IRTG(IR_EQ, IRT_FUNC), fn, kfunc);
123,898✔
1638
#if LJ_FR2
1639
      J->base[-2] = kfunc;
123,898✔
1640
#else
1641
      J->base[-1] = kfunc | TREF_FRAME;
1642
#endif
1643
      fn = kfunc;
123,898✔
1644
    }
1645
    tr = lj_record_constify(J, uvval(uvp));
1,066,062✔
1646
    if (tr)
1,066,062✔
1647
      return tr;
1648
  }
1649
noconstify:
73,828✔
1650
  /* Note: this effectively limits LJ_MAX_UPVAL to 127. */
1651
  uv = (uv << 8) | (hashrot(uvp->dhash, uvp->dhash + HASH_BIAS) & 0xff);
73,914✔
1652
  if (!uvp->closed) {
73,914✔
1653
    uref = tref_ref(emitir(IRTG(IR_UREFO, IRT_PGC), fn, uv));
503✔
1654
    /* In current stack? */
1655
    if (uvval(uvp) >= tvref(J->L->stack) &&
503✔
1656
        uvval(uvp) < tvref(J->L->maxstack)) {
503✔
1657
      int32_t slot = (int32_t)(uvval(uvp) - (J->L->base - J->baseslot));
494✔
1658
      if (slot >= 0) {  /* Aliases an SSA slot? */
494✔
1659
        emitir(IRTG(IR_EQ, IRT_PGC),
217✔
1660
               REF_BASE,
1661
               emitir(IRT(IR_ADD, IRT_PGC), uref,
1662
                      lj_ir_kint(J, (slot - 1 - LJ_FR2) * -8)));
1663
        slot -= (int32_t)J->baseslot;  /* Note: slot number may be negative! */
217✔
1664
        if (val == 0) {
217✔
1665
          return getslot(J, slot);
99✔
1666
        } else {
1667
          J->base[slot] = val;
118✔
1668
          if (slot >= (int32_t)J->maxslot) J->maxslot = (BCReg)(slot+1);
118✔
1669
          return 0;
118✔
1670
        }
1671
      }
1672
    }
1673
    emitir(IRTG(IR_UGT, IRT_PGC),
286✔
1674
           emitir(IRT(IR_SUB, IRT_PGC), uref, REF_BASE),
1675
           lj_ir_kint(J, (J->baseslot + J->maxslot) * 8));
1676
  } else {
1677
    needbarrier = 1;
73,411✔
1678
    uref = tref_ref(emitir(IRTG(IR_UREFC, IRT_PGC), fn, uv));
73,411✔
1679
  }
1680
  if (val == 0) {  /* Upvalue load */
73,697✔
1681
    IRType t = itype2irt(uvval(uvp));
73,614✔
1682
    TRef res = emitir(IRTG(IR_ULOAD, t), uref, 0);
73,614✔
1683
    if (irtype_ispri(t)) res = TREF_PRI(t);  /* Canonicalize primitive refs. */
73,614✔
1684
    return res;
73,614✔
1685
  } else {  /* Upvalue store. */
1686
    /* Convert int to number before storing. */
1687
    if (!LJ_DUALNUM && tref_isinteger(val))
83✔
1688
      val = emitir(IRTN(IR_CONV), val, IRCONV_NUM_INT);
15✔
1689
    emitir(IRT(IR_USTORE, tref_type(val)), uref, val);
83✔
1690
    if (needbarrier && tref_isgcv(val))
83✔
1691
      emitir(IRT(IR_OBAR, IRT_NIL), uref, val);
4✔
1692
    J->needsnap = 1;
83✔
1693
    return 0;
83✔
1694
  }
1695
}
1696

1697
/* -- Record calls to Lua functions --------------------------------------- */
1698

1699
/* Check unroll limits for calls. */
1700
static void check_call_unroll(jit_State *J, TraceNo lnk)
870,388✔
1701
{
1702
  cTValue *frame = J->L->base - 1;
870,388✔
1703
  void *pc = mref(frame_func(frame)->l.pc, void);
870,388✔
1704
  int32_t depth = J->framedepth;
870,388✔
1705
  int32_t count = 0;
870,388✔
1706
  if ((J->pt->flags & PROTO_VARARG)) depth--;  /* Vararg frame still missing. */
870,388✔
1707
  for (; depth > 0; depth--) {  /* Count frames with same prototype. */
2,162,411✔
1708
    if (frame_iscont(frame)) depth--;
1,292,023✔
1709
    frame = frame_prev(frame);
1,292,023✔
1710
    if (mref(frame_func(frame)->l.pc, void) == pc)
1,292,023✔
1711
      count++;
2,124✔
1712
  }
1713
  if (J->pc == J->startpc) {
870,388✔
1714
    if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
492✔
1715
      J->pc++;
150✔
1716
      if (J->framedepth + J->retdepth == 0)
150✔
1717
        lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno);  /* Tail-rec. */
5✔
1718
      else
1719
        lj_record_stop(J, LJ_TRLINK_UPREC, J->cur.traceno);  /* Up-recursion. */
145✔
1720
    }
1721
  } else {
1722
    if (count > J->param[JIT_P_callunroll]) {
869,896✔
1723
      if (lnk) {  /* Possible tail- or up-recursion. */
110✔
1724
        lj_trace_flush(J, lnk);  /* Flush trace that only returns. */
49✔
1725
        /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
1726
        hotcount_set(J2GG(J), J->pc+1, LJ_PRNG_BITS(J, 4));
49✔
1727
      }
1728
      lj_trace_err(J, LJ_TRERR_CUNROLL);
110✔
1729
    }
1730
  }
1731
}
870,278✔
1732

1733
/* Record Lua function setup. */
1734
static void rec_func_setup(jit_State *J)
873,604✔
1735
{
1736
  GCproto *pt = J->pt;
873,604✔
1737
  BCReg s, numparams = pt->numparams;
873,604✔
1738
  if ((pt->flags & PROTO_NOJIT))
873,604✔
1739
    lj_trace_err(J, LJ_TRERR_CJITOFF);
1✔
1740
  if (J->baseslot + pt->framesize >= LJ_MAX_JSLOTS)
873,603✔
1741
    lj_trace_err(J, LJ_TRERR_STACKOV);
×
1742
  /* Fill up missing parameters with nil. */
1743
  for (s = J->maxslot; s < numparams; s++)
874,049✔
1744
    J->base[s] = TREF_NIL;
446✔
1745
  /* The remaining slots should never be read before they are written. */
1746
  J->maxslot = numparams;
873,603✔
1747
}
873,603✔
1748

1749
/* Record Lua vararg function setup. */
1750
static void rec_func_vararg(jit_State *J)
109✔
1751
{
1752
  GCproto *pt = J->pt;
109✔
1753
  BCReg s, fixargs, vframe = J->maxslot+1+LJ_FR2;
109✔
1754
  lj_assertJ((pt->flags & PROTO_VARARG), "FUNCV in non-vararg function");
109✔
1755
  if (J->baseslot + vframe + pt->framesize >= LJ_MAX_JSLOTS)
109✔
1756
    lj_trace_err(J, LJ_TRERR_STACKOV);
×
1757
  J->base[vframe-1-LJ_FR2] = J->base[-1-LJ_FR2];  /* Copy function up. */
109✔
1758
#if LJ_FR2
1759
  J->base[vframe-1] = TREF_FRAME;
109✔
1760
#endif
1761
  /* Copy fixarg slots up and set their original slots to nil. */
1762
  fixargs = pt->numparams < J->maxslot ? pt->numparams : J->maxslot;
109✔
1763
  for (s = 0; s < fixargs; s++) {
145✔
1764
    J->base[vframe+s] = J->base[s];
36✔
1765
    J->base[s] = TREF_NIL;
36✔
1766
  }
1767
  J->maxslot = fixargs;
109✔
1768
  J->framedepth++;
109✔
1769
  J->base += vframe;
109✔
1770
  J->baseslot += vframe;
109✔
1771
}
109✔
1772

1773
/* Record entry to a Lua function. */
1774
static void rec_func_lua(jit_State *J)
139,278✔
1775
{
1776
  rec_func_setup(J);
139,278✔
1777
  check_call_unroll(J, 0);
139,277✔
1778
}
139,216✔
1779

1780
/* Record entry to an already compiled function. */
1781
static void rec_func_jit(jit_State *J, TraceNo lnk)
734,326✔
1782
{
1783
  GCtrace *T;
734,326✔
1784
  rec_func_setup(J);
734,326✔
1785
  T = traceref(J, lnk);
734,326✔
1786
  if (T->linktype == LJ_TRLINK_RETURN) {  /* Trace returns to interpreter? */
734,326✔
1787
    check_call_unroll(J, lnk);
731,111✔
1788
    /* Temporarily unpatch JFUNC* to continue recording across function. */
1789
    J->patchins = *J->pc;
731,062✔
1790
    J->patchpc = (BCIns *)J->pc;
731,062✔
1791
    *J->patchpc = T->startins;
731,062✔
1792
    return;
731,062✔
1793
  }
1794
  J->instunroll = 0;  /* Cannot continue across a compiled function. */
3,215✔
1795
  if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
3,215✔
1796
    lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno);  /* Extra tail-rec. */
×
1797
  else
1798
    lj_record_stop(J, LJ_TRLINK_ROOT, lnk);  /* Link to the function. */
3,215✔
1799
}
1800

1801
/* -- Vararg handling ----------------------------------------------------- */
1802

1803
/* Detect y = select(x, ...) idiom. */
1804
static int select_detect(jit_State *J)
16✔
1805
{
1806
  BCIns ins = J->pc[1];
16✔
1807
  if (bc_op(ins) == BC_CALLM && bc_b(ins) == 2 && bc_c(ins) == 1) {
16✔
1808
    cTValue *func = &J->L->base[bc_a(ins)];
14✔
1809
    if (tvisfunc(func) && funcV(func)->c.ffid == FF_select) {
14✔
1810
      TRef kfunc = lj_ir_kfunc(J, funcV(func));
10✔
1811
      emitir(IRTG(IR_EQ, IRT_FUNC), getslot(J, bc_a(ins)), kfunc);
10✔
1812
      return 1;
10✔
1813
    }
1814
  }
1815
  return 0;
1816
}
1817

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

1925
/* -- Record allocations -------------------------------------------------- */
1926

1927
static TRef rec_tnew(jit_State *J, uint32_t ah)
551✔
1928
{
1929
  uint32_t asize = ah & 0x7ff;
551✔
1930
  uint32_t hbits = ah >> 11;
551✔
1931
  TRef tr;
551✔
1932
  if (asize == 0x7ff) asize = 0x801;
×
1933
  tr = emitir(IRTG(IR_TNEW, IRT_TAB), asize, hbits);
551✔
1934
#ifdef LUAJIT_ENABLE_TABLE_BUMP
1935
  J->rbchash[(tr & (RBCHASH_SLOTS-1))].ref = tref_ref(tr);
1936
  setmref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pc, J->pc);
1937
  setgcref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
1938
#endif
1939
  return tr;
551✔
1940
}
1941

1942
/* -- Concatenation ------------------------------------------------------- */
1943

1944
typedef struct RecCatDataCP {
1945
  jit_State *J;
1946
  RecordIndex *ix;
1947
} RecCatDataCP;
1948

1949
static TValue *rec_mm_concat_cp(lua_State *L, lua_CFunction dummy, void *ud)
13✔
1950
{
1951
  RecCatDataCP *rcd = (RecCatDataCP *)ud;
13✔
1952
  UNUSED(L); UNUSED(dummy);
13✔
1953
  rec_mm_arith(rcd->J, rcd->ix, MM_concat);  /* Call __concat metamethod. */
13✔
1954
  return NULL;
12✔
1955
}
1956

1957
static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot)
561✔
1958
{
1959
  TRef *top = &J->base[topslot];
561✔
1960
  TValue savetv[5+LJ_FR2];
561✔
1961
  BCReg s;
561✔
1962
  RecordIndex ix;
561✔
1963
  RecCatDataCP rcd;
561✔
1964
  int errcode;
561✔
1965
  lj_assertJ(baseslot < topslot, "bad CAT arg");
561✔
1966
  for (s = baseslot; s <= topslot; s++)
1,986✔
1967
    (void)getslot(J, s);  /* Ensure all arguments have a reference. */
1,425✔
1968
  if (tref_isnumber_str(top[0]) && tref_isnumber_str(top[-1])) {
561✔
1969
    TRef tr, hdr, *trp, *xbase, *base = &J->base[baseslot];
550✔
1970
    /* First convert numbers to strings. */
1971
    for (trp = top; trp >= base; trp--) {
1,945✔
1972
      if (tref_isnumber(*trp))
1,397✔
1973
        *trp = emitir(IRT(IR_TOSTR, IRT_STR), *trp,
45✔
1974
                      tref_isnum(*trp) ? IRTOSTR_NUM : IRTOSTR_INT);
1975
      else if (!tref_isstr(*trp))
1,352✔
1976
        break;
1977
    }
1978
    xbase = ++trp;
550✔
1979
    tr = hdr = emitir(IRT(IR_BUFHDR, IRT_PGC),
550✔
1980
                      lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
1981
    do {
1,395✔
1982
      tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, *trp++);
1,395✔
1983
    } while (trp <= top);
1,395✔
1984
    tr = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
550✔
1985
    J->maxslot = (BCReg)(xbase - J->base);
550✔
1986
    if (xbase == base) return tr;  /* Return simple concatenation result. */
550✔
1987
    /* Pass partial result. */
1988
    topslot = J->maxslot--;
2✔
1989
    *xbase = tr;
2✔
1990
    top = xbase;
2✔
1991
    setstrV(J->L, &ix.keyv, &J2G(J)->strempty);  /* Simulate string result. */
2✔
1992
  } else {
1993
    J->maxslot = topslot-1;
11✔
1994
    copyTV(J->L, &ix.keyv, &J->L->base[topslot]);
11✔
1995
  }
1996
  copyTV(J->L, &ix.tabv, &J->L->base[topslot-1]);
13✔
1997
  ix.tab = top[-1];
13✔
1998
  ix.key = top[0];
13✔
1999
  memcpy(savetv, &J->L->base[topslot-1], sizeof(savetv));  /* Save slots. */
13✔
2000
  rcd.J = J;
13✔
2001
  rcd.ix = &ix;
13✔
2002
  errcode = lj_vm_cpcall(J->L, NULL, &rcd, rec_mm_concat_cp);
13✔
2003
  memcpy(&J->L->base[topslot-1], savetv, sizeof(savetv));  /* Restore slots. */
13✔
2004
  if (errcode) return (TRef)(-errcode);
13✔
2005
  return 0;  /* No result yet. */
2006
}
2007

2008
/* -- Record bytecode ops ------------------------------------------------- */
2009

2010
/* Prepare for comparison. */
2011
static void rec_comp_prep(jit_State *J)
823,097✔
2012
{
2013
  /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
2014
  if (J->cur.nsnap == 1 && J->cur.snap[0].ref == J->cur.nins)
823,097✔
2015
    emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
285✔
2016
  lj_snap_add(J);
823,097✔
2017
}
823,097✔
2018

2019
/* Fixup comparison. */
2020
static void rec_comp_fixup(jit_State *J, const BCIns *pc, int cond)
845,091✔
2021
{
2022
  BCIns jmpins = pc[1];
845,091✔
2023
  const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0);
845,091✔
2024
  SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
845,091✔
2025
  /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
2026
#if LJ_FR2
2027
  SnapEntry *flink = &J->cur.snapmap[snap->mapofs + snap->nent];
845,091✔
2028
  uint64_t pcbase;
845,091✔
2029
  memcpy(&pcbase, flink, sizeof(uint64_t));
845,091✔
2030
  pcbase = (pcbase & 0xff) | (u64ptr(npc) << 8);
845,091✔
2031
  memcpy(flink, &pcbase, sizeof(uint64_t));
845,091✔
2032
#else
2033
  J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc);
2034
#endif
2035
  J->needsnap = 1;
845,091✔
2036
  if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins);
845,091✔
2037
  lj_snap_shrink(J);  /* Shrink last snapshot if possible. */
845,091✔
2038
}
845,091✔
2039

2040
/* Record the next bytecode instruction (_before_ it's executed). */
2041
void lj_record_ins(jit_State *J)
8,400,612✔
2042
{
2043
  cTValue *lbase;
8,400,612✔
2044
  RecordIndex ix;
8,400,612✔
2045
  const BCIns *pc;
8,400,612✔
2046
  BCIns ins;
8,400,612✔
2047
  BCOp op;
8,400,612✔
2048
  TRef ra, rb, rc;
8,400,612✔
2049

2050
  /* Perform post-processing action before recording the next instruction. */
2051
  if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) {
8,400,612✔
2052
    switch (J->postproc) {
334,536✔
2053
    case LJ_POST_FIXCOMP:  /* Fixup comparison. */
22,098✔
2054
      pc = (const BCIns *)(uintptr_t)J2G(J)->tmptv.u64;
22,098✔
2055
      rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1)));
22,098✔
2056
      /* fallthrough */
2057
    case LJ_POST_FIXGUARD:  /* Fixup and emit pending guard. */
34,528✔
2058
    case LJ_POST_FIXGUARDSNAP:  /* Fixup and emit pending guard and snapshot. */
2059
      if (!tvistruecond(&J2G(J)->tmptv2)) {
34,528✔
2060
        J->fold.ins.o ^= 1;  /* Flip guard to opposite. */
12,423✔
2061
        if (J->postproc == LJ_POST_FIXGUARDSNAP) {
12,423✔
2062
          SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
1✔
2063
          J->cur.snapmap[snap->mapofs+snap->nent-1]--;  /* False -> true. */
1✔
2064
        }
2065
      }
2066
      lj_opt_fold(J);  /* Emit pending guard. */
34,528✔
2067
      /* fallthrough */
2068
    case LJ_POST_FIXBOOL:
34,542✔
2069
      if (!tvistruecond(&J2G(J)->tmptv2)) {
34,542✔
2070
        BCReg s;
12,429✔
2071
        TValue *tv = J->L->base;
12,429✔
2072
        for (s = 0; s < J->maxslot; s++)  /* Fixup stack slot (if any). */
62,281✔
2073
          if (J->base[s] == TREF_TRUE && tvisfalse(&tv[s])) {
49,860✔
2074
            J->base[s] = TREF_FALSE;
8✔
2075
            break;
8✔
2076
          }
2077
      }
2078
      break;
2079
    case LJ_POST_FIXCONST:
1✔
2080
      {
2081
        BCReg s;
1✔
2082
        TValue *tv = J->L->base;
1✔
2083
        for (s = 0; s < J->maxslot; s++)  /* Constify stack slots (if any). */
13✔
2084
          if (J->base[s] == TREF_NIL && !tvisnil(&tv[s]))
12✔
2085
            J->base[s] = lj_record_constify(J, &tv[s]);
1✔
2086
      }
2087
      break;
2088
    case LJ_POST_FFRETRY:  /* Suppress recording of retried fast function. */
299,993✔
2089
      if (bc_op(*J->pc) >= BC__MAX)
299,993✔
2090
        return;
23✔
2091
      break;
2092
    default: lj_assertJ(0, "bad post-processing mode"); break;
2093
    }
2094
    J->postproc = LJ_POST_NONE;
334,533✔
2095
  }
2096

2097
  /* Need snapshot before recording next bytecode (e.g. after a store). */
2098
  if (J->needsnap) {
8,400,609✔
2099
    J->needsnap = 0;
1,310,309✔
2100
    if (J->pt) lj_snap_purge(J);
1,310,309✔
2101
    lj_snap_add(J);
1,310,309✔
2102
    J->mergesnap = 1;
1,310,309✔
2103
  }
2104

2105
  /* Skip some bytecodes. */
2106
  if (LJ_UNLIKELY(J->bcskip > 0)) {
8,400,609✔
2107
    J->bcskip--;
20✔
2108
    return;
20✔
2109
  }
2110

2111
  /* Record only closed loops for root traces. */
2112
  pc = J->pc;
8,400,589✔
2113
  if (J->framedepth == 0 &&
8,400,589✔
2114
     (MSize)((char *)pc - (char *)J->bc_min) >= J->bc_extent)
2,630,460✔
2115
    lj_trace_err(J, LJ_TRERR_LLEAVE);
502✔
2116

2117
#ifdef LUA_USE_ASSERT
2118
  rec_check_slots(J);
2119
  rec_check_ir(J);
2120
#endif
2121

2122
#if LJ_HASPROFILE
2123
  rec_profile_ins(J, pc);
8,400,087✔
2124
#endif
2125

2126
  /* Keep a copy of the runtime values of var/num/str operands. */
2127
#define rav        (&ix.valv)
2128
#define rbv        (&ix.tabv)
2129
#define rcv        (&ix.keyv)
2130

2131
  lbase = J->L->base;
8,400,087✔
2132
  ins = *pc;
8,400,087✔
2133
  op = bc_op(ins);
8,400,087✔
2134
  ra = bc_a(ins);
8,400,087✔
2135
  ix.val = 0;
8,400,087✔
2136
  switch (bcmode_a(op)) {
8,400,087✔
2137
  case BCMvar:
1,213,096✔
2138
    copyTV(J->L, rav, &lbase[ra]); ix.val = ra = getslot(J, ra); break;
1,213,096✔
2139
  default: break;  /* Handled later. */
2140
  }
2141
  rb = bc_b(ins);
8,400,087✔
2142
  rc = bc_c(ins);
8,400,087✔
2143
  switch (bcmode_b(op)) {
8,400,087✔
2144
  case BCMnone: rb = 0; rc = bc_d(ins); break;  /* Upgrade rc to 'rd'. */
5,491,804✔
2145
  case BCMvar:
1,921,740✔
2146
    copyTV(J->L, rbv, &lbase[rb]); ix.tab = rb = getslot(J, rb); break;
1,921,740✔
2147
  default: break;  /* Handled later. */
2148
  }
2149
  switch (bcmode_c(op)) {
8,400,087✔
2150
  case BCMvar:
1,213,174✔
2151
    copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
1,213,174✔
2152
  case BCMpri: setpriV(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
639,550✔
2153
  case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
179,374✔
2154
    copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
179,374✔
2155
    lj_ir_knumint(J, numV(tv)); } break;
179,374✔
2156
  case BCMstr: { GCstr *s = gco2str(proto_kgc(J->pt, ~(ptrdiff_t)rc));
1,563,137✔
2157
    setstrV(J->L, rcv, s); ix.key = rc = lj_ir_kstr(J, s); } break;
1,563,137✔
2158
  default: break;  /* Handled later. */
2159
  }
2160

2161
  switch (op) {
8,400,087✔
2162

2163
  /* -- Comparison ops ---------------------------------------------------- */
2164

2165
  case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
278,679✔
2166
#if LJ_HASFFI
2167
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
278,679✔
2168
      rec_mm_comp_cdata(J, &ix, op, ((int)op & 2) ? MM_le : MM_lt);
22,079✔
2169
      break;
22,079✔
2170
    }
2171
#endif
2172
    /* Emit nothing for two numeric or string consts. */
2173
    if (!(tref_isk2(ra,rc) && tref_isnumber_str(ra) && tref_isnumber_str(rc))) {
256,600✔
2174
      IRType ta = tref_isinteger(ra) ? IRT_INT : tref_type(ra);
233,132✔
2175
      IRType tc = tref_isinteger(rc) ? IRT_INT : tref_type(rc);
233,132✔
2176
      int irop;
233,132✔
2177
      if (ta != tc) {
233,132✔
2178
        /* Widen mixed number/int comparisons to number/number comparison. */
2179
        if (ta == IRT_INT && tc == IRT_NUM) {
225,353✔
2180
          ra = emitir(IRTN(IR_CONV), ra, IRCONV_NUM_INT);
113,902✔
2181
          ta = IRT_NUM;
113,902✔
2182
        } else if (ta == IRT_NUM && tc == IRT_INT) {
111,451✔
2183
          rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
111,448✔
2184
        } else if (LJ_52) {
3✔
2185
          ta = IRT_NIL;  /* Force metamethod for different types. */
2186
        } else if (!((ta == IRT_FALSE || ta == IRT_TRUE) &&
3✔
2187
                     (tc == IRT_FALSE || tc == IRT_TRUE))) {
×
2188
          break;  /* Interpreter will throw for two different types. */
2189
        }
2190
      }
2191
      rec_comp_prep(J);
233,129✔
2192
      irop = (int)op - (int)BC_ISLT + (int)IR_LT;
233,129✔
2193
      if (ta == IRT_NUM) {
233,129✔
2194
        if ((irop & 1)) irop ^= 4;  /* ISGE/ISGT are unordered. */
232,991✔
2195
        if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
232,991✔
2196
          irop ^= 5;
224,406✔
2197
      } else if (ta == IRT_INT) {
138✔
2198
        if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
80✔
2199
          irop ^= 1;
23✔
2200
      } else if (ta == IRT_STR) {
58✔
2201
        if (!lj_ir_strcmp(strV(rav), strV(rcv), (IROp)irop)) irop ^= 1;
9✔
2202
        ra = lj_ir_call(J, IRCALL_lj_str_cmp, ra, rc);
9✔
2203
        rc = lj_ir_kint(J, 0);
9✔
2204
        ta = IRT_INT;
9✔
2205
      } else {
2206
        rec_mm_comp(J, &ix, (int)op);
49✔
2207
        break;
49✔
2208
      }
2209
      emitir(IRTG(irop, ta), ra, rc);
233,080✔
2210
      rec_comp_fixup(J, J->pc, ((int)op ^ irop) & 1);
233,080✔
2211
    }
2212
    break;
2213

2214
  case BC_ISEQV: case BC_ISNEV:
616,992✔
2215
  case BC_ISEQS: case BC_ISNES:
2216
  case BC_ISEQN: case BC_ISNEN:
2217
  case BC_ISEQP: case BC_ISNEP:
2218
#if LJ_HASFFI
2219
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
616,992✔
2220
      rec_mm_comp_cdata(J, &ix, op, MM_eq);
12,444✔
2221
      break;
12,444✔
2222
    }
2223
#endif
2224
    /* Emit nothing for two non-table, non-udata consts. */
2225
    if (!(tref_isk2(ra, rc) && !(tref_istab(ra) || tref_isudata(ra)))) {
604,548✔
2226
      int diff;
589,968✔
2227
      rec_comp_prep(J);
589,968✔
2228
      diff = lj_record_objcmp(J, ra, rc, rav, rcv);
589,968✔
2229
      if (diff == 2 || !(tref_istab(ra) || tref_isudata(ra)))
589,968✔
2230
        rec_comp_fixup(J, J->pc, ((int)op & 1) == !diff);
589,913✔
2231
      else if (diff == 1)  /* Only check __eq if different, but same type. */
55✔
2232
        rec_mm_equal(J, &ix, (int)op);
10✔
2233
    }
2234
    break;
2235

2236
  /* -- Unary test and copy ops ------------------------------------------- */
2237

2238
  case BC_ISTC: case BC_ISFC:
283✔
2239
    if ((op & 1) == tref_istruecond(rc))
283✔
2240
      rc = 0;  /* Don't store if condition is not true. */
257✔
2241
    /* fallthrough */
2242
  case BC_IST: case BC_ISF:  /* Type specialization suffices. */
2243
    if (bc_a(pc[1]) < J->maxslot)
60,188✔
2244
      J->maxslot = bc_a(pc[1]);  /* Shrink used slots. */
34,379✔
2245
    break;
2246

2247
  case BC_ISTYPE: case BC_ISNUM:
2248
    /* These coercions need to correspond with lj_meta_istype(). */
2249
    if (LJ_DUALNUM && rc == ~LJ_TNUMX+1)
11✔
2250
      ra = lj_opt_narrow_toint(J, ra);
2251
    else if (rc == ~LJ_TNUMX+2)
11✔
2252
      ra = lj_ir_tonum(J, ra);
2✔
2253
    else if (rc == ~LJ_TSTR+1)
9✔
2254
      ra = lj_ir_tostr(J, ra);
3✔
2255
    /* else: type specialization suffices. */
2256
    J->base[bc_a(ins)] = ra;
11✔
2257
    break;
11✔
2258

2259
  /* -- Unary ops --------------------------------------------------------- */
2260

2261
  case BC_NOT:
7✔
2262
    /* Type specialization already forces const result. */
2263
    rc = tref_istruecond(rc) ? TREF_FALSE : TREF_TRUE;
7✔
2264
    break;
2265

2266
  case BC_LEN:
59✔
2267
    if (tref_isstr(rc))
59✔
2268
      rc = emitir(IRTI(IR_FLOAD), rc, IRFL_STR_LEN);
5✔
2269
    else if (!LJ_52 && tref_istab(rc))
54✔
2270
      rc = lj_ir_call(J, IRCALL_lj_tab_len, rc);
52✔
2271
    else
2272
      rc = rec_mm_len(J, rc, rcv);
2✔
2273
    break;
2274

2275
  /* -- Arithmetic ops ---------------------------------------------------- */
2276

2277
  case BC_UNM:
25✔
2278
    if (tref_isnumber_str(rc)) {
25✔
2279
      rc = lj_opt_narrow_unm(J, rc, rcv);
22✔
2280
    } else {
2281
      ix.tab = rc;
3✔
2282
      copyTV(J->L, &ix.tabv, rcv);
3✔
2283
      rc = rec_mm_arith(J, &ix, MM_unm);
3✔
2284
    }
2285
    break;
2286

2287
  case BC_ADDNV: case BC_SUBNV: case BC_MULNV: case BC_DIVNV: case BC_MODNV:
119,933✔
2288
    /* Swap rb/rc and rbv/rcv. rav is temp. */
2289
    ix.tab = rc; ix.key = rc = rb; rb = ix.tab;
119,933✔
2290
    copyTV(J->L, rav, rbv);
119,933✔
2291
    copyTV(J->L, rbv, rcv);
119,933✔
2292
    copyTV(J->L, rcv, rav);
119,933✔
2293
    if (op == BC_MODNV)
119,933✔
2294
      goto recmod;
1✔
2295
    /* fallthrough */
2296
  case BC_ADDVN: case BC_SUBVN: case BC_MULVN: case BC_DIVVN:
2297
  case BC_ADDVV: case BC_SUBVV: case BC_MULVV: case BC_DIVVV: {
2298
    MMS mm = bcmode_mm(op);
348,440✔
2299
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
348,440✔
2300
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv,
307,885✔
2301
                               (int)mm - (int)MM_add + (int)IR_ADD);
307,885✔
2302
    else
2303
      rc = rec_mm_arith(J, &ix, mm);
40,555✔
2304
    break;
2305
    }
2306

2307
  case BC_MODVN: case BC_MODVV:
2308
  recmod:
134✔
2309
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
134✔
2310
      rc = lj_opt_narrow_mod(J, rb, rc, rbv, rcv);
129✔
2311
    else
2312
      rc = rec_mm_arith(J, &ix, MM_mod);
5✔
2313
    break;
2314

2315
  case BC_POW:
9,329✔
2316
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
9,329✔
2317
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv, IR_POW);
9,324✔
2318
    else
2319
      rc = rec_mm_arith(J, &ix, MM_pow);
5✔
2320
    break;
2321

2322
  /* -- Miscellaneous ops ------------------------------------------------- */
2323

2324
  case BC_CAT:
556✔
2325
    rc = rec_cat(J, rb, rc);
556✔
2326
    if (rc >= 0xffffff00)
556✔
2327
      lj_err_throw(J->L, -(int32_t)rc);  /* Propagate errors. */
×
2328
    break;
2329

2330
  /* -- Constant and move ops --------------------------------------------- */
2331

2332
  case BC_MOV:
595,909✔
2333
    /* Clear gap of method call to avoid resurrecting previous refs. */
2334
    if (ra > J->maxslot) {
595,909✔
2335
#if LJ_FR2
2336
      memset(J->base + J->maxslot, 0, (ra - J->maxslot) * sizeof(TRef));
453,515✔
2337
#else
2338
      J->base[ra-1] = 0;
2339
#endif
2340
    }
2341
    break;
2342
  case BC_KSTR: case BC_KNUM: case BC_KPRI:
2343
    break;
2344
  case BC_KSHORT:
300,946✔
2345
    rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
300,946✔
2346
    break;
300,946✔
2347
  case BC_KNIL:
15✔
2348
    if (LJ_FR2 && ra > J->maxslot)
15✔
2349
      J->base[ra-1] = 0;
1✔
2350
    while (ra <= rc)
825✔
2351
      J->base[ra++] = TREF_NIL;
810✔
2352
    if (rc >= J->maxslot) J->maxslot = rc+1;
15✔
2353
    break;
2354
#if LJ_HASFFI
2355
  case BC_KCDATA:
60✔
2356
    rc = lj_ir_kgc(J, proto_kgc(J->pt, ~(ptrdiff_t)rc), IRT_CDATA);
60✔
2357
    break;
60✔
2358
#endif
2359

2360
  /* -- Upvalue and function ops ------------------------------------------ */
2361

2362
  case BC_UGET:
1,139,775✔
2363
    rc = rec_upvalue(J, rc, 0);
1,139,775✔
2364
    break;
1,139,775✔
2365
  case BC_USETV: case BC_USETS: case BC_USETN: case BC_USETP:
201✔
2366
    rec_upvalue(J, ra, rc);
201✔
2367
    break;
201✔
2368

2369
  /* -- Table ops --------------------------------------------------------- */
2370

2371
  case BC_GGET: case BC_GSET:
5,286✔
2372
    settabV(J->L, &ix.tabv, tabref(J->fn->l.env));
5,286✔
2373
    ix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), getcurrf(J), IRFL_FUNC_ENV);
5,286✔
2374
    ix.idxchain = LJ_MAX_IDXCHAIN;
5,286✔
2375
    rc = lj_record_idx(J, &ix);
5,286✔
2376
    break;
5,286✔
2377

2378
  case BC_TGETB: case BC_TSETB:
774✔
2379
    setintV(&ix.keyv, (int32_t)rc);
774✔
2380
    ix.key = lj_ir_kint(J, (int32_t)rc);
774✔
2381
    /* fallthrough */
2382
  case BC_TGETV: case BC_TGETS: case BC_TSETV: case BC_TSETS:
1,563,811✔
2383
    ix.idxchain = LJ_MAX_IDXCHAIN;
1,563,811✔
2384
    rc = lj_record_idx(J, &ix);
1,563,811✔
2385
    break;
1,563,811✔
2386
  case BC_TGETR: case BC_TSETR:
26✔
2387
    ix.idxchain = 0;
26✔
2388
    rc = lj_record_idx(J, &ix);
26✔
2389
    break;
26✔
2390

2391
  case BC_TSETM:
5✔
2392
    rec_tsetm(J, ra, (BCReg)(J->L->top - J->L->base), (int32_t)rcv->u32.lo);
5✔
2393
    J->maxslot = ra;  /* The table slot at ra-1 is the highest used slot. */
5✔
2394
    break;
5✔
2395

2396
  case BC_TNEW:
2397
    rc = rec_tnew(J, rc);
551✔
2398
    break;
551✔
2399
  case BC_TDUP:
546✔
2400
    rc = emitir(IRTG(IR_TDUP, IRT_TAB),
546✔
2401
                lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
2402
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2403
    J->rbchash[(rc & (RBCHASH_SLOTS-1))].ref = tref_ref(rc);
2404
    setmref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pc, pc);
2405
    setgcref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
2406
#endif
2407
    break;
546✔
2408

2409
  /* -- Calls and vararg handling ----------------------------------------- */
2410

2411
  case BC_ITERC:
117✔
2412
    J->base[ra] = getslot(J, ra-3);
117✔
2413
    J->base[ra+1+LJ_FR2] = getslot(J, ra-2);
117✔
2414
    J->base[ra+2+LJ_FR2] = getslot(J, ra-1);
117✔
2415
    { /* Do the actual copy now because lj_record_call needs the values. */
2416
      TValue *b = &J->L->base[ra];
117✔
2417
      copyTV(J->L, b, b-3);
117✔
2418
      copyTV(J->L, b+1+LJ_FR2, b-2);
117✔
2419
      copyTV(J->L, b+2+LJ_FR2, b-1);
117✔
2420
    }
2421
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
117✔
2422
    break;
117✔
2423

2424
  /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
2425
  case BC_CALLM:
129,202✔
2426
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
129,202✔
2427
    /* fallthrough */
2428
  case BC_CALL:
985,823✔
2429
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
985,823✔
2430
    break;
985,823✔
2431

2432
  case BC_CALLMT:
14✔
2433
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
14✔
2434
    /* fallthrough */
2435
  case BC_CALLT:
113,963✔
2436
    lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
113,963✔
2437
    break;
113,963✔
2438

2439
  case BC_VARG:
47✔
2440
    rec_varg(J, ra, (ptrdiff_t)rb-1);
47✔
2441
    break;
47✔
2442

2443
  /* -- Returns ----------------------------------------------------------- */
2444

2445
  case BC_RETM:
29✔
2446
    /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
2447
    rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
29✔
2448
    /* fallthrough */
2449
  case BC_RET: case BC_RET0: case BC_RET1:
874,968✔
2450
#if LJ_HASPROFILE
2451
    rec_profile_ret(J);
874,968✔
2452
#endif
2453
    lj_record_ret(J, ra, (ptrdiff_t)rc-1);
874,968✔
2454
    break;
874,968✔
2455

2456
  /* -- Loops and branches ------------------------------------------------ */
2457

2458
  case BC_FORI:
145✔
2459
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)
145✔
2460
      J->loopref = J->cur.nins;
145✔
2461
    break;
2462
  case BC_JFORI:
104✔
2463
    lj_assertJ(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL,
104✔
2464
               "JFORI does not point to JFORL");
2465
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)  /* Link to existing loop. */
104✔
2466
      lj_record_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
101✔
2467
    /* Continue tracing if the loop is not entered. */
2468
    break;
2469

2470
  case BC_FORL:
2,573✔
2471
    rec_loop_interp(J, pc, rec_for(J, pc+((ptrdiff_t)rc-BCBIAS_J), 1));
2,573✔
2472
    break;
2,573✔
2473
  case BC_ITERL:
50✔
2474
    rec_loop_interp(J, pc, rec_iterl(J, *pc));
50✔
2475
    break;
50✔
2476
  case BC_LOOP:
21,486✔
2477
    rec_loop_interp(J, pc, rec_loop(J, ra, 1));
21,486✔
2478
    break;
21,486✔
2479

2480
  case BC_JFORL:
348✔
2481
    rec_loop_jit(J, rc, rec_for(J, pc+bc_j(traceref(J, rc)->startins), 1));
348✔
2482
    break;
348✔
2483
  case BC_JITERL:
65✔
2484
    rec_loop_jit(J, rc, rec_iterl(J, traceref(J, rc)->startins));
65✔
2485
    break;
65✔
2486
  case BC_JLOOP:
11,807✔
2487
    rec_loop_jit(J, rc, rec_loop(J, ra,
23,614✔
2488
                                 !bc_isret(bc_op(traceref(J, rc)->startins))));
11,807✔
2489
    break;
11,807✔
2490

2491
  case BC_IFORL:
2✔
2492
  case BC_IITERL:
2493
  case BC_ILOOP:
2494
  case BC_IFUNCF:
2495
  case BC_IFUNCV:
2496
    lj_trace_err(J, LJ_TRERR_BLACKL);
2✔
2497
    break;
141,471✔
2498

2499
  case BC_JMP:
141,471✔
2500
    if (ra < J->maxslot)
141,471✔
2501
      J->maxslot = ra;  /* Shrink used slots. */
128,362✔
2502
    break;
2503

2504
  /* -- Function headers -------------------------------------------------- */
2505

2506
  case BC_FUNCF:
2507
    rec_func_lua(J);
139,169✔
2508
    break;
2509
  case BC_JFUNCF:
734,326✔
2510
    rec_func_jit(J, rc);
734,326✔
2511
    break;
734,326✔
2512

2513
  case BC_FUNCV:
109✔
2514
    rec_func_vararg(J);
109✔
2515
    rec_func_lua(J);
109✔
2516
    break;
2517
  case BC_JFUNCV:
2518
    /* Cannot happen. No hotcall counting for varag funcs. */
2519
    lj_assertJ(0, "unsupported vararg hotcall");
2520
    break;
2521

2522
  case BC_FUNCC:
145,814✔
2523
  case BC_FUNCCW:
2524
    lj_ffrecord_func(J);
145,814✔
2525
    break;
145,814✔
2526

2527
  default:
189,164✔
2528
    if (op >= BC__MAX) {
189,164✔
2529
      lj_ffrecord_func(J);
189,164✔
2530
      break;
189,164✔
2531
    }
2532
    /* fallthrough */
2533
  case BC_ITERN:
2534
  case BC_ISNEXT:
2535
  case BC_UCLO:
2536
  case BC_FNEW:
2537
    setintV(&J->errinfo, (int32_t)op);
67✔
2538
    lj_trace_err_info(J, LJ_TRERR_NYIBC);
67✔
2539
    break;
8,397,772✔
2540
  }
2541

2542
  /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
2543
  if (bcmode_a(op) == BCMdst && rc) {
8,397,772✔
2544
    J->base[ra] = rc;
3,689,866✔
2545
    if (ra >= J->maxslot) {
3,689,866✔
2546
#if LJ_FR2
2547
      if (ra > J->maxslot) J->base[ra-1] = 0;
3,035,136✔
2548
#endif
2549
      J->maxslot = ra+1;
3,035,136✔
2550
    }
2551
  }
2552

2553
#undef rav
2554
#undef rbv
2555
#undef rcv
2556

2557
  /* Limit the number of recorded IR instructions and constants. */
2558
  if (J->cur.nins > REF_FIRST+(IRRef)J->param[JIT_P_maxrecord] ||
8,397,772✔
2559
      J->cur.nk < REF_BIAS-(IRRef)J->param[JIT_P_maxirconst])
8,397,772✔
2560
    lj_trace_err(J, LJ_TRERR_TRACEOV);
2✔
2561
}
2562

2563
/* -- Recording setup ----------------------------------------------------- */
2564

2565
/* Setup recording for a root trace started by a hot loop. */
2566
static const BCIns *rec_setup_root(jit_State *J)
5,966✔
2567
{
2568
  /* Determine the next PC and the bytecode range for the loop. */
2569
  const BCIns *pcj, *pc = J->pc;
5,966✔
2570
  BCIns ins = *pc;
5,966✔
2571
  BCReg ra = bc_a(ins);
5,966✔
2572
  switch (bc_op(ins)) {
5,966✔
2573
  case BC_FORL:
2,502✔
2574
    J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
2,502✔
2575
    pc += 1+bc_j(ins);
2,502✔
2576
    J->bc_min = pc;
2,502✔
2577
    break;
2,502✔
2578
  case BC_ITERL:
45✔
2579
    lj_assertJ(bc_op(pc[-1]) == BC_ITERC, "no ITERC before ITERL");
45✔
2580
    J->maxslot = ra + bc_b(pc[-1]) - 1;
45✔
2581
    J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
45✔
2582
    pc += 1+bc_j(ins);
45✔
2583
    lj_assertJ(bc_op(pc[-1]) == BC_JMP, "ITERL does not point to JMP+1");
45✔
2584
    J->bc_min = pc;
45✔
2585
    break;
45✔
2586
  case BC_LOOP:
1,247✔
2587
    /* Only check BC range for real loops, but not for "repeat until true". */
2588
    pcj = pc + bc_j(ins);
1,247✔
2589
    ins = *pcj;
1,247✔
2590
    if (bc_op(ins) == BC_JMP && bc_j(ins) < 0) {
1,247✔
2591
      J->bc_min = pcj+1 + bc_j(ins);
1,244✔
2592
      J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
1,244✔
2593
    }
2594
    J->maxslot = ra;
1,247✔
2595
    pc++;
1,247✔
2596
    break;
1,247✔
2597
  case BC_RET:
1✔
2598
  case BC_RET0:
2599
  case BC_RET1:
2600
    /* No bytecode range check for down-recursive root traces. */
2601
    J->maxslot = ra + bc_d(ins) - 1;
1✔
2602
    break;
1✔
2603
  case BC_FUNCF:
2,080✔
2604
    /* No bytecode range check for root traces started by a hot call. */
2605
    J->maxslot = J->pt->numparams;
2,080✔
2606
    pc++;
2,080✔
2607
    break;
2,080✔
2608
  case BC_CALLM:
91✔
2609
  case BC_CALL:
2610
  case BC_ITERC:
2611
    /* No bytecode range check for stitched traces. */
2612
    pc++;
91✔
2613
    break;
91✔
2614
  default:
2615
    lj_assertJ(0, "bad root trace start bytecode %d", bc_op(ins));
2616
    break;
2617
  }
2618
  return pc;
5,966✔
2619
}
2620

2621
/* Setup for recording a new trace. */
2622
void lj_record_setup(jit_State *J)
22,862✔
2623
{
2624
  uint32_t i;
22,862✔
2625

2626
  /* Initialize state related to current trace. */
2627
  memset(J->slot, 0, sizeof(J->slot));
22,862✔
2628
  memset(J->chain, 0, sizeof(J->chain));
22,862✔
2629
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2630
  memset(J->rbchash, 0, sizeof(J->rbchash));
2631
#endif
2632
  memset(J->bpropcache, 0, sizeof(J->bpropcache));
22,862✔
2633
  J->scev.idx = REF_NIL;
22,862✔
2634
  setmref(J->scev.pc, NULL);
22,862✔
2635

2636
  J->baseslot = 1+LJ_FR2;  /* Invoking function is at base[-1-LJ_FR2]. */
22,862✔
2637
  J->base = J->slot + J->baseslot;
22,862✔
2638
  J->maxslot = 0;
22,862✔
2639
  J->framedepth = 0;
22,862✔
2640
  J->retdepth = 0;
22,862✔
2641

2642
  J->instunroll = J->param[JIT_P_instunroll];
22,862✔
2643
  J->loopunroll = J->param[JIT_P_loopunroll];
22,862✔
2644
  J->tailcalled = 0;
22,862✔
2645
  J->loopref = 0;
22,862✔
2646

2647
  J->bc_min = NULL;  /* Means no limit. */
22,862✔
2648
  J->bc_extent = ~(MSize)0;
22,862✔
2649

2650
  /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2651
  emitir_raw(IRT(IR_BASE, IRT_PGC), J->parent, J->exitno);
22,862✔
2652
  for (i = 0; i <= 2; i++) {
114,310✔
2653
    IRIns *ir = IR(REF_NIL-i);
68,586✔
2654
    ir->i = 0;
68,586✔
2655
    ir->t.irt = (uint8_t)(IRT_NIL+i);
68,586✔
2656
    ir->o = IR_KPRI;
68,586✔
2657
    ir->prev = 0;
68,586✔
2658
  }
2659
  J->cur.nk = REF_TRUE;
22,862✔
2660

2661
  J->startpc = J->pc;
22,862✔
2662
  setmref(J->cur.startpc, J->pc);
22,862✔
2663
  if (J->parent) {  /* Side trace. */
22,862✔
2664
    GCtrace *T = traceref(J, J->parent);
16,896✔
2665
    TraceNo root = T->root ? T->root : J->parent;
16,896✔
2666
    J->cur.root = (uint16_t)root;
16,896✔
2667
    J->cur.startins = BCINS_AD(BC_JMP, 0, 0);
16,896✔
2668
    /* Check whether we could at least potentially form an extra loop. */
2669
    if (J->exitno == 0 && T->snap[0].nent == 0) {
16,896✔
2670
      /* We can narrow a FORL for some side traces, too. */
2671
      if (J->pc > proto_bc(J->pt) && bc_op(J->pc[-1]) == BC_JFORI &&
2,319✔
2672
          bc_d(J->pc[bc_j(J->pc[-1])-1]) == root) {
190✔
2673
        lj_snap_add(J);
190✔
2674
        rec_for_loop(J, J->pc-1, &J->scev, 1);
190✔
2675
        goto sidecheck;
190✔
2676
      }
2677
    } else {
2678
      J->startpc = NULL;  /* Prevent forming an extra loop. */
14,577✔
2679
    }
2680
    lj_snap_replay(J, T);
16,706✔
2681
  sidecheck:
16,896✔
2682
    if (traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] ||
16,896✔
2683
        T->snap[J->exitno].count >= J->param[JIT_P_hotexit] +
16,896✔
2684
                                    J->param[JIT_P_tryside]) {
16,896✔
2685
      lj_record_stop(J, LJ_TRLINK_INTERP, 0);
393✔
2686
    }
2687
  } else {  /* Root trace. */
2688
    J->cur.root = 0;
5,966✔
2689
    J->cur.startins = *J->pc;
5,966✔
2690
    J->pc = rec_setup_root(J);
5,966✔
2691
    /* Note: the loop instruction itself is recorded at the end and not
2692
    ** at the start! So snapshot #0 needs to point to the *next* instruction.
2693
    */
2694
    lj_snap_add(J);
5,966✔
2695
    if (bc_op(J->cur.startins) == BC_FORL)
5,966✔
2696
      rec_for_loop(J, J->pc-1, &J->scev, 1);
2,502✔
2697
    else if (bc_op(J->cur.startins) == BC_ITERC)
3,464✔
2698
      J->startpc = NULL;
3✔
2699
    if (1 + J->pt->framesize >= LJ_MAX_JSLOTS)
5,966✔
2700
      lj_trace_err(J, LJ_TRERR_STACKOV);
1✔
2701
  }
2702
#if LJ_HASPROFILE
2703
  J->prev_pt = NULL;
22,861✔
2704
  J->prev_line = -1;
22,861✔
2705
#endif
2706
#ifdef LUAJIT_ENABLE_CHECKHOOK
2707
  /* Regularly check for instruction/line hooks from compiled code and
2708
  ** exit to the interpreter if the hooks are set.
2709
  **
2710
  ** This is a compile-time option and disabled by default, since the
2711
  ** hook checks may be quite expensive in tight loops.
2712
  **
2713
  ** Note this is only useful if hooks are *not* set most of the time.
2714
  ** Use this only if you want to *asynchronously* interrupt the execution.
2715
  **
2716
  ** You can set the instruction hook via lua_sethook() with a count of 1
2717
  ** from a signal handler or another native thread. Please have a look
2718
  ** at the first few functions in luajit.c for an example (Ctrl-C handler).
2719
  */
2720
  {
2721
    TRef tr = emitir(IRT(IR_XLOAD, IRT_U8),
2722
                     lj_ir_kptr(J, &J2G(J)->hookmask), IRXLOAD_VOLATILE);
2723
    tr = emitir(IRTI(IR_BAND), tr, lj_ir_kint(J, (LUA_MASKLINE|LUA_MASKCOUNT)));
2724
    emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, 0));
2725
  }
2726
#endif
2727
}
22,861✔
2728

2729
#undef IR
2730
#undef emitir_raw
2731
#undef emitir
2732

2733
#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

© 2025 Coveralls, Inc