root/lj_asm.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. asm_mclimit
  2. checkmclim
  3. ra_setkref
  4. ra_dstart
  5. ra_dflush
  6. ra_dprintf
  7. ra_setup
  8. ra_rematk
  9. ra_spill
  10. ra_releasetmp
  11. ra_restore
  12. ra_save
  13. ra_evict
  14. ra_pick
  15. ra_scratch
  16. ra_evictset
  17. ra_evictk
  18. ra_allock
  19. ra_allockreg
  20. ra_allocref
  21. ra_alloc1
  22. ra_addrename
  23. ra_rename
  24. ra_dest
  25. ra_destreg
  26. ra_left
  27. ra_leftov
  28. ra_destpair
  29. asm_snap_canremat
  30. asm_sunk_store
  31. asm_snap_alloc1
  32. asm_snap_alloc
  33. asm_snap_checkrename
  34. asm_snap_prep
  35. asm_stack_adjust
  36. ir_khash
  37. asm_snew
  38. asm_tnew
  39. asm_tdup
  40. asm_gcstep
  41. asm_bufhdr
  42. asm_bufput
  43. asm_bufstr
  44. asm_tostr
  45. asm_conv64
  46. asm_newref
  47. asm_lref
  48. asm_collectargs
  49. asm_callx_flags
  50. asm_callid
  51. asm_call
  52. asm_fppow
  53. asm_fpjoin_pow
  54. asm_phi_break
  55. asm_phi_shuffle
  56. asm_phi_copyspill
  57. asm_phi_fixup
  58. asm_phi
  59. asm_loop
  60. asm_ir
  61. asm_head_root
  62. asm_head_side
  63. asm_baseslot
  64. asm_tail_link
  65. asm_setup_regsp
  66. lj_asm_trace

   1 /*
   2 ** IR assembler (SSA IR -> machine code).
   3 ** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
   4 */
   5 
   6 #define lj_asm_c
   7 #define LUA_CORE
   8 
   9 #include "lj_obj.h"
  10 
  11 #if LJ_HASJIT
  12 
  13 #include "lj_gc.h"
  14 #include "lj_str.h"
  15 #include "lj_tab.h"
  16 #include "lj_frame.h"
  17 #if LJ_HASFFI
  18 #include "lj_ctype.h"
  19 #endif
  20 #include "lj_ir.h"
  21 #include "lj_jit.h"
  22 #include "lj_ircall.h"
  23 #include "lj_iropt.h"
  24 #include "lj_mcode.h"
  25 #include "lj_iropt.h"
  26 #include "lj_trace.h"
  27 #include "lj_snap.h"
  28 #include "lj_asm.h"
  29 #include "lj_dispatch.h"
  30 #include "lj_vm.h"
  31 #include "lj_target.h"
  32 
  33 #ifdef LUA_USE_ASSERT
  34 #include <stdio.h>
  35 #endif
  36 
  37 /* -- Assembler state and common macros ----------------------------------- */
  38 
  39 /* Assembler state. */
  40 typedef struct ASMState {
  41   RegCost cost[RID_MAX];  /* Reference and blended allocation cost for regs. */
  42 
  43   MCode *mcp;           /* Current MCode pointer (grows down). */
  44   MCode *mclim;         /* Lower limit for MCode memory + red zone. */
  45 #ifdef LUA_USE_ASSERT
  46   MCode *mcp_prev;      /* Red zone overflow check. */
  47 #endif
  48 
  49   IRIns *ir;            /* Copy of pointer to IR instructions/constants. */
  50   jit_State *J;         /* JIT compiler state. */
  51 
  52 #if LJ_TARGET_X86ORX64
  53   x86ModRM mrm;         /* Fused x86 address operand. */
  54 #endif
  55 
  56   RegSet freeset;       /* Set of free registers. */
  57   RegSet modset;        /* Set of registers modified inside the loop. */
  58   RegSet weakset;       /* Set of weakly referenced registers. */
  59   RegSet phiset;        /* Set of PHI registers. */
  60 
  61   uint32_t flags;       /* Copy of JIT compiler flags. */
  62   int loopinv;          /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
  63 
  64   int32_t evenspill;    /* Next even spill slot. */
  65   int32_t oddspill;     /* Next odd spill slot (or 0). */
  66 
  67   IRRef curins;         /* Reference of current instruction. */
  68   IRRef stopins;        /* Stop assembly before hitting this instruction. */
  69   IRRef orignins;       /* Original T->nins. */
  70 
  71   IRRef snapref;        /* Current snapshot is active after this reference. */
  72   IRRef snaprename;     /* Rename highwater mark for snapshot check. */
  73   SnapNo snapno;        /* Current snapshot number. */
  74   SnapNo loopsnapno;    /* Loop snapshot number. */
  75 
  76   IRRef fuseref;        /* Fusion limit (loopref, 0 or FUSE_DISABLED). */
  77   IRRef sectref;        /* Section base reference (loopref or 0). */
  78   IRRef loopref;        /* Reference of LOOP instruction (or 0). */
  79 
  80   BCReg topslot;        /* Number of slots for stack check (unless 0). */
  81   int32_t gcsteps;      /* Accumulated number of GC steps (per section). */
  82 
  83   GCtrace *T;           /* Trace to assemble. */
  84   GCtrace *parent;      /* Parent trace (or NULL). */
  85 
  86   MCode *mcbot;         /* Bottom of reserved MCode. */
  87   MCode *mctop;         /* Top of generated MCode. */
  88   MCode *mcloop;        /* Pointer to loop MCode (or NULL). */
  89   MCode *invmcp;        /* Points to invertible loop branch (or NULL). */
  90   MCode *flagmcp;       /* Pending opportunity to merge flag setting ins. */
  91   MCode *realign;       /* Realign loop if not NULL. */
  92 
  93 #ifdef RID_NUM_KREF
  94   intptr_t krefk[RID_NUM_KREF];
  95 #endif
  96   IRRef1 phireg[RID_MAX];  /* PHI register references. */
  97   uint16_t parentmap[LJ_MAX_JSLOTS];  /* Parent instruction to RegSP map. */
  98 } ASMState;
  99 
 100 #define IR(ref)                 (&as->ir[(ref)])
 101 
 102 #define ASMREF_TMP1             REF_TRUE        /* Temp. register. */
 103 #define ASMREF_TMP2             REF_FALSE       /* Temp. register. */
 104 #define ASMREF_L                REF_NIL         /* Stores register for L. */
 105 
 106 /* Check for variant to invariant references. */
 107 #define iscrossref(as, ref)     ((ref) < as->sectref)
 108 
 109 /* Inhibit memory op fusion from variant to invariant references. */
 110 #define FUSE_DISABLED           (~(IRRef)0)
 111 #define mayfuse(as, ref)        ((ref) > as->fuseref)
 112 #define neverfuse(as)           (as->fuseref == FUSE_DISABLED)
 113 #define canfuse(as, ir)         (!neverfuse(as) && !irt_isphi((ir)->t))
 114 #define opisfusableload(o) \
 115   ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
 116    (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
 117 
 118 /* Sparse limit checks using a red zone before the actual limit. */
 119 #define MCLIM_REDZONE   64
 120 
 121 static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
 122 {
 123   lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
 124 }
 125 
 126 static LJ_AINLINE void checkmclim(ASMState *as)
 127 {
 128 #ifdef LUA_USE_ASSERT
 129   if (as->mcp + MCLIM_REDZONE < as->mcp_prev) {
 130     IRIns *ir = IR(as->curins+1);
 131     fprintf(stderr, "RED ZONE OVERFLOW: %p IR %04d  %02d %04d %04d\n", as->mcp,
 132             as->curins+1-REF_BIAS, ir->o, ir->op1-REF_BIAS, ir->op2-REF_BIAS);
 133     lua_assert(0);
 134   }
 135 #endif
 136   if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as);
 137 #ifdef LUA_USE_ASSERT
 138   as->mcp_prev = as->mcp;
 139 #endif
 140 }
 141 
 142 #ifdef RID_NUM_KREF
 143 #define ra_iskref(ref)          ((ref) < RID_NUM_KREF)
 144 #define ra_krefreg(ref)         ((Reg)(RID_MIN_KREF + (Reg)(ref)))
 145 #define ra_krefk(as, ref)       (as->krefk[(ref)])
 146 
 147 static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, intptr_t k)
 148 {
 149   IRRef ref = (IRRef)(r - RID_MIN_KREF);
 150   as->krefk[ref] = k;
 151   as->cost[r] = REGCOST(ref, ref);
 152 }
 153 
 154 #else
 155 #define ra_iskref(ref)          0
 156 #define ra_krefreg(ref)         RID_MIN_GPR
 157 #define ra_krefk(as, ref)       0
 158 #endif
 159 
 160 /* Arch-specific field offsets. */
 161 static const uint8_t field_ofs[IRFL__MAX+1] = {
 162 #define FLOFS(name, ofs)        (uint8_t)(ofs),
 163 IRFLDEF(FLOFS)
 164 #undef FLOFS
 165   0
 166 };
 167 
 168 /* -- Target-specific instruction emitter --------------------------------- */
 169 
 170 #if LJ_TARGET_X86ORX64
 171 #include "lj_emit_x86.h"
 172 #elif LJ_TARGET_ARM
 173 #include "lj_emit_arm.h"
 174 #elif LJ_TARGET_ARM64
 175 #include "lj_emit_arm64.h"
 176 #elif LJ_TARGET_PPC
 177 #include "lj_emit_ppc.h"
 178 #elif LJ_TARGET_MIPS
 179 #include "lj_emit_mips.h"
 180 #else
 181 #error "Missing instruction emitter for target CPU"
 182 #endif
 183 
 184 /* Generic load/store of register from/to stack slot. */
 185 #define emit_spload(as, ir, r, ofs) \
 186   emit_loadofs(as, ir, (r), RID_SP, (ofs))
 187 #define emit_spstore(as, ir, r, ofs) \
 188   emit_storeofs(as, ir, (r), RID_SP, (ofs))
 189 
 190 /* -- Register allocator debugging ---------------------------------------- */
 191 
 192 /* #define LUAJIT_DEBUG_RA */
 193 
 194 #ifdef LUAJIT_DEBUG_RA
 195 
 196 #include <stdio.h>
 197 #include <stdarg.h>
 198 
 199 #define RIDNAME(name)   #name,
 200 static const char *const ra_regname[] = {
 201   GPRDEF(RIDNAME)
 202   FPRDEF(RIDNAME)
 203   VRIDDEF(RIDNAME)
 204   NULL
 205 };
 206 #undef RIDNAME
 207 
 208 static char ra_dbg_buf[65536];
 209 static char *ra_dbg_p;
 210 static char *ra_dbg_merge;
 211 static MCode *ra_dbg_mcp;
 212 
 213 static void ra_dstart(void)
 214 {
 215   ra_dbg_p = ra_dbg_buf;
 216   ra_dbg_merge = NULL;
 217   ra_dbg_mcp = NULL;
 218 }
 219 
 220 static void ra_dflush(void)
 221 {
 222   fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
 223   ra_dstart();
 224 }
 225 
 226 static void ra_dprintf(ASMState *as, const char *fmt, ...)
 227 {
 228   char *p;
 229   va_list argp;
 230   va_start(argp, fmt);
 231   p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
 232   ra_dbg_mcp = NULL;
 233   p += sprintf(p, "%08x  \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
 234   for (;;) {
 235     const char *e = strchr(fmt, '$');
 236     if (e == NULL) break;
 237     memcpy(p, fmt, (size_t)(e-fmt));
 238     p += e-fmt;
 239     if (e[1] == 'r') {
 240       Reg r = va_arg(argp, Reg) & RID_MASK;
 241       if (r <= RID_MAX) {
 242         const char *q;
 243         for (q = ra_regname[r]; *q; q++)
 244           *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
 245       } else {
 246         *p++ = '?';
 247         lua_assert(0);
 248       }
 249     } else if (e[1] == 'f' || e[1] == 'i') {
 250       IRRef ref;
 251       if (e[1] == 'f')
 252         ref = va_arg(argp, IRRef);
 253       else
 254         ref = va_arg(argp, IRIns *) - as->ir;
 255       if (ref >= REF_BIAS)
 256         p += sprintf(p, "%04d", ref - REF_BIAS);
 257       else
 258         p += sprintf(p, "K%03d", REF_BIAS - ref);
 259     } else if (e[1] == 's') {
 260       uint32_t slot = va_arg(argp, uint32_t);
 261       p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
 262     } else if (e[1] == 'x') {
 263       p += sprintf(p, "%08x", va_arg(argp, int32_t));
 264     } else {
 265       lua_assert(0);
 266     }
 267     fmt = e+2;
 268   }
 269   va_end(argp);
 270   while (*fmt)
 271     *p++ = *fmt++;
 272   *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
 273   if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
 274     fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
 275     p = ra_dbg_buf;
 276   }
 277   ra_dbg_p = p;
 278 }
 279 
 280 #define RA_DBG_START()  ra_dstart()
 281 #define RA_DBG_FLUSH()  ra_dflush()
 282 #define RA_DBG_REF() \
 283   do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
 284        ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
 285 #define RA_DBGX(x)      ra_dprintf x
 286 
 287 #else
 288 #define RA_DBG_START()  ((void)0)
 289 #define RA_DBG_FLUSH()  ((void)0)
 290 #define RA_DBG_REF()    ((void)0)
 291 #define RA_DBGX(x)      ((void)0)
 292 #endif
 293 
 294 /* -- Register allocator -------------------------------------------------- */
 295 
 296 #define ra_free(as, r)          rset_set(as->freeset, (r))
 297 #define ra_modified(as, r)      rset_set(as->modset, (r))
 298 #define ra_weak(as, r)          rset_set(as->weakset, (r))
 299 #define ra_noweak(as, r)        rset_clear(as->weakset, (r))
 300 
 301 #define ra_used(ir)             (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
 302 
 303 /* Setup register allocator. */
 304 static void ra_setup(ASMState *as)
 305 {
 306   Reg r;
 307   /* Initially all regs (except the stack pointer) are free for use. */
 308   as->freeset = RSET_INIT;
 309   as->modset = RSET_EMPTY;
 310   as->weakset = RSET_EMPTY;
 311   as->phiset = RSET_EMPTY;
 312   memset(as->phireg, 0, sizeof(as->phireg));
 313   for (r = RID_MIN_GPR; r < RID_MAX; r++)
 314     as->cost[r] = REGCOST(~0u, 0u);
 315 }
 316 
 317 /* Rematerialize constants. */
 318 static Reg ra_rematk(ASMState *as, IRRef ref)
 319 {
 320   IRIns *ir;
 321   Reg r;
 322   if (ra_iskref(ref)) {
 323     r = ra_krefreg(ref);
 324     lua_assert(!rset_test(as->freeset, r));
 325     ra_free(as, r);
 326     ra_modified(as, r);
 327 #if LJ_64
 328     emit_loadu64(as, r, ra_krefk(as, ref));
 329 #else
 330     emit_loadi(as, r, ra_krefk(as, ref));
 331 #endif
 332     return r;
 333   }
 334   ir = IR(ref);
 335   r = ir->r;
 336   lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
 337   ra_free(as, r);
 338   ra_modified(as, r);
 339   ir->r = RID_INIT;  /* Do not keep any hint. */
 340   RA_DBGX((as, "remat     $i $r", ir, r));
 341 #if !LJ_SOFTFP32
 342   if (ir->o == IR_KNUM) {
 343     emit_loadk64(as, r, ir);
 344   } else
 345 #endif
 346   if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
 347     ra_sethint(ir->r, RID_BASE);  /* Restore BASE register hint. */
 348     emit_getgl(as, r, jit_base);
 349   } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
 350     lua_assert(irt_isnil(ir->t));  /* REF_NIL stores ASMREF_L register. */
 351     emit_getgl(as, r, cur_L);
 352 #if LJ_64
 353   } else if (ir->o == IR_KINT64) {
 354     emit_loadu64(as, r, ir_kint64(ir)->u64);
 355 #if LJ_GC64
 356   } else if (ir->o == IR_KGC) {
 357     emit_loadu64(as, r, (uintptr_t)ir_kgc(ir));
 358   } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
 359     emit_loadu64(as, r, (uintptr_t)ir_kptr(ir));
 360 #endif
 361 #endif
 362   } else {
 363     lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
 364                ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
 365     emit_loadi(as, r, ir->i);
 366   }
 367   return r;
 368 }
 369 
 370 /* Force a spill. Allocate a new spill slot if needed. */
 371 static int32_t ra_spill(ASMState *as, IRIns *ir)
 372 {
 373   int32_t slot = ir->s;
 374   lua_assert(ir >= as->ir + REF_TRUE);
 375   if (!ra_hasspill(slot)) {
 376     if (irt_is64(ir->t)) {
 377       slot = as->evenspill;
 378       as->evenspill += 2;
 379     } else if (as->oddspill) {
 380       slot = as->oddspill;
 381       as->oddspill = 0;
 382     } else {
 383       slot = as->evenspill;
 384       as->oddspill = slot+1;
 385       as->evenspill += 2;
 386     }
 387     if (as->evenspill > 256)
 388       lj_trace_err(as->J, LJ_TRERR_SPILLOV);
 389     ir->s = (uint8_t)slot;
 390   }
 391   return sps_scale(slot);
 392 }
 393 
 394 /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
 395 static Reg ra_releasetmp(ASMState *as, IRRef ref)
 396 {
 397   IRIns *ir = IR(ref);
 398   Reg r = ir->r;
 399   lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
 400   ra_free(as, r);
 401   ra_modified(as, r);
 402   ir->r = RID_INIT;
 403   return r;
 404 }
 405 
 406 /* Restore a register (marked as free). Rematerialize or force a spill. */
 407 static Reg ra_restore(ASMState *as, IRRef ref)
 408 {
 409   if (emit_canremat(ref)) {
 410     return ra_rematk(as, ref);
 411   } else {
 412     IRIns *ir = IR(ref);
 413     int32_t ofs = ra_spill(as, ir);  /* Force a spill slot. */
 414     Reg r = ir->r;
 415     lua_assert(ra_hasreg(r));
 416     ra_sethint(ir->r, r);  /* Keep hint. */
 417     ra_free(as, r);
 418     if (!rset_test(as->weakset, r)) {  /* Only restore non-weak references. */
 419       ra_modified(as, r);
 420       RA_DBGX((as, "restore   $i $r", ir, r));
 421       emit_spload(as, ir, r, ofs);
 422     }
 423     return r;
 424   }
 425 }
 426 
 427 /* Save a register to a spill slot. */
 428 static void ra_save(ASMState *as, IRIns *ir, Reg r)
 429 {
 430   RA_DBGX((as, "save      $i $r", ir, r));
 431   emit_spstore(as, ir, r, sps_scale(ir->s));
 432 }
 433 
 434 #define MINCOST(name) \
 435   if (rset_test(RSET_ALL, RID_##name) && \
 436       LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
 437     cost = as->cost[RID_##name];
 438 
 439 /* Evict the register with the lowest cost, forcing a restore. */
 440 static Reg ra_evict(ASMState *as, RegSet allow)
 441 {
 442   IRRef ref;
 443   RegCost cost = ~(RegCost)0;
 444   lua_assert(allow != RSET_EMPTY);
 445   if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
 446     GPRDEF(MINCOST)
 447   } else {
 448     FPRDEF(MINCOST)
 449   }
 450   ref = regcost_ref(cost);
 451   lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
 452   /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
 453   if (!irref_isk(ref) && (as->weakset & allow)) {
 454     IRIns *ir = IR(ref);
 455     if (!rset_test(as->weakset, ir->r))
 456       ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
 457   }
 458   return ra_restore(as, ref);
 459 }
 460 
 461 /* Pick any register (marked as free). Evict on-demand. */
 462 static Reg ra_pick(ASMState *as, RegSet allow)
 463 {
 464   RegSet pick = as->freeset & allow;
 465   if (!pick)
 466     return ra_evict(as, allow);
 467   else
 468     return rset_picktop(pick);
 469 }
 470 
 471 /* Get a scratch register (marked as free). */
 472 static Reg ra_scratch(ASMState *as, RegSet allow)
 473 {
 474   Reg r = ra_pick(as, allow);
 475   ra_modified(as, r);
 476   RA_DBGX((as, "scratch        $r", r));
 477   return r;
 478 }
 479 
 480 /* Evict all registers from a set (if not free). */
 481 static void ra_evictset(ASMState *as, RegSet drop)
 482 {
 483   RegSet work;
 484   as->modset |= drop;
 485 #if !LJ_SOFTFP
 486   work = (drop & ~as->freeset) & RSET_FPR;
 487   while (work) {
 488     Reg r = rset_pickbot(work);
 489     ra_restore(as, regcost_ref(as->cost[r]));
 490     rset_clear(work, r);
 491     checkmclim(as);
 492   }
 493 #endif
 494   work = (drop & ~as->freeset);
 495   while (work) {
 496     Reg r = rset_pickbot(work);
 497     ra_restore(as, regcost_ref(as->cost[r]));
 498     rset_clear(work, r);
 499     checkmclim(as);
 500   }
 501 }
 502 
 503 /* Evict (rematerialize) all registers allocated to constants. */
 504 static void ra_evictk(ASMState *as)
 505 {
 506   RegSet work;
 507 #if !LJ_SOFTFP
 508   work = ~as->freeset & RSET_FPR;
 509   while (work) {
 510     Reg r = rset_pickbot(work);
 511     IRRef ref = regcost_ref(as->cost[r]);
 512     if (emit_canremat(ref) && irref_isk(ref)) {
 513       ra_rematk(as, ref);
 514       checkmclim(as);
 515     }
 516     rset_clear(work, r);
 517   }
 518 #endif
 519   work = ~as->freeset & RSET_GPR;
 520   while (work) {
 521     Reg r = rset_pickbot(work);
 522     IRRef ref = regcost_ref(as->cost[r]);
 523     if (emit_canremat(ref) && irref_isk(ref)) {
 524       ra_rematk(as, ref);
 525       checkmclim(as);
 526     }
 527     rset_clear(work, r);
 528   }
 529 }
 530 
 531 #ifdef RID_NUM_KREF
 532 /* Allocate a register for a constant. */
 533 static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow)
 534 {
 535   /* First try to find a register which already holds the same constant. */
 536   RegSet pick, work = ~as->freeset & RSET_GPR;
 537   Reg r;
 538   while (work) {
 539     IRRef ref;
 540     r = rset_pickbot(work);
 541     ref = regcost_ref(as->cost[r]);
 542 #if LJ_64
 543     if (ref < ASMREF_L) {
 544       if (ra_iskref(ref)) {
 545         if (k == ra_krefk(as, ref))
 546           return r;
 547       } else {
 548         IRIns *ir = IR(ref);
 549         if ((ir->o == IR_KINT64 && k == (int64_t)ir_kint64(ir)->u64) ||
 550 #if LJ_GC64
 551             (ir->o == IR_KINT && k == ir->i) ||
 552             (ir->o == IR_KGC && k == (intptr_t)ir_kgc(ir)) ||
 553             ((ir->o == IR_KPTR || ir->o == IR_KKPTR) &&
 554              k == (intptr_t)ir_kptr(ir))
 555 #else
 556             (ir->o != IR_KINT64 && k == ir->i)
 557 #endif
 558            )
 559           return r;
 560       }
 561     }
 562 #else
 563     if (ref < ASMREF_L &&
 564         k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
 565       return r;
 566 #endif
 567     rset_clear(work, r);
 568   }
 569   pick = as->freeset & allow;
 570   if (pick) {
 571     /* Constants should preferably get unmodified registers. */
 572     if ((pick & ~as->modset))
 573       pick &= ~as->modset;
 574     r = rset_pickbot(pick);  /* Reduce conflicts with inverse allocation. */
 575   } else {
 576     r = ra_evict(as, allow);
 577   }
 578   RA_DBGX((as, "allock    $x $r", k, r));
 579   ra_setkref(as, r, k);
 580   rset_clear(as->freeset, r);
 581   ra_noweak(as, r);
 582   return r;
 583 }
 584 
 585 /* Allocate a specific register for a constant. */
 586 static void ra_allockreg(ASMState *as, intptr_t k, Reg r)
 587 {
 588   Reg kr = ra_allock(as, k, RID2RSET(r));
 589   if (kr != r) {
 590     IRIns irdummy;
 591     irdummy.t.irt = IRT_INT;
 592     ra_scratch(as, RID2RSET(r));
 593     emit_movrr(as, &irdummy, r, kr);
 594   }
 595 }
 596 #else
 597 #define ra_allockreg(as, k, r)          emit_loadi(as, (r), (k))
 598 #endif
 599 
 600 /* Allocate a register for ref from the allowed set of registers.
 601 ** Note: this function assumes the ref does NOT have a register yet!
 602 ** Picks an optimal register, sets the cost and marks the register as non-free.
 603 */
 604 static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
 605 {
 606   IRIns *ir = IR(ref);
 607   RegSet pick = as->freeset & allow;
 608   Reg r;
 609   lua_assert(ra_noreg(ir->r));
 610   if (pick) {
 611     /* First check register hint from propagation or PHI. */
 612     if (ra_hashint(ir->r)) {
 613       r = ra_gethint(ir->r);
 614       if (rset_test(pick, r))  /* Use hint register if possible. */
 615         goto found;
 616       /* Rematerialization is cheaper than missing a hint. */
 617       if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
 618         ra_rematk(as, regcost_ref(as->cost[r]));
 619         goto found;
 620       }
 621       RA_DBGX((as, "hintmiss  $f $r", ref, r));
 622     }
 623     /* Invariants should preferably get unmodified registers. */
 624     if (ref < as->loopref && !irt_isphi(ir->t)) {
 625       if ((pick & ~as->modset))
 626         pick &= ~as->modset;
 627       r = rset_pickbot(pick);  /* Reduce conflicts with inverse allocation. */
 628     } else {
 629       /* We've got plenty of regs, so get callee-save regs if possible. */
 630       if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
 631         pick &= ~RSET_SCRATCH;
 632       r = rset_picktop(pick);
 633     }
 634   } else {
 635     r = ra_evict(as, allow);
 636   }
 637 found:
 638   RA_DBGX((as, "alloc     $f $r", ref, r));
 639   ir->r = (uint8_t)r;
 640   rset_clear(as->freeset, r);
 641   ra_noweak(as, r);
 642   as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
 643   return r;
 644 }
 645 
 646 /* Allocate a register on-demand. */
 647 static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
 648 {
 649   Reg r = IR(ref)->r;
 650   /* Note: allow is ignored if the register is already allocated. */
 651   if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
 652   ra_noweak(as, r);
 653   return r;
 654 }
 655 
 656 /* Add a register rename to the IR. */
 657 static void ra_addrename(ASMState *as, Reg down, IRRef ref, SnapNo snapno)
 658 {
 659   IRRef ren;
 660   lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, snapno);
 661   ren = tref_ref(lj_ir_emit(as->J));
 662   as->J->cur.ir[ren].r = (uint8_t)down;
 663   as->J->cur.ir[ren].s = SPS_NONE;
 664 }
 665 
 666 /* Rename register allocation and emit move. */
 667 static void ra_rename(ASMState *as, Reg down, Reg up)
 668 {
 669   IRRef ref = regcost_ref(as->cost[up] = as->cost[down]);
 670   IRIns *ir = IR(ref);
 671   ir->r = (uint8_t)up;
 672   as->cost[down] = 0;
 673   lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
 674   lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
 675   ra_free(as, down);  /* 'down' is free ... */
 676   ra_modified(as, down);
 677   rset_clear(as->freeset, up);  /* ... and 'up' is now allocated. */
 678   ra_noweak(as, up);
 679   RA_DBGX((as, "rename    $f $r $r", regcost_ref(as->cost[up]), down, up));
 680   emit_movrr(as, ir, down, up);  /* Backwards codegen needs inverse move. */
 681   if (!ra_hasspill(IR(ref)->s)) {  /* Add the rename to the IR. */
 682     ra_addrename(as, down, ref, as->snapno);
 683   }
 684 }
 685 
 686 /* Pick a destination register (marked as free).
 687 ** Caveat: allow is ignored if there's already a destination register.
 688 ** Use ra_destreg() to get a specific register.
 689 */
 690 static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
 691 {
 692   Reg dest = ir->r;
 693   if (ra_hasreg(dest)) {
 694     ra_free(as, dest);
 695     ra_modified(as, dest);
 696   } else {
 697     if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
 698       dest = ra_gethint(dest);
 699       ra_modified(as, dest);
 700       RA_DBGX((as, "dest           $r", dest));
 701     } else {
 702       dest = ra_scratch(as, allow);
 703     }
 704     ir->r = dest;
 705   }
 706   if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
 707   return dest;
 708 }
 709 
 710 /* Force a specific destination register (marked as free). */
 711 static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
 712 {
 713   Reg dest = ra_dest(as, ir, RID2RSET(r));
 714   if (dest != r) {
 715     lua_assert(rset_test(as->freeset, r));
 716     ra_modified(as, r);
 717     emit_movrr(as, ir, dest, r);
 718   }
 719 }
 720 
 721 #if LJ_TARGET_X86ORX64
 722 /* Propagate dest register to left reference. Emit moves as needed.
 723 ** This is a required fixup step for all 2-operand machine instructions.
 724 */
 725 static void ra_left(ASMState *as, Reg dest, IRRef lref)
 726 {
 727   IRIns *ir = IR(lref);
 728   Reg left = ir->r;
 729   if (ra_noreg(left)) {
 730     if (irref_isk(lref)) {
 731       if (ir->o == IR_KNUM) {
 732         /* FP remat needs a load except for +0. Still better than eviction. */
 733         if (tvispzero(ir_knum(ir)) || !(as->freeset & RSET_FPR)) {
 734           emit_loadk64(as, dest, ir);
 735           return;
 736         }
 737 #if LJ_64
 738       } else if (ir->o == IR_KINT64) {
 739         emit_loadk64(as, dest, ir);
 740         return;
 741 #if LJ_GC64
 742       } else if (ir->o == IR_KGC || ir->o == IR_KPTR || ir->o == IR_KKPTR) {
 743         emit_loadk64(as, dest, ir);
 744         return;
 745 #endif
 746 #endif
 747       } else if (ir->o != IR_KPRI) {
 748         lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
 749                    ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
 750         emit_loadi(as, dest, ir->i);
 751         return;
 752       }
 753     }
 754     if (!ra_hashint(left) && !iscrossref(as, lref))
 755       ra_sethint(ir->r, dest);  /* Propagate register hint. */
 756     left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
 757   }
 758   ra_noweak(as, left);
 759   /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
 760   if (dest != left) {
 761     /* Use register renaming if dest is the PHI reg. */
 762     if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
 763       ra_modified(as, left);
 764       ra_rename(as, left, dest);
 765     } else {
 766       emit_movrr(as, ir, dest, left);
 767     }
 768   }
 769 }
 770 #else
 771 /* Similar to ra_left, except we override any hints. */
 772 static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
 773 {
 774   IRIns *ir = IR(lref);
 775   Reg left = ir->r;
 776   if (ra_noreg(left)) {
 777     ra_sethint(ir->r, dest);  /* Propagate register hint. */
 778     left = ra_allocref(as, lref,
 779                        (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
 780   }
 781   ra_noweak(as, left);
 782   if (dest != left) {
 783     /* Use register renaming if dest is the PHI reg. */
 784     if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
 785       ra_modified(as, left);
 786       ra_rename(as, left, dest);
 787     } else {
 788       emit_movrr(as, ir, dest, left);
 789     }
 790   }
 791 }
 792 #endif
 793 
 794 #if !LJ_64
 795 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
 796 static void ra_destpair(ASMState *as, IRIns *ir)
 797 {
 798   Reg destlo = ir->r, desthi = (ir+1)->r;
 799   /* First spill unrelated refs blocking the destination registers. */
 800   if (!rset_test(as->freeset, RID_RETLO) &&
 801       destlo != RID_RETLO && desthi != RID_RETLO)
 802     ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
 803   if (!rset_test(as->freeset, RID_RETHI) &&
 804       destlo != RID_RETHI && desthi != RID_RETHI)
 805     ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
 806   /* Next free the destination registers (if any). */
 807   if (ra_hasreg(destlo)) {
 808     ra_free(as, destlo);
 809     ra_modified(as, destlo);
 810   } else {
 811     destlo = RID_RETLO;
 812   }
 813   if (ra_hasreg(desthi)) {
 814     ra_free(as, desthi);
 815     ra_modified(as, desthi);
 816   } else {
 817     desthi = RID_RETHI;
 818   }
 819   /* Check for conflicts and shuffle the registers as needed. */
 820   if (destlo == RID_RETHI) {
 821     if (desthi == RID_RETLO) {
 822 #if LJ_TARGET_X86
 823       *--as->mcp = XI_XCHGa + RID_RETHI;
 824 #else
 825       emit_movrr(as, ir, RID_RETHI, RID_TMP);
 826       emit_movrr(as, ir, RID_RETLO, RID_RETHI);
 827       emit_movrr(as, ir, RID_TMP, RID_RETLO);
 828 #endif
 829     } else {
 830       emit_movrr(as, ir, RID_RETHI, RID_RETLO);
 831       if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
 832     }
 833   } else if (desthi == RID_RETLO) {
 834     emit_movrr(as, ir, RID_RETLO, RID_RETHI);
 835     if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
 836   } else {
 837     if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
 838     if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
 839   }
 840   /* Restore spill slots (if any). */
 841   if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
 842   if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
 843 }
 844 #endif
 845 
 846 /* -- Snapshot handling --------- ----------------------------------------- */
 847 
 848 /* Can we rematerialize a KNUM instead of forcing a spill? */
 849 static int asm_snap_canremat(ASMState *as)
 850 {
 851   Reg r;
 852   for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
 853     if (irref_isk(regcost_ref(as->cost[r])))
 854       return 1;
 855   return 0;
 856 }
 857 
 858 /* Check whether a sunk store corresponds to an allocation. */
 859 static int asm_sunk_store(ASMState *as, IRIns *ira, IRIns *irs)
 860 {
 861   if (irs->s == 255) {
 862     if (irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
 863         irs->o == IR_FSTORE || irs->o == IR_XSTORE) {
 864       IRIns *irk = IR(irs->op1);
 865       if (irk->o == IR_AREF || irk->o == IR_HREFK)
 866         irk = IR(irk->op1);
 867       return (IR(irk->op1) == ira);
 868     }
 869     return 0;
 870   } else {
 871     return (ira + irs->s == irs);  /* Quick check. */
 872   }
 873 }
 874 
 875 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
 876 static void asm_snap_alloc1(ASMState *as, IRRef ref)
 877 {
 878   IRIns *ir = IR(ref);
 879   if (!irref_isk(ref) && (!(ra_used(ir) || ir->r == RID_SUNK))) {
 880     if (ir->r == RID_SINK) {
 881       ir->r = RID_SUNK;
 882 #if LJ_HASFFI
 883       if (ir->o == IR_CNEWI) {  /* Allocate CNEWI value. */
 884         asm_snap_alloc1(as, ir->op2);
 885         if (LJ_32 && (ir+1)->o == IR_HIOP)
 886           asm_snap_alloc1(as, (ir+1)->op2);
 887       } else
 888 #endif
 889       {  /* Allocate stored values for TNEW, TDUP and CNEW. */
 890         IRIns *irs;
 891         lua_assert(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW);
 892         for (irs = IR(as->snapref-1); irs > ir; irs--)
 893           if (irs->r == RID_SINK && asm_sunk_store(as, ir, irs)) {
 894             lua_assert(irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
 895                        irs->o == IR_FSTORE || irs->o == IR_XSTORE);
 896             asm_snap_alloc1(as, irs->op2);
 897             if (LJ_32 && (irs+1)->o == IR_HIOP)
 898               asm_snap_alloc1(as, (irs+1)->op2);
 899           }
 900       }
 901     } else {
 902       RegSet allow;
 903       if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT) {
 904         IRIns *irc;
 905         for (irc = IR(as->curins); irc > ir; irc--)
 906           if ((irc->op1 == ref || irc->op2 == ref) &&
 907               !(irc->r == RID_SINK || irc->r == RID_SUNK))
 908             goto nosink;  /* Don't sink conversion if result is used. */
 909         asm_snap_alloc1(as, ir->op1);
 910         return;
 911       }
 912     nosink:
 913       allow = (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR;
 914       if ((as->freeset & allow) ||
 915                (allow == RSET_FPR && asm_snap_canremat(as))) {
 916         /* Get a weak register if we have a free one or can rematerialize. */
 917         Reg r = ra_allocref(as, ref, allow);  /* Allocate a register. */
 918         if (!irt_isphi(ir->t))
 919           ra_weak(as, r);  /* But mark it as weakly referenced. */
 920         checkmclim(as);
 921         RA_DBGX((as, "snapreg   $f $r", ref, ir->r));
 922       } else {
 923         ra_spill(as, ir);  /* Otherwise force a spill slot. */
 924         RA_DBGX((as, "snapspill $f $s", ref, ir->s));
 925       }
 926     }
 927   }
 928 }
 929 
 930 /* Allocate refs escaping to a snapshot. */
 931 static void asm_snap_alloc(ASMState *as)
 932 {
 933   SnapShot *snap = &as->T->snap[as->snapno];
 934   SnapEntry *map = &as->T->snapmap[snap->mapofs];
 935   MSize n, nent = snap->nent;
 936   for (n = 0; n < nent; n++) {
 937     SnapEntry sn = map[n];
 938     IRRef ref = snap_ref(sn);
 939     if (!irref_isk(ref)) {
 940       asm_snap_alloc1(as, ref);
 941       if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
 942         lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP);
 943         asm_snap_alloc1(as, ref+1);
 944       }
 945     }
 946   }
 947 }
 948 
 949 /* All guards for a snapshot use the same exitno. This is currently the
 950 ** same as the snapshot number. Since the exact origin of the exit cannot
 951 ** be determined, all guards for the same snapshot must exit with the same
 952 ** RegSP mapping.
 953 ** A renamed ref which has been used in a prior guard for the same snapshot
 954 ** would cause an inconsistency. The easy way out is to force a spill slot.
 955 */
 956 static int asm_snap_checkrename(ASMState *as, IRRef ren)
 957 {
 958   SnapShot *snap = &as->T->snap[as->snapno];
 959   SnapEntry *map = &as->T->snapmap[snap->mapofs];
 960   MSize n, nent = snap->nent;
 961   for (n = 0; n < nent; n++) {
 962     SnapEntry sn = map[n];
 963     IRRef ref = snap_ref(sn);
 964     if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
 965       IRIns *ir = IR(ref);
 966       ra_spill(as, ir);  /* Register renamed, so force a spill slot. */
 967       RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
 968       return 1;  /* Found. */
 969     }
 970   }
 971   return 0;  /* Not found. */
 972 }
 973 
 974 /* Prepare snapshot for next guard instruction. */
 975 static void asm_snap_prep(ASMState *as)
 976 {
 977   if (as->curins < as->snapref) {
 978     do {
 979       if (as->snapno == 0) return;  /* Called by sunk stores before snap #0. */
 980       as->snapno--;
 981       as->snapref = as->T->snap[as->snapno].ref;
 982     } while (as->curins < as->snapref);
 983     asm_snap_alloc(as);
 984     as->snaprename = as->T->nins;
 985   } else {
 986     /* Process any renames above the highwater mark. */
 987     for (; as->snaprename < as->T->nins; as->snaprename++) {
 988       IRIns *ir = &as->T->ir[as->snaprename];
 989       if (asm_snap_checkrename(as, ir->op1))
 990         ir->op2 = REF_BIAS-1;  /* Kill rename. */
 991     }
 992   }
 993 }
 994 
 995 /* -- Miscellaneous helpers ----------------------------------------------- */
 996 
 997 /* Calculate stack adjustment. */
 998 static int32_t asm_stack_adjust(ASMState *as)
 999 {
1000   if (as->evenspill <= SPS_FIXED)
1001     return 0;
1002   return sps_scale(sps_align(as->evenspill));
1003 }
1004 
1005 /* Must match with hash*() in lj_tab.c. */
1006 static uint32_t ir_khash(IRIns *ir)
1007 {
1008   uint32_t lo, hi;
1009   if (irt_isstr(ir->t)) {
1010     return ir_kstr(ir)->hash;
1011   } else if (irt_isnum(ir->t)) {
1012     lo = ir_knum(ir)->u32.lo;
1013     hi = ir_knum(ir)->u32.hi << 1;
1014   } else if (irt_ispri(ir->t)) {
1015     lua_assert(!irt_isnil(ir->t));
1016     return irt_type(ir->t)-IRT_FALSE;
1017   } else {
1018     lua_assert(irt_isgcv(ir->t));
1019     lo = u32ptr(ir_kgc(ir));
1020 #if LJ_GC64
1021     hi = (uint32_t)(u64ptr(ir_kgc(ir)) >> 32) | (irt_toitype(ir->t) << 15);
1022 #else
1023     hi = lo + HASH_BIAS;
1024 #endif
1025   }
1026   return hashrot(lo, hi);
1027 }
1028 
1029 /* -- Allocations --------------------------------------------------------- */
1030 
1031 static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
1032 static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
1033 
1034 static void asm_snew(ASMState *as, IRIns *ir)
1035 {
1036   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
1037   IRRef args[3];
1038   args[0] = ASMREF_L;  /* lua_State *L    */
1039   args[1] = ir->op1;   /* const char *str */
1040   args[2] = ir->op2;   /* size_t len      */
1041   as->gcsteps++;
1042   asm_setupresult(as, ir, ci);  /* GCstr * */
1043   asm_gencall(as, ci, args);
1044 }
1045 
1046 static void asm_tnew(ASMState *as, IRIns *ir)
1047 {
1048   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
1049   IRRef args[2];
1050   args[0] = ASMREF_L;     /* lua_State *L    */
1051   args[1] = ASMREF_TMP1;  /* uint32_t ahsize */
1052   as->gcsteps++;
1053   asm_setupresult(as, ir, ci);  /* GCtab * */
1054   asm_gencall(as, ci, args);
1055   ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
1056 }
1057 
1058 static void asm_tdup(ASMState *as, IRIns *ir)
1059 {
1060   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
1061   IRRef args[2];
1062   args[0] = ASMREF_L;  /* lua_State *L    */
1063   args[1] = ir->op1;   /* const GCtab *kt */
1064   as->gcsteps++;
1065   asm_setupresult(as, ir, ci);  /* GCtab * */
1066   asm_gencall(as, ci, args);
1067 }
1068 
1069 static void asm_gc_check(ASMState *as);
1070 
1071 /* Explicit GC step. */
1072 static void asm_gcstep(ASMState *as, IRIns *ir)
1073 {
1074   IRIns *ira;
1075   for (ira = IR(as->stopins+1); ira < ir; ira++)
1076     if ((ira->o == IR_TNEW || ira->o == IR_TDUP ||
1077          (LJ_HASFFI && (ira->o == IR_CNEW || ira->o == IR_CNEWI))) &&
1078         ra_used(ira))
1079       as->gcsteps++;
1080   if (as->gcsteps)
1081     asm_gc_check(as);
1082   as->gcsteps = 0x80000000;  /* Prevent implicit GC check further up. */
1083 }
1084 
1085 /* -- Buffer operations --------------------------------------------------- */
1086 
1087 static void asm_tvptr(ASMState *as, Reg dest, IRRef ref);
1088 
1089 static void asm_bufhdr(ASMState *as, IRIns *ir)
1090 {
1091   Reg sb = ra_dest(as, ir, RSET_GPR);
1092   if ((ir->op2 & IRBUFHDR_APPEND)) {
1093     /* Rematerialize const buffer pointer instead of likely spill. */
1094     IRIns *irp = IR(ir->op1);
1095     if (!(ra_hasreg(irp->r) || irp == ir-1 ||
1096           (irp == ir-2 && !ra_used(ir-1)))) {
1097       while (!(irp->o == IR_BUFHDR && !(irp->op2 & IRBUFHDR_APPEND)))
1098         irp = IR(irp->op1);
1099       if (irref_isk(irp->op1)) {
1100         ra_weak(as, ra_allocref(as, ir->op1, RSET_GPR));
1101         ir = irp;
1102       }
1103     }
1104   } else {
1105     Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb));
1106     /* Passing ir isn't strictly correct, but it's an IRT_PGC, too. */
1107     emit_storeofs(as, ir, tmp, sb, offsetof(SBuf, p));
1108     emit_loadofs(as, ir, tmp, sb, offsetof(SBuf, b));
1109   }
1110 #if LJ_TARGET_X86ORX64
1111   ra_left(as, sb, ir->op1);
1112 #else
1113   ra_leftov(as, sb, ir->op1);
1114 #endif
1115 }
1116 
1117 static void asm_bufput(ASMState *as, IRIns *ir)
1118 {
1119   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_putstr];
1120   IRRef args[3];
1121   IRIns *irs;
1122   int kchar = -1;
1123   args[0] = ir->op1;  /* SBuf * */
1124   args[1] = ir->op2;  /* GCstr * */
1125   irs = IR(ir->op2);
1126   lua_assert(irt_isstr(irs->t));
1127   if (irs->o == IR_KGC) {
1128     GCstr *s = ir_kstr(irs);
1129     if (s->len == 1) {  /* Optimize put of single-char string constant. */
1130       kchar = strdata(s)[0];
1131       args[1] = ASMREF_TMP1;  /* int, truncated to char */
1132       ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar];
1133     }
1134   } else if (mayfuse(as, ir->op2) && ra_noreg(irs->r)) {
1135     if (irs->o == IR_TOSTR) {  /* Fuse number to string conversions. */
1136       if (irs->op2 == IRTOSTR_NUM) {
1137         args[1] = ASMREF_TMP1;  /* TValue * */
1138         ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putnum];
1139       } else {
1140         lua_assert(irt_isinteger(IR(irs->op1)->t));
1141         args[1] = irs->op1;  /* int */
1142         if (irs->op2 == IRTOSTR_INT)
1143           ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putint];
1144         else
1145           ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar];
1146       }
1147     } else if (irs->o == IR_SNEW) {  /* Fuse string allocation. */
1148       args[1] = irs->op1;  /* const void * */
1149       args[2] = irs->op2;  /* MSize */
1150       ci = &lj_ir_callinfo[IRCALL_lj_buf_putmem];
1151     }
1152   }
1153   asm_setupresult(as, ir, ci);  /* SBuf * */
1154   asm_gencall(as, ci, args);
1155   if (args[1] == ASMREF_TMP1) {
1156     Reg tmp = ra_releasetmp(as, ASMREF_TMP1);
1157     if (kchar == -1)
1158       asm_tvptr(as, tmp, irs->op1);
1159     else
1160       ra_allockreg(as, kchar, tmp);
1161   }
1162 }
1163 
1164 static void asm_bufstr(ASMState *as, IRIns *ir)
1165 {
1166   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_tostr];
1167   IRRef args[1];
1168   args[0] = ir->op1;  /* SBuf *sb */
1169   as->gcsteps++;
1170   asm_setupresult(as, ir, ci);  /* GCstr * */
1171   asm_gencall(as, ci, args);
1172 }
1173 
1174 /* -- Type conversions ---------------------------------------------------- */
1175 
1176 static void asm_tostr(ASMState *as, IRIns *ir)
1177 {
1178   const CCallInfo *ci;
1179   IRRef args[2];
1180   args[0] = ASMREF_L;
1181   as->gcsteps++;
1182   if (ir->op2 == IRTOSTR_NUM) {
1183     args[1] = ASMREF_TMP1;  /* cTValue * */
1184     ci = &lj_ir_callinfo[IRCALL_lj_strfmt_num];
1185   } else {
1186     args[1] = ir->op1;  /* int32_t k */
1187     if (ir->op2 == IRTOSTR_INT)
1188       ci = &lj_ir_callinfo[IRCALL_lj_strfmt_int];
1189     else
1190       ci = &lj_ir_callinfo[IRCALL_lj_strfmt_char];
1191   }
1192   asm_setupresult(as, ir, ci);  /* GCstr * */
1193   asm_gencall(as, ci, args);
1194   if (ir->op2 == IRTOSTR_NUM)
1195     asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1);
1196 }
1197 
1198 #if LJ_32 && LJ_HASFFI && !LJ_SOFTFP && !LJ_TARGET_X86
1199 static void asm_conv64(ASMState *as, IRIns *ir)
1200 {
1201   IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
1202   IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
1203   IRCallID id;
1204   IRRef args[2];
1205   lua_assert((ir-1)->o == IR_CONV && ir->o == IR_HIOP);
1206   args[LJ_BE] = (ir-1)->op1;
1207   args[LJ_LE] = ir->op1;
1208   if (st == IRT_NUM || st == IRT_FLOAT) {
1209     id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64);
1210     ir--;
1211   } else {
1212     id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64);
1213   }
1214   {
1215 #if LJ_TARGET_ARM && !LJ_ABI_SOFTFP
1216     CCallInfo cim = lj_ir_callinfo[id], *ci = &cim;
1217     cim.flags |= CCI_VARARG;  /* These calls don't use the hard-float ABI! */
1218 #else
1219     const CCallInfo *ci = &lj_ir_callinfo[id];
1220 #endif
1221     asm_setupresult(as, ir, ci);
1222     asm_gencall(as, ci, args);
1223   }
1224 }
1225 #endif
1226 
1227 /* -- Memory references --------------------------------------------------- */
1228 
1229 static void asm_newref(ASMState *as, IRIns *ir)
1230 {
1231   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
1232   IRRef args[3];
1233   if (ir->r == RID_SINK)
1234     return;
1235   args[0] = ASMREF_L;     /* lua_State *L */
1236   args[1] = ir->op1;      /* GCtab *t     */
1237   args[2] = ASMREF_TMP1;  /* cTValue *key */
1238   asm_setupresult(as, ir, ci);  /* TValue * */
1239   asm_gencall(as, ci, args);
1240   asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2);
1241 }
1242 
1243 static void asm_lref(ASMState *as, IRIns *ir)
1244 {
1245   Reg r = ra_dest(as, ir, RSET_GPR);
1246 #if LJ_TARGET_X86ORX64
1247   ra_left(as, r, ASMREF_L);
1248 #else
1249   ra_leftov(as, r, ASMREF_L);
1250 #endif
1251 }
1252 
1253 /* -- Calls --------------------------------------------------------------- */
1254 
1255 /* Collect arguments from CALL* and CARG instructions. */
1256 static void asm_collectargs(ASMState *as, IRIns *ir,
1257                             const CCallInfo *ci, IRRef *args)
1258 {
1259   uint32_t n = CCI_XNARGS(ci);
1260   lua_assert(n <= CCI_NARGS_MAX*2);  /* Account for split args. */
1261   if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
1262   while (n-- > 1) {
1263     ir = IR(ir->op1);
1264     lua_assert(ir->o == IR_CARG);
1265     args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
1266   }
1267   args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
1268   lua_assert(IR(ir->op1)->o != IR_CARG);
1269 }
1270 
1271 /* Reconstruct CCallInfo flags for CALLX*. */
1272 static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
1273 {
1274   uint32_t nargs = 0;
1275   if (ir->op1 != REF_NIL) {  /* Count number of arguments first. */
1276     IRIns *ira = IR(ir->op1);
1277     nargs++;
1278     while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
1279   }
1280 #if LJ_HASFFI
1281   if (IR(ir->op2)->o == IR_CARG) {  /* Copy calling convention info. */
1282     CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
1283     CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
1284     nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
1285 #if LJ_TARGET_X86
1286     nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
1287 #endif
1288   }
1289 #endif
1290   return (nargs | (ir->t.irt << CCI_OTSHIFT));
1291 }
1292 
1293 static void asm_callid(ASMState *as, IRIns *ir, IRCallID id)
1294 {
1295   const CCallInfo *ci = &lj_ir_callinfo[id];
1296   IRRef args[2];
1297   args[0] = ir->op1;
1298   args[1] = ir->op2;
1299   asm_setupresult(as, ir, ci);
1300   asm_gencall(as, ci, args);
1301 }
1302 
1303 static void asm_call(ASMState *as, IRIns *ir)
1304 {
1305   IRRef args[CCI_NARGS_MAX];
1306   const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1307   asm_collectargs(as, ir, ci, args);
1308   asm_setupresult(as, ir, ci);
1309   asm_gencall(as, ci, args);
1310 }
1311 
1312 #if !LJ_SOFTFP32
1313 static void asm_fppow(ASMState *as, IRIns *ir, IRRef lref, IRRef rref)
1314 {
1315   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_pow];
1316   IRRef args[2];
1317   args[0] = lref;
1318   args[1] = rref;
1319   asm_setupresult(as, ir, ci);
1320   asm_gencall(as, ci, args);
1321 }
1322 
1323 static int asm_fpjoin_pow(ASMState *as, IRIns *ir)
1324 {
1325   IRIns *irp = IR(ir->op1);
1326   if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) {
1327     IRIns *irpp = IR(irp->op1);
1328     if (irpp == ir-2 && irpp->o == IR_FPMATH &&
1329         irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) {
1330       asm_fppow(as, ir, irpp->op1, irp->op2);
1331       return 1;
1332     }
1333   }
1334   return 0;
1335 }
1336 #endif
1337 
1338 /* -- PHI and loop handling ----------------------------------------------- */
1339 
1340 /* Break a PHI cycle by renaming to a free register (evict if needed). */
1341 static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
1342                           RegSet allow)
1343 {
1344   RegSet candidates = blocked & allow;
1345   if (candidates) {  /* If this register file has candidates. */
1346     /* Note: the set for ra_pick cannot be empty, since each register file
1347     ** has some registers never allocated to PHIs.
1348     */
1349     Reg down, up = ra_pick(as, ~blocked & allow);  /* Get a free register. */
1350     if (candidates & ~blockedby)  /* Optimize shifts, else it's a cycle. */
1351       candidates = candidates & ~blockedby;
1352     down = rset_picktop(candidates);  /* Pick candidate PHI register. */
1353     ra_rename(as, down, up);  /* And rename it to the free register. */
1354   }
1355 }
1356 
1357 /* PHI register shuffling.
1358 **
1359 ** The allocator tries hard to preserve PHI register assignments across
1360 ** the loop body. Most of the time this loop does nothing, since there
1361 ** are no register mismatches.
1362 **
1363 ** If a register mismatch is detected and ...
1364 ** - the register is currently free: rename it.
1365 ** - the register is blocked by an invariant: restore/remat and rename it.
1366 ** - Otherwise the register is used by another PHI, so mark it as blocked.
1367 **
1368 ** The renames are order-sensitive, so just retry the loop if a register
1369 ** is marked as blocked, but has been freed in the meantime. A cycle is
1370 ** detected if all of the blocked registers are allocated. To break the
1371 ** cycle rename one of them to a free register and retry.
1372 **
1373 ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1374 */
1375 static void asm_phi_shuffle(ASMState *as)
1376 {
1377   RegSet work;
1378 
1379   /* Find and resolve PHI register mismatches. */
1380   for (;;) {
1381     RegSet blocked = RSET_EMPTY;
1382     RegSet blockedby = RSET_EMPTY;
1383     RegSet phiset = as->phiset;
1384     while (phiset) {  /* Check all left PHI operand registers. */
1385       Reg r = rset_pickbot(phiset);
1386       IRIns *irl = IR(as->phireg[r]);
1387       Reg left = irl->r;
1388       if (r != left) {  /* Mismatch? */
1389         if (!rset_test(as->freeset, r)) {  /* PHI register blocked? */
1390           IRRef ref = regcost_ref(as->cost[r]);
1391           /* Blocked by other PHI (w/reg)? */
1392           if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
1393             rset_set(blocked, r);
1394             if (ra_hasreg(left))
1395               rset_set(blockedby, left);
1396             left = RID_NONE;
1397           } else {  /* Otherwise grab register from invariant. */
1398             ra_restore(as, ref);
1399             checkmclim(as);
1400           }
1401         }
1402         if (ra_hasreg(left)) {
1403           ra_rename(as, left, r);
1404           checkmclim(as);
1405         }
1406       }
1407       rset_clear(phiset, r);
1408     }
1409     if (!blocked) break;  /* Finished. */
1410     if (!(as->freeset & blocked)) {  /* Break cycles if none are free. */
1411       asm_phi_break(as, blocked, blockedby, RSET_GPR);
1412       if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
1413       checkmclim(as);
1414     }  /* Else retry some more renames. */
1415   }
1416 
1417   /* Restore/remat invariants whose registers are modified inside the loop. */
1418 #if !LJ_SOFTFP
1419   work = as->modset & ~(as->freeset | as->phiset) & RSET_FPR;
1420   while (work) {
1421     Reg r = rset_pickbot(work);
1422     ra_restore(as, regcost_ref(as->cost[r]));
1423     rset_clear(work, r);
1424     checkmclim(as);
1425   }
1426 #endif
1427   work = as->modset & ~(as->freeset | as->phiset);
1428   while (work) {
1429     Reg r = rset_pickbot(work);
1430     ra_restore(as, regcost_ref(as->cost[r]));
1431     rset_clear(work, r);
1432     checkmclim(as);
1433   }
1434 
1435   /* Allocate and save all unsaved PHI regs and clear marks. */
1436   work = as->phiset;
1437   while (work) {
1438     Reg r = rset_picktop(work);
1439     IRRef lref = as->phireg[r];
1440     IRIns *ir = IR(lref);
1441     if (ra_hasspill(ir->s)) {  /* Left PHI gained a spill slot? */
1442       irt_clearmark(ir->t);  /* Handled here, so clear marker now. */
1443       ra_alloc1(as, lref, RID2RSET(r));
1444       ra_save(as, ir, r);  /* Save to spill slot inside the loop. */
1445       checkmclim(as);
1446     }
1447     rset_clear(work, r);
1448   }
1449 }
1450 
1451 /* Copy unsynced left/right PHI spill slots. Rarely needed. */
1452 static void asm_phi_copyspill(ASMState *as)
1453 {
1454   int need = 0;
1455   IRIns *ir;
1456   for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--)
1457     if (ra_hasspill(ir->s) && ra_hasspill(IR(ir->op1)->s))
1458       need |= irt_isfp(ir->t) ? 2 : 1;  /* Unsynced spill slot? */
1459   if ((need & 1)) {  /* Copy integer spill slots. */
1460 #if !LJ_TARGET_X86ORX64
1461     Reg r = RID_TMP;
1462 #else
1463     Reg r = RID_RET;
1464     if ((as->freeset & RSET_GPR))
1465       r = rset_pickbot((as->freeset & RSET_GPR));
1466     else
1467       emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1468 #endif
1469     for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
1470       if (ra_hasspill(ir->s)) {
1471         IRIns *irl = IR(ir->op1);
1472         if (ra_hasspill(irl->s) && !irt_isfp(ir->t)) {
1473           emit_spstore(as, irl, r, sps_scale(irl->s));
1474           emit_spload(as, ir, r, sps_scale(ir->s));
1475           checkmclim(as);
1476         }
1477       }
1478     }
1479 #if LJ_TARGET_X86ORX64
1480     if (!rset_test(as->freeset, r))
1481       emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1482 #endif
1483   }
1484 #if !LJ_SOFTFP
1485   if ((need & 2)) {  /* Copy FP spill slots. */
1486 #if LJ_TARGET_X86
1487     Reg r = RID_XMM0;
1488 #else
1489     Reg r = RID_FPRET;
1490 #endif
1491     if ((as->freeset & RSET_FPR))
1492       r = rset_pickbot((as->freeset & RSET_FPR));
1493     if (!rset_test(as->freeset, r))
1494       emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1495     for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
1496       if (ra_hasspill(ir->s)) {
1497         IRIns *irl = IR(ir->op1);
1498         if (ra_hasspill(irl->s) && irt_isfp(ir->t)) {
1499           emit_spstore(as, irl, r, sps_scale(irl->s));
1500           emit_spload(as, ir, r, sps_scale(ir->s));
1501           checkmclim(as);
1502         }
1503       }
1504     }
1505     if (!rset_test(as->freeset, r))
1506       emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1507   }
1508 #endif
1509 }
1510 
1511 /* Emit renames for left PHIs which are only spilled outside the loop. */
1512 static void asm_phi_fixup(ASMState *as)
1513 {
1514   RegSet work = as->phiset;
1515   while (work) {
1516     Reg r = rset_picktop(work);
1517     IRRef lref = as->phireg[r];
1518     IRIns *ir = IR(lref);
1519     if (irt_ismarked(ir->t)) {
1520       irt_clearmark(ir->t);
1521       /* Left PHI gained a spill slot before the loop? */
1522       if (ra_hasspill(ir->s)) {
1523         ra_addrename(as, r, lref, as->loopsnapno);
1524       }
1525     }
1526     rset_clear(work, r);
1527   }
1528 }
1529 
1530 /* Setup right PHI reference. */
1531 static void asm_phi(ASMState *as, IRIns *ir)
1532 {
1533   RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
1534                  ~as->phiset;
1535   RegSet afree = (as->freeset & allow);
1536   IRIns *irl = IR(ir->op1);
1537   IRIns *irr = IR(ir->op2);
1538   if (ir->r == RID_SINK)  /* Sink PHI. */
1539     return;
1540   /* Spill slot shuffling is not implemented yet (but rarely needed). */
1541   if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
1542     lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1543   /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
1544   if ((afree & (afree-1))) {  /* Two or more free registers? */
1545     Reg r;
1546     if (ra_noreg(irr->r)) {  /* Get a register for the right PHI. */
1547       r = ra_allocref(as, ir->op2, allow);
1548     } else {  /* Duplicate right PHI, need a copy (rare). */
1549       r = ra_scratch(as, allow);
1550       emit_movrr(as, irr, r, irr->r);
1551     }
1552     ir->r = (uint8_t)r;
1553     rset_set(as->phiset, r);
1554     as->phireg[r] = (IRRef1)ir->op1;
1555     irt_setmark(irl->t);  /* Marks left PHIs _with_ register. */
1556     if (ra_noreg(irl->r))
1557       ra_sethint(irl->r, r); /* Set register hint for left PHI. */
1558   } else {  /* Otherwise allocate a spill slot. */
1559     /* This is overly restrictive, but it triggers only on synthetic code. */
1560     if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
1561       lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1562     ra_spill(as, ir);
1563     irr->s = ir->s;  /* Set right PHI spill slot. Sync left slot later. */
1564   }
1565 }
1566 
1567 static void asm_loop_fixup(ASMState *as);
1568 
1569 /* Middle part of a loop. */
1570 static void asm_loop(ASMState *as)
1571 {
1572   MCode *mcspill;
1573   /* LOOP is a guard, so the snapno is up to date. */
1574   as->loopsnapno = as->snapno;
1575   if (as->gcsteps)
1576     asm_gc_check(as);
1577   /* LOOP marks the transition from the variant to the invariant part. */
1578   as->flagmcp = as->invmcp = NULL;
1579   as->sectref = 0;
1580   if (!neverfuse(as)) as->fuseref = 0;
1581   asm_phi_shuffle(as);
1582   mcspill = as->mcp;
1583   asm_phi_copyspill(as);
1584   asm_loop_fixup(as);
1585   as->mcloop = as->mcp;
1586   RA_DBGX((as, "===== LOOP ====="));
1587   if (!as->realign) RA_DBG_FLUSH();
1588   if (as->mcp != mcspill)
1589     emit_jmp(as, mcspill);
1590 }
1591 
1592 /* -- Target-specific assembler ------------------------------------------- */
1593 
1594 #if LJ_TARGET_X86ORX64
1595 #include "lj_asm_x86.h"
1596 #elif LJ_TARGET_ARM
1597 #include "lj_asm_arm.h"
1598 #elif LJ_TARGET_ARM64
1599 #include "lj_asm_arm64.h"
1600 #elif LJ_TARGET_PPC
1601 #include "lj_asm_ppc.h"
1602 #elif LJ_TARGET_MIPS
1603 #include "lj_asm_mips.h"
1604 #else
1605 #error "Missing assembler for target CPU"
1606 #endif
1607 
1608 /* -- Instruction dispatch ------------------------------------------------ */
1609 
1610 /* Assemble a single instruction. */
1611 static void asm_ir(ASMState *as, IRIns *ir)
1612 {
1613   switch ((IROp)ir->o) {
1614   /* Miscellaneous ops. */
1615   case IR_LOOP: asm_loop(as); break;
1616   case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
1617   case IR_USE:
1618     ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
1619   case IR_PHI: asm_phi(as, ir); break;
1620   case IR_HIOP: asm_hiop(as, ir); break;
1621   case IR_GCSTEP: asm_gcstep(as, ir); break;
1622   case IR_PROF: asm_prof(as, ir); break;
1623 
1624   /* Guarded assertions. */
1625   case IR_LT: case IR_GE: case IR_LE: case IR_GT:
1626   case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
1627   case IR_ABC:
1628     asm_comp(as, ir);
1629     break;
1630   case IR_EQ: case IR_NE:
1631     if ((ir-1)->o == IR_HREF && ir->op1 == as->curins-1) {
1632       as->curins--;
1633       asm_href(as, ir-1, (IROp)ir->o);
1634     } else {
1635       asm_equal(as, ir);
1636     }
1637     break;
1638 
1639   case IR_RETF: asm_retf(as, ir); break;
1640 
1641   /* Bit ops. */
1642   case IR_BNOT: asm_bnot(as, ir); break;
1643   case IR_BSWAP: asm_bswap(as, ir); break;
1644   case IR_BAND: asm_band(as, ir); break;
1645   case IR_BOR: asm_bor(as, ir); break;
1646   case IR_BXOR: asm_bxor(as, ir); break;
1647   case IR_BSHL: asm_bshl(as, ir); break;
1648   case IR_BSHR: asm_bshr(as, ir); break;
1649   case IR_BSAR: asm_bsar(as, ir); break;
1650   case IR_BROL: asm_brol(as, ir); break;
1651   case IR_BROR: asm_bror(as, ir); break;
1652 
1653   /* Arithmetic ops. */
1654   case IR_ADD: asm_add(as, ir); break;
1655   case IR_SUB: asm_sub(as, ir); break;
1656   case IR_MUL: asm_mul(as, ir); break;
1657   case IR_MOD: asm_mod(as, ir); break;
1658   case IR_NEG: asm_neg(as, ir); break;
1659 #if LJ_SOFTFP32
1660   case IR_DIV: case IR_POW: case IR_ABS:
1661   case IR_ATAN2: case IR_LDEXP: case IR_FPMATH: case IR_TOBIT:
1662     lua_assert(0);  /* Unused for LJ_SOFTFP32. */
1663     break;
1664 #else
1665   case IR_DIV: asm_div(as, ir); break;
1666   case IR_POW: asm_pow(as, ir); break;
1667   case IR_ABS: asm_abs(as, ir); break;
1668   case IR_ATAN2: asm_atan2(as, ir); break;
1669   case IR_LDEXP: asm_ldexp(as, ir); break;
1670   case IR_FPMATH: asm_fpmath(as, ir); break;
1671   case IR_TOBIT: asm_tobit(as, ir); break;
1672 #endif
1673   case IR_MIN: asm_min(as, ir); break;
1674   case IR_MAX: asm_max(as, ir); break;
1675 
1676   /* Overflow-checking arithmetic ops. */
1677   case IR_ADDOV: asm_addov(as, ir); break;
1678   case IR_SUBOV: asm_subov(as, ir); break;
1679   case IR_MULOV: asm_mulov(as, ir); break;
1680 
1681   /* Memory references. */
1682   case IR_AREF: asm_aref(as, ir); break;
1683   case IR_HREF: asm_href(as, ir, 0); break;
1684   case IR_HREFK: asm_hrefk(as, ir); break;
1685   case IR_NEWREF: asm_newref(as, ir); break;
1686   case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
1687   case IR_FREF: asm_fref(as, ir); break;
1688   case IR_STRREF: asm_strref(as, ir); break;
1689   case IR_LREF: asm_lref(as, ir); break;
1690 
1691   /* Loads and stores. */
1692   case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1693     asm_ahuvload(as, ir);
1694     break;
1695   case IR_FLOAD: asm_fload(as, ir); break;
1696   case IR_XLOAD: asm_xload(as, ir); break;
1697   case IR_SLOAD: asm_sload(as, ir); break;
1698 
1699   case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
1700   case IR_FSTORE: asm_fstore(as, ir); break;
1701   case IR_XSTORE: asm_xstore(as, ir); break;
1702 
1703   /* Allocations. */
1704   case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
1705   case IR_TNEW: asm_tnew(as, ir); break;
1706   case IR_TDUP: asm_tdup(as, ir); break;
1707   case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
1708 
1709   /* Buffer operations. */
1710   case IR_BUFHDR: asm_bufhdr(as, ir); break;
1711   case IR_BUFPUT: asm_bufput(as, ir); break;
1712   case IR_BUFSTR: asm_bufstr(as, ir); break;
1713 
1714   /* Write barriers. */
1715   case IR_TBAR: asm_tbar(as, ir); break;
1716   case IR_OBAR: asm_obar(as, ir); break;
1717 
1718   /* Type conversions. */
1719   case IR_CONV: asm_conv(as, ir); break;
1720   case IR_TOSTR: asm_tostr(as, ir); break;
1721   case IR_STRTO: asm_strto(as, ir); break;
1722 
1723   /* Calls. */
1724   case IR_CALLA:
1725     as->gcsteps++;
1726     /* fallthrough */
1727   case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
1728   case IR_CALLXS: asm_callx(as, ir); break;
1729   case IR_CARG: break;
1730 
1731   default:
1732     setintV(&as->J->errinfo, ir->o);
1733     lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
1734     break;
1735   }
1736 }
1737 
1738 /* -- Head of trace ------------------------------------------------------- */
1739 
1740 /* Head of a root trace. */
1741 static void asm_head_root(ASMState *as)
1742 {
1743   int32_t spadj;
1744   asm_head_root_base(as);
1745   emit_setvmstate(as, (int32_t)as->T->traceno);
1746   spadj = asm_stack_adjust(as);
1747   as->T->spadjust = (uint16_t)spadj;
1748   emit_spsub(as, spadj);
1749   /* Root traces assume a checked stack for the starting proto. */
1750   as->T->topslot = gcref(as->T->startpt)->pt.framesize;
1751 }
1752 
1753 /* Head of a side trace.
1754 **
1755 ** The current simplistic algorithm requires that all slots inherited
1756 ** from the parent are live in a register between pass 2 and pass 3. This
1757 ** avoids the complexity of stack slot shuffling. But of course this may
1758 ** overflow the register set in some cases and cause the dreaded error:
1759 ** "NYI: register coalescing too complex". A refined algorithm is needed.
1760 */
1761 static void asm_head_side(ASMState *as)
1762 {
1763   IRRef1 sloadins[RID_MAX];
1764   RegSet allow = RSET_ALL;  /* Inverse of all coalesced registers. */
1765   RegSet live = RSET_EMPTY;  /* Live parent registers. */
1766   IRIns *irp = &as->parent->ir[REF_BASE];  /* Parent base. */
1767   int32_t spadj, spdelta;
1768   int pass2 = 0;
1769   int pass3 = 0;
1770   IRRef i;
1771 
1772   if (as->snapno && as->topslot > as->parent->topslot) {
1773     /* Force snap #0 alloc to prevent register overwrite in stack check. */
1774     as->snapno = 0;
1775     asm_snap_alloc(as);
1776   }
1777   allow = asm_head_side_base(as, irp, allow);
1778 
1779   /* Scan all parent SLOADs and collect register dependencies. */
1780   for (i = as->stopins; i > REF_BASE; i--) {
1781     IRIns *ir = IR(i);
1782     RegSP rs;
1783     lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
1784                (LJ_SOFTFP && ir->o == IR_HIOP) || ir->o == IR_PVAL);
1785     rs = as->parentmap[i - REF_FIRST];
1786     if (ra_hasreg(ir->r)) {
1787       rset_clear(allow, ir->r);
1788       if (ra_hasspill(ir->s)) {
1789         ra_save(as, ir, ir->r);
1790         checkmclim(as);
1791       }
1792     } else if (ra_hasspill(ir->s)) {
1793       irt_setmark(ir->t);
1794       pass2 = 1;
1795     }
1796     if (ir->r == rs) {  /* Coalesce matching registers right now. */
1797       ra_free(as, ir->r);
1798     } else if (ra_hasspill(regsp_spill(rs))) {
1799       if (ra_hasreg(ir->r))
1800         pass3 = 1;
1801     } else if (ra_used(ir)) {
1802       sloadins[rs] = (IRRef1)i;
1803       rset_set(live, rs);  /* Block live parent register. */
1804     }
1805   }
1806 
1807   /* Calculate stack frame adjustment. */
1808   spadj = asm_stack_adjust(as);
1809   spdelta = spadj - (int32_t)as->parent->spadjust;
1810   if (spdelta < 0) {  /* Don't shrink the stack frame. */
1811     spadj = (int32_t)as->parent->spadjust;
1812     spdelta = 0;
1813   }
1814   as->T->spadjust = (uint16_t)spadj;
1815 
1816   /* Reload spilled target registers. */
1817   if (pass2) {
1818     for (i = as->stopins; i > REF_BASE; i--) {
1819       IRIns *ir = IR(i);
1820       if (irt_ismarked(ir->t)) {
1821         RegSet mask;
1822         Reg r;
1823         RegSP rs;
1824         irt_clearmark(ir->t);
1825         rs = as->parentmap[i - REF_FIRST];
1826         if (!ra_hasspill(regsp_spill(rs)))
1827           ra_sethint(ir->r, rs);  /* Hint may be gone, set it again. */
1828         else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
1829           continue;  /* Same spill slot, do nothing. */
1830         mask = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
1831         if (mask == RSET_EMPTY)
1832           lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1833         r = ra_allocref(as, i, mask);
1834         ra_save(as, ir, r);
1835         rset_clear(allow, r);
1836         if (r == rs) {  /* Coalesce matching registers right now. */
1837           ra_free(as, r);
1838           rset_clear(live, r);
1839         } else if (ra_hasspill(regsp_spill(rs))) {
1840           pass3 = 1;
1841         }
1842         checkmclim(as);
1843       }
1844     }
1845   }
1846 
1847   /* Store trace number and adjust stack frame relative to the parent. */
1848   emit_setvmstate(as, (int32_t)as->T->traceno);
1849   emit_spsub(as, spdelta);
1850 
1851 #if !LJ_TARGET_X86ORX64
1852   /* Restore BASE register from parent spill slot. */
1853   if (ra_hasspill(irp->s))
1854     emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
1855 #endif
1856 
1857   /* Restore target registers from parent spill slots. */
1858   if (pass3) {
1859     RegSet work = ~as->freeset & RSET_ALL;
1860     while (work) {
1861       Reg r = rset_pickbot(work);
1862       IRRef ref = regcost_ref(as->cost[r]);
1863       RegSP rs = as->parentmap[ref - REF_FIRST];
1864       rset_clear(work, r);
1865       if (ra_hasspill(regsp_spill(rs))) {
1866         int32_t ofs = sps_scale(regsp_spill(rs));
1867         ra_free(as, r);
1868         emit_spload(as, IR(ref), r, ofs);
1869         checkmclim(as);
1870       }
1871     }
1872   }
1873 
1874   /* Shuffle registers to match up target regs with parent regs. */
1875   for (;;) {
1876     RegSet work;
1877 
1878     /* Repeatedly coalesce free live registers by moving to their target. */
1879     while ((work = as->freeset & live) != RSET_EMPTY) {
1880       Reg rp = rset_pickbot(work);
1881       IRIns *ir = IR(sloadins[rp]);
1882       rset_clear(live, rp);
1883       rset_clear(allow, rp);
1884       ra_free(as, ir->r);
1885       emit_movrr(as, ir, ir->r, rp);
1886       checkmclim(as);
1887     }
1888 
1889     /* We're done if no live registers remain. */
1890     if (live == RSET_EMPTY)
1891       break;
1892 
1893     /* Break cycles by renaming one target to a temp. register. */
1894     if (live & RSET_GPR) {
1895       RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
1896       if (tmpset == RSET_EMPTY)
1897         lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1898       ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
1899     }
1900     if (!LJ_SOFTFP && (live & RSET_FPR)) {
1901       RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
1902       if (tmpset == RSET_EMPTY)
1903         lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1904       ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
1905     }
1906     checkmclim(as);
1907     /* Continue with coalescing to fix up the broken cycle(s). */
1908   }
1909 
1910   /* Inherit top stack slot already checked by parent trace. */
1911   as->T->topslot = as->parent->topslot;
1912   if (as->topslot > as->T->topslot) {  /* Need to check for higher slot? */
1913 #ifdef EXITSTATE_CHECKEXIT
1914     /* Highest exit + 1 indicates stack check. */
1915     ExitNo exitno = as->T->nsnap;
1916 #else
1917     /* Reuse the parent exit in the context of the parent trace. */
1918     ExitNo exitno = as->J->exitno;
1919 #endif
1920     as->T->topslot = (uint8_t)as->topslot;  /* Remember for child traces. */
1921     asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
1922   }
1923 }
1924 
1925 /* -- Tail of trace ------------------------------------------------------- */
1926 
1927 /* Get base slot for a snapshot. */
1928 static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
1929 {
1930   SnapEntry *map = &as->T->snapmap[snap->mapofs];
1931   MSize n;
1932   for (n = snap->nent; n > 0; n--) {
1933     SnapEntry sn = map[n-1];
1934     if ((sn & SNAP_FRAME)) {
1935       *gotframe = 1;
1936       return snap_slot(sn) - LJ_FR2;
1937     }
1938   }
1939   return 0;
1940 }
1941 
1942 /* Link to another trace. */
1943 static void asm_tail_link(ASMState *as)
1944 {
1945   SnapNo snapno = as->T->nsnap-1;  /* Last snapshot. */
1946   SnapShot *snap = &as->T->snap[snapno];
1947   int gotframe = 0;
1948   BCReg baseslot = asm_baseslot(as, snap, &gotframe);
1949 
1950   as->topslot = snap->topslot;
1951   checkmclim(as);
1952   ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
1953 
1954   if (as->T->link == 0) {
1955     /* Setup fixed registers for exit to interpreter. */
1956     const BCIns *pc = snap_pc(&as->T->snapmap[snap->mapofs + snap->nent]);
1957     int32_t mres;
1958     if (bc_op(*pc) == BC_JLOOP) {  /* NYI: find a better way to do this. */
1959       BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1960       if (bc_isret(bc_op(*retpc)))
1961         pc = retpc;
1962     }
1963 #if LJ_GC64
1964     emit_loadu64(as, RID_LPC, u64ptr(pc));
1965 #else
1966     ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1967     ra_allockreg(as, i32ptr(pc), RID_LPC);
1968 #endif
1969     mres = (int32_t)(snap->nslots - baseslot - LJ_FR2);
1970     switch (bc_op(*pc)) {
1971     case BC_CALLM: case BC_CALLMT:
1972       mres -= (int32_t)(1 + LJ_FR2 + bc_a(*pc) + bc_c(*pc)); break;
1973     case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1974     case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1975     default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
1976     }
1977     ra_allockreg(as, mres, RID_RET);  /* Return MULTRES or 0. */
1978   } else if (baseslot) {
1979     /* Save modified BASE for linking to trace with higher start frame. */
1980     emit_setgl(as, RID_BASE, jit_base);
1981   }
1982   emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1983 
1984   if (as->J->ktrace) {  /* Patch ktrace slot with the final GCtrace pointer. */
1985     setgcref(IR(as->J->ktrace)[LJ_GC64].gcr, obj2gco(as->J->curfinal));
1986     IR(as->J->ktrace)->o = IR_KGC;
1987   }
1988 
1989   /* Sync the interpreter state with the on-trace state. */
1990   asm_stack_restore(as, snap);
1991 
1992   /* Root traces that add frames need to check the stack at the end. */
1993   if (!as->parent && gotframe)
1994     asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
1995 }
1996 
1997 /* -- Trace setup --------------------------------------------------------- */
1998 
1999 /* Clear reg/sp for all instructions and add register hints. */
2000 static void asm_setup_regsp(ASMState *as)
2001 {
2002   GCtrace *T = as->T;
2003   int sink = T->sinktags;
2004   IRRef nins = T->nins;
2005   IRIns *ir, *lastir;
2006   int inloop;
2007 #if LJ_TARGET_ARM
2008   uint32_t rload = 0xa6402a64;
2009 #endif
2010 
2011   ra_setup(as);
2012 
2013   /* Clear reg/sp for constants. */
2014   for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++) {
2015     ir->prev = REGSP_INIT;
2016     if (irt_is64(ir->t) && ir->o != IR_KNULL) {
2017 #if LJ_GC64
2018       /* The false-positive of irt_is64() for ASMREF_L (REF_NIL) is OK here. */
2019       ir->i = 0;  /* Will become non-zero only for RIP-relative addresses. */
2020 #else
2021       /* Make life easier for backends by putting address of constant in i. */
2022       ir->i = (int32_t)(intptr_t)(ir+1);
2023 #endif
2024       ir++;
2025     }
2026   }
2027 
2028   /* REF_BASE is used for implicit references to the BASE register. */
2029   lastir->prev = REGSP_HINT(RID_BASE);
2030 
2031   as->snaprename = nins;
2032   as->snapref = nins;
2033   as->snapno = T->nsnap;
2034 
2035   as->stopins = REF_BASE;
2036   as->orignins = nins;
2037   as->curins = nins;
2038 
2039   /* Setup register hints for parent link instructions. */
2040   ir = IR(REF_FIRST);
2041   if (as->parent) {
2042     uint16_t *p;
2043     lastir = lj_snap_regspmap(as->parent, as->J->exitno, ir);
2044     if (lastir - ir > LJ_MAX_JSLOTS)
2045       lj_trace_err(as->J, LJ_TRERR_NYICOAL);
2046     as->stopins = (IRRef)((lastir-1) - as->ir);
2047     for (p = as->parentmap; ir < lastir; ir++) {
2048       RegSP rs = ir->prev;
2049       *p++ = (uint16_t)rs;  /* Copy original parent RegSP to parentmap. */
2050       if (!ra_hasspill(regsp_spill(rs)))
2051         ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
2052       else
2053         ir->prev = REGSP_INIT;
2054     }
2055   }
2056 
2057   inloop = 0;
2058   as->evenspill = SPS_FIRST;
2059   for (lastir = IR(nins); ir < lastir; ir++) {
2060     if (sink) {
2061       if (ir->r == RID_SINK)
2062         continue;
2063       if (ir->r == RID_SUNK) {  /* Revert after ASM restart. */
2064         ir->r = RID_SINK;
2065         continue;
2066       }
2067     }
2068     switch (ir->o) {
2069     case IR_LOOP:
2070       inloop = 1;
2071       break;
2072 #if LJ_TARGET_ARM
2073     case IR_SLOAD:
2074       if (!((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP))
2075         break;
2076       /* fallthrough */
2077     case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2078       if (!LJ_SOFTFP && irt_isnum(ir->t)) break;
2079       ir->prev = (uint16_t)REGSP_HINT((rload & 15));
2080       rload = lj_ror(rload, 4);
2081       continue;
2082 #endif
2083     case IR_CALLXS: {
2084       CCallInfo ci;
2085       ci.flags = asm_callx_flags(as, ir);
2086       ir->prev = asm_setup_call_slots(as, ir, &ci);
2087       if (inloop)
2088         as->modset |= RSET_SCRATCH;
2089       continue;
2090       }
2091     case IR_CALLN: case IR_CALLA: case IR_CALLL: case IR_CALLS: {
2092       const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
2093       ir->prev = asm_setup_call_slots(as, ir, ci);
2094       if (inloop)
2095         as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
2096                       (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
2097       continue;
2098       }
2099 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
2100     case IR_HIOP:
2101       switch ((ir-1)->o) {
2102 #if LJ_SOFTFP && LJ_TARGET_ARM
2103       case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2104         if (ra_hashint((ir-1)->r)) {
2105           ir->prev = (ir-1)->prev + 1;
2106           continue;
2107         }
2108         break;
2109 #endif
2110 #if !LJ_SOFTFP && LJ_NEED_FP64
2111       case IR_CONV:
2112         if (irt_isfp((ir-1)->t)) {
2113           ir->prev = REGSP_HINT(RID_FPRET);
2114           continue;
2115         }
2116         /* fallthrough */
2117 #endif
2118       case IR_CALLN: case IR_CALLXS:
2119 #if LJ_SOFTFP
2120       case IR_MIN: case IR_MAX:
2121 #endif
2122         (ir-1)->prev = REGSP_HINT(RID_RETLO);
2123         ir->prev = REGSP_HINT(RID_RETHI);
2124         continue;
2125       default:
2126         break;
2127       }
2128       break;
2129 #endif
2130 #if LJ_SOFTFP
2131     case IR_MIN: case IR_MAX:
2132       if ((ir+1)->o != IR_HIOP) break;
2133       /* fallthrough */
2134 #endif
2135     /* C calls evict all scratch regs and return results in RID_RET. */
2136     case IR_SNEW: case IR_XSNEW: case IR_NEWREF: case IR_BUFPUT:
2137       if (REGARG_NUMGPR < 3 && as->evenspill < 3)
2138         as->evenspill = 3;  /* lj_str_new and lj_tab_newkey need 3 args. */
2139 #if LJ_TARGET_X86 && LJ_HASFFI
2140       if (0) {
2141     case IR_CNEW:
2142         if (ir->op2 != REF_NIL && as->evenspill < 4)
2143           as->evenspill = 4;  /* lj_cdata_newv needs 4 args. */
2144       }
2145 #else
2146     case IR_CNEW:
2147 #endif
2148     case IR_TNEW: case IR_TDUP: case IR_CNEWI: case IR_TOSTR:
2149     case IR_BUFSTR:
2150       ir->prev = REGSP_HINT(RID_RET);
2151       if (inloop)
2152         as->modset = RSET_SCRATCH;
2153       continue;
2154     case IR_STRTO: case IR_OBAR:
2155       if (inloop)
2156         as->modset = RSET_SCRATCH;
2157       break;
2158 #if !LJ_SOFTFP
2159     case IR_ATAN2:
2160 #if LJ_TARGET_X86
2161       if (as->evenspill < 4)  /* Leave room to call atan2(). */
2162         as->evenspill = 4;
2163 #endif
2164 #if !LJ_TARGET_X86ORX64
2165     case IR_LDEXP:
2166 #endif
2167 #endif
2168     case IR_POW:
2169       if (!LJ_SOFTFP && irt_isnum(ir->t)) {
2170         if (inloop)
2171           as->modset |= RSET_SCRATCH;
2172 #if LJ_TARGET_X86
2173         break;
2174 #else
2175         ir->prev = REGSP_HINT(RID_FPRET);
2176         continue;
2177 #endif
2178       }
2179       /* fallthrough for integer POW */
2180     case IR_DIV: case IR_MOD:
2181       if (!irt_isnum(ir->t)) {
2182         ir->prev = REGSP_HINT(RID_RET);
2183         if (inloop)
2184           as->modset |= (RSET_SCRATCH & RSET_GPR);
2185         continue;
2186       }
2187       break;
2188     case IR_FPMATH:
2189 #if LJ_TARGET_X86ORX64
2190       if (ir->op2 <= IRFPM_TRUNC) {
2191         if (!(as->flags & JIT_F_SSE4_1)) {
2192           ir->prev = REGSP_HINT(RID_XMM0);
2193           if (inloop)
2194             as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
2195           continue;
2196         }
2197         break;
2198       } else if (ir->op2 == IRFPM_EXP2 && !LJ_64) {
2199         if (as->evenspill < 4)  /* Leave room to call pow(). */
2200           as->evenspill = 4;
2201       }
2202 #endif
2203       if (inloop)
2204         as->modset |= RSET_SCRATCH;
2205 #if LJ_TARGET_X86
2206       break;
2207 #else
2208       ir->prev = REGSP_HINT(RID_FPRET);
2209       continue;
2210 #endif
2211 #if LJ_TARGET_X86ORX64
2212     /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
2213     case IR_BSHL: case IR_BSHR: case IR_BSAR:
2214       if ((as->flags & JIT_F_BMI2))  /* Except if BMI2 is available. */
2215         break;
2216     case IR_BROL: case IR_BROR:
2217       if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
2218         IR(ir->op2)->r = REGSP_HINT(RID_ECX);
2219         if (inloop)
2220           rset_set(as->modset, RID_ECX);
2221       }
2222       break;
2223 #endif
2224     /* Do not propagate hints across type conversions or loads. */
2225     case IR_TOBIT:
2226     case IR_XLOAD:
2227 #if !LJ_TARGET_ARM
2228     case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2229 #endif
2230       break;
2231     case IR_CONV:
2232       if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
2233           (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
2234         break;
2235       /* fallthrough */
2236     default:
2237       /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
2238       if (irref_isk(ir->op2) && !irref_isk(ir->op1) &&
2239           ra_hashint(regsp_reg(IR(ir->op1)->prev))) {
2240         ir->prev = IR(ir->op1)->prev;
2241         continue;
2242       }
2243       break;
2244     }
2245     ir->prev = REGSP_INIT;
2246   }
2247   if ((as->evenspill & 1))
2248     as->oddspill = as->evenspill++;
2249   else
2250     as->oddspill = 0;
2251 }
2252 
2253 /* -- Assembler core ------------------------------------------------------ */
2254 
2255 /* Assemble a trace. */
2256 void lj_asm_trace(jit_State *J, GCtrace *T)
2257 {
2258   ASMState as_;
2259   ASMState *as = &as_;
2260   MCode *origtop;
2261 
2262   /* Remove nops/renames left over from ASM restart due to LJ_TRERR_MCODELM. */
2263   {
2264     IRRef nins = T->nins;
2265     IRIns *ir = &T->ir[nins-1];
2266     if (ir->o == IR_NOP || ir->o == IR_RENAME) {
2267       do { ir--; nins--; } while (ir->o == IR_NOP || ir->o == IR_RENAME);
2268       T->nins = nins;
2269     }
2270   }
2271 
2272   /* Ensure an initialized instruction beyond the last one for HIOP checks. */
2273   /* This also allows one RENAME to be added without reallocating curfinal. */
2274   as->orignins = lj_ir_nextins(J);
2275   J->cur.ir[as->orignins].o = IR_NOP;
2276 
2277   /* Setup initial state. Copy some fields to reduce indirections. */
2278   as->J = J;
2279   as->T = T;
2280   J->curfinal = lj_trace_alloc(J->L, T);  /* This copies the IR, too. */
2281   as->flags = J->flags;
2282   as->loopref = J->loopref;
2283   as->realign = NULL;
2284   as->loopinv = 0;
2285   as->parent = J->parent ? traceref(J, J->parent) : NULL;
2286 
2287   /* Reserve MCode memory. */
2288   as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
2289   as->mcp = as->mctop;
2290   as->mclim = as->mcbot + MCLIM_REDZONE;
2291   asm_setup_target(as);
2292 
2293   /*
2294   ** This is a loop, because the MCode may have to be (re-)assembled
2295   ** multiple times:
2296   **
2297   ** 1. as->realign is set (and the assembly aborted), if the arch-specific
2298   **    backend wants the MCode to be aligned differently.
2299   **
2300   **    This is currently only the case on x86/x64, where small loops get
2301   **    an aligned loop body plus a short branch. Not much effort is wasted,
2302   **    because the abort happens very quickly and only once.
2303   **
2304   ** 2. The IR is immovable, since the MCode embeds pointers to various
2305   **    constants inside the IR. But RENAMEs may need to be added to the IR
2306   **    during assembly, which might grow and reallocate the IR. We check
2307   **    at the end if the IR (in J->cur.ir) has actually grown, resize the
2308   **    copy (in J->curfinal.ir) and try again.
2309   **
2310   **    95% of all traces have zero RENAMEs, 3% have one RENAME, 1.5% have
2311   **    2 RENAMEs and only 0.5% have more than that. That's why we opt to
2312   **    always have one spare slot in the IR (see above), which means we
2313   **    have to redo the assembly for only ~2% of all traces.
2314   **
2315   **    Very, very rarely, this needs to be done repeatedly, since the
2316   **    location of constants inside the IR (actually, reachability from
2317   **    a global pointer) may affect register allocation and thus the
2318   **    number of RENAMEs.
2319   */
2320   for (;;) {
2321     as->mcp = as->mctop;
2322 #ifdef LUA_USE_ASSERT
2323     as->mcp_prev = as->mcp;
2324 #endif
2325     as->ir = J->curfinal->ir;  /* Use the copied IR. */
2326     as->curins = J->cur.nins = as->orignins;
2327 
2328     RA_DBG_START();
2329     RA_DBGX((as, "===== STOP ====="));
2330 
2331     /* General trace setup. Emit tail of trace. */
2332     asm_tail_prep(as);
2333     as->mcloop = NULL;
2334     as->flagmcp = NULL;
2335     as->topslot = 0;
2336     as->gcsteps = 0;
2337     as->sectref = as->loopref;
2338     as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
2339     asm_setup_regsp(as);
2340     if (!as->loopref)
2341       asm_tail_link(as);
2342 
2343     /* Assemble a trace in linear backwards order. */
2344     for (as->curins--; as->curins > as->stopins; as->curins--) {
2345       IRIns *ir = IR(as->curins);
2346       lua_assert(!(LJ_32 && irt_isint64(ir->t)));  /* Handled by SPLIT. */
2347       if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
2348         continue;  /* Dead-code elimination can be soooo easy. */
2349       if (irt_isguard(ir->t))
2350         asm_snap_prep(as);
2351       RA_DBG_REF();
2352       checkmclim(as);
2353       asm_ir(as, ir);
2354     }
2355 
2356     if (as->realign && J->curfinal->nins >= T->nins)
2357       continue;  /* Retry in case only the MCode needs to be realigned. */
2358 
2359     /* Emit head of trace. */
2360     RA_DBG_REF();
2361     checkmclim(as);
2362     if (as->gcsteps > 0) {
2363       as->curins = as->T->snap[0].ref;
2364       asm_snap_prep(as);  /* The GC check is a guard. */
2365       asm_gc_check(as);
2366       as->curins = as->stopins;
2367     }
2368     ra_evictk(as);
2369     if (as->parent)
2370       asm_head_side(as);
2371     else
2372       asm_head_root(as);
2373     asm_phi_fixup(as);
2374 
2375     if (J->curfinal->nins >= T->nins) {  /* IR didn't grow? */
2376       lua_assert(J->curfinal->nk == T->nk);
2377       memcpy(J->curfinal->ir + as->orignins, T->ir + as->orignins,
2378              (T->nins - as->orignins) * sizeof(IRIns));  /* Copy RENAMEs. */
2379       T->nins = J->curfinal->nins;
2380       break;  /* Done. */
2381     }
2382 
2383     /* Otherwise try again with a bigger IR. */
2384     lj_trace_free(J2G(J), J->curfinal);
2385     J->curfinal = NULL;  /* In case lj_trace_alloc() OOMs. */
2386     J->curfinal = lj_trace_alloc(J->L, T);
2387     as->realign = NULL;
2388   }
2389 
2390   RA_DBGX((as, "===== START ===="));
2391   RA_DBG_FLUSH();
2392   if (as->freeset != RSET_ALL)
2393     lj_trace_err(as->J, LJ_TRERR_BADRA);  /* Ouch! Should never happen. */
2394 
2395   /* Set trace entry point before fixing up tail to allow link to self. */
2396   T->mcode = as->mcp;
2397   T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
2398   if (!as->loopref)
2399     asm_tail_fixup(as, T->link);  /* Note: this may change as->mctop! */
2400   T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
2401 #if LJ_TARGET_MCODE_FIXUP
2402   asm_mcode_fixup(T->mcode, T->szmcode);
2403 #endif
2404   lj_mcode_sync(T->mcode, origtop);
2405 }
2406 
2407 #undef IR
2408 
2409 #endif

/* [<][>][^][v][top][bottom][index][help] */