80458912d90f7d57d58fb1a5690f39dfcc7022e0
[WebKit-https.git] / Source / JavaScriptCore / dfg / DFGJITCompiler.cpp
1 /*
2  * Copyright (C) 2011, 2013-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 #include "DFGJITCompiler.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "CodeBlock.h"
32 #include "DFGFailedFinalizer.h"
33 #include "DFGInlineCacheWrapperInlines.h"
34 #include "DFGJITCode.h"
35 #include "DFGJITFinalizer.h"
36 #include "DFGOSRExitCompiler.h"
37 #include "DFGOperations.h"
38 #include "DFGRegisterBank.h"
39 #include "DFGSlowPathGenerator.h"
40 #include "DFGSpeculativeJIT.h"
41 #include "DFGThunks.h"
42 #include "JSCInlines.h"
43 #include "JSCJSValueInlines.h"
44 #include "LinkBuffer.h"
45 #include "MaxFrameExtentForSlowPathCall.h"
46 #include "StructureStubInfo.h"
47 #include "VM.h"
48
49 namespace JSC { namespace DFG {
50
51 JITCompiler::JITCompiler(Graph& dfg)
52     : CCallHelpers(&dfg.m_vm, dfg.m_codeBlock)
53     , m_graph(dfg)
54     , m_jitCode(adoptRef(new JITCode()))
55     , m_blockHeads(dfg.numBlocks())
56     , m_pcToCodeOriginMapBuilder(dfg.m_vm)
57 {
58     if (shouldDumpDisassembly() || m_graph.m_vm.m_perBytecodeProfiler)
59         m_disassembler = std::make_unique<Disassembler>(dfg);
60 #if ENABLE(FTL_JIT)
61     m_jitCode->tierUpInLoopHierarchy = WTFMove(m_graph.m_plan.tierUpInLoopHierarchy);
62     for (unsigned tierUpBytecode : m_graph.m_plan.tierUpAndOSREnterBytecodes)
63         m_jitCode->tierUpEntryTriggers.add(tierUpBytecode, 0);
64 #endif
65 }
66
67 JITCompiler::~JITCompiler()
68 {
69 }
70
71 void JITCompiler::linkOSRExits()
72 {
73     ASSERT(m_jitCode->osrExit.size() == m_exitCompilationInfo.size());
74     if (m_graph.compilation()) {
75         for (unsigned i = 0; i < m_jitCode->osrExit.size(); ++i) {
76             OSRExitCompilationInfo& info = m_exitCompilationInfo[i];
77             Vector<Label> labels;
78             if (!info.m_failureJumps.empty()) {
79                 for (unsigned j = 0; j < info.m_failureJumps.jumps().size(); ++j)
80                     labels.append(info.m_failureJumps.jumps()[j].label());
81             } else
82                 labels.append(info.m_replacementSource);
83             m_exitSiteLabels.append(labels);
84         }
85     }
86     
87     for (unsigned i = 0; i < m_jitCode->osrExit.size(); ++i) {
88         OSRExit& exit = m_jitCode->osrExit[i];
89         OSRExitCompilationInfo& info = m_exitCompilationInfo[i];
90         JumpList& failureJumps = info.m_failureJumps;
91         if (!failureJumps.empty())
92             failureJumps.link(this);
93         else
94             info.m_replacementDestination = label();
95
96         jitAssertHasValidCallFrame();
97         store32(TrustedImm32(i), &vm()->osrExitIndex);
98         exit.setPatchableCodeOffset(patchableJump());
99     }
100 }
101
102 void JITCompiler::compileEntry()
103 {
104     // This code currently matches the old JIT. In the function header we need to
105     // save return address and call frame via the prologue and perform a fast stack check.
106     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=56292
107     // We'll need to convert the remaining cti_ style calls (specifically the stack
108     // check) which will be dependent on stack layout. (We'd need to account for this in
109     // both normal return code and when jumping to an exception handler).
110     emitFunctionPrologue();
111     emitPutToCallFrameHeader(m_codeBlock, CallFrameSlot::codeBlock);
112 }
113
114 void JITCompiler::compileSetupRegistersForEntry()
115 {
116     emitSaveCalleeSaves();
117     emitMaterializeTagCheckRegisters();    
118 }
119
120 void JITCompiler::compileEntryExecutionFlag()
121 {
122 #if ENABLE(FTL_JIT)
123     if (m_graph.m_plan.canTierUpAndOSREnter())
124         store8(TrustedImm32(0), &m_jitCode->neverExecutedEntry);
125 #endif // ENABLE(FTL_JIT)
126 }
127
128 void JITCompiler::compileBody()
129 {
130     // We generate the speculative code path, followed by OSR exit code to return
131     // to the old JIT code if speculations fail.
132
133     bool compiledSpeculative = m_speculative->compile();
134     ASSERT_UNUSED(compiledSpeculative, compiledSpeculative);
135 }
136
137 void JITCompiler::compileExceptionHandlers()
138 {
139     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
140         m_exceptionChecksWithCallFrameRollback.link(this);
141
142         copyCalleeSavesToVMEntryFrameCalleeSavesBuffer();
143
144         // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
145         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
146         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
147         addPtr(TrustedImm32(m_graph.stackPointerOffset() * sizeof(Register)), GPRInfo::callFrameRegister, stackPointerRegister);
148
149 #if CPU(X86)
150         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
151         poke(GPRInfo::argumentGPR0);
152         poke(GPRInfo::argumentGPR1, 1);
153 #endif
154         m_calls.append(CallLinkRecord(call(), lookupExceptionHandlerFromCallerFrame));
155
156         jumpToExceptionHandler();
157     }
158
159     if (!m_exceptionChecks.empty()) {
160         m_exceptionChecks.link(this);
161
162         copyCalleeSavesToVMEntryFrameCalleeSavesBuffer();
163
164         // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
165         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
166         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
167
168 #if CPU(X86)
169         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
170         poke(GPRInfo::argumentGPR0);
171         poke(GPRInfo::argumentGPR1, 1);
172 #endif
173         m_calls.append(CallLinkRecord(call(), lookupExceptionHandler));
174
175         jumpToExceptionHandler();
176     }
177 }
178
179 void JITCompiler::link(LinkBuffer& linkBuffer)
180 {
181     // Link the code, populate data in CodeBlock data structures.
182     m_jitCode->common.frameRegisterCount = m_graph.frameRegisterCount();
183     m_jitCode->common.requiredRegisterCountForExit = m_graph.requiredRegisterCountForExit();
184
185     if (!m_graph.m_plan.inlineCallFrames->isEmpty())
186         m_jitCode->common.inlineCallFrames = m_graph.m_plan.inlineCallFrames;
187     
188 #if USE(JSVALUE32_64)
189     m_jitCode->common.doubleConstants = WTFMove(m_graph.m_doubleConstants);
190 #endif
191     
192     m_graph.registerFrozenValues();
193
194     BitVector usedJumpTables;
195     for (Bag<SwitchData>::iterator iter = m_graph.m_switchData.begin(); !!iter; ++iter) {
196         SwitchData& data = **iter;
197         if (!data.didUseJumpTable)
198             continue;
199         
200         if (data.kind == SwitchString)
201             continue;
202         
203         RELEASE_ASSERT(data.kind == SwitchImm || data.kind == SwitchChar);
204         
205         usedJumpTables.set(data.switchTableIndex);
206         SimpleJumpTable& table = m_codeBlock->switchJumpTable(data.switchTableIndex);
207         table.ctiDefault = linkBuffer.locationOf(m_blockHeads[data.fallThrough.block->index]);
208         table.ctiOffsets.grow(table.branchOffsets.size());
209         for (unsigned j = table.ctiOffsets.size(); j--;)
210             table.ctiOffsets[j] = table.ctiDefault;
211         for (unsigned j = data.cases.size(); j--;) {
212             SwitchCase& myCase = data.cases[j];
213             table.ctiOffsets[myCase.value.switchLookupValue(data.kind) - table.min] =
214                 linkBuffer.locationOf(m_blockHeads[myCase.target.block->index]);
215         }
216     }
217     
218     for (unsigned i = m_codeBlock->numberOfSwitchJumpTables(); i--;) {
219         if (usedJumpTables.get(i))
220             continue;
221         
222         m_codeBlock->switchJumpTable(i).clear();
223     }
224
225     // NOTE: we cannot clear string switch tables because (1) we're running concurrently
226     // and we cannot deref StringImpl's and (2) it would be weird to deref those
227     // StringImpl's since we refer to them.
228     for (Bag<SwitchData>::iterator switchDataIter = m_graph.m_switchData.begin(); !!switchDataIter; ++switchDataIter) {
229         SwitchData& data = **switchDataIter;
230         if (!data.didUseJumpTable)
231             continue;
232         
233         if (data.kind != SwitchString)
234             continue;
235         
236         StringJumpTable& table = m_codeBlock->stringSwitchJumpTable(data.switchTableIndex);
237         table.ctiDefault = linkBuffer.locationOf(m_blockHeads[data.fallThrough.block->index]);
238         StringJumpTable::StringOffsetTable::iterator iter;
239         StringJumpTable::StringOffsetTable::iterator end = table.offsetTable.end();
240         for (iter = table.offsetTable.begin(); iter != end; ++iter)
241             iter->value.ctiOffset = table.ctiDefault;
242         for (unsigned j = data.cases.size(); j--;) {
243             SwitchCase& myCase = data.cases[j];
244             iter = table.offsetTable.find(myCase.value.stringImpl());
245             RELEASE_ASSERT(iter != end);
246             iter->value.ctiOffset = linkBuffer.locationOf(m_blockHeads[myCase.target.block->index]);
247         }
248     }
249
250     // Link all calls out from the JIT code to their respective functions.
251     for (unsigned i = 0; i < m_calls.size(); ++i)
252         linkBuffer.link(m_calls[i].m_call, m_calls[i].m_function);
253
254     for (unsigned i = m_getByIds.size(); i--;)
255         m_getByIds[i].finalize(linkBuffer);
256     for (unsigned i = m_putByIds.size(); i--;)
257         m_putByIds[i].finalize(linkBuffer);
258
259     for (unsigned i = 0; i < m_ins.size(); ++i) {
260         StructureStubInfo& info = *m_ins[i].m_stubInfo;
261
262         CodeLocationLabel start = linkBuffer.locationOf(m_ins[i].m_jump);
263         info.patch.start = start;
264
265         ptrdiff_t inlineSize = MacroAssembler::differenceBetweenCodePtr(
266             start, linkBuffer.locationOf(m_ins[i].m_done));
267         RELEASE_ASSERT(inlineSize >= 0);
268         info.patch.inlineSize = inlineSize;
269
270         info.patch.deltaFromStartToSlowPathCallLocation = MacroAssembler::differenceBetweenCodePtr(
271             start, linkBuffer.locationOf(m_ins[i].m_slowPathGenerator->call()));
272
273         info.patch.deltaFromStartToSlowPathStart = MacroAssembler::differenceBetweenCodePtr(
274             start, linkBuffer.locationOf(m_ins[i].m_slowPathGenerator->label()));
275     }
276     
277     for (unsigned i = 0; i < m_jsCalls.size(); ++i) {
278         JSCallRecord& record = m_jsCalls[i];
279         CallLinkInfo& info = *record.m_info;
280         linkBuffer.link(record.m_slowCall, FunctionPtr(m_vm->getCTIStub(linkCallThunkGenerator).code().executableAddress()));
281         info.setCallLocations(linkBuffer.locationOfNearCall(record.m_slowCall),
282             linkBuffer.locationOf(record.m_targetToCheck),
283             linkBuffer.locationOfNearCall(record.m_fastCall));
284     }
285     
286     MacroAssemblerCodeRef osrExitThunk = vm()->getCTIStub(osrExitGenerationThunkGenerator);
287     CodeLocationLabel target = CodeLocationLabel(osrExitThunk.code());
288     for (unsigned i = 0; i < m_jitCode->osrExit.size(); ++i) {
289         OSRExit& exit = m_jitCode->osrExit[i];
290         OSRExitCompilationInfo& info = m_exitCompilationInfo[i];
291         linkBuffer.link(exit.getPatchableCodeOffsetAsJump(), target);
292         exit.correctJump(linkBuffer);
293         if (info.m_replacementSource.isSet()) {
294             m_jitCode->common.jumpReplacements.append(JumpReplacement(
295                 linkBuffer.locationOf(info.m_replacementSource),
296                 linkBuffer.locationOf(info.m_replacementDestination)));
297         }
298     }
299     
300     if (m_graph.compilation()) {
301         ASSERT(m_exitSiteLabels.size() == m_jitCode->osrExit.size());
302         for (unsigned i = 0; i < m_exitSiteLabels.size(); ++i) {
303             Vector<Label>& labels = m_exitSiteLabels[i];
304             Vector<const void*> addresses;
305             for (unsigned j = 0; j < labels.size(); ++j)
306                 addresses.append(linkBuffer.locationOf(labels[j]).executableAddress());
307             m_graph.compilation()->addOSRExitSite(addresses);
308         }
309     } else
310         ASSERT(!m_exitSiteLabels.size());
311
312     m_jitCode->common.compilation = m_graph.compilation();
313     
314     // Link new DFG exception handlers and remove baseline JIT handlers.
315     m_codeBlock->clearExceptionHandlers();
316     for (unsigned  i = 0; i < m_exceptionHandlerOSRExitCallSites.size(); i++) {
317         OSRExitCompilationInfo& info = m_exceptionHandlerOSRExitCallSites[i].exitInfo;
318         if (info.m_replacementDestination.isSet()) {
319             // If this is is *not* set, it means that we already jumped to the OSR exit in pure generated control flow.
320             // i.e, we explicitly emitted an exceptionCheck that we know will be caught in this machine frame.
321             // If this *is set*, it means we will be landing at this code location from genericUnwind from an
322             // exception thrown in a child call frame.
323             CodeLocationLabel catchLabel = linkBuffer.locationOf(info.m_replacementDestination);
324             HandlerInfo newExceptionHandler = m_exceptionHandlerOSRExitCallSites[i].baselineExceptionHandler;
325             CallSiteIndex callSite = m_exceptionHandlerOSRExitCallSites[i].callSiteIndex;
326             newExceptionHandler.start = callSite.bits();
327             newExceptionHandler.end = callSite.bits() + 1;
328             newExceptionHandler.nativeCode = catchLabel;
329             m_codeBlock->appendExceptionHandler(newExceptionHandler);
330         }
331     }
332
333     if (m_pcToCodeOriginMapBuilder.didBuildMapping())
334         m_codeBlock->setPCToCodeOriginMap(std::make_unique<PCToCodeOriginMap>(WTFMove(m_pcToCodeOriginMapBuilder), linkBuffer));
335 }
336
337 void JITCompiler::compile()
338 {
339     setStartOfCode();
340     compileEntry();
341     m_speculative = std::make_unique<SpeculativeJIT>(*this);
342
343     // Plant a check that sufficient space is available in the JSStack.
344     addPtr(TrustedImm32(virtualRegisterForLocal(m_graph.requiredRegisterCountForExecutionAndExit() - 1).offset() * sizeof(Register)), GPRInfo::callFrameRegister, GPRInfo::regT1);
345     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfOSStackLimitWithReserve()), GPRInfo::regT1);
346
347     addPtr(TrustedImm32(m_graph.stackPointerOffset() * sizeof(Register)), GPRInfo::callFrameRegister, stackPointerRegister);
348     checkStackPointerAlignment();
349     compileSetupRegistersForEntry();
350     compileEntryExecutionFlag();
351     compileBody();
352     setEndOfMainPath();
353
354     // === Footer code generation ===
355     //
356     // Generate the stack overflow handling; if the stack check in the entry head fails,
357     // we need to call out to a helper function to throw the StackOverflowError.
358     stackOverflow.link(this);
359
360     emitStoreCodeOrigin(CodeOrigin(0));
361
362     if (maxFrameExtentForSlowPathCall)
363         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
364
365     m_speculative->callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
366
367     // Generate slow path code.
368     m_speculative->runSlowPathGenerators(m_pcToCodeOriginMapBuilder);
369     m_pcToCodeOriginMapBuilder.appendItem(label(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
370     
371     compileExceptionHandlers();
372     linkOSRExits();
373     
374     // Create OSR entry trampolines if necessary.
375     m_speculative->createOSREntries();
376     setEndOfCode();
377
378     auto linkBuffer = std::make_unique<LinkBuffer>(*m_vm, *this, m_codeBlock, JITCompilationCanFail);
379     if (linkBuffer->didFailToAllocate()) {
380         m_graph.m_plan.finalizer = std::make_unique<FailedFinalizer>(m_graph.m_plan);
381         return;
382     }
383     
384     link(*linkBuffer);
385     m_speculative->linkOSREntries(*linkBuffer);
386
387     m_jitCode->shrinkToFit();
388     codeBlock()->shrinkToFit(CodeBlock::LateShrink);
389
390     disassemble(*linkBuffer);
391     
392     m_graph.m_plan.finalizer = std::make_unique<JITFinalizer>(
393         m_graph.m_plan, WTFMove(m_jitCode), WTFMove(linkBuffer));
394 }
395
396 void JITCompiler::compileFunction()
397 {
398     setStartOfCode();
399     compileEntry();
400
401     // === Function header code generation ===
402     // This is the main entry point, without performing an arity check.
403     // If we needed to perform an arity check we will already have moved the return address,
404     // so enter after this.
405     Label fromArityCheck(this);
406     // Plant a check that sufficient space is available in the JSStack.
407     addPtr(TrustedImm32(virtualRegisterForLocal(m_graph.requiredRegisterCountForExecutionAndExit() - 1).offset() * sizeof(Register)), GPRInfo::callFrameRegister, GPRInfo::regT1);
408     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfOSStackLimitWithReserve()), GPRInfo::regT1);
409
410     // Move the stack pointer down to accommodate locals
411     addPtr(TrustedImm32(m_graph.stackPointerOffset() * sizeof(Register)), GPRInfo::callFrameRegister, stackPointerRegister);
412     checkStackPointerAlignment();
413
414     compileSetupRegistersForEntry();
415     compileEntryExecutionFlag();
416
417     // === Function body code generation ===
418     m_speculative = std::make_unique<SpeculativeJIT>(*this);
419     compileBody();
420     setEndOfMainPath();
421
422     // === Function footer code generation ===
423     //
424     // Generate code to perform the stack overflow handling (if the stack check in
425     // the function header fails), and generate the entry point with arity check.
426     //
427     // Generate the stack overflow handling; if the stack check in the function head fails,
428     // we need to call out to a helper function to throw the StackOverflowError.
429     stackOverflow.link(this);
430
431     emitStoreCodeOrigin(CodeOrigin(0));
432
433     if (maxFrameExtentForSlowPathCall)
434         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
435
436     m_speculative->callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
437     
438     // The fast entry point into a function does not check the correct number of arguments
439     // have been passed to the call (we only use the fast entry point where we can statically
440     // determine the correct number of arguments have been passed, or have already checked).
441     // In cases where an arity check is necessary, we enter here.
442     // FIXME: change this from a cti call to a DFG style operation (normal C calling conventions).
443     m_arityCheck = label();
444     compileEntry();
445
446     load32(AssemblyHelpers::payloadFor((VirtualRegister)CallFrameSlot::argumentCount), GPRInfo::regT1);
447     branch32(AboveOrEqual, GPRInfo::regT1, TrustedImm32(m_codeBlock->numParameters())).linkTo(fromArityCheck, this);
448     emitStoreCodeOrigin(CodeOrigin(0));
449     if (maxFrameExtentForSlowPathCall)
450         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
451     m_speculative->callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck, GPRInfo::regT0);
452     if (maxFrameExtentForSlowPathCall)
453         addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
454     branchTest32(Zero, GPRInfo::returnValueGPR).linkTo(fromArityCheck, this);
455     emitStoreCodeOrigin(CodeOrigin(0));
456     move(GPRInfo::returnValueGPR, GPRInfo::argumentGPR0);
457     m_callArityFixup = call();
458     jump(fromArityCheck);
459     
460     // Generate slow path code.
461     m_speculative->runSlowPathGenerators(m_pcToCodeOriginMapBuilder);
462     m_pcToCodeOriginMapBuilder.appendItem(label(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
463     
464     compileExceptionHandlers();
465     linkOSRExits();
466     
467     // Create OSR entry trampolines if necessary.
468     m_speculative->createOSREntries();
469     setEndOfCode();
470
471     // === Link ===
472     auto linkBuffer = std::make_unique<LinkBuffer>(*m_vm, *this, m_codeBlock, JITCompilationCanFail);
473     if (linkBuffer->didFailToAllocate()) {
474         m_graph.m_plan.finalizer = std::make_unique<FailedFinalizer>(m_graph.m_plan);
475         return;
476     }
477     link(*linkBuffer);
478     m_speculative->linkOSREntries(*linkBuffer);
479     
480     m_jitCode->shrinkToFit();
481     codeBlock()->shrinkToFit(CodeBlock::LateShrink);
482     
483     linkBuffer->link(m_callArityFixup, FunctionPtr((m_vm->getCTIStub(arityFixupGenerator)).code().executableAddress()));
484     
485     disassemble(*linkBuffer);
486
487     MacroAssemblerCodePtr withArityCheck = linkBuffer->locationOf(m_arityCheck);
488
489     m_graph.m_plan.finalizer = std::make_unique<JITFinalizer>(
490         m_graph.m_plan, WTFMove(m_jitCode), WTFMove(linkBuffer), withArityCheck);
491 }
492
493 void JITCompiler::disassemble(LinkBuffer& linkBuffer)
494 {
495     if (shouldDumpDisassembly()) {
496         m_disassembler->dump(linkBuffer);
497         linkBuffer.didAlreadyDisassemble();
498     }
499     
500     if (m_graph.m_plan.compilation)
501         m_disassembler->reportToProfiler(m_graph.m_plan.compilation.get(), linkBuffer);
502 }
503
504 #if USE(JSVALUE32_64)
505 void* JITCompiler::addressOfDoubleConstant(Node* node)
506 {
507     double value = node->asNumber();
508     int64_t valueBits = bitwise_cast<int64_t>(value);
509     auto it = m_graph.m_doubleConstantsMap.find(valueBits);
510     if (it != m_graph.m_doubleConstantsMap.end())
511         return it->second;
512
513     if (!m_graph.m_doubleConstants)
514         m_graph.m_doubleConstants = std::make_unique<Bag<double>>();
515
516     double* addressInConstantPool = m_graph.m_doubleConstants->add();
517     *addressInConstantPool = value;
518     m_graph.m_doubleConstantsMap[valueBits] = addressInConstantPool;
519     return addressInConstantPool;
520 }
521 #endif
522
523 void JITCompiler::noticeOSREntry(BasicBlock& basicBlock, JITCompiler::Label blockHead, LinkBuffer& linkBuffer)
524 {
525     // OSR entry is not allowed into blocks deemed unreachable by control flow analysis.
526     if (!basicBlock.intersectionOfCFAHasVisited)
527         return;
528         
529     OSREntryData* entry = m_jitCode->appendOSREntryData(basicBlock.bytecodeBegin, linkBuffer.offsetOf(blockHead));
530     
531     entry->m_expectedValues = basicBlock.intersectionOfPastValuesAtHead;
532         
533     // Fix the expected values: in our protocol, a dead variable will have an expected
534     // value of (None, []). But the old JIT may stash some values there. So we really
535     // need (Top, TOP).
536     for (size_t argument = 0; argument < basicBlock.variablesAtHead.numberOfArguments(); ++argument) {
537         Node* node = basicBlock.variablesAtHead.argument(argument);
538         if (!node || !node->shouldGenerate())
539             entry->m_expectedValues.argument(argument).makeHeapTop();
540     }
541     for (size_t local = 0; local < basicBlock.variablesAtHead.numberOfLocals(); ++local) {
542         Node* node = basicBlock.variablesAtHead.local(local);
543         if (!node || !node->shouldGenerate())
544             entry->m_expectedValues.local(local).makeHeapTop();
545         else {
546             VariableAccessData* variable = node->variableAccessData();
547             entry->m_machineStackUsed.set(variable->machineLocal().toLocal());
548                 
549             switch (variable->flushFormat()) {
550             case FlushedDouble:
551                 entry->m_localsForcedDouble.set(local);
552                 break;
553             case FlushedInt52:
554                 entry->m_localsForcedAnyInt.set(local);
555                 break;
556             default:
557                 break;
558             }
559             
560             if (variable->local() != variable->machineLocal()) {
561                 entry->m_reshufflings.append(
562                     OSREntryReshuffling(
563                         variable->local().offset(), variable->machineLocal().offset()));
564             }
565         }
566     }
567         
568     entry->m_reshufflings.shrinkToFit();
569 }
570
571 void JITCompiler::appendExceptionHandlingOSRExit(ExitKind kind, unsigned eventStreamIndex, CodeOrigin opCatchOrigin, HandlerInfo* exceptionHandler, CallSiteIndex callSite, MacroAssembler::JumpList jumpsToFail)
572 {
573     OSRExit exit(kind, JSValueRegs(), graph().methodOfGettingAValueProfileFor(nullptr), m_speculative.get(), eventStreamIndex);
574     exit.m_codeOrigin = opCatchOrigin;
575     exit.m_exceptionHandlerCallSiteIndex = callSite;
576     OSRExitCompilationInfo& exitInfo = appendExitInfo(jumpsToFail);
577     jitCode()->appendOSRExit(exit);
578     m_exceptionHandlerOSRExitCallSites.append(ExceptionHandlingOSRExitInfo { exitInfo, *exceptionHandler, callSite });
579 }
580
581 void JITCompiler::exceptionCheck()
582 {
583     // It's important that we use origin.forExit here. Consider if we hoist string
584     // addition outside a loop, and that we exit at the point of that concatenation
585     // from an out of memory exception.
586     // If the original loop had a try/catch around string concatenation, if we "catch"
587     // that exception inside the loop, then the loops induction variable will be undefined 
588     // in the OSR exit value recovery. It's more defensible for the string concatenation, 
589     // then, to not be caught by the for loops' try/catch.
590     // Here is the program I'm speaking about:
591     //
592     // >>>> lets presume "c = a + b" gets hoisted here.
593     // for (var i = 0; i < length; i++) {
594     //     try {
595     //         c = a + b
596     //     } catch(e) { 
597     //         If we threw an out of memory error, and we cought the exception
598     //         right here, then "i" would almost certainly be undefined, which
599     //         would make no sense.
600     //         ... 
601     //     }
602     // }
603     CodeOrigin opCatchOrigin;
604     HandlerInfo* exceptionHandler;
605     bool willCatchException = m_graph.willCatchExceptionInMachineFrame(m_speculative->m_currentNode->origin.forExit, opCatchOrigin, exceptionHandler); 
606     if (willCatchException) {
607         unsigned streamIndex = m_speculative->m_outOfLineStreamIndex != UINT_MAX ? m_speculative->m_outOfLineStreamIndex : m_speculative->m_stream->size();
608         MacroAssembler::Jump hadException = emitNonPatchableExceptionCheck();
609         // We assume here that this is called after callOpeartion()/appendCall() is called.
610         appendExceptionHandlingOSRExit(ExceptionCheck, streamIndex, opCatchOrigin, exceptionHandler, m_jitCode->common.lastCallSite(), hadException);
611     } else
612         m_exceptionChecks.append(emitExceptionCheck());
613 }
614
615 CallSiteIndex JITCompiler::recordCallSiteAndGenerateExceptionHandlingOSRExitIfNeeded(const CodeOrigin& callSiteCodeOrigin, unsigned eventStreamIndex)
616 {
617     CodeOrigin opCatchOrigin;
618     HandlerInfo* exceptionHandler;
619     bool willCatchException = m_graph.willCatchExceptionInMachineFrame(callSiteCodeOrigin, opCatchOrigin, exceptionHandler);
620     CallSiteIndex callSite = addCallSite(callSiteCodeOrigin);
621     if (willCatchException)
622         appendExceptionHandlingOSRExit(GenericUnwind, eventStreamIndex, opCatchOrigin, exceptionHandler, callSite);
623     return callSite;
624 }
625
626 void JITCompiler::setEndOfMainPath()
627 {
628     m_pcToCodeOriginMapBuilder.appendItem(labelIgnoringWatchpoints(), m_speculative->m_origin.semantic);
629     if (LIKELY(!m_disassembler))
630         return;
631     m_disassembler->setEndOfMainPath(labelIgnoringWatchpoints());
632 }
633
634 void JITCompiler::setEndOfCode()
635 {
636     m_pcToCodeOriginMapBuilder.appendItem(labelIgnoringWatchpoints(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
637     if (LIKELY(!m_disassembler))
638         return;
639     m_disassembler->setEndOfCode(labelIgnoringWatchpoints());
640 }
641
642 } } // namespace JSC::DFG
643
644 #endif // ENABLE(DFG_JIT)