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