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