lcode.c 46 KB

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