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

tarantool / luajit / 6867995106

14 Nov 2023 06:27PM UTC coverage: 88.505% (+0.004%) from 88.501%
6867995106

push

github

igormunkin
tools: add cli flag to run profile dump parsers

It is really inconvenient to use a standalone shell script to parse
binary dumps from profilers. That is why this commit introduces a
CLI flag for tools in the LuaJIT, so now it is possible to parse
a memprof dump as simple as:
```
luajit -tm memprof.bin
luajit -tm --leak-only memprof.bin
```

And the sysprof too:
```
luajit -ts sysprof.bin
```

The scripts `luajit-parse-memprof` and `luajit-parse-sysprof`
are purged as a result of these changes.

Resolves tarantool/tarantool#5688

Reviewed-by: Sergey Kaplun <skaplun@tarantool.org>
Reviewed-by: Sergey Bronnikov <sergeyb@tarantool.org>
Signed-off-by: Igor Munkin <imun@tarantool.org>

5369 of 5980 branches covered (0.0%)

Branch coverage included in aggregate %.

19 of 25 new or added lines in 1 file covered. (76.0%)

9 existing lines in 4 files now uncovered.

20586 of 23346 relevant lines covered (88.18%)

2757380.68 hits per line

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

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

6
#define lj_record_c
7
#define LUA_CORE
8

9
#include "lj_obj.h"
10

11
#if LJ_HASJIT
12

13
#include "lj_err.h"
14
#include "lj_str.h"
15
#include "lj_tab.h"
16
#include "lj_meta.h"
17
#include "lj_frame.h"
18
#if LJ_HASFFI
19
#include "lj_ctype.h"
20
#endif
21
#include "lj_bc.h"
22
#include "lj_ff.h"
23
#if LJ_HASPROFILE
24
#include "lj_debug.h"
25
#endif
26
#include "lj_ir.h"
27
#include "lj_jit.h"
28
#include "lj_ircall.h"
29
#include "lj_iropt.h"
30
#include "lj_trace.h"
31
#include "lj_record.h"
32
#include "lj_ffrecord.h"
33
#include "lj_snap.h"
34
#include "lj_dispatch.h"
35
#include "lj_vm.h"
36

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

642
#if LJ_HASPROFILE
643

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

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

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

685
#endif
686

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1581
/* -- Upvalue access ------------------------------------------------------ */
1582

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

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

1682
/* -- Record calls to Lua functions --------------------------------------- */
1683

1684
/* Check unroll limits for calls. */
1685
static void check_call_unroll(jit_State *J, TraceNo lnk)
12,523✔
1686
{
1687
  cTValue *frame = J->L->base - 1;
12,523✔
1688
  void *pc = mref(frame_func(frame)->l.pc, void);
12,523✔
1689
  int32_t depth = J->framedepth;
12,523✔
1690
  int32_t count = 0;
12,523✔
1691
  if ((J->pt->flags & PROTO_VARARG)) depth--;  /* Vararg frame still missing. */
12,523✔
1692
  for (; depth > 0; depth--) {  /* Count frames with same prototype. */
35,207✔
1693
    if (frame_iscont(frame)) depth--;
22,684✔
1694
    frame = frame_prev(frame);
22,684✔
1695
    if (mref(frame_func(frame)->l.pc, void) == pc)
22,684✔
1696
      count++;
785✔
1697
  }
1698
  if (J->pc == J->startpc) {
12,523✔
1699
    if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
78✔
1700
      J->pc++;
20✔
1701
      if (J->framedepth + J->retdepth == 0)
20✔
1702
        lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno);  /* Tail-rec. */
4✔
1703
      else
1704
        lj_record_stop(J, LJ_TRLINK_UPREC, J->cur.traceno);  /* Up-recursion. */
16✔
1705
    }
1706
  } else {
1707
    if (count > J->param[JIT_P_callunroll]) {
12,445✔
1708
      if (lnk) {  /* Possible tail- or up-recursion. */
63✔
1709
        lj_trace_flush(J, lnk);  /* Flush trace that only returns. */
13✔
1710
        /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
1711
        hotcount_set(J2GG(J), J->pc+1, LJ_PRNG_BITS(J, 4));
13✔
1712
      }
1713
      lj_trace_err(J, LJ_TRERR_CUNROLL);
63✔
1714
    }
1715
  }
