1 /* 2 ** $Id: lcode.c $ 3 ** Code generator for Lua 4 ** See Copyright Notice in lua.h 5 */ 6 7 #define lcode_c 8 #define LUA_CORE 9 10 #include "lprefix.h" 11 12 13 #include <float.h> 14 #include <limits.h> 15 #include <math.h> 16 #include <stdlib.h> 17 18 #include "lua.h" 19 20 #include "lcode.h" 21 #include "ldebug.h" 22 #include "ldo.h" 23 #include "lgc.h" 24 #include "llex.h" 25 #include "lmem.h" 26 #include "lobject.h" 27 #include "lopcodes.h" 28 #include "lparser.h" 29 #include "lstring.h" 30 #include "ltable.h" 31 #include "lvm.h" 32 33 34 /* Maximum number of registers in a Lua function (must fit in 8 bits) */ 35 #define MAXREGS 255 36 37 38 #define hasjumps(e) ((e)->t != (e)->f) 39 40 41 static int codesJ (FuncState *fs, OpCode o, int sj, int k); 42 43 44 45 /* semantic error */ 46 l_noret luaK_semerror (LexState *ls, const char *msg) { 47 ls->t.token = 0; /* remove "near <token>" from final message */ 48 luaX_syntaxerror(ls, msg); 49 } 50 51 52 /* 53 ** If expression is a numeric constant, fills 'v' with its value 54 ** and returns 1. Otherwise, returns 0. 55 */ 56 static int tonumeral (const expdesc *e, TValue *v) { 57 if (hasjumps(e)) 58 return 0; /* not a numeral */ 59 switch (e->k) { 60 case VKINT: 61 if (v) setivalue(v, e->u.ival); 62 return 1; 63 case VKFLT: 64 if (v) setfltvalue(v, e->u.nval); 65 return 1; 66 default: return 0; 67 } 68 } 69 70 71 /* 72 ** Get the constant value from a constant expression 73 */ 74 static TValue *const2val (FuncState *fs, const expdesc *e) { 75 lua_assert(e->k == VCONST); 76 return &fs->ls->dyd->actvar.arr[e->u.info].k; 77 } 78 79 80 /* 81 ** If expression is a constant, fills 'v' with its value 82 ** and returns 1. Otherwise, returns 0. 83 */ 84 int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) { 85 if (hasjumps(e)) 86 return 0; /* not a constant */ 87 switch (e->k) { 88 case VFALSE: 89 setbfvalue(v); 90 return 1; 91 case VTRUE: 92 setbtvalue(v); 93 return 1; 94 case VNIL: 95 setnilvalue(v); 96 return 1; 97 case VKSTR: { 98 setsvalue(fs->ls->L, v, e->u.strval); 99 return 1; 100 } 101 case VCONST: { 102 setobj(fs->ls->L, v, const2val(fs, e)); 103 return 1; 104 } 105 default: return tonumeral(e, v); 106 } 107 } 108 109 110 /* 111 ** Return the previous instruction of the current code. If there 112 ** may be a jump target between the current instruction and the 113 ** previous one, return an invalid instruction (to avoid wrong 114 ** optimizations). 115 */ 116 static Instruction *previousinstruction (FuncState *fs) { 117 static const Instruction invalidinstruction = ~(Instruction)0; 118 if (fs->pc > fs->lasttarget) 119 return &fs->f->code[fs->pc - 1]; /* previous instruction */ 120 else 121 return cast(Instruction*, &invalidinstruction); 122 } 123 124 125 /* 126 ** Create a OP_LOADNIL instruction, but try to optimize: if the previous 127 ** instruction is also OP_LOADNIL and ranges are compatible, adjust 128 ** range of previous instruction instead of emitting a new one. (For 129 ** instance, 'local a; local b' will generate a single opcode.) 130 */ 131 void luaK_nil (FuncState *fs, int from, int n) { 132 int l = from + n - 1; /* last register to set nil */ 133 Instruction *previous = previousinstruction(fs); 134 if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ 135 int pfrom = GETARG_A(*previous); /* get previous range */ 136 int pl = pfrom + GETARG_B(*previous); 137 if ((pfrom <= from && from <= pl + 1) || 138 (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ 139 if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ 140 if (pl > l) l = pl; /* l = max(l, pl) */ 141 SETARG_A(*previous, from); 142 SETARG_B(*previous, l - from); 143 return; 144 } /* else go through */ 145 } 146 luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ 147 } 148 149 150 /* 151 ** Gets the destination address of a jump instruction. Used to traverse 152 ** a list of jumps. 153 */ 154 static int getjump (FuncState *fs, int pc) { 155 int offset = GETARG_sJ(fs->f->code[pc]); 156 if (offset == NO_JUMP) /* point to itself represents end of list */ 157 return NO_JUMP; /* end of list */ 158 else 159 return (pc+1)+offset; /* turn offset into absolute position */ 160 } 161 162 163 /* 164 ** Fix jump instruction at position 'pc' to jump to 'dest'. 165 ** (Jump addresses are relative in Lua) 166 */ 167 static void fixjump (FuncState *fs, int pc, int dest) { 168 Instruction *jmp = &fs->f->code[pc]; 169 int offset = dest - (pc + 1); 170 lua_assert(dest != NO_JUMP); 171 if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ)) 172 luaX_syntaxerror(fs->ls, "control structure too long"); 173 lua_assert(GET_OPCODE(*jmp) == OP_JMP); 174 SETARG_sJ(*jmp, offset); 175 } 176 177 178 /* 179 ** Concatenate jump-list 'l2' into jump-list 'l1' 180 */ 181 void luaK_concat (FuncState *fs, int *l1, int l2) { 182 if (l2 == NO_JUMP) return; /* nothing to concatenate? */ 183 else if (*l1 == NO_JUMP) /* no original list? */ 184 *l1 = l2; /* 'l1' points to 'l2' */ 185 else { 186 int list = *l1; 187 int next; 188 while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ 189 list = next; 190 fixjump(fs, list, l2); /* last element links to 'l2' */ 191 } 192 } 193 194 195 /* 196 ** Create a jump instruction and return its position, so its destination 197 ** can be fixed later (with 'fixjump'). 198 */ 199 int luaK_jump (FuncState *fs) { 200 return codesJ(fs, OP_JMP, NO_JUMP, 0); 201 } 202 203 204 /* 205 ** Code a 'return' instruction 206 */ 207 void luaK_ret (FuncState *fs, int first, int nret) { 208 OpCode op; 209 switch (nret) { 210 case 0: op = OP_RETURN0; break; 211 case 1: op = OP_RETURN1; break; 212 default: op = OP_RETURN; break; 213 } 214 luaK_codeABC(fs, op, first, nret + 1, 0); 215 } 216 217 218 /* 219 ** Code a "conditional jump", that is, a test or comparison opcode 220 ** followed by a jump. Return jump position. 221 */ 222 static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) { 223 luaK_codeABCk(fs, op, A, B, C, k); 224 return luaK_jump(fs); 225 } 226 227 228 /* 229 ** returns current 'pc' and marks it as a jump target (to avoid wrong 230 ** optimizations with consecutive instructions not in the same basic block). 231 */ 232 int luaK_getlabel (FuncState *fs) { 233 fs->lasttarget = fs->pc; 234 return fs->pc; 235 } 236 237 238 /* 239 ** Returns the position of the instruction "controlling" a given 240 ** jump (that is, its condition), or the jump itself if it is 241 ** unconditional. 242 */ 243 static Instruction *getjumpcontrol (FuncState *fs, int pc) { 244 Instruction *pi = &fs->f->code[pc]; 245 if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) 246 return pi-1; 247 else 248 return pi; 249 } 250 251 252 /* 253 ** Patch destination register for a TESTSET instruction. 254 ** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). 255 ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination 256 ** register. Otherwise, change instruction to a simple 'TEST' (produces 257 ** no register value) 258 */ 259 static int patchtestreg (FuncState *fs, int node, int reg) { 260 Instruction *i = getjumpcontrol(fs, node); 261 if (GET_OPCODE(*i) != OP_TESTSET) 262 return 0; /* cannot patch other instructions */ 263 if (reg != NO_REG && reg != GETARG_B(*i)) 264 SETARG_A(*i, reg); 265 else { 266 /* no register to put value or register already has the value; 267 change instruction to simple test */ 268 *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i)); 269 } 270 return 1; 271 } 272 273 274 /* 275 ** Traverse a list of tests ensuring no one produces a value 276 */ 277 static void removevalues (FuncState *fs, int list) { 278 for (; list != NO_JUMP; list = getjump(fs, list)) 279 patchtestreg(fs, list, NO_REG); 280 } 281 282 283 /* 284 ** Traverse a list of tests, patching their destination address and 285 ** registers: tests producing values jump to 'vtarget' (and put their 286 ** values in 'reg'), other tests jump to 'dtarget'. 287 */ 288 static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, 289 int dtarget) { 290 while (list != NO_JUMP) { 291 int next = getjump(fs, list); 292 if (patchtestreg(fs, list, reg)) 293 fixjump(fs, list, vtarget); 294 else 295 fixjump(fs, list, dtarget); /* jump to default target */ 296 list = next; 297 } 298 } 299 300 301 /* 302 ** Path all jumps in 'list' to jump to 'target'. 303 ** (The assert means that we cannot fix a jump to a forward address 304 ** because we only know addresses once code is generated.) 305 */ 306 void luaK_patchlist (FuncState *fs, int list, int target) { 307 lua_assert(target <= fs->pc); 308 patchlistaux(fs, list, target, NO_REG, target); 309 } 310 311 312 void luaK_patchtohere (FuncState *fs, int list) { 313 int hr = luaK_getlabel(fs); /* mark "here" as a jump target */ 314 luaK_patchlist(fs, list, hr); 315 } 316 317 318 /* limit for difference between lines in relative line info. */ 319 #define LIMLINEDIFF 0x80 320 321 322 /* 323 ** Save line info for a new instruction. If difference from last line 324 ** does not fit in a byte, of after that many instructions, save a new 325 ** absolute line info; (in that case, the special value 'ABSLINEINFO' 326 ** in 'lineinfo' signals the existence of this absolute information.) 327 ** Otherwise, store the difference from last line in 'lineinfo'. 328 */ 329 static void savelineinfo (FuncState *fs, Proto *f, int line) { 330 int linedif = line - fs->previousline; 331 int pc = fs->pc - 1; /* last instruction coded */ 332 if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) { 333 luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo, 334 f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines"); 335 f->abslineinfo[fs->nabslineinfo].pc = pc; 336 f->abslineinfo[fs->nabslineinfo++].line = line; 337 linedif = ABSLINEINFO; /* signal that there is absolute information */ 338 fs->iwthabs = 1; /* restart counter */ 339 } 340 luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte, 341 MAX_INT, "opcodes"); 342 f->lineinfo[pc] = linedif; 343 fs->previousline = line; /* last line saved */ 344 } 345 346 347 /* 348 ** Remove line information from the last instruction. 349 ** If line information for that instruction is absolute, set 'iwthabs' 350 ** above its max to force the new (replacing) instruction to have 351 ** absolute line info, too. 352 */ 353 static void removelastlineinfo (FuncState *fs) { 354 Proto *f = fs->f; 355 int pc = fs->pc - 1; /* last instruction coded */ 356 if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */ 357 fs->previousline -= f->lineinfo[pc]; /* correct last line saved */ 358 fs->iwthabs--; /* undo previous increment */ 359 } 360 else { /* absolute line information */ 361 lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc); 362 fs->nabslineinfo--; /* remove it */ 363 fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */ 364 } 365 } 366 367 368 /* 369 ** Remove the last instruction created, correcting line information 370 ** accordingly. 371 */ 372 static void removelastinstruction (FuncState *fs) { 373 removelastlineinfo(fs); 374 fs->pc--; 375 } 376 377 378 /* 379 ** Emit instruction 'i', checking for array sizes and saving also its 380 ** line information. Return 'i' position. 381 */ 382 int luaK_code (FuncState *fs, Instruction i) { 383 Proto *f = fs->f; 384 /* put new instruction in code array */ 385 luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, 386 MAX_INT, "opcodes"); 387 f->code[fs->pc++] = i; 388 savelineinfo(fs, f, fs->ls->lastline); 389 return fs->pc - 1; /* index of new instruction */ 390 } 391 392 393 /* 394 ** Format and emit an 'iABC' instruction. (Assertions check consistency 395 ** of parameters versus opcode.) 396 */ 397 int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) { 398 lua_assert(getOpMode(o) == iABC); 399 lua_assert(a <= MAXARG_A && b <= MAXARG_B && 400 c <= MAXARG_C && (k & ~1) == 0); 401 return luaK_code(fs, CREATE_ABCk(o, a, b, c, k)); 402 } 403 404 405 /* 406 ** Format and emit an 'iABx' instruction. 407 */ 408 int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { 409 lua_assert(getOpMode(o) == iABx); 410 lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); 411 return luaK_code(fs, CREATE_ABx(o, a, bc)); 412 } 413 414 415 /* 416 ** Format and emit an 'iAsBx' instruction. 417 */ 418 int luaK_codeAsBx (FuncState *fs, OpCode o, int a, int bc) { 419 unsigned int b = bc + OFFSET_sBx; 420 lua_assert(getOpMode(o) == iAsBx); 421 lua_assert(a <= MAXARG_A && b <= MAXARG_Bx); 422 return luaK_code(fs, CREATE_ABx(o, a, b)); 423 } 424 425 426 /* 427 ** Format and emit an 'isJ' instruction. 428 */ 429 static int codesJ (FuncState *fs, OpCode o, int sj, int k) { 430 unsigned int j = sj + OFFSET_sJ; 431 lua_assert(getOpMode(o) == isJ); 432 lua_assert(j <= MAXARG_sJ && (k & ~1) == 0); 433 return luaK_code(fs, CREATE_sJ(o, j, k)); 434 } 435 436 437 /* 438 ** Emit an "extra argument" instruction (format 'iAx') 439 */ 440 static int codeextraarg (FuncState *fs, int a) { 441 lua_assert(a <= MAXARG_Ax); 442 return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); 443 } 444 445 446 /* 447 ** Emit a "load constant" instruction, using either 'OP_LOADK' 448 ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' 449 ** instruction with "extra argument". 450 */ 451 static int luaK_codek (FuncState *fs, int reg, int k) { 452 if (k <= MAXARG_Bx) 453 return luaK_codeABx(fs, OP_LOADK, reg, k); 454 else { 455 int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); 456 codeextraarg(fs, k); 457 return p; 458 } 459 } 460 461 462 /* 463 ** Check register-stack level, keeping track of its maximum size 464 ** in field 'maxstacksize' 465 */ 466 void luaK_checkstack (FuncState *fs, int n) { 467 int newstack = fs->freereg + n; 468 if (newstack > fs->f->maxstacksize) { 469 if (newstack >= MAXREGS) 470 luaX_syntaxerror(fs->ls, 471 "function or expression needs too many registers"); 472 fs->f->maxstacksize = cast_byte(newstack); 473 } 474 } 475 476 477 /* 478 ** Reserve 'n' registers in register stack 479 */ 480 void luaK_reserveregs (FuncState *fs, int n) { 481 luaK_checkstack(fs, n); 482 fs->freereg += n; 483 } 484 485 486 /* 487 ** Free register 'reg', if it is neither a constant index nor 488 ** a local variable. 489 ) 490 */ 491 static void freereg (FuncState *fs, int reg) { 492 if (reg >= luaY_nvarstack(fs)) { 493 fs->freereg--; 494 lua_assert(reg == fs->freereg); 495 } 496 } 497 498 499 /* 500 ** Free two registers in proper order 501 */ 502 static void freeregs (FuncState *fs, int r1, int r2) { 503 if (r1 > r2) { 504 freereg(fs, r1); 505 freereg(fs, r2); 506 } 507 else { 508 freereg(fs, r2); 509 freereg(fs, r1); 510 } 511 } 512 513 514 /* 515 ** Free register used by expression 'e' (if any) 516 */ 517 static void freeexp (FuncState *fs, expdesc *e) { 518 if (e->k == VNONRELOC) 519 freereg(fs, e->u.info); 520 } 521 522 523 /* 524 ** Free registers used by expressions 'e1' and 'e2' (if any) in proper 525 ** order. 526 */ 527 static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { 528 int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; 529 int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; 530 freeregs(fs, r1, r2); 531 } 532 533 534 /* 535 ** Add constant 'v' to prototype's list of constants (field 'k'). 536 ** Use scanner's table to cache position of constants in constant list 537 ** and try to reuse constants. Because some values should not be used 538 ** as keys (nil cannot be a key, integer keys can collapse with float 539 ** keys), the caller must provide a useful 'key' for indexing the cache. 540 ** Note that all functions share the same table, so entering or exiting 541 ** a function can make some indices wrong. 542 */ 543 static int addk (FuncState *fs, TValue *key, TValue *v) { 544 TValue val; 545 lua_State *L = fs->ls->L; 546 Proto *f = fs->f; 547 const TValue *idx = luaH_get(fs->ls->h, key); /* query scanner table */ 548 int k, oldsize; 549 if (ttisinteger(idx)) { /* is there an index there? */ 550 k = cast_int(ivalue(idx)); 551 /* correct value? (warning: must distinguish floats from integers!) */ 552 if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) && 553 luaV_rawequalobj(&f->k[k], v)) 554 return k; /* reuse index */ 555 } 556 /* constant not found; create a new entry */ 557 oldsize = f->sizek; 558 k = fs->nk; 559 /* numerical value does not need GC barrier; 560 table has no metatable, so it does not need to invalidate cache */ 561 setivalue(&val, k); 562 luaH_finishset(L, fs->ls->h, key, idx, &val); 563 luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); 564 while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); 565 setobj(L, &f->k[k], v); 566 fs->nk++; 567 luaC_barrier(L, f, v); 568 return k; 569 } 570 571 572 /* 573 ** Add a string to list of constants and return its index. 574 */ 575 static int stringK (FuncState *fs, TString *s) { 576 TValue o; 577 setsvalue(fs->ls->L, &o, s); 578 return addk(fs, &o, &o); /* use string itself as key */ 579 } 580 581 582 /* 583 ** Add an integer to list of constants and return its index. 584 */ 585 static int luaK_intK (FuncState *fs, lua_Integer n) { 586 TValue o; 587 setivalue(&o, n); 588 return addk(fs, &o, &o); /* use integer itself as key */ 589 } 590 591 /* 592 ** Add a float to list of constants and return its index. Floats 593 ** with integral values need a different key, to avoid collision 594 ** with actual integers. To that, we add to the number its smaller 595 ** power-of-two fraction that is still significant in its scale. 596 ** For doubles, that would be 1/2^52. 597 ** (This method is not bulletproof: there may be another float 598 ** with that value, and for floats larger than 2^53 the result is 599 ** still an integer. At worst, this only wastes an entry with 600 ** a duplicate.) 601 */ 602 static int luaK_numberK (FuncState *fs, lua_Number r) { 603 TValue o; 604 lua_Integer ik; 605 setfltvalue(&o, r); 606 #ifndef LUA_AVOID_FLOAT 607 if (!luaV_flttointeger(r, &ik, F2Ieq)) /* not an integral value? */ 608 return addk(fs, &o, &o); /* use number itself as key */ 609 else { /* must build an alternative key */ 610 const int nbm = l_floatatt(MANT_DIG); 611 const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1); 612 const lua_Number k = (ik == 0) ? q : r + r*q; /* new key */ 613 TValue kv; 614 setfltvalue(&kv, k); 615 /* result is not an integral value, unless value is too large */ 616 lua_assert(!luaV_flttointeger(k, &ik, F2Ieq) || 617 l_mathop(fabs)(r) >= l_mathop(1e6)); 618 return addk(fs, &kv, &o); 619 } 620 #else 621 /* 622 ** When we're avoiding floats, allow any collision since floats are ints. 623 */ 624 return addk(fs, &o, &o); /* use number itself as key */ 625 #endif 626 } 627 628 629 /* 630 ** Add a false to list of constants and return its index. 631 */ 632 static int boolF (FuncState *fs) { 633 TValue o; 634 setbfvalue(&o); 635 return addk(fs, &o, &o); /* use boolean itself as key */ 636 } 637 638 639 /* 640 ** Add a true to list of constants and return its index. 641 */ 642 static int boolT (FuncState *fs) { 643 TValue o; 644 setbtvalue(&o); 645 return addk(fs, &o, &o); /* use boolean itself as key */ 646 } 647 648 649 /* 650 ** Add nil to list of constants and return its index. 651 */ 652 static int nilK (FuncState *fs) { 653 TValue k, v; 654 setnilvalue(&v); 655 /* cannot use nil as key; instead use table itself to represent nil */ 656 sethvalue(fs->ls->L, &k, fs->ls->h); 657 return addk(fs, &k, &v); 658 } 659 660 661 /* 662 ** Check whether 'i' can be stored in an 'sC' operand. Equivalent to 663 ** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of 664 ** overflows in the hidden addition inside 'int2sC'. 665 */ 666 static int fitsC (lua_Integer i) { 667 return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C)); 668 } 669 670 671 /* 672 ** Check whether 'i' can be stored in an 'sBx' operand. 673 */ 674 static int fitsBx (lua_Integer i) { 675 return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx); 676 } 677 678 679 void luaK_int (FuncState *fs, int reg, lua_Integer i) { 680 if (fitsBx(i)) 681 luaK_codeAsBx(fs, OP_LOADI, reg, cast_int(i)); 682 else 683 luaK_codek(fs, reg, luaK_intK(fs, i)); 684 } 685 686 687 static void luaK_float (FuncState *fs, int reg, lua_Number f) { 688 lua_Integer fi; 689 if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi)) 690 luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi)); 691 else 692 luaK_codek(fs, reg, luaK_numberK(fs, f)); 693 } 694 695 696 /* 697 ** Convert a constant in 'v' into an expression description 'e' 698 */ 699 static void const2exp (TValue *v, expdesc *e) { 700 switch (ttypetag(v)) { 701 case LUA_VNUMINT: 702 e->k = VKINT; e->u.ival = ivalue(v); 703 break; 704 case LUA_VNUMFLT: 705 e->k = VKFLT; e->u.nval = fltvalue(v); 706 break; 707 case LUA_VFALSE: 708 e->k = VFALSE; 709 break; 710 case LUA_VTRUE: 711 e->k = VTRUE; 712 break; 713 case LUA_VNIL: 714 e->k = VNIL; 715 break; 716 case LUA_VSHRSTR: case LUA_VLNGSTR: 717 e->k = VKSTR; e->u.strval = tsvalue(v); 718 break; 719 default: lua_assert(0); 720 } 721 } 722 723 724 /* 725 ** Fix an expression to return the number of results 'nresults'. 726 ** 'e' must be a multi-ret expression (function call or vararg). 727 */ 728 void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { 729 Instruction *pc = &getinstruction(fs, e); 730 if (e->k == VCALL) /* expression is an open function call? */ 731 SETARG_C(*pc, nresults + 1); 732 else { 733 lua_assert(e->k == VVARARG); 734 SETARG_C(*pc, nresults + 1); 735 SETARG_A(*pc, fs->freereg); 736 luaK_reserveregs(fs, 1); 737 } 738 } 739 740 741 /* 742 ** Convert a VKSTR to a VK 743 */ 744 static void str2K (FuncState *fs, expdesc *e) { 745 lua_assert(e->k == VKSTR); 746 e->u.info = stringK(fs, e->u.strval); 747 e->k = VK; 748 } 749 750 751 /* 752 ** Fix an expression to return one result. 753 ** If expression is not a multi-ret expression (function call or 754 ** vararg), it already returns one result, so nothing needs to be done. 755 ** Function calls become VNONRELOC expressions (as its result comes 756 ** fixed in the base register of the call), while vararg expressions 757 ** become VRELOC (as OP_VARARG puts its results where it wants). 758 ** (Calls are created returning one result, so that does not need 759 ** to be fixed.) 760 */ 761 void luaK_setoneret (FuncState *fs, expdesc *e) { 762 if (e->k == VCALL) { /* expression is an open function call? */ 763 /* already returns 1 value */ 764 lua_assert(GETARG_C(getinstruction(fs, e)) == 2); 765 e->k = VNONRELOC; /* result has fixed position */ 766 e->u.info = GETARG_A(getinstruction(fs, e)); 767 } 768 else if (e->k == VVARARG) { 769 SETARG_C(getinstruction(fs, e), 2); 770 e->k = VRELOC; /* can relocate its simple result */ 771 } 772 } 773 774 775 /* 776 ** Ensure that expression 'e' is not a variable (nor a <const>). 777 ** (Expression still may have jump lists.) 778 */ 779 void luaK_dischargevars (FuncState *fs, expdesc *e) { 780 switch (e->k) { 781 case VCONST: { 782 const2exp(const2val(fs, e), e); 783 break; 784 } 785 case VLOCAL: { /* already in a register */ 786 e->u.info = e->u.var.ridx; 787 e->k = VNONRELOC; /* becomes a non-relocatable value */ 788 break; 789 } 790 case VUPVAL: { /* move value to some (pending) register */ 791 e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); 792 e->k = VRELOC; 793 break; 794 } 795 case VINDEXUP: { 796 e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx); 797 e->k = VRELOC; 798 break; 799 } 800 case VINDEXI: { 801 freereg(fs, e->u.ind.t); 802 e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx); 803 e->k = VRELOC; 804 break; 805 } 806 case VINDEXSTR: { 807 freereg(fs, e->u.ind.t); 808 e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx); 809 e->k = VRELOC; 810 break; 811 } 812 case VINDEXED: { 813 freeregs(fs, e->u.ind.t, e->u.ind.idx); 814 e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx); 815 e->k = VRELOC; 816 break; 817 } 818 case VVARARG: case VCALL: { 819 luaK_setoneret(fs, e); 820 break; 821 } 822 default: break; /* there is one value available (somewhere) */ 823 } 824 } 825 826 827 /* 828 ** Ensure expression value is in register 'reg', making 'e' a 829 ** non-relocatable expression. 830 ** (Expression still may have jump lists.) 831 */ 832 static void discharge2reg (FuncState *fs, expdesc *e, int reg) { 833 luaK_dischargevars(fs, e); 834 switch (e->k) { 835 case VNIL: { 836 luaK_nil(fs, reg, 1); 837 break; 838 } 839 case VFALSE: { 840 luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0); 841 break; 842 } 843 case VTRUE: { 844 luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0); 845 break; 846 } 847 case VKSTR: { 848 str2K(fs, e); 849 } /* FALLTHROUGH */ 850 case VK: { 851 luaK_codek(fs, reg, e->u.info); 852 break; 853 } 854 case VKFLT: { 855 luaK_float(fs, reg, e->u.nval); 856 break; 857 } 858 case VKINT: { 859 luaK_int(fs, reg, e->u.ival); 860 break; 861 } 862 case VRELOC: { 863 Instruction *pc = &getinstruction(fs, e); 864 SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ 865 break; 866 } 867 case VNONRELOC: { 868 if (reg != e->u.info) 869 luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); 870 break; 871 } 872 default: { 873 lua_assert(e->k == VJMP); 874 return; /* nothing to do... */ 875 } 876 } 877 e->u.info = reg; 878 e->k = VNONRELOC; 879 } 880 881 882 /* 883 ** Ensure expression value is in a register, making 'e' a 884 ** non-relocatable expression. 885 ** (Expression still may have jump lists.) 886 */ 887 static void discharge2anyreg (FuncState *fs, expdesc *e) { 888 if (e->k != VNONRELOC) { /* no fixed register yet? */ 889 luaK_reserveregs(fs, 1); /* get a register */ 890 discharge2reg(fs, e, fs->freereg-1); /* put value there */ 891 } 892 } 893 894 895 static int code_loadbool (FuncState *fs, int A, OpCode op) { 896 luaK_getlabel(fs); /* those instructions may be jump targets */ 897 return luaK_codeABC(fs, op, A, 0, 0); 898 } 899 900 901 /* 902 ** check whether list has any jump that do not produce a value 903 ** or produce an inverted value 904 */ 905 static int need_value (FuncState *fs, int list) { 906 for (; list != NO_JUMP; list = getjump(fs, list)) { 907 Instruction i = *getjumpcontrol(fs, list); 908 if (GET_OPCODE(i) != OP_TESTSET) return 1; 909 } 910 return 0; /* not found */ 911 } 912 913 914 /* 915 ** Ensures final expression result (which includes results from its 916 ** jump lists) is in register 'reg'. 917 ** If expression has jumps, need to patch these jumps either to 918 ** its final position or to "load" instructions (for those tests 919 ** that do not produce values). 920 */ 921 static void exp2reg (FuncState *fs, expdesc *e, int reg) { 922 discharge2reg(fs, e, reg); 923 if (e->k == VJMP) /* expression itself is a test? */ 924 luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ 925 if (hasjumps(e)) { 926 int final; /* position after whole expression */ 927 int p_f = NO_JUMP; /* position of an eventual LOAD false */ 928 int p_t = NO_JUMP; /* position of an eventual LOAD true */ 929 if (need_value(fs, e->t) || need_value(fs, e->f)) { 930 int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); 931 p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */ 932 p_t = code_loadbool(fs, reg, OP_LOADTRUE); 933 /* jump around these booleans if 'e' is not a test */ 934 luaK_patchtohere(fs, fj); 935 } 936 final = luaK_getlabel(fs); 937 patchlistaux(fs, e->f, final, reg, p_f); 938 patchlistaux(fs, e->t, final, reg, p_t); 939 } 940 e->f = e->t = NO_JUMP; 941 e->u.info = reg; 942 e->k = VNONRELOC; 943 } 944 945 946 /* 947 ** Ensures final expression result is in next available register. 948 */ 949 void luaK_exp2nextreg (FuncState *fs, expdesc *e) { 950 luaK_dischargevars(fs, e); 951 freeexp(fs, e); 952 luaK_reserveregs(fs, 1); 953 exp2reg(fs, e, fs->freereg - 1); 954 } 955 956 957 /* 958 ** Ensures final expression result is in some (any) register 959 ** and return that register. 960 */ 961 int luaK_exp2anyreg (FuncState *fs, expdesc *e) { 962 luaK_dischargevars(fs, e); 963 if (e->k == VNONRELOC) { /* expression already has a register? */ 964 if (!hasjumps(e)) /* no jumps? */ 965 return e->u.info; /* result is already in a register */ 966 if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */ 967 exp2reg(fs, e, e->u.info); /* put final result in it */ 968 return e->u.info; 969 } 970 /* else expression has jumps and cannot change its register 971 to hold the jump values, because it is a local variable. 972 Go through to the default case. */ 973 } 974 luaK_exp2nextreg(fs, e); /* default: use next available register */ 975 return e->u.info; 976 } 977 978 979 /* 980 ** Ensures final expression result is either in a register 981 ** or in an upvalue. 982 */ 983 void luaK_exp2anyregup (FuncState *fs, expdesc *e) { 984 if (e->k != VUPVAL || hasjumps(e)) 985 luaK_exp2anyreg(fs, e); 986 } 987 988 989 /* 990 ** Ensures final expression result is either in a register 991 ** or it is a constant. 992 */ 993 void luaK_exp2val (FuncState *fs, expdesc *e) { 994 if (hasjumps(e)) 995 luaK_exp2anyreg(fs, e); 996 else 997 luaK_dischargevars(fs, e); 998 } 999 1000 1001 /* 1002 ** Try to make 'e' a K expression with an index in the range of R/K 1003 ** indices. Return true iff succeeded. 1004 */ 1005 static int luaK_exp2K (FuncState *fs, expdesc *e) { 1006 if (!hasjumps(e)) { 1007 int info; 1008 switch (e->k) { /* move constants to 'k' */ 1009 case VTRUE: info = boolT(fs); break; 1010 case VFALSE: info = boolF(fs); break; 1011 case VNIL: info = nilK(fs); break; 1012 case VKINT: info = luaK_intK(fs, e->u.ival); break; 1013 case VKFLT: info = luaK_numberK(fs, e->u.nval); break; 1014 case VKSTR: info = stringK(fs, e->u.strval); break; 1015 case VK: info = e->u.info; break; 1016 default: return 0; /* not a constant */ 1017 } 1018 if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */ 1019 e->k = VK; /* make expression a 'K' expression */ 1020 e->u.info = info; 1021 return 1; 1022 } 1023 } 1024 /* else, expression doesn't fit; leave it unchanged */ 1025 return 0; 1026 } 1027 1028 1029 /* 1030 ** Ensures final expression result is in a valid R/K index 1031 ** (that is, it is either in a register or in 'k' with an index 1032 ** in the range of R/K indices). 1033 ** Returns 1 iff expression is K. 1034 */ 1035 int luaK_exp2RK (FuncState *fs, expdesc *e) { 1036 if (luaK_exp2K(fs, e)) 1037 return 1; 1038 else { /* not a constant in the right range: put it in a register */ 1039 luaK_exp2anyreg(fs, e); 1040 return 0; 1041 } 1042 } 1043 1044 1045 static void codeABRK (FuncState *fs, OpCode o, int a, int b, 1046 expdesc *ec) { 1047 int k = luaK_exp2RK(fs, ec); 1048 luaK_codeABCk(fs, o, a, b, ec->u.info, k); 1049 } 1050 1051 1052 /* 1053 ** Generate code to store result of expression 'ex' into variable 'var'. 1054 */ 1055 void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { 1056 switch (var->k) { 1057 case VLOCAL: { 1058 freeexp(fs, ex); 1059 exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */ 1060 return; 1061 } 1062 case VUPVAL: { 1063 int e = luaK_exp2anyreg(fs, ex); 1064 luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); 1065 break; 1066 } 1067 case VINDEXUP: { 1068 codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex); 1069 break; 1070 } 1071 case VINDEXI: { 1072 codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex); 1073 break; 1074 } 1075 case VINDEXSTR: { 1076 codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex); 1077 break; 1078 } 1079 case VINDEXED: { 1080 codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex); 1081 break; 1082 } 1083 default: lua_assert(0); /* invalid var kind to store */ 1084 } 1085 freeexp(fs, ex); 1086 } 1087 1088 1089 /* 1090 ** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). 1091 */ 1092 void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { 1093 int ereg; 1094 luaK_exp2anyreg(fs, e); 1095 ereg = e->u.info; /* register where 'e' was placed */ 1096 freeexp(fs, e); 1097 e->u.info = fs->freereg; /* base register for op_self */ 1098 e->k = VNONRELOC; /* self expression has a fixed register */ 1099 luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ 1100 codeABRK(fs, OP_SELF, e->u.info, ereg, key); 1101 freeexp(fs, key); 1102 } 1103 1104 1105 /* 1106 ** Negate condition 'e' (where 'e' is a comparison). 1107 */ 1108 static void negatecondition (FuncState *fs, expdesc *e) { 1109 Instruction *pc = getjumpcontrol(fs, e->u.info); 1110 lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && 1111 GET_OPCODE(*pc) != OP_TEST); 1112 SETARG_k(*pc, (GETARG_k(*pc) ^ 1)); 1113 } 1114 1115 1116 /* 1117 ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' 1118 ** is true, code will jump if 'e' is true.) Return jump position. 1119 ** Optimize when 'e' is 'not' something, inverting the condition 1120 ** and removing the 'not'. 1121 */ 1122 static int jumponcond (FuncState *fs, expdesc *e, int cond) { 1123 if (e->k == VRELOC) { 1124 Instruction ie = getinstruction(fs, e); 1125 if (GET_OPCODE(ie) == OP_NOT) { 1126 removelastinstruction(fs); /* remove previous OP_NOT */ 1127 return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond); 1128 } 1129 /* else go through */ 1130 } 1131 discharge2anyreg(fs, e); 1132 freeexp(fs, e); 1133 return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond); 1134 } 1135 1136 1137 /* 1138 ** Emit code to go through if 'e' is true, jump otherwise. 1139 */ 1140 void luaK_goiftrue (FuncState *fs, expdesc *e) { 1141 int pc; /* pc of new jump */ 1142 luaK_dischargevars(fs, e); 1143 switch (e->k) { 1144 case VJMP: { /* condition? */ 1145 negatecondition(fs, e); /* jump when it is false */ 1146 pc = e->u.info; /* save jump position */ 1147 break; 1148 } 1149 case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { 1150 pc = NO_JUMP; /* always true; do nothing */ 1151 break; 1152 } 1153 default: { 1154 pc = jumponcond(fs, e, 0); /* jump when false */ 1155 break; 1156 } 1157 } 1158 luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ 1159 luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ 1160 e->t = NO_JUMP; 1161 } 1162 1163 1164 /* 1165 ** Emit code to go through if 'e' is false, jump otherwise. 1166 */ 1167 void luaK_goiffalse (FuncState *fs, expdesc *e) { 1168 int pc; /* pc of new jump */ 1169 luaK_dischargevars(fs, e); 1170 switch (e->k) { 1171 case VJMP: { 1172 pc = e->u.info; /* already jump if true */ 1173 break; 1174 } 1175 case VNIL: case VFALSE: { 1176 pc = NO_JUMP; /* always false; do nothing */ 1177 break; 1178 } 1179 default: { 1180 pc = jumponcond(fs, e, 1); /* jump if true */ 1181 break; 1182 } 1183 } 1184 luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ 1185 luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ 1186 e->f = NO_JUMP; 1187 } 1188 1189 1190 /* 1191 ** Code 'not e', doing constant folding. 1192 */ 1193 static void codenot (FuncState *fs, expdesc *e) { 1194 switch (e->k) { 1195 case VNIL: case VFALSE: { 1196 e->k = VTRUE; /* true == not nil == not false */ 1197 break; 1198 } 1199 case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { 1200 e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ 1201 break; 1202 } 1203 case VJMP: { 1204 negatecondition(fs, e); 1205 break; 1206 } 1207 case VRELOC: 1208 case VNONRELOC: { 1209 discharge2anyreg(fs, e); 1210 freeexp(fs, e); 1211 e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); 1212 e->k = VRELOC; 1213 break; 1214 } 1215 default: lua_assert(0); /* cannot happen */ 1216 } 1217 /* interchange true and false lists */ 1218 { int temp = e->f; e->f = e->t; e->t = temp; } 1219 removevalues(fs, e->f); /* values are useless when negated */ 1220 removevalues(fs, e->t); 1221 } 1222 1223 1224 /* 1225 ** Check whether expression 'e' is a small literal string 1226 */ 1227 static int isKstr (FuncState *fs, expdesc *e) { 1228 return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B && 1229 ttisshrstring(&fs->f->k[e->u.info])); 1230 } 1231 1232 /* 1233 ** Check whether expression 'e' is a literal integer. 1234 */ 1235 int luaK_isKint (expdesc *e) { 1236 return (e->k == VKINT && !hasjumps(e)); 1237 } 1238 1239 1240 /* 1241 ** Check whether expression 'e' is a literal integer in 1242 ** proper range to fit in register C 1243 */ 1244 static int isCint (expdesc *e) { 1245 return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C)); 1246 } 1247 1248 1249 /* 1250 ** Check whether expression 'e' is a literal integer in 1251 ** proper range to fit in register sC 1252 */ 1253 static int isSCint (expdesc *e) { 1254 return luaK_isKint(e) && fitsC(e->u.ival); 1255 } 1256 1257 1258 /* 1259 ** Check whether expression 'e' is a literal integer or float in 1260 ** proper range to fit in a register (sB or sC). 1261 */ 1262 static int isSCnumber (expdesc *e, int *pi, int *isfloat) { 1263 lua_Integer i; 1264 if (e->k == VKINT) 1265 i = e->u.ival; 1266 else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq)) 1267 *isfloat = 1; 1268 else 1269 return 0; /* not a number */ 1270 if (!hasjumps(e) && fitsC(i)) { 1271 *pi = int2sC(cast_int(i)); 1272 return 1; 1273 } 1274 else 1275 return 0; 1276 } 1277 1278 1279 /* 1280 ** Create expression 't[k]'. 't' must have its final result already in a 1281 ** register or upvalue. Upvalues can only be indexed by literal strings. 1282 ** Keys can be literal strings in the constant table or arbitrary 1283 ** values in registers. 1284 */ 1285 void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { 1286 if (k->k == VKSTR) 1287 str2K(fs, k); 1288 lua_assert(!hasjumps(t) && 1289 (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL)); 1290 if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */ 1291 luaK_exp2anyreg(fs, t); /* put it in a register */ 1292 if (t->k == VUPVAL) { 1293 t->u.ind.t = t->u.info; /* upvalue index */ 1294 t->u.ind.idx = k->u.info; /* literal string */ 1295 t->k = VINDEXUP; 1296 } 1297 else { 1298 /* register index of the table */ 1299 t->u.ind.t = (t->k == VLOCAL) ? t->u.var.ridx: t->u.info; 1300 if (isKstr(fs, k)) { 1301 t->u.ind.idx = k->u.info; /* literal string */ 1302 t->k = VINDEXSTR; 1303 } 1304 else if (isCint(k)) { 1305 t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */ 1306 t->k = VINDEXI; 1307 } 1308 else { 1309 t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */ 1310 t->k = VINDEXED; 1311 } 1312 } 1313 } 1314 1315 1316 /* 1317 ** Return false if folding can raise an error. 1318 ** Bitwise operations need operands convertible to integers; division 1319 ** operations cannot have 0 as divisor. 1320 */ 1321 static int validop (int op, TValue *v1, TValue *v2) { 1322 switch (op) { 1323 case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: 1324 case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ 1325 lua_Integer i; 1326 return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) && 1327 luaV_tointegerns(v2, &i, LUA_FLOORN2I)); 1328 } 1329 case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ 1330 return (nvalue(v2) != 0); 1331 default: return 1; /* everything else is valid */ 1332 } 1333 } 1334 1335 1336 /* 1337 ** Try to "constant-fold" an operation; return 1 iff successful. 1338 ** (In this case, 'e1' has the final result.) 1339 */ 1340 static int constfolding (FuncState *fs, int op, expdesc *e1, 1341 const expdesc *e2) { 1342 TValue v1, v2, res; 1343 if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) 1344 return 0; /* non-numeric operands or not safe to fold */ 1345 luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ 1346 if (ttisinteger(&res)) { 1347 e1->k = VKINT; 1348 e1->u.ival = ivalue(&res); 1349 } 1350 else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ 1351 lua_Number n = fltvalue(&res); 1352 if (luai_numisnan(n) || n == 0) 1353 return 0; 1354 e1->k = VKFLT; 1355 e1->u.nval = n; 1356 } 1357 return 1; 1358 } 1359 1360 1361 /* 1362 ** Convert a BinOpr to an OpCode (ORDER OPR - ORDER OP) 1363 */ 1364 l_sinline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) { 1365 lua_assert(baser <= opr && 1366 ((baser == OPR_ADD && opr <= OPR_SHR) || 1367 (baser == OPR_LT && opr <= OPR_LE))); 1368 return cast(OpCode, (cast_int(opr) - cast_int(baser)) + cast_int(base)); 1369 } 1370 1371 1372 /* 1373 ** Convert a UnOpr to an OpCode (ORDER OPR - ORDER OP) 1374 */ 1375 l_sinline OpCode unopr2op (UnOpr opr) { 1376 return cast(OpCode, (cast_int(opr) - cast_int(OPR_MINUS)) + 1377 cast_int(OP_UNM)); 1378 } 1379 1380 1381 /* 1382 ** Convert a BinOpr to a tag method (ORDER OPR - ORDER TM) 1383 */ 1384 l_sinline TMS binopr2TM (BinOpr opr) { 1385 lua_assert(OPR_ADD <= opr && opr <= OPR_SHR); 1386 return cast(TMS, (cast_int(opr) - cast_int(OPR_ADD)) + cast_int(TM_ADD)); 1387 } 1388 1389 1390 /* 1391 ** Emit code for unary expressions that "produce values" 1392 ** (everything but 'not'). 1393 ** Expression to produce final result will be encoded in 'e'. 1394 */ 1395 static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { 1396 int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ 1397 freeexp(fs, e); 1398 e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ 1399 e->k = VRELOC; /* all those operations are relocatable */ 1400 luaK_fixline(fs, line); 1401 } 1402 1403 1404 /* 1405 ** Emit code for binary expressions that "produce values" 1406 ** (everything but logical operators 'and'/'or' and comparison 1407 ** operators). 1408 ** Expression to produce final result will be encoded in 'e1'. 1409 */ 1410 static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2, 1411 OpCode op, int v2, int flip, int line, 1412 OpCode mmop, TMS event) { 1413 int v1 = luaK_exp2anyreg(fs, e1); 1414 int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0); 1415 freeexps(fs, e1, e2); 1416 e1->u.info = pc; 1417 e1->k = VRELOC; /* all those operations are relocatable */ 1418 luaK_fixline(fs, line); 1419 luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */ 1420 luaK_fixline(fs, line); 1421 } 1422 1423 1424 /* 1425 ** Emit code for binary expressions that "produce values" over 1426 ** two registers. 1427 */ 1428 static void codebinexpval (FuncState *fs, BinOpr opr, 1429 expdesc *e1, expdesc *e2, int line) { 1430 OpCode op = binopr2op(opr, OPR_ADD, OP_ADD); 1431 int v2 = luaK_exp2anyreg(fs, e2); /* make sure 'e2' is in a register */ 1432 /* 'e1' must be already in a register or it is a constant */ 1433 lua_assert((VNIL <= e1->k && e1->k <= VKSTR) || 1434 e1->k == VNONRELOC || e1->k == VRELOC); 1435 lua_assert(OP_ADD <= op && op <= OP_SHR); 1436 finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr)); 1437 } 1438 1439 1440 /* 1441 ** Code binary operators with immediate operands. 1442 */ 1443 static void codebini (FuncState *fs, OpCode op, 1444 expdesc *e1, expdesc *e2, int flip, int line, 1445 TMS event) { 1446 int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */ 1447 lua_assert(e2->k == VKINT); 1448 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event); 1449 } 1450 1451 1452 /* 1453 ** Code binary operators with K operand. 1454 */ 1455 static void codebinK (FuncState *fs, BinOpr opr, 1456 expdesc *e1, expdesc *e2, int flip, int line) { 1457 TMS event = binopr2TM(opr); 1458 int v2 = e2->u.info; /* K index */ 1459 OpCode op = binopr2op(opr, OPR_ADD, OP_ADDK); 1460 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event); 1461 } 1462 1463 1464 /* Try to code a binary operator negating its second operand. 1465 ** For the metamethod, 2nd operand must keep its original value. 1466 */ 1467 static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2, 1468 OpCode op, int line, TMS event) { 1469 if (!luaK_isKint(e2)) 1470 return 0; /* not an integer constant */ 1471 else { 1472 lua_Integer i2 = e2->u.ival; 1473 if (!(fitsC(i2) && fitsC(-i2))) 1474 return 0; /* not in the proper range */ 1475 else { /* operating a small integer constant */ 1476 int v2 = cast_int(i2); 1477 finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event); 1478 /* correct metamethod argument */ 1479 SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2)); 1480 return 1; /* successfully coded */ 1481 } 1482 } 1483 } 1484 1485 1486 static void swapexps (expdesc *e1, expdesc *e2) { 1487 expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */ 1488 } 1489 1490 1491 /* 1492 ** Code binary operators with no constant operand. 1493 */ 1494 static void codebinNoK (FuncState *fs, BinOpr opr, 1495 expdesc *e1, expdesc *e2, int flip, int line) { 1496 if (flip) 1497 swapexps(e1, e2); /* back to original order */ 1498 codebinexpval(fs, opr, e1, e2, line); /* use standard operators */ 1499 } 1500 1501 1502 /* 1503 ** Code arithmetic operators ('+', '-', ...). If second operand is a 1504 ** constant in the proper range, use variant opcodes with K operands. 1505 */ 1506 static void codearith (FuncState *fs, BinOpr opr, 1507 expdesc *e1, expdesc *e2, int flip, int line) { 1508 if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) /* K operand? */ 1509 codebinK(fs, opr, e1, e2, flip, line); 1510 else /* 'e2' is neither an immediate nor a K operand */ 1511 codebinNoK(fs, opr, e1, e2, flip, line); 1512 } 1513 1514 1515 /* 1516 ** Code commutative operators ('+', '*'). If first operand is a 1517 ** numeric constant, change order of operands to try to use an 1518 ** immediate or K operator. 1519 */ 1520 static void codecommutative (FuncState *fs, BinOpr op, 1521 expdesc *e1, expdesc *e2, int line) { 1522 int flip = 0; 1523 if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */ 1524 swapexps(e1, e2); /* change order */ 1525 flip = 1; 1526 } 1527 if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */ 1528 codebini(fs, OP_ADDI, e1, e2, flip, line, TM_ADD); 1529 else 1530 codearith(fs, op, e1, e2, flip, line); 1531 } 1532 1533 1534 /* 1535 ** Code bitwise operations; they are all commutative, so the function 1536 ** tries to put an integer constant as the 2nd operand (a K operand). 1537 */ 1538 static void codebitwise (FuncState *fs, BinOpr opr, 1539 expdesc *e1, expdesc *e2, int line) { 1540 int flip = 0; 1541 if (e1->k == VKINT) { 1542 swapexps(e1, e2); /* 'e2' will be the constant operand */ 1543 flip = 1; 1544 } 1545 if (e2->k == VKINT && luaK_exp2K(fs, e2)) /* K operand? */ 1546 codebinK(fs, opr, e1, e2, flip, line); 1547 else /* no constants */ 1548 codebinNoK(fs, opr, e1, e2, flip, line); 1549 } 1550 1551 1552 /* 1553 ** Emit code for order comparisons. When using an immediate operand, 1554 ** 'isfloat' tells whether the original value was a float. 1555 */ 1556 static void codeorder (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { 1557 int r1, r2; 1558 int im; 1559 int isfloat = 0; 1560 OpCode op; 1561 if (isSCnumber(e2, &im, &isfloat)) { 1562 /* use immediate operand */ 1563 r1 = luaK_exp2anyreg(fs, e1); 1564 r2 = im; 1565 op = binopr2op(opr, OPR_LT, OP_LTI); 1566 } 1567 else if (isSCnumber(e1, &im, &isfloat)) { 1568 /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */ 1569 r1 = luaK_exp2anyreg(fs, e2); 1570 r2 = im; 1571 op = binopr2op(opr, OPR_LT, OP_GTI); 1572 } 1573 else { /* regular case, compare two registers */ 1574 r1 = luaK_exp2anyreg(fs, e1); 1575 r2 = luaK_exp2anyreg(fs, e2); 1576 op = binopr2op(opr, OPR_LT, OP_LT); 1577 } 1578 freeexps(fs, e1, e2); 1579 e1->u.info = condjump(fs, op, r1, r2, isfloat, 1); 1580 e1->k = VJMP; 1581 } 1582 1583 1584 /* 1585 ** Emit code for equality comparisons ('==', '~='). 1586 ** 'e1' was already put as RK by 'luaK_infix'. 1587 */ 1588 static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { 1589 int r1, r2; 1590 int im; 1591 int isfloat = 0; /* not needed here, but kept for symmetry */ 1592 OpCode op; 1593 if (e1->k != VNONRELOC) { 1594 lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT); 1595 swapexps(e1, e2); 1596 } 1597 r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */ 1598 if (isSCnumber(e2, &im, &isfloat)) { 1599 op = OP_EQI; 1600 r2 = im; /* immediate operand */ 1601 } 1602 else if (luaK_exp2RK(fs, e2)) { /* 2nd expression is constant? */ 1603 op = OP_EQK; 1604 r2 = e2->u.info; /* constant index */ 1605 } 1606 else { 1607 op = OP_EQ; /* will compare two registers */ 1608 r2 = luaK_exp2anyreg(fs, e2); 1609 } 1610 freeexps(fs, e1, e2); 1611 e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ)); 1612 e1->k = VJMP; 1613 } 1614 1615 1616 /* 1617 ** Apply prefix operation 'op' to expression 'e'. 1618 */ 1619 void luaK_prefix (FuncState *fs, UnOpr opr, expdesc *e, int line) { 1620 static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; 1621 luaK_dischargevars(fs, e); 1622 switch (opr) { 1623 case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ 1624 if (constfolding(fs, opr + LUA_OPUNM, e, &ef)) 1625 break; 1626 /* else */ /* FALLTHROUGH */ 1627 case OPR_LEN: 1628 codeunexpval(fs, unopr2op(opr), e, line); 1629 break; 1630 case OPR_NOT: codenot(fs, e); break; 1631 default: lua_assert(0); 1632 } 1633 } 1634 1635 1636 /* 1637 ** Process 1st operand 'v' of binary operation 'op' before reading 1638 ** 2nd operand. 1639 */ 1640 void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { 1641 luaK_dischargevars(fs, v); 1642 switch (op) { 1643 case OPR_AND: { 1644 luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ 1645 break; 1646 } 1647 case OPR_OR: { 1648 luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ 1649 break; 1650 } 1651 case OPR_CONCAT: { 1652 luaK_exp2nextreg(fs, v); /* operand must be on the stack */ 1653 break; 1654 } 1655 case OPR_ADD: case OPR_SUB: 1656 case OPR_MUL: case OPR_DIV: case OPR_IDIV: 1657 case OPR_MOD: case OPR_POW: 1658 case OPR_BAND: case OPR_BOR: case OPR_BXOR: 1659 case OPR_SHL: case OPR_SHR: { 1660 if (!tonumeral(v, NULL)) 1661 luaK_exp2anyreg(fs, v); 1662 /* else keep numeral, which may be folded or used as an immediate 1663 operand */ 1664 break; 1665 } 1666 case OPR_EQ: case OPR_NE: { 1667 if (!tonumeral(v, NULL)) 1668 luaK_exp2RK(fs, v); 1669 /* else keep numeral, which may be an immediate operand */ 1670 break; 1671 } 1672 case OPR_LT: case OPR_LE: 1673 case OPR_GT: case OPR_GE: { 1674 int dummy, dummy2; 1675 if (!isSCnumber(v, &dummy, &dummy2)) 1676 luaK_exp2anyreg(fs, v); 1677 /* else keep numeral, which may be an immediate operand */ 1678 break; 1679 } 1680 default: lua_assert(0); 1681 } 1682 } 1683 1684 /* 1685 ** Create code for '(e1 .. e2)'. 1686 ** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))', 1687 ** because concatenation is right associative), merge both CONCATs. 1688 */ 1689 static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) { 1690 Instruction *ie2 = previousinstruction(fs); 1691 if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */ 1692 int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */ 1693 lua_assert(e1->u.info + 1 == GETARG_A(*ie2)); 1694 freeexp(fs, e2); 1695 SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */ 1696 SETARG_B(*ie2, n + 1); /* will concatenate one more element */ 1697 } 1698 else { /* 'e2' is not a concatenation */ 1699 luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */ 1700 freeexp(fs, e2); 1701 luaK_fixline(fs, line); 1702 } 1703 } 1704 1705 1706 /* 1707 ** Finalize code for binary operation, after reading 2nd operand. 1708 */ 1709 void luaK_posfix (FuncState *fs, BinOpr opr, 1710 expdesc *e1, expdesc *e2, int line) { 1711 luaK_dischargevars(fs, e2); 1712 if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2)) 1713 return; /* done by folding */ 1714 switch (opr) { 1715 case OPR_AND: { 1716 lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */ 1717 luaK_concat(fs, &e2->f, e1->f); 1718 *e1 = *e2; 1719 break; 1720 } 1721 case OPR_OR: { 1722 lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */ 1723 luaK_concat(fs, &e2->t, e1->t); 1724 *e1 = *e2; 1725 break; 1726 } 1727 case OPR_CONCAT: { /* e1 .. e2 */ 1728 luaK_exp2nextreg(fs, e2); 1729 codeconcat(fs, e1, e2, line); 1730 break; 1731 } 1732 case OPR_ADD: case OPR_MUL: { 1733 codecommutative(fs, opr, e1, e2, line); 1734 break; 1735 } 1736 case OPR_SUB: { 1737 if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB)) 1738 break; /* coded as (r1 + -I) */ 1739 /* ELSE */ 1740 } /* FALLTHROUGH */ 1741 case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: { 1742 codearith(fs, opr, e1, e2, 0, line); 1743 break; 1744 } 1745 case OPR_BAND: case OPR_BOR: case OPR_BXOR: { 1746 codebitwise(fs, opr, e1, e2, line); 1747 break; 1748 } 1749 case OPR_SHL: { 1750 if (isSCint(e1)) { 1751 swapexps(e1, e2); 1752 codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */ 1753 } 1754 else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) { 1755 /* coded as (r1 >> -I) */; 1756 } 1757 else /* regular case (two registers) */ 1758 codebinexpval(fs, opr, e1, e2, line); 1759 break; 1760 } 1761 case OPR_SHR: { 1762 if (isSCint(e2)) 1763 codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */ 1764 else /* regular case (two registers) */ 1765 codebinexpval(fs, opr, e1, e2, line); 1766 break; 1767 } 1768 case OPR_EQ: case OPR_NE: { 1769 codeeq(fs, opr, e1, e2); 1770 break; 1771 } 1772 case OPR_GT: case OPR_GE: { 1773 /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */ 1774 swapexps(e1, e2); 1775 opr = cast(BinOpr, (opr - OPR_GT) + OPR_LT); 1776 } /* FALLTHROUGH */ 1777 case OPR_LT: case OPR_LE: { 1778 codeorder(fs, opr, e1, e2); 1779 break; 1780 } 1781 default: lua_assert(0); 1782 } 1783 } 1784 1785 1786 /* 1787 ** Change line information associated with current position, by removing 1788 ** previous info and adding it again with new line. 1789 */ 1790 void luaK_fixline (FuncState *fs, int line) { 1791 removelastlineinfo(fs); 1792 savelineinfo(fs, fs->f, line); 1793 } 1794 1795 1796 void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) { 1797 Instruction *inst = &fs->f->code[pc]; 1798 int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */ 1799 int extra = asize / (MAXARG_C + 1); /* higher bits of array size */ 1800 int rc = asize % (MAXARG_C + 1); /* lower bits of array size */ 1801 int k = (extra > 0); /* true iff needs extra argument */ 1802 *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k); 1803 *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra); 1804 } 1805 1806 1807 /* 1808 ** Emit a SETLIST instruction. 1809 ** 'base' is register that keeps table; 1810 ** 'nelems' is #table plus those to be stored now; 1811 ** 'tostore' is number of values (in registers 'base + 1',...) to add to 1812 ** table (or LUA_MULTRET to add up to stack top). 1813 */ 1814 void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { 1815 lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); 1816 if (tostore == LUA_MULTRET) 1817 tostore = 0; 1818 if (nelems <= MAXARG_C) 1819 luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems); 1820 else { 1821 int extra = nelems / (MAXARG_C + 1); 1822 nelems %= (MAXARG_C + 1); 1823 luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1); 1824 codeextraarg(fs, extra); 1825 } 1826 fs->freereg = base + 1; /* free registers with list values */ 1827 } 1828 1829 1830 /* 1831 ** return the final target of a jump (skipping jumps to jumps) 1832 */ 1833 static int finaltarget (Instruction *code, int i) { 1834 int count; 1835 for (count = 0; count < 100; count++) { /* avoid infinite loops */ 1836 Instruction pc = code[i]; 1837 if (GET_OPCODE(pc) != OP_JMP) 1838 break; 1839 else 1840 i += GETARG_sJ(pc) + 1; 1841 } 1842 return i; 1843 } 1844 1845 1846 /* 1847 ** Do a final pass over the code of a function, doing small peephole 1848 ** optimizations and adjustments. 1849 */ 1850 void luaK_finish (FuncState *fs) { 1851 int i; 1852 Proto *p = fs->f; 1853 for (i = 0; i < fs->pc; i++) { 1854 Instruction *pc = &p->code[i]; 1855 lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc)); 1856 switch (GET_OPCODE(*pc)) { 1857 case OP_RETURN0: case OP_RETURN1: { 1858 if (!(fs->needclose || p->is_vararg)) 1859 break; /* no extra work */ 1860 /* else use OP_RETURN to do the extra work */ 1861 SET_OPCODE(*pc, OP_RETURN); 1862 } /* FALLTHROUGH */ 1863 case OP_RETURN: case OP_TAILCALL: { 1864 if (fs->needclose) 1865 SETARG_k(*pc, 1); /* signal that it needs to close */ 1866 if (p->is_vararg) 1867 SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */ 1868 break; 1869 } 1870 case OP_JMP: { 1871 int target = finaltarget(p->code, i); 1872 fixjump(fs, i, target); 1873 break; 1874 } 1875 default: break; 1876 } 1877 } 1878 } 1879