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

tarantool / luajit / 15994754186

01 Jul 2025 08:44AM UTC coverage: 93.064% (+0.04%) from 93.023%
15994754186

push

github

Buristan
ARM64: Fix LDP/STP fusing for unaligned accesses.

Thanks to Peter Cawley.

(cherry picked from commit 0fa2f1cbc)

The arm64 emitting of load/store operation works incorrectly in the
case when at least one offset of load/store to be fused into ldp/stp is
misaligned. In this case this misaligning is ignored, and instructions
are fused, which leads to loading/storing from/to at least one incorrect
address.

For example, the following instructions:
| stur  w0, [x1, #17]
| stur  w0, [x1, #21]

May be fused to the following:
| stp   w0, w0, [x1, #16]

This patch prevents fusion in this case by testing the alignment with
the help of bitwise ROR by the alignment value. In case of misaligned
offset, the value overflows the 7-bit length mask in the check.

The negative immediate (7-bit width including sign bit) is limited by
the corresponding addition of `64 << sc` (it is harmless in the case of
positive values).

Sergey Kaplun:
* added the description and the test for the problem

Part of tarantool/tarantool#11278

Reviewed-by: Sergey Bronnikov <sergeyb@tarantool.org>
Signed-off-by: Sergey Kaplun <skaplun@tarantool.org>
(cherry picked from commit 4fd46fab4)

5712 of 6046 branches covered (94.48%)

Branch coverage included in aggregate %.

21792 of 23508 relevant lines covered (92.7%)

3836149.2 hits per line

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

96.64
/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)
111,357✔
188
{
189
  /* Caller may set IRT_GUARD in t. */
190
  TRef ref = emitir_raw(IRT(IR_SLOAD, t), (int32_t)J->baseslot+slot, mode);
222,714✔
191
  J->base[slot] = ref;
111,357✔
192
  return ref;
111,357✔
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)
239,875✔
197
{
198
  IRType t = itype2irt(&J->L->base[slot]);
239,875✔
199
  TRef ref = emitir_raw(IRTG(IR_SLOAD, t), (int32_t)J->baseslot+slot,
239,875✔
200
                        IRSLOAD_TYPECHECK);
201
  if (irtype_ispri(t)) ref = TREF_PRI(t);  /* Canonicalize primitive refs. */
239,875✔
202
  J->base[slot] = ref;
239,875✔
203
  return ref;
239,875✔
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)
978,963✔
211
{
212
  if (J->base[-1-LJ_FR2])
978,963✔
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");
106,290✔
216
  return sloadt(J, -1-LJ_FR2, IRT_FUNC, IRSLOAD_READONLY);
106,290✔
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)
495,525✔
226
{
227
  int diff = !lj_obj_equal(av, bv);
495,525✔
228
  if (!tref_isk2(a, b)) {  /* Shortcut, also handles primitives. */
495,525✔
229
    IRType ta = tref_isinteger(a) ? IRT_INT : tref_type(a);
495,524✔
230
    IRType tb = tref_isinteger(b) ? IRT_INT : tref_type(b);
495,524✔
231
    if (ta != tb) {
495,524✔
232
      /* Widen mixed number/int comparisons to number/number comparison. */
233
      if (ta == IRT_INT && tb == IRT_NUM) {
464,387✔
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) {
464,385✔
237
        b = emitir(IRTN(IR_CONV), b, IRCONV_NUM_INT);
192✔
238
      } else {
239
        return 2;  /* Two different types are never equal. */
240
      }
241
    }
242
    emitir(IRTG(diff ? IR_NE : IR_EQ, ta), a, b);
43,670✔
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)
907,821✔
249
{
250
  if (tvisgcv(o))
907,821✔
251
    return lj_ir_kgc(J, gcV(o), itype2irt(o));
836,263✔
252
  else if (tvisint(o))
71,558✔
253
    return lj_ir_kint(J, intV(o));
254
  else if (tvisnum(o))
71,558✔
255
    return lj_ir_knumint(J, numV(o));
71,558✔
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)
14,767✔
273
{
274
  BCReg s;
14,767✔
275
  if (LJ_DUALNUM) return;
14,767✔
276
  for (s = J->baseslot+J->maxslot-1; s >= 1; s--) {
238,765✔
277
    TRef tr = J->slot[s];
223,999✔
278
    if (tref_isinteger(tr)) {
223,999✔
279
      IRIns *ir = IR(tref_ref(tr));
28,004✔
280
      if (!(ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_READONLY)))
28,004✔
281
        J->slot[s] = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
27,925✔
282
    }
283
  }
284
}
285

286
/* Stop recording. */
287
void lj_record_stop(jit_State *J, TraceLink linktype, TraceNo lnk)
18,492✔
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);
18,492✔
294
  J->cur.linktype = (uint8_t)linktype;
18,492✔
295
  J->cur.link = (uint16_t)lnk;
18,492✔
296
  /* Looping back at the same stack level? */
297
  if (lnk == J->cur.traceno && J->framedepth + J->retdepth == 0) {
18,492✔
298
    if ((J->flags & JIT_F_OPT_LOOP))  /* Shall we try to create a loop? */
4,440✔
299
      goto nocanon;  /* Do not canonicalize or we lose the narrowing. */
3,725✔
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);
14,767✔
304
nocanon:
18,491✔
305
  /* Note: all loop ops must set J->pc to the following instruction! */
306
  lj_snap_add(J);  /* Add loop snapshot. */
18,491✔
307
  J->needsnap = 0;
18,489✔
308
  J->mergesnap = 1;  /* In case recording continues. */
18,489✔
309
}
18,489✔
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)
15,323✔
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);
15,323✔
320
  for (pc = endpc-1; pc > startpc; pc--) {
31,381✔
321
    BCIns ins = *pc;
31,381✔
322
    BCOp op = bc_op(ins);
31,381✔
323
    /* First try to find the last instruction that stores to this slot. */
324
    if (bcmode_a(op) == BCMbase && bc_a(ins) <= slot) {
31,381✔
325
      return 0;  /* Multiple results, e.g. from a CALL or KNIL. */
326
    } else if (bcmode_a(op) == BCMdst && bc_a(ins) == slot) {
31,363✔
327
      if (op == BC_KSHORT || op == BC_KNUM) {  /* Found const. initializer. */
15,305✔
328
        /* Now try to verify there's no forward jump across it. */
329
        const BCIns *kpc = pc;
516,838✔
330
        for (; pc > startpc; pc--)
516,838✔
331
          if (bc_op(*pc) == BC_JMP) {
501,906✔
332
            const BCIns *target = pc+bc_j(*pc)+1;
44,020✔
333
            if (target > kpc && target <= endpc)
44,020✔
334
              return 0;  /* Conditional assignment. */
335
          }
336
        if (op == BC_KSHORT) {
14,932✔
337
          int32_t k = (int32_t)(int16_t)bc_d(ins);
14,825✔
338
          return t == IRT_INT ? lj_ir_kint(J, k) : lj_ir_knum(J, (lua_Number)k);
14,825✔
339
        } else {
340
          cTValue *tv = proto_knumtv(J->pt, bc_d(ins));
107✔
341
          if (t == IRT_INT) {
107✔
342
            int32_t k = numberVint(tv);
82✔
343
            if (tvisint(tv) || numV(tv) == (lua_Number)k)  /* -0 is ok here. */
82✔
344
              return lj_ir_kint(J, k);
78✔
345
            return 0;  /* Type mismatch. */
346
          } else {
347
            return lj_ir_knum(J, numberVnum(tv));
25✔
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)
5,067✔
359
{
360
  int conv = (tvisint(&J->L->base[slot]) != (t==IRT_INT)) ? IRSLOAD_CONVERT : 0;
5,067✔
361
  return sloadt(J, (int32_t)slot,
15,201✔
362
                t + (((mode & IRSLOAD_TYPECHECK) ||
5,067✔
363
                      (conv && t == IRT_INT && !(mode >> 16))) ?
5,067✔
364
                     IRT_GUARD : 0),
5,067✔
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,
11,126✔
370
                     IRType t, int mode)
371
{
372
  TRef tr = J->base[slot];
11,126✔
373
  if (!tr) {
11,126✔
374
    tr = find_kinit(J, fori, slot, t);
9,760✔
375
    if (!tr)
9,760✔
376
      tr = fori_load(J, slot, t, mode);
292✔
377
  }
378
  return tr;
11,126✔
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)
11,498✔
385
{
386
  return (tvisint(o) ? intV(o) : (int32_t)o->u32.hi) >= 0;
11,498✔
387
}
388

389
/* Simulate the runtime behavior of the FOR loop iterator. */
390
static LoopEvent rec_for_iter(IROp *op, cTValue *o, int isforl)
5,581✔
391
{
392
  lua_Number stopv = numberVnum(&o[FORL_STOP]);
5,581✔
393
  lua_Number idxv = numberVnum(&o[FORL_IDX]);
5,581✔
394
  lua_Number stepv = numberVnum(&o[FORL_STEP]);
5,581✔
395
  if (isforl)
5,581✔
396
    idxv += stepv;
5,227✔
397
  if (rec_for_direction(&o[FORL_STEP])) {
5,581✔
398
    if (idxv <= stopv) {
5,498✔
399
      *op = IR_LE;
5,332✔
400
      return idxv + 2*stepv > stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
5,332✔
401
    }
402
    *op = IR_GT; return LOOPEV_LEAVE;
166✔
403
  } else {
404
    if (stopv <= idxv) {
83✔
405
      *op = IR_GE;
82✔
406
      return idxv + 2*stepv < stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
82✔
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,
5,917✔
414
                          TRef stop, TRef step, int init)
415
{
416
  if (!tref_isk(step)) {
5,917✔
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);
202✔
419
    emitir(IRTG(dir ? IR_GE : IR_LT, t), step, zero);
203✔
420
    /* Add hoistable overflow checks for a narrowed FORL index. */
421
    if (init && t == IRT_INT) {
202✔
422
      if (tref_isk(stop)) {
9✔
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);
7✔
435
        emitir(IRTI(IR_USE), tr, 0);  /* ADDOV is weak. Avoid dead result. */
7✔
436
      }
437
    }
438
  } else if (init && t == IRT_INT && !tref_isk(stop)) {
5,715✔
439
    /* Constant step: optimize overflow check to a range check for stop. */
440
    int32_t k = IR(tref_ref(step))->i;
262✔
441
    k = (int32_t)(dir ? 0x7fffffff : 0x80000000) - k;
262✔
442
    emitir(IRTGI(dir ? IR_LE : IR_GE), stop, lj_ir_kint(J, k));
294✔
443
  }
444
}
5,917✔
445

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

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

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

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

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

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

573
/* Record LOOP/JLOOP. Now, that was easy. */
574
static LoopEvent rec_loop(jit_State *J, BCReg ra, int skip)
29,595✔
575
{
576
  if (ra < J->maxslot) J->maxslot = ra;
17,847✔
577
  J->pc += skip;
29,595✔
578
  return LOOPEV_ENTER;
29,595✔
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++)
9,917✔
586
    if (mref(J->penalty[i].pc, const BCIns) == pc) {
9,771✔
587
      if ((J->penalty[i].reason == LJ_TRERR_LLEAVE ||
30✔
588
           J->penalty[i].reason == LJ_TRERR_LINNER) &&
30✔
589
          J->penalty[i].val >= 2*PENALTY_MIN)
30✔
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)
25,136✔
598
{
599
  if (J->parent == 0 && J->exitno == 0) {
25,136✔
600
    if (pc == J->startpc && J->framedepth + J->retdepth == 0) {
4,487✔
601
      /* Same loop? */
602
      if (ev == LOOPEV_LEAVE)  /* Must loop back to form a root trace. */
4,288✔
603
        lj_trace_err(J, LJ_TRERR_LLEAVE);
33✔
604
      lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno);  /* Looping trace. */
4,255✔
605
    } else if (ev != LOOPEV_LEAVE) {  /* Entering inner loop? */
199✔
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))
193✔
613
        lj_trace_err(J, LJ_TRERR_LINNER);  /* Root trace hit an inner loop. */
156✔
614
      if ((ev != LOOPEV_ENTERLO &&
37✔
615
           J->loopref && J->cur.nins - J->loopref > 24) || --J->loopunroll < 0)
37✔
616
        lj_trace_err(J, LJ_TRERR_LUNROLL);  /* Limit loop unrolling. */
3✔
617
      J->loopref = J->cur.nins;
34✔
618
    }
619
  } else if (ev != LOOPEV_LEAVE) {  /* Side trace enters an inner loop. */
20,649✔
620
    J->loopref = J->cur.nins;
20,522✔
621
    if (--J->loopunroll < 0)
20,522✔
622
      lj_trace_err(J, LJ_TRERR_LUNROLL);  /* Limit loop unrolling. */
3✔
623
  }  /* Side trace continues across a loop that's left or not entered. */
624
}
24,941✔
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)
9,803✔
628
{
629
  if (J->parent == 0 && J->exitno == 0) {  /* Root trace hit an inner loop. */
9,803✔
630
    /* Better let the inner loop spawn a side trace back here. */
631
    lj_trace_err(J, LJ_TRERR_LINNER);
430✔
632
  } else if (ev != LOOPEV_LEAVE) {  /* Side trace enters a compiled loop. */
9,373✔
633
    J->instunroll = 0;  /* Cannot continue across a compiled loop op. */
9,347✔
634
    if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
9,347✔
635
      lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno);  /* Form extra loop. */
179✔
636
    else
637
      lj_record_stop(J, LJ_TRLINK_ROOT, lnk);  /* Link to the loop. */
9,168✔
638
  }  /* Side trace continues across a loop that's left or not entered. */
639
}
9,373✔
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)
7,169,109✔
670
{
671
  if (J->prof_mode && rec_profile_need(J, J->pt, pc)) {
7,169,109✔
672
    emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
1✔
673
    lj_snap_add(J);
1✔
674
  }
675
}
7,169,109✔
676

