lcode.c 41 KB

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