lcode.c 52 KB

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