/*
 * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "config.h"
#include "Structure.h"

#include "CodeBlock.h"
#include "DumpContext.h"
#include "IndexingHeaderInlineMethods.h"
#include "JSObject.h"
#include "JSPropertyNameEnumerator.h"
#include "Lookup.h"
#include "PropertyNameArray.h"
#include "StructureChain.h"
#include "StructureRareDataInlines.h"
#include "WeakGCMapInlines.h"
#include <wtf/CommaPrinter.h>
#include <wtf/RefCountedLeakCounter.h>
#include <wtf/RefPtr.h>
#include <wtf/Threading.h>

#define DUMP_STRUCTURE_ID_STATISTICS 0

#ifndef NDEBUG
#define DO_PROPERTYMAP_CONSTENCY_CHECK 0
#else
#define DO_PROPERTYMAP_CONSTENCY_CHECK 0
#endif

using namespace std;
using namespace WTF;

#if DUMP_PROPERTYMAP_STATS

int numProbes;
int numCollisions;
int numRehashes;
int numRemoves;

#endif

namespace JSC {

#if DUMP_STRUCTURE_ID_STATISTICS
static HashSet<Structure*>& liveStructureSet = *(new HashSet<Structure*>);
#endif

class SingleSlotTransitionWeakOwner : public WeakHandleOwner {
    void finalize(Handle<Unknown>, void* context)
    {
        StructureTransitionTable* table = reinterpret_cast<StructureTransitionTable*>(context);
        ASSERT(table->isUsingSingleSlot());
        WeakSet::deallocate(table->weakImpl());
        table->m_data = StructureTransitionTable::UsingSingleSlotFlag;
    }
};

static SingleSlotTransitionWeakOwner& singleSlotTransitionWeakOwner()
{
    static SingleSlotTransitionWeakOwner owner;
    return owner;
}

inline Structure* StructureTransitionTable::singleTransition() const
{
    ASSERT(isUsingSingleSlot());
    if (WeakImpl* impl = this->weakImpl()) {
        if (impl->state() == WeakImpl::Live)
            return jsCast<Structure*>(impl->jsValue().asCell());
    }
    return 0;
}

inline void StructureTransitionTable::setSingleTransition(Structure* structure)
{
    ASSERT(isUsingSingleSlot());
    if (WeakImpl* impl = this->weakImpl())
        WeakSet::deallocate(impl);
    WeakImpl* impl = WeakSet::allocate(structure, &singleSlotTransitionWeakOwner(), this);
    m_data = reinterpret_cast<intptr_t>(impl) | UsingSingleSlotFlag;
}

bool StructureTransitionTable::contains(UniquedStringImpl* rep, unsigned attributes) const
{
    if (isUsingSingleSlot()) {
        Structure* transition = singleTransition();
        return transition && transition->m_nameInPrevious == rep && transition->attributesInPrevious() == attributes;
    }
    return map()->get(make_pair(rep, attributes));
}

Structure* StructureTransitionTable::get(UniquedStringImpl* rep, unsigned attributes) const
{
    if (isUsingSingleSlot()) {
        Structure* transition = singleTransition();
        return (transition && transition->m_nameInPrevious == rep && transition->attributesInPrevious() == attributes) ? transition : 0;
    }
    return map()->get(make_pair(rep, attributes));
}

void StructureTransitionTable::add(JSGlobalData& vm, Structure* structure)
{
    if (isUsingSingleSlot()) {
        Structure* existingTransition = singleTransition();

        // This handles the first transition being added.
        if (!existingTransition) {
            setSingleTransition(structure);
            return;
        }

        // This handles the second transition being added
        // (or the first transition being despecified!)
        setMap(new TransitionMap(vm));
        add(vm, existingTransition);
    }

    // Add the structure to the map.

    // Newer versions of the STL have an std::make_pair function that takes rvalue references.
    // When either of the parameters are bitfields, the C++ compiler will try to bind them as lvalues, which is invalid. To work around this, use unary "+" to make the parameter an rvalue.
    // See https://bugs.webkit.org/show_bug.cgi?id=59261 for more details
    map()->set(make_pair(structure->m_nameInPrevious.get(), +structure->attributesInPrevious()), structure);
}

void Structure::dumpStatistics()
{
#if DUMP_STRUCTURE_ID_STATISTICS
    unsigned numberLeaf = 0;
    unsigned numberUsingSingleSlot = 0;
    unsigned numberSingletons = 0;
    unsigned numberWithPropertyMaps = 0;
    unsigned totalPropertyMapsSize = 0;

    HashSet<Structure*>::const_iterator end = liveStructureSet.end();
    for (HashSet<Structure*>::const_iterator it = liveStructureSet.begin(); it != end; ++it) {
        Structure* structure = *it;

        switch (structure->m_transitionTable.size()) {
            case 0:
                ++numberLeaf;
                if (!structure->previousID())
                    ++numberSingletons;
                break;

            case 1:
                ++numberUsingSingleSlot;
                break;
        }

        if (structure->propertyTable()) {
            ++numberWithPropertyMaps;
            totalPropertyMapsSize += structure->propertyTable()->sizeInMemory();
        }
    }

    dataLog("Number of live Structures: %d\n", liveStructureSet.size());
    dataLog("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
    dataLog("Number of Structures that are leaf nodes: %d\n", numberLeaf);
    dataLog("Number of Structures that singletons: %d\n", numberSingletons);
    dataLog("Number of Structures with PropertyMaps: %d\n", numberWithPropertyMaps);

    dataLog("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
    dataLog("Size of sum of all property maps: %d\n", totalPropertyMapsSize);
    dataLog("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyMapsSize) / static_cast<double>(liveStructureSet.size()));
#else
    dataLog("Dumping Structure statistics is not enabled.\n");
#endif
}

Structure::Structure(JSGlobalData& vm, JSGlobalObject* globalObject, JSValue prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
: JSCell(vm, vm.structureStructure.get())
, m_globalObject(vm, this, globalObject, WriteBarrier<JSGlobalObject>::MayBeNull)
, m_prototype(vm, this, prototype)
, m_classInfo(classInfo)
, m_transitionWatchpointSet(IsWatched)
, m_offset(invalidOffset)
, m_typeInfo(typeInfo)
, m_indexingType(indexingType)
, m_inlineCapacity(inlineCapacity)
, m_bitField(0)
{
    setDictionaryKind(NoneDictionaryKind);
    setHasGetterSetterProperties(classInfo->hasStaticSetterOrReadonlyProperties());
    setHasReadOnlyOrGetterSetterPropertiesExcludingProto(classInfo->hasStaticSetterOrReadonlyProperties());
    setIsQuickPropertyAccessAllowedForEnumeration(true);

    ASSERT(inlineCapacity <= JSFinalObject::maxInlineCapacity());
    ASSERT(inlineCapacity < firstOutOfLineOffset);
    ASSERT(!hasRareData());
    ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
	ASSERT(hasGetterSetterProperties() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
	ASSERT(!this->typeInfo().overridesGetCallData() || m_classInfo->methodTable.getCallData != &JSCell::getCallData);
}

const ClassInfo Structure::s_info = { "Structure", 0, 0, CREATE_METHOD_TABLE(Structure) };

Structure::Structure(JSGlobalData& vm)
: JSCell(CreatingEarlyCell)
, m_prototype(vm, this, jsNull())
, m_classInfo(info())
, m_transitionWatchpointSet(IsWatched)
, m_offset(invalidOffset)
, m_typeInfo(CellType)
, m_indexingType(0)
, m_inlineCapacity(0)
, m_bitField(0)
{
    setDictionaryKind(NoneDictionaryKind);
    setHasGetterSetterProperties(m_classInfo->hasStaticSetterOrReadonlyProperties());
    setHasReadOnlyOrGetterSetterPropertiesExcludingProto(m_classInfo->hasStaticSetterOrReadonlyProperties());
    setIsQuickPropertyAccessAllowedForEnumeration(true);

	ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
	ASSERT(hasGetterSetterProperties() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
	ASSERT(!this->typeInfo().overridesGetCallData() || m_classInfo->methodTable.getCallData != &JSCell::getCallData);
}

Structure::Structure(JSGlobalData& globalData, Structure* previous, DeferredStructureTransitionWatchpointFire* deferred)
: JSCell(globalData, globalData.structureStructure.get())
, m_prototype(globalData, this, previous->storedPrototype())
, m_classInfo(previous->m_classInfo)
, m_transitionWatchpointSet(IsWatched)
, m_offset(invalidOffset)
, m_typeInfo(previous->typeInfo())
, m_indexingType(previous->indexingTypeIncludingHistory())
, m_inlineCapacity(previous->m_inlineCapacity)
, m_bitField(0)
{
    setDictionaryKind(previous->dictionaryKind());
    setHasBeenFlattenedBefore(previous->hasBeenFlattenedBefore());
    setHasGetterSetterProperties(previous->hasGetterSetterProperties());
    setHasCustomGetterSetterProperties(previous->hasCustomGetterSetterProperties());
    setHasReadOnlyOrGetterSetterPropertiesExcludingProto(previous->hasReadOnlyOrGetterSetterPropertiesExcludingProto());
    setIsQuickPropertyAccessAllowedForEnumeration(previous->isQuickPropertyAccessAllowedForEnumeration());
	setDidPreventExtensions(previous->didPreventExtensions());
    setDidTransition(true);
    setStaticPropertiesReified(previous->staticPropertiesReified());

    setPreviousID(globalData, this, previous);

    m_cachedPrototypeChain.setMayBeNull(globalData, this, previous->m_cachedPrototypeChain.get());
    previous->m_cachedPrototypeChain.clear();

    previous->didTransitionFromThisStructure(deferred);

    // Copy this bit now, in case previous was being watched.
    setTransitionWatchpointIsLikelyToBeFired(previous->transitionWatchpointIsLikelyToBeFired());

    if (previous->m_globalObject)
        m_globalObject.set(globalData, this, previous->m_globalObject.get());
    ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
	ASSERT(hasGetterSetterProperties() || !m_classInfo->hasStaticSetterOrReadonlyProperties());
	ASSERT(!this->typeInfo().overridesGetCallData() || m_classInfo->methodTable.getCallData != &JSCell::getCallData);
}

void Structure::destroy(JSCell* cell)
{
    static_cast<Structure*>(cell)->Structure::~Structure();
}

void Structure::findStructuresAndMapForMaterialization(Vector<Structure*, 8>& structures, PropertyTable*& table)
{
    ASSERT(structures.isEmpty());
    table = 0;

    for (Structure* structure = this; structure; structure = structure->previousID()) {
        if (structure->propertyTable()) {
            table = structure->propertyTable().get();
            return;
        }

        structures.append(structure);
    }
}

void Structure::materializePropertyMap(JSGlobalData& globalData)
{
    ASSERT(structure()->classInfo() == info());
    ASSERT(!propertyTable());

    Vector<Structure*, 8> structures;
    PropertyTable* table;

    findStructuresAndMapForMaterialization(structures, table);

    if (!table)
        createPropertyMap(globalData, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
    else
        propertyTable().set(globalData, this, table->copy(globalData, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity)));

    for (size_t i = structures.size(); i--;) {
    	Structure* structure = structures[i];
        if (!structure->m_nameInPrevious)
            continue;
        PropertyMapEntry entry(structure->m_nameInPrevious.get(), structure->m_offset, structure->attributesInPrevious());
        propertyTable()->add(entry, m_offset, PropertyTable::PropertyOffsetMustNotChange);
	}

	checkOffsetConsistency();
}
 
Structure* Structure::addPropertyTransitionToExistingStructure(Structure* structure, UniquedStringImpl* uid, unsigned attributes, PropertyOffset& offset)
{
    ASSERT(!structure->isDictionary());
    ASSERT(structure->isObject());

    if (Structure* existingTransition = structure->m_transitionTable.get(uid, attributes)) {
        validateOffset(existingTransition->m_offset, existingTransition->inlineCapacity());
        offset = existingTransition->m_offset;
        return existingTransition;
    }

    return 0;
}

bool Structure::anyObjectInChainMayInterceptIndexedAccesses() const
{
    for (const Structure* current = this; ;) {
        if (current->mayInterceptIndexedAccesses())
            return true;

        JSValue prototype = current->storedPrototype();
        if (prototype.isNull())
            return false;

        current = asObject(prototype)->structure();
    }
}

bool Structure::holesMustForwardToPrototype(VM& vm) const
{
    if (this->mayInterceptIndexedAccesses())
        return true;

    JSValue prototype = this->storedPrototype();
    if (!prototype.isObject())
        return false;
    JSObject* object = asObject(prototype);

    while (true) {
        Structure& structure = *object->structure(vm);
        if (hasIndexedProperties(object->structure()->indexingType()) || structure.mayInterceptIndexedAccesses())
            return true;
        prototype = structure.storedPrototype();
        if (!prototype.isObject())
            return false;
        object = asObject(prototype);
    }

    RELEASE_ASSERT_NOT_REACHED();
    return false;
}

bool Structure::needsSlowPutIndexing() const
{
    return anyObjectInChainMayInterceptIndexedAccesses()
        || !globalObject()
        || globalObject()->isHavingABadTime();
}

NonPropertyTransition Structure::suggestedArrayStorageTransition() const
{
    if (needsSlowPutIndexing())
        return AllocateSlowPutArrayStorage;

    return AllocateArrayStorage;
}

Structure* Structure::addPropertyTransition(JSGlobalData& vm, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset, PutPropertySlot::Context context, DeferredStructureTransitionWatchpointFire* deferred)
{
    Structure* newStructure = addPropertyTransitionToExistingStructure(
        structure, propertyName.uid(), attributes, offset);
    if (newStructure)
        return newStructure;

    return addNewPropertyTransition(
        vm, structure, propertyName, attributes, offset, PutPropertySlot::UnknownContext);
}

Structure* Structure::addNewPropertyTransition(JSGlobalData& globalData, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset, PutPropertySlot::Context context, DeferredStructureTransitionWatchpointFire* deferred)
{
    ASSERT(!structure->isDictionary());
    ASSERT(structure->isObject());
    ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, offset));
    
    int maxTransitionLength;
	if (context == PutPropertySlot::PutById)
		maxTransitionLength = s_maxTransitionLengthForNonEvalPutById;
	else
		maxTransitionLength = s_maxTransitionLength;
	if (structure->transitionCount() > maxTransitionLength) {
        Structure* transition = toCacheableDictionaryTransition(globalData, structure, deferred);
        ASSERT(structure != transition);
        offset = transition->add(globalData, propertyName, attributes);
        return transition;
    }
    
    Structure* transition = create(globalData, structure, deferred);

    transition->m_nameInPrevious = propertyName.uid();
    transition->setAttributesInPrevious(attributes);
    transition->propertyTable().set(globalData, transition, structure->takePropertyTableOrCloneIfPinned(globalData));
    transition->m_offset = structure->m_offset;

    offset = transition->add(globalData, propertyName, attributes);

    checkOffset(transition->m_offset, transition->inlineCapacity());
    structure->m_transitionTable.add(globalData, transition);
    transition->checkOffsetConsistency();
    structure->checkOffsetConsistency();
    return transition;
}

Structure* Structure::removePropertyTransition(JSGlobalData& globalData, Structure* structure, PropertyName propertyName, PropertyOffset& offset)
{
    ASSERT(!structure->isUncacheableDictionary());

    Structure* transition = toUncacheableDictionaryTransition(globalData, structure);

    offset = transition->remove(propertyName);

    transition->checkOffsetConsistency();
    return transition;
}

Structure* Structure::changePrototypeTransition(JSGlobalData& globalData, Structure* structure, JSValue prototype)
{
    Structure* transition = create(globalData, structure);

    transition->m_prototype.set(globalData, transition, prototype);

    DeferGC deferGC(globalData.heap);
    structure->materializePropertyMapIfNecessary(globalData, deferGC);
    transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData));
	transition->m_offset = structure->m_offset;
    transition->pin();

    transition->checkOffsetConsistency();
    return transition;
}

Structure* Structure::attributeChangeTransition(JSGlobalData& globalData, Structure* structure, PropertyName propertyName, unsigned attributes)
{
    DeferGC deferGC(globalData.heap);
    if (!structure->isUncacheableDictionary()) {
        Structure* transition = create(globalData, structure);

        structure->materializePropertyMapIfNecessary(globalData, deferGC);
        transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData));
	    transition->m_offset = structure->m_offset;
        transition->pin();
        
        structure = transition;
    }

    ASSERT(structure->propertyTable());
    PropertyMapEntry* entry = structure->propertyTable()->get(propertyName.uid());
    ASSERT(entry);
    entry->attributes = attributes;

    structure->checkOffsetConsistency();
    return structure;
}

Structure* Structure::toDictionaryTransition(JSGlobalData& globalData, Structure* structure, DictionaryKind kind, DeferredStructureTransitionWatchpointFire* deferred)
{
    ASSERT(!structure->isUncacheableDictionary());
    
    Structure* transition = create(globalData, structure, deferred);

    DeferGC deferGC(globalData.heap);
    structure->materializePropertyMapIfNecessary(globalData, deferGC);
    transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData));
	transition->m_offset = structure->m_offset;
    transition->setDictionaryKind(kind);
    transition->pin();
    transition->setTransitionWatchpointIsLikelyToBeFired(true);

    transition->checkOffsetConsistency();
    return transition;
}

Structure* Structure::toCacheableDictionaryTransition(JSGlobalData& globalData, Structure* structure, DeferredStructureTransitionWatchpointFire* deferred)
{
    return toDictionaryTransition(globalData, structure, CachedDictionaryKind, deferred);
}

Structure* Structure::toUncacheableDictionaryTransition(JSGlobalData& globalData, Structure* structure)
{
    return toDictionaryTransition(globalData, structure, UncachedDictionaryKind);
}

// In future we may want to cache this transition.
Structure* Structure::sealTransition(JSGlobalData& globalData, Structure* structure)
{
    Structure* transition = preventExtensionsTransition(globalData, structure);

    if (transition->propertyTable()) {
        PropertyTable::iterator end = transition->propertyTable()->end();
        for (PropertyTable::iterator iter = transition->propertyTable()->begin(); iter != end; ++iter)
            iter->attributes |= DontDelete;
    }

    transition->checkOffsetConsistency();
    return transition;
}

// In future we may want to cache this transition.
Structure* Structure::freezeTransition(JSGlobalData& vm, Structure* structure)
{
    Structure* transition = preventExtensionsTransition(vm, structure);

    if (transition->propertyTable()) {
        PropertyTable::iterator iter = transition->propertyTable()->begin();
        PropertyTable::iterator end = transition->propertyTable()->end();
        if (iter != end)
            transition->setHasReadOnlyOrGetterSetterPropertiesExcludingProto(true);
        for (; iter != end; ++iter)
            iter->attributes |= iter->attributes & Accessor ? DontDelete : (DontDelete | ReadOnly);
    }

    ASSERT(transition->hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !transition->classInfo()->hasStaticSetterOrReadonlyProperties());
    ASSERT(transition->hasGetterSetterProperties() || !transition->classInfo()->hasStaticSetterOrReadonlyProperties());
    transition->checkOffsetConsistency();
    return transition;
}

// In future we may want to cache this transition.
Structure* Structure::preventExtensionsTransition(JSGlobalData& globalData, Structure* structure)
{
    Structure* transition = create(globalData, structure);

    // Don't set m_offset, as one can not transition to this.

    DeferGC deferGC(globalData.heap);
    structure->materializePropertyMapIfNecessary(globalData, deferGC);
    transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData));
	transition->m_offset = structure->m_offset;
    transition->setDidPreventExtensions(true);
    transition->pin();

    transition->checkOffsetConsistency();
    return transition;
}

PropertyTable* Structure::takePropertyTableOrCloneIfPinned(JSGlobalData& globalData)
{
    DeferGC deferGC(globalData.heap);
    materializePropertyMapIfNecessaryForPinning(globalData, deferGC);
    if (isPinnedPropertyTable())
        return propertyTable()->copy(globalData, propertyTable()->size() + 1);
    PropertyTable* takenPropertyTable = propertyTable().get();
    propertyTable().clear();
    return takenPropertyTable;
}

Structure* Structure::nonPropertyTransition(JSGlobalData& globalData, Structure* structure, NonPropertyTransition transitionKind)
{
    unsigned attributes = toAttributes(transitionKind);
    IndexingType indexingType = newIndexingType(structure->indexingTypeIncludingHistory(), transitionKind);

    if (JSGlobalObject* globalObject = structure->m_globalObject.get()) {
		if (globalObject->isOriginalArrayStructure(structure)) {
			Structure* result = globalObject->originalArrayStructureForIndexingType(indexingType);
			if (result->indexingTypeIncludingHistory() == indexingType) {
				structure->didTransitionFromThisStructure();
				return result;
			}
		}
	}

    Structure* existingTransition;
    if (!structure->isDictionary() && (existingTransition = structure->m_transitionTable.get(0, attributes))) {
    	ASSERT(existingTransition->attributesInPrevious() == attributes);
        ASSERT(existingTransition->indexingTypeIncludingHistory() == indexingType);
        return existingTransition;
    }

    Structure* transition = create(globalData, structure);
    transition->setAttributesInPrevious(attributes);
    transition->m_indexingType = indexingType;
    transition->propertyTable().set(globalData, transition, structure->takePropertyTableOrCloneIfPinned(globalData));
    transition->m_offset = structure->m_offset;
    checkOffset(transition->m_offset, transition->inlineCapacity());

    if (structure->isDictionary())
        transition->pin();
    else {
    	structure->m_transitionTable.add(globalData, transition);
    }
    transition->checkOffsetConsistency();
    return transition;
}

// In future we may want to cache this property.
bool Structure::isSealed(JSGlobalData& globalData)
{
    if (isStructureExtensible())
        return false;

    DeferGC deferGC(globalData.heap);
    materializePropertyMapIfNecessary(globalData, deferGC);
    if (!propertyTable())
        return true;

    PropertyTable::iterator end = propertyTable()->end();
    for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
        if ((iter->attributes & DontDelete) != DontDelete)
            return false;
    }
    return true;
}

// In future we may want to cache this property.
bool Structure::isFrozen(JSGlobalData& globalData)
{
    if (isStructureExtensible())
        return false;

    DeferGC deferGC(globalData.heap);
    materializePropertyMapIfNecessary(globalData, deferGC);
    if (!propertyTable())
        return true;

    PropertyTable::iterator end = propertyTable()->end();
    for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
        if (!(iter->attributes & DontDelete))
            return false;
        if (!(iter->attributes & (ReadOnly | Accessor)))
            return false;
    }
    return true;
}

Structure* Structure::flattenDictionaryStructure(JSGlobalData& vm, JSObject* object)
{
    checkOffsetConsistency();
    ASSERT(isDictionary());

    size_t beforeOutOfLineCapacity = this->outOfLineCapacity();
    if (isUncacheableDictionary()) {
        ASSERT(propertyTable());

        size_t propertyCount = propertyTable()->size();

        // Holds our values compacted by insertion order.
        Vector<JSValue> values(propertyCount);

        // Copies out our values from their hashed locations, compacting property table offsets as we go.
        unsigned i = 0;
        PropertyTable::iterator end = propertyTable()->end();
        m_offset = invalidOffset;
        for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter, ++i) {
            values[i] = object->getDirect(iter->offset);
            m_offset = iter->offset = offsetForPropertyNumber(i, m_inlineCapacity);
        }

        // Copies in our values to their compacted locations.
        for (unsigned i = 0; i < propertyCount; i++)
            object->putDirect(vm, offsetForPropertyNumber(i, m_inlineCapacity), values[i]);

        propertyTable()->clearDeletedOffsets();

        // We need to zero our unused property space; otherwise the GC might see a
        // stale pointer when we add properties in the future.
        memset(
            object->inlineStorageUnsafe() + inlineSize(),
            0,
            (inlineCapacity() - inlineSize()) * sizeof(EncodedJSValue));

        Butterfly* butterfly = object->butterfly();
        memset(
            butterfly->base(butterfly->indexingHeader()->preCapacity(this), beforeOutOfLineCapacity),
            0,
            (beforeOutOfLineCapacity - outOfLineSize()) * sizeof(EncodedJSValue));
        checkOffsetConsistency();
    }

    setDictionaryKind(NoneDictionaryKind);
    setHasBeenFlattenedBefore(true);

    size_t afterOutOfLineCapacity = this->outOfLineCapacity();

    if (beforeOutOfLineCapacity != afterOutOfLineCapacity) {
        ASSERT(beforeOutOfLineCapacity > afterOutOfLineCapacity);
        // If the object had a Butterfly but after flattening/compacting we no longer have need of it,
        // we need to zero it out because the collector depends on the Structure to know the size for copying.
        if (object->butterfly() && !afterOutOfLineCapacity && !this->hasIndexingHeader(object))
            object->setStructureAndButterfly(vm, this, 0);
        // If the object was down-sized to the point where the base of the Butterfly is no longer within the
        // first CopiedBlock::blockSize bytes, we'll get the wrong answer if we try to mask the base back to
        // the CopiedBlock header. To prevent this case we need to memmove the Butterfly down.
        else if (object->butterfly())
            object->shiftButterflyAfterFlattening(vm, beforeOutOfLineCapacity, afterOutOfLineCapacity);
    }

    // We need to do a writebarrier here because the GC thread might be scanning the butterfly while
    // we are shuffling properties around. See: https://bugs.webkit.org/show_bug.cgi?id=166989
    vm.heap.writeBarrier(object);

    return this;
}

PropertyOffset Structure::addPropertyWithoutTransition(JSGlobalData& globalData, PropertyName propertyName, unsigned attributes)
{
    DeferGC deferGC(globalData.heap);
    materializePropertyMapIfNecessaryForPinning(globalData, deferGC);
    
    pin();

    return add(globalData, propertyName, attributes);
}

PropertyOffset Structure::removePropertyWithoutTransition(JSGlobalData& globalData, PropertyName propertyName)
{
    ASSERT(isUncacheableDictionary());

    DeferGC deferGC(globalData.heap);
    materializePropertyMapIfNecessaryForPinning(globalData, deferGC);

    pin();
    return remove(propertyName);
}

void Structure::pin()
{
    ASSERT(propertyTable());
    setIsPinnedPropertyTable(true);
    clearPreviousID();
    m_nameInPrevious.clear();
}

void Structure::allocateRareData(JSGlobalData& globalData)
{
    ASSERT(!hasRareData());
    StructureRareData* rareData = StructureRareData::create(globalData, previous());
    m_previousOrRareData.set(globalData, this, rareData);
    setHasRareData(true);
    ASSERT(hasRareData());
}

WatchpointSet* Structure::ensurePropertyReplacementWatchpointSet(VM& vm, PropertyOffset offset)
{
    ASSERT(!isUncacheableDictionary());

    // In some places it's convenient to call this with an invalid offset. So, we do the check here.
    if (!isValidOffset(offset))
        return 0;

    if (!hasRareData())
        allocateRareData(vm);
    //ConcurrentJITLocker locker(m_lock);
    StructureRareData* rareData = this->rareData();
    if (!rareData->m_replacementWatchpointSets) {
        rareData->m_replacementWatchpointSets =
            adoptPtr(new StructureRareData::PropertyWatchpointMap());
        WTF::storeStoreFence();
    }
    StructureRareData::PropertyWatchpointMap::AddResult result = rareData->m_replacementWatchpointSets->add(offset, nullptr);
    if (result.isNewEntry)
        result.iterator->second = adoptRef(new WatchpointSet(IsWatched));
    return result.iterator->second.get();
}

void Structure::startWatchingPropertyForReplacements(VM& vm, PropertyName propertyName)
{
    ASSERT(!isUncacheableDictionary());

    startWatchingPropertyForReplacements(vm, get(vm, propertyName));
}

void Structure::didCachePropertyReplacement(VM& vm, PropertyOffset offset)
{
    ensurePropertyReplacementWatchpointSet(vm, offset)->fireAll(vm, "Did cache property replacement");
}

void Structure::startWatchingInternalProperties(VM& vm)
{
    if (!isUncacheableDictionary()) {
        startWatchingPropertyForReplacements(vm, vm.propertyNames->toStringTagSymbol);
        startWatchingPropertyForReplacements(vm, vm.propertyNames->toString);
        startWatchingPropertyForReplacements(vm, vm.propertyNames->valueOf);
    }
    setDidWatchInternalProperties(true);
}

#if DUMP_PROPERTYMAP_STATS

struct PropertyMapStatisticsExitLogger {
    ~PropertyMapStatisticsExitLogger();
};

static PropertyMapStatisticsExitLogger logger;

PropertyMapStatisticsExitLogger::~PropertyMapStatisticsExitLogger()
{
    dataLog("\nJSC::PropertyMap statistics\n\n");
    dataLog("%d probes\n", numProbes);
    dataLog("%d collisions (%.1f%%)\n", numCollisions, 100.0 * numCollisions / numProbes);
    dataLog("%d rehashes\n", numRehashes);
    dataLog("%d removes\n", numRemoves);
}

#endif

#if !DO_PROPERTYMAP_CONSTENCY_CHECK

inline void Structure::checkConsistency()
{
    checkOffsetConsistency();
}

#endif

PropertyTable* Structure::copyPropertyTable(JSGlobalData& globalData)
{
    if (!propertyTable())
        return 0;
    return PropertyTable::clone(globalData, *propertyTable().get());
}

PropertyTable* Structure::copyPropertyTableForPinning(JSGlobalData& globalData)
{
    if (propertyTable())
        return PropertyTable::clone(globalData, *propertyTable().get());
    return PropertyTable::create(globalData, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
}

PropertyOffset Structure::getWithoutMaterializing(VM&, UniquedStringImpl* uid, unsigned& attributes)
{
    Vector<Structure*, 8> structures;
    PropertyTable* table;

    findStructuresAndMapForMaterialization(structures, table);

    if (table) {
        PropertyMapEntry* entry = table->find(uid).first;
        if (entry) {
            attributes = entry->attributes;
            return entry->offset;
        }
    }

    for (unsigned i = structures.size(); i--;) {
        Structure* structure = structures[i];
        if (structure->m_nameInPrevious.get() != uid)
            continue;

        attributes = structure->attributesInPrevious();
        return structure->m_offset;
    }

    return invalidOffset;
}

PropertyOffset Structure::add(JSGlobalData& globalData, PropertyName propertyName, unsigned attributes)
{
    //GCSafeConcurrentJITLocker locker(m_lock, vm.heap);

    setDidWatchInternalProperties(false);

    ASSERT(!JSC::isValidOffset(get(globalData, propertyName)));

    checkConsistency();
    if (attributes & DontEnum || propertyName.isSymbol())
        setIsQuickPropertyAccessAllowedForEnumeration(false);

    auto* rep = propertyName.uid();

    if (!propertyTable())
        createPropertyMap(globalData);

    PropertyOffset newOffset = propertyTable()->nextOffset(m_inlineCapacity);

    propertyTable()->add(PropertyMapEntry(rep, newOffset, attributes), m_offset, PropertyTable::PropertyOffsetMayChange);

    checkConsistency();
    return newOffset;
}

PropertyOffset Structure::remove(PropertyName propertyName)
{
    checkConsistency();

    auto* rep = propertyName.uid();

    if (!propertyTable())
        return invalidOffset;

    PropertyTable::find_iterator position = propertyTable()->find(rep);
    if (!position.first)
        return invalidOffset;

    PropertyOffset offset = position.first->offset;

    propertyTable()->remove(position);
    propertyTable()->addDeletedOffset(offset);

    checkConsistency();
    return offset;
}

void Structure::createPropertyMap(JSGlobalData& globalData, unsigned capacity)
{
    ASSERT(!propertyTable());

    checkConsistency();
    propertyTable().set(globalData, this, PropertyTable::create(globalData, capacity));
}

void Structure::getPropertyNamesFromStructure(JSGlobalData& globalData, PropertyNameArray& propertyNames, EnumerationMode mode)
{
    DeferGC deferGC(globalData.heap);
    materializePropertyMapIfNecessary(globalData, deferGC);
    if (!propertyTable())
        return;

    bool knownUnique = propertyNames.canAddKnownUniqueForStructure();

    PropertyTable::iterator end = propertyTable()->end();
    for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
        ASSERT(!isQuickPropertyAccessAllowedForEnumeration() || !(iter->attributes & DontEnum));
        ASSERT(!isQuickPropertyAccessAllowedForEnumeration() || !iter->key->isSymbol());
        if (!(iter->attributes & DontEnum) || mode.includeDontEnumProperties()) {
			if (iter->key->isSymbol() && !propertyNames.includeSymbolProperties())
				continue;
            if (knownUnique)
                propertyNames.addUnchecked(iter->key);
            else
                propertyNames.add(iter->key);
        }
    }
}

void StructureFireDetail::dump(PrintStream& out) const
{
    //out.print("Structure transition from ", m_structure);
}

DeferredStructureTransitionWatchpointFire::DeferredStructureTransitionWatchpointFire()
    : m_structure(0)
{
}

DeferredStructureTransitionWatchpointFire::~DeferredStructureTransitionWatchpointFire()
{
    if (m_structure)
        m_structure->transitionWatchpointSet().fireAll(*m_structure->vm(), StructureFireDetail(m_structure));
}

void DeferredStructureTransitionWatchpointFire::add(const Structure* structure)
{
    RELEASE_ASSERT(!m_structure);
    RELEASE_ASSERT(structure);
    m_structure = structure;
}

void Structure::didTransitionFromThisStructure(DeferredStructureTransitionWatchpointFire* deferred) const
{
	// If the structure is being watched, and this is the kind of structure that the DFG would
	// like to watch, then make sure to note for all future versions of this structure that it's
	// unwise to watch it.
	if (m_transitionWatchpointSet.isBeingWatched())
		const_cast<Structure*>(this)->setTransitionWatchpointIsLikelyToBeFired(true);

    if (deferred)
        deferred->add(this);
    else
    	m_transitionWatchpointSet.fireAll(*vm(), StructureFireDetail(this));
}

JSValue Structure::prototypeForLookup(CodeBlock* codeBlock) const
{
    return prototypeForLookup(codeBlock->globalObject());
}

void Structure::visitChildren(JSCell* cell, SlotVisitor& visitor)
{
    Structure* thisObject = jsCast<Structure*>(cell);
    ASSERT_GC_OBJECT_INHERITS(thisObject, info());

    Base::visitChildren(thisObject, visitor);
    visitor.append(&thisObject->m_globalObject);
    if (!thisObject->isObject())
        thisObject->m_cachedPrototypeChain.clear();
    else {
        visitor.append(&thisObject->m_prototype);
        visitor.append(&thisObject->m_cachedPrototypeChain);
    }
    visitor.append(&thisObject->m_previousOrRareData);

    if (thisObject->isPinnedPropertyTable()) {
        ASSERT(thisObject->m_propertyTableUnsafe);
        visitor.append(&thisObject->m_propertyTableUnsafe);
    } else if (thisObject->m_propertyTableUnsafe)
        thisObject->m_propertyTableUnsafe.clear();
}

bool Structure::isCheapDuringGC()
{
    // FIXME: We could make this even safer by returning false if this structure's property table
    // has any large property names.
    // https://bugs.webkit.org/show_bug.cgi?id=157334

    return (!m_globalObject || Heap::isMarked(m_globalObject.get()))
        && (!storedPrototypeObject() || Heap::isMarked(storedPrototypeObject()));
}

bool Structure::markIfCheap(SlotVisitor& visitor)
{
    if (!isCheapDuringGC())
        return Heap::isMarked(this);

    visitor.appendUnbarrieredReadOnlyPointer(this);
    return true;
}

bool Structure::prototypeChainMayInterceptStoreTo(JSGlobalData& globalData, UniquedStringImpl* uid)
{
    // Note, this method is called from two kinds of places: (1) assertions and (2)
    // the compilation thread. As such, it does things somewhat carefully to ensure
    // thread safety. Currently that only affects the way we do Structure::get().
    if (parseIndex(*uid))
        return anyObjectInChainMayInterceptIndexedAccesses();

    for (Structure* current = this; ;) {
        JSValue prototype = current->storedPrototype();
        if (prototype.isNull())
            return false;

        current = prototype.asCell()->structure();

        unsigned attributes;
        PropertyOffset offset = current->getConcurrently(globalData, uid, attributes);
        if (!JSC::isValidOffset(offset))
            continue;

        if (attributes & (ReadOnly | Accessor))
            return true;

        return false;
    }

    ASSERT_NOT_REACHED();
    return false;
}

bool Structure::prototypeChainMayInterceptStoreTo(VM& vm, PropertyName propertyName)
{
    return prototypeChainMayInterceptStoreTo(vm, propertyName.uid());
}

#if 0
PassRefPtr<StructureShape> Structure::toStructureShape()
{
    Vector<Structure*, 8> structures;
    Structure* structure;
    PropertyTable* table;
    RefPtr<StructureShape> shape = StructureShape::create();

    findStructuresAndMapForMaterialization(structures, structure, table);

    if (table) {
        PropertyTable::iterator iter = table->begin();
        PropertyTable::iterator end = table->end();

        for (; iter != end; ++iter)
            shape->addProperty(*iter->key);

        structure->m_lock.unlock();
    }

    for (unsigned i = structures.size(); i--;) {
        Structure* structure = structures[i];
        if (!structure->m_nameInPrevious)
            continue;

        shape->addProperty(*structure->m_nameInPrevious);
    }

    shape->markAsFinal();
    return shape.release();
}
#endif

void Structure::dump(PrintStream& out) const
{
    out.print(RawPointer(this), ":[", classInfo()->className, ", {");

    Vector<Structure*, 8> structures;
    //Structure* structure;
    PropertyTable* table;

    const_cast<Structure*>(this)->findStructuresAndMapForMaterialization(structures, table);

    CommaPrinter comma;

    if (table) {
        PropertyTable::iterator iter = table->begin();
        PropertyTable::iterator end = table->end();
        for (; iter != end; ++iter)
            out.print(comma, iter->key, ":", static_cast<int>(iter->offset));

        //structure->m_lock.unlock();
    }

    for (unsigned i = structures.size(); i--;) {
        Structure* structure = structures[i];
        if (!structure->m_nameInPrevious)
            continue;
        out.print(comma, structure->m_nameInPrevious.get(), ":", static_cast<int>(structure->m_offset));
    }

    out.print("}, ", indexingTypeToString(indexingType()));

    if (m_prototype.get().isCell())
        out.print(", Proto:", RawPointer(m_prototype.get().asCell()));

    switch (dictionaryKind()) {
    case NoneDictionaryKind:
        break;
    case CachedDictionaryKind:
        out.print(", Dictionary");
        break;
    case UncachedDictionaryKind:
        out.print(", UncacheableDictionary");
        break;
    }

    out.print("]");
}

void Structure::dumpInContext(PrintStream& out, DumpContext* context) const
{
    if (context)
        context->structures.dumpBrief(this, out);
    else
        dump(out);
}

void Structure::dumpBrief(PrintStream& out, const CString& string) const
{
    out.print("%", string, ":", classInfo()->className);
}

void Structure::dumpContextHeader(PrintStream& out)
{
    out.print("Structures:");
}

#if DO_PROPERTYMAP_CONSTENCY_CHECK

void PropertyTable::checkConsistency()
{
    checkOffsetConsistency();
    ASSERT(m_indexSize >= PropertyTable::MinimumTableSize);
    ASSERT(m_indexMask);
    ASSERT(m_indexSize == m_indexMask + 1);
    ASSERT(!(m_indexSize & m_indexMask));

    ASSERT(m_keyCount <= m_indexSize / 2);
    ASSERT(m_keyCount + m_deletedCount <= m_indexSize / 2);
    ASSERT(m_deletedCount <= m_indexSize / 4);

    unsigned indexCount = 0;
    unsigned deletedIndexCount = 0;
    for (unsigned a = 0; a != m_indexSize; ++a) {
        unsigned entryIndex = m_index[a];
        if (entryIndex == PropertyTable::EmptyEntryIndex)
            continue;
        if (entryIndex == deletedEntryIndex()) {
            ++deletedIndexCount;
            continue;
        }
        ASSERT(entryIndex < deletedEntryIndex());
        ASSERT(entryIndex - 1 <= usedCount());
        ++indexCount;

        for (unsigned b = a + 1; b != m_indexSize; ++b)
            ASSERT(m_index[b] != entryIndex);
    }
    ASSERT(indexCount == m_keyCount);
    ASSERT(deletedIndexCount == m_deletedCount);

    ASSERT(!table()[deletedEntryIndex() - 1].key);

    unsigned nonEmptyEntryCount = 0;
    for (unsigned c = 0; c < usedCount(); ++c) {
        auto* rep = table()[c].key;
        if (rep == PROPERTY_MAP_DELETED_ENTRY_KEY)
            continue;
        ++nonEmptyEntryCount;
        unsigned i = IdentifierRepHash::hash(rep);
        unsigned k = 0;
        unsigned entryIndex;
        while (1) {
            entryIndex = m_index[i & m_indexMask];
            ASSERT(entryIndex != PropertyTable::EmptyEntryIndex);
            if (rep == table()[entryIndex - 1].key)
                break;
            if (k == 0)
                k = 1 | doubleHash(IdentifierRepHash::hash(rep));
            i += k;
        }
        ASSERT(entryIndex == c + 1);
    }

    ASSERT(nonEmptyEntryCount == m_keyCount);
}

void Structure::checkConsistency()
{
    if (!propertyTable())
        return;

    if (isQuickPropertyAccessAllowedForEnumeration()) {
        PropertyTable::iterator end = propertyTable()->end();
        for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
            ASSERT(!(iter->attributes & DontEnum));
            ASSERT(!iter->key->isSymbol());
        }
    }

    propertyTable()->checkConsistency();
}

#endif // DO_PROPERTYMAP_CONSTENCY_CHECK

bool ClassInfo::hasStaticSetterOrReadonlyProperties() const
{
    for (const ClassInfo* ci = this; ci; ci = ci->parentClass) {
        if (const HashTable* table = ci->staticPropHashTable) {
            if (table->hasSetterOrReadonlyProperties)
                return true;
        }
    }
    return false;
}

void Structure::setCachedPropertyNameEnumerator(VM& vm, JSPropertyNameEnumerator* enumerator)
{
    ASSERT(!isDictionary());
    if (!hasRareData())
        allocateRareData(vm);
    rareData()->setCachedPropertyNameEnumerator(vm, enumerator);
}

JSPropertyNameEnumerator* Structure::cachedPropertyNameEnumerator() const
{
    if (!hasRareData())
        return 0;
    return rareData()->cachedPropertyNameEnumerator();
}

static bool canCache(const Structure* structure)
{
    if (structure->isDictionary())
        return false;
    if (hasIndexedProperties(structure->indexingType()))
        return false;
    if (structure->typeInfo().overridesGetPropertyNames())
        return false;
    return true;
};

bool Structure::canCachePropertyNameEnumerator() const
{
    if (!canCache(this))
        return false;

    StructureChain* structureChain = m_cachedPrototypeChain.get();
    ASSERT(structureChain);

    WriteBarrier<Structure>* structure = structureChain->head();
    while (true) {
        if (!structure->get())
            return true;
        if (!canCache(structure->get()))
            return false;
        structure++;
    }

    ASSERT_NOT_REACHED();
    return true;
}

bool Structure::canAccessPropertiesQuicklyForEnumeration() const
{
    if (!isQuickPropertyAccessAllowedForEnumeration())
        return false;
    if (hasGetterSetterProperties())
        return false;
    if (isUncacheableDictionary())
        return false;
    return true;
}

} // namespace JSC
