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
/* -*- 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 "vm/ObjectGroup.h"

#include "mozilla/Maybe.h"
#include "mozilla/Unused.h"

#include "jsexn.h"

#include "builtin/DataViewObject.h"
#include "gc/FreeOp.h"
#include "gc/HashUtil.h"
#include "gc/Policy.h"
#include "gc/StoreBuffer.h"
#include "js/CharacterEncoding.h"
#include "js/UniquePtr.h"
#include "vm/ArrayObject.h"
#include "vm/GlobalObject.h"
#include "vm/JSObject.h"
#include "vm/RegExpObject.h"
#include "vm/Shape.h"
#include "vm/TaggedProto.h"

#include "gc/Marking-inl.h"
#include "gc/ObjectKind-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/TypeInference-inl.h"

using namespace js;

/////////////////////////////////////////////////////////////////////
// ObjectGroup
/////////////////////////////////////////////////////////////////////

ObjectGroup::ObjectGroup(const JSClass* clasp, TaggedProto proto,
                         JS::Realm* realm, ObjectGroupFlags initialFlags)
    : clasp_(clasp), proto_(proto), realm_(realm), flags_(initialFlags) {
  /* Windows may not appear on prototype chains. */
  MOZ_ASSERT_IF(proto.isObject(), !IsWindow(proto.toObject()));
  MOZ_ASSERT(JS::StringIsASCII(clasp->name));

  setGeneration(zone()->types.generation);
}

void ObjectGroup::finalize(JSFreeOp* fop) {
  if (auto newScript = newScriptDontCheckGeneration()) {
    newScript->clear();
    fop->delete_(this, newScript, newScript->gcMallocBytes(),
                 MemoryUse::ObjectGroupAddendum);
  }
  if (maybePreliminaryObjectsDontCheckGeneration()) {
    maybePreliminaryObjectsDontCheckGeneration()->clear();
  }
  fop->delete_(this, maybePreliminaryObjectsDontCheckGeneration(),
               MemoryUse::ObjectGroupAddendum);
}

void ObjectGroup::setProtoUnchecked(TaggedProto proto) {
  proto_ = proto;
  MOZ_ASSERT_IF(proto_.isObject() && proto_.toObject()->isNative(),
                proto_.toObject()->isDelegate());
}

void ObjectGroup::setProto(TaggedProto proto) {
  MOZ_ASSERT(singleton());
  setProtoUnchecked(proto);
}

size_t ObjectGroup::sizeOfExcludingThis(
    mozilla::MallocSizeOf mallocSizeOf) const {
  size_t n = 0;
  if (TypeNewScript* newScript = newScriptDontCheckGeneration()) {
    n += newScript->sizeOfIncludingThis(mallocSizeOf);
  }
  return n;
}

static inline size_t AddendumAllocSize(ObjectGroup::AddendumKind kind,
                                       void* addendum) {
  if (kind == ObjectGroup::Addendum_NewScript) {
    auto newScript = static_cast<TypeNewScript*>(addendum);
    return newScript->gcMallocBytes();
  }
  if (kind == ObjectGroup::Addendum_PreliminaryObjects) {
    return sizeof(PreliminaryObjectArrayWithTemplate);
  }
  // Other addendum kinds point to GC memory tracked elsewhere.
  return 0;
}

void ObjectGroup::setAddendum(AddendumKind kind, void* addendum,
                              bool isSweeping /* = flase */) {
  MOZ_ASSERT(!needsSweep());
  MOZ_ASSERT(kind <= (OBJECT_FLAG_ADDENDUM_MASK >> OBJECT_FLAG_ADDENDUM_SHIFT));

  RemoveCellMemory(this, AddendumAllocSize(addendumKind(), addendum_),
                   MemoryUse::ObjectGroupAddendum, isSweeping);

  if (!isSweeping) {
    // Trigger a write barrier if we are clearing new script or preliminary
    // object information outside of sweeping. Other addendums are immutable.
    AutoSweepObjectGroup sweep(this);
    switch (addendumKind()) {
      case Addendum_PreliminaryObjects:
        PreliminaryObjectArrayWithTemplate::writeBarrierPre(
            maybePreliminaryObjects(sweep));
        break;
      case Addendum_NewScript:
        TypeNewScript::writeBarrierPre(newScript(sweep));
        break;
      case Addendum_None:
        break;
      default:
        MOZ_ASSERT(addendumKind() == kind);
    }
  }

  flags_ &= ~OBJECT_FLAG_ADDENDUM_MASK;
  flags_ |= kind << OBJECT_FLAG_ADDENDUM_SHIFT;
  addendum_ = addendum;

  AddCellMemory(this, AddendumAllocSize(kind, addendum),
                MemoryUse::ObjectGroupAddendum);
}

/* static */
bool ObjectGroup::useSingletonForClone(JSFunction* fun) {
  if (!fun->isInterpreted()) {
    return false;
  }

  if (fun->isArrow()) {
    return false;
  }

  if (fun->isSingleton()) {
    return false;
  }

  /*
   * When a function is being used as a wrapper for another function, it
   * improves precision greatly to distinguish between different instances of
   * the wrapper; otherwise we will conflate much of the information about
   * the wrapped functions.
   *
   * An important example is the Class.create function at the core of the
   * Prototype.js library, which looks like:
   *
   * var Class = {
   *   create: function() {
   *     return function() {
   *       this.initialize.apply(this, arguments);
   *     }
   *   }
   * };
   *
   * Each instance of the innermost function will have a different wrapped
   * initialize method. We capture this, along with similar cases, by looking
   * for short scripts which use both .apply and arguments. For such scripts,
   * whenever creating a new instance of the function we both give that
   * instance a singleton type and clone the underlying script.
   */

  uint32_t begin, end;
  if (fun->hasScript()) {
    if (!fun->nonLazyScript()->isLikelyConstructorWrapper()) {
      return false;
    }
    begin = fun->nonLazyScript()->sourceStart();
    end = fun->nonLazyScript()->sourceEnd();
  } else {
    if (!fun->lazyScript()->isLikelyConstructorWrapper()) {
      return false;
    }
    begin = fun->lazyScript()->sourceStart();
    end = fun->lazyScript()->sourceEnd();
  }

  return end - begin <= 100;
}

/* static */
bool ObjectGroup::useSingletonForNewObject(JSContext* cx, JSScript* script,
                                           jsbytecode* pc) {
  /*
   * Make a heuristic guess at a use of JSOP_NEW that the constructed object
   * should have a fresh group. We do this when the NEW is immediately
   * followed by a simple assignment to an object's .prototype field.
   * This is designed to catch common patterns for subclassing in JS:
   *
   * function Super() { ... }
   * function Sub1() { ... }
   * function Sub2() { ... }
   *
   * Sub1.prototype = new Super();
   * Sub2.prototype = new Super();
   *
   * Using distinct groups for the particular prototypes of Sub1 and
   * Sub2 lets us continue to distinguish the two subclasses and any extra
   * properties added to those prototype objects.
   */
  if (script->isGenerator() || script->isAsync()) {
    return false;
  }
  if (JSOp(*pc) != JSOP_NEW) {
    return false;
  }
  pc += JSOP_NEW_LENGTH;
  if (JSOp(*pc) == JSOP_SETPROP) {
    if (script->getName(pc) == cx->names().prototype) {
      return true;
    }
  }
  return false;
}

/* static */
bool ObjectGroup::useSingletonForAllocationSite(JSScript* script,
                                                jsbytecode* pc,
                                                JSProtoKey key) {
  /*
   * Objects created outside loops in global and eval scripts should have
   * singleton types. For now this is only done for plain objects, but not
   * typed arrays or normal arrays.
   */

  if (script->functionNonDelazifying() && !script->treatAsRunOnce()) {
    return false;
  }

  if (key != JSProto_Object) {
    return false;
  }

  // All loops in the script will have a try note indicating their boundary.

  uint32_t offset = script->pcToOffset(pc);

  for (const JSTryNote& tn : script->trynotes()) {
    if (tn.kind != JSTRY_FOR_IN && tn.kind != JSTRY_FOR_OF &&
        tn.kind != JSTRY_LOOP) {
      continue;
    }

    if (tn.start <= offset && offset < tn.start + tn.length) {
      return false;
    }
  }

  return true;
}

