DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "jit/IonControlFlow.h"

#include "mozilla/DebugOnly.h"

using namespace js;
using namespace js::jit;
using mozilla::DebugOnly;

ControlFlowGenerator::ControlFlowGenerator(TempAllocator& temp,
                                           JSScript* script)
    : script(script),
      current(nullptr),
      pc(nullptr),
      alloc_(temp),
      blocks_(temp),
      cfgStack_(temp),
      loops_(temp),
      switches_(temp),
      labels_(temp),
      aborted_(false),
      checkedTryFinally_(false) {}

static inline int32_t GetJumpOffset(jsbytecode* pc) {
  MOZ_ASSERT(CodeSpec[JSOp(*pc)].type() == JOF_JUMP);
  return GET_JUMP_OFFSET(pc);
}

void ControlFlowGraph::dump(GenericPrinter& print, JSScript* script) {
  if (blocks_.length() == 0) {
    print.printf("Didn't run yet.\n");
    return;
  }

  fprintf(stderr, "Dumping cfg:\n\n");
  for (size_t i = 0; i < blocks_.length(); i++) {
    print.printf(" Block %zu, %zu:%zu\n", blocks_[i].id(),
                 script->pcToOffset(blocks_[i].startPc()),
                 script->pcToOffset(blocks_[i].stopPc()));

    jsbytecode* pc = blocks_[i].startPc();
    for (; pc < blocks_[i].stopPc(); pc += CodeSpec[JSOp(*pc)].length) {
      MOZ_ASSERT(pc < script->codeEnd());
      print.printf("  %zu: %s\n", script->pcToOffset(pc), CodeName[JSOp(*pc)]);
    }

    if (blocks_[i].stopIns()->isGoto()) {
      print.printf("  %s (popping:%zu) [", blocks_[i].stopIns()->Name(),
                   blocks_[i].stopIns()->toGoto()->popAmount());
    } else {
      print.printf("  %s [", blocks_[i].stopIns()->Name());
    }
    for (size_t j = 0; j < blocks_[i].stopIns()->numSuccessors(); j++) {
      if (j != 0) {
        print.printf(", ");
      }
      print.printf("%zu", blocks_[i].stopIns()->getSuccessor(j)->id());
    }
    print.printf("]\n\n");
  }
}

bool ControlFlowGraph::init(TempAllocator& alloc,
                            const CFGBlockVector& blocks) {
  if (!blocks_.reserve(blocks.length())) {
    return false;
  }

  for (size_t i = 0; i < blocks.length(); i++) {
    MOZ_ASSERT(blocks[i]->id() == i);
    CFGBlock block(blocks[i]->startPc());

    block.setStopPc(blocks[i]->stopPc());
    block.setId(i);
    blocks_.infallibleAppend(std::move(block));
  }

  for (size_t i = 0; i < blocks.length(); i++) {
    if (!alloc.ensureBallast()) {
      return false;
    }

    CFGControlInstruction* copy = nullptr;
    CFGControlInstruction* ins = blocks[i]->stopIns();
    switch (ins->type()) {
      case CFGControlInstruction::Type_Goto: {
        CFGBlock* successor = &blocks_[ins->getSuccessor(0)->id()];
        copy = CFGGoto::CopyWithNewTargets(alloc, ins->toGoto(), successor);
        break;
      }
      case CFGControlInstruction::Type_BackEdge: {
        CFGBlock* successor = &blocks_[ins->getSuccessor(0)->id()];
        copy = CFGBackEdge::CopyWithNewTargets(alloc, ins->toBackEdge(),
                                               successor);
        break;
      }
      case CFGControlInstruction::Type_LoopEntry: {
        CFGLoopEntry* old = ins->toLoopEntry();
        CFGBlock* successor = &blocks_[ins->getSuccessor(0)->id()];
        copy = CFGLoopEntry::CopyWithNewTargets(alloc, old, successor);
        break;
      }
      case CFGControlInstruction::Type_Throw: {
        copy = CFGThrow::New(alloc);
        break;
      }
      case CFGControlInstruction::Type_Test: {
        CFGTest* old = ins->toTest();
        CFGBlock* trueBranch = &blocks_[old->trueBranch()->id()];
        CFGBlock* falseBranch = &blocks_[old->falseBranch()->id()];
        copy = CFGTest::CopyWithNewTargets(alloc, old, trueBranch, falseBranch);
        break;
      }
      case CFGControlInstruction::Type_CondSwitchCase: {
        CFGCondSwitchCase* old = ins->toCondSwitchCase();
        CFGBlock* trueBranch = &blocks_[old->trueBranch()->id()];
        CFGBlock* falseBranch = &blocks_[old->falseBranch()->id()];
        copy = CFGCondSwitchCase::CopyWithNewTargets(alloc, old, trueBranch,
                                                     falseBranch);
        break;
      }
      case CFGControlInstruction::Type_Return: {
        copy = CFGReturn::New(alloc);
        break;
      }
      case CFGControlInstruction::Type_RetRVal: {
        copy = CFGRetRVal::New(alloc);
        break;
      }
      case CFGControlInstruction::Type_Try: {
        CFGTry* old = ins->toTry();
        CFGBlock* tryBlock = &blocks_[old->tryBlock()->id()];
        CFGBlock* merge = nullptr;
        if (old->numSuccessors() == 2) {
          merge = &blocks_[old->afterTryCatchBlock()->id()];
        }
        copy = CFGTry::CopyWithNewTargets(alloc, old, tryBlock, merge);
        break;
      }
      case CFGControlInstruction::Type_TableSwitch: {
        CFGTableSwitch* old = ins->toTableSwitch();
        CFGTableSwitch* tableSwitch =
            CFGTableSwitch::New(alloc, old->low(), old->high());
        if (!tableSwitch->addDefault(&blocks_[old->defaultCase()->id()])) {
          return false;
        }
        for (size_t i = 0; i < ins->numSuccessors() - 1; i++) {
          if (!tableSwitch->addCase(&blocks_[old->getCase(i)->id()])) {
            return false;
          }
        }
        copy = tableSwitch;
        break;
      }
    }
    MOZ_ASSERT(copy);
    blocks_[i].setStopIns(copy);
  }
  return true;
}

bool ControlFlowGenerator::addBlock(CFGBlock* block) {
  block->setId(blocks_.length());
  return blocks_.append(block);
}

