1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
|
import dis
import gc
from itertools import combinations, product
import opcode
import sys
import textwrap
import unittest
try:
import _testinternalcapi
except ImportError:
_testinternalcapi = None
from test import support
from test.support.bytecode_helper import (
BytecodeTestCase, CfgOptimizationTestCase, CompilationStepTestCase)
def compile_pattern_with_fast_locals(pattern):
source = textwrap.dedent(
f"""
def f(x):
match x:
case {pattern}:
pass
"""
)
namespace = {}
exec(source, namespace)
return namespace["f"].__code__
def count_instr_recursively(f, opname):
count = 0
for instr in dis.get_instructions(f):
if instr.opname == opname:
count += 1
if hasattr(f, '__code__'):
f = f.__code__
for c in f.co_consts:
if hasattr(c, 'co_code'):
count += count_instr_recursively(c, opname)
return count
def get_binop_argval(arg):
for i, nb_op in enumerate(opcode._nb_ops):
if arg == nb_op[0]:
return i
assert False, f"{arg} is not a valid BINARY_OP argument."
class TestTranforms(BytecodeTestCase):
def check_jump_targets(self, code):
instructions = list(dis.get_instructions(code))
targets = {instr.offset: instr for instr in instructions}
for instr in instructions:
if 'JUMP_' not in instr.opname:
continue
tgt = targets[instr.argval]
# jump to unconditional jump
if tgt.opname in ('JUMP_BACKWARD', 'JUMP_FORWARD'):
self.fail(f'{instr.opname} at {instr.offset} '
f'jumps to {tgt.opname} at {tgt.offset}')
# unconditional jump to RETURN_VALUE
if (instr.opname in ('JUMP_BACKWARD', 'JUMP_FORWARD') and
tgt.opname == 'RETURN_VALUE'):
self.fail(f'{instr.opname} at {instr.offset} '
f'jumps to {tgt.opname} at {tgt.offset}')
def check_lnotab(self, code):
"Check that the lnotab byte offsets are sensible."
code = dis._get_code_object(code)
lnotab = list(dis.findlinestarts(code))
# Don't bother checking if the line info is sensible, because
# most of the line info we can get at comes from lnotab.
min_bytecode = min(t[0] for t in lnotab)
max_bytecode = max(t[0] for t in lnotab)
self.assertGreaterEqual(min_bytecode, 0)
self.assertLess(max_bytecode, len(code.co_code))
# This could conceivably test more (and probably should, as there
# aren't very many tests of lnotab), if peepholer wasn't scheduled
# to be replaced anyway.
def test_unot(self):
# UNARY_NOT POP_JUMP_IF_FALSE --> POP_JUMP_IF_TRUE'
def unot(x):
if not x == 2:
del x
self.assertNotInBytecode(unot, 'UNARY_NOT')
self.assertNotInBytecode(unot, 'POP_JUMP_IF_FALSE')
self.assertInBytecode(unot, 'POP_JUMP_IF_TRUE')
self.check_lnotab(unot)
def test_elim_inversion_of_is_or_in(self):
for line, cmp_op, invert in (
('not a is b', 'IS_OP', 1,),
('not a is not b', 'IS_OP', 0,),
('not a in b', 'CONTAINS_OP', 1,),
('not a not in b', 'CONTAINS_OP', 0,),
):
with self.subTest(line=line):
code = compile(line, '', 'single')
self.assertInBytecode(code, cmp_op, invert)
self.check_lnotab(code)
def test_global_as_constant(self):
# LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False
def f():
x = None
x = None
return x
def g():
x = True
return x
def h():
x = False
return x
for func, elem in ((f, None), (g, True), (h, False)):
with self.subTest(func=func):
self.assertNotInBytecode(func, 'LOAD_GLOBAL')
self.assertInBytecode(func, 'LOAD_CONST', elem)
self.check_lnotab(func)
def f():
'Adding a docstring made this test fail in Py2.5.0'
return None
self.assertNotInBytecode(f, 'LOAD_GLOBAL')
self.assertInBytecode(f, 'LOAD_CONST', None)
self.check_lnotab(f)
def test_while_one(self):
# Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx
def f():
while 1:
pass
return list
for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'):
self.assertNotInBytecode(f, elem)
for elem in ('JUMP_BACKWARD',):
self.assertInBytecode(f, elem)
self.check_lnotab(f)
def test_pack_unpack(self):
for line, elem in (
('a, = a,', 'LOAD_CONST',),
('a, b = a, b', 'SWAP',),
('a, b, c = a, b, c', 'SWAP',),
):
with self.subTest(line=line):
code = compile(line,'','single')
self.assertInBytecode(code, elem)
self.assertNotInBytecode(code, 'BUILD_TUPLE')
self.assertNotInBytecode(code, 'UNPACK_SEQUENCE')
self.check_lnotab(code)
def test_constant_folding_tuples_of_constants(self):
for line, elem in (
('a = 1,2,3', (1, 2, 3)),
('("a","b","c")', ('a', 'b', 'c')),
('a,b,c,d = 1,2,3,4', (1, 2, 3, 4)),
('(None, 1, None)', (None, 1, None)),
('((1, 2), 3, 4)', ((1, 2), 3, 4)),
):
with self.subTest(line=line):
code = compile(line,'','single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
self.assertNotInBytecode(code, 'BUILD_TUPLE')
self.check_lnotab(code)
# Long tuples should be folded too.
code = compile(repr(tuple(range(10000))),'','single')
self.assertNotInBytecode(code, 'BUILD_TUPLE')
# One LOAD_CONST for the tuple, one for the None return value
load_consts = [instr for instr in dis.get_instructions(code)
if instr.opname == 'LOAD_CONST']
self.assertEqual(len(load_consts), 2)
self.check_lnotab(code)
# Bug 1053819: Tuple of constants misidentified when presented with:
# . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . .
# The following would segfault upon compilation
def crater():
(~[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
],)
self.check_lnotab(crater)
def test_constant_folding_lists_of_constants(self):
for line, elem in (
# in/not in constants with BUILD_LIST should be folded to a tuple:
('a in [1,2,3]', (1, 2, 3)),
('a not in ["a","b","c"]', ('a', 'b', 'c')),
('a in [None, 1, None]', (None, 1, None)),
('a not in [(1, 2), 3, 4]', ((1, 2), 3, 4)),
):
with self.subTest(line=line):
code = compile(line, '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', elem)
self.assertNotInBytecode(code, 'BUILD_LIST')
self.check_lnotab(code)
def test_constant_folding_sets_of_constants(self):
for line, elem in (
# in/not in constants with BUILD_SET should be folded to a frozenset:
('a in {1,2,3}', frozenset({1, 2, 3})),
('a not in {"a","b","c"}', frozenset({'a', 'c', 'b'})),
('a in {None, 1, None}', frozenset({1, None})),
('a not in {(1, 2), 3, 4}', frozenset({(1, 2), 3, 4})),
('a in {1, 2, 3, 3, 2, 1}', frozenset({1, 2, 3})),
):
with self.subTest(line=line):
code = compile(line, '', 'single')
self.assertNotInBytecode(code, 'BUILD_SET')
self.assertInBytecode(code, 'LOAD_CONST', elem)
self.check_lnotab(code)
# Ensure that the resulting code actually works:
def f(a):
return a in {1, 2, 3}
def g(a):
return a not in {1, 2, 3}
self.assertTrue(f(3))
self.assertTrue(not f(4))
self.check_lnotab(f)
self.assertTrue(not g(3))
self.assertTrue(g(4))
self.check_lnotab(g)
def test_constant_folding_small_int(self):
tests = [
('(0, )[0]', 0),
('(1 + 2, )[0]', 3),
('(2 + 2 * 2, )[0]', 6),
('(1, (1 + 2 + 3, ))[1][0]', 6),
('1 + 2', 3),
('2 + 2 * 2 // 2 - 2', 2),
('(255, )[0]', 255),
('(256, )[0]', None),
('(1000, )[0]', None),
('(1 - 2, )[0]', None),
('255 + 0', 255),
('255 + 1', None),
('-1', None),
('--1', 1),
('--255', 255),
('--256', None),
('~1', None),
('~~1', 1),
('~~255', 255),
('~~256', None),
('++255', 255),
('++256', None),
]
for expr, oparg in tests:
with self.subTest(expr=expr, oparg=oparg):
code = compile(expr, '', 'single')
if oparg is not None:
self.assertInBytecode(code, 'LOAD_SMALL_INT', oparg)
else:
self.assertNotInBytecode(code, 'LOAD_SMALL_INT')
self.check_lnotab(code)
def test_constant_folding_unaryop(self):
intrinsic_positive = 5
tests = [
('-0', 'UNARY_NEGATIVE', None, True, 'LOAD_SMALL_INT', 0),
('-0.0', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -0.0),
('-(1.0-1.0)', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -0.0),
('-0.5', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -0.5),
('---1', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -1),
('---""', 'UNARY_NEGATIVE', None, False, None, None),
('~~~1', 'UNARY_INVERT', None, True, 'LOAD_CONST', -2),
('~~~""', 'UNARY_INVERT', None, False, None, None),
('not not True', 'UNARY_NOT', None, True, 'LOAD_CONST', True),
('not not x', 'UNARY_NOT', None, True, 'LOAD_NAME', 'x'), # this should be optimized regardless of constant or not
('+++1', 'CALL_INTRINSIC_1', intrinsic_positive, True, 'LOAD_SMALL_INT', 1),
('---x', 'UNARY_NEGATIVE', None, False, None, None),
('~~~x', 'UNARY_INVERT', None, False, None, None),
('+++x', 'CALL_INTRINSIC_1', intrinsic_positive, False, None, None),
('~True', 'UNARY_INVERT', None, False, None, None),
]
for (
expr,
original_opcode,
original_argval,
is_optimized,
optimized_opcode,
optimized_argval,
) in tests:
with self.subTest(expr=expr, is_optimized=is_optimized):
code = compile(expr, "", "single")
if is_optimized:
self.assertNotInBytecode(code, original_opcode, argval=original_argval)
self.assertInBytecode(code, optimized_opcode, argval=optimized_argval)
else:
self.assertInBytecode(code, original_opcode, argval=original_argval)
self.check_lnotab(code)
# Check that -0.0 works after marshaling
def negzero():
return -(1.0-1.0)
for instr in dis.get_instructions(negzero):
self.assertNotStartsWith(instr.opname, 'UNARY_')
self.check_lnotab(negzero)
def test_constant_folding_binop(self):
tests = [
('1 + 2', 'NB_ADD', True, 'LOAD_SMALL_INT', 3),
('1 + 2 + 3', 'NB_ADD', True, 'LOAD_SMALL_INT', 6),
('1 + ""', 'NB_ADD', False, None, None),
('1 - 2', 'NB_SUBTRACT', True, 'LOAD_CONST', -1),
('1 - 2 - 3', 'NB_SUBTRACT', True, 'LOAD_CONST', -4),
('1 - ""', 'NB_SUBTRACT', False, None, None),
('2 * 2', 'NB_MULTIPLY', True, 'LOAD_SMALL_INT', 4),
('2 * 2 * 2', 'NB_MULTIPLY', True, 'LOAD_SMALL_INT', 8),
('2 / 2', 'NB_TRUE_DIVIDE', True, 'LOAD_CONST', 1.0),
('2 / 2 / 2', 'NB_TRUE_DIVIDE', True, 'LOAD_CONST', 0.5),
('2 / ""', 'NB_TRUE_DIVIDE', False, None, None),
('2 // 2', 'NB_FLOOR_DIVIDE', True, 'LOAD_SMALL_INT', 1),
('2 // 2 // 2', 'NB_FLOOR_DIVIDE', True, 'LOAD_SMALL_INT', 0),
('2 // ""', 'NB_FLOOR_DIVIDE', False, None, None),
('2 % 2', 'NB_REMAINDER', True, 'LOAD_SMALL_INT', 0),
('2 % 2 % 2', 'NB_REMAINDER', True, 'LOAD_SMALL_INT', 0),
('2 % ()', 'NB_REMAINDER', False, None, None),
('2 ** 2', 'NB_POWER', True, 'LOAD_SMALL_INT', 4),
('2 ** 2 ** 2', 'NB_POWER', True, 'LOAD_SMALL_INT', 16),
('2 ** ""', 'NB_POWER', False, None, None),
('2 << 2', 'NB_LSHIFT', True, 'LOAD_SMALL_INT', 8),
('2 << 2 << 2', 'NB_LSHIFT', True, 'LOAD_SMALL_INT', 32),
('2 << ""', 'NB_LSHIFT', False, None, None),
('2 >> 2', 'NB_RSHIFT', True, 'LOAD_SMALL_INT', 0),
('2 >> 2 >> 2', 'NB_RSHIFT', True, 'LOAD_SMALL_INT', 0),
('2 >> ""', 'NB_RSHIFT', False, None, None),
('2 | 2', 'NB_OR', True, 'LOAD_SMALL_INT', 2),
('2 | 2 | 2', 'NB_OR', True, 'LOAD_SMALL_INT', 2),
('2 | ""', 'NB_OR', False, None, None),
('2 & 2', 'NB_AND', True, 'LOAD_SMALL_INT', 2),
('2 & 2 & 2', 'NB_AND', True, 'LOAD_SMALL_INT', 2),
('2 & ""', 'NB_AND', False, None, None),
('2 ^ 2', 'NB_XOR', True, 'LOAD_SMALL_INT', 0),
('2 ^ 2 ^ 2', 'NB_XOR', True, 'LOAD_SMALL_INT', 2),
('2 ^ ""', 'NB_XOR', False, None, None),
('(1, )[0]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 1),
('(1, )[-1]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 1),
('(1 + 2, )[0]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 3),
('(1, (1, 2))[1][1]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 2),
('(1, 2)[2-1]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 2),
('(1, (1, 2))[1][2-1]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 2),
('(1, (1, 2))[1:6][0][2-1]', 'NB_SUBSCR', True, 'LOAD_SMALL_INT', 2),
('"a"[0]', 'NB_SUBSCR', True, 'LOAD_CONST', 'a'),
('("a" + "b")[1]', 'NB_SUBSCR', True, 'LOAD_CONST', 'b'),
('("a" + "b", )[0][1]', 'NB_SUBSCR', True, 'LOAD_CONST', 'b'),
('("a" * 10)[9]', 'NB_SUBSCR', True, 'LOAD_CONST', 'a'),
('(1, )[1]', 'NB_SUBSCR', False, None, None),
('(1, )[-2]', 'NB_SUBSCR', False, None, None),
('"a"[1]', 'NB_SUBSCR', False, None, None),
('"a"[-2]', 'NB_SUBSCR', False, None, None),
('("a" + "b")[2]', 'NB_SUBSCR', False, None, None),
('("a" + "b", )[0][2]', 'NB_SUBSCR', False, None, None),
('("a" + "b", )[1][0]', 'NB_SUBSCR', False, None, None),
('("a" * 10)[10]', 'NB_SUBSCR', False, None, None),
('(1, (1, 2))[2:6][0][2-1]', 'NB_SUBSCR', False, None, None),
]
for (
expr,
nb_op,
is_optimized,
optimized_opcode,
optimized_argval
) in tests:
with self.subTest(expr=expr, is_optimized=is_optimized):
code = compile(expr, '', 'single')
nb_op_val = get_binop_argval(nb_op)
if is_optimized:
self.assertNotInBytecode(code, 'BINARY_OP', argval=nb_op_val)
self.assertInBytecode(code, optimized_opcode, argval=optimized_argval)
else:
self.assertInBytecode(code, 'BINARY_OP', argval=nb_op_val)
self.check_lnotab(code)
# Verify that large sequences do not result from folding
code = compile('"x"*10000', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 10000)
self.assertNotIn("x"*10000, code.co_consts)
self.check_lnotab(code)
code = compile('1<<1000', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 1000)
self.assertNotIn(1<<1000, code.co_consts)
self.check_lnotab(code)
code = compile('2**1000', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 1000)
self.assertNotIn(2**1000, code.co_consts)
self.check_lnotab(code)
# Test binary subscript on unicode
# valid code get optimized
code = compile('"foo"[0]', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', 'f')
self.assertNotInBytecode(code, 'BINARY_OP')
self.check_lnotab(code)
code = compile('"\u0061\uffff"[1]', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', '\uffff')
self.assertNotInBytecode(code,'BINARY_OP')
self.check_lnotab(code)
# With PEP 393, non-BMP char get optimized
code = compile('"\U00012345"[0]', '', 'single')
self.assertInBytecode(code, 'LOAD_CONST', '\U00012345')
self.assertNotInBytecode(code, 'BINARY_OP')
self.check_lnotab(code)
# invalid code doesn't get optimized
# out of range
code = compile('"fuu"[10]', '', 'single')
self.assertInBytecode(code, 'BINARY_OP')
self.check_lnotab(code)
def test_constant_folding_remove_nop_location(self):
sources = [
"""
(-
-
-
1)
""",
"""
(1
+
2
+
3)
""",
"""
(1,
2,
3)[0]
""",
"""
[1,
2,
3]
""",
"""
{1,
2,
3}
""",
"""
1 in [
1,
2,
3
]
""",
"""
1 in {
1,
2,
3
}
""",
"""
for _ in [1,
2,
3]:
pass
""",
"""
for _ in [1,
2,
x]:
pass
""",
"""
for _ in {1,
2,
3}:
pass
"""
]
for source in sources:
code = compile(textwrap.dedent(source), '', 'single')
self.assertNotInBytecode(code, 'NOP')
def test_elim_extra_return(self):
# RETURN LOAD_CONST None RETURN --> RETURN
def f(x):
return x
self.assertNotInBytecode(f, 'LOAD_CONST', None)
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertEqual(len(returns), 1)
self.check_lnotab(f)
def test_elim_jump_to_return(self):
# JUMP_FORWARD to RETURN --> RETURN
def f(cond, true_value, false_value):
# Intentionally use two-line expression to test issue37213.
return (true_value if cond
else false_value)
self.check_jump_targets(f)
self.assertNotInBytecode(f, 'JUMP_FORWARD')
self.assertNotInBytecode(f, 'JUMP_BACKWARD')
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertEqual(len(returns), 2)
self.check_lnotab(f)
def test_elim_jump_to_uncond_jump(self):
# POP_JUMP_IF_FALSE to JUMP_FORWARD --> POP_JUMP_IF_FALSE to non-jump
def f():
if a:
# Intentionally use two-line expression to test issue37213.
if (c
or d):
foo()
else:
baz()
self.check_jump_targets(f)
self.check_lnotab(f)
def test_elim_jump_to_uncond_jump2(self):
# POP_JUMP_IF_FALSE to JUMP_BACKWARD --> POP_JUMP_IF_FALSE to non-jump
def f():
while a:
# Intentionally use two-line expression to test issue37213.
if (c
or d):
a = foo()
self.check_jump_targets(f)
self.check_lnotab(f)
def test_elim_jump_to_uncond_jump3(self):
# Intentionally use two-line expressions to test issue37213.
# POP_JUMP_IF_FALSE to POP_JUMP_IF_FALSE --> POP_JUMP_IF_FALSE to non-jump
def f(a, b, c):
return ((a and b)
and c)
self.check_jump_targets(f)
self.check_lnotab(f)
self.assertEqual(count_instr_recursively(f, 'POP_JUMP_IF_FALSE'), 2)
# POP_JUMP_IF_TRUE to POP_JUMP_IF_TRUE --> POP_JUMP_IF_TRUE to non-jump
def f(a, b, c):
return ((a or b)
or c)
self.check_jump_targets(f)
self.check_lnotab(f)
self.assertEqual(count_instr_recursively(f, 'POP_JUMP_IF_TRUE'), 2)
# JUMP_IF_FALSE_OR_POP to JUMP_IF_TRUE_OR_POP --> POP_JUMP_IF_FALSE to non-jump
def f(a, b, c):
return ((a and b)
or c)
self.check_jump_targets(f)
self.check_lnotab(f)
self.assertEqual(count_instr_recursively(f, 'POP_JUMP_IF_FALSE'), 1)
self.assertEqual(count_instr_recursively(f, 'POP_JUMP_IF_TRUE'), 1)
# POP_JUMP_IF_TRUE to POP_JUMP_IF_FALSE --> POP_JUMP_IF_TRUE to non-jump
def f(a, b, c):
return ((a or b)
and c)
self.check_jump_targets(f)
self.check_lnotab(f)
self.assertEqual(count_instr_recursively(f, 'POP_JUMP_IF_FALSE'), 1)
self.assertEqual(count_instr_recursively(f, 'POP_JUMP_IF_TRUE'), 1)
def test_elim_jump_to_uncond_jump4(self):
def f():
for i in range(5):
if i > 3:
print(i)
self.check_jump_targets(f)
def test_elim_jump_after_return1(self):
# Eliminate dead code: jumps immediately after returns can't be reached
def f(cond1, cond2):
if cond1: return 1
if cond2: return 2
while 1:
return 3
while 1:
if cond1: return 4
return 5
return 6
self.assertNotInBytecode(f, 'JUMP_FORWARD')
self.assertNotInBytecode(f, 'JUMP_BACKWARD')
returns = [instr for instr in dis.get_instructions(f)
if instr.opname == 'RETURN_VALUE']
self.assertLessEqual(len(returns), 6)
self.check_lnotab(f)
def test_make_function_doesnt_bail(self):
def f():
def g()->1+1:
pass
return g
self.assertNotInBytecode(f, 'BINARY_OP')
self.check_lnotab(f)
def test_in_literal_list(self):
def containtest():
return x in [a, b]
self.assertEqual(count_instr_recursively(containtest, 'BUILD_LIST'), 0)
self.check_lnotab(containtest)
def test_iterate_literal_list(self):
def forloop():
for x in [a, b]:
pass
self.assertEqual(count_instr_recursively(forloop, 'BUILD_LIST'), 0)
self.check_lnotab(forloop)
def test_condition_with_binop_with_bools(self):
def f():
if True or False:
return 1
return 0
self.assertEqual(f(), 1)
self.check_lnotab(f)
def test_if_with_if_expression(self):
# Check bpo-37289
def f(x):
if (True if x else False):
return True
return False
self.assertTrue(f(True))
self.check_lnotab(f)
def test_trailing_nops(self):
# Check the lnotab of a function that even after trivial
# optimization has trailing nops, which the lnotab adjustment has to
# handle properly (bpo-38115).
def f(x):
while 1:
return 3
while 1:
return 5
return 6
self.check_lnotab(f)
def test_assignment_idiom_in_comprehensions(self):
def listcomp():
return [y for x in a for y in [f(x)]]
self.assertEqual(count_instr_recursively(listcomp, 'FOR_ITER'), 1)
def setcomp():
return {y for x in a for y in [f(x)]}
self.assertEqual(count_instr_recursively(setcomp, 'FOR_ITER'), 1)
def dictcomp():
return {y: y for x in a for y in [f(x)]}
self.assertEqual(count_instr_recursively(dictcomp, 'FOR_ITER'), 1)
def genexpr():
return (y for x in a for y in [f(x)])
self.assertEqual(count_instr_recursively(genexpr, 'FOR_ITER'), 1)
@support.requires_resource('cpu')
def test_format_combinations(self):
flags = '-+ #0'
testcases = [
*product(('', '1234', 'абвг'), 'sra'),
*product((1234, -1234), 'duioxX'),
*product((1234.5678901, -1234.5678901), 'duifegFEG'),
*product((float('inf'), -float('inf')), 'fegFEG'),
]
width_precs = [
*product(('', '1', '30'), ('', '.', '.0', '.2')),
('', '.40'),
('30', '.40'),
]
for value, suffix in testcases:
for width, prec in width_precs:
for r in range(len(flags) + 1):
for spec in combinations(flags, r):
fmt = '%' + ''.join(spec) + width + prec + suffix
with self.subTest(fmt=fmt, value=value):
s1 = fmt % value
s2 = eval(f'{fmt!r} % (x,)', {'x': value})
self.assertEqual(s2, s1, f'{fmt = }')
def test_format_misc(self):
def format(fmt, *values):
vars = [f'x{i+1}' for i in range(len(values))]
if len(vars) == 1:
args = '(' + vars[0] + ',)'
else:
args = '(' + ', '.join(vars) + ')'
return eval(f'{fmt!r} % {args}', dict(zip(vars, values)))
self.assertEqual(format('string'), 'string')
self.assertEqual(format('x = %s!', 1234), 'x = 1234!')
self.assertEqual(format('x = %d!', 1234), 'x = 1234!')
self.assertEqual(format('x = %x!', 1234), 'x = 4d2!')
self.assertEqual(format('x = %f!', 1234), 'x = 1234.000000!')
self.assertEqual(format('x = %s!', 1234.0000625), 'x = 1234.0000625!')
self.assertEqual(format('x = %f!', 1234.0000625), 'x = 1234.000063!')
self.assertEqual(format('x = %d!', 1234.0000625), 'x = 1234!')
self.assertEqual(format('x = %s%% %%%%', 1234), 'x = 1234% %%')
self.assertEqual(format('x = %s!', '%% %s'), 'x = %% %s!')
self.assertEqual(format('x = %s, y = %d', 12, 34), 'x = 12, y = 34')
def test_format_errors(self):
with self.assertRaisesRegex(TypeError,
'not enough arguments for format string'):
eval("'%s' % ()")
with self.assertRaisesRegex(TypeError,
'not all arguments converted during string formatting'):
eval("'%s' % (x, y)", {'x': 1, 'y': 2})
with self.assertRaisesRegex(ValueError, 'incomplete format'):
eval("'%s%' % (x,)", {'x': 1234})
with self.assertRaisesRegex(ValueError, 'incomplete format'):
eval("'%s%%%' % (x,)", {'x': 1234})
with self.assertRaisesRegex(TypeError,
'not enough arguments for format string'):
eval("'%s%z' % (x,)", {'x': 1234})
with self.assertRaisesRegex(ValueError, 'unsupported format character'):
eval("'%s%z' % (x, 5)", {'x': 1234})
with self.assertRaisesRegex(TypeError, 'a real number is required, not str'):
eval("'%d' % (x,)", {'x': '1234'})
with self.assertRaisesRegex(TypeError, 'an integer is required, not float'):
eval("'%x' % (x,)", {'x': 1234.56})
with self.assertRaisesRegex(TypeError, 'an integer is required, not str'):
eval("'%x' % (x,)", {'x': '1234'})
with self.assertRaisesRegex(TypeError, 'must be real number, not str'):
eval("'%f' % (x,)", {'x': '1234'})
with self.assertRaisesRegex(TypeError,
'not enough arguments for format string'):
eval("'%s, %s' % (x, *y)", {'x': 1, 'y': []})
with self.assertRaisesRegex(TypeError,
'not all arguments converted during string formatting'):
eval("'%s, %s' % (x, *y)", {'x': 1, 'y': [2, 3]})
def test_static_swaps_unpack_two(self):
def f(a, b):
a, b = a, b
b, a = a, b
self.assertNotInBytecode(f, "SWAP")
def test_static_swaps_unpack_three(self):
def f(a, b, c):
a, b, c = a, b, c
a, c, b = a, b, c
b, a, c = a, b, c
b, c, a = a, b, c
c, a, b = a, b, c
c, b, a = a, b, c
self.assertNotInBytecode(f, "SWAP")
def test_static_swaps_match_mapping(self):
for a, b, c in product("_a", "_b", "_c"):
pattern = f"{{'a': {a}, 'b': {b}, 'c': {c}}}"
with self.subTest(pattern):
code = compile_pattern_with_fast_locals(pattern)
self.assertNotInBytecode(code, "SWAP")
def test_static_swaps_match_class(self):
forms = [
"C({}, {}, {})",
"C({}, {}, c={})",
"C({}, b={}, c={})",
"C(a={}, b={}, c={})"
]
for a, b, c in product("_a", "_b", "_c"):
for form in forms:
pattern = form.format(a, b, c)
with self.subTest(pattern):
code = compile_pattern_with_fast_locals(pattern)
self.assertNotInBytecode(code, "SWAP")
def test_static_swaps_match_sequence(self):
swaps = {"*_, b, c", "a, *_, c", "a, b, *_"}
forms = ["{}, {}, {}", "{}, {}, *{}", "{}, *{}, {}", "*{}, {}, {}"]
for a, b, c in product("_a", "_b", "_c"):
for form in forms:
pattern = form.format(a, b, c)
with self.subTest(pattern):
code = compile_pattern_with_fast_locals(pattern)
if pattern in swaps:
# If this fails... great! Remove this pattern from swaps
# to prevent regressing on any improvement:
self.assertInBytecode(code, "SWAP")
else:
self.assertNotInBytecode(code, "SWAP")
class TestBuglets(unittest.TestCase):
def test_bug_11510(self):
# folded constant set optimization was commingled with the tuple
# unpacking optimization which would fail if the set had duplicate
# elements so that the set length was unexpected
def f():
x, y = {1, 1}
return x, y
with self.assertRaises(ValueError):
f()
def test_bpo_42057(self):
for i in range(10):
try:
raise Exception
except Exception or Exception:
pass
def test_bpo_45773_pop_jump_if_true(self):
compile("while True or spam: pass", "<test>", "exec")
def test_bpo_45773_pop_jump_if_false(self):
compile("while True or not spam: pass", "<test>", "exec")
class TestMarkingVariablesAsUnKnown(BytecodeTestCase):
def setUp(self):
self.addCleanup(sys.settrace, sys.gettrace())
sys.settrace(None)
def test_load_fast_known_simple(self):
def f():
x = 1
y = x + x
self.assertInBytecode(f, 'LOAD_FAST_BORROW_LOAD_FAST_BORROW')
def test_load_fast_unknown_simple(self):
def f():
if condition():
x = 1
print(x)
self.assertInBytecode(f, 'LOAD_FAST_CHECK')
self.assertNotInBytecode(f, 'LOAD_FAST')
def test_load_fast_unknown_because_del(self):
def f():
x = 1
del x
print(x)
self.assertInBytecode(f, 'LOAD_FAST_CHECK')
self.assertNotInBytecode(f, 'LOAD_FAST')
def test_load_fast_known_because_parameter(self):
def f1(x):
print(x)
self.assertInBytecode(f1, 'LOAD_FAST_BORROW')
self.assertNotInBytecode(f1, 'LOAD_FAST_CHECK')
def f2(*, x):
print(x)
self.assertInBytecode(f2, 'LOAD_FAST_BORROW')
self.assertNotInBytecode(f2, 'LOAD_FAST_CHECK')
def f3(*args):
print(args)
self.assertInBytecode(f3, 'LOAD_FAST_BORROW')
self.assertNotInBytecode(f3, 'LOAD_FAST_CHECK')
def f4(**kwargs):
print(kwargs)
self.assertInBytecode(f4, 'LOAD_FAST_BORROW')
self.assertNotInBytecode(f4, 'LOAD_FAST_CHECK')
def f5(x=0):
print(x)
self.assertInBytecode(f5, 'LOAD_FAST_BORROW')
self.assertNotInBytecode(f5, 'LOAD_FAST_CHECK')
def test_load_fast_known_because_already_loaded(self):
def f():
if condition():
x = 1
print(x)
print(x)
self.assertInBytecode(f, 'LOAD_FAST_CHECK')
self.assertInBytecode(f, 'LOAD_FAST_BORROW')
def test_load_fast_known_multiple_branches(self):
def f():
if condition():
x = 1
else:
x = 2
print(x)
self.assertInBytecode(f, 'LOAD_FAST_BORROW')
self.assertNotInBytecode(f, 'LOAD_FAST_CHECK')
def test_load_fast_unknown_after_error(self):
def f():
try:
res = 1 / 0
except ZeroDivisionError:
pass
return res
# LOAD_FAST (known) still occurs in the no-exception branch.
# Assert that it doesn't occur in the LOAD_FAST_CHECK branch.
self.assertInBytecode(f, 'LOAD_FAST_CHECK')
def test_load_fast_unknown_after_error_2(self):
def f():
try:
1 / 0
except ZeroDivisionError:
print(a, b, c, d, e, f, g)
a = b = c = d = e = f = g = 1
self.assertInBytecode(f, 'LOAD_FAST_CHECK')
self.assertNotInBytecode(f, 'LOAD_FAST')
def test_load_fast_too_many_locals(self):
# When there get to be too many locals to analyze completely,
# later locals are all converted to LOAD_FAST_CHECK, except
# when a store or prior load occurred in the same basicblock.
def f():
a00 = a01 = a02 = a03 = a04 = a05 = a06 = a07 = a08 = a09 = 1
a10 = a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = 1
a20 = a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = 1
a30 = a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = 1
a40 = a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = 1
a50 = a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = 1
a60 = a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = 1
a70 = a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = 1
del a72, a73
print(a73)
print(a70, a71, a72, a73)
while True:
print(a00, a01, a62, a63)
print(a64, a65, a78, a79)
self.assertInBytecode(f, 'LOAD_FAST_BORROW_LOAD_FAST_BORROW', ("a00", "a01"))
self.assertNotInBytecode(f, 'LOAD_FAST_CHECK', "a00")
self.assertNotInBytecode(f, 'LOAD_FAST_CHECK', "a01")
for i in 62, 63:
# First 64 locals: analyze completely
self.assertInBytecode(f, 'LOAD_FAST_BORROW', f"a{i:02}")
self.assertNotInBytecode(f, 'LOAD_FAST_CHECK', f"a{i:02}")
for i in 64, 65, 78, 79:
# Locals >=64 not in the same basicblock
self.assertInBytecode(f, 'LOAD_FAST_CHECK', f"a{i:02}")
self.assertNotInBytecode(f, 'LOAD_FAST', f"a{i:02}")
for i in 70, 71:
# Locals >=64 in the same basicblock
self.assertInBytecode(f, 'LOAD_FAST_BORROW', f"a{i:02}")
self.assertNotInBytecode(f, 'LOAD_FAST_CHECK', f"a{i:02}")
# del statements should invalidate within basicblocks.
self.assertInBytecode(f, 'LOAD_FAST_CHECK', "a72")
self.assertNotInBytecode(f, 'LOAD_FAST', "a72")
# previous checked loads within a basicblock enable unchecked loads
self.assertInBytecode(f, 'LOAD_FAST_CHECK', "a73")
self.assertInBytecode(f, 'LOAD_FAST_BORROW', "a73")
def test_setting_lineno_no_undefined(self):
code = textwrap.dedent("""\
def f():
x = y = 2
if not x:
return 4
for i in range(55):
x + 6
L = 7
L = 8
L = 9
L = 10
""")
ns = {}
exec(code, ns)
f = ns['f']
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
co_code = f.__code__.co_code
def trace(frame, event, arg):
if event == 'line' and frame.f_lineno == 9:
frame.f_lineno = 3
sys.settrace(None)
return None
return trace
sys.settrace(trace)
result = f()
self.assertIsNone(result)
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
self.assertEqual(f.__code__.co_code, co_code)
def test_setting_lineno_one_undefined(self):
code = textwrap.dedent("""\
def f():
x = y = 2
if not x:
return 4
for i in range(55):
x + 6
del x
L = 8
L = 9
L = 10
""")
ns = {}
exec(code, ns)
f = ns['f']
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
co_code = f.__code__.co_code
def trace(frame, event, arg):
if event == 'line' and frame.f_lineno == 9:
frame.f_lineno = 3
sys.settrace(None)
return None
return trace
e = r"assigning None to 1 unbound local"
with self.assertWarnsRegex(RuntimeWarning, e):
sys.settrace(trace)
result = f()
self.assertEqual(result, 4)
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
self.assertEqual(f.__code__.co_code, co_code)
def test_setting_lineno_two_undefined(self):
code = textwrap.dedent("""\
def f():
x = y = 2
if not x:
return 4
for i in range(55):
x + 6
del x, y
L = 8
L = 9
L = 10
""")
ns = {}
exec(code, ns)
f = ns['f']
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
co_code = f.__code__.co_code
def trace(frame, event, arg):
if event == 'line' and frame.f_lineno == 9:
frame.f_lineno = 3
sys.settrace(None)
return None
return trace
e = r"assigning None to 2 unbound locals"
with self.assertWarnsRegex(RuntimeWarning, e):
sys.settrace(trace)
result = f()
self.assertEqual(result, 4)
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
self.assertEqual(f.__code__.co_code, co_code)
def make_function_with_no_checks(self):
code = textwrap.dedent("""\
def f():
x = 2
L = 3
L = 4
L = 5
if not L:
x + 7
y = 2
""")
ns = {}
exec(code, ns)
f = ns['f']
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
return f
def test_modifying_local_does_not_add_check(self):
f = self.make_function_with_no_checks()
def trace(frame, event, arg):
if event == 'line' and frame.f_lineno == 4:
frame.f_locals["x"] = 42
sys.settrace(None)
return None
return trace
sys.settrace(trace)
f()
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
def test_initializing_local_does_not_add_check(self):
f = self.make_function_with_no_checks()
def trace(frame, event, arg):
if event == 'line' and frame.f_lineno == 4:
frame.f_locals["y"] = 42
sys.settrace(None)
return None
return trace
sys.settrace(trace)
f()
self.assertInBytecode(f, "LOAD_FAST_BORROW")
self.assertNotInBytecode(f, "LOAD_FAST_CHECK")
class DirectCfgOptimizerTests(CfgOptimizationTestCase):
def cfg_optimization_test(self, insts, expected_insts,
consts=None, expected_consts=None,
nlocals=0):
self.check_instructions(insts)
self.check_instructions(expected_insts)
if expected_consts is None:
expected_consts = consts
seq = self.seq_from_insts(insts)
opt_insts, opt_consts = self.get_optimized(seq, consts, nlocals)
expected_insts = self.seq_from_insts(expected_insts).get_instructions()
self.assertInstructionsMatch(opt_insts, expected_insts)
self.assertEqual(opt_consts, expected_consts)
def test_conditional_jump_forward_non_const_condition(self):
insts = [
('LOAD_NAME', 1, 11),
('POP_JUMP_IF_TRUE', lbl := self.Label(), 12),
('LOAD_CONST', 2, 13),
('RETURN_VALUE', None, 13),
lbl,
('LOAD_CONST', 3, 14),
('RETURN_VALUE', None, 14),
]
expected_insts = [
('LOAD_NAME', 1, 11),
('POP_JUMP_IF_TRUE', lbl := self.Label(), 12),
('LOAD_SMALL_INT', 2, 13),
('RETURN_VALUE', None, 13),
lbl,
('LOAD_SMALL_INT', 3, 14),
('RETURN_VALUE', None, 14),
]
self.cfg_optimization_test(insts,
expected_insts,
consts=[0, 1, 2, 3, 4],
expected_consts=[0])
def test_list_exceeding_stack_use_guideline(self):
def f():
return [
0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24,
25, 26, 27, 28, 29,
30, 31, 32, 33, 34,
35, 36, 37, 38, 39
]
self.assertEqual(f(), list(range(40)))
def test_set_exceeding_stack_use_guideline(self):
def f():
return {
0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24,
25, 26, 27, 28, 29,
30, 31, 32, 33, 34,
35, 36, 37, 38, 39
}
self.assertEqual(f(), frozenset(range(40)))
def test_nested_const_foldings(self):
# (1, (--2 + ++2 * 2 // 2 - 2, )[0], ~~3, not not True) ==> (1, 2, 3, True)
intrinsic_positive = 5
before = [
('LOAD_SMALL_INT', 1, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('UNARY_NEGATIVE', None, 0),
('NOP', None, 0),
('UNARY_NEGATIVE', None, 0),
('NOP', None, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('CALL_INTRINSIC_1', intrinsic_positive, 0),
('NOP', None, 0),
('CALL_INTRINSIC_1', intrinsic_positive, 0),
('BINARY_OP', get_binop_argval('NB_MULTIPLY')),
('LOAD_SMALL_INT', 2, 0),
('NOP', None, 0),
('BINARY_OP', get_binop_argval('NB_FLOOR_DIVIDE')),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', get_binop_argval('NB_ADD')),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('NOP', None, 0),
('BINARY_OP', get_binop_argval('NB_SUBTRACT')),
('NOP', None, 0),
('BUILD_TUPLE', 1, 0),
('LOAD_SMALL_INT', 0, 0),
('BINARY_OP', get_binop_argval('NB_SUBSCR'), 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 3, 0),
('NOP', None, 0),
('UNARY_INVERT', None, 0),
('NOP', None, 0),
('UNARY_INVERT', None, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 3, 0),
('NOP', None, 0),
('UNARY_NOT', None, 0),
('NOP', None, 0),
('UNARY_NOT', None, 0),
('NOP', None, 0),
('BUILD_TUPLE', 4, 0),
('NOP', None, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_CONST', 1, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[-2, (1, 2, 3, True)])
def test_build_empty_tuple(self):
before = [
('BUILD_TUPLE', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[()])
def test_fold_tuple_of_constants(self):
before = [
('NOP', None, 0),
('LOAD_SMALL_INT', 1, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('NOP', None, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 3, 0),
('NOP', None, 0),
('BUILD_TUPLE', 3, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[(1, 2, 3)])
# not all consts
same = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_TUPLE', 3, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(same, same, consts=[])
def test_fold_constant_intrinsic_list_to_tuple(self):
INTRINSIC_LIST_TO_TUPLE = 6
# long tuple
consts = 1000
before = (
[('BUILD_LIST', 0, 0)] +
[('LOAD_CONST', 0, 0), ('LIST_APPEND', 1, 0)] * consts +
[('CALL_INTRINSIC_1', INTRINSIC_LIST_TO_TUPLE, 0), ('RETURN_VALUE', None, 0)]
)
after = [
('LOAD_CONST', 1, 0),
('RETURN_VALUE', None, 0)
]
result_const = tuple(["test"] * consts)
self.cfg_optimization_test(before, after, consts=["test"], expected_consts=["test", result_const])
# empty list
before = [
('BUILD_LIST', 0, 0),
('CALL_INTRINSIC_1', INTRINSIC_LIST_TO_TUPLE, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[()])
# multiple BUILD_LIST 0: ([], 1, [], 2)
same = [
('BUILD_LIST', 0, 0),
('BUILD_LIST', 0, 0),
('LIST_APPEND', 1, 0),
('LOAD_SMALL_INT', 1, 0),
('LIST_APPEND', 1, 0),
('BUILD_LIST', 0, 0),
('LIST_APPEND', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('LIST_APPEND', 1, 0),
('CALL_INTRINSIC_1', INTRINSIC_LIST_TO_TUPLE, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(same, same, consts=[])
# nested folding: (1, 1+1, 3)
before = [
('BUILD_LIST', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('LIST_APPEND', 1, 0),
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', get_binop_argval('NB_ADD'), 0),
('LIST_APPEND', 1, 0),
('LOAD_SMALL_INT', 3, 0),
('LIST_APPEND', 1, 0),
('CALL_INTRINSIC_1', INTRINSIC_LIST_TO_TUPLE, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[(1, 2, 3)])
# NOP's in between: (1, 2, 3)
before = [
('BUILD_LIST', 0, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 1, 0),
('NOP', None, 0),
('NOP', None, 0),
('LIST_APPEND', 1, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('NOP', None, 0),
('NOP', None, 0),
('LIST_APPEND', 1, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 3, 0),
('NOP', None, 0),
('LIST_APPEND', 1, 0),
('NOP', None, 0),
('CALL_INTRINSIC_1', INTRINSIC_LIST_TO_TUPLE, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[(1, 2, 3)])
def test_optimize_if_const_list(self):
before = [
('NOP', None, 0),
('LOAD_SMALL_INT', 1, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('NOP', None, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 3, 0),
('NOP', None, 0),
('BUILD_LIST', 3, 0),
('RETURN_VALUE', None, 0),
]
after = [
('BUILD_LIST', 0, 0),
('LOAD_CONST', 0, 0),
('LIST_EXTEND', 1, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[(1, 2, 3)])
# need minimum 3 consts to optimize
same = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_LIST', 2, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(same, same, consts=[])
# not all consts
same = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 3, 0),
('BUILD_LIST', 3, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(same, same, consts=[])
def test_optimize_if_const_set(self):
before = [
('NOP', None, 0),
('LOAD_SMALL_INT', 1, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 2, 0),
('NOP', None, 0),
('NOP', None, 0),
('LOAD_SMALL_INT', 3, 0),
('NOP', None, 0),
('BUILD_SET', 3, 0),
('RETURN_VALUE', None, 0),
]
after = [
('BUILD_SET', 0, 0),
('LOAD_CONST', 0, 0),
('SET_UPDATE', 1, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[frozenset({1, 2, 3})])
# need minimum 3 consts to optimize
same = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_SET', 2, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(same, same, consts=[])
# not all consts
same = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 3, 0),
('BUILD_SET', 3, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(same, same, consts=[])
def test_optimize_literal_list_for_iter(self):
# for _ in [1, 2]: pass ==> for _ in (1, 2): pass
before = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_LIST', 2, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 1, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, (1, 2)])
# for _ in [1, x]: pass ==> for _ in (1, x): pass
before = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 0, 0),
('BUILD_LIST', 2, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 0, 0),
('BUILD_TUPLE', 2, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None])
def test_optimize_literal_set_for_iter(self):
# for _ in {1, 2}: pass ==> for _ in (1, 2): pass
before = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_SET', 2, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 1, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, frozenset({1, 2})])
# non constant literal set is not changed
# for _ in {1, x}: pass ==> for _ in {1, x}: pass
same = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 0, 0),
('BUILD_SET', 2, 0),
('GET_ITER', None, 0),
start := self.Label(),
('FOR_ITER', end := self.Label(), 0),
('STORE_FAST', 0, 0),
('JUMP', start, 0),
end,
('END_FOR', None, 0),
('POP_ITER', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(same, same, consts=[None], expected_consts=[None])
def test_optimize_literal_list_contains(self):
# x in [1, 2] ==> x in (1, 2)
before = [
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_LIST', 2, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_CONST', 1, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, (1, 2)])
# x in [1, y] ==> x in (1, y)
before = [
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 1, 0),
('BUILD_LIST', 2, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 1, 0),
('BUILD_TUPLE', 2, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None])
def test_optimize_literal_set_contains(self):
# x in {1, 2} ==> x in (1, 2)
before = [
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BUILD_SET', 2, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_CONST', 1, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, frozenset({1, 2})])
# non constant literal set is not changed
# x in {1, y} ==> x in {1, y}
same = [
('LOAD_NAME', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('LOAD_NAME', 1, 0),
('BUILD_SET', 2, 0),
('CONTAINS_OP', 0, 0),
('POP_TOP', None, 0),
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(same, same, consts=[None], expected_consts=[None])
def test_optimize_unary_not(self):
# test folding
before = [
('LOAD_SMALL_INT', 1, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 1, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[True, False])
# test cancel out
before = [
('LOAD_NAME', 0, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test eliminate to bool
before = [
('LOAD_NAME', 0, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test folding & cancel out
before = [
('LOAD_SMALL_INT', 1, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[True])
# test folding & eliminate to bool
before = [
('LOAD_SMALL_INT', 1, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_CONST', 1, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[True, False])
# test cancel out & eliminate to bool (to bool stays as we are not iterating to a fixed point)
before = [
('LOAD_NAME', 0, 0),
('TO_BOOL', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
is_ = in_ = 0
isnot = notin = 1
# test is/isnot
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', is_, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', isnot, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test is/isnot cancel out
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', is_, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', is_, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test is/isnot eliminate to bool
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', is_, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', isnot, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test is/isnot cancel out & eliminate to bool
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', is_, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('IS_OP', is_, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test in/notin
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', in_, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', notin, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test in/notin cancel out
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', in_, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', in_, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test is/isnot & eliminate to bool
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', in_, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', notin, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test in/notin cancel out & eliminate to bool
before = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', in_, 0),
('UNARY_NOT', None, 0),
('UNARY_NOT', None, 0),
('TO_BOOL', None, 0),
('RETURN_VALUE', None, 0),
]
after = [
('LOAD_NAME', 0, 0),
('LOAD_NAME', 1, 0),
('CONTAINS_OP', in_, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
def test_optimize_if_const_unaryop(self):
# test unary negative
before = [
('LOAD_SMALL_INT', 2, 0),
('UNARY_NEGATIVE', None, 0),
('UNARY_NEGATIVE', None, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 2, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[-2])
# test unary invert
before = [
('LOAD_SMALL_INT', 2, 0),
('UNARY_INVERT', None, 0),
('UNARY_INVERT', None, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 2, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[-3])
# test unary positive
before = [
('LOAD_SMALL_INT', 2, 0),
('CALL_INTRINSIC_1', 5, 0),
('CALL_INTRINSIC_1', 5, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 2, 0),
('RETURN_VALUE', None, 0),
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
def test_optimize_if_const_binop(self):
add = get_binop_argval('NB_ADD')
sub = get_binop_argval('NB_SUBTRACT')
mul = get_binop_argval('NB_MULTIPLY')
div = get_binop_argval('NB_TRUE_DIVIDE')
floor = get_binop_argval('NB_FLOOR_DIVIDE')
rem = get_binop_argval('NB_REMAINDER')
pow = get_binop_argval('NB_POWER')
lshift = get_binop_argval('NB_LSHIFT')
rshift = get_binop_argval('NB_RSHIFT')
or_ = get_binop_argval('NB_OR')
and_ = get_binop_argval('NB_AND')
xor = get_binop_argval('NB_XOR')
subscr = get_binop_argval('NB_SUBSCR')
# test add
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', add, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', add, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 6, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test sub
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', sub, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', sub, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_CONST', 0, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[-2])
# test mul
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', mul, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', mul, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 8, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test div
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', div, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', div, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_CONST', 1, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[1.0, 0.5])
# test floor
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', floor, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', floor, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 0, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test rem
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', rem, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', rem, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 0, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test pow
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', pow, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', pow, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 16, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test lshift
before = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', lshift, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', lshift, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 4, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test rshift
before = [
('LOAD_SMALL_INT', 4, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', rshift, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', rshift, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 1, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test or
before = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', or_, 0),
('LOAD_SMALL_INT', 4, 0),
('BINARY_OP', or_, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 7, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test and
before = [
('LOAD_SMALL_INT', 1, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', and_, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', and_, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 1, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test xor
before = [
('LOAD_SMALL_INT', 2, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', xor, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', xor, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 2, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[], expected_consts=[])
# test subscr
before = [
('LOAD_CONST', 0, 0),
('LOAD_SMALL_INT', 1, 0),
('BINARY_OP', subscr, 0),
('LOAD_SMALL_INT', 2, 0),
('BINARY_OP', subscr, 0),
('RETURN_VALUE', None, 0)
]
after = [
('LOAD_SMALL_INT', 3, 0),
('RETURN_VALUE', None, 0)
]
self.cfg_optimization_test(before, after, consts=[(1, (1, 2, 3))], expected_consts=[(1, (1, 2, 3))])
def test_conditional_jump_forward_const_condition(self):
# The unreachable branch of the jump is removed, the jump
# becomes redundant and is replaced by a NOP (for the lineno)
insts = [
('LOAD_CONST', 3, 11),
('POP_JUMP_IF_TRUE', lbl := self.Label(), 12),
('LOAD_CONST', 2, 13),
lbl,
('LOAD_CONST', 3, 14),
('RETURN_VALUE', None, 14),
]
expected_insts = [
('NOP', None, 11),
('NOP', None, 12),
('LOAD_SMALL_INT', 3, 14),
('RETURN_VALUE', None, 14),
]
self.cfg_optimization_test(insts,
expected_insts,
consts=[0, 1, 2, 3, 4],
expected_consts=[0])
def test_conditional_jump_backward_non_const_condition(self):
insts = [
lbl1 := self.Label(),
('LOAD_NAME', 1, 11),
('POP_JUMP_IF_TRUE', lbl1, 12),
('LOAD_NAME', 2, 13),
('RETURN_VALUE', None, 13),
]
expected = [
lbl := self.Label(),
('LOAD_NAME', 1, 11),
('POP_JUMP_IF_TRUE', lbl, 12),
('LOAD_NAME', 2, 13),
('RETURN_VALUE', None, 13),
]
self.cfg_optimization_test(insts, expected, consts=list(range(5)))
def test_conditional_jump_backward_const_condition(self):
# The unreachable branch of the jump is removed
insts = [
lbl1 := self.Label(),
('LOAD_CONST', 3, 11),
('POP_JUMP_IF_TRUE', lbl1, 12),
('LOAD_CONST', 2, 13),
('RETURN_VALUE', None, 13),
]
expected_insts = [
lbl := self.Label(),
('NOP', None, 11),
('JUMP', lbl, 12),
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(5)))
def test_except_handler_label(self):
insts = [
('SETUP_FINALLY', handler := self.Label(), 10),
('POP_BLOCK', None, -1),
('LOAD_CONST', 1, 11),
('RETURN_VALUE', None, 11),
handler,
('LOAD_CONST', 2, 12),
('RETURN_VALUE', None, 12),
]
expected_insts = [
('SETUP_FINALLY', handler := self.Label(), 10),
('LOAD_SMALL_INT', 1, 11),
('RETURN_VALUE', None, 11),
handler,
('LOAD_SMALL_INT', 2, 12),
('RETURN_VALUE', None, 12),
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(5)))
def test_no_unsafe_static_swap(self):
# We can't change order of two stores to the same location
insts = [
('LOAD_CONST', 0, 1),
('LOAD_CONST', 1, 2),
('LOAD_CONST', 2, 3),
('SWAP', 3, 4),
('STORE_FAST', 1, 4),
('STORE_FAST', 1, 4),
('POP_TOP', None, 4),
('LOAD_CONST', 0, 5),
('RETURN_VALUE', None, 5)
]
expected_insts = [
('LOAD_SMALL_INT', 0, 1),
('LOAD_SMALL_INT', 1, 2),
('NOP', None, 3),
('STORE_FAST', 1, 4),
('POP_TOP', None, 4),
('LOAD_SMALL_INT', 0, 5),
('RETURN_VALUE', None, 5)
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(3)), nlocals=1)
def test_dead_store_elimination_in_same_lineno(self):
insts = [
('LOAD_CONST', 0, 1),
('LOAD_CONST', 1, 2),
('LOAD_CONST', 2, 3),
('STORE_FAST', 1, 4),
('STORE_FAST', 1, 4),
('STORE_FAST', 1, 4),
('LOAD_CONST', 0, 5),
('RETURN_VALUE', None, 5)
]
expected_insts = [
('LOAD_SMALL_INT', 0, 1),
('LOAD_SMALL_INT', 1, 2),
('NOP', None, 3),
('POP_TOP', None, 4),
('STORE_FAST', 1, 4),
('LOAD_SMALL_INT', 0, 5),
('RETURN_VALUE', None, 5)
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(3)), nlocals=1)
def test_no_dead_store_elimination_in_different_lineno(self):
insts = [
('LOAD_CONST', 0, 1),
('LOAD_CONST', 1, 2),
('LOAD_CONST', 2, 3),
('STORE_FAST', 1, 4),
('STORE_FAST', 1, 5),
('STORE_FAST', 1, 6),
('LOAD_CONST', 0, 5),
('RETURN_VALUE', None, 5)
]
expected_insts = [
('LOAD_SMALL_INT', 0, 1),
('LOAD_SMALL_INT', 1, 2),
('LOAD_SMALL_INT', 2, 3),
('STORE_FAST', 1, 4),
('STORE_FAST', 1, 5),
('STORE_FAST', 1, 6),
('LOAD_SMALL_INT', 0, 5),
('RETURN_VALUE', None, 5)
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(3)), nlocals=1)
def test_unconditional_jump_threading(self):
def get_insts(lno1, lno2, op1, op2):
return [
lbl2 := self.Label(),
('LOAD_NAME', 0, 10),
('POP_TOP', None, 10),
(op1, lbl1 := self.Label(), lno1),
('LOAD_NAME', 1, 20),
lbl1,
(op2, lbl2, lno2),
]
for op1 in ('JUMP', 'JUMP_NO_INTERRUPT'):
for op2 in ('JUMP', 'JUMP_NO_INTERRUPT'):
# different lines
lno1, lno2 = (4, 5)
with self.subTest(lno = (lno1, lno2), ops = (op1, op2)):
insts = get_insts(lno1, lno2, op1, op2)
op = 'JUMP' if 'JUMP' in (op1, op2) else 'JUMP_NO_INTERRUPT'
expected_insts = [
('LOAD_NAME', 0, 10),
('POP_TOP', None, 10),
('NOP', None, 4),
(op, 0, 5),
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(5)))
# Threading
for lno1, lno2 in [(-1, -1), (-1, 5), (6, -1), (7, 7)]:
with self.subTest(lno = (lno1, lno2), ops = (op1, op2)):
insts = get_insts(lno1, lno2, op1, op2)
lno = lno1 if lno1 != -1 else lno2
if lno == -1:
lno = 10 # Propagated from the line before
op = 'JUMP' if 'JUMP' in (op1, op2) else 'JUMP_NO_INTERRUPT'
expected_insts = [
('LOAD_NAME', 0, 10),
('POP_TOP', None, 10),
(op, 0, lno),
]
self.cfg_optimization_test(insts, expected_insts, consts=list(range(5)))
def test_list_to_tuple_get_iter(self):
# for _ in (*foo, *bar) -> for _ in [*foo, *bar]
INTRINSIC_LIST_TO_TUPLE = 6
insts = [
("BUILD_LIST", 0, 1),
("LOAD_FAST", 0, 2),
("LIST_EXTEND", 1, 3),
("LOAD_FAST", 1, 4),
("LIST_EXTEND", 1, 5),
("CALL_INTRINSIC_1", INTRINSIC_LIST_TO_TUPLE, 6),
("GET_ITER", None, 7),
top := self.Label(),
("FOR_ITER", end := self.Label(), 8),
("STORE_FAST", 2, 9),
("JUMP", top, 10),
end,
("END_FOR", None, 11),
("POP_TOP", None, 12),
("LOAD_CONST", 0, 13),
("RETURN_VALUE", None, 14),
]
expected_insts = [
("BUILD_LIST", 0, 1),
("LOAD_FAST_BORROW", 0, 2),
("LIST_EXTEND", 1, 3),
("LOAD_FAST_BORROW", 1, 4),
("LIST_EXTEND", 1, 5),
("NOP", None, 6), # ("CALL_INTRINSIC_1", INTRINSIC_LIST_TO_TUPLE, 6),
("GET_ITER", None, 7),
top := self.Label(),
("FOR_ITER", end := self.Label(), 8),
("STORE_FAST", 2, 9),
("JUMP", top, 10),
end,
("END_FOR", None, 11),
("POP_TOP", None, 12),
("LOAD_CONST", 0, 13),
("RETURN_VALUE", None, 14),
]
self.cfg_optimization_test(insts, expected_insts, consts=[None])
def test_list_to_tuple_get_iter_is_safe(self):
a, b = [], []
for item in (*(items := [0, 1, 2, 3]),):
a.append(item)
b.append(items.pop())
self.assertEqual(a, [0, 1, 2, 3])
self.assertEqual(b, [3, 2, 1, 0])
self.assertEqual(items, [])
class OptimizeLoadFastTestCase(DirectCfgOptimizerTests):
def make_bb(self, insts):
last_loc = insts[-1][2]
maxconst = 0
for op, arg, _ in insts:
if op == "LOAD_CONST":
maxconst = max(maxconst, arg)
consts = [None for _ in range(maxconst + 1)]
return insts + [
("LOAD_CONST", 0, last_loc + 1),
("RETURN_VALUE", None, last_loc + 2),
], consts
def check(self, insts, expected_insts, consts=None):
insts_bb, insts_consts = self.make_bb(insts)
expected_insts_bb, exp_consts = self.make_bb(expected_insts)
self.cfg_optimization_test(insts_bb, expected_insts_bb,
consts=insts_consts, expected_consts=exp_consts)
def test_optimized(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_FAST", 1, 2),
("BINARY_OP", 2, 3),
]
expected = [
("LOAD_FAST_BORROW", 0, 1),
("LOAD_FAST_BORROW", 1, 2),
("BINARY_OP", 2, 3),
]
self.check(insts, expected)
insts = [
("LOAD_FAST", 0, 1),
("LOAD_CONST", 1, 2),
("SWAP", 2, 3),
("POP_TOP", None, 4),
]
expected = [
("LOAD_FAST_BORROW", 0, 1),
("LOAD_CONST", 1, 2),
("SWAP", 2, 3),
("POP_TOP", None, 4),
]
self.check(insts, expected)
def test_unoptimized_if_unconsumed(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_FAST", 1, 2),
("POP_TOP", None, 3),
]
expected = [
("LOAD_FAST", 0, 1),
("LOAD_FAST_BORROW", 1, 2),
("POP_TOP", None, 3),
]
self.check(insts, expected)
insts = [
("LOAD_FAST", 0, 1),
("COPY", 1, 2),
("POP_TOP", None, 3),
]
expected = [
("LOAD_FAST", 0, 1),
("NOP", None, 2),
("NOP", None, 3),
]
self.check(insts, expected)
def test_unoptimized_if_support_killed(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_CONST", 0, 2),
("STORE_FAST", 0, 3),
("POP_TOP", None, 4),
]
self.check(insts, insts)
insts = [
("LOAD_FAST", 0, 1),
("LOAD_CONST", 0, 2),
("LOAD_CONST", 0, 3),
("STORE_FAST_STORE_FAST", ((0 << 4) | 1), 4),
("POP_TOP", None, 5),
]
self.check(insts, insts)
insts = [
("LOAD_FAST", 0, 1),
("DELETE_FAST", 0, 2),
("POP_TOP", None, 3),
]
self.check(insts, insts)
def test_unoptimized_if_aliased(self):
insts = [
("LOAD_FAST", 0, 1),
("STORE_FAST", 1, 2),
]
self.check(insts, insts)
insts = [
("LOAD_FAST", 0, 1),
("LOAD_CONST", 0, 3),
("STORE_FAST_STORE_FAST", ((0 << 4) | 1), 4),
]
self.check(insts, insts)
def test_consume_no_inputs(self):
insts = [
("LOAD_FAST", 0, 1),
("GET_LEN", None, 2),
("STORE_FAST", 1 , 3),
("STORE_FAST", 2, 4),
]
self.check(insts, insts)
def test_consume_some_inputs_no_outputs(self):
insts = [
("LOAD_FAST", 0, 1),
("GET_LEN", None, 2),
("LIST_APPEND", 0, 3),
]
self.check(insts, insts)
def test_check_exc_match(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_FAST", 1, 2),
("CHECK_EXC_MATCH", None, 3)
]
expected = [
("LOAD_FAST", 0, 1),
("LOAD_FAST_BORROW", 1, 2),
("CHECK_EXC_MATCH", None, 3)
]
self.check(insts, expected)
def test_for_iter(self):
insts = [
("LOAD_FAST", 0, 1),
top := self.Label(),
("FOR_ITER", end := self.Label(), 2),
("STORE_FAST", 2, 3),
("JUMP", top, 4),
end,
("END_FOR", None, 5),
("POP_TOP", None, 6),
("LOAD_CONST", 0, 7),
("RETURN_VALUE", None, 8),
]
self.cfg_optimization_test(insts, insts, consts=[None])
def test_load_attr(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_ATTR", 0, 2),
]
expected = [
("LOAD_FAST_BORROW", 0, 1),
("LOAD_ATTR", 0, 2),
]
self.check(insts, expected)
# Method call, leaves self on stack unconsumed
insts = [
("LOAD_FAST", 0, 1),
("LOAD_ATTR", 1, 2),
]
expected = [
("LOAD_FAST", 0, 1),
("LOAD_ATTR", 1, 2),
]
self.check(insts, expected)
def test_super_attr(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_FAST", 1, 2),
("LOAD_FAST", 2, 3),
("LOAD_SUPER_ATTR", 0, 4),
]
expected = [
("LOAD_FAST_BORROW", 0, 1),
("LOAD_FAST_BORROW", 1, 2),
("LOAD_FAST_BORROW", 2, 3),
("LOAD_SUPER_ATTR", 0, 4),
]
self.check(insts, expected)
# Method call, leaves self on stack unconsumed
insts = [
("LOAD_FAST", 0, 1),
("LOAD_FAST", 1, 2),
("LOAD_FAST", 2, 3),
("LOAD_SUPER_ATTR", 1, 4),
]
expected = [
("LOAD_FAST_BORROW", 0, 1),
("LOAD_FAST_BORROW", 1, 2),
("LOAD_FAST", 2, 3),
("LOAD_SUPER_ATTR", 1, 4),
]
self.check(insts, expected)
def test_send(self):
insts = [
("LOAD_FAST", 0, 1),
("LOAD_FAST", 1, 2),
("SEND", end := self.Label(), 3),
("LOAD_CONST", 0, 4),
("RETURN_VALUE", None, 5),
end,
("LOAD_CONST", 0, 6),
("RETURN_VALUE", None, 7)
]
expected = [
("LOAD_FAST", 0, 1),
("LOAD_FAST_BORROW", 1, 2),
("SEND", end := self.Label(), 3),
("LOAD_CONST", 0, 4),
("RETURN_VALUE", None, 5),
end,
("LOAD_CONST", 0, 6),
("RETURN_VALUE", None, 7)
]
self.cfg_optimization_test(insts, expected, consts=[None])
def test_format_simple(self):
# FORMAT_SIMPLE will leave its operand on the stack if it's a unicode
# object. We treat it conservatively and assume that it always leaves
# its operand on the stack.
insts = [
("LOAD_FAST", 0, 1),
("FORMAT_SIMPLE", None, 2),
("STORE_FAST", 1, 3),
]
self.check(insts, insts)
insts = [
("LOAD_FAST", 0, 1),
("FORMAT_SIMPLE", None, 2),
("POP_TOP", None, 3),
]
expected = [
("LOAD_FAST_BORROW", 0, 1),
("FORMAT_SIMPLE", None, 2),
("POP_TOP", None, 3),
]
self.check(insts, expected)
def test_set_function_attribute(self):
# SET_FUNCTION_ATTRIBUTE leaves the function on the stack
insts = [
("LOAD_CONST", 0, 1),
("LOAD_FAST", 0, 2),
("SET_FUNCTION_ATTRIBUTE", 2, 3),
("STORE_FAST", 1, 4),
("LOAD_CONST", 0, 5),
("RETURN_VALUE", None, 6)
]
self.cfg_optimization_test(insts, insts, consts=[None])
insts = [
("LOAD_CONST", 0, 1),
("LOAD_FAST", 0, 2),
("SET_FUNCTION_ATTRIBUTE", 2, 3),
("RETURN_VALUE", None, 4)
]
expected = [
("LOAD_CONST", 0, 1),
("LOAD_FAST_BORROW", 0, 2),
("SET_FUNCTION_ATTRIBUTE", 2, 3),
("RETURN_VALUE", None, 4)
]
self.cfg_optimization_test(insts, expected, consts=[None])
def test_get_yield_from_iter(self):
# GET_YIELD_FROM_ITER may leave its operand on the stack
insts = [
("LOAD_FAST", 0, 1),
("GET_YIELD_FROM_ITER", None, 2),
("LOAD_CONST", 0, 3),
send := self.Label(),
("SEND", end := self.Label(), 5),
("YIELD_VALUE", 1, 6),
("RESUME", 2, 7),
("JUMP", send, 8),
end,
("END_SEND", None, 9),
("LOAD_CONST", 0, 10),
("RETURN_VALUE", None, 11),
]
self.cfg_optimization_test(insts, insts, consts=[None])
def test_push_exc_info(self):
insts = [
("LOAD_FAST", 0, 1),
("PUSH_EXC_INFO", None, 2),
]
self.check(insts, insts)
def test_load_special(self):
# LOAD_SPECIAL may leave self on the stack
insts = [
("LOAD_FAST", 0, 1),
("LOAD_SPECIAL", 0, 2),
("STORE_FAST", 1, 3),
]
self.check(insts, insts)
def test_del_in_finally(self):
# This loads `obj` onto the stack, executes `del obj`, then returns the
# `obj` from the stack. See gh-133371 for more details.
def create_obj():
obj = [42]
try:
return obj
finally:
del obj
obj = create_obj()
# The crash in the linked issue happens while running GC during
# interpreter finalization, so run it here manually.
gc.collect()
self.assertEqual(obj, [42])
def test_format_simple_unicode(self):
# Repro from gh-134889
def f():
var = f"{1}"
var = f"{var}"
return var
self.assertEqual(f(), "1")
if __name__ == "__main__":
unittest.main()
|