/////////////////////////////////////////////////////////////////////
// JSObject
/////////////////////////////////////////////////////////////////////

bool GlobalObject::shouldSplicePrototype() {
  // During bootstrapping, we need to make sure not to splice a new prototype in
  // for the global object if its __proto__ had previously been set to non-null,
  // as this will change the prototype for all other objects with the same type.
  return staticPrototype() == nullptr;
}

/* static */
bool JSObject::splicePrototype(JSContext* cx, HandleObject obj,
                               Handle<TaggedProto> proto) {
  MOZ_ASSERT(cx->compartment() == obj->compartment());

  /*
   * For singleton groups representing only a single JSObject, the proto
   * can be rearranged as needed without destroying type information for
   * the old or new types.
   */
  MOZ_ASSERT(obj->isSingleton());

  // Windows may not appear on prototype chains.
  MOZ_ASSERT_IF(proto.isObject(), !IsWindow(proto.toObject()));

#ifdef DEBUG
  const JSClass* oldClass = obj->getClass();
#endif

  if (proto.isObject()) {
    RootedObject protoObj(cx, proto.toObject());
    if (!JSObject::setDelegate(cx, protoObj)) {
      return false;
    }
  }

  // Force type instantiation when splicing lazy group.
  RootedObjectGroup group(cx, JSObject::getGroup(cx, obj));
  if (!group) {
    return false;
  }
  RootedObjectGroup protoGroup(cx, nullptr);
  if (proto.isObject()) {
    RootedObject protoObj(cx, proto.toObject());
    protoGroup = JSObject::getGroup(cx, protoObj);
    if (!protoGroup) {
      return false;
    }
  }

  MOZ_ASSERT(group->clasp() == oldClass,
             "splicing a prototype doesn't change a group's class");
  group->setProto(proto);
  return true;
}

/* static */
ObjectGroup* JSObject::makeLazyGroup(JSContext* cx, HandleObject obj) {
  MOZ_ASSERT(obj->hasLazyGroup());
  MOZ_ASSERT(cx->compartment() == obj->compartment());

  // Find flags which need to be specified immediately on the object.
  // Don't track whether singletons are packed.
  ObjectGroupFlags initialFlags =
      OBJECT_FLAG_SINGLETON | OBJECT_FLAG_NON_PACKED;

  if (obj->isIteratedSingleton()) {
    initialFlags |= OBJECT_FLAG_ITERATED;
  }

  if (obj->isNative() && obj->as<NativeObject>().isIndexed()) {
    initialFlags |= OBJECT_FLAG_SPARSE_INDEXES;
  }

  if (obj->is<ArrayObject>() && obj->as<ArrayObject>().length() > INT32_MAX) {
    initialFlags |= OBJECT_FLAG_LENGTH_OVERFLOW;
  }

  Rooted<TaggedProto> proto(cx, obj->taggedProto());
  ObjectGroup* group = ObjectGroupRealm::makeGroup(
      cx, obj->nonCCWRealm(), obj->getClass(), proto, initialFlags);
  if (!group) {
    return nullptr;
  }

  AutoEnterAnalysis enter(cx);

  /* Fill in the type according to the state of this object. */

  if (obj->is<JSFunction>() && obj->as<JSFunction>().isInterpreted()) {
    group->setInterpretedFunction(&obj->as<JSFunction>());
  }

  obj->group_ = group;

  return group;
}

/* static */
bool JSObject::setNewGroupUnknown(JSContext* cx, ObjectGroupRealm& realm,
                                  const JSClass* clasp, JS::HandleObject obj) {
  ObjectGroup::setDefaultNewGroupUnknown(cx, realm, clasp, obj);
  return JSObject::setFlags(cx, obj, BaseShape::NEW_GROUP_UNKNOWN);
}

/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm NewTable
/////////////////////////////////////////////////////////////////////

/*
 * Entries for the per-realm set of groups which are the default
 * types to use for some prototype. An optional associated object is used which
 * allows multiple groups to be created with the same prototype. The
 * associated object may be a function (for types constructed with 'new') or a
 * type descriptor (for typed objects). These entries are also used for the set
 * of lazy groups in the realm, which use a null associated object
 * (though there are only a few of these per realm).
 */
struct ObjectGroupRealm::NewEntry {
  WeakHeapPtrObjectGroup group;

  // Note: This pointer is only used for equality and does not need a read
  // barrier.
  JSObject* associated;

  NewEntry(ObjectGroup* group, JSObject* associated)
      : group(group), associated(associated) {}

  struct Lookup {
    const JSClass* clasp;
    TaggedProto proto;
    JSObject* associated;

    Lookup(const JSClass* clasp, TaggedProto proto, JSObject* associated)
        : clasp(clasp), proto(proto), associated(associated) {
      MOZ_ASSERT((associated && associated->is<JSFunction>()) == !clasp);
    }

    explicit Lookup(const NewEntry& entry)
        : clasp(entry.group.unbarrieredGet()->clasp()),
          proto(entry.group.unbarrieredGet()->proto()),
          associated(entry.associated) {
      if (associated && associated->is<JSFunction>()) {
        clasp = nullptr;
      }
    }
  };

  bool needsSweep() {
    return IsAboutToBeFinalized(&group) ||
           (associated && IsAboutToBeFinalizedUnbarriered(&associated));
  }

  bool operator==(const NewEntry& other) const {
    return group == other.group && associated == other.associated;
  }
};

namespace js {
template <>
struct MovableCellHasher<ObjectGroupRealm::NewEntry> {
  using Key = ObjectGroupRealm::NewEntry;
  using Lookup = ObjectGroupRealm::NewEntry::Lookup;

  static bool hasHash(const Lookup& l) {
    return MovableCellHasher<TaggedProto>::hasHash(l.proto) &&
           MovableCellHasher<JSObject*>::hasHash(l.associated);
  }

  static bool ensureHash(const Lookup& l) {
    return MovableCellHasher<TaggedProto>::ensureHash(l.proto) &&
           MovableCellHasher<JSObject*>::ensureHash(l.associated);
  }

  static inline HashNumber hash(const Lookup& lookup) {
    HashNumber hash = MovableCellHasher<TaggedProto>::hash(lookup.proto);
    hash = mozilla::AddToHash(
        hash, MovableCellHasher<JSObject*>::hash(lookup.associated));
    return mozilla::AddToHash(hash, mozilla::HashGeneric(lookup.clasp));
  }

  static inline bool match(const ObjectGroupRealm::NewEntry& key,
                           const Lookup& lookup) {
    if (lookup.clasp && key.group.unbarrieredGet()->clasp() != lookup.clasp) {
      return false;
    }

    TaggedProto proto = key.group.unbarrieredGet()->proto();
    if (!MovableCellHasher<TaggedProto>::match(proto, lookup.proto)) {
      return false;
    }

    return MovableCellHasher<JSObject*>::match(key.associated,
                                               lookup.associated);
  }
};
} // namespace js

class ObjectGroupRealm::NewTable
    : public JS::WeakCache<js::GCHashSet<NewEntry, MovableCellHasher<NewEntry>,
                                         SystemAllocPolicy>> {
  using Table =
      js::GCHashSet<NewEntry, MovableCellHasher<NewEntry>, SystemAllocPolicy>;
  using Base = JS::WeakCache<Table>;

 public:
  explicit NewTable(Zone* zone) : Base(zone) {}
};

/* static*/ ObjectGroupRealm& ObjectGroupRealm::get(const ObjectGroup* group) {
  return group->realm()->objectGroups_;
}

/* static*/ ObjectGroupRealm& ObjectGroupRealm::getForNewObject(JSContext* cx) {
  return cx->realm()->objectGroups_;
}