677
static void rec_profile_ret(jit_State *J)
733,654✔
678
{
679
  if (J->prof_mode == 'f') {
733,654✔
680
    emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
×
681
    J->prev_pt = NULL;
×
682
    lj_snap_add(J);
×
683
  }
684
}
733,654✔
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,034,735✔
692
{
693
  TRef kfunc;
1,034,735✔
694
  if (isluafunc(fn)) {
1,034,735✔
695
    GCproto *pt = funcproto(fn);
732,618✔
696
    /* Too many closures created? Probably not a monomorphic function. */
697
    if (pt->flags >= PROTO_CLC_POLY) {  /* Specialize to prototype instead. */
732,618✔
698
      TRef trpt = emitir(IRT(IR_FLOAD, IRT_PGC), tr, IRFL_FUNC_PC);
15✔
699
      emitir(IRTG(IR_EQ, IRT_PGC), trpt, lj_ir_kptr(J, proto_bc(pt)));
15✔
700
      (void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);  /* Prevent GC of proto. */
15✔
701
      return tr;
15✔
702
    }
703
  } else {
704
    /* Don't specialize to non-monomorphic builtins. */
705
    switch (fn->c.ffid) {
302,117✔
706
    case FF_coroutine_wrap_aux:
107✔
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);
107✔
711
        emitir(IRTG(IR_EQ, IRT_INT), trid, lj_ir_kint(J, fn->c.ffid));
107✔
712
      }
713
      return tr;
107✔
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,034,613✔
721
  emitir(IRTG(IR_EQ, IRT_FUNC), tr, kfunc);
1,034,613✔
722
  return kfunc;
1,034,613✔
723
}
724

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

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

770
/* Record tail call. */
771
void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs)
95,046✔
772
{
773
  rec_call_setup(J, func, nargs);
95,046✔
774
  if (frame_isvarg(J->L->base - 1)) {
95,046✔
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)
95,046✔
784
    J->base[func+1] = TREF_FRAME;
93,109✔
785
  memmove(&J->base[-1-LJ_FR2], &J->base[func], sizeof(TRef)*(J->maxslot+1+LJ_FR2));
95,046✔
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)
95,046✔
789
    lj_trace_err(J, LJ_TRERR_LUNROLL);
1,383✔
790
}
93,663✔
791

