Foo::s_info should be Foo::info(), so that you can change how the s_info is actually...
[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 "DumpContext.h"
31 #include "JSObject.h"
32 #include "JSPropertyNameIterator.h"
33 #include "Lookup.h"
34 #include "PropertyNameArray.h"
35 #include "StructureChain.h"
36 #include "StructureRareDataInlines.h"
37 #include <wtf/CommaPrinter.h>
38 #include <wtf/RefCountedLeakCounter.h>
39 #include <wtf/RefPtr.h>
40 #include <wtf/Threading.h>
41
42 #define DUMP_STRUCTURE_ID_STATISTICS 0
43
44 #ifndef NDEBUG
45 #define DO_PROPERTYMAP_CONSTENCY_CHECK 0
46 #else
47 #define DO_PROPERTYMAP_CONSTENCY_CHECK 0
48 #endif
49
50 using namespace std;
51 using namespace WTF;
52
53 #if DUMP_PROPERTYMAP_STATS
54
55 int numProbes;
56 int numCollisions;
57 int numRehashes;
58 int numRemoves;
59
60 #endif
61
62 namespace JSC {
63
64 #if DUMP_STRUCTURE_ID_STATISTICS
65 static HashSet<Structure*>& liveStructureSet = *(new HashSet<Structure*>);
66 #endif
67
68 bool StructureTransitionTable::contains(StringImpl* rep, unsigned attributes) const
69 {
70     if (isUsingSingleSlot()) {
71         Structure* transition = singleTransition();
72         return transition && transition->m_nameInPrevious == rep && transition->m_attributesInPrevious == attributes;
73     }
74     return map()->get(make_pair(rep, attributes));
75 }
76
77 inline Structure* StructureTransitionTable::get(StringImpl* rep, unsigned attributes) const
78 {
79     if (isUsingSingleSlot()) {
80         Structure* transition = singleTransition();
81         return (transition && transition->m_nameInPrevious == rep && transition->m_attributesInPrevious == attributes) ? transition : 0;
82     }
83     return map()->get(make_pair(rep, attributes));
84 }
85
86 inline void StructureTransitionTable::add(VM& vm, Structure* structure)
87 {
88     if (isUsingSingleSlot()) {
89         Structure* existingTransition = singleTransition();
90
91         // This handles the first transition being added.
92         if (!existingTransition) {
93             setSingleTransition(vm, structure);
94             return;
95         }
96
97         // This handles the second transition being added
98         // (or the first transition being despecified!)
99         setMap(new TransitionMap());
100         add(vm, existingTransition);
101     }
102
103     // Add the structure to the map.
104
105     // Newer versions of the STL have an std::make_pair function that takes rvalue references.
106     // 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.
107     // See https://bugs.webkit.org/show_bug.cgi?id=59261 for more details
108     map()->set(make_pair(structure->m_nameInPrevious.get(), +structure->m_attributesInPrevious), structure);
109 }
110
111 void Structure::dumpStatistics()
112 {
113 #if DUMP_STRUCTURE_ID_STATISTICS
114     unsigned numberLeaf = 0;
115     unsigned numberUsingSingleSlot = 0;
116     unsigned numberSingletons = 0;
117     unsigned numberWithPropertyMaps = 0;
118     unsigned totalPropertyMapsSize = 0;
119
120     HashSet<Structure*>::const_iterator end = liveStructureSet.end();
121     for (HashSet<Structure*>::const_iterator it = liveStructureSet.begin(); it != end; ++it) {
122         Structure* structure = *it;
123
124         switch (structure->m_transitionTable.size()) {
125             case 0:
126                 ++numberLeaf;
127                 if (!structure->previousID())
128                     ++numberSingletons;
129                 break;
130
131             case 1:
132                 ++numberUsingSingleSlot;
133                 break;
134         }
135
136         if (structure->propertyTable()) {
137             ++numberWithPropertyMaps;
138             totalPropertyMapsSize += structure->propertyTable()->sizeInMemory();
139         }
140     }
141
142     dataLogF("Number of live Structures: %d\n", liveStructureSet.size());
143     dataLogF("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
144     dataLogF("Number of Structures that are leaf nodes: %d\n", numberLeaf);
145     dataLogF("Number of Structures that singletons: %d\n", numberSingletons);
146     dataLogF("Number of Structures with PropertyMaps: %d\n", numberWithPropertyMaps);
147
148     dataLogF("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
149     dataLogF("Size of sum of all property maps: %d\n", totalPropertyMapsSize);
150     dataLogF("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyMapsSize) / static_cast<double>(liveStructureSet.size()));
151 #else
152     dataLogF("Dumping Structure statistics is not enabled.\n");
153 #endif
154 }
155
156 Structure::Structure(VM& vm, JSGlobalObject* globalObject, JSValue prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
157     : JSCell(vm, vm.structureStructure.get())
158     , m_globalObject(vm, this, globalObject, WriteBarrier<JSGlobalObject>::MayBeNull)
159     , m_prototype(vm, this, prototype)
160     , m_classInfo(classInfo)
161     , m_transitionWatchpointSet(InitializedWatching)
162     , m_offset(invalidOffset)
163     , m_typeInfo(typeInfo)
164     , m_indexingType(indexingType)
165     , m_inlineCapacity(inlineCapacity)
166     , m_dictionaryKind(NoneDictionaryKind)
167     , m_isPinnedPropertyTable(false)
168     , m_hasGetterSetterProperties(false)
169     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(false)
170     , m_hasNonEnumerableProperties(false)
171     , m_attributesInPrevious(0)
172     , m_specificFunctionThrashCount(0)
173     , m_preventExtensions(false)
174     , m_didTransition(false)
175     , m_staticFunctionReified(false)
176 {
177     ASSERT(inlineCapacity <= JSFinalObject::maxInlineCapacity());
178     ASSERT(static_cast<PropertyOffset>(inlineCapacity) < firstOutOfLineOffset);
179     ASSERT(!typeInfo.structureHasRareData());
180 }
181
182 const ClassInfo Structure::s_info = { "Structure", 0, 0, 0, CREATE_METHOD_TABLE(Structure) };
183
184 Structure::Structure(VM& vm)
185     : JSCell(CreatingEarlyCell)
186     , m_prototype(vm, this, jsNull())
187     , m_classInfo(info())
188     , m_transitionWatchpointSet(InitializedWatching)
189     , m_offset(invalidOffset)
190     , m_typeInfo(CompoundType, OverridesVisitChildren)
191     , m_indexingType(0)
192     , m_inlineCapacity(0)
193     , m_dictionaryKind(NoneDictionaryKind)
194     , m_isPinnedPropertyTable(false)
195     , m_hasGetterSetterProperties(false)
196     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(false)
197     , m_hasNonEnumerableProperties(false)
198     , m_attributesInPrevious(0)
199     , m_specificFunctionThrashCount(0)
200     , m_preventExtensions(false)
201     , m_didTransition(false)
202     , m_staticFunctionReified(false)
203 {
204 }
205
206 Structure::Structure(VM& vm, const Structure* previous)
207     : JSCell(vm, vm.structureStructure.get())
208     , m_prototype(vm, this, previous->storedPrototype())
209     , m_classInfo(previous->m_classInfo)
210     , m_transitionWatchpointSet(InitializedWatching)
211     , m_offset(invalidOffset)
212     , m_typeInfo(previous->typeInfo().type(), previous->typeInfo().flags() & ~StructureHasRareData)
213     , m_indexingType(previous->indexingTypeIncludingHistory())
214     , m_inlineCapacity(previous->m_inlineCapacity)
215     , m_dictionaryKind(previous->m_dictionaryKind)
216     , m_isPinnedPropertyTable(false)
217     , m_hasGetterSetterProperties(previous->m_hasGetterSetterProperties)
218     , m_hasReadOnlyOrGetterSetterPropertiesExcludingProto(previous->m_hasReadOnlyOrGetterSetterPropertiesExcludingProto)
219     , m_hasNonEnumerableProperties(previous->m_hasNonEnumerableProperties)
220     , m_attributesInPrevious(0)
221     , m_specificFunctionThrashCount(previous->m_specificFunctionThrashCount)
222     , m_preventExtensions(previous->m_preventExtensions)
223     , m_didTransition(true)
224     , m_staticFunctionReified(previous->m_staticFunctionReified)
225 {
226     if (previous->typeInfo().structureHasRareData() && previous->rareData()->needsCloning())
227         cloneRareDataFrom(vm, previous);
228     else if (previous->previousID())
229         m_previousOrRareData.set(vm, this, previous->previousID());
230
231     previous->notifyTransitionFromThisStructure();
232     if (previous->m_globalObject)
233         m_globalObject.set(vm, this, previous->m_globalObject.get());
234 }
235
236 void Structure::destroy(JSCell* cell)
237 {
238     static_cast<Structure*>(cell)->Structure::~Structure();
239 }
240
241 void Structure::findStructuresAndMapForMaterialization(Vector<Structure*, 8>& structures, Structure*& structure, PropertyTable*& table)
242 {
243     ASSERT(structures.isEmpty());
244     table = 0;
245
246     for (structure = this; structure; structure = structure->previousID()) {
247         structure->m_lock.lock();
248         
249         table = structure->propertyTable().get();
250         if (table) {
251             // Leave the structure locked, so that the caller can do things to it atomically
252             // before it loses its property table.
253             return;
254         }
255         
256         structures.append(structure);
257         structure->m_lock.unlock();
258     }
259     
260     ASSERT(!structure);
261     ASSERT(!table);
262 }
263
264 void Structure::materializePropertyMap(VM& vm)
265 {
266     ASSERT(structure()->classInfo() == info());
267     ASSERT(!propertyTable());
268
269     Vector<Structure*, 8> structures;
270     Structure* structure;
271     PropertyTable* table;
272     
273     findStructuresAndMapForMaterialization(structures, structure, table);
274     
275     if (table) {
276         table = table->copy(vm, 0, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
277         structure->m_lock.unlock();
278     }
279     
280     // Must hold the lock on this structure, since we will be modifying this structure's
281     // property map. We don't want getConcurrently() to see the property map in a half-baked
282     // state.
283     ConcurrentJITLocker locker(m_lock);
284     if (!table)
285         createPropertyMap(locker, vm, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
286     else
287         propertyTable().set(vm, this, table);
288
289     for (size_t i = structures.size(); i--;) {
290         structure = structures[i];
291         if (!structure->m_nameInPrevious)
292             continue;
293         PropertyMapEntry entry(vm, this, structure->m_nameInPrevious.get(), structure->m_offset, structure->m_attributesInPrevious, structure->m_specificValueInPrevious.get());
294         propertyTable()->add(entry, m_offset, PropertyTable::PropertyOffsetMustNotChange);
295     }
296     
297     checkOffsetConsistency();
298 }
299
300 inline size_t nextOutOfLineStorageCapacity(size_t currentCapacity)
301 {
302     if (!currentCapacity)
303         return initialOutOfLineCapacity;
304     return currentCapacity * outOfLineGrowthFactor;
305 }
306
307 size_t Structure::suggestedNewOutOfLineStorageCapacity()
308 {
309     return nextOutOfLineStorageCapacity(outOfLineCapacity());
310 }
311  
312 void Structure::despecifyDictionaryFunction(VM& vm, PropertyName propertyName)
313 {
314     StringImpl* rep = propertyName.uid();
315
316     materializePropertyMapIfNecessary(vm);
317
318     ASSERT(isDictionary());
319     ASSERT(propertyTable());
320
321     PropertyMapEntry* entry = propertyTable()->find(rep).first;
322     ASSERT(entry);
323     entry->specificValue.clear();
324 }
325
326 Structure* Structure::addPropertyTransitionToExistingStructureImpl(Structure* structure, StringImpl* uid, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
327 {
328     ASSERT(!structure->isDictionary());
329     ASSERT(structure->isObject());
330
331     if (Structure* existingTransition = structure->m_transitionTable.get(uid, attributes)) {
332         JSCell* specificValueInPrevious = existingTransition->m_specificValueInPrevious.get();
333         if (specificValueInPrevious && specificValueInPrevious != specificValue)
334             return 0;
335         validateOffset(existingTransition->m_offset, existingTransition->inlineCapacity());
336         offset = existingTransition->m_offset;
337         return existingTransition;
338     }
339
340     return 0;
341 }
342
343 Structure* Structure::addPropertyTransitionToExistingStructure(Structure* structure, PropertyName propertyName, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
344 {
345     ASSERT(!isCompilationThread());
346     return addPropertyTransitionToExistingStructureImpl(structure, propertyName.uid(), attributes, specificValue, offset);
347 }
348
349 Structure* Structure::addPropertyTransitionToExistingStructureConcurrently(Structure* structure, StringImpl* uid, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
350 {
351     ConcurrentJITLocker locker(structure->m_lock);
352     return addPropertyTransitionToExistingStructureImpl(structure, uid, attributes, specificValue, offset);
353 }
354
355 bool Structure::anyObjectInChainMayInterceptIndexedAccesses() const
356 {
357     for (const Structure* current = this; ;) {
358         if (current->mayInterceptIndexedAccesses())
359             return true;
360         
361         JSValue prototype = current->storedPrototype();
362         if (prototype.isNull())
363             return false;
364         
365         current = asObject(prototype)->structure();
366     }
367 }
368
369 bool Structure::needsSlowPutIndexing() const
370 {
371     return anyObjectInChainMayInterceptIndexedAccesses()
372         || globalObject()->isHavingABadTime();
373 }
374
375 NonPropertyTransition Structure::suggestedArrayStorageTransition() const
376 {
377     if (needsSlowPutIndexing())
378         return AllocateSlowPutArrayStorage;
379     
380     return AllocateArrayStorage;
381 }
382
383 Structure* Structure::addPropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes, JSCell* specificValue, PropertyOffset& offset)
384 {
385     // If we have a specific function, we may have got to this point if there is
386     // already a transition with the correct property name and attributes, but
387     // specialized to a different function.  In this case we just want to give up
388     // and despecialize the transition.
389     // In this case we clear the value of specificFunction which will result
390     // in us adding a non-specific transition, and any subsequent lookup in
391     // Structure::addPropertyTransitionToExistingStructure will just use that.
392     if (specificValue && structure->m_transitionTable.contains(propertyName.uid(), attributes))
393         specificValue = 0;
394
395     ASSERT(!structure->isDictionary());
396     ASSERT(structure->isObject());
397     ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, specificValue, offset));
398     
399     if (structure->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
400         specificValue = 0;
401
402     if (structure->transitionCount() > s_maxTransitionLength) {
403         Structure* transition = toCacheableDictionaryTransition(vm, structure);
404         ASSERT(structure != transition);
405         offset = transition->putSpecificValue(vm, propertyName, attributes, specificValue);
406         return transition;
407     }
408     
409     Structure* transition = create(vm, structure);
410
411     transition->m_cachedPrototypeChain.setMayBeNull(vm, transition, structure->m_cachedPrototypeChain.get());
412     transition->setPreviousID(vm, transition, structure);
413     transition->m_nameInPrevious = propertyName.uid();
414     transition->m_attributesInPrevious = attributes;
415     transition->m_specificValueInPrevious.setMayBeNull(vm, transition, specificValue);
416     transition->propertyTable().set(vm, transition, structure->takePropertyTableOrCloneIfPinned(vm, transition));
417     transition->m_offset = structure->m_offset;
418
419     offset = transition->putSpecificValue(vm, propertyName, attributes, specificValue);
420
421     checkOffset(transition->m_offset, transition->inlineCapacity());
422     {
423         ConcurrentJITLocker locker(structure->m_lock);
424         structure->m_transitionTable.add(vm, transition);
425     }
426     transition->checkOffsetConsistency();
427     structure->checkOffsetConsistency();
428     return transition;
429 }
430
431 Structure* Structure::removePropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, PropertyOffset& offset)
432 {
433     ASSERT(!structure->isUncacheableDictionary());
434
435     Structure* transition = toUncacheableDictionaryTransition(vm, structure);
436
437     offset = transition->remove(propertyName);
438
439     transition->checkOffsetConsistency();
440     return transition;
441 }
442
443 Structure* Structure::changePrototypeTransition(VM& vm, Structure* structure, JSValue prototype)
444 {
445     Structure* transition = create(vm, structure);
446
447     transition->m_prototype.set(vm, transition, prototype);
448
449     structure->materializePropertyMapIfNecessary(vm);
450     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
451     transition->m_offset = structure->m_offset;
452     transition->pin();
453
454     transition->checkOffsetConsistency();
455     return transition;
456 }
457
458 Structure* Structure::despecifyFunctionTransition(VM& vm, Structure* structure, PropertyName replaceFunction)
459 {
460     ASSERT(structure->m_specificFunctionThrashCount < maxSpecificFunctionThrashCount);
461     Structure* transition = create(vm, structure);
462
463     ++transition->m_specificFunctionThrashCount;
464
465     structure->materializePropertyMapIfNecessary(vm);
466     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
467     transition->m_offset = structure->m_offset;
468     transition->pin();
469
470     if (transition->m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
471         transition->despecifyAllFunctions(vm);
472     else {
473         bool removed = transition->despecifyFunction(vm, replaceFunction);
474         ASSERT_UNUSED(removed, removed);
475     }
476
477     transition->checkOffsetConsistency();
478     return transition;
479 }
480
481 Structure* Structure::attributeChangeTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes)
482 {
483     if (!structure->isUncacheableDictionary()) {
484         Structure* transition = create(vm, structure);
485
486         structure->materializePropertyMapIfNecessary(vm);
487         transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
488         transition->m_offset = structure->m_offset;
489         transition->pin();
490         
491         structure = transition;
492     }
493
494     ASSERT(structure->propertyTable());
495     PropertyMapEntry* entry = structure->propertyTable()->find(propertyName.uid()).first;
496     ASSERT(entry);
497     entry->attributes = attributes;
498
499     structure->checkOffsetConsistency();
500     return structure;
501 }
502
503 Structure* Structure::toDictionaryTransition(VM& vm, Structure* structure, DictionaryKind kind)
504 {
505     ASSERT(!structure->isUncacheableDictionary());
506     
507     Structure* transition = create(vm, structure);
508
509     structure->materializePropertyMapIfNecessary(vm);
510     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
511     transition->m_offset = structure->m_offset;
512     transition->m_dictionaryKind = kind;
513     transition->pin();
514
515     transition->checkOffsetConsistency();
516     return transition;
517 }
518
519 Structure* Structure::toCacheableDictionaryTransition(VM& vm, Structure* structure)
520 {
521     return toDictionaryTransition(vm, structure, CachedDictionaryKind);
522 }
523
524 Structure* Structure::toUncacheableDictionaryTransition(VM& vm, Structure* structure)
525 {
526     return toDictionaryTransition(vm, structure, UncachedDictionaryKind);
527 }
528
529 // In future we may want to cache this transition.
530 Structure* Structure::sealTransition(VM& vm, Structure* structure)
531 {
532     Structure* transition = preventExtensionsTransition(vm, structure);
533
534     if (transition->propertyTable()) {
535         PropertyTable::iterator end = transition->propertyTable()->end();
536         for (PropertyTable::iterator iter = transition->propertyTable()->begin(); iter != end; ++iter)
537             iter->attributes |= DontDelete;
538     }
539
540     transition->checkOffsetConsistency();
541     return transition;
542 }
543
544 // In future we may want to cache this transition.
545 Structure* Structure::freezeTransition(VM& vm, Structure* structure)
546 {
547     Structure* transition = preventExtensionsTransition(vm, structure);
548
549     if (transition->propertyTable()) {
550         PropertyTable::iterator iter = transition->propertyTable()->begin();
551         PropertyTable::iterator end = transition->propertyTable()->end();
552         if (iter != end)
553             transition->m_hasReadOnlyOrGetterSetterPropertiesExcludingProto = true;
554         for (; iter != end; ++iter)
555             iter->attributes |= iter->attributes & Accessor ? DontDelete : (DontDelete | ReadOnly);
556     }
557
558     transition->checkOffsetConsistency();
559     return transition;
560 }
561
562 // In future we may want to cache this transition.
563 Structure* Structure::preventExtensionsTransition(VM& vm, Structure* structure)
564 {
565     Structure* transition = create(vm, structure);
566
567     // Don't set m_offset, as one can not transition to this.
568
569     structure->materializePropertyMapIfNecessary(vm);
570     transition->propertyTable().set(vm, transition, structure->copyPropertyTableForPinning(vm, transition));
571     transition->m_offset = structure->m_offset;
572     transition->m_preventExtensions = true;
573     transition->pin();
574
575     transition->checkOffsetConsistency();
576     return transition;
577 }
578
579 PropertyTable* Structure::takePropertyTableOrCloneIfPinned(VM& vm, Structure* owner)
580 {
581     materializePropertyMapIfNecessaryForPinning(vm);
582     
583     if (m_isPinnedPropertyTable)
584         return propertyTable()->copy(vm, owner, propertyTable()->size() + 1);
585     
586     // Hold the lock while stealing the table - so that getConcurrently() on another thread
587     // will either have to bypass this structure, or will get to use the property table
588     // before it is stolen.
589     ConcurrentJITLocker locker(m_lock);
590     PropertyTable* takenPropertyTable = propertyTable().get();
591     propertyTable().clear();
592     return takenPropertyTable;
593 }
594
595 Structure* Structure::nonPropertyTransition(VM& vm, Structure* structure, NonPropertyTransition transitionKind)
596 {
597     unsigned attributes = toAttributes(transitionKind);
598     IndexingType indexingType = newIndexingType(structure->indexingTypeIncludingHistory(), transitionKind);
599     
600     if (JSGlobalObject* globalObject = structure->m_globalObject.get()) {
601         if (globalObject->isOriginalArrayStructure(structure)) {
602             Structure* result = globalObject->originalArrayStructureForIndexingType(indexingType);
603             if (result->indexingTypeIncludingHistory() == indexingType) {
604                 structure->notifyTransitionFromThisStructure();
605                 return result;
606             }
607         }
608     }
609     
610     if (Structure* existingTransition = structure->m_transitionTable.get(0, attributes)) {
611         ASSERT(existingTransition->m_attributesInPrevious == attributes);
612         ASSERT(existingTransition->indexingTypeIncludingHistory() == indexingType);
613         return existingTransition;
614     }
615     
616     Structure* transition = create(vm, structure);
617     transition->setPreviousID(vm, transition, structure);
618     transition->m_attributesInPrevious = attributes;
619     transition->m_indexingType = indexingType;
620     transition->propertyTable().set(vm, transition, structure->takePropertyTableOrCloneIfPinned(vm, transition));
621     transition->m_offset = structure->m_offset;
622     checkOffset(transition->m_offset, transition->inlineCapacity());
623     
624     {
625         ConcurrentJITLocker locker(structure->m_lock);
626         structure->m_transitionTable.add(vm, transition);
627     }
628     transition->checkOffsetConsistency();
629     return transition;
630 }
631
632 // In future we may want to cache this property.
633 bool Structure::isSealed(VM& vm)
634 {
635     if (isExtensible())
636         return false;
637
638     materializePropertyMapIfNecessary(vm);
639     if (!propertyTable())
640         return true;
641
642     PropertyTable::iterator end = propertyTable()->end();
643     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
644         if ((iter->attributes & DontDelete) != DontDelete)
645             return false;
646     }
647     return true;
648 }
649
650 // In future we may want to cache this property.
651 bool Structure::isFrozen(VM& vm)
652 {
653     if (isExtensible())
654         return false;
655
656     materializePropertyMapIfNecessary(vm);
657     if (!propertyTable())
658         return true;
659
660     PropertyTable::iterator end = propertyTable()->end();
661     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
662         if (!(iter->attributes & DontDelete))
663             return false;
664         if (!(iter->attributes & (ReadOnly | Accessor)))
665             return false;
666     }
667     return true;
668 }
669
670 Structure* Structure::flattenDictionaryStructure(VM& vm, JSObject* object)
671 {
672     checkOffsetConsistency();
673     ASSERT(isDictionary());
674     if (isUncacheableDictionary()) {
675         ASSERT(propertyTable());
676
677         size_t propertyCount = propertyTable()->size();
678
679         // Holds our values compacted by insertion order.
680         Vector<JSValue> values(propertyCount);
681
682         // Copies out our values from their hashed locations, compacting property table offsets as we go.
683         unsigned i = 0;
684         PropertyTable::iterator end = propertyTable()->end();
685         m_offset = invalidOffset;
686         for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter, ++i) {
687             values[i] = object->getDirect(iter->offset);
688             m_offset = iter->offset = offsetForPropertyNumber(i, m_inlineCapacity);
689         }
690         
691         // Copies in our values to their compacted locations.
692         for (unsigned i = 0; i < propertyCount; i++)
693             object->putDirect(vm, offsetForPropertyNumber(i, m_inlineCapacity), values[i]);
694
695         propertyTable()->clearDeletedOffsets();
696         checkOffsetConsistency();
697     }
698
699     m_dictionaryKind = NoneDictionaryKind;
700     return this;
701 }
702
703 PropertyOffset Structure::addPropertyWithoutTransition(VM& vm, PropertyName propertyName, unsigned attributes, JSCell* specificValue)
704 {
705     ASSERT(!enumerationCache());
706
707     if (m_specificFunctionThrashCount == maxSpecificFunctionThrashCount)
708         specificValue = 0;
709
710     materializePropertyMapIfNecessaryForPinning(vm);
711     
712     pin();
713
714     return putSpecificValue(vm, propertyName, attributes, specificValue);
715 }
716
717 PropertyOffset Structure::removePropertyWithoutTransition(VM& vm, PropertyName propertyName)
718 {
719     ASSERT(isUncacheableDictionary());
720     ASSERT(!enumerationCache());
721
722     materializePropertyMapIfNecessaryForPinning(vm);
723
724     pin();
725     return remove(propertyName);
726 }
727
728 void Structure::pin()
729 {
730     ASSERT(propertyTable());
731     m_isPinnedPropertyTable = true;
732     clearPreviousID();
733     m_nameInPrevious.clear();
734 }
735
736 void Structure::allocateRareData(VM& vm)
737 {
738     ASSERT(!typeInfo().structureHasRareData());
739     StructureRareData* rareData = StructureRareData::create(vm, previous());
740     m_typeInfo = TypeInfo(typeInfo().type(), typeInfo().flags() | StructureHasRareData);
741     m_previousOrRareData.set(vm, this, rareData);
742 }
743
744 void Structure::cloneRareDataFrom(VM& vm, const Structure* other)
745 {
746     ASSERT(other->typeInfo().structureHasRareData());
747     StructureRareData* newRareData = StructureRareData::clone(vm, other->rareData());
748     m_typeInfo = TypeInfo(typeInfo().type(), typeInfo().flags() | StructureHasRareData);
749     m_previousOrRareData.set(vm, this, newRareData);
750 }
751
752 #if DUMP_PROPERTYMAP_STATS
753
754 struct PropertyMapStatisticsExitLogger {
755     ~PropertyMapStatisticsExitLogger();
756 };
757
758 static PropertyMapStatisticsExitLogger logger;
759
760 PropertyMapStatisticsExitLogger::~PropertyMapStatisticsExitLogger()
761 {
762     dataLogF("\nJSC::PropertyMap statistics\n\n");
763     dataLogF("%d probes\n", numProbes);
764     dataLogF("%d collisions (%.1f%%)\n", numCollisions, 100.0 * numCollisions / numProbes);
765     dataLogF("%d rehashes\n", numRehashes);
766     dataLogF("%d removes\n", numRemoves);
767 }
768
769 #endif
770
771 #if !DO_PROPERTYMAP_CONSTENCY_CHECK
772
773 inline void Structure::checkConsistency()
774 {
775     checkOffsetConsistency();
776 }
777
778 #endif
779
780 PropertyTable* Structure::copyPropertyTable(VM& vm, Structure* owner)
781 {
782     if (!propertyTable())
783         return 0;
784     return PropertyTable::clone(vm, owner, *propertyTable().get());
785 }
786
787 PropertyTable* Structure::copyPropertyTableForPinning(VM& vm, Structure* owner)
788 {
789     if (propertyTable())
790         return PropertyTable::clone(vm, owner, *propertyTable().get());
791     return PropertyTable::create(vm, numberOfSlotsForLastOffset(m_offset, m_inlineCapacity));
792 }
793
794 PropertyOffset Structure::getConcurrently(VM&, StringImpl* uid, unsigned& attributes, JSCell*& specificValue)
795 {
796     Vector<Structure*, 8> structures;
797     Structure* structure;
798     PropertyTable* table;
799     
800     findStructuresAndMapForMaterialization(structures, structure, table);
801     
802     if (table) {
803         PropertyMapEntry* entry = table->find(uid).first;
804         if (entry) {
805             attributes = entry->attributes;
806             specificValue = entry->specificValue.get();
807             PropertyOffset result = entry->offset;
808             structure->m_lock.unlock();
809             return result;
810         }
811         structure->m_lock.unlock();
812     }
813     
814     for (unsigned i = structures.size(); i--;) {
815         structure = structures[i];
816         if (structure->m_nameInPrevious.get() != uid)
817             continue;
818         
819         attributes = structure->m_attributesInPrevious;
820         specificValue = structure->m_specificValueInPrevious.get();
821         return structure->m_offset;
822     }
823     
824     return invalidOffset;
825 }
826
827 PropertyOffset Structure::get(VM& vm, PropertyName propertyName, unsigned& attributes, JSCell*& specificValue)
828 {
829     ASSERT(!isCompilationThread());
830     ASSERT(structure()->classInfo() == info());
831
832     materializePropertyMapIfNecessary(vm);
833     if (!propertyTable())
834         return invalidOffset;
835
836     PropertyMapEntry* entry = propertyTable()->find(propertyName.uid()).first;
837     if (!entry)
838         return invalidOffset;
839
840     attributes = entry->attributes;
841     specificValue = entry->specificValue.get();
842     return entry->offset;
843 }
844
845 bool Structure::despecifyFunction(VM& vm, PropertyName propertyName)
846 {
847     materializePropertyMapIfNecessary(vm);
848     if (!propertyTable())
849         return false;
850
851     PropertyMapEntry* entry = propertyTable()->find(propertyName.uid()).first;
852     if (!entry)
853         return false;
854
855     ASSERT(entry->specificValue);
856     entry->specificValue.clear();
857     return true;
858 }
859
860 void Structure::despecifyAllFunctions(VM& vm)
861 {
862     materializePropertyMapIfNecessary(vm);
863     if (!propertyTable())
864         return;
865
866     PropertyTable::iterator end = propertyTable()->end();
867     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter)
868         iter->specificValue.clear();
869 }
870
871 PropertyOffset Structure::putSpecificValue(VM& vm, PropertyName propertyName, unsigned attributes, JSCell* specificValue)
872 {
873     ConcurrentJITLocker locker(m_lock);
874     
875     ASSERT(!JSC::isValidOffset(get(vm, propertyName)));
876
877     checkConsistency();
878     if (attributes & DontEnum)
879         m_hasNonEnumerableProperties = true;
880
881     StringImpl* rep = propertyName.uid();
882
883     if (!propertyTable())
884         createPropertyMap(locker, vm);
885
886     PropertyOffset newOffset = propertyTable()->nextOffset(m_inlineCapacity);
887
888     propertyTable()->add(PropertyMapEntry(vm, this, rep, newOffset, attributes, specificValue), m_offset, PropertyTable::PropertyOffsetMayChange);
889     
890     checkConsistency();
891     return newOffset;
892 }
893
894 PropertyOffset Structure::remove(PropertyName propertyName)
895 {
896     ConcurrentJITLocker locker(m_lock);
897     
898     checkConsistency();
899
900     StringImpl* rep = propertyName.uid();
901
902     if (!propertyTable())
903         return invalidOffset;
904
905     PropertyTable::find_iterator position = propertyTable()->find(rep);
906     if (!position.first)
907         return invalidOffset;
908
909     PropertyOffset offset = position.first->offset;
910
911     propertyTable()->remove(position);
912     propertyTable()->addDeletedOffset(offset);
913
914     checkConsistency();
915     return offset;
916 }
917
918 void Structure::createPropertyMap(const ConcurrentJITLocker&, VM& vm, unsigned capacity)
919 {
920     ASSERT(!propertyTable());
921
922     checkConsistency();
923     propertyTable().set(vm, this, PropertyTable::create(vm, capacity));
924 }
925
926 void Structure::getPropertyNamesFromStructure(VM& vm, PropertyNameArray& propertyNames, EnumerationMode mode)
927 {
928     materializePropertyMapIfNecessary(vm);
929     if (!propertyTable())
930         return;
931
932     bool knownUnique = !propertyNames.size();
933
934     PropertyTable::iterator end = propertyTable()->end();
935     for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
936         ASSERT(m_hasNonEnumerableProperties || !(iter->attributes & DontEnum));
937         if (iter->key->isIdentifier() && (!(iter->attributes & DontEnum) || mode == IncludeDontEnumProperties)) {
938             if (knownUnique)
939                 propertyNames.addKnownUnique(iter->key);
940             else
941                 propertyNames.add(iter->key);
942         }
943     }
944 }
945
946 JSValue Structure::prototypeForLookup(CodeBlock* codeBlock) const
947 {
948     return prototypeForLookup(codeBlock->globalObject());
949 }
950
951 void Structure::visitChildren(JSCell* cell, SlotVisitor& visitor)
952 {
953     Structure* thisObject = jsCast<Structure*>(cell);
954     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
955     ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());
956
957     JSCell::visitChildren(thisObject, visitor);
958     visitor.append(&thisObject->m_globalObject);
959     if (!thisObject->isObject())
960         thisObject->m_cachedPrototypeChain.clear();
961     else {
962         visitor.append(&thisObject->m_prototype);
963         visitor.append(&thisObject->m_cachedPrototypeChain);
964     }
965     visitor.append(&thisObject->m_previousOrRareData);
966     visitor.append(&thisObject->m_specificValueInPrevious);
967
968     if (thisObject->m_isPinnedPropertyTable) {
969         ASSERT(thisObject->m_propertyTableUnsafe);
970         visitor.append(&thisObject->m_propertyTableUnsafe);
971     } else if (thisObject->m_propertyTableUnsafe)
972         thisObject->m_propertyTableUnsafe.clear();
973 }
974
975 bool Structure::prototypeChainMayInterceptStoreTo(VM& vm, PropertyName propertyName)
976 {
977     unsigned i = propertyName.asIndex();
978     if (i != PropertyName::NotAnIndex)
979         return anyObjectInChainMayInterceptIndexedAccesses();
980     
981     for (Structure* current = this; ;) {
982         JSValue prototype = current->storedPrototype();
983         if (prototype.isNull())
984             return false;
985         
986         current = prototype.asCell()->structure();
987         
988         unsigned attributes;
989         JSCell* specificValue;
990         PropertyOffset offset = current->get(vm, propertyName, attributes, specificValue);
991         if (!JSC::isValidOffset(offset))
992             continue;
993         
994         if (attributes & (ReadOnly | Accessor))
995             return true;
996         
997         return false;
998     }
999 }
1000
1001 void Structure::dump(PrintStream& out) const
1002 {
1003     out.print(RawPointer(this), ":[", classInfo()->className, ", {");
1004     
1005     Vector<Structure*, 8> structures;
1006     Structure* structure;
1007     PropertyTable* table;
1008     
1009     const_cast<Structure*>(this)->findStructuresAndMapForMaterialization(
1010         structures, structure, table);
1011     
1012     CommaPrinter comma;
1013     
1014     if (table) {
1015         PropertyTable::iterator iter = table->begin();
1016         PropertyTable::iterator end = table->end();
1017         for (; iter != end; ++iter)
1018             out.print(comma, iter->key, ":", static_cast<int>(iter->offset));
1019         
1020         structure->m_lock.unlock();
1021     }
1022     
1023     for (unsigned i = structures.size(); i--;) {
1024         Structure* structure = structures[i];
1025         if (!structure->m_nameInPrevious)
1026             continue;
1027         out.print(comma, structure->m_nameInPrevious.get(), ":", static_cast<int>(structure->m_offset));
1028     }
1029     
1030     out.print("}, ", IndexingTypeDump(indexingType()));
1031     
1032     if (m_prototype.get().isCell())
1033         out.print(", Proto:", RawPointer(m_prototype.get().asCell()));
1034     
1035     out.print("]");
1036 }
1037
1038 void Structure::dumpInContext(PrintStream& out, DumpContext* context) const
1039 {
1040     if (context)
1041         context->structures.dumpBrief(this, out);
1042     else
1043         dump(out);
1044 }
1045
1046 void Structure::dumpBrief(PrintStream& out, const CString& string) const
1047 {
1048     out.print("%", string, ":", classInfo()->className);
1049 }
1050
1051 void Structure::dumpContextHeader(PrintStream& out)
1052 {
1053     out.print("Structures:");
1054 }
1055
1056 #if DO_PROPERTYMAP_CONSTENCY_CHECK
1057
1058 void PropertyTable::checkConsistency()
1059 {
1060     checkOffsetConsistency();
1061     ASSERT(m_indexSize >= PropertyTable::MinimumTableSize);
1062     ASSERT(m_indexMask);
1063     ASSERT(m_indexSize == m_indexMask + 1);
1064     ASSERT(!(m_indexSize & m_indexMask));
1065
1066     ASSERT(m_keyCount <= m_indexSize / 2);
1067     ASSERT(m_keyCount + m_deletedCount <= m_indexSize / 2);
1068     ASSERT(m_deletedCount <= m_indexSize / 4);
1069
1070     unsigned indexCount = 0;
1071     unsigned deletedIndexCount = 0;
1072     for (unsigned a = 0; a != m_indexSize; ++a) {
1073         unsigned entryIndex = m_index[a];
1074         if (entryIndex == PropertyTable::EmptyEntryIndex)
1075             continue;
1076         if (entryIndex == deletedEntryIndex()) {
1077             ++deletedIndexCount;
1078             continue;
1079         }
1080         ASSERT(entryIndex < deletedEntryIndex());
1081         ASSERT(entryIndex - 1 <= usedCount());
1082         ++indexCount;
1083
1084         for (unsigned b = a + 1; b != m_indexSize; ++b)
1085             ASSERT(m_index[b] != entryIndex);
1086     }
1087     ASSERT(indexCount == m_keyCount);
1088     ASSERT(deletedIndexCount == m_deletedCount);
1089
1090     ASSERT(!table()[deletedEntryIndex() - 1].key);
1091
1092     unsigned nonEmptyEntryCount = 0;
1093     for (unsigned c = 0; c < usedCount(); ++c) {
1094         StringImpl* rep = table()[c].key;
1095         if (rep == PROPERTY_MAP_DELETED_ENTRY_KEY)
1096             continue;
1097         ++nonEmptyEntryCount;
1098         unsigned i = rep->existingHash();
1099         unsigned k = 0;
1100         unsigned entryIndex;
1101         while (1) {
1102             entryIndex = m_index[i & m_indexMask];
1103             ASSERT(entryIndex != PropertyTable::EmptyEntryIndex);
1104             if (rep == table()[entryIndex - 1].key)
1105                 break;
1106             if (k == 0)
1107                 k = 1 | doubleHash(rep->existingHash());
1108             i += k;
1109         }
1110         ASSERT(entryIndex == c + 1);
1111     }
1112
1113     ASSERT(nonEmptyEntryCount == m_keyCount);
1114 }
1115
1116 void Structure::checkConsistency()
1117 {
1118     if (!propertyTable())
1119         return;
1120
1121     if (!m_hasNonEnumerableProperties) {
1122         PropertyTable::iterator end = propertyTable()->end();
1123         for (PropertyTable::iterator iter = propertyTable()->begin(); iter != end; ++iter) {
1124             ASSERT(!(iter->attributes & DontEnum));
1125         }
1126     }
1127
1128     propertyTable()->checkConsistency();
1129 }
1130
1131 #endif // DO_PROPERTYMAP_CONSTENCY_CHECK
1132
1133 } // namespace JSC