1716
}
12,460✔
1717

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

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

1758
/* Record entry to a Lua function. */
1759
static void rec_func_lua(jit_State *J)
2,557✔
1760
{
1761
  rec_func_setup(J);
2,557✔
1762
  check_call_unroll(J, 0);
2,557✔
1763
}
2,507✔
1764

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

1786
/* -- Vararg handling ----------------------------------------------------- */
1787

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

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

1907
/* -- Record allocations -------------------------------------------------- */
1908

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

1924
/* -- Concatenation ------------------------------------------------------- */
1925

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

1972
/* -- Record bytecode ops ------------------------------------------------- */
1973

1974
/* Prepare for comparison. */
1975
static void rec_comp_prep(jit_State *J)
11,419✔
1976
{
1977
  /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
1978
  if (J->cur.nsnap == 1 && J->cur.snap[0].ref == J->cur.nins)
11,419✔
1979
    emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
65✔
1980
  lj_snap_add(J);
11,419✔
1981
}
11,419✔
1982

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

2004
/* Record the next bytecode instruction (_before_ it's executed). */
2005
void lj_record_ins(jit_State *J)
278,273✔
2006
{
2007
  cTValue *lbase;
278,273✔
2008
  RecordIndex ix;
278,273✔
2009
  const BCIns *pc;
278,273✔
2010
  BCIns ins;
278,273✔
2011
  BCOp op;
278,273✔
2012
  TRef ra, rb, rc;
278,273✔
2013

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

2061
  /* Need snapshot before recording next bytecode (e.g. after a store). */
2062
  if (J->needsnap) {
278,270✔
2063
    J->needsnap = 0;
65,961✔
2064
    if (J->pt) lj_snap_purge(J);
65,961✔
2065
    lj_snap_add(J);
65,961✔
2066
    J->mergesnap = 1;
65,961✔
2067
  }
2068

2069
  /* Skip some bytecodes. */
2070
  if (LJ_UNLIKELY(J->bcskip > 0)) {
278,270✔
2071
    J->bcskip--;
16✔
2072
    return;
16✔
2073
  }
2074

2075
  /* Record only closed loops for root traces. */
2076
  pc = J->pc;
278,254✔
2077
  if (J->framedepth == 0 &&
278,254✔
2078
     (MSize)((char *)pc - (char *)J->bc_min) >= J->bc_extent)
193,095✔
2079
    lj_trace_err(J, LJ_TRERR_LLEAVE);
485✔
2080

2081
#ifdef LUA_USE_ASSERT
2082
  rec_check_slots(J);
2083
  rec_check_ir(J);
2084
#endif
2085

2086
#if LJ_HASPROFILE
2087
  rec_profile_ins(J, pc);
277,769✔
2088
#endif
2089

2090
  /* Keep a copy of the runtime values of var/num/str operands. */
2091
#define rav        (&ix.valv)
2092
#define rbv        (&ix.tabv)
2093
#define rcv        (&ix.keyv)
2094

2095
  lbase = J->L->base;
277,769✔
2096
  ins = *pc;
277,769✔
2097
  op = bc_op(ins);
277,769✔
2098
  ra = bc_a(ins);
277,769✔
2099
  ix.val = 0;
277,769✔
2100
  switch (bcmode_a(op)) {
277,769✔
2101
  case BCMvar:
65,295✔
2102
    copyTV(J->L, rav, &lbase[ra]); ix.val = ra = getslot(J, ra); break;
65,295✔
2103
  default: break;  /* Handled later. */
2104
  }
2105
  rb = bc_b(ins);
277,769✔
2106
  rc = bc_c(ins);
277,769✔
2107
  switch (bcmode_b(op)) {
277,769✔
2108
  case BCMnone: rb = 0; rc = bc_d(ins); break;  /* Upgrade rc to 'rd'. */
95,641✔
2109
  case BCMvar:
165,072✔
2110
    copyTV(J->L, rbv, &lbase[rb]); ix.tab = rb = getslot(J, rb); break;
165,072✔
2111
  default: break;  /* Handled later. */
2112
  }
2113
  switch (bcmode_c(op)) {
277,769✔
2114
  case BCMvar:
68,362✔
2115
    copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
68,362✔
2116
  case BCMpri: setpriV(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
8,782✔
2117
  case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
5,655✔
2118
    copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
5,655✔
2119
    lj_ir_knumint(J, numV(tv)); } break;
5,655✔
2120
  case BCMstr: { GCstr *s = gco2str(proto_kgc(J->pt, ~(ptrdiff_t)rc));
112,171✔
2121
    setstrV(J->L, rcv, s); ix.key = rc = lj_ir_kstr(J, s); } break;
112,171✔
2122
  default: break;  /* Handled later. */
2123
  }
2124

2125
  switch (op) {
277,769✔
2126

2127
  /* -- Comparison ops ---------------------------------------------------- */
2128

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

2178
  case BC_ISEQV: case BC_ISNEV:
8,893✔
2179
  case BC_ISEQS: case BC_ISNES:
2180
  case BC_ISEQN: case BC_ISNEN:
2181
  case BC_ISEQP: case BC_ISNEP:
2182
#if LJ_HASFFI
2183
    if (tref_iscdata(ra) || tref_iscdata(rc)) {
8,893✔
2184
      rec_mm_comp_cdata(J, &ix, op, MM_eq);
46✔
2185
      break;
46✔
2186
    }
2187
#endif
2188
    /* Emit nothing for two non-table, non-udata consts. */
2189
    if (!(tref_isk2(ra, rc) && !(tref_istab(ra) || tref_isudata(ra)))) {
8,847✔
2190
      int diff;
7,380✔
2191
      rec_comp_prep(J);
7,380✔
2192
      diff = lj_record_objcmp(J, ra, rc, rav, rcv);
7,380✔
2193
      if (diff == 2 || !(tref_istab(ra) || tref_isudata(ra)))
7,380✔
2194
        rec_comp_fixup(J, J->pc, ((int)op & 1) == !diff);
7,326✔
2195
      else if (diff == 1)  /* Only check __eq if different, but same type. */
54✔
2196
        rec_mm_equal(J, &ix, (int)op);
10✔
2197
    }
2198
    break;
2199

2200
  /* -- Unary test and copy ops ------------------------------------------- */
2201

2202
  case BC_ISTC: case BC_ISFC:
172✔
2203
    if ((op & 1) == tref_istruecond(rc))
172✔
2204
      rc = 0;  /* Don't store if condition is not true. */
154✔
2205
    /* fallthrough */
2206
  case BC_IST: case BC_ISF:  /* Type specialization suffices. */
2207
    if (bc_a(pc[1]) < J->maxslot)
674✔
2208
      J->maxslot = bc_a(pc[1]);  /* Shrink used slots. */
160✔
2209
    break;
2210

2211
  case BC_ISTYPE: case BC_ISNUM:
2212
    /* These coercions need to correspond with lj_meta_istype(). */
2213
    if (LJ_DUALNUM && rc == ~LJ_TNUMX+1)
16✔
2214
      ra = lj_opt_narrow_toint(J, ra);
2215
    else if (rc == ~LJ_TNUMX+2)
16✔
2216
      ra = lj_ir_tonum(J, ra);
2✔
2217
    else if (rc == ~LJ_TSTR+1)
14✔
2218
      ra = lj_ir_tostr(J, ra);
7✔
2219
    /* else: type specialization suffices. */
2220
    J->base[bc_a(ins)] = ra;
16✔
2221
    break;
16✔
2222

2223
  /* -- Unary ops --------------------------------------------------------- */
2224

2225
  case BC_NOT:
5✔
2226
    /* Type specialization already forces const result. */
2227
    rc = tref_istruecond(rc) ? TREF_FALSE : TREF_TRUE;
5✔
2228
    break;
2229

2230
  case BC_LEN:
50✔
2231
    if (tref_isstr(rc))
50✔
2232
      rc = emitir(IRTI(IR_FLOAD), rc, IRFL_STR_LEN);
8✔
2233
    else if (!LJ_52 && tref_istab(rc))
42✔
2234
      rc = lj_ir_call(J, IRCALL_lj_tab_len, rc);
41✔
2235
    else
2236
      rc = rec_mm_len(J, rc, rcv);
1✔
2237
    break;
2238

2239
  /* -- Arithmetic ops ---------------------------------------------------- */
2240

2241
  case BC_UNM:
13✔
2242
    if (tref_isnumber_str(rc)) {
13✔
2243
      rc = lj_opt_narrow_unm(J, rc, rcv);
12✔
2244
    } else {
2245
      ix.tab = rc;
1✔
2246
      copyTV(J->L, &ix.tabv, rcv);
1✔
2247
      rc = rec_mm_arith(J, &ix, MM_unm);
1✔
2248
    }
2249
    break;
2250

2251
  case BC_ADDNV: case BC_SUBNV: case BC_MULNV: case BC_DIVNV: case BC_MODNV:
2,457✔
2252
    /* Swap rb/rc and rbv/rcv. rav is temp. */
2253
    ix.tab = rc; ix.key = rc = rb; rb = ix.tab;
2,457✔
2254
    copyTV(J->L, rav, rbv);
2,457✔
2255
    copyTV(J->L, rbv, rcv);
2,457✔
2256
    copyTV(J->L, rcv, rav);
2,457✔
2257
    if (op == BC_MODNV)
2,457✔
2258
      goto recmod;
17✔
2259
    /* fallthrough */
2260
  case BC_ADDVN: case BC_SUBVN: case BC_MULVN: case BC_DIVVN:
2261
  case BC_ADDVV: case BC_SUBVV: case BC_MULVV: case BC_DIVVV: {
2262
    MMS mm = bcmode_mm(op);
50,814✔
2263
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
50,814✔
2264
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv,
50,668✔
2265
                               (int)mm - (int)MM_add + (int)IR_ADD);
50,668✔
2266
    else
2267
      rc = rec_mm_arith(J, &ix, mm);
146✔
2268
    break;
2269
    }
2270

2271
  case BC_MODVN: case BC_MODVV:
2272
  recmod:
112✔
2273
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
112✔
2274
      rc = lj_opt_narrow_mod(J, rb, rc, rbv, rcv);
109✔
2275
    else
2276
      rc = rec_mm_arith(J, &ix, MM_mod);
3✔
2277
    break;
2278

2279
  case BC_POW:
242✔
2280
    if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
242✔
2281
      rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv, IR_POW);
