lcode.c 50 KB

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