lcode.c 45 KB

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