fourthTier: Landing the initial FTL logic in a single commit to avoid spurious
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.h
1 /*
2  * Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #ifndef CodeBlock_h
31 #define CodeBlock_h
32
33 #include "ArrayProfile.h"
34 #include "ByValInfo.h"
35 #include "BytecodeConventions.h"
36 #include "CallLinkInfo.h"
37 #include "CallReturnOffsetToBytecodeOffset.h"
38 #include "CodeBlockHash.h"
39 #include "CodeOrigin.h"
40 #include "CodeType.h"
41 #include "CompactJITCodeMap.h"
42 #include "DFGCodeBlocks.h"
43 #include "DFGCommon.h"
44 #include "DFGCommonData.h"
45 #include "DFGExitProfile.h"
46 #include "DFGMinifiedGraph.h"
47 #include "DFGOSREntry.h"
48 #include "DFGOSRExit.h"
49 #include "DFGVariableEventStream.h"
50 #include "EvalCodeCache.h"
51 #include "ExecutionCounter.h"
52 #include "ExpressionRangeInfo.h"
53 #include "HandlerInfo.h"
54 #include "ObjectAllocationProfile.h"
55 #include "Options.h"
56 #include "Instruction.h"
57 #include "JITCode.h"
58 #include "JITWriteBarrier.h"
59 #include "JSGlobalObject.h"
60 #include "JumpReplacementWatchpoint.h"
61 #include "JumpTable.h"
62 #include "LLIntCallLinkInfo.h"
63 #include "LazyOperandValueProfile.h"
64 #include "LineInfo.h"
65 #include "ProfilerCompilation.h"
66 #include "RegExpObject.h"
67 #include "ResolveOperation.h"
68 #include "StructureStubInfo.h"
69 #include "UnconditionalFinalizer.h"
70 #include "ValueProfile.h"
71 #include "Watchpoint.h"
72 #include <wtf/RefCountedArray.h>
73 #include <wtf/FastAllocBase.h>
74 #include <wtf/PassOwnPtr.h>
75 #include <wtf/Platform.h>
76 #include <wtf/RefPtr.h>
77 #include <wtf/SegmentedVector.h>
78 #include <wtf/Vector.h>
79 #include <wtf/text/WTFString.h>
80
81 namespace JSC {
82
83     class DFGCodeBlocks;
84     class ExecState;
85     class LLIntOffsetsExtractor;
86     class RepatchBuffer;
87
88     inline int unmodifiedArgumentsRegister(int argumentsRegister) { return argumentsRegister - 1; }
89
90     static ALWAYS_INLINE int missingThisObjectMarker() { return std::numeric_limits<int>::max(); }
91
92     class CodeBlock : public UnconditionalFinalizer, public WeakReferenceHarvester {
93         WTF_MAKE_FAST_ALLOCATED;
94         friend class JIT;
95         friend class LLIntOffsetsExtractor;
96     public:
97         enum CopyParsedBlockTag { CopyParsedBlock };
98     protected:
99         CodeBlock(CopyParsedBlockTag, CodeBlock& other);
100
101         CodeBlock(ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSGlobalObject*, unsigned baseScopeDepth, PassRefPtr<SourceProvider>, unsigned sourceOffset, unsigned firstLineColumnOffset, PassOwnPtr<CodeBlock> alternative);
102
103         WriteBarrier<JSGlobalObject> m_globalObject;
104         Heap* m_heap;
105
106     public:
107         JS_EXPORT_PRIVATE virtual ~CodeBlock();
108
109         UnlinkedCodeBlock* unlinkedCodeBlock() const { return m_unlinkedCode.get(); }
110
111         String inferredName() const;
112         CodeBlockHash hash() const;
113         String sourceCodeForTools() const; // Not quite the actual source we parsed; this will do things like prefix the source for a function with a reified signature.
114         String sourceCodeOnOneLine() const; // As sourceCodeForTools(), but replaces all whitespace runs with a single space.
115         void dumpAssumingJITType(PrintStream&, JITCode::JITType) const;
116         void dump(PrintStream&) const;
117
118         int numParameters() const { return m_numParameters; }
119         void setNumParameters(int newValue);
120
121         int* addressOfNumParameters() { return &m_numParameters; }
122         static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
123
124         CodeBlock* alternative() { return m_alternative.get(); }
125         PassOwnPtr<CodeBlock> releaseAlternative() { return m_alternative.release(); }
126         void setAlternative(PassOwnPtr<CodeBlock> alternative) { m_alternative = alternative; }
127
128         CodeSpecializationKind specializationKind() const
129         {
130             return specializationFromIsConstruct(m_isConstructor);
131         }
132
133 #if ENABLE(JIT)
134         CodeBlock* baselineVersion()
135         {
136             CodeBlock* result = replacement();
137             if (!result)
138                 return 0; // This can happen if we're in the process of creating the baseline version.
139             while (result->alternative())
140                 result = result->alternative();
141             ASSERT(result);
142             ASSERT(JITCode::isBaselineCode(result->getJITType()));
143             return result;
144         }
145 #else
146         CodeBlock* baselineVersion()
147         {
148             return this;
149         }
150 #endif
151
152         void visitAggregate(SlotVisitor&);
153
154         static void dumpStatistics();
155
156         void dumpBytecode(PrintStream& = WTF::dataFile());
157         void dumpBytecode(PrintStream&, unsigned bytecodeOffset);
158         void printStructures(PrintStream&, const Instruction*);
159         void printStructure(PrintStream&, const char* name, const Instruction*, int operand);
160
161         bool isStrictMode() const { return m_isStrictMode; }
162
163         inline bool isKnownNotImmediate(int index)
164         {
165             if (index == m_thisRegister && !m_isStrictMode)
166                 return true;
167
168             if (isConstantRegisterIndex(index))
169                 return getConstant(index).isCell();
170
171             return false;
172         }
173
174         ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
175         {
176             return index >= m_numVars;
177         }
178
179         HandlerInfo* handlerForBytecodeOffset(unsigned bytecodeOffset);
180         unsigned lineNumberForBytecodeOffset(unsigned bytecodeOffset);
181         unsigned columnNumberForBytecodeOffset(unsigned bytecodeOffset);
182         void expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot,
183                                               int& startOffset, int& endOffset, unsigned& line, unsigned& column);
184
185 #if ENABLE(JIT)
186
187         StructureStubInfo& getStubInfo(ReturnAddressPtr returnAddress)
188         {
189             return *(binarySearch<StructureStubInfo, void*>(m_structureStubInfos, m_structureStubInfos.size(), returnAddress.value(), getStructureStubInfoReturnLocation));
190         }
191
192         StructureStubInfo& getStubInfo(unsigned bytecodeIndex)
193         {
194             return *(binarySearch<StructureStubInfo, unsigned>(m_structureStubInfos, m_structureStubInfos.size(), bytecodeIndex, getStructureStubInfoBytecodeIndex));
195         }
196
197         void resetStub(StructureStubInfo&);
198
199         ByValInfo& getByValInfo(unsigned bytecodeIndex)
200         {
201             return *(binarySearch<ByValInfo, unsigned>(m_byValInfos, m_byValInfos.size(), bytecodeIndex, getByValInfoBytecodeIndex));
202         }
203
204         CallLinkInfo& getCallLinkInfo(ReturnAddressPtr returnAddress)
205         {
206             return *(binarySearch<CallLinkInfo, void*>(m_callLinkInfos, m_callLinkInfos.size(), returnAddress.value(), getCallLinkInfoReturnLocation));
207         }
208
209         CallLinkInfo& getCallLinkInfo(unsigned bytecodeIndex)
210         {
211             ASSERT(JITCode::isBaselineCode(getJITType()));
212             return *(binarySearch<CallLinkInfo, unsigned>(m_callLinkInfos, m_callLinkInfos.size(), bytecodeIndex, getCallLinkInfoBytecodeIndex));
213         }
214 #endif // ENABLE(JIT)
215
216 #if ENABLE(LLINT)
217         Instruction* adjustPCIfAtCallSite(Instruction*);
218 #endif
219         unsigned bytecodeOffset(ExecState*, ReturnAddressPtr);
220
221 #if ENABLE(JIT)
222         unsigned bytecodeOffsetForCallAtIndex(unsigned index)
223         {
224             if (!m_rareData)
225                 return 1;
226             Vector<CallReturnOffsetToBytecodeOffset, 0, UnsafeVectorOverflow>& callIndices = m_rareData->m_callReturnIndexVector;
227             if (!callIndices.size())
228                 return 1;
229             // FIXME: Fix places in DFG that call out to C that don't set the CodeOrigin. https://bugs.webkit.org/show_bug.cgi?id=118315
230             ASSERT(index < m_rareData->m_callReturnIndexVector.size());
231             if (index >= m_rareData->m_callReturnIndexVector.size())
232                 return 1;
233             return m_rareData->m_callReturnIndexVector[index].bytecodeOffset;
234         }
235
236         void unlinkCalls();
237
238         bool hasIncomingCalls() { return m_incomingCalls.begin() != m_incomingCalls.end(); }
239
240         void linkIncomingCall(CallLinkInfo* incoming)
241         {
242             m_incomingCalls.push(incoming);
243         }
244
245         bool isIncomingCallAlreadyLinked(CallLinkInfo* incoming)
246         {
247             return m_incomingCalls.isOnList(incoming);
248         }
249 #endif // ENABLE(JIT)
250
251 #if ENABLE(LLINT)
252         void linkIncomingCall(LLIntCallLinkInfo* incoming)
253         {
254             m_incomingLLIntCalls.push(incoming);
255         }
256 #endif // ENABLE(LLINT)
257
258         void unlinkIncomingCalls();
259
260 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
261         void setJITCodeMap(PassOwnPtr<CompactJITCodeMap> jitCodeMap)
262         {
263             m_jitCodeMap = jitCodeMap;
264         }
265         CompactJITCodeMap* jitCodeMap()
266         {
267             return m_jitCodeMap.get();
268         }
269 #endif
270         
271         unsigned bytecodeOffset(Instruction* returnAddress)
272         {
273             RELEASE_ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
274             return static_cast<Instruction*>(returnAddress) - instructions().begin();
275         }
276
277         bool isNumericCompareFunction() { return m_unlinkedCode->isNumericCompareFunction(); }
278
279         unsigned numberOfInstructions() const { return m_instructions.size(); }
280         RefCountedArray<Instruction>& instructions() { return m_instructions; }
281         const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
282
283         size_t predictedMachineCodeSize();
284
285         bool usesOpcode(OpcodeID);
286
287         unsigned instructionCount() { return m_instructions.size(); }
288
289         int argumentIndexAfterCapture(size_t argument);
290
291 #if ENABLE(JIT)
292         void setJITCode(PassRefPtr<JITCode> code, MacroAssemblerCodePtr codeWithArityCheck)
293         {
294             m_jitCode = code;
295             m_jitCodeWithArityCheck = codeWithArityCheck;
296 #if ENABLE(DFG_JIT)
297             if (JITCode::isOptimizingJIT(JITCode::jitTypeFor(m_jitCode)))
298                 m_vm->heap.m_dfgCodeBlocks.m_set.add(this);
299 #endif
300         }
301         PassRefPtr<JITCode> getJITCode() { return m_jitCode; }
302         MacroAssemblerCodePtr getJITCodeWithArityCheck() { return m_jitCodeWithArityCheck; }
303         JITCode::JITType getJITType() const { return JITCode::jitTypeFor(m_jitCode); }
304         virtual JSObject* compileOptimized(ExecState*, JSScope*, unsigned bytecodeIndex) = 0;
305         void jettison();
306         enum JITCompilationResult { AlreadyCompiled, CouldNotCompile, CompiledSuccessfully };
307         JITCompilationResult jitCompile(ExecState* exec)
308         {
309             if (getJITType() != JITCode::InterpreterThunk) {
310                 ASSERT(getJITType() == JITCode::BaselineJIT);
311                 return AlreadyCompiled;
312             }
313 #if ENABLE(JIT)
314             if (jitCompileImpl(exec))
315                 return CompiledSuccessfully;
316             return CouldNotCompile;
317 #else
318             UNUSED_PARAM(exec);
319             return CouldNotCompile;
320 #endif
321         }
322         virtual CodeBlock* replacement() = 0;
323
324         virtual DFG::CapabilityLevel canCompileWithDFGInternal() = 0;
325         DFG::CapabilityLevel canCompileWithDFG()
326         {
327             DFG::CapabilityLevel result = canCompileWithDFGInternal();
328             m_canCompileWithDFGState = result;
329             return result;
330         }
331         DFG::CapabilityLevel canCompileWithDFGState() { return m_canCompileWithDFGState; }
332
333         bool hasOptimizedReplacement()
334         {
335             ASSERT(JITCode::isBaselineCode(getJITType()));
336             bool result = JITCode::isHigherTier(replacement()->getJITType(), getJITType());
337 #if !ASSERT_DISABLED
338             if (result)
339                 ASSERT(JITCode::isOptimizingJIT(replacement()->getJITType()));
340             else {
341                 ASSERT(JITCode::isBaselineCode(replacement()->getJITType()));
342                 ASSERT(replacement() == this);
343             }
344 #endif
345             return result;
346         }
347 #else
348         JITCode::JITType getJITType() const { return JITCode::BaselineJIT; }
349 #endif
350
351         ScriptExecutable* ownerExecutable() const { return m_ownerExecutable.get(); }
352
353         void setVM(VM* vm) { m_vm = vm; }
354         VM* vm() { return m_vm; }
355
356         void setThisRegister(int thisRegister) { m_thisRegister = thisRegister; }
357         int thisRegister() const { return m_thisRegister; }
358
359         bool needsFullScopeChain() const { return m_unlinkedCode->needsFullScopeChain(); }
360         bool usesEval() const { return m_unlinkedCode->usesEval(); }
361
362         void setArgumentsRegister(int argumentsRegister)
363         {
364             ASSERT(argumentsRegister != -1);
365             m_argumentsRegister = argumentsRegister;
366             ASSERT(usesArguments());
367         }
368         int argumentsRegister() const
369         {
370             ASSERT(usesArguments());
371             return m_argumentsRegister;
372         }
373         int uncheckedArgumentsRegister()
374         {
375             if (!usesArguments())
376                 return InvalidVirtualRegister;
377             return argumentsRegister();
378         }
379         void setActivationRegister(int activationRegister)
380         {
381             m_activationRegister = activationRegister;
382         }
383         int activationRegister() const
384         {
385             ASSERT(needsFullScopeChain());
386             return m_activationRegister;
387         }
388         int uncheckedActivationRegister()
389         {
390             if (!needsFullScopeChain())
391                 return InvalidVirtualRegister;
392             return activationRegister();
393         }
394         bool usesArguments() const { return m_argumentsRegister != -1; }
395
396         bool needsActivation() const
397         {
398             return needsFullScopeChain() && codeType() != GlobalCode;
399         }
400
401         bool isCaptured(int operand, InlineCallFrame* inlineCallFrame = 0) const
402         {
403             if (operandIsArgument(operand))
404                 return operandToArgument(operand) && usesArguments();
405
406             if (inlineCallFrame)
407                 return inlineCallFrame->capturedVars.get(operand);
408
409             // The activation object isn't in the captured region, but it's "captured"
410             // in the sense that stores to its location can be observed indirectly.
411             if (needsActivation() && operand == activationRegister())
412                 return true;
413
414             // Ditto for the arguments object.
415             if (usesArguments() && operand == argumentsRegister())
416                 return true;
417
418             // Ditto for the arguments object.
419             if (usesArguments() && operand == unmodifiedArgumentsRegister(argumentsRegister()))
420                 return true;
421
422             // We're in global code so there are no locals to capture
423             if (!symbolTable())
424                 return false;
425
426             return operand >= symbolTable()->captureStart()
427             && operand < symbolTable()->captureEnd();
428         }
429
430         CodeType codeType() const { return m_unlinkedCode->codeType(); }
431
432         SourceProvider* source() const { return m_source.get(); }
433         unsigned sourceOffset() const { return m_sourceOffset; }
434         unsigned firstLineColumnOffset() const { return m_firstLineColumnOffset; }
435
436         size_t numberOfJumpTargets() const { return m_unlinkedCode->numberOfJumpTargets(); }
437         unsigned jumpTarget(int index) const { return m_unlinkedCode->jumpTarget(index); }
438
439         void createActivation(CallFrame*);
440
441         void clearEvalCache();
442
443         String nameForRegister(int registerNumber);
444
445 #if ENABLE(JIT)
446         void setNumberOfStructureStubInfos(size_t size) { m_structureStubInfos.grow(size); }
447         size_t numberOfStructureStubInfos() const { return m_structureStubInfos.size(); }
448         StructureStubInfo& structureStubInfo(int index) { return m_structureStubInfos[index]; }
449
450         void setNumberOfByValInfos(size_t size) { m_byValInfos.grow(size); }
451         size_t numberOfByValInfos() const { return m_byValInfos.size(); }
452         ByValInfo& byValInfo(size_t index) { return m_byValInfos[index]; }
453
454         void setNumberOfCallLinkInfos(size_t size) { m_callLinkInfos.grow(size); }
455         size_t numberOfCallLinkInfos() const { return m_callLinkInfos.size(); }
456         CallLinkInfo& callLinkInfo(int index) { return m_callLinkInfos[index]; }
457 #endif
458
459 #if ENABLE(VALUE_PROFILER)
460         unsigned numberOfArgumentValueProfiles()
461         {
462             ASSERT(m_numParameters >= 0);
463             ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
464             return m_argumentValueProfiles.size();
465         }
466         ValueProfile* valueProfileForArgument(unsigned argumentIndex)
467         {
468             ValueProfile* result = &m_argumentValueProfiles[argumentIndex];
469             ASSERT(result->m_bytecodeOffset == -1);
470             return result;
471         }
472
473         unsigned numberOfValueProfiles() { return m_valueProfiles.size(); }
474         ValueProfile* valueProfile(int index) { return &m_valueProfiles[index]; }
475         ValueProfile* valueProfileForBytecodeOffset(int bytecodeOffset)
476         {
477             ValueProfile* result = binarySearch<ValueProfile, int>(
478                                                                    m_valueProfiles, m_valueProfiles.size(), bytecodeOffset,
479                                                                    getValueProfileBytecodeOffset<ValueProfile>);
480             ASSERT(result->m_bytecodeOffset != -1);
481             ASSERT(instructions()[bytecodeOffset + opcodeLength(
482                                                                 m_vm->interpreter->getOpcodeID(
483                                                                                                instructions()[
484                                                                                                               bytecodeOffset].u.opcode)) - 1].u.profile == result);
485             return result;
486         }
487         SpeculatedType valueProfilePredictionForBytecodeOffset(int bytecodeOffset)
488         {
489             return valueProfileForBytecodeOffset(bytecodeOffset)->computeUpdatedPrediction();
490         }
491
492         unsigned totalNumberOfValueProfiles()
493         {
494             return numberOfArgumentValueProfiles() + numberOfValueProfiles();
495         }
496         ValueProfile* getFromAllValueProfiles(unsigned index)
497         {
498             if (index < numberOfArgumentValueProfiles())
499                 return valueProfileForArgument(index);
500             return valueProfile(index - numberOfArgumentValueProfiles());
501         }
502
503         RareCaseProfile* addRareCaseProfile(int bytecodeOffset)
504         {
505             m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
506             return &m_rareCaseProfiles.last();
507         }
508         unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
509         RareCaseProfile* rareCaseProfile(int index) { return &m_rareCaseProfiles[index]; }
510         RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset)
511         {
512             return tryBinarySearch<RareCaseProfile, int>(
513                                                          m_rareCaseProfiles, m_rareCaseProfiles.size(), bytecodeOffset,
514                                                          getRareCaseProfileBytecodeOffset);
515         }
516
517         bool likelyToTakeSlowCase(int bytecodeOffset)
518         {
519             if (!numberOfRareCaseProfiles())
520                 return false;
521             unsigned value = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
522             return value >= Options::likelyToTakeSlowCaseMinimumCount();
523         }
524
525         bool couldTakeSlowCase(int bytecodeOffset)
526         {
527             if (!numberOfRareCaseProfiles())
528                 return false;
529             unsigned value = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
530             return value >= Options::couldTakeSlowCaseMinimumCount();
531         }
532
533         RareCaseProfile* addSpecialFastCaseProfile(int bytecodeOffset)
534         {
535             m_specialFastCaseProfiles.append(RareCaseProfile(bytecodeOffset));
536             return &m_specialFastCaseProfiles.last();
537         }
538         unsigned numberOfSpecialFastCaseProfiles() { return m_specialFastCaseProfiles.size(); }
539         RareCaseProfile* specialFastCaseProfile(int index) { return &m_specialFastCaseProfiles[index]; }
540         RareCaseProfile* specialFastCaseProfileForBytecodeOffset(int bytecodeOffset)
541         {
542             return tryBinarySearch<RareCaseProfile, int>(
543                                                          m_specialFastCaseProfiles, m_specialFastCaseProfiles.size(), bytecodeOffset,
544                                                          getRareCaseProfileBytecodeOffset);
545         }
546
547         bool likelyToTakeSpecialFastCase(int bytecodeOffset)
548         {
549             if (!numberOfRareCaseProfiles())
550                 return false;
551             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
552             return specialFastCaseCount >= Options::likelyToTakeSlowCaseMinimumCount();
553         }
554
555         bool couldTakeSpecialFastCase(int bytecodeOffset)
556         {
557             if (!numberOfRareCaseProfiles())
558                 return false;
559             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
560             return specialFastCaseCount >= Options::couldTakeSlowCaseMinimumCount();
561         }
562
563         bool likelyToTakeDeepestSlowCase(int bytecodeOffset)
564         {
565             if (!numberOfRareCaseProfiles())
566                 return false;
567             unsigned slowCaseCount = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
568             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
569             unsigned value = slowCaseCount - specialFastCaseCount;
570             return value >= Options::likelyToTakeSlowCaseMinimumCount();
571         }
572
573         bool likelyToTakeAnySlowCase(int bytecodeOffset)
574         {
575             if (!numberOfRareCaseProfiles())
576                 return false;
577             unsigned slowCaseCount = rareCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
578             unsigned specialFastCaseCount = specialFastCaseProfileForBytecodeOffset(bytecodeOffset)->m_counter;
579             unsigned value = slowCaseCount + specialFastCaseCount;
580             return value >= Options::likelyToTakeSlowCaseMinimumCount();
581         }
582
583         unsigned numberOfArrayProfiles() const { return m_arrayProfiles.size(); }
584         const ArrayProfileVector& arrayProfiles() { return m_arrayProfiles; }
585         ArrayProfile* addArrayProfile(unsigned bytecodeOffset)
586         {
587             m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
588             return &m_arrayProfiles.last();
589         }
590         ArrayProfile* getArrayProfile(unsigned bytecodeOffset);
591         ArrayProfile* getOrAddArrayProfile(unsigned bytecodeOffset);
592 #endif
593
594         // Exception handling support
595
596         size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
597         void allocateHandlers(const Vector<UnlinkedHandlerInfo>& unlinkedHandlers)
598         {
599             size_t count = unlinkedHandlers.size();
600             if (!count)
601                 return;
602             createRareDataIfNecessary();
603             m_rareData->m_exceptionHandlers.resize(count);
604             for (size_t i = 0; i < count; ++i) {
605                 m_rareData->m_exceptionHandlers[i].start = unlinkedHandlers[i].start;
606                 m_rareData->m_exceptionHandlers[i].end = unlinkedHandlers[i].end;
607                 m_rareData->m_exceptionHandlers[i].target = unlinkedHandlers[i].target;
608                 m_rareData->m_exceptionHandlers[i].scopeDepth = unlinkedHandlers[i].scopeDepth;
609             }
610
611         }
612         HandlerInfo& exceptionHandler(int index) { RELEASE_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
613
614         bool hasExpressionInfo() { return m_unlinkedCode->hasExpressionInfo(); }
615
616 #if ENABLE(JIT)
617         Vector<CallReturnOffsetToBytecodeOffset, 0, UnsafeVectorOverflow>& callReturnIndexVector()
618         {
619             createRareDataIfNecessary();
620             return m_rareData->m_callReturnIndexVector;
621         }
622 #endif
623
624 #if ENABLE(DFG_JIT)
625         SegmentedVector<InlineCallFrame, 4>& inlineCallFrames()
626         {
627             createRareDataIfNecessary();
628             return m_rareData->m_inlineCallFrames;
629         }
630
631         Vector<CodeOriginAtCallReturnOffset, 0, UnsafeVectorOverflow>& codeOrigins()
632         {
633             createRareDataIfNecessary();
634             return m_rareData->m_codeOrigins;
635         }
636
637         // Having code origins implies that there has been some inlining.
638         bool hasCodeOrigins()
639         {
640             return m_rareData && !!m_rareData->m_codeOrigins.size();
641         }
642
643         bool codeOriginForReturn(ReturnAddressPtr, CodeOrigin&);
644
645         bool canGetCodeOrigin(unsigned index)
646         {
647             if (!m_rareData)
648                 return false;
649             return m_rareData->m_codeOrigins.size() > index;
650         }
651
652         CodeOrigin codeOrigin(unsigned index)
653         {
654             RELEASE_ASSERT(m_rareData);
655             return m_rareData->m_codeOrigins[index].codeOrigin;
656         }
657
658         bool addFrequentExitSite(const DFG::FrequentExitSite& site)
659         {
660             ASSERT(JITCode::isBaselineCode(getJITType()));
661             return m_exitProfile.add(site);
662         }
663
664         bool hasExitSite(const DFG::FrequentExitSite& site) const { return m_exitProfile.hasExitSite(site); }
665
666         DFG::ExitProfile& exitProfile() { return m_exitProfile; }
667
668         CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
669         {
670             return m_lazyOperandValueProfiles;
671         }
672 #endif
673
674         // Constant Pool
675
676         size_t numberOfIdentifiers() const { return m_identifiers.size(); }
677         void addIdentifier(const Identifier& i) { return m_identifiers.append(i); }
678         Identifier& identifier(int index) { return m_identifiers[index]; }
679
680         size_t numberOfConstantRegisters() const { return m_constantRegisters.size(); }
681         unsigned addConstant(JSValue v)
682         {
683             unsigned result = m_constantRegisters.size();
684             m_constantRegisters.append(WriteBarrier<Unknown>());
685             m_constantRegisters.last().set(m_globalObject->vm(), m_ownerExecutable.get(), v);
686             return result;
687         }
688
689
690         unsigned addOrFindConstant(JSValue);
691         WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
692         ALWAYS_INLINE bool isConstantRegisterIndex(int index) const { return index >= FirstConstantRegisterIndex; }
693         ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
694
695         FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
696         int numberOfFunctionDecls() { return m_functionDecls.size(); }
697         FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
698
699         RegExp* regexp(int index) const { return m_unlinkedCode->regexp(index); }
700
701         unsigned numberOfConstantBuffers() const
702         {
703             if (!m_rareData)
704                 return 0;
705             return m_rareData->m_constantBuffers.size();
706         }
707         unsigned addConstantBuffer(const Vector<JSValue>& buffer)
708         {
709             createRareDataIfNecessary();
710             unsigned size = m_rareData->m_constantBuffers.size();
711             m_rareData->m_constantBuffers.append(buffer);
712             return size;
713         }
714
715         Vector<JSValue>& constantBufferAsVector(unsigned index)
716         {
717             ASSERT(m_rareData);
718             return m_rareData->m_constantBuffers[index];
719         }
720         JSValue* constantBuffer(unsigned index)
721         {
722             return constantBufferAsVector(index).data();
723         }
724
725         JSGlobalObject* globalObject() { return m_globalObject.get(); }
726
727         JSGlobalObject* globalObjectFor(CodeOrigin);
728
729         // Jump Tables
730
731         size_t numberOfImmediateSwitchJumpTables() const { return m_rareData ? m_rareData->m_immediateSwitchJumpTables.size() : 0; }
732         SimpleJumpTable& addImmediateSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_immediateSwitchJumpTables.append(SimpleJumpTable()); return m_rareData->m_immediateSwitchJumpTables.last(); }
733         SimpleJumpTable& immediateSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_immediateSwitchJumpTables[tableIndex]; }
734
735         size_t numberOfCharacterSwitchJumpTables() const { return m_rareData ? m_rareData->m_characterSwitchJumpTables.size() : 0; }
736         SimpleJumpTable& addCharacterSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_characterSwitchJumpTables.append(SimpleJumpTable()); return m_rareData->m_characterSwitchJumpTables.last(); }
737         SimpleJumpTable& characterSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_characterSwitchJumpTables[tableIndex]; }
738
739         size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
740         StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
741         StringJumpTable& stringSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
742
743
744         SharedSymbolTable* symbolTable() const { return m_unlinkedCode->symbolTable(); }
745
746         EvalCodeCache& evalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_evalCodeCache; }
747
748         enum ShrinkMode {
749             // Shrink prior to generating machine code that may point directly into vectors.
750             EarlyShrink,
751
752             // Shrink after generating machine code, and after possibly creating new vectors
753             // and appending to others. At this time it is not safe to shrink certain vectors
754             // because we would have generated machine code that references them directly.
755             LateShrink
756         };
757         void shrinkToFit(ShrinkMode);
758
759         void copyPostParseDataFrom(CodeBlock* alternative);
760         void copyPostParseDataFromAlternative();
761
762         // Functions for controlling when JITting kicks in, in a mixed mode
763         // execution world.
764
765         bool checkIfJITThresholdReached()
766         {
767             return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
768         }
769
770         void dontJITAnytimeSoon()
771         {
772             m_llintExecuteCounter.deferIndefinitely();
773         }
774
775         void jitAfterWarmUp()
776         {
777             m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITAfterWarmUp(), this);
778         }
779
780         void jitSoon()
781         {
782             m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITSoon(), this);
783         }
784
785         const ExecutionCounter& llintExecuteCounter() const
786         {
787             return m_llintExecuteCounter;
788         }
789
790         // Functions for controlling when tiered compilation kicks in. This
791         // controls both when the optimizing compiler is invoked and when OSR
792         // entry happens. Two triggers exist: the loop trigger and the return
793         // trigger. In either case, when an addition to m_jitExecuteCounter
794         // causes it to become non-negative, the optimizing compiler is
795         // invoked. This includes a fast check to see if this CodeBlock has
796         // already been optimized (i.e. replacement() returns a CodeBlock
797         // that was optimized with a higher tier JIT than this one). In the
798         // case of the loop trigger, if the optimized compilation succeeds
799         // (or has already succeeded in the past) then OSR is attempted to
800         // redirect program flow into the optimized code.
801
802         // These functions are called from within the optimization triggers,
803         // and are used as a single point at which we define the heuristics
804         // for how much warm-up is mandated before the next optimization
805         // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
806         // as this is called from the CodeBlock constructor.
807
808         // When we observe a lot of speculation failures, we trigger a
809         // reoptimization. But each time, we increase the optimization trigger
810         // to avoid thrashing.
811         unsigned reoptimizationRetryCounter() const;
812         void countReoptimization();
813
814         int32_t codeTypeThresholdMultiplier() const;
815
816         int32_t counterValueForOptimizeAfterWarmUp();
817         int32_t counterValueForOptimizeAfterLongWarmUp();
818         int32_t counterValueForOptimizeSoon();
819
820         int32_t* addressOfJITExecuteCounter()
821         {
822             return &m_jitExecuteCounter.m_counter;
823         }
824
825         static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(ExecutionCounter, m_counter); }
826         static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(ExecutionCounter, m_activeThreshold); }
827         static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(ExecutionCounter, m_totalCount); }
828
829         const ExecutionCounter& jitExecuteCounter() const { return m_jitExecuteCounter; }
830
831         unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
832
833         // Check if the optimization threshold has been reached, and if not,
834         // adjust the heuristics accordingly. Returns true if the threshold has
835         // been reached.
836         bool checkIfOptimizationThresholdReached();
837
838         // Call this to force the next optimization trigger to fire. This is
839         // rarely wise, since optimization triggers are typically more
840         // expensive than executing baseline code.
841         void optimizeNextInvocation();
842
843         // Call this to prevent optimization from happening again. Note that
844         // optimization will still happen after roughly 2^29 invocations,
845         // so this is really meant to delay that as much as possible. This
846         // is called if optimization failed, and we expect it to fail in
847         // the future as well.
848         void dontOptimizeAnytimeSoon();
849
850         // Call this to reinitialize the counter to its starting state,
851         // forcing a warm-up to happen before the next optimization trigger
852         // fires. This is called in the CodeBlock constructor. It also
853         // makes sense to call this if an OSR exit occurred. Note that
854         // OSR exit code is code generated, so the value of the execute
855         // counter that this corresponds to is also available directly.
856         void optimizeAfterWarmUp();
857
858         // Call this to force an optimization trigger to fire only after
859         // a lot of warm-up.
860         void optimizeAfterLongWarmUp();
861
862         // Call this to cause an optimization trigger to fire soon, but
863         // not necessarily the next one. This makes sense if optimization
864         // succeeds. Successfuly optimization means that all calls are
865         // relinked to the optimized code, so this only affects call
866         // frames that are still executing this CodeBlock. The value here
867         // is tuned to strike a balance between the cost of OSR entry
868         // (which is too high to warrant making every loop back edge to
869         // trigger OSR immediately) and the cost of executing baseline
870         // code (which is high enough that we don't necessarily want to
871         // have a full warm-up). The intuition for calling this instead of
872         // optimizeNextInvocation() is for the case of recursive functions
873         // with loops. Consider that there may be N call frames of some
874         // recursive function, for a reasonably large value of N. The top
875         // one triggers optimization, and then returns, and then all of
876         // the others return. We don't want optimization to be triggered on
877         // each return, as that would be superfluous. It only makes sense
878         // to trigger optimization if one of those functions becomes hot
879         // in the baseline code.
880         void optimizeSoon();
881
882         uint32_t osrExitCounter() const { return m_osrExitCounter; }
883
884         void countOSRExit() { m_osrExitCounter++; }
885
886         uint32_t* addressOfOSRExitCounter() { return &m_osrExitCounter; }
887
888         static ptrdiff_t offsetOfOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_osrExitCounter); }
889
890 #if ENABLE(JIT)
891         uint32_t adjustedExitCountThreshold(uint32_t desiredThreshold);
892         uint32_t exitCountThresholdForReoptimization();
893         uint32_t exitCountThresholdForReoptimizationFromLoop();
894         bool shouldReoptimizeNow();
895         bool shouldReoptimizeFromLoopNow();
896 #endif
897
898 #if ENABLE(VALUE_PROFILER)
899         bool shouldOptimizeNow();
900         void updateAllValueProfilePredictions(OperationInProgress = NoOperation);
901         void updateAllArrayPredictions(OperationInProgress = NoOperation);
902         void updateAllPredictions(OperationInProgress = NoOperation);
903 #else
904         bool shouldOptimizeNow() { return false; }
905         void updateAllValueProfilePredictions(OperationInProgress = NoOperation) { }
906         void updateAllArrayPredictions(OperationInProgress = NoOperation) { }
907         void updateAllPredictions(OperationInProgress = NoOperation) { }
908 #endif
909
910 #if ENABLE(JIT)
911         void reoptimize();
912 #endif
913
914 #if ENABLE(VERBOSE_VALUE_PROFILE)
915         void dumpValueProfiles();
916 #endif
917
918         // FIXME: Make these remaining members private.
919
920         int m_numCalleeRegisters;
921         int m_numVars;
922         bool m_isConstructor;
923
924     protected:
925 #if ENABLE(JIT)
926         virtual bool jitCompileImpl(ExecState*) = 0;
927         virtual void jettisonImpl() = 0;
928 #endif
929         virtual void visitWeakReferences(SlotVisitor&);
930         virtual void finalizeUnconditionally();
931
932 #if ENABLE(DFG_JIT)
933         void tallyFrequentExitSites();
934 #else
935         void tallyFrequentExitSites() { }
936 #endif
937
938     private:
939         friend class DFGCodeBlocks;
940
941         double optimizationThresholdScalingFactor();
942
943 #if ENABLE(JIT)
944         ClosureCallStubRoutine* findClosureCallForReturnPC(ReturnAddressPtr);
945 #endif
946
947 #if ENABLE(VALUE_PROFILER)
948         void updateAllPredictionsAndCountLiveness(OperationInProgress, unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles);
949 #endif
950
951         void setIdentifiers(const Vector<Identifier>& identifiers)
952         {
953             RELEASE_ASSERT(m_identifiers.isEmpty());
954             m_identifiers.appendVector(identifiers);
955         }
956
957         void setConstantRegisters(const Vector<WriteBarrier<Unknown> >& constants)
958         {
959             size_t count = constants.size();
960             m_constantRegisters.resize(count);
961             for (size_t i = 0; i < count; i++)
962                 m_constantRegisters[i].set(*m_vm, ownerExecutable(), constants[i].get());
963         }
964
965         void dumpBytecode(PrintStream&, ExecState*, const Instruction* begin, const Instruction*&);
966
967         CString registerName(ExecState*, int r) const;
968         void printUnaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
969         void printBinaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
970         void printConditionalJump(PrintStream&, ExecState*, const Instruction*, const Instruction*&, int location, const char* op);
971         void printGetByIdOp(PrintStream&, ExecState*, int location, const Instruction*&);
972         void printGetByIdCacheStatus(PrintStream&, ExecState*, int location);
973         enum CacheDumpMode { DumpCaches, DontDumpCaches };
974         void printCallOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op, CacheDumpMode);
975         void printPutByIdOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
976         void beginDumpProfiling(PrintStream&, bool& hasPrintedProfiling);
977         void dumpValueProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
978         void dumpArrayProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
979 #if ENABLE(VALUE_PROFILER)
980         void dumpRareCaseProfile(PrintStream&, const char* name, RareCaseProfile*, bool& hasPrintedProfiling);
981 #endif
982
983         void visitStructures(SlotVisitor&, Instruction* vPC);
984
985 #if ENABLE(DFG_JIT)
986         bool shouldImmediatelyAssumeLivenessDuringScan()
987         {
988             // Null m_dfgData means that this is a baseline JIT CodeBlock. Baseline JIT
989             // CodeBlocks don't need to be jettisoned when their weak references go
990             // stale. So if a basline JIT CodeBlock gets scanned, we can assume that
991             // this means that it's live.
992             if (!JITCode::isOptimizingJIT(getJITType()))
993                 return true;
994
995             // For simplicity, we don't attempt to jettison code blocks during GC if
996             // they are executing. Instead we strongly mark their weak references to
997             // allow them to continue to execute soundly.
998             if (m_jitCode->dfgCommon()->mayBeExecuting)
999                 return true;
1000
1001             if (Options::forceDFGCodeBlockLiveness())
1002                 return true;
1003
1004             return false;
1005         }
1006 #else
1007         bool shouldImmediatelyAssumeLivenessDuringScan() { return true; }
1008 #endif
1009
1010         void performTracingFixpointIteration(SlotVisitor&);
1011
1012         void stronglyVisitStrongReferences(SlotVisitor&);
1013         void stronglyVisitWeakReferences(SlotVisitor&);
1014
1015         void createRareDataIfNecessary()
1016         {
1017             if (!m_rareData)
1018                 m_rareData = adoptPtr(new RareData);
1019         }
1020
1021 #if ENABLE(JIT)
1022         void resetStubInternal(RepatchBuffer&, StructureStubInfo&);
1023         void resetStubDuringGCInternal(RepatchBuffer&, StructureStubInfo&);
1024 #endif
1025         WriteBarrier<UnlinkedCodeBlock> m_unlinkedCode;
1026         int m_numParameters;
1027         WriteBarrier<ScriptExecutable> m_ownerExecutable;
1028         VM* m_vm;
1029
1030         RefCountedArray<Instruction> m_instructions;
1031         int m_thisRegister;
1032         int m_argumentsRegister;
1033         int m_activationRegister;
1034
1035         bool m_isStrictMode;
1036         bool m_needsActivation;
1037
1038         RefPtr<SourceProvider> m_source;
1039         unsigned m_sourceOffset;
1040         unsigned m_firstLineColumnOffset;
1041         unsigned m_codeType;
1042
1043 #if ENABLE(LLINT)
1044         SegmentedVector<LLIntCallLinkInfo, 8> m_llintCallLinkInfos;
1045         SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo> > m_incomingLLIntCalls;
1046 #endif
1047 #if ENABLE(JIT)
1048         Vector<StructureStubInfo> m_structureStubInfos;
1049         Vector<ByValInfo> m_byValInfos;
1050         Vector<CallLinkInfo> m_callLinkInfos;
1051         RefPtr<JITCode> m_jitCode;
1052         MacroAssemblerCodePtr m_jitCodeWithArityCheck;
1053         SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo> > m_incomingCalls;
1054 #endif
1055 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
1056         OwnPtr<CompactJITCodeMap> m_jitCodeMap;
1057 #endif
1058 #if ENABLE(DFG_JIT)
1059         // This is relevant to non-DFG code blocks that serve as the profiled code block
1060         // for DFG code blocks.
1061         DFG::ExitProfile m_exitProfile;
1062         CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1063 #endif
1064 #if ENABLE(VALUE_PROFILER)
1065         Vector<ValueProfile> m_argumentValueProfiles;
1066         SegmentedVector<ValueProfile, 8> m_valueProfiles;
1067         SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1068         SegmentedVector<RareCaseProfile, 8> m_specialFastCaseProfiles;
1069         SegmentedVector<ArrayAllocationProfile, 8> m_arrayAllocationProfiles;
1070         ArrayProfileVector m_arrayProfiles;
1071 #endif
1072         SegmentedVector<ObjectAllocationProfile, 8> m_objectAllocationProfiles;
1073
1074         // Constant Pool
1075         Vector<Identifier> m_identifiers;
1076         COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1077         // TODO: This could just be a pointer to m_unlinkedCodeBlock's data, but the DFG mutates
1078         // it, so we're stuck with it for now.
1079         Vector<WriteBarrier<Unknown> > m_constantRegisters;
1080         Vector<WriteBarrier<FunctionExecutable> > m_functionDecls;
1081         Vector<WriteBarrier<FunctionExecutable> > m_functionExprs;
1082
1083         OwnPtr<CodeBlock> m_alternative;
1084
1085         ExecutionCounter m_llintExecuteCounter;
1086
1087         ExecutionCounter m_jitExecuteCounter;
1088         int32_t m_totalJITExecutions;
1089         uint32_t m_osrExitCounter;
1090         uint16_t m_optimizationDelayCounter;
1091         uint16_t m_reoptimizationRetryCounter;
1092
1093         Vector<ResolveOperations> m_resolveOperations;
1094         Vector<PutToBaseOperation, 1> m_putToBaseOperations;
1095
1096         struct RareData {
1097             WTF_MAKE_FAST_ALLOCATED;
1098         public:
1099             Vector<HandlerInfo> m_exceptionHandlers;
1100
1101             // Buffers used for large array literals
1102             Vector<Vector<JSValue> > m_constantBuffers;
1103
1104             // Jump Tables
1105             Vector<SimpleJumpTable> m_immediateSwitchJumpTables;
1106             Vector<SimpleJumpTable> m_characterSwitchJumpTables;
1107             Vector<StringJumpTable> m_stringSwitchJumpTables;
1108
1109             EvalCodeCache m_evalCodeCache;
1110
1111 #if ENABLE(JIT)
1112             Vector<CallReturnOffsetToBytecodeOffset, 0, UnsafeVectorOverflow> m_callReturnIndexVector;
1113 #endif
1114 #if ENABLE(DFG_JIT)
1115             SegmentedVector<InlineCallFrame, 4> m_inlineCallFrames;
1116             Vector<CodeOriginAtCallReturnOffset, 0, UnsafeVectorOverflow> m_codeOrigins;
1117 #endif
1118         };
1119 #if COMPILER(MSVC)
1120         friend void WTF::deleteOwnedPtr<RareData>(RareData*);
1121 #endif
1122         OwnPtr<RareData> m_rareData;
1123 #if ENABLE(JIT)
1124         DFG::CapabilityLevel m_canCompileWithDFGState;
1125 #endif
1126     };
1127
1128     // Program code is not marked by any function, so we make the global object
1129     // responsible for marking it.
1130
1131     class GlobalCodeBlock : public CodeBlock {
1132     protected:
1133         GlobalCodeBlock(CopyParsedBlockTag, GlobalCodeBlock& other)
1134         : CodeBlock(CopyParsedBlock, other)
1135         {
1136         }
1137
1138         GlobalCodeBlock(ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSGlobalObject* globalObject, unsigned baseScopeDepth, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset, PassOwnPtr<CodeBlock> alternative)
1139         : CodeBlock(ownerExecutable, unlinkedCodeBlock, globalObject, baseScopeDepth, sourceProvider, sourceOffset, firstLineColumnOffset, alternative)
1140         {
1141         }
1142     };
1143
1144     class ProgramCodeBlock : public GlobalCodeBlock {
1145     public:
1146         ProgramCodeBlock(CopyParsedBlockTag, ProgramCodeBlock& other)
1147         : GlobalCodeBlock(CopyParsedBlock, other)
1148         {
1149         }
1150
1151         ProgramCodeBlock(ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset, PassOwnPtr<CodeBlock> alternative)
1152         : GlobalCodeBlock(ownerExecutable, unlinkedCodeBlock, globalObject, 0, sourceProvider, 0, firstLineColumnOffset, alternative)
1153         {
1154         }
1155
1156 #if ENABLE(JIT)
1157     protected:
1158         virtual JSObject* compileOptimized(ExecState*, JSScope*, unsigned bytecodeIndex);
1159         virtual void jettisonImpl();
1160         virtual bool jitCompileImpl(ExecState*);
1161         virtual CodeBlock* replacement();
1162         virtual DFG::CapabilityLevel canCompileWithDFGInternal();
1163 #endif
1164     };
1165
1166     class EvalCodeBlock : public GlobalCodeBlock {
1167     public:
1168         EvalCodeBlock(CopyParsedBlockTag, EvalCodeBlock& other)
1169         : GlobalCodeBlock(CopyParsedBlock, other)
1170         {
1171         }
1172         
1173         EvalCodeBlock(EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, int baseScopeDepth, PassOwnPtr<CodeBlock> alternative)
1174         : GlobalCodeBlock(ownerExecutable, unlinkedCodeBlock, globalObject, baseScopeDepth, sourceProvider, 0, 1, alternative)
1175         {
1176         }
1177         
1178         const Identifier& variable(unsigned index) { return unlinkedEvalCodeBlock()->variable(index); }
1179         unsigned numVariables() { return unlinkedEvalCodeBlock()->numVariables(); }
1180         
1181 #if ENABLE(JIT)
1182     protected:
1183         virtual JSObject* compileOptimized(ExecState*, JSScope*, unsigned bytecodeIndex);
1184         virtual void jettisonImpl();
1185         virtual bool jitCompileImpl(ExecState*);
1186         virtual CodeBlock* replacement();
1187         virtual DFG::CapabilityLevel canCompileWithDFGInternal();
1188 #endif
1189         
1190     private:
1191         UnlinkedEvalCodeBlock* unlinkedEvalCodeBlock() const { return jsCast<UnlinkedEvalCodeBlock*>(unlinkedCodeBlock()); }
1192     };
1193     
1194     class FunctionCodeBlock : public CodeBlock {
1195     public:
1196         FunctionCodeBlock(CopyParsedBlockTag, FunctionCodeBlock& other)
1197         : CodeBlock(CopyParsedBlock, other)
1198         {
1199         }
1200         
1201         FunctionCodeBlock(FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset, PassOwnPtr<CodeBlock> alternative = nullptr)
1202         : CodeBlock(ownerExecutable, unlinkedCodeBlock, globalObject, 0, sourceProvider, sourceOffset, firstLineColumnOffset, alternative)
1203         {
1204         }
1205         
1206 #if ENABLE(JIT)
1207     protected:
1208         virtual JSObject* compileOptimized(ExecState*, JSScope*, unsigned bytecodeIndex);
1209         virtual void jettisonImpl();
1210         virtual bool jitCompileImpl(ExecState*);
1211         virtual CodeBlock* replacement();
1212         virtual DFG::CapabilityLevel canCompileWithDFGInternal();
1213 #endif
1214     };
1215     
1216     inline CodeBlock* baselineCodeBlockForInlineCallFrame(InlineCallFrame* inlineCallFrame)
1217     {
1218         RELEASE_ASSERT(inlineCallFrame);
1219         ExecutableBase* executable = inlineCallFrame->executable.get();
1220         RELEASE_ASSERT(executable->structure()->classInfo() == &FunctionExecutable::s_info);
1221         return static_cast<FunctionExecutable*>(executable)->baselineCodeBlockFor(inlineCallFrame->isCall ? CodeForCall : CodeForConstruct);
1222     }
1223     
1224     inline CodeBlock* baselineCodeBlockForOriginAndBaselineCodeBlock(const CodeOrigin& codeOrigin, CodeBlock* baselineCodeBlock)
1225     {
1226         if (codeOrigin.inlineCallFrame)
1227             return baselineCodeBlockForInlineCallFrame(codeOrigin.inlineCallFrame);
1228         return baselineCodeBlock;
1229     }
1230     
1231     inline int CodeBlock::argumentIndexAfterCapture(size_t argument)
1232     {
1233         if (argument >= static_cast<size_t>(symbolTable()->parameterCount()))
1234             return CallFrame::argumentOffset(argument);
1235         
1236         const SlowArgument* slowArguments = symbolTable()->slowArguments();
1237         if (!slowArguments || slowArguments[argument].status == SlowArgument::Normal)
1238             return CallFrame::argumentOffset(argument);
1239         
1240         ASSERT(slowArguments[argument].status == SlowArgument::Captured);
1241         return slowArguments[argument].index;
1242     }
1243     
1244     inline Register& ExecState::r(int index)
1245     {
1246         CodeBlock* codeBlock = this->codeBlock();
1247         if (codeBlock->isConstantRegisterIndex(index))
1248             return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1249         return this[index];
1250     }
1251     
1252     inline Register& ExecState::uncheckedR(int index)
1253     {
1254         RELEASE_ASSERT(index < FirstConstantRegisterIndex);
1255         return this[index];
1256     }
1257     
1258 #if ENABLE(DFG_JIT)
1259     inline bool ExecState::isInlineCallFrame()
1260     {
1261         if (LIKELY(!codeBlock() || !JITCode::isOptimizingJIT(codeBlock()->getJITType())))
1262             return false;
1263         return isInlineCallFrameSlow();
1264     }
1265 #endif
1266     
1267     inline JSValue ExecState::argumentAfterCapture(size_t argument)
1268     {
1269         if (argument >= argumentCount())
1270             return jsUndefined();
1271         
1272         if (!codeBlock())
1273             return this[argumentOffset(argument)].jsValue();
1274         
1275         return this[codeBlock()->argumentIndexAfterCapture(argument)].jsValue();
1276     }
1277     
1278 #if ENABLE(DFG_JIT)
1279     inline void DFGCodeBlocks::mark(void* candidateCodeBlock)
1280     {
1281         // We have to check for 0 and -1 because those are used by the HashMap as markers.
1282         uintptr_t value = reinterpret_cast<uintptr_t>(candidateCodeBlock);
1283         
1284         // This checks for both of those nasty cases in one go.
1285         // 0 + 1 = 1
1286         // -1 + 1 = 0
1287         if (value + 1 <= 1)
1288             return;
1289         
1290         HashSet<CodeBlock*>::iterator iter = m_set.find(static_cast<CodeBlock*>(candidateCodeBlock));
1291         if (iter == m_set.end())
1292             return;
1293         
1294         (*iter)->m_jitCode->dfgCommon()->mayBeExecuting = true;
1295     }
1296 #endif
1297     
1298 } // namespace JSC
1299
1300 #endif // CodeBlock_h