MOZ_ALWAYS_INLINE ObjectGroup* ObjectGroupRealm::DefaultNewGroupCache::lookup(
    const JSClass* clasp, TaggedProto proto, JSObject* associated) {
  if (group_ && associated_ == associated && group_->proto() == proto &&
      (!clasp || group_->clasp() == clasp)) {
    return group_;
  }
  return nullptr;
}

/* static */
ObjectGroup* ObjectGroup::defaultNewGroup(JSContext* cx, const JSClass* clasp,
                                          TaggedProto proto,
                                          JSObject* associated) {
  MOZ_ASSERT_IF(associated, proto.isObject());
  MOZ_ASSERT_IF(proto.isObject(),
                cx->isInsideCurrentCompartment(proto.toObject()));

  // A null lookup clasp is used for 'new' groups with an associated
  // function. The group starts out as a plain object but might mutate into an
  // unboxed plain object.
  MOZ_ASSERT_IF(!clasp, !!associated);

  if (associated) {
    MOZ_ASSERT_IF(!associated->is<TypeDescr>(), !clasp);
    if (associated->is<JSFunction>()) {
      // Canonicalize new functions to use the original one associated with its
      // script.
      associated = associated->as<JSFunction>().maybeCanonicalFunction();

      // If we have previously cleared the 'new' script information for this
      // function, don't try to construct another one. Also, for simplicity,
      // don't bother optimizing cross-realm constructors.
      if (associated && (associated->as<JSFunction>().wasNewScriptCleared() ||
                         associated->as<JSFunction>().realm() != cx->realm())) {
        associated = nullptr;
      }
    } else if (associated->is<TypeDescr>()) {
      if (!clasp) {
        // This can happen when we call Reflect.construct with a TypeDescr as
        // newTarget argument. We're creating a plain object in this case, so
        // don't set the TypeDescr on the group.
        associated = nullptr;
      }
    } else {
      associated = nullptr;
    }

    if (!associated) {
      clasp = &PlainObject::class_;
    }
  }

  ObjectGroupRealm& groups = ObjectGroupRealm::getForNewObject(cx);

  if (ObjectGroup* group =
          groups.defaultNewGroupCache.lookup(clasp, proto, associated)) {
    return group;
  }

  AutoEnterAnalysis enter(cx);

  ObjectGroupRealm::NewTable*& table = groups.defaultNewTable;

  if (!table) {
    table = cx->new_<ObjectGroupRealm::NewTable>(cx->zone());
    if (!table) {
      return nullptr;
    }
  }

  if (proto.isObject() && !proto.toObject()->isDelegate()) {
    RootedObject protoObj(cx, proto.toObject());
    if (!JSObject::setDelegate(cx, protoObj)) {
      return nullptr;
    }

    // Objects which are prototypes of one another should be singletons, so
    // that their type information can be tracked more precisely. Limit
    // this group change to plain objects, to avoid issues with other types
    // of singletons like typed arrays.
    if (protoObj->is<PlainObject>() && !protoObj->isSingleton()) {
      if (!JSObject::changeToSingleton(cx, protoObj)) {
        return nullptr;
      }

      // |ReshapeForProtoMutation| ensures singletons will reshape when
      // prototype is mutated so clear the UNCACHEABLE_PROTO flag.
      if (protoObj->hasUncacheableProto()) {
        HandleNativeObject nobj = protoObj.as<NativeObject>();
        if (!NativeObject::clearFlag(cx, nobj, BaseShape::UNCACHEABLE_PROTO)) {
          return nullptr;
        }
      }
    }
  }

  ObjectGroupRealm::NewTable::AddPtr p = table->lookupForAdd(
      ObjectGroupRealm::NewEntry::Lookup(clasp, proto, associated));
  if (p) {
    ObjectGroup* group = p->group;
    MOZ_ASSERT_IF(clasp, group->clasp() == clasp);
    MOZ_ASSERT_IF(!clasp, group->clasp() == &PlainObject::class_);
    MOZ_ASSERT(group->proto() == proto);
    groups.defaultNewGroupCache.put(group, associated);
    return group;
  }

  ObjectGroupFlags initialFlags = 0;
  if (proto.isDynamic() ||
      (proto.isObject() && proto.toObject()->isNewGroupUnknown())) {
    initialFlags = OBJECT_FLAG_DYNAMIC_MASK;
  }

  Rooted<TaggedProto> protoRoot(cx, proto);
  ObjectGroup* group = ObjectGroupRealm::makeGroup(
      cx, cx->realm(), clasp ? clasp : &PlainObject::class_, protoRoot,
      initialFlags);
  if (!group) {
    return nullptr;
  }

  if (!table->add(p, ObjectGroupRealm::NewEntry(group, associated))) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  if (associated) {
    if (associated->is<JSFunction>()) {
      if (!TypeNewScript::make(cx, group, &associated->as<JSFunction>())) {
        return nullptr;
      }
    } else {
      group->setTypeDescr(&associated->as<TypeDescr>());
    }
  }

  /*
   * Some builtin objects have slotful native properties baked in at
   * creation via the Shape::{insert,get}initialShape mechanism. Since
   * these properties are never explicitly defined on new objects, update
   * the type information for them here.
   */

  const JSAtomState& names = cx->names();

  if (clasp == &RegExpObject::class_) {
    AddTypePropertyId(cx, group, nullptr, NameToId(names.lastIndex),
                      TypeSet::Int32Type());
  } else if (clasp == &StringObject::class_) {
    AddTypePropertyId(cx, group, nullptr, NameToId(names.length),
                      TypeSet::Int32Type());
  } else if (ErrorObject::isErrorClass(clasp)) {
    AddTypePropertyId(cx, group, nullptr, NameToId(names.fileName),
                      TypeSet::StringType());
    AddTypePropertyId(cx, group, nullptr, NameToId(names.lineNumber),
                      TypeSet::Int32Type());
    AddTypePropertyId(cx, group, nullptr, NameToId(names.columnNumber),
                      TypeSet::Int32Type());
  }

  groups.defaultNewGroupCache.put(group, associated);
  return group;
}

/* static */
ObjectGroup* ObjectGroup::lazySingletonGroup(JSContext* cx,
                                             ObjectGroup* oldGroup,
                                             const JSClass* clasp,
                                             TaggedProto proto) {
  ObjectGroupRealm& realm = oldGroup ? ObjectGroupRealm::get(oldGroup)
                                     : ObjectGroupRealm::getForNewObject(cx);

  MOZ_ASSERT_IF(proto.isObject(),
                cx->compartment() == proto.toObject()->compartment());

  ObjectGroupRealm::NewTable*& table = realm.lazyTable;

  if (!table) {
    table = cx->new_<ObjectGroupRealm::NewTable>(cx->zone());
    if (!table) {
      return nullptr;
    }
  }

  ObjectGroupRealm::NewTable::AddPtr p = table->lookupForAdd(
      ObjectGroupRealm::NewEntry::Lookup(clasp, proto, nullptr));
  if (p) {
    ObjectGroup* group = p->group;
    MOZ_ASSERT(group->lazy());

    return group;
  }

  AutoEnterAnalysis enter(cx);

  Rooted<TaggedProto> protoRoot(cx, proto);
  ObjectGroup* group = ObjectGroupRealm::makeGroup(
      cx, oldGroup ? oldGroup->realm() : cx->realm(), clasp, protoRoot,
      OBJECT_FLAG_SINGLETON | OBJECT_FLAG_LAZY_SINGLETON);
  if (!group) {
    return nullptr;
  }

  if (!table->add(p, ObjectGroupRealm::NewEntry(group, nullptr))) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  return group;
}

/* static */
void ObjectGroup::setDefaultNewGroupUnknown(JSContext* cx,
                                            ObjectGroupRealm& realm,
                                            const JSClass* clasp,
                                            HandleObject obj) {
  // If the object already has a new group, mark that group as unknown.
  ObjectGroupRealm::NewTable* table = realm.defaultNewTable;
  if (table) {
    Rooted<TaggedProto> taggedProto(cx, TaggedProto(obj));
    auto lookup =
        ObjectGroupRealm::NewEntry::Lookup(clasp, taggedProto, nullptr);
    auto p = table->lookup(lookup);
    if (p) {
      MarkObjectGroupUnknownProperties(cx, p->group);
    }
  }
}

