2 * Copyright (C) 2011, 2013, 2014, 2015 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "DFGOSREntry.h"
31 #include "CallFrame.h"
32 #include "CodeBlock.h"
33 #include "DFGJITCode.h"
36 #include "JSStackInlines.h"
37 #include "JSCInlines.h"
38 #include <wtf/CommaPrinter.h>
40 namespace JSC { namespace DFG {
42 void OSREntryData::dumpInContext(PrintStream& out, DumpContext* context) const
44 out.print("bc#", m_bytecodeIndex, ", machine code offset = ", m_machineCodeOffset);
45 out.print(", stack rules = [");
47 auto printOperand = [&] (VirtualRegister reg) {
48 out.print(inContext(m_expectedValues.operand(reg), context), " (");
49 VirtualRegister toReg;
50 bool overwritten = false;
51 for (OSREntryReshuffling reshuffling : m_reshufflings) {
52 if (reg == VirtualRegister(reshuffling.fromOffset)) {
53 toReg = VirtualRegister(reshuffling.toOffset);
56 if (reg == VirtualRegister(reshuffling.toOffset))
59 if (!overwritten && !toReg.isValid())
61 if (toReg.isValid()) {
62 if (toReg.isLocal() && !m_machineStackUsed.get(toReg.toLocal()))
65 out.print("maps to ", toReg);
67 out.print("overwritten");
68 if (reg.isLocal() && m_localsForcedDouble.get(reg.toLocal()))
69 out.print(", forced double");
70 if (reg.isLocal() && m_localsForcedMachineInt.get(reg.toLocal()))
71 out.print(", forced machine int");
76 for (size_t argumentIndex = m_expectedValues.numberOfArguments(); argumentIndex--;) {
77 out.print(comma, "arg", argumentIndex, ":");
78 printOperand(virtualRegisterForArgument(argumentIndex));
80 for (size_t localIndex = 0; localIndex < m_expectedValues.numberOfLocals(); ++localIndex) {
81 out.print(comma, "loc", localIndex, ":");
82 printOperand(virtualRegisterForLocal(localIndex));
85 out.print("], machine stack used = ", m_machineStackUsed);
88 void OSREntryData::dump(PrintStream& out) const
90 dumpInContext(out, nullptr);
94 void* prepareOSREntry(ExecState* exec, CodeBlock* codeBlock, unsigned bytecodeIndex)
96 ASSERT(JITCode::isOptimizingJIT(codeBlock->jitType()));
97 ASSERT(codeBlock->alternative());
98 ASSERT(codeBlock->alternative()->jitType() == JITCode::BaselineJIT);
99 ASSERT(!codeBlock->jitCodeMap());
101 if (!Options::enableOSREntryToDFG())
104 if (Options::verboseOSR()) {
106 "DFG OSR in ", *codeBlock->alternative(), " -> ", *codeBlock,
107 " from bc#", bytecodeIndex, "\n");
110 VM* vm = &exec->vm();
112 sanitizeStackForVM(vm);
115 codeBlock->ownerExecutable()->setDidTryToEnterInLoop(true);
117 if (codeBlock->jitType() != JITCode::DFGJIT) {
118 RELEASE_ASSERT(codeBlock->jitType() == JITCode::FTLJIT);
120 // When will this happen? We could have:
122 // - An exit from the FTL JIT into the baseline JIT followed by an attempt
123 // to reenter. We're fine with allowing this to fail. If it happens
124 // enough we'll just reoptimize. It basically means that the OSR exit cost
125 // us dearly and so reoptimizing is the right thing to do.
127 // - We have recursive code with hot loops. Consider that foo has a hot loop
128 // that calls itself. We have two foo's on the stack, lets call them foo1
129 // and foo2, with foo1 having called foo2 from foo's hot loop. foo2 gets
130 // optimized all the way into the FTL. Then it returns into foo1, and then
131 // foo1 wants to get optimized. It might reach this conclusion from its
132 // hot loop and attempt to OSR enter. And we'll tell it that it can't. It
133 // might be worth addressing this case, but I just think this case will
134 // be super rare. For now, if it does happen, it'll cause some compilation
137 if (Options::verboseOSR())
138 dataLog(" OSR failed because the target code block is not DFG.\n");
142 JITCode* jitCode = codeBlock->jitCode()->dfg();
143 OSREntryData* entry = jitCode->osrEntryDataForBytecodeIndex(bytecodeIndex);
146 if (Options::verboseOSR())
147 dataLogF(" OSR failed because the entrypoint was optimized out.\n");
151 ASSERT(entry->m_bytecodeIndex == bytecodeIndex);
153 // The code below checks if it is safe to perform OSR entry. It may find
154 // that it is unsafe to do so, for any number of reasons, which are documented
155 // below. If the code decides not to OSR then it returns 0, and it's the caller's
156 // responsibility to patch up the state in such a way as to ensure that it's
157 // both safe and efficient to continue executing baseline code for now. This
158 // should almost certainly include calling either codeBlock->optimizeAfterWarmUp()
159 // or codeBlock->dontOptimizeAnytimeSoon().
161 // 1) Verify predictions. If the predictions are inconsistent with the actual
162 // values, then OSR entry is not possible at this time. It's tempting to
163 // assume that we could somehow avoid this case. We can certainly avoid it
164 // for first-time loop OSR - that is, OSR into a CodeBlock that we have just
165 // compiled. Then we are almost guaranteed that all of the predictions will
166 // check out. It would be pretty easy to make that a hard guarantee. But
167 // then there would still be the case where two call frames with the same
168 // baseline CodeBlock are on the stack at the same time. The top one
169 // triggers compilation and OSR. In that case, we may no longer have
170 // accurate value profiles for the one deeper in the stack. Hence, when we
171 // pop into the CodeBlock that is deeper on the stack, we might OSR and
172 // realize that the predictions are wrong. Probably, in most cases, this is
173 // just an anomaly in the sense that the older CodeBlock simply went off
174 // into a less-likely path. So, the wisest course of action is to simply not
177 for (size_t argument = 0; argument < entry->m_expectedValues.numberOfArguments(); ++argument) {
178 if (argument >= exec->argumentCountIncludingThis()) {
179 if (Options::verboseOSR()) {
180 dataLogF(" OSR failed because argument %zu was not passed, expected ", argument);
181 entry->m_expectedValues.argument(argument).dump(WTF::dataFile());
189 value = exec->thisValue();
191 value = exec->argument(argument - 1);
193 if (!entry->m_expectedValues.argument(argument).validate(value)) {
194 if (Options::verboseOSR()) {
196 " OSR failed because argument ", argument, " is ", value,
197 ", expected ", entry->m_expectedValues.argument(argument), ".\n");
203 for (size_t local = 0; local < entry->m_expectedValues.numberOfLocals(); ++local) {
204 int localOffset = virtualRegisterForLocal(local).offset();
205 if (entry->m_localsForcedDouble.get(local)) {
206 if (!exec->registers()[localOffset].asanUnsafeJSValue().isNumber()) {
207 if (Options::verboseOSR()) {
209 " OSR failed because variable ", localOffset, " is ",
210 exec->registers()[localOffset].asanUnsafeJSValue(), ", expected number.\n");
216 if (entry->m_localsForcedMachineInt.get(local)) {
217 if (!exec->registers()[localOffset].asanUnsafeJSValue().isMachineInt()) {
218 if (Options::verboseOSR()) {
220 " OSR failed because variable ", localOffset, " is ",
221 exec->registers()[localOffset].asanUnsafeJSValue(), ", expected ",
228 if (!entry->m_expectedValues.local(local).validate(exec->registers()[localOffset].asanUnsafeJSValue())) {
229 if (Options::verboseOSR()) {
231 " OSR failed because variable ", localOffset, " is ",
232 exec->registers()[localOffset].asanUnsafeJSValue(), ", expected ",
233 entry->m_expectedValues.local(local), ".\n");
239 // 2) Check the stack height. The DFG JIT may require a taller stack than the
240 // baseline JIT, in some cases. If we can't grow the stack, then don't do
241 // OSR right now. That's the only option we have unless we want basic block
242 // boundaries to start throwing RangeErrors. Although that would be possible,
243 // it seems silly: you'd be diverting the program to error handling when it
244 // would have otherwise just kept running albeit less quickly.
246 unsigned frameSizeForCheck = jitCode->common.requiredRegisterCountForExecutionAndExit();
247 if (!vm->interpreter->stack().ensureCapacityFor(&exec->registers()[virtualRegisterForLocal(frameSizeForCheck - 1).offset()])) {
248 if (Options::verboseOSR())
249 dataLogF(" OSR failed because stack growth failed.\n");
253 if (Options::verboseOSR())
254 dataLogF(" OSR should succeed.\n");
256 // At this point we're committed to entering. We will do some work to set things up,
257 // but we also rely on our caller recognizing that when we return a non-null pointer,
258 // that means that we're already past the point of no return and we must succeed at
261 // 3) Set up the data in the scratch buffer and perform data format conversions.
263 unsigned frameSize = jitCode->common.frameRegisterCount;
264 unsigned baselineFrameSize = entry->m_expectedValues.numberOfLocals();
265 unsigned maxFrameSize = std::max(frameSize, baselineFrameSize);
267 Register* scratch = bitwise_cast<Register*>(vm->scratchBufferForSize(sizeof(Register) * (2 + JSStack::CallFrameHeaderSize + maxFrameSize))->dataBuffer());
269 *bitwise_cast<size_t*>(scratch + 0) = frameSize;
271 void* targetPC = codeBlock->jitCode()->executableAddressAtOffset(entry->m_machineCodeOffset);
272 if (Options::verboseOSR())
273 dataLogF(" OSR using target PC %p.\n", targetPC);
274 RELEASE_ASSERT(targetPC);
275 *bitwise_cast<void**>(scratch + 1) = targetPC;
277 Register* pivot = scratch + 2 + JSStack::CallFrameHeaderSize;
279 for (int index = -JSStack::CallFrameHeaderSize; index < static_cast<int>(baselineFrameSize); ++index) {
280 VirtualRegister reg(-1 - index);
283 if (entry->m_localsForcedDouble.get(reg.toLocal())) {
284 *bitwise_cast<double*>(pivot + index) = exec->registers()[reg.offset()].asanUnsafeJSValue().asNumber();
288 if (entry->m_localsForcedMachineInt.get(reg.toLocal())) {
289 *bitwise_cast<int64_t*>(pivot + index) = exec->registers()[reg.offset()].asanUnsafeJSValue().asMachineInt() << JSValue::int52ShiftAmount;
294 pivot[index] = exec->registers()[reg.offset()].asanUnsafeJSValue();
297 // 4) Reshuffle those registers that need reshuffling.
298 Vector<JSValue> temporaryLocals(entry->m_reshufflings.size());
299 for (unsigned i = entry->m_reshufflings.size(); i--;)
300 temporaryLocals[i] = pivot[VirtualRegister(entry->m_reshufflings[i].fromOffset).toLocal()].asanUnsafeJSValue();
301 for (unsigned i = entry->m_reshufflings.size(); i--;)
302 pivot[VirtualRegister(entry->m_reshufflings[i].toOffset).toLocal()] = temporaryLocals[i];
304 // 5) Clear those parts of the call frame that the DFG ain't using. This helps GC on
305 // some programs by eliminating some stale pointer pathologies.
306 for (unsigned i = frameSize; i--;) {
307 if (entry->m_machineStackUsed.get(i))
309 pivot[i] = JSValue();
312 // 6) Fix the call frame to have the right code block.
314 *bitwise_cast<CodeBlock**>(pivot - 1 - JSStack::CodeBlock) = codeBlock;
316 if (Options::verboseOSR())
317 dataLogF(" OSR returning data buffer %p.\n", scratch);
321 } } // namespace JSC::DFG
323 #endif // ENABLE(DFG_JIT)