/Python/peephole.c

http://unladen-swallow.googlecode.com/ · C · 680 lines · 498 code · 50 blank · 132 comment · 131 complexity · 1f61433d50c0be2cd8c591c203abf907 MD5 · raw file

  1. /* Peephole optimizations for bytecode compiler. */
  2. #include "Python.h"
  3. #include "Python-ast.h"
  4. #include "node.h"
  5. #include "pyarena.h"
  6. #include "ast.h"
  7. #include "code.h"
  8. #include "compile.h"
  9. #include "symtable.h"
  10. #include "opcode.h"
  11. #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
  12. #define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
  13. #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
  14. || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
  15. #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \
  16. || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
  17. || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
  18. #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP)
  19. #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
  20. #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
  21. #define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
  22. #define ISBASICBLOCK(blocks, start, bytes) \
  23. (blocks[start]==blocks[start+bytes-1])
  24. /* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
  25. with LOAD_CONST (c1, c2, ... cn).
  26. The consts table must still be in list form so that the
  27. new constant (c1, c2, ... cn) can be appended.
  28. Called with codestr pointing to the first LOAD_CONST.
  29. Bails out with no change if one or more of the LOAD_CONSTs is missing.
  30. Also works for BUILD_LIST when followed by an "in" or "not in" test.
  31. */
  32. static int
  33. tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts)
  34. {
  35. PyObject *newconst, *constant;
  36. Py_ssize_t i, arg, len_consts;
  37. /* Pre-conditions */
  38. assert(PyList_CheckExact(consts));
  39. assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
  40. assert(GETARG(codestr, (n*3)) == n);
  41. for (i=0 ; i<n ; i++)
  42. assert(codestr[i*3] == LOAD_CONST);
  43. /* Buildup new tuple of constants */
  44. newconst = PyTuple_New(n);
  45. if (newconst == NULL)
  46. return 0;
  47. len_consts = PyList_GET_SIZE(consts);
  48. for (i=0 ; i<n ; i++) {
  49. arg = GETARG(codestr, (i*3));
  50. assert(arg < len_consts);
  51. constant = PyList_GET_ITEM(consts, arg);
  52. Py_INCREF(constant);
  53. PyTuple_SET_ITEM(newconst, i, constant);
  54. }
  55. /* Append folded constant onto consts */
  56. if (PyList_Append(consts, newconst)) {
  57. Py_DECREF(newconst);
  58. return 0;
  59. }
  60. Py_DECREF(newconst);
  61. /* Write NOPs over old LOAD_CONSTS and
  62. add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
  63. memset(codestr, NOP, n*3);
  64. codestr[n*3] = LOAD_CONST;
  65. SETARG(codestr, (n*3), len_consts);
  66. return 1;
  67. }
  68. /* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
  69. with LOAD_CONST binop(c1,c2)
  70. The consts table must still be in list form so that the
  71. new constant can be appended.
  72. Called with codestr pointing to the first LOAD_CONST.
  73. Abandons the transformation if the folding fails (i.e. 1+'a').
  74. If the new constant is a sequence, only folds when the size
  75. is below a threshold value. That keeps pyc files from
  76. becoming large in the presence of code like: (None,)*1000.
  77. */
  78. static int
  79. fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
  80. {
  81. PyObject *newconst, *v, *w;
  82. Py_ssize_t len_consts, size;
  83. int opcode;
  84. /* Pre-conditions */
  85. assert(PyList_CheckExact(consts));
  86. assert(codestr[0] == LOAD_CONST);
  87. assert(codestr[3] == LOAD_CONST);
  88. /* Create new constant */
  89. v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
  90. w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
  91. opcode = codestr[6];
  92. switch (opcode) {
  93. case BINARY_POWER:
  94. newconst = PyNumber_Power(v, w, Py_None);
  95. break;
  96. case BINARY_MULTIPLY:
  97. newconst = PyNumber_Multiply(v, w);
  98. break;
  99. case BINARY_DIVIDE:
  100. /* Cannot fold this operation statically since
  101. the result can depend on the run-time presence
  102. of the -Qnew flag */
  103. return 0;
  104. case BINARY_TRUE_DIVIDE:
  105. newconst = PyNumber_TrueDivide(v, w);
  106. break;
  107. case BINARY_FLOOR_DIVIDE:
  108. newconst = PyNumber_FloorDivide(v, w);
  109. break;
  110. case BINARY_MODULO:
  111. newconst = PyNumber_Remainder(v, w);
  112. break;
  113. case BINARY_ADD:
  114. newconst = PyNumber_Add(v, w);
  115. break;
  116. case BINARY_SUBTRACT:
  117. newconst = PyNumber_Subtract(v, w);
  118. break;
  119. case BINARY_SUBSCR:
  120. newconst = PyObject_GetItem(v, w);
  121. break;
  122. case BINARY_LSHIFT:
  123. newconst = PyNumber_Lshift(v, w);
  124. break;
  125. case BINARY_RSHIFT:
  126. newconst = PyNumber_Rshift(v, w);
  127. break;
  128. case BINARY_AND:
  129. newconst = PyNumber_And(v, w);
  130. break;
  131. case BINARY_XOR:
  132. newconst = PyNumber_Xor(v, w);
  133. break;
  134. case BINARY_OR:
  135. newconst = PyNumber_Or(v, w);
  136. break;
  137. default:
  138. /* Called with an unknown opcode */
  139. PyErr_Format(PyExc_SystemError,
  140. "unexpected binary operation %d on a constant",
  141. opcode);
  142. return 0;
  143. }
  144. if (newconst == NULL) {
  145. PyErr_Clear();
  146. return 0;
  147. }
  148. size = PyObject_Size(newconst);
  149. if (size == -1)
  150. PyErr_Clear();
  151. else if (size > 20) {
  152. Py_DECREF(newconst);
  153. return 0;
  154. }
  155. /* Append folded constant into consts table */
  156. len_consts = PyList_GET_SIZE(consts);
  157. if (PyList_Append(consts, newconst)) {
  158. Py_DECREF(newconst);
  159. return 0;
  160. }
  161. Py_DECREF(newconst);
  162. /* Write NOP NOP NOP NOP LOAD_CONST newconst */
  163. memset(codestr, NOP, 4);
  164. codestr[4] = LOAD_CONST;
  165. SETARG(codestr, 4, len_consts);
  166. return 1;
  167. }
  168. static int
  169. fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
  170. {
  171. PyObject *newconst=NULL, *v;
  172. Py_ssize_t len_consts;
  173. int opcode;
  174. /* Pre-conditions */
  175. assert(PyList_CheckExact(consts));
  176. assert(codestr[0] == LOAD_CONST);
  177. /* Create new constant */
  178. v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
  179. opcode = codestr[3];
  180. switch (opcode) {
  181. case UNARY_NEGATIVE:
  182. /* Preserve the sign of -0.0 */
  183. if (PyObject_IsTrue(v) == 1)
  184. newconst = PyNumber_Negative(v);
  185. break;
  186. case UNARY_CONVERT:
  187. newconst = PyObject_Repr(v);
  188. break;
  189. case UNARY_INVERT:
  190. newconst = PyNumber_Invert(v);
  191. break;
  192. default:
  193. /* Called with an unknown opcode */
  194. PyErr_Format(PyExc_SystemError,
  195. "unexpected unary operation %d on a constant",
  196. opcode);
  197. return 0;
  198. }
  199. if (newconst == NULL) {
  200. PyErr_Clear();
  201. return 0;
  202. }
  203. /* Append folded constant into consts table */
  204. len_consts = PyList_GET_SIZE(consts);
  205. if (PyList_Append(consts, newconst)) {
  206. Py_DECREF(newconst);
  207. return 0;
  208. }
  209. Py_DECREF(newconst);
  210. /* Write NOP LOAD_CONST newconst */
  211. codestr[0] = NOP;
  212. codestr[1] = LOAD_CONST;
  213. SETARG(codestr, 1, len_consts);
  214. return 1;
  215. }
  216. /* Marks instructions that can be the targets of jumps so we keep them
  217. distinct through the peephole optimizer. */
  218. static unsigned int *
  219. markblocks(unsigned char *code, Py_ssize_t len, PyObject *lineno_obj)
  220. {
  221. unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
  222. unsigned char *lineno;
  223. Py_ssize_t tabsiz;
  224. Py_ssize_t code_index = 0;
  225. Py_ssize_t k;
  226. int i,j, opcode, blockcnt = 0;
  227. if (blocks == NULL) {
  228. PyErr_NoMemory();
  229. return NULL;
  230. }
  231. memset(blocks, 0, len*sizeof(int));
  232. /* Mark labels in the first pass */
  233. for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
  234. opcode = code[i];
  235. switch (opcode) {
  236. case FOR_ITER:
  237. case JUMP_FORWARD:
  238. case JUMP_IF_FALSE_OR_POP:
  239. case JUMP_IF_TRUE_OR_POP:
  240. case POP_JUMP_IF_FALSE:
  241. case POP_JUMP_IF_TRUE:
  242. case JUMP_ABSOLUTE:
  243. case CONTINUE_LOOP:
  244. case SETUP_LOOP:
  245. case SETUP_EXCEPT:
  246. case SETUP_FINALLY:
  247. j = GETJUMPTGT(code, i);
  248. blocks[j] = 1;
  249. break;
  250. }
  251. }
  252. /* Make sure none of the optimizations occur across line number
  253. boundaries, by making each logical line seem like its own block.
  254. This both makes code easier to debug and allows users to sensibly
  255. set the line number. */
  256. lineno = (unsigned char *)PyString_AS_STRING(lineno_obj);
  257. tabsiz = PyString_GET_SIZE(lineno_obj);
  258. for (k=0; k < tabsiz; k += 2) {
  259. code_index += lineno[k];
  260. /* This actually makes sense: a trace function
  261. can jump to the start of any line, so each
  262. line is a basic block. */
  263. blocks[code_index] = 1;
  264. }
  265. /* Build block numbers in the second pass */
  266. for (i=0 ; i<len ; i++) {
  267. blockcnt += blocks[i]; /* increment blockcnt over labels */
  268. blocks[i] = blockcnt;
  269. }
  270. return blocks;
  271. }
  272. /* Perform basic peephole optimizations to components of a code object.
  273. The consts object should still be in list form to allow new constants
  274. to be appended.
  275. To keep the optimizer simple, it bails out (does nothing) for code
  276. containing extended arguments or that has a length over 32,700. That
  277. allows us to avoid overflow and sign issues. Likewise, it bails when
  278. the lineno table has complex encoding for gaps >= 255.
  279. Optimizations are restricted to simple transformations occuring within a
  280. single basic block. All transformations keep the code size the same or
  281. smaller. For those that reduce size, the gaps are initially filled with
  282. NOPs. Later those NOPs are removed and the jump addresses retargeted in
  283. a single pass. Line numbering is adjusted accordingly. */
  284. PyObject *
  285. PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
  286. PyObject *lineno_obj)
  287. {
  288. Py_ssize_t i, j, codelen;
  289. int nops, h, adj;
  290. int tgt, tgttgt, opcode;
  291. unsigned char *codestr = NULL;
  292. unsigned char *lineno;
  293. int *addrmap = NULL;
  294. int new_line, cum_orig_line, last_line, tabsiz;
  295. int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
  296. unsigned int *blocks = NULL;
  297. char *name;
  298. /* Bail out if an exception is set */
  299. if (PyErr_Occurred())
  300. goto exitUnchanged;
  301. /* Bypass optimization when the lineno table is too complex */
  302. assert(PyString_Check(lineno_obj));
  303. lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
  304. tabsiz = PyString_GET_SIZE(lineno_obj);
  305. if (memchr(lineno, 255, tabsiz) != NULL)
  306. goto exitUnchanged;
  307. /* Avoid situations where jump retargeting could overflow */
  308. assert(PyString_Check(code));
  309. codelen = PyString_GET_SIZE(code);
  310. if (codelen > 32700)
  311. goto exitUnchanged;
  312. /* Make a modifiable copy of the code string */
  313. codestr = (unsigned char *)PyMem_Malloc(codelen);
  314. if (codestr == NULL)
  315. goto exitUnchanged;
  316. codestr = (unsigned char *)memcpy(codestr,
  317. PyString_AS_STRING(code), codelen);
  318. /* Verify that RETURN_VALUE terminates the codestring. This allows
  319. the various transformation patterns to look ahead several
  320. instructions without additional checks to make sure they are not
  321. looking beyond the end of the code string.
  322. */
  323. if (codestr[codelen-1] != RETURN_VALUE)
  324. goto exitUnchanged;
  325. /* Mapping to new jump targets after NOPs are removed */
  326. addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
  327. if (addrmap == NULL)
  328. goto exitUnchanged;
  329. blocks = markblocks(codestr, codelen, lineno_obj);
  330. if (blocks == NULL)
  331. goto exitUnchanged;
  332. assert(PyList_Check(consts));
  333. for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
  334. reoptimize_current:
  335. opcode = codestr[i];
  336. lastlc = cumlc;
  337. cumlc = 0;
  338. switch (opcode) {
  339. /* Replace UNARY_NOT POP_JUMP_IF_FALSE
  340. with POP_JUMP_IF_TRUE */
  341. case UNARY_NOT:
  342. if (codestr[i+1] != POP_JUMP_IF_FALSE
  343. || !ISBASICBLOCK(blocks,i,4))
  344. continue;
  345. j = GETARG(codestr, i+1);
  346. codestr[i] = POP_JUMP_IF_TRUE;
  347. SETARG(codestr, i, j);
  348. codestr[i+3] = NOP;
  349. goto reoptimize_current;
  350. /* not a is b --> a is not b
  351. not a in b --> a not in b
  352. not a is not b --> a is b
  353. not a not in b --> a in b
  354. */
  355. case COMPARE_OP:
  356. j = GETARG(codestr, i);
  357. if (j < 6 || j > 9 ||
  358. codestr[i+3] != UNARY_NOT ||
  359. !ISBASICBLOCK(blocks,i,4))
  360. continue;
  361. SETARG(codestr, i, (j^1));
  362. codestr[i+3] = NOP;
  363. break;
  364. /* Replace LOAD_GLOBAL/LOAD_NAME None
  365. with LOAD_CONST None */
  366. case LOAD_NAME:
  367. case LOAD_GLOBAL:
  368. j = GETARG(codestr, i);
  369. name = PyString_AsString(PyTuple_GET_ITEM(names, j));
  370. if (name == NULL || strcmp(name, "None") != 0)
  371. continue;
  372. for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
  373. if (PyList_GET_ITEM(consts, j) == Py_None)
  374. break;
  375. }
  376. if (j == PyList_GET_SIZE(consts)) {
  377. if (PyList_Append(consts, Py_None) == -1)
  378. goto exitUnchanged;
  379. }
  380. assert(PyList_GET_ITEM(consts, j) == Py_None);
  381. codestr[i] = LOAD_CONST;
  382. SETARG(codestr, i, j);
  383. cumlc = lastlc + 1;
  384. break;
  385. /* Skip over LOAD_CONST trueconst
  386. POP_JUMP_IF_FALSE xx. This improves
  387. "while 1" performance. */
  388. case LOAD_CONST:
  389. cumlc = lastlc + 1;
  390. j = GETARG(codestr, i);
  391. if (codestr[i+3] != POP_JUMP_IF_FALSE ||
  392. !ISBASICBLOCK(blocks,i,6) ||
  393. !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
  394. continue;
  395. memset(codestr+i, NOP, 6);
  396. cumlc = 0;
  397. break;
  398. /* Try to fold tuples of constants (includes a case for lists
  399. which are only used for "in" and "not in" tests).
  400. Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
  401. Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
  402. Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
  403. case BUILD_TUPLE:
  404. case BUILD_LIST:
  405. j = GETARG(codestr, i);
  406. h = i - 3 * j;
  407. if (h >= 0 &&
  408. j <= lastlc &&
  409. ((opcode == BUILD_TUPLE &&
  410. ISBASICBLOCK(blocks, h, 3*(j+1))) ||
  411. (opcode == BUILD_LIST &&
  412. codestr[i+3]==COMPARE_OP &&
  413. ISBASICBLOCK(blocks, h, 3*(j+2)) &&
  414. (GETARG(codestr,i+3)==6 ||
  415. GETARG(codestr,i+3)==7))) &&
  416. tuple_of_constants(&codestr[h], j, consts)) {
  417. assert(codestr[i] == LOAD_CONST);
  418. cumlc = 1;
  419. break;
  420. }
  421. if (codestr[i+3] != UNPACK_SEQUENCE ||
  422. !ISBASICBLOCK(blocks,i,6) ||
  423. j != GETARG(codestr, i+3))
  424. continue;
  425. if (j == 1) {
  426. memset(codestr+i, NOP, 6);
  427. } else if (j == 2) {
  428. codestr[i] = ROT_TWO;
  429. memset(codestr+i+1, NOP, 5);
  430. } else if (j == 3) {
  431. codestr[i] = ROT_THREE;
  432. codestr[i+1] = ROT_TWO;
  433. memset(codestr+i+2, NOP, 4);
  434. }
  435. break;
  436. /* Fold binary ops on constants.
  437. LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
  438. case BINARY_POWER:
  439. case BINARY_MULTIPLY:
  440. case BINARY_TRUE_DIVIDE:
  441. case BINARY_FLOOR_DIVIDE:
  442. case BINARY_MODULO:
  443. case BINARY_ADD:
  444. case BINARY_SUBTRACT:
  445. case BINARY_SUBSCR:
  446. case BINARY_LSHIFT:
  447. case BINARY_RSHIFT:
  448. case BINARY_AND:
  449. case BINARY_XOR:
  450. case BINARY_OR:
  451. if (lastlc >= 2 &&
  452. ISBASICBLOCK(blocks, i-6, 7) &&
  453. fold_binops_on_constants(&codestr[i-6], consts)) {
  454. i -= 2;
  455. assert(codestr[i] == LOAD_CONST);
  456. cumlc = 1;
  457. }
  458. break;
  459. /* Fold unary ops on constants.
  460. LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
  461. case UNARY_NEGATIVE:
  462. case UNARY_CONVERT:
  463. case UNARY_INVERT:
  464. if (lastlc >= 1 &&
  465. ISBASICBLOCK(blocks, i-3, 4) &&
  466. fold_unaryops_on_constants(&codestr[i-3], consts)) {
  467. i -= 2;
  468. assert(codestr[i] == LOAD_CONST);
  469. cumlc = 1;
  470. }
  471. break;
  472. /* Simplify conditional jump to conditional jump where the
  473. result of the first test implies the success of a similar
  474. test or the failure of the opposite test.
  475. Arises in code like:
  476. "if a and b:"
  477. "if a or b:"
  478. "a and b or c"
  479. "(a and b) and c"
  480. x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
  481. --> x:JUMP_IF_FALSE_OR_POP z
  482. x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
  483. --> x:POP_JUMP_IF_FALSE y+3
  484. where y+3 is the instruction following the second test.
  485. */
  486. case JUMP_IF_FALSE_OR_POP:
  487. case JUMP_IF_TRUE_OR_POP:
  488. tgt = GETJUMPTGT(codestr, i);
  489. j = codestr[tgt];
  490. if (CONDITIONAL_JUMP(j)) {
  491. /* NOTE: all possible jumps here are
  492. absolute! */
  493. if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
  494. /* The second jump will be
  495. taken iff the first is. */
  496. tgttgt = GETJUMPTGT(codestr, tgt);
  497. /* The current opcode inherits
  498. its target's stack behaviour */
  499. codestr[i] = j;
  500. SETARG(codestr, i, tgttgt);
  501. goto reoptimize_current;
  502. } else {
  503. /* The second jump is not taken
  504. if the first is (so jump past
  505. it), and all conditional
  506. jumps pop their argument when
  507. they're not taken (so change
  508. the first jump to pop its
  509. argument when it's taken). */
  510. if (JUMPS_ON_TRUE(opcode))
  511. codestr[i] = POP_JUMP_IF_TRUE;
  512. else
  513. codestr[i] = POP_JUMP_IF_FALSE;
  514. SETARG(codestr, i, (tgt + 3));
  515. goto reoptimize_current;
  516. }
  517. }
  518. /* Intentional fallthrough */
  519. /* Replace jumps to unconditional jumps */
  520. case POP_JUMP_IF_FALSE:
  521. case POP_JUMP_IF_TRUE:
  522. case FOR_ITER:
  523. case JUMP_FORWARD:
  524. case JUMP_ABSOLUTE:
  525. case CONTINUE_LOOP:
  526. case SETUP_LOOP:
  527. case SETUP_EXCEPT:
  528. case SETUP_FINALLY:
  529. tgt = GETJUMPTGT(codestr, i);
  530. /* Replace JUMP_* to a RETURN into just a RETURN */
  531. if (UNCONDITIONAL_JUMP(opcode) &&
  532. codestr[tgt] == RETURN_VALUE) {
  533. codestr[i] = RETURN_VALUE;
  534. memset(codestr+i+1, NOP, 2);
  535. continue;
  536. }
  537. if (!UNCONDITIONAL_JUMP(codestr[tgt]))
  538. continue;
  539. tgttgt = GETJUMPTGT(codestr, tgt);
  540. if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
  541. opcode = JUMP_ABSOLUTE;
  542. if (!ABSOLUTE_JUMP(opcode))
  543. tgttgt -= i + 3; /* Calc relative jump addr */
  544. if (tgttgt < 0) /* No backward relative jumps */
  545. continue;
  546. codestr[i] = opcode;
  547. SETARG(codestr, i, tgttgt);
  548. break;
  549. case EXTENDED_ARG:
  550. goto exitUnchanged;
  551. /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
  552. /* Remove unreachable JUMPs after RETURN */
  553. case RETURN_VALUE:
  554. if (i+4 >= codelen)
  555. continue;
  556. if (codestr[i+4] == RETURN_VALUE &&
  557. ISBASICBLOCK(blocks,i,5))
  558. memset(codestr+i+1, NOP, 4);
  559. else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
  560. ISBASICBLOCK(blocks,i,4))
  561. memset(codestr+i+1, NOP, 3);
  562. break;
  563. }
  564. }
  565. /* Fixup linenotab */
  566. for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
  567. addrmap[i] = i - nops;
  568. if (codestr[i] == NOP)
  569. nops++;
  570. }
  571. cum_orig_line = 0;
  572. last_line = 0;
  573. for (i=0 ; i < tabsiz ; i+=2) {
  574. cum_orig_line += lineno[i];
  575. new_line = addrmap[cum_orig_line];
  576. /* We checked above that no two lines are more than 255
  577. code elements apart. Since the peephole optimizer
  578. only reduces the size of the bytecode, we know that
  579. they're still less than 255 apart. */
  580. assert (new_line - last_line < 255);
  581. lineno[i] =((unsigned char)(new_line - last_line));
  582. last_line = new_line;
  583. }
  584. /* Remove NOPs and fixup jump targets */
  585. for (i=0, h=0 ; i<codelen ; ) {
  586. opcode = codestr[i];
  587. switch (opcode) {
  588. case NOP:
  589. i++;
  590. continue;
  591. case JUMP_ABSOLUTE:
  592. case CONTINUE_LOOP:
  593. case POP_JUMP_IF_FALSE:
  594. case POP_JUMP_IF_TRUE:
  595. case JUMP_IF_FALSE_OR_POP:
  596. case JUMP_IF_TRUE_OR_POP:
  597. j = addrmap[GETARG(codestr, i)];
  598. SETARG(codestr, i, j);
  599. break;
  600. case FOR_ITER:
  601. case JUMP_FORWARD:
  602. case SETUP_LOOP:
  603. case SETUP_EXCEPT:
  604. case SETUP_FINALLY:
  605. j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
  606. SETARG(codestr, i, j);
  607. break;
  608. }
  609. adj = CODESIZE(opcode);
  610. while (adj--)
  611. codestr[h++] = codestr[i++];
  612. }
  613. assert(h + nops == codelen);
  614. code = PyString_FromStringAndSize((char *)codestr, h);
  615. PyMem_Free(addrmap);
  616. PyMem_Free(codestr);
  617. PyMem_Free(blocks);
  618. return code;
  619. exitUnchanged:
  620. if (blocks != NULL)
  621. PyMem_Free(blocks);
  622. if (addrmap != NULL)
  623. PyMem_Free(addrmap);
  624. if (codestr != NULL)
  625. PyMem_Free(codestr);
  626. Py_INCREF(code);
  627. return code;
  628. }