lcode.c 45 KB

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