PolymorphicAccess::regenerate() shouldn't have to clone non-generated AccessCases
[WebKit-https.git] / Source / JavaScriptCore / bytecode / PolymorphicAccess.cpp
1 /*
2  * Copyright (C) 2014-2016 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 "PolymorphicAccess.h"
28
29 #if ENABLE(JIT)
30
31 #include "BinarySwitch.h"
32 #include "CCallHelpers.h"
33 #include "CodeBlock.h"
34 #include "DirectArguments.h"
35 #include "GetterSetter.h"
36 #include "Heap.h"
37 #include "JITOperations.h"
38 #include "JSCInlines.h"
39 #include "LinkBuffer.h"
40 #include "ScopedArguments.h"
41 #include "ScratchRegisterAllocator.h"
42 #include "StructureStubClearingWatchpoint.h"
43 #include "StructureStubInfo.h"
44 #include <wtf/CommaPrinter.h>
45 #include <wtf/ListDump.h>
46
47 namespace JSC {
48
49 static const bool verbose = false;
50
51 // EncodedJSValue in JSVALUE32_64 is a 64-bit integer. When being compiled in ARM EABI, it must be aligned on an even-numbered register (r0, r2 or [sp]).
52 // To prevent the assembler from using wrong registers, let's occupy r1 or r3 with a dummy argument when necessary.
53 #if (COMPILER_SUPPORTS(EABI) && CPU(ARM)) || CPU(MIPS)
54 #define EABI_32BIT_DUMMY_ARG      CCallHelpers::TrustedImm32(0),
55 #else
56 #define EABI_32BIT_DUMMY_ARG
57 #endif
58
59 void AccessGenerationResult::dump(PrintStream& out) const
60 {
61     out.print(m_kind);
62     if (m_code)
63         out.print(":", m_code);
64 }
65
66 Watchpoint* AccessGenerationState::addWatchpoint(const ObjectPropertyCondition& condition)
67 {
68     return WatchpointsOnStructureStubInfo::ensureReferenceAndAddWatchpoint(
69         watchpoints, jit->codeBlock(), stubInfo, condition);
70 }
71
72 void AccessGenerationState::restoreScratch()
73 {
74     allocator->restoreReusedRegistersByPopping(*jit, preservedReusedRegisterState);
75 }
76
77 void AccessGenerationState::succeed()
78 {
79     restoreScratch();
80     success.append(jit->jump());
81 }
82
83 void AccessGenerationState::calculateLiveRegistersForCallAndExceptionHandling(const RegisterSet& extra)
84 {
85     if (!m_calculatedRegistersForCallAndExceptionHandling) {
86         m_calculatedRegistersForCallAndExceptionHandling = true;
87
88         m_liveRegistersToPreserveAtExceptionHandlingCallSite = jit->codeBlock()->jitCode()->liveRegistersToPreserveAtExceptionHandlingCallSite(jit->codeBlock(), stubInfo->callSiteIndex);
89         m_needsToRestoreRegistersIfException = m_liveRegistersToPreserveAtExceptionHandlingCallSite.numberOfSetRegisters() > 0;
90         if (m_needsToRestoreRegistersIfException)
91             RELEASE_ASSERT(JITCode::isOptimizingJIT(jit->codeBlock()->jitType()));
92
93         m_liveRegistersForCall = RegisterSet(m_liveRegistersToPreserveAtExceptionHandlingCallSite, allocator->usedRegisters());
94         m_liveRegistersForCall.merge(extra);
95         m_liveRegistersForCall.exclude(RegisterSet::registersToNotSaveForJSCall());
96         m_liveRegistersForCall.merge(extra);
97     }
98 }
99
100 void AccessGenerationState::preserveLiveRegistersToStackForCall(const RegisterSet& extra)
101 {
102     calculateLiveRegistersForCallAndExceptionHandling(extra);
103     
104     unsigned extraStackPadding = 0;
105     unsigned numberOfStackBytesUsedForRegisterPreservation = ScratchRegisterAllocator::preserveRegistersToStackForCall(*jit, liveRegistersForCall(), extraStackPadding);
106     if (m_numberOfStackBytesUsedForRegisterPreservation != std::numeric_limits<unsigned>::max())
107         RELEASE_ASSERT(numberOfStackBytesUsedForRegisterPreservation == m_numberOfStackBytesUsedForRegisterPreservation);
108     m_numberOfStackBytesUsedForRegisterPreservation = numberOfStackBytesUsedForRegisterPreservation;
109 }
110
111 void AccessGenerationState::restoreLiveRegistersFromStackForCall(bool isGetter)
112 {
113     RegisterSet dontRestore;
114     if (isGetter) {
115         // This is the result value. We don't want to overwrite the result with what we stored to the stack.
116         // We sometimes have to store it to the stack just in case we throw an exception and need the original value.
117         dontRestore.set(valueRegs);
118     }
119     restoreLiveRegistersFromStackForCall(dontRestore);
120 }
121
122 void AccessGenerationState::restoreLiveRegistersFromStackForCallWithThrownException()
123 {
124     // Even if we're a getter, we don't want to ignore the result value like we normally do
125     // because the getter threw, and therefore, didn't return a value that means anything.
126     // Instead, we want to restore that register to what it was upon entering the getter
127     // inline cache. The subtlety here is if the base and the result are the same register,
128     // and the getter threw, we want OSR exit to see the original base value, not the result
129     // of the getter call.
130     RegisterSet dontRestore = liveRegistersForCall();
131     // As an optimization here, we only need to restore what is live for exception handling.
132     // We can construct the dontRestore set to accomplish this goal by having it contain only
133     // what is live for call but not live for exception handling. By ignoring things that are
134     // only live at the call but not the exception handler, we will only restore things live
135     // at the exception handler.
136     dontRestore.exclude(liveRegistersToPreserveAtExceptionHandlingCallSite());
137     restoreLiveRegistersFromStackForCall(dontRestore);
138 }
139
140 void AccessGenerationState::restoreLiveRegistersFromStackForCall(const RegisterSet& dontRestore)
141 {
142     unsigned extraStackPadding = 0;
143     ScratchRegisterAllocator::restoreRegistersFromStackForCall(*jit, liveRegistersForCall(), dontRestore, m_numberOfStackBytesUsedForRegisterPreservation, extraStackPadding);
144 }
145
146 CallSiteIndex AccessGenerationState::callSiteIndexForExceptionHandlingOrOriginal()
147 {
148     RELEASE_ASSERT(m_calculatedRegistersForCallAndExceptionHandling);
149
150     if (!m_calculatedCallSiteIndex) {
151         m_calculatedCallSiteIndex = true;
152
153         if (m_needsToRestoreRegistersIfException)
154             m_callSiteIndex = jit->codeBlock()->newExceptionHandlingCallSiteIndex(stubInfo->callSiteIndex);
155         else
156             m_callSiteIndex = originalCallSiteIndex();
157     }
158
159     return m_callSiteIndex;
160 }
161
162 const HandlerInfo& AccessGenerationState::originalExceptionHandler() const
163 {
164     RELEASE_ASSERT(m_needsToRestoreRegistersIfException);
165     HandlerInfo* exceptionHandler = jit->codeBlock()->handlerForIndex(stubInfo->callSiteIndex.bits());
166     RELEASE_ASSERT(exceptionHandler);
167     return *exceptionHandler;
168 }
169
170 CallSiteIndex AccessGenerationState::originalCallSiteIndex() const { return stubInfo->callSiteIndex; }
171
172 void AccessGenerationState::emitExplicitExceptionHandler()
173 {
174     restoreScratch();
175     jit->copyCalleeSavesToVMCalleeSavesBuffer();
176     if (needsToRestoreRegistersIfException()) {
177         // To the JIT that produces the original exception handling
178         // call site, they will expect the OSR exit to be arrived
179         // at from genericUnwind. Therefore we must model what genericUnwind
180         // does here. I.e, set callFrameForCatch and copy callee saves.
181
182         jit->storePtr(GPRInfo::callFrameRegister, jit->vm()->addressOfCallFrameForCatch());
183         CCallHelpers::Jump jumpToOSRExitExceptionHandler = jit->jump();
184
185         // We don't need to insert a new exception handler in the table
186         // because we're doing a manual exception check here. i.e, we'll
187         // never arrive here from genericUnwind().
188         HandlerInfo originalHandler = originalExceptionHandler();
189         jit->addLinkTask(
190             [=] (LinkBuffer& linkBuffer) {
191                 linkBuffer.link(jumpToOSRExitExceptionHandler, originalHandler.nativeCode);
192             });
193     } else {
194         jit->setupArguments(CCallHelpers::TrustedImmPtr(jit->vm()), GPRInfo::callFrameRegister);
195         CCallHelpers::Call lookupExceptionHandlerCall = jit->call();
196         jit->addLinkTask(
197             [=] (LinkBuffer& linkBuffer) {
198                 linkBuffer.link(lookupExceptionHandlerCall, lookupExceptionHandler);
199             });
200         jit->jumpToExceptionHandler();
201     }
202 }
203
204 AccessCase::AccessCase()
205 {
206 }
207
208 std::unique_ptr<AccessCase> AccessCase::tryGet(
209     VM& vm, JSCell* owner, AccessType type, PropertyOffset offset, Structure* structure,
210     const ObjectPropertyConditionSet& conditionSet, bool viaProxy, WatchpointSet* additionalSet)
211 {
212     std::unique_ptr<AccessCase> result(new AccessCase());
213
214     result->m_type = type;
215     result->m_offset = offset;
216     result->m_structure.set(vm, owner, structure);
217     result->m_conditionSet = conditionSet;
218
219     if (viaProxy || additionalSet) {
220         result->m_rareData = std::make_unique<RareData>();
221         result->m_rareData->viaProxy = viaProxy;
222         result->m_rareData->additionalSet = additionalSet;
223     }
224
225     return result;
226 }
227
228 std::unique_ptr<AccessCase> AccessCase::get(
229     VM& vm, JSCell* owner, AccessType type, PropertyOffset offset, Structure* structure,
230     const ObjectPropertyConditionSet& conditionSet, bool viaProxy, WatchpointSet* additionalSet,
231     PropertySlot::GetValueFunc customGetter, JSObject* customSlotBase)
232 {
233     std::unique_ptr<AccessCase> result(new AccessCase());
234
235     result->m_type = type;
236     result->m_offset = offset;
237     result->m_structure.set(vm, owner, structure);
238     result->m_conditionSet = conditionSet;
239
240     if (viaProxy || additionalSet || result->doesCalls() || customGetter || customSlotBase) {
241         result->m_rareData = std::make_unique<RareData>();
242         result->m_rareData->viaProxy = viaProxy;
243         result->m_rareData->additionalSet = additionalSet;
244         result->m_rareData->customAccessor.getter = customGetter;
245         result->m_rareData->customSlotBase.setMayBeNull(vm, owner, customSlotBase);
246     }
247
248     return result;
249 }
250
251 std::unique_ptr<AccessCase> AccessCase::megamorphicLoad(VM& vm, JSCell* owner)
252 {
253     UNUSED_PARAM(vm);
254     UNUSED_PARAM(owner);
255     
256     if (GPRInfo::numberOfRegisters < 9)
257         return nullptr;
258     
259     std::unique_ptr<AccessCase> result(new AccessCase());
260     
261     result->m_type = MegamorphicLoad;
262     
263     return result;
264 }
265
266 std::unique_ptr<AccessCase> AccessCase::replace(
267     VM& vm, JSCell* owner, Structure* structure, PropertyOffset offset)
268 {
269     std::unique_ptr<AccessCase> result(new AccessCase());
270
271     result->m_type = Replace;
272     result->m_offset = offset;
273     result->m_structure.set(vm, owner, structure);
274
275     return result;
276 }
277
278 std::unique_ptr<AccessCase> AccessCase::transition(
279     VM& vm, JSCell* owner, Structure* oldStructure, Structure* newStructure, PropertyOffset offset,
280     const ObjectPropertyConditionSet& conditionSet)
281 {
282     RELEASE_ASSERT(oldStructure == newStructure->previousID());
283
284     // Skip optimizing the case where we need a realloc, if we don't have
285     // enough registers to make it happen.
286     if (GPRInfo::numberOfRegisters < 6
287         && oldStructure->outOfLineCapacity() != newStructure->outOfLineCapacity()
288         && oldStructure->outOfLineCapacity()) {
289         return nullptr;
290     }
291
292     std::unique_ptr<AccessCase> result(new AccessCase());
293
294     result->m_type = Transition;
295     result->m_offset = offset;
296     result->m_structure.set(vm, owner, newStructure);
297     result->m_conditionSet = conditionSet;
298
299     return result;
300 }
301
302 std::unique_ptr<AccessCase> AccessCase::setter(
303     VM& vm, JSCell* owner, AccessType type, Structure* structure, PropertyOffset offset,
304     const ObjectPropertyConditionSet& conditionSet, PutPropertySlot::PutValueFunc customSetter,
305     JSObject* customSlotBase)
306 {
307     std::unique_ptr<AccessCase> result(new AccessCase());
308
309     result->m_type = type;
310     result->m_offset = offset;
311     result->m_structure.set(vm, owner, structure);
312     result->m_conditionSet = conditionSet;
313     result->m_rareData = std::make_unique<RareData>();
314     result->m_rareData->customAccessor.setter = customSetter;
315     result->m_rareData->customSlotBase.setMayBeNull(vm, owner, customSlotBase);
316
317     return result;
318 }
319
320 std::unique_ptr<AccessCase> AccessCase::in(
321     VM& vm, JSCell* owner, AccessType type, Structure* structure,
322     const ObjectPropertyConditionSet& conditionSet)
323 {
324     std::unique_ptr<AccessCase> result(new AccessCase());
325
326     result->m_type = type;
327     result->m_structure.set(vm, owner, structure);
328     result->m_conditionSet = conditionSet;
329
330     return result;
331 }
332
333 std::unique_ptr<AccessCase> AccessCase::getLength(VM&, JSCell*, AccessType type)
334 {
335     std::unique_ptr<AccessCase> result(new AccessCase());
336
337     result->m_type = type;
338
339     return result;
340 }
341
342 std::unique_ptr<AccessCase> AccessCase::getIntrinsic(
343     VM& vm, JSCell* owner, JSFunction* getter, PropertyOffset offset,
344     Structure* structure, const ObjectPropertyConditionSet& conditionSet)
345 {
346     std::unique_ptr<AccessCase> result(new AccessCase());
347
348     result->m_type = IntrinsicGetter;
349     result->m_structure.set(vm, owner, structure);
350     result->m_conditionSet = conditionSet;
351     result->m_offset = offset;
352
353     result->m_rareData = std::make_unique<RareData>();
354     result->m_rareData->intrinsicFunction.set(vm, owner, getter);
355
356     return result;
357 }
358
359 AccessCase::~AccessCase()
360 {
361 }
362
363 std::unique_ptr<AccessCase> AccessCase::fromStructureStubInfo(
364     VM& vm, JSCell* owner, StructureStubInfo& stubInfo)
365 {
366     switch (stubInfo.cacheType) {
367     case CacheType::GetByIdSelf:
368         return get(
369             vm, owner, Load, stubInfo.u.byIdSelf.offset,
370             stubInfo.u.byIdSelf.baseObjectStructure.get());
371
372     case CacheType::PutByIdReplace:
373         return replace(
374             vm, owner, stubInfo.u.byIdSelf.baseObjectStructure.get(), stubInfo.u.byIdSelf.offset);
375
376     default:
377         return nullptr;
378     }
379 }
380
381 std::unique_ptr<AccessCase> AccessCase::clone() const
382 {
383     std::unique_ptr<AccessCase> result(new AccessCase());
384     result->m_type = m_type;
385     result->m_offset = m_offset;
386     result->m_structure = m_structure;
387     result->m_conditionSet = m_conditionSet;
388     if (RareData* rareData = m_rareData.get()) {
389         result->m_rareData = std::make_unique<RareData>();
390         result->m_rareData->viaProxy = rareData->viaProxy;
391         result->m_rareData->additionalSet = rareData->additionalSet;
392         // NOTE: We don't copy the callLinkInfo, since that's created during code generation.
393         result->m_rareData->customAccessor.opaque = rareData->customAccessor.opaque;
394         result->m_rareData->customSlotBase = rareData->customSlotBase;
395         result->m_rareData->intrinsicFunction = rareData->intrinsicFunction;
396     }
397     return result;
398 }
399
400 Vector<WatchpointSet*, 2> AccessCase::commit(VM& vm, const Identifier& ident)
401 {
402     // It's fine to commit something that is already committed. That arises when we switch to using
403     // newly allocated watchpoints. When it happens, it's not efficient - but we think that's OK
404     // because most AccessCases have no extra watchpoints anyway.
405     RELEASE_ASSERT(m_state == Primordial || m_state == Committed);
406     
407     Vector<WatchpointSet*, 2> result;
408     
409     if ((structure() && structure()->needImpurePropertyWatchpoint())
410         || m_conditionSet.needImpurePropertyWatchpoint())
411         result.append(vm.ensureWatchpointSetForImpureProperty(ident));
412
413     if (additionalSet())
414         result.append(additionalSet());
415     
416     m_state = Committed;
417     
418     return result;
419 }
420
421 bool AccessCase::guardedByStructureCheck() const
422 {
423     if (viaProxy())
424         return false;
425
426     switch (m_type) {
427     case MegamorphicLoad:
428     case ArrayLength:
429     case StringLength:
430     case DirectArgumentsLength:
431     case ScopedArgumentsLength:
432         return false;
433     default:
434         return true;
435     }
436 }
437
438 JSObject* AccessCase::alternateBase() const
439 {
440     if (customSlotBase())
441         return customSlotBase();
442     return conditionSet().slotBaseCondition().object();
443 }
444
445 bool AccessCase::doesCalls(Vector<JSCell*>* cellsToMark) const
446 {
447     switch (type()) {
448     case Getter:
449     case Setter:
450     case CustomValueGetter:
451     case CustomAccessorGetter:
452     case CustomValueSetter:
453     case CustomAccessorSetter:
454         return true;
455     case Transition:
456         if (newStructure()->outOfLineCapacity() != structure()->outOfLineCapacity()
457             && structure()->couldHaveIndexingHeader()) {
458             if (cellsToMark)
459                 cellsToMark->append(newStructure());
460             return true;
461         }
462         return false;
463     default:
464         return false;
465     }
466 }
467
468 bool AccessCase::couldStillSucceed() const
469 {
470     return m_conditionSet.structuresEnsureValidityAssumingImpurePropertyWatchpoint();
471 }
472
473 bool AccessCase::canBeReplacedByMegamorphicLoad() const
474 {
475     return type() == Load
476         && !viaProxy()
477         && conditionSet().isEmpty()
478         && !additionalSet()
479         && !customSlotBase();
480 }
481
482 bool AccessCase::canReplace(const AccessCase& other) const
483 {
484     // We could do a lot better here, but for now we just do something obvious.
485     
486     if (type() == MegamorphicLoad && other.canBeReplacedByMegamorphicLoad())
487         return true;
488
489     if (!guardedByStructureCheck() || !other.guardedByStructureCheck()) {
490         // FIXME: Implement this!
491         return false;
492     }
493
494     return structure() == other.structure();
495 }
496
497 void AccessCase::dump(PrintStream& out) const
498 {
499     out.print(m_type, ":(");
500
501     CommaPrinter comma;
502     
503     out.print(comma, m_state);
504
505     if (m_type == Transition)
506         out.print(comma, "structure = ", pointerDump(structure()), " -> ", pointerDump(newStructure()));
507     else if (m_structure)
508         out.print(comma, "structure = ", pointerDump(m_structure.get()));
509
510     if (isValidOffset(m_offset))
511         out.print(comma, "offset = ", m_offset);
512     if (!m_conditionSet.isEmpty())
513         out.print(comma, "conditions = ", m_conditionSet);
514
515     if (RareData* rareData = m_rareData.get()) {
516         if (rareData->viaProxy)
517             out.print(comma, "viaProxy = ", rareData->viaProxy);
518         if (rareData->additionalSet)
519             out.print(comma, "additionalSet = ", RawPointer(rareData->additionalSet.get()));
520         if (rareData->callLinkInfo)
521             out.print(comma, "callLinkInfo = ", RawPointer(rareData->callLinkInfo.get()));
522         if (rareData->customAccessor.opaque)
523             out.print(comma, "customAccessor = ", RawPointer(rareData->customAccessor.opaque));
524         if (rareData->customSlotBase)
525             out.print(comma, "customSlotBase = ", RawPointer(rareData->customSlotBase.get()));
526     }
527
528     out.print(")");
529 }
530
531 bool AccessCase::visitWeak(VM& vm) const
532 {
533     if (m_structure && !Heap::isMarked(m_structure.get()))
534         return false;
535     if (!m_conditionSet.areStillLive())
536         return false;
537     if (m_rareData) {
538         if (m_rareData->callLinkInfo)
539             m_rareData->callLinkInfo->visitWeak(vm);
540         if (m_rareData->customSlotBase && !Heap::isMarked(m_rareData->customSlotBase.get()))
541             return false;
542         if (m_rareData->intrinsicFunction && !Heap::isMarked(m_rareData->intrinsicFunction.get()))
543             return false;
544     }
545     return true;
546 }
547
548 void AccessCase::generateWithGuard(
549     AccessGenerationState& state, CCallHelpers::JumpList& fallThrough)
550 {
551     SuperSamplerScope superSamplerScope(false);
552
553     RELEASE_ASSERT(m_state == Committed);
554     m_state = Generated;
555     
556     CCallHelpers& jit = *state.jit;
557     VM& vm = *jit.vm();
558     const Identifier& ident = *state.ident;
559     StructureStubInfo& stubInfo = *state.stubInfo;
560     JSValueRegs valueRegs = state.valueRegs;
561     GPRReg baseGPR = state.baseGPR;
562     GPRReg scratchGPR = state.scratchGPR;
563     
564     UNUSED_PARAM(vm);
565
566     switch (m_type) {
567     case ArrayLength: {
568         ASSERT(!viaProxy());
569         jit.load8(CCallHelpers::Address(baseGPR, JSCell::indexingTypeOffset()), scratchGPR);
570         fallThrough.append(
571             jit.branchTest32(
572                 CCallHelpers::Zero, scratchGPR, CCallHelpers::TrustedImm32(IsArray)));
573         fallThrough.append(
574             jit.branchTest32(
575                 CCallHelpers::Zero, scratchGPR, CCallHelpers::TrustedImm32(IndexingShapeMask)));
576         break;
577     }
578
579     case StringLength: {
580         ASSERT(!viaProxy());
581         fallThrough.append(
582             jit.branch8(
583                 CCallHelpers::NotEqual,
584                 CCallHelpers::Address(baseGPR, JSCell::typeInfoTypeOffset()),
585                 CCallHelpers::TrustedImm32(StringType)));
586         break;
587     }
588         
589     case DirectArgumentsLength: {
590         ASSERT(!viaProxy());
591         fallThrough.append(
592             jit.branch8(
593                 CCallHelpers::NotEqual,
594                 CCallHelpers::Address(baseGPR, JSCell::typeInfoTypeOffset()),
595                 CCallHelpers::TrustedImm32(DirectArgumentsType)));
596
597         fallThrough.append(
598             jit.branchTestPtr(
599                 CCallHelpers::NonZero,
600                 CCallHelpers::Address(baseGPR, DirectArguments::offsetOfOverrides())));
601         jit.load32(
602             CCallHelpers::Address(baseGPR, DirectArguments::offsetOfLength()),
603             valueRegs.payloadGPR());
604         jit.boxInt32(valueRegs.payloadGPR(), valueRegs, CCallHelpers::DoNotHaveTagRegisters);
605         state.succeed();
606         return;
607     }
608         
609     case ScopedArgumentsLength: {
610         ASSERT(!viaProxy());
611         fallThrough.append(
612             jit.branch8(
613                 CCallHelpers::NotEqual,
614                 CCallHelpers::Address(baseGPR, JSCell::typeInfoTypeOffset()),
615                 CCallHelpers::TrustedImm32(ScopedArgumentsType)));
616
617         fallThrough.append(
618             jit.branchTest8(
619                 CCallHelpers::NonZero,
620                 CCallHelpers::Address(baseGPR, ScopedArguments::offsetOfOverrodeThings())));
621         jit.load32(
622             CCallHelpers::Address(baseGPR, ScopedArguments::offsetOfTotalLength()),
623             valueRegs.payloadGPR());
624         jit.boxInt32(valueRegs.payloadGPR(), valueRegs, CCallHelpers::DoNotHaveTagRegisters);
625         state.succeed();
626         return;
627     }
628         
629     case MegamorphicLoad: {
630         UniquedStringImpl* key = ident.impl();
631         unsigned hash = IdentifierRepHash::hash(key);
632         
633         ScratchRegisterAllocator allocator(stubInfo.patch.usedRegisters);
634         allocator.lock(baseGPR);
635 #if USE(JSVALUE32_64)
636         allocator.lock(static_cast<GPRReg>(stubInfo.patch.baseTagGPR));
637 #endif
638         allocator.lock(valueRegs);
639         allocator.lock(scratchGPR);
640         
641         GPRReg intermediateGPR = scratchGPR;
642         GPRReg maskGPR = allocator.allocateScratchGPR();
643         GPRReg maskedHashGPR = allocator.allocateScratchGPR();
644         GPRReg indexGPR = allocator.allocateScratchGPR();
645         GPRReg offsetGPR = allocator.allocateScratchGPR();
646         
647         if (verbose) {
648             dataLog("baseGPR = ", baseGPR, "\n");
649             dataLog("valueRegs = ", valueRegs, "\n");
650             dataLog("scratchGPR = ", scratchGPR, "\n");
651             dataLog("intermediateGPR = ", intermediateGPR, "\n");
652             dataLog("maskGPR = ", maskGPR, "\n");
653             dataLog("maskedHashGPR = ", maskedHashGPR, "\n");
654             dataLog("indexGPR = ", indexGPR, "\n");
655             dataLog("offsetGPR = ", offsetGPR, "\n");
656         }
657
658         ScratchRegisterAllocator::PreservedState preservedState =
659             allocator.preserveReusedRegistersByPushing(jit, ScratchRegisterAllocator::ExtraStackSpace::SpaceForCCall);
660
661         CCallHelpers::JumpList myFailAndIgnore;
662         CCallHelpers::JumpList myFallThrough;
663         
664         jit.emitLoadStructure(baseGPR, intermediateGPR, maskGPR);
665         jit.loadPtr(
666             CCallHelpers::Address(intermediateGPR, Structure::propertyTableUnsafeOffset()),
667             intermediateGPR);
668         
669         myFailAndIgnore.append(jit.branchTestPtr(CCallHelpers::Zero, intermediateGPR));
670         
671         jit.load32(CCallHelpers::Address(intermediateGPR, PropertyTable::offsetOfIndexMask()), maskGPR);
672         jit.loadPtr(CCallHelpers::Address(intermediateGPR, PropertyTable::offsetOfIndex()), indexGPR);
673         jit.load32(
674             CCallHelpers::Address(intermediateGPR, PropertyTable::offsetOfIndexSize()),
675             intermediateGPR);
676
677         jit.move(maskGPR, maskedHashGPR);
678         jit.and32(CCallHelpers::TrustedImm32(hash), maskedHashGPR);
679         jit.lshift32(CCallHelpers::TrustedImm32(2), intermediateGPR);
680         jit.addPtr(indexGPR, intermediateGPR);
681         
682         CCallHelpers::Label loop = jit.label();
683         
684         jit.load32(CCallHelpers::BaseIndex(indexGPR, maskedHashGPR, CCallHelpers::TimesFour), offsetGPR);
685         
686         myFallThrough.append(
687             jit.branch32(
688                 CCallHelpers::Equal,
689                 offsetGPR,
690                 CCallHelpers::TrustedImm32(PropertyTable::EmptyEntryIndex)));
691         
692         jit.sub32(CCallHelpers::TrustedImm32(1), offsetGPR);
693         jit.mul32(CCallHelpers::TrustedImm32(sizeof(PropertyMapEntry)), offsetGPR, offsetGPR);
694         jit.addPtr(intermediateGPR, offsetGPR);
695         
696         CCallHelpers::Jump collision =  jit.branchPtr(
697             CCallHelpers::NotEqual,
698             CCallHelpers::Address(offsetGPR, OBJECT_OFFSETOF(PropertyMapEntry, key)),
699             CCallHelpers::TrustedImmPtr(key));
700         
701         // offsetGPR currently holds a pointer to the PropertyMapEntry, which has the offset and attributes.
702         // Check them and then attempt the load.
703         
704         myFallThrough.append(
705             jit.branchTest32(
706                 CCallHelpers::NonZero,
707                 CCallHelpers::Address(offsetGPR, OBJECT_OFFSETOF(PropertyMapEntry, attributes)),
708                 CCallHelpers::TrustedImm32(Accessor | CustomAccessor)));
709         
710         jit.load32(CCallHelpers::Address(offsetGPR, OBJECT_OFFSETOF(PropertyMapEntry, offset)), offsetGPR);
711         
712         jit.loadProperty(baseGPR, offsetGPR, valueRegs);
713         
714         allocator.restoreReusedRegistersByPopping(jit, preservedState);
715         state.succeed();
716         
717         collision.link(&jit);
718
719         jit.add32(CCallHelpers::TrustedImm32(1), maskedHashGPR);
720         
721         // FIXME: We could be smarter about this. Currently we're burning a GPR for the mask. But looping
722         // around isn't super common so we could, for example, recompute the mask from the difference between
723         // the table and index. But before we do that we should probably make it easier to multiply and
724         // divide by the size of PropertyMapEntry. That probably involves making PropertyMapEntry be arranged
725         // to have a power-of-2 size.
726         jit.and32(maskGPR, maskedHashGPR);
727         jit.jump().linkTo(loop, &jit);
728         
729         if (allocator.didReuseRegisters()) {
730             myFailAndIgnore.link(&jit);
731             allocator.restoreReusedRegistersByPopping(jit, preservedState);
732             state.failAndIgnore.append(jit.jump());
733             
734             myFallThrough.link(&jit);
735             allocator.restoreReusedRegistersByPopping(jit, preservedState);
736             fallThrough.append(jit.jump());
737         } else {
738             state.failAndIgnore.append(myFailAndIgnore);
739             fallThrough.append(myFallThrough);
740         }
741         return;
742     }
743
744     default: {
745         if (viaProxy()) {
746             fallThrough.append(
747                 jit.branch8(
748                     CCallHelpers::NotEqual,
749                     CCallHelpers::Address(baseGPR, JSCell::typeInfoTypeOffset()),
750                     CCallHelpers::TrustedImm32(PureForwardingProxyType)));
751
752             jit.loadPtr(CCallHelpers::Address(baseGPR, JSProxy::targetOffset()), scratchGPR);
753
754             fallThrough.append(
755                 jit.branchStructure(
756                     CCallHelpers::NotEqual,
757                     CCallHelpers::Address(scratchGPR, JSCell::structureIDOffset()),
758                     structure()));
759         } else {
760             fallThrough.append(
761                 jit.branchStructure(
762                     CCallHelpers::NotEqual,
763                     CCallHelpers::Address(baseGPR, JSCell::structureIDOffset()),
764                     structure()));
765         }
766         break;
767     } };
768
769     generateImpl(state);
770 }
771
772 void AccessCase::generate(AccessGenerationState& state)
773 {
774     RELEASE_ASSERT(m_state == Committed);
775     m_state = Generated;
776     
777     generateImpl(state);
778 }
779
780 void AccessCase::generateImpl(AccessGenerationState& state)
781 {
782     SuperSamplerScope superSamplerScope(false);
783     if (verbose)
784         dataLog("Generating code for: ", *this, "\n");
785     
786     ASSERT(m_state == Generated); // We rely on the callers setting this for us.
787     
788     CCallHelpers& jit = *state.jit;
789     VM& vm = *jit.vm();
790     CodeBlock* codeBlock = jit.codeBlock();
791     StructureStubInfo& stubInfo = *state.stubInfo;
792     const Identifier& ident = *state.ident;
793     JSValueRegs valueRegs = state.valueRegs;
794     GPRReg baseGPR = state.baseGPR;
795     GPRReg scratchGPR = state.scratchGPR;
796
797     ASSERT(m_conditionSet.structuresEnsureValidityAssumingImpurePropertyWatchpoint());
798
799     for (const ObjectPropertyCondition& condition : m_conditionSet) {
800         Structure* structure = condition.object()->structure();
801
802         if (condition.isWatchableAssumingImpurePropertyWatchpoint()) {
803             structure->addTransitionWatchpoint(state.addWatchpoint(condition));
804             continue;
805         }
806
807         if (!condition.structureEnsuresValidityAssumingImpurePropertyWatchpoint(structure)) {
808             // The reason why this cannot happen is that we require that PolymorphicAccess calls
809             // AccessCase::generate() only after it has verified that
810             // AccessCase::couldStillSucceed() returned true.
811             
812             dataLog("This condition is no longer met: ", condition, "\n");
813             RELEASE_ASSERT_NOT_REACHED();
814         }
815
816         // We will emit code that has a weak reference that isn't otherwise listed anywhere.
817         state.weakReferences.append(WriteBarrier<JSCell>(vm, codeBlock, structure));
818         
819         jit.move(CCallHelpers::TrustedImmPtr(condition.object()), scratchGPR);
820         state.failAndRepatch.append(
821             jit.branchStructure(
822                 CCallHelpers::NotEqual,
823                 CCallHelpers::Address(scratchGPR, JSCell::structureIDOffset()),
824                 structure));
825     }
826
827     switch (m_type) {
828     case InHit:
829     case InMiss:
830         jit.boxBooleanPayload(m_type == InHit, valueRegs.payloadGPR());
831         state.succeed();
832         return;
833
834     case Miss:
835         jit.moveTrustedValue(jsUndefined(), valueRegs);
836         state.succeed();
837         return;
838
839     case Load:
840     case GetGetter:
841     case Getter:
842     case Setter:
843     case CustomValueGetter:
844     case CustomAccessorGetter:
845     case CustomValueSetter:
846     case CustomAccessorSetter: {
847         if (isValidOffset(m_offset)) {
848             Structure* currStructure;
849             if (m_conditionSet.isEmpty())
850                 currStructure = structure();
851             else
852                 currStructure = m_conditionSet.slotBaseCondition().object()->structure();
853             currStructure->startWatchingPropertyForReplacements(vm, offset());
854         }
855
856         GPRReg baseForGetGPR;
857         if (viaProxy()) {
858             baseForGetGPR = valueRegs.payloadGPR();
859             jit.loadPtr(
860                 CCallHelpers::Address(baseGPR, JSProxy::targetOffset()),
861                 baseForGetGPR);
862         } else
863             baseForGetGPR = baseGPR;
864
865         GPRReg baseForAccessGPR;
866         if (!m_conditionSet.isEmpty()) {
867             jit.move(
868                 CCallHelpers::TrustedImmPtr(alternateBase()),
869                 scratchGPR);
870             baseForAccessGPR = scratchGPR;
871         } else
872             baseForAccessGPR = baseForGetGPR;
873
874         GPRReg loadedValueGPR = InvalidGPRReg;
875         if (m_type != CustomValueGetter && m_type != CustomAccessorGetter && m_type != CustomValueSetter && m_type != CustomAccessorSetter) {
876             if (m_type == Load || m_type == GetGetter)
877                 loadedValueGPR = valueRegs.payloadGPR();
878             else
879                 loadedValueGPR = scratchGPR;
880
881             GPRReg storageGPR;
882             if (isInlineOffset(m_offset))
883                 storageGPR = baseForAccessGPR;
884             else {
885                 jit.loadPtr(
886                     CCallHelpers::Address(baseForAccessGPR, JSObject::butterflyOffset()),
887                     loadedValueGPR);
888                 storageGPR = loadedValueGPR;
889             }
890
891 #if USE(JSVALUE64)
892             jit.load64(
893                 CCallHelpers::Address(storageGPR, offsetRelativeToBase(m_offset)), loadedValueGPR);
894 #else
895             if (m_type == Load || m_type == GetGetter) {
896                 jit.load32(
897                     CCallHelpers::Address(storageGPR, offsetRelativeToBase(m_offset) + TagOffset),
898                     valueRegs.tagGPR());
899             }
900             jit.load32(
901                 CCallHelpers::Address(storageGPR, offsetRelativeToBase(m_offset) + PayloadOffset),
902                 loadedValueGPR);
903 #endif
904         }
905
906         if (m_type == Load || m_type == GetGetter) {
907             state.succeed();
908             return;
909         }
910
911         // Stuff for custom getters/setters.
912         CCallHelpers::Call operationCall;
913
914         // Stuff for JS getters/setters.
915         CCallHelpers::DataLabelPtr addressOfLinkFunctionCheck;
916         CCallHelpers::Call fastPathCall;
917         CCallHelpers::Call slowPathCall;
918
919         CCallHelpers::Jump success;
920         CCallHelpers::Jump fail;
921
922         // This also does the necessary calculations of whether or not we're an
923         // exception handling call site.
924         state.preserveLiveRegistersToStackForCall();
925
926         jit.store32(
927             CCallHelpers::TrustedImm32(state.callSiteIndexForExceptionHandlingOrOriginal().bits()),
928             CCallHelpers::tagFor(static_cast<VirtualRegister>(JSStack::ArgumentCount)));
929
930         if (m_type == Getter || m_type == Setter) {
931             // Create a JS call using a JS call inline cache. Assume that:
932             //
933             // - SP is aligned and represents the extent of the calling compiler's stack usage.
934             //
935             // - FP is set correctly (i.e. it points to the caller's call frame header).
936             //
937             // - SP - FP is an aligned difference.
938             //
939             // - Any byte between FP (exclusive) and SP (inclusive) could be live in the calling
940             //   code.
941             //
942             // Therefore, we temporarily grow the stack for the purpose of the call and then
943             // shrink it after.
944
945             RELEASE_ASSERT(!m_rareData->callLinkInfo);
946             m_rareData->callLinkInfo = std::make_unique<CallLinkInfo>();
947             
948             // FIXME: If we generated a polymorphic call stub that jumped back to the getter
949             // stub, which then jumped back to the main code, then we'd have a reachability
950             // situation that the GC doesn't know about. The GC would ensure that the polymorphic
951             // call stub stayed alive, and it would ensure that the main code stayed alive, but
952             // it wouldn't know that the getter stub was alive. Ideally JIT stub routines would
953             // be GC objects, and then we'd be able to say that the polymorphic call stub has a
954             // reference to the getter stub.
955             // https://bugs.webkit.org/show_bug.cgi?id=148914
956             m_rareData->callLinkInfo->disallowStubs();
957             
958             m_rareData->callLinkInfo->setUpCall(
959                 CallLinkInfo::Call, stubInfo.codeOrigin, loadedValueGPR);
960
961             CCallHelpers::JumpList done;
962
963             // There is a "this" argument.
964             unsigned numberOfParameters = 1;
965             // ... and a value argument if we're calling a setter.
966             if (m_type == Setter)
967                 numberOfParameters++;
968
969             // Get the accessor; if there ain't one then the result is jsUndefined().
970             if (m_type == Setter) {
971                 jit.loadPtr(
972                     CCallHelpers::Address(loadedValueGPR, GetterSetter::offsetOfSetter()),
973                     loadedValueGPR);
974             } else {
975                 jit.loadPtr(
976                     CCallHelpers::Address(loadedValueGPR, GetterSetter::offsetOfGetter()),
977                     loadedValueGPR);
978             }
979
980             CCallHelpers::Jump returnUndefined = jit.branchTestPtr(
981                 CCallHelpers::Zero, loadedValueGPR);
982
983             unsigned numberOfRegsForCall = JSStack::CallFrameHeaderSize + numberOfParameters;
984
985             unsigned numberOfBytesForCall =
986                 numberOfRegsForCall * sizeof(Register) + sizeof(CallerFrameAndPC);
987
988             unsigned alignedNumberOfBytesForCall =
989                 WTF::roundUpToMultipleOf(stackAlignmentBytes(), numberOfBytesForCall);
990
991             jit.subPtr(
992                 CCallHelpers::TrustedImm32(alignedNumberOfBytesForCall),
993                 CCallHelpers::stackPointerRegister);
994
995             CCallHelpers::Address calleeFrame = CCallHelpers::Address(
996                 CCallHelpers::stackPointerRegister,
997                 -static_cast<ptrdiff_t>(sizeof(CallerFrameAndPC)));
998
999             jit.store32(
1000                 CCallHelpers::TrustedImm32(numberOfParameters),
1001                 calleeFrame.withOffset(JSStack::ArgumentCount * sizeof(Register) + PayloadOffset));
1002
1003             jit.storeCell(
1004                 loadedValueGPR, calleeFrame.withOffset(JSStack::Callee * sizeof(Register)));
1005
1006             jit.storeCell(
1007                 baseForGetGPR,
1008                 calleeFrame.withOffset(virtualRegisterForArgument(0).offset() * sizeof(Register)));
1009
1010             if (m_type == Setter) {
1011                 jit.storeValue(
1012                     valueRegs,
1013                     calleeFrame.withOffset(
1014                         virtualRegisterForArgument(1).offset() * sizeof(Register)));
1015             }
1016
1017             CCallHelpers::Jump slowCase = jit.branchPtrWithPatch(
1018                 CCallHelpers::NotEqual, loadedValueGPR, addressOfLinkFunctionCheck,
1019                 CCallHelpers::TrustedImmPtr(0));
1020
1021             fastPathCall = jit.nearCall();
1022             if (m_type == Getter)
1023                 jit.setupResults(valueRegs);
1024             done.append(jit.jump());
1025
1026             slowCase.link(&jit);
1027             jit.move(loadedValueGPR, GPRInfo::regT0);
1028 #if USE(JSVALUE32_64)
1029             // We *always* know that the getter/setter, if non-null, is a cell.
1030             jit.move(CCallHelpers::TrustedImm32(JSValue::CellTag), GPRInfo::regT1);
1031 #endif
1032             jit.move(CCallHelpers::TrustedImmPtr(m_rareData->callLinkInfo.get()), GPRInfo::regT2);
1033             slowPathCall = jit.nearCall();
1034             if (m_type == Getter)
1035                 jit.setupResults(valueRegs);
1036             done.append(jit.jump());
1037
1038             returnUndefined.link(&jit);
1039             if (m_type == Getter)
1040                 jit.moveTrustedValue(jsUndefined(), valueRegs);
1041
1042             done.link(&jit);
1043
1044             jit.addPtr(CCallHelpers::TrustedImm32((codeBlock->stackPointerOffset() * sizeof(Register)) - state.preservedReusedRegisterState.numberOfBytesPreserved - state.numberOfStackBytesUsedForRegisterPreservation()),
1045                 GPRInfo::callFrameRegister, CCallHelpers::stackPointerRegister);
1046             state.restoreLiveRegistersFromStackForCall(isGetter());
1047
1048             jit.addLinkTask(
1049                 [=, &vm] (LinkBuffer& linkBuffer) {
1050                     m_rareData->callLinkInfo->setCallLocations(
1051                         linkBuffer.locationOfNearCall(slowPathCall),
1052                         linkBuffer.locationOf(addressOfLinkFunctionCheck),
1053                         linkBuffer.locationOfNearCall(fastPathCall));
1054
1055                     linkBuffer.link(
1056                         slowPathCall,
1057                         CodeLocationLabel(vm.getCTIStub(linkCallThunkGenerator).code()));
1058                 });
1059         } else {
1060             // Need to make room for the C call so any of our stack spillage isn't overwritten. It's
1061             // hard to track if someone did spillage or not, so we just assume that we always need
1062             // to make some space here.
1063             jit.makeSpaceOnStackForCCall();
1064
1065             // getter: EncodedJSValue (*GetValueFunc)(ExecState*, EncodedJSValue thisValue, PropertyName);
1066             // setter: void (*PutValueFunc)(ExecState*, EncodedJSValue thisObject, EncodedJSValue value);
1067             // Custom values are passed the slotBase (the property holder), custom accessors are passed the thisVaule (reciever).
1068             GPRReg baseForCustomValue = m_type == CustomValueGetter || m_type == CustomValueSetter ? baseForAccessGPR : baseForGetGPR;
1069 #if USE(JSVALUE64)
1070             if (m_type == CustomValueGetter || m_type == CustomAccessorGetter) {
1071                 jit.setupArgumentsWithExecState(
1072                     baseForCustomValue,
1073                     CCallHelpers::TrustedImmPtr(ident.impl()));
1074             } else
1075                 jit.setupArgumentsWithExecState(baseForCustomValue, valueRegs.gpr());
1076 #else
1077             if (m_type == CustomValueGetter || m_type == CustomAccessorGetter) {
1078                 jit.setupArgumentsWithExecState(
1079                     EABI_32BIT_DUMMY_ARG baseForCustomValue,
1080                     CCallHelpers::TrustedImm32(JSValue::CellTag),
1081                     CCallHelpers::TrustedImmPtr(ident.impl()));
1082             } else {
1083                 jit.setupArgumentsWithExecState(
1084                     EABI_32BIT_DUMMY_ARG baseForCustomValue,
1085                     CCallHelpers::TrustedImm32(JSValue::CellTag),
1086                     valueRegs.payloadGPR(), valueRegs.tagGPR());
1087             }
1088 #endif
1089             jit.storePtr(GPRInfo::callFrameRegister, &vm.topCallFrame);
1090
1091             operationCall = jit.call();
1092             jit.addLinkTask(
1093                 [=] (LinkBuffer& linkBuffer) {
1094                     linkBuffer.link(operationCall, FunctionPtr(m_rareData->customAccessor.opaque));
1095                 });
1096
1097             if (m_type == CustomValueGetter || m_type == CustomAccessorGetter)
1098                 jit.setupResults(valueRegs);
1099             jit.reclaimSpaceOnStackForCCall();
1100
1101             CCallHelpers::Jump noException =
1102                 jit.emitExceptionCheck(CCallHelpers::InvertedExceptionCheck);
1103
1104             state.restoreLiveRegistersFromStackForCallWithThrownException();
1105             state.emitExplicitExceptionHandler();
1106         
1107             noException.link(&jit);
1108             state.restoreLiveRegistersFromStackForCall(isGetter());
1109         }
1110         state.succeed();
1111         return;
1112     }
1113
1114     case Replace: {
1115         if (InferredType* type = structure()->inferredTypeFor(ident.impl())) {
1116             if (verbose)
1117                 dataLog("Have type: ", type->descriptor(), "\n");
1118             state.failAndRepatch.append(
1119                 jit.branchIfNotType(
1120                     valueRegs, scratchGPR, type->descriptor(), CCallHelpers::DoNotHaveTagRegisters));
1121         } else if (verbose)
1122             dataLog("Don't have type.\n");
1123         
1124         if (isInlineOffset(m_offset)) {
1125             jit.storeValue(
1126                 valueRegs,
1127                 CCallHelpers::Address(
1128                     baseGPR,
1129                     JSObject::offsetOfInlineStorage() +
1130                     offsetInInlineStorage(m_offset) * sizeof(JSValue)));
1131         } else {
1132             jit.loadPtr(CCallHelpers::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR);
1133             jit.storeValue(
1134                 valueRegs,
1135                 CCallHelpers::Address(
1136                     scratchGPR, offsetInButterfly(m_offset) * sizeof(JSValue)));
1137         }
1138         state.succeed();
1139         return;
1140     }
1141
1142     case Transition: {
1143         // AccessCase::transition() should have returned null if this wasn't true.
1144         RELEASE_ASSERT(GPRInfo::numberOfRegisters >= 6 || !structure()->outOfLineCapacity() || structure()->outOfLineCapacity() == newStructure()->outOfLineCapacity());
1145
1146         if (InferredType* type = newStructure()->inferredTypeFor(ident.impl())) {
1147             if (verbose)
1148                 dataLog("Have type: ", type->descriptor(), "\n");
1149             state.failAndRepatch.append(
1150                 jit.branchIfNotType(
1151                     valueRegs, scratchGPR, type->descriptor(), CCallHelpers::DoNotHaveTagRegisters));
1152         } else if (verbose)
1153             dataLog("Don't have type.\n");
1154         
1155         // NOTE: This logic is duplicated in AccessCase::doesCalls(). It's important that doesCalls() knows
1156         // exactly when this would make calls.
1157         bool allocating = newStructure()->outOfLineCapacity() != structure()->outOfLineCapacity();
1158         bool reallocating = allocating && structure()->outOfLineCapacity();
1159         bool allocatingInline = allocating && !structure()->couldHaveIndexingHeader();
1160
1161         ScratchRegisterAllocator allocator(stubInfo.patch.usedRegisters);
1162         allocator.lock(baseGPR);
1163 #if USE(JSVALUE32_64)
1164         allocator.lock(static_cast<GPRReg>(stubInfo.patch.baseTagGPR));
1165 #endif
1166         allocator.lock(valueRegs);
1167         allocator.lock(scratchGPR);
1168
1169         GPRReg scratchGPR2 = InvalidGPRReg;
1170         GPRReg scratchGPR3 = InvalidGPRReg;
1171         if (allocatingInline) {
1172             scratchGPR2 = allocator.allocateScratchGPR();
1173             scratchGPR3 = allocator.allocateScratchGPR();
1174         }
1175
1176         ScratchRegisterAllocator::PreservedState preservedState =
1177             allocator.preserveReusedRegistersByPushing(jit, ScratchRegisterAllocator::ExtraStackSpace::SpaceForCCall);
1178         
1179         CCallHelpers::JumpList slowPath;
1180
1181         ASSERT(structure()->transitionWatchpointSetHasBeenInvalidated());
1182
1183         if (allocating) {
1184             size_t newSize = newStructure()->outOfLineCapacity() * sizeof(JSValue);
1185             
1186             if (allocatingInline) {
1187                 CopiedAllocator* copiedAllocator = &vm.heap.storageAllocator();
1188
1189                 if (!reallocating) {
1190                     jit.loadPtr(&copiedAllocator->m_currentRemaining, scratchGPR);
1191                     slowPath.append(
1192                         jit.branchSubPtr(
1193                             CCallHelpers::Signed, CCallHelpers::TrustedImm32(newSize), scratchGPR));
1194                     jit.storePtr(scratchGPR, &copiedAllocator->m_currentRemaining);
1195                     jit.negPtr(scratchGPR);
1196                     jit.addPtr(
1197                         CCallHelpers::AbsoluteAddress(&copiedAllocator->m_currentPayloadEnd), scratchGPR);
1198                     jit.addPtr(CCallHelpers::TrustedImm32(sizeof(JSValue)), scratchGPR);
1199                 } else {
1200                     // Handle the case where we are reallocating (i.e. the old structure/butterfly
1201                     // already had out-of-line property storage).
1202                     size_t oldSize = structure()->outOfLineCapacity() * sizeof(JSValue);
1203                     ASSERT(newSize > oldSize);
1204             
1205                     jit.loadPtr(CCallHelpers::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR3);
1206                     jit.loadPtr(&copiedAllocator->m_currentRemaining, scratchGPR);
1207                     slowPath.append(
1208                         jit.branchSubPtr(
1209                             CCallHelpers::Signed, CCallHelpers::TrustedImm32(newSize), scratchGPR));
1210                     jit.storePtr(scratchGPR, &copiedAllocator->m_currentRemaining);
1211                     jit.negPtr(scratchGPR);
1212                     jit.addPtr(
1213                         CCallHelpers::AbsoluteAddress(&copiedAllocator->m_currentPayloadEnd), scratchGPR);
1214                     jit.addPtr(CCallHelpers::TrustedImm32(sizeof(JSValue)), scratchGPR);
1215                     // We have scratchGPR = new storage, scratchGPR3 = old storage,
1216                     // scratchGPR2 = available
1217                     for (size_t offset = 0; offset < oldSize; offset += sizeof(void*)) {
1218                         jit.loadPtr(
1219                             CCallHelpers::Address(
1220                                 scratchGPR3,
1221                                 -static_cast<ptrdiff_t>(
1222                                     offset + sizeof(JSValue) + sizeof(void*))),
1223                             scratchGPR2);
1224                         jit.storePtr(
1225                             scratchGPR2,
1226                             CCallHelpers::Address(
1227                                 scratchGPR,
1228                                 -static_cast<ptrdiff_t>(offset + sizeof(JSValue) + sizeof(void*))));
1229                     }
1230                 }
1231             } else {
1232                 // Handle the case where we are allocating out-of-line using an operation.
1233                 RegisterSet extraRegistersToPreserve;
1234                 extraRegistersToPreserve.set(baseGPR);
1235                 extraRegistersToPreserve.set(valueRegs);
1236                 state.preserveLiveRegistersToStackForCall(extraRegistersToPreserve);
1237                 
1238                 jit.store32(
1239                     CCallHelpers::TrustedImm32(
1240                         state.callSiteIndexForExceptionHandlingOrOriginal().bits()),
1241                     CCallHelpers::tagFor(static_cast<VirtualRegister>(JSStack::ArgumentCount)));
1242                 
1243                 jit.makeSpaceOnStackForCCall();
1244                 
1245                 if (!reallocating) {
1246                     jit.setupArgumentsWithExecState(baseGPR);
1247                     
1248                     CCallHelpers::Call operationCall = jit.call();
1249                     jit.addLinkTask(
1250                         [=] (LinkBuffer& linkBuffer) {
1251                             linkBuffer.link(
1252                                 operationCall,
1253                                 FunctionPtr(operationReallocateButterflyToHavePropertyStorageWithInitialCapacity));
1254                         });
1255                 } else {
1256                     // Handle the case where we are reallocating (i.e. the old structure/butterfly
1257                     // already had out-of-line property storage).
1258                     jit.setupArgumentsWithExecState(
1259                         baseGPR, CCallHelpers::TrustedImm32(newSize / sizeof(JSValue)));
1260                     
1261                     CCallHelpers::Call operationCall = jit.call();
1262                     jit.addLinkTask(
1263                         [=] (LinkBuffer& linkBuffer) {
1264                             linkBuffer.link(
1265                                 operationCall,
1266                                 FunctionPtr(operationReallocateButterflyToGrowPropertyStorage));
1267                         });
1268                 }
1269                 
1270                 jit.reclaimSpaceOnStackForCCall();
1271                 jit.move(GPRInfo::returnValueGPR, scratchGPR);
1272                 
1273                 CCallHelpers::Jump noException =
1274                     jit.emitExceptionCheck(CCallHelpers::InvertedExceptionCheck);
1275                 
1276                 state.restoreLiveRegistersFromStackForCallWithThrownException();
1277                 state.emitExplicitExceptionHandler();
1278                 
1279                 noException.link(&jit);
1280                 state.restoreLiveRegistersFromStackForCall();
1281             }
1282         }
1283
1284         if (isInlineOffset(m_offset)) {
1285             jit.storeValue(
1286                 valueRegs,
1287                 CCallHelpers::Address(
1288                     baseGPR,
1289                     JSObject::offsetOfInlineStorage() +
1290                     offsetInInlineStorage(m_offset) * sizeof(JSValue)));
1291         } else {
1292             if (!allocating)
1293                 jit.loadPtr(CCallHelpers::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR);
1294             jit.storeValue(
1295                 valueRegs,
1296                 CCallHelpers::Address(scratchGPR, offsetInButterfly(m_offset) * sizeof(JSValue)));
1297         }
1298         
1299         // If we had allocated using an operation then we would have already executed the store
1300         // barrier and we would have already stored the butterfly into the object.
1301         if (allocatingInline) {
1302             CCallHelpers::Jump ownerIsRememberedOrInEden = jit.jumpIfIsRememberedOrInEden(baseGPR);
1303             WriteBarrierBuffer& writeBarrierBuffer = jit.vm()->heap.writeBarrierBuffer();
1304             jit.load32(writeBarrierBuffer.currentIndexAddress(), scratchGPR2);
1305             slowPath.append(
1306                 jit.branch32(
1307                     CCallHelpers::AboveOrEqual, scratchGPR2,
1308                     CCallHelpers::TrustedImm32(writeBarrierBuffer.capacity())));
1309             
1310             jit.add32(CCallHelpers::TrustedImm32(1), scratchGPR2);
1311             jit.store32(scratchGPR2, writeBarrierBuffer.currentIndexAddress());
1312             
1313             jit.move(CCallHelpers::TrustedImmPtr(writeBarrierBuffer.buffer()), scratchGPR3);
1314             // We use an offset of -sizeof(void*) because we already added 1 to scratchGPR2.
1315             jit.storePtr(
1316                 baseGPR,
1317                 CCallHelpers::BaseIndex(
1318                     scratchGPR3, scratchGPR2, CCallHelpers::ScalePtr,
1319                     static_cast<int32_t>(-sizeof(void*))));
1320             ownerIsRememberedOrInEden.link(&jit);
1321             
1322             // We set the new butterfly and the structure last. Doing it this way ensures that
1323             // whatever we had done up to this point is forgotten if we choose to branch to slow
1324             // path.
1325             
1326             jit.storePtr(scratchGPR, CCallHelpers::Address(baseGPR, JSObject::butterflyOffset()));
1327         }
1328         
1329         uint32_t structureBits = bitwise_cast<uint32_t>(newStructure()->id());
1330         jit.store32(
1331             CCallHelpers::TrustedImm32(structureBits),
1332             CCallHelpers::Address(baseGPR, JSCell::structureIDOffset()));
1333
1334         allocator.restoreReusedRegistersByPopping(jit, preservedState);
1335         state.succeed();
1336         
1337         // We will have a slow path if we were allocating without the help of an operation.
1338         if (allocatingInline) {
1339             if (allocator.didReuseRegisters()) {
1340                 slowPath.link(&jit);
1341                 allocator.restoreReusedRegistersByPopping(jit, preservedState);
1342                 state.failAndIgnore.append(jit.jump());
1343             } else
1344                 state.failAndIgnore.append(slowPath);
1345         } else
1346             RELEASE_ASSERT(slowPath.empty());
1347         return;
1348     }
1349
1350     case ArrayLength: {
1351         jit.loadPtr(CCallHelpers::Address(baseGPR, JSObject::butterflyOffset()), scratchGPR);
1352         jit.load32(CCallHelpers::Address(scratchGPR, ArrayStorage::lengthOffset()), scratchGPR);
1353         state.failAndIgnore.append(
1354             jit.branch32(CCallHelpers::LessThan, scratchGPR, CCallHelpers::TrustedImm32(0)));
1355         jit.boxInt32(scratchGPR, valueRegs, CCallHelpers::DoNotHaveTagRegisters);
1356         state.succeed();
1357         return;
1358     }
1359
1360     case StringLength: {
1361         jit.load32(CCallHelpers::Address(baseGPR, JSString::offsetOfLength()), valueRegs.payloadGPR());
1362         jit.boxInt32(valueRegs.payloadGPR(), valueRegs, CCallHelpers::DoNotHaveTagRegisters);
1363         state.succeed();
1364         return;
1365     }
1366         
1367     case IntrinsicGetter: {
1368         RELEASE_ASSERT(isValidOffset(offset()));
1369
1370         // We need to ensure the getter value does not move from under us. Note that GetterSetters
1371         // are immutable so we just need to watch the property not any value inside it.
1372         Structure* currStructure;
1373         if (m_conditionSet.isEmpty())
1374             currStructure = structure();
1375         else
1376             currStructure = m_conditionSet.slotBaseCondition().object()->structure();
1377         currStructure->startWatchingPropertyForReplacements(vm, offset());
1378
1379         emitIntrinsicGetter(state);
1380         return;
1381     }
1382
1383     case DirectArgumentsLength:
1384     case ScopedArgumentsLength:
1385     case MegamorphicLoad:
1386         // These need to be handled by generateWithGuard(), since the guard is part of the
1387         // algorithm. We can be sure that nobody will call generate() directly for these since they
1388         // are not guarded by structure checks.
1389         RELEASE_ASSERT_NOT_REACHED();
1390     }
1391     
1392     RELEASE_ASSERT_NOT_REACHED();
1393 }
1394
1395 PolymorphicAccess::PolymorphicAccess() { }
1396 PolymorphicAccess::~PolymorphicAccess() { }
1397
1398 AccessGenerationResult PolymorphicAccess::addCases(
1399     VM& vm, CodeBlock* codeBlock, StructureStubInfo& stubInfo, const Identifier& ident,
1400     Vector<std::unique_ptr<AccessCase>> originalCasesToAdd)
1401 {
1402     SuperSamplerScope superSamplerScope(false);
1403     
1404     // This method will add the originalCasesToAdd to the list one at a time while preserving the
1405     // invariants:
1406     // - If a newly added case canReplace() any existing case, then the existing case is removed before
1407     //   the new case is added. Removal doesn't change order of the list. Any number of existing cases
1408     //   can be removed via the canReplace() rule.
1409     // - Cases in the list always appear in ascending order of time of addition. Therefore, if you
1410     //   cascade through the cases in reverse order, you will get the most recent cases first.
1411     // - If this method fails (returns null, doesn't add the cases), then both the previous case list
1412     //   and the previous stub are kept intact and the new cases are destroyed. It's OK to attempt to
1413     //   add more things after failure.
1414     
1415     // First ensure that the originalCasesToAdd doesn't contain duplicates.
1416     Vector<std::unique_ptr<AccessCase>> casesToAdd;
1417     for (unsigned i = 0; i < originalCasesToAdd.size(); ++i) {
1418         std::unique_ptr<AccessCase> myCase = WTFMove(originalCasesToAdd[i]);
1419
1420         // Add it only if it is not replaced by the subsequent cases in the list.
1421         bool found = false;
1422         for (unsigned j = i + 1; j < originalCasesToAdd.size(); ++j) {
1423             if (originalCasesToAdd[j]->canReplace(*myCase)) {
1424                 found = true;
1425                 break;
1426             }
1427         }
1428
1429         if (found)
1430             continue;
1431         
1432         casesToAdd.append(WTFMove(myCase));
1433     }
1434
1435     if (verbose)
1436         dataLog("casesToAdd: ", listDump(casesToAdd), "\n");
1437
1438     // If there aren't any cases to add, then fail on the grounds that there's no point to generating a
1439     // new stub that will be identical to the old one. Returning null should tell the caller to just
1440     // keep doing what they were doing before.
1441     if (casesToAdd.isEmpty())
1442         return AccessGenerationResult::MadeNoChanges;
1443
1444     // Now add things to the new list. Note that at this point, we will still have old cases that
1445     // may be replaced by the new ones. That's fine. We will sort that out when we regenerate.
1446     for (auto& caseToAdd : casesToAdd) {
1447         commit(vm, m_watchpoints, codeBlock, stubInfo, ident, *caseToAdd);
1448         m_list.append(WTFMove(caseToAdd));
1449     }
1450     
1451     if (verbose)
1452         dataLog("After addCases: m_list: ", listDump(m_list), "\n");
1453
1454     return AccessGenerationResult::Buffered;
1455 }
1456
1457 AccessGenerationResult PolymorphicAccess::addCase(
1458     VM& vm, CodeBlock* codeBlock, StructureStubInfo& stubInfo, const Identifier& ident,
1459     std::unique_ptr<AccessCase> newAccess)
1460 {
1461     Vector<std::unique_ptr<AccessCase>> newAccesses;
1462     newAccesses.append(WTFMove(newAccess));
1463     return addCases(vm, codeBlock, stubInfo, ident, WTFMove(newAccesses));
1464 }
1465
1466 bool PolymorphicAccess::visitWeak(VM& vm) const
1467 {
1468     for (unsigned i = 0; i < size(); ++i) {
1469         if (!at(i).visitWeak(vm))
1470             return false;
1471     }
1472     if (Vector<WriteBarrier<JSCell>>* weakReferences = m_weakReferences.get()) {
1473         for (WriteBarrier<JSCell>& weakReference : *weakReferences) {
1474             if (!Heap::isMarked(weakReference.get()))
1475                 return false;
1476         }
1477     }
1478     return true;
1479 }
1480
1481 void PolymorphicAccess::dump(PrintStream& out) const
1482 {
1483     out.print(RawPointer(this), ":[");
1484     CommaPrinter comma;
1485     for (auto& entry : m_list)
1486         out.print(comma, *entry);
1487     out.print("]");
1488 }
1489
1490 void PolymorphicAccess::commit(
1491     VM& vm, std::unique_ptr<WatchpointsOnStructureStubInfo>& watchpoints, CodeBlock* codeBlock,
1492     StructureStubInfo& stubInfo, const Identifier& ident, AccessCase& accessCase)
1493 {
1494     // NOTE: We currently assume that this is relatively rare. It mainly arises for accesses to
1495     // properties on DOM nodes. For sure we cache many DOM node accesses, but even in
1496     // Real Pages (TM), we appear to spend most of our time caching accesses to properties on
1497     // vanilla objects or exotic objects from within JSC (like Arguments, those are super popular).
1498     // Those common kinds of JSC object accesses don't hit this case.
1499     
1500     for (WatchpointSet* set : accessCase.commit(vm, ident)) {
1501         Watchpoint* watchpoint =
1502             WatchpointsOnStructureStubInfo::ensureReferenceAndAddWatchpoint(
1503                 watchpoints, codeBlock, &stubInfo, ObjectPropertyCondition());
1504         
1505         set->add(watchpoint);
1506     }
1507 }
1508
1509 AccessGenerationResult PolymorphicAccess::regenerate(
1510     VM& vm, CodeBlock* codeBlock, StructureStubInfo& stubInfo, const Identifier& ident)
1511 {
1512     SuperSamplerScope superSamplerScope(false);
1513     
1514     if (verbose)
1515         dataLog("Regenerate with m_list: ", listDump(m_list), "\n");
1516     
1517     AccessGenerationState state;
1518
1519     state.access = this;
1520     state.stubInfo = &stubInfo;
1521     state.ident = &ident;
1522     
1523     state.baseGPR = static_cast<GPRReg>(stubInfo.patch.baseGPR);
1524     state.valueRegs = JSValueRegs(
1525 #if USE(JSVALUE32_64)
1526         static_cast<GPRReg>(stubInfo.patch.valueTagGPR),
1527 #endif
1528         static_cast<GPRReg>(stubInfo.patch.valueGPR));
1529
1530     ScratchRegisterAllocator allocator(stubInfo.patch.usedRegisters);
1531     state.allocator = &allocator;
1532     allocator.lock(state.baseGPR);
1533     allocator.lock(state.valueRegs);
1534 #if USE(JSVALUE32_64)
1535     allocator.lock(static_cast<GPRReg>(stubInfo.patch.baseTagGPR));
1536 #endif
1537
1538     state.scratchGPR = allocator.allocateScratchGPR();
1539     
1540     CCallHelpers jit(&vm, codeBlock);
1541     state.jit = &jit;
1542
1543     state.preservedReusedRegisterState =
1544         allocator.preserveReusedRegistersByPushing(jit, ScratchRegisterAllocator::ExtraStackSpace::NoExtraSpace);
1545
1546     // Regenerating is our opportunity to figure out what our list of cases should look like. We
1547     // do this here. The newly produced 'cases' list may be smaller than m_list. We don't edit
1548     // m_list in-place because we may still fail, in which case we want the PolymorphicAccess object
1549     // to be unmutated. For sure, we want it to hang onto any data structures that may be referenced
1550     // from the code of the current stub (aka previous).
1551     ListType cases;
1552     unsigned srcIndex = 0;
1553     unsigned dstIndex = 0;
1554     while (srcIndex < m_list.size()) {
1555         std::unique_ptr<AccessCase> someCase = WTFMove(m_list[srcIndex++]);
1556         
1557         // If the case had been generated, then we have to keep the original in m_list in case we
1558         // fail to regenerate. That case may have data structures that are used by the code that it
1559         // had generated. If the case had not been generated, then we want to remove it from m_list.
1560         bool isGenerated = someCase->state() == AccessCase::Generated;
1561         
1562         [&] () {
1563             if (!someCase->couldStillSucceed())
1564                 return;
1565
1566             // Figure out if this is replaced by any later case.
1567             for (unsigned j = srcIndex; j < m_list.size(); ++j) {
1568                 if (m_list[j]->canReplace(*someCase))
1569                     return;
1570             }
1571             
1572             if (isGenerated)
1573                 cases.append(someCase->clone());
1574             else
1575                 cases.append(WTFMove(someCase));
1576         }();
1577         
1578         if (isGenerated)
1579             m_list[dstIndex++] = WTFMove(someCase);
1580     }
1581     m_list.resize(dstIndex);
1582     
1583     if (verbose)
1584         dataLog("In regenerate: cases: ", listDump(cases), "\n");
1585     
1586     // Now that we've removed obviously unnecessary cases, we can check if the megamorphic load
1587     // optimization is applicable. Note that we basically tune megamorphicLoadCost according to code
1588     // size. It would be faster to just allow more repatching with many load cases, and avoid the
1589     // megamorphicLoad optimization, if we had infinite executable memory.
1590     if (cases.size() >= Options::megamorphicLoadCost()) {
1591         unsigned numSelfLoads = 0;
1592         for (auto& newCase : cases) {
1593             if (newCase->canBeReplacedByMegamorphicLoad())
1594                 numSelfLoads++;
1595         }
1596         
1597         if (numSelfLoads >= Options::megamorphicLoadCost()) {
1598             if (auto mega = AccessCase::megamorphicLoad(vm, codeBlock)) {
1599                 cases.removeAllMatching(
1600                     [&] (std::unique_ptr<AccessCase>& newCase) -> bool {
1601                         return newCase->canBeReplacedByMegamorphicLoad();
1602                     });
1603                 
1604                 cases.append(WTFMove(mega));
1605             }
1606         }
1607     }
1608     
1609     if (verbose)
1610         dataLog("Optimized cases: ", listDump(cases), "\n");
1611     
1612     // At this point we're convinced that 'cases' contains the cases that we want to JIT now and we
1613     // won't change that set anymore.
1614     
1615     bool allGuardedByStructureCheck = true;
1616     bool hasJSGetterSetterCall = false;
1617     for (auto& newCase : cases) {
1618         commit(vm, state.watchpoints, codeBlock, stubInfo, ident, *newCase);
1619         allGuardedByStructureCheck &= newCase->guardedByStructureCheck();
1620         if (newCase->type() == AccessCase::Getter || newCase->type() == AccessCase::Setter)
1621             hasJSGetterSetterCall = true;
1622     }
1623
1624     if (cases.isEmpty()) {
1625         // This is super unlikely, but we make it legal anyway.
1626         state.failAndRepatch.append(jit.jump());
1627     } else if (!allGuardedByStructureCheck || cases.size() == 1) {
1628         // If there are any proxies in the list, we cannot just use a binary switch over the structure.
1629         // We need to resort to a cascade. A cascade also happens to be optimal if we only have just
1630         // one case.
1631         CCallHelpers::JumpList fallThrough;
1632
1633         // Cascade through the list, preferring newer entries.
1634         for (unsigned i = cases.size(); i--;) {
1635             fallThrough.link(&jit);
1636             cases[i]->generateWithGuard(state, fallThrough);
1637         }
1638         state.failAndRepatch.append(fallThrough);
1639     } else {
1640         jit.load32(
1641             CCallHelpers::Address(state.baseGPR, JSCell::structureIDOffset()),
1642             state.scratchGPR);
1643         
1644         Vector<int64_t> caseValues(cases.size());
1645         for (unsigned i = 0; i < cases.size(); ++i)
1646             caseValues[i] = bitwise_cast<int32_t>(cases[i]->structure()->id());
1647         
1648         BinarySwitch binarySwitch(state.scratchGPR, caseValues, BinarySwitch::Int32);
1649         while (binarySwitch.advance(jit))
1650             cases[binarySwitch.caseIndex()]->generate(state);
1651         state.failAndRepatch.append(binarySwitch.fallThrough());
1652     }
1653
1654     if (!state.failAndIgnore.empty()) {
1655         state.failAndIgnore.link(&jit);
1656         
1657         // Make sure that the inline cache optimization code knows that we are taking slow path because
1658         // of something that isn't patchable. The slow path will decrement "countdown" and will only
1659         // patch things if the countdown reaches zero. We increment the slow path count here to ensure
1660         // that the slow path does not try to patch.
1661         jit.load8(&stubInfo.countdown, state.scratchGPR);
1662         jit.add32(CCallHelpers::TrustedImm32(1), state.scratchGPR);
1663         jit.store8(state.scratchGPR, &stubInfo.countdown);
1664     }
1665
1666     CCallHelpers::JumpList failure;
1667     if (allocator.didReuseRegisters()) {
1668         state.failAndRepatch.link(&jit);
1669         state.restoreScratch();
1670     } else
1671         failure = state.failAndRepatch;
1672     failure.append(jit.jump());
1673
1674     CodeBlock* codeBlockThatOwnsExceptionHandlers = nullptr;
1675     CallSiteIndex callSiteIndexForExceptionHandling;
1676     if (state.needsToRestoreRegistersIfException() && hasJSGetterSetterCall) {
1677         // Emit the exception handler.
1678         // Note that this code is only reachable when doing genericUnwind from a pure JS getter/setter .
1679         // Note also that this is not reachable from custom getter/setter. Custom getter/setters will have 
1680         // their own exception handling logic that doesn't go through genericUnwind.
1681         MacroAssembler::Label makeshiftCatchHandler = jit.label();
1682
1683         int stackPointerOffset = codeBlock->stackPointerOffset() * sizeof(EncodedJSValue);
1684         stackPointerOffset -= state.preservedReusedRegisterState.numberOfBytesPreserved;
1685         stackPointerOffset -= state.numberOfStackBytesUsedForRegisterPreservation();
1686
1687         jit.loadPtr(vm.addressOfCallFrameForCatch(), GPRInfo::callFrameRegister);
1688         jit.addPtr(CCallHelpers::TrustedImm32(stackPointerOffset), GPRInfo::callFrameRegister, CCallHelpers::stackPointerRegister);
1689
1690         state.restoreLiveRegistersFromStackForCallWithThrownException();
1691         state.restoreScratch();
1692         CCallHelpers::Jump jumpToOSRExitExceptionHandler = jit.jump();
1693
1694         HandlerInfo oldHandler = state.originalExceptionHandler();
1695         CallSiteIndex newExceptionHandlingCallSite = state.callSiteIndexForExceptionHandling();
1696         jit.addLinkTask(
1697             [=] (LinkBuffer& linkBuffer) {
1698                 linkBuffer.link(jumpToOSRExitExceptionHandler, oldHandler.nativeCode);
1699
1700                 HandlerInfo handlerToRegister = oldHandler;
1701                 handlerToRegister.nativeCode = linkBuffer.locationOf(makeshiftCatchHandler);
1702                 handlerToRegister.start = newExceptionHandlingCallSite.bits();
1703                 handlerToRegister.end = newExceptionHandlingCallSite.bits() + 1;
1704                 codeBlock->appendExceptionHandler(handlerToRegister);
1705             });
1706
1707         // We set these to indicate to the stub to remove itself from the CodeBlock's
1708         // exception handler table when it is deallocated.
1709         codeBlockThatOwnsExceptionHandlers = codeBlock;
1710         ASSERT(JITCode::isOptimizingJIT(codeBlockThatOwnsExceptionHandlers->jitType()));
1711         callSiteIndexForExceptionHandling = state.callSiteIndexForExceptionHandling();
1712     }
1713
1714     LinkBuffer linkBuffer(vm, jit, codeBlock, JITCompilationCanFail);
1715     if (linkBuffer.didFailToAllocate()) {
1716         if (verbose)
1717             dataLog("Did fail to allocate.\n");
1718         return AccessGenerationResult::GaveUp;
1719     }
1720
1721     CodeLocationLabel successLabel =
1722         stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToDone);
1723         
1724     linkBuffer.link(state.success, successLabel);
1725
1726     linkBuffer.link(
1727         failure,
1728         stubInfo.callReturnLocation.labelAtOffset(stubInfo.patch.deltaCallToSlowCase));
1729     
1730     if (verbose)
1731         dataLog(*codeBlock, " ", stubInfo.codeOrigin, ": Generating polymorphic access stub for ", listDump(cases), "\n");
1732
1733     MacroAssemblerCodeRef code = FINALIZE_CODE_FOR(
1734         codeBlock, linkBuffer,
1735         ("%s", toCString("Access stub for ", *codeBlock, " ", stubInfo.codeOrigin, " with return point ", successLabel, ": ", listDump(cases)).data()));
1736
1737     bool doesCalls = false;
1738     Vector<JSCell*> cellsToMark;
1739     for (auto& entry : cases)
1740         doesCalls |= entry->doesCalls(&cellsToMark);
1741     
1742     m_stubRoutine = createJITStubRoutine(code, vm, codeBlock, doesCalls, cellsToMark, codeBlockThatOwnsExceptionHandlers, callSiteIndexForExceptionHandling);
1743     m_watchpoints = WTFMove(state.watchpoints);
1744     if (!state.weakReferences.isEmpty())
1745         m_weakReferences = std::make_unique<Vector<WriteBarrier<JSCell>>>(WTFMove(state.weakReferences));
1746     if (verbose)
1747         dataLog("Returning: ", code.code(), "\n");
1748     
1749     m_list = WTFMove(cases);
1750     
1751     AccessGenerationResult::Kind resultKind;
1752     if (m_list.size() >= Options::maxAccessVariantListSize())
1753         resultKind = AccessGenerationResult::GeneratedFinalCode;
1754     else
1755         resultKind = AccessGenerationResult::GeneratedNewCode;
1756     
1757     return AccessGenerationResult(resultKind, code.code());
1758 }
1759
1760 void PolymorphicAccess::aboutToDie()
1761 {
1762     if (m_stubRoutine)
1763         m_stubRoutine->aboutToDie();
1764 }
1765
1766 } // namespace JSC
1767
1768 namespace WTF {
1769
1770 using namespace JSC;
1771
1772 void printInternal(PrintStream& out, AccessGenerationResult::Kind kind)
1773 {
1774     switch (kind) {
1775     case AccessGenerationResult::MadeNoChanges:
1776         out.print("MadeNoChanges");
1777         return;
1778     case AccessGenerationResult::GaveUp:
1779         out.print("GaveUp");
1780         return;
1781     case AccessGenerationResult::Buffered:
1782         out.print("Buffered");
1783         return;
1784     case AccessGenerationResult::GeneratedNewCode:
1785         out.print("GeneratedNewCode");
1786         return;
1787     case AccessGenerationResult::GeneratedFinalCode:
1788         out.print("GeneratedFinalCode");
1789         return;
1790     }
1791     
1792     RELEASE_ASSERT_NOT_REACHED();
1793 }
1794
1795 void printInternal(PrintStream& out, AccessCase::AccessType type)
1796 {
1797     switch (type) {
1798     case AccessCase::Load:
1799         out.print("Load");
1800         return;
1801     case AccessCase::MegamorphicLoad:
1802         out.print("MegamorphicLoad");
1803         return;
1804     case AccessCase::Transition:
1805         out.print("Transition");
1806         return;
1807     case AccessCase::Replace:
1808         out.print("Replace");
1809         return;
1810     case AccessCase::Miss:
1811         out.print("Miss");
1812         return;
1813     case AccessCase::GetGetter:
1814         out.print("GetGetter");
1815         return;
1816     case AccessCase::Getter:
1817         out.print("Getter");
1818         return;
1819     case AccessCase::Setter:
1820         out.print("Setter");
1821         return;
1822     case AccessCase::CustomValueGetter:
1823         out.print("CustomValueGetter");
1824         return;
1825     case AccessCase::CustomAccessorGetter:
1826         out.print("CustomAccessorGetter");
1827         return;
1828     case AccessCase::CustomValueSetter:
1829         out.print("CustomValueSetter");
1830         return;
1831     case AccessCase::CustomAccessorSetter:
1832         out.print("CustomAccessorSetter");
1833         return;
1834     case AccessCase::IntrinsicGetter:
1835         out.print("IntrinsicGetter");
1836         return;
1837     case AccessCase::InHit:
1838         out.print("InHit");
1839         return;
1840     case AccessCase::InMiss:
1841         out.print("InMiss");
1842         return;
1843     case AccessCase::ArrayLength:
1844         out.print("ArrayLength");
1845         return;
1846     case AccessCase::StringLength:
1847         out.print("StringLength");
1848         return;
1849     case AccessCase::DirectArgumentsLength:
1850         out.print("DirectArgumentsLength");
1851         return;
1852     case AccessCase::ScopedArgumentsLength:
1853         out.print("ScopedArgumentsLength");
1854         return;
1855     }
1856
1857     RELEASE_ASSERT_NOT_REACHED();
1858 }
1859
1860 void printInternal(PrintStream& out, AccessCase::State state)
1861 {
1862     switch (state) {
1863     case AccessCase::Primordial:
1864         out.print("Primordial");
1865         return;
1866     case AccessCase::Committed:
1867         out.print("Committed");
1868         return;
1869     case AccessCase::Generated:
1870         out.print("Generated");
1871         return;
1872     }
1873
1874     RELEASE_ASSERT_NOT_REACHED();
1875 }
1876
1877 } // namespace WTF
1878
1879 #endif // ENABLE(JIT)
1880
1881