Call linking slow paths should be passed a CallLinkInfo* directly so that you can...
[WebKit-https.git] / Source / JavaScriptCore / jit / JITCall.cpp
1 /*
2  * Copyright (C) 2008, 2013, 2014 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #if ENABLE(JIT)
29 #if USE(JSVALUE64)
30 #include "JIT.h"
31
32 #include "Arguments.h"
33 #include "CodeBlock.h"
34 #include "JITInlines.h"
35 #include "JSArray.h"
36 #include "JSFunction.h"
37 #include "Interpreter.h"
38 #include "JSCInlines.h"
39 #include "RepatchBuffer.h"
40 #include "ResultType.h"
41 #include "SamplingTool.h"
42 #include "StackAlignment.h"
43 #include "ThunkGenerators.h"
44 #include <wtf/StringPrintStream.h>
45
46
47 namespace JSC {
48
49 void JIT::emitPutCallResult(Instruction* instruction)
50 {
51     int dst = instruction[1].u.operand;
52     emitValueProfilingSite();
53     emitPutVirtualRegister(dst);
54 }
55
56 void JIT::compileLoadVarargs(Instruction* instruction)
57 {
58     int thisValue = instruction[3].u.operand;
59     int arguments = instruction[4].u.operand;
60     int firstFreeRegister = instruction[5].u.operand;
61     int firstVarArgOffset = instruction[6].u.operand;
62
63     JumpList slowCase;
64     JumpList end;
65     bool canOptimize = m_codeBlock->usesArguments()
66         && arguments == m_codeBlock->argumentsRegister().offset()
67         && !m_codeBlock->symbolTable()->slowArguments();
68
69     if (canOptimize) {
70         emitGetVirtualRegister(arguments, regT0);
71         slowCase.append(branch64(NotEqual, regT0, TrustedImm64(JSValue::encode(JSValue()))));
72
73         emitGetFromCallFrameHeader32(JSStack::ArgumentCount, regT0);
74         if (firstVarArgOffset) {
75             Jump sufficientArguments = branch32(GreaterThan, regT0, TrustedImm32(firstVarArgOffset + 1));
76             move(TrustedImm32(1), regT0);
77             Jump endVarArgs = jump();
78             sufficientArguments.link(this);
79             sub32(TrustedImm32(firstVarArgOffset), regT0);
80             endVarArgs.link(this);
81         }
82         slowCase.append(branch32(Above, regT0, TrustedImm32(Arguments::MaxArguments + 1)));
83         // regT0: argumentCountIncludingThis
84         move(regT0, regT1);
85         add64(TrustedImm32(-firstFreeRegister + JSStack::CallFrameHeaderSize), regT1);
86         // regT1 now has the required frame size in Register units
87         // Round regT1 to next multiple of stackAlignmentRegisters()
88         add64(TrustedImm32(stackAlignmentRegisters() - 1), regT1);
89         and64(TrustedImm32(~(stackAlignmentRegisters() - 1)), regT1);
90
91         neg64(regT1);
92         lshift64(TrustedImm32(3), regT1);
93         addPtr(callFrameRegister, regT1);
94         // regT1: newCallFrame
95
96         slowCase.append(branchPtr(Above, AbsoluteAddress(m_vm->addressOfStackLimit()), regT1));
97
98         // Initialize ArgumentCount.
99         store32(regT0, Address(regT1, JSStack::ArgumentCount * static_cast<int>(sizeof(Register)) + OBJECT_OFFSETOF(EncodedValueDescriptor, asBits.payload)));
100
101         // Initialize 'this'.
102         emitGetVirtualRegister(thisValue, regT2);
103         store64(regT2, Address(regT1, CallFrame::thisArgumentOffset() * static_cast<int>(sizeof(Register))));
104
105         // Copy arguments.
106         signExtend32ToPtr(regT0, regT0);
107         end.append(branchSub64(Zero, TrustedImm32(1), regT0));
108         // regT0: argumentCount
109
110         Label copyLoop = label();
111         load64(BaseIndex(callFrameRegister, regT0, TimesEight, (CallFrame::thisArgumentOffset() + firstVarArgOffset) * static_cast<int>(sizeof(Register))), regT2);
112         store64(regT2, BaseIndex(regT1, regT0, TimesEight, CallFrame::thisArgumentOffset() * static_cast<int>(sizeof(Register))));
113         branchSub64(NonZero, TrustedImm32(1), regT0).linkTo(copyLoop, this);
114
115         end.append(jump());
116     }
117
118     if (canOptimize)
119         slowCase.link(this);
120
121     emitGetVirtualRegister(arguments, regT1);
122     callOperation(operationSizeFrameForVarargs, regT1, firstFreeRegister, firstVarArgOffset);
123     move(returnValueGPR, stackPointerRegister);
124     emitGetVirtualRegister(thisValue, regT1);
125     emitGetVirtualRegister(arguments, regT2);
126     callOperation(operationLoadVarargs, returnValueGPR, regT1, regT2, firstVarArgOffset);
127     move(returnValueGPR, regT1);
128
129     if (canOptimize)
130         end.link(this);
131     
132     addPtr(TrustedImm32(sizeof(CallerFrameAndPC)), regT1, stackPointerRegister);
133 }
134
135 void JIT::compileCallEval(Instruction* instruction)
136 {
137     addPtr(TrustedImm32(-static_cast<ptrdiff_t>(sizeof(CallerFrameAndPC))), stackPointerRegister, regT1);
138     callOperationNoExceptionCheck(operationCallEval, regT1);
139
140     Jump noException = emitExceptionCheck(InvertedExceptionCheck);
141     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, stackPointerRegister);    
142     exceptionCheck(jump());
143
144     noException.link(this);
145     addSlowCase(branch64(Equal, regT0, TrustedImm64(JSValue::encode(JSValue()))));
146
147     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, stackPointerRegister);
148     checkStackPointerAlignment();
149
150     sampleCodeBlock(m_codeBlock);
151     
152     emitPutCallResult(instruction);
153 }
154
155 void JIT::compileCallEvalSlowCase(Instruction* instruction, Vector<SlowCaseEntry>::iterator& iter)
156 {
157     linkSlowCase(iter);
158
159     load64(Address(stackPointerRegister, sizeof(Register) * JSStack::Callee - sizeof(CallerFrameAndPC)), regT0);
160     move(TrustedImmPtr(&CallLinkInfo::dummy()), regT2);
161     emitNakedCall(m_vm->getCTIStub(virtualCallThunkGenerator).code());
162     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, stackPointerRegister);
163     checkStackPointerAlignment();
164
165     sampleCodeBlock(m_codeBlock);
166     
167     emitPutCallResult(instruction);
168 }
169
170 void JIT::compileOpCall(OpcodeID opcodeID, Instruction* instruction, unsigned callLinkInfoIndex)
171 {
172     int callee = instruction[2].u.operand;
173
174     /* Caller always:
175         - Updates callFrameRegister to callee callFrame.
176         - Initializes ArgumentCount; CallerFrame; Callee.
177
178        For a JS call:
179         - Caller initializes ScopeChain.
180         - Callee initializes ReturnPC; CodeBlock.
181         - Callee restores callFrameRegister before return.
182
183        For a non-JS call:
184         - Caller initializes ScopeChain; ReturnPC; CodeBlock.
185         - Caller restores callFrameRegister after return.
186     */
187     COMPILE_ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_construct), call_and_construct_opcodes_must_be_same_length);
188     COMPILE_ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_call_varargs), call_and_call_varargs_opcodes_must_be_same_length);
189     if (opcodeID == op_call_varargs)
190         compileLoadVarargs(instruction);
191     else {
192         int argCount = instruction[3].u.operand;
193         int registerOffset = -instruction[4].u.operand;
194
195         if (opcodeID == op_call && shouldEmitProfiling()) {
196             emitGetVirtualRegister(registerOffset + CallFrame::argumentOffsetIncludingThis(0), regT0);
197             Jump done = emitJumpIfNotJSCell(regT0);
198             load32(Address(regT0, JSCell::structureIDOffset()), regT0);
199             store32(regT0, instruction[OPCODE_LENGTH(op_call) - 2].u.arrayProfile->addressOfLastSeenStructureID());
200             done.link(this);
201         }
202     
203         addPtr(TrustedImm32(registerOffset * sizeof(Register) + sizeof(CallerFrameAndPC)), callFrameRegister, stackPointerRegister);
204         store32(TrustedImm32(argCount), Address(stackPointerRegister, JSStack::ArgumentCount * static_cast<int>(sizeof(Register)) + PayloadOffset - sizeof(CallerFrameAndPC)));
205     } // SP holds newCallFrame + sizeof(CallerFrameAndPC), with ArgumentCount initialized.
206     
207     uint32_t bytecodeOffset = instruction - m_codeBlock->instructions().begin();
208     uint32_t locationBits = CallFrame::Location::encodeAsBytecodeOffset(bytecodeOffset);
209     store32(TrustedImm32(locationBits), Address(callFrameRegister, JSStack::ArgumentCount * static_cast<int>(sizeof(Register)) + TagOffset));
210     emitGetVirtualRegister(callee, regT0); // regT0 holds callee.
211
212     store64(regT0, Address(stackPointerRegister, JSStack::Callee * static_cast<int>(sizeof(Register)) - sizeof(CallerFrameAndPC)));
213
214     if (opcodeID == op_call_eval) {
215         compileCallEval(instruction);
216         return;
217     }
218
219     DataLabelPtr addressOfLinkedFunctionCheck;
220     Jump slowCase = branchPtrWithPatch(NotEqual, regT0, addressOfLinkedFunctionCheck, TrustedImmPtr(0));
221     addSlowCase(slowCase);
222
223     ASSERT(m_callCompilationInfo.size() == callLinkInfoIndex);
224     CallLinkInfo* info = m_codeBlock->addCallLinkInfo();
225     info->callType = CallLinkInfo::callTypeFor(opcodeID);
226     info->codeOrigin = CodeOrigin(m_bytecodeOffset);
227     info->calleeGPR = regT0;
228     m_callCompilationInfo.append(CallCompilationInfo());
229     m_callCompilationInfo[callLinkInfoIndex].hotPathBegin = addressOfLinkedFunctionCheck;
230     m_callCompilationInfo[callLinkInfoIndex].callLinkInfo = info;
231
232     loadPtr(Address(regT0, OBJECT_OFFSETOF(JSFunction, m_scope)), regT2);
233     store64(regT2, Address(MacroAssembler::stackPointerRegister, JSStack::ScopeChain * sizeof(Register) - sizeof(CallerFrameAndPC)));
234
235     m_callCompilationInfo[callLinkInfoIndex].hotPathOther = emitNakedCall();
236
237     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, stackPointerRegister);
238     checkStackPointerAlignment();
239
240     sampleCodeBlock(m_codeBlock);
241     
242     emitPutCallResult(instruction);
243 }
244
245 void JIT::compileOpCallSlowCase(OpcodeID opcodeID, Instruction* instruction, Vector<SlowCaseEntry>::iterator& iter, unsigned callLinkInfoIndex)
246 {
247     if (opcodeID == op_call_eval) {
248         compileCallEvalSlowCase(instruction, iter);
249         return;
250     }
251
252     linkSlowCase(iter);
253
254     ThunkGenerator generator = linkThunkGeneratorFor(
255         opcodeID == op_construct ? CodeForConstruct : CodeForCall,
256         RegisterPreservationNotRequired);
257     
258     move(TrustedImmPtr(m_callCompilationInfo[callLinkInfoIndex].callLinkInfo), regT2);
259     m_callCompilationInfo[callLinkInfoIndex].callReturnLocation = emitNakedCall(m_vm->getCTIStub(generator).code());
260
261     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, stackPointerRegister);
262     checkStackPointerAlignment();
263
264     sampleCodeBlock(m_codeBlock);
265     
266     emitPutCallResult(instruction);
267 }
268
269 void JIT::privateCompileClosureCall(CallLinkInfo* callLinkInfo, CodeBlock* calleeCodeBlock, Structure* expectedStructure, ExecutableBase* expectedExecutable, MacroAssemblerCodePtr codePtr)
270 {
271     JumpList slowCases;
272
273     slowCases.append(branchTestPtr(NonZero, regT0, tagMaskRegister));
274     slowCases.append(branchStructure(NotEqual, Address(regT0, JSCell::structureIDOffset()), expectedStructure));
275     slowCases.append(branchPtr(NotEqual, Address(regT0, JSFunction::offsetOfExecutable()), TrustedImmPtr(expectedExecutable)));
276     
277     loadPtr(Address(regT0, JSFunction::offsetOfScopeChain()), regT1);
278     emitPutToCallFrameHeader(regT1, JSStack::ScopeChain);
279     
280     Call call = nearCall();
281     Jump done = jump();
282     
283     slowCases.link(this);
284     move(TrustedImmPtr(callLinkInfo->callReturnLocation.executableAddress()), regT2);
285     restoreReturnAddressBeforeReturn(regT2);
286     Jump slow = jump();
287     
288     LinkBuffer patchBuffer(*m_vm, this, m_codeBlock);
289     
290     patchBuffer.link(call, FunctionPtr(codePtr.executableAddress()));
291     patchBuffer.link(done, callLinkInfo->hotPathOther.labelAtOffset(0));
292     patchBuffer.link(slow, CodeLocationLabel(m_vm->getCTIStub(virtualCallThunkGenerator).code()));
293     
294     RefPtr<ClosureCallStubRoutine> stubRoutine = adoptRef(new ClosureCallStubRoutine(
295         FINALIZE_CODE(
296             patchBuffer,
297             ("Baseline closure call stub for %s, return point %p, target %p (%s)",
298                 toCString(*m_codeBlock).data(),
299                 callLinkInfo->hotPathOther.labelAtOffset(0).executableAddress(),
300                 codePtr.executableAddress(),
301                 toCString(pointerDump(calleeCodeBlock)).data())),
302         *m_vm, m_codeBlock->ownerExecutable(), expectedStructure, expectedExecutable,
303         callLinkInfo->codeOrigin));
304     
305     RepatchBuffer repatchBuffer(m_codeBlock);
306     
307     repatchBuffer.replaceWithJump(
308         RepatchBuffer::startOfBranchPtrWithPatchOnRegister(callLinkInfo->hotPathBegin),
309         CodeLocationLabel(stubRoutine->code().code()));
310     repatchBuffer.relink(callLinkInfo->callReturnLocation, m_vm->getCTIStub(virtualCallThunkGenerator).code());
311
312     callLinkInfo->stub = stubRoutine.release();
313 }
314
315 void JIT::emit_op_call(Instruction* currentInstruction)
316 {
317     compileOpCall(op_call, currentInstruction, m_callLinkInfoIndex++);
318 }
319
320 void JIT::emit_op_call_eval(Instruction* currentInstruction)
321 {
322     compileOpCall(op_call_eval, currentInstruction, m_callLinkInfoIndex);
323 }
324
325 void JIT::emit_op_call_varargs(Instruction* currentInstruction)
326 {
327     compileOpCall(op_call_varargs, currentInstruction, m_callLinkInfoIndex++);
328 }
329
330 void JIT::emit_op_construct(Instruction* currentInstruction)
331 {
332     compileOpCall(op_construct, currentInstruction, m_callLinkInfoIndex++);
333 }
334
335 void JIT::emitSlow_op_call(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
336 {
337     compileOpCallSlowCase(op_call, currentInstruction, iter, m_callLinkInfoIndex++);
338 }
339
340 void JIT::emitSlow_op_call_eval(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
341 {
342     compileOpCallSlowCase(op_call_eval, currentInstruction, iter, m_callLinkInfoIndex);
343 }
344  
345 void JIT::emitSlow_op_call_varargs(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
346 {
347     compileOpCallSlowCase(op_call_varargs, currentInstruction, iter, m_callLinkInfoIndex++);
348 }
349
350 void JIT::emitSlow_op_construct(Instruction* currentInstruction, Vector<SlowCaseEntry>::iterator& iter)
351 {
352     compileOpCallSlowCase(op_construct, currentInstruction, iter, m_callLinkInfoIndex++);
353 }
354
355 } // namespace JSC
356
357 #endif // USE(JSVALUE64)
358 #endif // ENABLE(JIT)