#ifdef DEBUG
/* static */
bool ObjectGroup::hasDefaultNewGroup(JSObject* proto, const JSClass* clasp,
                                     ObjectGroup* group) {
  ObjectGroupRealm::NewTable* table =
      ObjectGroupRealm::get(group).defaultNewTable;

  if (table) {
    auto lookup =
        ObjectGroupRealm::NewEntry::Lookup(clasp, TaggedProto(proto), nullptr);
    auto p = table->lookup(lookup);
    return p && p->group == group;
  }
  return false;
}
#endif /* DEBUG */

inline const JSClass* GetClassForProtoKey(JSProtoKey key) {
  switch (key) {
    case JSProto_Null:
    case JSProto_Object:
      return &PlainObject::class_;
    case JSProto_Array:
      return &ArrayObject::class_;

    case JSProto_Int8Array:
    case JSProto_Uint8Array:
    case JSProto_Int16Array:
    case JSProto_Uint16Array:
    case JSProto_Int32Array:
    case JSProto_Uint32Array:
    case JSProto_Float32Array:
    case JSProto_Float64Array:
    case JSProto_Uint8ClampedArray:
    case JSProto_BigInt64Array:
    case JSProto_BigUint64Array:
      return &TypedArrayObject::classes[key - JSProto_Int8Array];

    default:
      // We only expect to see plain objects, arrays, and typed arrays here.
      MOZ_CRASH("Bad proto key");
  }
}

/* static */
ObjectGroup* ObjectGroup::defaultNewGroup(JSContext* cx, JSProtoKey key) {
  JSObject* proto = nullptr;
  if (key != JSProto_Null) {
    proto = GlobalObject::getOrCreatePrototype(cx, key);
    if (!proto) {
      return nullptr;
    }
  }
  return defaultNewGroup(cx, GetClassForProtoKey(key), TaggedProto(proto));
}

/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm ArrayObjectTable
/////////////////////////////////////////////////////////////////////

struct ObjectGroupRealm::ArrayObjectKey : public DefaultHasher<ArrayObjectKey> {
  TypeSet::Type type;

  ArrayObjectKey() : type(TypeSet::UndefinedType()) {}

  explicit ArrayObjectKey(TypeSet::Type type) : type(type) {}

  static inline uint32_t hash(const ArrayObjectKey& v) { return v.type.raw(); }

  static inline bool match(const ArrayObjectKey& v1, const ArrayObjectKey& v2) {
    return v1.type == v2.type;
  }

  bool operator==(const ArrayObjectKey& other) { return type == other.type; }

  bool operator!=(const ArrayObjectKey& other) { return !(*this == other); }

  bool needsSweep() {
    MOZ_ASSERT(type.isUnknown() || !type.isSingleton());
    if (!type.isUnknown() && type.isGroup()) {
      ObjectGroup* group = type.groupNoBarrier();
      if (IsAboutToBeFinalizedUnbarriered(&group)) {
        return true;
      }
      if (group != type.groupNoBarrier()) {
        type = TypeSet::ObjectType(group);
      }
    }
    return false;
  }
};

static inline bool NumberTypes(TypeSet::Type a, TypeSet::Type b) {
  return (a.isPrimitive(ValueType::Int32) ||
          a.isPrimitive(ValueType::Double)) &&
         (b.isPrimitive(ValueType::Int32) || b.isPrimitive(ValueType::Double));
}

/*
 * As for GetValueType, but requires object types to be non-singletons with
 * their default prototype. These are the only values that should appear in
 * arrays and objects whose type can be fixed.
 */
static inline TypeSet::Type GetValueTypeForTable(const Value& v) {
  TypeSet::Type type = TypeSet::GetValueType(v);
  MOZ_ASSERT(!type.isSingleton());
  return type;
}

/* static */
ArrayObject* ObjectGroup::newArrayObject(JSContext* cx, const Value* vp,
                                         size_t length, NewObjectKind newKind,
                                         NewArrayKind arrayKind) {
  MOZ_ASSERT(newKind != SingletonObject);

  // If we are making a copy on write array, don't try to adjust the group as
  // getOrFixupCopyOnWriteObject will do this before any objects are copied
  // from this one.
  if (arrayKind == NewArrayKind::CopyOnWrite) {
    ArrayObject* obj = NewDenseCopiedArray(cx, length, vp, nullptr, newKind);
    if (!obj || !ObjectElements::MakeElementsCopyOnWrite(cx, obj)) {
      return nullptr;
    }
    return obj;
  }

  // Get a type which captures all the elements in the array to be created.
  Rooted<TypeSet::Type> elementType(cx, TypeSet::UnknownType());
  if (arrayKind != NewArrayKind::UnknownIndex && length != 0) {
    elementType = GetValueTypeForTable(vp[0]);
    for (unsigned i = 1; i < length; i++) {
      TypeSet::Type ntype = GetValueTypeForTable(vp[i]);
      if (ntype != elementType) {
        if (NumberTypes(elementType, ntype)) {
          elementType = TypeSet::DoubleType();
        } else {
          elementType = TypeSet::UnknownType();
          break;
        }
      }
    }
  }

  ObjectGroupRealm& realm = ObjectGroupRealm::getForNewObject(cx);
  ObjectGroupRealm::ArrayObjectTable*& table = realm.arrayObjectTable;

  if (!table) {
    table = cx->new_<ObjectGroupRealm::ArrayObjectTable>();
    if (!table) {
      return nullptr;
    }
  }

  ObjectGroupRealm::ArrayObjectKey key(elementType);
  DependentAddPtr<ObjectGroupRealm::ArrayObjectTable> p(cx, *table, key);

  RootedObjectGroup group(cx);
  if (p) {
    group = p->value();
  } else {
    JSObject* proto = GlobalObject::getOrCreateArrayPrototype(cx, cx->global());
    if (!proto) {
      return nullptr;
    }
    Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
    group = ObjectGroupRealm::makeGroup(cx, cx->realm(), &ArrayObject::class_,
                                        taggedProto);
    if (!group) {
      return nullptr;
    }

    AddTypePropertyId(cx, group, nullptr, JSID_VOID, elementType);

    if (!p.add(cx, *table, ObjectGroupRealm::ArrayObjectKey(elementType),
               group)) {
      return nullptr;
    }
  }

  // The type of the elements being added will already be reflected in type
  // information.
  ShouldUpdateTypes updateTypes = ShouldUpdateTypes::DontUpdate;
  return NewCopiedArrayTryUseGroup(cx, group, vp, length, newKind, updateTypes);
}

// Try to change the group of |source| to match that of |target|.
static bool GiveObjectGroup(JSContext* cx, JSObject* source, JSObject* target) {
  MOZ_ASSERT(source->group() != target->group());

  if (!target->is<ArrayObject>() || !source->is<ArrayObject>()) {
    return true;
  }

  source->setGroup(target->group());

  for (size_t i = 0; i < source->as<ArrayObject>().getDenseInitializedLength();
       i++) {
    Value v = source->as<ArrayObject>().getDenseElement(i);
    AddTypePropertyId(cx, source->group(), source, JSID_VOID, v);
  }

  return true;
}

static bool SameGroup(JSObject* first, JSObject* second) {
  return first->group() == second->group();
}