// We try to build a control-flow graph in the order that it would be built as
// if traversing the AST. This leads to a nice ordering and lets us build SSA
// in one pass, since the bytecode is structured.
//
// Things get interesting when we encounter a control structure. This can be
// either an IFEQ, downward GOTO, or a decompiler hint stashed away in source
// notes. Once we encounter such an opcode, we recover the structure of the
// control flow (its branches and bounds), and push it on a stack.
//
// As we continue traversing the bytecode, we look for points that would
// terminate the topmost control flow path pushed on the stack. These are:
//  (1) The bounds of the current structure (end of a loop or join/edge of a
//      branch).
//  (2) A "return", "break", or "continue" statement.
//
// For (1), we expect that there is a current block in the progress of being
// built, and we complete the necessary edges in the CFG. For (2), we expect
// that there is no active block.
bool ControlFlowGenerator::traverseBytecode() {
  blocks_.clear();

  current = CFGBlock::New(alloc(), script->code());
  pc = current->startPc();

  if (!addBlock(current)) {
    return false;
  }

  for (;;) {
    MOZ_ASSERT(pc < script->codeEnd());

    for (;;) {
      if (!alloc().ensureBallast()) {
        return false;
      }

      // Check if we've hit an expected join point or edge in the bytecode.
      // Leaving one control structure could place us at the edge of another,
      // thus |while| instead of |if| so we don't skip any opcodes.
      MOZ_ASSERT_IF(!cfgStack_.empty(), cfgStack_.back().stopAt >= pc);
      if (!cfgStack_.empty() && cfgStack_.back().stopAt == pc) {
        ControlStatus status = processCfgStack();
        if (status == ControlStatus::Error) {
          return false;
        }
        if (status == ControlStatus::Abort) {
          aborted_ = true;
          return false;
        }
        if (!current) {
          return true;
        }
        continue;
      }

      // Some opcodes need to be handled early because they affect control
      // flow, terminating the current basic block and/or instructing the
      // traversal algorithm to continue from a new pc.
      //
      //   (1) If the opcode does not affect control flow, then the opcode
      //       is inspected and transformed to IR. This is the process_opcode
      //       label.
      //   (2) A loop could be detected via a forward GOTO. In this case,
      //       we don't want to process the GOTO, but the following
      //       instruction.
      //   (3) A RETURN, STOP, BREAK, or CONTINUE may require processing the
      //       CFG stack to terminate open branches.
      //
      // Similar to above, snooping control flow could land us at another
      // control flow point, so we iterate until it's time to inspect a real
      // opcode.
      ControlStatus status;
      if ((status = snoopControlFlow(JSOp(*pc))) == ControlStatus::None) {
        break;
      }
      if (status == ControlStatus::Error) {
        return false;
      }
      if (status == ControlStatus::Abort) {
        aborted_ = true;
        return false;
      }
      if (!current) {
        return true;
      }
    }

    JSOp op = JSOp(*pc);
    pc += CodeSpec[op].length;
  }
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::snoopControlFlow(
    JSOp op) {
  switch (op) {
    case JSOP_NOP: {
      jssrcnote* sn = GetSrcNote(gsn, script, pc);
      if (sn && SN_TYPE(sn) == SRC_FOR) {
        return processForLoop(op, sn);
      }
      break;
    }

    case JSOP_RETURN:
    case JSOP_RETRVAL:
      return processReturn(op);

    case JSOP_THROW:
      return processThrow();

    case JSOP_GOTO: {
      jssrcnote* sn = GetSrcNote(gsn, script, pc);
      switch (sn ? SN_TYPE(sn) : SRC_NULL) {
        case SRC_BREAK:
        case SRC_BREAK2LABEL:
          return processBreak(op, sn);

        case SRC_CONTINUE:
          return processContinue(op);

        case SRC_SWITCHBREAK:
          return processSwitchBreak(op);

        case SRC_WHILE:
        case SRC_FOR_IN:
        case SRC_FOR_OF:
          // while (cond) { }
          return processWhileOrForInOrForOfLoop(sn);

        default:
          // Hard assert for now - make an error later.
          MOZ_CRASH("unknown goto case");
      }
      break;
    }

    case JSOP_LOOPHEAD: {
      jssrcnote* sn = GetSrcNote(gsn, script, pc);
      if (sn && SN_TYPE(sn) == SRC_DO_WHILE) {
        return processDoWhileLoop(sn);
      }
      break;
    }

    case JSOP_TABLESWITCH: {
      jssrcnote* sn = GetSrcNote(gsn, script, pc);
      return processTableSwitch(op, sn);
    }

    case JSOP_CONDSWITCH:
      return processCondSwitch();

    case JSOP_IFNE:
      // We should never reach an IFNE, it's a stopAt point, which will
      // trigger closing the loop.
      MOZ_CRASH("we should never reach an ifne!");

    case JSOP_IFEQ:
      return processIfStart(JSOP_IFEQ);

    case JSOP_AND:
    case JSOP_OR:
      return processAndOr(op);

    case JSOP_LABEL:
      return processLabel();

    case JSOP_TRY:
      return processTry();

    case JSOP_THROWMSG:
      // Not implemented yet.
      return ControlStatus::Abort;

    default:
      break;
  }
  return ControlStatus::None;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processReturn(
    JSOp op) {
  MOZ_ASSERT(op == JSOP_RETURN || op == JSOP_RETRVAL);

  CFGControlInstruction* ins;
  if (op == JSOP_RETURN) {
    ins = CFGReturn::New(alloc());
  } else {
    ins = CFGRetRVal::New(alloc());
  }
  endCurrentBlock(ins);

  return processControlEnd();
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processThrow() {
  CFGThrow* ins = CFGThrow::New(alloc());
  endCurrentBlock(ins);

  return processControlEnd();
}

void ControlFlowGenerator::endCurrentBlock(CFGControlInstruction* ins) {
  current->setStopPc(pc);
  current->setStopIns(ins);

  // Make sure no one tries to use this block now.
  current = nullptr;
}

// Processes the top of the CFG stack. This is used from two places:
// (1) processControlEnd(), whereby a break, continue, or return may interrupt
//     an in-progress CFG structure before reaching its actual termination
//     point in the bytecode.
// (2) traverseBytecode(), whereby we reach the last instruction in a CFG
//     structure.
ControlFlowGenerator::ControlStatus ControlFlowGenerator::processCfgStack() {
  ControlStatus status = processCfgEntry(cfgStack_.back());

  // If this terminated a CFG structure, act like processControlEnd() and
  // keep propagating upward.
  while (status == ControlStatus::Ended) {
    popCfgStack();
    if (cfgStack_.empty()) {
      return status;
    }
    status = processCfgEntry(cfgStack_.back());
  }

  // If some join took place, the current structure is finished.
  if (status == ControlStatus::Joined) {
    popCfgStack();
  }

  return status;
}

// Given that the current control flow structure has ended forcefully,
// via a return, break, or continue (rather than joining), propagate the
// termination up. For example, a return nested 5 loops deep may terminate
// every outer loop at once, if there are no intervening conditionals:
//
// for (...) {
//   for (...) {
//     return x;
//   }
// }
//
// If |current| is nullptr when this function returns, then there is no more
// control flow to be processed.
ControlFlowGenerator::ControlStatus ControlFlowGenerator::processControlEnd() {
  MOZ_ASSERT(!current);

  if (cfgStack_.empty()) {
    // If there is no more control flow to process, then this is the
    // last return in the function.
    return ControlStatus::Ended;
  }

  return processCfgStack();
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processCfgEntry(
    CFGState& state) {
  switch (state.state) {
    case CFGState::IF_TRUE:
    case CFGState::IF_TRUE_EMPTY_ELSE:
      return processIfEnd(state);

    case CFGState::IF_ELSE_TRUE:
      return processIfElseTrueEnd(state);

    case CFGState::IF_ELSE_FALSE:
      return processIfElseFalseEnd(state);

    case CFGState::DO_WHILE_LOOP_BODY:
      return processDoWhileBodyEnd(state);

    case CFGState::DO_WHILE_LOOP_COND:
      return processDoWhileCondEnd(state);

    case CFGState::WHILE_LOOP_COND:
      return processWhileCondEnd(state);

    case CFGState::WHILE_LOOP_BODY:
      return processWhileBodyEnd(state);

    case CFGState::FOR_LOOP_COND:
      return processForCondEnd(state);

    case CFGState::FOR_LOOP_BODY:
      return processForBodyEnd(state);

    case CFGState::FOR_LOOP_UPDATE:
      return processForUpdateEnd(state);

    case CFGState::TABLE_SWITCH:
      return processNextTableSwitchCase(state);

    case CFGState::COND_SWITCH_CASE:
      return processCondSwitchCase(state);

    case CFGState::COND_SWITCH_BODY:
      return processCondSwitchBody(state);

    case CFGState::AND_OR:
      return processAndOrEnd(state);

    case CFGState::LABEL:
      return processLabelEnd(state);

    case CFGState::TRY:
      return processTryEnd(state);

    default:
      MOZ_CRASH("unknown cfgstate");
  }
}

void ControlFlowGenerator::popCfgStack() {
  if (cfgStack_.back().isLoop()) {
    loops_.popBack();
  }
  if (cfgStack_.back().state == CFGState::LABEL) {
    labels_.popBack();
  }
  cfgStack_.popBack();
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processLabelEnd(
    CFGState& state) {
  MOZ_ASSERT(state.state == CFGState::LABEL);

  // If there are no breaks and no current, controlflow is terminated.
  if (!state.label.breaks && !current) {
    return ControlStatus::Ended;
  }

  // If there are no breaks to this label, there's nothing to do.
  if (!state.label.breaks) {
    return ControlStatus::Joined;
  }

  CFGBlock* successor = createBreakCatchBlock(state.label.breaks, state.stopAt);
  if (!successor) {
    return ControlStatus::Error;
  }

  if (current) {
    current->setStopIns(CFGGoto::New(alloc(), successor));
    current->setStopPc(pc);
  }

  current = successor;
  pc = successor->startPc();

  if (!addBlock(successor)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processTry() {
  MOZ_ASSERT(JSOp(*pc) == JSOP_TRY);

  // Try-finally is not yet supported.
  if (!checkedTryFinally_) {
    for (const JSTryNote& tn : script->trynotes()) {
      if (tn.kind == JSTRY_FINALLY) {
        return ControlStatus::Abort;
      }
    }
    checkedTryFinally_ = true;
  }

  jssrcnote* sn = GetSrcNote(gsn, script, pc);
  MOZ_ASSERT(SN_TYPE(sn) == SRC_TRY);

  // Get the pc of the last instruction in the try block. It's a JSOP_GOTO to
  // jump over the catch block.
  jsbytecode* endpc =
      pc + GetSrcNoteOffset(sn, SrcNote::Try::EndOfTryJumpOffset);
  MOZ_ASSERT(JSOp(*endpc) == JSOP_GOTO);
  MOZ_ASSERT(GetJumpOffset(endpc) > 0);

  jsbytecode* afterTry = endpc + GetJumpOffset(endpc);

  // If controlflow in the try body is terminated (by a return or throw
  // statement), the code after the try-statement may still be reachable
  // via the catch block (which we don't compile) and OSR can enter it.
  // For example:
  //
  //     try {
  //         throw 3;
  //     } catch(e) { }
  //
  //     for (var i=0; i<1000; i++) {}
  //
  // To handle this, we create two blocks: one for the try block and one
  // for the code following the try-catch statement.

  CFGBlock* tryBlock = CFGBlock::New(alloc(), GetNextPc(pc));

  CFGBlock* successor = CFGBlock::New(alloc(), afterTry);
  current->setStopIns(CFGTry::New(alloc(), tryBlock, endpc, successor));
  current->setStopPc(pc);

  if (!cfgStack_.append(CFGState::Try(endpc, successor))) {
    return ControlStatus::Error;
  }

  current = tryBlock;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processTryEnd(
    CFGState& state) {
  MOZ_ASSERT(state.state == CFGState::TRY);
  MOZ_ASSERT(state.try_.successor);

  if (current) {
    current->setStopIns(CFGGoto::New(alloc(), state.try_.successor));
    current->setStopPc(pc);
  }

  // Start parsing the code after this try-catch statement.
  current = state.try_.successor;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processIfEnd(
    CFGState& state) {
  if (current) {
    // Here, the false block is the join point. Create an edge from the
    // current block to the false block. Note that a RETURN opcode
    // could have already ended the block.
    current->setStopIns(CFGGoto::New(alloc(), state.branch.ifFalse));
    current->setStopPc(pc);
  }

  current = state.branch.ifFalse;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processIfElseTrueEnd(
    CFGState& state) {
  // We've reached the end of the true branch of an if-else. Don't
  // create an edge yet, just transition to parsing the false branch.
  state.state = CFGState::IF_ELSE_FALSE;
  state.branch.ifTrue = current;
  state.stopAt = state.branch.falseEnd;

  if (current) {
    current->setStopPc(pc);
  }

  current = state.branch.ifFalse;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processIfElseFalseEnd(
    CFGState& state) {
  // Update the state to have the latest block from the false path.
  state.branch.ifFalse = current;
  if (current) {
    current->setStopPc(pc);
  }

  // To create the join node, we need an incoming edge that has not been
  // terminated yet.
  CFGBlock* pred =
      state.branch.ifTrue ? state.branch.ifTrue : state.branch.ifFalse;
  CFGBlock* other = (pred == state.branch.ifTrue) ? state.branch.ifFalse
                                                  : state.branch.ifTrue;

  if (!pred) {
    return ControlStatus::Ended;
  }

  // Create a new block to represent the join.
  CFGBlock* join = CFGBlock::New(alloc(), state.branch.falseEnd);

  // Create edges from the true and false blocks as needed.
  pred->setStopIns(CFGGoto::New(alloc(), join));

  if (other) {
    other->setStopIns(CFGGoto::New(alloc(), join));
  }

  // Ignore unreachable remainder of false block if existent.
  current = join;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

CFGBlock* ControlFlowGenerator::createBreakCatchBlock(DeferredEdge* edge,
                                                      jsbytecode* pc) {
  // Create block, using the first break statement as predecessor
  CFGBlock* successor = CFGBlock::New(alloc(), pc);

  // Finish up remaining breaks.
  while (edge) {
    if (!alloc().ensureBallast()) {
      return nullptr;
    }

    CFGGoto* brk = CFGGoto::New(alloc(), successor);
    edge->block->setStopIns(brk);
    edge = edge->next;
  }

  return successor;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processDoWhileBodyEnd(
    CFGState& state) {
  if (!processDeferredContinues(state)) {
    return ControlStatus::Error;
  }

  // No current means control flow cannot reach the condition, so this will
  // never loop.
  if (!current) {
    return processBrokenLoop(state);
  }

  CFGBlock* header = CFGBlock::New(alloc(), state.loop.updatepc);
  current->setStopIns(CFGGoto::New(alloc(), header));
  current->setStopPc(pc);

  state.state = CFGState::DO_WHILE_LOOP_COND;
  state.stopAt = state.loop.updateEnd;

  current = header;
  pc = header->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processDoWhileCondEnd(
    CFGState& state) {
  MOZ_ASSERT(JSOp(*pc) == JSOP_IFNE);

  // We're guaranteed a |current|, it's impossible to break or return from
  // inside the conditional expression.
  MOZ_ASSERT(current);

  // Create the successor block.
  CFGBlock* successor = CFGBlock::New(alloc(), GetNextPc(pc));

  CFGLoopEntry* entry = state.loop.entry->stopIns()->toLoopEntry();
  entry->setLoopStopPc(pc);

  // Create backedge with pc at start of loop to make sure we capture the
  // right stack.
  CFGBlock* backEdge = CFGBlock::New(alloc(), entry->successor()->startPc());
  backEdge->setStopIns(CFGBackEdge::New(alloc(), entry->successor()));
  backEdge->setStopPc(entry->successor()->startPc());

  if (!addBlock(backEdge)) {
    return ControlStatus::Error;
  }

  // Create the test instruction and end the current block.
  CFGTest* test = CFGTest::New(alloc(), backEdge, successor);
  current->setStopIns(test);
  current->setStopPc(pc);
  return finishLoop(state, successor);
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processWhileCondEnd(
    CFGState& state) {
  MOZ_ASSERT(JSOp(*pc) == JSOP_IFNE || JSOp(*pc) == JSOP_IFEQ);

  // Create the body and successor blocks.
  CFGBlock* body = CFGBlock::New(alloc(), state.loop.bodyStart);
  state.loop.successor = CFGBlock::New(alloc(), state.loop.exitpc);
  if (!body || !state.loop.successor) {
    return ControlStatus::Error;
  }

  CFGTest* test;
  if (JSOp(*pc) == JSOP_IFNE) {
    test = CFGTest::New(alloc(), body, state.loop.successor);
  } else {
    test = CFGTest::New(alloc(), state.loop.successor, body);
  }
  current->setStopIns(test);
  current->setStopPc(pc);

  state.state = CFGState::WHILE_LOOP_BODY;
  state.stopAt = state.loop.bodyEnd;

  current = body;
  pc = body->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processWhileBodyEnd(
    CFGState& state) {
  if (!processDeferredContinues(state)) {
    return ControlStatus::Error;
  }

  if (!current) {
    return processBrokenLoop(state);
  }

  CFGLoopEntry* entry = state.loop.entry->stopIns()->toLoopEntry();
  entry->setLoopStopPc(pc);

  current->setStopIns(CFGBackEdge::New(alloc(), entry->successor()));
  if (pc != current->startPc()) {
    current->setStopPc(pc);
  } else {
    // If the block is empty update the pc to the start of loop to make
    // sure we capture the right stack.
    current->setStartPc(entry->successor()->startPc());
    current->setStopPc(entry->successor()->startPc());
  }
  return finishLoop(state, state.loop.successor);
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processForCondEnd(
    CFGState& state) {
  MOZ_ASSERT(JSOp(*pc) == JSOP_IFNE);

  // Create the body and successor blocks.
  CFGBlock* body = CFGBlock::New(alloc(), state.loop.bodyStart);
  state.loop.successor = CFGBlock::New(alloc(), state.loop.exitpc);

  CFGTest* test = CFGTest::New(alloc(), body, state.loop.successor);
  current->setStopIns(test);
  current->setStopPc(pc);

  state.state = CFGState::FOR_LOOP_BODY;
  state.stopAt = state.loop.bodyEnd;

  current = body;
  pc = body->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processForBodyEnd(
    CFGState& state) {
  if (!processDeferredContinues(state)) {
    return ControlStatus::Error;
  }

  // If there is no updatepc, just go right to processing what would be the
  // end of the update clause. Otherwise, |current| might be nullptr; if this is
  // the case, the update is unreachable anyway.
  if (!state.loop.updatepc || !current) {
    return processForUpdateEnd(state);
  }

  // MOZ_ASSERT(pc == state.loop.updatepc);

  if (state.loop.updatepc != pc) {
    CFGBlock* next = CFGBlock::New(alloc(), state.loop.updatepc);
    current->setStopIns(CFGGoto::New(alloc(), next));
    current->setStopPc(pc);
    current = next;

    if (!addBlock(current)) {
      return ControlStatus::Error;
    }
  }

  pc = state.loop.updatepc;

  state.state = CFGState::FOR_LOOP_UPDATE;
  state.stopAt = state.loop.updateEnd;
  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processForUpdateEnd(
    CFGState& state) {
  // If there is no current, we couldn't reach the loop edge and there was no
  // update clause.
  if (!current) {
    return processBrokenLoop(state);
  }

  CFGLoopEntry* entry = state.loop.entry->stopIns()->toLoopEntry();
  entry->setLoopStopPc(pc);

  current->setStopIns(CFGBackEdge::New(alloc(), entry->successor()));
  if (pc != current->startPc()) {
    current->setStopPc(pc);
  } else {
    // If the block is empty update the pc to the start of loop to make
    // sure we capture the right stack.
    current->setStartPc(entry->successor()->startPc());
    current->setStopPc(entry->successor()->startPc());
  }
  return finishLoop(state, state.loop.successor);
}

ControlFlowGenerator::ControlStatus
ControlFlowGenerator::processWhileOrForInOrForOfLoop(jssrcnote* sn) {
  // while (cond) { } loops have the following structure:
  //    GOTO cond   ; SRC_WHILE (offset to IFNE)
  //    LOOPHEAD
  //    ...
  //  cond:
  //    LOOPENTRY
  //    ...
  //    IFNE        ; goes to LOOPHEAD
  // for-in/for-of loops are similar; for-in/for-of have IFEQ as the back
  // jump, and the cond of for-in will be a MOREITER.
  MOZ_ASSERT(SN_TYPE(sn) == SRC_FOR_OF || SN_TYPE(sn) == SRC_FOR_IN ||
             SN_TYPE(sn) == SRC_WHILE);
  static_assert(unsigned(SrcNote::While::BackJumpOffset) ==
                    unsigned(SrcNote::ForIn::BackJumpOffset),
                "SrcNote::{While,ForIn,ForOf}::BackJumpOffset should be same");
  static_assert(unsigned(SrcNote::While::BackJumpOffset) ==
                    unsigned(SrcNote::ForOf::BackJumpOffset),
                "SrcNote::{While,ForIn,ForOf}::BackJumpOffset should be same");
  int backjumppcOffset = GetSrcNoteOffset(sn, SrcNote::While::BackJumpOffset);
  jsbytecode* backjumppc = pc + backjumppcOffset;
  MOZ_ASSERT(backjumppc > pc);

  // Verify that the back jump goes back to a loophead op.
  MOZ_ASSERT(JSOp(*GetNextPc(pc)) == JSOP_LOOPHEAD);
  MOZ_ASSERT(GetNextPc(pc) == backjumppc + GetJumpOffset(backjumppc));

  jsbytecode* loopEntry = pc + GetJumpOffset(pc);

  size_t stackPhiCount;
  if (SN_TYPE(sn) == SRC_FOR_OF) {
    stackPhiCount = 3;
  } else if (SN_TYPE(sn) == SRC_FOR_IN) {
    stackPhiCount = 1;
  } else {
    stackPhiCount = 0;
  }

  // Skip past the JSOP_LOOPHEAD for the body start.
  jsbytecode* loopHead = GetNextPc(pc);
  jsbytecode* bodyStart = GetNextPc(loopHead);
  jsbytecode* bodyEnd = pc + GetJumpOffset(pc);
  jsbytecode* exitpc = GetNextPc(backjumppc);
  jsbytecode* continuepc = pc;

  CFGBlock* header = CFGBlock::New(alloc(), loopEntry);

  CFGLoopEntry* ins = CFGLoopEntry::New(alloc(), header, stackPhiCount);
  if (LoopEntryCanIonOsr(loopEntry)) {
    ins->setCanOsr();
  }

  if (SN_TYPE(sn) == SRC_FOR_IN) {
    ins->setIsForIn();
  }

  current->setStopIns(ins);
  current->setStopPc(pc);

  if (!pushLoop(CFGState::WHILE_LOOP_COND, backjumppc, current, loopHead,
                bodyEnd, bodyStart, bodyEnd, exitpc, continuepc)) {
    return ControlStatus::Error;
  }

  // Parse the condition first.
  current = header;
  pc = header->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processBrokenLoop(
    CFGState& state) {
  MOZ_ASSERT(!current);

  state.loop.entry->stopIns()->toLoopEntry()->setIsBrokenLoop();

  // If the loop started with a condition (while/for) then even if the
  // structure never actually loops, the condition itself can still fail and
  // thus we must resume at the successor, if one exists.
  current = state.loop.successor;
  if (current) {
    if (!addBlock(current)) {
      return ControlStatus::Error;
    }
  }

  // Join the breaks together and continue parsing.
  if (state.loop.breaks) {
    CFGBlock* block =
        createBreakCatchBlock(state.loop.breaks, state.loop.exitpc);
    if (!block) {
      return ControlStatus::Error;
    }

    if (current) {
      current->setStopIns(CFGGoto::New(alloc(), block));
      current->setStopPc(current->startPc());
    }

    current = block;

    if (!addBlock(current)) {
      return ControlStatus::Error;
    }
  }

  // If the loop is not gated on a condition, and has only returns, we'll
  // reach this case. For example:
  // do { ... return; } while ();
  if (!current) {
    return ControlStatus::Ended;
  }

  // Otherwise, the loop is gated on a condition and/or has breaks so keep
  // parsing at the successor.
  pc = current->startPc();
  return ControlStatus::Joined;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::finishLoop(
    CFGState& state, CFGBlock* successor) {
  MOZ_ASSERT(current);

  if (state.loop.breaks) {
    if (successor) {
      if (!addBlock(successor)) {
        return ControlStatus::Error;
      }
    }

    // Create a catch block to join all break exits.
    CFGBlock* block =
        createBreakCatchBlock(state.loop.breaks, state.loop.exitpc);
    if (!block) {
      return ControlStatus::Error;
    }

    if (successor) {
      // Finally, create an unconditional edge from the successor to the
      // catch block.
      successor->setStopIns(CFGGoto::New(alloc(), block));
      successor->setStopPc(successor->startPc());
    }
    successor = block;
  }

  // An infinite loop (for (;;) { }) will not have a successor.
  if (!successor) {
    current = nullptr;
    return ControlStatus::Ended;
  }

  current = successor;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

bool ControlFlowGenerator::processDeferredContinues(CFGState& state) {
  // If there are any continues for this loop, and there is an update block,
  // then we need to create a new basic block to house the update.
  if (state.loop.continues) {
    DeferredEdge* edge = state.loop.continues;

    CFGBlock* update = CFGBlock::New(alloc(), pc);

    if (current) {
      current->setStopIns(CFGGoto::New(alloc(), update));
      current->setStopPc(pc);
    }

    // Remaining edges
    while (edge) {
      if (!alloc().ensureBallast()) {
        return false;
      }
      edge->block->setStopIns(CFGGoto::New(alloc(), update));
      edge = edge->next;
    }
    state.loop.continues = nullptr;

    current = update;
    if (!addBlock(current)) {
      return false;
    }
  }

  return true;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processCondSwitch() {
  // CondSwitch op looks as follows:
  //   condswitch [length +exit_pc; first case offset +next-case ]
  //   {
  //     {
  //       ... any code ...
  //       case (+jump) [pcdelta offset +next-case]
  //     }+
  //     default (+jump)
  //     ... jump targets ...
  //   }
  //
  // The default case is always emitted even if there is no default case in
  // the source.  The last case statement pcdelta source note might have a 0
  // offset on the last case (not all the time).
  //
  // A conditional evaluate the condition of each case and compare it to the
  // switch value with a strict equality.  Cases conditions are iterated
  // linearly until one is matching. If one case succeeds, the flow jumps into
  // the corresponding body block.  The body block might alias others and
  // might continue in the next body block if the body is not terminated with
  // a break.
  //
  // Algorithm:
  //  1/ Loop over the case chain to reach the default target
  //   & Estimate the number of uniq bodies.
  //  2/ Generate code for all cases (see processCondSwitchCase).
  //  3/ Generate code for all bodies (see processCondSwitchBody).

  MOZ_ASSERT(JSOp(*pc) == JSOP_CONDSWITCH);
  jssrcnote* sn = GetSrcNote(gsn, script, pc);
  MOZ_ASSERT(SN_TYPE(sn) == SRC_CONDSWITCH);

  // Get the exit pc
  jsbytecode* exitpc =
      pc + GetSrcNoteOffset(sn, SrcNote::CondSwitch::EndOffset);
  jsbytecode* firstCase =
      pc + GetSrcNoteOffset(sn, SrcNote::CondSwitch::FirstCaseOffset);

  // Iterate all cases in the conditional switch.
  // - Stop at the default case. (always emitted after the last case)
  // - Estimate the number of uniq bodies. This estimation might be off by 1
  //   if the default body alias a case body.
  jsbytecode* curCase = firstCase;
  jsbytecode* lastTarget = GetJumpOffset(curCase) + curCase;
  size_t nbBodies = 1;  // default target and the first body.

  MOZ_ASSERT(pc < curCase && curCase <= exitpc);
  while (JSOp(*curCase) == JSOP_CASE) {
    // Fetch the next case.
    jssrcnote* caseSn = GetSrcNote(gsn, script, curCase);
    MOZ_ASSERT(caseSn && SN_TYPE(caseSn) == SRC_NEXTCASE);
    ptrdiff_t off = GetSrcNoteOffset(caseSn, SrcNote::NextCase::NextCaseOffset);
    MOZ_ASSERT_IF(off == 0, JSOp(*GetNextPc(curCase)) == JSOP_JUMPTARGET);
    curCase = off ? curCase + off : GetNextPc(GetNextPc(curCase));
    MOZ_ASSERT(pc < curCase && curCase <= exitpc);

    // Count non-aliased cases.
    jsbytecode* curTarget = GetJumpOffset(curCase) + curCase;
    if (lastTarget < curTarget) {
      nbBodies++;
    }
    lastTarget = curTarget;
  }

  // The current case now be the default case which jump to the body of the
  // default case, which might be behind the last target.
  MOZ_ASSERT(JSOp(*curCase) == JSOP_DEFAULT);
  jsbytecode* defaultTarget = GetJumpOffset(curCase) + curCase;
  MOZ_ASSERT(curCase < defaultTarget && defaultTarget <= exitpc);

  // Iterate over all cases again to find the position of the default block.
  curCase = firstCase;
  lastTarget = nullptr;
  size_t defaultIdx = 0;
  while (JSOp(*curCase) == JSOP_CASE) {
    jsbytecode* curTarget = GetJumpOffset(curCase) + curCase;
    if (lastTarget < defaultTarget && defaultTarget <= curTarget) {
      if (defaultTarget < curTarget) {
        nbBodies++;
      }
      break;
    }
    if (lastTarget < curTarget) {
      defaultIdx++;
    }

    jssrcnote* caseSn = GetSrcNote(gsn, script, curCase);
    ptrdiff_t off = GetSrcNoteOffset(caseSn, SrcNote::NextCase::NextCaseOffset);
    curCase = off ? curCase + off : GetNextPc(GetNextPc(curCase));
    lastTarget = curTarget;
  }

  // Allocate the current graph state.
  CFGState state = CFGState::CondSwitch(alloc(), exitpc, defaultTarget);
  if (!state.switch_.bodies || !state.switch_.bodies->init(alloc(), nbBodies)) {
    return ControlStatus::Error;
  }
  state.switch_.defaultIdx = defaultIdx;

  // Create the default case already.
  FixedList<CFGBlock*>& bodies = *state.switch_.bodies;
  bodies[state.switch_.defaultIdx] = CFGBlock::New(alloc(), defaultTarget);

  // Skip default case.
  if (state.switch_.defaultIdx == 0) {
    state.switch_.currentIdx++;
  }

  // We loop on case conditions with processCondSwitchCase.
  MOZ_ASSERT(JSOp(*firstCase) == JSOP_CASE);
  state.stopAt = firstCase;
  state.state = CFGState::COND_SWITCH_CASE;

  if (!cfgStack_.append(state)) {
    return ControlStatus::Error;
  }

  jsbytecode* nextPc = GetNextPc(pc);
  CFGBlock* next = CFGBlock::New(alloc(), nextPc);

  current->setStopIns(CFGGoto::New(alloc(), next));
  current->setStopPc(pc);

  current = next;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processCondSwitchCase(
    CFGState& state) {
  MOZ_ASSERT(state.state == CFGState::COND_SWITCH_CASE);
  MOZ_ASSERT(!state.switch_.breaks);
  MOZ_ASSERT(current);
  MOZ_ASSERT(JSOp(*pc) == JSOP_CASE);
  FixedList<CFGBlock*>& bodies = *state.switch_.bodies;
  uint32_t& currentIdx = state.switch_.currentIdx;

  jsbytecode* lastTarget =
      currentIdx ? bodies[currentIdx - 1]->startPc() : nullptr;

  // Fetch the following case in which we will continue.
  jssrcnote* sn = GetSrcNote(gsn, script, pc);
  ptrdiff_t off = GetSrcNoteOffset(sn, SrcNote::NextCase::NextCaseOffset);
  MOZ_ASSERT_IF(off == 0, JSOp(*GetNextPc(pc)) == JSOP_JUMPTARGET);
  jsbytecode* casePc = off ? pc + off : GetNextPc(GetNextPc(pc));
  bool nextIsDefault = JSOp(*casePc) == JSOP_DEFAULT;
  MOZ_ASSERT(JSOp(*casePc) == JSOP_CASE || nextIsDefault);

  // Allocate the block of the matching case.
  jsbytecode* bodyTarget = pc + GetJumpOffset(pc);
  CFGBlock* bodyBlock = nullptr;
  if (lastTarget < bodyTarget) {
    // Skip default case.
    if (currentIdx == state.switch_.defaultIdx) {
      currentIdx++;
      lastTarget = bodies[currentIdx - 1]->startPc();
      if (lastTarget < bodyTarget) {
        bodyBlock = CFGBlock::New(alloc(), bodyTarget);
        bodies[currentIdx++] = bodyBlock;
      } else {
        // This body alias the previous one.
        MOZ_ASSERT(lastTarget == bodyTarget);
        MOZ_ASSERT(currentIdx > 0);
        bodyBlock = bodies[currentIdx - 1];
      }
    } else {
      bodyBlock = CFGBlock::New(alloc(), bodyTarget);
      bodies[currentIdx++] = bodyBlock;
    }

  } else {
    // This body alias the previous one.
    MOZ_ASSERT(lastTarget == bodyTarget);
    MOZ_ASSERT(currentIdx > 0);
    bodyBlock = bodies[currentIdx - 1];
  }

  CFGBlock* emptyBlock = CFGBlock::New(alloc(), bodyBlock->startPc());
  emptyBlock->setStopIns(CFGGoto::New(alloc(), bodyBlock));
  emptyBlock->setStopPc(bodyBlock->startPc());
  if (!addBlock(emptyBlock)) {
    return ControlStatus::Error;
  }

  if (nextIsDefault) {
    CFGBlock* defaultBlock = bodies[state.switch_.defaultIdx];

    CFGBlock* emptyBlock2 = CFGBlock::New(alloc(), defaultBlock->startPc());
    emptyBlock2->setStopIns(CFGGoto::New(alloc(), defaultBlock));
    emptyBlock2->setStopPc(defaultBlock->startPc());
    if (!addBlock(emptyBlock2)) {
      return ControlStatus::Error;
    }

    current->setStopIns(CFGCondSwitchCase::NewFalseBranchIsDefault(
        alloc(), emptyBlock, emptyBlock2));
    current->setStopPc(pc);

    return processCondSwitchDefault(state);
  }

  CFGBlock* nextBlock = CFGBlock::New(alloc(), GetNextPc(pc));
  current->setStopIns(CFGCondSwitchCase::NewFalseBranchIsNextCase(
      alloc(), emptyBlock, nextBlock));
  current->setStopPc(pc);

  // Continue until the case condition.
  current = nextBlock;
  pc = current->startPc();
  state.stopAt = casePc;

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus
ControlFlowGenerator::processCondSwitchDefault(CFGState& state) {
  uint32_t& currentIdx = state.switch_.currentIdx;

  // The last case condition is finished.  Loop in processCondSwitchBody,
  // with potential stops in processSwitchBreak.

#ifdef DEBUG
  // Test that we calculated the number of bodies correctly.
  FixedList<CFGBlock*>& bodies = *state.switch_.bodies;
  MOZ_ASSERT(state.switch_.currentIdx == bodies.length() ||
             state.switch_.defaultIdx + 1 == bodies.length());
#endif

  // Handle break statements in processSwitchBreak while processing
  // bodies.
  ControlFlowInfo breakInfo(cfgStack_.length() - 1, state.switch_.exitpc);
  if (!switches_.append(breakInfo)) {
    return ControlStatus::Error;
  }

  // Jump into the first body.
  currentIdx = 0;
  current = nullptr;
  state.state = CFGState::COND_SWITCH_BODY;

  return processCondSwitchBody(state);
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processCondSwitchBody(
    CFGState& state) {
  MOZ_ASSERT(state.state == CFGState::COND_SWITCH_BODY);
  MOZ_ASSERT(pc <= state.switch_.exitpc);
  FixedList<CFGBlock*>& bodies = *state.switch_.bodies;
  uint32_t& currentIdx = state.switch_.currentIdx;

  MOZ_ASSERT(currentIdx <= bodies.length());
  if (currentIdx == bodies.length()) {
    MOZ_ASSERT_IF(current, pc == state.switch_.exitpc);
    return processSwitchEnd(state.switch_.breaks, state.switch_.exitpc);
  }

  // Get the next body
  CFGBlock* nextBody = bodies[currentIdx++];
  MOZ_ASSERT_IF(current, pc == nextBody->startPc());

  // The last body continue into the new one.
  if (current) {
    current->setStopIns(CFGGoto::New(alloc(), nextBody));
    current->setStopPc(pc);
  }

  // Continue in the next body.
  current = nextBody;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  if (currentIdx < bodies.length()) {
    state.stopAt = bodies[currentIdx]->startPc();
  } else {
    state.stopAt = state.switch_.exitpc;
  }
  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processAndOrEnd(
    CFGState& state) {
  MOZ_ASSERT(current);
  CFGBlock* lhs = state.branch.ifFalse;

  // Create a new block to represent the join.
  CFGBlock* join = CFGBlock::New(alloc(), state.stopAt);

  // End the rhs.
  current->setStopIns(CFGGoto::New(alloc(), join));
  current->setStopPc(pc);

  // End the lhs.
  lhs->setStopIns(CFGGoto::New(alloc(), join));
  lhs->setStopPc(pc);

  // Set the join path as current path.
  current = join;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processForLoop(
    JSOp op, jssrcnote* sn) {
  // Skip the NOP.
  MOZ_ASSERT(op == JSOP_NOP);
  pc = GetNextPc(pc);

  jsbytecode* condpc = pc + GetSrcNoteOffset(sn, SrcNote::For::CondOffset);
  jsbytecode* updatepc = pc + GetSrcNoteOffset(sn, SrcNote::For::UpdateOffset);
  jsbytecode* backjumppc =
      pc + GetSrcNoteOffset(sn, SrcNote::For::BackJumpOffset);
  jsbytecode* exitpc = GetNextPc(backjumppc);

  // for loops have the following structures:
  //
  //   NOP
  //   [GOTO cond]
  //   LOOPHEAD
  // body:
  //    ; [body]
  // [update:]
  //   [FRESHENBLOCKSCOPE, if needed by a cloned block]
  //    ; [update]
  // [cond:]
  //   LOOPENTRY
  //    ; [cond]
  //   [GOTO body | IFNE body]
  //
  // If there is a condition (condpc != backjumppc), this acts similar to a
  // while loop otherwise, it acts like a do-while loop.
  //
  // Note that currently Ion does not compile pushblockscope/popblockscope as
  // necessary prerequisites to freshenblockscope.  So the code below doesn't
  // and needn't consider the implications of freshenblockscope.
  jsbytecode* bodyStart = pc;
  jsbytecode* bodyEnd = updatepc;
  jsbytecode* loopEntry = condpc;
  if (condpc != backjumppc) {
    MOZ_ASSERT(JSOp(*bodyStart) == JSOP_GOTO);
    MOZ_ASSERT(bodyStart + GetJumpOffset(bodyStart) == condpc);
    bodyStart = GetNextPc(bodyStart);
  } else {
    // No loop condition, such as for(j = 0; ; j++)
    if (op != JSOP_NOP) {
      // If the loop starts with POP, we have to skip a NOP.
      MOZ_ASSERT(JSOp(*bodyStart) == JSOP_NOP);
      bodyStart = GetNextPc(bodyStart);
    }
    loopEntry = GetNextPc(bodyStart);
  }
  jsbytecode* loopHead = bodyStart;
  MOZ_ASSERT(JSOp(*bodyStart) == JSOP_LOOPHEAD);
  MOZ_ASSERT(backjumppc + GetJumpOffset(backjumppc) == bodyStart);
  bodyStart = GetNextPc(bodyStart);

  MOZ_ASSERT(JSOp(*loopEntry) == JSOP_LOOPENTRY);

  CFGBlock* header = CFGBlock::New(alloc(), loopEntry);

  CFGLoopEntry* ins = CFGLoopEntry::New(alloc(), header, 0);
  if (LoopEntryCanIonOsr(loopEntry)) {
    ins->setCanOsr();
  }

  current->setStopIns(ins);
  current->setStopPc(pc);

  // If there is no condition, we immediately parse the body. Otherwise, we
  // parse the condition.
  jsbytecode* stopAt;
  CFGState::State initial;
  if (condpc != backjumppc) {
    pc = condpc;
    stopAt = backjumppc;
    initial = CFGState::FOR_LOOP_COND;
  } else {
    pc = bodyStart;
    stopAt = bodyEnd;
    initial = CFGState::FOR_LOOP_BODY;
  }

  if (!pushLoop(initial, stopAt, current, loopHead, pc, bodyStart, bodyEnd,
                exitpc, updatepc)) {
    return ControlStatus::Error;
  }

  CFGState& state = cfgStack_.back();
  state.loop.condpc = (condpc != backjumppc) ? condpc : nullptr;
  state.loop.updatepc = (updatepc != condpc) ? updatepc : nullptr;
  if (state.loop.updatepc) {
    state.loop.updateEnd = condpc;
  }

  current = header;
  if (!addBlock(current)) {
    return ControlStatus::Error;
  }
  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processDoWhileLoop(
    jssrcnote* sn) {
  // do { } while() loops have the following structure:
  //    NOP
  //    LOOPHEAD    ; SRC_DO_WHILE (offsets to COND and IFNE)
  //    LOOPENTRY
  //    ...         ; body
  //    ...
  //    COND        ; start of condition
  //    ...
  //    IFNE ->     ; goes to LOOPHEAD
  int condition_offset = GetSrcNoteOffset(sn, SrcNote::DoWhile::CondOffset);
  jsbytecode* conditionpc = pc + condition_offset;
  int offset = GetSrcNoteOffset(sn, SrcNote::DoWhile::BackJumpOffset);
  jsbytecode* ifne = pc + offset;
  MOZ_ASSERT(ifne > pc);

  // Verify that the IFNE goes back to a loophead op.
  jsbytecode* loopHead = pc;
  MOZ_ASSERT(JSOp(*loopHead) == JSOP_LOOPHEAD);
  MOZ_ASSERT(loopHead == ifne + GetJumpOffset(ifne));

  jsbytecode* loopEntry = GetNextPc(loopHead);

  CFGBlock* header = CFGBlock::New(alloc(), loopEntry);

  CFGLoopEntry* ins = CFGLoopEntry::New(alloc(), header, 0);
  if (LoopEntryCanIonOsr(loopEntry)) {
    ins->setCanOsr();
  }

  current->setStopIns(ins);
  current->setStopPc(pc);

  jsbytecode* bodyEnd = conditionpc;
  jsbytecode* exitpc = GetNextPc(ifne);
  if (!pushLoop(CFGState::DO_WHILE_LOOP_BODY, conditionpc, current, loopHead,
                loopEntry, loopEntry, bodyEnd, exitpc, conditionpc)) {
    return ControlStatus::Error;
  }

  CFGState& state = cfgStack_.back();
  state.loop.updatepc = conditionpc;
  state.loop.updateEnd = ifne;

  current = header;
  pc = loopEntry;

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

bool ControlFlowGenerator::pushLoop(CFGState::State initial, jsbytecode* stopAt,
                                    CFGBlock* entry, jsbytecode* loopHead,
                                    jsbytecode* initialPc,
                                    jsbytecode* bodyStart, jsbytecode* bodyEnd,
                                    jsbytecode* exitpc,
                                    jsbytecode* continuepc) {
  ControlFlowInfo loop(cfgStack_.length(), continuepc);
  if (!loops_.append(loop)) {
    return false;
  }

  CFGState state;
  state.state = initial;
  state.stopAt = stopAt;
  state.loop.bodyStart = bodyStart;
  state.loop.bodyEnd = bodyEnd;
  state.loop.exitpc = exitpc;
  state.loop.entry = entry;
  state.loop.successor = nullptr;
  state.loop.breaks = nullptr;
  state.loop.continues = nullptr;
  state.loop.initialState = initial;
  state.loop.initialPc = initialPc;
  state.loop.initialStopAt = stopAt;
  state.loop.loopHead = loopHead;
  return cfgStack_.append(state);
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processBreak(
    JSOp op, jssrcnote* sn) {
  MOZ_ASSERT(op == JSOP_GOTO);

  MOZ_ASSERT(SN_TYPE(sn) == SRC_BREAK || SN_TYPE(sn) == SRC_BREAK2LABEL);

  // Find the break target.
  jsbytecode* target = pc + GetJumpOffset(pc);
  DebugOnly<bool> found = false;

  if (SN_TYPE(sn) == SRC_BREAK2LABEL) {
    for (size_t i = labels_.length() - 1;; i--) {
      CFGState& cfg = cfgStack_[labels_[i].cfgEntry];
      MOZ_ASSERT(cfg.state == CFGState::LABEL);
      if (cfg.stopAt == target) {
        cfg.label.breaks =
            new (alloc()) DeferredEdge(current, cfg.label.breaks);
        found = true;
        break;
      }
      if (i == 0) {
        break;
      }
    }
  } else {
    for (size_t i = loops_.length() - 1;; i--) {
      CFGState& cfg = cfgStack_[loops_[i].cfgEntry];
      MOZ_ASSERT(cfg.isLoop());
      if (cfg.loop.exitpc == target) {
        cfg.loop.breaks = new (alloc()) DeferredEdge(current, cfg.loop.breaks);
        found = true;
        break;
      }
      if (i == 0) {
        break;
      }
    }
  }

  current->setStopPc(pc);

  MOZ_ASSERT(found);

  current = nullptr;
  pc += CodeSpec[op].length;
  return processControlEnd();
}

static inline jsbytecode* EffectiveContinue(jsbytecode* pc) {
  if (JSOp(*pc) == JSOP_GOTO) {
    return pc + GetJumpOffset(pc);
  }
  return pc;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processContinue(
    JSOp op) {
  MOZ_ASSERT(op == JSOP_GOTO);

  // Find the target loop.
  CFGState* found = nullptr;
  jsbytecode* target = pc + GetJumpOffset(pc);
  for (size_t i = loops_.length() - 1;; i--) {
    if (loops_[i].continuepc == target + JSOP_JUMPTARGET_LENGTH ||
        EffectiveContinue(loops_[i].continuepc) == target) {
      found = &cfgStack_[loops_[i].cfgEntry];
      break;
    }
    if (i == 0) {
      break;
    }
  }

  // There must always be a valid target loop structure. If not, there's
  // probably an off-by-something error in which pc we track.
  MOZ_ASSERT(found);
  CFGState& state = *found;

  state.loop.continues =
      new (alloc()) DeferredEdge(current, state.loop.continues);
  if (!state.loop.continues) {
    return ControlStatus::Error;
  }
  current->setStopPc(pc);

  current = nullptr;
  pc += CodeSpec[op].length;
  return processControlEnd();
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processSwitchBreak(
    JSOp op) {
  MOZ_ASSERT(op == JSOP_GOTO);

  // Find the target switch.
  CFGState* found = nullptr;
  jsbytecode* target = pc + GetJumpOffset(pc);
  for (size_t i = switches_.length() - 1;; i--) {
    if (switches_[i].continuepc == target) {
      found = &cfgStack_[switches_[i].cfgEntry];
      break;
    }
    if (i == 0) {
      break;
    }
  }

  // There must always be a valid target loop structure. If not, there's
  // probably an off-by-something error in which pc we track.
  MOZ_ASSERT(found);
  CFGState& state = *found;

  DeferredEdge** breaks = nullptr;
  switch (state.state) {
    case CFGState::TABLE_SWITCH:
      breaks = &state.switch_.breaks;
      break;
    case CFGState::COND_SWITCH_BODY:
      breaks = &state.switch_.breaks;
      break;
    default:
      MOZ_CRASH("Unexpected switch state.");
  }

  *breaks = new (alloc()) DeferredEdge(current, *breaks);

  current->setStopPc(pc);

  current = nullptr;
  pc += CodeSpec[op].length;
  return processControlEnd();
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processIfStart(
    JSOp op) {
  // IFEQ always has a forward offset.
  jsbytecode* trueStart = pc + CodeSpec[op].length;
  jsbytecode* falseStart = pc + GetJumpOffset(pc);
  MOZ_ASSERT(falseStart > pc);

  // We only handle cases that emit source notes.
  jssrcnote* sn = GetSrcNote(gsn, script, pc);
  if (!sn) {
    return ControlStatus::Error;
  }

  // Create true and false branches.
  CFGBlock* ifTrue = CFGBlock::New(alloc(), trueStart);
  CFGBlock* ifFalse = CFGBlock::New(alloc(), falseStart);

  CFGTest* test = CFGTest::New(alloc(), ifTrue, ifFalse);
  current->setStopIns(test);
  current->setStopPc(pc);

  // The bytecode for if/ternary gets emitted either like this:
  //
  //    IFEQ X     ; src note (IF_ELSE, COND)
  //    ...
  //    GOTO Z
  // X: JUMPTARGET ; else/else if
  //    ...
  // Z: JUMPTARGET ; join
  //
  // Or like this:
  //
  //    IFEQ X     ; src note (IF)
  //    ...
  // X: JUMPTARGET ; join
  //
  // We want to parse the bytecode as if we were parsing the AST, so for the
  // IF_ELSE/COND cases, we use the IFEQ/GOTO bytecode offsets to follow the
  // branch. For the IF case, the IFEQ offset is the join point.
  switch (SN_TYPE(sn)) {
    case SRC_IF:
      if (!cfgStack_.append(CFGState::If(falseStart, test))) {
        return ControlStatus::Error;
      }
      break;

    case SRC_IF_ELSE:
    case SRC_COND: {
      // Infer the join point from the JSOP_GOTO[X] sitting here, then
      // assert as we much we can that this is the right GOTO.
      MOZ_ASSERT(JSOp(*falseStart) == JSOP_JUMPTARGET);
      jsbytecode* trueEnd = falseStart - JSOP_GOTO_LENGTH;
      MOZ_ASSERT(trueEnd > pc);
      MOZ_ASSERT(JSOp(*trueEnd) == JSOP_GOTO);
      MOZ_ASSERT(!GetSrcNote(gsn, script, trueEnd));

      jsbytecode* falseEnd = trueEnd + GetJumpOffset(trueEnd);
      MOZ_ASSERT(falseEnd > trueEnd);
      MOZ_ASSERT(falseEnd >= falseStart);

      if (!cfgStack_.append(CFGState::IfElse(trueEnd, falseEnd, test))) {
        return ControlStatus::Error;
      }
      break;
    }

    default:
      MOZ_CRASH("unexpected source note type");
  }

  // Switch to parsing the true branch. Note that no PC update is needed,
  // it's the next instruction.
  current = ifTrue;
  pc = ifTrue->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

int ControlFlowGenerator::CmpSuccessors(const void* a, const void* b) {
  const CFGBlock* a0 = *(CFGBlock* const*)a;
  const CFGBlock* b0 = *(CFGBlock* const*)b;
  if (a0->startPc() == b0->startPc()) {
    return 0;
  }

  return (a0->startPc() > b0->startPc()) ? 1 : -1;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processTableSwitch(
    JSOp op, jssrcnote* sn) {
  // TableSwitch op contains the following data
  // (length between data is JUMP_OFFSET_LEN)
  //
  // 0: Offset of default case
  // 1: Lowest number in tableswitch
  // 2: Highest number in tableswitch
  // 3: Offset of case low
  // 4: Offset of case low+1
  // .: ...
  // .: Offset of case high

  MOZ_ASSERT(op == JSOP_TABLESWITCH);
  MOZ_ASSERT(SN_TYPE(sn) == SRC_TABLESWITCH);

  // Get the default and exit pc
  jsbytecode* exitpc =
      pc + GetSrcNoteOffset(sn, SrcNote::TableSwitch::EndOffset);
  jsbytecode* defaultpc = pc + GET_JUMP_OFFSET(pc);

  MOZ_ASSERT(defaultpc > pc && defaultpc <= exitpc);

  // Get the low and high from the tableswitch
  jsbytecode* pc2 = pc;
  pc2 += JUMP_OFFSET_LEN;
  int low = GET_JUMP_OFFSET(pc2);
  pc2 += JUMP_OFFSET_LEN;
  int high = GET_JUMP_OFFSET(pc2);
  pc2 += JUMP_OFFSET_LEN;

  // Create MIR instruction
  CFGTableSwitch* tableswitch = CFGTableSwitch::New(alloc(), low, high);

  // Create default case
  CFGBlock* defaultcase = CFGBlock::New(alloc(), defaultpc);

  if (!tableswitch->addDefault(defaultcase)) {
    return ControlStatus::Error;
  }

  // Create cases
  for (int i = 0; i < high - low + 1; i++) {
    if (!alloc().ensureBallast()) {
      return ControlStatus::Error;
    }

    jsbytecode* casepc = script->tableSwitchCasePC(pc, i);
    MOZ_ASSERT(casepc >= pc && casepc <= exitpc);

    CFGBlock* caseBlock;

    if (casepc == defaultpc) {
      // This is a missing case. Jump to the 'default' target.
      caseBlock = CFGBlock::New(alloc(), defaultpc);
      caseBlock->setStopIns(CFGGoto::New(alloc(), defaultcase));
    } else {
      // If this is an actual case (not filled gap),
      // add this block to the list that still needs to get processed.
      caseBlock = CFGBlock::New(alloc(), casepc);
    }

    if (!tableswitch->addCase(caseBlock)) {
      return ControlStatus::Error;
    }

    pc2 += JUMP_OFFSET_LEN;
  }

  // Create info
  ControlFlowInfo switchinfo(cfgStack_.length(), exitpc);
  if (!switches_.append(switchinfo)) {
    return ControlStatus::Error;
  }

  // Use a state to retrieve some information
  CFGState state = CFGState::TableSwitch(alloc(), exitpc);
  if (!state.switch_.bodies ||
      !state.switch_.bodies->init(alloc(), tableswitch->numSuccessors())) {
    return ControlStatus::Error;
  }

  FixedList<CFGBlock*>& bodies = *state.switch_.bodies;
  for (size_t i = 0; i < tableswitch->numSuccessors(); i++) {
    bodies[i] = tableswitch->getSuccessor(i);
  }

  qsort(bodies.begin(), state.switch_.bodies->length(), sizeof(CFGBlock*),
        CmpSuccessors);

  // Save the MIR instruction as last instruction of this block.
  current->setStopIns(tableswitch);
  current->setStopPc(pc);

  // If there is only one successor the block should stop at the end of the
  // switch Else it should stop at the start of the next successor
  if (bodies.length() > 1) {
    state.stopAt = bodies[1]->startPc();
  } else {
    state.stopAt = exitpc;
  }

  if (!cfgStack_.append(state)) {
    return ControlStatus::Error;
  }

  current = bodies[0];
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus
ControlFlowGenerator::processNextTableSwitchCase(CFGState& state) {
  MOZ_ASSERT(state.state == CFGState::TABLE_SWITCH);
  FixedList<CFGBlock*>& bodies = *state.switch_.bodies;

  state.switch_.currentIdx++;

  // Test if there are still unprocessed successors (cases/default)
  if (state.switch_.currentIdx >= bodies.length()) {
    return processSwitchEnd(state.switch_.breaks, state.switch_.exitpc);
  }

  // Get the next successor
  CFGBlock* successor = bodies[state.switch_.currentIdx];

  // Add current block as predecessor if available.
  // This means the previous case didn't have a break statement.
  // So flow will continue in this block.
  if (current) {
    current->setStopIns(CFGGoto::New(alloc(), successor));
    current->setStopPc(pc);
  }

  // If this is the last successor the block should stop at the end of the
  // tableswitch Else it should stop at the start of the next successor
  if (state.switch_.currentIdx + 1 < bodies.length()) {
    state.stopAt = bodies[state.switch_.currentIdx + 1]->startPc();
  } else {
    state.stopAt = state.switch_.exitpc;
  }

  current = bodies[state.switch_.currentIdx];
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processSwitchEnd(
    DeferredEdge* breaks, jsbytecode* exitpc) {
  // No break statements, no current.
  // This means that control flow is cut-off from this point
  // (e.g. all cases have return statements).
  if (!breaks && !current) {
    return ControlStatus::Ended;
  }

  // Create successor block.
  // If there are breaks, create block with breaks as predecessor
  // Else create a block with current as predecessor
  CFGBlock* successor = nullptr;
  if (breaks) {
    successor = createBreakCatchBlock(breaks, exitpc);
    if (!successor) {
      return ControlStatus::Error;
    }
  } else {
    successor = CFGBlock::New(alloc(), exitpc);
  }

  // If there is current, the current block flows into this one.
  // So current is also a predecessor to this block
  if (current) {
    current->setStopIns(CFGGoto::New(alloc(), successor));
    current->setStopPc(pc);
  }

  current = successor;
  pc = successor->startPc();

  if (!addBlock(successor)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Joined;
}

ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::If(
    jsbytecode* join, CFGTest* test) {
  CFGState state;
  state.state = IF_TRUE;
  state.stopAt = join;
  state.branch.ifFalse = test->getSuccessor(1);
  state.branch.test = test;
  return state;
}

ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::IfElse(
    jsbytecode* trueEnd, jsbytecode* falseEnd, CFGTest* test) {
  CFGBlock* ifFalse = test->getSuccessor(1);

  CFGState state;
  // If the end of the false path is the same as the start of the
  // false path, then the "else" block is empty and we can devolve
  // this to the IF_TRUE case. We handle this here because there is
  // still an extra GOTO on the true path and we want stopAt to point
  // there, whereas the IF_TRUE case does not have the GOTO.
  state.state =
      (falseEnd == ifFalse->startPc()) ? IF_TRUE_EMPTY_ELSE : IF_ELSE_TRUE;
  state.stopAt = trueEnd;
  state.branch.falseEnd = falseEnd;
  state.branch.ifFalse = ifFalse;
  state.branch.test = test;
  return state;
}

ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::AndOr(
    jsbytecode* join, CFGBlock* lhs) {
  CFGState state;
  state.state = AND_OR;
  state.stopAt = join;
  state.branch.ifFalse = lhs;
  state.branch.test = nullptr;
  return state;
}

ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::TableSwitch(
    TempAllocator& alloc, jsbytecode* exitpc) {
  CFGState state;
  state.state = TABLE_SWITCH;
  state.stopAt = exitpc;
  state.switch_.bodies =
      (FixedList<CFGBlock*>*)alloc.allocate(sizeof(FixedList<CFGBlock*>));
  state.switch_.currentIdx = 0;
  state.switch_.exitpc = exitpc;
  state.switch_.breaks = nullptr;
  return state;
}

ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::CondSwitch(
    TempAllocator& alloc, jsbytecode* exitpc, jsbytecode* defaultTarget) {
  CFGState state;
  state.state = COND_SWITCH_CASE;
  state.stopAt = nullptr;
  state.switch_.bodies =
      (FixedList<CFGBlock*>*)alloc.allocate(sizeof(FixedList<CFGBlock*>));
  state.switch_.currentIdx = 0;
  state.switch_.defaultTarget = defaultTarget;
  state.switch_.defaultIdx = uint32_t(-1);
  state.switch_.exitpc = exitpc;
  state.switch_.breaks = nullptr;
  return state;
}
ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::Label(
    jsbytecode* exitpc) {
  CFGState state;
  state.state = LABEL;
  state.stopAt = exitpc;
  state.label.breaks = nullptr;
  return state;
}

ControlFlowGenerator::CFGState ControlFlowGenerator::CFGState::Try(
    jsbytecode* exitpc, CFGBlock* successor) {
  CFGState state;
  state.state = TRY;
  state.stopAt = exitpc;
  state.try_.successor = successor;
  return state;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processAndOr(
    JSOp op) {
  MOZ_ASSERT(op == JSOP_AND || op == JSOP_OR);

  jsbytecode* rhsStart = pc + CodeSpec[op].length;
  jsbytecode* joinStart = pc + GetJumpOffset(pc);
  MOZ_ASSERT(joinStart > pc);

  CFGBlock* evalLhs = CFGBlock::New(alloc(), joinStart);
  CFGBlock* evalRhs = CFGBlock::New(alloc(), rhsStart);

  CFGTest* test = (op == JSOP_AND) ? CFGTest::New(alloc(), evalRhs, evalLhs)
                                   : CFGTest::New(alloc(), evalLhs, evalRhs);
  test->keepCondition();
  current->setStopIns(test);
  current->setStopPc(pc);

  // Create the rhs block.
  if (!cfgStack_.append(CFGState::AndOr(joinStart, evalLhs))) {
    return ControlStatus::Error;
  }

  if (!addBlock(evalLhs)) {
    return ControlStatus::Error;
  }

  current = evalRhs;
  pc = current->startPc();

  if (!addBlock(current)) {
    return ControlStatus::Error;
  }

  return ControlStatus::Jumped;
}

ControlFlowGenerator::ControlStatus ControlFlowGenerator::processLabel() {
  MOZ_ASSERT(JSOp(*pc) == JSOP_LABEL);

  jsbytecode* endpc = pc + GET_CODE_OFFSET(pc);
  MOZ_ASSERT(endpc > pc);

  ControlFlowInfo label(cfgStack_.length(), endpc);
  if (!labels_.append(label)) {
    return ControlStatus::Error;
  }

  if (!cfgStack_.append(CFGState::Label(endpc))) {
    return ControlStatus::Error;
  }

  return ControlStatus::None;
}