792
/* Check unroll limits for down-recursion. */
793
static int check_downrec_unroll(jit_State *J, GCproto *pt)
35✔
794
{
795
  IRRef ptref;
35✔
796
  for (ptref = J->chain[IR_KGC]; ptref; ptref = IR(ptref)->prev)
74✔
797
    if (ir_kgc(IR(ptref)) == obj2gco(pt)) {
40✔
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,033,896✔
819
{
820
  TValue *frame = J->L->base - 1;
1,033,896✔
821
  ptrdiff_t i;
1,033,896✔
822
  BCReg baseadj = 0;
1,033,896✔
823
  for (i = 0; i < gotresults; i++)
1,978,720✔
824
    (void)getslot(J, rbase+i);  /* Ensure all results have a reference. */
944,824✔
825
  while (frame_ispcall(frame)) {  /* Immediately resolve pcall() returns. */
1,033,927✔
826
    BCReg cbase = (BCReg)frame_delta(frame);
48✔
827
    if (--J->framedepth <= 0)
48✔
828
      lj_trace_err(J, LJ_TRERR_NYIRETL);
17✔
829
    lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
31✔
830
    gotresults++;
31✔
831
    baseadj += cbase;
31✔
832
    rbase += cbase;
31✔
833
    J->baseslot -= (BCReg)cbase;
31✔
834
    J->base -= cbase;
31✔
835
    J->base[--rbase] = TREF_TRUE;  /* Prepend true to results. */
31✔
836
    frame = frame_prevd(frame);
31✔
837
    J->needsnap = 1;  /* Stop catching on-trace errors. */
31✔
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,033,879✔
841
       (!frame_islua(frame) ||
112,662✔
842
        (J->parent == 0 && J->exitno == 0 &&
112,603✔
843
         !bc_isret(bc_op(J->cur.startins))))) {
938✔
844
    /* NYI: specialize to frame type and return directly, not via RET*. */
845
    for (i = 0; i < (ptrdiff_t)rbase; i++)
2,428✔
846
      J->base[i] = 0;  /* Purge dead slots. */
1,432✔
847
    J->maxslot = rbase + (BCReg)gotresults;
996✔
848
    lj_record_stop(J, LJ_TRLINK_RETURN, 0);  /* Return to interpreter. */
996✔
849
    return;
996✔
850
  }
851
  if (frame_isvarg(frame)) {
1,032,883✔
852
    BCReg cbase = (BCReg)frame_delta(frame);
130✔
853
    if (--J->framedepth < 0)  /* NYI: return of vararg func to lower frame. */
130✔
854
      lj_trace_err(J, LJ_TRERR_NYIRETL);
×
855
    lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
130✔
856
    baseadj += cbase;
130✔
857
    rbase += cbase;
130✔
858
    J->baseslot -= (BCReg)cbase;
130✔
859
    J->base -= cbase;
130✔
860
    frame = frame_prevd(frame);
130✔
861
  }
862
  if (frame_islua(frame)) {  /* Return to Lua frame. */
1,032,883✔
863
    BCIns callins = *(frame_pc(frame)-1);
929,622✔
864
    ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
929,622✔
865
    BCReg cbase = bc_a(callins);
929,622✔
866
    GCproto *pt = funcproto(frame_func(frame - (cbase+1+LJ_FR2)));
929,622✔
867
    if ((pt->flags & PROTO_NOJIT))
929,622✔
868
      lj_trace_err(J, LJ_TRERR_CJITOFF);
×
869
    if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
929,622✔
870
      if (!J->cur.root && check_downrec_unroll(J, pt)) {
111,666✔
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);
111,665✔
877
    }
878
    for (i = 0; i < nresults; i++)  /* Adjust results. */
1,726,404✔
879
      J->base[i-1-LJ_FR2] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
796,783✔
880
    J->maxslot = cbase+(BCReg)nresults;
929,621✔
881
    if (J->framedepth > 0) {  /* Return to a frame that is part of the trace. */
929,621✔
882
      J->framedepth--;
817,512✔
883
      lj_assertJ(J->baseslot > cbase+1+LJ_FR2, "bad baseslot for return");
817,512✔
884
      J->baseslot -= cbase+1+LJ_FR2;
817,512✔
885
      J->base -= cbase+1+LJ_FR2;
817,512✔
886
    } else if (J->parent == 0 && J->exitno == 0 &&
112,109✔
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. */
112,086✔
891
      lj_trace_err(J, LJ_TRERR_NYIRETL);  /* No way to insert snapshot here. */
×
892
    } else if (1 + pt->framesize >= LJ_MAX_JSLOTS ||
112,086✔
893
               J->baseslot + J->maxslot >= LJ_MAX_JSLOTS) {
112,085✔
894
      lj_trace_err(J, LJ_TRERR_STACKOV);
2✔
895
    } else {  /* Return to lower frame. Guard for the target we return to. */
896
      TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
112,084✔
897
      TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
112,084✔
898
      emitir(IRTG(IR_RETF, IRT_PGC), trpt, trpc);
112,084✔
899
      J->retdepth++;
112,084✔
900
      J->needsnap = 1;
112,084✔
901
      lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot for return");
112,084✔
902
      /* Shift result slots up and clear the slots of the new frame below. */
903
      memmove(J->base + cbase, J->base-1-LJ_FR2, sizeof(TRef)*nresults);
112,084✔
904
      memset(J->base-1-LJ_FR2, 0, sizeof(TRef)*(cbase+1+LJ_FR2));
112,084✔
905
    }
906
  } else if (frame_iscont(frame)) {  /* Return to continuation frame. */
103,261✔
907
    ASMFunction cont = frame_contf(frame);
103,261✔
908
    BCReg cbase = (BCReg)frame_delta(frame);
103,261✔
909
    if ((J->framedepth -= 2) < 0)
103,261✔
910
      lj_trace_err(J, LJ_TRERR_NYIRETL);
6✔
911
    J->baseslot -= (BCReg)cbase;
103,255✔
912
    J->base -= cbase;
103,255✔
913
    J->maxslot = cbase-(2<<LJ_FR2);
103,255✔
914
    if (cont == lj_cont_ra) {
103,255✔
915
      /* Copy result to destination slot. */
916
      BCReg dst = bc_a(*(frame_contpc(frame)-1));
72,054✔
917
      J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
72,054✔
918
      if (dst >= J->maxslot) {
72,054✔
919
        J->maxslot = dst+1;
×
920
      }
921
    } else if (cont == lj_cont_nop) {
31,201✔
922
      /* Nothing to do here. */
923
    } else if (cont == lj_cont_cat) {
31,049✔
924
      BCReg bslot = bc_b(*(frame_contpc(frame)-1));
13✔
925
      TRef tr = gotresults ? J->base[cbase+rbase] : TREF_NIL;
13✔
926
      if (bslot != J->maxslot) {  /* Concatenate the remainder. */
13✔
927
        /* Simulate lower frame and result. */
928
        TValue *b = J->L->base - baseadj, save;
7✔
929
        /* Can't handle MM_concat + CALLT + fast func side-effects. */
930
        if (J->postproc != LJ_POST_NONE)
7✔
931
          lj_trace_err(J, LJ_TRERR_NYIRETL);
1✔
932
        J->base[J->maxslot] = tr;
6✔
933
        copyTV(J->L, &save, b-(2<<LJ_FR2));
6✔
934
        if (gotresults)
6✔
935
          copyTV(J->L, b-(2<<LJ_FR2), b+rbase);
6✔
936
        else
937
          setnilV(b-(2<<LJ_FR2));
×
938
        J->L->base = b - cbase;
6✔
939
        tr = rec_cat(J, bslot, cbase-(2<<LJ_FR2));
6✔
940
        b = J->L->base + cbase;  /* Undo. */
6✔
941
        J->L->base = b + baseadj;
6✔
942
        copyTV(J->L, b-(2<<LJ_FR2), &save);
6✔
943
      }
944
      if (tr >= 0xffffff00) {
12✔
945
        lj_err_throw(J->L, -(int32_t)tr);  /* Propagate errors. */
2✔
946
      } else if (tr) {  /* Store final result. */
10✔
947
        BCReg dst = bc_a(*(frame_contpc(frame)-1));
6✔
948
        J->base[dst] = tr;
6✔
949
        if (dst >= J->maxslot) {
6✔
950
          J->maxslot = dst+1;
×
951
        }
952
      }  /* Otherwise continue with another __concat call. */
953
    } else {
954
      /* Result type already specialized. */
955
      lj_assertJ(cont == lj_cont_condf || cont == lj_cont_condt,
956
                 "bad continuation type");
957
    }
958
  } else {
959
    lj_trace_err(J, LJ_TRERR_NYIRETL);  /* NYI: handle return to C frame. */
×
960
  }
961
  lj_assertJ(J->baseslot >= 1+LJ_FR2, "bad baseslot for return");
1,033,844✔
962
}
963

964
/* -- Metamethod handling ------------------------------------------------- */
965

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

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

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

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

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

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

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

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

1225
/* -- Indexed access ------------------------------------------------------ */
1226

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

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

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

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

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

1405
/* Determine whether a key is NOT one of the fast metamethod names. */
1406
static int nommstr(jit_State *J, TRef key)
277,584✔
1407
{
1408
  if (tref_isstr(key)) {
277,584✔
1409
    if (tref_isk(key)) {
274,487✔
1410
      GCstr *str = ir_kstr(IR(tref_ref(key)));
274,473✔
1411
      uint32_t mm;
274,473✔
1412
      for (mm = 0; mm <= MM_FAST; mm++)
1,921,311✔
1413
        if (mmname_str(J2G(J), mm) == str)
1,646,838✔
1414
          return 0;  /* MUST be one the fast metamethod names. */
1415
    } else {
1416
      return 0;  /* Variable string key MAY be a metamethod name. */
1417
    }
1418
  }
1419
  return 1;  /* CANNOT be a metamethod name. */
1420
}
1421

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

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

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

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

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

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

1598
/* -- Upvalue access ------------------------------------------------------ */
1599

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

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

1699
/* -- Record calls to Lua functions --------------------------------------- */
1700

1701
/* Check unroll limits for calls. */
1702
static void check_call_unroll(jit_State *J, TraceNo lnk)
729,762✔
1703
{
1704
  cTValue *frame = J->L->base - 1;
729,762✔
1705
  void *pc = mref(frame_func(frame)->l.pc, void);
729,762✔
1706
  int32_t depth = J->framedepth;
729,762✔
1707
  int32_t count = 0;
729,762✔
1708
  if ((J->pt->flags & PROTO_VARARG)) depth--;  /* Vararg frame still missing. */
729,762✔
1709
  for (; depth > 0; depth--) {  /* Count frames with same prototype. */
1,824,754✔
1710
    if (frame_iscont(frame)) depth--;
1,094,992✔
1711
    frame = frame_prev(frame);
1,094,992✔
1712
    if (mref(frame_func(frame)->l.pc, void) == pc)
1,094,992✔
1713
      count++;
1,905✔
1714
  }
1715
  if (J->pc == J->startpc) {
729,762✔
1716
    if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
435✔
1717
      J->pc++;
132✔
1718
      if (J->framedepth + J->retdepth == 0)
132✔
1719
        lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno);  /* Tail-rec. */
6✔
1720
      else
1721
        lj_record_stop(J, LJ_TRLINK_UPREC, J->cur.traceno);  /* Up-recursion. */
126✔
1722
    }
1723
  } else {
1724
    if (count > J->param[JIT_P_callunroll]) {
729,327✔
1725
      if (lnk) {  /* Possible tail- or up-recursion. */
84✔
1726
        lj_trace_flush(J, lnk);  /* Flush trace that only returns. */
34✔
1727
        /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
1728
        hotcount_set(J2GG(J), J->pc+1, LJ_PRNG_BITS(J, 4));
34✔
1729
      }
1730
      lj_trace_err(J, LJ_TRERR_CUNROLL);
84✔
1731
    }
1732
  }
