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