// When generating a multidimensional array of literals, such as
// [[1,2],[3,4],[5.5,6.5]], try to ensure that each element of the array has
// the same group. This is mainly important when the elements might have
// different native vs. unboxed layouts, or different unboxed layouts, and
// accessing the heterogenous layouts from JIT code will be much slower than
// if they were homogenous.
//
// To do this, with each new array element we compare it with one of the
// previous ones, and try to mutate the group of the new element to fit that
// of the old element. If this isn't possible, the groups for all old elements
// are mutated to fit that of the new element.
bool js::CombineArrayElementTypes(JSContext* cx, JSObject* newObj,
                                  const Value* compare, size_t ncompare) {
  if (!ncompare || !compare[0].isObject()) {
    return true;
  }

  JSObject* oldObj = &compare[0].toObject();
  if (SameGroup(oldObj, newObj)) {
    return true;
  }

  if (!GiveObjectGroup(cx, newObj, oldObj)) {
    return false;
  }

  if (SameGroup(oldObj, newObj)) {
    return true;
  }

  if (!GiveObjectGroup(cx, oldObj, newObj)) {
    return false;
  }

  if (SameGroup(oldObj, newObj)) {
    for (size_t i = 1; i < ncompare; i++) {
      if (compare[i].isObject() && !SameGroup(&compare[i].toObject(), newObj)) {
        if (!GiveObjectGroup(cx, &compare[i].toObject(), newObj)) {
          return false;
        }
      }
    }
  }

  return true;
}

// Similarly to CombineArrayElementTypes, if we are generating an array of
// plain objects with a consistent property layout, such as
// [{p:[1,2]},{p:[3,4]},{p:[5.5,6.5]}], where those plain objects in
// turn have arrays as their own properties, try to ensure that a consistent
// group is given to each array held by the same property of the plain objects.
bool js::CombinePlainObjectPropertyTypes(JSContext* cx, JSObject* newObj,
                                         const Value* compare,
                                         size_t ncompare) {
  if (!ncompare || !compare[0].isObject()) {
    return true;
  }

  JSObject* oldObj = &compare[0].toObject();
  if (!SameGroup(oldObj, newObj)) {
    return true;
  }

  if (newObj->is<PlainObject>()) {
    if (newObj->as<PlainObject>().lastProperty() !=
        oldObj->as<PlainObject>().lastProperty()) {
      return true;
    }

    for (size_t slot = 0; slot < newObj->as<PlainObject>().slotSpan(); slot++) {
      Value newValue = newObj->as<PlainObject>().getSlot(slot);
      Value oldValue = oldObj->as<PlainObject>().getSlot(slot);

      if (!newValue.isObject() || !oldValue.isObject()) {
        continue;
      }

      JSObject* newInnerObj = &newValue.toObject();
      JSObject* oldInnerObj = &oldValue.toObject();

      if (SameGroup(oldInnerObj, newInnerObj)) {
        continue;
      }

      if (!GiveObjectGroup(cx, newInnerObj, oldInnerObj)) {
        return false;
      }

      if (SameGroup(oldInnerObj, newInnerObj)) {
        continue;
      }

      if (!GiveObjectGroup(cx, oldInnerObj, newInnerObj)) {
        return false;
      }

      if (SameGroup(oldInnerObj, newInnerObj)) {
        for (size_t i = 1; i < ncompare; i++) {
          if (compare[i].isObject() &&
              SameGroup(&compare[i].toObject(), newObj)) {
            Value otherValue =
                compare[i].toObject().as<PlainObject>().getSlot(slot);
            if (otherValue.isObject() &&
                !SameGroup(&otherValue.toObject(), newInnerObj)) {
              if (!GiveObjectGroup(cx, &otherValue.toObject(), newInnerObj)) {
                return false;
              }
            }
          }
        }
      }
    }
  }
  return true;
}

/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm PlainObjectTable
/////////////////////////////////////////////////////////////////////

struct ObjectGroupRealm::PlainObjectKey {
  jsid* properties;
  uint32_t nproperties;

  struct Lookup {
    IdValuePair* properties;
    uint32_t nproperties;

    Lookup(IdValuePair* properties, uint32_t nproperties)
        : properties(properties), nproperties(nproperties) {}
  };

  static inline HashNumber hash(const Lookup& lookup) {
    HashNumber hash = HashId(lookup.properties[lookup.nproperties - 1].id);
    return mozilla::AddToHash(hash, lookup.nproperties);
  }

  static inline bool match(const PlainObjectKey& v, const Lookup& lookup) {
    if (lookup.nproperties != v.nproperties) {
      return false;
    }
    for (size_t i = 0; i < lookup.nproperties; i++) {
      if (lookup.properties[i].id != v.properties[i]) {
        return false;
      }
    }
    return true;
  }

  bool needsSweep() {
    for (unsigned i = 0; i < nproperties; i++) {
      if (gc::IsAboutToBeFinalizedUnbarriered(&properties[i])) {
        return true;
      }
    }
    return false;
  }
};

struct ObjectGroupRealm::PlainObjectEntry {
  WeakHeapPtrObjectGroup group;
  WeakHeapPtrShape shape;
  TypeSet::Type* types;

  bool needsSweep(unsigned nproperties) {
    if (IsAboutToBeFinalized(&group)) {
      return true;
    }
    if (IsAboutToBeFinalized(&shape)) {
      return true;
    }
    for (unsigned i = 0; i < nproperties; i++) {
      MOZ_ASSERT(!types[i].isSingleton());
      if (types[i].isGroup()) {
        ObjectGroup* group = types[i].groupNoBarrier();
        if (IsAboutToBeFinalizedUnbarriered(&group)) {
          return true;
        }
        if (group != types[i].groupNoBarrier()) {
          types[i] = TypeSet::ObjectType(group);
        }
      }
    }
    return false;
  }
};

static bool CanShareObjectGroup(IdValuePair* properties, size_t nproperties) {
  // Don't reuse groups for objects containing indexed properties, which
  // might end up as dense elements.
  for (size_t i = 0; i < nproperties; i++) {
    uint32_t index;
    if (IdIsIndex(properties[i].id, &index)) {
      return false;
    }
  }
  return true;
}

static bool AddPlainObjectProperties(JSContext* cx, HandlePlainObject obj,
                                     IdValuePair* properties,
                                     size_t nproperties) {
  RootedId propid(cx);
  RootedValue value(cx);

  for (size_t i = 0; i < nproperties; i++) {
    propid = properties[i].id;
    value = properties[i].value;
    if (!NativeDefineDataProperty(cx, obj, propid, value, JSPROP_ENUMERATE)) {
      return false;
    }
  }

  return true;
}

PlainObject* js::NewPlainObjectWithProperties(JSContext* cx,
                                              IdValuePair* properties,
                                              size_t nproperties,
                                              NewObjectKind newKind) {
  gc::AllocKind allocKind = gc::GetGCObjectKind(nproperties);
  RootedPlainObject obj(
      cx, NewBuiltinClassInstance<PlainObject>(cx, allocKind, newKind));
  if (!obj || !AddPlainObjectProperties(cx, obj, properties, nproperties)) {
    return nullptr;
  }
  return obj;
}