239✔
2282
    else
2283
      rc = rec_mm_arith(J, &ix, MM_pow);
3✔
2284
    break;
2285

2286
  /* -- Miscellaneous ops ------------------------------------------------- */
2287

2288
  case BC_CAT:
298✔
2289
    rc = rec_cat(J, rb, rc);
298✔
2290
    break;
298✔
2291

2292
  /* -- Constant and move ops --------------------------------------------- */
2293

2294
  case BC_MOV:
11,138✔
2295
    /* Clear gap of method call to avoid resurrecting previous refs. */
2296
    if (ra > J->maxslot) {
11,138✔
2297
#if LJ_FR2
2298
      memset(J->base + J->maxslot, 0, (ra - J->maxslot) * sizeof(TRef));
6,389✔
2299
#else
2300
      J->base[ra-1] = 0;
2301
#endif
2302
    }
2303
    break;
2304
  case BC_KSTR: case BC_KNUM: case BC_KPRI:
2305
    break;
2306
  case BC_KSHORT:
7,330✔
2307
    rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
7,330✔
2308
    break;
7,330✔
2309
  case BC_KNIL:
11✔
2310
    if (LJ_FR2 && ra > J->maxslot)
11✔
2311
      J->base[ra-1] = 0;
1✔
2312
    while (ra <= rc)
