"this" should be in TDZ until super is called in the constructor of a derived class
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012, 2013, 2014 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
30 #include "JIT.h"
31
32 #include "ArityCheckFailReturnThunks.h"
33 #include "CodeBlock.h"
34 #include "DFGCapabilities.h"
35 #include "Interpreter.h"
36 #include "JITInlines.h"
37 #include "JITOperations.h"
38 #include "JSArray.h"
39 #include "JSFunction.h"
40 #include "LinkBuffer.h"
41 #include "MaxFrameExtentForSlowPathCall.h"
42 #include "JSCInlines.h"
43 #include "ProfilerDatabase.h"
44 #include "RepatchBuffer.h"
45 #include "ResultType.h"
46 #include "SamplingTool.h"
47 #include "SlowPathCall.h"
48 #include "StackAlignment.h"
49 #include "TypeProfilerLog.h"
50 #include <wtf/CryptographicallyRandomNumber.h>
51
52 using namespace std;
53
54 namespace JSC {
55
56 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
57 {
58     RepatchBuffer repatchBuffer(codeblock);
59     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
60 }
61
62 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
63 {
64     RepatchBuffer repatchBuffer(codeblock);
65     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
66 }
67
68 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
69 {
70     RepatchBuffer repatchBuffer(codeblock);
71     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
72 }
73
74 JIT::JIT(VM* vm, CodeBlock* codeBlock)
75     : JSInterfaceJIT(vm, codeBlock)
76     , m_interpreter(vm->interpreter)
77     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
78     , m_bytecodeOffset(std::numeric_limits<unsigned>::max())
79     , m_getByIdIndex(UINT_MAX)
80     , m_putByIdIndex(UINT_MAX)
81     , m_byValInstructionIndex(UINT_MAX)
82     , m_callLinkInfoIndex(UINT_MAX)
83     , m_randomGenerator(cryptographicallyRandomNumber())
84     , m_canBeOptimized(false)
85     , m_shouldEmitProfiling(false)
86 {
87 }
88
89 #if ENABLE(DFG_JIT)
90 void JIT::emitEnterOptimizationCheck()
91 {
92     if (!canBeOptimized())
93         return;
94
95     JumpList skipOptimize;
96     
97     skipOptimize.append(branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForEntry()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter())));
98     ASSERT(!m_bytecodeOffset);
99     callOperation(operationOptimize, m_bytecodeOffset);
100     skipOptimize.append(branchTestPtr(Zero, returnValueGPR));
101     move(returnValueGPR2, stackPointerRegister);
102     jump(returnValueGPR);
103     skipOptimize.link(this);
104 }
105 #endif
106
107 void JIT::assertStackPointerOffset()
108 {
109     if (ASSERT_DISABLED)
110         return;
111     
112     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT0);
113     Jump ok = branchPtr(Equal, regT0, stackPointerRegister);
114     breakpoint();
115     ok.link(this);
116 }
117
118 #define NEXT_OPCODE(name) \
119     m_bytecodeOffset += OPCODE_LENGTH(name); \
120     break;
121
122 #define DEFINE_SLOW_OP(name) \
123     case op_##name: { \
124         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
125         slowPathCall.call(); \
126         NEXT_OPCODE(op_##name); \
127     }
128
129 #define DEFINE_OP(name) \
130     case name: { \
131         emit_##name(currentInstruction); \
132         NEXT_OPCODE(name); \
133     }
134
135 #define DEFINE_SLOWCASE_OP(name) \
136     case name: { \
137         emitSlow_##name(currentInstruction, iter); \
138         NEXT_OPCODE(name); \
139     }
140
141 void JIT::privateCompileMainPass()
142 {
143     jitAssertTagsInPlace();
144     jitAssertArgumentCountSane();
145     
146     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
147     unsigned instructionCount = m_codeBlock->instructions().size();
148
149     m_callLinkInfoIndex = 0;
150
151     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
152         if (m_disassembler)
153             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
154         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
155         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
156
157 #if ENABLE(OPCODE_SAMPLING)
158         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
159             sampleInstruction(currentInstruction);
160 #endif
161
162         m_labels[m_bytecodeOffset] = label();
163
164 #if ENABLE(JIT_VERBOSE)
165         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
166 #endif
167         
168         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
169
170         if (m_compilation) {
171             add64(
172                 TrustedImm32(1),
173                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
174                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
175         }
176         
177         if (Options::eagerlyUpdateTopCallFrame())
178             updateTopCallFrame();
179         
180         switch (opcodeID) {
181         DEFINE_SLOW_OP(del_by_val)
182         DEFINE_SLOW_OP(in)
183         DEFINE_SLOW_OP(less)
184         DEFINE_SLOW_OP(lesseq)
185         DEFINE_SLOW_OP(greater)
186         DEFINE_SLOW_OP(greatereq)
187         DEFINE_SLOW_OP(is_function)
188         DEFINE_SLOW_OP(is_object_or_null)
189         DEFINE_SLOW_OP(typeof)
190
191         DEFINE_OP(op_touch_entry)
192         DEFINE_OP(op_add)
193         DEFINE_OP(op_bitand)
194         DEFINE_OP(op_bitor)
195         DEFINE_OP(op_bitxor)
196         DEFINE_OP(op_call)
197         DEFINE_OP(op_call_eval)
198         DEFINE_OP(op_call_varargs)
199         DEFINE_OP(op_construct_varargs)
200         DEFINE_OP(op_catch)
201         DEFINE_OP(op_construct)
202         DEFINE_OP(op_create_this)
203         DEFINE_OP(op_to_this)
204         DEFINE_OP(op_check_tdz)
205         DEFINE_OP(op_init_lazy_reg)
206         DEFINE_OP(op_create_arguments)
207         DEFINE_OP(op_debug)
208         DEFINE_OP(op_del_by_id)
209         DEFINE_OP(op_div)
210         DEFINE_OP(op_end)
211         DEFINE_OP(op_enter)
212         DEFINE_OP(op_create_lexical_environment)
213         DEFINE_OP(op_get_scope)
214         DEFINE_OP(op_eq)
215         DEFINE_OP(op_eq_null)
216         case op_get_by_id_out_of_line:
217         case op_get_array_length:
218         DEFINE_OP(op_get_by_id)
219         DEFINE_OP(op_get_arguments_length)
220         DEFINE_OP(op_get_by_val)
221         DEFINE_OP(op_get_argument_by_val)
222         DEFINE_OP(op_check_has_instance)
223         DEFINE_OP(op_instanceof)
224         DEFINE_OP(op_is_undefined)
225         DEFINE_OP(op_is_boolean)
226         DEFINE_OP(op_is_number)
227         DEFINE_OP(op_is_string)
228         DEFINE_OP(op_is_object)
229         DEFINE_OP(op_jeq_null)
230         DEFINE_OP(op_jfalse)
231         DEFINE_OP(op_jmp)
232         DEFINE_OP(op_jneq_null)
233         DEFINE_OP(op_jneq_ptr)
234         DEFINE_OP(op_jless)
235         DEFINE_OP(op_jlesseq)
236         DEFINE_OP(op_jgreater)
237         DEFINE_OP(op_jgreatereq)
238         DEFINE_OP(op_jnless)
239         DEFINE_OP(op_jnlesseq)
240         DEFINE_OP(op_jngreater)
241         DEFINE_OP(op_jngreatereq)
242         DEFINE_OP(op_jtrue)
243         DEFINE_OP(op_loop_hint)
244         DEFINE_OP(op_lshift)
245         DEFINE_OP(op_mod)
246         DEFINE_OP(op_mov)
247         DEFINE_OP(op_mul)
248         DEFINE_OP(op_negate)
249         DEFINE_OP(op_neq)
250         DEFINE_OP(op_neq_null)
251         DEFINE_OP(op_new_array)
252         DEFINE_OP(op_new_array_with_size)
253         DEFINE_OP(op_new_array_buffer)
254         DEFINE_OP(op_new_func)
255         DEFINE_OP(op_new_func_exp)
256         DEFINE_OP(op_new_object)
257         DEFINE_OP(op_new_regexp)
258         DEFINE_OP(op_not)
259         DEFINE_OP(op_nstricteq)
260         DEFINE_OP(op_pop_scope)
261         DEFINE_OP(op_dec)
262         DEFINE_OP(op_inc)
263         DEFINE_OP(op_profile_did_call)
264         DEFINE_OP(op_profile_will_call)
265         DEFINE_OP(op_profile_type)
266         DEFINE_OP(op_profile_control_flow)
267         DEFINE_OP(op_push_name_scope)
268         DEFINE_OP(op_push_with_scope)
269         case op_put_by_id_out_of_line:
270         case op_put_by_id_transition_direct:
271         case op_put_by_id_transition_normal:
272         case op_put_by_id_transition_direct_out_of_line:
273         case op_put_by_id_transition_normal_out_of_line:
274         DEFINE_OP(op_put_by_id)
275         DEFINE_OP(op_put_by_index)
276         case op_put_by_val_direct:
277         DEFINE_OP(op_put_by_val)
278         DEFINE_OP(op_put_getter_setter)
279         case op_init_global_const_nop:
280             NEXT_OPCODE(op_init_global_const_nop);
281         DEFINE_OP(op_init_global_const)
282
283         DEFINE_OP(op_ret)
284         DEFINE_OP(op_rshift)
285         DEFINE_OP(op_unsigned)
286         DEFINE_OP(op_urshift)
287         DEFINE_OP(op_strcat)
288         DEFINE_OP(op_stricteq)
289         DEFINE_OP(op_sub)
290         DEFINE_OP(op_switch_char)
291         DEFINE_OP(op_switch_imm)
292         DEFINE_OP(op_switch_string)
293         DEFINE_OP(op_tear_off_arguments)
294         DEFINE_OP(op_throw)
295         DEFINE_OP(op_throw_static_error)
296         DEFINE_OP(op_to_number)
297         DEFINE_OP(op_to_primitive)
298
299         DEFINE_OP(op_resolve_scope)
300         DEFINE_OP(op_get_from_scope)
301         DEFINE_OP(op_put_to_scope)
302
303         DEFINE_OP(op_get_enumerable_length)
304         DEFINE_OP(op_has_generic_property)
305         DEFINE_OP(op_has_structure_property)
306         DEFINE_OP(op_has_indexed_property)
307         DEFINE_OP(op_get_direct_pname)
308         DEFINE_OP(op_get_structure_property_enumerator)
309         DEFINE_OP(op_get_generic_property_enumerator)
310         DEFINE_OP(op_next_enumerator_pname)
311         DEFINE_OP(op_to_index_string)
312         default:
313             RELEASE_ASSERT_NOT_REACHED();
314         }
315     }
316
317     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
318
319 #ifndef NDEBUG
320     // Reset this, in order to guard its use with ASSERTs.
321     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
322 #endif
323 }
324
325 void JIT::privateCompileLinkPass()
326 {
327     unsigned jmpTableCount = m_jmpTable.size();
328     for (unsigned i = 0; i < jmpTableCount; ++i)
329         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
330     m_jmpTable.clear();
331 }
332
333 void JIT::privateCompileSlowCases()
334 {
335     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
336
337     m_getByIdIndex = 0;
338     m_putByIdIndex = 0;
339     m_byValInstructionIndex = 0;
340     m_callLinkInfoIndex = 0;
341     
342     // Use this to assert that slow-path code associates new profiling sites with existing
343     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
344     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
345     // instructions and the slow-path executions. Furthermore, if the slow-path code created
346     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
347     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
348     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
349
350     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
351         m_bytecodeOffset = iter->to;
352
353         unsigned firstTo = m_bytecodeOffset;
354
355         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
356         
357         RareCaseProfile* rareCaseProfile = 0;
358         if (shouldEmitProfiling())
359             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
360
361 #if ENABLE(JIT_VERBOSE)
362         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
363 #endif
364         
365         if (m_disassembler)
366             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
367
368         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
369         DEFINE_SLOWCASE_OP(op_add)
370         DEFINE_SLOWCASE_OP(op_bitand)
371         DEFINE_SLOWCASE_OP(op_bitor)
372         DEFINE_SLOWCASE_OP(op_bitxor)
373         DEFINE_SLOWCASE_OP(op_call)
374         DEFINE_SLOWCASE_OP(op_call_eval)
375         DEFINE_SLOWCASE_OP(op_call_varargs)
376         DEFINE_SLOWCASE_OP(op_construct_varargs)
377         DEFINE_SLOWCASE_OP(op_construct)
378         DEFINE_SLOWCASE_OP(op_to_this)
379         DEFINE_SLOWCASE_OP(op_check_tdz)
380         DEFINE_SLOWCASE_OP(op_create_this)
381         DEFINE_SLOWCASE_OP(op_div)
382         DEFINE_SLOWCASE_OP(op_eq)
383         case op_get_by_id_out_of_line:
384         case op_get_array_length:
385         DEFINE_SLOWCASE_OP(op_get_by_id)
386         DEFINE_SLOWCASE_OP(op_get_arguments_length)
387         DEFINE_SLOWCASE_OP(op_get_by_val)
388         DEFINE_SLOWCASE_OP(op_get_argument_by_val)
389         DEFINE_SLOWCASE_OP(op_check_has_instance)
390         DEFINE_SLOWCASE_OP(op_instanceof)
391         DEFINE_SLOWCASE_OP(op_jfalse)
392         DEFINE_SLOWCASE_OP(op_jless)
393         DEFINE_SLOWCASE_OP(op_jlesseq)
394         DEFINE_SLOWCASE_OP(op_jgreater)
395         DEFINE_SLOWCASE_OP(op_jgreatereq)
396         DEFINE_SLOWCASE_OP(op_jnless)
397         DEFINE_SLOWCASE_OP(op_jnlesseq)
398         DEFINE_SLOWCASE_OP(op_jngreater)
399         DEFINE_SLOWCASE_OP(op_jngreatereq)
400         DEFINE_SLOWCASE_OP(op_jtrue)
401         DEFINE_SLOWCASE_OP(op_loop_hint)
402         DEFINE_SLOWCASE_OP(op_lshift)
403         DEFINE_SLOWCASE_OP(op_mod)
404         DEFINE_SLOWCASE_OP(op_mul)
405         DEFINE_SLOWCASE_OP(op_negate)
406         DEFINE_SLOWCASE_OP(op_neq)
407         DEFINE_SLOWCASE_OP(op_new_object)
408         DEFINE_SLOWCASE_OP(op_not)
409         DEFINE_SLOWCASE_OP(op_nstricteq)
410         DEFINE_SLOWCASE_OP(op_dec)
411         DEFINE_SLOWCASE_OP(op_inc)
412         case op_put_by_id_out_of_line:
413         case op_put_by_id_transition_direct:
414         case op_put_by_id_transition_normal:
415         case op_put_by_id_transition_direct_out_of_line:
416         case op_put_by_id_transition_normal_out_of_line:
417         DEFINE_SLOWCASE_OP(op_put_by_id)
418         case op_put_by_val_direct:
419         DEFINE_SLOWCASE_OP(op_put_by_val)
420         DEFINE_SLOWCASE_OP(op_rshift)
421         DEFINE_SLOWCASE_OP(op_unsigned)
422         DEFINE_SLOWCASE_OP(op_urshift)
423         DEFINE_SLOWCASE_OP(op_stricteq)
424         DEFINE_SLOWCASE_OP(op_sub)
425         DEFINE_SLOWCASE_OP(op_to_number)
426         DEFINE_SLOWCASE_OP(op_to_primitive)
427         DEFINE_SLOWCASE_OP(op_has_indexed_property)
428         DEFINE_SLOWCASE_OP(op_has_structure_property)
429         DEFINE_SLOWCASE_OP(op_get_direct_pname)
430
431         DEFINE_SLOWCASE_OP(op_resolve_scope)
432         DEFINE_SLOWCASE_OP(op_get_from_scope)
433         DEFINE_SLOWCASE_OP(op_put_to_scope)
434
435         default:
436             RELEASE_ASSERT_NOT_REACHED();
437         }
438
439         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
440         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
441         
442         if (shouldEmitProfiling())
443             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
444
445         emitJumpSlowToHot(jump(), 0);
446     }
447
448     RELEASE_ASSERT(m_getByIdIndex == m_getByIds.size());
449     RELEASE_ASSERT(m_putByIdIndex == m_putByIds.size());
450     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
451     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
452
453 #ifndef NDEBUG
454     // Reset this, in order to guard its use with ASSERTs.
455     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
456 #endif
457 }
458
459 CompilationResult JIT::privateCompile(JITCompilationEffort effort)
460 {
461     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
462     switch (level) {
463     case DFG::CannotCompile:
464         m_canBeOptimized = false;
465         m_canBeOptimizedOrInlined = false;
466         m_shouldEmitProfiling = false;
467         break;
468     case DFG::CanCompile:
469     case DFG::CanCompileAndInline:
470         m_canBeOptimized = true;
471         m_canBeOptimizedOrInlined = true;
472         m_shouldEmitProfiling = true;
473         break;
474     default:
475         RELEASE_ASSERT_NOT_REACHED();
476         break;
477     }
478     
479     switch (m_codeBlock->codeType()) {
480     case GlobalCode:
481     case EvalCode:
482         m_codeBlock->m_shouldAlwaysBeInlined = false;
483         break;
484     case FunctionCode:
485         // We could have already set it to false because we detected an uninlineable call.
486         // Don't override that observation.
487         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
488         break;
489     }
490
491     // This ensures that we have the most up to date type information when performing typecheck optimizations for op_profile_type.
492     if (m_vm->typeProfiler())
493         m_vm->typeProfilerLog()->processLogEntries(ASCIILiteral("Preparing for JIT compilation."));
494     
495     if (Options::showDisassembly() || m_vm->m_perBytecodeProfiler)
496         m_disassembler = std::make_unique<JITDisassembler>(m_codeBlock);
497     if (m_vm->m_perBytecodeProfiler) {
498         m_compilation = adoptRef(
499             new Profiler::Compilation(
500                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
501                 Profiler::Baseline));
502         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
503     }
504     
505     if (m_disassembler)
506         m_disassembler->setStartOfCode(label());
507
508     // Just add a little bit of randomness to the codegen
509     if (m_randomGenerator.getUint32() & 1)
510         nop();
511
512     emitFunctionPrologue();
513     emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
514
515     Label beginLabel(this);
516
517     sampleCodeBlock(m_codeBlock);
518 #if ENABLE(OPCODE_SAMPLING)
519     sampleInstruction(m_codeBlock->instructions().begin());
520 #endif
521
522     if (m_codeBlock->codeType() == FunctionCode) {
523         ASSERT(m_bytecodeOffset == std::numeric_limits<unsigned>::max());
524         if (shouldEmitProfiling()) {
525             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
526                 // If this is a constructor, then we want to put in a dummy profiling site (to
527                 // keep things consistent) but we don't actually want to record the dummy value.
528                 if (m_codeBlock->m_isConstructor && !argument)
529                     continue;
530                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
531 #if USE(JSVALUE64)
532                 load64(Address(callFrameRegister, offset), regT0);
533 #elif USE(JSVALUE32_64)
534                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
535                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
536 #endif
537                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
538             }
539         }
540     }
541
542     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT1);
543     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfStackLimit()), regT1);
544
545     move(regT1, stackPointerRegister);
546     checkStackPointerAlignment();
547
548     privateCompileMainPass();
549     privateCompileLinkPass();
550     privateCompileSlowCases();
551     
552     if (m_disassembler)
553         m_disassembler->setEndOfSlowPath(label());
554
555     stackOverflow.link(this);
556     m_bytecodeOffset = 0;
557     if (maxFrameExtentForSlowPathCall)
558         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
559     callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
560
561     Label arityCheck;
562     if (m_codeBlock->codeType() == FunctionCode) {
563         arityCheck = label();
564         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
565         emitFunctionPrologue();
566         emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
567
568         load32(payloadFor(JSStack::ArgumentCount), regT1);
569         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
570
571         m_bytecodeOffset = 0;
572
573         if (maxFrameExtentForSlowPathCall)
574             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
575         callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck);
576         if (maxFrameExtentForSlowPathCall)
577             addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
578         if (returnValueGPR != regT0)
579             move(returnValueGPR, regT0);
580         branchTest32(Zero, regT0).linkTo(beginLabel, this);
581         GPRReg thunkReg;
582 #if USE(JSVALUE64)
583         thunkReg = GPRInfo::regT7;
584 #else
585         thunkReg = GPRInfo::regT5;
586 #endif
587         move(TrustedImmPtr(m_vm->arityCheckFailReturnThunks->returnPCsFor(*m_vm, m_codeBlock->numParameters())), thunkReg);
588         loadPtr(BaseIndex(thunkReg, regT0, timesPtr()), thunkReg);
589         emitNakedCall(m_vm->getCTIStub(arityFixupGenerator).code());
590
591 #if !ASSERT_DISABLED
592         m_bytecodeOffset = std::numeric_limits<unsigned>::max(); // Reset this, in order to guard its use with ASSERTs.
593 #endif
594
595         jump(beginLabel);
596     }
597
598     ASSERT(m_jmpTable.isEmpty());
599     
600     privateCompileExceptionHandlers();
601     
602     if (m_disassembler)
603         m_disassembler->setEndOfCode(label());
604
605     LinkBuffer patchBuffer(*m_vm, *this, m_codeBlock, effort);
606     if (patchBuffer.didFailToAllocate())
607         return CompilationFailed;
608
609     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
610     for (unsigned i = 0; i < m_switches.size(); ++i) {
611         SwitchRecord record = m_switches[i];
612         unsigned bytecodeOffset = record.bytecodeOffset;
613
614         if (record.type != SwitchRecord::String) {
615             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
616             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
617
618             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
619
620             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
621                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
622                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
623             }
624         } else {
625             ASSERT(record.type == SwitchRecord::String);
626
627             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
628
629             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
630             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
631                 unsigned offset = it->value.branchOffset;
632                 it->value.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
633             }
634         }
635     }
636
637     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
638         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
639         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
640     }
641
642     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
643         if (iter->to)
644             patchBuffer.link(iter->from, FunctionPtr(iter->to));
645     }
646
647     for (unsigned i = m_getByIds.size(); i--;)
648         m_getByIds[i].finalize(patchBuffer);
649     for (unsigned i = m_putByIds.size(); i--;)
650         m_putByIds[i].finalize(patchBuffer);
651
652     m_codeBlock->setNumberOfByValInfos(m_byValCompilationInfo.size());
653     for (unsigned i = 0; i < m_byValCompilationInfo.size(); ++i) {
654         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(m_byValCompilationInfo[i].badTypeJump));
655         CodeLocationLabel doneTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].doneTarget);
656         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].slowPathTarget);
657         CodeLocationCall returnAddress = patchBuffer.locationOf(m_byValCompilationInfo[i].returnAddress);
658         
659         m_codeBlock->byValInfo(i) = ByValInfo(
660             m_byValCompilationInfo[i].bytecodeIndex,
661             badTypeJump,
662             m_byValCompilationInfo[i].arrayMode,
663             differenceBetweenCodePtr(badTypeJump, doneTarget),
664             differenceBetweenCodePtr(returnAddress, slowPathTarget));
665     }
666     for (unsigned i = 0; i < m_callCompilationInfo.size(); ++i) {
667         CallCompilationInfo& compilationInfo = m_callCompilationInfo[i];
668         CallLinkInfo& info = *compilationInfo.callLinkInfo;
669         info.callReturnLocation = patchBuffer.locationOfNearCall(compilationInfo.callReturnLocation);
670         info.hotPathBegin = patchBuffer.locationOf(compilationInfo.hotPathBegin);
671         info.hotPathOther = patchBuffer.locationOfNearCall(compilationInfo.hotPathOther);
672     }
673
674     CompactJITCodeMap::Encoder jitCodeMapEncoder;
675     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
676         if (m_labels[bytecodeOffset].isSet())
677             jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
678     }
679     m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
680
681     MacroAssemblerCodePtr withArityCheck;
682     if (m_codeBlock->codeType() == FunctionCode)
683         withArityCheck = patchBuffer.locationOf(arityCheck);
684
685     if (Options::showDisassembly())
686         m_disassembler->dump(patchBuffer);
687     if (m_compilation) {
688         m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
689         m_vm->m_perBytecodeProfiler->addCompilation(m_compilation);
690     }
691     
692     CodeRef result = patchBuffer.finalizeCodeWithoutDisassembly();
693     
694     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
695         static_cast<double>(result.size()) /
696         static_cast<double>(m_codeBlock->instructions().size()));
697     
698     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
699     m_codeBlock->setJITCode(
700         adoptRef(new DirectJITCode(result, withArityCheck, JITCode::BaselineJIT)));
701     
702 #if ENABLE(JIT_VERBOSE)
703     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
704 #endif
705     
706     return CompilationSuccessful;
707 }
708
709 void JIT::privateCompileExceptionHandlers()
710 {
711     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
712         m_exceptionChecksWithCallFrameRollback.link(this);
713
714         // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
715
716         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
717         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
718
719 #if CPU(X86)
720         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
721         poke(GPRInfo::argumentGPR0);
722         poke(GPRInfo::argumentGPR1, 1);
723 #endif
724         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandlerFromCallerFrame).value()));
725         jumpToExceptionHandler();
726     }
727
728     if (!m_exceptionChecks.empty()) {
729         m_exceptionChecks.link(this);
730
731         // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
732         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
733         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
734
735 #if CPU(X86)
736         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
737         poke(GPRInfo::argumentGPR0);
738         poke(GPRInfo::argumentGPR1, 1);
739 #endif
740         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandler).value()));
741         jumpToExceptionHandler();
742     }
743 }
744
745 unsigned JIT::frameRegisterCountFor(CodeBlock* codeBlock)
746 {
747     ASSERT(static_cast<unsigned>(codeBlock->m_numCalleeRegisters) == WTF::roundUpToMultipleOf(stackAlignmentRegisters(), static_cast<unsigned>(codeBlock->m_numCalleeRegisters)));
748
749     return roundLocalRegisterCountForFramePointerOffset(codeBlock->m_numCalleeRegisters + maxFrameExtentForSlowPathCallInRegisters);
750 }
751
752 int JIT::stackPointerOffsetFor(CodeBlock* codeBlock)
753 {
754     return virtualRegisterForLocal(frameRegisterCountFor(codeBlock) - 1).offset();
755 }
756
757 } // namespace JSC
758
759 #endif // ENABLE(JIT)