lcode.c 46 KB

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