1733
}
729,678✔
1734

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

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

1775
/* Record entry to a Lua function. */
1776
static void rec_func_lua(jit_State *J)
115,546✔
1777
{
1778
  rec_func_setup(J);
115,546✔
1779
  check_call_unroll(J, 0);
115,544✔
1780
}
115,494✔
1781

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

1803
/* -- Vararg handling ----------------------------------------------------- */
1804

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

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

1927
/* -- Record allocations -------------------------------------------------- */
1928

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

1944
/* -- Concatenation ------------------------------------------------------- */
1945

1946
typedef struct RecCatDataCP {
1947
  TValue savetv[5+LJ_FR2];
1948
  jit_State *J;
1949
  BCReg baseslot, topslot;
1950
  TRef tr;
1951
} RecCatDataCP;
1952

1953
static TValue *rec_mm_concat_cp(lua_State *L, lua_CFunction dummy, void *ud)
302✔
1954
{
1955
  RecCatDataCP *rcd = (RecCatDataCP *)ud;
302✔
1956
  jit_State *J = rcd->J;
302✔
1957
  BCReg baseslot = rcd->baseslot, topslot = rcd->topslot;
302✔
1958
  TRef *top = &J->base[topslot];
302✔
1959
  BCReg s;
302✔
1960
  RecordIndex ix;
302✔
1961
  UNUSED(L); UNUSED(dummy);
302✔
1962
  lj_assertJ(baseslot < topslot, "bad CAT arg");
302✔
1963
  for (s = baseslot; s <= topslot; s++)
1,076✔
1964
    (void)getslot(J, s);  /* Ensure all arguments have a reference. */
774✔
1965
  if (tref_isnumber_str(top[0]) && tref_isnumber_str(top[-1])) {
302✔
1966
    TRef tr, hdr, *trp, *xbase, *base = &J->base[baseslot];
290✔
1967
    /* First convert numbers to strings. */
1968
    for (trp = top; trp >= base; trp--) {
1,031✔
1969
      if (tref_isnumber(*trp))
743✔
1970
        *trp = emitir(IRT(IR_TOSTR, IRT_STR), *trp,
51✔
1971
                      tref_isnum(*trp) ? IRTOSTR_NUM : IRTOSTR_INT);
1972
      else if (!tref_isstr(*trp))
692✔
1973
        break;
1974
    }
1975
    xbase = ++trp;
290✔
1976
    tr = hdr = emitir(IRT(IR_BUFHDR, IRT_PGC),
290✔
1977
                      lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
1978
    do {
741✔
1979
      tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, *trp++);
741✔
1980
    } while (trp <= top);
740✔
1981
    tr = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
289✔
1982
    J->maxslot = (BCReg)(xbase - J->base);
289✔
1983
    if (xbase == base) {
289✔
1984
      rcd->tr = tr;  /* Return simple concatenation result. */
287✔
1985
      return NULL;
287✔
1986
    }
1987
    /* Pass partial result. */
1988
    rcd->topslot = topslot = J->maxslot--;
2✔
1989
    /* Save updated range of slots. */
1990
    memcpy(rcd->savetv, &L->base[topslot-1], sizeof(rcd->savetv));
2✔
1991
    *xbase = tr;
2✔
1992
    top = xbase;
2✔
1993
    setstrV(J->L, &ix.keyv, &J2G(J)->strempty);  /* Simulate string result. */
2✔
1994
  } else {
1995
    J->maxslot = topslot-1;
12✔
1996
    copyTV(J->L, &ix.keyv, &J->L->base[topslot]);
12✔
1997
  }
1998
  copyTV(J->L, &ix.tabv, &J->L->base[topslot-1]);
14✔
1999
  ix.tab = top[-1];
14✔
2000
  ix.key = top[0];
14✔
2001
  rec_mm_arith(J, &ix, MM_concat);  /* Call __concat metamethod. */
14✔
2002
  rcd->tr = 0;  /* No result yet. */
13✔
2003
  return NULL;
13✔
2004
}
2005

2006
static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot)
302✔
2007
{
2008
  lua_State *L = J->L;
302✔
2009
  ptrdiff_t delta = L->top - L->base;
302✔
2010
  TValue errobj;
302✔
2011
  RecCatDataCP rcd;
302✔
2012
  int errcode;
302✔
2013
  rcd.J = J;
302✔
2014
  rcd.baseslot = baseslot;
302✔
2015
  rcd.topslot = topslot;
302✔
2016
  /* Save slots. */
2017
  memcpy(rcd.savetv, &L->base[topslot-1], sizeof(rcd.savetv));
302✔
2018
  errcode = lj_vm_cpcall(L, NULL, &rcd, rec_mm_concat_cp);
302✔
2019
  if (errcode) copyTV(L, &errobj, L->top-1);
302✔
2020
  /* Restore slots. */
2021
  memcpy(&L->base[rcd.topslot-1], rcd.savetv, sizeof(rcd.savetv));
302✔
2022
  if (errcode) {
302✔
2023
    L->top = L->base + delta;
2✔
2024
    copyTV(L, L->top++, &errobj);
2✔
2025
    return (TRef)(-errcode);
2✔
2026
  }
2027
  return rcd.tr;
300✔
2028
}
2029

2030
/* -- Record bytecode ops ------------------------------------------------- */
2031

2032
/* Prepare for comparison. */
2033
static void rec_comp_prep(jit_State *J)
689,518✔
2034
{
2035
  /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
2036
  if (J->cur.nsnap == 1 && J->cur.snap[0].ref == J->cur.nins)
689,518✔
2037
    emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
315✔
2038
  lj_snap_add(J);
689,518✔
2039
}
689,518✔
2040

2041
/* Fixup comparison. */
2042
static void rec_comp_fixup(jit_State *J, const BCIns *pc, int cond)
710,138✔
2043
{
2044
  BCIns jmpins = pc[1];
710,138✔
2045
  const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0);
710,138✔
2046
  SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
710,138✔
2047
  /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
2048
#if LJ_FR2
2049
  SnapEntry *flink = &J->cur.snapmap[snap->mapofs + snap->nent];
710,138✔
2050
  uint64_t pcbase;
710,138✔
2051
  memcpy(&pcbase, flink, sizeof(uint64_t));
710,138✔
2052
  pcbase = (pcbase & 0xff) | (u64ptr(npc) << 8);
710,138✔
2053
  memcpy(flink, &pcbase, sizeof(uint64_t));
710,138✔
2054
#else
2055
  J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc);
2056
#endif
2057
  J->needsnap = 1;
710,138✔
2058
  if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins);
710,138✔
2059
  lj_snap_shrink(J);  /* Shrink last snapshot if possible. */
710,138✔
2060
}
710,138✔
2061

