Move all of the branchIs<type> helpers from SpeculativeJIT into AssemblyHelpers
[WebKit-https.git] / Source / JavaScriptCore / dfg / DFGSpeculativeJIT.cpp
1 /*
2  * Copyright (C) 2011-2015 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 "DFGSpeculativeJIT.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "BinarySwitch.h"
32 #include "DFGAbstractInterpreterInlines.h"
33 #include "DFGArrayifySlowPathGenerator.h"
34 #include "DFGCallArrayAllocatorSlowPathGenerator.h"
35 #include "DFGCallCreateDirectArgumentsSlowPathGenerator.h"
36 #include "DFGMayExit.h"
37 #include "DFGSaneStringGetByValSlowPathGenerator.h"
38 #include "DFGSlowPathGenerator.h"
39 #include "DirectArguments.h"
40 #include "JSCInlines.h"
41 #include "JSEnvironmentRecord.h"
42 #include "JSLexicalEnvironment.h"
43 #include "LinkBuffer.h"
44 #include "ScopedArguments.h"
45 #include "ScratchRegisterAllocator.h"
46 #include "WriteBarrierBuffer.h"
47 #include <wtf/MathExtras.h>
48
49 namespace JSC { namespace DFG {
50
51 SpeculativeJIT::SpeculativeJIT(JITCompiler& jit)
52     : m_compileOkay(true)
53     , m_jit(jit)
54     , m_currentNode(0)
55     , m_lastGeneratedNode(LastNodeType)
56     , m_indexInBlock(0)
57     , m_generationInfo(m_jit.graph().frameRegisterCount())
58     , m_state(m_jit.graph())
59     , m_interpreter(m_jit.graph(), m_state)
60     , m_stream(&jit.jitCode()->variableEventStream)
61     , m_minifiedGraph(&jit.jitCode()->minifiedDFG)
62     , m_isCheckingArgumentTypes(false)
63 {
64 }
65
66 SpeculativeJIT::~SpeculativeJIT()
67 {
68 }
69
70 void SpeculativeJIT::emitAllocateJSArray(GPRReg resultGPR, Structure* structure, GPRReg storageGPR, unsigned numElements)
71 {
72     ASSERT(hasUndecided(structure->indexingType()) || hasInt32(structure->indexingType()) || hasDouble(structure->indexingType()) || hasContiguous(structure->indexingType()));
73     
74     GPRTemporary scratch(this);
75     GPRTemporary scratch2(this);
76     GPRReg scratchGPR = scratch.gpr();
77     GPRReg scratch2GPR = scratch2.gpr();
78     
79     unsigned vectorLength = std::max(BASE_VECTOR_LEN, numElements);
80     
81     JITCompiler::JumpList slowCases;
82     
83     slowCases.append(
84         emitAllocateBasicStorage(TrustedImm32(vectorLength * sizeof(JSValue) + sizeof(IndexingHeader)), storageGPR));
85     m_jit.subPtr(TrustedImm32(vectorLength * sizeof(JSValue)), storageGPR);
86     emitAllocateJSObject<JSArray>(resultGPR, TrustedImmPtr(structure), storageGPR, scratchGPR, scratch2GPR, slowCases);
87     
88     m_jit.store32(TrustedImm32(numElements), MacroAssembler::Address(storageGPR, Butterfly::offsetOfPublicLength()));
89     m_jit.store32(TrustedImm32(vectorLength), MacroAssembler::Address(storageGPR, Butterfly::offsetOfVectorLength()));
90     
91     if (hasDouble(structure->indexingType()) && numElements < vectorLength) {
92 #if USE(JSVALUE64)
93         m_jit.move(TrustedImm64(bitwise_cast<int64_t>(PNaN)), scratchGPR);
94         for (unsigned i = numElements; i < vectorLength; ++i)
95             m_jit.store64(scratchGPR, MacroAssembler::Address(storageGPR, sizeof(double) * i));
96 #else
97         EncodedValueDescriptor value;
98         value.asInt64 = JSValue::encode(JSValue(JSValue::EncodeAsDouble, PNaN));
99         for (unsigned i = numElements; i < vectorLength; ++i) {
100             m_jit.store32(TrustedImm32(value.asBits.tag), MacroAssembler::Address(storageGPR, sizeof(double) * i + OBJECT_OFFSETOF(JSValue, u.asBits.tag)));
101             m_jit.store32(TrustedImm32(value.asBits.payload), MacroAssembler::Address(storageGPR, sizeof(double) * i + OBJECT_OFFSETOF(JSValue, u.asBits.payload)));
102         }
103 #endif
104     }
105     
106     // I want a slow path that also loads out the storage pointer, and that's
107     // what this custom CallArrayAllocatorSlowPathGenerator gives me. It's a lot
108     // of work for a very small piece of functionality. :-/
109     addSlowPathGenerator(std::make_unique<CallArrayAllocatorSlowPathGenerator>(
110         slowCases, this, operationNewArrayWithSize, resultGPR, storageGPR,
111         structure, numElements));
112 }
113
114 void SpeculativeJIT::emitGetLength(InlineCallFrame* inlineCallFrame, GPRReg lengthGPR, bool includeThis)
115 {
116     if (inlineCallFrame && !inlineCallFrame->isVarargs())
117         m_jit.move(TrustedImm32(inlineCallFrame->arguments.size() - !includeThis), lengthGPR);
118     else {
119         VirtualRegister argumentCountRegister;
120         if (!inlineCallFrame)
121             argumentCountRegister = VirtualRegister(JSStack::ArgumentCount);
122         else
123             argumentCountRegister = inlineCallFrame->argumentCountRegister;
124         m_jit.load32(JITCompiler::payloadFor(argumentCountRegister), lengthGPR);
125         if (!includeThis)
126             m_jit.sub32(TrustedImm32(1), lengthGPR);
127     }
128 }
129
130 void SpeculativeJIT::emitGetLength(CodeOrigin origin, GPRReg lengthGPR, bool includeThis)
131 {
132     emitGetLength(origin.inlineCallFrame, lengthGPR, includeThis);
133 }
134
135 void SpeculativeJIT::emitGetCallee(CodeOrigin origin, GPRReg calleeGPR)
136 {
137     if (origin.inlineCallFrame) {
138         if (origin.inlineCallFrame->isClosureCall) {
139             m_jit.loadPtr(
140                 JITCompiler::addressFor(origin.inlineCallFrame->calleeRecovery.virtualRegister()),
141                 calleeGPR);
142         } else {
143             m_jit.move(
144                 TrustedImmPtr(origin.inlineCallFrame->calleeRecovery.constant().asCell()),
145                 calleeGPR);
146         }
147     } else
148         m_jit.loadPtr(JITCompiler::addressFor(JSStack::Callee), calleeGPR);
149 }
150
151 void SpeculativeJIT::emitGetArgumentStart(CodeOrigin origin, GPRReg startGPR)
152 {
153     m_jit.addPtr(
154         TrustedImm32(
155             JITCompiler::argumentsStart(origin).offset() * static_cast<int>(sizeof(Register))),
156         GPRInfo::callFrameRegister, startGPR);
157 }
158
159 void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Node* node, MacroAssembler::Jump jumpToFail)
160 {
161     if (!m_compileOkay)
162         return;
163     ASSERT(m_isCheckingArgumentTypes || m_canExit);
164     m_jit.appendExitInfo(jumpToFail);
165     m_jit.jitCode()->appendOSRExit(OSRExit(kind, jsValueSource, m_jit.graph().methodOfGettingAValueProfileFor(node), this, m_stream->size()));
166 }
167
168 void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Node* node, const MacroAssembler::JumpList& jumpsToFail)
169 {
170     if (!m_compileOkay)
171         return;
172     ASSERT(m_isCheckingArgumentTypes || m_canExit);
173     m_jit.appendExitInfo(jumpsToFail);
174     m_jit.jitCode()->appendOSRExit(OSRExit(kind, jsValueSource, m_jit.graph().methodOfGettingAValueProfileFor(node), this, m_stream->size()));
175 }
176
177 OSRExitJumpPlaceholder SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Node* node)
178 {
179     if (!m_compileOkay)
180         return OSRExitJumpPlaceholder();
181     ASSERT(m_isCheckingArgumentTypes || m_canExit);
182     unsigned index = m_jit.jitCode()->osrExit.size();
183     m_jit.appendExitInfo();
184     m_jit.jitCode()->appendOSRExit(OSRExit(kind, jsValueSource, m_jit.graph().methodOfGettingAValueProfileFor(node), this, m_stream->size()));
185     return OSRExitJumpPlaceholder(index);
186 }
187
188 OSRExitJumpPlaceholder SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Edge nodeUse)
189 {
190     ASSERT(m_isCheckingArgumentTypes || m_canExit);
191     return speculationCheck(kind, jsValueSource, nodeUse.node());
192 }
193
194 void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Edge nodeUse, MacroAssembler::Jump jumpToFail)
195 {
196     ASSERT(m_isCheckingArgumentTypes || m_canExit);
197     speculationCheck(kind, jsValueSource, nodeUse.node(), jumpToFail);
198 }
199
200 void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Edge nodeUse, const MacroAssembler::JumpList& jumpsToFail)
201 {
202     ASSERT(m_isCheckingArgumentTypes || m_canExit);
203     speculationCheck(kind, jsValueSource, nodeUse.node(), jumpsToFail);
204 }
205
206 void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Node* node, MacroAssembler::Jump jumpToFail, const SpeculationRecovery& recovery)
207 {
208     if (!m_compileOkay)
209         return;
210     ASSERT(m_isCheckingArgumentTypes || m_canExit);
211     unsigned recoveryIndex = m_jit.jitCode()->appendSpeculationRecovery(recovery);
212     m_jit.appendExitInfo(jumpToFail);
213     m_jit.jitCode()->appendOSRExit(OSRExit(kind, jsValueSource, m_jit.graph().methodOfGettingAValueProfileFor(node), this, m_stream->size(), recoveryIndex));
214 }
215
216 void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, Edge nodeUse, MacroAssembler::Jump jumpToFail, const SpeculationRecovery& recovery)
217 {
218     ASSERT(m_isCheckingArgumentTypes || m_canExit);
219     speculationCheck(kind, jsValueSource, nodeUse.node(), jumpToFail, recovery);
220 }
221
222 void SpeculativeJIT::emitInvalidationPoint(Node* node)
223 {
224     if (!m_compileOkay)
225         return;
226     ASSERT(m_canExit);
227     OSRExitCompilationInfo& info = m_jit.appendExitInfo(JITCompiler::JumpList());
228     m_jit.jitCode()->appendOSRExit(OSRExit(
229         UncountableInvalidation, JSValueSource(),
230         m_jit.graph().methodOfGettingAValueProfileFor(node),
231         this, m_stream->size()));
232     info.m_replacementSource = m_jit.watchpointLabel();
233     ASSERT(info.m_replacementSource.isSet());
234     noResult(node);
235 }
236
237 void SpeculativeJIT::terminateSpeculativeExecution(ExitKind kind, JSValueRegs jsValueRegs, Node* node)
238 {
239     ASSERT(m_isCheckingArgumentTypes || m_canExit);
240     if (!m_compileOkay)
241         return;
242     speculationCheck(kind, jsValueRegs, node, m_jit.jump());
243     m_compileOkay = false;
244     if (verboseCompilationEnabled())
245         dataLog("Bailing compilation.\n");
246 }
247
248 void SpeculativeJIT::terminateSpeculativeExecution(ExitKind kind, JSValueRegs jsValueRegs, Edge nodeUse)
249 {
250     ASSERT(m_isCheckingArgumentTypes || m_canExit);
251     terminateSpeculativeExecution(kind, jsValueRegs, nodeUse.node());
252 }
253
254 void SpeculativeJIT::typeCheck(JSValueSource source, Edge edge, SpeculatedType typesPassedThrough, MacroAssembler::Jump jumpToFail)
255 {
256     ASSERT(needsTypeCheck(edge, typesPassedThrough));
257     m_interpreter.filter(edge, typesPassedThrough);
258     speculationCheck(BadType, source, edge.node(), jumpToFail);
259 }
260
261 RegisterSet SpeculativeJIT::usedRegisters()
262 {
263     RegisterSet result;
264     
265     for (unsigned i = GPRInfo::numberOfRegisters; i--;) {
266         GPRReg gpr = GPRInfo::toRegister(i);
267         if (m_gprs.isInUse(gpr))
268             result.set(gpr);
269     }
270     for (unsigned i = FPRInfo::numberOfRegisters; i--;) {
271         FPRReg fpr = FPRInfo::toRegister(i);
272         if (m_fprs.isInUse(fpr))
273             result.set(fpr);
274     }
275     
276     result.merge(RegisterSet::specialRegisters());
277     
278     return result;
279 }
280
281 void SpeculativeJIT::addSlowPathGenerator(std::unique_ptr<SlowPathGenerator> slowPathGenerator)
282 {
283     m_slowPathGenerators.append(WTF::move(slowPathGenerator));
284 }
285
286 void SpeculativeJIT::runSlowPathGenerators()
287 {
288     for (unsigned i = 0; i < m_slowPathGenerators.size(); ++i)
289         m_slowPathGenerators[i]->generate(this);
290 }
291
292 // On Windows we need to wrap fmod; on other platforms we can call it directly.
293 // On ARMv7 we assert that all function pointers have to low bit set (point to thumb code).
294 #if CALLING_CONVENTION_IS_STDCALL || CPU(ARM_THUMB2)
295 static double JIT_OPERATION fmodAsDFGOperation(double x, double y)
296 {
297     return fmod(x, y);
298 }
299 #else
300 #define fmodAsDFGOperation fmod
301 #endif
302
303 void SpeculativeJIT::clearGenerationInfo()
304 {
305     for (unsigned i = 0; i < m_generationInfo.size(); ++i)
306         m_generationInfo[i] = GenerationInfo();
307     m_gprs = RegisterBank<GPRInfo>();
308     m_fprs = RegisterBank<FPRInfo>();
309 }
310
311 SilentRegisterSavePlan SpeculativeJIT::silentSavePlanForGPR(VirtualRegister spillMe, GPRReg source)
312 {
313     GenerationInfo& info = generationInfoFromVirtualRegister(spillMe);
314     Node* node = info.node();
315     DataFormat registerFormat = info.registerFormat();
316     ASSERT(registerFormat != DataFormatNone);
317     ASSERT(registerFormat != DataFormatDouble);
318         
319     SilentSpillAction spillAction;
320     SilentFillAction fillAction;
321         
322     if (!info.needsSpill())
323         spillAction = DoNothingForSpill;
324     else {
325 #if USE(JSVALUE64)
326         ASSERT(info.gpr() == source);
327         if (registerFormat == DataFormatInt32)
328             spillAction = Store32Payload;
329         else if (registerFormat == DataFormatCell || registerFormat == DataFormatStorage)
330             spillAction = StorePtr;
331         else if (registerFormat == DataFormatInt52 || registerFormat == DataFormatStrictInt52)
332             spillAction = Store64;
333         else {
334             ASSERT(registerFormat & DataFormatJS);
335             spillAction = Store64;
336         }
337 #elif USE(JSVALUE32_64)
338         if (registerFormat & DataFormatJS) {
339             ASSERT(info.tagGPR() == source || info.payloadGPR() == source);
340             spillAction = source == info.tagGPR() ? Store32Tag : Store32Payload;
341         } else {
342             ASSERT(info.gpr() == source);
343             spillAction = Store32Payload;
344         }
345 #endif
346     }
347         
348     if (registerFormat == DataFormatInt32) {
349         ASSERT(info.gpr() == source);
350         ASSERT(isJSInt32(info.registerFormat()));
351         if (node->hasConstant()) {
352             ASSERT(node->isInt32Constant());
353             fillAction = SetInt32Constant;
354         } else
355             fillAction = Load32Payload;
356     } else if (registerFormat == DataFormatBoolean) {
357 #if USE(JSVALUE64)
358         RELEASE_ASSERT_NOT_REACHED();
359 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
360         fillAction = DoNothingForFill;
361 #endif
362 #elif USE(JSVALUE32_64)
363         ASSERT(info.gpr() == source);
364         if (node->hasConstant()) {
365             ASSERT(node->isBooleanConstant());
366             fillAction = SetBooleanConstant;
367         } else
368             fillAction = Load32Payload;
369 #endif
370     } else if (registerFormat == DataFormatCell) {
371         ASSERT(info.gpr() == source);
372         if (node->hasConstant()) {
373             DFG_ASSERT(m_jit.graph(), m_currentNode, node->isCellConstant());
374             node->asCell(); // To get the assertion.
375             fillAction = SetCellConstant;
376         } else {
377 #if USE(JSVALUE64)
378             fillAction = LoadPtr;
379 #else
380             fillAction = Load32Payload;
381 #endif
382         }
383     } else if (registerFormat == DataFormatStorage) {
384         ASSERT(info.gpr() == source);
385         fillAction = LoadPtr;
386     } else if (registerFormat == DataFormatInt52) {
387         if (node->hasConstant())
388             fillAction = SetInt52Constant;
389         else if (info.spillFormat() == DataFormatInt52)
390             fillAction = Load64;
391         else if (info.spillFormat() == DataFormatStrictInt52)
392             fillAction = Load64ShiftInt52Left;
393         else if (info.spillFormat() == DataFormatNone)
394             fillAction = Load64;
395         else {
396             RELEASE_ASSERT_NOT_REACHED();
397 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
398             fillAction = Load64; // Make GCC happy.
399 #endif
400         }
401     } else if (registerFormat == DataFormatStrictInt52) {
402         if (node->hasConstant())
403             fillAction = SetStrictInt52Constant;
404         else if (info.spillFormat() == DataFormatInt52)
405             fillAction = Load64ShiftInt52Right;
406         else if (info.spillFormat() == DataFormatStrictInt52)
407             fillAction = Load64;
408         else if (info.spillFormat() == DataFormatNone)
409             fillAction = Load64;
410         else {
411             RELEASE_ASSERT_NOT_REACHED();
412 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
413             fillAction = Load64; // Make GCC happy.
414 #endif
415         }
416     } else {
417         ASSERT(registerFormat & DataFormatJS);
418 #if USE(JSVALUE64)
419         ASSERT(info.gpr() == source);
420         if (node->hasConstant()) {
421             if (node->isCellConstant())
422                 fillAction = SetTrustedJSConstant;
423             else
424                 fillAction = SetJSConstant;
425         } else if (info.spillFormat() == DataFormatInt32) {
426             ASSERT(registerFormat == DataFormatJSInt32);
427             fillAction = Load32PayloadBoxInt;
428         } else
429             fillAction = Load64;
430 #else
431         ASSERT(info.tagGPR() == source || info.payloadGPR() == source);
432         if (node->hasConstant())
433             fillAction = info.tagGPR() == source ? SetJSConstantTag : SetJSConstantPayload;
434         else if (info.payloadGPR() == source)
435             fillAction = Load32Payload;
436         else { // Fill the Tag
437             switch (info.spillFormat()) {
438             case DataFormatInt32:
439                 ASSERT(registerFormat == DataFormatJSInt32);
440                 fillAction = SetInt32Tag;
441                 break;
442             case DataFormatCell:
443                 ASSERT(registerFormat == DataFormatJSCell);
444                 fillAction = SetCellTag;
445                 break;
446             case DataFormatBoolean:
447                 ASSERT(registerFormat == DataFormatJSBoolean);
448                 fillAction = SetBooleanTag;
449                 break;
450             default:
451                 fillAction = Load32Tag;
452                 break;
453             }
454         }
455 #endif
456     }
457         
458     return SilentRegisterSavePlan(spillAction, fillAction, node, source);
459 }
460     
461 SilentRegisterSavePlan SpeculativeJIT::silentSavePlanForFPR(VirtualRegister spillMe, FPRReg source)
462 {
463     GenerationInfo& info = generationInfoFromVirtualRegister(spillMe);
464     Node* node = info.node();
465     ASSERT(info.registerFormat() == DataFormatDouble);
466
467     SilentSpillAction spillAction;
468     SilentFillAction fillAction;
469         
470     if (!info.needsSpill())
471         spillAction = DoNothingForSpill;
472     else {
473         ASSERT(!node->hasConstant());
474         ASSERT(info.spillFormat() == DataFormatNone);
475         ASSERT(info.fpr() == source);
476         spillAction = StoreDouble;
477     }
478         
479 #if USE(JSVALUE64)
480     if (node->hasConstant()) {
481         node->asNumber(); // To get the assertion.
482         fillAction = SetDoubleConstant;
483     } else {
484         ASSERT(info.spillFormat() == DataFormatNone || info.spillFormat() == DataFormatDouble);
485         fillAction = LoadDouble;
486     }
487 #elif USE(JSVALUE32_64)
488     ASSERT(info.registerFormat() == DataFormatDouble);
489     if (node->hasConstant()) {
490         node->asNumber(); // To get the assertion.
491         fillAction = SetDoubleConstant;
492     } else
493         fillAction = LoadDouble;
494 #endif
495
496     return SilentRegisterSavePlan(spillAction, fillAction, node, source);
497 }
498     
499 void SpeculativeJIT::silentSpill(const SilentRegisterSavePlan& plan)
500 {
501     switch (plan.spillAction()) {
502     case DoNothingForSpill:
503         break;
504     case Store32Tag:
505         m_jit.store32(plan.gpr(), JITCompiler::tagFor(plan.node()->virtualRegister()));
506         break;
507     case Store32Payload:
508         m_jit.store32(plan.gpr(), JITCompiler::payloadFor(plan.node()->virtualRegister()));
509         break;
510     case StorePtr:
511         m_jit.storePtr(plan.gpr(), JITCompiler::addressFor(plan.node()->virtualRegister()));
512         break;
513 #if USE(JSVALUE64)
514     case Store64:
515         m_jit.store64(plan.gpr(), JITCompiler::addressFor(plan.node()->virtualRegister()));
516         break;
517 #endif
518     case StoreDouble:
519         m_jit.storeDouble(plan.fpr(), JITCompiler::addressFor(plan.node()->virtualRegister()));
520         break;
521     default:
522         RELEASE_ASSERT_NOT_REACHED();
523     }
524 }
525     
526 void SpeculativeJIT::silentFill(const SilentRegisterSavePlan& plan, GPRReg canTrample)
527 {
528 #if USE(JSVALUE32_64)
529     UNUSED_PARAM(canTrample);
530 #endif
531     switch (plan.fillAction()) {
532     case DoNothingForFill:
533         break;
534     case SetInt32Constant:
535         m_jit.move(Imm32(plan.node()->asInt32()), plan.gpr());
536         break;
537 #if USE(JSVALUE64)
538     case SetInt52Constant:
539         m_jit.move(Imm64(plan.node()->asMachineInt() << JSValue::int52ShiftAmount), plan.gpr());
540         break;
541     case SetStrictInt52Constant:
542         m_jit.move(Imm64(plan.node()->asMachineInt()), plan.gpr());
543         break;
544 #endif // USE(JSVALUE64)
545     case SetBooleanConstant:
546         m_jit.move(TrustedImm32(plan.node()->asBoolean()), plan.gpr());
547         break;
548     case SetCellConstant:
549         m_jit.move(TrustedImmPtr(plan.node()->asCell()), plan.gpr());
550         break;
551 #if USE(JSVALUE64)
552     case SetTrustedJSConstant:
553         m_jit.move(valueOfJSConstantAsImm64(plan.node()).asTrustedImm64(), plan.gpr());
554         break;
555     case SetJSConstant:
556         m_jit.move(valueOfJSConstantAsImm64(plan.node()), plan.gpr());
557         break;
558     case SetDoubleConstant:
559         m_jit.move(Imm64(reinterpretDoubleToInt64(plan.node()->asNumber())), canTrample);
560         m_jit.move64ToDouble(canTrample, plan.fpr());
561         break;
562     case Load32PayloadBoxInt:
563         m_jit.load32(JITCompiler::payloadFor(plan.node()->virtualRegister()), plan.gpr());
564         m_jit.or64(GPRInfo::tagTypeNumberRegister, plan.gpr());
565         break;
566     case Load32PayloadConvertToInt52:
567         m_jit.load32(JITCompiler::payloadFor(plan.node()->virtualRegister()), plan.gpr());
568         m_jit.signExtend32ToPtr(plan.gpr(), plan.gpr());
569         m_jit.lshift64(TrustedImm32(JSValue::int52ShiftAmount), plan.gpr());
570         break;
571     case Load32PayloadSignExtend:
572         m_jit.load32(JITCompiler::payloadFor(plan.node()->virtualRegister()), plan.gpr());
573         m_jit.signExtend32ToPtr(plan.gpr(), plan.gpr());
574         break;
575 #else
576     case SetJSConstantTag:
577         m_jit.move(Imm32(plan.node()->asJSValue().tag()), plan.gpr());
578         break;
579     case SetJSConstantPayload:
580         m_jit.move(Imm32(plan.node()->asJSValue().payload()), plan.gpr());
581         break;
582     case SetInt32Tag:
583         m_jit.move(TrustedImm32(JSValue::Int32Tag), plan.gpr());
584         break;
585     case SetCellTag:
586         m_jit.move(TrustedImm32(JSValue::CellTag), plan.gpr());
587         break;
588     case SetBooleanTag:
589         m_jit.move(TrustedImm32(JSValue::BooleanTag), plan.gpr());
590         break;
591     case SetDoubleConstant:
592         m_jit.loadDouble(TrustedImmPtr(m_jit.addressOfDoubleConstant(plan.node())), plan.fpr());
593         break;
594 #endif
595     case Load32Tag:
596         m_jit.load32(JITCompiler::tagFor(plan.node()->virtualRegister()), plan.gpr());
597         break;
598     case Load32Payload:
599         m_jit.load32(JITCompiler::payloadFor(plan.node()->virtualRegister()), plan.gpr());
600         break;
601     case LoadPtr:
602         m_jit.loadPtr(JITCompiler::addressFor(plan.node()->virtualRegister()), plan.gpr());
603         break;
604 #if USE(JSVALUE64)
605     case Load64:
606         m_jit.load64(JITCompiler::addressFor(plan.node()->virtualRegister()), plan.gpr());
607         break;
608     case Load64ShiftInt52Right:
609         m_jit.load64(JITCompiler::addressFor(plan.node()->virtualRegister()), plan.gpr());
610         m_jit.rshift64(TrustedImm32(JSValue::int52ShiftAmount), plan.gpr());
611         break;
612     case Load64ShiftInt52Left:
613         m_jit.load64(JITCompiler::addressFor(plan.node()->virtualRegister()), plan.gpr());
614         m_jit.lshift64(TrustedImm32(JSValue::int52ShiftAmount), plan.gpr());
615         break;
616 #endif
617     case LoadDouble:
618         m_jit.loadDouble(JITCompiler::addressFor(plan.node()->virtualRegister()), plan.fpr());
619         break;
620     default:
621         RELEASE_ASSERT_NOT_REACHED();
622     }
623 }
624     
625 JITCompiler::Jump SpeculativeJIT::jumpSlowForUnwantedArrayMode(GPRReg tempGPR, ArrayMode arrayMode, IndexingType shape)
626 {
627     switch (arrayMode.arrayClass()) {
628     case Array::OriginalArray: {
629         CRASH();
630 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
631         JITCompiler::Jump result; // I already know that VC++ takes unkindly to the expression "return Jump()", so I'm doing it this way in anticipation of someone eventually using VC++ to compile the DFG.
632         return result;
633 #endif
634     }
635         
636     case Array::Array:
637         m_jit.and32(TrustedImm32(IsArray | IndexingShapeMask), tempGPR);
638         return m_jit.branch32(
639             MacroAssembler::NotEqual, tempGPR, TrustedImm32(IsArray | shape));
640         
641     case Array::NonArray:
642     case Array::OriginalNonArray:
643         m_jit.and32(TrustedImm32(IsArray | IndexingShapeMask), tempGPR);
644         return m_jit.branch32(
645             MacroAssembler::NotEqual, tempGPR, TrustedImm32(shape));
646         
647     case Array::PossiblyArray:
648         m_jit.and32(TrustedImm32(IndexingShapeMask), tempGPR);
649         return m_jit.branch32(MacroAssembler::NotEqual, tempGPR, TrustedImm32(shape));
650     }
651     
652     RELEASE_ASSERT_NOT_REACHED();
653     return JITCompiler::Jump();
654 }
655
656 JITCompiler::JumpList SpeculativeJIT::jumpSlowForUnwantedArrayMode(GPRReg tempGPR, ArrayMode arrayMode)
657 {
658     JITCompiler::JumpList result;
659     
660     switch (arrayMode.type()) {
661     case Array::Int32:
662         return jumpSlowForUnwantedArrayMode(tempGPR, arrayMode, Int32Shape);
663
664     case Array::Double:
665         return jumpSlowForUnwantedArrayMode(tempGPR, arrayMode, DoubleShape);
666
667     case Array::Contiguous:
668         return jumpSlowForUnwantedArrayMode(tempGPR, arrayMode, ContiguousShape);
669
670     case Array::ArrayStorage:
671     case Array::SlowPutArrayStorage: {
672         ASSERT(!arrayMode.isJSArrayWithOriginalStructure());
673         
674         if (arrayMode.isJSArray()) {
675             if (arrayMode.isSlowPut()) {
676                 result.append(
677                     m_jit.branchTest32(
678                         MacroAssembler::Zero, tempGPR, MacroAssembler::TrustedImm32(IsArray)));
679                 m_jit.and32(TrustedImm32(IndexingShapeMask), tempGPR);
680                 m_jit.sub32(TrustedImm32(ArrayStorageShape), tempGPR);
681                 result.append(
682                     m_jit.branch32(
683                         MacroAssembler::Above, tempGPR,
684                         TrustedImm32(SlowPutArrayStorageShape - ArrayStorageShape)));
685                 break;
686             }
687             m_jit.and32(TrustedImm32(IsArray | IndexingShapeMask), tempGPR);
688             result.append(
689                 m_jit.branch32(MacroAssembler::NotEqual, tempGPR, TrustedImm32(IsArray | ArrayStorageShape)));
690             break;
691         }
692         m_jit.and32(TrustedImm32(IndexingShapeMask), tempGPR);
693         if (arrayMode.isSlowPut()) {
694             m_jit.sub32(TrustedImm32(ArrayStorageShape), tempGPR);
695             result.append(
696                 m_jit.branch32(
697                     MacroAssembler::Above, tempGPR,
698                     TrustedImm32(SlowPutArrayStorageShape - ArrayStorageShape)));
699             break;
700         }
701         result.append(
702             m_jit.branch32(MacroAssembler::NotEqual, tempGPR, TrustedImm32(ArrayStorageShape)));
703         break;
704     }
705     default:
706         CRASH();
707         break;
708     }
709     
710     return result;
711 }
712
713 void SpeculativeJIT::checkArray(Node* node)
714 {
715     ASSERT(node->arrayMode().isSpecific());
716     ASSERT(!node->arrayMode().doesConversion());
717     
718     SpeculateCellOperand base(this, node->child1());
719     GPRReg baseReg = base.gpr();
720     
721     if (node->arrayMode().alreadyChecked(m_jit.graph(), node, m_state.forNode(node->child1()))) {
722         noResult(m_currentNode);
723         return;
724     }
725     
726     const ClassInfo* expectedClassInfo = 0;
727     
728     switch (node->arrayMode().type()) {
729     case Array::String:
730         RELEASE_ASSERT_NOT_REACHED(); // Should have been a Phantom(String:)
731         break;
732     case Array::Int32:
733     case Array::Double:
734     case Array::Contiguous:
735     case Array::ArrayStorage:
736     case Array::SlowPutArrayStorage: {
737         GPRTemporary temp(this);
738         GPRReg tempGPR = temp.gpr();
739         m_jit.load8(MacroAssembler::Address(baseReg, JSCell::indexingTypeOffset()), tempGPR);
740         speculationCheck(
741             BadIndexingType, JSValueSource::unboxedCell(baseReg), 0,
742             jumpSlowForUnwantedArrayMode(tempGPR, node->arrayMode()));
743         
744         noResult(m_currentNode);
745         return;
746     }
747     case Array::DirectArguments:
748         speculateCellTypeWithoutTypeFiltering(node->child1(), baseReg, DirectArgumentsType);
749         noResult(m_currentNode);
750         return;
751     case Array::ScopedArguments:
752         speculateCellTypeWithoutTypeFiltering(node->child1(), baseReg, ScopedArgumentsType);
753         noResult(m_currentNode);
754         return;
755     default:
756         speculateCellTypeWithoutTypeFiltering(
757             node->child1(), baseReg,
758             typeForTypedArrayType(node->arrayMode().typedArrayType()));
759         noResult(m_currentNode);
760         return;
761     }
762     
763     RELEASE_ASSERT(expectedClassInfo);
764     
765     GPRTemporary temp(this);
766     GPRTemporary temp2(this);
767     m_jit.emitLoadStructure(baseReg, temp.gpr(), temp2.gpr());
768     speculationCheck(
769         BadType, JSValueSource::unboxedCell(baseReg), node,
770         m_jit.branchPtr(
771             MacroAssembler::NotEqual,
772             MacroAssembler::Address(temp.gpr(), Structure::classInfoOffset()),
773             MacroAssembler::TrustedImmPtr(expectedClassInfo)));
774     
775     noResult(m_currentNode);
776 }
777
778 void SpeculativeJIT::arrayify(Node* node, GPRReg baseReg, GPRReg propertyReg)
779 {
780     ASSERT(node->arrayMode().doesConversion());
781     
782     GPRTemporary temp(this);
783     GPRTemporary structure;
784     GPRReg tempGPR = temp.gpr();
785     GPRReg structureGPR = InvalidGPRReg;
786     
787     if (node->op() != ArrayifyToStructure) {
788         GPRTemporary realStructure(this);
789         structure.adopt(realStructure);
790         structureGPR = structure.gpr();
791     }
792         
793     // We can skip all that comes next if we already have array storage.
794     MacroAssembler::JumpList slowPath;
795     
796     if (node->op() == ArrayifyToStructure) {
797         slowPath.append(m_jit.branchWeakStructure(
798             JITCompiler::NotEqual,
799             JITCompiler::Address(baseReg, JSCell::structureIDOffset()),
800             node->structure()));
801     } else {
802         m_jit.load8(
803             MacroAssembler::Address(baseReg, JSCell::indexingTypeOffset()), tempGPR);
804         
805         slowPath.append(jumpSlowForUnwantedArrayMode(tempGPR, node->arrayMode()));
806     }
807     
808     addSlowPathGenerator(std::make_unique<ArrayifySlowPathGenerator>(
809         slowPath, this, node, baseReg, propertyReg, tempGPR, structureGPR));
810     
811     noResult(m_currentNode);
812 }
813
814 void SpeculativeJIT::arrayify(Node* node)
815 {
816     ASSERT(node->arrayMode().isSpecific());
817     
818     SpeculateCellOperand base(this, node->child1());
819     
820     if (!node->child2()) {
821         arrayify(node, base.gpr(), InvalidGPRReg);
822         return;
823     }
824     
825     SpeculateInt32Operand property(this, node->child2());
826     
827     arrayify(node, base.gpr(), property.gpr());
828 }
829
830 GPRReg SpeculativeJIT::fillStorage(Edge edge)
831 {
832     VirtualRegister virtualRegister = edge->virtualRegister();
833     GenerationInfo& info = generationInfoFromVirtualRegister(virtualRegister);
834     
835     switch (info.registerFormat()) {
836     case DataFormatNone: {
837         if (info.spillFormat() == DataFormatStorage) {
838             GPRReg gpr = allocate();
839             m_gprs.retain(gpr, virtualRegister, SpillOrderSpilled);
840             m_jit.loadPtr(JITCompiler::addressFor(virtualRegister), gpr);
841             info.fillStorage(*m_stream, gpr);
842             return gpr;
843         }
844         
845         // Must be a cell; fill it as a cell and then return the pointer.
846         return fillSpeculateCell(edge);
847     }
848         
849     case DataFormatStorage: {
850         GPRReg gpr = info.gpr();
851         m_gprs.lock(gpr);
852         return gpr;
853     }
854         
855     default:
856         return fillSpeculateCell(edge);
857     }
858 }
859
860 void SpeculativeJIT::useChildren(Node* node)
861 {
862     if (node->flags() & NodeHasVarArgs) {
863         for (unsigned childIdx = node->firstChild(); childIdx < node->firstChild() + node->numChildren(); childIdx++) {
864             if (!!m_jit.graph().m_varArgChildren[childIdx])
865                 use(m_jit.graph().m_varArgChildren[childIdx]);
866         }
867     } else {
868         Edge child1 = node->child1();
869         if (!child1) {
870             ASSERT(!node->child2() && !node->child3());
871             return;
872         }
873         use(child1);
874         
875         Edge child2 = node->child2();
876         if (!child2) {
877             ASSERT(!node->child3());
878             return;
879         }
880         use(child2);
881         
882         Edge child3 = node->child3();
883         if (!child3)
884             return;
885         use(child3);
886     }
887 }
888
889 void SpeculativeJIT::compileIn(Node* node)
890 {
891     SpeculateCellOperand base(this, node->child2());
892     GPRReg baseGPR = base.gpr();
893     
894     if (JSString* string = node->child1()->dynamicCastConstant<JSString*>()) {
895         if (string->tryGetValueImpl() && string->tryGetValueImpl()->isAtomic()) {
896             StructureStubInfo* stubInfo = m_jit.codeBlock()->addStubInfo();
897             
898             GPRTemporary result(this);
899             GPRReg resultGPR = result.gpr();
900
901             use(node->child1());
902             
903             MacroAssembler::PatchableJump jump = m_jit.patchableJump();
904             MacroAssembler::Label done = m_jit.label();
905             
906             auto slowPath = slowPathCall(
907                 jump.m_jump, this, operationInOptimize,
908                 JSValueRegs::payloadOnly(resultGPR), stubInfo, baseGPR,
909                 string->tryGetValueImpl());
910             
911             stubInfo->codeOrigin = node->origin.semantic;
912             stubInfo->patch.baseGPR = static_cast<int8_t>(baseGPR);
913             stubInfo->patch.valueGPR = static_cast<int8_t>(resultGPR);
914             stubInfo->patch.usedRegisters = usedRegisters();
915             stubInfo->patch.spillMode = NeedToSpill;
916
917             m_jit.addIn(InRecord(jump, done, slowPath.get(), stubInfo));
918             addSlowPathGenerator(WTF::move(slowPath));
919
920             base.use();
921
922             blessedBooleanResult(resultGPR, node, UseChildrenCalledExplicitly);
923             return;
924         }
925     }
926
927     JSValueOperand key(this, node->child1());
928     JSValueRegs regs = key.jsValueRegs();
929         
930     GPRFlushedCallResult result(this);
931     GPRReg resultGPR = result.gpr();
932         
933     base.use();
934     key.use();
935         
936     flushRegisters();
937     callOperation(
938         operationGenericIn, extractResult(JSValueRegs::payloadOnly(resultGPR)),
939         baseGPR, regs);
940     blessedBooleanResult(resultGPR, node, UseChildrenCalledExplicitly);
941 }
942
943 bool SpeculativeJIT::nonSpeculativeCompare(Node* node, MacroAssembler::RelationalCondition cond, S_JITOperation_EJJ helperFunction)
944 {
945     unsigned branchIndexInBlock = detectPeepHoleBranch();
946     if (branchIndexInBlock != UINT_MAX) {
947         Node* branchNode = m_block->at(branchIndexInBlock);
948
949         ASSERT(node->adjustedRefCount() == 1);
950         
951         nonSpeculativePeepholeBranch(node, branchNode, cond, helperFunction);
952     
953         m_indexInBlock = branchIndexInBlock;
954         m_currentNode = branchNode;
955         
956         return true;
957     }
958     
959     nonSpeculativeNonPeepholeCompare(node, cond, helperFunction);
960     
961     return false;
962 }
963
964 bool SpeculativeJIT::nonSpeculativeStrictEq(Node* node, bool invert)
965 {
966     unsigned branchIndexInBlock = detectPeepHoleBranch();
967     if (branchIndexInBlock != UINT_MAX) {
968         Node* branchNode = m_block->at(branchIndexInBlock);
969
970         ASSERT(node->adjustedRefCount() == 1);
971         
972         nonSpeculativePeepholeStrictEq(node, branchNode, invert);
973     
974         m_indexInBlock = branchIndexInBlock;
975         m_currentNode = branchNode;
976         
977         return true;
978     }
979     
980     nonSpeculativeNonPeepholeStrictEq(node, invert);
981     
982     return false;
983 }
984
985 static const char* dataFormatString(DataFormat format)
986 {
987     // These values correspond to the DataFormat enum.
988     const char* strings[] = {
989         "[  ]",
990         "[ i]",
991         "[ d]",
992         "[ c]",
993         "Err!",
994         "Err!",
995         "Err!",
996         "Err!",
997         "[J ]",
998         "[Ji]",
999         "[Jd]",
1000         "[Jc]",
1001         "Err!",
1002         "Err!",
1003         "Err!",
1004         "Err!",
1005     };
1006     return strings[format];
1007 }
1008
1009 void SpeculativeJIT::dump(const char* label)
1010 {
1011     if (label)
1012         dataLogF("<%s>\n", label);
1013
1014     dataLogF("  gprs:\n");
1015     m_gprs.dump();
1016     dataLogF("  fprs:\n");
1017     m_fprs.dump();
1018     dataLogF("  VirtualRegisters:\n");
1019     for (unsigned i = 0; i < m_generationInfo.size(); ++i) {
1020         GenerationInfo& info = m_generationInfo[i];
1021         if (info.alive())
1022             dataLogF("    % 3d:%s%s", i, dataFormatString(info.registerFormat()), dataFormatString(info.spillFormat()));
1023         else
1024             dataLogF("    % 3d:[__][__]", i);
1025         if (info.registerFormat() == DataFormatDouble)
1026             dataLogF(":fpr%d\n", info.fpr());
1027         else if (info.registerFormat() != DataFormatNone
1028 #if USE(JSVALUE32_64)
1029             && !(info.registerFormat() & DataFormatJS)
1030 #endif
1031             ) {
1032             ASSERT(info.gpr() != InvalidGPRReg);
1033             dataLogF(":%s\n", GPRInfo::debugName(info.gpr()));
1034         } else
1035             dataLogF("\n");
1036     }
1037     if (label)
1038         dataLogF("</%s>\n", label);
1039 }
1040
1041 GPRTemporary::GPRTemporary()
1042     : m_jit(0)
1043     , m_gpr(InvalidGPRReg)
1044 {
1045 }
1046
1047 GPRTemporary::GPRTemporary(SpeculativeJIT* jit)
1048     : m_jit(jit)
1049     , m_gpr(InvalidGPRReg)
1050 {
1051     m_gpr = m_jit->allocate();
1052 }
1053
1054 GPRTemporary::GPRTemporary(SpeculativeJIT* jit, GPRReg specific)
1055     : m_jit(jit)
1056     , m_gpr(InvalidGPRReg)
1057 {
1058     m_gpr = m_jit->allocate(specific);
1059 }
1060
1061 #if USE(JSVALUE32_64)
1062 GPRTemporary::GPRTemporary(
1063     SpeculativeJIT* jit, ReuseTag, JSValueOperand& op1, WhichValueWord which)
1064     : m_jit(jit)
1065     , m_gpr(InvalidGPRReg)
1066 {
1067     if (!op1.isDouble() && m_jit->canReuse(op1.node()))
1068         m_gpr = m_jit->reuse(op1.gpr(which));
1069     else
1070         m_gpr = m_jit->allocate();
1071 }
1072 #endif // USE(JSVALUE32_64)
1073
1074 JSValueRegsTemporary::JSValueRegsTemporary() { }
1075
1076 JSValueRegsTemporary::JSValueRegsTemporary(SpeculativeJIT* jit)
1077 #if USE(JSVALUE64)
1078     : m_gpr(jit)
1079 #else
1080     : m_payloadGPR(jit)
1081     , m_tagGPR(jit)
1082 #endif
1083 {
1084 }
1085
1086 JSValueRegsTemporary::~JSValueRegsTemporary() { }
1087
1088 JSValueRegs JSValueRegsTemporary::regs()
1089 {
1090 #if USE(JSVALUE64)
1091     return JSValueRegs(m_gpr.gpr());
1092 #else
1093     return JSValueRegs(m_tagGPR.gpr(), m_payloadGPR.gpr());
1094 #endif
1095 }
1096
1097 void GPRTemporary::adopt(GPRTemporary& other)
1098 {
1099     ASSERT(!m_jit);
1100     ASSERT(m_gpr == InvalidGPRReg);
1101     ASSERT(other.m_jit);
1102     ASSERT(other.m_gpr != InvalidGPRReg);
1103     m_jit = other.m_jit;
1104     m_gpr = other.m_gpr;
1105     other.m_jit = 0;
1106     other.m_gpr = InvalidGPRReg;
1107 }
1108
1109 FPRTemporary::FPRTemporary(SpeculativeJIT* jit)
1110     : m_jit(jit)
1111     , m_fpr(InvalidFPRReg)
1112 {
1113     m_fpr = m_jit->fprAllocate();
1114 }
1115
1116 FPRTemporary::FPRTemporary(SpeculativeJIT* jit, SpeculateDoubleOperand& op1)
1117     : m_jit(jit)
1118     , m_fpr(InvalidFPRReg)
1119 {
1120     if (m_jit->canReuse(op1.node()))
1121         m_fpr = m_jit->reuse(op1.fpr());
1122     else
1123         m_fpr = m_jit->fprAllocate();
1124 }
1125
1126 FPRTemporary::FPRTemporary(SpeculativeJIT* jit, SpeculateDoubleOperand& op1, SpeculateDoubleOperand& op2)
1127     : m_jit(jit)
1128     , m_fpr(InvalidFPRReg)
1129 {
1130     if (m_jit->canReuse(op1.node()))
1131         m_fpr = m_jit->reuse(op1.fpr());
1132     else if (m_jit->canReuse(op2.node()))
1133         m_fpr = m_jit->reuse(op2.fpr());
1134     else
1135         m_fpr = m_jit->fprAllocate();
1136 }
1137
1138 #if USE(JSVALUE32_64)
1139 FPRTemporary::FPRTemporary(SpeculativeJIT* jit, JSValueOperand& op1)
1140     : m_jit(jit)
1141     , m_fpr(InvalidFPRReg)
1142 {
1143     if (op1.isDouble() && m_jit->canReuse(op1.node()))
1144         m_fpr = m_jit->reuse(op1.fpr());
1145     else
1146         m_fpr = m_jit->fprAllocate();
1147 }
1148 #endif
1149
1150 void SpeculativeJIT::compilePeepHoleDoubleBranch(Node* node, Node* branchNode, JITCompiler::DoubleCondition condition)
1151 {
1152     BasicBlock* taken = branchNode->branchData()->taken.block;
1153     BasicBlock* notTaken = branchNode->branchData()->notTaken.block;
1154     
1155     SpeculateDoubleOperand op1(this, node->child1());
1156     SpeculateDoubleOperand op2(this, node->child2());
1157     
1158     branchDouble(condition, op1.fpr(), op2.fpr(), taken);
1159     jump(notTaken);
1160 }
1161
1162 void SpeculativeJIT::compilePeepHoleObjectEquality(Node* node, Node* branchNode)
1163 {
1164     BasicBlock* taken = branchNode->branchData()->taken.block;
1165     BasicBlock* notTaken = branchNode->branchData()->notTaken.block;
1166
1167     MacroAssembler::RelationalCondition condition = MacroAssembler::Equal;
1168     
1169     if (taken == nextBlock()) {
1170         condition = MacroAssembler::NotEqual;
1171         BasicBlock* tmp = taken;
1172         taken = notTaken;
1173         notTaken = tmp;
1174     }
1175
1176     SpeculateCellOperand op1(this, node->child1());
1177     SpeculateCellOperand op2(this, node->child2());
1178     
1179     GPRReg op1GPR = op1.gpr();
1180     GPRReg op2GPR = op2.gpr();
1181     
1182     if (masqueradesAsUndefinedWatchpointIsStillValid()) {
1183         if (m_state.forNode(node->child1()).m_type & ~SpecObject) {
1184             speculationCheck(
1185                 BadType, JSValueSource::unboxedCell(op1GPR), node->child1(), m_jit.branchIfNotObject(op1GPR));
1186         }
1187         if (m_state.forNode(node->child2()).m_type & ~SpecObject) {
1188             speculationCheck(
1189                 BadType, JSValueSource::unboxedCell(op2GPR), node->child2(), m_jit.branchIfNotObject(op2GPR));
1190         }
1191     } else {
1192         if (m_state.forNode(node->child1()).m_type & ~SpecObject) {
1193             speculationCheck(
1194                 BadType, JSValueSource::unboxedCell(op1GPR), node->child1(),
1195                 m_jit.branchIfNotObject(op1GPR));
1196         }
1197         speculationCheck(BadType, JSValueSource::unboxedCell(op1GPR), node->child1(),
1198             m_jit.branchTest8(
1199                 MacroAssembler::NonZero, 
1200                 MacroAssembler::Address(op1GPR, JSCell::typeInfoFlagsOffset()), 
1201                 MacroAssembler::TrustedImm32(MasqueradesAsUndefined)));
1202
1203         if (m_state.forNode(node->child2()).m_type & ~SpecObject) {
1204             speculationCheck(
1205                 BadType, JSValueSource::unboxedCell(op2GPR), node->child2(),
1206                 m_jit.branchIfNotObject(op2GPR));
1207         }
1208         speculationCheck(BadType, JSValueSource::unboxedCell(op2GPR), node->child2(),
1209             m_jit.branchTest8(
1210                 MacroAssembler::NonZero, 
1211                 MacroAssembler::Address(op2GPR, JSCell::typeInfoFlagsOffset()), 
1212                 MacroAssembler::TrustedImm32(MasqueradesAsUndefined)));
1213     }
1214
1215     branchPtr(condition, op1GPR, op2GPR, taken);
1216     jump(notTaken);
1217 }
1218
1219 void SpeculativeJIT::compilePeepHoleBooleanBranch(Node* node, Node* branchNode, JITCompiler::RelationalCondition condition)
1220 {
1221     BasicBlock* taken = branchNode->branchData()->taken.block;
1222     BasicBlock* notTaken = branchNode->branchData()->notTaken.block;
1223
1224     // The branch instruction will branch to the taken block.
1225     // If taken is next, switch taken with notTaken & invert the branch condition so we can fall through.
1226     if (taken == nextBlock()) {
1227         condition = JITCompiler::invert(condition);
1228         BasicBlock* tmp = taken;
1229         taken = notTaken;
1230         notTaken = tmp;
1231     }
1232
1233     if (node->child1()->isBooleanConstant()) {
1234         bool imm = node->child1()->asBoolean();
1235         SpeculateBooleanOperand op2(this, node->child2());
1236         branch32(condition, JITCompiler::Imm32(static_cast<int32_t>(JSValue::encode(jsBoolean(imm)))), op2.gpr(), taken);
1237     } else if (node->child2()->isBooleanConstant()) {
1238         SpeculateBooleanOperand op1(this, node->child1());
1239         bool imm = node->child2()->asBoolean();
1240         branch32(condition, op1.gpr(), JITCompiler::Imm32(static_cast<int32_t>(JSValue::encode(jsBoolean(imm)))), taken);
1241     } else {
1242         SpeculateBooleanOperand op1(this, node->child1());
1243         SpeculateBooleanOperand op2(this, node->child2());
1244         branch32(condition, op1.gpr(), op2.gpr(), taken);
1245     }
1246
1247     jump(notTaken);
1248 }
1249
1250 void SpeculativeJIT::compilePeepHoleInt32Branch(Node* node, Node* branchNode, JITCompiler::RelationalCondition condition)
1251 {
1252     BasicBlock* taken = branchNode->branchData()->taken.block;
1253     BasicBlock* notTaken = branchNode->branchData()->notTaken.block;
1254
1255     // The branch instruction will branch to the taken block.
1256     // If taken is next, switch taken with notTaken & invert the branch condition so we can fall through.
1257     if (taken == nextBlock()) {
1258         condition = JITCompiler::invert(condition);
1259         BasicBlock* tmp = taken;
1260         taken = notTaken;
1261         notTaken = tmp;
1262     }
1263
1264     if (node->child1()->isInt32Constant()) {
1265         int32_t imm = node->child1()->asInt32();
1266         SpeculateInt32Operand op2(this, node->child2());
1267         branch32(condition, JITCompiler::Imm32(imm), op2.gpr(), taken);
1268     } else if (node->child2()->isInt32Constant()) {
1269         SpeculateInt32Operand op1(this, node->child1());
1270         int32_t imm = node->child2()->asInt32();
1271         branch32(condition, op1.gpr(), JITCompiler::Imm32(imm), taken);
1272     } else {
1273         SpeculateInt32Operand op1(this, node->child1());
1274         SpeculateInt32Operand op2(this, node->child2());
1275         branch32(condition, op1.gpr(), op2.gpr(), taken);
1276     }
1277
1278     jump(notTaken);
1279 }
1280
1281 // Returns true if the compare is fused with a subsequent branch.
1282 bool SpeculativeJIT::compilePeepHoleBranch(Node* node, MacroAssembler::RelationalCondition condition, MacroAssembler::DoubleCondition doubleCondition, S_JITOperation_EJJ operation)
1283 {
1284     // Fused compare & branch.
1285     unsigned branchIndexInBlock = detectPeepHoleBranch();
1286     if (branchIndexInBlock != UINT_MAX) {
1287         Node* branchNode = m_block->at(branchIndexInBlock);
1288
1289         // detectPeepHoleBranch currently only permits the branch to be the very next node,
1290         // so can be no intervening nodes to also reference the compare. 
1291         ASSERT(node->adjustedRefCount() == 1);
1292
1293         if (node->isBinaryUseKind(Int32Use))
1294             compilePeepHoleInt32Branch(node, branchNode, condition);
1295 #if USE(JSVALUE64)
1296         else if (node->isBinaryUseKind(Int52RepUse))
1297             compilePeepHoleInt52Branch(node, branchNode, condition);
1298 #endif // USE(JSVALUE64)
1299         else if (node->isBinaryUseKind(DoubleRepUse))
1300             compilePeepHoleDoubleBranch(node, branchNode, doubleCondition);
1301         else if (node->op() == CompareEq) {
1302             if (node->isBinaryUseKind(StringUse) || node->isBinaryUseKind(StringIdentUse)) {
1303                 // Use non-peephole comparison, for now.
1304                 return false;
1305             }
1306             if (node->isBinaryUseKind(BooleanUse))
1307                 compilePeepHoleBooleanBranch(node, branchNode, condition);
1308             else if (node->isBinaryUseKind(ObjectUse))
1309                 compilePeepHoleObjectEquality(node, branchNode);
1310             else if (node->isBinaryUseKind(ObjectUse, ObjectOrOtherUse))
1311                 compilePeepHoleObjectToObjectOrOtherEquality(node->child1(), node->child2(), branchNode);
1312             else if (node->isBinaryUseKind(ObjectOrOtherUse, ObjectUse))
1313                 compilePeepHoleObjectToObjectOrOtherEquality(node->child2(), node->child1(), branchNode);
1314             else {
1315                 nonSpeculativePeepholeBranch(node, branchNode, condition, operation);
1316                 return true;
1317             }
1318         } else {
1319             nonSpeculativePeepholeBranch(node, branchNode, condition, operation);
1320             return true;
1321         }
1322
1323         use(node->child1());
1324         use(node->child2());
1325         m_indexInBlock = branchIndexInBlock;
1326         m_currentNode = branchNode;
1327         return true;
1328     }
1329     return false;
1330 }
1331
1332 void SpeculativeJIT::noticeOSRBirth(Node* node)
1333 {
1334     if (!node->hasVirtualRegister())
1335         return;
1336     
1337     VirtualRegister virtualRegister = node->virtualRegister();
1338     GenerationInfo& info = generationInfoFromVirtualRegister(virtualRegister);
1339     
1340     info.noticeOSRBirth(*m_stream, node, virtualRegister);
1341 }
1342
1343 void SpeculativeJIT::compileMovHint(Node* node)
1344 {
1345     ASSERT(node->containsMovHint() && node->op() != ZombieHint);
1346     
1347     Node* child = node->child1().node();
1348     noticeOSRBirth(child);
1349     
1350     m_stream->appendAndLog(VariableEvent::movHint(MinifiedID(child), node->unlinkedLocal()));
1351 }
1352
1353 void SpeculativeJIT::bail(AbortReason reason)
1354 {
1355     if (verboseCompilationEnabled())
1356         dataLog("Bailing compilation.\n");
1357     m_compileOkay = true;
1358     m_jit.abortWithReason(reason, m_lastGeneratedNode);
1359     clearGenerationInfo();
1360 }
1361
1362 void SpeculativeJIT::compileCurrentBlock()
1363 {
1364     ASSERT(m_compileOkay);
1365     
1366     if (!m_block)
1367         return;
1368     
1369     ASSERT(m_block->isReachable);
1370     
1371     m_jit.blockHeads()[m_block->index] = m_jit.label();
1372
1373     if (!m_block->intersectionOfCFAHasVisited) {
1374         // Don't generate code for basic blocks that are unreachable according to CFA.
1375         // But to be sure that nobody has generated a jump to this block, drop in a
1376         // breakpoint here.
1377         m_jit.abortWithReason(DFGUnreachableBasicBlock);
1378         return;
1379     }
1380
1381     m_stream->appendAndLog(VariableEvent::reset());
1382     
1383     m_jit.jitAssertHasValidCallFrame();
1384     m_jit.jitAssertTagsInPlace();
1385     m_jit.jitAssertArgumentCountSane();
1386
1387     m_state.reset();
1388     m_state.beginBasicBlock(m_block);
1389     
1390     for (size_t i = m_block->variablesAtHead.size(); i--;) {
1391         int operand = m_block->variablesAtHead.operandForIndex(i);
1392         Node* node = m_block->variablesAtHead[i];
1393         if (!node)
1394             continue; // No need to record dead SetLocal's.
1395         
1396         VariableAccessData* variable = node->variableAccessData();
1397         DataFormat format;
1398         if (!node->refCount())
1399             continue; // No need to record dead SetLocal's.
1400         format = dataFormatFor(variable->flushFormat());
1401         m_stream->appendAndLog(
1402             VariableEvent::setLocal(
1403                 VirtualRegister(operand),
1404                 variable->machineLocal(),
1405                 format));
1406     }
1407     
1408     m_codeOriginForExitTarget = CodeOrigin();
1409     m_codeOriginForExitProfile = CodeOrigin();
1410     
1411     for (m_indexInBlock = 0; m_indexInBlock < m_block->size(); ++m_indexInBlock) {
1412         m_currentNode = m_block->at(m_indexInBlock);
1413         
1414         // We may have hit a contradiction that the CFA was aware of but that the JIT
1415         // didn't cause directly.
1416         if (!m_state.isValid()) {
1417             bail(DFGBailedAtTopOfBlock);
1418             return;
1419         }
1420
1421         if (ASSERT_DISABLED)
1422             m_canExit = true; // Essentially disable the assertions.
1423         else
1424             m_canExit = mayExit(m_jit.graph(), m_currentNode);
1425         
1426         m_interpreter.startExecuting();
1427         m_jit.setForNode(m_currentNode);
1428         m_codeOriginForExitTarget = m_currentNode->origin.forExit;
1429         m_codeOriginForExitProfile = m_currentNode->origin.semantic;
1430         m_lastGeneratedNode = m_currentNode->op();
1431         
1432         ASSERT(m_currentNode->shouldGenerate());
1433         
1434         if (verboseCompilationEnabled()) {
1435             dataLogF(
1436                 "SpeculativeJIT generating Node @%d (bc#%u) at JIT offset 0x%x",
1437                 (int)m_currentNode->index(),
1438                 m_currentNode->origin.semantic.bytecodeIndex, m_jit.debugOffset());
1439             dataLog("\n");
1440         }
1441         
1442         compile(m_currentNode);
1443         
1444         if (belongsInMinifiedGraph(m_currentNode->op()))
1445             m_minifiedGraph->append(MinifiedNode::fromNode(m_currentNode));
1446         
1447 #if ENABLE(DFG_REGISTER_ALLOCATION_VALIDATION)
1448         m_jit.clearRegisterAllocationOffsets();
1449 #endif
1450         
1451         if (!m_compileOkay) {
1452             bail(DFGBailedAtEndOfNode);
1453             return;
1454         }
1455         
1456         // Make sure that the abstract state is rematerialized for the next node.
1457         m_interpreter.executeEffects(m_indexInBlock);
1458     }
1459     
1460     // Perform the most basic verification that children have been used correctly.
1461     if (!ASSERT_DISABLED) {
1462         for (unsigned index = 0; index < m_generationInfo.size(); ++index) {
1463             GenerationInfo& info = m_generationInfo[index];
1464             RELEASE_ASSERT(!info.alive());
1465         }
1466     }
1467 }
1468
1469 // If we are making type predictions about our arguments then
1470 // we need to check that they are correct on function entry.
1471 void SpeculativeJIT::checkArgumentTypes()
1472 {
1473     ASSERT(!m_currentNode);
1474     m_isCheckingArgumentTypes = true;
1475     m_codeOriginForExitTarget = CodeOrigin(0);
1476     m_codeOriginForExitProfile = CodeOrigin(0);
1477
1478     for (int i = 0; i < m_jit.codeBlock()->numParameters(); ++i) {
1479         Node* node = m_jit.graph().m_arguments[i];
1480         if (!node) {
1481             // The argument is dead. We don't do any checks for such arguments.
1482             continue;
1483         }
1484         
1485         ASSERT(node->op() == SetArgument);
1486         ASSERT(node->shouldGenerate());
1487
1488         VariableAccessData* variableAccessData = node->variableAccessData();
1489         FlushFormat format = variableAccessData->flushFormat();
1490         
1491         if (format == FlushedJSValue)
1492             continue;
1493         
1494         VirtualRegister virtualRegister = variableAccessData->local();
1495
1496         JSValueSource valueSource = JSValueSource(JITCompiler::addressFor(virtualRegister));
1497         
1498 #if USE(JSVALUE64)
1499         switch (format) {
1500         case FlushedInt32: {
1501             speculationCheck(BadType, valueSource, node, m_jit.branch64(MacroAssembler::Below, JITCompiler::addressFor(virtualRegister), GPRInfo::tagTypeNumberRegister));
1502             break;
1503         }
1504         case FlushedBoolean: {
1505             GPRTemporary temp(this);
1506             m_jit.load64(JITCompiler::addressFor(virtualRegister), temp.gpr());
1507             m_jit.xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), temp.gpr());
1508             speculationCheck(BadType, valueSource, node, m_jit.branchTest64(MacroAssembler::NonZero, temp.gpr(), TrustedImm32(static_cast<int32_t>(~1))));
1509             break;
1510         }
1511         case FlushedCell: {
1512             speculationCheck(BadType, valueSource, node, m_jit.branchTest64(MacroAssembler::NonZero, JITCompiler::addressFor(virtualRegister), GPRInfo::tagMaskRegister));
1513             break;
1514         }
1515         default:
1516             RELEASE_ASSERT_NOT_REACHED();
1517             break;
1518         }
1519 #else
1520         switch (format) {
1521         case FlushedInt32: {
1522             speculationCheck(BadType, valueSource, node, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::Int32Tag)));
1523             break;
1524         }
1525         case FlushedBoolean: {
1526             speculationCheck(BadType, valueSource, node, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::BooleanTag)));
1527             break;
1528         }
1529         case FlushedCell: {
1530             speculationCheck(BadType, valueSource, node, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::CellTag)));
1531             break;
1532         }
1533         default:
1534             RELEASE_ASSERT_NOT_REACHED();
1535             break;
1536         }
1537 #endif
1538     }
1539     m_isCheckingArgumentTypes = false;
1540 }
1541
1542 bool SpeculativeJIT::compile()
1543 {
1544     checkArgumentTypes();
1545     
1546     ASSERT(!m_currentNode);
1547     for (BlockIndex blockIndex = 0; blockIndex < m_jit.graph().numBlocks(); ++blockIndex) {
1548         m_jit.setForBlockIndex(blockIndex);
1549         m_block = m_jit.graph().block(blockIndex);
1550         compileCurrentBlock();
1551     }
1552     linkBranches();
1553     return true;
1554 }
1555
1556 void SpeculativeJIT::createOSREntries()
1557 {
1558     for (BlockIndex blockIndex = 0; blockIndex < m_jit.graph().numBlocks(); ++blockIndex) {
1559         BasicBlock* block = m_jit.graph().block(blockIndex);
1560         if (!block)
1561             continue;
1562         if (!block->isOSRTarget)
1563             continue;
1564         
1565         // Currently we don't have OSR entry trampolines. We could add them
1566         // here if need be.
1567         m_osrEntryHeads.append(m_jit.blockHeads()[blockIndex]);
1568     }
1569 }
1570
1571 void SpeculativeJIT::linkOSREntries(LinkBuffer& linkBuffer)
1572 {
1573     unsigned osrEntryIndex = 0;
1574     for (BlockIndex blockIndex = 0; blockIndex < m_jit.graph().numBlocks(); ++blockIndex) {
1575         BasicBlock* block = m_jit.graph().block(blockIndex);
1576         if (!block)
1577             continue;
1578         if (!block->isOSRTarget)
1579             continue;
1580         m_jit.noticeOSREntry(*block, m_osrEntryHeads[osrEntryIndex++], linkBuffer);
1581     }
1582     ASSERT(osrEntryIndex == m_osrEntryHeads.size());
1583 }
1584
1585 void SpeculativeJIT::compileDoublePutByVal(Node* node, SpeculateCellOperand& base, SpeculateStrictInt32Operand& property)
1586 {
1587     Edge child3 = m_jit.graph().varArgChild(node, 2);
1588     Edge child4 = m_jit.graph().varArgChild(node, 3);
1589
1590     ArrayMode arrayMode = node->arrayMode();
1591     
1592     GPRReg baseReg = base.gpr();
1593     GPRReg propertyReg = property.gpr();
1594     
1595     SpeculateDoubleOperand value(this, child3);
1596
1597     FPRReg valueReg = value.fpr();
1598     
1599     DFG_TYPE_CHECK(
1600         JSValueRegs(), child3, SpecFullRealNumber,
1601         m_jit.branchDouble(
1602             MacroAssembler::DoubleNotEqualOrUnordered, valueReg, valueReg));
1603     
1604     if (!m_compileOkay)
1605         return;
1606     
1607     StorageOperand storage(this, child4);
1608     GPRReg storageReg = storage.gpr();
1609
1610     if (node->op() == PutByValAlias) {
1611         // Store the value to the array.
1612         GPRReg propertyReg = property.gpr();
1613         FPRReg valueReg = value.fpr();
1614         m_jit.storeDouble(valueReg, MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesEight));
1615         
1616         noResult(m_currentNode);
1617         return;
1618     }
1619     
1620     GPRTemporary temporary;
1621     GPRReg temporaryReg = temporaryRegisterForPutByVal(temporary, node);
1622
1623     MacroAssembler::Jump slowCase;
1624     
1625     if (arrayMode.isInBounds()) {
1626         speculationCheck(
1627             OutOfBounds, JSValueRegs(), 0,
1628             m_jit.branch32(MacroAssembler::AboveOrEqual, propertyReg, MacroAssembler::Address(storageReg, Butterfly::offsetOfPublicLength())));
1629     } else {
1630         MacroAssembler::Jump inBounds = m_jit.branch32(MacroAssembler::Below, propertyReg, MacroAssembler::Address(storageReg, Butterfly::offsetOfPublicLength()));
1631         
1632         slowCase = m_jit.branch32(MacroAssembler::AboveOrEqual, propertyReg, MacroAssembler::Address(storageReg, Butterfly::offsetOfVectorLength()));
1633         
1634         if (!arrayMode.isOutOfBounds())
1635             speculationCheck(OutOfBounds, JSValueRegs(), 0, slowCase);
1636         
1637         m_jit.add32(TrustedImm32(1), propertyReg, temporaryReg);
1638         m_jit.store32(temporaryReg, MacroAssembler::Address(storageReg, Butterfly::offsetOfPublicLength()));
1639         
1640         inBounds.link(&m_jit);
1641     }
1642     
1643     m_jit.storeDouble(valueReg, MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesEight));
1644
1645     base.use();
1646     property.use();
1647     value.use();
1648     storage.use();
1649     
1650     if (arrayMode.isOutOfBounds()) {
1651         addSlowPathGenerator(
1652             slowPathCall(
1653                 slowCase, this,
1654                 m_jit.codeBlock()->isStrictMode() ? operationPutDoubleByValBeyondArrayBoundsStrict : operationPutDoubleByValBeyondArrayBoundsNonStrict,
1655                 NoResult, baseReg, propertyReg, valueReg));
1656     }
1657
1658     noResult(m_currentNode, UseChildrenCalledExplicitly);
1659 }
1660
1661 void SpeculativeJIT::compileGetCharCodeAt(Node* node)
1662 {
1663     SpeculateCellOperand string(this, node->child1());
1664     SpeculateStrictInt32Operand index(this, node->child2());
1665     StorageOperand storage(this, node->child3());
1666
1667     GPRReg stringReg = string.gpr();
1668     GPRReg indexReg = index.gpr();
1669     GPRReg storageReg = storage.gpr();
1670     
1671     ASSERT(speculationChecked(m_state.forNode(node->child1()).m_type, SpecString));
1672
1673     // unsigned comparison so we can filter out negative indices and indices that are too large
1674     speculationCheck(Uncountable, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::AboveOrEqual, indexReg, MacroAssembler::Address(stringReg, JSString::offsetOfLength())));
1675
1676     GPRTemporary scratch(this);
1677     GPRReg scratchReg = scratch.gpr();
1678
1679     m_jit.loadPtr(MacroAssembler::Address(stringReg, JSString::offsetOfValue()), scratchReg);
1680
1681     // Load the character into scratchReg
1682     JITCompiler::Jump is16Bit = m_jit.branchTest32(MacroAssembler::Zero, MacroAssembler::Address(scratchReg, StringImpl::flagsOffset()), TrustedImm32(StringImpl::flagIs8Bit()));
1683
1684     m_jit.load8(MacroAssembler::BaseIndex(storageReg, indexReg, MacroAssembler::TimesOne, 0), scratchReg);
1685     JITCompiler::Jump cont8Bit = m_jit.jump();
1686
1687     is16Bit.link(&m_jit);
1688
1689     m_jit.load16(MacroAssembler::BaseIndex(storageReg, indexReg, MacroAssembler::TimesTwo, 0), scratchReg);
1690
1691     cont8Bit.link(&m_jit);
1692
1693     int32Result(scratchReg, m_currentNode);
1694 }
1695
1696 void SpeculativeJIT::compileGetByValOnString(Node* node)
1697 {
1698     SpeculateCellOperand base(this, node->child1());
1699     SpeculateStrictInt32Operand property(this, node->child2());
1700     StorageOperand storage(this, node->child3());
1701     GPRReg baseReg = base.gpr();
1702     GPRReg propertyReg = property.gpr();
1703     GPRReg storageReg = storage.gpr();
1704
1705     GPRTemporary scratch(this);
1706     GPRReg scratchReg = scratch.gpr();
1707 #if USE(JSVALUE32_64)
1708     GPRTemporary resultTag;
1709     GPRReg resultTagReg = InvalidGPRReg;
1710     if (node->arrayMode().isOutOfBounds()) {
1711         GPRTemporary realResultTag(this);
1712         resultTag.adopt(realResultTag);
1713         resultTagReg = resultTag.gpr();
1714     }
1715 #endif
1716
1717     ASSERT(ArrayMode(Array::String).alreadyChecked(m_jit.graph(), node, m_state.forNode(node->child1())));
1718
1719     // unsigned comparison so we can filter out negative indices and indices that are too large
1720     JITCompiler::Jump outOfBounds = m_jit.branch32(
1721         MacroAssembler::AboveOrEqual, propertyReg,
1722         MacroAssembler::Address(baseReg, JSString::offsetOfLength()));
1723     if (node->arrayMode().isInBounds())
1724         speculationCheck(OutOfBounds, JSValueRegs(), 0, outOfBounds);
1725
1726     m_jit.loadPtr(MacroAssembler::Address(baseReg, JSString::offsetOfValue()), scratchReg);
1727
1728     // Load the character into scratchReg
1729     JITCompiler::Jump is16Bit = m_jit.branchTest32(MacroAssembler::Zero, MacroAssembler::Address(scratchReg, StringImpl::flagsOffset()), TrustedImm32(StringImpl::flagIs8Bit()));
1730
1731     m_jit.load8(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesOne, 0), scratchReg);
1732     JITCompiler::Jump cont8Bit = m_jit.jump();
1733
1734     is16Bit.link(&m_jit);
1735
1736     m_jit.load16(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesTwo, 0), scratchReg);
1737
1738     JITCompiler::Jump bigCharacter =
1739         m_jit.branch32(MacroAssembler::AboveOrEqual, scratchReg, TrustedImm32(0x100));
1740
1741     // 8 bit string values don't need the isASCII check.
1742     cont8Bit.link(&m_jit);
1743
1744     m_jit.lshift32(MacroAssembler::TrustedImm32(sizeof(void*) == 4 ? 2 : 3), scratchReg);
1745     m_jit.addPtr(MacroAssembler::TrustedImmPtr(m_jit.vm()->smallStrings.singleCharacterStrings()), scratchReg);
1746     m_jit.loadPtr(scratchReg, scratchReg);
1747
1748     addSlowPathGenerator(
1749         slowPathCall(
1750             bigCharacter, this, operationSingleCharacterString, scratchReg, scratchReg));
1751
1752     if (node->arrayMode().isOutOfBounds()) {
1753 #if USE(JSVALUE32_64)
1754         m_jit.move(TrustedImm32(JSValue::CellTag), resultTagReg);
1755 #endif
1756
1757         JSGlobalObject* globalObject = m_jit.globalObjectFor(node->origin.semantic);
1758         if (globalObject->stringPrototypeChainIsSane()) {
1759 #if USE(JSVALUE64)
1760             addSlowPathGenerator(std::make_unique<SaneStringGetByValSlowPathGenerator>(
1761                 outOfBounds, this, JSValueRegs(scratchReg), baseReg, propertyReg));
1762 #else
1763             addSlowPathGenerator(std::make_unique<SaneStringGetByValSlowPathGenerator>(
1764                 outOfBounds, this, JSValueRegs(resultTagReg, scratchReg),
1765                 baseReg, propertyReg));
1766 #endif
1767         } else {
1768 #if USE(JSVALUE64)
1769             addSlowPathGenerator(
1770                 slowPathCall(
1771                     outOfBounds, this, operationGetByValStringInt,
1772                     scratchReg, baseReg, propertyReg));
1773 #else
1774             addSlowPathGenerator(
1775                 slowPathCall(
1776                     outOfBounds, this, operationGetByValStringInt,
1777                     resultTagReg, scratchReg, baseReg, propertyReg));
1778 #endif
1779         }
1780         
1781 #if USE(JSVALUE64)
1782         jsValueResult(scratchReg, m_currentNode);
1783 #else
1784         jsValueResult(resultTagReg, scratchReg, m_currentNode);
1785 #endif
1786     } else
1787         cellResult(scratchReg, m_currentNode);
1788 }
1789
1790 void SpeculativeJIT::compileFromCharCode(Node* node)
1791 {
1792     SpeculateStrictInt32Operand property(this, node->child1());
1793     GPRReg propertyReg = property.gpr();
1794     GPRTemporary smallStrings(this);
1795     GPRTemporary scratch(this);
1796     GPRReg scratchReg = scratch.gpr();
1797     GPRReg smallStringsReg = smallStrings.gpr();
1798
1799     JITCompiler::JumpList slowCases;
1800     slowCases.append(m_jit.branch32(MacroAssembler::AboveOrEqual, propertyReg, TrustedImm32(0xff)));
1801     m_jit.move(MacroAssembler::TrustedImmPtr(m_jit.vm()->smallStrings.singleCharacterStrings()), smallStringsReg);
1802     m_jit.loadPtr(MacroAssembler::BaseIndex(smallStringsReg, propertyReg, MacroAssembler::ScalePtr, 0), scratchReg);
1803
1804     slowCases.append(m_jit.branchTest32(MacroAssembler::Zero, scratchReg));
1805     addSlowPathGenerator(slowPathCall(slowCases, this, operationStringFromCharCode, scratchReg, propertyReg));
1806     cellResult(scratchReg, m_currentNode);
1807 }
1808
1809 GeneratedOperandType SpeculativeJIT::checkGeneratedTypeForToInt32(Node* node)
1810 {
1811     VirtualRegister virtualRegister = node->virtualRegister();
1812     GenerationInfo& info = generationInfoFromVirtualRegister(virtualRegister);
1813
1814     switch (info.registerFormat()) {
1815     case DataFormatStorage:
1816         RELEASE_ASSERT_NOT_REACHED();
1817
1818     case DataFormatBoolean:
1819     case DataFormatCell:
1820         terminateSpeculativeExecution(Uncountable, JSValueRegs(), 0);
1821         return GeneratedOperandTypeUnknown;
1822
1823     case DataFormatNone:
1824     case DataFormatJSCell:
1825     case DataFormatJS:
1826     case DataFormatJSBoolean:
1827     case DataFormatJSDouble:
1828         return GeneratedOperandJSValue;
1829
1830     case DataFormatJSInt32:
1831     case DataFormatInt32:
1832         return GeneratedOperandInteger;
1833
1834     default:
1835         RELEASE_ASSERT_NOT_REACHED();
1836         return GeneratedOperandTypeUnknown;
1837     }
1838 }
1839
1840 void SpeculativeJIT::compileValueToInt32(Node* node)
1841 {
1842     switch (node->child1().useKind()) {
1843 #if USE(JSVALUE64)
1844     case Int52RepUse: {
1845         SpeculateStrictInt52Operand op1(this, node->child1());
1846         GPRTemporary result(this, Reuse, op1);
1847         GPRReg op1GPR = op1.gpr();
1848         GPRReg resultGPR = result.gpr();
1849         m_jit.zeroExtend32ToPtr(op1GPR, resultGPR);
1850         int32Result(resultGPR, node, DataFormatInt32);
1851         return;
1852     }
1853 #endif // USE(JSVALUE64)
1854         
1855     case DoubleRepUse: {
1856         GPRTemporary result(this);
1857         SpeculateDoubleOperand op1(this, node->child1());
1858         FPRReg fpr = op1.fpr();
1859         GPRReg gpr = result.gpr();
1860         JITCompiler::Jump notTruncatedToInteger = m_jit.branchTruncateDoubleToInt32(fpr, gpr, JITCompiler::BranchIfTruncateFailed);
1861         
1862         addSlowPathGenerator(slowPathCall(notTruncatedToInteger, this, toInt32, gpr, fpr));
1863         
1864         int32Result(gpr, node);
1865         return;
1866     }
1867     
1868     case NumberUse:
1869     case NotCellUse: {
1870         switch (checkGeneratedTypeForToInt32(node->child1().node())) {
1871         case GeneratedOperandInteger: {
1872             SpeculateInt32Operand op1(this, node->child1(), ManualOperandSpeculation);
1873             GPRTemporary result(this, Reuse, op1);
1874             m_jit.move(op1.gpr(), result.gpr());
1875             int32Result(result.gpr(), node, op1.format());
1876             return;
1877         }
1878         case GeneratedOperandJSValue: {
1879             GPRTemporary result(this);
1880 #if USE(JSVALUE64)
1881             JSValueOperand op1(this, node->child1(), ManualOperandSpeculation);
1882
1883             GPRReg gpr = op1.gpr();
1884             GPRReg resultGpr = result.gpr();
1885             FPRTemporary tempFpr(this);
1886             FPRReg fpr = tempFpr.fpr();
1887
1888             JITCompiler::Jump isInteger = m_jit.branch64(MacroAssembler::AboveOrEqual, gpr, GPRInfo::tagTypeNumberRegister);
1889             JITCompiler::JumpList converted;
1890
1891             if (node->child1().useKind() == NumberUse) {
1892                 DFG_TYPE_CHECK(
1893                     JSValueRegs(gpr), node->child1(), SpecBytecodeNumber,
1894                     m_jit.branchTest64(
1895                         MacroAssembler::Zero, gpr, GPRInfo::tagTypeNumberRegister));
1896             } else {
1897                 JITCompiler::Jump isNumber = m_jit.branchTest64(MacroAssembler::NonZero, gpr, GPRInfo::tagTypeNumberRegister);
1898                 
1899                 DFG_TYPE_CHECK(
1900                     JSValueRegs(gpr), node->child1(), ~SpecCell, m_jit.branchIfCell(JSValueRegs(gpr)));
1901                 
1902                 // It's not a cell: so true turns into 1 and all else turns into 0.
1903                 m_jit.compare64(JITCompiler::Equal, gpr, TrustedImm32(ValueTrue), resultGpr);
1904                 converted.append(m_jit.jump());
1905                 
1906                 isNumber.link(&m_jit);
1907             }
1908
1909             // First, if we get here we have a double encoded as a JSValue
1910             m_jit.move(gpr, resultGpr);
1911             unboxDouble(resultGpr, fpr);
1912
1913             silentSpillAllRegisters(resultGpr);
1914             callOperation(toInt32, resultGpr, fpr);
1915             silentFillAllRegisters(resultGpr);
1916
1917             converted.append(m_jit.jump());
1918
1919             isInteger.link(&m_jit);
1920             m_jit.zeroExtend32ToPtr(gpr, resultGpr);
1921
1922             converted.link(&m_jit);
1923 #else
1924             Node* childNode = node->child1().node();
1925             VirtualRegister virtualRegister = childNode->virtualRegister();
1926             GenerationInfo& info = generationInfoFromVirtualRegister(virtualRegister);
1927
1928             JSValueOperand op1(this, node->child1(), ManualOperandSpeculation);
1929
1930             GPRReg payloadGPR = op1.payloadGPR();
1931             GPRReg resultGpr = result.gpr();
1932         
1933             JITCompiler::JumpList converted;
1934
1935             if (info.registerFormat() == DataFormatJSInt32)
1936                 m_jit.move(payloadGPR, resultGpr);
1937             else {
1938                 GPRReg tagGPR = op1.tagGPR();
1939                 FPRTemporary tempFpr(this);
1940                 FPRReg fpr = tempFpr.fpr();
1941                 FPRTemporary scratch(this);
1942
1943                 JITCompiler::Jump isInteger = m_jit.branch32(MacroAssembler::Equal, tagGPR, TrustedImm32(JSValue::Int32Tag));
1944
1945                 if (node->child1().useKind() == NumberUse) {
1946                     DFG_TYPE_CHECK(
1947                         op1.jsValueRegs(), node->child1(), SpecBytecodeNumber,
1948                         m_jit.branch32(
1949                             MacroAssembler::AboveOrEqual, tagGPR,
1950                             TrustedImm32(JSValue::LowestTag)));
1951                 } else {
1952                     JITCompiler::Jump isNumber = m_jit.branch32(MacroAssembler::Below, tagGPR, TrustedImm32(JSValue::LowestTag));
1953                     
1954                     DFG_TYPE_CHECK(
1955                         op1.jsValueRegs(), node->child1(), ~SpecCell,
1956                         m_jit.branchIfCell(op1.jsValueRegs()));
1957                     
1958                     // It's not a cell: so true turns into 1 and all else turns into 0.
1959                     JITCompiler::Jump isBoolean = m_jit.branch32(JITCompiler::Equal, tagGPR, TrustedImm32(JSValue::BooleanTag));
1960                     m_jit.move(TrustedImm32(0), resultGpr);
1961                     converted.append(m_jit.jump());
1962                     
1963                     isBoolean.link(&m_jit);
1964                     m_jit.move(payloadGPR, resultGpr);
1965                     converted.append(m_jit.jump());
1966                     
1967                     isNumber.link(&m_jit);
1968                 }
1969
1970                 unboxDouble(tagGPR, payloadGPR, fpr, scratch.fpr());
1971
1972                 silentSpillAllRegisters(resultGpr);
1973                 callOperation(toInt32, resultGpr, fpr);
1974                 silentFillAllRegisters(resultGpr);
1975
1976                 converted.append(m_jit.jump());
1977
1978                 isInteger.link(&m_jit);
1979                 m_jit.move(payloadGPR, resultGpr);
1980
1981                 converted.link(&m_jit);
1982             }
1983 #endif
1984             int32Result(resultGpr, node);
1985             return;
1986         }
1987         case GeneratedOperandTypeUnknown:
1988             RELEASE_ASSERT(!m_compileOkay);
1989             return;
1990         }
1991         RELEASE_ASSERT_NOT_REACHED();
1992         return;
1993     }
1994     
1995     default:
1996         ASSERT(!m_compileOkay);
1997         return;
1998     }
1999 }
2000
2001 void SpeculativeJIT::compileUInt32ToNumber(Node* node)
2002 {
2003     if (doesOverflow(node->arithMode())) {
2004         // We know that this sometimes produces doubles. So produce a double every
2005         // time. This at least allows subsequent code to not have weird conditionals.
2006             
2007         SpeculateInt32Operand op1(this, node->child1());
2008         FPRTemporary result(this);
2009             
2010         GPRReg inputGPR = op1.gpr();
2011         FPRReg outputFPR = result.fpr();
2012             
2013         m_jit.convertInt32ToDouble(inputGPR, outputFPR);
2014             
2015         JITCompiler::Jump positive = m_jit.branch32(MacroAssembler::GreaterThanOrEqual, inputGPR, TrustedImm32(0));
2016         m_jit.addDouble(JITCompiler::AbsoluteAddress(&AssemblyHelpers::twoToThe32), outputFPR);
2017         positive.link(&m_jit);
2018             
2019         doubleResult(outputFPR, node);
2020         return;
2021     }
2022     
2023     RELEASE_ASSERT(node->arithMode() == Arith::CheckOverflow);
2024
2025     SpeculateInt32Operand op1(this, node->child1());
2026     GPRTemporary result(this);
2027
2028     m_jit.move(op1.gpr(), result.gpr());
2029
2030     speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::LessThan, result.gpr(), TrustedImm32(0)));
2031
2032     int32Result(result.gpr(), node, op1.format());
2033 }
2034
2035 void SpeculativeJIT::compileDoubleAsInt32(Node* node)
2036 {
2037     SpeculateDoubleOperand op1(this, node->child1());
2038     FPRTemporary scratch(this);
2039     GPRTemporary result(this);
2040     
2041     FPRReg valueFPR = op1.fpr();
2042     FPRReg scratchFPR = scratch.fpr();
2043     GPRReg resultGPR = result.gpr();
2044
2045     JITCompiler::JumpList failureCases;
2046     RELEASE_ASSERT(shouldCheckOverflow(node->arithMode()));
2047     m_jit.branchConvertDoubleToInt32(
2048         valueFPR, resultGPR, failureCases, scratchFPR,
2049         shouldCheckNegativeZero(node->arithMode()));
2050     speculationCheck(Overflow, JSValueRegs(), 0, failureCases);
2051
2052     int32Result(resultGPR, node);
2053 }
2054
2055 void SpeculativeJIT::compileDoubleRep(Node* node)
2056 {
2057     switch (node->child1().useKind()) {
2058     case NumberUse: {
2059         ASSERT(!node->child1()->isNumberConstant()); // This should have been constant folded.
2060     
2061         if (isInt32Speculation(m_state.forNode(node->child1()).m_type)) {
2062             SpeculateInt32Operand op1(this, node->child1(), ManualOperandSpeculation);
2063             FPRTemporary result(this);
2064             m_jit.convertInt32ToDouble(op1.gpr(), result.fpr());
2065             doubleResult(result.fpr(), node);
2066             return;
2067         }
2068     
2069         JSValueOperand op1(this, node->child1(), ManualOperandSpeculation);
2070         FPRTemporary result(this);
2071     
2072 #if USE(JSVALUE64)
2073         GPRTemporary temp(this);
2074
2075         GPRReg op1GPR = op1.gpr();
2076         GPRReg tempGPR = temp.gpr();
2077         FPRReg resultFPR = result.fpr();
2078     
2079         JITCompiler::Jump isInteger = m_jit.branch64(
2080             MacroAssembler::AboveOrEqual, op1GPR, GPRInfo::tagTypeNumberRegister);
2081     
2082         if (needsTypeCheck(node->child1(), SpecBytecodeNumber)) {
2083             typeCheck(
2084                 JSValueRegs(op1GPR), node->child1(), SpecBytecodeNumber,
2085                 m_jit.branchTest64(MacroAssembler::Zero, op1GPR, GPRInfo::tagTypeNumberRegister));
2086         }
2087     
2088         m_jit.move(op1GPR, tempGPR);
2089         unboxDouble(tempGPR, resultFPR);
2090         JITCompiler::Jump done = m_jit.jump();
2091     
2092         isInteger.link(&m_jit);
2093         m_jit.convertInt32ToDouble(op1GPR, resultFPR);
2094         done.link(&m_jit);
2095 #else // USE(JSVALUE64) -> this is the 32_64 case
2096         FPRTemporary temp(this);
2097     
2098         GPRReg op1TagGPR = op1.tagGPR();
2099         GPRReg op1PayloadGPR = op1.payloadGPR();
2100         FPRReg tempFPR = temp.fpr();
2101         FPRReg resultFPR = result.fpr();
2102     
2103         JITCompiler::Jump isInteger = m_jit.branch32(
2104             MacroAssembler::Equal, op1TagGPR, TrustedImm32(JSValue::Int32Tag));
2105     
2106         if (needsTypeCheck(node->child1(), SpecBytecodeNumber)) {
2107             typeCheck(
2108                 JSValueRegs(op1TagGPR, op1PayloadGPR), node->child1(), SpecBytecodeNumber,
2109                 m_jit.branch32(MacroAssembler::AboveOrEqual, op1TagGPR, TrustedImm32(JSValue::LowestTag)));
2110         }
2111     
2112         unboxDouble(op1TagGPR, op1PayloadGPR, resultFPR, tempFPR);
2113         JITCompiler::Jump done = m_jit.jump();
2114     
2115         isInteger.link(&m_jit);
2116         m_jit.convertInt32ToDouble(op1PayloadGPR, resultFPR);
2117         done.link(&m_jit);
2118 #endif // USE(JSVALUE64)
2119     
2120         doubleResult(resultFPR, node);
2121         return;
2122     }
2123         
2124 #if USE(JSVALUE64)
2125     case Int52RepUse: {
2126         SpeculateStrictInt52Operand value(this, node->child1());
2127         FPRTemporary result(this);
2128         
2129         GPRReg valueGPR = value.gpr();
2130         FPRReg resultFPR = result.fpr();
2131
2132         m_jit.convertInt64ToDouble(valueGPR, resultFPR);
2133         
2134         doubleResult(resultFPR, node);
2135         return;
2136     }
2137 #endif // USE(JSVALUE64)
2138         
2139     default:
2140         RELEASE_ASSERT_NOT_REACHED();
2141         return;
2142     }
2143 }
2144
2145 void SpeculativeJIT::compileValueRep(Node* node)
2146 {
2147     switch (node->child1().useKind()) {
2148     case DoubleRepUse: {
2149         SpeculateDoubleOperand value(this, node->child1());
2150         JSValueRegsTemporary result(this);
2151         
2152         FPRReg valueFPR = value.fpr();
2153         JSValueRegs resultRegs = result.regs();
2154         
2155         // It's very tempting to in-place filter the value to indicate that it's not impure NaN
2156         // anymore. Unfortunately, this would be unsound. If it's a GetLocal or if the value was
2157         // subject to a prior SetLocal, filtering the value would imply that the corresponding
2158         // local was purified.
2159         if (needsTypeCheck(node->child1(), ~SpecDoubleImpureNaN))
2160             m_jit.purifyNaN(valueFPR);
2161
2162         boxDouble(valueFPR, resultRegs);
2163         
2164         jsValueResult(resultRegs, node);
2165         return;
2166     }
2167         
2168 #if USE(JSVALUE64)
2169     case Int52RepUse: {
2170         SpeculateStrictInt52Operand value(this, node->child1());
2171         GPRTemporary result(this);
2172         
2173         GPRReg valueGPR = value.gpr();
2174         GPRReg resultGPR = result.gpr();
2175         
2176         boxInt52(valueGPR, resultGPR, DataFormatStrictInt52);
2177         
2178         jsValueResult(resultGPR, node);
2179         return;
2180     }
2181 #endif // USE(JSVALUE64)
2182         
2183     default:
2184         RELEASE_ASSERT_NOT_REACHED();
2185         return;
2186     }
2187 }
2188
2189 static double clampDoubleToByte(double d)
2190 {
2191     d += 0.5;
2192     if (!(d > 0))
2193         d = 0;
2194     else if (d > 255)
2195         d = 255;
2196     return d;
2197 }
2198
2199 static void compileClampIntegerToByte(JITCompiler& jit, GPRReg result)
2200 {
2201     MacroAssembler::Jump inBounds = jit.branch32(MacroAssembler::BelowOrEqual, result, JITCompiler::TrustedImm32(0xff));
2202     MacroAssembler::Jump tooBig = jit.branch32(MacroAssembler::GreaterThan, result, JITCompiler::TrustedImm32(0xff));
2203     jit.xorPtr(result, result);
2204     MacroAssembler::Jump clamped = jit.jump();
2205     tooBig.link(&jit);
2206     jit.move(JITCompiler::TrustedImm32(255), result);
2207     clamped.link(&jit);
2208     inBounds.link(&jit);
2209 }
2210
2211 static void compileClampDoubleToByte(JITCompiler& jit, GPRReg result, FPRReg source, FPRReg scratch)
2212 {
2213     // Unordered compare so we pick up NaN
2214     static const double zero = 0;
2215     static const double byteMax = 255;
2216     static const double half = 0.5;
2217     jit.loadDouble(MacroAssembler::TrustedImmPtr(&zero), scratch);
2218     MacroAssembler::Jump tooSmall = jit.branchDouble(MacroAssembler::DoubleLessThanOrEqualOrUnordered, source, scratch);
2219     jit.loadDouble(MacroAssembler::TrustedImmPtr(&byteMax), scratch);
2220     MacroAssembler::Jump tooBig = jit.branchDouble(MacroAssembler::DoubleGreaterThan, source, scratch);
2221     
2222     jit.loadDouble(MacroAssembler::TrustedImmPtr(&half), scratch);
2223     // FIXME: This should probably just use a floating point round!
2224     // https://bugs.webkit.org/show_bug.cgi?id=72054
2225     jit.addDouble(source, scratch);
2226     jit.truncateDoubleToInt32(scratch, result);   
2227     MacroAssembler::Jump truncatedInt = jit.jump();
2228     
2229     tooSmall.link(&jit);
2230     jit.xorPtr(result, result);
2231     MacroAssembler::Jump zeroed = jit.jump();
2232     
2233     tooBig.link(&jit);
2234     jit.move(JITCompiler::TrustedImm32(255), result);
2235     
2236     truncatedInt.link(&jit);
2237     zeroed.link(&jit);
2238
2239 }
2240
2241 JITCompiler::Jump SpeculativeJIT::jumpForTypedArrayOutOfBounds(Node* node, GPRReg baseGPR, GPRReg indexGPR)
2242 {
2243     if (node->op() == PutByValAlias)
2244         return JITCompiler::Jump();
2245     JSArrayBufferView* view = m_jit.graph().tryGetFoldableView(
2246         m_state.forNode(m_jit.graph().child(node, 0)).m_value, node->arrayMode());
2247     if (view) {
2248         uint32_t length = view->length();
2249         Node* indexNode = m_jit.graph().child(node, 1).node();
2250         if (indexNode->isInt32Constant() && indexNode->asUInt32() < length)
2251             return JITCompiler::Jump();
2252         return m_jit.branch32(
2253             MacroAssembler::AboveOrEqual, indexGPR, MacroAssembler::Imm32(length));
2254     }
2255     return m_jit.branch32(
2256         MacroAssembler::AboveOrEqual, indexGPR,
2257         MacroAssembler::Address(baseGPR, JSArrayBufferView::offsetOfLength()));
2258 }
2259
2260 void SpeculativeJIT::emitTypedArrayBoundsCheck(Node* node, GPRReg baseGPR, GPRReg indexGPR)
2261 {
2262     JITCompiler::Jump jump = jumpForTypedArrayOutOfBounds(node, baseGPR, indexGPR);
2263     if (!jump.isSet())
2264         return;
2265     speculationCheck(OutOfBounds, JSValueRegs(), 0, jump);
2266 }
2267
2268 void SpeculativeJIT::compileGetByValOnIntTypedArray(Node* node, TypedArrayType type)
2269 {
2270     ASSERT(isInt(type));
2271     
2272     SpeculateCellOperand base(this, node->child1());
2273     SpeculateStrictInt32Operand property(this, node->child2());
2274     StorageOperand storage(this, node->child3());
2275
2276     GPRReg baseReg = base.gpr();
2277     GPRReg propertyReg = property.gpr();
2278     GPRReg storageReg = storage.gpr();
2279
2280     GPRTemporary result(this);
2281     GPRReg resultReg = result.gpr();
2282
2283     ASSERT(node->arrayMode().alreadyChecked(m_jit.graph(), node, m_state.forNode(node->child1())));
2284
2285     emitTypedArrayBoundsCheck(node, baseReg, propertyReg);
2286     switch (elementSize(type)) {
2287     case 1:
2288         if (isSigned(type))
2289             m_jit.load8SignedExtendTo32(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesOne), resultReg);
2290         else
2291             m_jit.load8(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesOne), resultReg);
2292         break;
2293     case 2:
2294         if (isSigned(type))
2295             m_jit.load16SignedExtendTo32(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesTwo), resultReg);
2296         else
2297             m_jit.load16(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesTwo), resultReg);
2298         break;
2299     case 4:
2300         m_jit.load32(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesFour), resultReg);
2301         break;
2302     default:
2303         CRASH();
2304     }
2305     if (elementSize(type) < 4 || isSigned(type)) {
2306         int32Result(resultReg, node);
2307         return;
2308     }
2309     
2310     ASSERT(elementSize(type) == 4 && !isSigned(type));
2311     if (node->shouldSpeculateInt32()) {
2312         speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::LessThan, resultReg, TrustedImm32(0)));
2313         int32Result(resultReg, node);
2314         return;
2315     }
2316     
2317 #if USE(JSVALUE64)
2318     if (node->shouldSpeculateMachineInt()) {
2319         m_jit.zeroExtend32ToPtr(resultReg, resultReg);
2320         strictInt52Result(resultReg, node);
2321         return;
2322     }
2323 #endif
2324     
2325     FPRTemporary fresult(this);
2326     m_jit.convertInt32ToDouble(resultReg, fresult.fpr());
2327     JITCompiler::Jump positive = m_jit.branch32(MacroAssembler::GreaterThanOrEqual, resultReg, TrustedImm32(0));
2328     m_jit.addDouble(JITCompiler::AbsoluteAddress(&AssemblyHelpers::twoToThe32), fresult.fpr());
2329     positive.link(&m_jit);
2330     doubleResult(fresult.fpr(), node);
2331 }
2332
2333 void SpeculativeJIT::compilePutByValForIntTypedArray(GPRReg base, GPRReg property, Node* node, TypedArrayType type)
2334 {
2335     ASSERT(isInt(type));
2336     
2337     StorageOperand storage(this, m_jit.graph().varArgChild(node, 3));
2338     GPRReg storageReg = storage.gpr();
2339     
2340     Edge valueUse = m_jit.graph().varArgChild(node, 2);
2341     
2342     GPRTemporary value;
2343     GPRReg valueGPR = InvalidGPRReg;
2344     
2345     if (valueUse->isConstant()) {
2346         JSValue jsValue = valueUse->asJSValue();
2347         if (!jsValue.isNumber()) {
2348             terminateSpeculativeExecution(Uncountable, JSValueRegs(), 0);
2349             noResult(node);
2350             return;
2351         }
2352         double d = jsValue.asNumber();
2353         if (isClamped(type)) {
2354             ASSERT(elementSize(type) == 1);
2355             d = clampDoubleToByte(d);
2356         }
2357         GPRTemporary scratch(this);
2358         GPRReg scratchReg = scratch.gpr();
2359         m_jit.move(Imm32(toInt32(d)), scratchReg);
2360         value.adopt(scratch);
2361         valueGPR = scratchReg;
2362     } else {
2363         switch (valueUse.useKind()) {
2364         case Int32Use: {
2365             SpeculateInt32Operand valueOp(this, valueUse);
2366             GPRTemporary scratch(this);
2367             GPRReg scratchReg = scratch.gpr();
2368             m_jit.move(valueOp.gpr(), scratchReg);
2369             if (isClamped(type)) {
2370                 ASSERT(elementSize(type) == 1);
2371                 compileClampIntegerToByte(m_jit, scratchReg);
2372             }
2373             value.adopt(scratch);
2374             valueGPR = scratchReg;
2375             break;
2376         }
2377             
2378 #if USE(JSVALUE64)
2379         case Int52RepUse: {
2380             SpeculateStrictInt52Operand valueOp(this, valueUse);
2381             GPRTemporary scratch(this);
2382             GPRReg scratchReg = scratch.gpr();
2383             m_jit.move(valueOp.gpr(), scratchReg);
2384             if (isClamped(type)) {
2385                 ASSERT(elementSize(type) == 1);
2386                 MacroAssembler::Jump inBounds = m_jit.branch64(
2387                     MacroAssembler::BelowOrEqual, scratchReg, JITCompiler::TrustedImm64(0xff));
2388                 MacroAssembler::Jump tooBig = m_jit.branch64(
2389                     MacroAssembler::GreaterThan, scratchReg, JITCompiler::TrustedImm64(0xff));
2390                 m_jit.move(TrustedImm32(0), scratchReg);
2391                 MacroAssembler::Jump clamped = m_jit.jump();
2392                 tooBig.link(&m_jit);
2393                 m_jit.move(JITCompiler::TrustedImm32(255), scratchReg);
2394                 clamped.link(&m_jit);
2395                 inBounds.link(&m_jit);
2396             }
2397             value.adopt(scratch);
2398             valueGPR = scratchReg;
2399             break;
2400         }
2401 #endif // USE(JSVALUE64)
2402             
2403         case DoubleRepUse: {
2404             if (isClamped(type)) {
2405                 ASSERT(elementSize(type) == 1);
2406                 SpeculateDoubleOperand valueOp(this, valueUse);
2407                 GPRTemporary result(this);
2408                 FPRTemporary floatScratch(this);
2409                 FPRReg fpr = valueOp.fpr();
2410                 GPRReg gpr = result.gpr();
2411                 compileClampDoubleToByte(m_jit, gpr, fpr, floatScratch.fpr());
2412                 value.adopt(result);
2413                 valueGPR = gpr;
2414             } else {
2415                 SpeculateDoubleOperand valueOp(this, valueUse);
2416                 GPRTemporary result(this);
2417                 FPRReg fpr = valueOp.fpr();
2418                 GPRReg gpr = result.gpr();
2419                 MacroAssembler::Jump notNaN = m_jit.branchDouble(MacroAssembler::DoubleEqual, fpr, fpr);
2420                 m_jit.xorPtr(gpr, gpr);
2421                 MacroAssembler::Jump fixed = m_jit.jump();
2422                 notNaN.link(&m_jit);
2423                 
2424                 MacroAssembler::Jump failed = m_jit.branchTruncateDoubleToInt32(
2425                     fpr, gpr, MacroAssembler::BranchIfTruncateFailed);
2426                 
2427                 addSlowPathGenerator(slowPathCall(failed, this, toInt32, gpr, fpr));
2428                 
2429                 fixed.link(&m_jit);
2430                 value.adopt(result);
2431                 valueGPR = gpr;
2432             }
2433             break;
2434         }
2435             
2436         default:
2437             RELEASE_ASSERT_NOT_REACHED();
2438             break;
2439         }
2440     }
2441     
2442     ASSERT_UNUSED(valueGPR, valueGPR != property);
2443     ASSERT(valueGPR != base);
2444     ASSERT(valueGPR != storageReg);
2445     MacroAssembler::Jump outOfBounds = jumpForTypedArrayOutOfBounds(node, base, property);
2446     if (node->arrayMode().isInBounds() && outOfBounds.isSet()) {
2447         speculationCheck(OutOfBounds, JSValueSource(), 0, outOfBounds);
2448         outOfBounds = MacroAssembler::Jump();
2449     }
2450
2451     switch (elementSize(type)) {
2452     case 1:
2453         m_jit.store8(value.gpr(), MacroAssembler::BaseIndex(storageReg, property, MacroAssembler::TimesOne));
2454         break;
2455     case 2:
2456         m_jit.store16(value.gpr(), MacroAssembler::BaseIndex(storageReg, property, MacroAssembler::TimesTwo));
2457         break;
2458     case 4:
2459         m_jit.store32(value.gpr(), MacroAssembler::BaseIndex(storageReg, property, MacroAssembler::TimesFour));
2460         break;
2461     default:
2462         CRASH();
2463     }
2464     if (outOfBounds.isSet())
2465         outOfBounds.link(&m_jit);
2466     noResult(node);
2467 }
2468
2469 void SpeculativeJIT::compileGetByValOnFloatTypedArray(Node* node, TypedArrayType type)
2470 {
2471     ASSERT(isFloat(type));
2472     
2473     SpeculateCellOperand base(this, node->child1());
2474     SpeculateStrictInt32Operand property(this, node->child2());
2475     StorageOperand storage(this, node->child3());
2476
2477     GPRReg baseReg = base.gpr();
2478     GPRReg propertyReg = property.gpr();
2479     GPRReg storageReg = storage.gpr();
2480
2481     ASSERT(node->arrayMode().alreadyChecked(m_jit.graph(), node, m_state.forNode(node->child1())));
2482
2483     FPRTemporary result(this);
2484     FPRReg resultReg = result.fpr();
2485     emitTypedArrayBoundsCheck(node, baseReg, propertyReg);
2486     switch (elementSize(type)) {
2487     case 4:
2488         m_jit.loadFloat(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesFour), resultReg);
2489         m_jit.convertFloatToDouble(resultReg, resultReg);
2490         break;
2491     case 8: {
2492         m_jit.loadDouble(MacroAssembler::BaseIndex(storageReg, propertyReg, MacroAssembler::TimesEight), resultReg);
2493         break;
2494     }
2495     default:
2496         RELEASE_ASSERT_NOT_REACHED();
2497     }
2498     
2499     doubleResult(resultReg, node);
2500 }
2501
2502 void SpeculativeJIT::compilePutByValForFloatTypedArray(GPRReg base, GPRReg property, Node* node, TypedArrayType type)
2503 {
2504     ASSERT(isFloat(type));
2505     
2506     StorageOperand storage(this, m_jit.graph().varArgChild(node, 3));
2507     GPRReg storageReg = storage.gpr();
2508     
2509     Edge baseUse = m_jit.graph().varArgChild(node, 0);
2510     Edge valueUse = m_jit.graph().varArgChild(node, 2);
2511
2512     SpeculateDoubleOperand valueOp(this, valueUse);
2513     FPRTemporary scratch(this);
2514     FPRReg valueFPR = valueOp.fpr();
2515     FPRReg scratchFPR = scratch.fpr();
2516
2517     ASSERT_UNUSED(baseUse, node->arrayMode().alreadyChecked(m_jit.graph(), node, m_state.forNode(baseUse)));
2518     
2519     MacroAssembler::Jump outOfBounds = jumpForTypedArrayOutOfBounds(node, base, property);
2520     if (node->arrayMode().isInBounds() && outOfBounds.isSet()) {
2521         speculationCheck(OutOfBounds, JSValueSource(), 0, outOfBounds);
2522         outOfBounds = MacroAssembler::Jump();
2523     }
2524     
2525     switch (elementSize(type)) {
2526     case 4: {
2527         m_jit.moveDouble(valueFPR, scratchFPR);
2528         m_jit.convertDoubleToFloat(valueFPR, scratchFPR);
2529         m_jit.storeFloat(scratchFPR, MacroAssembler::BaseIndex(storageReg, property, MacroAssembler::TimesFour));
2530         break;
2531     }
2532     case 8:
2533         m_jit.storeDouble(valueFPR, MacroAssembler::BaseIndex(storageReg, property, MacroAssembler::TimesEight));
2534         break;
2535     default:
2536         RELEASE_ASSERT_NOT_REACHED();
2537     }
2538     if (outOfBounds.isSet())
2539         outOfBounds.link(&m_jit);
2540     noResult(node);
2541 }
2542
2543 void SpeculativeJIT::compileInstanceOfForObject(Node*, GPRReg valueReg, GPRReg prototypeReg, GPRReg scratchReg, GPRReg scratch2Reg)
2544 {
2545     // Check that prototype is an object.
2546     speculationCheck(BadType, JSValueRegs(), 0, m_jit.branchIfNotObject(prototypeReg));
2547     
2548     // Initialize scratchReg with the value being checked.
2549     m_jit.move(valueReg, scratchReg);
2550     
2551     // Walk up the prototype chain of the value (in scratchReg), comparing to prototypeReg.
2552     MacroAssembler::Label loop(&m_jit);
2553     m_jit.emitLoadStructure(scratchReg, scratchReg, scratch2Reg);
2554     m_jit.loadPtr(MacroAssembler::Address(scratchReg, Structure::prototypeOffset() + CellPayloadOffset), scratchReg);
2555     MacroAssembler::Jump isInstance = m_jit.branchPtr(MacroAssembler::Equal, scratchReg, prototypeReg);
2556 #if USE(JSVALUE64)
2557     m_jit.branchIfCell(JSValueRegs(scratchReg)).linkTo(loop, &m_jit);
2558 #else
2559     m_jit.branchTestPtr(MacroAssembler::NonZero, scratchReg).linkTo(loop, &m_jit);
2560 #endif
2561     
2562     // No match - result is false.
2563 #if USE(JSVALUE64)
2564     m_jit.move(MacroAssembler::TrustedImm64(JSValue::encode(jsBoolean(false))), scratchReg);
2565 #else
2566     m_jit.move(MacroAssembler::TrustedImm32(0), scratchReg);
2567 #endif
2568     MacroAssembler::Jump putResult = m_jit.jump();
2569     
2570     isInstance.link(&m_jit);
2571 #if USE(JSVALUE64)
2572     m_jit.move(MacroAssembler::TrustedImm64(JSValue::encode(jsBoolean(true))), scratchReg);
2573 #else
2574     m_jit.move(MacroAssembler::TrustedImm32(1), scratchReg);
2575 #endif
2576     
2577     putResult.link(&m_jit);
2578 }
2579
2580 void SpeculativeJIT::compileInstanceOf(Node* node)
2581 {
2582     if (node->child1().useKind() == UntypedUse) {
2583         // It might not be a cell. Speculate less aggressively.
2584         // Or: it might only be used once (i.e. by us), so we get zero benefit
2585         // from speculating any more aggressively than we absolutely need to.
2586         
2587         JSValueOperand value(this, node->child1());
2588         SpeculateCellOperand prototype(this, node->child2());
2589         GPRTemporary scratch(this);
2590         GPRTemporary scratch2(this);
2591         
2592         GPRReg prototypeReg = prototype.gpr();
2593         GPRReg scratchReg = scratch.gpr();
2594         GPRReg scratch2Reg = scratch2.gpr();
2595         
2596         MacroAssembler::Jump isCell = m_jit.branchIfCell(value.jsValueRegs());
2597         GPRReg valueReg = value.jsValueRegs().payloadGPR();
2598         moveFalseTo(scratchReg);
2599
2600         MacroAssembler::Jump done = m_jit.jump();
2601         
2602         isCell.link(&m_jit);
2603         
2604         compileInstanceOfForObject(node, valueReg, prototypeReg, scratchReg, scratch2Reg);
2605         
2606         done.link(&m_jit);
2607
2608         blessedBooleanResult(scratchReg, node);
2609         return;
2610     }
2611     
2612     SpeculateCellOperand value(this, node->child1());
2613     SpeculateCellOperand prototype(this, node->child2());
2614     
2615     GPRTemporary scratch(this);
2616     GPRTemporary scratch2(this);
2617     
2618     GPRReg valueReg = value.gpr();
2619     GPRReg prototypeReg = prototype.gpr();
2620     GPRReg scratchReg = scratch.gpr();
2621     GPRReg scratch2Reg = scratch2.gpr();
2622     
2623     compileInstanceOfForObject(node, valueReg, prototypeReg, scratchReg, scratch2Reg);
2624
2625     blessedBooleanResult(scratchReg, node);
2626 }
2627
2628 void SpeculativeJIT::compileAdd(Node* node)
2629 {
2630     switch (node->binaryUseKind()) {
2631     case Int32Use: {
2632         ASSERT(!shouldCheckNegativeZero(node->arithMode()));
2633         
2634         if (node->child1()->isInt32Constant()) {
2635             int32_t imm1 = node->child1()->asInt32();
2636             SpeculateInt32Operand op2(this, node->child2());
2637             GPRTemporary result(this);
2638
2639             if (!shouldCheckOverflow(node->arithMode())) {
2640                 m_jit.move(op2.gpr(), result.gpr());
2641                 m_jit.add32(Imm32(imm1), result.gpr());
2642             } else
2643                 speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchAdd32(MacroAssembler::Overflow, op2.gpr(), Imm32(imm1), result.gpr()));
2644
2645             int32Result(result.gpr(), node);
2646             return;
2647         }
2648         
2649         if (node->child2()->isInt32Constant()) {
2650             SpeculateInt32Operand op1(this, node->child1());
2651             int32_t imm2 = node->child2()->asInt32();
2652             GPRTemporary result(this);
2653                 
2654             if (!shouldCheckOverflow(node->arithMode())) {
2655                 m_jit.move(op1.gpr(), result.gpr());
2656                 m_jit.add32(Imm32(imm2), result.gpr());
2657             } else
2658                 speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchAdd32(MacroAssembler::Overflow, op1.gpr(), Imm32(imm2), result.gpr()));
2659
2660             int32Result(result.gpr(), node);
2661             return;
2662         }
2663                 
2664         SpeculateInt32Operand op1(this, node->child1());
2665         SpeculateInt32Operand op2(this, node->child2());
2666         GPRTemporary result(this, Reuse, op1, op2);
2667
2668         GPRReg gpr1 = op1.gpr();
2669         GPRReg gpr2 = op2.gpr();
2670         GPRReg gprResult = result.gpr();
2671
2672         if (!shouldCheckOverflow(node->arithMode())) {
2673             if (gpr1 == gprResult)
2674                 m_jit.add32(gpr2, gprResult);
2675             else {
2676                 m_jit.move(gpr2, gprResult);
2677                 m_jit.add32(gpr1, gprResult);
2678             }
2679         } else {
2680             MacroAssembler::Jump check = m_jit.branchAdd32(MacroAssembler::Overflow, gpr1, gpr2, gprResult);
2681                 
2682             if (gpr1 == gprResult)
2683                 speculationCheck(Overflow, JSValueRegs(), 0, check, SpeculationRecovery(SpeculativeAdd, gprResult, gpr2));
2684             else if (gpr2 == gprResult)
2685                 speculationCheck(Overflow, JSValueRegs(), 0, check, SpeculationRecovery(SpeculativeAdd, gprResult, gpr1));
2686             else
2687                 speculationCheck(Overflow, JSValueRegs(), 0, check);
2688         }
2689
2690         int32Result(gprResult, node);
2691         return;
2692     }
2693         
2694 #if USE(JSVALUE64)
2695     case Int52RepUse: {
2696         ASSERT(shouldCheckOverflow(node->arithMode()));
2697         ASSERT(!shouldCheckNegativeZero(node->arithMode()));
2698
2699         // Will we need an overflow check? If we can prove that neither input can be
2700         // Int52 then the overflow check will not be necessary.
2701         if (!m_state.forNode(node->child1()).couldBeType(SpecInt52)
2702             && !m_state.forNode(node->child2()).couldBeType(SpecInt52)) {
2703             SpeculateWhicheverInt52Operand op1(this, node->child1());
2704             SpeculateWhicheverInt52Operand op2(this, node->child2(), op1);
2705             GPRTemporary result(this, Reuse, op1);
2706             m_jit.move(op1.gpr(), result.gpr());
2707             m_jit.add64(op2.gpr(), result.gpr());
2708             int52Result(result.gpr(), node, op1.format());
2709             return;
2710         }
2711         
2712         SpeculateInt52Operand op1(this, node->child1());
2713         SpeculateInt52Operand op2(this, node->child2());
2714         GPRTemporary result(this);
2715         m_jit.move(op1.gpr(), result.gpr());
2716         speculationCheck(
2717             Int52Overflow, JSValueRegs(), 0,
2718             m_jit.branchAdd64(MacroAssembler::Overflow, op2.gpr(), result.gpr()));
2719         int52Result(result.gpr(), node);
2720         return;
2721     }
2722 #endif // USE(JSVALUE64)
2723     
2724     case DoubleRepUse: {
2725         SpeculateDoubleOperand op1(this, node->child1());
2726         SpeculateDoubleOperand op2(this, node->child2());
2727         FPRTemporary result(this, op1, op2);
2728
2729         FPRReg reg1 = op1.fpr();
2730         FPRReg reg2 = op2.fpr();
2731         m_jit.addDouble(reg1, reg2, result.fpr());
2732
2733         doubleResult(result.fpr(), node);
2734         return;
2735     }
2736         
2737     default:
2738         RELEASE_ASSERT_NOT_REACHED();
2739         break;
2740     }
2741 }
2742
2743 void SpeculativeJIT::compileMakeRope(Node* node)
2744 {
2745     ASSERT(node->child1().useKind() == KnownStringUse);
2746     ASSERT(node->child2().useKind() == KnownStringUse);
2747     ASSERT(!node->child3() || node->child3().useKind() == KnownStringUse);
2748     
2749     SpeculateCellOperand op1(this, node->child1());
2750     SpeculateCellOperand op2(this, node->child2());
2751     SpeculateCellOperand op3(this, node->child3());
2752     GPRTemporary result(this);
2753     GPRTemporary allocator(this);
2754     GPRTemporary scratch(this);
2755     
2756     GPRReg opGPRs[3];
2757     unsigned numOpGPRs;
2758     opGPRs[0] = op1.gpr();
2759     opGPRs[1] = op2.gpr();
2760     if (node->child3()) {
2761         opGPRs[2] = op3.gpr();
2762         numOpGPRs = 3;
2763     } else {
2764         opGPRs[2] = InvalidGPRReg;
2765         numOpGPRs = 2;
2766     }
2767     GPRReg resultGPR = result.gpr();
2768     GPRReg allocatorGPR = allocator.gpr();
2769     GPRReg scratchGPR = scratch.gpr();
2770     
2771     JITCompiler::JumpList slowPath;
2772     MarkedAllocator& markedAllocator = m_jit.vm()->heap.allocatorForObjectWithDestructor(sizeof(JSRopeString));
2773     m_jit.move(TrustedImmPtr(&markedAllocator), allocatorGPR);
2774     emitAllocateJSCell(resultGPR, allocatorGPR, TrustedImmPtr(m_jit.vm()->stringStructure.get()), scratchGPR, slowPath);
2775         
2776     m_jit.storePtr(TrustedImmPtr(0), JITCompiler::Address(resultGPR, JSString::offsetOfValue()));
2777     for (unsigned i = 0; i < numOpGPRs; ++i)
2778         m_jit.storePtr(opGPRs[i], JITCompiler::Address(resultGPR, JSRopeString::offsetOfFibers() + sizeof(WriteBarrier<JSString>) * i));
2779     for (unsigned i = numOpGPRs; i < JSRopeString::s_maxInternalRopeLength; ++i)
2780         m_jit.storePtr(TrustedImmPtr(0), JITCompiler::Address(resultGPR, JSRopeString::offsetOfFibers() + sizeof(WriteBarrier<JSString>) * i));
2781     m_jit.load32(JITCompiler::Address(opGPRs[0], JSString::offsetOfFlags()), scratchGPR);
2782     m_jit.load32(JITCompiler::Address(opGPRs[0], JSString::offsetOfLength()), allocatorGPR);
2783     if (!ASSERT_DISABLED) {
2784         JITCompiler::Jump ok = m_jit.branch32(
2785             JITCompiler::GreaterThanOrEqual, allocatorGPR, TrustedImm32(0));
2786         m_jit.abortWithReason(DFGNegativeStringLength);
2787         ok.link(&m_jit);
2788     }
2789     for (unsigned i = 1; i < numOpGPRs; ++i) {
2790         m_jit.and32(JITCompiler::Address(opGPRs[i], JSString::offsetOfFlags()), scratchGPR);
2791         speculationCheck(
2792             Uncountable, JSValueSource(), nullptr,
2793             m_jit.branchAdd32(
2794                 JITCompiler::Overflow,
2795                 JITCompiler::Address(opGPRs[i], JSString::offsetOfLength()), allocatorGPR));
2796     }
2797     m_jit.and32(JITCompiler::TrustedImm32(JSString::Is8Bit), scratchGPR);
2798     m_jit.store32(scratchGPR, JITCompiler::Address(resultGPR, JSString::offsetOfFlags()));
2799     if (!ASSERT_DISABLED) {
2800         JITCompiler::Jump ok = m_jit.branch32(
2801             JITCompiler::GreaterThanOrEqual, allocatorGPR, TrustedImm32(0));
2802         m_jit.abortWithReason(DFGNegativeStringLength);
2803         ok.link(&m_jit);
2804     }
2805     m_jit.store32(allocatorGPR, JITCompiler::Address(resultGPR, JSString::offsetOfLength()));
2806     
2807     switch (numOpGPRs) {
2808     case 2:
2809         addSlowPathGenerator(slowPathCall(
2810             slowPath, this, operationMakeRope2, resultGPR, opGPRs[0], opGPRs[1]));
2811         break;
2812     case 3:
2813         addSlowPathGenerator(slowPathCall(
2814             slowPath, this, operationMakeRope3, resultGPR, opGPRs[0], opGPRs[1], opGPRs[2]));
2815         break;
2816     default:
2817         RELEASE_ASSERT_NOT_REACHED();
2818         break;
2819     }
2820         
2821     cellResult(resultGPR, node);
2822 }
2823
2824 void SpeculativeJIT::compileArithClz32(Node* node)
2825 {
2826     ASSERT_WITH_MESSAGE(node->child1().useKind() == Int32Use || node->child1().useKind() == KnownInt32Use, "The Fixup phase should have enforced a Int32 operand.");
2827     SpeculateInt32Operand value(this, node->child1());
2828     GPRTemporary result(this, Reuse, value);
2829     GPRReg valueReg = value.gpr();
2830     GPRReg resultReg = result.gpr();
2831     m_jit.countLeadingZeros32(valueReg, resultReg);
2832     int32Result(resultReg, node);
2833 }
2834
2835 void SpeculativeJIT::compileArithSub(Node* node)
2836 {
2837     switch (node->binaryUseKind()) {
2838     case Int32Use: {
2839         ASSERT(!shouldCheckNegativeZero(node->arithMode()));
2840         
2841         if (node->child2()->isNumberConstant()) {
2842             SpeculateInt32Operand op1(this, node->child1());
2843             int32_t imm2 = node->child2()->asInt32();
2844             GPRTemporary result(this);
2845
2846             if (!shouldCheckOverflow(node->arithMode())) {
2847                 m_jit.move(op1.gpr(), result.gpr());
2848                 m_jit.sub32(Imm32(imm2), result.gpr());
2849             } else {
2850                 GPRTemporary scratch(this);
2851                 speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchSub32(MacroAssembler::Overflow, op1.gpr(), Imm32(imm2), result.gpr(), scratch.gpr()));
2852             }
2853
2854             int32Result(result.gpr(), node);
2855             return;
2856         }
2857             
2858         if (node->child1()->isNumberConstant()) {
2859             int32_t imm1 = node->child1()->asInt32();
2860             SpeculateInt32Operand op2(this, node->child2());
2861             GPRTemporary result(this);
2862                 
2863             m_jit.move(Imm32(imm1), result.gpr());
2864             if (!shouldCheckOverflow(node->arithMode()))
2865                 m_jit.sub32(op2.gpr(), result.gpr());
2866             else
2867                 speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchSub32(MacroAssembler::Overflow, op2.gpr(), result.gpr()));
2868                 
2869             int32Result(result.gpr(), node);
2870             return;
2871         }
2872             
2873         SpeculateInt32Operand op1(this, node->child1());
2874         SpeculateInt32Operand op2(this, node->child2());
2875         GPRTemporary result(this);
2876
2877         if (!shouldCheckOverflow(node->arithMode())) {
2878             m_jit.move(op1.gpr(), result.gpr());
2879             m_jit.sub32(op2.gpr(), result.gpr());
2880         } else
2881             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchSub32(MacroAssembler::Overflow, op1.gpr(), op2.gpr(), result.gpr()));
2882
2883         int32Result(result.gpr(), node);
2884         return;
2885     }
2886         
2887 #if USE(JSVALUE64)
2888     case Int52RepUse: {
2889         ASSERT(shouldCheckOverflow(node->arithMode()));
2890         ASSERT(!shouldCheckNegativeZero(node->arithMode()));
2891
2892         // Will we need an overflow check? If we can prove that neither input can be
2893         // Int52 then the overflow check will not be necessary.
2894         if (!m_state.forNode(node->child1()).couldBeType(SpecInt52)
2895             && !m_state.forNode(node->child2()).couldBeType(SpecInt52)) {
2896             SpeculateWhicheverInt52Operand op1(this, node->child1());
2897             SpeculateWhicheverInt52Operand op2(this, node->child2(), op1);
2898             GPRTemporary result(this, Reuse, op1);
2899             m_jit.move(op1.gpr(), result.gpr());
2900             m_jit.sub64(op2.gpr(), result.gpr());
2901             int52Result(result.gpr(), node, op1.format());
2902             return;
2903         }
2904         
2905         SpeculateInt52Operand op1(this, node->child1());
2906         SpeculateInt52Operand op2(this, node->child2());
2907         GPRTemporary result(this);
2908         m_jit.move(op1.gpr(), result.gpr());
2909         speculationCheck(
2910             Int52Overflow, JSValueRegs(), 0,
2911             m_jit.branchSub64(MacroAssembler::Overflow, op2.gpr(), result.gpr()));
2912         int52Result(result.gpr(), node);
2913         return;
2914     }
2915 #endif // USE(JSVALUE64)
2916
2917     case DoubleRepUse: {
2918         SpeculateDoubleOperand op1(this, node->child1());
2919         SpeculateDoubleOperand op2(this, node->child2());
2920         FPRTemporary result(this, op1);
2921
2922         FPRReg reg1 = op1.fpr();
2923         FPRReg reg2 = op2.fpr();
2924         m_jit.subDouble(reg1, reg2, result.fpr());
2925
2926         doubleResult(result.fpr(), node);
2927         return;
2928     }
2929         
2930     default:
2931         RELEASE_ASSERT_NOT_REACHED();
2932         return;
2933     }
2934 }
2935
2936 void SpeculativeJIT::compileArithNegate(Node* node)
2937 {
2938     switch (node->child1().useKind()) {
2939     case Int32Use: {
2940         SpeculateInt32Operand op1(this, node->child1());
2941         GPRTemporary result(this);
2942
2943         m_jit.move(op1.gpr(), result.gpr());
2944
2945         // Note: there is no notion of being not used as a number, but someone
2946         // caring about negative zero.
2947         
2948         if (!shouldCheckOverflow(node->arithMode()))
2949             m_jit.neg32(result.gpr());
2950         else if (!shouldCheckNegativeZero(node->arithMode()))
2951             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchNeg32(MacroAssembler::Overflow, result.gpr()));
2952         else {
2953             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(MacroAssembler::Zero, result.gpr(), TrustedImm32(0x7fffffff)));
2954             m_jit.neg32(result.gpr());
2955         }
2956
2957         int32Result(result.gpr(), node);
2958         return;
2959     }
2960
2961 #if USE(JSVALUE64)
2962     case Int52RepUse: {
2963         ASSERT(shouldCheckOverflow(node->arithMode()));
2964         
2965         if (!m_state.forNode(node->child1()).couldBeType(SpecInt52)) {
2966             SpeculateWhicheverInt52Operand op1(this, node->child1());
2967             GPRTemporary result(this);
2968             GPRReg op1GPR = op1.gpr();
2969             GPRReg resultGPR = result.gpr();
2970             m_jit.move(op1GPR, resultGPR);
2971             m_jit.neg64(resultGPR);
2972             if (shouldCheckNegativeZero(node->arithMode())) {
2973                 speculationCheck(
2974                     NegativeZero, JSValueRegs(), 0,
2975                     m_jit.branchTest64(MacroAssembler::Zero, resultGPR));
2976             }
2977             int52Result(resultGPR, node, op1.format());
2978             return;
2979         }
2980         
2981         SpeculateInt52Operand op1(this, node->child1());
2982         GPRTemporary result(this);
2983         GPRReg op1GPR = op1.gpr();
2984         GPRReg resultGPR = result.gpr();
2985         m_jit.move(op1GPR, resultGPR);
2986         speculationCheck(
2987             Int52Overflow, JSValueRegs(), 0,
2988             m_jit.branchNeg64(MacroAssembler::Overflow, resultGPR));
2989         if (shouldCheckNegativeZero(node->arithMode())) {
2990             speculationCheck(
2991                 NegativeZero, JSValueRegs(), 0,
2992                 m_jit.branchTest64(MacroAssembler::Zero, resultGPR));
2993         }
2994         int52Result(resultGPR, node);
2995         return;
2996     }
2997 #endif // USE(JSVALUE64)
2998         
2999     case DoubleRepUse: {
3000         SpeculateDoubleOperand op1(this, node->child1());
3001         FPRTemporary result(this);
3002         
3003         m_jit.negateDouble(op1.fpr(), result.fpr());
3004         
3005         doubleResult(result.fpr(), node);
3006         return;
3007     }
3008         
3009     default:
3010         RELEASE_ASSERT_NOT_REACHED();
3011         return;
3012     }
3013 }
3014 void SpeculativeJIT::compileArithMul(Node* node)
3015 {
3016     switch (node->binaryUseKind()) {
3017     case Int32Use: {
3018         SpeculateInt32Operand op1(this, node->child1());
3019         SpeculateInt32Operand op2(this, node->child2());
3020         GPRTemporary result(this);
3021
3022         GPRReg reg1 = op1.gpr();
3023         GPRReg reg2 = op2.gpr();
3024
3025         // We can perform truncated multiplications if we get to this point, because if the
3026         // fixup phase could not prove that it would be safe, it would have turned us into
3027         // a double multiplication.
3028         if (!shouldCheckOverflow(node->arithMode())) {
3029             m_jit.move(reg1, result.gpr());
3030             m_jit.mul32(reg2, result.gpr());
3031         } else {
3032             speculationCheck(
3033                 Overflow, JSValueRegs(), 0,
3034                 m_jit.branchMul32(MacroAssembler::Overflow, reg1, reg2, result.gpr()));
3035         }
3036             
3037         // Check for negative zero, if the users of this node care about such things.
3038         if (shouldCheckNegativeZero(node->arithMode())) {
3039             MacroAssembler::Jump resultNonZero = m_jit.branchTest32(MacroAssembler::NonZero, result.gpr());
3040             speculationCheck(NegativeZero, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::LessThan, reg1, TrustedImm32(0)));
3041             speculationCheck(NegativeZero, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::LessThan, reg2, TrustedImm32(0)));
3042             resultNonZero.link(&m_jit);
3043         }
3044
3045         int32Result(result.gpr(), node);
3046         return;
3047     }
3048     
3049 #if USE(JSVALUE64)   
3050     case Int52RepUse: {
3051         ASSERT(shouldCheckOverflow(node->arithMode()));
3052         
3053         // This is super clever. We want to do an int52 multiplication and check the
3054         // int52 overflow bit. There is no direct hardware support for this, but we do
3055         // have the ability to do an int64 multiplication and check the int64 overflow
3056         // bit. We leverage that. Consider that a, b are int52 numbers inside int64
3057         // registers, with the high 12 bits being sign-extended. We can do:
3058         //
3059         //     (a * (b << 12))
3060         //
3061         // This will give us a left-shifted int52 (value is in high 52 bits, low 16
3062         // bits are zero) plus the int52 overflow bit. I.e. whether this 64-bit
3063         // multiplication overflows is identical to whether the 'a * b' 52-bit
3064         // multiplication overflows.
3065         //
3066         // In our nomenclature, this is:
3067         //
3068         //     strictInt52(a) * int52(b) => int52
3069         //
3070         // That is "strictInt52" means unshifted and "int52" means left-shifted by 16
3071         // bits.
3072         //
3073         // We don't care which of op1 or op2 serves as the left-shifted operand, so
3074         // we just do whatever is more convenient for op1 and have op2 do the
3075         // opposite. This ensures that we do at most one shift.
3076
3077         SpeculateWhicheverInt52Operand op1(this, node->child1());
3078         SpeculateWhicheverInt52Operand op2(this, node->child2(), OppositeShift, op1);
3079         GPRTemporary result(this);
3080         
3081         GPRReg op1GPR = op1.gpr();
3082         GPRReg op2GPR = op2.gpr();
3083         GPRReg resultGPR = result.gpr();
3084         
3085         m_jit.move(op1GPR, resultGPR);
3086         speculationCheck(
3087             Int52Overflow, JSValueRegs(), 0,
3088             m_jit.branchMul64(MacroAssembler::Overflow, op2GPR, resultGPR));
3089         
3090         if (shouldCheckNegativeZero(node->arithMode())) {
3091             MacroAssembler::Jump resultNonZero = m_jit.branchTest64(
3092                 MacroAssembler::NonZero, resultGPR);
3093             speculationCheck(
3094                 NegativeZero, JSValueRegs(), 0,
3095                 m_jit.branch64(MacroAssembler::LessThan, op1GPR, TrustedImm64(0)));
3096             speculationCheck(
3097                 NegativeZero, JSValueRegs(), 0,
3098                 m_jit.branch64(MacroAssembler::LessThan, op2GPR, TrustedImm64(0)));
3099             resultNonZero.link(&m_jit);
3100         }
3101         
3102         int52Result(resultGPR, node);
3103         return;
3104     }
3105 #endif // USE(JSVALUE64)
3106         
3107     case DoubleRepUse: {
3108         SpeculateDoubleOperand op1(this, node->child1());
3109         SpeculateDoubleOperand op2(this, node->child2());
3110         FPRTemporary result(this, op1, op2);
3111         
3112         FPRReg reg1 = op1.fpr();
3113         FPRReg reg2 = op2.fpr();
3114         
3115         m_jit.mulDouble(reg1, reg2, result.fpr());
3116         
3117         doubleResult(result.fpr(), node);
3118         return;
3119     }
3120         
3121     default:
3122         RELEASE_ASSERT_NOT_REACHED();
3123         return;
3124     }
3125 }
3126
3127 void SpeculativeJIT::compileArithDiv(Node* node)
3128 {
3129     switch (node->binaryUseKind()) {
3130     case Int32Use: {
3131 #if CPU(X86) || CPU(X86_64)
3132         SpeculateInt32Operand op1(this, node->child1());
3133         SpeculateInt32Operand op2(this, node->child2());
3134         GPRTemporary eax(this, X86Registers::eax);
3135         GPRTemporary edx(this, X86Registers::edx);
3136         GPRReg op1GPR = op1.gpr();
3137         GPRReg op2GPR = op2.gpr();
3138     
3139         GPRReg op2TempGPR;
3140         GPRReg temp;
3141         if (op2GPR == X86Registers::eax || op2GPR == X86Registers::edx) {
3142             op2TempGPR = allocate();
3143             temp = op2TempGPR;
3144         } else {
3145             op2TempGPR = InvalidGPRReg;
3146             if (op1GPR == X86Registers::eax)
3147                 temp = X86Registers::edx;
3148             else
3149                 temp = X86Registers::eax;
3150         }
3151     
3152         ASSERT(temp != op1GPR);
3153         ASSERT(temp != op2GPR);
3154     
3155         m_jit.add32(JITCompiler::TrustedImm32(1), op2GPR, temp);
3156     
3157         JITCompiler::Jump safeDenominator = m_jit.branch32(JITCompiler::Above, temp, JITCompiler::TrustedImm32(1));
3158     
3159         JITCompiler::JumpList done;
3160         if (shouldCheckOverflow(node->arithMode())) {
3161             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, op2GPR));
3162             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branch32(JITCompiler::Equal, op1GPR, TrustedImm32(-2147483647-1)));
3163         } else {
3164             // This is the case where we convert the result to an int after we're done, and we
3165             // already know that the denominator is either -1 or 0. So, if the denominator is
3166             // zero, then the result should be zero. If the denominator is not zero (i.e. it's
3167             // -1) and the numerator is -2^31 then the result should be -2^31. Otherwise we
3168             // are happy to fall through to a normal division, since we're just dividing
3169             // something by negative 1.
3170         
3171             JITCompiler::Jump notZero = m_jit.branchTest32(JITCompiler::NonZero, op2GPR);
3172             m_jit.move(TrustedImm32(0), eax.gpr());
3173             done.append(m_jit.jump());
3174         
3175             notZero.link(&m_jit);
3176             JITCompiler::Jump notNeg2ToThe31 =
3177                 m_jit.branch32(JITCompiler::NotEqual, op1GPR, TrustedImm32(-2147483647-1));
3178             m_jit.zeroExtend32ToPtr(op1GPR, eax.gpr());
3179             done.append(m_jit.jump());
3180         
3181             notNeg2ToThe31.link(&m_jit);
3182         }
3183     
3184         safeDenominator.link(&m_jit);
3185     
3186         // If the user cares about negative zero, then speculate that we're not about
3187         // to produce negative zero.
3188         if (shouldCheckNegativeZero(node->arithMode())) {
3189             MacroAssembler::Jump numeratorNonZero = m_jit.branchTest32(MacroAssembler::NonZero, op1GPR);
3190             speculationCheck(NegativeZero, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::LessThan, op2GPR, TrustedImm32(0)));
3191             numeratorNonZero.link(&m_jit);
3192         }
3193     
3194         if (op2TempGPR != InvalidGPRReg) {
3195             m_jit.move(op2GPR, op2TempGPR);
3196             op2GPR = op2TempGPR;
3197         }
3198             
3199         m_jit.move(op1GPR, eax.gpr());
3200         m_jit.assembler().cdq();
3201         m_jit.assembler().idivl_r(op2GPR);
3202             
3203         if (op2TempGPR != InvalidGPRReg)
3204             unlock(op2TempGPR);
3205
3206         // Check that there was no remainder. If there had been, then we'd be obligated to
3207         // produce a double result instead.
3208         if (shouldCheckOverflow(node->arithMode()))
3209             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::NonZero, edx.gpr()));
3210         
3211         done.link(&m_jit);
3212         int32Result(eax.gpr(), node);
3213 #elif HAVE(ARM_IDIV_INSTRUCTIONS) || CPU(ARM64)
3214         SpeculateInt32Operand op1(this, node->child1());
3215         SpeculateInt32Operand op2(this, node->child2());
3216         GPRReg op1GPR = op1.gpr();
3217         GPRReg op2GPR = op2.gpr();
3218         GPRTemporary quotient(this);
3219         GPRTemporary multiplyAnswer(this);
3220
3221         // If the user cares about negative zero, then speculate that we're not about
3222         // to produce negative zero.
3223         if (shouldCheckNegativeZero(node->arithMode())) {
3224             MacroAssembler::Jump numeratorNonZero = m_jit.branchTest32(MacroAssembler::NonZero, op1GPR);
3225             speculationCheck(NegativeZero, JSValueRegs(), 0, m_jit.branch32(MacroAssembler::LessThan, op2GPR, TrustedImm32(0)));
3226             numeratorNonZero.link(&m_jit);
3227         }
3228
3229         m_jit.assembler().sdiv<32>(quotient.gpr(), op1GPR, op2GPR);
3230
3231         // Check that there was no remainder. If there had been, then we'd be obligated to
3232         // produce a double result instead.
3233         if (shouldCheckOverflow(node->arithMode())) {
3234             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchMul32(JITCompiler::Overflow, quotient.gpr(), op2GPR, multiplyAnswer.gpr()));
3235             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branch32(JITCompiler::NotEqual, multiplyAnswer.gpr(), op1GPR));
3236         }
3237
3238         int32Result(quotient.gpr(), node);
3239 #else
3240         RELEASE_ASSERT_NOT_REACHED();
3241 #endif
3242         break;
3243     }
3244         
3245     case DoubleRepUse: {
3246         SpeculateDoubleOperand op1(this, node->child1());
3247         SpeculateDoubleOperand op2(this, node->child2());
3248         FPRTemporary result(this, op1);
3249         
3250         FPRReg reg1 = op1.fpr();
3251         FPRReg reg2 = op2.fpr();
3252         m_jit.divDouble(reg1, reg2, result.fpr());
3253         
3254         doubleResult(result.fpr(), node);
3255         break;
3256     }
3257         
3258     default:
3259         RELEASE_ASSERT_NOT_REACHED();
3260         break;
3261     }
3262 }
3263
3264 void SpeculativeJIT::compileArithMod(Node* node)
3265 {
3266     switch (node->binaryUseKind()) {
3267     case Int32Use: {
3268         // In the fast path, the dividend value could be the final result
3269         // (in case of |dividend| < |divisor|), so we speculate it as strict int32.
3270         SpeculateStrictInt32Operand op1(this, node->child1());
3271         
3272         if (node->child2()->isInt32Constant()) {
3273             int32_t divisor = node->child2()->asInt32();
3274             if (divisor > 1 && hasOneBitSet(divisor)) {
3275                 unsigned logarithm = WTF::fastLog2(divisor);
3276                 GPRReg dividendGPR = op1.gpr();
3277                 GPRTemporary result(this);
3278                 GPRReg resultGPR = result.gpr();
3279
3280                 // This is what LLVM generates. It's pretty crazy. Here's my
3281                 // attempt at understanding it.
3282                 
3283                 // First, compute either divisor - 1, or 0, depending on whether
3284                 // the dividend is negative:
3285                 //
3286                 // If dividend < 0:  resultGPR = divisor - 1
3287                 // If dividend >= 0: resultGPR = 0
3288                 m_jit.move(dividendGPR, resultGPR);
3289                 m_jit.rshift32(TrustedImm32(31), resultGPR);
3290                 m_jit.urshift32(TrustedImm32(32 - logarithm), resultGPR);
3291                 
3292                 // Add in the dividend, so that:
3293                 //
3294                 // If dividend < 0:  resultGPR = dividend + divisor - 1
3295                 // If dividend >= 0: resultGPR = dividend
3296                 m_jit.add32(dividendGPR, resultGPR);
3297                 
3298                 // Mask so as to only get the *high* bits. This rounds down
3299                 // (towards negative infinity) resultGPR to the nearest multiple
3300                 // of divisor, so that:
3301                 //
3302                 // If dividend < 0:  resultGPR = floor((dividend + divisor - 1) / divisor)
3303                 // If dividend >= 0: resultGPR = floor(dividend / divisor)
3304                 //
3305                 // Note that this can be simplified to:
3306                 //
3307                 // If dividend < 0:  resultGPR = ceil(dividend / divisor)
3308                 // If dividend >= 0: resultGPR = floor(dividend / divisor)
3309                 //
3310                 // Note that if the dividend is negative, resultGPR will also be negative.
3311                 // Regardless of the sign of dividend, resultGPR will be rounded towards
3312                 // zero, because of how things are conditionalized.
3313                 m_jit.and32(TrustedImm32(-divisor), resultGPR);
3314                 
3315                 // Subtract resultGPR from dividendGPR, which yields the remainder:
3316                 //
3317                 // resultGPR = dividendGPR - resultGPR
3318                 m_jit.neg32(resultGPR);
3319                 m_jit.add32(dividendGPR, resultGPR);
3320                 
3321                 if (shouldCheckNegativeZero(node->arithMode())) {
3322                     // Check that we're not about to create negative zero.
3323                     JITCompiler::Jump numeratorPositive = m_jit.branch32(JITCompiler::GreaterThanOrEqual, dividendGPR, TrustedImm32(0));
3324                     speculationCheck(NegativeZero, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, resultGPR));
3325                     numeratorPositive.link(&m_jit);
3326                 }
3327
3328                 int32Result(resultGPR, node);
3329                 return;
3330             }
3331         }
3332         
3333 #if CPU(X86) || CPU(X86_64)
3334         if (node->child2()->isInt32Constant()) {
3335             int32_t divisor = node->child2()->asInt32();
3336             if (divisor && divisor != -1) {
3337                 GPRReg op1Gpr = op1.gpr();
3338
3339                 GPRTemporary eax(this, X86Registers::eax);
3340                 GPRTemporary edx(this, X86Registers::edx);
3341                 GPRTemporary scratch(this);
3342                 GPRReg scratchGPR = scratch.gpr();
3343
3344                 GPRReg op1SaveGPR;
3345                 if (op1Gpr == X86Registers::eax || op1Gpr == X86Registers::edx) {
3346                     op1SaveGPR = allocate();
3347                     ASSERT(op1Gpr != op1SaveGPR);
3348                     m_jit.move(op1Gpr, op1SaveGPR);
3349                 } else
3350                     op1SaveGPR = op1Gpr;
3351                 ASSERT(op1SaveGPR != X86Registers::eax);
3352                 ASSERT(op1SaveGPR != X86Registers::edx);
3353
3354                 m_jit.move(op1Gpr, eax.gpr());
3355                 m_jit.move(TrustedImm32(divisor), scratchGPR);
3356                 m_jit.assembler().cdq();
3357                 m_jit.assembler().idivl_r(scratchGPR);
3358                 if (shouldCheckNegativeZero(node->arithMode())) {
3359                     JITCompiler::Jump numeratorPositive = m_jit.branch32(JITCompiler::GreaterThanOrEqual, op1SaveGPR, TrustedImm32(0));
3360                     speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, edx.gpr()));
3361                     numeratorPositive.link(&m_jit);
3362                 }
3363             
3364                 if (op1SaveGPR != op1Gpr)
3365                     unlock(op1SaveGPR);
3366
3367                 int32Result(edx.gpr(), node);
3368                 return;
3369             }
3370         }
3371 #endif
3372
3373         SpeculateInt32Operand op2(this, node->child2());
3374 #if CPU(X86) || CPU(X86_64)
3375         GPRTemporary eax(this, X86Registers::eax);
3376         GPRTemporary edx(this, X86Registers::edx);
3377         GPRReg op1GPR = op1.gpr();
3378         GPRReg op2GPR = op2.gpr();
3379     
3380         GPRReg op2TempGPR;
3381         GPRReg temp;
3382         GPRReg op1SaveGPR;
3383     
3384         if (op2GPR == X86Registers::eax || op2GPR == X86Registers::edx) {
3385             op2TempGPR = allocate();
3386             temp = op2TempGPR;
3387         } else {
3388             op2TempGPR = InvalidGPRReg;
3389             if (op1GPR == X86Registers::eax)
3390                 temp = X86Registers::edx;
3391             else
3392                 temp = X86Registers::eax;
3393         }
3394     
3395         if (op1GPR == X86Registers::eax || op1GPR == X86Registers::edx) {
3396             op1SaveGPR = allocate();
3397             ASSERT(op1GPR != op1SaveGPR);
3398             m_jit.move(op1GPR, op1SaveGPR);
3399         } else
3400             op1SaveGPR = op1GPR;
3401     
3402         ASSERT(temp != op1GPR);
3403         ASSERT(temp != op2GPR);
3404         ASSERT(op1SaveGPR != X86Registers::eax);
3405         ASSERT(op1SaveGPR != X86Registers::edx);
3406     
3407         m_jit.add32(JITCompiler::TrustedImm32(1), op2GPR, temp);
3408     
3409         JITCompiler::Jump safeDenominator = m_jit.branch32(JITCompiler::Above, temp, JITCompiler::TrustedImm32(1));
3410     
3411         JITCompiler::JumpList done;
3412         
3413         // FIXME: -2^31 / -1 will actually yield negative zero, so we could have a
3414         // separate case for that. But it probably doesn't matter so much.
3415         if (shouldCheckOverflow(node->arithMode())) {
3416             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, op2GPR));
3417             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branch32(JITCompiler::Equal, op1GPR, TrustedImm32(-2147483647-1)));
3418         } else {
3419             // This is the case where we convert the result to an int after we're done, and we
3420             // already know that the denominator is either -1 or 0. So, if the denominator is
3421             // zero, then the result should be zero. If the denominator is not zero (i.e. it's
3422             // -1) and the numerator is -2^31 then the result should be 0. Otherwise we are
3423             // happy to fall through to a normal division, since we're just dividing something
3424             // by negative 1.
3425         
3426             JITCompiler::Jump notZero = m_jit.branchTest32(JITCompiler::NonZero, op2GPR);
3427             m_jit.move(TrustedImm32(0), edx.gpr());
3428             done.append(m_jit.jump());
3429         
3430             notZero.link(&m_jit);
3431             JITCompiler::Jump notNeg2ToThe31 =
3432                 m_jit.branch32(JITCompiler::NotEqual, op1GPR, TrustedImm32(-2147483647-1));
3433             m_jit.move(TrustedImm32(0), edx.gpr());
3434             done.append(m_jit.jump());
3435         
3436             notNeg2ToThe31.link(&m_jit);
3437         }
3438         
3439         safeDenominator.link(&m_jit);
3440             
3441         if (op2TempGPR != InvalidGPRReg) {
3442             m_jit.move(op2GPR, op2TempGPR);
3443             op2GPR = op2TempGPR;
3444         }
3445             
3446         m_jit.move(op1GPR, eax.gpr());
3447         m_jit.assembler().cdq();
3448         m_jit.assembler().idivl_r(op2GPR);
3449             
3450         if (op2TempGPR != InvalidGPRReg)
3451             unlock(op2TempGPR);
3452
3453         // Check that we're not about to create negative zero.
3454         if (shouldCheckNegativeZero(node->arithMode())) {
3455             JITCompiler::Jump numeratorPositive = m_jit.branch32(JITCompiler::GreaterThanOrEqual, op1SaveGPR, TrustedImm32(0));
3456             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, edx.gpr()));
3457             numeratorPositive.link(&m_jit);
3458         }
3459     
3460         if (op1SaveGPR != op1GPR)
3461             unlock(op1SaveGPR);
3462             
3463         done.link(&m_jit);
3464         int32Result(edx.gpr(), node);
3465
3466 #elif HAVE(ARM_IDIV_INSTRUCTIONS) || CPU(ARM64)
3467         GPRTemporary temp(this);
3468         GPRTemporary quotientThenRemainder(this);
3469         GPRTemporary multiplyAnswer(this);
3470         GPRReg dividendGPR = op1.gpr();
3471         GPRReg divisorGPR = op2.gpr();
3472         GPRReg quotientThenRemainderGPR = quotientThenRemainder.gpr();
3473         GPRReg multiplyAnswerGPR = multiplyAnswer.gpr();
3474
3475         JITCompiler::JumpList done;
3476     
3477         if (shouldCheckOverflow(node->arithMode()))
3478             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, divisorGPR));
3479         else {
3480             JITCompiler::Jump denominatorNotZero = m_jit.branchTest32(JITCompiler::NonZero, divisorGPR);
3481             m_jit.move(divisorGPR, quotientThenRemainderGPR);
3482             done.append(m_jit.jump());
3483             denominatorNotZero.link(&m_jit);
3484         }
3485
3486         m_jit.assembler().sdiv<32>(quotientThenRemainderGPR, dividendGPR, divisorGPR);
3487         // FIXME: It seems like there are cases where we don't need this? What if we have
3488         // arithMode() == Arith::Unchecked?
3489         // https://bugs.webkit.org/show_bug.cgi?id=126444
3490         speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchMul32(JITCompiler::Overflow, quotientThenRemainderGPR, divisorGPR, multiplyAnswerGPR));
3491 #if HAVE(ARM_IDIV_INSTRUCTIONS)
3492         m_jit.assembler().sub(quotientThenRemainderGPR, dividendGPR, multiplyAnswerGPR);
3493 #else
3494         m_jit.assembler().sub<32>(quotientThenRemainderGPR, dividendGPR, multiplyAnswerGPR);
3495 #endif
3496
3497         // If the user cares about negative zero, then speculate that we're not about
3498         // to produce negative zero.
3499         if (shouldCheckNegativeZero(node->arithMode())) {
3500             // Check that we're not about to create negative zero.
3501             JITCompiler::Jump numeratorPositive = m_jit.branch32(JITCompiler::GreaterThanOrEqual, dividendGPR, TrustedImm32(0));
3502             speculationCheck(Overflow, JSValueRegs(), 0, m_jit.branchTest32(JITCompiler::Zero, quotientThenRemainderGPR));
3503             numeratorPositive.link(&m_jit);
3504         }
3505
3506         done.link(&m_jit);
3507
3508         int32Result(quotientThenRemainderGPR, node);
3509 #else // not architecture that can do integer division
3510         RELEASE_ASSERT_NOT_REACHED();
3511 #endif
3512         return;
3513     }
3514         
3515     case DoubleRepUse: {
3516         SpeculateDoubleOperand op1(this, node->child1());
3517         SpeculateDoubleOperand op2(this, node->child2());
3518         
3519         FPRReg op1FPR = op1.fpr();
3520         FPRReg op2FPR = op2.fpr();
3521         
3522         flushRegisters();
3523         
3524         FPRResult result(this);
3525         
3526         callOperation(fmodAsDFGOperation, result.fpr(), op1FPR, op2FPR);
3527         
3528         doubleResult(result.fpr(), node);
3529         return;
3530     }
3531         
3532     default:
3533         RELEASE_ASSERT_NOT_REACHED();
3534         return;
3535     }
3536 }
3537
3538 void SpeculativeJIT::compileArithSqrt(Node* node)
3539 {
3540     SpeculateDoubleOperand op1(this, node->child1());
3541     FPRReg op1FPR = op1.fpr();
3542
3543     if (!MacroAssembler::supportsFloatingPointSqrt() || !Options::enableArchitectureSpecificOptimizations()) {
3544         flushRegisters();
3545         FPRResult result(this);
3546         callOperation(sqrt, result.fpr(), op1FPR);
3547         doubleResult(result.fpr(), node);
3548     } else {
3549         FPRTemporary result(this, op1);
3550         m_jit.sqrtDouble(op1.fpr(), result.fpr());
3551         doubleResult(result.fpr(), node);
3552     }
3553 }
3554
3555 // For small positive integers , it is worth doing a tiny inline loop to exponentiate the base.
3556 // Every register is clobbered by this helper.
3557 static MacroAssembler::Jump compileArithPowIntegerFastPath(JITCompiler& assembler, FPRReg xOperand, GPRReg yOperand, FPRReg result)
3558 {
3559     MacroAssembler::JumpList skipFastPath;
3560     skipFastPath.append(assembler.branch32(MacroAssembler::LessThan, yOperand, MacroAssembler::TrustedImm32(0)));
3561     skipFastPath.append(assembler.branch32(MacroAssembler::GreaterThan, yOperand, MacroAssembler::TrustedImm32(1000)));
3562
3563     static const double oneConstant = 1.0;
3564     assembler.loadDouble(MacroAssembler::TrustedImmPtr(&oneConstant), result);
3565
3566     MacroAssembler::Label startLoop(assembler.label());
3567     MacroAssembler::Jump exponentIsEven = assembler.branchTest32(MacroAssembler::Zero, yOperand, MacroAssembler::TrustedImm32(1));
3568     assembler.mulDouble(xOperand, result);
3569     exponentIsEven.link(&assembler);
3570     assembler.mulDouble(xOperand, xOperand);
3571     assembler.rshift32(MacroAssembler::TrustedImm32(1), yOperand);
3572     assembler.branchTest32(MacroAssembler::NonZero, yOperand).linkTo(startLoop, &assembler);
3573
3574     MacroAssembler::Jump skipSlowPath = assembler.jump();
3575     skipFastPath.link(&assembler);
3576
3577     return skipSlowPath;
3578 }
3579
3580 void SpeculativeJIT::compileArithPow(Node* node)
3581 {
3582     if (node->child2().useKind() == Int32Use) {
3583         SpeculateDoubleOperand xOperand(this, node->child1());
3584         SpeculateInt32Operand yOperand(this, node->child2());
3585         FPRReg xOperandfpr = xOperand.fpr();
3586         GPRReg yOperandGpr = yOperand.gpr();
3587         FPRTemporary yOperandfpr(this);
3588
3589         flushRegisters();
3590
3591         FPRResult result(this);
3592         FPRReg resultFpr = result.fpr();
3593
3594         FPRTemporary xOperandCopy(this);
3595         FPRReg xOperandCopyFpr = xOperandCopy.fpr();
3596         m_jit.moveDouble(xOperandfpr, xOperandCopyFpr);
3597
3598         GPRTemporary counter(this);
3599         GPRReg counterGpr = counter.gpr();
3600         m_jit.move(yOperandGpr, counterGpr);
3601
3602         MacroAssembler::Jump skipFallback = compileArithPowIntegerFastPath(m_jit, xOperandCopyFpr, counterGpr, resultFpr);
3603         m_jit.convertInt32ToDouble(yOperandGpr, yOperandfpr.fpr());
3604         callOperation(operationMathPow, resultFpr, xOperandfpr, yOperandfpr.fpr());
3605
3606         skipFallback.link(&m_jit);
3607         doubleResult(resultFpr, node);
3608         return;
3609     }
3610
3611     SpeculateDoubleOperand xOperand(this, node->child1());
3612     SpeculateDoubleOperand yOperand(this, node->child2());
3613     FPRReg xOperandfpr = xOperand.fpr();
3614     FPRReg yOperandfpr = yOperand.fpr();
3615
3616     flushRegisters();
3617
3618     FPRResult result(this);
3619     FPRReg resultFpr = result.fpr();
3620
3621     FPRTemporary xOperandCopy(this);
3622     FPRReg xOperandCopyFpr = xOperandCopy.fpr();
3623
3624     FPRTemporary scratch(this);
3625     FPRReg scratchFpr = scratch.fpr();
3626
3627     GPRTemporary yOperandInteger(this);
3628     GPRReg yOperandIntegerGpr = yOperandInteger.gpr();
3629     MacroAssembler::JumpList failedExponentConversionToInteger;
3630     m_jit.branchConvertDoubleToInt32(yOperandfpr, yOperandIntegerGpr, failedExponentConversionToInteger, scratchFpr, false);
3631
3632     m_jit.moveDouble(xOperandfpr, xOperandCopyFpr);
3633     MacroAssembler::Jump skipFallback = compileArithPowIntegerFastPath(m_jit, xOperandCopyFpr, yOperandInteger.gpr(), resultFpr);
3634     failedExponentConversionToInteger.link(&m_jit);
3635
3636     callOperation(operationMathPow, resultFpr, xOperandfpr, yOperandfpr);
3637     skipFallback.link(&m_jit);
3638     doubleResult(resultFpr, node);
3639 }
3640
3641 void SpeculativeJIT::compileArithLog(Node* node)
3642 {
3643     SpeculateDoubleOperand op1(this, node->child1());
3644     FPRReg op1FPR = op1.fpr();
3645     flushRegisters();
3646     FPRResult result(this);
3647     callOperation(log, result.fpr(), op1FPR);
3648     doubleResult(result.fpr(), node);
3649 }
3650
3651 // Returns true if the compare is fused with a subsequent branch.
3652 bool SpeculativeJIT::compare(Node* node, MacroAssembler::RelationalCondition condition, MacroAssembler::DoubleCondition doubleCondition, S_JITOperation_EJJ operation)
3653 {
3654     if (compilePeepHoleBranch(node, condition, doubleCondition, operation))
3655         return true;
3656
3657     if (node->isBinaryUseKind(Int32Use)) {
3658         compileInt32Compare(node, condition);
3659         return false;
3660     }
3661     
3662 #if USE(JSVALUE64)
3663     if (node->isBinaryUseKind(Int52RepUse)) {
3664         compileInt52Compare(node, condition);
3665         return false;
3666     }
3667 #endif // USE(JSVALUE64)
3668     
3669     if (node->isBinaryUseKind(DoubleRepUse)) {
3670         compileDoubleCompare(node, doubleCondition);
3671         return false;
3672     }
3673     
3674     if (node->op() == CompareEq) {
3675         if (node->isBinaryUseKind(StringUse)) {
3676             compileStringEquality(node);
3677             return false;
3678         }
3679         
3680         if (node->isBinaryUseKind(BooleanUse)) {
3681             compileBooleanCompare(node, condition);
3682             return false;
3683         }
3684
3685         if (node->isBinaryUseKind(StringIdentUse)) {
3686             compileStringIdentEquality(node);
3687             return false;
3688         }
3689         
3690         if (node->isBinaryUseKind(ObjectUse)) {
3691             compileObjectEquality(node);
3692             return false;
3693         }
3694         
3695         if (node->isBinaryUseKind(ObjectUse, ObjectOrOtherUse)) {
3696             compileObjectToObjectOrOtherEquality(node->child1(), node->child2());
3697             return false;
3698         }
3699         
3700         if (node->isBinaryUseKind(ObjectOrOtherUse, ObjectUse)) {
3701             compileObjectToObjectOrOtherEquality(node->child2(), node->child1());
3702             return false;
3703         }
3704     }
3705     
3706     nonSpeculativeNonPeepholeCompare(node, condition, operation);
3707     return false;
3708 }
3709
3710 bool SpeculativeJIT::compileStrictEq(Node* node)
3711 {
3712     if (node->isBinaryUseKind(BooleanUse)) {
3713         unsigned branchIndexInBlock = detectPeepHoleBranch();
3714         if (branchIndexInBlock != UINT_MAX) {
3715             Node* branchNode = m_block->at(branchIndexInBlock);
3716             compilePeepHoleBooleanBranch(node, branchNode, MacroAssembler::Equal);
3717             use(node->child1());
3718             use(node->child2());
3719             m_indexInBlock = branchIndexInBlock;
3720             m_currentNode = branchNode;
3721             return true;
3722         }
3723         compileBooleanCompare(node, MacroAssembler::Equal);
3724         return false;
3725     }
3726
3727     if (node->isBinaryUseKind(Int32Use)) {
3728         unsigned branchIndexInBlock = detectPeepHoleBranch();
3729         if (branchIndexInBlock != UINT_MAX) {
3730             Node* branchNode = m_block->at(branchIndexInBlock);
3731             compilePeepHoleInt32Branch(node, branchNode, MacroAssembler::Equal);
3732             use(node->child1());
3733             use(node->child2());
3734             m_indexInBlock = branchIndexInBlock;
3735             m_currentNode = branchNode;
3736             return true;
3737         }
3738         compileInt32Compare(node, MacroAssembler::Equal);
3739         return false;
3740     }
3741     
3742 #if USE(JSVALUE64)   
3743     if (node->isBinaryUseKind(Int52RepUse)) {
3744         unsigned branchIndexInBlock = detectPeepHoleBranch();
3745         if (branchIndexInBlock != UINT_MAX) {
3746             Node* branchNode = m_block->at(branchIndexInBlock);
3747             compilePeepHoleInt52Branch(node, branchNode, MacroAssembler::Equal);
3748             use(node->child1());
3749             use(node->child2());
3750             m_indexInBlock = branchIndexInBlock;
3751             m_currentNode = branchNode;
3752             return true;
3753         }
3754         compileInt52Compare(node, MacroAssembler::Equal);
3755         return false;
3756     }
3757 #endif // USE(JSVALUE64)
3758
3759     if (node->isBinaryUseKind(DoubleRepUse)) {
3760         unsigned branchIndexInBlock = detectPeepHoleBranch();
3761         if (branchIndexInBlock != UINT_MAX) {
3762             Node* branchNode = m_block->at(branchIndexInBlock);
3763             compilePeepHoleDoubleBranch(node, branchNode, MacroAssembler::DoubleEqual);
3764             use(node->child1());
3765             use(node->child2());
3766             m_indexInBlock = branchIndexInBlock;
3767             m_currentNode = branchNode;
3768             return true;
3769         }
3770         compileDoubleCompare(node, MacroAssembler::DoubleEqual);
3771         return false;
3772     }
3773     
3774     if (node->isBinaryUseKind(StringUse)) {
3775         compileStringEquality(node);
3776         return false;
3777     }
3778     
3779     if (node->isBinaryUseKind(StringIdentUse)) {
3780         compileStringIdentEquality(node);
3781         return false;
3782     }
3783
3784     if (node->isBinaryUseKind(ObjectUse)) {
3785         unsigned branchIndexInBlock = detectPeepHoleBranch();
3786         if (branchIndexInBlock != UINT_MAX) {
3787             Node* branchNode = m_block->at(branchIndexInBlock);
3788             compilePeepHoleObjectEquality(node, branchNode);
3789             use(node->child1());
3790             use(node->child2());
3791             m_indexInBlock = branchIndexInBlock;
3792             m_currentNode = branchNode;
3793             return true;
3794         }
3795         compileObjectEquality(node);
3796         return false;
3797     }
3798
3799     if (node->isBinaryUseKind(MiscUse, UntypedUse)
3800         || node->isBinaryUseKind(UntypedUse, MiscUse)) {
3801         compileMiscStrictEq(node);
3802         return false;
3803     }
3804     
3805     if (node->isBinaryUseKind(StringIdentUse, NotStringVarUse)) {
3806         compileStringIdentToNotStringVarEquality(nod