JIT.cpp 28.7 KB
Newer Older
1
/*
2
 * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "config.h"
27 28

#if ENABLE(JIT)
ggaren@apple.com's avatar
ggaren@apple.com committed
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 34 35
#include "MacroAssembler.h"
JSC::MacroAssemblerX86Common::SSE2CheckState JSC::MacroAssemblerX86Common::s_sse2CheckState = NotCheckedSSE2;
#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 46
#include "LinkBuffer.h"
#include "RepatchBuffer.h"
47
#include "ResultType.h"
48
#include "SamplingTool.h"
darin@apple.com's avatar
darin@apple.com committed
49

50 51
using namespace std;

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 79
#if USE(JSVALUE32_64)
    , m_jumpTargetIndex(0)
80
    , m_mappedBytecodeOffset((unsigned)-1)
81
    , m_mappedVirtualRegisterIndex(RegisterFile::ReturnPC)
82 83 84
    , m_mappedTag((RegisterID)-1)
    , m_mappedPayload((RegisterID)-1)
#else
85 86
    , m_lastResultBytecodeRegister(std::numeric_limits<int>::max())
    , m_jumpTargetsPosition(0)
87
#endif
88 89 90 91 92
#if USE(OS_RANDOMNESS)
    , m_randomGenerator(cryptographicallyRandomNumber())
#else
    , m_randomGenerator(static_cast<unsigned>(randomNumber() * 0xFFFFFFF))
#endif
93 94 95
{
}

96
#if ENABLE(DFG_JIT)
97 98
void JIT::emitOptimizationCheck(OptimizationCheckKind kind)
{
99 100 101
    if (!shouldEmitProfiling())
        return;
    
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 105
    if (kind == LoopOptimizationCheck)
        stubCall.addArgument(Imm32(m_bytecodeOffset));
106 107 108 109 110
    stubCall.call();
    skipOptimize.link(this);
}
#endif

111 112 113 114 115 116 117 118 119 120 121 122
#if CPU(X86)
void JIT::emitTimeoutCheck()
{
    Jump skipTimeout = branchSub32(NonZero, TrustedImm32(1), AbsoluteAddress(&m_globalData->m_timeoutCount));
    JITStubCall stubCall(this, cti_timeout_check);
    stubCall.addArgument(regT1, regT0); // save last result registers.
    stubCall.call(regT0);
    store32(regT0, &m_globalData->m_timeoutCount);
    stubCall.getArgument(0, regT1, regT0); // reload last result registers.
    skipTimeout.link(this);
}
#elif USE(JSVALUE32_64)
123
void JIT::emitTimeoutCheck()
124
{
125
    Jump skipTimeout = branchSub32(NonZero, TrustedImm32(1), timeoutCheckRegister);
126 127 128 129 130
    JITStubCall stubCall(this, cti_timeout_check);
    stubCall.addArgument(regT1, regT0); // save last result registers.
    stubCall.call(timeoutCheckRegister);
    stubCall.getArgument(0, regT1, regT0); // reload last result registers.
    skipTimeout.link(this);
131
}
132
#else
ggaren@apple.com's avatar
ggaren@apple.com committed
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 146
    break;

147
#if USE(JSVALUE32_64)
148
#define DEFINE_BINARY_OP(name) \
149
    case name: { \
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        JITStubCall stubCall(this, cti_##name); \
        stubCall.addArgument(currentInstruction[2].u.operand); \
        stubCall.addArgument(currentInstruction[3].u.operand); \
        stubCall.call(currentInstruction[1].u.operand); \
        NEXT_OPCODE(name); \
    }

#define DEFINE_UNARY_OP(name) \
    case name: { \
        JITStubCall stubCall(this, cti_##name); \
        stubCall.addArgument(currentInstruction[2].u.operand); \
        stubCall.call(currentInstruction[1].u.operand); \
        NEXT_OPCODE(name); \
    }

#else // USE(JSVALUE32_64)

#define DEFINE_BINARY_OP(name) \
    case name: { \
        JITStubCall stubCall(this, cti_##name); \
170 171 172
        stubCall.addArgument(currentInstruction[2].u.operand, regT2); \
        stubCall.addArgument(currentInstruction[3].u.operand, regT2); \
        stubCall.call(currentInstruction[1].u.operand); \
173 174 175
        NEXT_OPCODE(name); \
    }

176
#define DEFINE_UNARY_OP(name) \
177
    case name: { \
178
        JITStubCall stubCall(this, cti_##name); \
179 180
        stubCall.addArgument(currentInstruction[2].u.operand, regT2); \
        stubCall.call(currentInstruction[1].u.operand); \
181 182
        NEXT_OPCODE(name); \
    }
183
#endif // USE(JSVALUE32_64)
184

185 186 187 188 189 190 191 192 193 194 195 196
#define DEFINE_OP(name) \
    case name: { \
        emit_##name(currentInstruction); \
        NEXT_OPCODE(name); \
    }

#define DEFINE_SLOWCASE_OP(name) \
    case name: { \
        emitSlow_##name(currentInstruction, iter); \
        NEXT_OPCODE(name); \
    }

197
void JIT::privateCompileMainPass()
198
{
199
    Instruction* instructionsBegin = m_codeBlock->instructions().begin();
200
    unsigned instructionCount = m_codeBlock->instructions().size();
201 202 203

    m_globalResolveInfoIndex = 0;
    m_callLinkInfoIndex = 0;
204

205 206 207
    for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
        Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
        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 213
#endif

214
#if USE(JSVALUE64)
215
        if (atJumpTarget())
216
            killLastResultRegister();
217 218
#endif

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 227 228 229
        DEFINE_BINARY_OP(op_del_by_val)
        DEFINE_BINARY_OP(op_in)
        DEFINE_BINARY_OP(op_less)
        DEFINE_BINARY_OP(op_lesseq)
230 231
        DEFINE_BINARY_OP(op_greater)
        DEFINE_BINARY_OP(op_greatereq)
232 233 234 235 236 237 238
        DEFINE_UNARY_OP(op_is_boolean)
        DEFINE_UNARY_OP(op_is_function)
        DEFINE_UNARY_OP(op_is_number)
        DEFINE_UNARY_OP(op_is_object)
        DEFINE_UNARY_OP(op_is_string)
        DEFINE_UNARY_OP(op_is_undefined)
        DEFINE_UNARY_OP(op_typeof)
239

240 241 242 243 244 245 246 247 248
        DEFINE_OP(op_add)
        DEFINE_OP(op_bitand)
        DEFINE_OP(op_bitor)
        DEFINE_OP(op_bitxor)
        DEFINE_OP(op_call)
        DEFINE_OP(op_call_eval)
        DEFINE_OP(op_call_varargs)
        DEFINE_OP(op_catch)
        DEFINE_OP(op_construct)
barraclough@apple.com's avatar
barraclough@apple.com committed
249 250
        DEFINE_OP(op_get_callee)
        DEFINE_OP(op_create_this)
251
        DEFINE_OP(op_convert_this)
252
        DEFINE_OP(op_init_lazy_reg)
253 254 255
        DEFINE_OP(op_create_arguments)
        DEFINE_OP(op_debug)
        DEFINE_OP(op_del_by_id)
256
        DEFINE_OP(op_div)
257 258
        DEFINE_OP(op_end)
        DEFINE_OP(op_enter)
259
        DEFINE_OP(op_create_activation)
260 261 262
        DEFINE_OP(op_eq)
        DEFINE_OP(op_eq_null)
        DEFINE_OP(op_get_by_id)
263
        DEFINE_OP(op_get_arguments_length)
264
        DEFINE_OP(op_get_by_val)
265
        DEFINE_OP(op_get_argument_by_val)
266
        DEFINE_OP(op_get_by_pname)
267
        DEFINE_OP(op_get_global_var)
268
        DEFINE_OP(op_get_pnames)
269
        DEFINE_OP(op_get_scoped_var)
270
        DEFINE_OP(op_check_has_instance)
271 272 273 274 275 276 277
        DEFINE_OP(op_instanceof)
        DEFINE_OP(op_jeq_null)
        DEFINE_OP(op_jfalse)
        DEFINE_OP(op_jmp)
        DEFINE_OP(op_jmp_scopes)
        DEFINE_OP(op_jneq_null)
        DEFINE_OP(op_jneq_ptr)
278
        DEFINE_OP(op_jless)
279
        DEFINE_OP(op_jlesseq)
280 281 282
        DEFINE_OP(op_jgreater)
        DEFINE_OP(op_jgreatereq)
        DEFINE_OP(op_jnless)
283
        DEFINE_OP(op_jnlesseq)
284 285
        DEFINE_OP(op_jngreater)
        DEFINE_OP(op_jngreatereq)
286 287 288
        DEFINE_OP(op_jsr)
        DEFINE_OP(op_jtrue)
        DEFINE_OP(op_loop)
289
        DEFINE_OP(op_loop_hint)
290 291
        DEFINE_OP(op_loop_if_less)
        DEFINE_OP(op_loop_if_lesseq)
292 293
        DEFINE_OP(op_loop_if_greater)
        DEFINE_OP(op_loop_if_greatereq)
294
        DEFINE_OP(op_loop_if_true)
295
        DEFINE_OP(op_loop_if_false)
296
        DEFINE_OP(op_lshift)
297
        DEFINE_OP(op_method_check)
298 299 300
        DEFINE_OP(op_mod)
        DEFINE_OP(op_mov)
        DEFINE_OP(op_mul)
301
        DEFINE_OP(op_negate)
302 303 304
        DEFINE_OP(op_neq)
        DEFINE_OP(op_neq_null)
        DEFINE_OP(op_new_array)
305
        DEFINE_OP(op_new_array_buffer)
306 307 308
        DEFINE_OP(op_new_func)
        DEFINE_OP(op_new_func_exp)
        DEFINE_OP(op_new_object)
309
        DEFINE_OP(op_new_regexp)
310 311 312 313 314 315 316 317
        DEFINE_OP(op_next_pname)
        DEFINE_OP(op_not)
        DEFINE_OP(op_nstricteq)
        DEFINE_OP(op_pop_scope)
        DEFINE_OP(op_post_dec)
        DEFINE_OP(op_post_inc)
        DEFINE_OP(op_pre_dec)
        DEFINE_OP(op_pre_inc)
318 319
        DEFINE_OP(op_profile_did_call)
        DEFINE_OP(op_profile_will_call)
320 321
        DEFINE_OP(op_push_new_scope)
        DEFINE_OP(op_push_scope)
322 323
        case op_put_by_id_transition_direct:
        case op_put_by_id_transition_normal:
324 325 326
        DEFINE_OP(op_put_by_id)
        DEFINE_OP(op_put_by_index)
        DEFINE_OP(op_put_by_val)
barraclough@apple.com's avatar
barraclough@apple.com committed
327
        DEFINE_OP(op_put_getter_setter)
328 329 330 331
        DEFINE_OP(op_put_global_var)
        DEFINE_OP(op_put_scoped_var)
        DEFINE_OP(op_resolve)
        DEFINE_OP(op_resolve_base)
332
        DEFINE_OP(op_ensure_property_exists)
333
        DEFINE_OP(op_resolve_global)
334
        DEFINE_OP(op_resolve_global_dynamic)
335 336
        DEFINE_OP(op_resolve_skip)
        DEFINE_OP(op_resolve_with_base)
337
        DEFINE_OP(op_resolve_with_this)
338
        DEFINE_OP(op_ret)
339
        DEFINE_OP(op_call_put_result)
340
        DEFINE_OP(op_ret_object_or_this)
341
        DEFINE_OP(op_rshift)
342
        DEFINE_OP(op_urshift)
343 344 345 346 347 348 349 350 351 352
        DEFINE_OP(op_sret)
        DEFINE_OP(op_strcat)
        DEFINE_OP(op_stricteq)
        DEFINE_OP(op_sub)
        DEFINE_OP(op_switch_char)
        DEFINE_OP(op_switch_imm)
        DEFINE_OP(op_switch_string)
        DEFINE_OP(op_tear_off_activation)
        DEFINE_OP(op_tear_off_arguments)
        DEFINE_OP(op_throw)
353
        DEFINE_OP(op_throw_reference_error)
354 355
        DEFINE_OP(op_to_jsnumber)
        DEFINE_OP(op_to_primitive)
356

357 358 359 360 361
        case op_get_array_length:
        case op_get_by_id_chain:
        case op_get_by_id_generic:
        case op_get_by_id_proto:
        case op_get_by_id_self:
362 363 364
        case op_get_by_id_getter_chain:
        case op_get_by_id_getter_proto:
        case op_get_by_id_getter_self:
365 366 367
        case op_get_by_id_custom_chain:
        case op_get_by_id_custom_proto:
        case op_get_by_id_custom_self:
368 369 370
        case op_get_string_length:
        case op_put_by_id_generic:
        case op_put_by_id_replace:
371
        case op_put_by_id_transition:
372 373 374
            ASSERT_NOT_REACHED();
        }
    }
375

376
    ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
377 378

#ifndef NDEBUG
379
    // Reset this, in order to guard its use with ASSERTs.
380
    m_bytecodeOffset = (unsigned)-1;
381
#endif
382 383
}

384
void JIT::privateCompileLinkPass()
385 386 387
{
    unsigned jmpTableCount = m_jmpTable.size();
    for (unsigned i = 0; i < jmpTableCount; ++i)
388
        m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
389 390 391
    m_jmpTable.clear();
}

392
void JIT::privateCompileSlowCases()
393
{
394
    Instruction* instructionsBegin = m_codeBlock->instructions().begin();
395 396

    m_propertyAccessInstructionIndex = 0;
397
    m_globalResolveInfoIndex = 0;
398
    m_callLinkInfoIndex = 0;
399 400 401 402 403 404 405 406 407 408
    
#if !ASSERT_DISABLED && ENABLE(VALUE_PROFILER)
    // Use this to assert that slow-path code associates new profiling sites with existing
    // ValueProfiles rather than creating new ones. This ensures that for a given instruction
    // (say, get_by_id) we get combined statistics for both the fast-path executions of that
    // instructions and the slow-path executions. Furthermore, if the slow-path code created
    // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
    // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
    unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
#endif
409

410
    for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
411
#if USE(JSVALUE64)
412
        killLastResultRegister();
413
#endif
414

415
        m_bytecodeOffset = iter->to;
416
#ifndef NDEBUG
417
        unsigned firstTo = m_bytecodeOffset;
418
#endif
419
        Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
420 421
        
#if ENABLE(VALUE_PROFILER)
422
        RareCaseProfile* rareCaseProfile = 0;
423
        if (m_canBeOptimized)
424
            rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
425
#endif
426

427
#if ENABLE(JIT_VERBOSE)
428
        dataLog("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
429 430
#endif

431
        switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
432 433 434 435 436 437 438 439 440
        DEFINE_SLOWCASE_OP(op_add)
        DEFINE_SLOWCASE_OP(op_bitand)
        DEFINE_SLOWCASE_OP(op_bitor)
        DEFINE_SLOWCASE_OP(op_bitxor)
        DEFINE_SLOWCASE_OP(op_call)
        DEFINE_SLOWCASE_OP(op_call_eval)
        DEFINE_SLOWCASE_OP(op_call_varargs)
        DEFINE_SLOWCASE_OP(op_construct)
        DEFINE_SLOWCASE_OP(op_convert_this)
441
        DEFINE_SLOWCASE_OP(op_create_this)
442
        DEFINE_SLOWCASE_OP(op_div)
443 444
        DEFINE_SLOWCASE_OP(op_eq)
        DEFINE_SLOWCASE_OP(op_get_by_id)
445
        DEFINE_SLOWCASE_OP(op_get_arguments_length)
446
        DEFINE_SLOWCASE_OP(op_get_by_val)
447
        DEFINE_SLOWCASE_OP(op_get_argument_by_val)
448
        DEFINE_SLOWCASE_OP(op_get_by_pname)
449
        DEFINE_SLOWCASE_OP(op_check_has_instance)
450 451
        DEFINE_SLOWCASE_OP(op_instanceof)
        DEFINE_SLOWCASE_OP(op_jfalse)
452
        DEFINE_SLOWCASE_OP(op_jless)
453
        DEFINE_SLOWCASE_OP(op_jlesseq)
454 455 456
        DEFINE_SLOWCASE_OP(op_jgreater)
        DEFINE_SLOWCASE_OP(op_jgreatereq)
        DEFINE_SLOWCASE_OP(op_jnless)
457
        DEFINE_SLOWCASE_OP(op_jnlesseq)
458 459
        DEFINE_SLOWCASE_OP(op_jngreater)
        DEFINE_SLOWCASE_OP(op_jngreatereq)
460 461 462
        DEFINE_SLOWCASE_OP(op_jtrue)
        DEFINE_SLOWCASE_OP(op_loop_if_less)
        DEFINE_SLOWCASE_OP(op_loop_if_lesseq)
463 464
        DEFINE_SLOWCASE_OP(op_loop_if_greater)
        DEFINE_SLOWCASE_OP(op_loop_if_greatereq)
465
        DEFINE_SLOWCASE_OP(op_loop_if_true)
466
        DEFINE_SLOWCASE_OP(op_loop_if_false)
467
        DEFINE_SLOWCASE_OP(op_lshift)
468
        DEFINE_SLOWCASE_OP(op_method_check)
469 470
        DEFINE_SLOWCASE_OP(op_mod)
        DEFINE_SLOWCASE_OP(op_mul)
471
        DEFINE_SLOWCASE_OP(op_negate)
472
        DEFINE_SLOWCASE_OP(op_neq)
473
        DEFINE_SLOWCASE_OP(op_new_array)
474
        DEFINE_SLOWCASE_OP(op_new_object)
475 476
        DEFINE_SLOWCASE_OP(op_new_func)
        DEFINE_SLOWCASE_OP(op_new_func_exp)
477 478 479 480 481 482
        DEFINE_SLOWCASE_OP(op_not)
        DEFINE_SLOWCASE_OP(op_nstricteq)
        DEFINE_SLOWCASE_OP(op_post_dec)
        DEFINE_SLOWCASE_OP(op_post_inc)
        DEFINE_SLOWCASE_OP(op_pre_dec)
        DEFINE_SLOWCASE_OP(op_pre_inc)
483 484
        case op_put_by_id_transition_direct:
        case op_put_by_id_transition_normal:
485 486
        DEFINE_SLOWCASE_OP(op_put_by_id)
        DEFINE_SLOWCASE_OP(op_put_by_val)
487
        DEFINE_SLOWCASE_OP(op_resolve_global)
488
        DEFINE_SLOWCASE_OP(op_resolve_global_dynamic)
489
        DEFINE_SLOWCASE_OP(op_rshift)
490
        DEFINE_SLOWCASE_OP(op_urshift)
491 492 493 494
        DEFINE_SLOWCASE_OP(op_stricteq)
        DEFINE_SLOWCASE_OP(op_sub)
        DEFINE_SLOWCASE_OP(op_to_jsnumber)
        DEFINE_SLOWCASE_OP(op_to_primitive)
495 496 497 498
        default:
            ASSERT_NOT_REACHED();
        }

499 500
        ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to,"Not enough jumps linked in slow case codegen.");
        ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
501 502 503
        
#if ENABLE(VALUE_PROFILER)
        if (m_canBeOptimized)
504
            add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
505
#endif
506

507
        emitJumpSlowToHot(jump(), 0);
508
    }
509

510
    ASSERT(m_propertyAccessInstructionIndex == m_propertyAccessCompilationInfo.size());
511
    ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
512 513 514
#if ENABLE(VALUE_PROFILER)
    ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
#endif
515 516

#ifndef NDEBUG
517
    // Reset this, in order to guard its use with ASSERTs.
518
    m_bytecodeOffset = (unsigned)-1;
519
#endif
520 521
}

522
JITCode JIT::privateCompile(CodePtr* functionEntryArityCheck, JITCompilationEffort effort)
523
{
524 525 526 527
#if ENABLE(JIT_VERBOSE_OSR)
    printf("Compiling JIT code!\n");
#endif
    
528
#if ENABLE(VALUE_PROFILER)
529
    m_canBeOptimized = m_codeBlock->canCompileWithDFG();
530
#endif
531

532 533 534 535
    // Just add a little bit of randomness to the codegen
    if (m_randomGenerator.getUint32() & 1)
        nop();

536 537
    preserveReturnAddressAfterCall(regT2);
    emitPutToCallFrameHeader(regT2, RegisterFile::ReturnPC);
538
    emitPutImmediateToCallFrameHeader(m_codeBlock, RegisterFile::CodeBlock);
539 540 541

    Label beginLabel(this);

542
    sampleCodeBlock(m_codeBlock);
543
#if ENABLE(OPCODE_SAMPLING)
544
    sampleInstruction(m_codeBlock->instructions().begin());
545 546
#endif

547
    Jump registerFileCheck;
548
    if (m_codeBlock->codeType() == FunctionCode) {
549
#if ENABLE(DFG_JIT)
550
#if DFG_ENABLE(SUCCESS_STATS)
551 552 553
        static SamplingCounter counter("orignalJIT");
        emitCount(counter);
#endif
554
#endif
555

556 557
#if ENABLE(VALUE_PROFILER)
        ASSERT(m_bytecodeOffset == (unsigned)-1);
558
        if (shouldEmitProfiling()) {
559
            for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
560 561
                // If this is a constructor, then we want to put in a dummy profiling site (to
                // keep things consistent) but we don't actually want to record the dummy value.
562
                if (m_codeBlock->m_isConstructor && !argument)
563 564
                    continue;
                int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
565
#if USE(JSVALUE64)
566
                loadPtr(Address(callFrameRegister, offset), regT0);
567
#elif USE(JSVALUE32_64)
568 569
                load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
                load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
570
#endif
571
                emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
572
            }
573 574 575
        }
#endif

576
        addPtr(TrustedImm32(m_codeBlock->m_numCalleeRegisters * sizeof(Register)), callFrameRegister, regT1);
577
        registerFileCheck = branchPtr(Below, AbsoluteAddress(m_globalData->interpreter->registerFile().addressOfEnd()), regT1);
578 579
    }

580
    Label functionBody = label();
581 582 583
    
#if ENABLE(VALUE_PROFILER)
    if (m_canBeOptimized)
584
        add32(TrustedImm32(1), AbsoluteAddress(&m_codeBlock->m_executionEntryCount));
585
#endif
586

587 588 589 590
    privateCompileMainPass();
    privateCompileLinkPass();
    privateCompileSlowCases();

591
    Label arityCheck;
592
    if (m_codeBlock->codeType() == FunctionCode) {
593
        registerFileCheck.link(this);
594
        m_bytecodeOffset = 0;
595
        JITStubCall(this, cti_register_file_check).call();
596
#ifndef NDEBUG
597
        m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
598
#endif
599
        jump(functionBody);
600 601 602 603

        arityCheck = label();
        preserveReturnAddressAfterCall(regT2);
        emitPutToCallFrameHeader(regT2, RegisterFile::ReturnPC);
604 605
        emitPutImmediateToCallFrameHeader(m_codeBlock, RegisterFile::CodeBlock);

606
        load32(payloadFor(RegisterFile::ArgumentCount), regT1);
607
        branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
608

609
        m_bytecodeOffset = 0;
610
        JITStubCall(this, m_codeBlock->m_isConstructor ? cti_op_construct_arityCheck : cti_op_call_arityCheck).call(callFrameRegister);
611 612 613
#if !ASSERT_DISABLED
        m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
#endif
614

615
        jump(beginLabel);
616 617
    }

618 619
    ASSERT(m_jmpTable.isEmpty());

620 621 622
    LinkBuffer patchBuffer(*m_globalData, this, m_codeBlock, effort);
    if (patchBuffer.didFailToAllocate())
        return JITCode();
623 624 625 626

    // Translate vPC offsets into addresses in JIT generated code, for switch tables.
    for (unsigned i = 0; i < m_switches.size(); ++i) {
        SwitchRecord record = m_switches[i];
627
        unsigned bytecodeOffset = record.bytecodeOffset;
628

629 630 631
        if (record.type != SwitchRecord::String) {
            ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
            ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
632

633
            record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
634

635 636
            for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
                unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
637
                record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
638 639
            }
        } else {
640
            ASSERT(record.type == SwitchRecord::String);
641

642
            record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
643

644 645
            StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
            for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
646
                unsigned offset = it->second.branchOffset;
647
                it->second.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
648 649 650 651
            }
        }
    }

652 653
    for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
        HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
654
        handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
655
    }
656 657

    for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
658
        if (iter->to)
659
            patchBuffer.link(iter->from, FunctionPtr(iter->to));
660 661
    }

662
    if (m_codeBlock->needsCallReturnIndices()) {
663
        m_codeBlock->callReturnIndexVector().reserveCapacity(m_calls.size());
664
        for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter)
665
            m_codeBlock->callReturnIndexVector().append(CallReturnOffsetToBytecodeOffset(patchBuffer.returnAddressOffset(iter->from), iter->bytecodeOffset));
666 667 668 669
    }

    // Link absolute addresses for jsr
    for (Vector<JSRInfo>::iterator iter = m_jsrSites.begin(); iter != m_jsrSites.end(); ++iter)
670
        patchBuffer.patch(iter->storeLocation, patchBuffer.locationOf(iter->target).executableAddress());
671

672 673
    m_codeBlock->setNumberOfStructureStubInfos(m_propertyAccessCompilationInfo.size());
    for (unsigned i = 0; i < m_propertyAccessCompilationInfo.size(); ++i) {
674
        StructureStubInfo& info = m_codeBlock->structureStubInfo(i);
675 676
        ASSERT(m_propertyAccessCompilationInfo[i].bytecodeIndex != std::numeric_limits<unsigned>::max());
        info.bytecodeIndex = m_propertyAccessCompilationInfo[i].bytecodeIndex;
677 678
        info.callReturnLocation = patchBuffer.locationOf(m_propertyAccessCompilationInfo[i].callReturnLocation);
        info.hotPathBegin = patchBuffer.locationOf(m_propertyAccessCompilationInfo[i].hotPathBegin);
679
    }
680
    m_codeBlock->setNumberOfCallLinkInfos(m_callStructureStubCompilationInfo.size());
681 682
    for (unsigned i = 0; i < m_codeBlock->numberOfCallLinkInfos(); ++i) {
        CallLinkInfo& info = m_codeBlock->callLinkInfo(i);
683
        info.callType = m_callStructureStubCompilationInfo[i].callType;
684
        info.bytecodeIndex = m_callStructureStubCompilationInfo[i].bytecodeIndex;
685
        info.callReturnLocation = CodeLocationLabel(patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].callReturnLocation));
686
        info.hotPathBegin = patchBuffer.locationOf(m_callStructureStubCompilationInfo[i].hotPathBegin);
687
        info.hotPathOther = patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].hotPathOther);
688
    }
689 690 691 692
    unsigned methodCallCount = m_methodCallCompilationInfo.size();
    m_codeBlock->addMethodCallLinkInfos(methodCallCount);
    for (unsigned i = 0; i < methodCallCount; ++i) {
        MethodCallLinkInfo& info = m_codeBlock->methodCallLinkInfo(i);
693
        info.bytecodeIndex = m_methodCallCompilationInfo[i].bytecodeIndex;
694
        info.cachedStructure.setLocation(patchBuffer.locationOf(m_methodCallCompilationInfo[i].structureToCompare));
695 696
        info.callReturnLocation = m_codeBlock->structureStubInfo(m_methodCallCompilationInfo[i].propertyAccessIndex).callReturnLocation;
    }
697

698
#if ENABLE(DFG_JIT) || ENABLE(LLINT)
699
    if (canBeOptimized()
700 701 702 703
#if ENABLE(LLINT)
        || true
#endif
        ) {
704 705 706 707 708 709 710
        CompactJITCodeMap::Encoder jitCodeMapEncoder;
        for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
            if (m_labels[bytecodeOffset].isSet())
                jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
        }
        m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
    }
711 712
#endif

713
    if (m_codeBlock->codeType() == FunctionCode && functionEntryArityCheck)
714
        *functionEntryArityCheck = patchBuffer.locationOf(arityCheck);
715
    
716 717
    CodeRef result = patchBuffer.finalizeCode();
    
718 719 720 721
    m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
        static_cast<double>(result.size()) /
        static_cast<double>(m_codeBlock->instructions().size()));
    
722
#if ENABLE(JIT_VERBOSE)
723
    dataLog("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
724 725 726
#endif
    
    return JITCode(result, JITCode::BaselineJIT);
727 728
}

729
void JIT::linkFor(JSFunction* callee, CodeBlock* callerCodeBlock, CodeBlock* calleeCodeBlock, JIT::CodePtr code, CallLinkInfo* callLinkInfo, JSGlobalData* globalData, CodeSpecializationKind kind)
730
{
731
    RepatchBuffer repatchBuffer(callerCodeBlock);
732

733 734 735 736 737 738 739
    ASSERT(!callLinkInfo->isLinked());
    callLinkInfo->callee.set(*globalData, callLinkInfo->hotPathBegin, callerCodeBlock->ownerExecutable(), callee);
    callLinkInfo->lastSeenCallee.set(*globalData, callerCodeBlock->ownerExecutable(), callee);
    repatchBuffer.relink(callLinkInfo->hotPathOther, code);

    if (calleeCodeBlock)
        calleeCodeBlock->linkIncomingCall(callLinkInfo);
740

741
    // Patch the slow patch so we do not continue to try to link.
742
    if (kind == CodeForCall) {
743
        repatchBuffer.relink(CodeLocationNearCall(callLinkInfo->callReturnLocation), globalData->jitStubs->ctiVirtualCall());
744
        return;
745 746
    }

747
    ASSERT(kind == CodeForConstruct);
748
    repatchBuffer.relink(CodeLocationNearCall(callLinkInfo->callReturnLocation), globalData->jitStubs->ctiVirtualConstruct());
749
}
750

751
} // namespace JSC