2062
/* Record the next bytecode instruction (_before_ it's executed). */
2063
void lj_record_ins(jit_State *J)
7,169,644✔
2064
{
2065
  cTValue *lbase;
7,169,644✔
2066
  RecordIndex ix;
7,169,644✔
2067
  const BCIns *pc;
7,169,644✔
2068
  BCIns ins;
7,169,644✔
2069
  BCOp op;
7,169,644✔
2070
  TRef ra, rb, rc;
7,169,644✔
2071

2072
  /* Perform post-processing action before recording the next instruction. */
2073
  if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) {
7,169,644✔
2074
    switch (J->postproc) {
300,202✔
2075
    case LJ_POST_FIXCOMP:  /* Fixup comparison. */
20,728✔
2076
      pc = (const BCIns *)(uintptr_t)J2G(J)->tmptv.u64;
20,728✔
2077
      rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1)));
20,728✔
2078
      /* fallthrough */
2079
    case LJ_POST_FIXGUARD:  /* Fixup and emit pending guard. */
30,985✔
2080
    case LJ_POST_FIXGUARDSNAP:  /* Fixup and emit pending guard and snapshot. */
2081
      if (!tvistruecond(&J2G(J)->tmptv2)) {
30,985✔
2082
        J->fold.ins.o ^= 1;  /* Flip guard to opposite. */
10,250✔
2083
        if (J->postproc == LJ_POST_FIXGUARDSNAP) {
10,250✔
2084
          SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
1✔
2085
          J->cur.snapmap[snap->mapofs+snap->nent-1]--;  /* False -> true. */
1✔
2086
        }
2087
      }
2088
      lj_opt_fold(J);  /* Emit pending guard. */
30,985✔
2089
      /* fallthrough */
2090
    case LJ_POST_FIXBOOL:
30,999✔
2091
      if (!tvistruecond(&J2G(J)->tmptv2)) {
30,999✔
2092
        BCReg s;
10,256✔
2093
        TValue *tv = J->L->base;
10,256✔
2094
        for (s = 0; s < J->maxslot; s++)  /* Fixup stack slot (if any). */
51,416✔
2095
          if (J->base[s] == TREF_TRUE && tvisfalse(&tv[s])) {
41,168✔
2096
            J->base[s] = TREF_FALSE;
8✔
2097
            break;
8✔
2098
          }
2099
      }
2100
      break;
2101
    case LJ_POST_FIXCONST:
1✔
2102
      {
2103
        BCReg s;
1✔
2104
        TValue *tv = J->L->base;
1✔
2105
        for (s = 0; s < J->maxslot; s++)  /* Constify stack slots (if any). */
13✔
2106
          if (J->base[s] == TREF_NIL && !tvisnil(&tv[s]))
12✔
2107
            J->base[s] = lj_record_constify(J, &tv[s]);
1✔
2108
      }
2109
      break;
2110
    case LJ_POST_FFRETRY:  /* Suppress recording of retried fast function. */
269,202✔
2111
      if (bc_op(*J->pc) >= BC__MAX)
269,202✔
2112
        return;
23✔
2113
      break;
2114
    default: lj_assertJ(0, "bad post-processing mode"); break;
2115
    }
2116
    J->postproc = LJ_POST_NONE;
300,199✔
2117
  }
2118

2119
  /* Need snapshot before recording next bytecode (e.g. after a store). */
2120
  if (J->needsnap) {
7,169,641✔
2121
    J->needsnap = 0;
1,111,333✔
2122
    if (J->pt) lj_snap_purge(J);
1,111,333✔
2123
    lj_snap_add(J);
1,111,333✔
2124
    J->mergesnap = 1;
1,111,333✔
2125
  }
2126

2127
  /* Skip some bytecodes. */
2128
  if (LJ_UNLIKELY(J->bcskip > 0)) {
7,169,641✔
2129
    J->bcskip--;
20✔
2130
    return;
20✔
2131
  }
2132

2133
  /* Record only closed loops for root traces. */
2134
  pc = J->pc;
7,169,621✔
2135
  if (J->framedepth == 0 &&
7,169,621✔
2136
     (MSize)((char *)pc - (char *)J->bc_min) >= J->bc_extent)
2,215,656✔
2137
    lj_trace_err(J, LJ_TRERR_LLEAVE);
512✔
2138

2139
#ifdef LUA_USE_ASSERT
2140
  rec_check_slots(J);
2141
  rec_check_ir(J);
2142
#endif
2143

2144
#if LJ_HASPROFILE
2145
  rec_profile_ins(J, pc);
7,169,109✔
2146
#endif
2147

2148
  /* Keep a copy of the runtime values of var/num/str operands. */
2149
#define rav        (&ix.valv)
2150
#define rbv        (&ix.tabv)
2151
#define rcv        (&ix.keyv)
2152

2153
  lbase = J->L->base;
7,169,109✔
2154
  ins = *pc;
7,169,109✔
2155
  op = bc_op(ins);
7,169,109✔
2156
  ra = bc_a(ins);
7,169,109✔
2157
  ix.val = 0;
7,169,109✔
2158
  switch (bcmode_a(op)) {
7,169,109✔
2159
  case BCMvar:
1,032,600✔
2160
    copyTV(J->L, rav, &lbase[ra]); ix.val = ra = getslot(J, ra); break;
1,032,600✔
2161
  default: break;  /* Handled later. */
2162
  }
2163
  rb = bc_b(ins);
7,169,109✔
2164
  rc = bc_c(ins);
7,169,109✔
2165
  switch (bcmode_b(op)) {
7,169,109✔
2166
  case BCMnone: rb = 0; rc = bc_d(ins); break;  /* Upgrade rc to 'rd'. */
4,669,906✔
2167
  case BCMvar:
1,662,383✔
2168
    copyTV(J->L, rbv, &lbase[rb]); ix.tab = rb = getslot(J, rb); break;
1,662,383✔
2169
  default: break;  /* Handled later. */
2170
  }
2171
  switch (bcmode_c(op)) {
7,169,109✔
2172
  case BCMvar:
1,047,834✔
2173
    copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
1,047,834✔
2174
  case BCMpri: setpriV(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
539,345✔
2175
  case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
155,021✔
2176
    copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
155,021✔
2177
    lj_ir_knumint(J, numV(tv)); } break;
155,021✔
2178
  case BCMstr: { GCstr *s = gco2str(proto_kgc(J->pt, ~(ptrdiff_t)rc));
1,344,086✔
2179
    setstrV(J->L, rcv, s); ix.key = rc = lj_ir_kstr(J, s); } break;
1,344,086✔
2180
  default: break;  /* Handled later. */
2181
  }
2182

2183
  switch (op) {
7,169,109✔
2184

2185
  /* -- Comparison ops ---------------------------------------------------- */
2186

2187
  case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
236,650✔
2188
#if LJ_HASFFI
2189
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
236,650✔
2190
      rec_mm_comp_cdata(J, &ix, op, ((int)op & 2) ? MM_le : MM_lt);
20,709✔
2191
      break;
20,709✔
2192
    }
2193
#endif
2194
    /* Emit nothing for two numeric or string consts. */
2195
    if (!(tref_isk2(ra,rc) && tref_isnumber_str(ra) && tref_isnumber_str(rc))) {
215,941✔
2196
      IRType ta = tref_isinteger(ra) ? IRT_INT : tref_type(ra);
193,997✔
2197
      IRType tc = tref_isinteger(rc) ? IRT_INT : tref_type(rc);
193,997✔
2198
      int irop;
193,997✔
2199
      if (ta != tc) {
193,997✔
2200
        /* Widen mixed number/int comparisons to number/number comparison. */
2201
        if (ta == IRT_INT && tc == IRT_NUM) {
187,162✔
2202
          ra = emitir(IRTN(IR_CONV), ra, IRCONV_NUM_INT);
94,637✔
2203
          ta = IRT_NUM;
94,637✔
2204
        } else if (ta == IRT_NUM && tc == IRT_INT) {
92,525✔
2205
          rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
92,522✔
2206
        } else if (LJ_52) {
3✔
2207
          ta = IRT_NIL;  /* Force metamethod for different types. */
2208
        } else if (!((ta == IRT_FALSE || ta == IRT_TRUE) &&
3✔
2209
                     (tc == IRT_FALSE || tc == IRT_TRUE))) {
×
2210
          break;  /* Interpreter will throw for two different types. */
2211
        }
2212
      }
2213
      rec_comp_prep(J);
193,994✔
2214
      irop = (int)op - (int)BC_ISLT + (int)IR_LT;
193,994✔
2215
      if (ta == IRT_NUM) {
193,994✔
2216
        if ((irop & 1)) irop ^= 4;  /* ISGE/ISGT are unordered. */
193,865✔
2217
        if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
193,865✔
2218
          irop ^= 5;
186,441✔
2219
      } else if (ta == IRT_INT) {
129✔
2220
        if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
79✔
2221
          irop ^= 1;
20✔
2222
      } else if (ta == IRT_STR) {
50✔
2223
        if (!lj_ir_strcmp(strV(rav), strV(rcv), (IROp)irop)) irop ^= 1;
1✔
2224
        ra = lj_ir_call(J, IRCALL_lj_str_cmp, ra, rc);
1✔
2225
        rc = lj_ir_kint(J, 0);
1✔
2226
        ta = IRT_INT;
1✔
2227
      } else {
2228
        rec_mm_comp(J, &ix, (int)op);
49✔
2229
        break;
49✔
2230
      }
2231
      emitir(IRTG(irop, ta), ra, rc);
193,945✔
2232
      rec_comp_fixup(J, J->pc, ((int)op ^ irop) & 1);
193,945✔
2233
    }
