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