lcode.c 55 KB

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