2234
    break;
2235

2236
  case BC_ISEQV: case BC_ISNEV:
518,228✔
2237
  case BC_ISEQS: case BC_ISNES:
2238
  case BC_ISEQN: case BC_ISNEN:
2239
  case BC_ISEQP: case BC_ISNEP:
2240
#if LJ_HASFFI
2241
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
518,228✔
2242
      rec_mm_comp_cdata(J, &ix, op, MM_eq);
10,271✔
2243
      break;
10,271✔
2244
    }
2245
#endif
2246
    /* Emit nothing for two non-table, non-udata consts. */
2247
    if (!(tref_isk2(ra, rc) && !(tref_istab(ra) || tref_isudata(ra)))) {
507,957✔
2248
      int diff;
495,524✔
2249
      rec_comp_prep(J);
495,524✔
2250
      diff = lj_record_objcmp(J, ra, rc, rav, rcv);
495,524✔
2251
      if (diff == 2 || !(tref_istab(ra) || tref_isudata(ra)))
495,524✔
2252
        rec_comp_fixup(J, J->pc, ((int)op & 1) == !diff);
495,465✔
2253
      else if (diff == 1)  /* Only check __eq if different, but same type. */
59✔
2254
        rec_mm_equal(J, &ix, (int)op);
10✔
2255
    }
2256
    break;
2257

2258
  /* -- Unary test and copy ops ------------------------------------------- */
2259

2260
  case BC_ISTC: case BC_ISFC:
221✔
2261
    if ((op & 1) == tref_istruecond(rc))
221✔
2262
      rc = 0;  /* Don't store if condition is not true. */
195✔
2263
    /* fallthrough */
2264
  case BC_IST: case BC_ISF:  /* Type specialization suffices. */
2265
    if (bc_a(pc[1]) < J->maxslot)
52,189✔
2266
      J->maxslot = bc_a(pc[1]);  /* Shrink used slots. */
30,873✔
2267
    break;
2268

2269
  case BC_ISTYPE: case BC_ISNUM:
2270
    /* These coercions need to correspond with lj_meta_istype(). */
2271
    if (LJ_DUALNUM && rc == ~LJ_TNUMX+1)
12✔
2272
      ra = lj_opt_narrow_toint(J, ra);
2273
    else if (rc == ~LJ_TNUMX+2)
12✔
2274
      ra = lj_ir_tonum(J, ra);
2✔
2275
    else if (rc == ~LJ_TSTR+1)
10✔
2276
      ra = lj_ir_tostr(J, ra);
3✔
2277
    /* else: type specialization suffices. */
2278
    J->base[bc_a(ins)] = ra;
12✔
2279
    break;
12✔
2280

2281
  /* -- Unary ops --------------------------------------------------------- */
2282

2283
  case BC_NOT:
3✔
2284
    /* Type specialization already forces const result. */
2285
    rc = tref_istruecond(rc) ? TREF_FALSE : TREF_TRUE;
3✔
2286
    break;
2287

2288
  case BC_LEN:
55✔
2289
    if (tref_isstr(rc))
55✔
2290
      rc = emitir(IRTI(IR_FLOAD), rc, IRFL_STR_LEN);
5✔
2291
    else if (!LJ_52 && tref_istab(rc))
50✔
2292
      rc = lj_ir_call(J, IRCALL_lj_tab_len, rc);
48✔
2293
    else
2294
      rc = rec_mm_len(J, rc, rcv);
2✔
2295
    break;
2296

2297
  /* -- Arithmetic ops ---------------------------------------------------- */
2298

2299
  case BC_UNM:
26✔
2300
    if (tref_isnumber_str(rc)) {
26✔
2301
      rc = lj_opt_narrow_unm(J, rc, rcv);
23✔
2302
    } else {
2303
      ix.tab = rc;
3✔
2304
      copyTV(J->L, &ix.tabv, rcv);
3✔
2305
      rc = rec_mm_arith(J, &ix, MM_unm);
3✔
2306
    }
2307
    break;
2308

2309
  case BC_ADDNV: case BC_SUBNV: case BC_MULNV: case BC_DIVNV: case BC_MODNV:
100,317✔
2310
    /* Swap rb/rc and rbv/rcv. rav is temp. */
2311
    ix.tab = rc; ix.key = rc = rb; rb = ix.tab;
100,317✔
2312
    copyTV(J->L, rav, rbv);
100,317✔
2313
    copyTV(J->L, rbv, rcv);
100,317✔
2314
    copyTV(J->L, rcv, rav);
100,317✔
2315
    if (op == BC_MODNV)
100,317✔
2316
      goto recmod;
1✔
2317
    /* fallthrough */
2318
  case BC_ADDVN: case BC_SUBVN: case BC_MULVN: case BC_DIVVN:
2319
  case BC_ADDVV: case BC_SUBVV: case BC_MULVV: case BC_DIVVV: {
2320
    MMS mm = bcmode_mm(op);
309,855✔
2321
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
309,855✔
2322
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv,
268,870✔
2323
                               (int)mm - (int)MM_add + (int)IR_ADD);
268,870✔
2324
    else
2325
      rc = rec_mm_arith(J, &ix, mm);
40,985✔
2326
    break;
2327
    }
2328

2329
  case BC_MODVN: case BC_MODVV:
2330
  recmod:
75✔
2331
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
75✔
2332
      rc = lj_opt_narrow_mod(J, rb, rc, rbv, rcv);
70✔
2333
    else
2334
      rc = rec_mm_arith(J, &ix, MM_mod);
5✔
2335
    break;
2336

2337
  case BC_POW:
10,252✔
2338
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
10,252✔
2339
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv, IR_POW);
10,246✔
2340
    else
2341
      rc = rec_mm_arith(J, &ix, MM_pow);
6✔
2342
    break;
2343

2344
  /* -- Miscellaneous ops ------------------------------------------------- */
2345

2346
  case BC_CAT:
296✔
2347
    rc = rec_cat(J, rb, rc);
296✔
2348
    if (rc >= 0xffffff00)
296✔
2349
      lj_err_throw(J->L, -(int32_t)rc);  /* Propagate errors. */
×
2350
    break;
2351

2352
  /* -- Constant and move ops --------------------------------------------- */
2353

2354
  case BC_MOV:
505,419✔
2355
    /* Clear gap of method call to avoid resurrecting previous refs. */
2356
    if (ra > J->maxslot) {
505,419✔
2357
#if LJ_FR2
2358
      memset(J->base + J->maxslot, 0, (ra - J->maxslot) * sizeof(TRef));
384,251✔
2359
#else
2360
      J->base[ra-1] = 0;
2361
#endif
2362
    }
2363
    break;
2364
  case BC_KSTR: case BC_KNUM: case BC_KPRI:
2365
    break;
2366
  case BC_KSHORT:
255,675✔
2367
    rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
255,675✔
2368
    break;
255,675✔
2369
  case BC_KNIL:
20✔
2370
    if (LJ_FR2 && ra > J->maxslot)
20✔
2371
      J->base[ra-1] = 0;
1✔
2372
    while (ra <= rc)
1,247✔
2373
      J->base[ra++] = TREF_NIL;
1,227✔
2374
    if (rc >= J->maxslot) J->maxslot = rc+1;
20✔
2375
    break;
2376
#if LJ_HASFFI
2377
  case BC_KCDATA:
59✔
2378
    rc = lj_ir_kgc(J, proto_kgc(J->pt, ~(ptrdiff_t)rc), IRT_CDATA);
59✔
2379
    break;
59✔
2380
#endif
2381

2382
  /* -- Upvalue and function ops ------------------------------------------ */
2383

2384
  case BC_UGET:
973,633✔
2385
    rc = rec_upvalue(J, rc, 0);
973,633✔
2386
    break;
973,633✔
2387
  case BC_USETV: case BC_USETS: case BC_USETN: case BC_USETP:
209✔
2388
    rec_upvalue(J, ra, rc);
209✔
2389
    break;
209✔
2390

2391
  /* -- Table ops --------------------------------------------------------- */
2392

2393
  case BC_GGET: case BC_GSET:
5,121✔
2394
    settabV(J->L, &ix.tabv, tabref(J->fn->l.env));
5,121✔
2395
    ix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), getcurrf(J), IRFL_FUNC_ENV);
