lj_asm.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. /*
  2. ** IR assembler (SSA IR -> machine code).
  3. ** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
  4. */
  5. #define lj_asm_c
  6. #define LUA_CORE
  7. #include "lj_obj.h"
  8. #if LJ_HASJIT
  9. #include "lj_gc.h"
  10. #include "lj_str.h"
  11. #include "lj_tab.h"
  12. #include "lj_frame.h"
  13. #if LJ_HASFFI
  14. #include "lj_ctype.h"
  15. #endif
  16. #include "lj_ir.h"
  17. #include "lj_jit.h"
  18. #include "lj_ircall.h"
  19. #include "lj_iropt.h"
  20. #include "lj_mcode.h"
  21. #include "lj_iropt.h"
  22. #include "lj_trace.h"
  23. #include "lj_snap.h"
  24. #include "lj_asm.h"
  25. #include "lj_dispatch.h"
  26. #include "lj_vm.h"
  27. #include "lj_target.h"
  28. #ifdef LUA_USE_ASSERT
  29. #include <stdio.h>
  30. #endif
  31. /* -- Assembler state and common macros ----------------------------------- */
  32. /* Assembler state. */
  33. typedef struct ASMState {
  34. RegCost cost[RID_MAX]; /* Reference and blended allocation cost for regs. */
  35. MCode *mcp; /* Current MCode pointer (grows down). */
  36. MCode *mclim; /* Lower limit for MCode memory + red zone. */
  37. #ifdef LUA_USE_ASSERT
  38. MCode *mcp_prev; /* Red zone overflow check. */
  39. #endif
  40. IRIns *ir; /* Copy of pointer to IR instructions/constants. */
  41. jit_State *J; /* JIT compiler state. */
  42. #if LJ_TARGET_X86ORX64
  43. x86ModRM mrm; /* Fused x86 address operand. */
  44. #endif
  45. RegSet freeset; /* Set of free registers. */
  46. RegSet modset; /* Set of registers modified inside the loop. */
  47. RegSet weakset; /* Set of weakly referenced registers. */
  48. RegSet phiset; /* Set of PHI registers. */
  49. uint32_t flags; /* Copy of JIT compiler flags. */
  50. int loopinv; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
  51. int32_t evenspill; /* Next even spill slot. */
  52. int32_t oddspill; /* Next odd spill slot (or 0). */
  53. IRRef curins; /* Reference of current instruction. */
  54. IRRef stopins; /* Stop assembly before hitting this instruction. */
  55. IRRef orignins; /* Original T->nins. */
  56. IRRef snapref; /* Current snapshot is active after this reference. */
  57. IRRef snaprename; /* Rename highwater mark for snapshot check. */
  58. SnapNo snapno; /* Current snapshot number. */
  59. SnapNo loopsnapno; /* Loop snapshot number. */
  60. IRRef fuseref; /* Fusion limit (loopref, 0 or FUSE_DISABLED). */
  61. IRRef sectref; /* Section base reference (loopref or 0). */
  62. IRRef loopref; /* Reference of LOOP instruction (or 0). */
  63. BCReg topslot; /* Number of slots for stack check (unless 0). */
  64. int32_t gcsteps; /* Accumulated number of GC steps (per section). */
  65. GCtrace *T; /* Trace to assemble. */
  66. GCtrace *parent; /* Parent trace (or NULL). */
  67. MCode *mcbot; /* Bottom of reserved MCode. */
  68. MCode *mctop; /* Top of generated MCode. */
  69. MCode *mcloop; /* Pointer to loop MCode (or NULL). */
  70. MCode *invmcp; /* Points to invertible loop branch (or NULL). */
  71. MCode *flagmcp; /* Pending opportunity to merge flag setting ins. */
  72. MCode *realign; /* Realign loop if not NULL. */
  73. #ifdef RID_NUM_KREF
  74. int32_t krefk[RID_NUM_KREF];
  75. #endif
  76. IRRef1 phireg[RID_MAX]; /* PHI register references. */
  77. uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent instruction to RegSP map. */
  78. } ASMState;
  79. #define IR(ref) (&as->ir[(ref)])
  80. #define ASMREF_TMP1 REF_TRUE /* Temp. register. */
  81. #define ASMREF_TMP2 REF_FALSE /* Temp. register. */
  82. #define ASMREF_L REF_NIL /* Stores register for L. */
  83. /* Check for variant to invariant references. */
  84. #define iscrossref(as, ref) ((ref) < as->sectref)
  85. /* Inhibit memory op fusion from variant to invariant references. */
  86. #define FUSE_DISABLED (~(IRRef)0)
  87. #define mayfuse(as, ref) ((ref) > as->fuseref)
  88. #define neverfuse(as) (as->fuseref == FUSE_DISABLED)
  89. #define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t))
  90. #define opisfusableload(o) \
  91. ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
  92. (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
  93. /* Sparse limit checks using a red zone before the actual limit. */
  94. #define MCLIM_REDZONE 64
  95. static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
  96. {
  97. lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
  98. }
  99. static LJ_AINLINE void checkmclim(ASMState *as)
  100. {
  101. #ifdef LUA_USE_ASSERT
  102. if (as->mcp + MCLIM_REDZONE < as->mcp_prev) {
  103. IRIns *ir = IR(as->curins+1);
  104. fprintf(stderr, "RED ZONE OVERFLOW: %p IR %04d %02d %04d %04d\n", as->mcp,
  105. as->curins+1-REF_BIAS, ir->o, ir->op1-REF_BIAS, ir->op2-REF_BIAS);
  106. lua_assert(0);
  107. }
  108. #endif
  109. if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as);
  110. #ifdef LUA_USE_ASSERT
  111. as->mcp_prev = as->mcp;
  112. #endif
  113. }
  114. #ifdef RID_NUM_KREF
  115. #define ra_iskref(ref) ((ref) < RID_NUM_KREF)
  116. #define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
  117. #define ra_krefk(as, ref) (as->krefk[(ref)])
  118. static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k)
  119. {
  120. IRRef ref = (IRRef)(r - RID_MIN_KREF);
  121. as->krefk[ref] = k;
  122. as->cost[r] = REGCOST(ref, ref);
  123. }
  124. #else
  125. #define ra_iskref(ref) 0
  126. #define ra_krefreg(ref) RID_MIN_GPR
  127. #define ra_krefk(as, ref) 0
  128. #endif
  129. /* Arch-specific field offsets. */
  130. static const uint8_t field_ofs[IRFL__MAX+1] = {
  131. #define FLOFS(name, ofs) (uint8_t)(ofs),
  132. IRFLDEF(FLOFS)
  133. #undef FLOFS
  134. 0
  135. };
  136. /* -- Target-specific instruction emitter --------------------------------- */
  137. #if LJ_TARGET_X86ORX64
  138. #include "lj_emit_x86.h"
  139. #elif LJ_TARGET_ARM
  140. #include "lj_emit_arm.h"
  141. #elif LJ_TARGET_PPC
  142. #include "lj_emit_ppc.h"
  143. #elif LJ_TARGET_MIPS
  144. #include "lj_emit_mips.h"
  145. #else
  146. #error "Missing instruction emitter for target CPU"
  147. #endif
  148. /* -- Register allocator debugging ---------------------------------------- */
  149. /* #define LUAJIT_DEBUG_RA */
  150. #ifdef LUAJIT_DEBUG_RA
  151. #include <stdio.h>
  152. #include <stdarg.h>
  153. #define RIDNAME(name) #name,
  154. static const char *const ra_regname[] = {
  155. GPRDEF(RIDNAME)
  156. FPRDEF(RIDNAME)
  157. VRIDDEF(RIDNAME)
  158. NULL
  159. };
  160. #undef RIDNAME
  161. static char ra_dbg_buf[65536];
  162. static char *ra_dbg_p;
  163. static char *ra_dbg_merge;
  164. static MCode *ra_dbg_mcp;
  165. static void ra_dstart(void)
  166. {
  167. ra_dbg_p = ra_dbg_buf;
  168. ra_dbg_merge = NULL;
  169. ra_dbg_mcp = NULL;
  170. }
  171. static void ra_dflush(void)
  172. {
  173. fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
  174. ra_dstart();
  175. }
  176. static void ra_dprintf(ASMState *as, const char *fmt, ...)
  177. {
  178. char *p;
  179. va_list argp;
  180. va_start(argp, fmt);
  181. p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
  182. ra_dbg_mcp = NULL;
  183. p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
  184. for (;;) {
  185. const char *e = strchr(fmt, '$');
  186. if (e == NULL) break;
  187. memcpy(p, fmt, (size_t)(e-fmt));
  188. p += e-fmt;
  189. if (e[1] == 'r') {
  190. Reg r = va_arg(argp, Reg) & RID_MASK;
  191. if (r <= RID_MAX) {
  192. const char *q;
  193. for (q = ra_regname[r]; *q; q++)
  194. *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
  195. } else {
  196. *p++ = '?';
  197. lua_assert(0);
  198. }
  199. } else if (e[1] == 'f' || e[1] == 'i') {
  200. IRRef ref;
  201. if (e[1] == 'f')
  202. ref = va_arg(argp, IRRef);
  203. else
  204. ref = va_arg(argp, IRIns *) - as->ir;
  205. if (ref >= REF_BIAS)
  206. p += sprintf(p, "%04d", ref - REF_BIAS);
  207. else
  208. p += sprintf(p, "K%03d", REF_BIAS - ref);
  209. } else if (e[1] == 's') {
  210. uint32_t slot = va_arg(argp, uint32_t);
  211. p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
  212. } else if (e[1] == 'x') {
  213. p += sprintf(p, "%08x", va_arg(argp, int32_t));
  214. } else {
  215. lua_assert(0);
  216. }
  217. fmt = e+2;
  218. }
  219. va_end(argp);
  220. while (*fmt)
  221. *p++ = *fmt++;
  222. *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
  223. if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
  224. fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
  225. p = ra_dbg_buf;
  226. }
  227. ra_dbg_p = p;
  228. }
  229. #define RA_DBG_START() ra_dstart()
  230. #define RA_DBG_FLUSH() ra_dflush()
  231. #define RA_DBG_REF() \
  232. do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
  233. ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
  234. #define RA_DBGX(x) ra_dprintf x
  235. #else
  236. #define RA_DBG_START() ((void)0)
  237. #define RA_DBG_FLUSH() ((void)0)
  238. #define RA_DBG_REF() ((void)0)
  239. #define RA_DBGX(x) ((void)0)
  240. #endif
  241. /* -- Register allocator -------------------------------------------------- */
  242. #define ra_free(as, r) rset_set(as->freeset, (r))
  243. #define ra_modified(as, r) rset_set(as->modset, (r))
  244. #define ra_weak(as, r) rset_set(as->weakset, (r))
  245. #define ra_noweak(as, r) rset_clear(as->weakset, (r))
  246. #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
  247. /* Setup register allocator. */
  248. static void ra_setup(ASMState *as)
  249. {
  250. Reg r;
  251. /* Initially all regs (except the stack pointer) are free for use. */
  252. as->freeset = RSET_INIT;
  253. as->modset = RSET_EMPTY;
  254. as->weakset = RSET_EMPTY;
  255. as->phiset = RSET_EMPTY;
  256. memset(as->phireg, 0, sizeof(as->phireg));
  257. for (r = RID_MIN_GPR; r < RID_MAX; r++)
  258. as->cost[r] = REGCOST(~0u, 0u);
  259. }
  260. /* Rematerialize constants. */
  261. static Reg ra_rematk(ASMState *as, IRRef ref)
  262. {
  263. IRIns *ir;
  264. Reg r;
  265. if (ra_iskref(ref)) {
  266. r = ra_krefreg(ref);
  267. lua_assert(!rset_test(as->freeset, r));
  268. ra_free(as, r);
  269. ra_modified(as, r);
  270. emit_loadi(as, r, ra_krefk(as, ref));
  271. return r;
  272. }
  273. ir = IR(ref);
  274. r = ir->r;
  275. lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
  276. ra_free(as, r);
  277. ra_modified(as, r);
  278. ir->r = RID_INIT; /* Do not keep any hint. */
  279. RA_DBGX((as, "remat $i $r", ir, r));
  280. #if !LJ_SOFTFP
  281. if (ir->o == IR_KNUM) {
  282. emit_loadn(as, r, ir_knum(ir));
  283. } else
  284. #endif
  285. if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
  286. ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
  287. emit_getgl(as, r, jit_base);
  288. } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
  289. lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
  290. emit_getgl(as, r, jit_L);
  291. #if LJ_64
  292. } else if (ir->o == IR_KINT64) {
  293. emit_loadu64(as, r, ir_kint64(ir)->u64);
  294. #endif
  295. } else {
  296. lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
  297. ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
  298. emit_loadi(as, r, ir->i);
  299. }
  300. return r;
  301. }
  302. /* Force a spill. Allocate a new spill slot if needed. */
  303. static int32_t ra_spill(ASMState *as, IRIns *ir)
  304. {
  305. int32_t slot = ir->s;
  306. if (!ra_hasspill(slot)) {
  307. if (irt_is64(ir->t)) {
  308. slot = as->evenspill;
  309. as->evenspill += 2;
  310. } else if (as->oddspill) {
  311. slot = as->oddspill;
  312. as->oddspill = 0;
  313. } else {
  314. slot = as->evenspill;
  315. as->oddspill = slot+1;
  316. as->evenspill += 2;
  317. }
  318. if (as->evenspill > 256)
  319. lj_trace_err(as->J, LJ_TRERR_SPILLOV);
  320. ir->s = (uint8_t)slot;
  321. }
  322. return sps_scale(slot);
  323. }
  324. /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
  325. static Reg ra_releasetmp(ASMState *as, IRRef ref)
  326. {
  327. IRIns *ir = IR(ref);
  328. Reg r = ir->r;
  329. lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
  330. ra_free(as, r);
  331. ra_modified(as, r);
  332. ir->r = RID_INIT;
  333. return r;
  334. }
  335. /* Restore a register (marked as free). Rematerialize or force a spill. */
  336. static Reg ra_restore(ASMState *as, IRRef ref)
  337. {
  338. if (emit_canremat(ref)) {
  339. return ra_rematk(as, ref);
  340. } else {
  341. IRIns *ir = IR(ref);
  342. int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
  343. Reg r = ir->r;
  344. lua_assert(ra_hasreg(r));
  345. ra_sethint(ir->r, r); /* Keep hint. */
  346. ra_free(as, r);
  347. if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
  348. ra_modified(as, r);
  349. RA_DBGX((as, "restore $i $r", ir, r));
  350. emit_spload(as, ir, r, ofs);
  351. }
  352. return r;
  353. }
  354. }
  355. /* Save a register to a spill slot. */
  356. static void ra_save(ASMState *as, IRIns *ir, Reg r)
  357. {
  358. RA_DBGX((as, "save $i $r", ir, r));
  359. emit_spstore(as, ir, r, sps_scale(ir->s));
  360. }
  361. #define MINCOST(name) \
  362. if (rset_test(RSET_ALL, RID_##name) && \
  363. LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
  364. cost = as->cost[RID_##name];
  365. /* Evict the register with the lowest cost, forcing a restore. */
  366. static Reg ra_evict(ASMState *as, RegSet allow)
  367. {
  368. IRRef ref;
  369. RegCost cost = ~(RegCost)0;
  370. lua_assert(allow != RSET_EMPTY);
  371. if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
  372. GPRDEF(MINCOST)
  373. } else {
  374. FPRDEF(MINCOST)
  375. }
  376. ref = regcost_ref(cost);
  377. lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
  378. /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
  379. if (!irref_isk(ref) && (as->weakset & allow)) {
  380. IRIns *ir = IR(ref);
  381. if (!rset_test(as->weakset, ir->r))
  382. ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
  383. }
  384. return ra_restore(as, ref);
  385. }
  386. /* Pick any register (marked as free). Evict on-demand. */
  387. static Reg ra_pick(ASMState *as, RegSet allow)
  388. {
  389. RegSet pick = as->freeset & allow;
  390. if (!pick)
  391. return ra_evict(as, allow);
  392. else
  393. return rset_picktop(pick);
  394. }
  395. /* Get a scratch register (marked as free). */
  396. static Reg ra_scratch(ASMState *as, RegSet allow)
  397. {
  398. Reg r = ra_pick(as, allow);
  399. ra_modified(as, r);
  400. RA_DBGX((as, "scratch $r", r));
  401. return r;
  402. }
  403. /* Evict all registers from a set (if not free). */
  404. static void ra_evictset(ASMState *as, RegSet drop)
  405. {
  406. RegSet work;
  407. as->modset |= drop;
  408. #if !LJ_SOFTFP
  409. work = (drop & ~as->freeset) & RSET_FPR;
  410. while (work) {
  411. Reg r = rset_pickbot(work);
  412. ra_restore(as, regcost_ref(as->cost[r]));
  413. rset_clear(work, r);
  414. checkmclim(as);
  415. }
  416. #endif
  417. work = (drop & ~as->freeset);
  418. while (work) {
  419. Reg r = rset_pickbot(work);
  420. ra_restore(as, regcost_ref(as->cost[r]));
  421. rset_clear(work, r);
  422. checkmclim(as);
  423. }
  424. }
  425. /* Evict (rematerialize) all registers allocated to constants. */
  426. static void ra_evictk(ASMState *as)
  427. {
  428. RegSet work;
  429. #if !LJ_SOFTFP
  430. work = ~as->freeset & RSET_FPR;
  431. while (work) {
  432. Reg r = rset_pickbot(work);
  433. IRRef ref = regcost_ref(as->cost[r]);
  434. if (emit_canremat(ref) && irref_isk(ref)) {
  435. ra_rematk(as, ref);
  436. checkmclim(as);
  437. }
  438. rset_clear(work, r);
  439. }
  440. #endif
  441. work = ~as->freeset & RSET_GPR;
  442. while (work) {
  443. Reg r = rset_pickbot(work);
  444. IRRef ref = regcost_ref(as->cost[r]);
  445. if (emit_canremat(ref) && irref_isk(ref)) {
  446. ra_rematk(as, ref);
  447. checkmclim(as);
  448. }
  449. rset_clear(work, r);
  450. }
  451. }
  452. #ifdef RID_NUM_KREF
  453. /* Allocate a register for a constant. */
  454. static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
  455. {
  456. /* First try to find a register which already holds the same constant. */
  457. RegSet pick, work = ~as->freeset & RSET_GPR;
  458. Reg r;
  459. while (work) {
  460. IRRef ref;
  461. r = rset_pickbot(work);
  462. ref = regcost_ref(as->cost[r]);
  463. if (ref < ASMREF_L &&
  464. k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
  465. return r;
  466. rset_clear(work, r);
  467. }
  468. pick = as->freeset & allow;
  469. if (pick) {
  470. /* Constants should preferably get unmodified registers. */
  471. if ((pick & ~as->modset))
  472. pick &= ~as->modset;
  473. r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
  474. } else {
  475. r = ra_evict(as, allow);
  476. }
  477. RA_DBGX((as, "allock $x $r", k, r));
  478. ra_setkref(as, r, k);
  479. rset_clear(as->freeset, r);
  480. ra_noweak(as, r);
  481. return r;
  482. }
  483. /* Allocate a specific register for a constant. */
  484. static void ra_allockreg(ASMState *as, int32_t k, Reg r)
  485. {
  486. Reg kr = ra_allock(as, k, RID2RSET(r));
  487. if (kr != r) {
  488. IRIns irdummy;
  489. irdummy.t.irt = IRT_INT;
  490. ra_scratch(as, RID2RSET(r));
  491. emit_movrr(as, &irdummy, r, kr);
  492. }
  493. }
  494. #else
  495. #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
  496. #endif
  497. /* Allocate a register for ref from the allowed set of registers.
  498. ** Note: this function assumes the ref does NOT have a register yet!
  499. ** Picks an optimal register, sets the cost and marks the register as non-free.
  500. */
  501. static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
  502. {
  503. IRIns *ir = IR(ref);
  504. RegSet pick = as->freeset & allow;
  505. Reg r;
  506. lua_assert(ra_noreg(ir->r));
  507. if (pick) {
  508. /* First check register hint from propagation or PHI. */
  509. if (ra_hashint(ir->r)) {
  510. r = ra_gethint(ir->r);
  511. if (rset_test(pick, r)) /* Use hint register if possible. */
  512. goto found;
  513. /* Rematerialization is cheaper than missing a hint. */
  514. if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
  515. ra_rematk(as, regcost_ref(as->cost[r]));
  516. goto found;
  517. }
  518. RA_DBGX((as, "hintmiss $f $r", ref, r));
  519. }
  520. /* Invariants should preferably get unmodified registers. */
  521. if (ref < as->loopref && !irt_isphi(ir->t)) {
  522. if ((pick & ~as->modset))
  523. pick &= ~as->modset;
  524. r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
  525. } else {
  526. /* We've got plenty of regs, so get callee-save regs if possible. */
  527. if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
  528. pick &= ~RSET_SCRATCH;
  529. r = rset_picktop(pick);
  530. }
  531. } else {
  532. r = ra_evict(as, allow);
  533. }
  534. found:
  535. RA_DBGX((as, "alloc $f $r", ref, r));
  536. ir->r = (uint8_t)r;
  537. rset_clear(as->freeset, r);
  538. ra_noweak(as, r);
  539. as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
  540. return r;
  541. }
  542. /* Allocate a register on-demand. */
  543. static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
  544. {
  545. Reg r = IR(ref)->r;
  546. /* Note: allow is ignored if the register is already allocated. */
  547. if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
  548. ra_noweak(as, r);
  549. return r;
  550. }
  551. /* Rename register allocation and emit move. */
  552. static void ra_rename(ASMState *as, Reg down, Reg up)
  553. {
  554. IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
  555. IRIns *ir = IR(ref);
  556. ir->r = (uint8_t)up;
  557. as->cost[down] = 0;
  558. lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
  559. lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
  560. ra_free(as, down); /* 'down' is free ... */
  561. ra_modified(as, down);
  562. rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
  563. ra_noweak(as, up);
  564. RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
  565. emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
  566. if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
  567. lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno);
  568. ren = tref_ref(lj_ir_emit(as->J));
  569. as->ir = as->T->ir; /* The IR may have been reallocated. */
  570. IR(ren)->r = (uint8_t)down;
  571. IR(ren)->s = SPS_NONE;
  572. }
  573. }
  574. /* Pick a destination register (marked as free).
  575. ** Caveat: allow is ignored if there's already a destination register.
  576. ** Use ra_destreg() to get a specific register.
  577. */
  578. static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
  579. {
  580. Reg dest = ir->r;
  581. if (ra_hasreg(dest)) {
  582. ra_free(as, dest);
  583. ra_modified(as, dest);
  584. } else {
  585. if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
  586. dest = ra_gethint(dest);
  587. ra_modified(as, dest);
  588. RA_DBGX((as, "dest $r", dest));
  589. } else {
  590. dest = ra_scratch(as, allow);
  591. }
  592. ir->r = dest;
  593. }
  594. if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
  595. return dest;
  596. }
  597. /* Force a specific destination register (marked as free). */
  598. static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
  599. {
  600. Reg dest = ra_dest(as, ir, RID2RSET(r));
  601. if (dest != r) {
  602. lua_assert(rset_test(as->freeset, r));
  603. ra_modified(as, r);
  604. emit_movrr(as, ir, dest, r);
  605. }
  606. }
  607. #if LJ_TARGET_X86ORX64
  608. /* Propagate dest register to left reference. Emit moves as needed.
  609. ** This is a required fixup step for all 2-operand machine instructions.
  610. */
  611. static void ra_left(ASMState *as, Reg dest, IRRef lref)
  612. {
  613. IRIns *ir = IR(lref);
  614. Reg left = ir->r;
  615. if (ra_noreg(left)) {
  616. if (irref_isk(lref)) {
  617. if (ir->o == IR_KNUM) {
  618. cTValue *tv = ir_knum(ir);
  619. /* FP remat needs a load except for +0. Still better than eviction. */
  620. if (tvispzero(tv) || !(as->freeset & RSET_FPR)) {
  621. emit_loadn(as, dest, tv);
  622. return;
  623. }
  624. #if LJ_64
  625. } else if (ir->o == IR_KINT64) {
  626. emit_loadu64(as, dest, ir_kint64(ir)->u64);
  627. return;
  628. #endif
  629. } else {
  630. lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
  631. ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
  632. emit_loadi(as, dest, ir->i);
  633. return;
  634. }
  635. }
  636. if (!ra_hashint(left) && !iscrossref(as, lref))
  637. ra_sethint(ir->r, dest); /* Propagate register hint. */
  638. left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
  639. }
  640. ra_noweak(as, left);
  641. /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
  642. if (dest != left) {
  643. /* Use register renaming if dest is the PHI reg. */
  644. if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
  645. ra_modified(as, left);
  646. ra_rename(as, left, dest);
  647. } else {
  648. emit_movrr(as, ir, dest, left);
  649. }
  650. }
  651. }
  652. #else
  653. /* Similar to ra_left, except we override any hints. */
  654. static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
  655. {
  656. IRIns *ir = IR(lref);
  657. Reg left = ir->r;
  658. if (ra_noreg(left)) {
  659. ra_sethint(ir->r, dest); /* Propagate register hint. */
  660. left = ra_allocref(as, lref,
  661. (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
  662. }
  663. ra_noweak(as, left);
  664. if (dest != left) {
  665. /* Use register renaming if dest is the PHI reg. */
  666. if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
  667. ra_modified(as, left);
  668. ra_rename(as, left, dest);
  669. } else {
  670. emit_movrr(as, ir, dest, left);
  671. }
  672. }
  673. }
  674. #endif
  675. #if !LJ_64
  676. /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
  677. static void ra_destpair(ASMState *as, IRIns *ir)
  678. {
  679. Reg destlo = ir->r, desthi = (ir+1)->r;
  680. /* First spill unrelated refs blocking the destination registers. */
  681. if (!rset_test(as->freeset, RID_RETLO) &&
  682. destlo != RID_RETLO && desthi != RID_RETLO)
  683. ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
  684. if (!rset_test(as->freeset, RID_RETHI) &&
  685. destlo != RID_RETHI && desthi != RID_RETHI)
  686. ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
  687. /* Next free the destination registers (if any). */
  688. if (ra_hasreg(destlo)) {
  689. ra_free(as, destlo);
  690. ra_modified(as, destlo);
  691. } else {
  692. destlo = RID_RETLO;
  693. }
  694. if (ra_hasreg(desthi)) {
  695. ra_free(as, desthi);
  696. ra_modified(as, desthi);
  697. } else {
  698. desthi = RID_RETHI;
  699. }
  700. /* Check for conflicts and shuffle the registers as needed. */
  701. if (destlo == RID_RETHI) {
  702. if (desthi == RID_RETLO) {
  703. #if LJ_TARGET_X86
  704. *--as->mcp = XI_XCHGa + RID_RETHI;
  705. #else
  706. emit_movrr(as, ir, RID_RETHI, RID_TMP);
  707. emit_movrr(as, ir, RID_RETLO, RID_RETHI);
  708. emit_movrr(as, ir, RID_TMP, RID_RETLO);
  709. #endif
  710. } else {
  711. emit_movrr(as, ir, RID_RETHI, RID_RETLO);
  712. if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
  713. }
  714. } else if (desthi == RID_RETLO) {
  715. emit_movrr(as, ir, RID_RETLO, RID_RETHI);
  716. if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
  717. } else {
  718. if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
  719. if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
  720. }
  721. /* Restore spill slots (if any). */
  722. if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
  723. if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
  724. }
  725. #endif
  726. /* -- Snapshot handling --------- ----------------------------------------- */
  727. /* Can we rematerialize a KNUM instead of forcing a spill? */
  728. static int asm_snap_canremat(ASMState *as)
  729. {
  730. Reg r;
  731. for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
  732. if (irref_isk(regcost_ref(as->cost[r])))
  733. return 1;
  734. return 0;
  735. }
  736. /* Check whether a sunk store corresponds to an allocation. */
  737. static int asm_sunk_store(ASMState *as, IRIns *ira, IRIns *irs)
  738. {
  739. if (irs->s == 255) {
  740. if (irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
  741. irs->o == IR_FSTORE || irs->o == IR_XSTORE) {
  742. IRIns *irk = IR(irs->op1);
  743. if (irk->o == IR_AREF || irk->o == IR_HREFK)
  744. irk = IR(irk->op1);
  745. return (IR(irk->op1) == ira);
  746. }
  747. return 0;
  748. } else {
  749. return (ira + irs->s == irs); /* Quick check. */
  750. }
  751. }
  752. /* Allocate register or spill slot for a ref that escapes to a snapshot. */
  753. static void asm_snap_alloc1(ASMState *as, IRRef ref)
  754. {
  755. IRIns *ir = IR(ref);
  756. if (!irref_isk(ref) && (!(ra_used(ir) || ir->r == RID_SUNK))) {
  757. if (ir->r == RID_SINK) {
  758. ir->r = RID_SUNK;
  759. #if LJ_HASFFI
  760. if (ir->o == IR_CNEWI) { /* Allocate CNEWI value. */
  761. asm_snap_alloc1(as, ir->op2);
  762. if (LJ_32 && (ir+1)->o == IR_HIOP)
  763. asm_snap_alloc1(as, (ir+1)->op2);
  764. } else
  765. #endif
  766. { /* Allocate stored values for TNEW, TDUP and CNEW. */
  767. IRIns *irs;
  768. lua_assert(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW);
  769. for (irs = IR(as->snapref-1); irs > ir; irs--)
  770. if (irs->r == RID_SINK && asm_sunk_store(as, ir, irs)) {
  771. lua_assert(irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
  772. irs->o == IR_FSTORE || irs->o == IR_XSTORE);
  773. asm_snap_alloc1(as, irs->op2);
  774. if (LJ_32 && (irs+1)->o == IR_HIOP)
  775. asm_snap_alloc1(as, (irs+1)->op2);
  776. }
  777. }
  778. } else {
  779. RegSet allow;
  780. if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT) {
  781. IRIns *irc;
  782. for (irc = IR(as->curins); irc > ir; irc--)
  783. if ((irc->op1 == ref || irc->op2 == ref) &&
  784. !(irc->r == RID_SINK || irc->r == RID_SUNK))
  785. goto nosink; /* Don't sink conversion if result is used. */
  786. asm_snap_alloc1(as, ir->op1);
  787. return;
  788. }
  789. nosink:
  790. allow = (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR;
  791. if ((as->freeset & allow) ||
  792. (allow == RSET_FPR && asm_snap_canremat(as))) {
  793. /* Get a weak register if we have a free one or can rematerialize. */
  794. Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
  795. if (!irt_isphi(ir->t))
  796. ra_weak(as, r); /* But mark it as weakly referenced. */
  797. checkmclim(as);
  798. RA_DBGX((as, "snapreg $f $r", ref, ir->r));
  799. } else {
  800. ra_spill(as, ir); /* Otherwise force a spill slot. */
  801. RA_DBGX((as, "snapspill $f $s", ref, ir->s));
  802. }
  803. }
  804. }
  805. }
  806. /* Allocate refs escaping to a snapshot. */
  807. static void asm_snap_alloc(ASMState *as)
  808. {
  809. SnapShot *snap = &as->T->snap[as->snapno];
  810. SnapEntry *map = &as->T->snapmap[snap->mapofs];
  811. MSize n, nent = snap->nent;
  812. for (n = 0; n < nent; n++) {
  813. SnapEntry sn = map[n];
  814. IRRef ref = snap_ref(sn);
  815. if (!irref_isk(ref)) {
  816. asm_snap_alloc1(as, ref);
  817. if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
  818. lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP);
  819. asm_snap_alloc1(as, ref+1);
  820. }
  821. }
  822. }
  823. }
  824. /* All guards for a snapshot use the same exitno. This is currently the
  825. ** same as the snapshot number. Since the exact origin of the exit cannot
  826. ** be determined, all guards for the same snapshot must exit with the same
  827. ** RegSP mapping.
  828. ** A renamed ref which has been used in a prior guard for the same snapshot
  829. ** would cause an inconsistency. The easy way out is to force a spill slot.
  830. */
  831. static int asm_snap_checkrename(ASMState *as, IRRef ren)
  832. {
  833. SnapShot *snap = &as->T->snap[as->snapno];
  834. SnapEntry *map = &as->T->snapmap[snap->mapofs];
  835. MSize n, nent = snap->nent;
  836. for (n = 0; n < nent; n++) {
  837. SnapEntry sn = map[n];
  838. IRRef ref = snap_ref(sn);
  839. if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
  840. IRIns *ir = IR(ref);
  841. ra_spill(as, ir); /* Register renamed, so force a spill slot. */
  842. RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
  843. return 1; /* Found. */
  844. }
  845. }
  846. return 0; /* Not found. */
  847. }
  848. /* Prepare snapshot for next guard instruction. */
  849. static void asm_snap_prep(ASMState *as)
  850. {
  851. if (as->curins < as->snapref) {
  852. do {
  853. if (as->snapno == 0) return; /* Called by sunk stores before snap #0. */
  854. as->snapno--;
  855. as->snapref = as->T->snap[as->snapno].ref;
  856. } while (as->curins < as->snapref);
  857. asm_snap_alloc(as);
  858. as->snaprename = as->T->nins;
  859. } else {
  860. /* Process any renames above the highwater mark. */
  861. for (; as->snaprename < as->T->nins; as->snaprename++) {
  862. IRIns *ir = IR(as->snaprename);
  863. if (asm_snap_checkrename(as, ir->op1))
  864. ir->op2 = REF_BIAS-1; /* Kill rename. */
  865. }
  866. }
  867. }
  868. /* -- Miscellaneous helpers ----------------------------------------------- */
  869. /* Collect arguments from CALL* and CARG instructions. */
  870. static void asm_collectargs(ASMState *as, IRIns *ir,
  871. const CCallInfo *ci, IRRef *args)
  872. {
  873. uint32_t n = CCI_NARGS(ci);
  874. lua_assert(n <= CCI_NARGS_MAX*2); /* Account for split args. */
  875. if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
  876. while (n-- > 1) {
  877. ir = IR(ir->op1);
  878. lua_assert(ir->o == IR_CARG);
  879. args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
  880. }
  881. args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
  882. lua_assert(IR(ir->op1)->o != IR_CARG);
  883. }
  884. /* Reconstruct CCallInfo flags for CALLX*. */
  885. static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
  886. {
  887. uint32_t nargs = 0;
  888. if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
  889. IRIns *ira = IR(ir->op1);
  890. nargs++;
  891. while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
  892. }
  893. #if LJ_HASFFI
  894. if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
  895. CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
  896. CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
  897. nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
  898. #if LJ_TARGET_X86
  899. nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
  900. #endif
  901. }
  902. #endif
  903. return (nargs | (ir->t.irt << CCI_OTSHIFT));
  904. }
  905. /* Calculate stack adjustment. */
  906. static int32_t asm_stack_adjust(ASMState *as)
  907. {
  908. if (as->evenspill <= SPS_FIXED)
  909. return 0;
  910. return sps_scale(sps_align(as->evenspill));
  911. }
  912. /* Must match with hash*() in lj_tab.c. */
  913. static uint32_t ir_khash(IRIns *ir)
  914. {
  915. uint32_t lo, hi;
  916. if (irt_isstr(ir->t)) {
  917. return ir_kstr(ir)->hash;
  918. } else if (irt_isnum(ir->t)) {
  919. lo = ir_knum(ir)->u32.lo;
  920. hi = ir_knum(ir)->u32.hi << 1;
  921. } else if (irt_ispri(ir->t)) {
  922. lua_assert(!irt_isnil(ir->t));
  923. return irt_type(ir->t)-IRT_FALSE;
  924. } else {
  925. lua_assert(irt_isgcv(ir->t));
  926. lo = u32ptr(ir_kgc(ir));
  927. hi = lo + HASH_BIAS;
  928. }
  929. return hashrot(lo, hi);
  930. }
  931. /* -- Allocations --------------------------------------------------------- */
  932. static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
  933. static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
  934. static void asm_snew(ASMState *as, IRIns *ir)
  935. {
  936. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
  937. IRRef args[3];
  938. args[0] = ASMREF_L; /* lua_State *L */
  939. args[1] = ir->op1; /* const char *str */
  940. args[2] = ir->op2; /* size_t len */
  941. as->gcsteps++;
  942. asm_setupresult(as, ir, ci); /* GCstr * */
  943. asm_gencall(as, ci, args);
  944. }
  945. static void asm_tnew(ASMState *as, IRIns *ir)
  946. {
  947. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
  948. IRRef args[2];
  949. args[0] = ASMREF_L; /* lua_State *L */
  950. args[1] = ASMREF_TMP1; /* uint32_t ahsize */
  951. as->gcsteps++;
  952. asm_setupresult(as, ir, ci); /* GCtab * */
  953. asm_gencall(as, ci, args);
  954. ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
  955. }
  956. static void asm_tdup(ASMState *as, IRIns *ir)
  957. {
  958. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
  959. IRRef args[2];
  960. args[0] = ASMREF_L; /* lua_State *L */
  961. args[1] = ir->op1; /* const GCtab *kt */
  962. as->gcsteps++;
  963. asm_setupresult(as, ir, ci); /* GCtab * */
  964. asm_gencall(as, ci, args);
  965. }
  966. static void asm_gc_check(ASMState *as);
  967. /* Explicit GC step. */
  968. static void asm_gcstep(ASMState *as, IRIns *ir)
  969. {
  970. IRIns *ira;
  971. for (ira = IR(as->stopins+1); ira < ir; ira++)
  972. if ((ira->o == IR_TNEW || ira->o == IR_TDUP ||
  973. (LJ_HASFFI && (ira->o == IR_CNEW || ira->o == IR_CNEWI))) &&
  974. ra_used(ira))
  975. as->gcsteps++;
  976. if (as->gcsteps)
  977. asm_gc_check(as);
  978. as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */
  979. }
  980. /* -- PHI and loop handling ----------------------------------------------- */
  981. /* Break a PHI cycle by renaming to a free register (evict if needed). */
  982. static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
  983. RegSet allow)
  984. {
  985. RegSet candidates = blocked & allow;
  986. if (candidates) { /* If this register file has candidates. */
  987. /* Note: the set for ra_pick cannot be empty, since each register file
  988. ** has some registers never allocated to PHIs.
  989. */
  990. Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
  991. if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
  992. candidates = candidates & ~blockedby;
  993. down = rset_picktop(candidates); /* Pick candidate PHI register. */
  994. ra_rename(as, down, up); /* And rename it to the free register. */
  995. }
  996. }
  997. /* PHI register shuffling.
  998. **
  999. ** The allocator tries hard to preserve PHI register assignments across
  1000. ** the loop body. Most of the time this loop does nothing, since there
  1001. ** are no register mismatches.
  1002. **
  1003. ** If a register mismatch is detected and ...
  1004. ** - the register is currently free: rename it.
  1005. ** - the register is blocked by an invariant: restore/remat and rename it.
  1006. ** - Otherwise the register is used by another PHI, so mark it as blocked.
  1007. **
  1008. ** The renames are order-sensitive, so just retry the loop if a register
  1009. ** is marked as blocked, but has been freed in the meantime. A cycle is
  1010. ** detected if all of the blocked registers are allocated. To break the
  1011. ** cycle rename one of them to a free register and retry.
  1012. **
  1013. ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
  1014. */
  1015. static void asm_phi_shuffle(ASMState *as)
  1016. {
  1017. RegSet work;
  1018. /* Find and resolve PHI register mismatches. */
  1019. for (;;) {
  1020. RegSet blocked = RSET_EMPTY;
  1021. RegSet blockedby = RSET_EMPTY;
  1022. RegSet phiset = as->phiset;
  1023. while (phiset) { /* Check all left PHI operand registers. */
  1024. Reg r = rset_pickbot(phiset);
  1025. IRIns *irl = IR(as->phireg[r]);
  1026. Reg left = irl->r;
  1027. if (r != left) { /* Mismatch? */
  1028. if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
  1029. IRRef ref = regcost_ref(as->cost[r]);
  1030. /* Blocked by other PHI (w/reg)? */
  1031. if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
  1032. rset_set(blocked, r);
  1033. if (ra_hasreg(left))
  1034. rset_set(blockedby, left);
  1035. left = RID_NONE;
  1036. } else { /* Otherwise grab register from invariant. */
  1037. ra_restore(as, ref);
  1038. checkmclim(as);
  1039. }
  1040. }
  1041. if (ra_hasreg(left)) {
  1042. ra_rename(as, left, r);
  1043. checkmclim(as);
  1044. }
  1045. }
  1046. rset_clear(phiset, r);
  1047. }
  1048. if (!blocked) break; /* Finished. */
  1049. if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
  1050. asm_phi_break(as, blocked, blockedby, RSET_GPR);
  1051. if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
  1052. checkmclim(as);
  1053. } /* Else retry some more renames. */
  1054. }
  1055. /* Restore/remat invariants whose registers are modified inside the loop. */
  1056. #if !LJ_SOFTFP
  1057. work = as->modset & ~(as->freeset | as->phiset) & RSET_FPR;
  1058. while (work) {
  1059. Reg r = rset_pickbot(work);
  1060. ra_restore(as, regcost_ref(as->cost[r]));
  1061. rset_clear(work, r);
  1062. checkmclim(as);
  1063. }
  1064. #endif
  1065. work = as->modset & ~(as->freeset | as->phiset);
  1066. while (work) {
  1067. Reg r = rset_pickbot(work);
  1068. ra_restore(as, regcost_ref(as->cost[r]));
  1069. rset_clear(work, r);
  1070. checkmclim(as);
  1071. }
  1072. /* Allocate and save all unsaved PHI regs and clear marks. */
  1073. work = as->phiset;
  1074. while (work) {
  1075. Reg r = rset_picktop(work);
  1076. IRRef lref = as->phireg[r];
  1077. IRIns *ir = IR(lref);
  1078. if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
  1079. irt_clearmark(ir->t); /* Handled here, so clear marker now. */
  1080. ra_alloc1(as, lref, RID2RSET(r));
  1081. ra_save(as, ir, r); /* Save to spill slot inside the loop. */
  1082. checkmclim(as);
  1083. }
  1084. rset_clear(work, r);
  1085. }
  1086. }
  1087. /* Copy unsynced left/right PHI spill slots. Rarely needed. */
  1088. static void asm_phi_copyspill(ASMState *as)
  1089. {
  1090. int need = 0;
  1091. IRIns *ir;
  1092. for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--)
  1093. if (ra_hasspill(ir->s) && ra_hasspill(IR(ir->op1)->s))
  1094. need |= irt_isfp(ir->t) ? 2 : 1; /* Unsynced spill slot? */
  1095. if ((need & 1)) { /* Copy integer spill slots. */
  1096. #if !LJ_TARGET_X86ORX64
  1097. Reg r = RID_TMP;
  1098. #else
  1099. Reg r = RID_RET;
  1100. if ((as->freeset & RSET_GPR))
  1101. r = rset_pickbot((as->freeset & RSET_GPR));
  1102. else
  1103. emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1104. #endif
  1105. for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
  1106. if (ra_hasspill(ir->s)) {
  1107. IRIns *irl = IR(ir->op1);
  1108. if (ra_hasspill(irl->s) && !irt_isfp(ir->t)) {
  1109. emit_spstore(as, irl, r, sps_scale(irl->s));
  1110. emit_spload(as, ir, r, sps_scale(ir->s));
  1111. checkmclim(as);
  1112. }
  1113. }
  1114. }
  1115. #if LJ_TARGET_X86ORX64
  1116. if (!rset_test(as->freeset, r))
  1117. emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1118. #endif
  1119. }
  1120. #if !LJ_SOFTFP
  1121. if ((need & 2)) { /* Copy FP spill slots. */
  1122. #if LJ_TARGET_X86
  1123. Reg r = RID_XMM0;
  1124. #else
  1125. Reg r = RID_FPRET;
  1126. #endif
  1127. if ((as->freeset & RSET_FPR))
  1128. r = rset_pickbot((as->freeset & RSET_FPR));
  1129. if (!rset_test(as->freeset, r))
  1130. emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1131. for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
  1132. if (ra_hasspill(ir->s)) {
  1133. IRIns *irl = IR(ir->op1);
  1134. if (ra_hasspill(irl->s) && irt_isfp(ir->t)) {
  1135. emit_spstore(as, irl, r, sps_scale(irl->s));
  1136. emit_spload(as, ir, r, sps_scale(ir->s));
  1137. checkmclim(as);
  1138. }
  1139. }
  1140. }
  1141. if (!rset_test(as->freeset, r))
  1142. emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1143. }
  1144. #endif
  1145. }
  1146. /* Emit renames for left PHIs which are only spilled outside the loop. */
  1147. static void asm_phi_fixup(ASMState *as)
  1148. {
  1149. RegSet work = as->phiset;
  1150. while (work) {
  1151. Reg r = rset_picktop(work);
  1152. IRRef lref = as->phireg[r];
  1153. IRIns *ir = IR(lref);
  1154. if (irt_ismarked(ir->t)) {
  1155. irt_clearmark(ir->t);
  1156. /* Left PHI gained a spill slot before the loop? */
  1157. if (ra_hasspill(ir->s)) {
  1158. IRRef ren;
  1159. lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
  1160. ren = tref_ref(lj_ir_emit(as->J));
  1161. as->ir = as->T->ir; /* The IR may have been reallocated. */
  1162. IR(ren)->r = (uint8_t)r;
  1163. IR(ren)->s = SPS_NONE;
  1164. }
  1165. }
  1166. rset_clear(work, r);
  1167. }
  1168. }
  1169. /* Setup right PHI reference. */
  1170. static void asm_phi(ASMState *as, IRIns *ir)
  1171. {
  1172. RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
  1173. ~as->phiset;
  1174. RegSet afree = (as->freeset & allow);
  1175. IRIns *irl = IR(ir->op1);
  1176. IRIns *irr = IR(ir->op2);
  1177. if (ir->r == RID_SINK) /* Sink PHI. */
  1178. return;
  1179. /* Spill slot shuffling is not implemented yet (but rarely needed). */
  1180. if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
  1181. lj_trace_err(as->J, LJ_TRERR_NYIPHI);
  1182. /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
  1183. if ((afree & (afree-1))) { /* Two or more free registers? */
  1184. Reg r;
  1185. if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
  1186. r = ra_allocref(as, ir->op2, allow);
  1187. } else { /* Duplicate right PHI, need a copy (rare). */
  1188. r = ra_scratch(as, allow);
  1189. emit_movrr(as, irr, r, irr->r);
  1190. }
  1191. ir->r = (uint8_t)r;
  1192. rset_set(as->phiset, r);
  1193. as->phireg[r] = (IRRef1)ir->op1;
  1194. irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
  1195. if (ra_noreg(irl->r))
  1196. ra_sethint(irl->r, r); /* Set register hint for left PHI. */
  1197. } else { /* Otherwise allocate a spill slot. */
  1198. /* This is overly restrictive, but it triggers only on synthetic code. */
  1199. if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
  1200. lj_trace_err(as->J, LJ_TRERR_NYIPHI);
  1201. ra_spill(as, ir);
  1202. irr->s = ir->s; /* Set right PHI spill slot. Sync left slot later. */
  1203. }
  1204. }
  1205. static void asm_loop_fixup(ASMState *as);
  1206. /* Middle part of a loop. */
  1207. static void asm_loop(ASMState *as)
  1208. {
  1209. MCode *mcspill;
  1210. /* LOOP is a guard, so the snapno is up to date. */
  1211. as->loopsnapno = as->snapno;
  1212. if (as->gcsteps)
  1213. asm_gc_check(as);
  1214. /* LOOP marks the transition from the variant to the invariant part. */
  1215. as->flagmcp = as->invmcp = NULL;
  1216. as->sectref = 0;
  1217. if (!neverfuse(as)) as->fuseref = 0;
  1218. asm_phi_shuffle(as);
  1219. mcspill = as->mcp;
  1220. asm_phi_copyspill(as);
  1221. asm_loop_fixup(as);
  1222. as->mcloop = as->mcp;
  1223. RA_DBGX((as, "===== LOOP ====="));
  1224. if (!as->realign) RA_DBG_FLUSH();
  1225. if (as->mcp != mcspill)
  1226. emit_jmp(as, mcspill);
  1227. }
  1228. /* -- Target-specific assembler ------------------------------------------- */
  1229. #if LJ_TARGET_X86ORX64
  1230. #include "lj_asm_x86.h"
  1231. #elif LJ_TARGET_ARM
  1232. #include "lj_asm_arm.h"
  1233. #elif LJ_TARGET_PPC
  1234. #include "lj_asm_ppc.h"
  1235. #elif LJ_TARGET_MIPS
  1236. #include "lj_asm_mips.h"
  1237. #else
  1238. #error "Missing assembler for target CPU"
  1239. #endif
  1240. /* -- Head of trace ------------------------------------------------------- */
  1241. /* Head of a root trace. */
  1242. static void asm_head_root(ASMState *as)
  1243. {
  1244. int32_t spadj;
  1245. asm_head_root_base(as);
  1246. emit_setvmstate(as, (int32_t)as->T->traceno);
  1247. spadj = asm_stack_adjust(as);
  1248. as->T->spadjust = (uint16_t)spadj;
  1249. emit_spsub(as, spadj);
  1250. /* Root traces assume a checked stack for the starting proto. */
  1251. as->T->topslot = gcref(as->T->startpt)->pt.framesize;
  1252. }
  1253. /* Head of a side trace.
  1254. **
  1255. ** The current simplistic algorithm requires that all slots inherited
  1256. ** from the parent are live in a register between pass 2 and pass 3. This
  1257. ** avoids the complexity of stack slot shuffling. But of course this may
  1258. ** overflow the register set in some cases and cause the dreaded error:
  1259. ** "NYI: register coalescing too complex". A refined algorithm is needed.
  1260. */
  1261. static void asm_head_side(ASMState *as)
  1262. {
  1263. IRRef1 sloadins[RID_MAX];
  1264. RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
  1265. RegSet live = RSET_EMPTY; /* Live parent registers. */
  1266. IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
  1267. int32_t spadj, spdelta;
  1268. int pass2 = 0;
  1269. int pass3 = 0;
  1270. IRRef i;
  1271. allow = asm_head_side_base(as, irp, allow);
  1272. /* Scan all parent SLOADs and collect register dependencies. */
  1273. for (i = as->stopins; i > REF_BASE; i--) {
  1274. IRIns *ir = IR(i);
  1275. RegSP rs;
  1276. lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
  1277. (LJ_SOFTFP && ir->o == IR_HIOP) || ir->o == IR_PVAL);
  1278. rs = as->parentmap[i - REF_FIRST];
  1279. if (ra_hasreg(ir->r)) {
  1280. rset_clear(allow, ir->r);
  1281. if (ra_hasspill(ir->s)) {
  1282. ra_save(as, ir, ir->r);
  1283. checkmclim(as);
  1284. }
  1285. } else if (ra_hasspill(ir->s)) {
  1286. irt_setmark(ir->t);
  1287. pass2 = 1;
  1288. }
  1289. if (ir->r == rs) { /* Coalesce matching registers right now. */
  1290. ra_free(as, ir->r);
  1291. } else if (ra_hasspill(regsp_spill(rs))) {
  1292. if (ra_hasreg(ir->r))
  1293. pass3 = 1;
  1294. } else if (ra_used(ir)) {
  1295. sloadins[rs] = (IRRef1)i;
  1296. rset_set(live, rs); /* Block live parent register. */
  1297. }
  1298. }
  1299. /* Calculate stack frame adjustment. */
  1300. spadj = asm_stack_adjust(as);
  1301. spdelta = spadj - (int32_t)as->parent->spadjust;
  1302. if (spdelta < 0) { /* Don't shrink the stack frame. */
  1303. spadj = (int32_t)as->parent->spadjust;
  1304. spdelta = 0;
  1305. }
  1306. as->T->spadjust = (uint16_t)spadj;
  1307. /* Reload spilled target registers. */
  1308. if (pass2) {
  1309. for (i = as->stopins; i > REF_BASE; i--) {
  1310. IRIns *ir = IR(i);
  1311. if (irt_ismarked(ir->t)) {
  1312. RegSet mask;
  1313. Reg r;
  1314. RegSP rs;
  1315. irt_clearmark(ir->t);
  1316. rs = as->parentmap[i - REF_FIRST];
  1317. if (!ra_hasspill(regsp_spill(rs)))
  1318. ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
  1319. else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
  1320. continue; /* Same spill slot, do nothing. */
  1321. mask = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
  1322. if (mask == RSET_EMPTY)
  1323. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1324. r = ra_allocref(as, i, mask);
  1325. ra_save(as, ir, r);
  1326. rset_clear(allow, r);
  1327. if (r == rs) { /* Coalesce matching registers right now. */
  1328. ra_free(as, r);
  1329. rset_clear(live, r);
  1330. } else if (ra_hasspill(regsp_spill(rs))) {
  1331. pass3 = 1;
  1332. }
  1333. checkmclim(as);
  1334. }
  1335. }
  1336. }
  1337. /* Store trace number and adjust stack frame relative to the parent. */
  1338. emit_setvmstate(as, (int32_t)as->T->traceno);
  1339. emit_spsub(as, spdelta);
  1340. #if !LJ_TARGET_X86ORX64
  1341. /* Restore BASE register from parent spill slot. */
  1342. if (ra_hasspill(irp->s))
  1343. emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
  1344. #endif
  1345. /* Restore target registers from parent spill slots. */
  1346. if (pass3) {
  1347. RegSet work = ~as->freeset & RSET_ALL;
  1348. while (work) {
  1349. Reg r = rset_pickbot(work);
  1350. IRRef ref = regcost_ref(as->cost[r]);
  1351. RegSP rs = as->parentmap[ref - REF_FIRST];
  1352. rset_clear(work, r);
  1353. if (ra_hasspill(regsp_spill(rs))) {
  1354. int32_t ofs = sps_scale(regsp_spill(rs));
  1355. ra_free(as, r);
  1356. emit_spload(as, IR(ref), r, ofs);
  1357. checkmclim(as);
  1358. }
  1359. }
  1360. }
  1361. /* Shuffle registers to match up target regs with parent regs. */
  1362. for (;;) {
  1363. RegSet work;
  1364. /* Repeatedly coalesce free live registers by moving to their target. */
  1365. while ((work = as->freeset & live) != RSET_EMPTY) {
  1366. Reg rp = rset_pickbot(work);
  1367. IRIns *ir = IR(sloadins[rp]);
  1368. rset_clear(live, rp);
  1369. rset_clear(allow, rp);
  1370. ra_free(as, ir->r);
  1371. emit_movrr(as, ir, ir->r, rp);
  1372. checkmclim(as);
  1373. }
  1374. /* We're done if no live registers remain. */
  1375. if (live == RSET_EMPTY)
  1376. break;
  1377. /* Break cycles by renaming one target to a temp. register. */
  1378. if (live & RSET_GPR) {
  1379. RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
  1380. if (tmpset == RSET_EMPTY)
  1381. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1382. ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
  1383. }
  1384. if (!LJ_SOFTFP && (live & RSET_FPR)) {
  1385. RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
  1386. if (tmpset == RSET_EMPTY)
  1387. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1388. ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
  1389. }
  1390. checkmclim(as);
  1391. /* Continue with coalescing to fix up the broken cycle(s). */
  1392. }
  1393. /* Inherit top stack slot already checked by parent trace. */
  1394. as->T->topslot = as->parent->topslot;
  1395. if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
  1396. #ifdef EXITSTATE_CHECKEXIT
  1397. /* Highest exit + 1 indicates stack check. */
  1398. ExitNo exitno = as->T->nsnap;
  1399. #else
  1400. /* Reuse the parent exit in the context of the parent trace. */
  1401. ExitNo exitno = as->J->exitno;
  1402. #endif
  1403. as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
  1404. asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
  1405. }
  1406. }
  1407. /* -- Tail of trace ------------------------------------------------------- */
  1408. /* Get base slot for a snapshot. */
  1409. static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
  1410. {
  1411. SnapEntry *map = &as->T->snapmap[snap->mapofs];
  1412. MSize n;
  1413. for (n = snap->nent; n > 0; n--) {
  1414. SnapEntry sn = map[n-1];
  1415. if ((sn & SNAP_FRAME)) {
  1416. *gotframe = 1;
  1417. return snap_slot(sn);
  1418. }
  1419. }
  1420. return 0;
  1421. }
  1422. /* Link to another trace. */
  1423. static void asm_tail_link(ASMState *as)
  1424. {
  1425. SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
  1426. SnapShot *snap = &as->T->snap[snapno];
  1427. int gotframe = 0;
  1428. BCReg baseslot = asm_baseslot(as, snap, &gotframe);
  1429. as->topslot = snap->topslot;
  1430. checkmclim(as);
  1431. ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
  1432. if (as->T->link == 0) {
  1433. /* Setup fixed registers for exit to interpreter. */
  1434. const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
  1435. int32_t mres;
  1436. if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
  1437. BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
  1438. if (bc_isret(bc_op(*retpc)))
  1439. pc = retpc;
  1440. }
  1441. ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
  1442. ra_allockreg(as, i32ptr(pc), RID_LPC);
  1443. mres = (int32_t)(snap->nslots - baseslot);
  1444. switch (bc_op(*pc)) {
  1445. case BC_CALLM: case BC_CALLMT:
  1446. mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
  1447. case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
  1448. case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
  1449. default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
  1450. }
  1451. ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
  1452. } else if (baseslot) {
  1453. /* Save modified BASE for linking to trace with higher start frame. */
  1454. emit_setgl(as, RID_BASE, jit_base);
  1455. }
  1456. emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
  1457. /* Sync the interpreter state with the on-trace state. */
  1458. asm_stack_restore(as, snap);
  1459. /* Root traces that add frames need to check the stack at the end. */
  1460. if (!as->parent && gotframe)
  1461. asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
  1462. }
  1463. /* -- Trace setup --------------------------------------------------------- */
  1464. /* Clear reg/sp for all instructions and add register hints. */
  1465. static void asm_setup_regsp(ASMState *as)
  1466. {
  1467. GCtrace *T = as->T;
  1468. int sink = T->sinktags;
  1469. IRRef nins = T->nins;
  1470. IRIns *ir, *lastir;
  1471. int inloop;
  1472. #if LJ_TARGET_ARM
  1473. uint32_t rload = 0xa6402a64;
  1474. #endif
  1475. ra_setup(as);
  1476. /* Clear reg/sp for constants. */
  1477. for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++)
  1478. ir->prev = REGSP_INIT;
  1479. /* REF_BASE is used for implicit references to the BASE register. */
  1480. lastir->prev = REGSP_HINT(RID_BASE);
  1481. ir = IR(nins-1);
  1482. if (ir->o == IR_RENAME) {
  1483. do { ir--; nins--; } while (ir->o == IR_RENAME);
  1484. T->nins = nins; /* Remove any renames left over from ASM restart. */
  1485. }
  1486. as->snaprename = nins;
  1487. as->snapref = nins;
  1488. as->snapno = T->nsnap;
  1489. as->stopins = REF_BASE;
  1490. as->orignins = nins;
  1491. as->curins = nins;
  1492. /* Setup register hints for parent link instructions. */
  1493. ir = IR(REF_FIRST);
  1494. if (as->parent) {
  1495. uint16_t *p;
  1496. lastir = lj_snap_regspmap(as->parent, as->J->exitno, ir);
  1497. if (lastir - ir > LJ_MAX_JSLOTS)
  1498. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1499. as->stopins = (IRRef)((lastir-1) - as->ir);
  1500. for (p = as->parentmap; ir < lastir; ir++) {
  1501. RegSP rs = ir->prev;
  1502. *p++ = (uint16_t)rs; /* Copy original parent RegSP to parentmap. */
  1503. if (!ra_hasspill(regsp_spill(rs)))
  1504. ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
  1505. else
  1506. ir->prev = REGSP_INIT;
  1507. }
  1508. }
  1509. inloop = 0;
  1510. as->evenspill = SPS_FIRST;
  1511. for (lastir = IR(nins); ir < lastir; ir++) {
  1512. if (sink) {
  1513. if (ir->r == RID_SINK)
  1514. continue;
  1515. if (ir->r == RID_SUNK) { /* Revert after ASM restart. */
  1516. ir->r = RID_SINK;
  1517. continue;
  1518. }
  1519. }
  1520. switch (ir->o) {
  1521. case IR_LOOP:
  1522. inloop = 1;
  1523. break;
  1524. #if LJ_TARGET_ARM
  1525. case IR_SLOAD:
  1526. if (!((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP))
  1527. break;
  1528. /* fallthrough */
  1529. case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  1530. if (!LJ_SOFTFP && irt_isnum(ir->t)) break;
  1531. ir->prev = (uint16_t)REGSP_HINT((rload & 15));
  1532. rload = lj_ror(rload, 4);
  1533. continue;
  1534. #endif
  1535. case IR_CALLXS: {
  1536. CCallInfo ci;
  1537. ci.flags = asm_callx_flags(as, ir);
  1538. ir->prev = asm_setup_call_slots(as, ir, &ci);
  1539. if (inloop)
  1540. as->modset |= RSET_SCRATCH;
  1541. continue;
  1542. }
  1543. case IR_CALLN: case IR_CALLL: case IR_CALLS: {
  1544. const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
  1545. ir->prev = asm_setup_call_slots(as, ir, ci);
  1546. if (inloop)
  1547. as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
  1548. (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
  1549. continue;
  1550. }
  1551. #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
  1552. case IR_HIOP:
  1553. switch ((ir-1)->o) {
  1554. #if LJ_SOFTFP && LJ_TARGET_ARM
  1555. case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  1556. if (ra_hashint((ir-1)->r)) {
  1557. ir->prev = (ir-1)->prev + 1;
  1558. continue;
  1559. }
  1560. break;
  1561. #endif
  1562. #if !LJ_SOFTFP && LJ_NEED_FP64
  1563. case IR_CONV:
  1564. if (irt_isfp((ir-1)->t)) {
  1565. ir->prev = REGSP_HINT(RID_FPRET);
  1566. continue;
  1567. }
  1568. /* fallthrough */
  1569. #endif
  1570. case IR_CALLN: case IR_CALLXS:
  1571. #if LJ_SOFTFP
  1572. case IR_MIN: case IR_MAX:
  1573. #endif
  1574. (ir-1)->prev = REGSP_HINT(RID_RETLO);
  1575. ir->prev = REGSP_HINT(RID_RETHI);
  1576. continue;
  1577. default:
  1578. break;
  1579. }
  1580. break;
  1581. #endif
  1582. #if LJ_SOFTFP
  1583. case IR_MIN: case IR_MAX:
  1584. if ((ir+1)->o != IR_HIOP) break;
  1585. /* fallthrough */
  1586. #endif
  1587. /* C calls evict all scratch regs and return results in RID_RET. */
  1588. case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
  1589. if (REGARG_NUMGPR < 3 && as->evenspill < 3)
  1590. as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
  1591. case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
  1592. ir->prev = REGSP_HINT(RID_RET);
  1593. if (inloop)
  1594. as->modset = RSET_SCRATCH;
  1595. continue;
  1596. case IR_STRTO: case IR_OBAR:
  1597. if (inloop)
  1598. as->modset = RSET_SCRATCH;
  1599. break;
  1600. #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
  1601. case IR_ATAN2: case IR_LDEXP:
  1602. #endif
  1603. case IR_POW:
  1604. if (!LJ_SOFTFP && irt_isnum(ir->t)) {
  1605. #if LJ_TARGET_X86ORX64
  1606. ir->prev = REGSP_HINT(RID_XMM0);
  1607. if (inloop)
  1608. as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
  1609. #else
  1610. ir->prev = REGSP_HINT(RID_FPRET);
  1611. if (inloop)
  1612. as->modset |= RSET_SCRATCH;
  1613. #endif
  1614. continue;
  1615. }
  1616. /* fallthrough for integer POW */
  1617. case IR_DIV: case IR_MOD:
  1618. if (!irt_isnum(ir->t)) {
  1619. ir->prev = REGSP_HINT(RID_RET);
  1620. if (inloop)
  1621. as->modset |= (RSET_SCRATCH & RSET_GPR);
  1622. continue;
  1623. }
  1624. break;
  1625. case IR_FPMATH:
  1626. #if LJ_TARGET_X86ORX64
  1627. if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
  1628. ir->prev = REGSP_HINT(RID_XMM0);
  1629. #if !LJ_64
  1630. if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
  1631. as->evenspill = 4;
  1632. #endif
  1633. if (inloop)
  1634. as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
  1635. continue;
  1636. } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
  1637. ir->prev = REGSP_HINT(RID_XMM0);
  1638. if (inloop)
  1639. as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
  1640. continue;
  1641. }
  1642. break;
  1643. #else
  1644. ir->prev = REGSP_HINT(RID_FPRET);
  1645. if (inloop)
  1646. as->modset |= RSET_SCRATCH;
  1647. continue;
  1648. #endif
  1649. #if LJ_TARGET_X86ORX64
  1650. /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
  1651. case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
  1652. if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
  1653. IR(ir->op2)->r = REGSP_HINT(RID_ECX);
  1654. if (inloop)
  1655. rset_set(as->modset, RID_ECX);
  1656. }
  1657. break;
  1658. #endif
  1659. /* Do not propagate hints across type conversions or loads. */
  1660. case IR_TOBIT:
  1661. case IR_XLOAD:
  1662. #if !LJ_TARGET_ARM
  1663. case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  1664. #endif
  1665. break;
  1666. case IR_CONV:
  1667. if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
  1668. (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
  1669. break;
  1670. /* fallthrough */
  1671. default:
  1672. /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
  1673. if (irref_isk(ir->op2) && !irref_isk(ir->op1) &&
  1674. ra_hashint(regsp_reg(IR(ir->op1)->prev))) {
  1675. ir->prev = IR(ir->op1)->prev;
  1676. continue;
  1677. }
  1678. break;
  1679. }
  1680. ir->prev = REGSP_INIT;
  1681. }
  1682. if ((as->evenspill & 1))
  1683. as->oddspill = as->evenspill++;
  1684. else
  1685. as->oddspill = 0;
  1686. }
  1687. /* -- Assembler core ------------------------------------------------------ */
  1688. /* Assemble a trace. */
  1689. void lj_asm_trace(jit_State *J, GCtrace *T)
  1690. {
  1691. ASMState as_;
  1692. ASMState *as = &as_;
  1693. MCode *origtop;
  1694. /* Ensure an initialized instruction beyond the last one for HIOP checks. */
  1695. J->cur.nins = lj_ir_nextins(J);
  1696. J->cur.ir[J->cur.nins].o = IR_NOP;
  1697. /* Setup initial state. Copy some fields to reduce indirections. */
  1698. as->J = J;
  1699. as->T = T;
  1700. as->ir = T->ir;
  1701. as->flags = J->flags;
  1702. as->loopref = J->loopref;
  1703. as->realign = NULL;
  1704. as->loopinv = 0;
  1705. as->parent = J->parent ? traceref(J, J->parent) : NULL;
  1706. /* Reserve MCode memory. */
  1707. as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
  1708. as->mcp = as->mctop;
  1709. as->mclim = as->mcbot + MCLIM_REDZONE;
  1710. asm_setup_target(as);
  1711. do {
  1712. as->mcp = as->mctop;
  1713. #ifdef LUA_USE_ASSERT
  1714. as->mcp_prev = as->mcp;
  1715. #endif
  1716. as->curins = T->nins;
  1717. RA_DBG_START();
  1718. RA_DBGX((as, "===== STOP ====="));
  1719. /* General trace setup. Emit tail of trace. */
  1720. asm_tail_prep(as);
  1721. as->mcloop = NULL;
  1722. as->flagmcp = NULL;
  1723. as->topslot = 0;
  1724. as->gcsteps = 0;
  1725. as->sectref = as->loopref;
  1726. as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
  1727. asm_setup_regsp(as);
  1728. if (!as->loopref)
  1729. asm_tail_link(as);
  1730. /* Assemble a trace in linear backwards order. */
  1731. for (as->curins--; as->curins > as->stopins; as->curins--) {
  1732. IRIns *ir = IR(as->curins);
  1733. lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
  1734. if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
  1735. continue; /* Dead-code elimination can be soooo easy. */
  1736. if (irt_isguard(ir->t))
  1737. asm_snap_prep(as);
  1738. RA_DBG_REF();
  1739. checkmclim(as);
  1740. asm_ir(as, ir);
  1741. }
  1742. } while (as->realign); /* Retry in case the MCode needs to be realigned. */
  1743. /* Emit head of trace. */
  1744. RA_DBG_REF();
  1745. checkmclim(as);
  1746. if (as->gcsteps > 0) {
  1747. as->curins = as->T->snap[0].ref;
  1748. asm_snap_prep(as); /* The GC check is a guard. */
  1749. asm_gc_check(as);
  1750. }
  1751. ra_evictk(as);
  1752. if (as->parent)
  1753. asm_head_side(as);
  1754. else
  1755. asm_head_root(as);
  1756. asm_phi_fixup(as);
  1757. RA_DBGX((as, "===== START ===="));
  1758. RA_DBG_FLUSH();
  1759. if (as->freeset != RSET_ALL)
  1760. lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
  1761. /* Set trace entry point before fixing up tail to allow link to self. */
  1762. T->mcode = as->mcp;
  1763. T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
  1764. if (!as->loopref)
  1765. asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
  1766. T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
  1767. lj_mcode_sync(T->mcode, origtop);
  1768. }
  1769. #undef IR
  1770. #endif