src/lj_opt_narrow.c - luajit-2.0-src

Data types defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** NARROW: Narrowing of numbers to integers (double to int32_t).
  3. ** STRIPOV: Stripping of overflow checks.
  4. ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
  5. */

  6. #define lj_opt_narrow_c
  7. #define LUA_CORE

  8. #include "lj_obj.h"

  9. #if LJ_HASJIT

  10. #include "lj_bc.h"
  11. #include "lj_ir.h"
  12. #include "lj_jit.h"
  13. #include "lj_iropt.h"
  14. #include "lj_trace.h"
  15. #include "lj_vm.h"
  16. #include "lj_strscan.h"

  17. /* Rationale for narrowing optimizations:
  18. **
  19. ** Lua has only a single number type and this is a FP double by default.
  20. ** Narrowing doubles to integers does not pay off for the interpreter on a
  21. ** current-generation x86/x64 machine. Most FP operations need the same
  22. ** amount of execution resources as their integer counterparts, except
  23. ** with slightly longer latencies. Longer latencies are a non-issue for
  24. ** the interpreter, since they are usually hidden by other overhead.
  25. **
  26. ** The total CPU execution bandwidth is the sum of the bandwidth of the FP
  27. ** and the integer units, because they execute in parallel. The FP units
  28. ** have an equal or higher bandwidth than the integer units. Not using
  29. ** them means losing execution bandwidth. Moving work away from them to
  30. ** the already quite busy integer units is a losing proposition.
  31. **
  32. ** The situation for JIT-compiled code is a bit different: the higher code
  33. ** density makes the extra latencies much more visible. Tight loops expose
  34. ** the latencies for updating the induction variables. Array indexing
  35. ** requires narrowing conversions with high latencies and additional
  36. ** guards (to check that the index is really an integer). And many common
  37. ** optimizations only work on integers.
  38. **
  39. ** One solution would be speculative, eager narrowing of all number loads.
  40. ** This causes many problems, like losing -0 or the need to resolve type
  41. ** mismatches between traces. It also effectively forces the integer type
  42. ** to have overflow-checking semantics. This impedes many basic
  43. ** optimizations and requires adding overflow checks to all integer
  44. ** arithmetic operations (whereas FP arithmetics can do without).
  45. **
  46. ** Always replacing an FP op with an integer op plus an overflow check is
  47. ** counter-productive on a current-generation super-scalar CPU. Although
  48. ** the overflow check branches are highly predictable, they will clog the
  49. ** execution port for the branch unit and tie up reorder buffers. This is
  50. ** turning a pure data-flow dependency into a different data-flow
  51. ** dependency (with slightly lower latency) *plus* a control dependency.
  52. ** In general, you don't want to do this since latencies due to data-flow
  53. ** dependencies can be well hidden by out-of-order execution.
  54. **
  55. ** A better solution is to keep all numbers as FP values and only narrow
  56. ** when it's beneficial to do so. LuaJIT uses predictive narrowing for
  57. ** induction variables and demand-driven narrowing for index expressions,
  58. ** integer arguments and bit operations. Additionally it can eliminate or
  59. ** hoist most of the resulting overflow checks. Regular arithmetic
  60. ** computations are never narrowed to integers.
  61. **
  62. ** The integer type in the IR has convenient wrap-around semantics and
  63. ** ignores overflow. Extra operations have been added for
  64. ** overflow-checking arithmetic (ADDOV/SUBOV) instead of an extra type.
  65. ** Apart from reducing overall complexity of the compiler, this also
  66. ** nicely solves the problem where you want to apply algebraic
  67. ** simplifications to ADD, but not to ADDOV. And the x86/x64 assembler can
  68. ** use lea instead of an add for integer ADD, but not for ADDOV (lea does
  69. ** not affect the flags, but it helps to avoid register moves).
  70. **
  71. **
  72. ** All of the above has to be reconsidered for architectures with slow FP
  73. ** operations or without a hardware FPU. The dual-number mode of LuaJIT
  74. ** addresses this issue. Arithmetic operations are performed on integers
  75. ** as far as possible and overflow checks are added as needed.
  76. **
  77. ** This implies that narrowing for integer arguments and bit operations
  78. ** should also strip overflow checks, e.g. replace ADDOV with ADD. The
  79. ** original overflow guards are weak and can be eliminated by DCE, if
  80. ** there's no other use.
  81. **
  82. ** A slight twist is that it's usually beneficial to use overflow-checked
  83. ** integer arithmetics if all inputs are already integers. This is the only
  84. ** change that affects the single-number mode, too.
  85. */

  86. /* Some local macros to save typing. Undef'd at the end. */
  87. #define IR(ref)                        (&J->cur.ir[(ref)])
  88. #define fins                        (&J->fold.ins)

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

  91. #define emitir_raw(ot, a, b)        (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))

  92. /* -- Elimination of narrowing type conversions --------------------------- */

  93. /* Narrowing of index expressions and bit operations is demand-driven. The
  94. ** trace recorder emits a narrowing type conversion (CONV.int.num or TOBIT)
  95. ** in all of these cases (e.g. array indexing or string indexing). FOLD
  96. ** already takes care of eliminating simple redundant conversions like
  97. ** CONV.int.num(CONV.num.int(x)) ==> x.
  98. **
  99. ** But the surrounding code is FP-heavy and arithmetic operations are
  100. ** performed on FP numbers (for the single-number mode). Consider a common
  101. ** example such as 'x=t[i+1]', with 'i' already an integer (due to induction
  102. ** variable narrowing). The index expression would be recorded as
  103. **   CONV.int.num(ADD(CONV.num.int(i), 1))
  104. ** which is clearly suboptimal.
  105. **
  106. ** One can do better by recursively backpropagating the narrowing type
  107. ** conversion across FP arithmetic operations. This turns FP ops into
  108. ** their corresponding integer counterparts. Depending on the semantics of
  109. ** the conversion they also need to check for overflow. Currently only ADD
  110. ** and SUB are supported.
  111. **
  112. ** The above example can be rewritten as
  113. **   ADDOV(CONV.int.num(CONV.num.int(i)), 1)
  114. ** and then into ADDOV(i, 1) after folding of the conversions. The original
  115. ** FP ops remain in the IR and are eliminated by DCE since all references to
  116. ** them are gone.
  117. **
  118. ** [In dual-number mode the trace recorder already emits ADDOV etc., but
  119. ** this can be further reduced. See below.]
  120. **
  121. ** Special care has to be taken to avoid narrowing across an operation
  122. ** which is potentially operating on non-integral operands. One obvious
  123. ** case is when an expression contains a non-integral constant, but ends
  124. ** up as an integer index at runtime (like t[x+1.5] with x=0.5).
  125. **
  126. ** Operations with two non-constant operands illustrate a similar problem
  127. ** (like t[a+b] with a=1.5 and b=2.5). Backpropagation has to stop there,
  128. ** unless it can be proven that either operand is integral (e.g. by CSEing
  129. ** a previous conversion). As a not-so-obvious corollary this logic also
  130. ** applies for a whole expression tree (e.g. t[(a+1)+(b+1)]).
  131. **
  132. ** Correctness of the transformation is guaranteed by avoiding to expand
  133. ** the tree by adding more conversions than the one we would need to emit
  134. ** if not backpropagating. TOBIT employs a more optimistic rule, because
  135. ** the conversion has special semantics, designed to make the life of the
  136. ** compiler writer easier. ;-)
  137. **
  138. ** Using on-the-fly backpropagation of an expression tree doesn't work
  139. ** because it's unknown whether the transform is correct until the end.
  140. ** This either requires IR rollback and cache invalidation for every
  141. ** subtree or a two-pass algorithm. The former didn't work out too well,
  142. ** so the code now combines a recursive collector with a stack-based
  143. ** emitter.
  144. **
  145. ** [A recursive backpropagation algorithm with backtracking, employing
  146. ** skip-list lookup and round-robin caching, emitting stack operations
  147. ** on-the-fly for a stack-based interpreter -- and all of that in a meager
  148. ** kilobyte? Yep, compilers are a great treasure chest. Throw away your
  149. ** textbooks and read the codebase of a compiler today!]
  150. **
  151. ** There's another optimization opportunity for array indexing: it's
  152. ** always accompanied by an array bounds-check. The outermost overflow
  153. ** check may be delegated to the ABC operation. This works because ABC is
  154. ** an unsigned comparison and wrap-around due to overflow creates negative
  155. ** numbers.
  156. **
  157. ** But this optimization is only valid for constants that cannot overflow
  158. ** an int32_t into the range of valid array indexes [0..2^27+1). A check
  159. ** for +-2^30 is safe since -2^31 - 2^30 wraps to 2^30 and 2^31-1 + 2^30
  160. ** wraps to -2^30-1.
  161. **
  162. ** It's also good enough in practice, since e.g. t[i+1] or t[i-10] are
  163. ** quite common. So the above example finally ends up as ADD(i, 1)!
  164. **
  165. ** Later on, the assembler is able to fuse the whole array reference and
  166. ** the ADD into the memory operands of loads and other instructions. This
  167. ** is why LuaJIT is able to generate very pretty (and fast) machine code
  168. ** for array indexing. And that, my dear, concludes another story about
  169. ** one of the hidden secrets of LuaJIT ...
  170. */

  171. /* Maximum backpropagation depth and maximum stack size. */
  172. #define NARROW_MAX_BACKPROP        100
  173. #define NARROW_MAX_STACK        256

  174. /* The stack machine has a 32 bit instruction format: [IROpT | IRRef1]
  175. ** The lower 16 bits hold a reference (or 0). The upper 16 bits hold
  176. ** the IR opcode + type or one of the following special opcodes:
  177. */
  178. enum {
  179.   NARROW_REF,                /* Push ref. */
  180.   NARROW_CONV,                /* Push conversion of ref. */
  181.   NARROW_SEXT,                /* Push sign-extension of ref. */
  182.   NARROW_INT                /* Push KINT ref. The next code holds an int32_t. */
  183. };

  184. typedef uint32_t NarrowIns;

  185. #define NARROWINS(op, ref)        (((op) << 16) + (ref))
  186. #define narrow_op(ins)                ((IROpT)((ins) >> 16))
  187. #define narrow_ref(ins)                ((IRRef1)(ins))

  188. /* Context used for narrowing of type conversions. */
  189. typedef struct NarrowConv {
  190.   jit_State *J;                /* JIT compiler state. */
  191.   NarrowIns *sp;        /* Current stack pointer. */
  192.   NarrowIns *maxsp;        /* Maximum stack pointer minus redzone. */
  193.   int lim;                /* Limit on the number of emitted conversions. */
  194.   IRRef mode;                /* Conversion mode (IRCONV_*). */
  195.   IRType t;                /* Destination type: IRT_INT or IRT_I64. */
  196.   NarrowIns stack[NARROW_MAX_STACK];  /* Stack holding stack-machine code. */
  197. } NarrowConv;

  198. /* Lookup a reference in the backpropagation cache. */
  199. static BPropEntry *narrow_bpc_get(jit_State *J, IRRef1 key, IRRef mode)
  200. {
  201.   ptrdiff_t i;
  202.   for (i = 0; i < BPROP_SLOTS; i++) {
  203.     BPropEntry *bp = &J->bpropcache[i];
  204.     /* Stronger checks are ok, too. */
  205.     if (bp->key == key && bp->mode >= mode &&
  206.         ((bp->mode ^ mode) & IRCONV_MODEMASK) == 0)
  207.       return bp;
  208.   }
  209.   return NULL;
  210. }

  211. /* Add an entry to the backpropagation cache. */
  212. static void narrow_bpc_set(jit_State *J, IRRef1 key, IRRef1 val, IRRef mode)
  213. {
  214.   uint32_t slot = J->bpropslot;
  215.   BPropEntry *bp = &J->bpropcache[slot];
  216.   J->bpropslot = (slot + 1) & (BPROP_SLOTS-1);
  217.   bp->key = key;
  218.   bp->val = val;
  219.   bp->mode = mode;
  220. }

  221. /* Backpropagate overflow stripping. */
  222. static void narrow_stripov_backprop(NarrowConv *nc, IRRef ref, int depth)
  223. {
  224.   jit_State *J = nc->J;
  225.   IRIns *ir = IR(ref);
  226.   if (ir->o == IR_ADDOV || ir->o == IR_SUBOV ||
  227.       (ir->o == IR_MULOV && (nc->mode & IRCONV_CONVMASK) == IRCONV_ANY)) {
  228.     BPropEntry *bp = narrow_bpc_get(nc->J, ref, IRCONV_TOBIT);
  229.     if (bp) {
  230.       ref = bp->val;
  231.     } else if (++depth < NARROW_MAX_BACKPROP && nc->sp < nc->maxsp) {
  232.       narrow_stripov_backprop(nc, ir->op1, depth);
  233.       narrow_stripov_backprop(nc, ir->op2, depth);
  234.       *nc->sp++ = NARROWINS(IRT(ir->o - IR_ADDOV + IR_ADD, IRT_INT), ref);
  235.       return;
  236.     }
  237.   }
  238.   *nc->sp++ = NARROWINS(NARROW_REF, ref);
  239. }

  240. /* Backpropagate narrowing conversion. Return number of needed conversions. */
  241. static int narrow_conv_backprop(NarrowConv *nc, IRRef ref, int depth)
  242. {
  243.   jit_State *J = nc->J;
  244.   IRIns *ir = IR(ref);
  245.   IRRef cref;

  246.   /* Check the easy cases first. */
  247.   if (ir->o == IR_CONV && (ir->op2 & IRCONV_SRCMASK) == IRT_INT) {
  248.     if ((nc->mode & IRCONV_CONVMASK) <= IRCONV_ANY)
  249.       narrow_stripov_backprop(nc, ir->op1, depth+1);
  250.     else
  251.       *nc->sp++ = NARROWINS(NARROW_REF, ir->op1);  /* Undo conversion. */
  252.     if (nc->t == IRT_I64)
  253.       *nc->sp++ = NARROWINS(NARROW_SEXT, 0);  /* Sign-extend integer. */
  254.     return 0;
  255.   } else if (ir->o == IR_KNUM) {  /* Narrow FP constant. */
  256.     lua_Number n = ir_knum(ir)->n;
  257.     if ((nc->mode & IRCONV_CONVMASK) == IRCONV_TOBIT) {
  258.       /* Allows a wider range of constants. */
  259.       int64_t k64 = (int64_t)n;
  260.       if (n == (lua_Number)k64) {  /* Only if const doesn't lose precision. */
  261.         *nc->sp++ = NARROWINS(NARROW_INT, 0);
  262.         *nc->sp++ = (NarrowIns)k64;  /* But always truncate to 32 bits. */
  263.         return 0;
  264.       }
  265.     } else {
  266.       int32_t k = lj_num2int(n);
  267.       /* Only if constant is a small integer. */
  268.       if (checki16(k) && n == (lua_Number)k) {
  269.         *nc->sp++ = NARROWINS(NARROW_INT, 0);
  270.         *nc->sp++ = (NarrowIns)k;
  271.         return 0;
  272.       }
  273.     }
  274.     return 10/* Never narrow other FP constants (this is rare). */
  275.   }

  276.   /* Try to CSE the conversion. Stronger checks are ok, too. */
  277.   cref = J->chain[fins->o];
  278.   while (cref > ref) {
  279.     IRIns *cr = IR(cref);
  280.     if (cr->op1 == ref &&
  281.         (fins->o == IR_TOBIT ||
  282.          ((cr->op2 & IRCONV_MODEMASK) == (nc->mode & IRCONV_MODEMASK) &&
  283.           irt_isguard(cr->t) >= irt_isguard(fins->t)))) {
  284.       *nc->sp++ = NARROWINS(NARROW_REF, cref);
  285.       return 0/* Already there, no additional conversion needed. */
  286.     }
  287.     cref = cr->prev;
  288.   }

  289.   /* Backpropagate across ADD/SUB. */
  290.   if (ir->o == IR_ADD || ir->o == IR_SUB) {
  291.     /* Try cache lookup first. */
  292.     IRRef mode = nc->mode;
  293.     BPropEntry *bp;
  294.     /* Inner conversions need a stronger check. */
  295.     if ((mode & IRCONV_CONVMASK) == IRCONV_INDEX && depth > 0)
  296.       mode += IRCONV_CHECK-IRCONV_INDEX;
  297.     bp = narrow_bpc_get(nc->J, (IRRef1)ref, mode);
  298.     if (bp) {
  299.       *nc->sp++ = NARROWINS(NARROW_REF, bp->val);
  300.       return 0;
  301.     } else if (nc->t == IRT_I64) {
  302.       /* Try sign-extending from an existing (checked) conversion to int. */
  303.       mode = (IRT_INT<<5)|IRT_NUM|IRCONV_INDEX;
  304.       bp = narrow_bpc_get(nc->J, (IRRef1)ref, mode);
  305.       if (bp) {
  306.         *nc->sp++ = NARROWINS(NARROW_REF, bp->val);
  307.         *nc->sp++ = NARROWINS(NARROW_SEXT, 0);
  308.         return 0;
  309.       }
  310.     }
  311.     if (++depth < NARROW_MAX_BACKPROP && nc->sp < nc->maxsp) {
  312.       NarrowIns *savesp = nc->sp;
  313.       int count = narrow_conv_backprop(nc, ir->op1, depth);
  314.       count += narrow_conv_backprop(nc, ir->op2, depth);
  315.       if (count <= nc->lim) {  /* Limit total number of conversions. */
  316.         *nc->sp++ = NARROWINS(IRT(ir->o, nc->t), ref);
  317.         return count;
  318.       }
  319.       nc->sp = savesp;  /* Too many conversions, need to backtrack. */
  320.     }
  321.   }

  322.   /* Otherwise add a conversion. */
  323.   *nc->sp++ = NARROWINS(NARROW_CONV, ref);
  324.   return 1;
  325. }

  326. /* Emit the conversions collected during backpropagation. */
  327. static IRRef narrow_conv_emit(jit_State *J, NarrowConv *nc)
  328. {
  329.   /* The fins fields must be saved now -- emitir() overwrites them. */
  330.   IROpT guardot = irt_isguard(fins->t) ? IRTG(IR_ADDOV-IR_ADD, 0) : 0;
  331.   IROpT convot = fins->ot;
  332.   IRRef1 convop2 = fins->op2;
  333.   NarrowIns *next = nc->stack;  /* List of instructions from backpropagation. */
  334.   NarrowIns *last = nc->sp;
  335.   NarrowIns *sp = nc->stack;  /* Recycle the stack to store operands. */
  336.   while (next < last) {  /* Simple stack machine to process the ins. list. */
  337.     NarrowIns ref = *next++;
  338.     IROpT op = narrow_op(ref);
  339.     if (op == NARROW_REF) {
  340.       *sp++ = ref;
  341.     } else if (op == NARROW_CONV) {
  342.       *sp++ = emitir_raw(convot, ref, convop2);  /* Raw emit avoids a loop. */
  343.     } else if (op == NARROW_SEXT) {
  344.       lua_assert(sp >= nc->stack+1);
  345.       sp[-1] = emitir(IRT(IR_CONV, IRT_I64), sp[-1],
  346.                       (IRT_I64<<5)|IRT_INT|IRCONV_SEXT);
  347.     } else if (op == NARROW_INT) {
  348.       lua_assert(next < last);
  349.       *sp++ = nc->t == IRT_I64 ?
  350.               lj_ir_kint64(J, (int64_t)(int32_t)*next++) :
  351.               lj_ir_kint(J, *next++);
  352.     } else/* Regular IROpT. Pops two operands and pushes one result. */
  353.       IRRef mode = nc->mode;
  354.       lua_assert(sp >= nc->stack+2);
  355.       sp--;
  356.       /* Omit some overflow checks for array indexing. See comments above. */
  357.       if ((mode & IRCONV_CONVMASK) == IRCONV_INDEX) {
  358.         if (next == last && irref_isk(narrow_ref(sp[0])) &&
  359.           (uint32_t)IR(narrow_ref(sp[0]))->i + 0x40000000u < 0x80000000u)
  360.           guardot = 0;
  361.         else  /* Otherwise cache a stronger check. */
  362.           mode += IRCONV_CHECK-IRCONV_INDEX;
  363.       }
  364.       sp[-1] = emitir(op+guardot, sp[-1], sp[0]);
  365.       /* Add to cache. */
  366.       if (narrow_ref(ref))
  367.         narrow_bpc_set(J, narrow_ref(ref), narrow_ref(sp[-1]), mode);
  368.     }
  369.   }
  370.   lua_assert(sp == nc->stack+1);
  371.   return nc->stack[0];
  372. }

  373. /* Narrow a type conversion of an arithmetic operation. */
  374. TRef LJ_FASTCALL lj_opt_narrow_convert(jit_State *J)
  375. {
  376.   if ((J->flags & JIT_F_OPT_NARROW)) {
  377.     NarrowConv nc;
  378.     nc.J = J;
  379.     nc.sp = nc.stack;
  380.     nc.maxsp = &nc.stack[NARROW_MAX_STACK-4];
  381.     nc.t = irt_type(fins->t);
  382.     if (fins->o == IR_TOBIT) {
  383.       nc.mode = IRCONV_TOBIT/* Used only in the backpropagation cache. */
  384.       nc.lim = 2/* TOBIT can use a more optimistic rule. */
  385.     } else {
  386.       nc.mode = fins->op2;
  387.       nc.lim = 1;
  388.     }
  389.     if (narrow_conv_backprop(&nc, fins->op1, 0) <= nc.lim)
  390.       return narrow_conv_emit(J, &nc);
  391.   }
  392.   return NEXTFOLD;
  393. }

  394. /* -- Narrowing of implicit conversions ----------------------------------- */

  395. /* Recursively strip overflow checks. */
  396. static TRef narrow_stripov(jit_State *J, TRef tr, int lastop, IRRef mode)
  397. {
  398.   IRRef ref = tref_ref(tr);
  399.   IRIns *ir = IR(ref);
  400.   int op = ir->o;
  401.   if (op >= IR_ADDOV && op <= lastop) {
  402.     BPropEntry *bp = narrow_bpc_get(J, ref, mode);
  403.     if (bp) {
  404.       return TREF(bp->val, irt_t(IR(bp->val)->t));
  405.     } else {
  406.       IRRef op1 = ir->op1, op2 = ir->op2;  /* The IR may be reallocated. */
  407.       op1 = narrow_stripov(J, op1, lastop, mode);
  408.       op2 = narrow_stripov(J, op2, lastop, mode);
  409.       tr = emitir(IRT(op - IR_ADDOV + IR_ADD,
  410.                       ((mode & IRCONV_DSTMASK) >> IRCONV_DSH)), op1, op2);
  411.       narrow_bpc_set(J, ref, tref_ref(tr), mode);
  412.     }
  413.   } else if (LJ_64 && (mode & IRCONV_SEXT) && !irt_is64(ir->t)) {
  414.     tr = emitir(IRT(IR_CONV, IRT_INTP), tr, mode);
  415.   }
  416.   return tr;
  417. }

  418. /* Narrow array index. */
  419. TRef LJ_FASTCALL lj_opt_narrow_index(jit_State *J, TRef tr)
  420. {
  421.   IRIns *ir;
  422.   lua_assert(tref_isnumber(tr));
  423.   if (tref_isnum(tr))  /* Conversion may be narrowed, too. See above. */
  424.     return emitir(IRTGI(IR_CONV), tr, IRCONV_INT_NUM|IRCONV_INDEX);
  425.   /* Omit some overflow checks for array indexing. See comments above. */
  426.   ir = IR(tref_ref(tr));
  427.   if ((ir->o == IR_ADDOV || ir->o == IR_SUBOV) && irref_isk(ir->op2) &&
  428.       (uint32_t)IR(ir->op2)->i + 0x40000000u < 0x80000000u)
  429.     return emitir(IRTI(ir->o - IR_ADDOV + IR_ADD), ir->op1, ir->op2);
  430.   return tr;
  431. }

  432. /* Narrow conversion to integer operand (overflow undefined). */
  433. TRef LJ_FASTCALL lj_opt_narrow_toint(jit_State *J, TRef tr)
  434. {
  435.   if (tref_isstr(tr))
  436.     tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
  437.   if (tref_isnum(tr))  /* Conversion may be narrowed, too. See above. */
  438.     return emitir(IRTI(IR_CONV), tr, IRCONV_INT_NUM|IRCONV_ANY);
  439.   if (!tref_isinteger(tr))
  440.     lj_trace_err(J, LJ_TRERR_BADTYPE);
  441.   /*
  442.   ** Undefined overflow semantics allow stripping of ADDOV, SUBOV and MULOV.
  443.   ** Use IRCONV_TOBIT for the cache entries, since the semantics are the same.
  444.   */
  445.   return narrow_stripov(J, tr, IR_MULOV, (IRT_INT<<5)|IRT_INT|IRCONV_TOBIT);
  446. }

  447. /* Narrow conversion to bitop operand (overflow wrapped). */
  448. TRef LJ_FASTCALL lj_opt_narrow_tobit(jit_State *J, TRef tr)
  449. {
  450.   if (tref_isstr(tr))
  451.     tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
  452.   if (tref_isnum(tr))  /* Conversion may be narrowed, too. See above. */
  453.     return emitir(IRTI(IR_TOBIT), tr, lj_ir_knum_tobit(J));
  454.   if (!tref_isinteger(tr))
  455.     lj_trace_err(J, LJ_TRERR_BADTYPE);
  456.   /*
  457.   ** Wrapped overflow semantics allow stripping of ADDOV and SUBOV.
  458.   ** MULOV cannot be stripped due to precision widening.
  459.   */
  460.   return narrow_stripov(J, tr, IR_SUBOV, (IRT_INT<<5)|IRT_INT|IRCONV_TOBIT);
  461. }

  462. #if LJ_HASFFI
  463. /* Narrow C array index (overflow undefined). */
  464. TRef LJ_FASTCALL lj_opt_narrow_cindex(jit_State *J, TRef tr)
  465. {
  466.   lua_assert(tref_isnumber(tr));
  467.   if (tref_isnum(tr))
  468.     return emitir(IRT(IR_CONV, IRT_INTP), tr, (IRT_INTP<<5)|IRT_NUM|IRCONV_ANY);
  469.   /* Undefined overflow semantics allow stripping of ADDOV, SUBOV and MULOV. */
  470.   return narrow_stripov(J, tr, IR_MULOV,
  471.                         LJ_64 ? ((IRT_INTP<<5)|IRT_INT|IRCONV_SEXT) :
  472.                                 ((IRT_INTP<<5)|IRT_INT|IRCONV_TOBIT));
  473. }
  474. #endif

  475. /* -- Narrowing of arithmetic operators ----------------------------------- */

  476. /* Check whether a number fits into an int32_t (-0 is ok, too). */
  477. static int numisint(lua_Number n)
  478. {
  479.   return (n == (lua_Number)lj_num2int(n));
  480. }

  481. /* Narrowing of arithmetic operations. */
  482. TRef lj_opt_narrow_arith(jit_State *J, TRef rb, TRef rc,
  483.                          TValue *vb, TValue *vc, IROp op)
  484. {
  485.   if (tref_isstr(rb)) {
  486.     rb = emitir(IRTG(IR_STRTO, IRT_NUM), rb, 0);
  487.     lj_strscan_num(strV(vb), vb);
  488.   }
  489.   if (tref_isstr(rc)) {
  490.     rc = emitir(IRTG(IR_STRTO, IRT_NUM), rc, 0);
  491.     lj_strscan_num(strV(vc), vc);
  492.   }
  493.   /* Must not narrow MUL in non-DUALNUM variant, because it loses -0. */
  494.   if ((op >= IR_ADD && op <= (LJ_DUALNUM ? IR_MUL : IR_SUB)) &&
  495.       tref_isinteger(rb) && tref_isinteger(rc) &&
  496.       numisint(lj_vm_foldarith(numberVnum(vb), numberVnum(vc),
  497.                                (int)op - (int)IR_ADD)))
  498.     return emitir(IRTGI((int)op - (int)IR_ADD + (int)IR_ADDOV), rb, rc);
  499.   if (!tref_isnum(rb)) rb = emitir(IRTN(IR_CONV), rb, IRCONV_NUM_INT);
  500.   if (!tref_isnum(rc)) rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
  501.   return emitir(IRTN(op), rb, rc);
  502. }

  503. /* Narrowing of unary minus operator. */
  504. TRef lj_opt_narrow_unm(jit_State *J, TRef rc, TValue *vc)
  505. {
  506.   if (tref_isstr(rc)) {
  507.     rc = emitir(IRTG(IR_STRTO, IRT_NUM), rc, 0);
  508.     lj_strscan_num(strV(vc), vc);
  509.   }
  510.   if (tref_isinteger(rc)) {
  511.     if ((uint32_t)numberVint(vc) != 0x80000000u)
  512.       return emitir(IRTGI(IR_SUBOV), lj_ir_kint(J, 0), rc);
  513.     rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
  514.   }
  515.   return emitir(IRTN(IR_NEG), rc, lj_ir_knum_neg(J));
  516. }

  517. /* Narrowing of modulo operator. */
  518. TRef lj_opt_narrow_mod(jit_State *J, TRef rb, TRef rc, TValue *vc)
  519. {
  520.   TRef tmp;
  521.   if (tvisstr(vc) && !lj_strscan_num(strV(vc), vc))
  522.     lj_trace_err(J, LJ_TRERR_BADTYPE);
  523.   if ((LJ_DUALNUM || (J->flags & JIT_F_OPT_NARROW)) &&
  524.       tref_isinteger(rb) && tref_isinteger(rc) &&
  525.       (tvisint(vc) ? intV(vc) != 0 : !tviszero(vc))) {
  526.     emitir(IRTGI(IR_NE), rc, lj_ir_kint(J, 0));
  527.     return emitir(IRTI(IR_MOD), rb, rc);
  528.   }
  529.   /* b % c ==> b - floor(b/c)*c */
  530.   rb = lj_ir_tonum(J, rb);
  531.   rc = lj_ir_tonum(J, rc);
  532.   tmp = emitir(IRTN(IR_DIV), rb, rc);
  533.   tmp = emitir(IRTN(IR_FPMATH), tmp, IRFPM_FLOOR);
  534.   tmp = emitir(IRTN(IR_MUL), tmp, rc);
  535.   return emitir(IRTN(IR_SUB), rb, tmp);
  536. }

  537. /* Narrowing of power operator or math.pow. */
  538. TRef lj_opt_narrow_pow(jit_State *J, TRef rb, TRef rc, TValue *vc)
  539. {
  540.   if (tvisstr(vc) && !lj_strscan_num(strV(vc), vc))
  541.     lj_trace_err(J, LJ_TRERR_BADTYPE);
  542.   /* Narrowing must be unconditional to preserve (-x)^i semantics. */
  543.   if (tvisint(vc) || numisint(numV(vc))) {
  544.     int checkrange = 0;
  545.     /* Split pow is faster for bigger exponents. But do this only for (+k)^i. */
  546.     if (tref_isk(rb) && (int32_t)ir_knum(IR(tref_ref(rb)))->u32.hi >= 0) {
  547.       int32_t k = numberVint(vc);
  548.       if (!(k >= -65536 && k <= 65536)) goto split_pow;
  549.       checkrange = 1;
  550.     }
  551.     if (!tref_isinteger(rc)) {
  552.       if (tref_isstr(rc))
  553.         rc = emitir(IRTG(IR_STRTO, IRT_NUM), rc, 0);
  554.       /* Guarded conversion to integer! */
  555.       rc = emitir(IRTGI(IR_CONV), rc, IRCONV_INT_NUM|IRCONV_CHECK);
  556.     }
  557.     if (checkrange && !tref_isk(rc)) {  /* Range guard: -65536 <= i <= 65536 */
  558.       TRef tmp = emitir(IRTI(IR_ADD), rc, lj_ir_kint(J, 65536));
  559.       emitir(IRTGI(IR_ULE), tmp, lj_ir_kint(J, 2*65536));
  560.     }
  561.     return emitir(IRTN(IR_POW), rb, rc);
  562.   }
  563. split_pow:
  564.   /* FOLD covers most cases, but some are easier to do here. */
  565.   if (tref_isk(rb) && tvispone(ir_knum(IR(tref_ref(rb)))))
  566.     return rb;  /* 1 ^ x ==> 1 */
  567.   rc = lj_ir_tonum(J, rc);
  568.   if (tref_isk(rc) && ir_knum(IR(tref_ref(rc)))->n == 0.5)
  569.     return emitir(IRTN(IR_FPMATH), rb, IRFPM_SQRT);  /* x ^ 0.5 ==> sqrt(x) */
  570.   /* Split up b^c into exp2(c*log2(b)). Assembler may rejoin later. */
  571.   rb = emitir(IRTN(IR_FPMATH), rb, IRFPM_LOG2);
  572.   rc = emitir(IRTN(IR_MUL), rb, rc);
  573.   return emitir(IRTN(IR_FPMATH), rc, IRFPM_EXP2);
  574. }

  575. /* -- Predictive narrowing of induction variables ------------------------- */

  576. /* Narrow a single runtime value. */
  577. static int narrow_forl(jit_State *J, cTValue *o)
  578. {
  579.   if (tvisint(o)) return 1;
  580.   if (LJ_DUALNUM || (J->flags & JIT_F_OPT_NARROW)) return numisint(numV(o));
  581.   return 0;
  582. }

  583. /* Narrow the FORL index type by looking at the runtime values. */
  584. IRType lj_opt_narrow_forl(jit_State *J, cTValue *tv)
  585. {
  586.   lua_assert(tvisnumber(&tv[FORL_IDX]) &&
  587.              tvisnumber(&tv[FORL_STOP]) &&
  588.              tvisnumber(&tv[FORL_STEP]));
  589.   /* Narrow only if the runtime values of start/stop/step are all integers. */
  590.   if (narrow_forl(J, &tv[FORL_IDX]) &&
  591.       narrow_forl(J, &tv[FORL_STOP]) &&
  592.       narrow_forl(J, &tv[FORL_STEP])) {
  593.     /* And if the loop index can't possibly overflow. */
  594.     lua_Number step = numberVnum(&tv[FORL_STEP]);
  595.     lua_Number sum = numberVnum(&tv[FORL_STOP]) + step;
  596.     if (0 <= step ? (sum <= 2147483647.0) : (sum >= -2147483648.0))
  597.       return IRT_INT;
  598.   }
  599.   return IRT_NUM;
  600. }

  601. #undef IR
  602. #undef fins
  603. #undef emitir
  604. #undef emitir_raw

  605. #endif