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