613✔
2313
      J->base[ra++] = TREF_NIL;
602✔
2314
    if (rc >= J->maxslot) J->maxslot = rc+1;
11✔
2315
    break;
2316
#if LJ_HASFFI
2317
  case BC_KCDATA:
30✔
2318
    rc = lj_ir_kgc(J, proto_kgc(J->pt, ~(ptrdiff_t)rc), IRT_CDATA);
30✔
2319
    break;
30✔
2320
#endif
2321

2322
  /* -- Upvalue and function ops ------------------------------------------ */
2323

2324
  case BC_UGET:
16,238✔
2325
    rc = rec_upvalue(J, rc, 0);
16,238✔
2326
    break;
16,238✔
2327
  case BC_USETV: case BC_USETS: case BC_USETN: case BC_USETP:
170✔
2328
    rec_upvalue(J, ra, rc);
170✔
2329
    break;
170✔
2330

2331
  /* -- Table ops --------------------------------------------------------- */
2332

2333
  case BC_GGET: case BC_GSET:
2,400✔
2334
    settabV(J->L, &ix.tabv, tabref(J->fn->l.env));
2,400✔
2335
    ix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), getcurrf(J), IRFL_FUNC_ENV);
2,400✔
2336
    ix.idxchain = LJ_MAX_IDXCHAIN;