5,121✔
2396
    ix.idxchain = LJ_MAX_IDXCHAIN;
5,121✔
2397
    rc = lj_record_idx(J, &ix);
5,121✔
2398
    break;
5,121✔
2399

2400
  case BC_TGETB: case BC_TSETB:
748✔
2401
    setintV(&ix.keyv, (int32_t)rc);
748✔
2402
    ix.key = lj_ir_kint(J, (int32_t)rc);
748✔
2403
    /* fallthrough */
2404
  case BC_TGETV: case BC_TGETS: case BC_TSETV: case BC_TSETS:
1,342,175✔
2405
    ix.idxchain = LJ_MAX_IDXCHAIN;
1,342,175✔
2406
    rc = lj_record_idx(J, &ix);
1,342,175✔
2407
    break;
1,342,175✔
2408
  case BC_TGETR: case BC_TSETR:
26✔
2409
    ix.idxchain = 0;
26✔
2410
    rc = lj_record_idx(J, &ix);
26✔
2411
    break;
26✔
2412

2413
  case BC_TSETM:
5✔
2414
    rec_tsetm(J, ra, (BCReg)(J->L->top - J->L->base), (int32_t)rcv->u32.lo);
5✔
2415
    J->maxslot = ra;  /* The table slot at ra-1 is the highest used slot. */
5✔
2416
    break;
5✔
2417

2418
  case BC_TNEW:
2419
    rc = rec_tnew(J, rc);
554✔
2420
    break;
554✔
2421
  case BC_TDUP:
482✔
2422
    rc = emitir(IRTG(IR_TDUP, IRT_TAB),
482✔
2423
                lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
2424
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2425
    J->rbchash[(rc & (RBCHASH_SLOTS-1))].ref = tref_ref(rc);
2426
    setmref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pc, pc);
2427
    setgcref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
2428
#endif
2429
    break;
482✔
2430

2431
  /* -- Calls and vararg handling ----------------------------------------- */
2432

2433
  case BC_ITERC:
219✔
2434
    J->base[ra] = getslot(J, ra-3);
219✔
2435
    J->base[ra+1+LJ_FR2] = getslot(J, ra-2);
219✔
2436
    J->base[ra+2+LJ_FR2] = getslot(J, ra-1);
219✔
2437
    { /* Do the actual copy now because lj_record_call needs the values. */
2438
      TValue *b = &J->L->base[ra];
219✔
2439
      copyTV(J->L, b, b-3);
219✔
2440
      copyTV(J->L, b+1+LJ_FR2, b-2);
219✔
2441
      copyTV(J->L, b+2+LJ_FR2, b-1);
219✔
2442
    }
2443
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
219✔
2444
    break;
219✔
2445

2446
  /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
2447
  case BC_CALLM:
110,548✔
2448
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
110,548✔
2449
    /* fallthrough */
2450
  case BC_CALL:
836,157✔
2451
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
836,157✔
2452
    break;
836,157✔
2453

2454
  case BC_CALLMT:
15✔
2455
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
15✔
2456
    /* fallthrough */
2457
  case BC_CALLT:
95,044✔
2458
    lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
95,044✔
2459
    break;
95,044✔
2460

2461
  case BC_VARG:
148✔
2462
    rec_varg(J, ra, (ptrdiff_t)rb-1);
148✔
2463
    break;
148✔
2464

2465
  /* -- Returns ----------------------------------------------------------- */
2466

2467
  case BC_RETM:
38✔
2468
    /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
2469
    rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
38✔
2470
    /* fallthrough */
2471
  case BC_RET: case BC_RET0: case BC_RET1:
733,654✔
2472
#if LJ_HASPROFILE
2473
    rec_profile_ret(J);
733,654✔
2474
#endif
2475
    lj_record_ret(J, ra, (ptrdiff_t)rc-1);
733,654✔
2476
    break;
733,654✔
2477

2478
  /* -- Loops and branches ------------------------------------------------ */
2479

2480
  case BC_FORI:
247✔
2481
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)
247✔
2482
      J->loopref = J->cur.nins;
247✔
2483
    break;
2484
  case BC_JFORI:
108✔
2485
    lj_assertJ(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL,
108✔
2486
               "JFORI does not point to JFORL");
2487
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)  /* Link to existing loop. */
108✔
2488
      lj_record_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
105✔
2489
    /* Continue tracing if the loop is not entered. */
2490
    break;
2491

2492
  case BC_FORL:
4,844✔
2493
    rec_loop_interp(J, pc, rec_for(J, pc+((ptrdiff_t)rc-BCBIAS_J), 1));
4,844✔
2494
    break;
4,844✔
2495
  case BC_ITERL:
52✔
2496
    rec_loop_interp(J, pc, rec_iterl(J, *pc));
52✔
2497
    break;
52✔
2498
  case BC_LOOP:
20,240✔
2499
    rec_loop_interp(J, pc, rec_loop(J, ra, 1));
20,240✔
2500
    break;
20,240✔
2501

2502
  case BC_JFORL:
383✔
2503
    rec_loop_jit(J, rc, rec_for(J, pc+bc_j(traceref(J, rc)->startins), 1));
383✔
2504
    break;
383✔
2505
  case BC_JITERL:
65✔
2506
    rec_loop_jit(J, rc, rec_iterl(J, traceref(J, rc)->startins));
65✔
2507
    break;
65✔
2508
  case BC_JLOOP:
9,355✔
2509
    rec_loop_jit(J, rc, rec_loop(J, ra,
18,710✔
2510
                                 !bc_isret(bc_op(traceref(J, rc)->startins))));
9,355✔
2511
    break;
9,355✔
2512

2513
  case BC_IFORL:
2✔
2514
  case BC_IITERL:
2515
  case BC_ILOOP:
2516
  case BC_IFUNCF:
2517
  case BC_IFUNCV:
2518
    lj_trace_err(J, LJ_TRERR_BLACKL);
2✔
2519
    break;
117,402✔
2520

2521
  case BC_JMP:
117,402✔
2522
    if (ra < J->maxslot)
117,402✔
2523
      J->maxslot = ra;  /* Shrink used slots. */
106,495✔
2524
    break;
2525

2526
  /* -- Function headers -------------------------------------------------- */
2527

2528
  case BC_FUNCF:
2529
    rec_func_lua(J);
115,336✔
2530
    break;
2531
  case BC_JFUNCF:
617,054✔
2532
    rec_func_jit(J, rc);
617,054✔
2533
    break;
617,054✔
2534

2535
  case BC_FUNCV:
210✔
2536
    rec_func_vararg(J);
210✔
2537
    rec_func_lua(J);
210✔
2538
    break;
2539
  case BC_JFUNCV:
2540
    /* Cannot happen. No hotcall counting for varag funcs. */
2541
    lj_assertJ(0, "unsupported vararg hotcall");
2542
    break;
2543

2544
  case BC_FUNCC:
135,654✔
2545
  case BC_FUNCCW:
2546
    lj_ffrecord_func(J);
135,654✔
2547
    break;
135,654✔
2548

2549
  default:
165,099✔
2550
    if (op >= BC__MAX) {
165,099✔
2551
      lj_ffrecord_func(J);
165,099✔
2552
      break;
165,099✔
2553
    }
2554
    /* fallthrough */
2555
  case BC_ITERN:
2556
  case BC_ISNEXT:
2557
  case BC_UCLO:
2558
  case BC_FNEW:
2559
    setintV(&J->errinfo, (int32_t)op);
71✔
2560
    lj_trace_err_info(J, LJ_TRERR_NYIBC);
71✔
2561
    break;
7,166,808✔
2562
  }
2563

2564
  /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
2565
  if (bcmode_a(op) == BCMdst && rc) {
7,166,808✔
2566
    J->base[ra] = rc;
3,160,694✔
2567
    if (ra >= J->maxslot) {
3,160,694✔
2568
#if LJ_FR2
2569
      if (ra > J->maxslot) J->base[ra-1] = 0;
2,566,894✔
2570
#endif
2571
      J->maxslot = ra+1;
2,566,894✔
2572
    }
2573
  }
2574

2575
#undef rav
2576
#undef rbv
2577
#undef rcv
2578

2579
  /* Limit the number of recorded IR instructions and constants. */
2580
  if (J->cur.nins > REF_FIRST+(IRRef)J->param[JIT_P_maxrecord] ||
7,166,808✔
2581
      J->cur.nk < REF_BIAS-(IRRef)J->param[JIT_P_maxirconst])
7,166,808✔
2582
    lj_trace_err(J, LJ_TRERR_TRACEOV);
2✔
2583
}
2584

2585
/* -- Recording setup ----------------------------------------------------- */
2586

