The DFG should be able to tier-up and OSR enter into the FTL
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2010, 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 #include "config.h"
31 #include "CodeBlock.h"
32
33 #include "BytecodeGenerator.h"
34 #include "CallLinkStatus.h"
35 #include "DFGCapabilities.h"
36 #include "DFGCommon.h"
37 #include "DFGDriver.h"
38 #include "DFGNode.h"
39 #include "DFGRepatch.h"
40 #include "DFGWorklist.h"
41 #include "Debugger.h"
42 #include "Interpreter.h"
43 #include "JIT.h"
44 #include "JITStubs.h"
45 #include "JSActivation.h"
46 #include "JSCJSValue.h"
47 #include "JSFunction.h"
48 #include "JSNameScope.h"
49 #include "LowLevelInterpreter.h"
50 #include "Operations.h"
51 #include "PolymorphicPutByIdList.h"
52 #include "ReduceWhitespace.h"
53 #include "RepatchBuffer.h"
54 #include "SlotVisitorInlines.h"
55 #include <stdio.h>
56 #include <wtf/CommaPrinter.h>
57 #include <wtf/StringExtras.h>
58 #include <wtf/StringPrintStream.h>
59
60 #if ENABLE(DFG_JIT)
61 #include "DFGOperations.h"
62 #endif
63
64 #if ENABLE(FTL_JIT)
65 #include "FTLJITCode.h"
66 #endif
67
68 #define DUMP_CODE_BLOCK_STATISTICS 0
69
70 namespace JSC {
71
72 CString CodeBlock::inferredName() const
73 {
74     switch (codeType()) {
75     case GlobalCode:
76         return "<global>";
77     case EvalCode:
78         return "<eval>";
79     case FunctionCode:
80         return jsCast<FunctionExecutable*>(ownerExecutable())->inferredName().utf8();
81     default:
82         CRASH();
83         return CString("", 0);
84     }
85 }
86
87 bool CodeBlock::hasHash() const
88 {
89     return !!m_hash;
90 }
91
92 bool CodeBlock::isSafeToComputeHash() const
93 {
94     return !isCompilationThread();
95 }
96
97 CodeBlockHash CodeBlock::hash() const
98 {
99     if (!m_hash) {
100         RELEASE_ASSERT(isSafeToComputeHash());
101         m_hash = CodeBlockHash(ownerExecutable()->source(), specializationKind());
102     }
103     return m_hash;
104 }
105
106 CString CodeBlock::sourceCodeForTools() const
107 {
108     if (codeType() != FunctionCode)
109         return ownerExecutable()->source().toUTF8();
110     
111     SourceProvider* provider = source();
112     FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
113     UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
114     unsigned unlinkedStartOffset = unlinked->startOffset();
115     unsigned linkedStartOffset = executable->source().startOffset();
116     int delta = linkedStartOffset - unlinkedStartOffset;
117     unsigned rangeStart = delta + unlinked->functionStartOffset();
118     unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
119     return toCString(
120         "function ",
121         provider->source().impl()->utf8ForRange(rangeStart, rangeEnd - rangeStart));
122 }
123
124 CString CodeBlock::sourceCodeOnOneLine() const
125 {
126     return reduceWhitespace(sourceCodeForTools());
127 }
128
129 void CodeBlock::dumpAssumingJITType(PrintStream& out, JITCode::JITType jitType) const
130 {
131     if (hasHash() || isSafeToComputeHash())
132         out.print(inferredName(), "#", hash(), ":[", RawPointer(this), "->", RawPointer(ownerExecutable()), ", ", jitType, codeType());
133     else
134         out.print(inferredName(), "#<no-hash>:[", RawPointer(this), "->", RawPointer(ownerExecutable()), ", ", jitType, codeType());
135
136     if (codeType() == FunctionCode)
137         out.print(specializationKind());
138     if (this->jitType() == JITCode::BaselineJIT && m_shouldAlwaysBeInlined)
139         out.print(" (SABI)");
140     if (ownerExecutable()->neverInline())
141         out.print(" (NeverInline)");
142     out.print("]");
143 }
144
145 void CodeBlock::dump(PrintStream& out) const
146 {
147     dumpAssumingJITType(out, jitType());
148 }
149
150 static CString constantName(int k, JSValue value)
151 {
152     return toCString(value, "(@k", k - FirstConstantRegisterIndex, ")");
153 }
154
155 static CString idName(int id0, const Identifier& ident)
156 {
157     return toCString(ident.impl(), "(@id", id0, ")");
158 }
159
160 CString CodeBlock::registerName(int r) const
161 {
162     if (r == missingThisObjectMarker())
163         return "<null>";
164
165     if (isConstantRegisterIndex(r))
166         return constantName(r, getConstant(r));
167
168     return toCString("r", r);
169 }
170
171 static CString regexpToSourceString(RegExp* regExp)
172 {
173     char postfix[5] = { '/', 0, 0, 0, 0 };
174     int index = 1;
175     if (regExp->global())
176         postfix[index++] = 'g';
177     if (regExp->ignoreCase())
178         postfix[index++] = 'i';
179     if (regExp->multiline())
180         postfix[index] = 'm';
181
182     return toCString("/", regExp->pattern().impl(), postfix);
183 }
184
185 static CString regexpName(int re, RegExp* regexp)
186 {
187     return toCString(regexpToSourceString(regexp), "(@re", re, ")");
188 }
189
190 NEVER_INLINE static const char* debugHookName(int debugHookID)
191 {
192     switch (static_cast<DebugHookID>(debugHookID)) {
193         case DidEnterCallFrame:
194             return "didEnterCallFrame";
195         case WillLeaveCallFrame:
196             return "willLeaveCallFrame";
197         case WillExecuteStatement:
198             return "willExecuteStatement";
199         case WillExecuteProgram:
200             return "willExecuteProgram";
201         case DidExecuteProgram:
202             return "didExecuteProgram";
203         case DidReachBreakpoint:
204             return "didReachBreakpoint";
205     }
206
207     RELEASE_ASSERT_NOT_REACHED();
208     return "";
209 }
210
211 void CodeBlock::printUnaryOp(PrintStream& out, ExecState*, int location, const Instruction*& it, const char* op)
212 {
213     int r0 = (++it)->u.operand;
214     int r1 = (++it)->u.operand;
215
216     out.printf("[%4d] %s\t\t %s, %s", location, op, registerName(r0).data(), registerName(r1).data());
217 }
218
219 void CodeBlock::printBinaryOp(PrintStream& out, ExecState*, int location, const Instruction*& it, const char* op)
220 {
221     int r0 = (++it)->u.operand;
222     int r1 = (++it)->u.operand;
223     int r2 = (++it)->u.operand;
224     out.printf("[%4d] %s\t\t %s, %s, %s", location, op, registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
225 }
226
227 void CodeBlock::printConditionalJump(PrintStream& out, ExecState*, const Instruction*, const Instruction*& it, int location, const char* op)
228 {
229     int r0 = (++it)->u.operand;
230     int offset = (++it)->u.operand;
231     out.printf("[%4d] %s\t\t %s, %d(->%d)", location, op, registerName(r0).data(), offset, location + offset);
232 }
233
234 void CodeBlock::printGetByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it)
235 {
236     const char* op;
237     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
238     case op_get_by_id:
239         op = "get_by_id";
240         break;
241     case op_get_by_id_out_of_line:
242         op = "get_by_id_out_of_line";
243         break;
244     case op_get_by_id_self:
245         op = "get_by_id_self";
246         break;
247     case op_get_by_id_proto:
248         op = "get_by_id_proto";
249         break;
250     case op_get_by_id_chain:
251         op = "get_by_id_chain";
252         break;
253     case op_get_by_id_getter_self:
254         op = "get_by_id_getter_self";
255         break;
256     case op_get_by_id_getter_proto:
257         op = "get_by_id_getter_proto";
258         break;
259     case op_get_by_id_getter_chain:
260         op = "get_by_id_getter_chain";
261         break;
262     case op_get_by_id_custom_self:
263         op = "get_by_id_custom_self";
264         break;
265     case op_get_by_id_custom_proto:
266         op = "get_by_id_custom_proto";
267         break;
268     case op_get_by_id_custom_chain:
269         op = "get_by_id_custom_chain";
270         break;
271     case op_get_by_id_generic:
272         op = "get_by_id_generic";
273         break;
274     case op_get_array_length:
275         op = "array_length";
276         break;
277     case op_get_string_length:
278         op = "string_length";
279         break;
280     default:
281         RELEASE_ASSERT_NOT_REACHED();
282         op = 0;
283     }
284     int r0 = (++it)->u.operand;
285     int r1 = (++it)->u.operand;
286     int id0 = (++it)->u.operand;
287     out.printf("[%4d] %s\t %s, %s, %s", location, op, registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
288     it += 4; // Increment up to the value profiler.
289 }
290
291 #if ENABLE(JIT) || ENABLE(LLINT) // unused in some configurations
292 static void dumpStructure(PrintStream& out, const char* name, ExecState* exec, Structure* structure, const Identifier& ident)
293 {
294     if (!structure)
295         return;
296     
297     out.printf("%s = %p", name, structure);
298     
299     PropertyOffset offset = structure->getConcurrently(exec->vm(), ident.impl());
300     if (offset != invalidOffset)
301         out.printf(" (offset = %d)", offset);
302 }
303 #endif
304
305 #if ENABLE(JIT) // unused when not ENABLE(JIT), leading to silly warnings
306 static void dumpChain(PrintStream& out, ExecState* exec, StructureChain* chain, const Identifier& ident)
307 {
308     out.printf("chain = %p: [", chain);
309     bool first = true;
310     for (WriteBarrier<Structure>* currentStructure = chain->head();
311          *currentStructure;
312          ++currentStructure) {
313         if (first)
314             first = false;
315         else
316             out.printf(", ");
317         dumpStructure(out, "struct", exec, currentStructure->get(), ident);
318     }
319     out.printf("]");
320 }
321 #endif
322
323 void CodeBlock::printGetByIdCacheStatus(PrintStream& out, ExecState* exec, int location)
324 {
325     Instruction* instruction = instructions().begin() + location;
326
327     const Identifier& ident = identifier(instruction[3].u.operand);
328     
329     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
330     
331 #if ENABLE(LLINT)
332     if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_get_array_length)
333         out.printf(" llint(array_length)");
334     else if (Structure* structure = instruction[4].u.structure.get()) {
335         out.printf(" llint(");
336         dumpStructure(out, "struct", exec, structure, ident);
337         out.printf(")");
338     }
339 #endif
340
341 #if ENABLE(JIT)
342     if (numberOfStructureStubInfos()) {
343         StructureStubInfo& stubInfo = getStubInfo(location);
344         if (stubInfo.seen) {
345             out.printf(" jit(");
346             
347             Structure* baseStructure = 0;
348             Structure* prototypeStructure = 0;
349             StructureChain* chain = 0;
350             PolymorphicAccessStructureList* structureList = 0;
351             int listSize = 0;
352             
353             switch (stubInfo.accessType) {
354             case access_get_by_id_self:
355                 out.printf("self");
356                 baseStructure = stubInfo.u.getByIdSelf.baseObjectStructure.get();
357                 break;
358             case access_get_by_id_proto:
359                 out.printf("proto");
360                 baseStructure = stubInfo.u.getByIdProto.baseObjectStructure.get();
361                 prototypeStructure = stubInfo.u.getByIdProto.prototypeStructure.get();
362                 break;
363             case access_get_by_id_chain:
364                 out.printf("chain");
365                 baseStructure = stubInfo.u.getByIdChain.baseObjectStructure.get();
366                 chain = stubInfo.u.getByIdChain.chain.get();
367                 break;
368             case access_get_by_id_self_list:
369                 out.printf("self_list");
370                 structureList = stubInfo.u.getByIdSelfList.structureList;
371                 listSize = stubInfo.u.getByIdSelfList.listSize;
372                 break;
373             case access_get_by_id_proto_list:
374                 out.printf("proto_list");
375                 structureList = stubInfo.u.getByIdProtoList.structureList;
376                 listSize = stubInfo.u.getByIdProtoList.listSize;
377                 break;
378             case access_unset:
379                 out.printf("unset");
380                 break;
381             case access_get_by_id_generic:
382                 out.printf("generic");
383                 break;
384             case access_get_array_length:
385                 out.printf("array_length");
386                 break;
387             case access_get_string_length:
388                 out.printf("string_length");
389                 break;
390             default:
391                 RELEASE_ASSERT_NOT_REACHED();
392                 break;
393             }
394             
395             if (baseStructure) {
396                 out.printf(", ");
397                 dumpStructure(out, "struct", exec, baseStructure, ident);
398             }
399             
400             if (prototypeStructure) {
401                 out.printf(", ");
402                 dumpStructure(out, "prototypeStruct", exec, baseStructure, ident);
403             }
404             
405             if (chain) {
406                 out.printf(", ");
407                 dumpChain(out, exec, chain, ident);
408             }
409             
410             if (structureList) {
411                 out.printf(", list = %p: [", structureList);
412                 for (int i = 0; i < listSize; ++i) {
413                     if (i)
414                         out.printf(", ");
415                     out.printf("(");
416                     dumpStructure(out, "base", exec, structureList->list[i].base.get(), ident);
417                     if (structureList->list[i].isChain) {
418                         if (structureList->list[i].u.chain.get()) {
419                             out.printf(", ");
420                             dumpChain(out, exec, structureList->list[i].u.chain.get(), ident);
421                         }
422                     } else {
423                         if (structureList->list[i].u.proto.get()) {
424                             out.printf(", ");
425                             dumpStructure(out, "proto", exec, structureList->list[i].u.proto.get(), ident);
426                         }
427                     }
428                     out.printf(")");
429                 }
430                 out.printf("]");
431             }
432             out.printf(")");
433         }
434     }
435 #endif
436 }
437
438 void CodeBlock::printCallOp(PrintStream& out, ExecState*, int location, const Instruction*& it, const char* op, CacheDumpMode cacheDumpMode, bool& hasPrintedProfiling)
439 {
440     int dst = (++it)->u.operand;
441     int func = (++it)->u.operand;
442     int argCount = (++it)->u.operand;
443     int registerOffset = (++it)->u.operand;
444     out.printf("[%4d] %s %s, %s, %d, %d", location, op, registerName(dst).data(), registerName(func).data(), argCount, registerOffset);
445     if (cacheDumpMode == DumpCaches) {
446 #if ENABLE(LLINT)
447         LLIntCallLinkInfo* callLinkInfo = it[1].u.callLinkInfo;
448         if (callLinkInfo->lastSeenCallee) {
449             out.printf(
450                 " llint(%p, exec %p)",
451                 callLinkInfo->lastSeenCallee.get(),
452                 callLinkInfo->lastSeenCallee->executable());
453         }
454 #endif
455 #if ENABLE(JIT)
456         if (numberOfCallLinkInfos()) {
457             JSFunction* target = getCallLinkInfo(location).lastSeenCallee.get();
458             if (target)
459                 out.printf(" jit(%p, exec %p)", target, target->executable());
460         }
461 #endif
462         out.print(" status(", CallLinkStatus::computeFor(this, location), ")");
463     }
464     ++it;
465     dumpArrayProfiling(out, it, hasPrintedProfiling);
466     dumpValueProfiling(out, it, hasPrintedProfiling);
467 }
468
469 void CodeBlock::printPutByIdOp(PrintStream& out, ExecState*, int location, const Instruction*& it, const char* op)
470 {
471     int r0 = (++it)->u.operand;
472     int id0 = (++it)->u.operand;
473     int r1 = (++it)->u.operand;
474     out.printf("[%4d] %s\t %s, %s, %s", location, op, registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data());
475     it += 5;
476 }
477
478 void CodeBlock::dumpBytecode(PrintStream& out)
479 {
480     // We only use the ExecState* for things that don't actually lead to JS execution,
481     // like converting a JSString to a String. Hence the globalExec is appropriate.
482     ExecState* exec = m_globalObject->globalExec();
483     
484     size_t instructionCount = 0;
485
486     for (size_t i = 0; i < instructions().size(); i += opcodeLengths[exec->interpreter()->getOpcodeID(instructions()[i].u.opcode)])
487         ++instructionCount;
488
489     out.print(*this);
490     out.printf(
491         ": %lu m_instructions; %lu bytes; %d parameter(s); %d callee register(s); %d variable(s)",
492         static_cast<unsigned long>(instructions().size()),
493         static_cast<unsigned long>(instructions().size() * sizeof(Instruction)),
494         m_numParameters, m_numCalleeRegisters, m_numVars);
495     if (symbolTable() && symbolTable()->captureCount()) {
496         out.printf(
497             "; %d captured var(s) (from r%d to r%d, inclusive)",
498             symbolTable()->captureCount(), symbolTable()->captureStart(), symbolTable()->captureEnd() - 1);
499     }
500     if (usesArguments()) {
501         out.printf(
502             "; uses arguments, in r%d, r%d",
503             argumentsRegister(),
504             unmodifiedArgumentsRegister(argumentsRegister()));
505     }
506     if (needsFullScopeChain() && codeType() == FunctionCode)
507         out.printf("; activation in r%d", activationRegister());
508
509     const Instruction* begin = instructions().begin();
510     const Instruction* end = instructions().end();
511     for (const Instruction* it = begin; it != end; ++it)
512         dumpBytecode(out, exec, begin, it);
513
514     if (numberOfIdentifiers()) {
515         out.printf("\nIdentifiers:\n");
516         size_t i = 0;
517         do {
518             out.printf("  id%u = %s\n", static_cast<unsigned>(i), identifier(i).string().utf8().data());
519             ++i;
520         } while (i != numberOfIdentifiers());
521     }
522
523     if (!m_constantRegisters.isEmpty()) {
524         out.printf("\nConstants:\n");
525         size_t i = 0;
526         do {
527             out.printf("   k%u = %s\n", static_cast<unsigned>(i), toCString(m_constantRegisters[i].get()).data());
528             ++i;
529         } while (i < m_constantRegisters.size());
530     }
531
532     if (size_t count = m_unlinkedCode->numberOfRegExps()) {
533         out.printf("\nm_regexps:\n");
534         size_t i = 0;
535         do {
536             out.printf("  re%u = %s\n", static_cast<unsigned>(i), regexpToSourceString(m_unlinkedCode->regexp(i)).data());
537             ++i;
538         } while (i < count);
539     }
540
541 #if ENABLE(JIT)
542     if (!m_structureStubInfos.isEmpty())
543         out.printf("\nStructures:\n");
544 #endif
545
546     if (m_rareData && !m_rareData->m_exceptionHandlers.isEmpty()) {
547         out.printf("\nException Handlers:\n");
548         unsigned i = 0;
549         do {
550             out.printf("\t %d: { start: [%4d] end: [%4d] target: [%4d] depth: [%4d] }\n", i + 1, m_rareData->m_exceptionHandlers[i].start, m_rareData->m_exceptionHandlers[i].end, m_rareData->m_exceptionHandlers[i].target, m_rareData->m_exceptionHandlers[i].scopeDepth);
551             ++i;
552         } while (i < m_rareData->m_exceptionHandlers.size());
553     }
554     
555     if (m_rareData && !m_rareData->m_switchJumpTables.isEmpty()) {
556         out.printf("Switch Jump Tables:\n");
557         unsigned i = 0;
558         do {
559             out.printf("  %1d = {\n", i);
560             int entry = 0;
561             Vector<int32_t>::const_iterator end = m_rareData->m_switchJumpTables[i].branchOffsets.end();
562             for (Vector<int32_t>::const_iterator iter = m_rareData->m_switchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
563                 if (!*iter)
564                     continue;
565                 out.printf("\t\t%4d => %04d\n", entry + m_rareData->m_switchJumpTables[i].min, *iter);
566             }
567             out.printf("      }\n");
568             ++i;
569         } while (i < m_rareData->m_switchJumpTables.size());
570     }
571     
572     if (m_rareData && !m_rareData->m_stringSwitchJumpTables.isEmpty()) {
573         out.printf("\nString Switch Jump Tables:\n");
574         unsigned i = 0;
575         do {
576             out.printf("  %1d = {\n", i);
577             StringJumpTable::StringOffsetTable::const_iterator end = m_rareData->m_stringSwitchJumpTables[i].offsetTable.end();
578             for (StringJumpTable::StringOffsetTable::const_iterator iter = m_rareData->m_stringSwitchJumpTables[i].offsetTable.begin(); iter != end; ++iter)
579                 out.printf("\t\t\"%s\" => %04d\n", String(iter->key).utf8().data(), iter->value.branchOffset);
580             out.printf("      }\n");
581             ++i;
582         } while (i < m_rareData->m_stringSwitchJumpTables.size());
583     }
584
585     out.printf("\n");
586 }
587
588 void CodeBlock::beginDumpProfiling(PrintStream& out, bool& hasPrintedProfiling)
589 {
590     if (hasPrintedProfiling) {
591         out.print("; ");
592         return;
593     }
594     
595     out.print("    ");
596     hasPrintedProfiling = true;
597 }
598
599 void CodeBlock::dumpValueProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
600 {
601     ConcurrentJITLocker locker(m_lock);
602     
603     ++it;
604 #if ENABLE(VALUE_PROFILER)
605     CString description = it->u.profile->briefDescription(locker);
606     if (!description.length())
607         return;
608     beginDumpProfiling(out, hasPrintedProfiling);
609     out.print(description);
610 #else
611     UNUSED_PARAM(out);
612     UNUSED_PARAM(hasPrintedProfiling);
613 #endif
614 }
615
616 void CodeBlock::dumpArrayProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
617 {
618     ConcurrentJITLocker locker(m_lock);
619     
620     ++it;
621 #if ENABLE(VALUE_PROFILER)
622     if (!it->u.arrayProfile)
623         return;
624     CString description = it->u.arrayProfile->briefDescription(locker, this);
625     if (!description.length())
626         return;
627     beginDumpProfiling(out, hasPrintedProfiling);
628     out.print(description);
629 #else
630     UNUSED_PARAM(out);
631     UNUSED_PARAM(hasPrintedProfiling);
632 #endif
633 }
634
635 #if ENABLE(VALUE_PROFILER)
636 void CodeBlock::dumpRareCaseProfile(PrintStream& out, const char* name, RareCaseProfile* profile, bool& hasPrintedProfiling)
637 {
638     if (!profile || !profile->m_counter)
639         return;
640
641     beginDumpProfiling(out, hasPrintedProfiling);
642     out.print(name, profile->m_counter);
643 }
644 #endif
645
646 void CodeBlock::dumpBytecode(PrintStream& out, ExecState* exec, const Instruction* begin, const Instruction*& it)
647 {
648     int location = it - begin;
649     bool hasPrintedProfiling = false;
650     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
651         case op_enter: {
652             out.printf("[%4d] enter", location);
653             break;
654         }
655         case op_create_activation: {
656             int r0 = (++it)->u.operand;
657             out.printf("[%4d] create_activation %s", location, registerName(r0).data());
658             break;
659         }
660         case op_create_arguments: {
661             int r0 = (++it)->u.operand;
662             out.printf("[%4d] create_arguments\t %s", location, registerName(r0).data());
663             break;
664         }
665         case op_init_lazy_reg: {
666             int r0 = (++it)->u.operand;
667             out.printf("[%4d] init_lazy_reg\t %s", location, registerName(r0).data());
668             break;
669         }
670         case op_get_callee: {
671             int r0 = (++it)->u.operand;
672             out.printf("[%4d] get_callee %s\n", location, registerName(r0).data());
673             ++it;
674             break;
675         }
676         case op_create_this: {
677             int r0 = (++it)->u.operand;
678             int r1 = (++it)->u.operand;
679             unsigned inferredInlineCapacity = (++it)->u.operand;
680             out.printf("[%4d] create_this %s, %s, %u", location, registerName(r0).data(), registerName(r1).data(), inferredInlineCapacity);
681             break;
682         }
683         case op_to_this: {
684             int r0 = (++it)->u.operand;
685             out.printf("[%4d] to_this\t %s", location, registerName(r0).data());
686             ++it; // Skip value profile.
687             break;
688         }
689         case op_new_object: {
690             int r0 = (++it)->u.operand;
691             unsigned inferredInlineCapacity = (++it)->u.operand;
692             out.printf("[%4d] new_object\t %s, %u", location, registerName(r0).data(), inferredInlineCapacity);
693             ++it; // Skip object allocation profile.
694             break;
695         }
696         case op_new_array: {
697             int dst = (++it)->u.operand;
698             int argv = (++it)->u.operand;
699             int argc = (++it)->u.operand;
700             out.printf("[%4d] new_array\t %s, %s, %d", location, registerName(dst).data(), registerName(argv).data(), argc);
701             ++it; // Skip array allocation profile.
702             break;
703         }
704         case op_new_array_with_size: {
705             int dst = (++it)->u.operand;
706             int length = (++it)->u.operand;
707             out.printf("[%4d] new_array_with_size\t %s, %s", location, registerName(dst).data(), registerName(length).data());
708             ++it; // Skip array allocation profile.
709             break;
710         }
711         case op_new_array_buffer: {
712             int dst = (++it)->u.operand;
713             int argv = (++it)->u.operand;
714             int argc = (++it)->u.operand;
715             out.printf("[%4d] new_array_buffer\t %s, %d, %d", location, registerName(dst).data(), argv, argc);
716             ++it; // Skip array allocation profile.
717             break;
718         }
719         case op_new_regexp: {
720             int r0 = (++it)->u.operand;
721             int re0 = (++it)->u.operand;
722             out.printf("[%4d] new_regexp\t %s, ", location, registerName(r0).data());
723             if (r0 >=0 && r0 < (int)m_unlinkedCode->numberOfRegExps())
724                 out.printf("%s", regexpName(re0, regexp(re0)).data());
725             else
726                 out.printf("bad_regexp(%d)", re0);
727             break;
728         }
729         case op_mov: {
730             int r0 = (++it)->u.operand;
731             int r1 = (++it)->u.operand;
732             out.printf("[%4d] mov\t\t %s, %s", location, registerName(r0).data(), registerName(r1).data());
733             break;
734         }
735         case op_not: {
736             printUnaryOp(out, exec, location, it, "not");
737             break;
738         }
739         case op_eq: {
740             printBinaryOp(out, exec, location, it, "eq");
741             break;
742         }
743         case op_eq_null: {
744             printUnaryOp(out, exec, location, it, "eq_null");
745             break;
746         }
747         case op_neq: {
748             printBinaryOp(out, exec, location, it, "neq");
749             break;
750         }
751         case op_neq_null: {
752             printUnaryOp(out, exec, location, it, "neq_null");
753             break;
754         }
755         case op_stricteq: {
756             printBinaryOp(out, exec, location, it, "stricteq");
757             break;
758         }
759         case op_nstricteq: {
760             printBinaryOp(out, exec, location, it, "nstricteq");
761             break;
762         }
763         case op_less: {
764             printBinaryOp(out, exec, location, it, "less");
765             break;
766         }
767         case op_lesseq: {
768             printBinaryOp(out, exec, location, it, "lesseq");
769             break;
770         }
771         case op_greater: {
772             printBinaryOp(out, exec, location, it, "greater");
773             break;
774         }
775         case op_greatereq: {
776             printBinaryOp(out, exec, location, it, "greatereq");
777             break;
778         }
779         case op_inc: {
780             int r0 = (++it)->u.operand;
781             out.printf("[%4d] pre_inc\t\t %s", location, registerName(r0).data());
782             break;
783         }
784         case op_dec: {
785             int r0 = (++it)->u.operand;
786             out.printf("[%4d] pre_dec\t\t %s", location, registerName(r0).data());
787             break;
788         }
789         case op_to_number: {
790             printUnaryOp(out, exec, location, it, "to_number");
791             break;
792         }
793         case op_negate: {
794             printUnaryOp(out, exec, location, it, "negate");
795             break;
796         }
797         case op_add: {
798             printBinaryOp(out, exec, location, it, "add");
799             ++it;
800             break;
801         }
802         case op_mul: {
803             printBinaryOp(out, exec, location, it, "mul");
804             ++it;
805             break;
806         }
807         case op_div: {
808             printBinaryOp(out, exec, location, it, "div");
809             ++it;
810             break;
811         }
812         case op_mod: {
813             printBinaryOp(out, exec, location, it, "mod");
814             break;
815         }
816         case op_sub: {
817             printBinaryOp(out, exec, location, it, "sub");
818             ++it;
819             break;
820         }
821         case op_lshift: {
822             printBinaryOp(out, exec, location, it, "lshift");
823             break;            
824         }
825         case op_rshift: {
826             printBinaryOp(out, exec, location, it, "rshift");
827             break;
828         }
829         case op_urshift: {
830             printBinaryOp(out, exec, location, it, "urshift");
831             break;
832         }
833         case op_bitand: {
834             printBinaryOp(out, exec, location, it, "bitand");
835             ++it;
836             break;
837         }
838         case op_bitxor: {
839             printBinaryOp(out, exec, location, it, "bitxor");
840             ++it;
841             break;
842         }
843         case op_bitor: {
844             printBinaryOp(out, exec, location, it, "bitor");
845             ++it;
846             break;
847         }
848         case op_check_has_instance: {
849             int r0 = (++it)->u.operand;
850             int r1 = (++it)->u.operand;
851             int r2 = (++it)->u.operand;
852             int offset = (++it)->u.operand;
853             out.printf("[%4d] check_has_instance\t\t %s, %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), offset, location + offset);
854             break;
855         }
856         case op_instanceof: {
857             int r0 = (++it)->u.operand;
858             int r1 = (++it)->u.operand;
859             int r2 = (++it)->u.operand;
860             out.printf("[%4d] instanceof\t\t %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
861             break;
862         }
863         case op_typeof: {
864             printUnaryOp(out, exec, location, it, "typeof");
865             break;
866         }
867         case op_is_undefined: {
868             printUnaryOp(out, exec, location, it, "is_undefined");
869             break;
870         }
871         case op_is_boolean: {
872             printUnaryOp(out, exec, location, it, "is_boolean");
873             break;
874         }
875         case op_is_number: {
876             printUnaryOp(out, exec, location, it, "is_number");
877             break;
878         }
879         case op_is_string: {
880             printUnaryOp(out, exec, location, it, "is_string");
881             break;
882         }
883         case op_is_object: {
884             printUnaryOp(out, exec, location, it, "is_object");
885             break;
886         }
887         case op_is_function: {
888             printUnaryOp(out, exec, location, it, "is_function");
889             break;
890         }
891         case op_in: {
892             printBinaryOp(out, exec, location, it, "in");
893             break;
894         }
895         case op_init_global_const_nop: {
896             out.printf("[%4d] init_global_const_nop\t", location);
897             it++;
898             it++;
899             it++;
900             it++;
901             break;
902         }
903         case op_init_global_const: {
904             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
905             int r0 = (++it)->u.operand;
906             out.printf("[%4d] init_global_const\t g%d(%p), %s", location, m_globalObject->findRegisterIndex(registerPointer), registerPointer, registerName(r0).data());
907             it++;
908             it++;
909             break;
910         }
911         case op_get_by_id:
912         case op_get_by_id_out_of_line:
913         case op_get_by_id_self:
914         case op_get_by_id_proto:
915         case op_get_by_id_chain:
916         case op_get_by_id_getter_self:
917         case op_get_by_id_getter_proto:
918         case op_get_by_id_getter_chain:
919         case op_get_by_id_custom_self:
920         case op_get_by_id_custom_proto:
921         case op_get_by_id_custom_chain:
922         case op_get_by_id_generic:
923         case op_get_array_length:
924         case op_get_string_length: {
925             printGetByIdOp(out, exec, location, it);
926             printGetByIdCacheStatus(out, exec, location);
927             dumpValueProfiling(out, it, hasPrintedProfiling);
928             break;
929         }
930         case op_get_arguments_length: {
931             printUnaryOp(out, exec, location, it, "get_arguments_length");
932             it++;
933             break;
934         }
935         case op_put_by_id: {
936             printPutByIdOp(out, exec, location, it, "put_by_id");
937             break;
938         }
939         case op_put_by_id_out_of_line: {
940             printPutByIdOp(out, exec, location, it, "put_by_id_out_of_line");
941             break;
942         }
943         case op_put_by_id_replace: {
944             printPutByIdOp(out, exec, location, it, "put_by_id_replace");
945             break;
946         }
947         case op_put_by_id_transition: {
948             printPutByIdOp(out, exec, location, it, "put_by_id_transition");
949             break;
950         }
951         case op_put_by_id_transition_direct: {
952             printPutByIdOp(out, exec, location, it, "put_by_id_transition_direct");
953             break;
954         }
955         case op_put_by_id_transition_direct_out_of_line: {
956             printPutByIdOp(out, exec, location, it, "put_by_id_transition_direct_out_of_line");
957             break;
958         }
959         case op_put_by_id_transition_normal: {
960             printPutByIdOp(out, exec, location, it, "put_by_id_transition_normal");
961             break;
962         }
963         case op_put_by_id_transition_normal_out_of_line: {
964             printPutByIdOp(out, exec, location, it, "put_by_id_transition_normal_out_of_line");
965             break;
966         }
967         case op_put_by_id_generic: {
968             printPutByIdOp(out, exec, location, it, "put_by_id_generic");
969             break;
970         }
971         case op_put_getter_setter: {
972             int r0 = (++it)->u.operand;
973             int id0 = (++it)->u.operand;
974             int r1 = (++it)->u.operand;
975             int r2 = (++it)->u.operand;
976             out.printf("[%4d] put_getter_setter\t %s, %s, %s, %s", location, registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data(), registerName(r2).data());
977             break;
978         }
979         case op_del_by_id: {
980             int r0 = (++it)->u.operand;
981             int r1 = (++it)->u.operand;
982             int id0 = (++it)->u.operand;
983             out.printf("[%4d] del_by_id\t %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
984             break;
985         }
986         case op_get_by_val: {
987             int r0 = (++it)->u.operand;
988             int r1 = (++it)->u.operand;
989             int r2 = (++it)->u.operand;
990             out.printf("[%4d] get_by_val\t %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
991             dumpArrayProfiling(out, it, hasPrintedProfiling);
992             dumpValueProfiling(out, it, hasPrintedProfiling);
993             break;
994         }
995         case op_get_argument_by_val: {
996             int r0 = (++it)->u.operand;
997             int r1 = (++it)->u.operand;
998             int r2 = (++it)->u.operand;
999             out.printf("[%4d] get_argument_by_val\t %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1000             ++it;
1001             dumpValueProfiling(out, it, hasPrintedProfiling);
1002             break;
1003         }
1004         case op_get_by_pname: {
1005             int r0 = (++it)->u.operand;
1006             int r1 = (++it)->u.operand;
1007             int r2 = (++it)->u.operand;
1008             int r3 = (++it)->u.operand;
1009             int r4 = (++it)->u.operand;
1010             int r5 = (++it)->u.operand;
1011             out.printf("[%4d] get_by_pname\t %s, %s, %s, %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data(), registerName(r4).data(), registerName(r5).data());
1012             break;
1013         }
1014         case op_put_by_val: {
1015             int r0 = (++it)->u.operand;
1016             int r1 = (++it)->u.operand;
1017             int r2 = (++it)->u.operand;
1018             out.printf("[%4d] put_by_val\t %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1019             dumpArrayProfiling(out, it, hasPrintedProfiling);
1020             break;
1021         }
1022         case op_del_by_val: {
1023             int r0 = (++it)->u.operand;
1024             int r1 = (++it)->u.operand;
1025             int r2 = (++it)->u.operand;
1026             out.printf("[%4d] del_by_val\t %s, %s, %s", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1027             break;
1028         }
1029         case op_put_by_index: {
1030             int r0 = (++it)->u.operand;
1031             unsigned n0 = (++it)->u.operand;
1032             int r1 = (++it)->u.operand;
1033             out.printf("[%4d] put_by_index\t %s, %u, %s", location, registerName(r0).data(), n0, registerName(r1).data());
1034             break;
1035         }
1036         case op_jmp: {
1037             int offset = (++it)->u.operand;
1038             out.printf("[%4d] jmp\t\t %d(->%d)", location, offset, location + offset);
1039             break;
1040         }
1041         case op_jtrue: {
1042             printConditionalJump(out, exec, begin, it, location, "jtrue");
1043             break;
1044         }
1045         case op_jfalse: {
1046             printConditionalJump(out, exec, begin, it, location, "jfalse");
1047             break;
1048         }
1049         case op_jeq_null: {
1050             printConditionalJump(out, exec, begin, it, location, "jeq_null");
1051             break;
1052         }
1053         case op_jneq_null: {
1054             printConditionalJump(out, exec, begin, it, location, "jneq_null");
1055             break;
1056         }
1057         case op_jneq_ptr: {
1058             int r0 = (++it)->u.operand;
1059             Special::Pointer pointer = (++it)->u.specialPointer;
1060             int offset = (++it)->u.operand;
1061             out.printf("[%4d] jneq_ptr\t\t %s, %d (%p), %d(->%d)", location, registerName(r0).data(), pointer, m_globalObject->actualPointerFor(pointer), offset, location + offset);
1062             break;
1063         }
1064         case op_jless: {
1065             int r0 = (++it)->u.operand;
1066             int r1 = (++it)->u.operand;
1067             int offset = (++it)->u.operand;
1068             out.printf("[%4d] jless\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1069             break;
1070         }
1071         case op_jlesseq: {
1072             int r0 = (++it)->u.operand;
1073             int r1 = (++it)->u.operand;
1074             int offset = (++it)->u.operand;
1075             out.printf("[%4d] jlesseq\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1076             break;
1077         }
1078         case op_jgreater: {
1079             int r0 = (++it)->u.operand;
1080             int r1 = (++it)->u.operand;
1081             int offset = (++it)->u.operand;
1082             out.printf("[%4d] jgreater\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1083             break;
1084         }
1085         case op_jgreatereq: {
1086             int r0 = (++it)->u.operand;
1087             int r1 = (++it)->u.operand;
1088             int offset = (++it)->u.operand;
1089             out.printf("[%4d] jgreatereq\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1090             break;
1091         }
1092         case op_jnless: {
1093             int r0 = (++it)->u.operand;
1094             int r1 = (++it)->u.operand;
1095             int offset = (++it)->u.operand;
1096             out.printf("[%4d] jnless\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1097             break;
1098         }
1099         case op_jnlesseq: {
1100             int r0 = (++it)->u.operand;
1101             int r1 = (++it)->u.operand;
1102             int offset = (++it)->u.operand;
1103             out.printf("[%4d] jnlesseq\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1104             break;
1105         }
1106         case op_jngreater: {
1107             int r0 = (++it)->u.operand;
1108             int r1 = (++it)->u.operand;
1109             int offset = (++it)->u.operand;
1110             out.printf("[%4d] jngreater\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1111             break;
1112         }
1113         case op_jngreatereq: {
1114             int r0 = (++it)->u.operand;
1115             int r1 = (++it)->u.operand;
1116             int offset = (++it)->u.operand;
1117             out.printf("[%4d] jngreatereq\t\t %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1118             break;
1119         }
1120         case op_loop_hint: {
1121             out.printf("[%4d] loop_hint", location);
1122             break;
1123         }
1124         case op_switch_imm: {
1125             int tableIndex = (++it)->u.operand;
1126             int defaultTarget = (++it)->u.operand;
1127             int scrutineeRegister = (++it)->u.operand;
1128             out.printf("[%4d] switch_imm\t %d, %d(->%d), %s", location, tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1129             break;
1130         }
1131         case op_switch_char: {
1132             int tableIndex = (++it)->u.operand;
1133             int defaultTarget = (++it)->u.operand;
1134             int scrutineeRegister = (++it)->u.operand;
1135             out.printf("[%4d] switch_char\t %d, %d(->%d), %s", location, tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1136             break;
1137         }
1138         case op_switch_string: {
1139             int tableIndex = (++it)->u.operand;
1140             int defaultTarget = (++it)->u.operand;
1141             int scrutineeRegister = (++it)->u.operand;
1142             out.printf("[%4d] switch_string\t %d, %d(->%d), %s", location, tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1143             break;
1144         }
1145         case op_new_func: {
1146             int r0 = (++it)->u.operand;
1147             int f0 = (++it)->u.operand;
1148             int shouldCheck = (++it)->u.operand;
1149             out.printf("[%4d] new_func\t\t %s, f%d, %s", location, registerName(r0).data(), f0, shouldCheck ? "<Checked>" : "<Unchecked>");
1150             break;
1151         }
1152         case op_new_func_exp: {
1153             int r0 = (++it)->u.operand;
1154             int f0 = (++it)->u.operand;
1155             out.printf("[%4d] new_func_exp\t %s, f%d", location, registerName(r0).data(), f0);
1156             break;
1157         }
1158         case op_call: {
1159             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling);
1160             break;
1161         }
1162         case op_call_eval: {
1163             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling);
1164             break;
1165         }
1166         case op_call_varargs: {
1167             int result = (++it)->u.operand;
1168             int callee = (++it)->u.operand;
1169             int thisValue = (++it)->u.operand;
1170             int arguments = (++it)->u.operand;
1171             int firstFreeRegister = (++it)->u.operand;
1172             ++it;
1173             out.printf("[%4d] call_varargs\t %s, %s, %s, %s, %d", location, registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister);
1174             dumpValueProfiling(out, it, hasPrintedProfiling);
1175             break;
1176         }
1177         case op_tear_off_activation: {
1178             int r0 = (++it)->u.operand;
1179             out.printf("[%4d] tear_off_activation\t %s", location, registerName(r0).data());
1180             break;
1181         }
1182         case op_tear_off_arguments: {
1183             int r0 = (++it)->u.operand;
1184             int r1 = (++it)->u.operand;
1185             out.printf("[%4d] tear_off_arguments %s, %s", location, registerName(r0).data(), registerName(r1).data());
1186             break;
1187         }
1188         case op_ret: {
1189             int r0 = (++it)->u.operand;
1190             out.printf("[%4d] ret\t\t %s", location, registerName(r0).data());
1191             break;
1192         }
1193         case op_ret_object_or_this: {
1194             int r0 = (++it)->u.operand;
1195             int r1 = (++it)->u.operand;
1196             out.printf("[%4d] constructor_ret\t\t %s %s", location, registerName(r0).data(), registerName(r1).data());
1197             break;
1198         }
1199         case op_construct: {
1200             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling);
1201             break;
1202         }
1203         case op_strcat: {
1204             int r0 = (++it)->u.operand;
1205             int r1 = (++it)->u.operand;
1206             int count = (++it)->u.operand;
1207             out.printf("[%4d] strcat\t\t %s, %s, %d", location, registerName(r0).data(), registerName(r1).data(), count);
1208             break;
1209         }
1210         case op_to_primitive: {
1211             int r0 = (++it)->u.operand;
1212             int r1 = (++it)->u.operand;
1213             out.printf("[%4d] to_primitive\t %s, %s", location, registerName(r0).data(), registerName(r1).data());
1214             break;
1215         }
1216         case op_get_pnames: {
1217             int r0 = it[1].u.operand;
1218             int r1 = it[2].u.operand;
1219             int r2 = it[3].u.operand;
1220             int r3 = it[4].u.operand;
1221             int offset = it[5].u.operand;
1222             out.printf("[%4d] get_pnames\t %s, %s, %s, %s, %d(->%d)", location, registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), registerName(r3).data(), offset, location + offset);
1223             it += OPCODE_LENGTH(op_get_pnames) - 1;
1224             break;
1225         }
1226         case op_next_pname: {
1227             int dest = it[1].u.operand;
1228             int base = it[2].u.operand;
1229             int i = it[3].u.operand;
1230             int size = it[4].u.operand;
1231             int iter = it[5].u.operand;
1232             int offset = it[6].u.operand;
1233             out.printf("[%4d] next_pname\t %s, %s, %s, %s, %s, %d(->%d)", location, registerName(dest).data(), registerName(base).data(), registerName(i).data(), registerName(size).data(), registerName(iter).data(), offset, location + offset);
1234             it += OPCODE_LENGTH(op_next_pname) - 1;
1235             break;
1236         }
1237         case op_push_with_scope: {
1238             int r0 = (++it)->u.operand;
1239             out.printf("[%4d] push_with_scope\t %s", location, registerName(r0).data());
1240             break;
1241         }
1242         case op_pop_scope: {
1243             out.printf("[%4d] pop_scope", location);
1244             break;
1245         }
1246         case op_push_name_scope: {
1247             int id0 = (++it)->u.operand;
1248             int r1 = (++it)->u.operand;
1249             unsigned attributes = (++it)->u.operand;
1250             out.printf("[%4d] push_name_scope \t%s, %s, %u", location, idName(id0, identifier(id0)).data(), registerName(r1).data(), attributes);
1251             break;
1252         }
1253         case op_catch: {
1254             int r0 = (++it)->u.operand;
1255             out.printf("[%4d] catch\t\t %s", location, registerName(r0).data());
1256             break;
1257         }
1258         case op_throw: {
1259             int r0 = (++it)->u.operand;
1260             out.printf("[%4d] throw\t\t %s", location, registerName(r0).data());
1261             break;
1262         }
1263         case op_throw_static_error: {
1264             int k0 = (++it)->u.operand;
1265             int k1 = (++it)->u.operand;
1266             out.printf("[%4d] throw_static_error\t %s, %s", location, constantName(k0, getConstant(k0)).data(), k1 ? "true" : "false");
1267             break;
1268         }
1269         case op_debug: {
1270             int debugHookID = (++it)->u.operand;
1271             int firstLine = (++it)->u.operand;
1272             int lastLine = (++it)->u.operand;
1273             int column = (++it)->u.operand;
1274             out.printf("[%4d] debug\t\t %s, %d, %d, %d", location, debugHookName(debugHookID), firstLine, lastLine, column);
1275             break;
1276         }
1277         case op_profile_will_call: {
1278             int function = (++it)->u.operand;
1279             out.printf("[%4d] profile_will_call %s", location, registerName(function).data());
1280             break;
1281         }
1282         case op_profile_did_call: {
1283             int function = (++it)->u.operand;
1284             out.printf("[%4d] profile_did_call\t %s", location, registerName(function).data());
1285             break;
1286         }
1287         case op_end: {
1288             int r0 = (++it)->u.operand;
1289             out.printf("[%4d] end\t\t %s", location, registerName(r0).data());
1290             break;
1291         }
1292         case op_resolve_scope: {
1293             int r0 = (++it)->u.operand;
1294             int id0 = (++it)->u.operand;
1295             int resolveModeAndType = (++it)->u.operand;
1296             ++it; // depth
1297             out.printf("[%4d] resolve_scope\t %s, %s, %d", location, registerName(r0).data(), idName(id0, identifier(id0)).data(), resolveModeAndType);
1298             break;
1299         }
1300         case op_get_from_scope: {
1301             int r0 = (++it)->u.operand;
1302             int r1 = (++it)->u.operand;
1303             int id0 = (++it)->u.operand;
1304             int resolveModeAndType = (++it)->u.operand;
1305             ++it; // Structure
1306             ++it; // Operand
1307             ++it; // Skip value profile.
1308             out.printf("[%4d] get_from_scope\t %s, %s, %s, %d", location, registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data(), resolveModeAndType);
1309             break;
1310         }
1311         case op_put_to_scope: {
1312             int r0 = (++it)->u.operand;
1313             int id0 = (++it)->u.operand;
1314             int r1 = (++it)->u.operand;
1315             int resolveModeAndType = (++it)->u.operand;
1316             ++it; // Structure
1317             ++it; // Operand
1318             out.printf("[%4d] put_to_scope\t %s, %s, %s, %d", location, registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data(), resolveModeAndType);
1319             break;
1320         }
1321 #if ENABLE(LLINT_C_LOOP)
1322         default:
1323             RELEASE_ASSERT_NOT_REACHED();
1324 #endif
1325     }
1326
1327 #if ENABLE(VALUE_PROFILER)
1328     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1329     dumpRareCaseProfile(out, "special fast case: ", specialFastCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1330 #endif
1331     
1332 #if ENABLE(DFG_JIT)
1333     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1334     if (!exitSites.isEmpty()) {
1335         out.print(" !! frequent exits: ");
1336         CommaPrinter comma;
1337         for (unsigned i = 0; i < exitSites.size(); ++i)
1338             out.print(comma, exitSites[i].kind());
1339     }
1340 #else // ENABLE(DFG_JIT)
1341     UNUSED_PARAM(location);
1342 #endif // ENABLE(DFG_JIT)
1343     out.print("\n");
1344 }
1345
1346 void CodeBlock::dumpBytecode(PrintStream& out, unsigned bytecodeOffset)
1347 {
1348     ExecState* exec = m_globalObject->globalExec();
1349     const Instruction* it = instructions().begin() + bytecodeOffset;
1350     dumpBytecode(out, exec, instructions().begin(), it);
1351 }
1352
1353 #if DUMP_CODE_BLOCK_STATISTICS
1354 static HashSet<CodeBlock*> liveCodeBlockSet;
1355 #endif
1356
1357 #define FOR_EACH_MEMBER_VECTOR(macro) \
1358     macro(instructions) \
1359     macro(structureStubInfos) \
1360     macro(callLinkInfos) \
1361     macro(linkedCallerList) \
1362     macro(identifiers) \
1363     macro(functionExpressions) \
1364     macro(constantRegisters)
1365
1366 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1367     macro(regexps) \
1368     macro(functions) \
1369     macro(exceptionHandlers) \
1370     macro(switchJumpTables) \
1371     macro(stringSwitchJumpTables) \
1372     macro(evalCodeCache) \
1373     macro(expressionInfo) \
1374     macro(lineInfo) \
1375     macro(callReturnIndexVector)
1376
1377 template<typename T>
1378 static size_t sizeInBytes(const Vector<T>& vector)
1379 {
1380     return vector.capacity() * sizeof(T);
1381 }
1382
1383 void CodeBlock::dumpStatistics()
1384 {
1385 #if DUMP_CODE_BLOCK_STATISTICS
1386     #define DEFINE_VARS(name) size_t name##IsNotEmpty = 0; size_t name##TotalSize = 0;
1387         FOR_EACH_MEMBER_VECTOR(DEFINE_VARS)
1388         FOR_EACH_MEMBER_VECTOR_RARE_DATA(DEFINE_VARS)
1389     #undef DEFINE_VARS
1390
1391     // Non-vector data members
1392     size_t evalCodeCacheIsNotEmpty = 0;
1393
1394     size_t symbolTableIsNotEmpty = 0;
1395     size_t symbolTableTotalSize = 0;
1396
1397     size_t hasRareData = 0;
1398
1399     size_t isFunctionCode = 0;
1400     size_t isGlobalCode = 0;
1401     size_t isEvalCode = 0;
1402
1403     HashSet<CodeBlock*>::const_iterator end = liveCodeBlockSet.end();
1404     for (HashSet<CodeBlock*>::const_iterator it = liveCodeBlockSet.begin(); it != end; ++it) {
1405         CodeBlock* codeBlock = *it;
1406
1407         #define GET_STATS(name) if (!codeBlock->m_##name.isEmpty()) { name##IsNotEmpty++; name##TotalSize += sizeInBytes(codeBlock->m_##name); }
1408             FOR_EACH_MEMBER_VECTOR(GET_STATS)
1409         #undef GET_STATS
1410
1411         if (codeBlock->symbolTable() && !codeBlock->symbolTable()->isEmpty()) {
1412             symbolTableIsNotEmpty++;
1413             symbolTableTotalSize += (codeBlock->symbolTable()->capacity() * (sizeof(SymbolTable::KeyType) + sizeof(SymbolTable::MappedType)));
1414         }
1415
1416         if (codeBlock->m_rareData) {
1417             hasRareData++;
1418             #define GET_STATS(name) if (!codeBlock->m_rareData->m_##name.isEmpty()) { name##IsNotEmpty++; name##TotalSize += sizeInBytes(codeBlock->m_rareData->m_##name); }
1419                 FOR_EACH_MEMBER_VECTOR_RARE_DATA(GET_STATS)
1420             #undef GET_STATS
1421
1422             if (!codeBlock->m_rareData->m_evalCodeCache.isEmpty())
1423                 evalCodeCacheIsNotEmpty++;
1424         }
1425
1426         switch (codeBlock->codeType()) {
1427             case FunctionCode:
1428                 ++isFunctionCode;
1429                 break;
1430             case GlobalCode:
1431                 ++isGlobalCode;
1432                 break;
1433             case EvalCode:
1434                 ++isEvalCode;
1435                 break;
1436         }
1437     }
1438
1439     size_t totalSize = 0;
1440
1441     #define GET_TOTAL_SIZE(name) totalSize += name##TotalSize;
1442         FOR_EACH_MEMBER_VECTOR(GET_TOTAL_SIZE)
1443         FOR_EACH_MEMBER_VECTOR_RARE_DATA(GET_TOTAL_SIZE)
1444     #undef GET_TOTAL_SIZE
1445
1446     totalSize += symbolTableTotalSize;
1447     totalSize += (liveCodeBlockSet.size() * sizeof(CodeBlock));
1448
1449     dataLogF("Number of live CodeBlocks: %d\n", liveCodeBlockSet.size());
1450     dataLogF("Size of a single CodeBlock [sizeof(CodeBlock)]: %zu\n", sizeof(CodeBlock));
1451     dataLogF("Size of all CodeBlocks: %zu\n", totalSize);
1452     dataLogF("Average size of a CodeBlock: %zu\n", totalSize / liveCodeBlockSet.size());
1453
1454     dataLogF("Number of FunctionCode CodeBlocks: %zu (%.3f%%)\n", isFunctionCode, static_cast<double>(isFunctionCode) * 100.0 / liveCodeBlockSet.size());
1455     dataLogF("Number of GlobalCode CodeBlocks: %zu (%.3f%%)\n", isGlobalCode, static_cast<double>(isGlobalCode) * 100.0 / liveCodeBlockSet.size());
1456     dataLogF("Number of EvalCode CodeBlocks: %zu (%.3f%%)\n", isEvalCode, static_cast<double>(isEvalCode) * 100.0 / liveCodeBlockSet.size());
1457
1458     dataLogF("Number of CodeBlocks with rare data: %zu (%.3f%%)\n", hasRareData, static_cast<double>(hasRareData) * 100.0 / liveCodeBlockSet.size());
1459
1460     #define PRINT_STATS(name) dataLogF("Number of CodeBlocks with " #name ": %zu\n", name##IsNotEmpty); dataLogF("Size of all " #name ": %zu\n", name##TotalSize); 
1461         FOR_EACH_MEMBER_VECTOR(PRINT_STATS)
1462         FOR_EACH_MEMBER_VECTOR_RARE_DATA(PRINT_STATS)
1463     #undef PRINT_STATS
1464
1465     dataLogF("Number of CodeBlocks with evalCodeCache: %zu\n", evalCodeCacheIsNotEmpty);
1466     dataLogF("Number of CodeBlocks with symbolTable: %zu\n", symbolTableIsNotEmpty);
1467
1468     dataLogF("Size of all symbolTables: %zu\n", symbolTableTotalSize);
1469
1470 #else
1471     dataLogF("Dumping CodeBlock statistics is not enabled.\n");
1472 #endif
1473 }
1474
1475 CodeBlock::CodeBlock(CopyParsedBlockTag, CodeBlock& other)
1476     : m_globalObject(other.m_globalObject)
1477     , m_heap(other.m_heap)
1478     , m_numCalleeRegisters(other.m_numCalleeRegisters)
1479     , m_numVars(other.m_numVars)
1480     , m_isConstructor(other.m_isConstructor)
1481     , m_shouldAlwaysBeInlined(true)
1482     , m_didFailFTLCompilation(false)
1483     , m_unlinkedCode(*other.m_vm, other.m_ownerExecutable.get(), other.m_unlinkedCode.get())
1484     , m_ownerExecutable(*other.m_vm, other.m_ownerExecutable.get(), other.m_ownerExecutable.get())
1485     , m_vm(other.m_vm)
1486     , m_instructions(other.m_instructions)
1487     , m_thisRegister(other.m_thisRegister)
1488     , m_argumentsRegister(other.m_argumentsRegister)
1489     , m_activationRegister(other.m_activationRegister)
1490     , m_isStrictMode(other.m_isStrictMode)
1491     , m_needsActivation(other.m_needsActivation)
1492     , m_source(other.m_source)
1493     , m_sourceOffset(other.m_sourceOffset)
1494     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1495     , m_codeType(other.m_codeType)
1496     , m_additionalIdentifiers(other.m_additionalIdentifiers)
1497     , m_constantRegisters(other.m_constantRegisters)
1498     , m_functionDecls(other.m_functionDecls)
1499     , m_functionExprs(other.m_functionExprs)
1500     , m_osrExitCounter(0)
1501     , m_optimizationDelayCounter(0)
1502     , m_reoptimizationRetryCounter(0)
1503     , m_hash(other.m_hash)
1504 #if ENABLE(JIT)
1505     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1506 #endif
1507 {
1508     ASSERT(m_heap->isDeferred());
1509     setNumParameters(other.numParameters());
1510     optimizeAfterWarmUp();
1511     jitAfterWarmUp();
1512
1513     if (other.m_rareData) {
1514         createRareDataIfNecessary();
1515         
1516         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1517         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1518         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1519         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1520     }
1521     
1522     m_heap->m_codeBlocks.add(this);
1523     m_heap->reportExtraMemoryCost(sizeof(CodeBlock));
1524 }
1525
1526 CodeBlock::CodeBlock(ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1527     : m_globalObject(scope->globalObject()->vm(), ownerExecutable, scope->globalObject())
1528     , m_heap(&m_globalObject->vm().heap)
1529     , m_numCalleeRegisters(unlinkedCodeBlock->m_numCalleeRegisters)
1530     , m_numVars(unlinkedCodeBlock->m_numVars)
1531     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1532     , m_shouldAlwaysBeInlined(true)
1533     , m_didFailFTLCompilation(false)
1534     , m_unlinkedCode(m_globalObject->vm(), ownerExecutable, unlinkedCodeBlock)
1535     , m_ownerExecutable(m_globalObject->vm(), ownerExecutable, ownerExecutable)
1536     , m_vm(unlinkedCodeBlock->vm())
1537     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1538     , m_argumentsRegister(unlinkedCodeBlock->argumentsRegister())
1539     , m_activationRegister(unlinkedCodeBlock->activationRegister())
1540     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1541     , m_needsActivation(unlinkedCodeBlock->needsFullScopeChain() && unlinkedCodeBlock->codeType() == FunctionCode)
1542     , m_source(sourceProvider)
1543     , m_sourceOffset(sourceOffset)
1544     , m_firstLineColumnOffset(firstLineColumnOffset)
1545     , m_codeType(unlinkedCodeBlock->codeType())
1546     , m_osrExitCounter(0)
1547     , m_optimizationDelayCounter(0)
1548     , m_reoptimizationRetryCounter(0)
1549 #if ENABLE(JIT)
1550     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1551 #endif
1552 {
1553     ASSERT(m_heap->isDeferred());
1554
1555     ASSERT(m_source);
1556     setNumParameters(unlinkedCodeBlock->numParameters());
1557
1558 #if DUMP_CODE_BLOCK_STATISTICS
1559     liveCodeBlockSet.add(this);
1560 #endif
1561
1562     setConstantRegisters(unlinkedCodeBlock->constantRegisters());
1563     if (unlinkedCodeBlock->usesGlobalObject())
1564         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister()].set(*m_vm, ownerExecutable, m_globalObject.get());
1565     m_functionDecls.grow(unlinkedCodeBlock->numberOfFunctionDecls());
1566     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1567         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1568         unsigned lineCount = unlinkedExecutable->lineCount();
1569         unsigned firstLine = ownerExecutable->lineNo() + unlinkedExecutable->firstLineOffset();
1570         unsigned startColumn = unlinkedExecutable->functionStartColumn();
1571         startColumn += (unlinkedExecutable->firstLineOffset() ? 1 : ownerExecutable->startColumn());
1572         unsigned startOffset = sourceOffset + unlinkedExecutable->startOffset();
1573         unsigned sourceLength = unlinkedExecutable->sourceLength();
1574         SourceCode code(m_source, startOffset, startOffset + sourceLength, firstLine, startColumn);
1575         FunctionExecutable* executable = FunctionExecutable::create(*m_vm, code, unlinkedExecutable, firstLine, firstLine + lineCount, startColumn);
1576         m_functionDecls[i].set(*m_vm, ownerExecutable, executable);
1577     }
1578
1579     m_functionExprs.grow(unlinkedCodeBlock->numberOfFunctionExprs());
1580     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1581         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1582         unsigned lineCount = unlinkedExecutable->lineCount();
1583         unsigned firstLine = ownerExecutable->lineNo() + unlinkedExecutable->firstLineOffset();
1584         unsigned startColumn = unlinkedExecutable->functionStartColumn();
1585         startColumn += (unlinkedExecutable->firstLineOffset() ? 1 : ownerExecutable->startColumn());
1586         unsigned startOffset = sourceOffset + unlinkedExecutable->startOffset();
1587         unsigned sourceLength = unlinkedExecutable->sourceLength();
1588         SourceCode code(m_source, startOffset, startOffset + sourceLength, firstLine, startColumn);
1589         FunctionExecutable* executable = FunctionExecutable::create(*m_vm, code, unlinkedExecutable, firstLine, firstLine + lineCount, startColumn);
1590         m_functionExprs[i].set(*m_vm, ownerExecutable, executable);
1591     }
1592
1593     if (unlinkedCodeBlock->hasRareData()) {
1594         createRareDataIfNecessary();
1595         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1596             m_rareData->m_constantBuffers.grow(count);
1597             for (size_t i = 0; i < count; i++) {
1598                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1599                 m_rareData->m_constantBuffers[i] = buffer;
1600             }
1601         }
1602         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1603             m_rareData->m_exceptionHandlers.grow(count);
1604             size_t nonLocalScopeDepth = scope->depth();
1605             for (size_t i = 0; i < count; i++) {
1606                 const UnlinkedHandlerInfo& handler = unlinkedCodeBlock->exceptionHandler(i);
1607                 m_rareData->m_exceptionHandlers[i].start = handler.start;
1608                 m_rareData->m_exceptionHandlers[i].end = handler.end;
1609                 m_rareData->m_exceptionHandlers[i].target = handler.target;
1610                 m_rareData->m_exceptionHandlers[i].scopeDepth = nonLocalScopeDepth + handler.scopeDepth;
1611 #if ENABLE(JIT) && ENABLE(LLINT)
1612                 m_rareData->m_exceptionHandlers[i].nativeCode = CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(llint_op_catch)));
1613 #endif
1614             }
1615         }
1616
1617         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
1618             m_rareData->m_stringSwitchJumpTables.grow(count);
1619             for (size_t i = 0; i < count; i++) {
1620                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
1621                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
1622                 for (; ptr != end; ++ptr) {
1623                     OffsetLocation offset;
1624                     offset.branchOffset = ptr->value;
1625                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
1626                 }
1627             }
1628         }
1629
1630         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
1631             m_rareData->m_switchJumpTables.grow(count);
1632             for (size_t i = 0; i < count; i++) {
1633                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
1634                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
1635                 destTable.branchOffsets = sourceTable.branchOffsets;
1636                 destTable.min = sourceTable.min;
1637             }
1638         }
1639     }
1640
1641     // Allocate metadata buffers for the bytecode
1642 #if ENABLE(LLINT)
1643     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
1644         m_llintCallLinkInfos.resizeToFit(size);
1645 #endif
1646 #if ENABLE(DFG_JIT)
1647     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
1648         m_arrayProfiles.grow(size);
1649     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
1650         m_arrayAllocationProfiles.grow(size);
1651     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
1652         m_valueProfiles.grow(size);
1653 #endif
1654     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
1655         m_objectAllocationProfiles.grow(size);
1656
1657     // Copy and translate the UnlinkedInstructions
1658     size_t instructionCount = unlinkedCodeBlock->instructions().size();
1659     UnlinkedInstruction* pc = unlinkedCodeBlock->instructions().data();
1660     Vector<Instruction, 0, UnsafeVectorOverflow> instructions(instructionCount);
1661     for (size_t i = 0; i < unlinkedCodeBlock->instructions().size(); ) {
1662         unsigned opLength = opcodeLength(pc[i].u.opcode);
1663         instructions[i] = vm()->interpreter->getOpcode(pc[i].u.opcode);
1664         for (size_t j = 1; j < opLength; ++j) {
1665             if (sizeof(int32_t) != sizeof(intptr_t))
1666                 instructions[i + j].u.pointer = 0;
1667             instructions[i + j].u.operand = pc[i + j].u.operand;
1668         }
1669         switch (pc[i].u.opcode) {
1670 #if ENABLE(DFG_JIT)
1671         case op_get_by_val:
1672         case op_get_argument_by_val: {
1673             int arrayProfileIndex = pc[i + opLength - 2].u.operand;
1674             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1675
1676             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1677             // fallthrough
1678         }
1679         case op_to_this:
1680         case op_get_by_id:
1681         case op_call_varargs:
1682         case op_get_callee: {
1683             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1684             ASSERT(profile->m_bytecodeOffset == -1);
1685             profile->m_bytecodeOffset = i;
1686             instructions[i + opLength - 1] = profile;
1687             break;
1688         }
1689         case op_put_by_val: {
1690             int arrayProfileIndex = pc[i + opLength - 1].u.operand;
1691             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1692             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1693             break;
1694         }
1695
1696         case op_new_array:
1697         case op_new_array_buffer:
1698         case op_new_array_with_size: {
1699             int arrayAllocationProfileIndex = pc[i + opLength - 1].u.operand;
1700             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
1701             break;
1702         }
1703 #endif
1704         case op_new_object: {
1705             int objectAllocationProfileIndex = pc[i + opLength - 1].u.operand;
1706             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
1707             int inferredInlineCapacity = pc[i + opLength - 2].u.operand;
1708
1709             instructions[i + opLength - 1] = objectAllocationProfile;
1710             objectAllocationProfile->initialize(*vm(),
1711                 m_ownerExecutable.get(), m_globalObject->objectPrototype(), inferredInlineCapacity);
1712             break;
1713         }
1714
1715         case op_call:
1716         case op_call_eval: {
1717 #if ENABLE(DFG_JIT)
1718             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1719             ASSERT(profile->m_bytecodeOffset == -1);
1720             profile->m_bytecodeOffset = i;
1721             instructions[i + opLength - 1] = profile;
1722             int arrayProfileIndex = pc[i + opLength - 2].u.operand;
1723             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1724             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1725 #endif
1726 #if ENABLE(LLINT)
1727             instructions[i + 5] = &m_llintCallLinkInfos[pc[i + 5].u.operand];
1728 #endif
1729             break;
1730         }
1731         case op_construct: {
1732 #if ENABLE(LLINT)
1733             instructions[i + 5] = &m_llintCallLinkInfos[pc[i + 5].u.operand];
1734 #endif
1735 #if ENABLE(DFG_JIT)
1736             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1737             ASSERT(profile->m_bytecodeOffset == -1);
1738             profile->m_bytecodeOffset = i;
1739             instructions[i + opLength - 1] = profile;
1740 #endif
1741             break;
1742         }
1743         case op_get_by_id_out_of_line:
1744         case op_get_by_id_self:
1745         case op_get_by_id_proto:
1746         case op_get_by_id_chain:
1747         case op_get_by_id_getter_self:
1748         case op_get_by_id_getter_proto:
1749         case op_get_by_id_getter_chain:
1750         case op_get_by_id_custom_self:
1751         case op_get_by_id_custom_proto:
1752         case op_get_by_id_custom_chain:
1753         case op_get_by_id_generic:
1754         case op_get_array_length:
1755         case op_get_string_length:
1756             CRASH();
1757
1758         case op_init_global_const_nop: {
1759             ASSERT(codeType() == GlobalCode);
1760             Identifier ident = identifier(pc[i + 4].u.operand);
1761             SymbolTableEntry entry = m_globalObject->symbolTable()->get(ident.impl());
1762             if (entry.isNull())
1763                 break;
1764
1765             // It's likely that we'll write to this var, so notify now and avoid the overhead of doing so at runtime.
1766             entry.notifyWrite();
1767
1768             instructions[i + 0] = vm()->interpreter->getOpcode(op_init_global_const);
1769             instructions[i + 1] = &m_globalObject->registerAt(entry.getIndex());
1770             break;
1771         }
1772
1773         case op_resolve_scope: {
1774             const Identifier& ident = identifier(pc[i + 2].u.operand);
1775             ResolveType type = static_cast<ResolveType>(pc[i + 3].u.operand);
1776
1777             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), scope, ident, Get, type);
1778             instructions[i + 3].u.operand = op.type;
1779             instructions[i + 4].u.operand = op.depth;
1780             break;
1781         }
1782
1783         case op_get_from_scope: {
1784 #if ENABLE(VALUE_PROFILER)
1785             ValueProfile* profile = &m_valueProfiles[pc[i + opLength - 1].u.operand];
1786             ASSERT(profile->m_bytecodeOffset == -1);
1787             profile->m_bytecodeOffset = i;
1788             instructions[i + opLength - 1] = profile;
1789 #endif
1790
1791             // get_from_scope dst, scope, id, ResolveModeAndType, Structure, Operand
1792             const Identifier& ident = identifier(pc[i + 3].u.operand);
1793             ResolveModeAndType modeAndType = ResolveModeAndType(pc[i + 4].u.operand);
1794             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), scope, ident, Get, modeAndType.type());
1795
1796             instructions[i + 4].u.operand = ResolveModeAndType(modeAndType.mode(), op.type).operand();
1797             if (op.structure)
1798                 instructions[i + 5].u.structure.set(*vm(), ownerExecutable, op.structure);
1799             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
1800             break;
1801         }
1802
1803         case op_put_to_scope: {
1804             // put_to_scope scope, id, value, ResolveModeAndType, Structure, Operand
1805             const Identifier& ident = identifier(pc[i + 2].u.operand);
1806             ResolveModeAndType modeAndType = ResolveModeAndType(pc[i + 4].u.operand);
1807             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), scope, ident, Put, modeAndType.type());
1808
1809             instructions[i + 4].u.operand = ResolveModeAndType(modeAndType.mode(), op.type).operand();
1810             if (op.structure)
1811                 instructions[i + 5].u.structure.set(*vm(), ownerExecutable, op.structure);
1812             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
1813             break;
1814         }
1815
1816         case op_debug: {
1817             instructions[i + 4] = columnNumberForBytecodeOffset(i);
1818             break;
1819         }
1820
1821         default:
1822             break;
1823         }
1824         i += opLength;
1825     }
1826     m_instructions = WTF::RefCountedArray<Instruction>(instructions);
1827
1828     // Set optimization thresholds only after m_instructions is initialized, since these
1829     // rely on the instruction count (and are in theory permitted to also inspect the
1830     // instruction stream to more accurate assess the cost of tier-up).
1831     optimizeAfterWarmUp();
1832     jitAfterWarmUp();
1833
1834     // If the concurrent thread will want the code block's hash, then compute it here
1835     // synchronously.
1836     if (Options::showDisassembly()
1837         || Options::showDFGDisassembly()
1838         || Options::dumpBytecodeAtDFGTime()
1839         || Options::verboseCompilation()
1840         || Options::logCompilationChanges()
1841         || Options::validateGraph()
1842         || Options::validateGraphAtEachPhase()
1843         || Options::verboseOSR()
1844         || Options::verboseCompilationQueue()
1845         || Options::reportCompileTimes()
1846         || Options::verboseCFA())
1847         hash();
1848
1849     if (Options::dumpGeneratedBytecodes())
1850         dumpBytecode();
1851     m_heap->m_codeBlocks.add(this);
1852     m_heap->reportExtraMemoryCost(sizeof(CodeBlock) + m_instructions.size() * sizeof(Instruction));
1853 }
1854
1855 CodeBlock::~CodeBlock()
1856 {
1857     if (m_vm->m_perBytecodeProfiler)
1858         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
1859     
1860 #if ENABLE(VERBOSE_VALUE_PROFILE)
1861     dumpValueProfiles();
1862 #endif
1863
1864 #if ENABLE(LLINT)    
1865     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1866         m_incomingLLIntCalls.begin()->remove();
1867 #endif // ENABLE(LLINT)
1868 #if ENABLE(JIT)
1869     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
1870     // Consider that two CodeBlocks become unreachable at the same time. There
1871     // is no guarantee about the order in which the CodeBlocks are destroyed.
1872     // So, if we don't remove incoming calls, and get destroyed before the
1873     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
1874     // destructor will try to remove nodes from our (no longer valid) linked list.
1875     while (m_incomingCalls.begin() != m_incomingCalls.end())
1876         m_incomingCalls.begin()->remove();
1877     
1878     // Note that our outgoing calls will be removed from other CodeBlocks'
1879     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
1880     // destructors.
1881
1882     for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i)
1883         m_structureStubInfos[i].deref();
1884 #endif // ENABLE(JIT)
1885
1886 #if DUMP_CODE_BLOCK_STATISTICS
1887     liveCodeBlockSet.remove(this);
1888 #endif
1889 }
1890
1891 void CodeBlock::setNumParameters(int newValue)
1892 {
1893     m_numParameters = newValue;
1894
1895 #if ENABLE(VALUE_PROFILER)
1896     m_argumentValueProfiles.resizeToFit(newValue);
1897 #endif
1898 }
1899
1900 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
1901 {
1902     EvalCacheMap::iterator end = m_cacheMap.end();
1903     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
1904         visitor.append(&ptr->value);
1905 }
1906
1907 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
1908 {
1909 #if ENABLE(FTL_JIT)
1910     if (jitType() != JITCode::DFGJIT)
1911         return 0;
1912     DFG::JITCode* jitCode = m_jitCode->dfg();
1913     return jitCode->osrEntryBlock.get();
1914 #else // ENABLE(FTL_JIT)
1915     return 0;
1916 #endif // ENABLE(FTL_JIT)
1917 }
1918
1919 void CodeBlock::visitAggregate(SlotVisitor& visitor)
1920 {
1921 #if ENABLE(PARALLEL_GC)
1922     // I may be asked to scan myself more than once, and it may even happen concurrently.
1923     // To this end, use a CAS loop to check if I've been called already. Only one thread
1924     // may proceed past this point - whichever one wins the CAS race.
1925     unsigned oldValue;
1926     do {
1927         oldValue = m_visitAggregateHasBeenCalled;
1928         if (oldValue) {
1929             // Looks like someone else won! Return immediately to ensure that we don't
1930             // trace the same CodeBlock concurrently. Doing so is hazardous since we will
1931             // be mutating the state of ValueProfiles, which contain JSValues, which can
1932             // have word-tearing on 32-bit, leading to awesome timing-dependent crashes
1933             // that are nearly impossible to track down.
1934             
1935             // Also note that it must be safe to return early as soon as we see the
1936             // value true (well, (unsigned)1), since once a GC thread is in this method
1937             // and has won the CAS race (i.e. was responsible for setting the value true)
1938             // it will definitely complete the rest of this method before declaring
1939             // termination.
1940             return;
1941         }
1942     } while (!WTF::weakCompareAndSwap(&m_visitAggregateHasBeenCalled, 0, 1));
1943 #endif // ENABLE(PARALLEL_GC)
1944     
1945     if (!!m_alternative)
1946         m_alternative->visitAggregate(visitor);
1947     
1948     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
1949         otherBlock->visitAggregate(visitor);
1950
1951     visitor.reportExtraMemoryUsage(sizeof(CodeBlock));
1952     if (m_jitCode)
1953         visitor.reportExtraMemoryUsage(m_jitCode->size());
1954     if (m_instructions.size()) {
1955         // Divide by refCount() because m_instructions points to something that is shared
1956         // by multiple CodeBlocks, and we only want to count it towards the heap size once.
1957         // Having each CodeBlock report only its proportional share of the size is one way
1958         // of accomplishing this.
1959         visitor.reportExtraMemoryUsage(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
1960     }
1961
1962     visitor.append(&m_unlinkedCode);
1963
1964     // There are three things that may use unconditional finalizers: lazy bytecode freeing,
1965     // inline cache clearing, and jettisoning. The probability of us wanting to do at
1966     // least one of those things is probably quite close to 1. So we add one no matter what
1967     // and when it runs, it figures out whether it has any work to do.
1968     visitor.addUnconditionalFinalizer(this);
1969     
1970     // There are two things that we use weak reference harvesters for: DFG fixpoint for
1971     // jettisoning, and trying to find structures that would be live based on some
1972     // inline cache. So it makes sense to register them regardless.
1973     visitor.addWeakReferenceHarvester(this);
1974     m_allTransitionsHaveBeenMarked = false;
1975     
1976     if (shouldImmediatelyAssumeLivenessDuringScan()) {
1977         // This code block is live, so scan all references strongly and return.
1978         stronglyVisitStrongReferences(visitor);
1979         stronglyVisitWeakReferences(visitor);
1980         propagateTransitions(visitor);
1981         return;
1982     }
1983     
1984 #if ENABLE(DFG_JIT)
1985     // We get here if we're live in the sense that our owner executable is live,
1986     // but we're not yet live for sure in another sense: we may yet decide that this
1987     // code block should be jettisoned based on its outgoing weak references being
1988     // stale. Set a flag to indicate that we're still assuming that we're dead, and
1989     // perform one round of determining if we're live. The GC may determine, based on
1990     // either us marking additional objects, or by other objects being marked for
1991     // other reasons, that this iteration should run again; it will notify us of this
1992     // decision by calling harvestWeakReferences().
1993     
1994     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
1995     
1996     propagateTransitions(visitor);
1997     determineLiveness(visitor);
1998 #else // ENABLE(DFG_JIT)
1999     RELEASE_ASSERT_NOT_REACHED();
2000 #endif // ENABLE(DFG_JIT)
2001 }
2002
2003 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2004 {
2005     UNUSED_PARAM(visitor);
2006
2007     if (m_allTransitionsHaveBeenMarked)
2008         return;
2009
2010     bool allAreMarkedSoFar = true;
2011         
2012 #if ENABLE(LLINT)
2013     Interpreter* interpreter = m_vm->interpreter;
2014     if (jitType() == JITCode::InterpreterThunk) {
2015         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2016         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2017             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2018             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2019             case op_put_by_id_transition_direct:
2020             case op_put_by_id_transition_normal:
2021             case op_put_by_id_transition_direct_out_of_line:
2022             case op_put_by_id_transition_normal_out_of_line: {
2023                 if (Heap::isMarked(instruction[4].u.structure.get()))
2024                     visitor.append(&instruction[6].u.structure);
2025                 else
2026                     allAreMarkedSoFar = false;
2027                 break;
2028             }
2029             default:
2030                 break;
2031             }
2032         }
2033     }
2034 #endif // ENABLE(LLINT)
2035
2036 #if ENABLE(JIT)
2037     if (JITCode::isJIT(jitType())) {
2038         for (unsigned i = 0; i < m_structureStubInfos.size(); ++i) {
2039             StructureStubInfo& stubInfo = m_structureStubInfos[i];
2040             switch (stubInfo.accessType) {
2041             case access_put_by_id_transition_normal:
2042             case access_put_by_id_transition_direct: {
2043                 JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2044                 if ((!origin || Heap::isMarked(origin))
2045                     && Heap::isMarked(stubInfo.u.putByIdTransition.previousStructure.get()))
2046                     visitor.append(&stubInfo.u.putByIdTransition.structure);
2047                 else
2048                     allAreMarkedSoFar = false;
2049                 break;
2050             }
2051
2052             case access_put_by_id_list: {
2053                 PolymorphicPutByIdList* list = stubInfo.u.putByIdList.list;
2054                 JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2055                 if (origin && !Heap::isMarked(origin)) {
2056                     allAreMarkedSoFar = false;
2057                     break;
2058                 }
2059                 for (unsigned j = list->size(); j--;) {
2060                     PutByIdAccess& access = list->m_list[j];
2061                     if (!access.isTransition())
2062                         continue;
2063                     if (Heap::isMarked(access.oldStructure()))
2064                         visitor.append(&access.m_newStructure);
2065                     else
2066                         allAreMarkedSoFar = false;
2067                 }
2068                 break;
2069             }
2070             
2071             default:
2072                 break;
2073             }
2074         }
2075     }
2076 #endif // ENABLE(JIT)
2077     
2078 #if ENABLE(DFG_JIT)
2079     if (JITCode::isOptimizingJIT(jitType())) {
2080         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2081         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2082             if ((!dfgCommon->transitions[i].m_codeOrigin
2083                  || Heap::isMarked(dfgCommon->transitions[i].m_codeOrigin.get()))
2084                 && Heap::isMarked(dfgCommon->transitions[i].m_from.get())) {
2085                 // If the following three things are live, then the target of the
2086                 // transition is also live:
2087                 // - This code block. We know it's live already because otherwise
2088                 //   we wouldn't be scanning ourselves.
2089                 // - The code origin of the transition. Transitions may arise from
2090                 //   code that was inlined. They are not relevant if the user's
2091                 //   object that is required for the inlinee to run is no longer
2092                 //   live.
2093                 // - The source of the transition. The transition checks if some
2094                 //   heap location holds the source, and if so, stores the target.
2095                 //   Hence the source must be live for the transition to be live.
2096                 visitor.append(&dfgCommon->transitions[i].m_to);
2097             } else
2098                 allAreMarkedSoFar = false;
2099         }
2100     }
2101 #endif // ENABLE(DFG_JIT)
2102     
2103     if (allAreMarkedSoFar)
2104         m_allTransitionsHaveBeenMarked = true;
2105 }
2106
2107 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2108 {
2109     UNUSED_PARAM(visitor);
2110     
2111     if (shouldImmediatelyAssumeLivenessDuringScan())
2112         return;
2113     
2114 #if ENABLE(DFG_JIT)
2115     // Check if we have any remaining work to do.
2116     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2117     if (dfgCommon->livenessHasBeenProved)
2118         return;
2119     
2120     // Now check all of our weak references. If all of them are live, then we
2121     // have proved liveness and so we scan our strong references. If at end of
2122     // GC we still have not proved liveness, then this code block is toast.
2123     bool allAreLiveSoFar = true;
2124     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2125         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2126             allAreLiveSoFar = false;
2127             break;
2128         }
2129     }
2130     
2131     // If some weak references are dead, then this fixpoint iteration was
2132     // unsuccessful.
2133     if (!allAreLiveSoFar)
2134         return;
2135     
2136     // All weak references are live. Record this information so we don't
2137     // come back here again, and scan the strong references.
2138     dfgCommon->livenessHasBeenProved = true;
2139     stronglyVisitStrongReferences(visitor);
2140 #endif // ENABLE(DFG_JIT)
2141 }
2142
2143 void CodeBlock::visitWeakReferences(SlotVisitor& visitor)
2144 {
2145     propagateTransitions(visitor);
2146     determineLiveness(visitor);
2147 }
2148
2149 void CodeBlock::finalizeUnconditionally()
2150 {
2151 #if ENABLE(LLINT)
2152     Interpreter* interpreter = m_vm->interpreter;
2153     if (JITCode::couldBeInterpreted(jitType())) {
2154         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2155         for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2156             Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2157             switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2158             case op_get_by_id:
2159             case op_get_by_id_out_of_line:
2160             case op_put_by_id:
2161             case op_put_by_id_out_of_line:
2162                 if (!curInstruction[4].u.structure || Heap::isMarked(curInstruction[4].u.structure.get()))
2163                     break;
2164                 if (Options::verboseOSR())
2165                     dataLogF("Clearing LLInt property access with structure %p.\n", curInstruction[4].u.structure.get());
2166                 curInstruction[4].u.structure.clear();
2167                 curInstruction[5].u.operand = 0;
2168                 break;
2169             case op_put_by_id_transition_direct:
2170             case op_put_by_id_transition_normal:
2171             case op_put_by_id_transition_direct_out_of_line:
2172             case op_put_by_id_transition_normal_out_of_line:
2173                 if (Heap::isMarked(curInstruction[4].u.structure.get())
2174                     && Heap::isMarked(curInstruction[6].u.structure.get())
2175                     && Heap::isMarked(curInstruction[7].u.structureChain.get()))
2176                     break;
2177                 if (Options::verboseOSR()) {
2178                     dataLogF("Clearing LLInt put transition with structures %p -> %p, chain %p.\n",
2179                             curInstruction[4].u.structure.get(),
2180                             curInstruction[6].u.structure.get(),
2181                             curInstruction[7].u.structureChain.get());
2182                 }
2183                 curInstruction[4].u.structure.clear();
2184                 curInstruction[6].u.structure.clear();
2185                 curInstruction[7].u.structureChain.clear();
2186                 curInstruction[0].u.opcode = interpreter->getOpcode(op_put_by_id);
2187                 break;
2188             case op_get_array_length:
2189                 break;
2190             case op_get_from_scope:
2191             case op_put_to_scope: {
2192                 WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2193                 if (!structure || Heap::isMarked(structure.get()))
2194                     break;
2195                 if (Options::verboseOSR())
2196                     dataLogF("Clearing LLInt scope access with structure %p.\n", structure.get());
2197                 structure.clear();
2198                 break;
2199             }
2200             default:
2201                 RELEASE_ASSERT_NOT_REACHED();
2202             }
2203         }
2204
2205         for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2206             if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2207                 if (Options::verboseOSR())
2208                     dataLog("Clearing LLInt call from ", *this, "\n");
2209                 m_llintCallLinkInfos[i].unlink();
2210             }
2211             if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2212                 m_llintCallLinkInfos[i].lastSeenCallee.clear();
2213         }
2214     }
2215 #endif // ENABLE(LLINT)
2216
2217 #if ENABLE(DFG_JIT)
2218     // Check if we're not live. If we are, then jettison.
2219     if (!(shouldImmediatelyAssumeLivenessDuringScan() || m_jitCode->dfgCommon()->livenessHasBeenProved)) {
2220         if (Options::verboseOSR())
2221             dataLog(*this, " has dead weak references, jettisoning during GC.\n");
2222
2223         if (DFG::shouldShowDisassembly()) {
2224             dataLog(*this, " will be jettisoned because of the following dead references:\n");
2225             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2226             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2227                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
2228                 JSCell* origin = transition.m_codeOrigin.get();
2229                 JSCell* from = transition.m_from.get();
2230                 JSCell* to = transition.m_to.get();
2231                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
2232                     continue;
2233                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
2234             }
2235             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2236                 JSCell* weak = dfgCommon->weakReferences[i].get();
2237                 if (Heap::isMarked(weak))
2238                     continue;
2239                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
2240             }
2241         }
2242         
2243         jettison();
2244         return;
2245     }
2246 #endif // ENABLE(DFG_JIT)
2247
2248 #if ENABLE(JIT)
2249     // Handle inline caches.
2250     if (!!jitCode()) {
2251         RepatchBuffer repatchBuffer(this);
2252         for (unsigned i = 0; i < numberOfCallLinkInfos(); ++i) {
2253             if (callLinkInfo(i).isLinked()) {
2254                 if (ClosureCallStubRoutine* stub = callLinkInfo(i).stub.get()) {
2255                     if (!Heap::isMarked(stub->structure())
2256                         || !Heap::isMarked(stub->executable())) {
2257                         if (Options::verboseOSR()) {
2258                             dataLog(
2259                                 "Clearing closure call from ", *this, " to ",
2260                                 stub->executable()->hashFor(callLinkInfo(i).specializationKind()),
2261                                 ", stub routine ", RawPointer(stub), ".\n");
2262                         }
2263                         callLinkInfo(i).unlink(*m_vm, repatchBuffer);
2264                     }
2265                 } else if (!Heap::isMarked(callLinkInfo(i).callee.get())) {
2266                     if (Options::verboseOSR()) {
2267                         dataLog(
2268                             "Clearing call from ", *this, " to ",
2269                             RawPointer(callLinkInfo(i).callee.get()), " (",
2270                             callLinkInfo(i).callee.get()->executable()->hashFor(
2271                                 callLinkInfo(i).specializationKind()),
2272                             ").\n");
2273                     }
2274                     callLinkInfo(i).unlink(*m_vm, repatchBuffer);
2275                 }
2276             }
2277             if (!!callLinkInfo(i).lastSeenCallee
2278                 && !Heap::isMarked(callLinkInfo(i).lastSeenCallee.get()))
2279                 callLinkInfo(i).lastSeenCallee.clear();
2280         }
2281         for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i) {
2282             StructureStubInfo& stubInfo = m_structureStubInfos[i];
2283             
2284             if (stubInfo.visitWeakReferences())
2285                 continue;
2286             
2287             resetStubDuringGCInternal(repatchBuffer, stubInfo);
2288         }
2289     }
2290 #endif
2291 }
2292
2293 #if ENABLE(JIT)
2294 void CodeBlock::resetStub(StructureStubInfo& stubInfo)
2295 {
2296     if (stubInfo.accessType == access_unset)
2297         return;
2298     
2299     RepatchBuffer repatchBuffer(this);
2300     resetStubInternal(repatchBuffer, stubInfo);
2301 }
2302
2303 void CodeBlock::resetStubInternal(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2304 {
2305     AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
2306     
2307     if (Options::verboseOSR()) {
2308         // This can be called from GC destructor calls, so we don't try to do a full dump
2309         // of the CodeBlock.
2310         dataLog("Clearing structure cache (kind ", static_cast<int>(stubInfo.accessType), ") in ", RawPointer(this), ".\n");
2311     }
2312
2313     switch (jitType()) {
2314     case JITCode::BaselineJIT:
2315         if (isGetByIdAccess(accessType))
2316             JIT::resetPatchGetById(repatchBuffer, &stubInfo);
2317         else {
2318             RELEASE_ASSERT(isPutByIdAccess(accessType));
2319             JIT::resetPatchPutById(repatchBuffer, &stubInfo);
2320         }
2321         break;
2322     case JITCode::DFGJIT:
2323         if (isGetByIdAccess(accessType))
2324             DFG::dfgResetGetByID(repatchBuffer, stubInfo);
2325         else if (isPutByIdAccess(accessType))
2326             DFG::dfgResetPutByID(repatchBuffer, stubInfo);
2327         else {
2328             RELEASE_ASSERT(isInAccess(accessType));
2329             DFG::dfgResetIn(repatchBuffer, stubInfo);
2330         }
2331         break;
2332     default:
2333         RELEASE_ASSERT_NOT_REACHED();
2334         break;
2335     }
2336     
2337     stubInfo.reset();
2338 }
2339
2340 void CodeBlock::resetStubDuringGCInternal(RepatchBuffer& repatchBuffer, StructureStubInfo& stubInfo)
2341 {
2342     resetStubInternal(repatchBuffer, stubInfo);
2343     stubInfo.resetByGC = true;
2344 }
2345 #endif
2346
2347 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2348 {
2349     visitor.append(&m_globalObject);
2350     visitor.append(&m_ownerExecutable);
2351     visitor.append(&m_unlinkedCode);
2352     if (m_rareData)
2353         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2354     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2355     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2356         visitor.append(&m_functionExprs[i]);
2357     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2358         visitor.append(&m_functionDecls[i]);
2359     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
2360         m_objectAllocationProfiles[i].visitAggregate(visitor);
2361
2362     updateAllPredictions(Collection);
2363 }
2364
2365 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2366 {
2367     UNUSED_PARAM(visitor);
2368
2369 #if ENABLE(DFG_JIT)
2370     if (!JITCode::isOptimizingJIT(jitType()))
2371         return;
2372     
2373     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2374
2375     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2376         if (!!dfgCommon->transitions[i].m_codeOrigin)
2377             visitor.append(&dfgCommon->transitions[i].m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
2378         visitor.append(&dfgCommon->transitions[i].m_from);
2379         visitor.append(&dfgCommon->transitions[i].m_to);
2380     }
2381     
2382     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
2383         visitor.append(&dfgCommon->weakReferences[i]);
2384 #endif    
2385 }
2386
2387 CodeBlock* CodeBlock::baselineVersion()
2388 {
2389     if (JITCode::isBaselineCode(jitType()))
2390         return this;
2391 #if ENABLE(JIT)
2392     CodeBlock* result = replacement();
2393     while (result->alternative())
2394         result = result->alternative();
2395     RELEASE_ASSERT(result);
2396     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()));
2397     return result;
2398 #else
2399     RELEASE_ASSERT_NOT_REACHED();
2400     return 0;
2401 #endif
2402 }
2403
2404 #if ENABLE(JIT)
2405 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
2406 {
2407     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
2408 }
2409
2410 bool CodeBlock::hasOptimizedReplacement()
2411 {
2412     return hasOptimizedReplacement(jitType());
2413 }
2414 #endif
2415
2416 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset)
2417 {
2418     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2419
2420     if (!m_rareData)
2421         return 0;
2422     
2423     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2424     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2425         // Handlers are ordered innermost first, so the first handler we encounter
2426         // that contains the source address is the correct handler to use.
2427         if (exceptionHandlers[i].start <= bytecodeOffset && exceptionHandlers[i].end > bytecodeOffset)
2428             return &exceptionHandlers[i];
2429     }
2430
2431     return 0;
2432 }
2433
2434 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
2435 {
2436     RELEASE_ASSERT(bytecodeOffset < instructions().size());
2437     return m_ownerExecutable->lineNo() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
2438 }
2439
2440 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
2441 {
2442     int divot;
2443     int startOffset;
2444     int endOffset;
2445     unsigned line;
2446     unsigned column;
2447     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2448     return column;
2449 }
2450
2451 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
2452 {
2453     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
2454     divot += m_sourceOffset;
2455     column += line ? 1 : firstLineColumnOffset();
2456     line += m_ownerExecutable->lineNo();
2457 }
2458
2459 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
2460 {
2461 #if ENABLE(JIT)
2462     m_structureStubInfos.shrinkToFit();
2463     m_callLinkInfos.shrinkToFit();
2464 #endif
2465 #if ENABLE(VALUE_PROFILER)
2466     m_rareCaseProfiles.shrinkToFit();
2467     m_specialFastCaseProfiles.shrinkToFit();
2468 #endif
2469     
2470     if (shrinkMode == EarlyShrink) {
2471         m_additionalIdentifiers.shrinkToFit();
2472         m_functionDecls.shrinkToFit();
2473         m_functionExprs.shrinkToFit();
2474         m_constantRegisters.shrinkToFit();
2475         
2476         if (m_rareData) {
2477             m_rareData->m_switchJumpTables.shrinkToFit();
2478             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
2479         }
2480     } // else don't shrink these, because we would have already pointed pointers into these tables.
2481
2482     if (m_rareData) {
2483         m_rareData->m_exceptionHandlers.shrinkToFit();
2484 #if ENABLE(JIT)
2485         m_rareData->m_callReturnIndexVector.shrinkToFit();
2486 #endif
2487 #if ENABLE(DFG_JIT)
2488         m_rareData->m_inlineCallFrames.shrinkToFit();
2489         m_rareData->m_codeOrigins.shrinkToFit();
2490 #endif
2491     }
2492 }
2493
2494 void CodeBlock::createActivation(CallFrame* callFrame)
2495 {
2496     ASSERT(codeType() == FunctionCode);
2497     ASSERT(needsFullScopeChain());
2498     ASSERT(!callFrame->uncheckedR(activationRegister()).jsValue());
2499     JSActivation* activation = JSActivation::create(callFrame->vm(), callFrame, this);
2500     callFrame->uncheckedR(activationRegister()) = JSValue(activation);
2501     callFrame->setScope(activation);
2502 }
2503
2504 unsigned CodeBlock::addOrFindConstant(JSValue v)
2505 {
2506     unsigned result;
2507     if (findConstant(v, result))
2508         return result;
2509     return addConstant(v);
2510 }
2511
2512 bool CodeBlock::findConstant(JSValue v, unsigned& index)
2513 {
2514     unsigned numberOfConstants = numberOfConstantRegisters();
2515     for (unsigned i = 0; i < numberOfConstants; ++i) {
2516         if (getConstant(FirstConstantRegisterIndex + i) == v) {
2517             index = i;
2518             return true;
2519         }
2520     }
2521     index = numberOfConstants;
2522     return false;
2523 }
2524
2525 #if ENABLE(JIT)
2526 void CodeBlock::unlinkCalls()
2527 {
2528     if (!!m_alternative)
2529         m_alternative->unlinkCalls();
2530 #if ENABLE(LLINT)
2531     for (size_t i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2532         if (m_llintCallLinkInfos[i].isLinked())
2533             m_llintCallLinkInfos[i].unlink();
2534     }
2535 #endif
2536     if (!m_callLinkInfos.size())
2537         return;
2538     if (!m_vm->canUseJIT())
2539         return;
2540     RepatchBuffer repatchBuffer(this);
2541     for (size_t i = 0; i < m_callLinkInfos.size(); i++) {
2542         if (!m_callLinkInfos[i].isLinked())
2543             continue;
2544         m_callLinkInfos[i].unlink(*m_vm, repatchBuffer);
2545     }
2546 }
2547
2548 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
2549 {
2550     noticeIncomingCall(callerFrame);
2551     m_incomingCalls.push(incoming);
2552 }
2553 #endif // ENABLE(JIT)
2554
2555 void CodeBlock::unlinkIncomingCalls()
2556 {
2557 #if ENABLE(LLINT)
2558     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
2559         m_incomingLLIntCalls.begin()->unlink();
2560 #endif // ENABLE(LLINT)
2561 #if ENABLE(JIT)
2562     if (m_incomingCalls.isEmpty())
2563         return;
2564     RepatchBuffer repatchBuffer(this);
2565     while (m_incomingCalls.begin() != m_incomingCalls.end())
2566         m_incomingCalls.begin()->unlink(*m_vm, repatchBuffer);
2567 #endif // ENABLE(JIT)
2568 }
2569
2570 #if ENABLE(LLINT)
2571 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
2572 {
2573     noticeIncomingCall(callerFrame);
2574     m_incomingLLIntCalls.push(incoming);
2575 }
2576 #endif // ENABLE(LLINT)
2577
2578 #if ENABLE(JIT)
2579 ClosureCallStubRoutine* CodeBlock::findClosureCallForReturnPC(ReturnAddressPtr returnAddress)
2580 {
2581     for (unsigned i = m_callLinkInfos.size(); i--;) {
2582         CallLinkInfo& info = m_callLinkInfos[i];
2583         if (!info.stub)
2584             continue;
2585         if (!info.stub->code().executableMemory()->contains(returnAddress.value()))
2586             continue;
2587
2588         RELEASE_ASSERT(info.stub->codeOrigin().bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2589         return info.stub.get();
2590     }
2591     
2592     // The stub routine may have been jettisoned. This is rare, but we have to handle it.
2593     const JITStubRoutineSet& set = m_vm->heap.jitStubRoutines();
2594     for (unsigned i = set.size(); i--;) {
2595         GCAwareJITStubRoutine* genericStub = set.at(i);
2596         if (!genericStub->isClosureCall())
2597             continue;
2598         ClosureCallStubRoutine* stub = static_cast<ClosureCallStubRoutine*>(genericStub);
2599         if (!stub->code().executableMemory()->contains(returnAddress.value()))
2600             continue;
2601         RELEASE_ASSERT(stub->codeOrigin().bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2602         return stub;
2603     }
2604     
2605     return 0;
2606 }
2607 #endif
2608
2609 unsigned CodeBlock::bytecodeOffset(ExecState* exec, ReturnAddressPtr returnAddress)
2610 {
2611     UNUSED_PARAM(exec);
2612     UNUSED_PARAM(returnAddress);
2613 #if ENABLE(LLINT)
2614 #if !ENABLE(LLINT_C_LOOP)
2615     // When using the JIT, we could have addresses that are not bytecode
2616     // addresses. We check if the return address is in the LLint glue and
2617     // opcode handlers range here to ensure that we are looking at bytecode
2618     // before attempting to convert the return address into a bytecode offset.
2619     //
2620     // In the case of the C Loop LLInt, the JIT is disabled, and the only
2621     // valid return addresses should be bytecode PCs. So, we can and need to
2622     // forego this check because when we do not ENABLE(COMPUTED_GOTO_OPCODES),
2623     // then the bytecode "PC"s are actually the opcodeIDs and are not bounded
2624     // by llint_begin and llint_end.
2625     if (returnAddress.value() >= LLInt::getCodePtr(llint_begin)
2626         && returnAddress.value() <= LLInt::getCodePtr(llint_end))
2627 #endif
2628     {
2629         RELEASE_ASSERT(exec->codeBlock());
2630         RELEASE_ASSERT(exec->codeBlock() == this);
2631         RELEASE_ASSERT(JITCode::isBaselineCode(jitType()));
2632         Instruction* instruction = exec->currentVPC();
2633         RELEASE_ASSERT(instruction);
2634
2635         return bytecodeOffset(instruction);
2636     }
2637 #endif // !ENABLE(LLINT)
2638
2639 #if ENABLE(JIT)
2640     if (!m_rareData)
2641         return 1;
2642     Vector<CallReturnOffsetToBytecodeOffset, 0, UnsafeVectorOverflow>& callIndices = m_rareData->m_callReturnIndexVector;
2643     if (!callIndices.size())
2644         return 1;
2645     
2646     if (jitCode()->contains(returnAddress.value())) {
2647         unsigned callReturnOffset = jitCode()->offsetOf(returnAddress.value());
2648         CallReturnOffsetToBytecodeOffset* result =
2649             binarySearch<CallReturnOffsetToBytecodeOffset, unsigned>(
2650                 callIndices, callIndices.size(), callReturnOffset, getCallReturnOffset);
2651         RELEASE_ASSERT(result->callReturnOffset == callReturnOffset);
2652         RELEASE_ASSERT(result->bytecodeOffset < instructionCount());
2653         return result->bytecodeOffset;
2654     }
2655     ClosureCallStubRoutine* closureInfo = findClosureCallForReturnPC(returnAddress);
2656     CodeOrigin origin = closureInfo->codeOrigin();
2657     while (InlineCallFrame* inlineCallFrame = origin.inlineCallFrame) {
2658         if (inlineCallFrame->baselineCodeBlock() == this)
2659             break;
2660         origin = inlineCallFrame->caller;
2661         RELEASE_ASSERT(origin.bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2662     }
2663     RELEASE_ASSERT(origin.bytecodeIndex != CodeOrigin::invalidBytecodeIndex);
2664     unsigned bytecodeIndex = origin.bytecodeIndex;
2665     RELEASE_ASSERT(bytecodeIndex < instructionCount());
2666     return bytecodeIndex;
2667 #endif // ENABLE(JIT)
2668
2669 #if !ENABLE(LLINT) && !ENABLE(JIT)
2670     return 1;
2671 #endif
2672 }
2673
2674 void CodeBlock::clearEvalCache()
2675 {
2676     if (!!m_alternative)
2677         m_alternative->clearEvalCache();
2678     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2679         otherBlock->clearEvalCache();
2680     if (!m_rareData)
2681         return;
2682     m_rareData->m_evalCodeCache.clear();
2683 }
2684
2685 template<typename T, size_t inlineCapacity, typename U, typename V>
2686 inline void replaceExistingEntries(Vector<T, inlineCapacity, U>& target, Vector<T, inlineCapacity, V>& source)
2687 {
2688     ASSERT(target.size() <= source.size());
2689     for (size_t i = 0; i < target.size(); ++i)
2690         target[i] = source[i];
2691 }
2692
2693 void CodeBlock::copyPostParseDataFrom(CodeBlock* alternative)
2694 {
2695     if (!alternative)
2696         return;
2697     
2698     replaceExistingEntries(m_constantRegisters, alternative->m_constantRegisters);
2699     replaceExistingEntries(m_functionDecls, alternative->m_functionDecls);
2700     replaceExistingEntries(m_functionExprs, alternative->m_functionExprs);
2701     if (!!m_rareData && !!alternative->m_rareData)
2702         replaceExistingEntries(m_rareData->m_constantBuffers, alternative->m_rareData->m_constantBuffers);
2703 }
2704
2705 void CodeBlock::copyPostParseDataFromAlternative()
2706 {
2707     copyPostParseDataFrom(m_alternative.get());
2708 }
2709
2710 void CodeBlock::install()
2711 {
2712     ownerExecutable()->installCode(this);
2713 }
2714
2715 PassRefPtr<CodeBlock> CodeBlock::newReplacement()
2716 {
2717     return ownerExecutable()->newReplacementCodeBlockFor(specializationKind());
2718 }
2719
2720 #if ENABLE(JIT)
2721 void CodeBlock::reoptimize()
2722 {
2723     ASSERT(replacement() != this);
2724     ASSERT(replacement()->alternative() == this);
2725     if (DFG::shouldShowDisassembly())
2726         dataLog(*replacement(), " will be jettisoned due to reoptimization of ", *this, ".\n");
2727     replacement()->jettison();
2728     countReoptimization();
2729 }
2730
2731 CodeBlock* ProgramCodeBlock::replacement()
2732 {
2733     return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
2734 }
2735
2736 CodeBlock* EvalCodeBlock::replacement()
2737 {
2738     return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
2739 }
2740
2741 CodeBlock* FunctionCodeBlock::replacement()
2742 {
2743     return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
2744 }
2745
2746 DFG::CapabilityLevel ProgramCodeBlock::capabilityLevelInternal()
2747 {
2748     return DFG::programCapabilityLevel(this);
2749 }
2750
2751 DFG::CapabilityLevel EvalCodeBlock::capabilityLevelInternal()
2752 {
2753     return DFG::evalCapabilityLevel(this);
2754 }
2755
2756 DFG::CapabilityLevel FunctionCodeBlock::capabilityLevelInternal()
2757 {
2758     if (m_isConstructor)
2759         return DFG::functionForConstructCapabilityLevel(this);
2760     return DFG::functionForCallCapabilityLevel(this);
2761 }
2762
2763 void CodeBlock::jettison()
2764 {
2765     DeferGC deferGC(*m_heap);
2766     ASSERT(JITCode::isOptimizingJIT(jitType()));
2767     ASSERT(this == replacement());
2768     alternative()->optimizeAfterWarmUp();
2769     tallyFrequentExitSites();
2770     if (DFG::shouldShowDisassembly())
2771         dataLog("Jettisoning ", *this, ".\n");
2772     alternative()->install();
2773 }
2774 #endif
2775
2776 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2777 {
2778     if (!codeOrigin.inlineCallFrame)
2779         return globalObject();
2780     return jsCast<FunctionExecutable*>(codeOrigin.inlineCallFrame->executable.get())->eitherCodeBlock()->globalObject();
2781 }
2782
2783 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2784 {
2785     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2786     
2787     if (Options::verboseCallLink())
2788         dataLog("Noticing call link from ", *callerCodeBlock, " to ", *this, "\n");
2789     
2790     if (!m_shouldAlwaysBeInlined)
2791         return;
2792
2793 #if ENABLE(DFG_JIT)
2794     if (!hasBaselineJITProfiling())
2795         return;
2796
2797     if (!DFG::mightInlineFunction(this))
2798         return;
2799
2800     if (!canInline(m_capabilityLevelState))
2801         return;
2802
2803     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2804         // If the caller is still in the interpreter, then we can't expect inlining to
2805         // happen anytime soon. Assume it's profitable to optimize it separately. This
2806         // ensures that a function is SABI only if it is called no more frequently than
2807         // any of its callers.
2808         m_shouldAlwaysBeInlined = false;
2809         if (Options::verboseCallLink())
2810             dataLog("    Marking SABI because caller is in LLInt.\n");
2811         return;
2812     }
2813     
2814     if (callerCodeBlock->codeType() != FunctionCode) {
2815         // If the caller is either eval or global code, assume that that won't be
2816         // optimized anytime soon. For eval code this is particularly true since we
2817         // delay eval optimization by a *lot*.
2818         m_shouldAlwaysBeInlined = false;
2819         if (Options::verboseCallLink())
2820             dataLog("    Marking SABI because caller is not a function.\n");
2821         return;
2822     }
2823     
2824     ExecState* frame = callerFrame;
2825     for (unsigned i = Options::maximumInliningDepth(); i--; frame = frame->callerFrame()) {
2826         if (frame->hasHostCallFrameFlag())
2827             break;
2828         if (frame->codeBlock() == this) {
2829             // Recursive calls won't be inlined.
2830             if (Options::verboseCallLink())
2831                 dataLog("    Marking SABI because recursion was detected.\n");
2832             m_shouldAlwaysBeInlined = false;
2833             return;
2834         }
2835     }
2836     
2837     RELEASE_ASSERT(callerCodeBlock->m_capabilityLevelState != DFG::CapabilityLevelNotSet);
2838     
2839     if (canCompile(callerCodeBlock->m_capabilityLevelState))
2840         return;
2841     
2842     if (Options::verboseCallLink())
2843         dataLog("    Marking SABI because the caller is not a DFG candidate.\n");
2844     
2845     m_shouldAlwaysBeInlined = false;
2846 #endif
2847 }
2848
2849 #if ENABLE(JIT)
2850 unsigned CodeBlock::reoptimizationRetryCounter() const
2851 {
2852     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2853     return m_reoptimizationRetryCounter;
2854 }
2855
2856 void CodeBlock::countReoptimization()
2857 {
2858     m_reoptimizationRetryCounter++;
2859     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2860         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2861 }
2862
2863 unsigned CodeBlock::numberOfDFGCompiles()
2864 {
2865     ASSERT(JITCode::isBaselineCode(jitType()));
2866     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
2867 }
2868
2869 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2870 {
2871     if (codeType() == EvalCode)
2872         return Options::evalThresholdMultiplier();
2873     
2874     return 1;
2875 }
2876
2877 double CodeBlock::optimizationThresholdScalingFactor()
2878 {
2879     // This expression arises from doing a least-squares fit of
2880     //
2881     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2882     //
2883     // against the data points:
2884     //
2885     //    x       F[x_]
2886     //    10       0.9          (smallest reasonable code block)
2887     //   200       1.0          (typical small-ish code block)
2888     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2889     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2890     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2891     // 10000       6.0          (similar to above)
2892     //
2893     // I achieve the minimization using the following Mathematica code:
2894     //
2895     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2896     //
2897     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2898     //
2899     // solution = 
2900     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2901     //         {a, b, c, d}][[2]]
2902     //
2903     // And the code below (to initialize a, b, c, d) is generated by:
2904     //
2905     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2906     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2907     //
2908     // We've long known the following to be true:
2909     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2910     //   than later.
2911     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2912     //   and sometimes have a large enough threshold that we never optimize them.
2913     // - The difference in cost is not totally linear because (a) just invoking the
2914     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2915     //   in the correlation between instruction count and the actual compilation cost
2916     //   that for those large blocks, the instruction count should not have a strong
2917     //   influence on our threshold.
2918     //
2919     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2920     // example where the heuristics were right (code block in 3d-cube with instruction
2921     // count 320, which got compiled early as it should have been) and one where they were
2922     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2923     // to compile and didn't run often enough to warrant compilation in my opinion), and
2924     // then threw in additional data points that represented my own guess of what our
2925     // heuristics should do for some round-numbered examples.
2926     //
2927     // The expression to which I decided to fit the data arose because I started with an
2928     // affine function, and then did two things: put the linear part in an Abs to ensure
2929     // that the fit didn't end up choosing a negative value of c (which would result in
2930     // the function turning over and going negative for large x) and I threw in a Sqrt
2931     // term because Sqrt represents my intution that the function should be more sensitive
2932     // to small changes in small values of x, but less sensitive when x gets large.
2933     
2934     // Note that the current fit essentially eliminates the linear portion of the
2935     // expression (c == 0.0).
2936     const double a = 0.061504;
2937     const double b = 1.02406;
2938     const double c = 0.0;
2939     const double d = 0.825914;
2940     
2941     double instructionCount = this->instructionCount();
2942     
2943     ASSERT(instructionCount); // Make sure this is called only after we have an instruction stream; otherwise it'll just return the value of d, which makes no sense.
2944     
2945     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2946     if (Options::verboseOSR()) {
2947         dataLog(
2948             *this, ": instruction count is ", instructionCount,
2949             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2950             "\n");
2951     }
2952     return result * codeTypeThresholdMultiplier();
2953 }
2954
2955 static int32_t clipThreshold(double threshold)
2956 {
2957     if (threshold < 1.0)
2958         return 1;
2959     
2960     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2961         return std::numeric_limits<int32_t>::max();
2962     
2963     return static_cast<int32_t>(threshold);
2964 }
2965
2966 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2967 {
2968     return clipThreshold(
2969         static_cast<double>(desiredThreshold) *
2970         optimizationThresholdScalingFactor() *
2971         (1 << reoptimizationRetryCounter()));
2972 }
2973
2974 bool CodeBlock::checkIfOptimizationThresholdReached()
2975 {
2976 #if ENABLE(DFG_JIT)
2977     if (DFG::Worklist* worklist = m_vm->worklist.get()) {
2978         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2979             == DFG::Worklist::Compiled) {
2980             optimizeNextInvocation();
2981             return true;
2982         }
2983     }
2984 #endif
2985     
2986     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2987 }
2988
2989 void CodeBlock::optimizeNextInvocation()
2990 {
2991     if (Options::verboseOSR())
2992         dataLog(*this, ": Optimizing next invocation.\n");
2993     m_jitExecuteCounter.setNewThreshold(0, this);
2994 }
2995
2996 void CodeBlock::dontOptimizeAnytimeSoon()
2997 {
2998     if (Options::verboseOSR())
2999         dataLog(*this, ": Not optimizing anytime soon.\n");
3000     m_jitExecuteCounter.deferIndefinitely();
3001 }
3002
3003 void CodeBlock::optimizeAfterWarmUp()
3004 {
3005     if (Options::verboseOSR())
3006         dataLog(*this, ": Optimizing after warm-up.\n");
3007 #if ENABLE(DFG_JIT)
3008     m_jitExecuteCounter.setNewThreshold(
3009         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
3010 #endif
3011 }
3012
3013 void CodeBlock::optimizeAfterLongWarmUp()
3014 {
3015     if (Options::verboseOSR())
3016         dataLog(*this, ": Optimizing after long warm-up.\n");
3017 #if ENABLE(DFG_JIT)
3018     m_jitExecuteCounter.setNewThreshold(
3019         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
3020 #endif
3021 }
3022
3023 void CodeBlock::optimizeSoon()
3024 {
3025     if (Options::verboseOSR())
3026         dataLog(*this, ": Optimizing soon.\n");
3027 #if ENABLE(DFG_JIT)
3028     m_jitExecuteCounter.setNewThreshold(
3029         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
3030 #endif
3031 }
3032
3033 void CodeBlock::forceOptimizationSlowPathConcurrently()
3034 {
3035     if (Options::verboseOSR())
3036         dataLog(*this, ": Forcing slow path concurrently.\n");
3037     m_jitExecuteCounter.forceSlowPathConcurrently();
3038 }
3039
3040 #if ENABLE(DFG_JIT)
3041 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
3042 {
3043     RELEASE_ASSERT(jitType() == JITCode::BaselineJIT);
3044     RELEASE_ASSERT((result == CompilationSuccessful) == (replacement() != this));
3045     switch (result) {
3046     case CompilationSuccessful:
3047         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
3048         optimizeNextInvocation();
3049         return;
3050     case CompilationFailed:
3051         dontOptimizeAnytimeSoon();
3052         return;
3053     case CompilationDeferred:
3054         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
3055         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
3056         // necessarily guarantee anything. So, we make sure that even if that
3057         // function ends up being a no-op, we still eventually retry and realize
3058         // that we have optimized code ready.
3059         optimizeAfterWarmUp();
3060         return;
3061     case CompilationInvalidated:
3062         // Retry with exponential backoff.
3063         countReoptimization();
3064         optimizeAfterWarmUp();
3065         return;
3066     }
3067     RELEASE_ASSERT_NOT_REACHED();
3068 }
3069
3070 #endif
3071     
3072 static bool structureStubInfoLessThan(const StructureStubInfo& a, const StructureStubInfo& b)
3073 {
3074     return a.callReturnLocation.executableAddress() < b.callReturnLocation.executableAddress();
3075 }
3076
3077 void CodeBlock::sortStructureStubInfos()
3078 {
3079     std::sort(m_structureStubInfos.begin(), m_structureStubInfos.end(), structureStubInfoLessThan);
3080 }
3081
3082 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
3083 {
3084     ASSERT(JITCode::isOptimizingJIT(jitType()));
3085     // Compute this the lame way so we don't saturate. This is called infrequently
3086     // enough that this loop won't hurt us.
3087     unsigned result = desiredThreshold;
3088     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
3089         unsigned newResult = result << 1;
3090         if (newResult < result)
3091             return std::numeric_limits<uint32_t>::max();
3092         result = newResult;
3093     }
3094     return result;
3095 }
3096
3097 uint32_t CodeBlock::exitCountThresholdForReoptimization()
3098 {
3099     return adjustedExitCountThreshold(Options::osrExitCountForReoptimization() * codeTypeThresholdMultiplier());
3100 }
3101
3102 uint32_t CodeBlock::exitCountThresholdForReoptimizationFromLoop()
3103 {
3104     return adjustedExitCountThreshold(Options::osrExitCountForReoptimizationFromLoop() * codeTypeThresholdMultiplier());
3105 }
3106
3107 bool CodeBlock::shouldReoptimizeNow()
3108 {
3109     return osrExitCounter() >= exitCountThresholdForReoptimization();
3110 }
3111
3112 bool CodeBlock::shouldReoptimizeFromLoopNow()
3113 {
3114     return osrExitCounter() >= exitCountThresholdForReoptimizationFromLoop();
3115 }
3116 #endif
3117
3118 #if ENABLE(VALUE_PROFILER)
3119 ArrayProfile* CodeBlock::getArrayProfile(unsigned bytecodeOffset)
3120 {
3121     for (unsigned i = 0; i < m_arrayProfiles.size(); ++i) {
3122         if (m_arrayProfiles[i].bytecodeOffset() == bytecodeOffset)
3123             return &m_arrayProfiles[i];
3124     }
3125     return 0;
3126 }
3127
3128 ArrayProfile* CodeBlock::getOrAddArrayProfile(unsigned bytecodeOffset)
3129 {
3130     ArrayProfile* result = getArrayProfile(bytecodeOffset);
3131     if (result)
3132         return result;
3133     return addArrayProfile(bytecodeOffset);
3134 }
3135
3136 void CodeBlock::updateAllPredictionsAndCountLiveness(
3137     OperationInProgress operation, unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles)
3138 {
3139     ConcurrentJITLocker locker(m_lock);
3140     
3141     numberOfLiveNonArgumentValueProfiles = 0;
3142     numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
3143     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
3144         ValueProfile* profile = getFromAllValueProfiles(i);
3145         unsigned numSamples = profile->totalNumberOfSamples();
3146         if (numSamples > ValueProfile::numberOfBuckets)
3147             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
3148         numberOfSamplesInProfiles += numSamples;
3149         if (profile->m_bytecodeOffset < 0) {
3150             profile->computeUpdatedPrediction(locker, operation);
3151             continue;
3152         }
3153         if (profile->numberOfSamples() || profile->m_prediction != SpecNone)
3154             numberOfLiveNonArgumentValueProfiles++;
3155         profile->computeUpdatedPrediction(locker, operation);
3156     }
3157     
3158 #if ENABLE(DFG_JIT)
3159     m_lazyOperandValueProfiles.computeUpdatedPredictions(locker, operation);
3160 #endif
3161 }
3162
3163 void CodeBlock::updateAllValueProfilePredictions(OperationInProgress operation)
3164 {
3165     unsigned ignoredValue1, ignoredValue2;
3166     updateAllPredictionsAndCountLiveness(operation, ignoredValue1, ignoredValue2);
3167 }
3168
3169 void CodeBlock::updateAllArrayPredictions()
3170 {
3171     ConcurrentJITLocker locker(m_lock);
3172     
3173     for (unsigned i = m_arrayProfiles.size(); i--;)
3174         m_arrayProfiles[i].computeUpdatedPrediction(locker, this);
3175     
3176     // Don't count these either, for similar reasons.
3177     for (unsigned i = m_arrayAllocationProfiles.size(); i--;)
3178         m_arrayAllocationProfiles[i].updateIndexingType();
3179 }
3180
3181 void CodeBlock::updateAllPredictions(OperationInProgress operation)
3182 {
3183     updateAllValueProfilePredictions(operation);
3184     updateAllArrayPredictions();
3185 }
3186
3187 bool CodeBlock::shouldOptimizeNow()
3188 {
3189     if (Options::verboseOSR())
3190         dataLog("Considering optimizing ", *this, "...\n");
3191
3192 #if ENABLE(VERBOSE_VALUE_PROFILE)
3193     dumpValueProfiles();
3194 #endif
3195
3196     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay())
3197         return true;
3198     
3199     updateAllArrayPredictions();
3200     
3201     unsigned numberOfLiveNonArgumentValueProfiles;
3202     unsigned numberOfSamplesInProfiles;
3203     updateAllPredictionsAndCountLiveness(NoOperation, numberOfLiveNonArgumentValueProfiles, numberOfSamplesInProfiles);
3204
3205     if (Options::verboseOSR()) {
3206         dataLogF(
3207             "Profile hotness: %lf (%u / %u), %lf (%u / %u)\n",
3208             (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(),
3209             numberOfLiveNonArgumentValueProfiles, numberOfValueProfiles(),
3210             (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles(),
3211             numberOfSamplesInProfiles, ValueProfile::numberOfBuckets * numberOfValueProfiles());
3212     }
3213
3214     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate())
3215         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate())
3216         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay())
3217         return true;
3218     
3219     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
3220     m_optimizationDelayCounter++;
3221     optimizeAfterWarmUp();
3222     return false;
3223 }
3224 #endif
3225
3226 #if ENABLE(DFG_JIT)
3227 void CodeBlock::tallyFrequentExitSites()
3228 {
3229     ASSERT(JITCode::isOptimizingJIT(jitType()));
3230     ASSERT(alternative()->jitType() == JITCode::BaselineJIT);
3231     
3232     CodeBlock* profiledBlock = alternative();
3233     
3234     switch (jitType()) {
3235     case JITCode::DFGJIT: {
3236         DFG::JITCode* jitCode = m_jitCode->dfg();
3237         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
3238             DFG::OSRExit& exit = jitCode->osrExit[i];
3239             
3240             if (!exit.considerAddingAsFrequentExitSite(profiledBlock))
3241                 continue;
3242             
3243 #if DFG_ENABLE(DEBUG_VERBOSE)
3244             dataLog("OSR exit #", i, " (bc#", exit.m_codeOrigin.bytecodeIndex, ", ", exit.m_kind, ") for ", *this, " occurred frequently: counting as frequent exit site.\n");
3245 #endif
3246         }
3247         break;
3248     }
3249
3250 #if ENABLE(FTL_JIT)
3251     case JITCode::FTLJIT: {
3252         // There is no easy way to avoid duplicating this code since the FTL::JITCode::osrExit
3253         // vector contains a totally different type, that just so happens to behave like
3254         // DFG::JITCode::osrExit.
3255         FTL::JITCode* jitCode = m_jitCode->ftl();
3256         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
3257             FTL::OSRExit& exit = jitCode->osrExit[i];
3258