fourthTier: Re-worked non-local variable resolution
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012, 2013 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
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 "DFGCapabilities.h"
39 #include "Interpreter.h"
40 #include "JITInlines.h"
41 #include "JITStubCall.h"
42 #include "JSArray.h"
43 #include "JSFunction.h"
44 #include "LinkBuffer.h"
45 #include "Operations.h"
46 #include "RepatchBuffer.h"
47 #include "ResultType.h"
48 #include "SamplingTool.h"
49 #include <wtf/CryptographicallyRandomNumber.h>
50
51 using namespace std;
52
53 namespace JSC {
54
55 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
56 {
57     RepatchBuffer repatchBuffer(codeblock);
58     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
59 }
60
61 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
62 {
63     RepatchBuffer repatchBuffer(codeblock);
64     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
65 }
66
67 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
68 {
69     RepatchBuffer repatchBuffer(codeblock);
70     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
71 }
72
73 JIT::JIT(VM* vm, CodeBlock* codeBlock)
74     : m_interpreter(vm->interpreter)
75     , m_vm(vm)
76     , m_codeBlock(codeBlock)
77     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
78     , m_bytecodeOffset((unsigned)-1)
79     , m_propertyAccessInstructionIndex(UINT_MAX)
80     , m_byValInstructionIndex(UINT_MAX)
81     , m_callLinkInfoIndex(UINT_MAX)
82 #if USE(JSVALUE32_64)
83     , m_jumpTargetIndex(0)
84     , m_mappedBytecodeOffset((unsigned)-1)
85     , m_mappedVirtualRegisterIndex(JSStack::ReturnPC)
86     , m_mappedTag((RegisterID)-1)
87     , m_mappedPayload((RegisterID)-1)
88 #else
89     , m_lastResultBytecodeRegister(std::numeric_limits<int>::max())
90     , m_jumpTargetsPosition(0)
91 #endif
92     , m_randomGenerator(cryptographicallyRandomNumber())
93 #if ENABLE(VALUE_PROFILER)
94     , m_canBeOptimized(false)
95     , m_shouldEmitProfiling(false)
96 #endif
97 {
98 }
99
100 #if ENABLE(DFG_JIT)
101 void JIT::emitEnterOptimizationCheck()
102 {
103     if (!canBeOptimized())
104         return;
105
106     Jump skipOptimize = branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForReturn()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter()));
107     JITStubCall stubCall(this, cti_optimize);
108     stubCall.addArgument(TrustedImm32(m_bytecodeOffset));
109     ASSERT(!m_bytecodeOffset);
110     stubCall.call();
111     skipOptimize.link(this);
112 }
113 #endif
114
115 #define NEXT_OPCODE(name) \
116     m_bytecodeOffset += OPCODE_LENGTH(name); \
117     break;
118
119 #if USE(JSVALUE32_64)
120 #define DEFINE_BINARY_OP(name) \
121     case name: { \
122         JITStubCall stubCall(this, cti_##name); \
123         stubCall.addArgument(currentInstruction[2].u.operand); \
124         stubCall.addArgument(currentInstruction[3].u.operand); \
125         stubCall.call(currentInstruction[1].u.operand); \
126         NEXT_OPCODE(name); \
127     }
128
129 #define DEFINE_UNARY_OP(name) \
130     case name: { \
131         JITStubCall stubCall(this, cti_##name); \
132         stubCall.addArgument(currentInstruction[2].u.operand); \
133         stubCall.call(currentInstruction[1].u.operand); \
134         NEXT_OPCODE(name); \
135     }
136
137 #else // USE(JSVALUE32_64)
138
139 #define DEFINE_BINARY_OP(name) \
140     case name: { \
141         JITStubCall stubCall(this, cti_##name); \
142         stubCall.addArgument(currentInstruction[2].u.operand, regT2); \
143         stubCall.addArgument(currentInstruction[3].u.operand, regT2); \
144         stubCall.call(currentInstruction[1].u.operand); \
145         NEXT_OPCODE(name); \
146     }
147
148 #define DEFINE_UNARY_OP(name) \
149     case name: { \
150         JITStubCall stubCall(this, cti_##name); \
151         stubCall.addArgument(currentInstruction[2].u.operand, regT2); \
152         stubCall.call(currentInstruction[1].u.operand); \
153         NEXT_OPCODE(name); \
154     }
155 #endif // USE(JSVALUE32_64)
156
157 #define DEFINE_OP(name) \
158     case name: { \
159         emit_##name(currentInstruction); \
160         NEXT_OPCODE(name); \
161     }
162
163 #define DEFINE_SLOWCASE_OP(name) \
164     case name: { \
165         emitSlow_##name(currentInstruction, iter); \
166         NEXT_OPCODE(name); \
167     }
168
169 void JIT::privateCompileMainPass()
170 {
171     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
172     unsigned instructionCount = m_codeBlock->instructions().size();
173
174     m_callLinkInfoIndex = 0;
175
176     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
177         if (m_disassembler)
178             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
179         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
180         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
181
182 #if ENABLE(OPCODE_SAMPLING)
183         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
184             sampleInstruction(currentInstruction);
185 #endif
186
187 #if USE(JSVALUE64)
188         if (atJumpTarget())
189             killLastResultRegister();
190 #endif
191
192         m_labels[m_bytecodeOffset] = label();
193
194 #if ENABLE(JIT_VERBOSE)
195         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
196 #endif
197         
198         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
199
200         if (m_compilation) {
201             add64(
202                 TrustedImm32(1),
203                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
204                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
205         }
206
207         switch (opcodeID) {
208         DEFINE_BINARY_OP(op_del_by_val)
209         DEFINE_BINARY_OP(op_in)
210         DEFINE_BINARY_OP(op_less)
211         DEFINE_BINARY_OP(op_lesseq)
212         DEFINE_BINARY_OP(op_greater)
213         DEFINE_BINARY_OP(op_greatereq)
214         DEFINE_UNARY_OP(op_is_function)
215         DEFINE_UNARY_OP(op_is_object)
216         DEFINE_UNARY_OP(op_typeof)
217
218         DEFINE_OP(op_add)
219         DEFINE_OP(op_bitand)
220         DEFINE_OP(op_bitor)
221         DEFINE_OP(op_bitxor)
222         DEFINE_OP(op_call)
223         DEFINE_OP(op_call_eval)
224         DEFINE_OP(op_call_varargs)
225         DEFINE_OP(op_catch)
226         DEFINE_OP(op_construct)
227         DEFINE_OP(op_get_callee)
228         DEFINE_OP(op_create_this)
229         DEFINE_OP(op_to_this)
230         DEFINE_OP(op_init_lazy_reg)
231         DEFINE_OP(op_create_arguments)
232         DEFINE_OP(op_debug)
233         DEFINE_OP(op_del_by_id)
234         DEFINE_OP(op_div)
235         DEFINE_OP(op_end)
236         DEFINE_OP(op_enter)
237         DEFINE_OP(op_create_activation)
238         DEFINE_OP(op_eq)
239         DEFINE_OP(op_eq_null)
240         case op_get_by_id_out_of_line:
241         case op_get_array_length:
242         DEFINE_OP(op_get_by_id)
243         DEFINE_OP(op_get_arguments_length)
244         DEFINE_OP(op_get_by_val)
245         DEFINE_OP(op_get_argument_by_val)
246         DEFINE_OP(op_get_by_pname)
247         DEFINE_OP(op_get_pnames)
248         DEFINE_OP(op_check_has_instance)
249         DEFINE_OP(op_instanceof)
250         DEFINE_OP(op_is_undefined)
251         DEFINE_OP(op_is_boolean)
252         DEFINE_OP(op_is_number)
253         DEFINE_OP(op_is_string)
254         DEFINE_OP(op_jeq_null)
255         DEFINE_OP(op_jfalse)
256         DEFINE_OP(op_jmp)
257         DEFINE_OP(op_jneq_null)
258         DEFINE_OP(op_jneq_ptr)
259         DEFINE_OP(op_jless)
260         DEFINE_OP(op_jlesseq)
261         DEFINE_OP(op_jgreater)
262         DEFINE_OP(op_jgreatereq)
263         DEFINE_OP(op_jnless)
264         DEFINE_OP(op_jnlesseq)
265         DEFINE_OP(op_jngreater)
266         DEFINE_OP(op_jngreatereq)
267         DEFINE_OP(op_jtrue)
268         DEFINE_OP(op_loop_hint)
269         DEFINE_OP(op_lshift)
270         DEFINE_OP(op_mod)
271         DEFINE_OP(op_mov)
272         DEFINE_OP(op_mul)
273         DEFINE_OP(op_negate)
274         DEFINE_OP(op_neq)
275         DEFINE_OP(op_neq_null)
276         DEFINE_OP(op_new_array)
277         DEFINE_OP(op_new_array_with_size)
278         DEFINE_OP(op_new_array_buffer)
279         DEFINE_OP(op_new_func)
280         DEFINE_OP(op_new_func_exp)
281         DEFINE_OP(op_new_object)
282         DEFINE_OP(op_new_regexp)
283         DEFINE_OP(op_next_pname)
284         DEFINE_OP(op_not)
285         DEFINE_OP(op_nstricteq)
286         DEFINE_OP(op_pop_scope)
287         DEFINE_OP(op_dec)
288         DEFINE_OP(op_inc)
289         DEFINE_OP(op_profile_did_call)
290         DEFINE_OP(op_profile_will_call)
291         DEFINE_OP(op_push_name_scope)
292         DEFINE_OP(op_push_with_scope)
293         case op_put_by_id_out_of_line:
294         case op_put_by_id_transition_direct:
295         case op_put_by_id_transition_normal:
296         case op_put_by_id_transition_direct_out_of_line:
297         case op_put_by_id_transition_normal_out_of_line:
298         DEFINE_OP(op_put_by_id)
299         DEFINE_OP(op_put_by_index)
300         DEFINE_OP(op_put_by_val)
301         DEFINE_OP(op_put_getter_setter)
302         case op_init_global_const_nop:
303             NEXT_OPCODE(op_init_global_const_nop);
304         DEFINE_OP(op_init_global_const)
305
306         DEFINE_OP(op_ret)
307         DEFINE_OP(op_ret_object_or_this)
308         DEFINE_OP(op_rshift)
309         DEFINE_OP(op_urshift)
310         DEFINE_OP(op_strcat)
311         DEFINE_OP(op_stricteq)
312         DEFINE_OP(op_sub)
313         DEFINE_OP(op_switch_char)
314         DEFINE_OP(op_switch_imm)
315         DEFINE_OP(op_switch_string)
316         DEFINE_OP(op_tear_off_activation)
317         DEFINE_OP(op_tear_off_arguments)
318         DEFINE_OP(op_throw)
319         DEFINE_OP(op_throw_static_error)
320         DEFINE_OP(op_to_number)
321         DEFINE_OP(op_to_primitive)
322
323         DEFINE_OP(op_resolve_scope)
324         DEFINE_OP(op_get_from_scope)
325         DEFINE_OP(op_put_to_scope)
326
327         case op_get_by_id_chain:
328         case op_get_by_id_generic:
329         case op_get_by_id_proto:
330         case op_get_by_id_self:
331         case op_get_by_id_getter_chain:
332         case op_get_by_id_getter_proto:
333         case op_get_by_id_getter_self:
334         case op_get_by_id_custom_chain:
335         case op_get_by_id_custom_proto:
336         case op_get_by_id_custom_self:
337         case op_get_string_length:
338         case op_put_by_id_generic:
339         case op_put_by_id_replace:
340         case op_put_by_id_transition:
341             RELEASE_ASSERT_NOT_REACHED();
342         }
343     }
344
345     RELEASE_ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
346
347 #ifndef NDEBUG
348     // Reset this, in order to guard its use with ASSERTs.
349     m_bytecodeOffset = (unsigned)-1;
350 #endif
351 }
352
353 void JIT::privateCompileLinkPass()
354 {
355     unsigned jmpTableCount = m_jmpTable.size();
356     for (unsigned i = 0; i < jmpTableCount; ++i)
357         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
358     m_jmpTable.clear();
359 }
360
361 void JIT::privateCompileSlowCases()
362 {
363     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
364
365     m_propertyAccessInstructionIndex = 0;
366     m_byValInstructionIndex = 0;
367     m_callLinkInfoIndex = 0;
368     
369 #if ENABLE(VALUE_PROFILER)
370     // Use this to assert that slow-path code associates new profiling sites with existing
371     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
372     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
373     // instructions and the slow-path executions. Furthermore, if the slow-path code created
374     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
375     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
376     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
377 #endif
378
379     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
380 #if USE(JSVALUE64)
381         killLastResultRegister();
382 #endif
383
384         m_bytecodeOffset = iter->to;
385
386         unsigned firstTo = m_bytecodeOffset;
387
388         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
389         
390 #if ENABLE(VALUE_PROFILER)
391         RareCaseProfile* rareCaseProfile = 0;
392         if (shouldEmitProfiling())
393             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
394 #endif
395
396 #if ENABLE(JIT_VERBOSE)
397         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
398 #endif
399         
400         if (m_disassembler)
401             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
402
403         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
404         DEFINE_SLOWCASE_OP(op_add)
405         DEFINE_SLOWCASE_OP(op_bitand)
406         DEFINE_SLOWCASE_OP(op_bitor)
407         DEFINE_SLOWCASE_OP(op_bitxor)
408         DEFINE_SLOWCASE_OP(op_call)
409         DEFINE_SLOWCASE_OP(op_call_eval)
410         DEFINE_SLOWCASE_OP(op_call_varargs)
411         DEFINE_SLOWCASE_OP(op_construct)
412         DEFINE_SLOWCASE_OP(op_to_this)
413         DEFINE_SLOWCASE_OP(op_create_this)
414         DEFINE_SLOWCASE_OP(op_div)
415         DEFINE_SLOWCASE_OP(op_eq)
416         case op_get_by_id_out_of_line:
417         case op_get_array_length:
418         DEFINE_SLOWCASE_OP(op_get_by_id)
419         DEFINE_SLOWCASE_OP(op_get_arguments_length)
420         DEFINE_SLOWCASE_OP(op_get_by_val)
421         DEFINE_SLOWCASE_OP(op_get_argument_by_val)
422         DEFINE_SLOWCASE_OP(op_get_by_pname)
423         DEFINE_SLOWCASE_OP(op_check_has_instance)
424         DEFINE_SLOWCASE_OP(op_instanceof)
425         DEFINE_SLOWCASE_OP(op_jfalse)
426         DEFINE_SLOWCASE_OP(op_jless)
427         DEFINE_SLOWCASE_OP(op_jlesseq)
428         DEFINE_SLOWCASE_OP(op_jgreater)
429         DEFINE_SLOWCASE_OP(op_jgreatereq)
430         DEFINE_SLOWCASE_OP(op_jnless)
431         DEFINE_SLOWCASE_OP(op_jnlesseq)
432         DEFINE_SLOWCASE_OP(op_jngreater)
433         DEFINE_SLOWCASE_OP(op_jngreatereq)
434         DEFINE_SLOWCASE_OP(op_jtrue)
435         DEFINE_SLOWCASE_OP(op_loop_hint)
436         DEFINE_SLOWCASE_OP(op_lshift)
437         DEFINE_SLOWCASE_OP(op_mod)
438         DEFINE_SLOWCASE_OP(op_mul)
439         DEFINE_SLOWCASE_OP(op_negate)
440         DEFINE_SLOWCASE_OP(op_neq)
441         DEFINE_SLOWCASE_OP(op_new_object)
442         DEFINE_SLOWCASE_OP(op_not)
443         DEFINE_SLOWCASE_OP(op_nstricteq)
444         DEFINE_SLOWCASE_OP(op_dec)
445         DEFINE_SLOWCASE_OP(op_inc)
446         case op_put_by_id_out_of_line:
447         case op_put_by_id_transition_direct:
448         case op_put_by_id_transition_normal:
449         case op_put_by_id_transition_direct_out_of_line:
450         case op_put_by_id_transition_normal_out_of_line:
451         DEFINE_SLOWCASE_OP(op_put_by_id)
452         DEFINE_SLOWCASE_OP(op_put_by_val)
453         DEFINE_SLOWCASE_OP(op_rshift)
454         DEFINE_SLOWCASE_OP(op_urshift)
455         DEFINE_SLOWCASE_OP(op_stricteq)
456         DEFINE_SLOWCASE_OP(op_sub)
457         DEFINE_SLOWCASE_OP(op_to_number)
458         DEFINE_SLOWCASE_OP(op_to_primitive)
459
460         DEFINE_SLOWCASE_OP(op_resolve_scope)
461         DEFINE_SLOWCASE_OP(op_get_from_scope)
462         DEFINE_SLOWCASE_OP(op_put_to_scope)
463
464         default:
465             RELEASE_ASSERT_NOT_REACHED();
466         }
467
468         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
469         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
470         
471 #if ENABLE(VALUE_PROFILER)
472         if (shouldEmitProfiling())
473             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
474 #endif
475
476         emitJumpSlowToHot(jump(), 0);
477     }
478
479     RELEASE_ASSERT(m_propertyAccessInstructionIndex == m_propertyAccessCompilationInfo.size());
480     RELEASE_ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
481 #if ENABLE(VALUE_PROFILER)
482     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
483 #endif
484
485 #ifndef NDEBUG
486     // Reset this, in order to guard its use with ASSERTs.
487     m_bytecodeOffset = (unsigned)-1;
488 #endif
489 }
490
491 ALWAYS_INLINE void PropertyStubCompilationInfo::copyToStubInfo(StructureStubInfo& info, LinkBuffer &linkBuffer)
492 {
493     ASSERT(bytecodeIndex != std::numeric_limits<unsigned>::max());
494     info.codeOrigin = CodeOrigin(bytecodeIndex);
495     info.callReturnLocation = linkBuffer.locationOf(callReturnLocation);
496     info.hotPathBegin = linkBuffer.locationOf(hotPathBegin);
497
498     switch (m_type) {
499     case GetById: {
500         CodeLocationLabel hotPathBeginLocation = linkBuffer.locationOf(hotPathBegin);
501         info.patch.baseline.u.get.structureToCompare = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getStructureToCompare));
502         info.patch.baseline.u.get.structureCheck = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getStructureCheck));
503         info.patch.baseline.u.get.propertyStorageLoad = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(propertyStorageLoad));
504 #if USE(JSVALUE64)
505         info.patch.baseline.u.get.displacementLabel = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel));
506 #else
507         info.patch.baseline.u.get.displacementLabel1 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel1));
508         info.patch.baseline.u.get.displacementLabel2 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel2));
509 #endif
510         info.patch.baseline.u.get.putResult = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getPutResult));
511         info.patch.baseline.u.get.coldPathBegin = MacroAssembler::differenceBetweenCodePtr(linkBuffer.locationOf(getColdPathBegin), linkBuffer.locationOf(callReturnLocation));
512         break;
513     }
514     case PutById:
515         CodeLocationLabel hotPathBeginLocation = linkBuffer.locationOf(hotPathBegin);
516         info.patch.baseline.u.put.structureToCompare = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putStructureToCompare));
517         info.patch.baseline.u.put.propertyStorageLoad = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(propertyStorageLoad));
518 #if USE(JSVALUE64)
519         info.patch.baseline.u.put.displacementLabel = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putDisplacementLabel));
520 #else
521         info.patch.baseline.u.put.displacementLabel1 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putDisplacementLabel1));
522         info.patch.baseline.u.put.displacementLabel2 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putDisplacementLabel2));
523 #endif
524         break;
525     }
526 }
527
528 PassRefPtr<JITCode> JIT::privateCompile(CodePtr* functionEntryArityCheck, JITCompilationEffort effort)
529 {
530 #if ENABLE(VALUE_PROFILER)
531     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
532     switch (level) {
533     case DFG::CannotCompile:
534         m_canBeOptimized = false;
535         m_canBeOptimizedOrInlined = false;
536         m_shouldEmitProfiling = false;
537         break;
538     case DFG::CanInline:
539         m_canBeOptimized = false;
540         m_canBeOptimizedOrInlined = true;
541         m_shouldEmitProfiling = true;
542         break;
543     case DFG::CanCompile:
544     case DFG::CanCompileAndInline:
545         m_canBeOptimized = true;
546         m_canBeOptimizedOrInlined = true;
547         m_shouldEmitProfiling = true;
548         break;
549     default:
550         RELEASE_ASSERT_NOT_REACHED();
551         break;
552     }
553     
554     switch (m_codeBlock->codeType()) {
555     case GlobalCode:
556     case EvalCode:
557         m_codeBlock->m_shouldAlwaysBeInlined = false;
558         break;
559     case FunctionCode:
560         // We could have already set it to false because we detected an uninlineable call.
561         // Don't override that observation.
562         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
563         break;
564     }
565 #endif
566     
567     if (Options::showDisassembly() || m_vm->m_perBytecodeProfiler)
568         m_disassembler = adoptPtr(new JITDisassembler(m_codeBlock));
569     if (m_vm->m_perBytecodeProfiler) {
570         m_compilation = adoptRef(
571             new Profiler::Compilation(
572                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
573                 Profiler::Baseline));
574         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
575     }
576     
577     if (m_disassembler)
578         m_disassembler->setStartOfCode(label());
579
580     // Just add a little bit of randomness to the codegen
581     if (m_randomGenerator.getUint32() & 1)
582         nop();
583
584     preserveReturnAddressAfterCall(regT2);
585     emitPutToCallFrameHeader(regT2, JSStack::ReturnPC);
586     emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
587
588     Label beginLabel(this);
589
590     sampleCodeBlock(m_codeBlock);
591 #if ENABLE(OPCODE_SAMPLING)
592     sampleInstruction(m_codeBlock->instructions().begin());
593 #endif
594
595     Jump stackCheck;
596     if (m_codeBlock->codeType() == FunctionCode) {
597 #if ENABLE(DFG_JIT)
598 #if DFG_ENABLE(SUCCESS_STATS)
599         static SamplingCounter counter("orignalJIT");
600         emitCount(counter);
601 #endif
602 #endif
603
604 #if ENABLE(VALUE_PROFILER)
605         ASSERT(m_bytecodeOffset == (unsigned)-1);
606         if (shouldEmitProfiling()) {
607             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
608                 // If this is a constructor, then we want to put in a dummy profiling site (to
609                 // keep things consistent) but we don't actually want to record the dummy value.
610                 if (m_codeBlock->m_isConstructor && !argument)
611                     continue;
612                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
613 #if USE(JSVALUE64)
614                 load64(Address(callFrameRegister, offset), regT0);
615 #elif USE(JSVALUE32_64)
616                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
617                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
618 #endif
619                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
620             }
621         }
622 #endif
623
624         addPtr(TrustedImm32(m_codeBlock->m_numCalleeRegisters * sizeof(Register)), callFrameRegister, regT1);
625         stackCheck = branchPtr(Below, AbsoluteAddress(m_vm->interpreter->stack().addressOfEnd()), regT1);
626     }
627
628     Label functionBody = label();
629     
630     privateCompileMainPass();
631     privateCompileLinkPass();
632     privateCompileSlowCases();
633     
634     if (m_disassembler)
635         m_disassembler->setEndOfSlowPath(label());
636
637     Label arityCheck;
638     if (m_codeBlock->codeType() == FunctionCode) {
639         stackCheck.link(this);
640         m_bytecodeOffset = 0;
641         JITStubCall(this, cti_stack_check).call();
642 #ifndef NDEBUG
643         m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
644 #endif
645         jump(functionBody);
646
647         arityCheck = label();
648         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
649         preserveReturnAddressAfterCall(regT2);
650         emitPutToCallFrameHeader(regT2, JSStack::ReturnPC);
651         emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
652
653         load32(payloadFor(JSStack::ArgumentCount), regT1);
654         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
655
656         m_bytecodeOffset = 0;
657         JITStubCall(this, m_codeBlock->m_isConstructor ? cti_op_construct_arityCheck : cti_op_call_arityCheck).call(callFrameRegister);
658 #if !ASSERT_DISABLED
659         m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
660 #endif
661
662         jump(beginLabel);
663     }
664
665     ASSERT(m_jmpTable.isEmpty());
666     
667     if (m_disassembler)
668         m_disassembler->setEndOfCode(label());
669
670     LinkBuffer patchBuffer(*m_vm, this, m_codeBlock, effort);
671     if (patchBuffer.didFailToAllocate())
672         return PassRefPtr<JITCode>();
673
674     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
675     for (unsigned i = 0; i < m_switches.size(); ++i) {
676         SwitchRecord record = m_switches[i];
677         unsigned bytecodeOffset = record.bytecodeOffset;
678
679         if (record.type != SwitchRecord::String) {
680             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
681             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
682
683             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
684
685             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
686                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
687                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
688             }
689         } else {
690             ASSERT(record.type == SwitchRecord::String);
691
692             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
693
694             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
695             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
696                 unsigned offset = it->value.branchOffset;
697                 it->value.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
698             }
699         }
700     }
701
702     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
703         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
704         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
705     }
706
707     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
708         if (iter->to)
709             patchBuffer.link(iter->from, FunctionPtr(iter->to));
710     }
711
712     m_codeBlock->callReturnIndexVector().reserveCapacity(m_calls.size());
713     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter)
714         m_codeBlock->callReturnIndexVector().append(CallReturnOffsetToBytecodeOffset(patchBuffer.returnAddressOffset(iter->from), iter->bytecodeOffset));
715
716     m_codeBlock->setNumberOfStructureStubInfos(m_propertyAccessCompilationInfo.size());
717     for (unsigned i = 0; i < m_propertyAccessCompilationInfo.size(); ++i)
718         m_propertyAccessCompilationInfo[i].copyToStubInfo(m_codeBlock->structureStubInfo(i), patchBuffer);
719     m_codeBlock->setNumberOfByValInfos(m_byValCompilationInfo.size());
720     for (unsigned i = 0; i < m_byValCompilationInfo.size(); ++i) {
721         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(m_byValCompilationInfo[i].badTypeJump));
722         CodeLocationLabel doneTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].doneTarget);
723         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].slowPathTarget);
724         CodeLocationCall returnAddress = patchBuffer.locationOf(m_byValCompilationInfo[i].returnAddress);
725         
726         m_codeBlock->byValInfo(i) = ByValInfo(
727             m_byValCompilationInfo[i].bytecodeIndex,
728             badTypeJump,
729             m_byValCompilationInfo[i].arrayMode,
730             differenceBetweenCodePtr(badTypeJump, doneTarget),
731             differenceBetweenCodePtr(returnAddress, slowPathTarget));
732     }
733     m_codeBlock->setNumberOfCallLinkInfos(m_callStructureStubCompilationInfo.size());
734     for (unsigned i = 0; i < m_codeBlock->numberOfCallLinkInfos(); ++i) {
735         CallLinkInfo& info = m_codeBlock->callLinkInfo(i);
736         info.callType = m_callStructureStubCompilationInfo[i].callType;
737         info.codeOrigin = CodeOrigin(m_callStructureStubCompilationInfo[i].bytecodeIndex);
738         info.callReturnLocation = patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].callReturnLocation);
739         info.hotPathBegin = patchBuffer.locationOf(m_callStructureStubCompilationInfo[i].hotPathBegin);
740         info.hotPathOther = patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].hotPathOther);
741         info.calleeGPR = regT0;
742     }
743
744 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
745     if (canBeOptimizedOrInlined()
746 #if ENABLE(LLINT)
747         || true
748 #endif
749         ) {
750         CompactJITCodeMap::Encoder jitCodeMapEncoder;
751         for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
752             if (m_labels[bytecodeOffset].isSet())
753                 jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
754         }
755         m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
756     }
757 #endif
758
759     if (m_codeBlock->codeType() == FunctionCode && functionEntryArityCheck)
760         *functionEntryArityCheck = patchBuffer.locationOf(arityCheck);
761
762     if (Options::showDisassembly())
763         m_disassembler->dump(patchBuffer);
764     if (m_compilation) {
765         m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
766         m_vm->m_perBytecodeProfiler->addCompilation(m_compilation);
767     }
768     
769     CodeRef result = patchBuffer.finalizeCodeWithoutDisassembly();
770     
771     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
772         static_cast<double>(result.size()) /
773         static_cast<double>(m_codeBlock->instructions().size()));
774     
775     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
776     
777 #if ENABLE(JIT_VERBOSE)
778     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
779 #endif
780     
781     return adoptRef(new DirectJITCode(result, JITCode::BaselineJIT));
782 }
783
784 void JIT::linkFor(ExecState* exec, JSFunction* callee, CodeBlock* callerCodeBlock, CodeBlock* calleeCodeBlock, JIT::CodePtr code, CallLinkInfo* callLinkInfo, VM* vm, CodeSpecializationKind kind)
785 {
786     RepatchBuffer repatchBuffer(callerCodeBlock);
787
788     ASSERT(!callLinkInfo->isLinked());
789     callLinkInfo->callee.set(*vm, callLinkInfo->hotPathBegin, callerCodeBlock->ownerExecutable(), callee);
790     callLinkInfo->lastSeenCallee.set(*vm, callerCodeBlock->ownerExecutable(), callee);
791     repatchBuffer.relink(callLinkInfo->hotPathOther, code);
792
793     if (calleeCodeBlock)
794         calleeCodeBlock->linkIncomingCall(exec, callLinkInfo);
795
796     // Patch the slow patch so we do not continue to try to link.
797     if (kind == CodeForCall) {
798         ASSERT(callLinkInfo->callType == CallLinkInfo::Call
799                || callLinkInfo->callType == CallLinkInfo::CallVarargs);
800         if (callLinkInfo->callType == CallLinkInfo::Call) {
801             repatchBuffer.relink(callLinkInfo->callReturnLocation, vm->getCTIStub(linkClosureCallGenerator).code());
802             return;
803         }
804
805         repatchBuffer.relink(callLinkInfo->callReturnLocation, vm->getCTIStub(virtualCallGenerator).code());
806         return;
807     }
808
809     ASSERT(kind == CodeForConstruct);
810     repatchBuffer.relink(callLinkInfo->callReturnLocation, vm->getCTIStub(virtualConstructGenerator).code());
811 }
812
813 void JIT::linkSlowCall(CodeBlock* callerCodeBlock, CallLinkInfo* callLinkInfo)
814 {
815     RepatchBuffer repatchBuffer(callerCodeBlock);
816
817     repatchBuffer.relink(callLinkInfo->callReturnLocation, callerCodeBlock->vm()->getCTIStub(virtualCallGenerator).code());
818 }
819
820 } // namespace JSC
821
822 #endif // ENABLE(JIT)