2,400✔
2337
    rc = lj_record_idx(J, &ix);
2,400✔
2338
    break;
2,400✔
2339

2340
  case BC_TGETB: case BC_TSETB:
463✔
2341
    setintV(&ix.keyv, (int32_t)rc);
463✔
2342
    ix.key = lj_ir_kint(J, (int32_t)rc);
463✔
2343
    /* fallthrough */
2344
  case BC_TGETV: case BC_TGETS: case BC_TSETV: case BC_TSETS:
113,878✔
2345
    ix.idxchain = LJ_MAX_IDXCHAIN;
113,878✔
2346
    rc = lj_record_idx(J, &ix);
113,878✔
2347
    break;
113,878✔
2348
  case BC_TGETR: case BC_TSETR:
26✔
2349
    ix.idxchain = 0;
26✔
2350
    rc = lj_record_idx(J, &ix);
26✔
2351
    break;
26✔
2352

2353
  case BC_TSETM:
5✔
2354
    rec_tsetm(J, ra, (BCReg)(J->L->top - J->L->base), (int32_t)rcv->u32.lo);
5✔
2355
    J->maxslot = ra;  /* The table slot at ra-1 is the highest used slot. */
5✔
2356
    break;
5✔
2357

2358
  case BC_TNEW:
2359
    rc = rec_tnew(J, rc);
469✔
2360
    break;
469✔
2361
  case BC_TDUP:
173✔
2362
    rc = emitir(IRTG(IR_TDUP, IRT_TAB),
173✔
2363
                lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
2364
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2365
    J->rbchash[(rc & (RBCHASH_SLOTS-1))].ref = tref_ref(rc);
2366
    setmref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pc, pc);
2367
    setgcref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
2368
#endif
2369
    break;
173✔
2370

2371
  /* -- Calls and vararg handling ----------------------------------------- */
2372

2373
  case BC_ITERC:
111✔
2374
    J->base[ra] = getslot(J, ra-3);
111✔
2375
    J->base[ra+1+LJ_FR2] = getslot(J, ra-2);
111✔
2376
    J->base[ra+2+LJ_FR2] = getslot(J, ra-1);
111✔
2377
    { /* Do the actual copy now because lj_record_call needs the values. */
2378
      TValue *b = &J->L->base[ra];
111✔
2379
      copyTV(J->L, b, b-3);
111✔
2380
      copyTV(J->L, b+1+LJ_FR2, b-2);
111✔
2381
      copyTV(J->L, b+2+LJ_FR2, b-1);
111✔
2382
    }
2383
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
111✔
2384
    break;
111✔
2385

2386
  /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
2387
  case BC_CALLM:
2,561✔
2388
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
2,561✔
2389
    /* fallthrough */
2390
  case BC_CALL:
16,609✔
2391
    lj_record_call(J, ra, (ptrdiff_t)rc-1);
