More stack limit and reserved zone renaming.
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012-2016 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 "CodeBlock.h"
33 #include "CodeBlockWithJITType.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 "PCToCodeOriginMap.h"
44 #include "ProfilerDatabase.h"
45 #include "ResultType.h"
46 #include "SlowPathCall.h"
47 #include "StackAlignment.h"
48 #include "SuperSampler.h"
49 #include "TypeProfilerLog.h"
50 #include <wtf/CryptographicallyRandomNumber.h>
51
52 using namespace std;
53
54 namespace JSC {
55
56 double totalBaselineCompileTime;
57 double totalDFGCompileTime;
58 double totalFTLCompileTime;
59 double totalFTLDFGCompileTime;
60 double totalFTLB3CompileTime;
61
62 void ctiPatchCallByReturnAddress(ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
63 {
64     MacroAssembler::repatchCall(
65         CodeLocationCall(MacroAssemblerCodePtr(returnAddress)),
66         newCalleeFunction);
67 }
68
69 JIT::JIT(VM* vm, CodeBlock* codeBlock)
70     : JSInterfaceJIT(vm, codeBlock)
71     , m_interpreter(vm->interpreter)
72     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
73     , m_bytecodeOffset(std::numeric_limits<unsigned>::max())
74     , m_getByIdIndex(UINT_MAX)
75     , m_putByIdIndex(UINT_MAX)
76     , m_byValInstructionIndex(UINT_MAX)
77     , m_callLinkInfoIndex(UINT_MAX)
78     , m_randomGenerator(cryptographicallyRandomNumber())
79     , m_pcToCodeOriginMapBuilder(*vm)
80     , m_canBeOptimized(false)
81     , m_shouldEmitProfiling(false)
82 {
83 }
84
85 JIT::~JIT()
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
100     copyCalleeSavesFromFrameOrRegisterToVMEntryFrameCalleeSavesBuffer();
101
102     callOperation(operationOptimize, m_bytecodeOffset);
103     skipOptimize.append(branchTestPtr(Zero, returnValueGPR));
104     move(returnValueGPR2, stackPointerRegister);
105     jump(returnValueGPR);
106     skipOptimize.link(this);
107 }
108 #endif
109
110 void JIT::emitNotifyWrite(WatchpointSet* set)
111 {
112     if (!set || set->state() == IsInvalidated) {
113         addSlowCase(Jump());
114         return;
115     }
116     
117     addSlowCase(branch8(NotEqual, AbsoluteAddress(set->addressOfState()), TrustedImm32(IsInvalidated)));
118 }
119
120 void JIT::emitNotifyWrite(GPRReg pointerToSet)
121 {
122     addSlowCase(branch8(NotEqual, Address(pointerToSet, WatchpointSet::offsetOfState()), TrustedImm32(IsInvalidated)));
123 }
124
125 void JIT::assertStackPointerOffset()
126 {
127     if (ASSERT_DISABLED)
128         return;
129     
130     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT0);
131     Jump ok = branchPtr(Equal, regT0, stackPointerRegister);
132     breakpoint();
133     ok.link(this);
134 }
135
136 #define NEXT_OPCODE(name) \
137     m_bytecodeOffset += OPCODE_LENGTH(name); \
138     break;
139
140 #define DEFINE_SLOW_OP(name) \
141     case op_##name: { \
142         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
143         slowPathCall.call(); \
144         NEXT_OPCODE(op_##name); \
145     }
146
147 #define DEFINE_OP(name) \
148     case name: { \
149         emit_##name(currentInstruction); \
150         NEXT_OPCODE(name); \
151     }
152
153 #define DEFINE_SLOWCASE_OP(name) \
154     case name: { \
155         emitSlow_##name(currentInstruction, iter); \
156         NEXT_OPCODE(name); \
157     }
158
159 void JIT::privateCompileMainPass()
160 {
161     if (false)
162         dataLog("Compiling ", *m_codeBlock, "\n");
163     
164     jitAssertTagsInPlace();
165     jitAssertArgumentCountSane();
166     
167     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
168     unsigned instructionCount = m_instructions.size();
169
170     m_callLinkInfoIndex = 0;
171
172     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
173         if (m_disassembler)
174             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
175         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
176         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
177
178         m_pcToCodeOriginMapBuilder.appendItem(label(), CodeOrigin(m_bytecodeOffset));
179
180 #if ENABLE(OPCODE_SAMPLING)
181         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
182             sampleInstruction(currentInstruction);
183 #endif
184
185         m_labels[m_bytecodeOffset] = label();
186
187 #if ENABLE(JIT_VERBOSE)
188         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
189 #endif
190         
191         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
192
193         if (m_compilation) {
194             add64(
195                 TrustedImm32(1),
196                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
197                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
198         }
199         
200         if (Options::eagerlyUpdateTopCallFrame())
201             updateTopCallFrame();
202
203         unsigned bytecodeOffset = m_bytecodeOffset;
204
205         switch (opcodeID) {
206         DEFINE_SLOW_OP(in)
207         DEFINE_SLOW_OP(less)
208         DEFINE_SLOW_OP(lesseq)
209         DEFINE_SLOW_OP(greater)
210         DEFINE_SLOW_OP(greatereq)
211         DEFINE_SLOW_OP(is_function)
212         DEFINE_SLOW_OP(is_object_or_null)
213         DEFINE_SLOW_OP(typeof)
214
215         DEFINE_OP(op_add)
216         DEFINE_OP(op_bitand)
217         DEFINE_OP(op_bitor)
218         DEFINE_OP(op_bitxor)
219         DEFINE_OP(op_call)
220         DEFINE_OP(op_tail_call)
221         DEFINE_OP(op_call_eval)
222         DEFINE_OP(op_call_varargs)
223         DEFINE_OP(op_tail_call_varargs)
224         DEFINE_OP(op_tail_call_forward_arguments)
225         DEFINE_OP(op_construct_varargs)
226         DEFINE_OP(op_catch)
227         DEFINE_OP(op_construct)
228         DEFINE_OP(op_create_this)
229         DEFINE_OP(op_to_this)
230         DEFINE_OP(op_create_direct_arguments)
231         DEFINE_OP(op_create_scoped_arguments)
232         DEFINE_OP(op_create_cloned_arguments)
233         DEFINE_OP(op_argument_count)
234         DEFINE_OP(op_copy_rest)
235         DEFINE_OP(op_get_rest_length)
236         DEFINE_OP(op_check_tdz)
237         DEFINE_OP(op_assert)
238         DEFINE_OP(op_save)
239         DEFINE_OP(op_resume)
240         DEFINE_OP(op_debug)
241         DEFINE_OP(op_del_by_id)
242         DEFINE_OP(op_del_by_val)
243         DEFINE_OP(op_div)
244         DEFINE_OP(op_end)
245         DEFINE_OP(op_enter)
246         DEFINE_OP(op_get_scope)
247         DEFINE_OP(op_eq)
248         DEFINE_OP(op_eq_null)
249         DEFINE_OP(op_try_get_by_id)
250         case op_get_array_length:
251         case op_get_by_id_proto_load:
252         case op_get_by_id_unset:
253         DEFINE_OP(op_get_by_id)
254         DEFINE_OP(op_get_by_id_with_this)
255         DEFINE_OP(op_get_by_val)
256         DEFINE_OP(op_get_by_val_with_this)
257         DEFINE_OP(op_overrides_has_instance)
258         DEFINE_OP(op_instanceof)
259         DEFINE_OP(op_instanceof_custom)
260         DEFINE_OP(op_is_empty)
261         DEFINE_OP(op_is_undefined)
262         DEFINE_OP(op_is_boolean)
263         DEFINE_OP(op_is_number)
264         DEFINE_OP(op_is_string)
265         DEFINE_OP(op_is_jsarray)
266         DEFINE_OP(op_is_object)
267         DEFINE_OP(op_jeq_null)
268         DEFINE_OP(op_jfalse)
269         DEFINE_OP(op_jmp)
270         DEFINE_OP(op_jneq_null)
271         DEFINE_OP(op_jneq_ptr)
272         DEFINE_OP(op_jless)
273         DEFINE_OP(op_jlesseq)
274         DEFINE_OP(op_jgreater)
275         DEFINE_OP(op_jgreatereq)
276         DEFINE_OP(op_jnless)
277         DEFINE_OP(op_jnlesseq)
278         DEFINE_OP(op_jngreater)
279         DEFINE_OP(op_jngreatereq)
280         DEFINE_OP(op_jtrue)
281         DEFINE_OP(op_loop_hint)
282         DEFINE_OP(op_watchdog)
283         DEFINE_OP(op_lshift)
284         DEFINE_OP(op_mod)
285         DEFINE_OP(op_mov)
286         DEFINE_OP(op_mul)
287         DEFINE_OP(op_negate)
288         DEFINE_OP(op_neq)
289         DEFINE_OP(op_neq_null)
290         DEFINE_OP(op_new_array)
291         DEFINE_OP(op_new_array_with_size)
292         DEFINE_OP(op_new_array_buffer)
293         DEFINE_OP(op_new_func)
294         DEFINE_OP(op_new_func_exp)
295         DEFINE_OP(op_new_generator_func)
296         DEFINE_OP(op_new_generator_func_exp)
297         DEFINE_OP(op_new_object)
298         DEFINE_OP(op_new_regexp)
299         DEFINE_OP(op_not)
300         DEFINE_OP(op_nstricteq)
301         DEFINE_OP(op_dec)
302         DEFINE_OP(op_inc)
303         DEFINE_OP(op_profile_type)
304         DEFINE_OP(op_profile_control_flow)
305         DEFINE_OP(op_push_with_scope)
306         DEFINE_OP(op_create_lexical_environment)
307         DEFINE_OP(op_get_parent_scope)
308         DEFINE_OP(op_put_by_id)
309         DEFINE_OP(op_put_by_id_with_this)
310         DEFINE_OP(op_put_by_index)
311         case op_put_by_val_direct:
312         DEFINE_OP(op_put_by_val)
313         DEFINE_OP(op_put_by_val_with_this)
314         DEFINE_OP(op_put_getter_by_id)
315         DEFINE_OP(op_put_setter_by_id)
316         DEFINE_OP(op_put_getter_setter_by_id)
317         DEFINE_OP(op_put_getter_by_val)
318         DEFINE_OP(op_put_setter_by_val)
319
320         DEFINE_OP(op_ret)
321         DEFINE_OP(op_rshift)
322         DEFINE_OP(op_unsigned)
323         DEFINE_OP(op_urshift)
324         DEFINE_OP(op_set_function_name)
325         DEFINE_OP(op_strcat)
326         DEFINE_OP(op_stricteq)
327         DEFINE_OP(op_sub)
328         DEFINE_OP(op_switch_char)
329         DEFINE_OP(op_switch_imm)
330         DEFINE_OP(op_switch_string)
331         DEFINE_OP(op_throw)
332         DEFINE_OP(op_throw_static_error)
333         DEFINE_OP(op_to_number)
334         DEFINE_OP(op_to_string)
335         DEFINE_OP(op_to_primitive)
336
337         DEFINE_OP(op_resolve_scope)
338         DEFINE_OP(op_get_from_scope)
339         DEFINE_OP(op_put_to_scope)
340         DEFINE_OP(op_get_from_arguments)
341         DEFINE_OP(op_put_to_arguments)
342
343         DEFINE_OP(op_get_enumerable_length)
344         DEFINE_OP(op_has_generic_property)
345         DEFINE_OP(op_has_structure_property)
346         DEFINE_OP(op_has_indexed_property)
347         DEFINE_OP(op_get_direct_pname)
348         DEFINE_OP(op_get_property_enumerator)
349         DEFINE_OP(op_enumerator_structure_pname)
350         DEFINE_OP(op_enumerator_generic_pname)
351         DEFINE_OP(op_to_index_string)
352             
353         DEFINE_OP(op_log_shadow_chicken_prologue)
354         DEFINE_OP(op_log_shadow_chicken_tail)
355         default:
356             RELEASE_ASSERT_NOT_REACHED();
357         }
358
359         if (false)
360             dataLog("At ", bytecodeOffset, ": ", m_slowCases.size(), "\n");
361     }
362
363     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
364
365 #ifndef NDEBUG
366     // Reset this, in order to guard its use with ASSERTs.
367     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
368 #endif
369 }
370
371 void JIT::privateCompileLinkPass()
372 {
373     unsigned jmpTableCount = m_jmpTable.size();
374     for (unsigned i = 0; i < jmpTableCount; ++i)
375         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
376     m_jmpTable.clear();
377 }
378
379 void JIT::privateCompileSlowCases()
380 {
381     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
382
383     m_getByIdIndex = 0;
384     m_putByIdIndex = 0;
385     m_byValInstructionIndex = 0;
386     m_callLinkInfoIndex = 0;
387     
388     // Use this to assert that slow-path code associates new profiling sites with existing
389     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
390     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
391     // instructions and the slow-path executions. Furthermore, if the slow-path code created
392     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
393     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
394     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
395
396     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
397         m_bytecodeOffset = iter->to;
398
399         m_pcToCodeOriginMapBuilder.appendItem(label(), CodeOrigin(m_bytecodeOffset));
400
401         unsigned firstTo = m_bytecodeOffset;
402
403         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
404         
405         RareCaseProfile* rareCaseProfile = 0;
406         if (shouldEmitProfiling())
407             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
408
409 #if ENABLE(JIT_VERBOSE)
410         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
411 #endif
412         
413         if (m_disassembler)
414             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
415
416         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
417         DEFINE_SLOWCASE_OP(op_add)
418         DEFINE_SLOWCASE_OP(op_bitand)
419         DEFINE_SLOWCASE_OP(op_bitor)
420         DEFINE_SLOWCASE_OP(op_bitxor)
421         DEFINE_SLOWCASE_OP(op_call)
422         DEFINE_SLOWCASE_OP(op_tail_call)
423         DEFINE_SLOWCASE_OP(op_call_eval)
424         DEFINE_SLOWCASE_OP(op_call_varargs)
425         DEFINE_SLOWCASE_OP(op_tail_call_varargs)
426         DEFINE_SLOWCASE_OP(op_tail_call_forward_arguments)
427         DEFINE_SLOWCASE_OP(op_construct_varargs)
428         DEFINE_SLOWCASE_OP(op_construct)
429         DEFINE_SLOWCASE_OP(op_to_this)
430         DEFINE_SLOWCASE_OP(op_check_tdz)
431         DEFINE_SLOWCASE_OP(op_create_this)
432         DEFINE_SLOWCASE_OP(op_div)
433         DEFINE_SLOWCASE_OP(op_eq)
434         DEFINE_SLOWCASE_OP(op_try_get_by_id)
435         case op_get_array_length:
436         case op_get_by_id_proto_load:
437         case op_get_by_id_unset:
438         DEFINE_SLOWCASE_OP(op_get_by_id)
439         DEFINE_SLOWCASE_OP(op_get_by_val)
440         DEFINE_SLOWCASE_OP(op_instanceof)
441         DEFINE_SLOWCASE_OP(op_instanceof_custom)
442         DEFINE_SLOWCASE_OP(op_jfalse)
443         DEFINE_SLOWCASE_OP(op_jless)
444         DEFINE_SLOWCASE_OP(op_jlesseq)
445         DEFINE_SLOWCASE_OP(op_jgreater)
446         DEFINE_SLOWCASE_OP(op_jgreatereq)
447         DEFINE_SLOWCASE_OP(op_jnless)
448         DEFINE_SLOWCASE_OP(op_jnlesseq)
449         DEFINE_SLOWCASE_OP(op_jngreater)
450         DEFINE_SLOWCASE_OP(op_jngreatereq)
451         DEFINE_SLOWCASE_OP(op_jtrue)
452         DEFINE_SLOWCASE_OP(op_loop_hint)
453         DEFINE_SLOWCASE_OP(op_watchdog)
454         DEFINE_SLOWCASE_OP(op_lshift)
455         DEFINE_SLOWCASE_OP(op_mod)
456         DEFINE_SLOWCASE_OP(op_mul)
457         DEFINE_SLOWCASE_OP(op_negate)
458         DEFINE_SLOWCASE_OP(op_neq)
459         DEFINE_SLOWCASE_OP(op_new_object)
460         DEFINE_SLOWCASE_OP(op_not)
461         DEFINE_SLOWCASE_OP(op_nstricteq)
462         DEFINE_SLOWCASE_OP(op_dec)
463         DEFINE_SLOWCASE_OP(op_inc)
464         DEFINE_SLOWCASE_OP(op_put_by_id)
465         case op_put_by_val_direct:
466         DEFINE_SLOWCASE_OP(op_put_by_val)
467         DEFINE_SLOWCASE_OP(op_rshift)
468         DEFINE_SLOWCASE_OP(op_unsigned)
469         DEFINE_SLOWCASE_OP(op_urshift)
470         DEFINE_SLOWCASE_OP(op_stricteq)
471         DEFINE_SLOWCASE_OP(op_sub)
472         DEFINE_SLOWCASE_OP(op_to_number)
473         DEFINE_SLOWCASE_OP(op_to_string)
474         DEFINE_SLOWCASE_OP(op_to_primitive)
475         DEFINE_SLOWCASE_OP(op_has_indexed_property)
476         DEFINE_SLOWCASE_OP(op_has_structure_property)
477         DEFINE_SLOWCASE_OP(op_get_direct_pname)
478
479         DEFINE_SLOWCASE_OP(op_resolve_scope)
480         DEFINE_SLOWCASE_OP(op_get_from_scope)
481         DEFINE_SLOWCASE_OP(op_put_to_scope)
482
483         default:
484             RELEASE_ASSERT_NOT_REACHED();
485         }
486
487         if (false)
488             dataLog("At ", firstTo, " slow: ", iter - m_slowCases.begin(), "\n");
489
490         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
491         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
492         
493         if (shouldEmitProfiling())
494             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
495
496         emitJumpSlowToHot(jump(), 0);
497     }
498
499     RELEASE_ASSERT(m_getByIdIndex == m_getByIds.size());
500     RELEASE_ASSERT(m_putByIdIndex == m_putByIds.size());
501     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
502     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
503
504 #ifndef NDEBUG
505     // Reset this, in order to guard its use with ASSERTs.
506     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
507 #endif
508 }
509
510 void JIT::compileWithoutLinking(JITCompilationEffort effort)
511 {
512     double before = 0;
513     if (UNLIKELY(computeCompileTimes()))
514         before = monotonicallyIncreasingTimeMS();
515     
516     {
517         ConcurrentJITLocker locker(m_codeBlock->m_lock);
518         m_instructions = m_codeBlock->instructions().clone();
519     }
520
521     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
522     switch (level) {
523     case DFG::CannotCompile:
524         m_canBeOptimized = false;
525         m_canBeOptimizedOrInlined = false;
526         m_shouldEmitProfiling = false;
527         break;
528     case DFG::CanCompile:
529     case DFG::CanCompileAndInline:
530         m_canBeOptimized = true;
531         m_canBeOptimizedOrInlined = true;
532         m_shouldEmitProfiling = true;
533         break;
534     default:
535         RELEASE_ASSERT_NOT_REACHED();
536         break;
537     }
538     
539     switch (m_codeBlock->codeType()) {
540     case GlobalCode:
541     case ModuleCode:
542     case EvalCode:
543         m_codeBlock->m_shouldAlwaysBeInlined = false;
544         break;
545     case FunctionCode:
546         // We could have already set it to false because we detected an uninlineable call.
547         // Don't override that observation.
548         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
549         break;
550     }
551
552     if (Options::dumpDisassembly() || (m_vm->m_perBytecodeProfiler && Options::disassembleBaselineForProfiler()))
553         m_disassembler = std::make_unique<JITDisassembler>(m_codeBlock);
554     if (m_vm->m_perBytecodeProfiler) {
555         m_compilation = adoptRef(
556             new Profiler::Compilation(
557                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
558                 Profiler::Baseline));
559         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
560     }
561     
562     m_pcToCodeOriginMapBuilder.appendItem(label(), CodeOrigin(0, nullptr));
563
564     if (m_disassembler)
565         m_disassembler->setStartOfCode(label());
566
567     // Just add a little bit of randomness to the codegen
568     if (m_randomGenerator.getUint32() & 1)
569         nop();
570
571     emitFunctionPrologue();
572     emitPutToCallFrameHeader(m_codeBlock, CallFrameSlot::codeBlock);
573
574     Label beginLabel(this);
575
576     sampleCodeBlock(m_codeBlock);
577 #if ENABLE(OPCODE_SAMPLING)
578     sampleInstruction(m_codeBlock->instructions().begin());
579 #endif
580
581     if (m_codeBlock->codeType() == FunctionCode) {
582         ASSERT(m_bytecodeOffset == std::numeric_limits<unsigned>::max());
583         if (shouldEmitProfiling()) {
584             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
585                 // If this is a constructor, then we want to put in a dummy profiling site (to
586                 // keep things consistent) but we don't actually want to record the dummy value.
587                 if (m_codeBlock->m_isConstructor && !argument)
588                     continue;
589                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
590 #if USE(JSVALUE64)
591                 load64(Address(callFrameRegister, offset), regT0);
592 #elif USE(JSVALUE32_64)
593                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
594                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
595 #endif
596                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
597             }
598         }
599     }
600
601     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT1);
602     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfSoftStackLimit()), regT1);
603
604     move(regT1, stackPointerRegister);
605     checkStackPointerAlignment();
606
607     emitSaveCalleeSaves();
608     emitMaterializeTagCheckRegisters();
609     
610     RELEASE_ASSERT(!JITCode::isJIT(m_codeBlock->jitType()));
611
612     privateCompileMainPass();
613     privateCompileLinkPass();
614     privateCompileSlowCases();
615     
616     if (m_disassembler)
617         m_disassembler->setEndOfSlowPath(label());
618     m_pcToCodeOriginMapBuilder.appendItem(label(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
619
620     stackOverflow.link(this);
621     m_bytecodeOffset = 0;
622     if (maxFrameExtentForSlowPathCall)
623         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
624     callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
625
626     if (m_codeBlock->codeType() == FunctionCode) {
627         m_arityCheck = label();
628         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
629         emitFunctionPrologue();
630         emitPutToCallFrameHeader(m_codeBlock, CallFrameSlot::codeBlock);
631
632         load32(payloadFor(CallFrameSlot::argumentCount), regT1);
633         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
634
635         m_bytecodeOffset = 0;
636
637         if (maxFrameExtentForSlowPathCall)
638             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
639         callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck);
640         if (maxFrameExtentForSlowPathCall)
641             addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
642         branchTest32(Zero, returnValueGPR).linkTo(beginLabel, this);
643         move(returnValueGPR, GPRInfo::argumentGPR0);
644         emitNakedCall(m_vm->getCTIStub(arityFixupGenerator).code());
645
646 #if !ASSERT_DISABLED
647         m_bytecodeOffset = std::numeric_limits<unsigned>::max(); // Reset this, in order to guard its use with ASSERTs.
648 #endif
649
650         jump(beginLabel);
651     }
652
653     ASSERT(m_jmpTable.isEmpty());
654     
655     privateCompileExceptionHandlers();
656     
657     if (m_disassembler)
658         m_disassembler->setEndOfCode(label());
659     m_pcToCodeOriginMapBuilder.appendItem(label(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
660
661     m_linkBuffer = std::unique_ptr<LinkBuffer>(new LinkBuffer(*m_vm, *this, m_codeBlock, effort));
662
663     double after;
664     if (UNLIKELY(computeCompileTimes())) {
665         after = monotonicallyIncreasingTimeMS();
666
667         if (Options::reportTotalCompileTimes())
668             totalBaselineCompileTime += after - before;
669     }
670     if (UNLIKELY(reportCompileTimes())) {
671         CString codeBlockName = toCString(*m_codeBlock);
672         
673         dataLog("Optimized ", codeBlockName, " with Baseline JIT into ", m_linkBuffer->size(), " bytes in ", after - before, " ms.\n");
674     }
675 }
676
677 CompilationResult JIT::link()
678 {
679     LinkBuffer& patchBuffer = *m_linkBuffer;
680     
681     if (patchBuffer.didFailToAllocate())
682         return CompilationFailed;
683
684     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
685     for (unsigned i = 0; i < m_switches.size(); ++i) {
686         SwitchRecord record = m_switches[i];
687         unsigned bytecodeOffset = record.bytecodeOffset;
688
689         if (record.type != SwitchRecord::String) {
690             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
691             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
692
693             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
694
695             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
696                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
697                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
698             }
699         } else {
700             ASSERT(record.type == SwitchRecord::String);
701
702             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
703
704             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
705             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
706                 unsigned offset = it->value.branchOffset;
707                 it->value.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
708             }
709         }
710     }
711
712     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
713         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
714         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
715     }
716
717     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
718         if (iter->to)
719             patchBuffer.link(iter->from, FunctionPtr(iter->to));
720     }
721
722     for (unsigned i = m_getByIds.size(); i--;)
723         m_getByIds[i].finalize(patchBuffer);
724     for (unsigned i = m_putByIds.size(); i--;)
725         m_putByIds[i].finalize(patchBuffer);
726
727     for (const auto& byValCompilationInfo : m_byValCompilationInfo) {
728         PatchableJump patchableNotIndexJump = byValCompilationInfo.notIndexJump;
729         CodeLocationJump notIndexJump = CodeLocationJump();
730         if (Jump(patchableNotIndexJump).isSet())
731             notIndexJump = CodeLocationJump(patchBuffer.locationOf(patchableNotIndexJump));
732         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(byValCompilationInfo.badTypeJump));
733         CodeLocationLabel doneTarget = patchBuffer.locationOf(byValCompilationInfo.doneTarget);
734         CodeLocationLabel nextHotPathTarget = patchBuffer.locationOf(byValCompilationInfo.nextHotPathTarget);
735         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(byValCompilationInfo.slowPathTarget);
736         CodeLocationCall returnAddress = patchBuffer.locationOf(byValCompilationInfo.returnAddress);
737
738         *byValCompilationInfo.byValInfo = ByValInfo(
739             byValCompilationInfo.bytecodeIndex,
740             notIndexJump,
741             badTypeJump,
742             byValCompilationInfo.arrayMode,
743             byValCompilationInfo.arrayProfile,
744             differenceBetweenCodePtr(badTypeJump, doneTarget),
745             differenceBetweenCodePtr(badTypeJump, nextHotPathTarget),
746             differenceBetweenCodePtr(returnAddress, slowPathTarget));
747     }
748     for (unsigned i = 0; i < m_callCompilationInfo.size(); ++i) {
749         CallCompilationInfo& compilationInfo = m_callCompilationInfo[i];
750         CallLinkInfo& info = *compilationInfo.callLinkInfo;
751         info.setCallLocations(patchBuffer.locationOfNearCall(compilationInfo.callReturnLocation),
752             patchBuffer.locationOf(compilationInfo.hotPathBegin),
753             patchBuffer.locationOfNearCall(compilationInfo.hotPathOther));
754     }
755
756     CompactJITCodeMap::Encoder jitCodeMapEncoder;
757     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
758         if (m_labels[bytecodeOffset].isSet())
759             jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
760     }
761     m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
762
763     MacroAssemblerCodePtr withArityCheck;
764     if (m_codeBlock->codeType() == FunctionCode)
765         withArityCheck = patchBuffer.locationOf(m_arityCheck);
766
767     if (Options::dumpDisassembly()) {
768         m_disassembler->dump(patchBuffer);
769         patchBuffer.didAlreadyDisassemble();
770     }
771     if (m_compilation) {
772         if (Options::disassembleBaselineForProfiler())
773             m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
774         m_vm->m_perBytecodeProfiler->addCompilation(m_codeBlock, m_compilation);
775     }
776
777     if (m_pcToCodeOriginMapBuilder.didBuildMapping())
778         m_codeBlock->setPCToCodeOriginMap(std::make_unique<PCToCodeOriginMap>(WTFMove(m_pcToCodeOriginMapBuilder), patchBuffer));
779     
780     CodeRef result = FINALIZE_CODE(
781         patchBuffer,
782         ("Baseline JIT code for %s", toCString(CodeBlockWithJITType(m_codeBlock, JITCode::BaselineJIT)).data()));
783     
784     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
785         static_cast<double>(result.size()) /
786         static_cast<double>(m_instructions.size()));
787
788     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
789     m_codeBlock->setJITCode(
790         adoptRef(new DirectJITCode(result, withArityCheck, JITCode::BaselineJIT)));
791
792 #if ENABLE(JIT_VERBOSE)
793     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
794 #endif
795     
796     return CompilationSuccessful;
797 }
798
799 CompilationResult JIT::privateCompile(JITCompilationEffort effort)
800 {
801     doMainThreadPreparationBeforeCompile();
802     compileWithoutLinking(effort);
803     return link();
804 }
805
806 void JIT::privateCompileExceptionHandlers()
807 {
808     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
809         m_exceptionChecksWithCallFrameRollback.link(this);
810
811         copyCalleeSavesToVMEntryFrameCalleeSavesBuffer();
812
813         // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
814
815         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
816         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
817
818 #if CPU(X86)
819         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
820         poke(GPRInfo::argumentGPR0);
821         poke(GPRInfo::argumentGPR1, 1);
822 #endif
823         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandlerFromCallerFrame).value()));
824         jumpToExceptionHandler();
825     }
826
827     if (!m_exceptionChecks.empty()) {
828         m_exceptionChecks.link(this);
829
830         copyCalleeSavesToVMEntryFrameCalleeSavesBuffer();
831
832         // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
833         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
834         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
835
836 #if CPU(X86)
837         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
838         poke(GPRInfo::argumentGPR0);
839         poke(GPRInfo::argumentGPR1, 1);
840 #endif
841         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandler).value()));
842         jumpToExceptionHandler();
843     }
844 }
845
846 void JIT::doMainThreadPreparationBeforeCompile()
847 {
848     // This ensures that we have the most up to date type information when performing typecheck optimizations for op_profile_type.
849     if (m_vm->typeProfiler())
850         m_vm->typeProfilerLog()->processLogEntries(ASCIILiteral("Preparing for JIT compilation."));
851 }
852
853 unsigned JIT::frameRegisterCountFor(CodeBlock* codeBlock)
854 {
855     ASSERT(static_cast<unsigned>(codeBlock->m_numCalleeLocals) == WTF::roundUpToMultipleOf(stackAlignmentRegisters(), static_cast<unsigned>(codeBlock->m_numCalleeLocals)));
856
857     return roundLocalRegisterCountForFramePointerOffset(codeBlock->m_numCalleeLocals + maxFrameExtentForSlowPathCallInRegisters);
858 }
859
860 int JIT::stackPointerOffsetFor(CodeBlock* codeBlock)
861 {
862     return virtualRegisterForLocal(frameRegisterCountFor(codeBlock) - 1).offset();
863 }
864
865 bool JIT::reportCompileTimes()
866 {
867     return Options::reportCompileTimes() || Options::reportBaselineCompileTimes();
868 }
869
870 bool JIT::computeCompileTimes()
871 {
872     return reportCompileTimes() || Options::reportTotalCompileTimes();
873 }
874
875 HashMap<CString, double> JIT::compileTimeStats()
876 {
877     HashMap<CString, double> result;
878     if (Options::reportTotalCompileTimes()) {
879         result.add("Total Compile Time", totalBaselineCompileTime + totalDFGCompileTime + totalFTLCompileTime);
880         result.add("Baseline Compile Time", totalBaselineCompileTime);
881 #if ENABLE(DFG_JIT)
882         result.add("DFG Compile Time", totalDFGCompileTime);
883 #if ENABLE(FTL_JIT)
884         result.add("FTL Compile Time", totalFTLCompileTime);
885         result.add("FTL (DFG) Compile Time", totalFTLDFGCompileTime);
886         result.add("FTL (B3) Compile Time", totalFTLB3CompileTime);
887 #endif // ENABLE(FTL_JIT)
888 #endif // ENABLE(DFG_JIT)
889     }
890     return result;
891 }
892
893 } // namespace JSC
894
895 #endif // ENABLE(JIT)