1 /*
2 ** $Id: lcode.c,v 2.101 2015/04/29 18:24:11 roberto Exp $
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 <math.h>
14 #include <stdlib.h>
15 
16 #include "lua.h"
17 
18 #include "lcode.h"
19 #include "ldebug.h"
20 #include "ldo.h"
21 #include "lgc.h"
22 #include "llex.h"
23 #include "lmem.h"
24 #include "lobject.h"
25 #include "lopcodes.h"
26 #include "lparser.h"
27 #include "lstring.h"
28 #include "ltable.h"
29 #include "lvm.h"
30 
31 
32 /* Maximum number of registers in a Lua function (must fit in 8 bits) */
33 #define MAXREGS		255
34 
35 
36 #define hasjumps(e)	((e)->t != (e)->f)
37 
38 
tonumeral(expdesc * e,TValue * v)39 static int tonumeral(expdesc *e, TValue *v) {
40   if (e->t != NO_JUMP || e->f != NO_JUMP)
41     return 0;  /* not a numeral */
42   switch (e->k) {
43     case VKINT:
44       if (v) setivalue(v, e->u.ival);
45       return 1;
46     case VKFLT:
47       if (v) setfltvalue(v, e->u.nval);
48       return 1;
49     default: return 0;
50   }
51 }
52 
53 
luaK_nil(FuncState * fs,int from,int n)54 void luaK_nil (FuncState *fs, int from, int n) {
55   Instruction *previous;
56   int l = from + n - 1;  /* last register to set nil */
57   if (fs->pc > fs->lasttarget) {  /* no jumps to current position? */
58     previous = &fs->f->code[fs->pc-1];
59     if (GET_OPCODE(*previous) == OP_LOADNIL) {
60       int pfrom = GETARG_A(*previous);
61       int pl = pfrom + GETARG_B(*previous);
62       if ((pfrom <= from && from <= pl + 1) ||
63           (from <= pfrom && pfrom <= l + 1)) {  /* can connect both? */
64         if (pfrom < from) from = pfrom;  /* from = min(from, pfrom) */
65         if (pl > l) l = pl;  /* l = max(l, pl) */
66         SETARG_A(*previous, from);
67         SETARG_B(*previous, l - from);
68         return;
69       }
70     }  /* else go through */
71   }
72   luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0);  /* else no optimization */
73 }
74 
75 
luaK_jump(FuncState * fs)76 int luaK_jump (FuncState *fs) {
77   int jpc = fs->jpc;  /* save list of jumps to here */
78   int j;
79   fs->jpc = NO_JUMP;
80   j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
81   luaK_concat(fs, &j, jpc);  /* keep them on hold */
82   return j;
83 }
84 
85 
luaK_ret(FuncState * fs,int first,int nret)86 void luaK_ret (FuncState *fs, int first, int nret) {
87   luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
88 }
89 
90 
condjump(FuncState * fs,OpCode op,int A,int B,int C)91 static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {
92   luaK_codeABC(fs, op, A, B, C);
93   return luaK_jump(fs);
94 }
95 
96 
fixjump(FuncState * fs,int pc,int dest)97 static void fixjump (FuncState *fs, int pc, int dest) {
98   Instruction *jmp = &fs->f->code[pc];
99   int offset = dest-(pc+1);
100   lua_assert(dest != NO_JUMP);
101   if (abs(offset) > MAXARG_sBx)
102     luaX_syntaxerror(fs->ls, "control structure too long");
103   SETARG_sBx(*jmp, offset);
104 }
105 
106 
107 /*
108 ** returns current 'pc' and marks it as a jump target (to avoid wrong
109 ** optimizations with consecutive instructions not in the same basic block).
110 */
luaK_getlabel(FuncState * fs)111 int luaK_getlabel (FuncState *fs) {
112   fs->lasttarget = fs->pc;
113   return fs->pc;
114 }
115 
116 
getjump(FuncState * fs,int pc)117 static int getjump (FuncState *fs, int pc) {
118   int offset = GETARG_sBx(fs->f->code[pc]);
119   if (offset == NO_JUMP)  /* point to itself represents end of list */
120     return NO_JUMP;  /* end of list */
121   else
122     return (pc+1)+offset;  /* turn offset into absolute position */
123 }
124 
125 
getjumpcontrol(FuncState * fs,int pc)126 static Instruction *getjumpcontrol (FuncState *fs, int pc) {
127   Instruction *pi = &fs->f->code[pc];
128   if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
129     return pi-1;
130   else
131     return pi;
132 }
133 
134 
135 /*
136 ** check whether list has any jump that do not produce a value
137 ** (or produce an inverted value)
138 */
need_value(FuncState * fs,int list)139 static int need_value (FuncState *fs, int list) {
140   for (; list != NO_JUMP; list = getjump(fs, list)) {
141     Instruction i = *getjumpcontrol(fs, list);
142     if (GET_OPCODE(i) != OP_TESTSET) return 1;
143   }
144   return 0;  /* not found */
145 }
146 
147 
patchtestreg(FuncState * fs,int node,int reg)148 static int patchtestreg (FuncState *fs, int node, int reg) {
149   Instruction *i = getjumpcontrol(fs, node);
150   if (GET_OPCODE(*i) != OP_TESTSET)
151     return 0;  /* cannot patch other instructions */
152   if (reg != NO_REG && reg != GETARG_B(*i))
153     SETARG_A(*i, reg);
154   else  /* no register to put value or register already has the value */
155     *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));
156 
157   return 1;
158 }
159 
160 
removevalues(FuncState * fs,int list)161 static void removevalues (FuncState *fs, int list) {
162   for (; list != NO_JUMP; list = getjump(fs, list))
163       patchtestreg(fs, list, NO_REG);
164 }
165 
166 
patchlistaux(FuncState * fs,int list,int vtarget,int reg,int dtarget)167 static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
168                           int dtarget) {
169   while (list != NO_JUMP) {
170     int next = getjump(fs, list);
171     if (patchtestreg(fs, list, reg))
172       fixjump(fs, list, vtarget);
173     else
174       fixjump(fs, list, dtarget);  /* jump to default target */
175     list = next;
176   }
177 }
178 
179 
dischargejpc(FuncState * fs)180 static void dischargejpc (FuncState *fs) {
181   patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);
182   fs->jpc = NO_JUMP;
183 }
184 
185 
luaK_patchlist(FuncState * fs,int list,int target)186 void luaK_patchlist (FuncState *fs, int list, int target) {
187   if (target == fs->pc)
188     luaK_patchtohere(fs, list);
189   else {
190     lua_assert(target < fs->pc);
191     patchlistaux(fs, list, target, NO_REG, target);
192   }
193 }
194 
195 
luaK_patchclose(FuncState * fs,int list,int level)196 void luaK_patchclose (FuncState *fs, int list, int level) {
197   level++;  /* argument is +1 to reserve 0 as non-op */
198   while (list != NO_JUMP) {
199     int next = getjump(fs, list);
200     lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP &&
201                 (GETARG_A(fs->f->code[list]) == 0 ||
202                  GETARG_A(fs->f->code[list]) >= level));
203     SETARG_A(fs->f->code[list], level);
204     list = next;
205   }
206 }
207 
208 
luaK_patchtohere(FuncState * fs,int list)209 void luaK_patchtohere (FuncState *fs, int list) {
210   luaK_getlabel(fs);
211   luaK_concat(fs, &fs->jpc, list);
212 }
213 
214 
luaK_concat(FuncState * fs,int * l1,int l2)215 void luaK_concat (FuncState *fs, int *l1, int l2) {
216   if (l2 == NO_JUMP) return;
217   else if (*l1 == NO_JUMP)
218     *l1 = l2;
219   else {
220     int list = *l1;
221     int next;
222     while ((next = getjump(fs, list)) != NO_JUMP)  /* find last element */
223       list = next;
224     fixjump(fs, list, l2);
225   }
226 }
227 
228 
luaK_code(FuncState * fs,Instruction i)229 static int luaK_code (FuncState *fs, Instruction i) {
230   Proto *f = fs->f;
231   dischargejpc(fs);  /* 'pc' will change */
232   /* put new instruction in code array */
233   luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
234                   MAX_INT, "opcodes");
235   f->code[fs->pc] = i;
236   /* save corresponding line information */
237   luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
238                   MAX_INT, "opcodes");
239   f->lineinfo[fs->pc] = fs->ls->lastline;
240   return fs->pc++;
241 }
242 
243 
luaK_codeABC(FuncState * fs,OpCode o,int a,int b,int c)244 int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
245   lua_assert(getOpMode(o) == iABC);
246   lua_assert(getBMode(o) != OpArgN || b == 0);
247   lua_assert(getCMode(o) != OpArgN || c == 0);
248   lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C);
249   return luaK_code(fs, CREATE_ABC(o, a, b, c));
250 }
251 
252 
luaK_codeABx(FuncState * fs,OpCode o,int a,unsigned int bc)253 int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
254   lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
255   lua_assert(getCMode(o) == OpArgN);
256   lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);
257   return luaK_code(fs, CREATE_ABx(o, a, bc));
258 }
259 
260 
codeextraarg(FuncState * fs,int a)261 static int codeextraarg (FuncState *fs, int a) {
262   lua_assert(a <= MAXARG_Ax);
263   return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));
264 }
265 
266 
luaK_codek(FuncState * fs,int reg,int k)267 int luaK_codek (FuncState *fs, int reg, int k) {
268   if (k <= MAXARG_Bx)
269     return luaK_codeABx(fs, OP_LOADK, reg, k);
270   else {
271     int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
272     codeextraarg(fs, k);
273     return p;
274   }
275 }
276 
277 
luaK_checkstack(FuncState * fs,int n)278 void luaK_checkstack (FuncState *fs, int n) {
279   int newstack = fs->freereg + n;
280   if (newstack > fs->f->maxstacksize) {
281     if (newstack >= MAXREGS)
282       luaX_syntaxerror(fs->ls,
283         "function or expression needs too many registers");
284     fs->f->maxstacksize = cast_byte(newstack);
285   }
286 }
287 
288 
luaK_reserveregs(FuncState * fs,int n)289 void luaK_reserveregs (FuncState *fs, int n) {
290   luaK_checkstack(fs, n);
291   fs->freereg += n;
292 }
293 
294 
freereg(FuncState * fs,int reg)295 static void freereg (FuncState *fs, int reg) {
296   if (!ISK(reg) && reg >= fs->nactvar) {
297     fs->freereg--;
298     lua_assert(reg == fs->freereg);
299   }
300 }
301 
302 
freeexp(FuncState * fs,expdesc * e)303 static void freeexp (FuncState *fs, expdesc *e) {
304   if (e->k == VNONRELOC)
305     freereg(fs, e->u.info);
306 }
307 
308 
309 /*
310 ** Use scanner's table to cache position of constants in constant list
311 ** and try to reuse constants
312 */
addk(FuncState * fs,TValue * key,TValue * v)313 static int addk (FuncState *fs, TValue *key, TValue *v) {
314   lua_State *L = fs->ls->L;
315   Proto *f = fs->f;
316   TValue *idx = luaH_set(L, fs->ls->h, key);  /* index scanner table */
317   int k, oldsize;
318   if (ttisinteger(idx)) {  /* is there an index there? */
319     k = cast_int(ivalue(idx));
320     /* correct value? (warning: must distinguish floats from integers!) */
321     if (k < fs->nk && ttype(&f->k[k]) == ttype(v) &&
322                       luaV_rawequalobj(&f->k[k], v))
323       return k;  /* reuse index */
324   }
325   /* constant not found; create a new entry */
326   oldsize = f->sizek;
327   k = fs->nk;
328   /* numerical value does not need GC barrier;
329      table has no metatable, so it does not need to invalidate cache */
330   setivalue(idx, k);
331   luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
332   while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
333   setobj(L, &f->k[k], v);
334   fs->nk++;
335   luaC_barrier(L, f, v);
336   return k;
337 }
338 
339 
luaK_stringK(FuncState * fs,TString * s)340 int luaK_stringK (FuncState *fs, TString *s) {
341   TValue o;
342   setsvalue(fs->ls->L, &o, s);
343   return addk(fs, &o, &o);
344 }
345 
346 
347 /*
348 ** Integers use userdata as keys to avoid collision with floats with same
349 ** value; conversion to 'void*' used only for hashing, no "precision"
350 ** problems
351 */
luaK_intK(FuncState * fs,lua_Integer n)352 int luaK_intK (FuncState *fs, lua_Integer n) {
353   TValue k, o;
354   setpvalue(&k, cast(void*, cast(size_t, n)));
355   setivalue(&o, n);
356   return addk(fs, &k, &o);
357 }
358 
359 
luaK_numberK(FuncState * fs,lua_Number r)360 static int luaK_numberK (FuncState *fs, lua_Number r) {
361   TValue o;
362   setfltvalue(&o, r);
363   return addk(fs, &o, &o);
364 }
365 
366 
boolK(FuncState * fs,int b)367 static int boolK (FuncState *fs, int b) {
368   TValue o;
369   setbvalue(&o, b);
370   return addk(fs, &o, &o);
371 }
372 
373 
nilK(FuncState * fs)374 static int nilK (FuncState *fs) {
375   TValue k, v;
376   setnilvalue(&v);
377   /* cannot use nil as key; instead use table itself to represent nil */
378   sethvalue(fs->ls->L, &k, fs->ls->h);
379   return addk(fs, &k, &v);
380 }
381 
382 
luaK_setreturns(FuncState * fs,expdesc * e,int nresults)383 void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
384   if (e->k == VCALL) {  /* expression is an open function call? */
385     SETARG_C(getcode(fs, e), nresults+1);
386   }
387   else if (e->k == VVARARG) {
388     SETARG_B(getcode(fs, e), nresults+1);
389     SETARG_A(getcode(fs, e), fs->freereg);
390     luaK_reserveregs(fs, 1);
391   }
392 }
393 
394 
luaK_setoneret(FuncState * fs,expdesc * e)395 void luaK_setoneret (FuncState *fs, expdesc *e) {
396   if (e->k == VCALL) {  /* expression is an open function call? */
397     e->k = VNONRELOC;
398     e->u.info = GETARG_A(getcode(fs, e));
399   }
400   else if (e->k == VVARARG) {
401     SETARG_B(getcode(fs, e), 2);
402     e->k = VRELOCABLE;  /* can relocate its simple result */
403   }
404 }
405 
406 
luaK_dischargevars(FuncState * fs,expdesc * e)407 void luaK_dischargevars (FuncState *fs, expdesc *e) {
408   switch (e->k) {
409     case VLOCAL: {
410       e->k = VNONRELOC;
411       break;
412     }
413     case VUPVAL: {
414       e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
415       e->k = VRELOCABLE;
416       break;
417     }
418     case VINDEXED: {
419       OpCode op = OP_GETTABUP;  /* assume 't' is in an upvalue */
420       freereg(fs, e->u.ind.idx);
421       if (e->u.ind.vt == VLOCAL) {  /* 't' is in a register? */
422         freereg(fs, e->u.ind.t);
423         op = OP_GETTABLE;
424       }
425       e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx);
426       e->k = VRELOCABLE;
427       break;
428     }
429     case VVARARG:
430     case VCALL: {
431       luaK_setoneret(fs, e);
432       break;
433     }
434     default: break;  /* there is one value available (somewhere) */
435   }
436 }
437 
438 
code_label(FuncState * fs,int A,int b,int jump)439 static int code_label (FuncState *fs, int A, int b, int jump) {
440   luaK_getlabel(fs);  /* those instructions may be jump targets */
441   return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
442 }
443 
444 
discharge2reg(FuncState * fs,expdesc * e,int reg)445 static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
446   luaK_dischargevars(fs, e);
447   switch (e->k) {
448     case VNIL: {
449       luaK_nil(fs, reg, 1);
450       break;
451     }
452     case VFALSE: case VTRUE: {
453       luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
454       break;
455     }
456     case VK: {
457       luaK_codek(fs, reg, e->u.info);
458       break;
459     }
460     case VKFLT: {
461       luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));
462       break;
463     }
464     case VKINT: {
465       luaK_codek(fs, reg, luaK_intK(fs, e->u.ival));
466       break;
467     }
468     case VRELOCABLE: {
469       Instruction *pc = &getcode(fs, e);
470       SETARG_A(*pc, reg);
471       break;
472     }
473     case VNONRELOC: {
474       if (reg != e->u.info)
475         luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
476       break;
477     }
478     default: {
479       lua_assert(e->k == VVOID || e->k == VJMP);
480       return;  /* nothing to do... */
481     }
482   }
483   e->u.info = reg;
484   e->k = VNONRELOC;
485 }
486 
487 
discharge2anyreg(FuncState * fs,expdesc * e)488 static void discharge2anyreg (FuncState *fs, expdesc *e) {
489   if (e->k != VNONRELOC) {
490     luaK_reserveregs(fs, 1);
491     discharge2reg(fs, e, fs->freereg-1);
492   }
493 }
494 
495 
exp2reg(FuncState * fs,expdesc * e,int reg)496 static void exp2reg (FuncState *fs, expdesc *e, int reg) {
497   discharge2reg(fs, e, reg);
498   if (e->k == VJMP)
499     luaK_concat(fs, &e->t, e->u.info);  /* put this jump in 't' list */
500   if (hasjumps(e)) {
501     int final;  /* position after whole expression */
502     int p_f = NO_JUMP;  /* position of an eventual LOAD false */
503     int p_t = NO_JUMP;  /* position of an eventual LOAD true */
504     if (need_value(fs, e->t) || need_value(fs, e->f)) {
505       int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
506       p_f = code_label(fs, reg, 0, 1);
507       p_t = code_label(fs, reg, 1, 0);
508       luaK_patchtohere(fs, fj);
509     }
510     final = luaK_getlabel(fs);
511     patchlistaux(fs, e->f, final, reg, p_f);
512     patchlistaux(fs, e->t, final, reg, p_t);
513   }
514   e->f = e->t = NO_JUMP;
515   e->u.info = reg;
516   e->k = VNONRELOC;
517 }
518 
519 
luaK_exp2nextreg(FuncState * fs,expdesc * e)520 void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
521   luaK_dischargevars(fs, e);
522   freeexp(fs, e);
523   luaK_reserveregs(fs, 1);
524   exp2reg(fs, e, fs->freereg - 1);
525 }
526 
527 
luaK_exp2anyreg(FuncState * fs,expdesc * e)528 int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
529   luaK_dischargevars(fs, e);
530   if (e->k == VNONRELOC) {
531     if (!hasjumps(e)) return e->u.info;  /* exp is already in a register */
532     if (e->u.info >= fs->nactvar) {  /* reg. is not a local? */
533       exp2reg(fs, e, e->u.info);  /* put value on it */
534       return e->u.info;
535     }
536   }
537   luaK_exp2nextreg(fs, e);  /* default */
538   return e->u.info;
539 }
540 
541 
luaK_exp2anyregup(FuncState * fs,expdesc * e)542 void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
543   if (e->k != VUPVAL || hasjumps(e))
544     luaK_exp2anyreg(fs, e);
545 }
546 
547 
luaK_exp2val(FuncState * fs,expdesc * e)548 void luaK_exp2val (FuncState *fs, expdesc *e) {
549   if (hasjumps(e))
550     luaK_exp2anyreg(fs, e);
551   else
552     luaK_dischargevars(fs, e);
553 }
554 
555 
luaK_exp2RK(FuncState * fs,expdesc * e)556 int luaK_exp2RK (FuncState *fs, expdesc *e) {
557   luaK_exp2val(fs, e);
558   switch (e->k) {
559     case VTRUE:
560     case VFALSE:
561     case VNIL: {
562       if (fs->nk <= MAXINDEXRK) {  /* constant fits in RK operand? */
563         e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE));
564         e->k = VK;
565         return RKASK(e->u.info);
566       }
567       else break;
568     }
569     case VKINT: {
570       e->u.info = luaK_intK(fs, e->u.ival);
571       e->k = VK;
572       goto vk;
573     }
574     case VKFLT: {
575       e->u.info = luaK_numberK(fs, e->u.nval);
576       e->k = VK;
577     }
578     /* FALLTHROUGH */
579     case VK: {
580      vk:
581       if (e->u.info <= MAXINDEXRK)  /* constant fits in 'argC'? */
582         return RKASK(e->u.info);
583       else break;
584     }
585     default: break;
586   }
587   /* not a constant in the right range: put it in a register */
588   return luaK_exp2anyreg(fs, e);
589 }
590 
591 
luaK_storevar(FuncState * fs,expdesc * var,expdesc * ex)592 void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
593   switch (var->k) {
594     case VLOCAL: {
595       freeexp(fs, ex);
596       exp2reg(fs, ex, var->u.info);
597       return;
598     }
599     case VUPVAL: {
600       int e = luaK_exp2anyreg(fs, ex);
601       luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
602       break;
603     }
604     case VINDEXED: {
605       OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP;
606       int e = luaK_exp2RK(fs, ex);
607       luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e);
608       break;
609     }
610     default: {
611       lua_assert(0);  /* invalid var kind to store */
612       break;
613     }
614   }
615   freeexp(fs, ex);
616 }
617 
618 
luaK_self(FuncState * fs,expdesc * e,expdesc * key)619 void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
620   int ereg;
621   luaK_exp2anyreg(fs, e);
622   ereg = e->u.info;  /* register where 'e' was placed */
623   freeexp(fs, e);
624   e->u.info = fs->freereg;  /* base register for op_self */
625   e->k = VNONRELOC;
626   luaK_reserveregs(fs, 2);  /* function and 'self' produced by op_self */
627   luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));
628   freeexp(fs, key);
629 }
630 
631 
invertjump(FuncState * fs,expdesc * e)632 static void invertjump (FuncState *fs, expdesc *e) {
633   Instruction *pc = getjumpcontrol(fs, e->u.info);
634   lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
635                                            GET_OPCODE(*pc) != OP_TEST);
636   SETARG_A(*pc, !(GETARG_A(*pc)));
637 }
638 
639 
jumponcond(FuncState * fs,expdesc * e,int cond)640 static int jumponcond (FuncState *fs, expdesc *e, int cond) {
641   if (e->k == VRELOCABLE) {
642     Instruction ie = getcode(fs, e);
643     if (GET_OPCODE(ie) == OP_NOT) {
644       fs->pc--;  /* remove previous OP_NOT */
645       return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
646     }
647     /* else go through */
648   }
649   discharge2anyreg(fs, e);
650   freeexp(fs, e);
651   return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond);
652 }
653 
654 
luaK_goiftrue(FuncState * fs,expdesc * e)655 void luaK_goiftrue (FuncState *fs, expdesc *e) {
656   int pc;  /* pc of last jump */
657   luaK_dischargevars(fs, e);
658   switch (e->k) {
659     case VJMP: {
660       invertjump(fs, e);
661       pc = e->u.info;
662       break;
663     }
664     case VK: case VKFLT: case VKINT: case VTRUE: {
665       pc = NO_JUMP;  /* always true; do nothing */
666       break;
667     }
668     default: {
669       pc = jumponcond(fs, e, 0);
670       break;
671     }
672   }
673   luaK_concat(fs, &e->f, pc);  /* insert last jump in 'f' list */
674   luaK_patchtohere(fs, e->t);
675   e->t = NO_JUMP;
676 }
677 
678 
luaK_goiffalse(FuncState * fs,expdesc * e)679 void luaK_goiffalse (FuncState *fs, expdesc *e) {
680   int pc;  /* pc of last jump */
681   luaK_dischargevars(fs, e);
682   switch (e->k) {
683     case VJMP: {
684       pc = e->u.info;
685       break;
686     }
687     case VNIL: case VFALSE: {
688       pc = NO_JUMP;  /* always false; do nothing */
689       break;
690     }
691     default: {
692       pc = jumponcond(fs, e, 1);
693       break;
694     }
695   }
696   luaK_concat(fs, &e->t, pc);  /* insert last jump in 't' list */
697   luaK_patchtohere(fs, e->f);
698   e->f = NO_JUMP;
699 }
700 
701 
codenot(FuncState * fs,expdesc * e)702 static void codenot (FuncState *fs, expdesc *e) {
703   luaK_dischargevars(fs, e);
704   switch (e->k) {
705     case VNIL: case VFALSE: {
706       e->k = VTRUE;
707       break;
708     }
709     case VK: case VKFLT: case VKINT: case VTRUE: {
710       e->k = VFALSE;
711       break;
712     }
713     case VJMP: {
714       invertjump(fs, e);
715       break;
716     }
717     case VRELOCABLE:
718     case VNONRELOC: {
719       discharge2anyreg(fs, e);
720       freeexp(fs, e);
721       e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
722       e->k = VRELOCABLE;
723       break;
724     }
725     default: {
726       lua_assert(0);  /* cannot happen */
727       break;
728     }
729   }
730   /* interchange true and false lists */
731   { int temp = e->f; e->f = e->t; e->t = temp; }
732   removevalues(fs, e->f);
733   removevalues(fs, e->t);
734 }
735 
736 
luaK_indexed(FuncState * fs,expdesc * t,expdesc * k)737 void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
738   lua_assert(!hasjumps(t));
739   t->u.ind.t = t->u.info;
740   t->u.ind.idx = luaK_exp2RK(fs, k);
741   t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL
742                                  : check_exp(vkisinreg(t->k), VLOCAL);
743   t->k = VINDEXED;
744 }
745 
746 
747 /*
748 ** return false if folding can raise an error
749 */
validop(int op,TValue * v1,TValue * v2)750 static int validop (int op, TValue *v1, TValue *v2) {
751   switch (op) {
752     case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
753     case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: {  /* conversion errors */
754       lua_Integer i;
755       return (tointeger(v1, &i) && tointeger(v2, &i));
756     }
757     case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD:  /* division by 0 */
758       return (nvalue(v2) != 0);
759     default: return 1;  /* everything else is valid */
760   }
761 }
762 
763 
764 /*
765 ** Try to "constant-fold" an operation; return 1 iff successful
766 */
constfolding(FuncState * fs,int op,expdesc * e1,expdesc * e2)767 static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) {
768   TValue v1, v2, res;
769   if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
770     return 0;  /* non-numeric operands or not safe to fold */
771   luaO_arith(fs->ls->L, op, &v1, &v2, &res);  /* does operation */
772   if (ttisinteger(&res)) {
773     e1->k = VKINT;
774     e1->u.ival = ivalue(&res);
775   }
776   else {  /* folds neither NaN nor 0.0 (to avoid collapsing with -0.0) */
777     lua_Number n = fltvalue(&res);
778     if (luai_numisnan(n) || n == 0)
779       return 0;
780     e1->k = VKFLT;
781     e1->u.nval = n;
782   }
783   return 1;
784 }
785 
786 
787 /*
788 ** Code for binary and unary expressions that "produce values"
789 ** (arithmetic operations, bitwise operations, concat, length). First
790 ** try to do constant folding (only for numeric [arithmetic and
791 ** bitwise] operations, which is what 'lua_arith' accepts).
792 ** Expression to produce final result will be encoded in 'e1'.
793 */
codeexpval(FuncState * fs,OpCode op,expdesc * e1,expdesc * e2,int line)794 static void codeexpval (FuncState *fs, OpCode op,
795                         expdesc *e1, expdesc *e2, int line) {
796   lua_assert(op >= OP_ADD);
797   if (op <= OP_BNOT && constfolding(fs, (op - OP_ADD) + LUA_OPADD, e1, e2))
798     return;  /* result has been folded */
799   else {
800     int o1, o2;
801     /* move operands to registers (if needed) */
802     if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) {  /* unary op? */
803       o2 = 0;  /* no second expression */
804       o1 = luaK_exp2anyreg(fs, e1);  /* cannot operate on constants */
805     }
806     else {  /* regular case (binary operators) */
807       o2 = luaK_exp2RK(fs, e2);  /* both operands are "RK" */
808       o1 = luaK_exp2RK(fs, e1);
809     }
810     if (o1 > o2) {  /* free registers in proper order */
811       freeexp(fs, e1);
812       freeexp(fs, e2);
813     }
814     else {
815       freeexp(fs, e2);
816       freeexp(fs, e1);
817     }
818     e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);  /* generate opcode */
819     e1->k = VRELOCABLE;  /* all those operations are relocable */
820     luaK_fixline(fs, line);
821   }
822 }
823 
824 
codecomp(FuncState * fs,OpCode op,int cond,expdesc * e1,expdesc * e2)825 static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
826                                                           expdesc *e2) {
827   int o1 = luaK_exp2RK(fs, e1);
828   int o2 = luaK_exp2RK(fs, e2);
829   freeexp(fs, e2);
830   freeexp(fs, e1);
831   if (cond == 0 && op != OP_EQ) {
832     int temp;  /* exchange args to replace by '<' or '<=' */
833     temp = o1; o1 = o2; o2 = temp;  /* o1 <==> o2 */
834     cond = 1;
835   }
836   e1->u.info = condjump(fs, op, cond, o1, o2);
837   e1->k = VJMP;
838 }
839 
840 
luaK_prefix(FuncState * fs,UnOpr op,expdesc * e,int line)841 void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
842   expdesc e2;
843   e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
844   switch (op) {
845     case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
846       codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
847       break;
848     }
849     case OPR_NOT: codenot(fs, e); break;
850     default: lua_assert(0);
851   }
852 }
853 
854 
luaK_infix(FuncState * fs,BinOpr op,expdesc * v)855 void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
856   switch (op) {
857     case OPR_AND: {
858       luaK_goiftrue(fs, v);
859       break;
860     }
861     case OPR_OR: {
862       luaK_goiffalse(fs, v);
863       break;
864     }
865     case OPR_CONCAT: {
866       luaK_exp2nextreg(fs, v);  /* operand must be on the 'stack' */
867       break;
868     }
869     case OPR_ADD: case OPR_SUB:
870     case OPR_MUL: case OPR_DIV: case OPR_IDIV:
871     case OPR_MOD: case OPR_POW:
872     case OPR_BAND: case OPR_BOR: case OPR_BXOR:
873     case OPR_SHL: case OPR_SHR: {
874       if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v);
875       break;
876     }
877     default: {
878       luaK_exp2RK(fs, v);
879       break;
880     }
881   }
882 }
883 
884 
luaK_posfix(FuncState * fs,BinOpr op,expdesc * e1,expdesc * e2,int line)885 void luaK_posfix (FuncState *fs, BinOpr op,
886                   expdesc *e1, expdesc *e2, int line) {
887   switch (op) {
888     case OPR_AND: {
889       lua_assert(e1->t == NO_JUMP);  /* list must be closed */
890       luaK_dischargevars(fs, e2);
891       luaK_concat(fs, &e2->f, e1->f);
892       *e1 = *e2;
893       break;
894     }
895     case OPR_OR: {
896       lua_assert(e1->f == NO_JUMP);  /* list must be closed */
897       luaK_dischargevars(fs, e2);
898       luaK_concat(fs, &e2->t, e1->t);
899       *e1 = *e2;
900       break;
901     }
902     case OPR_CONCAT: {
903       luaK_exp2val(fs, e2);
904       if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
905         lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1);
906         freeexp(fs, e1);
907         SETARG_B(getcode(fs, e2), e1->u.info);
908         e1->k = VRELOCABLE; e1->u.info = e2->u.info;
909       }
910       else {
911         luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */
912         codeexpval(fs, OP_CONCAT, e1, e2, line);
913       }
914       break;
915     }
916     case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
917     case OPR_IDIV: case OPR_MOD: case OPR_POW:
918     case OPR_BAND: case OPR_BOR: case OPR_BXOR:
919     case OPR_SHL: case OPR_SHR: {
920       codeexpval(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
921       break;
922     }
923     case OPR_EQ: case OPR_LT: case OPR_LE: {
924       codecomp(fs, cast(OpCode, (op - OPR_EQ) + OP_EQ), 1, e1, e2);
925       break;
926     }
927     case OPR_NE: case OPR_GT: case OPR_GE: {
928       codecomp(fs, cast(OpCode, (op - OPR_NE) + OP_EQ), 0, e1, e2);
929       break;
930     }
931     default: lua_assert(0);
932   }
933 }
934 
935 
luaK_fixline(FuncState * fs,int line)936 void luaK_fixline (FuncState *fs, int line) {
937   fs->f->lineinfo[fs->pc - 1] = line;
938 }
939 
940 
luaK_setlist(FuncState * fs,int base,int nelems,int tostore)941 void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
942   int c =  (nelems - 1)/LFIELDS_PER_FLUSH + 1;
943   int b = (tostore == LUA_MULTRET) ? 0 : tostore;
944   lua_assert(tostore != 0);
945   if (c <= MAXARG_C)
946     luaK_codeABC(fs, OP_SETLIST, base, b, c);
947   else if (c <= MAXARG_Ax) {
948     luaK_codeABC(fs, OP_SETLIST, base, b, 0);
949     codeextraarg(fs, c);
950   }
951   else
952     luaX_syntaxerror(fs->ls, "constructor too long");
953   fs->freereg = base + 1;  /* free registers with list values */
954 }
955 
956