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 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2025 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "astutils.h"
#include "config.h"
#include "errortypes.h"
#include "findtoken.h"
#include "infer.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "utils.h"
#include "valueflow.h"
#include "valueptr.h"
#include "vfvalue.h"
#include "checkclass.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <list>
#include <set>
#include <type_traits>
#include <unordered_map>
#include <utility>
const Token* findExpression(const nonneg int exprid,
const Token* start,
const Token* end,
const std::function<bool(const Token*)>& pred)
{
if (exprid == 0)
return nullptr;
if (!precedes(start, end))
return nullptr;
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (tok->exprId() != exprid)
continue;
if (pred(tok))
return tok;
}
return nullptr;
}
static int findArgumentPosRecursive(const Token* tok, const Token* tokToFind, bool &found, nonneg int depth=0)
{
++depth;
if (!tok || depth >= 100)
return -1;
if (tok->str() == ",") {
int res = findArgumentPosRecursive(tok->astOperand1(), tokToFind, found, depth);
if (res == -1)
return -1;
if (found)
return res;
const int argn = res;
res = findArgumentPosRecursive(tok->astOperand2(), tokToFind, found, depth);
if (res == -1)
return -1;
return argn + res;
}
if (tokToFind == tok)
found = true;
return 1;
}
static int findArgumentPos(const Token* tok, const Token* tokToFind){
bool found = false;
const int argn = findArgumentPosRecursive(tok, tokToFind, found, 0);
if (found)
return argn - 1;
return -1;
}
static int getArgumentPos(const Token* ftok, const Token* tokToFind){
const Token* tok = ftok;
if (Token::Match(tok, "%name% (|{"))
tok = ftok->next();
if (!Token::Match(tok, "(|{|["))
return -1;
const Token* startTok = tok->astOperand2();
if (!startTok && tok->next() != tok->link())
startTok = tok->astOperand1();
return findArgumentPos(startTok, tokToFind);
}
template<class T, class OuputIterator, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static void astFlattenCopy(T* tok, const char* op, OuputIterator out, nonneg int depth = 100)
{
--depth;
if (!tok || depth < 0)
return;
if (strcmp(tok->str().c_str(), op) == 0) {
astFlattenCopy(tok->astOperand1(), op, out, depth);
astFlattenCopy(tok->astOperand2(), op, out, depth);
} else {
*out = tok;
++out;
}
}
std::vector<const Token*> astFlatten(const Token* tok, const char* op)
{
std::vector<const Token*> result;
astFlattenCopy(tok, op, std::back_inserter(result));
return result;
}
std::vector<Token*> astFlatten(Token* tok, const char* op)
{
std::vector<Token*> result;
astFlattenCopy(tok, op, std::back_inserter(result));
return result;
}
nonneg int astCount(const Token* tok, const char* op, int depth)
{
--depth;
if (!tok || depth < 0)
return 0;
if (strcmp(tok->str().c_str(), op) == 0)
return astCount(tok->astOperand1(), op, depth) + astCount(tok->astOperand2(), op, depth);
return 1;
}
bool astHasToken(const Token* root, const Token * tok)
{
if (!root)
return false;
while (tok->astParent() && tok != root)
tok = tok->astParent();
return root == tok;
}
bool astHasVar(const Token * tok, nonneg int varid)
{
if (!tok)
return false;
if (tok->varId() == varid)
return true;
return astHasVar(tok->astOperand1(), varid) || astHasVar(tok->astOperand2(), varid);
}
bool astHasExpr(const Token* tok, nonneg int exprid)
{
if (!tok)
return false;
if (tok->exprId() == exprid)
return true;
return astHasExpr(tok->astOperand1(), exprid) || astHasExpr(tok->astOperand2(), exprid);
}
static bool astIsCharWithSign(const Token *tok, ValueType::Sign sign)
{
if (!tok)
return false;
const ValueType *valueType = tok->valueType();
if (!valueType)
return false;
return valueType->type == ValueType::Type::CHAR && valueType->pointer == 0U && valueType->sign == sign;
}
bool astIsSignedChar(const Token *tok)
{
return astIsCharWithSign(tok, ValueType::Sign::SIGNED);
}
bool astIsUnknownSignChar(const Token *tok)
{
return astIsCharWithSign(tok, ValueType::Sign::UNKNOWN_SIGN);
}
bool astIsGenericChar(const Token* tok)
{
return !astIsPointer(tok) && tok && tok->valueType() && (tok->valueType()->type == ValueType::Type::CHAR || tok->valueType()->type == ValueType::Type::WCHAR_T);
}
bool astIsPrimitive(const Token* tok)
{
const ValueType* vt = tok ? tok->valueType() : nullptr;
if (!vt)
return false;
return vt->isPrimitive();
}
bool astIsIntegral(const Token *tok, bool unknown)
{
const ValueType *vt = tok ? tok->valueType() : nullptr;
if (!vt)
return unknown;
return vt->isIntegral() && vt->pointer == 0U;
}
bool astIsUnsigned(const Token* tok)
{
return tok && tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED;
}
bool astIsFloat(const Token *tok, bool unknown)
{
const ValueType *vt = tok ? tok->valueType() : nullptr;
if (!vt)
return unknown;
return vt->type >= ValueType::Type::FLOAT && vt->pointer == 0U;
}
bool astIsBool(const Token *tok)
{
return tok && (tok->isBoolean() || (tok->valueType() && tok->valueType()->type == ValueType::Type::BOOL && !tok->valueType()->pointer));
}
bool astIsPointer(const Token *tok)
{
return tok && tok->valueType() && tok->valueType()->pointer;
}
bool astIsSmartPointer(const Token* tok)
{
return tok && tok->valueType() && tok->valueType()->smartPointerTypeToken;
}
bool astIsUniqueSmartPointer(const Token* tok)
{
if (!astIsSmartPointer(tok))
return false;
if (!tok->valueType()->smartPointer)
return false;
return tok->valueType()->smartPointer->unique;
}
bool astIsIterator(const Token *tok)
{
return tok && tok->valueType() && tok->valueType()->type == ValueType::Type::ITERATOR;
}
bool astIsContainer(const Token* tok) {
return getLibraryContainer(tok) != nullptr && !astIsIterator(tok);
}
bool astIsNonStringContainer(const Token* tok)
{
const Library::Container* container = getLibraryContainer(tok);
return container && !container->stdStringLike && !astIsIterator(tok);
}
bool astIsContainerView(const Token* tok)
{
const Library::Container* container = getLibraryContainer(tok);
return container && !astIsIterator(tok) && container->view;
}
bool astIsContainerOwned(const Token* tok) {
return astIsContainer(tok) && !astIsContainerView(tok);
}
bool astIsContainerString(const Token* tok)
{
if (!tok)
return false;
if (!tok->valueType())
return false;
const Library::Container* container = tok->valueType()->container;
if (!container)
return false;
return container->stdStringLike;
}
static std::pair<const Token*, const Library::Container*> getContainerFunction(const Token* tok, const Settings* settings)
{
const Library::Container* cont{};
if (!tok || !tok->valueType() || (!tok->valueType()->container && (!settings || !(cont = settings->library.detectContainerOrIterator(tok->valueType()->smartPointerTypeToken)))))
return {};
const Token* parent = tok->astParent();
if (Token::Match(parent, ". %name% (") && astIsLHS(tok)) {
return { parent->next(), cont ? cont : tok->valueType()->container };
}
return {};
}
Library::Container::Action astContainerAction(const Token* tok, const Token** ftok, const Settings* settings)
{
const auto ftokCont = getContainerFunction(tok, settings);
if (ftok)
*ftok = ftokCont.first;
if (!ftokCont.first)
return Library::Container::Action::NO_ACTION;
return ftokCont.second->getAction(ftokCont.first->str());
}
Library::Container::Yield astContainerYield(const Token* tok, const Token** ftok, const Settings* settings)
{
const auto ftokCont = getContainerFunction(tok, settings);
if (ftok)
*ftok = ftokCont.first;
if (!ftokCont.first)
return Library::Container::Yield::NO_YIELD;
return ftokCont.second->getYield(ftokCont.first->str());
}
Library::Container::Yield astFunctionYield(const Token* tok, const Settings& settings, const Token** ftok)
{
if (!tok)
return Library::Container::Yield::NO_YIELD;
const auto* function = settings.library.getFunction(tok);
if (!function)
return Library::Container::Yield::NO_YIELD;
if (ftok)
*ftok = tok;
return function->containerYield;
}
bool astIsRangeBasedForDecl(const Token* tok)
{
return Token::simpleMatch(tok->astParent(), ":") && Token::simpleMatch(tok->astParent()->astParent(), "(");
}
std::string astCanonicalType(const Token *expr, bool pointedToType)
{
if (!expr)
return "";
std::pair<const Token*, const Token*> decl = Token::typeDecl(expr, pointedToType);
if (decl.first && decl.second) {
std::string ret;
for (const Token *type = decl.first; Token::Match(type,"%name%|::") && type != decl.second; type = type->next()) {
if (!Token::Match(type, "const|static"))
ret += type->str();
}
return ret;
}
return "";
}
static bool match(const Token *tok, const std::string &rhs)
{
if (tok->str() == rhs)
return true;
if (!tok->varId() && tok->hasKnownIntValue() && MathLib::toString(tok->values().front().intvalue) == rhs)
return true;
return false;
}
const Token * astIsVariableComparison(const Token *tok, const std::string &comp, const std::string &rhs, const Token **vartok)
{
if (!tok)
return nullptr;
const Token *ret = nullptr;
if (tok->isComparisonOp()) {
if (tok->astOperand1() && match(tok->astOperand1(), rhs)) {
// Invert comparator
std::string s = tok->str();
if (s[0] == '>')
s[0] = '<';
else if (s[0] == '<')
s[0] = '>';
if (s == comp) {
ret = tok->astOperand2();
}
} else if (tok->str() == comp && tok->astOperand2() && match(tok->astOperand2(), rhs)) {
ret = tok->astOperand1();
}
} else if (comp == "!=" && rhs == "0") {
if (tok->str() == "!") {
ret = tok->astOperand1();
// handle (!(x==0)) as (x!=0)
astIsVariableComparison(ret, "==", "0", &ret);
} else
ret = tok;
} else if (comp == "==" && rhs == "0") {
if (tok->str() == "!") {
ret = tok->astOperand1();
// handle (!(x!=0)) as (x==0)
astIsVariableComparison(ret, "!=", "0", &ret);
}
}
while (ret && ret->str() == ".")
ret = ret->astOperand2();
if (ret && ret->str() == "=" && ret->astOperand1() && ret->astOperand1()->varId())
ret = ret->astOperand1();
else if (ret && ret->varId() == 0U)
ret = nullptr;
if (vartok)
*vartok = ret;
return ret;
}
bool isVariableDecl(const Token* tok)
{
if (!tok)
return false;
const Variable* var = tok->variable();
if (!var)
return false;
if (var->nameToken() == tok)
return true;
const Token * const varDeclEndToken = var->declEndToken();
return Token::Match(varDeclEndToken, "; %var%") && varDeclEndToken->next() == tok;
}
bool isStlStringType(const Token* tok)
{
return Token::Match(tok, "std :: string|wstring|u16string|u32string !!::") ||
(Token::simpleMatch(tok, "std :: basic_string <") && !Token::simpleMatch(tok->linkAt(3), "> ::"));
}
bool isTemporary(const Token* tok, const Library* library, bool unknown)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, "."))
return (tok->originalName() != "->" && isTemporary(tok->astOperand1(), library)) ||
isTemporary(tok->astOperand2(), library);
if (Token::Match(tok, ",|::"))
return isTemporary(tok->astOperand2(), library);
if (tok->isCast() || (tok->isCpp() && isCPPCast(tok)))
return isTemporary(tok->astOperand2(), library);
if (Token::Match(tok, ".|[|++|--|%name%|%assign%"))
return false;
if (tok->isUnaryOp("*"))
return false;
if (Token::Match(tok, "&|<<|>>") && isLikelyStream(tok->astOperand1()))
return false;
if (Token::simpleMatch(tok, "?")) {
const Token* branchTok = tok->astOperand2();
if (!branchTok->astOperand1() || !branchTok->astOperand1()->valueType())
return false;
if (!branchTok->astOperand2()->valueType())
return false;
return !branchTok->astOperand1()->valueType()->isTypeEqual(branchTok->astOperand2()->valueType());
}
if (Token::simpleMatch(tok, "(") && tok->astOperand1() &&
(tok->astOperand2() || Token::simpleMatch(tok->next(), ")"))) {
if (Token::simpleMatch(tok->astOperand1(), "typeid"))
return false;
if (tok->valueType()) {
if (tok->valueType()->pointer > 0) {
const Token* const parent = tok->astParent();
if (Token::simpleMatch(parent, "&"))
return true;
if (Token::simpleMatch(parent, "return") && parent->valueType()->reference != Reference::None &&
parent->valueType()->container && parent->valueType()->container->stdStringLike)
return true;
}
return tok->valueType()->reference == Reference::None && tok->valueType()->pointer == 0;
}
const Token* ftok = nullptr;
if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1))
ftok = tok->linkAt(-1)->previous();
else
ftok = tok->previous();
if (!ftok)
return false;
if (const Function * f = ftok->function())
return !Function::returnsReference(f, true);
if (ftok->type())
return true;
if (library) {
const std::string& returnType = library->returnValueType(ftok);
return !returnType.empty() && returnType.back() != '&';
}
return unknown;
}
if (tok->isCast())
return false;
// Currying a function is unknown in cppcheck
if (Token::simpleMatch(tok, "(") && Token::simpleMatch(tok->astOperand1(), "("))
return unknown;
if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->astParent(), "return") && tok->astOperand1() &&
!tok->astOperand2())
return isTemporary(tok->astOperand1(), library);
return true;
}
static bool isFunctionCall(const Token* tok)
{
if (Token::Match(tok, "%name% ("))
return true;
if (Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> ("))
return true;
if (Token::Match(tok, "%name% ::"))
return isFunctionCall(tok->tokAt(2));
return false;
}
static bool hasToken(const Token * startTok, const Token * stopTok, const Token * tok)
{
for (const Token * tok2 = startTok; tok2 != stopTok; tok2 = tok2->next()) {
if (tok2 == tok)
return true;
}
return false;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* previousBeforeAstLeftmostLeafGeneric(T* tok)
{
if (!tok)
return nullptr;
T* leftmostLeaf = tok;
while (leftmostLeaf->astOperand1())
leftmostLeaf = leftmostLeaf->astOperand1();
return leftmostLeaf->previous();
}
const Token* previousBeforeAstLeftmostLeaf(const Token* tok)
{
return previousBeforeAstLeftmostLeafGeneric(tok);
}
Token* previousBeforeAstLeftmostLeaf(Token* tok)
{
return previousBeforeAstLeftmostLeafGeneric(tok);
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* nextAfterAstRightmostLeafGeneric(T* tok)
{
T * rightmostLeaf = tok;
if (!rightmostLeaf || !rightmostLeaf->astOperand1())
return nullptr;
do {
if (T* lam = findLambdaEndToken(rightmostLeaf)) {
rightmostLeaf = lam;
break;
}
if (rightmostLeaf->astOperand2() && precedes(rightmostLeaf, rightmostLeaf->astOperand2()))
rightmostLeaf = rightmostLeaf->astOperand2();
else if (rightmostLeaf->astOperand1() && precedes(rightmostLeaf, rightmostLeaf->astOperand1()))
rightmostLeaf = rightmostLeaf->astOperand1();
else
break;
} while (rightmostLeaf->astOperand1() || rightmostLeaf->astOperand2());
while (Token::Match(rightmostLeaf->next(), "]|)") && !hasToken(rightmostLeaf->linkAt(1), rightmostLeaf->next(), tok))
rightmostLeaf = rightmostLeaf->next();
if (Token::Match(rightmostLeaf, "{|(|[") && rightmostLeaf->link())
rightmostLeaf = rightmostLeaf->link();
return rightmostLeaf->next();
}
const Token* nextAfterAstRightmostLeaf(const Token* tok)
{
return nextAfterAstRightmostLeafGeneric(tok);
}
Token* nextAfterAstRightmostLeaf(Token* tok)
{
return nextAfterAstRightmostLeafGeneric(tok);
}
const Token* astParentSkipParens(const Token* tok)
{
return astParentSkipParens(const_cast<Token*>(tok));
}
Token* astParentSkipParens(Token* tok)
{
if (!tok)
return nullptr;
Token * parent = tok->astParent();
if (!Token::simpleMatch(parent, "("))
return parent;
if (parent->link() != nextAfterAstRightmostLeaf(tok))
return parent;
if (Token::Match(parent->previous(), "%name% (") ||
(Token::simpleMatch(parent->previous(), "> (") && parent->linkAt(-1)))
return parent;
return astParentSkipParens(parent);
}
const Token* getParentMember(const Token * tok)
{
if (!tok)
return tok;
const Token * parent = tok->astParent();
if (!Token::simpleMatch(parent, "."))
return tok;
if (astIsRHS(tok)) {
if (Token::simpleMatch(parent->astOperand1(), "."))
return parent->astOperand1()->astOperand2();
return parent->astOperand1();
}
const Token * gparent = parent->astParent();
if (!Token::simpleMatch(gparent, ".") || gparent->astOperand2() != parent)
return tok;
if (gparent->astOperand1())
return gparent->astOperand1();
return tok;
}
const Token* getParentLifetime(const Token* tok)
{
if (!tok)
return tok;
// Skipping checking for variable if its a pointer-to-member
if (!Token::simpleMatch(tok->previous(), ". *")) {
const Variable* var = tok->variable();
// TODO: Call getLifetimeVariable for deeper analysis
if (!var)
return tok;
if (var->isLocal() || var->isArgument())
return tok;
}
const Token* parent = getParentMember(tok);
if (parent != tok)
return getParentLifetime(parent);
return tok;
}
static std::vector<const Token*> getParentMembers(const Token* tok)
{
if (!tok)
return {};
if (!Token::simpleMatch(tok->astParent(), "."))
return {tok};
const Token* parent = tok->astParent();
while (Token::simpleMatch(parent->astParent(), "."))
parent = parent->astParent();
std::vector<const Token*> result;
for (const Token* tok2 : astFlatten(parent, ".")) {
if (Token::simpleMatch(tok2, "(") && Token::simpleMatch(tok2->astOperand1(), ".")) {
std::vector<const Token*> sub = getParentMembers(tok2->astOperand1());
result.insert(result.end(), sub.cbegin(), sub.cend());
}
result.push_back(tok2);
}
return result;
}
static const Token* getParentLifetimeObject(const Token* tok)
{
while (Token::simpleMatch(tok, "["))
tok = tok->astOperand1();
return tok;
}
const Token* getParentLifetime(const Token* tok, const Library& library)
{
std::vector<const Token*> members = getParentMembers(tok);
if (members.size() < 2)
return tok;
// Find the first local variable, temporary, or array
auto it = std::find_if(members.crbegin(), members.crend(), [&](const Token* tok2) {
const Variable* var = tok2->variable();
if (var)
return var->isLocal() || var->isArgument();
if (Token::simpleMatch(tok2, "["))
return true;
return isTemporary(tok2, &library);
});
if (it == members.rend())
return tok;
// If any of the submembers are borrowed types then stop
if (std::any_of(it.base() - 1, members.cend() - 1, [&](const Token* tok2) {
const Token* obj = getParentLifetimeObject(tok2);
if (!obj)
return false;
const Variable* var = obj->variable();
// Check for arrays first since astIsPointer will return true, but an array is not a borrowed type
if (var && var->isArray())
return false;
if (astIsPointer(obj) || astIsContainerView(obj) || astIsIterator(obj))
return true;
if (!astIsUniqueSmartPointer(obj)) {
if (astIsSmartPointer(obj))
return true;
const Token* dotTok = obj->next();
if (!Token::simpleMatch(dotTok, ".")) {
const Token* endTok = nextAfterAstRightmostLeaf(obj);
if (!endTok)
dotTok = obj->next();
else if (Token::simpleMatch(endTok, "."))
dotTok = endTok;
else if (Token::simpleMatch(endTok->next(), "."))
dotTok = endTok->next();
}
// If we are dereferencing the member variable then treat it as borrowed
if (Token::simpleMatch(dotTok, ".") && dotTok->originalName() == "->")
return true;
}
return var && var->isReference();
}))
return nullptr;
const Token* result = getParentLifetimeObject(*it);
if (result != *it)
return getParentLifetime(result);
return result;
}
static bool isInConstructorList(const Token* tok)
{
if (!tok)
return false;
if (!astIsRHS(tok))
return false;
const Token* parent = tok->astParent();
if (!Token::Match(parent, "{|("))
return false;
if (!Token::Match(parent->previous(), "%var% {|("))
return false;
if (!parent->astOperand1() || !parent->astOperand2())
return false;
do {
parent = parent->astParent();
} while (Token::simpleMatch(parent, ","));
return Token::simpleMatch(parent, ":") && !Token::simpleMatch(parent->astParent(), "?");
}
std::vector<ValueType> getParentValueTypes(const Token* tok, const Settings& settings, const Token** parent)
{
if (!tok)
return {};
if (!tok->astParent())
return {};
if (isInConstructorList(tok)) {
if (parent)
*parent = tok->astParent()->astOperand1();
if (tok->astParent()->astOperand1()->valueType())
return {*tok->astParent()->astOperand1()->valueType()};
return {};
}
const Token* ftok = nullptr;
if (Token::Match(tok->astParent(), "(|{|,")) {
int argn = -1;
ftok = getTokenArgumentFunction(tok, argn);
const Token* typeTok = nullptr;
if (ftok && argn >= 0) {
if (ftok->function()) {
std::vector<ValueType> result;
const Token* nameTok = nullptr;
for (const Variable* var : getArgumentVars(ftok, argn)) {
if (!var)
continue;
if (!var->valueType())
continue;
nameTok = var->nameToken();
result.push_back(*var->valueType());
if (var->isArray())
result.back().pointer += var->dimensions().size();
}
if (result.size() == 1 && nameTok && parent) {
*parent = nameTok;
}
return result;
}
if (const Type* t = Token::typeOf(ftok, &typeTok)) {
if (astIsPointer(typeTok))
return {*typeTok->valueType()};
const Scope* scope = t->classScope;
// Check for aggregate constructors
if (scope && scope->numConstructors == 0 && t->derivedFrom.empty() &&
(t->isClassType() || t->isStructType()) && numberOfArguments(ftok) <= scope->varlist.size() &&
!scope->varlist.empty()) {
assert(argn < scope->varlist.size());
auto it = std::next(scope->varlist.cbegin(), argn);
if (it->valueType())
return {*it->valueType()};
}
}
}
}
if (Token::Match(tok->astParent()->tokAt(-2), ". push_back|push_front|insert|push (") &&
astIsContainer(tok->astParent()->tokAt(-2)->astOperand1())) {
const Token* contTok = tok->astParent()->tokAt(-2)->astOperand1();
const ValueType* vtCont = contTok->valueType();
if (!vtCont->containerTypeToken)
return {};
ValueType vtParent = ValueType::parseDecl(vtCont->containerTypeToken, settings);
return {std::move(vtParent)};
}
// The return type of a function is not the parent valuetype
if (Token::simpleMatch(tok->astParent(), "(") && ftok && !tok->astParent()->isCast() &&
ftok->tokType() != Token::eType)
return {};
if (parent && Token::Match(tok->astParent(), "return|(|{|%assign%")) {
*parent = tok->astParent();
}
if (tok->astParent()->valueType())
return {*tok->astParent()->valueType()};
return {};
}
bool astIsLHS(const Token* tok)
{
if (!tok)
return false;
const Token* parent = tok->astParent();
if (!parent)
return false;
if (!parent->astOperand1())
return false;
if (!parent->astOperand2())
return false;
return parent->astOperand1() == tok;
}
bool astIsRHS(const Token* tok)
{
if (!tok)
return false;
const Token* parent = tok->astParent();
if (!parent)
return false;
if (!parent->astOperand1())
return false;
if (!parent->astOperand2())
return false;
return parent->astOperand2() == tok;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getCondTokImpl(T* tok)
{
if (!tok)
return nullptr;
if (Token::simpleMatch(tok, "("))
return getCondTok(tok->previous());
if (Token::simpleMatch(tok, "do {")) {
T* endTok = tok->linkAt(1);
if (Token::simpleMatch(endTok, "} while ("))
return endTok->tokAt(2)->astOperand2();
}
if (Token::simpleMatch(tok, "for") && Token::simpleMatch(tok->next()->astOperand2(), ";") &&
tok->next()->astOperand2()->astOperand2())
return tok->next()->astOperand2()->astOperand2()->astOperand1();
if (Token::simpleMatch(tok->next()->astOperand2(), ";"))
return tok->next()->astOperand2()->astOperand1();
if (tok->isName() && !tok->isControlFlowKeyword())
return nullptr;
return tok->next()->astOperand2();
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getCondTokFromEndImpl(T* endBlock)
{
if (!Token::simpleMatch(endBlock, "}"))
return nullptr;
T* startBlock = endBlock->link();
if (!Token::simpleMatch(startBlock, "{"))
return nullptr;
if (Token::simpleMatch(startBlock->previous(), "do"))
return getCondTok(startBlock->previous());
if (Token::simpleMatch(startBlock->previous(), ")"))
return getCondTok(startBlock->linkAt(-1));
if (Token::simpleMatch(startBlock->tokAt(-2), "} else {"))
return getCondTokFromEnd(startBlock->tokAt(-2));
return nullptr;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getInitTokImpl(T* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok, "%name% ("))
return getInitTokImpl(tok->next());
if (tok->str() != "(")
return nullptr;
if (!Token::simpleMatch(tok->astOperand2(), ";"))
return nullptr;
if (Token::simpleMatch(tok->astOperand2()->astOperand1(), ";"))
return nullptr;
return tok->astOperand2()->astOperand1();
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getStepTokImpl(T* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok, "%name% ("))
return getStepTokImpl(tok->next());
if (tok->str() != "(")
return nullptr;
if (!Token::simpleMatch(tok->astOperand2(), ";"))
return nullptr;
if (!Token::simpleMatch(tok->astOperand2()->astOperand2(), ";"))
return nullptr;
return tok->astOperand2()->astOperand2()->astOperand2();
}
Token* getCondTok(Token* tok)
{
return getCondTokImpl(tok);
}
const Token* getCondTok(const Token* tok)
{
return getCondTokImpl(tok);
}
Token* getCondTokFromEnd(Token* endBlock)
{
return getCondTokFromEndImpl(endBlock);
}
const Token* getCondTokFromEnd(const Token* endBlock)
{
return getCondTokFromEndImpl(endBlock);
}
Token* getInitTok(Token* tok) {
return getInitTokImpl(tok);
}
const Token* getInitTok(const Token* tok) {
return getInitTokImpl(tok);
}
Token* getStepTok(Token* tok) {
return getStepTokImpl(tok);
}
const Token* getStepTok(const Token* tok) {
return getStepTokImpl(tok);
}
const Token *findNextTokenFromBreak(const Token *breakToken)
{
const Scope *scope = breakToken->scope();
while (scope) {
if (scope->isLoopScope() || scope->type == Scope::ScopeType::eSwitch) {
if (scope->type == Scope::ScopeType::eDo && Token::simpleMatch(scope->bodyEnd, "} while ("))
return scope->bodyEnd->linkAt(2)->next();
return scope->bodyEnd;
}
scope = scope->nestedIn;
}
return nullptr;
}
bool extractForLoopValues(const Token *forToken,
nonneg int &varid,
bool &knownInitValue,
MathLib::bigint &initValue,
bool &partialCond,
MathLib::bigint &stepValue,
MathLib::bigint &lastValue)
{
if (!Token::simpleMatch(forToken, "for (") || !Token::simpleMatch(forToken->next()->astOperand2(), ";"))
return false;
const Token *initExpr = forToken->next()->astOperand2()->astOperand1();
const Token *condExpr = forToken->next()->astOperand2()->astOperand2()->astOperand1();
const Token *incExpr = forToken->next()->astOperand2()->astOperand2()->astOperand2();
if (!initExpr || !initExpr->isBinaryOp() || initExpr->str() != "=" || !Token::Match(initExpr->astOperand1(), "%var%"))
return false;
std::vector<MathLib::bigint> minInitValue =
getMinValue(makeIntegralInferModel(), initExpr->astOperand2()->values());
if (minInitValue.empty()) {
const ValueFlow::Value* v = initExpr->astOperand2()->getMinValue(true);
if (v)
minInitValue.push_back(v->intvalue);
}
if (minInitValue.empty())
return false;
varid = initExpr->astOperand1()->varId();
knownInitValue = initExpr->astOperand2()->hasKnownIntValue();
initValue = minInitValue.front();
partialCond = Token::Match(condExpr, "%oror%|&&");
visitAstNodes(condExpr, [varid, &condExpr](const Token *tok) {
if (Token::Match(tok, "%oror%|&&"))
return ChildrenToVisit::op1_and_op2;
if (Token::Match(tok, "<|<=") && tok->isBinaryOp() && tok->astOperand1()->varId() == varid && tok->astOperand2()->hasKnownIntValue()) {
if (Token::Match(condExpr, "%oror%|&&") || tok->astOperand2()->getKnownIntValue() < condExpr->astOperand2()->getKnownIntValue())
condExpr = tok;
}
return ChildrenToVisit::none;
});
if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != varid || !condExpr->astOperand2()->hasKnownIntValue())
return false;
if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != varid)
return false;
stepValue = 1;
if (condExpr->str() == "<")
lastValue = condExpr->astOperand2()->getKnownIntValue() - 1;
else
lastValue = condExpr->astOperand2()->getKnownIntValue();
return true;
}
static const Token * getVariableInitExpression(const Variable * var)
{
if (!var)
return nullptr;
const Token *varDeclEndToken = var->declEndToken();
if (!varDeclEndToken)
return nullptr;
if (Token::Match(varDeclEndToken, "; %varid% =", var->declarationId()))
return varDeclEndToken->tokAt(2)->astOperand2();
return varDeclEndToken->astOperand2();
}
const Token* isInLoopCondition(const Token* tok)
{
const Token* top = tok->astTop();
return Token::Match(top->previous(), "for|while (") ? top : nullptr;
}
/// If tok2 comes after tok1
bool precedes(const Token * tok1, const Token * tok2)
{
if (tok1 == tok2)
return false;
if (!tok1)
return false;
if (!tok2)
return true;
return tok1->index() < tok2->index();
}
/// If tok1 comes after tok2
bool succeeds(const Token* tok1, const Token* tok2)
{
if (tok1 == tok2)
return false;
if (!tok1)
return false;
if (!tok2)
return true;
return tok1->index() > tok2->index();
}
bool isAliasOf(const Token *tok, nonneg int varid, bool* inconclusive)
{
if (tok->varId() == varid)
return false;
// NOLINTNEXTLINE(readability-use-anyofallof) - TODO: fix this / also Cppcheck false negative
for (const ValueFlow::Value &val : tok->values()) {
if (!val.isLocalLifetimeValue())
continue;
if (val.tokvalue->varId() == varid) {
if (val.isInconclusive()) {
if (inconclusive)
*inconclusive = true;
else
continue;
}
return true;
}
}
return false;
}
bool isAliasOf(const Token* tok, const Token* expr, int* indirect)
{
const Token* r = nullptr;
if (indirect)
*indirect = 1;
for (const ReferenceToken& ref : followAllReferences(tok)) {
const bool pointer = astIsPointer(ref.token);
r = findAstNode(expr, [&](const Token* childTok) {
if (childTok->exprId() == 0)
return false;
if (ref.token != tok && expr->exprId() == childTok->exprId()) {
if (indirect)
*indirect = 0;
return true;
}
for (const ValueFlow::Value& val : ref.token->values()) {
if (val.isImpossible())
continue;
if (val.isLocalLifetimeValue() || (pointer && val.isSymbolicValue() && val.intvalue == 0)) {
if (findAstNode(val.tokvalue,
[&](const Token* aliasTok) {
return aliasTok != childTok && aliasTok->exprId() == childTok->exprId();
})) {
return true;
}
}
}
return false;
});
if (r)
break;
}
return r;
}
static bool isAliased(const Token *startTok, const Token *endTok, nonneg int varid)
{
if (!precedes(startTok, endTok))
return false;
for (const Token *tok = startTok; tok != endTok; tok = tok->next()) {
if (Token::Match(tok, "= & %varid% ;", varid))
return true;
if (isAliasOf(tok, varid))
return true;
}
return false;
}
bool exprDependsOnThis(const Token* expr, bool onVar, nonneg int depth)
{
if (!expr)
return false;
if (expr->str() == "this")
return true;
if (depth >= 1000)
// Abort recursion to avoid stack overflow
return true;
++depth;
// calling nonstatic method?
if (Token::Match(expr, "%name% (")) {
if (expr->function() && expr->function()->nestedIn && expr->function()->nestedIn->isClassOrStruct() && !expr->function()->isStatic()) {
// is it a method of this?
const Scope* fScope = expr->scope();
while (!fScope->functionOf && fScope->nestedIn)
fScope = fScope->nestedIn;
const Scope* classScope = fScope->functionOf;
if (classScope && classScope->function)
classScope = classScope->function->token->scope();
if (classScope && classScope->isClassOrStruct())
return contains(classScope->findAssociatedScopes(), expr->function()->nestedIn);
return false;
}
if (expr->isOperatorKeyword() && !Token::simpleMatch(expr->next()->astParent(), "."))
return true;
}
if (onVar && expr->variable()) {
const Variable* var = expr->variable();
return ((var->isPrivate() || var->isPublic() || var->isProtected()) && !var->isStatic());
}
if (Token::simpleMatch(expr, "."))
return exprDependsOnThis(expr->astOperand1(), onVar, depth);
return exprDependsOnThis(expr->astOperand1(), onVar, depth) || exprDependsOnThis(expr->astOperand2(), onVar, depth);
}
static bool hasUnknownVars(const Token* startTok)
{
bool result = false;
visitAstNodes(startTok, [&](const Token* tok) {
if (tok->varId() > 0 && !tok->variable()) {
result = true;
return ChildrenToVisit::done;
}
return ChildrenToVisit::op1_and_op2;
});
return result;
}
bool isStructuredBindingVariable(const Variable* var)
{
if (!var)
return false;
const Token* tok = var->nameToken();
while (tok && Token::Match(tok->astParent(), "[|,|:"))
tok = tok->astParent();
return tok && (tok->str() == "[" || Token::simpleMatch(tok->previous(), "] :")); // TODO: remove workaround when #11105 is fixed
}
/// This takes a token that refers to a variable and it will return the token
/// to the expression that the variable is assigned to. If its not valid to
/// make such substitution then it will return the original token.
static const Token * followVariableExpression(const Settings& settings, const Token * tok, const Token * end = nullptr)
{
if (!tok)
return tok;
// Skip following variables that is across multiple files
if (end && end->fileIndex() != tok->fileIndex())
return tok;
// Skip array access
if (Token::Match(tok, "%var% ["))
return tok;
// Skip pointer indirection
if (tok->astParent() && tok->isUnaryOp("*"))
return tok;
// Skip following variables if it is used in an assignment
if (Token::Match(tok->next(), "%assign%"))
return tok;
const Variable * var = tok->variable();
const Token * varTok = getVariableInitExpression(var);
if (!varTok)
return tok;
if (hasUnknownVars(varTok))
return tok;
if (var->isVolatile())
return tok;
if (!var->isLocal() && !var->isConst())
return tok;
if (var->isStatic() && !var->isConst())
return tok;
if (var->isArgument())
return tok;
if (isStructuredBindingVariable(var))
return tok;
// assigning a floating point value to an integer does not preserve the value
if (var->valueType() && var->valueType()->isIntegral() && varTok->valueType() && varTok->valueType()->isFloat())
return tok;
const Token * lastTok = precedes(tok, end) ? end : tok;
// If this is in a loop then check if variables are modified in the entire scope
const Token * endToken = (isInLoopCondition(tok) || isInLoopCondition(varTok) || var->scope() != tok->scope()) ? var->scope()->bodyEnd : lastTok;
if (!var->isConst() && (!precedes(varTok, endToken) || isVariableChanged(varTok, endToken, tok->varId(), false, settings)))
return tok;
if (precedes(varTok, endToken) && isAliased(varTok, endToken, tok->varId()))
return tok;
const Token* startToken = nextAfterAstRightmostLeaf(varTok);
if (!startToken)
startToken = varTok;
if (varTok->exprId() == 0) {
if (!varTok->isLiteral())
return tok;
} else if (!precedes(startToken, endToken)) {
return tok;
} else if (findExpressionChanged(varTok, startToken, endToken, settings)) {
return tok;
}
return varTok;
}
static void followVariableExpressionError(const Token *tok1, const Token *tok2, ErrorPath* errors)
{
if (!errors)
return;
if (!tok1)
return;
if (!tok2)
return;
ErrorPathItem item = std::make_pair(tok2, "'" + tok1->str() + "' is assigned value '" + tok2->expressionString() + "' here.");
if (std::find(errors->cbegin(), errors->cend(), item) != errors->cend())
return;
errors->push_back(std::move(item));
}
SmallVector<ReferenceToken> followAllReferences(const Token* tok,
bool temporary,
bool inconclusive,
ErrorPath errors,
int depth)
{
struct ReferenceTokenLess {
bool operator()(const ReferenceToken& x, const ReferenceToken& y) const {
return x.token < y.token;
}
};
if (!tok)
return {};
if (depth < 0) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
const Variable *var = tok->variable();
if (var && var->declarationId() == tok->varId()) {
if (var->nameToken() == tok || isStructuredBindingVariable(var)) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (var->isReference() || var->isRValueReference()) {
const Token * const varDeclEndToken = var->declEndToken();
if (!varDeclEndToken) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (var->isArgument()) {
errors.emplace_back(varDeclEndToken, "Passed to reference.");
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (Token::simpleMatch(varDeclEndToken, "=")) {
if (astHasToken(varDeclEndToken, tok))
return {};
errors.emplace_back(varDeclEndToken, "Assigned to reference.");
const Token *vartok = varDeclEndToken->astOperand2();
if (vartok == tok || (!temporary && isTemporary(vartok, nullptr, true) &&
(var->isConst() || var->isRValueReference()))) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (vartok)
return followAllReferences(vartok, temporary, inconclusive, std::move(errors), depth - 1);
}
}
} else if (Token::simpleMatch(tok, "?") && Token::simpleMatch(tok->astOperand2(), ":")) {
std::set<ReferenceToken, ReferenceTokenLess> result;
const Token* tok2 = tok->astOperand2();
auto refs = followAllReferences(tok2->astOperand1(), temporary, inconclusive, errors, depth - 1);
result.insert(refs.cbegin(), refs.cend());
refs = followAllReferences(tok2->astOperand2(), temporary, inconclusive, errors, depth - 1);
result.insert(refs.cbegin(), refs.cend());
if (!inconclusive && result.size() != 1) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (!result.empty()) {
SmallVector<ReferenceToken> refs_result;
refs_result.insert(refs_result.end(), result.cbegin(), result.cend());
return refs_result;
}
} else if (tok->previous() && tok->previous()->function() && Token::Match(tok->previous(), "%name% (")) {
const Function *f = tok->previous()->function();
if (!Function::returnsReference(f)) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
std::set<ReferenceToken, ReferenceTokenLess> result;
std::vector<const Token*> returns = Function::findReturns(f);
for (const Token* returnTok : returns) {
if (returnTok == tok)
continue;
for (const ReferenceToken& rt :
followAllReferences(returnTok, temporary, inconclusive, errors, depth - returns.size())) {
const Variable* argvar = rt.token->variable();
if (!argvar) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) {
const int n = getArgumentPos(argvar, f);
if (n < 0) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
std::vector<const Token*> args = getArguments(tok->previous());
if (n >= args.size()) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
const Token* argTok = args[n];
ErrorPath er = errors;
er.emplace_back(returnTok, "Return reference.");
er.emplace_back(tok->previous(), "Called function passing '" + argTok->expressionString() + "'.");
auto refs =
followAllReferences(argTok, temporary, inconclusive, std::move(er), depth - returns.size());
result.insert(refs.cbegin(), refs.cend());
if (!inconclusive && result.size() > 1) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
}
}
}
if (!result.empty()) {
SmallVector<ReferenceToken> refs_result;
refs_result.insert(refs_result.end(), result.cbegin(), result.cend());
return refs_result;
}
}
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
const Token* followReferences(const Token* tok, ErrorPath* errors)
{
if (!tok)
return nullptr;
auto refs = followAllReferences(tok, true, false);
if (refs.size() == 1) {
if (errors)
*errors = std::move(refs.front().errors);
return refs.front().token;
}
return nullptr;
}
static bool isSameLifetime(const Token * const tok1, const Token * const tok2)
{
ValueFlow::Value v1 = ValueFlow::getLifetimeObjValue(tok1);
if (!v1.isLifetimeValue())
return false;
ValueFlow::Value v2 = ValueFlow::getLifetimeObjValue(tok2);
if (!v2.isLifetimeValue())
return false;
return v1.tokvalue == v2.tokvalue;
}
static bool compareKnownValue(const Token * const tok1, const Token * const tok2, const std::function<bool(const ValueFlow::Value&, const ValueFlow::Value&, bool)> &compare)
{
static const auto isKnownFn = std::mem_fn(&ValueFlow::Value::isKnown);
const auto v1 = std::find_if(tok1->values().cbegin(), tok1->values().cend(), isKnownFn);
if (v1 == tok1->values().end()) {
return false;
}
if (v1->isNonValue() || v1->isContainerSizeValue() || v1->isSymbolicValue())
return false;
const auto v2 = std::find_if(tok2->values().cbegin(), tok2->values().cend(), isKnownFn);
if (v2 == tok2->values().end()) {
return false;
}
if (v1->valueType != v2->valueType) {
return false;
}
const bool sameLifetime = isSameLifetime(tok1, tok2);
return compare(*v1, *v2, sameLifetime);
}
bool isEqualKnownValue(const Token * const tok1, const Token * const tok2)
{
return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) {
bool r = v1.equalValue(v2);
if (v1.isIteratorValue()) {
r &= sameLifetime;
}
return r;
});
}
static inline bool isDifferentKnownValues(const Token * const tok1, const Token * const tok2)
{
return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) {
bool r = v1.equalValue(v2);
if (v1.isIteratorValue()) {
r &= sameLifetime;
}
return !r;
});
}
static inline bool isSameConstantValue(bool macro, const Token* tok1, const Token* tok2)
{
if (tok1 == nullptr || tok2 == nullptr)
return false;
auto adjustForCast = [](const Token* tok) {
if (tok->astOperand2() && Token::Match(tok->previous(), "%type% (|{") && tok->previous()->isStandardType())
return tok->astOperand2();
return tok;
};
tok1 = adjustForCast(tok1);
if (!tok1->isNumber() && !tok1->enumerator())
return false;
tok2 = adjustForCast(tok2);
if (!tok2->isNumber() && !tok2->enumerator())
return false;
if (macro && (tok1->isExpandedMacro() || tok2->isExpandedMacro() || tok1->isTemplateArg() || tok2->isTemplateArg()))
return false;
const ValueType * v1 = tok1->valueType();
const ValueType * v2 = tok2->valueType();
if (!v1 || !v2 || v1->sign != v2->sign || v1->type != v2->type || v1->pointer != v2->pointer)
return false;
return isEqualKnownValue(tok1, tok2);
}
static bool isForLoopCondition(const Token * const tok)
{
if (!tok)
return false;
const Token *const parent = tok->astParent();
return Token::simpleMatch(parent, ";") && parent->astOperand1() == tok &&
Token::simpleMatch(parent->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent(), "(") &&
parent->astParent()->astParent()->astOperand1()->str() == "for";
}
static bool isForLoopIncrement(const Token* const tok)
{
if (!tok)
return false;
const Token *const parent = tok->astParent();
return Token::simpleMatch(parent, ";") && parent->astOperand2() == tok &&
Token::simpleMatch(parent->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent(), "(") &&
parent->astParent()->astParent()->astOperand1()->str() == "for";
}
bool isUsedAsBool(const Token* const tok, const Settings& settings)
{
if (!tok)
return false;
if (isForLoopIncrement(tok))
return false;
if (astIsBool(tok))
return true;
if (Token::Match(tok, "!|&&|%oror%|%comp%"))
return true;
const Token* parent = tok->astParent();
if (!parent)
return false;
if (Token::simpleMatch(parent, "["))
return false;
if (parent->isUnaryOp("*"))
return false;
if (Token::simpleMatch(parent, ".")) {
if (astIsRHS(tok))
return isUsedAsBool(parent, settings);
return false;
}
if (Token::Match(parent, "&&|!|%oror%"))
return true;
if (parent->isCast())
return !Token::simpleMatch(parent->astOperand1(), "dynamic_cast") && isUsedAsBool(parent, settings);
if (parent->isUnaryOp("*"))
return isUsedAsBool(parent, settings);
if (Token::Match(parent, "==|!=") && (tok->astSibling()->isNumber() || tok->astSibling()->isKeyword()) && tok->astSibling()->hasKnownIntValue() &&
tok->astSibling()->values().front().intvalue == 0)
return true;
if (parent->str() == "(" && astIsRHS(tok) && Token::Match(parent->astOperand1(), "if|while"))
return true;
if (Token::simpleMatch(parent, "?") && astIsLHS(tok))
return true;
if (isForLoopCondition(tok))
return true;
if (!Token::Match(parent, "%cop%") && !(parent->str() == "(" && tok == parent->astOperand1())) {
if (parent->str() == "," && parent->isInitComma())
return false;
std::vector<ValueType> vtParents = getParentValueTypes(tok, settings);
return std::any_of(vtParents.cbegin(), vtParents.cend(), [&](const ValueType& vt) {
return vt.pointer == 0 && vt.type == ValueType::BOOL;
});
}
return false;
}
bool compareTokenFlags(const Token* tok1, const Token* tok2, bool macro) {
if (macro) {
if (tok1->isExpandedMacro() != tok2->isExpandedMacro())
return false;
if (tok1->isExpandedMacro()) { // both are macros
if (tok1->getMacroName() != tok2->getMacroName())
return false;
if (tok1->astParent() && tok2->astParent() && tok1->astParent()->isExpandedMacro() && tok1->astParent()->getMacroName() == tok2->astParent()->getMacroName())
return false;
}
if (tok1->isTemplateArg() || tok2->isTemplateArg())
return false;
}
if (tok1->isComplex() != tok2->isComplex())
return false;
if (tok1->isLong() != tok2->isLong())
return false;
if (tok1->isUnsigned() != tok2->isUnsigned())
return false;
if (tok1->isSigned() != tok2->isSigned())
return false;
return true;
}
static bool astIsBoolLike(const Token* tok, const Settings& settings)
{
return astIsBool(tok) || isUsedAsBool(tok, settings);
}
bool isSameExpression(bool macro, const Token *tok1, const Token *tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors)
{
if (tok1 == tok2)
return true;
if (tok1 == nullptr || tok2 == nullptr)
return false;
// tokens needs to be from the same TokenList so no need check standard on both of them
if (tok1->isCpp()) {
if (tok1->str() == "." && tok1->astOperand1() && tok1->astOperand1()->str() == "this")
tok1 = tok1->astOperand2();
if (tok2->str() == "." && tok2->astOperand1() && tok2->astOperand1()->str() == "this")
tok2 = tok2->astOperand2();
}
// Skip double not
if (Token::simpleMatch(tok1, "!") && Token::simpleMatch(tok1->astOperand1(), "!") && !Token::simpleMatch(tok1->astParent(), "=") && astIsBoolLike(tok2, settings)) {
return isSameExpression(macro, tok1->astOperand1()->astOperand1(), tok2, settings, pure, followVar, errors);
}
if (Token::simpleMatch(tok2, "!") && Token::simpleMatch(tok2->astOperand1(), "!") && !Token::simpleMatch(tok2->astParent(), "=") && astIsBoolLike(tok1, settings)) {
return isSameExpression(macro, tok1, tok2->astOperand1()->astOperand1(), settings, pure, followVar, errors);
}
const bool tok_str_eq = tok1->str() == tok2->str();
if (!tok_str_eq && isDifferentKnownValues(tok1, tok2))
return false;
const Token *followTok1 = tok1, *followTok2 = tok2;
while (Token::simpleMatch(followTok1, "::") && followTok1->astOperand2())
followTok1 = followTok1->astOperand2();
while (Token::simpleMatch(followTok2, "::") && followTok2->astOperand2())
followTok2 = followTok2->astOperand2();
if (isSameConstantValue(macro, followTok1, followTok2))
return true;
// Follow variable
if (followVar && !tok_str_eq && (followTok1->varId() || followTok2->varId() || followTok1->enumerator() || followTok2->enumerator())) {
const Token * varTok1 = followVariableExpression(settings, followTok1, followTok2);
if ((varTok1->str() == followTok2->str()) || isSameConstantValue(macro, varTok1, followTok2)) {
followVariableExpressionError(followTok1, varTok1, errors);
return isSameExpression(macro, varTok1, followTok2, settings, true, followVar, errors);
}
const Token * varTok2 = followVariableExpression(settings, followTok2, followTok1);
if ((followTok1->str() == varTok2->str()) || isSameConstantValue(macro, followTok1, varTok2)) {
followVariableExpressionError(followTok2, varTok2, errors);
return isSameExpression(macro, followTok1, varTok2, settings, true, followVar, errors);
}
if ((varTok1->str() == varTok2->str()) || isSameConstantValue(macro, varTok1, varTok2)) {
followVariableExpressionError(tok1, varTok1, errors);
followVariableExpressionError(tok2, varTok2, errors);
return isSameExpression(macro, varTok1, varTok2, settings, true, followVar, errors);
}
}
// Follow references
if (!tok_str_eq) {
const Token* refTok1 = followReferences(tok1, errors);
const Token* refTok2 = followReferences(tok2, errors);
if (refTok1 != tok1 || refTok2 != tok2) {
if (refTok1 && !refTok1->varId() && refTok2 && !refTok2->varId()) { // complex reference expression
const Token *start = refTok1, *end = refTok2;
if (!precedes(start, end))
std::swap(start, end);
if (findExpressionChanged(start, start, end, settings))
return false;
}
return isSameExpression(macro, refTok1, refTok2, settings, pure, followVar, errors);
}
}
if (tok1->varId() != tok2->varId() || !tok_str_eq || tok1->originalName() != tok2->originalName()) {
if ((Token::Match(tok1,"<|>") && Token::Match(tok2,"<|>")) ||
(Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) {
return isSameExpression(macro, tok1->astOperand1(), tok2->astOperand2(), settings, pure, followVar, errors) &&
isSameExpression(macro, tok1->astOperand2(), tok2->astOperand1(), settings, pure, followVar, errors);
}
const Token* condTok = nullptr;
const Token* exprTok = nullptr;
if (Token::Match(tok1, "==|!=")) {
condTok = tok1;
exprTok = tok2;
} else if (Token::Match(tok2, "==|!=")) {
condTok = tok2;
exprTok = tok1;
}
if (condTok && condTok->astOperand1() && condTok->astOperand2() && !Token::Match(exprTok, "%comp%")) {
const Token* varTok1 = nullptr;
const Token* varTok2 = exprTok;
const ValueFlow::Value* value = nullptr;
if (condTok->astOperand1()->hasKnownIntValue()) {
value = &condTok->astOperand1()->values().front();
varTok1 = condTok->astOperand2();
} else if (condTok->astOperand2()->hasKnownIntValue()) {
value = &condTok->astOperand2()->values().front();
varTok1 = condTok->astOperand1();
}
const bool exprIsNot = Token::simpleMatch(exprTok, "!");
if (exprIsNot)
varTok2 = exprTok->astOperand1();
bool compare = false;
if (value) {
if (value->intvalue == 0 && exprIsNot && Token::simpleMatch(condTok, "==")) {
compare = true;
} else if (value->intvalue == 0 && !exprIsNot && Token::simpleMatch(condTok, "!=")) {
compare = true;
} else if (value->intvalue != 0 && exprIsNot && Token::simpleMatch(condTok, "!=")) {
compare = true;
} else if (value->intvalue != 0 && !exprIsNot && Token::simpleMatch(condTok, "==")) {
compare = true;
}
}
if (compare && astIsBoolLike(varTok1, settings) && astIsBoolLike(varTok2, settings))
return isSameExpression(macro, varTok1, varTok2, settings, pure, followVar, errors);
}
return false;
}
if (!compareTokenFlags(tok1, tok2, macro))
return false;
if (pure && tok1->isName() && tok1->strAt(1) == "(" && tok1->str() != "sizeof" && !(tok1->variable() && tok1 == tok1->variable()->nameToken())) {
if (!tok1->function()) {
if (Token::simpleMatch(tok1->previous(), ".")) {
const Token *lhs = tok1->previous();
while (Token::Match(lhs, "(|.|["))
lhs = lhs->astOperand1();
if (!lhs)
return false;
const bool lhsIsConst = (lhs->variable() && lhs->variable()->isConst()) ||
(lhs->valueType() && lhs->valueType()->constness > 0) ||
(Token::Match(lhs, "%var% . %name% (") && settings.library.isFunctionConst(lhs->tokAt(2)));
if (!lhsIsConst)
return false;
} else {
const Token * ftok = tok1;
if (!settings.library.isFunctionConst(ftok) && !ftok->isAttributeConst() && !ftok->isAttributePure())
return false;
}
} else {
if (!tok1->function()->isConst() && !tok1->function()->isAttributeConst() &&
!tok1->function()->isAttributePure())
return false;
}
}
// templates/casts
if ((tok1->next() && tok1->linkAt(1) && Token::Match(tok1, "%name% <")) ||
(tok2->next() && tok2->linkAt(1) && Token::Match(tok2, "%name% <"))) {
// non-const template function that is not a dynamic_cast => return false
if (pure && Token::simpleMatch(tok1->linkAt(1), "> (") &&
!(tok1->function() && tok1->function()->isConst()) &&
tok1->str() != "dynamic_cast")
return false;
// some template/cast stuff.. check that the template arguments are same
const Token *t1 = tok1->next();
const Token *t2 = tok2->next();
const Token *end1 = t1->link();
const Token *end2 = t2->link();
while (t1 && t2 && t1 != end1 && t2 != end2) {
if (t1->str() != t2->str() || !compareTokenFlags(t1, t2, macro))
return false;
t1 = t1->next();
t2 = t2->next();
}
if (t1 != end1 || t2 != end2)
return false;
}
if (tok1->tokType() == Token::eIncDecOp || tok1->isAssignmentOp())
return false;
// bailout when we see ({..})
if (tok1->str() == "{")
return false;
// cast => assert that the casts are equal
if (tok1->str() == "(" && tok1->previous() &&
!tok1->previous()->isName() &&
!(tok1->strAt(-1) == ">" && tok1->linkAt(-1))) {
const Token *t1 = tok1->next();
const Token *t2 = tok2->next();
while (t1 && t2 &&
t1->str() == t2->str() &&
compareTokenFlags(t1, t2, macro) &&
(t1->isName() || t1->str() == "*")) {
t1 = t1->next();
t2 = t2->next();
}
if (!t1 || !t2 || t1->str() != ")" || t2->str() != ")")
return false;
}
bool noncommutativeEquals =
isSameExpression(macro, tok1->astOperand1(), tok2->astOperand1(), settings, pure, followVar, errors);
noncommutativeEquals = noncommutativeEquals &&
isSameExpression(macro, tok1->astOperand2(), tok2->astOperand2(), settings, pure, followVar, errors);
if (noncommutativeEquals)
return true;
// in c++, a+b might be different to b+a, depending on the type of a and b
if (tok1->isCpp() && tok1->str() == "+" && tok1->isBinaryOp()) {
const ValueType* vt1 = tok1->astOperand1()->valueType();
const ValueType* vt2 = tok1->astOperand2()->valueType();
if (!(vt1 && (vt1->type >= ValueType::VOID || vt1->pointer) && vt2 && (vt2->type >= ValueType::VOID || vt2->pointer)))
return false;
}
const bool commutative = tok1->isBinaryOp() && Token::Match(tok1, "%or%|%oror%|+|*|&|&&|^|==|!=");
bool commutativeEquals = commutative &&
isSameExpression(macro, tok1->astOperand2(), tok2->astOperand1(), settings, pure, followVar, errors);
commutativeEquals = commutativeEquals &&
isSameExpression(macro, tok1->astOperand1(), tok2->astOperand2(), settings, pure, followVar, errors);
return commutativeEquals;
}
static bool isZeroBoundCond(const Token * const cond)
{
if (cond == nullptr)
return false;
// Assume unsigned
// TODO: Handle reverse conditions
const bool isZero = cond->astOperand2()->getValue(0);
if (cond->str() == "==" || cond->str() == ">=")
return isZero;
if (cond->str() == "<=")
return true;
if (cond->str() == "<")
return !isZero;
if (cond->str() == ">")
return false;
return false;
}
bool isOppositeCond(bool isNot, const Token * const cond1, const Token * const cond2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors)
{
if (!cond1 || !cond2)
return false;
if (isSameExpression(true, cond1, cond2, settings, pure, followVar, errors))
return false;
if (!isNot && cond1->str() == "&&" && cond2->str() == "&&") {
for (const Token* tok1: {
cond1->astOperand1(), cond1->astOperand2()
}) {
for (const Token* tok2: {
cond2->astOperand1(), cond2->astOperand2()
}) {
if (isSameExpression(true, tok1, tok2, settings, pure, followVar, errors)) {
if (isOppositeCond(isNot, tok1->astSibling(), tok2->astSibling(), settings, pure, followVar, errors))
return true;
}
}
}
}
if (cond1->str() != cond2->str() && (cond1->str() == "||" || cond2->str() == "||")) {
const Token* orCond = nullptr;
const Token* otherCond = nullptr;
if (cond1->str() == "||") {
orCond = cond1;
otherCond = cond2;
}
if (cond2->str() == "||") {
orCond = cond2;
otherCond = cond1;
}
return isOppositeCond(isNot, orCond->astOperand1(), otherCond, settings, pure, followVar, errors) &&
isOppositeCond(isNot, orCond->astOperand2(), otherCond, settings, pure, followVar, errors);
}
if (cond1->str() == "!") {
if (cond2->str() == "!=") {
if (cond2->astOperand1() && cond2->astOperand1()->str() == "0")
return isSameExpression(true, cond1->astOperand1(), cond2->astOperand2(), settings, pure, followVar, errors);
if (cond2->astOperand2() && cond2->astOperand2()->str() == "0")
return isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors);
}
if (!isUsedAsBool(cond2, settings))
return false;
return isSameExpression(true, cond1->astOperand1(), cond2, settings, pure, followVar, errors);
}
if (cond2->str() == "!")
return isOppositeCond(isNot, cond2, cond1, settings, pure, followVar, errors);
if (!isNot) {
if (cond1->str() == "==" && cond2->str() == "==") {
if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors))
return isDifferentKnownValues(cond1->astOperand2(), cond2->astOperand2());
if (isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors))
return isDifferentKnownValues(cond1->astOperand1(), cond2->astOperand1());
}
// TODO: Handle reverse conditions
if (Library::isContainerYield(cond1, Library::Container::Yield::EMPTY, "empty") &&
Library::isContainerYield(cond2->astOperand1(), Library::Container::Yield::SIZE, "size") &&
isSameExpression(true,
cond1->astOperand1()->astOperand1(),
cond2->astOperand1()->astOperand1()->astOperand1(),
settings,
pure,
followVar,
errors)) {
return !isZeroBoundCond(cond2);
}
if (Library::isContainerYield(cond2, Library::Container::Yield::EMPTY, "empty") &&
Library::isContainerYield(cond1->astOperand1(), Library::Container::Yield::SIZE, "size") &&
isSameExpression(true,
cond2->astOperand1()->astOperand1(),
cond1->astOperand1()->astOperand1()->astOperand1(),
settings,
pure,
followVar,
errors)) {
return !isZeroBoundCond(cond1);
}
}
if (!cond1->isComparisonOp() || !cond2->isComparisonOp())
return false;
const std::string &comp1 = cond1->str();
// condition found .. get comparator
std::string comp2;
if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors) &&
isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors)) {
comp2 = cond2->str();
} else if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand2(), settings, pure, followVar, errors) &&
isSameExpression(true, cond1->astOperand2(), cond2->astOperand1(), settings, pure, followVar, errors)) {
comp2 = cond2->str();
if (comp2[0] == '>')
comp2[0] = '<';
else if (comp2[0] == '<')
comp2[0] = '>';
}
if (!isNot && comp2.empty()) {
const Token *expr1 = nullptr, *value1 = nullptr, *expr2 = nullptr, *value2 = nullptr;
std::string op1 = cond1->str(), op2 = cond2->str();
if (cond1->astOperand2()->hasKnownIntValue()) {
expr1 = cond1->astOperand1();
value1 = cond1->astOperand2();
} else if (cond1->astOperand1()->hasKnownIntValue()) {
expr1 = cond1->astOperand2();
value1 = cond1->astOperand1();
if (op1[0] == '>')
op1[0] = '<';
else if (op1[0] == '<')
op1[0] = '>';
}
if (cond2->astOperand2()->hasKnownIntValue()) {
expr2 = cond2->astOperand1();
value2 = cond2->astOperand2();
} else if (cond2->astOperand1()->hasKnownIntValue()) {
expr2 = cond2->astOperand2();
value2 = cond2->astOperand1();
if (op2[0] == '>')
op2[0] = '<';
else if (op2[0] == '<')
op2[0] = '>';
}
if (!expr1 || !value1 || !expr2 || !value2) {
return false;
}
if (!isSameExpression(true, expr1, expr2, settings, pure, followVar, errors))
return false;
const ValueFlow::Value &rhsValue1 = value1->values().front();
const ValueFlow::Value &rhsValue2 = value2->values().front();
if (op1 == "<" || op1 == "<=")
return (op2 == "==" || op2 == ">" || op2 == ">=") && (rhsValue1.intvalue < rhsValue2.intvalue);
if (op1 == ">=" || op1 == ">")
return (op2 == "==" || op2 == "<" || op2 == "<=") && (rhsValue1.intvalue > rhsValue2.intvalue);
return false;
}
// is condition opposite?
return ((comp1 == "==" && comp2 == "!=") ||
(comp1 == "!=" && comp2 == "==") ||
(comp1 == "<" && comp2 == ">=") ||
(comp1 == "<=" && comp2 == ">") ||
(comp1 == ">" && comp2 == "<=") ||
(comp1 == ">=" && comp2 == "<") ||
(!isNot && ((comp1 == "<" && comp2 == ">") ||
(comp1 == ">" && comp2 == "<") ||
(comp1 == "==" && (comp2 == "!=" || comp2 == ">" || comp2 == "<")) ||
((comp1 == "!=" || comp1 == ">" || comp1 == "<") && comp2 == "==")
)));
}
bool isOppositeExpression(const Token * const tok1, const Token * const tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors)
{
if (!tok1 || !tok2)
return false;
if (isOppositeCond(true, tok1, tok2, settings, pure, followVar, errors))
return true;
if (tok1->isUnaryOp("-") && !(tok2->astParent() && tok2->astParent()->tokType() == Token::eBitOp))
return isSameExpression(true, tok1->astOperand1(), tok2, settings, pure, followVar, errors);
if (tok2->isUnaryOp("-") && !(tok2->astParent() && tok2->astParent()->tokType() == Token::eBitOp))
return isSameExpression(true, tok2->astOperand1(), tok1, settings, pure, followVar, errors);
return false;
}
static bool functionModifiesArguments(const Function* f)
{
return std::any_of(f->argumentList.cbegin(), f->argumentList.cend(), [](const Variable& var) {
if (var.isReference() || var.isPointer())
return !var.isConst();
return true;
});
}
bool isConstFunctionCall(const Token* ftok, const Library& library)
{
if (isUnevaluated(ftok))
return true;
if (!Token::Match(ftok, "%name% ("))
return false;
if (const Function* f = ftok->function()) {
if (f->isAttributePure() || f->isAttributeConst())
return true;
// Any modified arguments
if (functionModifiesArguments(f))
return false;
if (Function::returnsVoid(f))
return false;
// Member function call
if (Token::simpleMatch(ftok->previous(), ".") || exprDependsOnThis(ftok->next())) {
if (f->isConst())
return true;
// Check for const overloaded function that just return the const version
if (!Function::returnsConst(f)) {
std::vector<const Function*> fs = f->getOverloadedFunctions();
if (std::any_of(fs.cbegin(), fs.cend(), [&](const Function* g) {
if (f == g)
return false;
if (f->argumentList.size() != g->argumentList.size())
return false;
if (functionModifiesArguments(g))
return false;
if (g->isConst() && Function::returnsConst(g))
return true;
return false;
}))
return true;
}
return false;
}
if (f->argumentList.empty())
return f->isConstexpr();
} else if (Token::Match(ftok->previous(), ". %name% (") && ftok->previous()->originalName() != "->" &&
astIsSmartPointer(ftok->previous()->astOperand1())) {
return Token::Match(ftok, "get|get_deleter ( )");
} else if (Token::Match(ftok->previous(), ". %name% (") && astIsContainer(ftok->previous()->astOperand1())) {
const Library::Container* container = ftok->previous()->astOperand1()->valueType()->container;
if (!container)
return false;
if (container->getYield(ftok->str()) != Library::Container::Yield::NO_YIELD)
return true;
if (container->getAction(ftok->str()) == Library::Container::Action::FIND_CONST)
return true;
return false;
} else if (const Library::Function* lf = library.getFunction(ftok)) {
if (lf->ispure)
return true;
if (lf->containerYield != Library::Container::Yield::NO_YIELD)
return true;
if (lf->containerAction == Library::Container::Action::FIND_CONST)
return true;
return false;
} else {
const bool memberFunction = Token::Match(ftok->previous(), ". %name% (");
bool constMember = !memberFunction;
if (Token::Match(ftok->tokAt(-2), "%var% . %name% (")) {
const Variable* var = ftok->tokAt(-2)->variable();
if (var)
constMember = var->isConst();
}
// TODO: Only check const on lvalues
std::vector<const Token*> args = getArguments(ftok);
if (args.empty())
return false;
return constMember && std::all_of(args.cbegin(), args.cend(), [](const Token* tok) {
const Variable* var = tok->variable();
if (var)
return var->isConst();
return false;
});
}
return true;
}
bool isConstExpression(const Token *tok, const Library& library)
{
if (!tok)
return true;
if (tok->variable() && tok->variable()->isVolatile())
return false;
if (tok->isName() && tok->strAt(1) == "(") {
if (!isConstFunctionCall(tok, library))
return false;
}
if (tok->tokType() == Token::eIncDecOp)
return false;
if (tok->isAssignmentOp())
return false;
if (isLikelyStreamRead(tok))
return false;
// bailout when we see ({..})
if (tok->str() == "{")
return false;
return isConstExpression(tok->astOperand1(), library) && isConstExpression(tok->astOperand2(), library);
}
bool isWithoutSideEffects(const Token* tok, bool checkArrayAccess, bool checkReference)
{
if (!tok)
return true;
if (!tok->isCpp())
return true;
while (tok && tok->astOperand2() && tok->astOperand2()->str() != "(")
tok = tok->astOperand2();
if (tok && tok->varId()) {
const Variable* var = tok->variable();
return var && ((!var->isClass() && (checkReference || !var->isReference())) || var->isPointer() || (checkArrayAccess ? var->isStlType() && !var->isStlType(CheckClass::stl_containers_not_const) : var->isStlType()));
}
return true;
}
bool isUniqueExpression(const Token* tok)
{
if (!tok)
return true;
if (tok->function()) {
const Function * fun = tok->function();
const Scope * scope = fun->nestedIn;
if (!scope)
return true;
const std::string returnType = fun->retType ? fun->retType->name() : fun->retDef->stringifyList(fun->tokenDef);
if (!std::all_of(scope->functionList.begin(), scope->functionList.end(), [&](const Function& f) {
if (f.type != Function::eFunction)
return true;
const std::string freturnType = f.retType ? f.retType->name() : f.retDef->stringifyList(f.returnDefEnd());
return f.argumentList.size() != fun->argumentList.size() || returnType != freturnType || f.name() == fun->name();
}))
return false;
} else if (tok->variable()) {
const Variable * var = tok->variable();
const Scope * scope = var->scope();
if (!scope)
return true;
const Type * varType = var->type();
// Iterate over the variables in scope and the parameters of the function if possible
const Function * fun = scope->function;
auto pred = [=](const Variable& v) {
if (varType)
return v.type() && v.type()->name() == varType->name() && v.name() != var->name();
return v.isFloatingType() == var->isFloatingType() &&
v.isEnumType() == var->isEnumType() &&
v.isClass() == var->isClass() &&
v.isArray() == var->isArray() &&
v.isPointer() == var->isPointer() &&
v.name() != var->name();
};
if (std::any_of(scope->varlist.cbegin(), scope->varlist.cend(), pred))
return false;
if (fun) {
if (std::any_of(fun->argumentList.cbegin(), fun->argumentList.cend(), pred))
return false;
}
} else if (!isUniqueExpression(tok->astOperand1())) {
return false;
}
return isUniqueExpression(tok->astOperand2());
}
static bool isEscaped(const Token* tok, bool functionsScope, const Library& library)
{
if (library.isnoreturn(tok))
return true;
if (functionsScope)
return Token::simpleMatch(tok, "throw");
return Token::Match(tok, "return|throw");
}
static bool isEscapedOrJump(const Token* tok, bool functionsScope, const Library& library)
{
if (library.isnoreturn(tok))
return true;
if (functionsScope)
return Token::simpleMatch(tok, "throw");
return Token::Match(tok, "return|goto|throw|continue|break");
}
bool isEscapeFunction(const Token* ftok, const Library* library)
{
if (!Token::Match(ftok, "%name% ("))
return false;
const Function* function = ftok->function();
if (function) {
if (function->isEscapeFunction())
return true;
if (function->isAttributeNoreturn())
return true;
} else if (library) {
if (library->isnoreturn(ftok))
return true;
}
return false;
}
static bool hasNoreturnFunction(const Token* tok, const Library& library, const Token** unknownFunc)
{
if (!tok)
return false;
const Token* ftok = tok->str() == "(" ? tok->previous() : nullptr;
while (Token::simpleMatch(ftok, "("))
ftok = ftok->astOperand1();
if (ftok) {
const Function * function = ftok->function();
if (function) {
if (function->isEscapeFunction())
return true;
if (function->isAttributeNoreturn())
return true;
} else if (library.isnoreturn(ftok)) {
return true;
} else if (Token::Match(ftok, "exit|abort")) {
return true;
}
if (unknownFunc && !function && library.functions().count(library.getFunctionName(ftok)) == 0)
*unknownFunc = ftok;
return false;
}
if (tok->isConstOp()) {
return hasNoreturnFunction(tok->astOperand1(), library, unknownFunc) || hasNoreturnFunction(tok->astOperand2(), library, unknownFunc);
}
return false;
}
bool isReturnScope(const Token* const endToken, const Library& library, const Token** unknownFunc, bool functionScope)
{
if (!endToken || endToken->str() != "}")
return false;
const Token *prev = endToken->previous();
while (prev && Token::simpleMatch(prev->previous(), "; ;"))
prev = prev->previous();
if (prev && Token::simpleMatch(prev->previous(), "} ;"))
prev = prev->previous();
if (Token::simpleMatch(prev, "}")) {
if (Token::simpleMatch(prev->link()->tokAt(-2), "} else {"))
return isReturnScope(prev, library, unknownFunc, functionScope) &&
isReturnScope(prev->link()->tokAt(-2), library, unknownFunc, functionScope);
// TODO: Check all cases
if (!functionScope && Token::simpleMatch(prev->link()->previous(), ") {") &&
Token::simpleMatch(prev->link()->linkAt(-1)->previous(), "switch (") &&
!Token::findsimplematch(prev->link(), "break", prev)) {
return isReturnScope(prev, library, unknownFunc, functionScope);
}
if (isEscaped(prev->link()->astTop(), functionScope, library))
return true;
if (Token::Match(prev->link()->previous(), "[;{}] {"))
return isReturnScope(prev, library, unknownFunc, functionScope);
} else if (Token::simpleMatch(prev, ";")) {
if (prev->tokAt(-2) && hasNoreturnFunction(prev->tokAt(-2)->astTop(), library, unknownFunc))
return true;
// Unknown symbol
if (Token::Match(prev->tokAt(-2), ";|}|{ %name% ;") && prev->previous()->isIncompleteVar()) {
if (unknownFunc)
*unknownFunc = prev->previous();
return false;
}
if (Token::simpleMatch(prev->previous(), ") ;") && prev->linkAt(-1) &&
isEscaped(prev->linkAt(-1)->astTop(), functionScope, library))
return true;
if (isEscaped(prev->previous()->astTop(), functionScope, library))
return true;
// return/goto statement
prev = prev->previous();
while (prev && !Token::Match(prev, ";|{|}") && !isEscapedOrJump(prev, functionScope, library))
prev = prev->previous();
return prev && prev->isName();
}
return false;
}
bool isWithinScope(const Token* tok, const Variable* var, Scope::ScopeType type)
{
if (!tok || !var)
return false;
const Scope* scope = tok->scope();
while (scope && scope != var->scope()) {
if (scope->type == type)
return true;
scope = scope->nestedIn;
}
return false;
}
bool isVariableChangedByFunctionCall(const Token *tok, int indirect, nonneg int varid, const Settings &settings, bool *inconclusive)
{
if (!tok)
return false;
if (tok->varId() == varid)
return isVariableChangedByFunctionCall(tok, indirect, settings, inconclusive);
return isVariableChangedByFunctionCall(tok->astOperand1(), indirect, varid, settings, inconclusive) ||
isVariableChangedByFunctionCall(tok->astOperand2(), indirect, varid, settings, inconclusive);
}
bool isScopeBracket(const Token* tok)
{
if (!Token::Match(tok, "{|}"))
return false;
if (!tok->scope())
return false;
if (tok->str() == "{")
return tok->scope()->bodyStart == tok;
if (tok->str() == "}")
return tok->scope()->bodyEnd == tok;
return false;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getTokenArgumentFunctionImpl(T* tok, int& argn)
{
argn = -1;
{
T* parent = tok->astParent();
if (parent && (parent->isUnaryOp("&") || parent->isIncDecOp()))
parent = parent->astParent();
while (parent && parent->isCast())
parent = parent->astParent();
if (Token::Match(parent, "[+-]") && parent->valueType() && parent->valueType()->pointer)
parent = parent->astParent();
// passing variable to subfunction?
if (Token::Match(parent, "[[(,{.]") || Token::Match(parent, "%oror%|&&") || (parent && parent->isUnaryOp("*")))
;
else if (Token::simpleMatch(parent, ":")) {
while (Token::Match(parent, "[?:]"))
parent = parent->astParent();
while (Token::simpleMatch(parent, ","))
parent = parent->astParent();
if (!parent || parent->str() != "(")
return nullptr;
} else
return nullptr;
}
T* argtok = tok;
while (argtok && argtok->astParent() && (!Token::Match(argtok->astParent(), ",|(|{") || argtok->astParent()->isCast())) {
argtok = argtok->astParent();
}
if (!argtok)
return nullptr;
if (Token::simpleMatch(argtok, ","))
argtok = argtok->astOperand1();
tok = argtok;
while (Token::Match(tok->astParent(), ",|(|{")) {
tok = tok->astParent();
if (Token::Match(tok, "(|{"))
break;
}
argn = getArgumentPos(tok, argtok);
if (argn == -1)
return nullptr;
if (!Token::Match(tok, "{|("))
return nullptr;
if (tok->astOperand2())
tok = tok->astOperand1();
while (tok && (tok->isUnaryOp("*") || tok->str() == "["))
tok = tok->astOperand1();
if (Token::Match(tok, ". * %name%")) // bailout for pointer to member
return tok->tokAt(2);
while (Token::simpleMatch(tok, "."))
tok = tok->astOperand2();
while (Token::simpleMatch(tok, "::")) {
// If there is only a op1 and not op2, then this is a global scope
if (!tok->astOperand2() && tok->astOperand1()) {
tok = tok->astOperand1();
break;
}
tok = tok->astOperand2();
if (Token::simpleMatch(tok, "<") && tok->link())
tok = tok->astOperand1();
}
if (tok && tok->link() && tok->str() == ">")
tok = tok->link()->previous();
if (!Token::Match(tok, "%name%|(|{"))
return nullptr;
// Skip labels
if (Token::Match(tok, "%name% :"))
return nullptr;
return tok;
}
const Token* getTokenArgumentFunction(const Token* tok, int& argn) {
return getTokenArgumentFunctionImpl(tok, argn);
}
Token* getTokenArgumentFunction(Token* tok, int& argn) {
return getTokenArgumentFunctionImpl(tok, argn);
}
std::vector<const Variable*> getArgumentVars(const Token* tok, int argnr)
{
std::vector<const Variable*> result;
if (!tok)
return result;
if (tok->function()) {
const Variable* argvar = tok->function()->getArgumentVar(argnr);
if (argvar)
return {argvar};
return result;
}
if (tok->variable() || Token::simpleMatch(tok, "{") || Token::Match(tok->previous(), "%type% (|{")) {
const Type* type = Token::typeOf(tok);
if (!type)
return result;
const Scope* typeScope = type->classScope;
if (!typeScope)
return result;
const bool tokIsBrace = Token::simpleMatch(tok, "{");
// Aggregate constructor
if (tokIsBrace && typeScope->numConstructors == 0 && argnr < typeScope->varlist.size()) {
auto it = std::next(typeScope->varlist.cbegin(), argnr);
return {&*it};
}
const int argCount = numberOfArguments(tok);
const bool constructor = tokIsBrace || (tok->variable() && tok->variable()->nameToken() == tok);
for (const Function &function : typeScope->functionList) {
if (function.argCount() < argCount)
continue;
if (constructor && !function.isConstructor())
continue;
if (!constructor && !Token::simpleMatch(function.token, "operator()"))
continue;
const Variable* argvar = function.getArgumentVar(argnr);
if (argvar)
result.push_back(argvar);
}
}
return result;
}
static bool isCPPCastKeyword(const Token* tok)
{
if (!tok)
return false;
return endsWith(tok->str(), "_cast");
}
static bool isTrivialConstructor(const Token* tok)
{
const Token* typeTok = nullptr;
const Type* t = Token::typeOf(tok, &typeTok);
if (t)
return false;
if (typeTok->valueType() && typeTok->valueType()->isPrimitive())
return true;
return false;
}
static bool isArray(const Token* tok)
{
if (!tok)
return false;
if (tok->variable())
return tok->variable()->isArray();
if (Token::simpleMatch(tok, "."))
return isArray(tok->astOperand2());
return false;
}
static inline
// limit it to CLang as compiling with GCC might fail with
// error: inlining failed in call to always_inline 'bool isMutableExpression(const Token*)': function not considered for inlining
// error: inlining failed in call to ‘always_inline’ ‘bool isMutableExpression(const Token*)’: recursive inlining
#if defined(__clang__)
__attribute__((always_inline))
#endif
bool isMutableExpression(const Token* tok)
{
if (!tok)
return false;
if (tok->isLiteral() || tok->isKeyword() || tok->isStandardType() || tok->isEnumerator())
return false;
if (Token::Match(tok, ",|;|:|]|)|}"))
return false;
if (Token::simpleMatch(tok, "[ ]"))
return false;
if (tok->previous() && tok->previous()->isKeyword() && Token::Match(tok->previous(), "%name% ("))
return false;
if (tok->link() && Token::Match(tok, "<|>"))
return false;
if (tok->astOperand1() && Token::simpleMatch(tok, "["))
return isMutableExpression(tok->astOperand1());
if (const Variable* var = tok->variable()) {
if (var->nameToken() == tok)
return false;
if (!var->isPointer() && var->isConst())
return false;
}
return true;
}
bool isVariableChangedByFunctionCall(const Token *tok, int indirect, const Settings &settings, bool *inconclusive)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, ","))
return false;
const Token * const tok1 = tok;
// address of variable
const bool addressOf = tok->astParent() && tok->astParent()->isUnaryOp("&");
if (addressOf)
indirect++;
const bool deref = tok->astParent() && tok->astParent()->isUnaryOp("*");
if (deref && indirect > 0)
indirect--;
if (indirect == 1 && tok->isCpp() && tok->tokAt(-1) && Token::simpleMatch(tok->tokAt(-2), "new (")) // placement new TODO: fix AST
return true;
int argnr;
tok = getTokenArgumentFunction(tok, argnr);
if (!tok)
return false; // not a function => variable not changed
if (Token::simpleMatch(tok, "{") && isTrivialConstructor(tok))
return false;
if (tok->isKeyword() && !isCPPCastKeyword(tok) && !startsWith(tok->str(),"operator"))
return false;
// A functional cast won't modify the variable
if (Token::Match(tok, "%type% (|{") && tok->tokType() == Token::eType && astIsPrimitive(tok->next()))
return false;
const Token * parenTok = tok->next();
if (Token::simpleMatch(parenTok, "<") && parenTok->link())
parenTok = parenTok->link()->next();
const bool possiblyPassedByReference = (parenTok->next() == tok1 || Token::Match(tok1->previous(), ", %name% [,)}]"));
if (!tok->function() && !tok->variable() && tok->isName()) {
// Check if direction (in, out, inout) is specified in the library configuration and use that
const Library::ArgumentChecks::Direction argDirection = settings.library.getArgDirection(tok, 1 + argnr, indirect);
if (argDirection == Library::ArgumentChecks::Direction::DIR_IN)
return false;
const bool requireNonNull = settings.library.isnullargbad(tok, 1 + argnr);
if (argDirection == Library::ArgumentChecks::Direction::DIR_OUT ||
argDirection == Library::ArgumentChecks::Direction::DIR_INOUT) {
if (indirect == 0 && isArray(tok1))
return true;
const bool requireInit = settings.library.isuninitargbad(tok, 1 + argnr);
// Assume that if the variable must be initialized then the indirection is 1
if (indirect > 0 && requireInit && requireNonNull)
return true;
}
if (Token::simpleMatch(tok->tokAt(-2), "std :: tie"))
return true;
// if the library says 0 is invalid
// => it is assumed that parameter is an in parameter (TODO: this is a bad heuristic)
if (indirect == 0 && requireNonNull)
return false;
// possible pass-by-reference => inconclusive
if (possiblyPassedByReference) {
if (inconclusive != nullptr)
*inconclusive = true;
return false;
}
// Safe guess: Assume that parameter is changed by function call
return true;
}
if (const Variable* var = tok->variable()) {
if (tok == var->nameToken() && (!var->isReference() || (var->isConst() && var->type() == tok1->type())) && (!var->isClass() || (var->valueType() && var->valueType()->container))) // const ref or passed to (copy) ctor
return false;
}
std::vector<const Variable*> args = getArgumentVars(tok, argnr);
bool conclusive = false;
for (const Variable *arg:args) {
if (!arg)
continue;
conclusive = true;
if (indirect > 0) {
if (arg->isPointer() && !(arg->valueType() && arg->valueType()->isConst(indirect)))
return true;
if (indirect > 1 && addressOf && arg->isPointer() && (!arg->valueType() || !arg->valueType()->isConst(indirect-1)))
return true;
if (arg->isArray() || (!arg->isPointer() && (!arg->valueType() || arg->valueType()->type == ValueType::UNKNOWN_TYPE)))
return true;
}
if (!arg->isConst() && arg->isReference())
return true;
}
if (addressOf && tok1->astParent()->isUnaryOp("&")) {
const Token* castToken = tok1->astParent();
while (castToken->astParent()->isCast())
castToken = castToken->astParent();
if (Token::Match(castToken->astParent(), ",|(") &&
castToken->valueType() &&
castToken->valueType()->isIntegral() &&
castToken->valueType()->pointer == 0)
return true;
}
if (!conclusive && inconclusive) {
*inconclusive = true;
}
return false;
}
bool isVariableChanged(const Token *tok, int indirect, const Settings &settings, int depth)
{
if (!isMutableExpression(tok))
return false;
if (indirect == 0 && isConstVarExpression(tok))
return false;
const Token *tok2 = tok;
int derefs = 0;
while ((tok2->astParent() && tok2->astParent()->isUnaryOp("*")) ||
(Token::simpleMatch(tok2->astParent(), ".") && !Token::Match(tok2->astParent()->astParent(), "[(,]")) ||
(tok2->astParent() && tok2->astParent()->isUnaryOp("&") && Token::simpleMatch(tok2->astParent()->astParent(), ".") && tok2->astParent()->astParent()->originalName()=="->") ||
(Token::simpleMatch(tok2->astParent(), "[") && tok2 == tok2->astParent()->astOperand1())) {
if (tok2->astParent() && (tok2->astParent()->isUnaryOp("*") || (astIsLHS(tok2) && tok2->astParent()->originalName() == "->")))
derefs++;
if (derefs > indirect)
break;
if (tok2->astParent() && tok2->astParent()->isUnaryOp("&") && Token::simpleMatch(tok2->astParent()->astParent(), ".") && tok2->astParent()->astParent()->originalName()=="->")
tok2 = tok2->astParent();
tok2 = tok2->astParent();
}
if (tok2->astParent() && tok2->astParent()->isUnaryOp("&")) {
const Token* parent = tok2->astParent();
while (parent->astParent() && parent->astParent()->isCast())
parent = parent->astParent();
if (parent->astParent() && parent->astParent()->isUnaryOp("*"))
tok2 = parent->astParent();
}
while ((Token::simpleMatch(tok2, ":") && Token::simpleMatch(tok2->astParent(), "?")) ||
(Token::simpleMatch(tok2->astParent(), ":") && Token::simpleMatch(tok2->astParent()->astParent(), "?")))
tok2 = tok2->astParent();
if (indirect == 0 && tok2->astParent() && tok2->astParent()->tokType() == Token::eIncDecOp)
return true;
auto skipRedundantPtrOp = [](const Token* tok, const Token* parent) {
const Token* gparent = parent ? parent->astParent() : nullptr;
while (parent && gparent && ((parent->isUnaryOp("*") && gparent->isUnaryOp("&")) || (parent->isUnaryOp("&") && gparent->isUnaryOp("*")))) {
tok = gparent;
parent = gparent->astParent();
if (parent)
gparent = parent->astParent();
}
return tok;
};
tok2 = skipRedundantPtrOp(tok2, tok2->astParent());
if (tok2->astParent() && tok2->astParent()->isAssignmentOp()) {
if (astIsLHS(tok2))
return true;
// Check if assigning to a non-const lvalue
const Variable * var = getLHSVariable(tok2->astParent());
if (var && var->isReference() && !var->isConst() && var->nameToken() &&
var->nameToken()->next() == tok2->astParent()) {
if (!var->isLocal() || isVariableChanged(var, settings, depth - 1))
return true;
}
}
const ValueType* vt = tok->variable() ? tok->variable()->valueType() : tok->valueType();
// Check addressof
if (tok2->astParent() && tok2->astParent()->isUnaryOp("&")) {
if (isVariableChanged(tok2->astParent(), indirect + 1, settings, depth - 1))
return true;
} else {
// If its already const then it cant be modified
if (vt && vt->isConst(indirect))
return false;
}
if (tok2->isCpp() && Token::Match(tok2->astParent(), ">>|&") && astIsRHS(tok2) && isLikelyStreamRead(tok2->astParent()))
return true;
if (isLikelyStream(tok2))
return true;
// Member function call
if (Token::Match(tok2->astParent(), ". %name%") && isFunctionCall(tok2->astParent()->next()) &&
tok2->astParent()->astOperand1() == tok2) {
// Member function cannot change what `this` points to
if (indirect == 0 && astIsPointer(tok))
return false;
const Token *ftok = tok2->astParent()->astOperand2();
const Token* const ctok = tok2->str() == "." ? tok2->astOperand2() : tok2;
if (astIsContainer(ctok) && ctok->valueType() && ctok->valueType()->container) {
const Library::Container* c = ctok->valueType()->container;
const Library::Container::Action action = c->getAction(ftok->str());
if (contains({Library::Container::Action::INSERT,
Library::Container::Action::ERASE,
Library::Container::Action::APPEND,
Library::Container::Action::CHANGE,
Library::Container::Action::CHANGE_CONTENT,
Library::Container::Action::CHANGE_INTERNAL,
Library::Container::Action::CLEAR,
Library::Container::Action::FIND,
Library::Container::Action::PUSH,
Library::Container::Action::POP,
Library::Container::Action::RESIZE},
action))
return true;
const Library::Container::Yield yield = c->getYield(ftok->str());
// If accessing element check if the element is changed
if (contains({Library::Container::Yield::ITEM, Library::Container::Yield::AT_INDEX}, yield))
return isVariableChanged(ftok->next(), indirect, settings, depth - 1);
if (contains({Library::Container::Yield::BUFFER,
Library::Container::Yield::BUFFER_NT,
Library::Container::Yield::START_ITERATOR,
Library::Container::Yield::ITERATOR},
yield)) {
return isVariableChanged(ftok->next(), indirect + 1, settings, depth - 1);
}
if (contains({Library::Container::Yield::SIZE,
Library::Container::Yield::EMPTY,
Library::Container::Yield::END_ITERATOR},
yield)) {
return false;
}
}
if (settings.library.isFunctionConst(ftok) || (astIsSmartPointer(tok) && ftok->str() == "get")) // TODO: replace with action/yield?
return false;
const Function * fun = ftok->function();
if (!fun)
return true;
return !fun->isConst();
}
// Member pointer
if (Token::Match(tok2->astParent(), ". * ( & %name% ::")) {
const Token* ftok = tok2->astParent()->linkAt(2)->previous();
// TODO: Check for pointer to member variable
if (!ftok->function() || !ftok->function()->isConst())
return true;
}
if (Token::Match(tok2->astParent(), ". * %name%")) // bailout
return true;
if (Token::simpleMatch(tok2, "[") && astIsContainer(tok) && vt && vt->container && vt->container->stdAssociativeLike)
return true;
const Token *ftok = tok2;
while (ftok && (!Token::Match(ftok, "[({]") || ftok->isCast()))
ftok = ftok->astParent();
if (ftok && Token::Match(ftok->link(), ")|} !!{")) {
if (ftok->str() == "(" && Token::simpleMatch(ftok->astOperand1(), "[")) // operator() on array element, bail out
return true;
const Token * ptok = tok2;
while (Token::Match(ptok->astParent(), ".|::|["))
ptok = ptok->astParent();
int pindirect = indirect;
if (indirect == 0 && astIsLHS(tok2) && Token::Match(ptok, ". %var%") && astIsPointer(ptok->next()))
pindirect = 1;
bool inconclusive = false;
bool isChanged = isVariableChangedByFunctionCall(ptok, pindirect, settings, &inconclusive);
isChanged |= inconclusive;
if (isChanged)
return true;
}
const Token *parent = tok2->astParent();
while (Token::Match(parent, ".|::"))
parent = parent->astParent();
if (parent && parent->tokType() == Token::eIncDecOp && (indirect == 0 || tok2 != tok))
return true;
// structured binding, nonconst reference variable in lhs
if (Token::Match(tok2->astParent(), ":|=") && tok2 == tok2->astParent()->astOperand2() && Token::simpleMatch(tok2->astParent()->previous(), "]")) {
const Token *typeStart = tok2->astParent()->linkAt(-1)->previous();
if (Token::simpleMatch(typeStart, "&"))
typeStart = typeStart->previous();
if (typeStart && Token::Match(typeStart->previous(), "[;{}(] auto &| [")) {
for (const Token *vartok = typeStart->tokAt(2); vartok != tok2; vartok = vartok->next()) {
if (vartok->varId()) {
const Variable* refvar = vartok->variable();
if (!refvar || (!refvar->isConst() && refvar->isReference()))
return true;
}
}
}
}
if (Token::simpleMatch(tok2->astParent(), ":") && tok2->astParent()->astParent() && Token::simpleMatch(tok2->astParent()->astParent()->previous(), "for (")) {
// TODO: Check if container is empty or not
if (astIsLHS(tok2))
return true;
const Token * varTok = tok2->astParent()->previous();
if (!varTok)
return false;
const Variable * loopVar = varTok->variable();
if (!loopVar)
return false;
if (!loopVar->isConst() && loopVar->isReference() && isVariableChanged(loopVar, settings, depth - 1))
return true;
return false;
}
if (indirect > 0) {
// check for `*(ptr + 1) = new_value` case
parent = tok2->astParent();
while (parent && ((parent->isArithmeticalOp() && parent->isBinaryOp()) || parent->isIncDecOp())) {
parent = parent->astParent();
}
if (Token::simpleMatch(parent, "*")) {
if (parent->astParent() && parent->astParent()->isAssignmentOp() &&
(parent->astParent()->astOperand1() == parent)) {
return true;
}
}
}
return false;
}
bool isVariableChanged(const Token *start, const Token *end, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
return findVariableChanged(start, end, 0, exprid, globalvar, settings, depth) != nullptr;
}
bool isVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
return findVariableChanged(start, end, indirect, exprid, globalvar, settings, depth) != nullptr;
}
const Token* findExpression(const Token* start, const nonneg int exprid)
{
const Function* f = Scope::nestedInFunction(start->scope());
if (!f)
return nullptr;
const Scope* scope = f->functionScope;
if (!scope)
return nullptr;
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->exprId() != exprid)
continue;
return tok;
}
return nullptr;
}
const Token* findEscapeStatement(const Scope* scope, const Library* library)
{
if (!scope)
return nullptr;
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
const Scope* escapeScope = tok->scope();
if (!escapeScope->isExecutable()) { // skip type definitions
tok = escapeScope->bodyEnd;
continue;
}
if (const Token* lambdaEnd = findLambdaEndToken(tok)) { // skip lambdas
tok = lambdaEnd;
continue;
}
if (!tok->isName())
continue;
if (isEscapeFunction(tok, library))
return tok;
if (!tok->isKeyword())
continue;
if (Token::Match(tok, "goto|return|throw")) // TODO: check try/catch, labels?
return tok;
if (!Token::Match(tok, "break|continue"))
continue;
const bool isBreak = tok->str()[0] == 'b';
while (escapeScope && escapeScope != scope) {
if (escapeScope->isLoopScope() || (isBreak && escapeScope->type == Scope::ScopeType::eSwitch))
return nullptr;
escapeScope = escapeScope->nestedIn;
}
return tok;
}
return nullptr;
}
template<class F,
REQUIRES("F must be a function that returns a Token class",
std::is_convertible<decltype(std::declval<F>()()), const Token*> )>
static bool isExpressionChangedAt(const F& getExprTok,
const Token* tok,
int indirect,
const nonneg int exprid,
bool globalvar,
const Settings& settings,
int depth)
{
if (depth < 0)
return true;
if (!isMutableExpression(tok))
return false;
if (tok->exprId() != exprid || (!tok->varId() && !tok->isName())) {
if (globalvar && Token::Match(tok, "%name% (") &&
(!(tok->function() && (tok->function()->isAttributePure() || tok->function()->isAttributeConst())))) {
if (!Token::simpleMatch(tok->astParent(), "."))
return true;
const auto yield = astContainerYield(tok->astParent()->astOperand1());
if (yield != Library::Container::Yield::SIZE && yield != Library::Container::Yield::EMPTY &&
yield != Library::Container::Yield::BUFFER && yield != Library::Container::Yield::BUFFER_NT)
// TODO: Is global variable really changed by function call?
return true;
}
int i = 1;
bool aliased = false;
// If we can't find the expression then assume it is an alias
auto expr = getExprTok();
if (!expr && !(tok->valueType() && tok->valueType()->pointer == 0 && tok->valueType()->reference == Reference::None))
aliased = true;
if (!aliased)
aliased = isAliasOf(tok, expr, &i);
if (!aliased)
return false;
if (isVariableChanged(tok, indirect + i, settings, depth))
return true;
// TODO: Try to traverse the lambda function
if (Token::Match(tok, "%var% ("))
return true;
return false;
}
return (isVariableChanged(tok, indirect, settings, depth));
}
bool isExpressionChangedAt(const Token* expr,
const Token* tok,
int indirect,
bool globalvar,
const Settings& settings,
int depth)
{
return isExpressionChangedAt([&] {
return expr;
}, tok, indirect, expr->exprId(), globalvar, settings, depth);
}
Token* findVariableChanged(Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
if (!precedes(start, end))
return nullptr;
if (depth < 0)
return start;
auto getExprTok = utils::memoize([&] {
return findExpression(start, exprid);
});
for (Token *tok = start; tok != end; tok = tok->next()) {
if (isExpressionChangedAt(getExprTok, tok, indirect, exprid, globalvar, settings, depth))
return tok;
}
return nullptr;
}
const Token* findVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
return findVariableChanged(const_cast<Token*>(start), end, indirect, exprid, globalvar, settings, depth);
}
bool isVariableChanged(const Variable * var, const Settings &settings, int depth)
{
if (!var)
return false;
if (!var->scope())
return false;
const Token * start = var->declEndToken();
if (!start)
return false;
if (Token::Match(start, "; %varid% =", var->declarationId()))
start = start->tokAt(2);
if (Token::simpleMatch(start, "=")) {
const Token* next = nextAfterAstRightmostLeafGeneric(start);
if (next)
start = next;
}
return findExpressionChanged(var->nameToken(), start->next(), var->scope()->bodyEnd, settings, depth);
}
bool isVariablesChanged(const Token* start,
const Token* end,
int indirect,
const std::vector<const Variable*> &vars,
const Settings& settings)
{
std::set<int> varids;
std::transform(vars.cbegin(), vars.cend(), std::inserter(varids, varids.begin()), [](const Variable* var) {
return var->declarationId();
});
const bool globalvar = std::any_of(vars.cbegin(), vars.cend(), [](const Variable* var) {
return var->isGlobal();
});
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (tok->varId() == 0 || varids.count(tok->varId()) == 0) {
if (globalvar && Token::Match(tok, "%name% ("))
// TODO: Is global variable really changed by function call?
return true;
continue;
}
if (isVariableChanged(tok, indirect, settings))
return true;
}
return false;
}
bool isThisChanged(const Token* tok, int indirect, const Settings& settings)
{
if ((Token::Match(tok->previous(), "%name% (") && !Token::simpleMatch(tok->astOperand1(), ".")) ||
Token::Match(tok->tokAt(-3), "this . %name% (")) {
if (tok->previous()->function()) {
return (!tok->previous()->function()->isConst() && !tok->previous()->function()->isStatic());
}
if (!tok->previous()->isKeyword() || tok->previous()->isOperatorKeyword()) {
return true;
}
}
if (isVariableChanged(tok, indirect, settings))
return true;
return false;
}
static const Token* findThisChanged(const Token* start, const Token* end, int indirect, const Settings& settings)
{
if (!precedes(start, end))
return nullptr;
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (!exprDependsOnThis(tok))
continue;
if (isThisChanged(tok, indirect, settings))
return tok;
}
return nullptr;
}
template<class Find>
static const Token* findExpressionChangedImpl(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
int depth,
Find find)
{
if (depth < 0)
return start;
if (!precedes(start, end))
return nullptr;
const Token* result = nullptr;
findAstNode(expr, [&](const Token* tok) {
if (exprDependsOnThis(tok)) {
result = findThisChanged(start, end, /*indirect*/ 0, settings);
if (result)
return true;
}
bool global = false;
if (tok->variable()) {
if (tok->variable()->isConst())
return false;
global = !tok->variable()->isLocal() && !tok->variable()->isArgument() &&
!(tok->variable()->isMember() && !tok->variable()->isStatic());
} else if (tok->isIncompleteVar() && !tok->isIncompleteConstant()) {
global = true;
}
if (tok->exprId() > 0 || global) {
const Token* modifedTok = find(start, end, [&](const Token* tok2) {
int indirect = 0;
if (const ValueType* vt = tok->valueType()) {
indirect = vt->pointer;
if (vt->type == ValueType::ITERATOR)
++indirect;
}
for (int i = 0; i <= indirect; ++i) {
if (isExpressionChangedAt(tok, tok2, i, global, settings, depth))
return true;
}
return false;
});
if (modifedTok) {
result = modifedTok;
return true;
}
}
return false;
});
return result;
}
namespace {
struct ExpressionChangedSimpleFind {
template<class F>
const Token* operator()(const Token* start, const Token* end, F f) const
{
return findToken(start, end, f);
}
};
struct ExpressionChangedSkipDeadCode {
const Library& library;
const std::function<std::vector<MathLib::bigint>(const Token* tok)>* evaluate;
ExpressionChangedSkipDeadCode(const Library& library,
const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate)
: library(library), evaluate(&evaluate)
{}
template<class F>
const Token* operator()(const Token* start, const Token* end, F f) const
{
return findTokenSkipDeadCode(library, start, end, std::move(f), *evaluate);
}
};
}
const Token* findExpressionChanged(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
int depth)
{
return findExpressionChangedImpl(expr, start, end, settings, depth, ExpressionChangedSimpleFind{});
}
const Token* findExpressionChangedSkipDeadCode(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate,
int depth)
{
return findExpressionChangedImpl(
expr, start, end, settings, depth, ExpressionChangedSkipDeadCode{settings.library, evaluate});
}
const Token* getArgumentStart(const Token* ftok)
{
const Token* tok = ftok;
if (Token::Match(tok, "%name% (|{|)"))
tok = ftok->next();
while (Token::simpleMatch(tok, ")"))
tok = tok->next();
if (!Token::Match(tok, "(|{|["))
return nullptr;
const Token* startTok = tok->astOperand2();
if (!startTok && tok->next() != tok->link())
startTok = tok->astOperand1();
return startTok;
}
int numberOfArguments(const Token* ftok) {
return astCount(getArgumentStart(ftok), ",");
}
int numberOfArgumentsWithoutAst(const Token* start)
{
int arguments = 0;
const Token* openBracket = start->next();
while (Token::simpleMatch(openBracket, ")"))
openBracket = openBracket->next();
if (openBracket && openBracket->str()=="(" && openBracket->next() && openBracket->strAt(1)!=")") {
const Token* argument=openBracket->next();
while (argument) {
++arguments;
argument = argument->nextArgument();
}
}
return arguments;
}
std::vector<const Token*> getArguments(const Token* ftok) {
return astFlatten(getArgumentStart(ftok), ",");
}
int getArgumentPos(const Variable* var, const Function* f)
{
auto arg_it = std::find_if(f->argumentList.cbegin(), f->argumentList.cend(), [&](const Variable& v) {
return v.nameToken() == var->nameToken();
});
if (arg_it == f->argumentList.end())
return -1;
return std::distance(f->argumentList.cbegin(), arg_it);
}
const Token* getIteratorExpression(const Token* tok)
{
if (!tok)
return nullptr;
if (tok->isUnaryOp("*"))
return nullptr;
if (!tok->isName()) {
const Token* iter1 = getIteratorExpression(tok->astOperand1());
if (iter1)
return iter1;
if (tok->str() == "(")
return nullptr;
const Token* iter2 = getIteratorExpression(tok->astOperand2());
if (iter2)
return iter2;
} else if (Token::Match(tok, "begin|cbegin|rbegin|crbegin|end|cend|rend|crend (")) {
if (Token::Match(tok->previous(), ". %name% ( ) !!."))
return tok->previous()->astOperand1();
if (!Token::simpleMatch(tok->previous(), ".") && Token::Match(tok, "%name% ( !!)") &&
!Token::simpleMatch(tok->linkAt(1), ") ."))
return tok->next()->astOperand2();
}
return nullptr;
}
bool isIteratorPair(const std::vector<const Token*>& args)
{
if (args.size() != 2)
return false;
if (astIsPointer(args[0]) && astIsPointer(args[1]))
return true;
// Check if iterator is from same container
const Token* tok1 = nullptr;
const Token* tok2 = nullptr;
if (astIsIterator(args[0]) && astIsIterator(args[1])) {
tok1 = ValueFlow::getLifetimeObjValue(args[0]).tokvalue;
tok2 = ValueFlow::getLifetimeObjValue(args[1]).tokvalue;
if (!tok1 || !tok2)
return true;
} else {
tok1 = getIteratorExpression(args[0]);
tok2 = getIteratorExpression(args[1]);
}
if (tok1 && tok2)
return tok1->exprId() == tok2->exprId();
return tok1 || tok2;
}
const Token *findLambdaStartToken(const Token *last)
{
if (!last || !last->isCpp() || last->str() != "}")
return nullptr;
const Token* tok = last->link();
if (Token::simpleMatch(tok->astParent(), "("))
tok = tok->astParent();
if (Token::simpleMatch(tok->astParent(), "["))
return tok->astParent();
return nullptr;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* findLambdaEndTokenGeneric(T* first)
{
auto maybeLambda = [](T* tok) -> bool {
while (Token::Match(tok, "*|%name%|::|>")) {
if (tok->link())
tok = tok->link()->previous();
else {
if (tok->str() == ">")
return true;
if (tok->str() == "new")
return false;
tok = tok->previous();
}
}
return true;
};
if (!first || !first->isCpp() || first->str() != "[")
return nullptr;
if (!maybeLambda(first->previous()))
return nullptr;
if (!Token::Match(first->link(), "] (|{|<"))
return nullptr;
const Token* roundOrCurly = first->link()->next();
if (roundOrCurly->link() && roundOrCurly->str() == "<")
roundOrCurly = roundOrCurly->link()->next();
if (first->astOperand1() != roundOrCurly)
return nullptr;
T * tok = first;
if (tok->astOperand1() && tok->astOperand1()->str() == "(")
tok = tok->astOperand1();
if (tok->astOperand1() && tok->astOperand1()->str() == "{")
return tok->astOperand1()->link();
return nullptr;
}
const Token* findLambdaEndToken(const Token* first)
{
return findLambdaEndTokenGeneric(first);
}
Token* findLambdaEndToken(Token* first)
{
return findLambdaEndTokenGeneric(first);
}
bool isLikelyStream(const Token *stream)
{
if (!stream)
return false;
if (!stream->isCpp())
return false;
if (!Token::Match(stream->astParent(), "&|<<|>>") || !stream->astParent()->isBinaryOp())
return false;
if (stream->astParent()->astOperand1() != stream)
return false;
return !astIsIntegral(stream, false);
}
bool isLikelyStreamRead(const Token *op)
{
if (!op)
return false;
if (!op->isCpp())
return false;
if (!Token::Match(op, "&|>>") || !op->isBinaryOp())
return false;
if (!Token::Match(op->astOperand2(), "%name%|.|*|[") && op->str() != op->astOperand2()->str())
return false;
const Token *parent = op;
while (parent->astParent() && parent->astParent()->str() == op->str())
parent = parent->astParent();
if (parent->astParent() && !Token::Match(parent->astParent(), "%oror%|&&|(|,|.|!|;|return"))
return false;
if (op->str() == "&" && parent->astParent())
return false;
if (!parent->astOperand1() || !parent->astOperand2())
return false;
return (!parent->astOperand1()->valueType() || !parent->astOperand1()->valueType()->isIntegral());
}
bool isCPPCast(const Token* tok)
{
return tok && Token::simpleMatch(tok->previous(), "> (") && tok->astOperand2() && tok->astOperand1() && isCPPCastKeyword(tok->astOperand1());
}
bool isConstVarExpression(const Token *tok, const std::function<bool(const Token*)>& skipPredicate)
{
if (!tok)
return false;
if (tok->str() == "?" && tok->astOperand2() && tok->astOperand2()->str() == ":") // ternary operator
return isConstVarExpression(tok->astOperand2()->astOperand1()) && isConstVarExpression(tok->astOperand2()->astOperand2()); // left and right of ":"
if (skipPredicate && skipPredicate(tok))
return false;
if (Token::simpleMatch(tok->previous(), "sizeof ("))
return true;
if (Token::Match(tok->previous(), "%name% (")) {
if (Token::simpleMatch(tok->astOperand1(), ".") && !isConstVarExpression(tok->astOperand1(), skipPredicate))
return false;
std::vector<const Token *> args = getArguments(tok);
if (args.empty() && tok->previous()->function() && tok->previous()->function()->isConstexpr())
return true;
return !args.empty() && std::all_of(args.cbegin(), args.cend(), [&](const Token* t) {
return isConstVarExpression(t, skipPredicate);
});
}
if (isCPPCast(tok)) {
return isConstVarExpression(tok->astOperand2(), skipPredicate);
}
if (Token::Match(tok, "( %type%"))
return isConstVarExpression(tok->astOperand1(), skipPredicate);
if (tok->str() == "::" && tok->hasKnownValue())
return isConstVarExpression(tok->astOperand2(), skipPredicate);
if (Token::Match(tok, "%cop%|[|.")) {
if (tok->astOperand1() && !isConstVarExpression(tok->astOperand1(), skipPredicate))
return false;
if (tok->astOperand2() && !isConstVarExpression(tok->astOperand2(), skipPredicate))
return false;
return true;
}
if (Token::Match(tok, "%bool%|%num%|%str%|%char%|nullptr|NULL"))
return true;
if (tok->isEnumerator())
return true;
if (tok->variable())
return tok->variable()->isConst() && tok->variable()->nameToken() && tok->variable()->nameToken()->hasKnownValue();
return false;
}
static ExprUsage getFunctionUsage(const Token* tok, int indirect, const Settings& settings)
{
const bool addressOf = tok->astParent() && tok->astParent()->isUnaryOp("&");
int argnr;
const Token* ftok = getTokenArgumentFunction(tok, argnr);
if (!ftok)
return ExprUsage::None;
const Function* func = ftok->function();
// variable init/constructor call?
if (!func && ftok->variable() && ftok == ftok->variable()->nameToken()) {
// STL types or containers don't initialize external variables
if (ftok->variable()->isStlType() || (ftok->variable()->valueType() && ftok->variable()->valueType()->container))
return ExprUsage::Used;
// TODO: resolve multiple constructors
if (ftok->variable()->type() && ftok->variable()->type()->classScope) {
const int nCtor = ftok->variable()->type()->classScope->numConstructors;
if (nCtor == 0)
return ExprUsage::Used;
if (nCtor == 1) {
const Scope* scope = ftok->variable()->type()->classScope;
auto it = std::find_if(scope->functionList.begin(), scope->functionList.end(), [](const Function& f) {
return f.isConstructor();
});
if (it != scope->functionList.end())
func = &*it;
}
}
}
if (func) {
std::vector<const Variable*> args = getArgumentVars(ftok, argnr);
for (const Variable* arg : args) {
if (!arg)
continue;
if (arg->isReference() || (arg->isPointer() && indirect == 1)) {
if (!func->hasBody())
return ExprUsage::PassedByReference;
for (const Token* bodytok = func->functionScope->bodyStart; bodytok != func->functionScope->bodyEnd; bodytok = bodytok->next()) {
if (bodytok->variable() == arg) {
if (arg->isReference())
return ExprUsage::PassedByReference;
if (Token::Match(bodytok->astParent(), "%comp%|!"))
return ExprUsage::NotUsed;
return ExprUsage::PassedByReference;
}
}
return ExprUsage::NotUsed;
}
}
if (!args.empty() && indirect == 0 && !addressOf)
return ExprUsage::Used;
} else if (ftok->isControlFlowKeyword()) {
return ExprUsage::Used;
} else if (ftok->str() == "{") {
return indirect == 0 ? ExprUsage::Used : ExprUsage::Inconclusive;
} else {
const bool isnullbad = settings.library.isnullargbad(ftok, argnr + 1);
if (indirect == 0 && astIsPointer(tok) && !addressOf && isnullbad)
return ExprUsage::Used;
bool hasIndirect = false;
const bool isuninitbad = settings.library.isuninitargbad(ftok, argnr + 1, indirect, &hasIndirect);
if (isuninitbad && (!addressOf || isnullbad))
return ExprUsage::Used;
}
return ExprUsage::Inconclusive;
}
bool isLeafDot(const Token* tok)
{
if (!tok)
return false;
const Token * parent = tok->astParent();
if (!Token::simpleMatch(parent, "."))
return false;
if (parent->astOperand2() == tok && !Token::simpleMatch(parent->astParent(), "."))
return true;
return isLeafDot(parent);
}
ExprUsage getExprUsage(const Token* tok, int indirect, const Settings& settings)
{
const Token* parent = tok->astParent();
if (indirect > 0 && parent) {
while (Token::simpleMatch(parent, "[") && parent->astParent())
parent = parent->astParent();
if (Token::Match(parent, "%assign%") && (astIsRHS(tok) || astIsLHS(parent->astOperand1())))
return ExprUsage::NotUsed;
if (Token::Match(parent, "++|--"))
return ExprUsage::NotUsed;
if (parent->isConstOp())
return ExprUsage::NotUsed;
if (parent->isCast())
return ExprUsage::NotUsed;
if (Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "?"))
return getExprUsage(parent->astParent(), indirect, settings);
if (isUsedAsBool(tok, settings))
return ExprUsage::NotUsed;
}
if (tok->isUnaryOp("&") && !parent)
return ExprUsage::NotUsed;
if (indirect == 0) {
if (Token::Match(parent, "%cop%|%assign%|++|--") && parent->str() != "=" &&
!parent->isUnaryOp("&") &&
!(astIsRHS(tok) && isLikelyStreamRead(parent)))
return ExprUsage::Used;
if (isLeafDot(tok)) {
const Token* op = parent->astParent();
while (Token::simpleMatch(op, "."))
op = op->astParent();
if (Token::Match(op, "%assign%|++|--")) {
if (op->str() == "=") {
if (precedes(tok, op))
return ExprUsage::NotUsed;
} else
return ExprUsage::Used;
}
}
if (Token::simpleMatch(parent, "=") && astIsRHS(tok)) {
const Token* const lhs = parent->astOperand1();
if (lhs && lhs->variable() && lhs->variable()->isReference() && lhs == lhs->variable()->nameToken())
return ExprUsage::NotUsed;
return ExprUsage::Used;
}
// Function call or index
if (((Token::simpleMatch(parent, "(") && !parent->isCast()) || (Token::simpleMatch(parent, "[") && tok->valueType())) &&
(astIsLHS(tok) || Token::simpleMatch(parent, "( )")))
return ExprUsage::Used;
}
return getFunctionUsage(tok, indirect, settings);
}
static void getLHSVariablesRecursive(std::vector<const Variable*>& vars, const Token* tok)
{
if (!tok)
return;
if (vars.empty() && Token::Match(tok, "*|&|&&|[")) {
getLHSVariablesRecursive(vars, tok->astOperand1());
if (!vars.empty() || Token::simpleMatch(tok, "["))
return;
getLHSVariablesRecursive(vars, tok->astOperand2());
} else if (Token::Match(tok->previous(), "this . %var%")) {
getLHSVariablesRecursive(vars, tok->next());
} else if (Token::simpleMatch(tok, ".")) {
getLHSVariablesRecursive(vars, tok->astOperand1());
getLHSVariablesRecursive(vars, tok->astOperand2());
} else if (Token::simpleMatch(tok, "::")) {
getLHSVariablesRecursive(vars, tok->astOperand2());
} else if (tok->variable()) {
vars.push_back(tok->variable());
}
}
std::vector<const Variable*> getLHSVariables(const Token* tok)
{
std::vector<const Variable*> result;
if (!Token::Match(tok, "%assign%|(|{"))
return result;
if (!tok->astOperand1())
return result;
if (tok->astOperand1()->varId() > 0 && tok->astOperand1()->variable())
return {tok->astOperand1()->variable()};
getLHSVariablesRecursive(result, tok->astOperand1());
return result;
}
static const Token* getLHSVariableRecursive(const Token* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok, "*|&|&&|[")) {
const Token* vartok = getLHSVariableRecursive(tok->astOperand1());
if ((vartok && vartok->variable()) || Token::simpleMatch(tok, "["))
return vartok;
return getLHSVariableRecursive(tok->astOperand2());
}
if (Token::Match(tok->previous(), "this . %var%"))
return tok->next();
return tok;
}
const Variable *getLHSVariable(const Token *tok)
{
if (!tok || !tok->isAssignmentOp())
return nullptr;
if (!tok->astOperand1())
return nullptr;
if (tok->astOperand1()->varId() > 0 && tok->astOperand1()->variable())
return tok->astOperand1()->variable();
const Token* vartok = getLHSVariableRecursive(tok->astOperand1());
if (!vartok)
return nullptr;
return vartok->variable();
}
const Token* getLHSVariableToken(const Token* tok)
{
if (!Token::Match(tok, "%assign%"))
return nullptr;
if (!tok->astOperand1())
return nullptr;
if (tok->astOperand1()->varId() > 0)
return tok->astOperand1();
const Token* vartok = getLHSVariableRecursive(tok->astOperand1());
if (vartok && vartok->variable() && vartok->variable()->nameToken() == vartok)
return vartok;
return tok->astOperand1();
}
const Token* findAllocFuncCallToken(const Token *expr, const Library &library)
{
if (!expr)
return nullptr;
if (Token::Match(expr, "[+-]")) {
const Token *tok1 = findAllocFuncCallToken(expr->astOperand1(), library);
return tok1 ? tok1 : findAllocFuncCallToken(expr->astOperand2(), library);
}
if (expr->isCast())
return findAllocFuncCallToken(expr->astOperand2() ? expr->astOperand2() : expr->astOperand1(), library);
if (Token::Match(expr->previous(), "%name% (") && library.getAllocFuncInfo(expr->astOperand1()))
return expr->astOperand1();
return (Token::simpleMatch(expr, "new") && expr->astOperand1()) ? expr : nullptr;
}
bool isNullOperand(const Token *expr)
{
if (!expr)
return false;
if (expr->isCpp() && Token::Match(expr, "static_cast|const_cast|dynamic_cast|reinterpret_cast <"))
expr = expr->astParent();
else if (!expr->isCast())
return Token::Match(expr, "NULL|nullptr");
if (expr->valueType() && expr->valueType()->pointer == 0)
return false;
const Token *castOp = expr->astOperand2() ? expr->astOperand2() : expr->astOperand1();
return Token::Match(castOp, "NULL|nullptr") || (MathLib::isInt(castOp->str()) && MathLib::isNullValue(castOp->str()));
}
bool isGlobalData(const Token *expr)
{
// function call that returns reference => assume global data
if (expr && expr->str() == "(" && expr->valueType() && expr->valueType()->reference != Reference::None) {
if (expr->isBinaryOp())
return true;
if (expr->astOperand1() && precedes(expr->astOperand1(), expr))
return true;
}
bool globalData = false;
bool var = false;
visitAstNodes(expr,
[expr, &globalData, &var](const Token *tok) {
if (tok->varId())
var = true;
if (tok->varId() && !tok->variable()) {
// Bailout, this is probably global
globalData = true;
return ChildrenToVisit::none;
}
if (tok->originalName() == "->") {
// TODO check if pointer points at local data
globalData = true;
return ChildrenToVisit::none;
}
if (Token::Match(tok, "[*[]") && tok->astOperand1() && tok->astOperand1()->variable()) {
// TODO check if pointer points at local data
const Variable *lhsvar = tok->astOperand1()->variable();
const ValueType *lhstype = tok->astOperand1()->valueType();
if (lhsvar->isPointer()) {
globalData = true;
return ChildrenToVisit::none;
}
if (lhsvar->isArgument() && lhsvar->isArray()) {
globalData = true;
return ChildrenToVisit::none;
}
if (lhsvar->isArgument() && (!lhstype || (lhstype->type <= ValueType::Type::VOID && !lhstype->container))) {
globalData = true;
return ChildrenToVisit::none;
}
}
if (tok->varId() == 0 && tok->isName() && tok->strAt(-1) != ".") {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()) {
// TODO : Check references
if (tok->variable()->isReference() && tok != tok->variable()->nameToken()) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()->isExtern()) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->strAt(-1) != "." && !tok->variable()->isLocal() && !tok->variable()->isArgument()) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()->isArgument() && tok->variable()->isPointer() && tok != expr) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()->isPointerArray()) {
globalData = true;
return ChildrenToVisit::none;
}
}
// Unknown argument type => it might be some reference type..
if (tok->isCpp() && tok->str() == "." && tok->astOperand1() && tok->astOperand1()->variable() && !tok->astOperand1()->valueType()) {
globalData = true;
return ChildrenToVisit::none;
}
if (Token::Match(tok, ".|["))
return ChildrenToVisit::op1;
return ChildrenToVisit::op1_and_op2;
});
return globalData || !var;
}
bool isUnevaluated(const Token *tok)
{
return Token::Match(tok, "alignof|_Alignof|_alignof|__alignof|__alignof__|decltype|offsetof|sizeof|typeid|typeof|__typeof__ (");
}
static std::set<MathLib::bigint> getSwitchValues(const Token *startbrace, bool &hasDefault)
{
std::set<MathLib::bigint> values;
const Token *endbrace = startbrace->link();
if (!endbrace)
return values;
hasDefault = false;
for (const Token *tok = startbrace->next(); tok && tok != endbrace; tok = tok->next()) {
if (Token::simpleMatch(tok, "{") && tok->scope()->type == Scope::ScopeType::eSwitch) {
tok = tok->link();
continue;
}
if (Token::simpleMatch(tok, "default")) {
hasDefault = true;
break;
}
if (Token::simpleMatch(tok, "case")) {
const Token *valueTok = tok->astOperand1();
if (valueTok->hasKnownIntValue())
values.insert(valueTok->getKnownIntValue());
continue;
}
}
return values;
}
bool isExhaustiveSwitch(const Token *startbrace)
{
if (!startbrace || !Token::simpleMatch(startbrace->previous(), ") {") || startbrace->scope()->type != Scope::ScopeType::eSwitch)
return false;
const Token *rpar = startbrace->previous();
const Token *lpar = rpar->link();
const Token *condition = lpar->astOperand2();
if (!condition->valueType())
return true;
bool hasDefault = false;
const std::set<MathLib::bigint> switchValues = getSwitchValues(startbrace, hasDefault);
if (hasDefault)
return true;
if (condition->valueType()->type == ValueType::Type::BOOL)
return switchValues.count(0) && switchValues.count(1);
if (condition->valueType()->isEnum()) {
const std::vector<Enumerator> &enumList = condition->valueType()->typeScope->enumeratorList;
return std::all_of(enumList.cbegin(), enumList.cend(), [&](const Enumerator &e) {
return !e.value_known || switchValues.count(e.value);
});
}
return false;
}
bool isUnreachableOperand(const Token *tok)
{
for (;;)
{
const Token *parent = tok->astParent();
if (!parent)
break;
if (parent->isBinaryOp()) {
const bool left = tok == parent->astOperand1();
const Token *sibling = left ? parent->astOperand2() : parent->astOperand1();
// logical and
if (Token::simpleMatch(parent, "&&") && !left && sibling->hasKnownIntValue()
&& !sibling->getKnownIntValue())
return true;
// logical or
if (Token::simpleMatch(parent, "||") && !left && sibling->hasKnownIntValue()
&& sibling->getKnownIntValue())
return true;
// ternary
if (Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "?")) {
const Token *condTok = parent->astParent()->astOperand1();
if (condTok->hasKnownIntValue() && static_cast<bool>(condTok->getKnownIntValue()) != left)
return true;
}
}
tok = parent;
}
return false;
}
static bool unknownLeafValuesAreTemplateArgs(const Token *tok)
{
if (!tok)
return true;
if (!tok->astOperand1() && !tok->astOperand2())
return tok->isTemplateArg() || tok->hasKnownIntValue();
return unknownLeafValuesAreTemplateArgs(tok->astOperand1())
&& unknownLeafValuesAreTemplateArgs(tok->astOperand2());
}
static const Token *skipUnreachableIfBranch(const Token *tok)
{
const Token *condTok = tok->linkAt(-1);
if (!condTok)
return tok;
if (!Token::simpleMatch(condTok->tokAt(-1), "if") && !Token::simpleMatch(condTok->tokAt(-2), "if constexpr"))
return tok;
condTok = condTok->astOperand2();
if (!condTok)
return tok;
if ((condTok->hasKnownIntValue() && condTok->getKnownIntValue() == 0)
|| (unknownLeafValuesAreTemplateArgs(condTok) && condTok->getValue(0))) {
tok = tok->link();
}
return tok;
}
static const Token *skipUnreachableElseBranch(const Token *tok)
{
if (!Token::simpleMatch(tok->tokAt(-2), "} else {"))
return tok;
const Token *condTok = tok->linkAt(-2);
if (!condTok)
return tok;
condTok = condTok->linkAt(-1);
if (!condTok)
return tok;
if (!Token::simpleMatch(condTok->tokAt(-1), "if (") && !Token::simpleMatch(condTok->tokAt(-2), "if constexpr ("))
return tok;
condTok = condTok->astOperand2();
if ((condTok->hasKnownIntValue() && condTok->getKnownIntValue() != 0)
|| (unknownLeafValuesAreTemplateArgs(condTok) && condTok->getValueNE(0))) {
tok = tok->link();
}
return tok;
}
const Token *skipUnreachableBranch(const Token *tok)
{
if (!Token::simpleMatch(tok, "{"))
return tok;
if (tok->scope()->type == Scope::ScopeType::eIf) {
return skipUnreachableIfBranch(tok);
}
if (tok->scope()->type == Scope::ScopeType::eElse) {
return skipUnreachableElseBranch(tok);
}
return tok;
}
|