Unused Structure property tables waste 14MB on Membuster.
[WebKit-https.git] / Source / JavaScriptCore / runtime / Structure.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2013 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "Structure.h"
28
29 #include "CodeBlock.h"
30 #include "JSObject.h"
31 #include "JSPropertyNameIterator.h"
32 #include "Lookup.h"
33 #include "PropertyNameArray.h"
34 #include "StructureChain.h"
35 #include "StructureRareDataInlines.h"
36 #include <wtf/RefCountedLeakCounter.h>
37 #include <wtf/RefPtr.h>
38 #include <wtf/Threading.h>
39
40 #define DUMP_STRUCTURE_ID_STATISTICS 0
41
42 #ifndef NDEBUG
43 #define DO_PROPERTYMAP_CONSTENCY_CHECK 0
44 #else
45 #define DO_PROPERTYMAP_CONSTENCY_CHECK 0
46 #endif
47
48 using namespace std;
49 using namespace WTF;
50
51 #if DUMP_PROPERTYMAP_STATS
52
53 int numProbes;
54 int numCollisions;
55 int numRehashes;
56 int numRemoves;
57
58 #endif
59
60 namespace JSC {
61
62 #if DUMP_STRUCTURE_ID_STATISTICS
63 static HashSet<Structure*>& liveStructureSet = *(new HashSet<Structure*>);
64 #endif
65
66 bool StructureTransitionTable::contains(StringImpl* rep, unsigned attributes) const
67 {
68     if (isUsingSingleSlot()) {
69         Structure* transition = singleTransition();
70         return transition && transition->m_nameInPrevious == rep && transition->m_attributesInPrevious == attributes;
71     }
72     return map()->get(make_pair(rep, attributes));
73 }
74
75 inline Structure* StructureTransitionTable::get(StringImpl* rep, unsigned attributes) const
76 {
77     if (isUsingSingleSlot()) {
78         Structure* transition = singleTransition();
79         return (transition && transition->m_nameInPrevious == rep && transition->m_attributesInPrevious == attributes) ? transition : 0;
80     }
81     return map()->get(make_pair(rep, attributes));
82 }
83
84 inline void StructureTransitionTable::add(JSGlobalData& globalData, Structure* structure)
85 {
86     if (isUsingSingleSlot()) {
87         Structure* existingTransition = singleTransition();
88
89         // This handles the first transition being added.
90         if (!existingTransition) {
91             setSingleTransition(globalData, structure);
92             return;
93         }
94
95         // This handles the second transition being added
96         // (or the first transition being despecified!)
97         setMap(new TransitionMap());
98         add(globalData, existingTransition);
99     }
100
101     // Add the structure to the map.
102
103     // Newer versions of the STL have an std::make_pair function that takes rvalue references.
104     // 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.
105     // See https://bugs.webkit.org/show_bug.cgi?id=59261 for more details
106     map()->set(make_pair(structure->m_nameInPrevious, +structure->m_attributesInPrevious), structure);
107 }
108
109 void Structure::dumpStatistics()
110 {
111 #if DUMP_STRUCTURE_ID_STATISTICS
112     unsigned numberLeaf = 0;
113     unsigned numberUsingSingleSlot = 0;
114     unsigned numberSingletons = 0;
115     unsigned numberWithPropertyMaps = 0;
116     unsigned totalPropertyMapsSize = 0;
117
118     HashSet<Structure*>::const_iterator end = liveStructureSet.end();
119     for (HashSet<Structure*>::const_iterator it = liveStructureSet.begin(); it != end; ++it) {
120         Structure* structure = *it;
121
122         switch (structure->m_transitionTable.size()) {
123             case 0:
124                 ++numberLeaf;
125                 if (!structure->previousID())
126                     ++numberSingletons;
127                 break;
128
129             case 1:
130                 ++numberUsingSingleSlot;
131                 break;
132         }
133
134         if (structure->propertyTable()) {
135             ++numberWithPropertyMaps;
136             totalPropertyMapsSize += structure->propertyTable()->sizeInMemory();
137         }
138     }
139
140     dataLogF("Number of live Structures: %d\n", liveStructureSet.size());
141     dataLogF("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
142     dataLogF("Number of Structures that are leaf nodes: %d\n", numberLeaf);
143     dataLogF("Number of Structures that singletons: %d\n", numberSingletons);
144     dataLogF("Number of Structures with PropertyMaps: %d\n", numberWithPropertyMaps);
145
146     dataLogF("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
147     dataLogF("Size of sum of all property maps: %d\n", totalPropertyMapsSize);
148     dataLogF("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyMapsSize) / static_cast<double>(liveStructureSet.size()));
149 #else
150     dataLogF("Dumping Structure statistics is not enabled.\n");
151 #endif
152 }
153
154 Structure::Structure(JSGlobalData& globalData, JSGlobalObject* globalObject, JSValue prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
155     : JSCell(globalData, globalData.structureStructure.get())
156     , m_typeInfo(typeInfo)
157     , m_indexingType(indexingType)
158     , m_globalObject(globalData, this, globalObject, WriteBarrier<JSGlobalObject>::MayBeNull)
159     , m_prototype(globalData, this, prototype)
160     , m_classInfo(classInfo)
161     , m_transitionWatchpointSet(InitializedWatching)
162     , m_inlineCapacity(inlineCapacity)
163     , m_offset(invalidOffset)
164     , m_dictionaryKind(NoneDictionaryKind)
165     , m_isPinnedPropertyTable(false)
166     , m_hasGetterSetterProperties(false)
167     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(false)
168     , m_hasNonEnumerableProperties(false)
169     , m_attributesInPrevious(0)
170     , m_specificFunctionThrashCount(0)
171     , m_preventExtensions(false)
172     , m_didTransition(false)
173     , m_staticFunctionReified(false)
174 {
175     ASSERT(inlineCapacity <= JSFinalObject::maxInlineCapacity());
176     ASSERT(static_cast<PropertyOffset>(inlineCapacity) < firstOutOfLineOffset);
177     ASSERT(!typeInfo.structureHasRareData());
178 }
179
180 const ClassInfo Structure::s_info = { "Structure", 0, 0, 0, CREATE_METHOD_TABLE(Structure) };
181
182 Structure::Structure(JSGlobalData& globalData)
183     : JSCell(CreatingEarlyCell)
184     , m_typeInfo(CompoundType, OverridesVisitChildren)
185     , m_indexingType(0)
186     , m_prototype(globalData, this, jsNull())
187     , m_classInfo(&s_info)
188     , m_transitionWatchpointSet(InitializedWatching)
189     , m_inlineCapacity(0)
190     , m_offset(invalidOffset)
191     , m_dictionaryKind(NoneDictionaryKind)
192     , m_isPinnedPropertyTable(false)
193     , m_hasGetterSetterProperties(false)
194     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(false)
195     , m_hasNonEnumerableProperties(false)
196     , m_attributesInPrevious(0)
197     , m_specificFunctionThrashCount(0)
198     , m_preventExtensions(false)
199     , m_didTransition(false)
200     , m_staticFunctionReified(false)
201 {
202 }
203
204 Structure::Structure(JSGlobalData& globalData, const Structure* previous)
205     : JSCell(globalData, globalData.structureStructure.get())
206     , m_typeInfo(previous->typeInfo())
207     , m_indexingType(previous->indexingTypeIncludingHistory())
208     , m_prototype(globalData, this, previous->storedPrototype())
209     , m_classInfo(previous->m_classInfo)
210     , m_transitionWatchpointSet(InitializedWatching)
211     , m_inlineCapacity(previous->m_inlineCapacity)
212     , m_offset(invalidOffset)
213     , m_dictionaryKind(previous->m_dictionaryKind)
214     , m_isPinnedPropertyTable(false)
215     , m_hasGetterSetterProperties(previous->m_hasGetterSetterProperties)
216     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(previous->m_hasReadOnlyOrGetterSetterPropertiesExcludingProto)
217     , m_hasNonEnumerableProperties(previous->m_hasNonEnumerableProperties)
218     , m_attributesInPrevious(0)
219     , m_specificFunctionThrashCount(previous->m_specificFunctionThrashCount)
220     , m_preventExtensions(previous->m_preventExtensions)
221     , m_didTransition(true)
222     , m_staticFunctionReified(previous->m_staticFunctionReified)
223 {
224     previous->notifyTransitionFromThisStructure();
225     if (previous->m_globalObject)
226         m_globalObject.set(globalData, this, previous->m_globalObject.get());
227 }
228
229 void Structure::destroy(JSCell* cell)
230 {
231     static_cast<Structure*>(cell)->Structure::~Structure();
232 }
233
234 void Structure::materializePropertyMap(JSGlobalData& globalData)
235 {
236     ASSERT(structure()->classInfo() == &s_info);
237     ASSERT(!propertyTable());
238
239     Vector<Structure*, 8> structures;
240     structures.append(this);
241
242     Structure* structure = this;
243
244     // Search for the last Structure with a property table.
245     while ((structure = structure->previousID())) {
246         if (structure->m_isPinnedPropertyTable) {
247             ASSERT(structure->propertyTable());
248             ASSERT(!structure->previousID());
249
250             propertyTable().set(globalData, this, structure->propertyTable()->copy(globalData, 0, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity)));
251             break;
252         }
253
254         structures.append(structure);
255     }
256
257     if (!propertyTable())
258         createPropertyMap(globalData, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
259
260     for (ptrdiff_t i = structures.size() - 1; i >= 0; --i) {
261         structure = structures[i];
262         if (!structure->m_nameInPrevious)
263             continue;
264         PropertyMapEntry entry(globalData, this, structure->m_nameInPrevious.get(), structure->m_offset, structure->m_attributesInPrevious, structure->m_specificValueInPrevious.get());
265         propertyTable()->add(entry, m_offset, PropertyTable::PropertyOffsetMustNotChange);
266     }
267     
268     checkOffsetConsistency();
269 }
270
271 inline size_t nextOutOfLineStorageCapacity(size_t currentCapacity)
272 {
273     if (!currentCapacity)
274         return initialOutOfLineCapacity;
275     return currentCapacity * outOfLineGrowthFactor;
276 }
277
278 size_t Structure::suggestedNewOutOfLineStorageCapacity()
279 {
280     return nextOutOfLineStorageCapacity(outOfLineCapacity());
281 }
282  
283 void Structure::despecifyDictionaryFunction(JSGlobalData& globalData, PropertyName propertyName)
284 {
285     StringImpl* rep = propertyName.uid();
286
287     materializePropertyMapIfNecessary(globalData);
288
289     ASSERT(isDictionary());
290     ASSERT(propertyTable());
291
292     PropertyMapEntry* entry = propertyTable()->find(rep).first;
293     ASSERT(entry);
294     entry->specificValue.clear();
295 }
296
297 Structure* Structure::addPropertyTransitionToExistingStructure(Structure* structure, PropertyName propertyName, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
298 {
299     ASSERT(!structure->isDictionary());
300     ASSERT(structure->isObject());
301
302     if (Structure* existingTransition = structure->m_transitionTable.get(propertyName.uid(), attributes)) {
303         JSCell* specificValueInPrevious = existingTransition->m_specificValueInPrevious.get();
304         if (specificValueInPrevious && specificValueInPrevious != specificValue)
305             return 0;
306         validateOffset(existingTransition->m_offset, existingTransition->inlineCapacity());
307         offset = existingTransition->m_offset;
308         return existingTransition;
309     }
310
311     return 0;
312 }
313
314 bool Structure::anyObjectInChainMayInterceptIndexedAccesses() const
315 {
316     for (const Structure* current = this; ;) {
317         if (current->mayInterceptIndexedAccesses())
318             return true;
319         
320         JSValue prototype = current->storedPrototype();
321         if (prototype.isNull())
322             return false;
323         
324         current = asObject(prototype)->structure();
325     }
326 }
327
328 bool Structure::needsSlowPutIndexing() const
329 {
330     return anyObjectInChainMayInterceptIndexedAccesses()
331         || globalObject()->isHavingABadTime();
332 }
333
334 NonPropertyTransition Structure::suggestedArrayStorageTransition() const
335 {
336     if (needsSlowPutIndexing())
337         return AllocateSlowPutArrayStorage;
338     
339     return AllocateArrayStorage;
340 }
341
342 Structure* Structure::addPropertyTransition(JSGlobalData& globalData, Structure* structure, PropertyName propertyName, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
343 {
344     // If we have a specific function, we may have got to this point if there is
345     // already a transition with the correct property name and attributes, but
346     // specialized to a different function.  In this case we just want to give up
347     // and despecialize the transition.
348     // In this case we clear the value of specificFunction which will result
349     // in us adding a non-specific transition, and any subsequent lookup in
350     // Structure::addPropertyTransitionToExistingStructure will just use that.
351     if (specificValue && structure->m_transitionTable.contains(propertyName.uid(), attributes))
352         specificValue = 0;
353
354     ASSERT(!structure->isDictionary());
355     ASSERT(structure->isObject());
356     ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, specificValue, offset));
357     
358     if (structure->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
359         specificValue = 0;
360
361     if (structure->transitionCount() > s_maxTransitionLength) {
362         Structure* transition = toCacheableDictionaryTransition(globalData, structure);
363         ASSERT(structure != transition);
364         offset = transition->putSpecificValue(globalData, propertyName, attributes, specificValue);
365         return transition;
366     }
367     
368     Structure* transition = create(globalData, structure);
369
370     transition->m_cachedPrototypeChain.setMayBeNull(globalData, transition, structure->m_cachedPrototypeChain.get());
371     transition->setPreviousID(globalData, transition, structure);
372     transition->m_nameInPrevious = propertyName.uid();
373     transition->m_attributesInPrevious = attributes;
374     transition->m_specificValueInPrevious.setMayBeNull(globalData, transition, specificValue);
375     transition->propertyTable().set(globalData, transition, structure->takePropertyTableOrCloneIfPinned(globalData, transition));
376     transition->m_offset = structure->m_offset;
377
378     offset = transition->putSpecificValue(globalData, propertyName, attributes, specificValue);
379
380     checkOffset(transition->m_offset, transition->inlineCapacity());
381     structure->m_transitionTable.add(globalData, transition);
382     transition->checkOffsetConsistency();
383     structure->checkOffsetConsistency();
384     return transition;
385 }
386
387 Structure* Structure::removePropertyTransition(JSGlobalData& globalData, Structure* structure, PropertyName propertyName, PropertyOffset& offset)
388 {
389     ASSERT(!structure->isUncacheableDictionary());
390
391     Structure* transition = toUncacheableDictionaryTransition(globalData, structure);
392
393     offset = transition->remove(propertyName);
394
395     transition->checkOffsetConsistency();
396     return transition;
397 }
398
399 Structure* Structure::changePrototypeTransition(JSGlobalData& globalData, Structure* structure, JSValue prototype)
400 {
401     Structure* transition = create(globalData, structure);
402
403     transition->m_prototype.set(globalData, transition, prototype);
404
405     structure->materializePropertyMapIfNecessary(globalData);
406     transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData, transition));
407     transition->m_offset = structure->m_offset;
408     transition->pin();
409
410     transition->checkOffsetConsistency();
411     return transition;
412 }
413
414 Structure* Structure::despecifyFunctionTransition(JSGlobalData& globalData, Structure* structure, PropertyName replaceFunction)
415 {
416     ASSERT(structure->m_specificFunctionThrashCount < maxSpecificFunctionThrashCount);
417     Structure* transition = create(globalData, structure);
418
419     ++transition->m_specificFunctionThrashCount;
420
421     structure->materializePropertyMapIfNecessary(globalData);
422     transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData, transition));
423     transition->m_offset = structure->m_offset;
424     transition->pin();
425
426     if (transition->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
427         transition->despecifyAllFunctions(globalData);
428     else {
429         bool removed = transition->despecifyFunction(globalData, replaceFunction);
430         ASSERT_UNUSED(removed, removed);
431     }
432
433     transition->checkOffsetConsistency();
434     return transition;
435 }
436
437 Structure* Structure::attributeChangeTransition(JSGlobalData& globalData, Structure* structure, PropertyName propertyName, unsigned attributes)
438 {
439     if (!structure->isUncacheableDictionary()) {
440         Structure* transition = create(globalData, structure);
441
442         structure->materializePropertyMapIfNecessary(globalData);
443         transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData, transition));
444         transition->m_offset = structure->m_offset;
445         transition->pin();
446         
447         structure = transition;
448     }
449
450     ASSERT(structure->propertyTable());
451     PropertyMapEntry* entry = structure->propertyTable()->find(propertyName.uid()).first;
452     ASSERT(entry);
453     entry->attributes = attributes;
454
455     structure->checkOffsetConsistency();
456     return structure;
457 }
458
459 Structure* Structure::toDictionaryTransition(JSGlobalData& globalData, Structure* structure, DictionaryKind kind)
460 {
461     ASSERT(!structure->isUncacheableDictionary());
462     
463     Structure* transition = create(globalData, structure);
464
465     structure->materializePropertyMapIfNecessary(globalData);
466     transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData, transition));
467     transition->m_offset = structure->m_offset;
468     transition->m_dictionaryKind = kind;
469     transition->pin();
470
471     transition->checkOffsetConsistency();
472     return transition;
473 }
474
475 Structure* Structure::toCacheableDictionaryTransition(JSGlobalData& globalData, Structure* structure)
476 {
477     return toDictionaryTransition(globalData, structure, CachedDictionaryKind);
478 }
479
480 Structure* Structure::toUncacheableDictionaryTransition(JSGlobalData& globalData, Structure* structure)
481 {
482     return toDictionaryTransition(globalData, structure, UncachedDictionaryKind);
483 }
484
485 // In future we may want to cache this transition.
486 Structure* Structure::sealTransition(JSGlobalData& globalData, Structure* structure)
487 {
488     Structure* transition = preventExtensionsTransition(globalData, structure);
489
490     if (transition->propertyTable()) {
491         PropertyTable::iterator end = transition->propertyTable()->end();
492         for (PropertyTable::iterator iter = transition->propertyTable()->begin(); iter != end; ++iter)
493             iter->attributes |= DontDelete;
494     }
495
496     transition->checkOffsetConsistency();
497     return transition;
498 }
499
500 // In future we may want to cache this transition.
501 Structure* Structure::freezeTransition(JSGlobalData& globalData, Structure* structure)
502 {
503     Structure* transition = preventExtensionsTransition(globalData, structure);
504
505     if (transition->propertyTable()) {
506         PropertyTable::iterator iter = transition->propertyTable()->begin();
507         PropertyTable::iterator end = transition->propertyTable()->end();
508         if (iter != end)
509             transition->m_hasReadOnlyOrGetterSetterPropertiesExcludingProto = true;
510         for (; iter != end; ++iter)
511             iter->attributes |= iter->attributes & Accessor ? DontDelete : (DontDelete | ReadOnly);
512     }
513
514     transition->checkOffsetConsistency();
515     return transition;
516 }
517
518 // In future we may want to cache this transition.
519 Structure* Structure::preventExtensionsTransition(JSGlobalData& globalData, Structure* structure)
520 {
521     Structure* transition = create(globalData, structure);
522
523     // Don't set m_offset, as one can not transition to this.
524
525     structure->materializePropertyMapIfNecessary(globalData);
526     transition->propertyTable().set(globalData, transition, structure->copyPropertyTableForPinning(globalData, transition));
527     transition->m_offset = structure->m_offset;
528     transition->m_preventExtensions = true;
529     transition->pin();
530
531     transition->checkOffsetConsistency();
532     return transition;
533 }
534
535 PropertyTable* Structure::takePropertyTableOrCloneIfPinned(JSGlobalData& globalData, Structure* owner)
536 {
537     materializePropertyMapIfNecessaryForPinning(globalData);
538     if (m_isPinnedPropertyTable)
539         return propertyTable()->copy(globalData, owner, propertyTable()->size() + 1);
540     PropertyTable* takenPropertyTable = propertyTable().get();
541     propertyTable().clear();
542     return takenPropertyTable;
543 }
544
545 Structure* Structure::nonPropertyTransition(JSGlobalData& globalData, Structure* structure, NonPropertyTransition transitionKind)
546 {
547     unsigned attributes = toAttributes(transitionKind);
548     IndexingType indexingType = newIndexingType(structure->indexingTypeIncludingHistory(), transitionKind);
549     
550     if (JSGlobalObject* globalObject = structure->m_globalObject.get()) {
551         if (globalObject->isOriginalArrayStructure(structure)) {
552             Structure* result = globalObject->originalArrayStructureForIndexingType(indexingType);
553             if (result->indexingTypeIncludingHistory() == indexingType) {
554                 structure->notifyTransitionFromThisStructure();
555                 return result;
556             }
557         }
558     }
559     
560     if (Structure* existingTransition = structure->m_transitionTable.get(0, attributes)) {
561         ASSERT(existingTransition->m_attributesInPrevious == attributes);
562         ASSERT(existingTransition->indexingTypeIncludingHistory() == indexingType);
563         return existingTransition;
564     }
565     
566     Structure* transition = create(globalData, structure);
567     transition->setPreviousID(globalData, transition, structure);
568     transition->m_attributesInPrevious = attributes;
569     transition->m_indexingType = indexingType;
570     transition->propertyTable().set(globalData, transition, structure->takePropertyTableOrCloneIfPinned(globalData, transition));
571     transition->m_offset = structure->m_offset;
572     checkOffset(transition->m_offset, transition->inlineCapacity());
573     
574     structure->m_transitionTable.add(globalData, transition);
575     transition->checkOffsetConsistency();
576     return transition;
577 }
578
579 // In future we may want to cache this property.
580 bool Structure::isSealed(JSGlobalData& globalData)
581 {
582     if (isExtensible())
583         return false;
584
585     materializePropertyMapIfNecessary(globalData);
586     if (!propertyTable())
587         return true;
588
589     PropertyTable::iterator end = propertyTable()->end();
590     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
591         if ((iter->attributes & DontDelete) != DontDelete)
592             return false;
593     }
594     return true;
595 }
596
597 // In future we may want to cache this property.
598 bool Structure::isFrozen(JSGlobalData& globalData)
599 {
600     if (isExtensible())
601         return false;
602
603     materializePropertyMapIfNecessary(globalData);
604     if (!propertyTable())
605         return true;
606
607     PropertyTable::iterator end = propertyTable()->end();
608     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
609         if (!(iter->attributes & DontDelete))
610             return false;
611         if (!(iter->attributes & (ReadOnly | Accessor)))
612             return false;
613     }
614     return true;
615 }
616
617 Structure* Structure::flattenDictionaryStructure(JSGlobalData& globalData, JSObject* object)
618 {
619     checkOffsetConsistency();
620     ASSERT(isDictionary());
621     if (isUncacheableDictionary()) {
622         ASSERT(propertyTable());
623
624         size_t propertyCount = propertyTable()->size();
625
626         // Holds our values compacted by insertion order.
627         Vector<JSValue> values(propertyCount);
628
629         // Copies out our values from their hashed locations, compacting property table offsets as we go.
630         unsigned i = 0;
631         PropertyTable::iterator end = propertyTable()->end();
632         m_offset = invalidOffset;
633         for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter, ++i) {
634             values[i] = object->getDirect(iter->offset);
635             m_offset = iter->offset = offsetForPropertyNumber(i, m_inlineCapacity);
636         }
637         
638         // Copies in our values to their compacted locations.
639         for (unsigned i = 0; i < propertyCount; i++)
640             object->putDirect(globalData, offsetForPropertyNumber(i, m_inlineCapacity), values[i]);
641
642         propertyTable()->clearDeletedOffsets();
643         checkOffsetConsistency();
644     }
645
646     m_dictionaryKind = NoneDictionaryKind;
647     return this;
648 }
649
650 PropertyOffset Structure::addPropertyWithoutTransition(JSGlobalData& globalData, PropertyName propertyName, unsigned attributes, JSCell* specificValue)
651 {
652     ASSERT(!enumerationCache());
653
654     if (m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
655         specificValue = 0;
656
657     materializePropertyMapIfNecessaryForPinning(globalData);
658     
659     pin();
660
661     return putSpecificValue(globalData, propertyName, attributes, specificValue);
662 }
663
664 PropertyOffset Structure::removePropertyWithoutTransition(JSGlobalData& globalData, PropertyName propertyName)
665 {
666     ASSERT(isUncacheableDictionary());
667     ASSERT(!enumerationCache());
668
669     materializePropertyMapIfNecessaryForPinning(globalData);
670
671     pin();
672     return remove(propertyName);
673 }
674
675 void Structure::pin()
676 {
677     ASSERT(propertyTable());
678     m_isPinnedPropertyTable = true;
679     clearPreviousID();
680     m_nameInPrevious.clear();
681 }
682
683 void Structure::allocateRareData(JSGlobalData& globalData)
684 {
685     ASSERT(!typeInfo().structureHasRareData());
686     StructureRareData* rareData = StructureRareData::create(globalData, previous());
687     m_typeInfo = TypeInfo(typeInfo().type(), typeInfo().flags() | StructureHasRareData);
688     m_previousOrRareData.set(globalData, this, rareData);
689 }
690
691 void Structure::cloneRareDataFrom(JSGlobalData& globalData, const Structure* other)
692 {
693     ASSERT(other->typeInfo().structureHasRareData());
694     StructureRareData* newRareData = StructureRareData::clone(globalData, other->rareData());
695     m_previousOrRareData.set(globalData, this, newRareData);
696 }
697
698 #if DUMP_PROPERTYMAP_STATS
699
700 struct PropertyMapStatisticsExitLogger {
701     ~PropertyMapStatisticsExitLogger();
702 };
703
704 static PropertyMapStatisticsExitLogger logger;
705
706 PropertyMapStatisticsExitLogger::~PropertyMapStatisticsExitLogger()
707 {
708     dataLogF("\nJSC::PropertyMap statistics\n\n");
709     dataLogF("%d probes\n", numProbes);
710     dataLogF("%d collisions (%.1f%%)\n", numCollisions, 100.0 * numCollisions / numProbes);
711     dataLogF("%d rehashes\n", numRehashes);
712     dataLogF("%d removes\n", numRemoves);
713 }
714
715 #endif
716
717 #if !DO_PROPERTYMAP_CONSTENCY_CHECK
718
719 inline void Structure::checkConsistency()
720 {
721     checkOffsetConsistency();
722 }
723
724 #endif
725
726 PropertyTable* Structure::copyPropertyTable(JSGlobalData& globalData, Structure* owner)
727 {
728     if (!propertyTable())
729         return 0;
730     return PropertyTable::clone(globalData, owner, *propertyTable().get());
731 }
732
733 PropertyTable* Structure::copyPropertyTableForPinning(JSGlobalData& globalData, Structure* owner)
734 {
735     if (propertyTable())
736         return PropertyTable::clone(globalData, owner, *propertyTable().get());
737     return PropertyTable::create(globalData, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
738 }
739
740 PropertyOffset Structure::get(JSGlobalData& globalData, PropertyName propertyName, unsigned& attributes, JSCell*& specificValue)
741 {
742     ASSERT(structure()->classInfo() == &s_info);
743
744     materializePropertyMapIfNecessary(globalData);
745     if (!propertyTable())
746         return invalidOffset;
747
748     PropertyMapEntry* entry = propertyTable()->find(propertyName.uid()).first;
749     if (!entry)
750         return invalidOffset;
751
752     attributes = entry->attributes;
753     specificValue = entry->specificValue.get();
754     return entry->offset;
755 }
756
757 bool Structure::despecifyFunction(JSGlobalData& globalData, PropertyName propertyName)
758 {
759     materializePropertyMapIfNecessary(globalData);
760     if (!propertyTable())
761         return false;
762
763     PropertyMapEntry* entry = propertyTable()->find(propertyName.uid()).first;
764     if (!entry)
765         return false;
766
767     ASSERT(entry->specificValue);
768     entry->specificValue.clear();
769     return true;
770 }
771
772 void Structure::despecifyAllFunctions(JSGlobalData& globalData)
773 {
774     materializePropertyMapIfNecessary(globalData);
775     if (!propertyTable())
776         return;
777
778     PropertyTable::iterator end = propertyTable()->end();
779     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter)
780         iter->specificValue.clear();
781 }
782
783 PropertyOffset Structure::putSpecificValue(JSGlobalData& globalData, PropertyName propertyName, unsigned attributes, JSCell* specificValue)
784 {
785     ASSERT(!JSC::isValidOffset(get(globalData, propertyName)));
786
787     checkConsistency();
788     if (attributes & DontEnum)
789         m_hasNonEnumerableProperties = true;
790
791     StringImpl* rep = propertyName.uid();
792
793     if (!propertyTable())
794         createPropertyMap(globalData);
795
796     PropertyOffset newOffset = propertyTable()->nextOffset(m_inlineCapacity);
797
798     propertyTable()->add(PropertyMapEntry(globalData, this, rep, newOffset, attributes, specificValue), m_offset, PropertyTable::PropertyOffsetMayChange);
799     
800     checkConsistency();
801     return newOffset;
802 }
803
804 PropertyOffset Structure::remove(PropertyName propertyName)
805 {
806     checkConsistency();
807
808     StringImpl* rep = propertyName.uid();
809
810     if (!propertyTable())
811         return invalidOffset;
812
813     PropertyTable::find_iterator position = propertyTable()->find(rep);
814     if (!position.first)
815         return invalidOffset;
816
817     PropertyOffset offset = position.first->offset;
818
819     propertyTable()->remove(position);
820     propertyTable()->addDeletedOffset(offset);
821
822     checkConsistency();
823     return offset;
824 }
825
826 void Structure::createPropertyMap(JSGlobalData& globalData, unsigned capacity)
827 {
828     ASSERT(!propertyTable());
829
830     checkConsistency();
831     propertyTable().set(globalData, this, PropertyTable::create(globalData, capacity));
832 }
833
834 void Structure::getPropertyNamesFromStructure(JSGlobalData& globalData, PropertyNameArray& propertyNames, EnumerationMode mode)
835 {
836     materializePropertyMapIfNecessary(globalData);
837     if (!propertyTable())
838         return;
839
840     bool knownUnique = !propertyNames.size();
841
842     PropertyTable::iterator end = propertyTable()->end();
843     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
844         ASSERT(m_hasNonEnumerableProperties || !(iter->attributes & DontEnum));
845         if (iter->key->isIdentifier() && (!(iter->attributes & DontEnum) || mode == IncludeDontEnumProperties)) {
846             if (knownUnique)
847                 propertyNames.addKnownUnique(iter->key);
848             else
849                 propertyNames.add(iter->key);
850         }
851     }
852 }
853
854 JSValue Structure::prototypeForLookup(CodeBlock* codeBlock) const
855 {
856     return prototypeForLookup(codeBlock->globalObject());
857 }
858
859 void Structure::visitChildren(JSCell* cell, SlotVisitor& visitor)
860 {
861     Structure* thisObject = jsCast<Structure*>(cell);
862     ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
863     ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());
864
865     JSCell::visitChildren(thisObject, visitor);
866     visitor.append(&thisObject->m_globalObject);
867     if (!thisObject->isObject())
868         thisObject->m_cachedPrototypeChain.clear();
869     else {
870         visitor.append(&thisObject->m_prototype);
871         visitor.append(&thisObject->m_cachedPrototypeChain);
872     }
873     visitor.append(&thisObject->m_previousOrRareData);
874     visitor.append(&thisObject->m_specificValueInPrevious);
875
876     if (thisObject->m_isPinnedPropertyTable) {
877         ASSERT(thisObject->m_propertyTableUnsafe);
878         visitor.append(&thisObject->m_propertyTableUnsafe);
879     } else if (thisObject->m_propertyTableUnsafe)
880         thisObject->m_propertyTableUnsafe.clear();
881 }
882
883 bool Structure::prototypeChainMayInterceptStoreTo(JSGlobalData& globalData, PropertyName propertyName)
884 {
885     unsigned i = propertyName.asIndex();
886     if (i != PropertyName::NotAnIndex)
887         return anyObjectInChainMayInterceptIndexedAccesses();
888     
889     for (Structure* current = this; ;) {
890         JSValue prototype = current->storedPrototype();
891         if (prototype.isNull())
892             return false;
893         
894         current = prototype.asCell()->structure();
895         
896         unsigned attributes;
897         JSCell* specificValue;
898         PropertyOffset offset = current->get(globalData, propertyName, attributes, specificValue);
899         if (!JSC::isValidOffset(offset))
900             continue;
901         
902         if (attributes & (ReadOnly | Accessor))
903             return true;
904         
905         return false;
906     }
907 }
908
909 #if DO_PROPERTYMAP_CONSTENCY_CHECK
910
911 void PropertyTable::checkConsistency()
912 {
913     checkOffsetConsistency();
914     ASSERT(m_indexSize >= PropertyTable::MinimumTableSize);
915     ASSERT(m_indexMask);
916     ASSERT(m_indexSize == m_indexMask + 1);
917     ASSERT(!(m_indexSize & m_indexMask));
918
919     ASSERT(m_keyCount <= m_indexSize / 2);
920     ASSERT(m_keyCount + m_deletedCount <= m_indexSize / 2);
921     ASSERT(m_deletedCount <= m_indexSize / 4);
922
923     unsigned indexCount = 0;
924     unsigned deletedIndexCount = 0;
925     for (unsigned a = 0; a != m_indexSize; ++a) {
926         unsigned entryIndex = m_index[a];
927         if (entryIndex == PropertyTable::EmptyEntryIndex)
928             continue;
929         if (entryIndex == deletedEntryIndex()) {
930             ++deletedIndexCount;
931             continue;
932         }
933         ASSERT(entryIndex < deletedEntryIndex());
934         ASSERT(entryIndex - 1 <= usedCount());
935         ++indexCount;
936
937         for (unsigned b = a + 1; b != m_indexSize; ++b)
938             ASSERT(m_index[b] != entryIndex);
939     }
940     ASSERT(indexCount == m_keyCount);
941     ASSERT(deletedIndexCount == m_deletedCount);
942
943     ASSERT(!table()[deletedEntryIndex() - 1].key);
944
945     unsigned nonEmptyEntryCount = 0;
946     for (unsigned c = 0; c < usedCount(); ++c) {
947         StringImpl* rep = table()[c].key;
948         if (rep == PROPERTY_MAP_DELETED_ENTRY_KEY)
949             continue;
950         ++nonEmptyEntryCount;
951         unsigned i = rep->existingHash();
952         unsigned k = 0;
953         unsigned entryIndex;
954         while (1) {
955             entryIndex = m_index[i & m_indexMask];
956             ASSERT(entryIndex != PropertyTable::EmptyEntryIndex);
957             if (rep == table()[entryIndex - 1].key)
958                 break;
959             if (k == 0)
960                 k = 1 | doubleHash(rep->existingHash());
961             i += k;
962         }
963         ASSERT(entryIndex == c + 1);
964     }
965
966     ASSERT(nonEmptyEntryCount == m_keyCount);
967 }
968
969 void Structure::checkConsistency()
970 {
971     if (!propertyTable())
972         return;
973
974     if (!m_hasNonEnumerableProperties) {
975         PropertyTable::iterator end = propertyTable()->end();
976         for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
977             ASSERT(!(iter->attributes & DontEnum));
978         }
979     }
980
981     propertyTable()->checkConsistency();
982 }
983
984 #endif // DO_PROPERTYMAP_CONSTENCY_CHECK
985
986 } // namespace JSC