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