Implement fast path for op_new_array in the baseline JIT
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009 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
28 #if ENABLE(JIT)
29 #include "JIT.h"
30
31 // This probably does not belong here; adding here for now as a quick Windows build fix.
32 #if ENABLE(ASSEMBLER) && CPU(X86) && !OS(MAC_OS_X)
33 #include "MacroAssembler.h"
34 JSC::MacroAssemblerX86Common::SSE2CheckState JSC::MacroAssemblerX86Common::s_sse2CheckState = NotCheckedSSE2;
35 #endif
36
37 #include "CodeBlock.h"
38 #include "CryptographicallyRandomNumber.h"
39 #include "DFGNode.h" // for DFG_SUCCESS_STATS
40 #include "Interpreter.h"
41 #include "JITInlineMethods.h"
42 #include "JITStubCall.h"
43 #include "JSArray.h"
44 #include "JSFunction.h"
45 #include "LinkBuffer.h"
46 #include "RepatchBuffer.h"
47 #include "ResultType.h"
48 #include "SamplingTool.h"
49
50 using namespace std;
51
52 namespace JSC {
53
54 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
55 {
56     RepatchBuffer repatchBuffer(codeblock);
57     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
58 }
59
60 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
61 {
62     RepatchBuffer repatchBuffer(codeblock);
63     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
64 }
65
66 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
67 {
68     RepatchBuffer repatchBuffer(codeblock);
69     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
70 }
71
72 JIT::JIT(JSGlobalData* globalData, CodeBlock* codeBlock)
73     : m_interpreter(globalData->interpreter)
74     , m_globalData(globalData)
75     , m_codeBlock(codeBlock)
76     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
77     , m_bytecodeOffset((unsigned)-1)
78 #if USE(JSVALUE32_64)
79     , m_jumpTargetIndex(0)
80     , m_mappedBytecodeOffset((unsigned)-1)
81     , m_mappedVirtualRegisterIndex(RegisterFile::ReturnPC)
82     , m_mappedTag((RegisterID)-1)
83     , m_mappedPayload((RegisterID)-1)
84 #else
85     , m_lastResultBytecodeRegister(std::numeric_limits<int>::max())
86     , m_jumpTargetsPosition(0)
87 #endif
88 #if USE(OS_RANDOMNESS)
89     , m_randomGenerator(cryptographicallyRandomNumber())
90 #else
91     , m_randomGenerator(static_cast<unsigned>(randomNumber() * 0xFFFFFFF))
92 #endif
93 {
94 }
95
96 #if ENABLE(DFG_JIT)
97 void JIT::emitOptimizationCheck(OptimizationCheckKind kind)
98 {
99     if (!shouldEmitProfiling())
100         return;
101     
102     Jump skipOptimize = branchAdd32(Signed, TrustedImm32(kind == LoopOptimizationCheck ? Options::executionCounterIncrementForLoop : Options::executionCounterIncrementForReturn), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter()));
103     JITStubCall stubCall(this, kind == LoopOptimizationCheck ? cti_optimize_from_loop : cti_optimize_from_ret);
104     if (kind == LoopOptimizationCheck)
105         stubCall.addArgument(Imm32(m_bytecodeOffset));
106     stubCall.call();
107     skipOptimize.link(this);
108 }
109 #endif
110
111 #if CPU(X86)
112 void JIT::emitTimeoutCheck()
113 {
114     Jump skipTimeout = branchSub32(NonZero, TrustedImm32(1), AbsoluteAddress(&m_globalData->m_timeoutCount));
115     JITStubCall stubCall(this, cti_timeout_check);
116     stubCall.addArgument(regT1, regT0); // save last result registers.
117     stubCall.call(regT0);
118     store32(regT0, &m_globalData->m_timeoutCount);
119     stubCall.getArgument(0, regT1, regT0); // reload last result registers.
120     skipTimeout.link(this);
121 }
122 #elif USE(JSVALUE32_64)
123 void JIT::emitTimeoutCheck()
124 {
125     Jump skipTimeout = branchSub32(NonZero, TrustedImm32(1), timeoutCheckRegister);
126     JITStubCall stubCall(this, cti_timeout_check);
127     stubCall.addArgument(regT1, regT0); // save last result registers.
128     stubCall.call(timeoutCheckRegister);
129     stubCall.getArgument(0, regT1, regT0); // reload last result registers.
130     skipTimeout.link(this);
131 }
132 #else
133 void JIT::emitTimeoutCheck()
134 {
135     Jump skipTimeout = branchSub32(NonZero, TrustedImm32(1), timeoutCheckRegister);
136     JITStubCall(this, cti_timeout_check).call(timeoutCheckRegister);
137     skipTimeout.link(this);
138
139     killLastResultRegister();
140 }
141 #endif
142
143 #define NEXT_OPCODE(name) \
144     m_bytecodeOffset += OPCODE_LENGTH(name); \
145     break;
146
147 #if USE(JSVALUE32_64)
148 #define DEFINE_BINARY_OP(name) \
149     case name: { \
150         JITStubCall stubCall(this, cti_##name); \
151         stubCall.addArgument(currentInstruction[2].u.operand); \
152         stubCall.addArgument(currentInstruction[3].u.operand); \
153         stubCall.call(currentInstruction[1].u.operand); \
154         NEXT_OPCODE(name); \
155     }
156
157 #define DEFINE_UNARY_OP(name) \
158     case name: { \
159         JITStubCall stubCall(this, cti_##name); \
160         stubCall.addArgument(currentInstruction[2].u.operand); \
161         stubCall.call(currentInstruction[1].u.operand); \
162         NEXT_OPCODE(name); \
163     }
164
165 #else // USE(JSVALUE32_64)
166
167 #define DEFINE_BINARY_OP(name) \
168     case name: { \
169         JITStubCall stubCall(this, cti_##name); \
170         stubCall.addArgument(currentInstruction[2].u.operand, regT2); \
171         stubCall.addArgument(currentInstruction[3].u.operand, regT2); \
172         stubCall.call(currentInstruction[1].u.operand); \
173         NEXT_OPCODE(name); \
174     }
175
176 #define DEFINE_UNARY_OP(name) \
177     case name: { \
178         JITStubCall stubCall(this, cti_##name); \
179         stubCall.addArgument(currentInstruction[2].u.operand, regT2); \
180         stubCall.call(currentInstruction[1].u.operand); \
181         NEXT_OPCODE(name); \
182     }
183 #endif // USE(JSVALUE32_64)
184
185 #define DEFINE_OP(name) \
186     case name: { \
187         emit_##name(currentInstruction); \
188         NEXT_OPCODE(name); \
189     }
190
191 #define DEFINE_SLOWCASE_OP(name) \
192     case name: { \
193         emitSlow_##name(currentInstruction, iter); \
194         NEXT_OPCODE(name); \
195     }
196
197 void JIT::privateCompileMainPass()
198 {
199     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
200     unsigned instructionCount = m_codeBlock->instructions().size();
201
202     m_globalResolveInfoIndex = 0;
203     m_callLinkInfoIndex = 0;
204
205     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
206         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
207         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
208
209 #if ENABLE(OPCODE_SAMPLING)
210         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
211             sampleInstruction(currentInstruction);
212 #endif
213
214 #if USE(JSVALUE64)
215         if (atJumpTarget())
216             killLastResultRegister();
217 #endif
218
219         m_labels[m_bytecodeOffset] = label();
220
221 #if ENABLE(JIT_VERBOSE)
222         dataLog("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
223 #endif
224
225         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
226         DEFINE_BINARY_OP(op_del_by_val)
227         DEFINE_BINARY_OP(op_in)
228         DEFINE_BINARY_OP(op_less)
229         DEFINE_BINARY_OP(op_lesseq)
230         DEFINE_BINARY_OP(op_greater)
231         DEFINE_BINARY_OP(op_greatereq)
232         DEFINE_UNARY_OP(op_is_boolean)
233         DEFINE_UNARY_OP(op_is_function)
234         DEFINE_UNARY_OP(op_is_number)
235         DEFINE_UNARY_OP(op_is_object)
236         DEFINE_UNARY_OP(op_is_string)
237         DEFINE_UNARY_OP(op_is_undefined)
238 #if USE(JSVALUE64)
239         DEFINE_UNARY_OP(op_negate)
240 #endif
241         DEFINE_UNARY_OP(op_typeof)
242
243         DEFINE_OP(op_add)
244         DEFINE_OP(op_bitand)
245         DEFINE_OP(op_bitnot)
246         DEFINE_OP(op_bitor)
247         DEFINE_OP(op_bitxor)
248         DEFINE_OP(op_call)
249         DEFINE_OP(op_call_eval)
250         DEFINE_OP(op_call_varargs)
251         DEFINE_OP(op_catch)
252         DEFINE_OP(op_construct)
253         DEFINE_OP(op_get_callee)
254         DEFINE_OP(op_create_this)
255         DEFINE_OP(op_convert_this)
256         DEFINE_OP(op_init_lazy_reg)
257         DEFINE_OP(op_create_arguments)
258         DEFINE_OP(op_debug)
259         DEFINE_OP(op_del_by_id)
260         DEFINE_OP(op_div)
261         DEFINE_OP(op_end)
262         DEFINE_OP(op_enter)
263         DEFINE_OP(op_create_activation)
264         DEFINE_OP(op_eq)
265         DEFINE_OP(op_eq_null)
266         DEFINE_OP(op_get_by_id)
267         DEFINE_OP(op_get_arguments_length)
268         DEFINE_OP(op_get_by_val)
269         DEFINE_OP(op_get_argument_by_val)
270         DEFINE_OP(op_get_by_pname)
271         DEFINE_OP(op_get_global_var)
272         DEFINE_OP(op_get_pnames)
273         DEFINE_OP(op_get_scoped_var)
274         DEFINE_OP(op_check_has_instance)
275         DEFINE_OP(op_instanceof)
276         DEFINE_OP(op_jeq_null)
277         DEFINE_OP(op_jfalse)
278         DEFINE_OP(op_jmp)
279         DEFINE_OP(op_jmp_scopes)
280         DEFINE_OP(op_jneq_null)
281         DEFINE_OP(op_jneq_ptr)
282         DEFINE_OP(op_jless)
283         DEFINE_OP(op_jlesseq)
284         DEFINE_OP(op_jgreater)
285         DEFINE_OP(op_jgreatereq)
286         DEFINE_OP(op_jnless)
287         DEFINE_OP(op_jnlesseq)
288         DEFINE_OP(op_jngreater)
289         DEFINE_OP(op_jngreatereq)
290         DEFINE_OP(op_jsr)
291         DEFINE_OP(op_jtrue)
292         DEFINE_OP(op_loop)
293         DEFINE_OP(op_loop_hint)
294         DEFINE_OP(op_loop_if_less)
295         DEFINE_OP(op_loop_if_lesseq)
296         DEFINE_OP(op_loop_if_greater)
297         DEFINE_OP(op_loop_if_greatereq)
298         DEFINE_OP(op_loop_if_true)
299         DEFINE_OP(op_loop_if_false)
300         DEFINE_OP(op_lshift)
301         DEFINE_OP(op_method_check)
302         DEFINE_OP(op_mod)
303         DEFINE_OP(op_mov)
304         DEFINE_OP(op_mul)
305 #if USE(JSVALUE32_64)
306         DEFINE_OP(op_negate)
307 #endif
308         DEFINE_OP(op_neq)
309         DEFINE_OP(op_neq_null)
310         DEFINE_OP(op_new_array)
311         DEFINE_OP(op_new_array_buffer)
312         DEFINE_OP(op_new_func)
313         DEFINE_OP(op_new_func_exp)
314         DEFINE_OP(op_new_object)
315         DEFINE_OP(op_new_regexp)
316         DEFINE_OP(op_next_pname)
317         DEFINE_OP(op_not)
318         DEFINE_OP(op_nstricteq)
319         DEFINE_OP(op_pop_scope)
320         DEFINE_OP(op_post_dec)
321         DEFINE_OP(op_post_inc)
322         DEFINE_OP(op_pre_dec)
323         DEFINE_OP(op_pre_inc)
324         DEFINE_OP(op_profile_did_call)
325         DEFINE_OP(op_profile_will_call)
326         DEFINE_OP(op_push_new_scope)
327         DEFINE_OP(op_push_scope)
328         case op_put_by_id_transition_direct:
329         case op_put_by_id_transition_normal:
330         DEFINE_OP(op_put_by_id)
331         DEFINE_OP(op_put_by_index)
332         DEFINE_OP(op_put_by_val)
333         DEFINE_OP(op_put_getter_setter)
334         DEFINE_OP(op_put_global_var)
335         DEFINE_OP(op_put_scoped_var)
336         DEFINE_OP(op_resolve)
337         DEFINE_OP(op_resolve_base)
338         DEFINE_OP(op_ensure_property_exists)
339         DEFINE_OP(op_resolve_global)
340         DEFINE_OP(op_resolve_global_dynamic)
341         DEFINE_OP(op_resolve_skip)
342         DEFINE_OP(op_resolve_with_base)
343         DEFINE_OP(op_resolve_with_this)
344         DEFINE_OP(op_ret)
345         DEFINE_OP(op_call_put_result)
346         DEFINE_OP(op_ret_object_or_this)
347         DEFINE_OP(op_rshift)
348         DEFINE_OP(op_urshift)
349         DEFINE_OP(op_sret)
350         DEFINE_OP(op_strcat)
351         DEFINE_OP(op_stricteq)
352         DEFINE_OP(op_sub)
353         DEFINE_OP(op_switch_char)
354         DEFINE_OP(op_switch_imm)
355         DEFINE_OP(op_switch_string)
356         DEFINE_OP(op_tear_off_activation)
357         DEFINE_OP(op_tear_off_arguments)
358         DEFINE_OP(op_throw)
359         DEFINE_OP(op_throw_reference_error)
360         DEFINE_OP(op_to_jsnumber)
361         DEFINE_OP(op_to_primitive)
362
363         case op_get_array_length:
364         case op_get_by_id_chain:
365         case op_get_by_id_generic:
366         case op_get_by_id_proto:
367         case op_get_by_id_self:
368         case op_get_by_id_getter_chain:
369         case op_get_by_id_getter_proto:
370         case op_get_by_id_getter_self:
371         case op_get_by_id_custom_chain:
372         case op_get_by_id_custom_proto:
373         case op_get_by_id_custom_self:
374         case op_get_string_length:
375         case op_put_by_id_generic:
376         case op_put_by_id_replace:
377         case op_put_by_id_transition:
378             ASSERT_NOT_REACHED();
379         }
380     }
381
382     ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
383
384 #ifndef NDEBUG
385     // Reset this, in order to guard its use with ASSERTs.
386     m_bytecodeOffset = (unsigned)-1;
387 #endif
388 }
389
390 void JIT::privateCompileLinkPass()
391 {
392     unsigned jmpTableCount = m_jmpTable.size();
393     for (unsigned i = 0; i < jmpTableCount; ++i)
394         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
395     m_jmpTable.clear();
396 }
397
398 void JIT::privateCompileSlowCases()
399 {
400     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
401
402     m_propertyAccessInstructionIndex = 0;
403     m_globalResolveInfoIndex = 0;
404     m_callLinkInfoIndex = 0;
405     
406 #if !ASSERT_DISABLED && ENABLE(VALUE_PROFILER)
407     // Use this to assert that slow-path code associates new profiling sites with existing
408     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
409     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
410     // instructions and the slow-path executions. Furthermore, if the slow-path code created
411     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
412     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
413     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
414 #endif
415
416     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
417 #if USE(JSVALUE64)
418         killLastResultRegister();
419 #endif
420
421         m_bytecodeOffset = iter->to;
422 #ifndef NDEBUG
423         unsigned firstTo = m_bytecodeOffset;
424 #endif
425         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
426         
427 #if ENABLE(VALUE_PROFILER)
428         RareCaseProfile* rareCaseProfile = 0;
429         if (m_canBeOptimized)
430             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
431 #endif
432
433 #if ENABLE(JIT_VERBOSE)
434         dataLog("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
435 #endif
436
437         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
438         DEFINE_SLOWCASE_OP(op_add)
439         DEFINE_SLOWCASE_OP(op_bitand)
440         DEFINE_SLOWCASE_OP(op_bitnot)
441         DEFINE_SLOWCASE_OP(op_bitor)
442         DEFINE_SLOWCASE_OP(op_bitxor)
443         DEFINE_SLOWCASE_OP(op_call)
444         DEFINE_SLOWCASE_OP(op_call_eval)
445         DEFINE_SLOWCASE_OP(op_call_varargs)
446         DEFINE_SLOWCASE_OP(op_construct)
447         DEFINE_SLOWCASE_OP(op_convert_this)
448         DEFINE_SLOWCASE_OP(op_create_this)
449         DEFINE_SLOWCASE_OP(op_div)
450         DEFINE_SLOWCASE_OP(op_eq)
451         DEFINE_SLOWCASE_OP(op_get_by_id)
452         DEFINE_SLOWCASE_OP(op_get_arguments_length)
453         DEFINE_SLOWCASE_OP(op_get_by_val)
454         DEFINE_SLOWCASE_OP(op_get_argument_by_val)
455         DEFINE_SLOWCASE_OP(op_get_by_pname)
456         DEFINE_SLOWCASE_OP(op_check_has_instance)
457         DEFINE_SLOWCASE_OP(op_instanceof)
458         DEFINE_SLOWCASE_OP(op_jfalse)
459         DEFINE_SLOWCASE_OP(op_jless)
460         DEFINE_SLOWCASE_OP(op_jlesseq)
461         DEFINE_SLOWCASE_OP(op_jgreater)
462         DEFINE_SLOWCASE_OP(op_jgreatereq)
463         DEFINE_SLOWCASE_OP(op_jnless)
464         DEFINE_SLOWCASE_OP(op_jnlesseq)
465         DEFINE_SLOWCASE_OP(op_jngreater)
466         DEFINE_SLOWCASE_OP(op_jngreatereq)
467         DEFINE_SLOWCASE_OP(op_jtrue)
468         DEFINE_SLOWCASE_OP(op_loop_if_less)
469         DEFINE_SLOWCASE_OP(op_loop_if_lesseq)
470         DEFINE_SLOWCASE_OP(op_loop_if_greater)
471         DEFINE_SLOWCASE_OP(op_loop_if_greatereq)
472         DEFINE_SLOWCASE_OP(op_loop_if_true)
473         DEFINE_SLOWCASE_OP(op_loop_if_false)
474         DEFINE_SLOWCASE_OP(op_lshift)
475         DEFINE_SLOWCASE_OP(op_method_check)
476         DEFINE_SLOWCASE_OP(op_mod)
477         DEFINE_SLOWCASE_OP(op_mul)
478 #if USE(JSVALUE32_64)
479         DEFINE_SLOWCASE_OP(op_negate)
480 #endif
481         DEFINE_SLOWCASE_OP(op_neq)
482         DEFINE_SLOWCASE_OP(op_new_array)
483         DEFINE_SLOWCASE_OP(op_new_object)
484         DEFINE_SLOWCASE_OP(op_new_func)
485         DEFINE_SLOWCASE_OP(op_new_func_exp)
486         DEFINE_SLOWCASE_OP(op_not)
487         DEFINE_SLOWCASE_OP(op_nstricteq)
488         DEFINE_SLOWCASE_OP(op_post_dec)
489         DEFINE_SLOWCASE_OP(op_post_inc)
490         DEFINE_SLOWCASE_OP(op_pre_dec)
491         DEFINE_SLOWCASE_OP(op_pre_inc)
492         case op_put_by_id_transition_direct:
493         case op_put_by_id_transition_normal:
494         DEFINE_SLOWCASE_OP(op_put_by_id)
495         DEFINE_SLOWCASE_OP(op_put_by_val)
496         DEFINE_SLOWCASE_OP(op_resolve_global)
497         DEFINE_SLOWCASE_OP(op_resolve_global_dynamic)
498         DEFINE_SLOWCASE_OP(op_rshift)
499         DEFINE_SLOWCASE_OP(op_urshift)
500         DEFINE_SLOWCASE_OP(op_stricteq)
501         DEFINE_SLOWCASE_OP(op_sub)
502         DEFINE_SLOWCASE_OP(op_to_jsnumber)
503         DEFINE_SLOWCASE_OP(op_to_primitive)
504         default:
505             ASSERT_NOT_REACHED();
506         }
507
508         ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to,"Not enough jumps linked in slow case codegen.");
509         ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
510         
511 #if ENABLE(VALUE_PROFILER)
512         if (m_canBeOptimized)
513             add32(Imm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
514 #endif
515
516         emitJumpSlowToHot(jump(), 0);
517     }
518
519     ASSERT(m_propertyAccessInstructionIndex == m_propertyAccessCompilationInfo.size());
520     ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
521 #if ENABLE(VALUE_PROFILER)
522     ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
523 #endif
524
525 #ifndef NDEBUG
526     // Reset this, in order to guard its use with ASSERTs.
527     m_bytecodeOffset = (unsigned)-1;
528 #endif
529 }
530
531 JITCode JIT::privateCompile(CodePtr* functionEntryArityCheck)
532 {
533 #if ENABLE(JIT_VERBOSE_OSR)
534     printf("Compiling JIT code!\n");
535 #endif
536     
537 #if ENABLE(VALUE_PROFILER)
538     m_canBeOptimized = m_codeBlock->canCompileWithDFG();
539 #endif
540
541     // Just add a little bit of randomness to the codegen
542     if (m_randomGenerator.getUint32() & 1)
543         nop();
544
545     preserveReturnAddressAfterCall(regT2);
546     emitPutToCallFrameHeader(regT2, RegisterFile::ReturnPC);
547     emitPutImmediateToCallFrameHeader(m_codeBlock, RegisterFile::CodeBlock);
548
549     Label beginLabel(this);
550
551     sampleCodeBlock(m_codeBlock);
552 #if ENABLE(OPCODE_SAMPLING)
553     sampleInstruction(m_codeBlock->instructions().begin());
554 #endif
555
556     Jump registerFileCheck;
557     if (m_codeBlock->codeType() == FunctionCode) {
558 #if ENABLE(DFG_JIT)
559 #if DFG_ENABLE(SUCCESS_STATS)
560         static SamplingCounter counter("orignalJIT");
561         emitCount(counter);
562 #endif
563 #endif
564
565 #if ENABLE(VALUE_PROFILER)
566         ASSERT(m_bytecodeOffset == (unsigned)-1);
567         if (shouldEmitProfiling()) {
568             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
569                 // If this is a constructor, then we want to put in a dummy profiling site (to
570                 // keep things consistent) but we don't actually want to record the dummy value.
571                 if (m_codeBlock->m_isConstructor && !argument)
572                     continue;
573                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
574 #if USE(JSVALUE64)
575                 loadPtr(Address(callFrameRegister, offset), regT0);
576 #elif USE(JSVALUE32_64)
577                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
578                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
579 #endif
580                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
581             }
582         }
583 #endif
584
585         addPtr(Imm32(m_codeBlock->m_numCalleeRegisters * sizeof(Register)), callFrameRegister, regT1);
586         registerFileCheck = branchPtr(Below, AbsoluteAddress(m_globalData->interpreter->registerFile().addressOfEnd()), regT1);
587     }
588
589     Label functionBody = label();
590     
591 #if ENABLE(VALUE_PROFILER)
592     if (m_canBeOptimized)
593         add32(Imm32(1), AbsoluteAddress(&m_codeBlock->m_executionEntryCount));
594 #endif
595
596     privateCompileMainPass();
597     privateCompileLinkPass();
598     privateCompileSlowCases();
599
600     Label arityCheck;
601     if (m_codeBlock->codeType() == FunctionCode) {
602         registerFileCheck.link(this);
603         m_bytecodeOffset = 0;
604         JITStubCall(this, cti_register_file_check).call();
605 #ifndef NDEBUG
606         m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
607 #endif
608         jump(functionBody);
609
610         arityCheck = label();
611         preserveReturnAddressAfterCall(regT2);
612         emitPutToCallFrameHeader(regT2, RegisterFile::ReturnPC);
613         emitPutImmediateToCallFrameHeader(m_codeBlock, RegisterFile::CodeBlock);
614
615         load32(payloadFor(RegisterFile::ArgumentCount), regT1);
616         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
617
618         m_bytecodeOffset = 0;
619         JITStubCall(this, m_codeBlock->m_isConstructor ? cti_op_construct_arityCheck : cti_op_call_arityCheck).call(callFrameRegister);
620 #if !ASSERT_DISABLED
621         m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
622 #endif
623
624         jump(beginLabel);
625     }
626
627     ASSERT(m_jmpTable.isEmpty());
628
629     LinkBuffer patchBuffer(*m_globalData, this, m_codeBlock);
630
631     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
632     for (unsigned i = 0; i < m_switches.size(); ++i) {
633         SwitchRecord record = m_switches[i];
634         unsigned bytecodeOffset = record.bytecodeOffset;
635
636         if (record.type != SwitchRecord::String) {
637             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
638             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
639
640             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
641
642             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
643                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
644                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
645             }
646         } else {
647             ASSERT(record.type == SwitchRecord::String);
648
649             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
650
651             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
652             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
653                 unsigned offset = it->second.branchOffset;
654                 it->second.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
655             }
656         }
657     }
658
659     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
660         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
661         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
662     }
663
664     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
665         if (iter->to)
666             patchBuffer.link(iter->from, FunctionPtr(iter->to));
667     }
668
669     if (m_codeBlock->needsCallReturnIndices()) {
670         m_codeBlock->callReturnIndexVector().reserveCapacity(m_calls.size());
671         for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter)
672             m_codeBlock->callReturnIndexVector().append(CallReturnOffsetToBytecodeOffset(patchBuffer.returnAddressOffset(iter->from), iter->bytecodeOffset));
673     }
674
675     // Link absolute addresses for jsr
676     for (Vector<JSRInfo>::iterator iter = m_jsrSites.begin(); iter != m_jsrSites.end(); ++iter)
677         patchBuffer.patch(iter->storeLocation, patchBuffer.locationOf(iter->target).executableAddress());
678
679     m_codeBlock->setNumberOfStructureStubInfos(m_propertyAccessCompilationInfo.size());
680     for (unsigned i = 0; i < m_propertyAccessCompilationInfo.size(); ++i) {
681         StructureStubInfo& info = m_codeBlock->structureStubInfo(i);
682         ASSERT(m_propertyAccessCompilationInfo[i].bytecodeIndex != std::numeric_limits<unsigned>::max());
683         info.bytecodeIndex = m_propertyAccessCompilationInfo[i].bytecodeIndex;
684         info.callReturnLocation = patchBuffer.locationOf(m_propertyAccessCompilationInfo[i].callReturnLocation);
685         info.hotPathBegin = patchBuffer.locationOf(m_propertyAccessCompilationInfo[i].hotPathBegin);
686     }
687     m_codeBlock->setNumberOfCallLinkInfos(m_callStructureStubCompilationInfo.size());
688     for (unsigned i = 0; i < m_codeBlock->numberOfCallLinkInfos(); ++i) {
689         CallLinkInfo& info = m_codeBlock->callLinkInfo(i);
690         info.callType = m_callStructureStubCompilationInfo[i].callType;
691         info.bytecodeIndex = m_callStructureStubCompilationInfo[i].bytecodeIndex;
692         info.callReturnLocation = CodeLocationLabel(patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].callReturnLocation));
693         info.hotPathBegin = patchBuffer.locationOf(m_callStructureStubCompilationInfo[i].hotPathBegin);
694         info.hotPathOther = patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].hotPathOther);
695     }
696     unsigned methodCallCount = m_methodCallCompilationInfo.size();
697     m_codeBlock->addMethodCallLinkInfos(methodCallCount);
698     for (unsigned i = 0; i < methodCallCount; ++i) {
699         MethodCallLinkInfo& info = m_codeBlock->methodCallLinkInfo(i);
700         info.bytecodeIndex = m_methodCallCompilationInfo[i].bytecodeIndex;
701         info.cachedStructure.setLocation(patchBuffer.locationOf(m_methodCallCompilationInfo[i].structureToCompare));
702         info.callReturnLocation = m_codeBlock->structureStubInfo(m_methodCallCompilationInfo[i].propertyAccessIndex).callReturnLocation;
703     }
704
705 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
706     if (canBeOptimized()
707 #if ENABLE(LLINT)
708         || true
709 #endif
710         ) {
711         CompactJITCodeMap::Encoder jitCodeMapEncoder;
712         for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
713             if (m_labels[bytecodeOffset].isSet())
714                 jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
715         }
716         m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
717     }
718 #endif
719
720     if (m_codeBlock->codeType() == FunctionCode && functionEntryArityCheck)
721         *functionEntryArityCheck = patchBuffer.locationOf(arityCheck);
722     
723     CodeRef result = patchBuffer.finalizeCode();
724     
725 #if ENABLE(JIT_VERBOSE)
726     dataLog("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
727 #endif
728     
729     return JITCode(result, JITCode::BaselineJIT);
730 }
731
732 void JIT::linkFor(JSFunction* callee, CodeBlock* callerCodeBlock, CodeBlock* calleeCodeBlock, JIT::CodePtr code, CallLinkInfo* callLinkInfo, JSGlobalData* globalData, CodeSpecializationKind kind)
733 {
734     RepatchBuffer repatchBuffer(callerCodeBlock);
735
736     ASSERT(!callLinkInfo->isLinked());
737     callLinkInfo->callee.set(*globalData, callLinkInfo->hotPathBegin, callerCodeBlock->ownerExecutable(), callee);
738     callLinkInfo->lastSeenCallee.set(*globalData, callerCodeBlock->ownerExecutable(), callee);
739     repatchBuffer.relink(callLinkInfo->hotPathOther, code);
740
741     if (calleeCodeBlock)
742         calleeCodeBlock->linkIncomingCall(callLinkInfo);
743
744     // Patch the slow patch so we do not continue to try to link.
745     if (kind == CodeForCall) {
746         repatchBuffer.relink(CodeLocationNearCall(callLinkInfo->callReturnLocation), globalData->jitStubs->ctiVirtualCall());
747         return;
748     }
749
750     ASSERT(kind == CodeForConstruct);
751     repatchBuffer.relink(CodeLocationNearCall(callLinkInfo->callReturnLocation), globalData->jitStubs->ctiVirtualConstruct());
752 }
753
754 } // namespace JSC
755
756 #endif // ENABLE(JIT)