16,609✔
2392
    break;
16,609✔
2393

2394
  case BC_CALLMT:
6✔
2395
    rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
6✔
2396
    /* fallthrough */
2397
  case BC_CALLT:
1,925✔
2398
    lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
1,925✔
2399
    break;
1,925✔
2400

2401
  case BC_VARG:
38✔
2402
    rec_varg(J, ra, (ptrdiff_t)rb-1);
38✔
2403
    break;
38✔
2404

2405
  /* -- Returns ----------------------------------------------------------- */
2406

2407
  case BC_RETM:
26✔
2408
    /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
2409
    rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
26✔
2410
    /* fallthrough */
2411
  case BC_RET: case BC_RET0: case BC_RET1:
13,730✔
2412
#if LJ_HASPROFILE
2413
    rec_profile_ret(J);
13,730✔
2414
#endif
2415
    lj_record_ret(J, ra, (ptrdiff_t)rc-1);
13,730✔
2416
    break;
13,730✔
2417

2418
  /* -- Loops and branches ------------------------------------------------ */
2419

2420
  case BC_FORI:
151✔
2421
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)
151✔
2422
      J->loopref = J->cur.nins;
151✔
2423
    break;
2424
  case BC_JFORI:
71✔
2425
    lj_assertJ(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL,
71✔
2426
               "JFORI does not point to JFORL");
2427
    if (rec_for(J, pc, 0) != LOOPEV_LEAVE)  /* Link to existing loop. */
71✔
2428
      lj_record_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
68✔
2429
    /* Continue tracing if the loop is not entered. */
2430
    break;
2431

2432
  case BC_FORL:
2,130✔
2433
    rec_loop_interp(J, pc, rec_for(J, pc+((ptrdiff_t)rc-BCBIAS_J), 1));
2,130✔
2434
    break;
2,130✔
2435
  case BC_ITERL:
43✔
2436
    rec_loop_interp(J, pc, rec_iterl(J, *pc));
43✔
2437
    break;
43✔
2438
  case BC_LOOP:
93✔
2439
    rec_loop_interp(J, pc, rec_loop(J, ra));
93✔
2440
    break;
93✔
2441

2442
  case BC_JFORL:
327✔
2443
    rec_loop_jit(J, rc, rec_for(J, pc+bc_j(traceref(J, rc)->startins), 1));
327✔
2444
    break;
327✔
2445
  case BC_JITERL:
66✔
2446
    rec_loop_jit(J, rc, rec_iterl(J, traceref(J, rc)->startins));
66✔
2447
    break;
66✔
2448
  case BC_JLOOP:
1,441✔
2449
    rec_loop_jit(J, rc, rec_loop(J, ra));
1,441✔
2450
    break;
1,441✔
2451

2452
  case BC_IFORL:
×
2453
  case BC_IITERL:
2454
  case BC_ILOOP:
2455
  case BC_IFUNCF:
2456
  case BC_IFUNCV:
2457
    lj_trace_err(J, LJ_TRERR_BLACKL);
×
2458
    break;
1,577✔
2459

2460
  case BC_JMP:
1,577✔
2461
    if (ra < J->maxslot)
1,577✔
2462
      J->maxslot = ra;  /* Shrink used slots. */
1,019✔
2463
    break;
2464

2465
  /* -- Function headers -------------------------------------------------- */
2466

2467
  case BC_FUNCF:
2468
    rec_func_lua(J);
2,456✔
2469
    break;
2470
  case BC_JFUNCF:
10,750✔
2471
    rec_func_jit(J, rc);
10,750✔
2472
    break;
10,750✔
2473

2474
  case BC_FUNCV:
101✔
2475
    rec_func_vararg(J);
101✔
2476
    rec_func_lua(J);
101✔
2477
    break;
2478
  case BC_JFUNCV:
2479
    /* Cannot happen. No hotcall counting for varag funcs. */
2480
    lj_assertJ(0, "unsupported vararg hotcall");
2481
    break;
2482

2483
  case BC_FUNCC:
1,565✔
2484
  case BC_FUNCCW:
2485
    lj_ffrecord_func(J);