/* static */
JSObject* ObjectGroup::newPlainObject(JSContext* cx, IdValuePair* properties,
                                      size_t nproperties,
                                      NewObjectKind newKind) {
  // Watch for simple cases where we don't try to reuse plain object groups.
  if (newKind == SingletonObject || nproperties == 0 ||
      nproperties >= PropertyTree::MAX_HEIGHT) {
    return NewPlainObjectWithProperties(cx, properties, nproperties, newKind);
  }

  ObjectGroupRealm& realm = ObjectGroupRealm::getForNewObject(cx);
  ObjectGroupRealm::PlainObjectTable*& table = realm.plainObjectTable;

  if (!table) {
    table = cx->new_<ObjectGroupRealm::PlainObjectTable>();
    if (!table) {
      return nullptr;
    }
  }

  ObjectGroupRealm::PlainObjectKey::Lookup lookup(properties, nproperties);
  ObjectGroupRealm::PlainObjectTable::Ptr p = table->lookup(lookup);

  if (!p) {
    if (!CanShareObjectGroup(properties, nproperties)) {
      return NewPlainObjectWithProperties(cx, properties, nproperties, newKind);
    }

    JSObject* proto = GlobalObject::getOrCreatePrototype(cx, JSProto_Object);
    if (!proto) {
      return nullptr;
    }

    Rooted<TaggedProto> tagged(cx, TaggedProto(proto));
    RootedObjectGroup group(
        cx, ObjectGroupRealm::makeGroup(cx, cx->realm(), &PlainObject::class_,
                                        tagged));
    if (!group) {
      return nullptr;
    }

    gc::AllocKind allocKind = gc::GetGCObjectKind(nproperties);
    RootedPlainObject obj(cx, NewObjectWithGroup<PlainObject>(
                                  cx, group, allocKind, TenuredObject));
    if (!obj || !AddPlainObjectProperties(cx, obj, properties, nproperties)) {
      return nullptr;
    }

    // Don't make entries with duplicate property names, which will show up
    // here as objects with fewer properties than we thought we were
    // adding to the object. In this case, reset the object's group to the
    // default (which will have unknown properties) so that the group we
    // just created will be collected by the GC.
    if (obj->slotSpan() != nproperties) {
      ObjectGroup* group =
          defaultNewGroup(cx, obj->getClass(), obj->taggedProto());
      if (!group) {
        return nullptr;
      }
      obj->setGroup(group);
      return obj;
    }

    // Keep track of the initial objects we create with this type.
    // If the initial ones have a consistent shape and property types, we
    // will try to use an unboxed layout for the group.
    PreliminaryObjectArrayWithTemplate* preliminaryObjects =
        cx->new_<PreliminaryObjectArrayWithTemplate>(obj->lastProperty());
    if (!preliminaryObjects) {
      return nullptr;
    }
    group->setPreliminaryObjects(preliminaryObjects);
    preliminaryObjects->registerNewObject(obj);

    auto ids = cx->make_zeroed_pod_array<jsid>(nproperties);
    if (!ids) {
      return nullptr;
    }

    auto types = cx->make_zeroed_pod_array<TypeSet::Type>(nproperties);
    if (!types) {
      return nullptr;
    }

    for (size_t i = 0; i < nproperties; i++) {
      ids[i] = properties[i].id;
      types[i] = GetValueTypeForTable(obj->getSlot(i));
      AddTypePropertyId(cx, group, nullptr, IdToTypeId(ids[i]), types[i]);
    }

    ObjectGroupRealm::PlainObjectKey key;
    key.properties = ids.get();
    key.nproperties = nproperties;
    MOZ_ASSERT(ObjectGroupRealm::PlainObjectKey::match(key, lookup));

    ObjectGroupRealm::PlainObjectEntry entry;
    entry.group.set(group);
    entry.shape.set(obj->lastProperty());
    entry.types = types.get();

    ObjectGroupRealm::PlainObjectTable::AddPtr np = table->lookupForAdd(lookup);
    if (!table->add(np, key, entry)) {
      ReportOutOfMemory(cx);
      return nullptr;
    }

    mozilla::Unused << ids.release();
    mozilla::Unused << types.release();

    return obj;
  }

  RootedObjectGroup group(cx, p->value().group);

  // AutoSweepObjectGroup checks no GC happens in its scope, so we use Maybe
  // and reset() it before GC calls.
  mozilla::Maybe<AutoSweepObjectGroup> sweep;
  sweep.emplace(group);

  // Update property types according to the properties we are about to add.
  // Do this before we do anything which can GC, which might move or remove
  // this table entry.
  if (!group->unknownProperties(*sweep)) {
    for (size_t i = 0; i < nproperties; i++) {
      TypeSet::Type type = p->value().types[i];
      TypeSet::Type ntype = GetValueTypeForTable(properties[i].value);
      if (ntype == type) {
        continue;
      }
      if (ntype.isPrimitive(ValueType::Int32) &&
          type.isPrimitive(ValueType::Double)) {
        // The property types already reflect 'int32'.
      } else {
        if (ntype.isPrimitive(ValueType::Double) &&
            type.isPrimitive(ValueType::Int32)) {
          // Include 'double' in the property types to avoid the update below
          // later.
          p->value().types[i] = TypeSet::DoubleType();
        }
        AddTypePropertyId(cx, group, nullptr, IdToTypeId(properties[i].id),
                          ntype);
      }
    }
  }

  RootedShape shape(cx, p->value().shape);

  if (group->maybePreliminaryObjects(*sweep)) {
    newKind = TenuredObject;
  }

  sweep.reset();

  gc::AllocKind allocKind = gc::GetGCObjectKind(nproperties);
  RootedPlainObject obj(
      cx, NewObjectWithGroup<PlainObject>(cx, group, allocKind, newKind));

  if (!obj || !obj->setLastProperty(cx, shape)) {
    return nullptr;
  }

  for (size_t i = 0; i < nproperties; i++) {
    obj->setSlot(i, properties[i].value);
  }

  sweep.emplace(group);

  if (group->maybePreliminaryObjects(*sweep)) {
    group->maybePreliminaryObjects(*sweep)->registerNewObject(obj);
    group->maybePreliminaryObjects(*sweep)->maybeAnalyze(cx, group);
  }

  return obj;
}

/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm AllocationSiteTable
/////////////////////////////////////////////////////////////////////

struct ObjectGroupRealm::AllocationSiteKey {
  WeakHeapPtrScript script;

  uint32_t offset : 24;
  JSProtoKey kind : 8;

  WeakHeapPtrObject proto;

  static const uint32_t OFFSET_LIMIT = (1 << 23);

  AllocationSiteKey(JSScript* script_, uint32_t offset_, JSProtoKey kind_,
                    JSObject* proto_)
      : script(script_), offset(offset_), kind(kind_), proto(proto_) {
    MOZ_ASSERT(offset_ < OFFSET_LIMIT);
  }

  AllocationSiteKey(const AllocationSiteKey& key)
      : script(key.script),
        offset(key.offset),
        kind(key.kind),
        proto(key.proto) {}

  AllocationSiteKey(AllocationSiteKey&& key)
      : script(std::move(key.script)),
        offset(key.offset),
        kind(key.kind),
        proto(std::move(key.proto)) {}

  void operator=(AllocationSiteKey&& key) {
    script = std::move(key.script);
    offset = key.offset;
    kind = key.kind;
    proto = std::move(key.proto);
  }

  void trace(JSTracer* trc) {
    TraceRoot(trc, &script, "AllocationSiteKey script");
    TraceNullableRoot(trc, &proto, "AllocationSiteKey proto");
  }

  bool needsSweep() {
    return IsAboutToBeFinalizedUnbarriered(script.unsafeGet()) ||
           (proto && IsAboutToBeFinalizedUnbarriered(proto.unsafeGet()));
  }

  bool operator==(const AllocationSiteKey& other) const {
    return script == other.script && offset == other.offset &&
           kind == other.kind && proto == other.proto;
  }
};

namespace js {
template <>
struct MovableCellHasher<ObjectGroupRealm::AllocationSiteKey> {
  using Key = ObjectGroupRealm::AllocationSiteKey;
  using Lookup = ObjectGroupRealm::AllocationSiteKey;

  static bool hasHash(const Lookup& l) {
    return MovableCellHasher<JSScript*>::hasHash(l.script.unbarrieredGet()) &&
           MovableCellHasher<JSObject*>::hasHash(l.proto.unbarrieredGet());
  }
  static bool ensureHash(const Lookup& l) {
    return MovableCellHasher<JSScript*>::ensureHash(
               l.script.unbarrieredGet()) &&
           MovableCellHasher<JSObject*>::ensureHash(l.proto.unbarrieredGet());
  }
  static inline HashNumber hash(const Key& key) {
    HashNumber hash = mozilla::HashGeneric(key.offset, key.kind);
    hash = mozilla::AddToHash(
        hash, MovableCellHasher<JSScript*>::hash(key.script.unbarrieredGet()));
    hash = mozilla::AddToHash(
        hash, MovableCellHasher<JSObject*>::hash(key.proto.unbarrieredGet()));
    return hash;
  }

  static inline bool match(const Key& a, const Lookup& b) {
    return a.offset == b.offset && a.kind == b.kind &&
           MovableCellHasher<JSScript*>::match(a.script.unbarrieredGet(),
                                               b.script.unbarrieredGet()) &&
           MovableCellHasher<JSObject*>::match(a.proto.unbarrieredGet(),
                                               b.proto.unbarrieredGet());
  }
};
} // namespace js

