lcode.c 46 KB

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