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