class ObjectGroupRealm::AllocationSiteTable
    : public JS::WeakCache<js::GCHashMap<
          AllocationSiteKey, WeakHeapPtrObjectGroup,
          MovableCellHasher<AllocationSiteKey>, SystemAllocPolicy>> {
  using Table =
      js::GCHashMap<AllocationSiteKey, WeakHeapPtrObjectGroup,
                    MovableCellHasher<AllocationSiteKey>, SystemAllocPolicy>;
  using Base = JS::WeakCache<Table>;

 public:
  explicit AllocationSiteTable(Zone* zone) : Base(zone) {}
};

/* static */
ObjectGroup* ObjectGroup::allocationSiteGroup(
    JSContext* cx, JSScript* scriptArg, jsbytecode* pc, JSProtoKey kind,
    HandleObject protoArg /* = nullptr */) {
  MOZ_ASSERT(!useSingletonForAllocationSite(scriptArg, pc, kind));
  MOZ_ASSERT_IF(protoArg, kind == JSProto_Array);
  MOZ_ASSERT(cx->realm() == scriptArg->realm());

  uint32_t offset = scriptArg->pcToOffset(pc);

  if (offset >= ObjectGroupRealm::AllocationSiteKey::OFFSET_LIMIT) {
    if (protoArg) {
      return defaultNewGroup(cx, GetClassForProtoKey(kind),
                             TaggedProto(protoArg));
    }
    return defaultNewGroup(cx, kind);
  }

  ObjectGroupRealm& realm = ObjectGroupRealm::getForNewObject(cx);
  ObjectGroupRealm::AllocationSiteTable*& table = realm.allocationSiteTable;

  if (!table) {
    table = cx->new_<ObjectGroupRealm::AllocationSiteTable>(cx->zone());
    if (!table) {
      return nullptr;
    }
  }

  RootedScript script(cx, scriptArg);
  JSObject* proto = protoArg;
  if (!proto && kind != JSProto_Null) {
    proto = GlobalObject::getOrCreatePrototype(cx, kind);
    if (!proto) {
      return nullptr;
    }
  }

  Rooted<ObjectGroupRealm::AllocationSiteKey> key(
      cx, ObjectGroupRealm::AllocationSiteKey(script, offset, kind, proto));

  ObjectGroupRealm::AllocationSiteTable::AddPtr p = table->lookupForAdd(key);
  if (p) {
    return p->value();
  }

  AutoEnterAnalysis enter(cx);

  Rooted<TaggedProto> tagged(cx, TaggedProto(proto));
  ObjectGroup* res = ObjectGroupRealm::makeGroup(
      cx, script->realm(), GetClassForProtoKey(kind), tagged,
      OBJECT_FLAG_FROM_ALLOCATION_SITE);
  if (!res) {
    return nullptr;
  }

  if (JSOp(*pc) == JSOP_NEWOBJECT) {
    // Keep track of the preliminary objects with this group, so we can try
    // to use an unboxed layout for the object once some are allocated.
    Shape* shape = script->getObject(pc)->as<PlainObject>().lastProperty();
    if (!shape->isEmptyShape()) {
      PreliminaryObjectArrayWithTemplate* preliminaryObjects =
          cx->new_<PreliminaryObjectArrayWithTemplate>(shape);
      if (preliminaryObjects) {
        res->setPreliminaryObjects(preliminaryObjects);
      } else {
        cx->recoverFromOutOfMemory();
      }
    }
  }

  if (!table->add(p, key, res)) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  return res;
}

void ObjectGroupRealm::replaceAllocationSiteGroup(JSScript* script,
                                                  jsbytecode* pc,
                                                  JSProtoKey kind,
                                                  ObjectGroup* group) {
  MOZ_ASSERT(script->realm() == group->realm());

  AllocationSiteKey key(script, script->pcToOffset(pc), kind,
                        group->proto().toObjectOrNull());

  AllocationSiteTable::Ptr p = allocationSiteTable->lookup(key);
  MOZ_RELEASE_ASSERT(p);
  allocationSiteTable->remove(p);
  {
    AutoEnterOOMUnsafeRegion oomUnsafe;
    if (!allocationSiteTable->putNew(key, group)) {
      oomUnsafe.crash("Inconsistent object table");
    }
  }
}

/* static */
ObjectGroup* ObjectGroup::callingAllocationSiteGroup(JSContext* cx,
                                                     JSProtoKey key,
                                                     HandleObject proto) {
  MOZ_ASSERT_IF(proto, key == JSProto_Array);

  jsbytecode* pc;
  RootedScript script(cx, cx->currentScript(&pc));
  if (script) {
    return allocationSiteGroup(cx, script, pc, key, proto);
  }
  if (proto) {
    return defaultNewGroup(cx, GetClassForProtoKey(key), TaggedProto(proto));
  }
  return defaultNewGroup(cx, key);
}

/* static */
bool ObjectGroup::setAllocationSiteObjectGroup(JSContext* cx,
                                               HandleScript script,
                                               jsbytecode* pc, HandleObject obj,
                                               bool singleton) {
  JSProtoKey key = JSCLASS_CACHED_PROTO_KEY(obj->getClass());
  MOZ_ASSERT(key != JSProto_Null);
  MOZ_ASSERT(singleton == useSingletonForAllocationSite(script, pc, key));

  if (singleton) {
    MOZ_ASSERT(obj->isSingleton());
  } else {
    ObjectGroup* group = allocationSiteGroup(cx, script, pc, key);
    if (!group) {
      return false;
    }
    obj->setGroup(group);
  }

  return true;
}

/* static */
ArrayObject* ObjectGroup::getOrFixupCopyOnWriteObject(JSContext* cx,
                                                      HandleScript script,
                                                      jsbytecode* pc) {
  // Make sure that the template object for script/pc has a type indicating
  // that the object and its copies have copy on write elements.
  RootedArrayObject obj(
      cx, &script->getObject(GET_UINT32_INDEX(pc))->as<ArrayObject>());
  MOZ_ASSERT(obj->denseElementsAreCopyOnWrite());

  {
    AutoSweepObjectGroup sweepObjGroup(obj->group());
    if (obj->group()->fromAllocationSite(sweepObjGroup)) {
      MOZ_ASSERT(
          obj->group()->hasAnyFlags(sweepObjGroup, OBJECT_FLAG_COPY_ON_WRITE));
      return obj;
    }
  }

  RootedObjectGroup group(cx,
                          allocationSiteGroup(cx, script, pc, JSProto_Array));
  if (!group) {
    return nullptr;
  }

  AutoSweepObjectGroup sweepGroup(group);
  group->addFlags(sweepGroup, OBJECT_FLAG_COPY_ON_WRITE);

  // Update type information in the initializer object group.
  MOZ_ASSERT(obj->slotSpan() == 0);
  for (size_t i = 0; i < obj->getDenseInitializedLength(); i++) {
    const Value& v = obj->getDenseElement(i);
    AddTypePropertyId(cx, group, nullptr, JSID_VOID, v);
  }

  obj->setGroup(group);
  return obj;
}

/* static */
ArrayObject* ObjectGroup::getCopyOnWriteObject(JSScript* script,
                                               jsbytecode* pc) {
  // getOrFixupCopyOnWriteObject should already have been called for
  // script/pc, ensuring that the template object has a group with the
  // COPY_ON_WRITE flag. We don't assert this here, due to a corner case
  // where this property doesn't hold. See jsop_newarray_copyonwrite in
  // IonBuilder.
  ArrayObject* obj =
      &script->getObject(GET_UINT32_INDEX(pc))->as<ArrayObject>();
  MOZ_ASSERT(obj->denseElementsAreCopyOnWrite());

  return obj;
}

/* static */
bool ObjectGroup::findAllocationSite(JSContext* cx, const ObjectGroup* group,
                                     JSScript** script, uint32_t* offset) {
  *script = nullptr;
  *offset = 0;

  ObjectGroupRealm& realm = ObjectGroupRealm::get(group);
  const ObjectGroupRealm::AllocationSiteTable* table =
      realm.allocationSiteTable;

  if (!table) {
    return false;
  }

  for (ObjectGroupRealm::AllocationSiteTable::Range r = table->all();
       !r.empty(); r.popFront()) {
    if (group == r.front().value()) {
      *script = r.front().key().script;
      *offset = r.front().key().offset;
      return true;
    }
  }

  return false;
}