2587
/* Setup recording for a root trace started by a hot loop. */
2588
static const BCIns *rec_setup_root(jit_State *J)
7,637✔
2589
{
2590
  /* Determine the next PC and the bytecode range for the loop. */
2591
  const BCIns *pcj, *pc = J->pc;
7,637✔
2592
  BCIns ins = *pc;
7,637✔
2593
  BCReg ra = bc_a(ins);
7,637✔
2594
  switch (bc_op(ins)) {
7,637✔
2595
  case BC_FORL:
4,453✔
2596
    J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
4,453✔
2597
    pc += 1+bc_j(ins);
4,453✔
2598
    J->bc_min = pc;
4,453✔
2599
    break;
4,453✔
2600
  case BC_ITERL:
43✔
2601
    lj_assertJ(bc_op(pc[-1]) == BC_ITERC, "no ITERC before ITERL");
43✔
2602
    J->maxslot = ra + bc_b(pc[-1]) - 1;
43✔
2603
    J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
43✔
2604
    pc += 1+bc_j(ins);
43✔
2605
    lj_assertJ(bc_op(pc[-1]) == BC_JMP, "ITERL does not point to JMP+1");
43✔
2606
    J->bc_min = pc;
43✔
2607
    break;
43✔
2608
  case BC_LOOP:
1,174✔
2609
    /* Only check BC range for real loops, but not for "repeat until true". */
2610
    pcj = pc + bc_j(ins);
1,174✔
2611
    ins = *pcj;
1,174✔
2612
    if (bc_op(ins) == BC_JMP && bc_j(ins) < 0) {
1,174✔
2613
      J->bc_min = pcj+1 + bc_j(ins);
1,171✔
2614
      J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
1,171✔
2615
    }
2616
    J->maxslot = ra;
1,174✔
2617
    pc++;
1,174✔
2618
    break;
1,174✔
2619
  case BC_RET:
1✔
2620
  case BC_RET0:
2621
  case BC_RET1:
2622
    /* No bytecode range check for down-recursive root traces. */
2623
    J->maxslot = ra + bc_d(ins) - 1;
1✔
2624
    break;
1✔
2625
  case BC_FUNCF:
1,864✔
2626
    /* No bytecode range check for root traces started by a hot call. */
2627
    J->maxslot = J->pt->numparams;
1,864✔
2628
    pc++;
1,864✔
2629
    break;
1,864✔
2630
  case BC_CALLM:
102✔
2631
  case BC_CALL:
2632
  case BC_ITERC:
2633
    /* No bytecode range check for stitched traces. */
2634
    pc++;
102✔
2635
    break;
102✔
2636
  default:
2637
    lj_assertJ(0, "bad root trace start bytecode %d", bc_op(ins));
2638
    break;
2639
  }
2640
  return pc;
7,637✔
2641
}
2642

2643
/* Setup for recording a new trace. */
2644
void lj_record_setup(jit_State *J)
22,117✔
2645
{
2646
  uint32_t i;
22,117✔
2647

2648
  /* Initialize state related to current trace. */
2649
  memset(J->slot, 0, sizeof(J->slot));
22,117✔
2650
  memset(J->chain, 0, sizeof(J->chain));
22,117✔
2651
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2652
  memset(J->rbchash, 0, sizeof(J->rbchash));
2653
#endif
2654
  memset(J->bpropcache, 0, sizeof(J->bpropcache));
22,117✔
2655
  J->scev.idx = REF_NIL;
22,117✔
2656
  setmref(J->scev.pc, NULL);
22,117✔
2657

2658
  J->baseslot = 1+LJ_FR2;  /* Invoking function is at base[-1-LJ_FR2]. */
22,117✔
2659
  J->base = J->slot + J->baseslot;
22,117✔
2660
  J->maxslot = 0;
22,117✔
2661
  J->framedepth = 0;
22,117✔
2662
  J->retdepth = 0;
22,117✔
2663

2664
  J->instunroll = J->param[JIT_P_instunroll];
22,117✔
2665
  J->loopunroll = J->param[JIT_P_loopunroll];
22,117✔
2666
  J->tailcalled = 0;
22,117✔
2667
  J->loopref = 0;
22,117✔
2668

2669
  J->bc_min = NULL;  /* Means no limit. */
22,117✔
2670
  J->bc_extent = ~(MSize)0;
22,117✔
2671

2672
  /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2673
  emitir_raw(IRT(IR_BASE, IRT_PGC), J->parent, J->exitno);
22,117✔
2674
  for (i = 0; i <= 2; i++) {
110,585✔
2675
    IRIns *ir = IR(REF_NIL-i);
66,351✔
2676
    ir->i = 0;
66,351✔
2677
    ir->t.irt = (uint8_t)(IRT_NIL+i);
66,351✔
2678
    ir->o = IR_KPRI;
66,351✔
2679
    ir->prev = 0;
66,351✔
2680
  }
2681
  J->cur.nk = REF_TRUE;
22,117✔
2682

2683
  J->startpc = J->pc;
22,117✔
2684
  setmref(J->cur.startpc, J->pc);
22,117✔
2685
  if (J->parent) {  /* Side trace. */
22,117✔
2686
    GCtrace *T = traceref(J, J->parent);
14,480✔
2687
    TraceNo root = T->root ? T->root : J->parent;
14,480✔
2688
    J->cur.root = (uint16_t)root;
14,480✔
2689
    J->cur.startins = BCINS_AD(BC_JMP, 0, 0);
14,480✔
2690
    /* Check whether we could at least potentially form an extra loop. */
2691
    if (J->exitno == 0 && T->snap[0].nent == 0) {
14,480✔
2692
      /* We can narrow a FORL for some side traces, too. */
2693
      if (J->pc > proto_bc(J->pt) && bc_op(J->pc[-1]) == BC_JFORI &&
2,093✔
2694
          bc_d(J->pc[bc_j(J->pc[-1])-1]) == root) {
191✔
2695
        lj_snap_add(J);
191✔
2696
        rec_for_loop(J, J->pc-1, &J->scev, 1);
191✔
2697
        goto sidecheck;
191✔
2698
      }
2699
    } else {
2700
      J->startpc = NULL;  /* Prevent forming an extra loop. */
12,387✔
2701
    }
2702
    lj_snap_replay(J, T);
14,289✔
2703
  sidecheck:
14,480✔
2704
    if (traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] ||
14,480✔
2705
        T->snap[J->exitno].count >= J->param[JIT_P_hotexit] +
14,479✔
2706
                                    J->param[JIT_P_tryside]) {
14,479✔
2707
      lj_record_stop(J, LJ_TRLINK_INTERP, 0);
421✔
2708
    }
2709
  } else {  /* Root trace. */
2710
    J->cur.root = 0;
7,637✔
2711
    J->cur.startins = *J->pc;
7,637✔
2712
    J->pc = rec_setup_root(J);
7,637✔
2713
    /* Note: the loop instruction itself is recorded at the end and not
2714
    ** at the start! So snapshot #0 needs to point to the *next* instruction.
2715
    */
2716
    lj_snap_add(J);
7,637✔
2717
    if (bc_op(J->cur.startins) == BC_FORL)
7,637✔
2718
      rec_for_loop(J, J->pc-1, &J->scev, 1);
4,453✔
2719
    else if (bc_op(J->cur.startins) == BC_ITERC)
3,184✔
2720
      J->startpc = NULL;
6✔
2721
    if (1 + J->pt->framesize >= LJ_MAX_JSLOTS)
7,637✔
2722
      lj_trace_err(J, LJ_TRERR_STACKOV);
1✔
2723
  }
2724
#if LJ_HASPROFILE
2725
  J->prev_pt = NULL;
22,116✔
2726
  J->prev_line = -1;
22,116✔
2727
#endif
2728
#ifdef LUAJIT_ENABLE_CHECKHOOK
2729
  /* Regularly check for instruction/line hooks from compiled code and
2730
  ** exit to the interpreter if the hooks are set.
2731
  **
2732
  ** This is a compile-time option and disabled by default, since the
2733
  ** hook checks may be quite expensive in tight loops.
2734
  **
2735
  ** Note this is only useful if hooks are *not* set most of the time.
2736
  ** Use this only if you want to *asynchronously* interrupt the execution.
2737
  **
2738
  ** You can set the instruction hook via lua_sethook() with a count of 1
2739
  ** from a signal handler or another native thread. Please have a look
2740
  ** at the first few functions in luajit.c for an example (Ctrl-C handler).
2741
  */
2742
  {
2743
    TRef tr = emitir(IRT(IR_XLOAD, IRT_U8),
2744
                     lj_ir_kptr(J, &J2G(J)->hookmask), IRXLOAD_VOLATILE);
2745
    tr = emitir(IRTI(IR_BAND), tr, lj_ir_kint(J, (LUA_MASKLINE|LUA_MASKCOUNT)));
2746
    emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, 0));
2747
  }
2748
#endif
2749
}
22,116✔
2750

2751
#undef IR
2752
#undef emitir_raw
2753
#undef emitir
2754

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