1,565✔
2486
    break;
1,565✔
2487

2488
  default:
4,541✔
2489
    if (op >= BC__MAX) {
4,541✔
2490
      lj_ffrecord_func(J);
4,541✔
2491
      break;
4,541✔
2492
    }
2493
    /* fallthrough */
2494
  case BC_ITERN:
2495
  case BC_ISNEXT:
2496
  case BC_UCLO:
2497
  case BC_FNEW:
2498
    setintV(&J->errinfo, (int32_t)op);
46✔
2499
    lj_trace_err_info(J, LJ_TRERR_NYIBC);
46✔
2500
    break;
277,219✔
2501
  }
2502

2503
  /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
2504
  if (bcmode_a(op) == BCMdst && rc) {
277,219✔
2505
    J->base[ra] = rc;
153,395✔
2506
    if (ra >= J->maxslot) {
153,395✔
2507
#if LJ_FR2
2508
      if (ra > J->maxslot) J->base[ra-1] = 0;
53,785✔
2509
#endif
2510
      J->maxslot = ra+1;
53,785✔
2511
    }
2512
  }
2513

2514
#undef rav
2515
#undef rbv
2516
#undef rcv
2517

2518
  /* Limit the number of recorded IR instructions and constants. */
2519
  if (J->cur.nins > REF_FIRST+(IRRef)J->param[JIT_P_maxrecord] ||
277,219✔
2520
      J->cur.nk < REF_BIAS-(IRRef)J->param[JIT_P_maxirconst])
277,219✔
2521
    lj_trace_err(J, LJ_TRERR_TRACEOV);
1✔
2522
}
2523

2524
/* -- Recording setup ----------------------------------------------------- */
2525

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

2582
/* Setup for recording a new trace. */
2583
void lj_record_setup(jit_State *J)
7,028✔
2584
{
2585
  uint32_t i;
7,028✔
2586

2587
  /* Initialize state related to current trace. */
2588
  memset(J->slot, 0, sizeof(J->slot));
7,028✔
2589
  memset(J->chain, 0, sizeof(J->chain));
7,028✔
2590
#ifdef LUAJIT_ENABLE_TABLE_BUMP
2591
  memset(J->rbchash, 0, sizeof(J->rbchash));
2592
#endif
2593
  memset(J->bpropcache, 0, sizeof(J->bpropcache));
7,028✔
2594
  J->scev.idx = REF_NIL;
7,028✔
2595
  setmref(J->scev.pc, NULL);
7,028✔
2596

2597
  J->baseslot = 1+LJ_FR2;  /* Invoking function is at base[-1-LJ_FR2]. */
7,028✔
2598
  J->base = J->slot + J->baseslot;
7,028✔
2599
  J->maxslot = 0;
7,028✔
2600
  J->framedepth = 0;
7,028✔
2601
  J->retdepth = 0;
7,028✔
2602

2603
  J->instunroll = J->param[JIT_P_instunroll];
7,028✔
2604
  J->loopunroll = J->param[JIT_P_loopunroll];
7,028✔
2605
  J->tailcalled = 0;
7,028✔
2606
  J->loopref = 0;
7,028✔
2607

2608
  J->bc_min = NULL;  /* Means no limit. */
7,028✔
2609
  J->bc_extent = ~(MSize)0;
7,028✔
2610

2611
  /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2612
  emitir_raw(IRT(IR_BASE, IRT_PGC), J->parent, J->exitno);
7,028✔
2613
  for (i = 0; i <= 2; i++) {
35,140✔
2614
    IRIns *ir = IR(REF_NIL-i);
21,084✔
2615
    ir->i = 0;
21,084✔
2616
    ir->t.irt = (uint8_t)(IRT_NIL+i);
21,084✔
2617
    ir->o = IR_KPRI;
21,084✔
2618
    ir->prev = 0;
21,084✔
2619
  }
2620
  J->cur.nk = REF_TRUE;
7,028✔
2621

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

2690
#undef IR
2691
#undef emitir_raw
2692
#undef emitir
2693

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

© 2026 Coveralls, Inc