/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm
/////////////////////////////////////////////////////////////////////

ObjectGroupRealm::~ObjectGroupRealm() {
  js_delete(defaultNewTable);
  js_delete(lazyTable);
  js_delete(arrayObjectTable);
  js_delete(plainObjectTable);
  js_delete(allocationSiteTable);
  stringSplitStringGroup = nullptr;
}

void ObjectGroupRealm::removeDefaultNewGroup(const JSClass* clasp,
                                             TaggedProto proto,
                                             JSObject* associated) {
  auto p = defaultNewTable->lookup(NewEntry::Lookup(clasp, proto, associated));
  MOZ_RELEASE_ASSERT(p);

  defaultNewTable->remove(p);
  defaultNewGroupCache.purge();
}

void ObjectGroupRealm::replaceDefaultNewGroup(const JSClass* clasp,
                                              TaggedProto proto,
                                              JSObject* associated,
                                              ObjectGroup* group) {
  NewEntry::Lookup lookup(clasp, proto, associated);

  auto p = defaultNewTable->lookup(lookup);
  MOZ_RELEASE_ASSERT(p);
  defaultNewTable->remove(p);
  defaultNewGroupCache.purge();
  {
    AutoEnterOOMUnsafeRegion oomUnsafe;
    if (!defaultNewTable->putNew(lookup, NewEntry(group, associated))) {
      oomUnsafe.crash("Inconsistent object table");
    }
  }
}

/* static */
ObjectGroup* ObjectGroupRealm::makeGroup(
    JSContext* cx, Realm* realm, const JSClass* clasp,
    Handle<TaggedProto> proto, ObjectGroupFlags initialFlags /* = 0 */) {
  MOZ_ASSERT_IF(proto.isObject(),
                cx->isInsideCurrentCompartment(proto.toObject()));

  ObjectGroup* group = Allocate<ObjectGroup>(cx);
  if (!group) {
    return nullptr;
  }
  new (group) ObjectGroup(clasp, proto, realm, initialFlags);

  return group;
}

/* static */
ObjectGroup* ObjectGroupRealm::getStringSplitStringGroup(JSContext* cx) {
  ObjectGroupRealm& groups = ObjectGroupRealm::getForNewObject(cx);

  ObjectGroup* group = groups.stringSplitStringGroup.get();
  if (group) {
    return group;
  }

  // The following code is a specialized version of the code
  // for ObjectGroup::allocationSiteGroup().

  JSObject* proto = GlobalObject::getOrCreateArrayPrototype(cx, cx->global());
  if (!proto) {
    return nullptr;
  }
  Rooted<TaggedProto> tagged(cx, TaggedProto(proto));

  group = makeGroup(cx, cx->realm(), &ArrayObject::class_, tagged);
  if (!group) {
    return nullptr;
  }

  groups.stringSplitStringGroup.set(group);
  return group;
}

void ObjectGroupRealm::addSizeOfExcludingThis(
    mozilla::MallocSizeOf mallocSizeOf, size_t* allocationSiteTables,
    size_t* arrayObjectGroupTables, size_t* plainObjectGroupTables,
    size_t* realmTables) {
  if (allocationSiteTable) {
    *allocationSiteTables +=
        allocationSiteTable->sizeOfIncludingThis(mallocSizeOf);
  }

  if (arrayObjectTable) {
    *arrayObjectGroupTables +=
        arrayObjectTable->shallowSizeOfIncludingThis(mallocSizeOf);
  }

  if (plainObjectTable) {
    *plainObjectGroupTables +=
        plainObjectTable->shallowSizeOfIncludingThis(mallocSizeOf);

    for (PlainObjectTable::Enum e(*plainObjectTable); !e.empty();
         e.popFront()) {
      const PlainObjectKey& key = e.front().key();
      const PlainObjectEntry& value = e.front().value();

      /* key.ids and values.types have the same length. */
      *plainObjectGroupTables +=
          mallocSizeOf(key.properties) + mallocSizeOf(value.types);
    }
  }

  if (defaultNewTable) {
    *realmTables += defaultNewTable->sizeOfIncludingThis(mallocSizeOf);
  }

  if (lazyTable) {
    *realmTables += lazyTable->sizeOfIncludingThis(mallocSizeOf);
  }
}

void ObjectGroupRealm::clearTables() {
  if (allocationSiteTable) {
    allocationSiteTable->clear();
  }
  if (arrayObjectTable) {
    arrayObjectTable->clear();
  }
  if (plainObjectTable) {
    for (PlainObjectTable::Enum e(*plainObjectTable); !e.empty();
         e.popFront()) {
      const PlainObjectKey& key = e.front().key();
      PlainObjectEntry& entry = e.front().value();
      js_free(key.properties);
      js_free(entry.types);
    }
    plainObjectTable->clear();
  }
  if (defaultNewTable) {
    defaultNewTable->clear();
  }
  if (lazyTable) {
    lazyTable->clear();
  }
  defaultNewGroupCache.purge();
}

/* static */
bool ObjectGroupRealm::PlainObjectTableSweepPolicy::needsSweep(
    PlainObjectKey* key, PlainObjectEntry* entry) {
  if (!(JS::GCPolicy<PlainObjectKey>::needsSweep(key) ||
        entry->needsSweep(key->nproperties))) {
    return false;
  }
  js_free(key->properties);
  js_free(entry->types);
  return true;
}

void ObjectGroupRealm::sweep() {
  /*
   * Iterate through the array/object group tables and remove all entries
   * referencing collected data. These tables only hold weak references.
   */

  if (arrayObjectTable) {
    arrayObjectTable->sweep();
  }
  if (plainObjectTable) {
    plainObjectTable->sweep();
  }
  if (stringSplitStringGroup) {
    if (JS::GCPolicy<WeakHeapPtrObjectGroup>::needsSweep(
            &stringSplitStringGroup)) {
      stringSplitStringGroup = nullptr;
    }
  }
}

void ObjectGroupRealm::fixupNewTableAfterMovingGC(NewTable* table) {
  /*
   * Each entry's hash depends on the object's prototype and we can't tell
   * whether that has been moved or not in sweepNewObjectGroupTable().
   */
  if (table) {
    for (NewTable::Enum e(*table); !e.empty(); e.popFront()) {
      NewEntry& entry = e.mutableFront();

      ObjectGroup* group = entry.group.unbarrieredGet();
      if (IsForwarded(group)) {
        group = Forwarded(group);
        entry.group.set(group);
      }
      TaggedProto proto = group->proto();
      if (proto.isObject() && IsForwarded(proto.toObject())) {
        proto = TaggedProto(Forwarded(proto.toObject()));
        // Update the group's proto here so that we are able to lookup
        // entries in this table before all object pointers are updated.
        group->proto() = proto;
      }
      if (entry.associated && IsForwarded(entry.associated)) {
        entry.associated = Forwarded(entry.associated);
      }
    }
  }
}

#ifdef JSGC_HASH_TABLE_CHECKS

void ObjectGroupRealm::checkNewTableAfterMovingGC(NewTable* table) {
  /*
   * Assert that nothing points into the nursery or needs to be relocated, and
   * that the hash table entries are discoverable.
   */
  if (!table) {
    return;
  }

  for (auto r = table->all(); !r.empty(); r.popFront()) {
    NewEntry entry = r.front();
    CheckGCThingAfterMovingGC(entry.group.unbarrieredGet());
    TaggedProto proto = entry.group.unbarrieredGet()->proto();
    if (proto.isObject()) {
      CheckGCThingAfterMovingGC(proto.toObject());
    }
    CheckGCThingAfterMovingGC(entry.associated);

    auto ptr = table->lookup(NewEntry::Lookup(entry));
    MOZ_RELEASE_ASSERT(ptr.found() && &*ptr == &r.front());
  }
}

#endif  // JSGC_HASH_TABLE_CHECKS