91001093ecb69539088e334f65c4cd63bf47608c
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2010 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 "DFGCapabilities.h"
35 #include "DFGNode.h"
36 #include "DFGRepatch.h"
37 #include "Debugger.h"
38 #include "Interpreter.h"
39 #include "JIT.h"
40 #include "JITStubs.h"
41 #include "JSActivation.h"
42 #include "JSFunction.h"
43 #include "JSStaticScopeObject.h"
44 #include "JSValue.h"
45 #include "LowLevelInterpreter.h"
46 #include "MethodCallLinkStatus.h"
47 #include "RepatchBuffer.h"
48 #include "UStringConcatenate.h"
49 #include <stdio.h>
50 #include <wtf/StringExtras.h>
51
52 #if ENABLE(DFG_JIT)
53 #include "DFGOperations.h"
54 #endif
55
56 #define DUMP_CODE_BLOCK_STATISTICS 0
57
58 namespace JSC {
59
60 #if ENABLE(DFG_JIT)
61 using namespace DFG;
62 #endif
63
64 static UString escapeQuotes(const UString& str)
65 {
66     UString result = str;
67     size_t pos = 0;
68     while ((pos = result.find('\"', pos)) != notFound) {
69         result = makeUString(result.substringSharingImpl(0, pos), "\"\\\"\"", result.substringSharingImpl(pos + 1));
70         pos += 4;
71     }
72     return result;
73 }
74
75 static UString valueToSourceString(ExecState* exec, JSValue val)
76 {
77     if (!val)
78         return "0";
79
80     if (val.isString())
81         return makeUString("\"", escapeQuotes(val.toString(exec)->value(exec)), "\"");
82
83     return val.description();
84 }
85
86 static CString constantName(ExecState* exec, int k, JSValue value)
87 {
88     return makeUString(valueToSourceString(exec, value), "(@k", UString::number(k - FirstConstantRegisterIndex), ")").utf8();
89 }
90
91 static CString idName(int id0, const Identifier& ident)
92 {
93     return makeUString(ident.ustring(), "(@id", UString::number(id0), ")").utf8();
94 }
95
96 CString CodeBlock::registerName(ExecState* exec, int r) const
97 {
98     if (r == missingThisObjectMarker())
99         return "<null>";
100
101     if (isConstantRegisterIndex(r))
102         return constantName(exec, r, getConstant(r));
103
104     return makeUString("r", UString::number(r)).utf8();
105 }
106
107 static UString regexpToSourceString(RegExp* regExp)
108 {
109     char postfix[5] = { '/', 0, 0, 0, 0 };
110     int index = 1;
111     if (regExp->global())
112         postfix[index++] = 'g';
113     if (regExp->ignoreCase())
114         postfix[index++] = 'i';
115     if (regExp->multiline())
116         postfix[index] = 'm';
117
118     return makeUString("/", regExp->pattern(), postfix);
119 }
120
121 static CString regexpName(int re, RegExp* regexp)
122 {
123     return makeUString(regexpToSourceString(regexp), "(@re", UString::number(re), ")").utf8();
124 }
125
126 static UString pointerToSourceString(void* p)
127 {
128     char buffer[2 + 2 * sizeof(void*) + 1]; // 0x [two characters per byte] \0
129     snprintf(buffer, sizeof(buffer), "%p", p);
130     return buffer;
131 }
132
133 NEVER_INLINE static const char* debugHookName(int debugHookID)
134 {
135     switch (static_cast<DebugHookID>(debugHookID)) {
136         case DidEnterCallFrame:
137             return "didEnterCallFrame";
138         case WillLeaveCallFrame:
139             return "willLeaveCallFrame";
140         case WillExecuteStatement:
141             return "willExecuteStatement";
142         case WillExecuteProgram:
143             return "willExecuteProgram";
144         case DidExecuteProgram:
145             return "didExecuteProgram";
146         case DidReachBreakpoint:
147             return "didReachBreakpoint";
148     }
149
150     ASSERT_NOT_REACHED();
151     return "";
152 }
153
154 void CodeBlock::printUnaryOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op)
155 {
156     int r0 = (++it)->u.operand;
157     int r1 = (++it)->u.operand;
158
159     dataLog("[%4d] %s\t\t %s, %s\n", location, op, registerName(exec, r0).data(), registerName(exec, r1).data());
160 }
161
162 void CodeBlock::printBinaryOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op)
163 {
164     int r0 = (++it)->u.operand;
165     int r1 = (++it)->u.operand;
166     int r2 = (++it)->u.operand;
167     dataLog("[%4d] %s\t\t %s, %s, %s\n", location, op, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
168 }
169
170 void CodeBlock::printConditionalJump(ExecState* exec, const Vector<Instruction>::const_iterator&, Vector<Instruction>::const_iterator& it, int location, const char* op)
171 {
172     int r0 = (++it)->u.operand;
173     int offset = (++it)->u.operand;
174     dataLog("[%4d] %s\t\t %s, %d(->%d)\n", location, op, registerName(exec, r0).data(), offset, location + offset);
175 }
176
177 void CodeBlock::printGetByIdOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it)
178 {
179     const char* op;
180     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
181     case op_get_by_id:
182         op = "get_by_id";
183         break;
184     case op_get_by_id_self:
185         op = "get_by_id_self";
186         break;
187     case op_get_by_id_proto:
188         op = "get_by_id_proto";
189         break;
190     case op_get_by_id_chain:
191         op = "get_by_id_chain";
192         break;
193     case op_get_by_id_getter_self:
194         op = "get_by_id_getter_self";
195         break;
196     case op_get_by_id_getter_proto:
197         op = "get_by_id_getter_proto";
198         break;
199     case op_get_by_id_getter_chain:
200         op = "get_by_id_getter_chain";
201         break;
202     case op_get_by_id_custom_self:
203         op = "get_by_id_custom_self";
204         break;
205     case op_get_by_id_custom_proto:
206         op = "get_by_id_custom_proto";
207         break;
208     case op_get_by_id_custom_chain:
209         op = "get_by_id_custom_chain";
210         break;
211     case op_get_by_id_generic:
212         op = "get_by_id_generic";
213         break;
214     case op_get_array_length:
215         op = "array_length";
216         break;
217     case op_get_string_length:
218         op = "string_length";
219         break;
220     default:
221         ASSERT_NOT_REACHED();
222         op = 0;
223     }
224     int r0 = (++it)->u.operand;
225     int r1 = (++it)->u.operand;
226     int id0 = (++it)->u.operand;
227     dataLog("[%4d] %s\t %s, %s, %s", location, op, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
228     it += 5;
229 }
230
231 static void dumpStructure(const char* name, ExecState* exec, Structure* structure, Identifier& ident)
232 {
233     if (!structure)
234         return;
235     
236     dataLog("%s = %p", name, structure);
237     
238     size_t offset = structure->get(exec->globalData(), ident);
239     if (offset != notFound)
240         dataLog(" (offset = %lu)", static_cast<unsigned long>(offset));
241 }
242
243 static void dumpChain(ExecState* exec, StructureChain* chain, Identifier& ident)
244 {
245     dataLog("chain = %p: [", chain);
246     bool first = true;
247     for (WriteBarrier<Structure>* currentStructure = chain->head();
248          *currentStructure;
249          ++currentStructure) {
250         if (first)
251             first = false;
252         else
253             dataLog(", ");
254         dumpStructure("struct", exec, currentStructure->get(), ident);
255     }
256     dataLog("]");
257 }
258
259 void CodeBlock::printGetByIdCacheStatus(ExecState* exec, int location)
260 {
261     Instruction* instruction = instructions().begin() + location;
262
263     if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_method_check)
264         instruction++;
265     
266     Identifier& ident = identifier(instruction[3].u.operand);
267     
268 #if ENABLE(LLINT)
269     Structure* structure = instruction[4].u.structure.get();
270     dataLog(" llint(");
271     dumpStructure("struct", exec, structure, ident);
272     dataLog(")");
273 #endif
274
275 #if ENABLE(JIT)
276     if (numberOfStructureStubInfos()) {
277         dataLog(" jit(");
278         StructureStubInfo& stubInfo = getStubInfo(location);
279         if (!stubInfo.seen)
280             dataLog("not seen");
281         else {
282             Structure* baseStructure = 0;
283             Structure* prototypeStructure = 0;
284             StructureChain* chain = 0;
285             PolymorphicAccessStructureList* structureList = 0;
286             int listSize = 0;
287             
288             switch (stubInfo.accessType) {
289             case access_get_by_id_self:
290                 dataLog("self");
291                 baseStructure = stubInfo.u.getByIdSelf.baseObjectStructure.get();
292                 break;
293             case access_get_by_id_proto:
294                 dataLog("proto");
295                 baseStructure = stubInfo.u.getByIdProto.baseObjectStructure.get();
296                 prototypeStructure = stubInfo.u.getByIdProto.prototypeStructure.get();
297                 break;
298             case access_get_by_id_chain:
299                 dataLog("chain");
300                 baseStructure = stubInfo.u.getByIdChain.baseObjectStructure.get();
301                 chain = stubInfo.u.getByIdChain.chain.get();
302                 break;
303             case access_get_by_id_self_list:
304                 dataLog("self_list");
305                 structureList = stubInfo.u.getByIdSelfList.structureList;
306                 listSize = stubInfo.u.getByIdSelfList.listSize;
307                 break;
308             case access_get_by_id_proto_list:
309                 dataLog("proto_list");
310                 structureList = stubInfo.u.getByIdProtoList.structureList;
311                 listSize = stubInfo.u.getByIdProtoList.listSize;
312                 break;
313             case access_unset:
314                 dataLog("unset");
315                 break;
316             case access_get_by_id_generic:
317                 dataLog("generic");
318                 break;
319             case access_get_array_length:
320                 dataLog("array_length");
321                 break;
322             case access_get_string_length:
323                 dataLog("string_length");
324                 break;
325             default:
326                 ASSERT_NOT_REACHED();
327                 break;
328             }
329             
330             if (baseStructure) {
331                 dataLog(", ");
332                 dumpStructure("struct", exec, baseStructure, ident);
333             }
334             
335             if (prototypeStructure) {
336                 dataLog(", ");
337                 dumpStructure("prototypeStruct", exec, baseStructure, ident);
338             }
339             
340             if (chain) {
341                 dataLog(", ");
342                 dumpChain(exec, chain, ident);
343             }
344             
345             if (structureList) {
346                 dataLog(", list = %p: [", structureList);
347                 for (int i = 0; i < listSize; ++i) {
348                     if (i)
349                         dataLog(", ");
350                     dataLog("(");
351                     dumpStructure("base", exec, structureList->list[i].base.get(), ident);
352                     if (structureList->list[i].isChain) {
353                         if (structureList->list[i].u.chain.get()) {
354                             dataLog(", ");
355                             dumpChain(exec, structureList->list[i].u.chain.get(), ident);
356                         }
357                     } else {
358                         if (structureList->list[i].u.proto.get()) {
359                             dataLog(", ");
360                             dumpStructure("proto", exec, structureList->list[i].u.proto.get(), ident);
361                         }
362                     }
363                     dataLog(")");
364                 }
365                 dataLog("]");
366             }
367         }
368         dataLog(")");
369     }
370 #endif
371 }
372
373 void CodeBlock::printCallOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op, CacheDumpMode cacheDumpMode)
374 {
375     int func = (++it)->u.operand;
376     int argCount = (++it)->u.operand;
377     int registerOffset = (++it)->u.operand;
378     dataLog("[%4d] %s\t %s, %d, %d", location, op, registerName(exec, func).data(), argCount, registerOffset);
379     if (cacheDumpMode == DumpCaches) {
380 #if ENABLE(LLINT)
381         LLIntCallLinkInfo* callLinkInfo = it[1].u.callLinkInfo;
382         if (callLinkInfo->lastSeenCallee) {
383             dataLog(" llint(%p, exec %p)",
384                     callLinkInfo->lastSeenCallee.get(),
385                     callLinkInfo->lastSeenCallee->executable());
386         } else
387             dataLog(" llint(not set)");
388 #endif
389 #if ENABLE(JIT)
390         if (numberOfCallLinkInfos()) {
391             JSFunction* target = getCallLinkInfo(location).lastSeenCallee.get();
392             if (target)
393                 dataLog(" jit(%p, exec %p)", target, target->executable());
394             else
395                 dataLog(" jit(not set)");
396         }
397 #endif
398     }
399     dataLog("\n");
400     it += 2;
401 }
402
403 void CodeBlock::printPutByIdOp(ExecState* exec, int location, Vector<Instruction>::const_iterator& it, const char* op)
404 {
405     int r0 = (++it)->u.operand;
406     int id0 = (++it)->u.operand;
407     int r1 = (++it)->u.operand;
408     dataLog("[%4d] %s\t %s, %s, %s\n", location, op, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), registerName(exec, r1).data());
409     it += 5;
410 }
411
412 #if ENABLE(JIT)
413 static bool isGlobalResolve(OpcodeID opcodeID)
414 {
415     return opcodeID == op_resolve_global || opcodeID == op_resolve_global_dynamic;
416 }
417
418 static unsigned instructionOffsetForNth(ExecState* exec, const RefCountedArray<Instruction>& instructions, int nth, bool (*predicate)(OpcodeID))
419 {
420     size_t i = 0;
421     while (i < instructions.size()) {
422         OpcodeID currentOpcode = exec->interpreter()->getOpcodeID(instructions[i].u.opcode);
423         if (predicate(currentOpcode)) {
424             if (!--nth)
425                 return i;
426         }
427         i += opcodeLengths[currentOpcode];
428     }
429
430     ASSERT_NOT_REACHED();
431     return 0;
432 }
433
434 static void printGlobalResolveInfo(const GlobalResolveInfo& resolveInfo, unsigned instructionOffset)
435 {
436     dataLog("  [%4d] %s: %s\n", instructionOffset, "resolve_global", pointerToSourceString(resolveInfo.structure).utf8().data());
437 }
438 #endif
439
440 void CodeBlock::printStructure(const char* name, const Instruction* vPC, int operand)
441 {
442     unsigned instructionOffset = vPC - instructions().begin();
443     dataLog("  [%4d] %s: %s\n", instructionOffset, name, pointerToSourceString(vPC[operand].u.structure).utf8().data());
444 }
445
446 void CodeBlock::printStructures(const Instruction* vPC)
447 {
448     Interpreter* interpreter = m_globalData->interpreter;
449     unsigned instructionOffset = vPC - instructions().begin();
450
451     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id)) {
452         printStructure("get_by_id", vPC, 4);
453         return;
454     }
455     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_self)) {
456         printStructure("get_by_id_self", vPC, 4);
457         return;
458     }
459     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_proto)) {
460         dataLog("  [%4d] %s: %s, %s\n", instructionOffset, "get_by_id_proto", pointerToSourceString(vPC[4].u.structure).utf8().data(), pointerToSourceString(vPC[5].u.structure).utf8().data());
461         return;
462     }
463     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_transition)) {
464         dataLog("  [%4d] %s: %s, %s, %s\n", instructionOffset, "put_by_id_transition", pointerToSourceString(vPC[4].u.structure).utf8().data(), pointerToSourceString(vPC[5].u.structure).utf8().data(), pointerToSourceString(vPC[6].u.structureChain).utf8().data());
465         return;
466     }
467     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_chain)) {
468         dataLog("  [%4d] %s: %s, %s\n", instructionOffset, "get_by_id_chain", pointerToSourceString(vPC[4].u.structure).utf8().data(), pointerToSourceString(vPC[5].u.structureChain).utf8().data());
469         return;
470     }
471     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id)) {
472         printStructure("put_by_id", vPC, 4);
473         return;
474     }
475     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_replace)) {
476         printStructure("put_by_id_replace", vPC, 4);
477         return;
478     }
479     if (vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global)) {
480         printStructure("resolve_global", vPC, 4);
481         return;
482     }
483     if (vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global_dynamic)) {
484         printStructure("resolve_global_dynamic", vPC, 4);
485         return;
486     }
487
488     // These m_instructions doesn't ref Structures.
489     ASSERT(vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_call) || vPC[0].u.opcode == interpreter->getOpcode(op_call_eval) || vPC[0].u.opcode == interpreter->getOpcode(op_construct));
490 }
491
492 void CodeBlock::dump(ExecState* exec)
493 {
494     size_t instructionCount = 0;
495
496     for (size_t i = 0; i < instructions().size(); i += opcodeLengths[exec->interpreter()->getOpcodeID(instructions()[i].u.opcode)])
497         ++instructionCount;
498
499     dataLog(
500         "%lu m_instructions; %lu bytes at %p (%s); %d parameter(s); %d callee register(s); %d variable(s)",
501         static_cast<unsigned long>(instructions().size()),
502         static_cast<unsigned long>(instructions().size() * sizeof(Instruction)),
503         this, codeTypeToString(codeType()), m_numParameters, m_numCalleeRegisters,
504         m_numVars);
505     if (m_numCapturedVars)
506         dataLog("; %d captured var(s)", m_numCapturedVars);
507     if (usesArguments()) {
508         dataLog(
509             "; uses arguments, in r%d, r%d",
510             argumentsRegister(),
511             unmodifiedArgumentsRegister(argumentsRegister()));
512     }
513     if (needsFullScopeChain() && codeType() == FunctionCode)
514         dataLog("; activation in r%d", activationRegister());
515     dataLog("\n\n");
516
517     Vector<Instruction>::const_iterator begin = instructions().begin();
518     Vector<Instruction>::const_iterator end = instructions().end();
519     for (Vector<Instruction>::const_iterator it = begin; it != end; ++it)
520         dump(exec, begin, it);
521
522     if (!m_identifiers.isEmpty()) {
523         dataLog("\nIdentifiers:\n");
524         size_t i = 0;
525         do {
526             dataLog("  id%u = %s\n", static_cast<unsigned>(i), m_identifiers[i].ustring().utf8().data());
527             ++i;
528         } while (i != m_identifiers.size());
529     }
530
531     if (!m_constantRegisters.isEmpty()) {
532         dataLog("\nConstants:\n");
533         size_t i = 0;
534         do {
535             dataLog("   k%u = %s\n", static_cast<unsigned>(i), valueToSourceString(exec, m_constantRegisters[i].get()).utf8().data());
536             ++i;
537         } while (i < m_constantRegisters.size());
538     }
539
540     if (m_rareData && !m_rareData->m_regexps.isEmpty()) {
541         dataLog("\nm_regexps:\n");
542         size_t i = 0;
543         do {
544             dataLog("  re%u = %s\n", static_cast<unsigned>(i), regexpToSourceString(m_rareData->m_regexps[i].get()).utf8().data());
545             ++i;
546         } while (i < m_rareData->m_regexps.size());
547     }
548
549 #if ENABLE(JIT)
550     if (!m_globalResolveInfos.isEmpty() || !m_structureStubInfos.isEmpty())
551         dataLog("\nStructures:\n");
552
553     if (!m_globalResolveInfos.isEmpty()) {
554         size_t i = 0;
555         do {
556              printGlobalResolveInfo(m_globalResolveInfos[i], instructionOffsetForNth(exec, instructions(), i + 1, isGlobalResolve));
557              ++i;
558         } while (i < m_globalResolveInfos.size());
559     }
560 #endif
561 #if ENABLE(CLASSIC_INTERPRETER)
562     if (!m_globalResolveInstructions.isEmpty() || !m_propertyAccessInstructions.isEmpty())
563         dataLog("\nStructures:\n");
564
565     if (!m_globalResolveInstructions.isEmpty()) {
566         size_t i = 0;
567         do {
568              printStructures(&instructions()[m_globalResolveInstructions[i]]);
569              ++i;
570         } while (i < m_globalResolveInstructions.size());
571     }
572     if (!m_propertyAccessInstructions.isEmpty()) {
573         size_t i = 0;
574         do {
575             printStructures(&instructions()[m_propertyAccessInstructions[i]]);
576              ++i;
577         } while (i < m_propertyAccessInstructions.size());
578     }
579 #endif
580
581     if (m_rareData && !m_rareData->m_exceptionHandlers.isEmpty()) {
582         dataLog("\nException Handlers:\n");
583         unsigned i = 0;
584         do {
585             dataLog("\t %d: { start: [%4d] end: [%4d] target: [%4d] }\n", i + 1, m_rareData->m_exceptionHandlers[i].start, m_rareData->m_exceptionHandlers[i].end, m_rareData->m_exceptionHandlers[i].target);
586             ++i;
587         } while (i < m_rareData->m_exceptionHandlers.size());
588     }
589     
590     if (m_rareData && !m_rareData->m_immediateSwitchJumpTables.isEmpty()) {
591         dataLog("Immediate Switch Jump Tables:\n");
592         unsigned i = 0;
593         do {
594             dataLog("  %1d = {\n", i);
595             int entry = 0;
596             Vector<int32_t>::const_iterator end = m_rareData->m_immediateSwitchJumpTables[i].branchOffsets.end();
597             for (Vector<int32_t>::const_iterator iter = m_rareData->m_immediateSwitchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
598                 if (!*iter)
599                     continue;
600                 dataLog("\t\t%4d => %04d\n", entry + m_rareData->m_immediateSwitchJumpTables[i].min, *iter);
601             }
602             dataLog("      }\n");
603             ++i;
604         } while (i < m_rareData->m_immediateSwitchJumpTables.size());
605     }
606     
607     if (m_rareData && !m_rareData->m_characterSwitchJumpTables.isEmpty()) {
608         dataLog("\nCharacter Switch Jump Tables:\n");
609         unsigned i = 0;
610         do {
611             dataLog("  %1d = {\n", i);
612             int entry = 0;
613             Vector<int32_t>::const_iterator end = m_rareData->m_characterSwitchJumpTables[i].branchOffsets.end();
614             for (Vector<int32_t>::const_iterator iter = m_rareData->m_characterSwitchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
615                 if (!*iter)
616                     continue;
617                 ASSERT(!((i + m_rareData->m_characterSwitchJumpTables[i].min) & ~0xFFFF));
618                 UChar ch = static_cast<UChar>(entry + m_rareData->m_characterSwitchJumpTables[i].min);
619                 dataLog("\t\t\"%s\" => %04d\n", UString(&ch, 1).utf8().data(), *iter);
620         }
621             dataLog("      }\n");
622             ++i;
623         } while (i < m_rareData->m_characterSwitchJumpTables.size());
624     }
625     
626     if (m_rareData && !m_rareData->m_stringSwitchJumpTables.isEmpty()) {
627         dataLog("\nString Switch Jump Tables:\n");
628         unsigned i = 0;
629         do {
630             dataLog("  %1d = {\n", i);
631             StringJumpTable::StringOffsetTable::const_iterator end = m_rareData->m_stringSwitchJumpTables[i].offsetTable.end();
632             for (StringJumpTable::StringOffsetTable::const_iterator iter = m_rareData->m_stringSwitchJumpTables[i].offsetTable.begin(); iter != end; ++iter)
633                 dataLog("\t\t\"%s\" => %04d\n", UString(iter->first).utf8().data(), iter->second.branchOffset);
634             dataLog("      }\n");
635             ++i;
636         } while (i < m_rareData->m_stringSwitchJumpTables.size());
637     }
638
639     dataLog("\n");
640 }
641
642 void CodeBlock::dump(ExecState* exec, const Vector<Instruction>::const_iterator& begin, Vector<Instruction>::const_iterator& it)
643 {
644     int location = it - begin;
645     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
646         case op_enter: {
647             dataLog("[%4d] enter\n", location);
648             break;
649         }
650         case op_create_activation: {
651             int r0 = (++it)->u.operand;
652             dataLog("[%4d] create_activation %s\n", location, registerName(exec, r0).data());
653             break;
654         }
655         case op_create_arguments: {
656             int r0 = (++it)->u.operand;
657             dataLog("[%4d] create_arguments\t %s\n", location, registerName(exec, r0).data());
658             break;
659         }
660         case op_init_lazy_reg: {
661             int r0 = (++it)->u.operand;
662             dataLog("[%4d] init_lazy_reg\t %s\n", location, registerName(exec, r0).data());
663             break;
664         }
665         case op_create_this: {
666             int r0 = (++it)->u.operand;
667             dataLog("[%4d] create_this %s\n", location, registerName(exec, r0).data());
668             break;
669         }
670         case op_convert_this: {
671             int r0 = (++it)->u.operand;
672             dataLog("[%4d] convert_this\t %s\n", location, registerName(exec, r0).data());
673             ++it; // Skip value profile.
674             break;
675         }
676         case op_new_object: {
677             int r0 = (++it)->u.operand;
678             dataLog("[%4d] new_object\t %s\n", location, registerName(exec, r0).data());
679             break;
680         }
681         case op_new_array: {
682             int dst = (++it)->u.operand;
683             int argv = (++it)->u.operand;
684             int argc = (++it)->u.operand;
685             dataLog("[%4d] new_array\t %s, %s, %d\n", location, registerName(exec, dst).data(), registerName(exec, argv).data(), argc);
686             break;
687         }
688         case op_new_array_buffer: {
689             int dst = (++it)->u.operand;
690             int argv = (++it)->u.operand;
691             int argc = (++it)->u.operand;
692             dataLog("[%4d] new_array_buffer %s, %d, %d\n", location, registerName(exec, dst).data(), argv, argc);
693             break;
694         }
695         case op_new_regexp: {
696             int r0 = (++it)->u.operand;
697             int re0 = (++it)->u.operand;
698             dataLog("[%4d] new_regexp\t %s, ", location, registerName(exec, r0).data());
699             if (r0 >=0 && r0 < (int)numberOfRegExps())
700                 dataLog("%s\n", regexpName(re0, regexp(re0)).data());
701             else
702                 dataLog("bad_regexp(%d)\n", re0);
703             break;
704         }
705         case op_mov: {
706             int r0 = (++it)->u.operand;
707             int r1 = (++it)->u.operand;
708             dataLog("[%4d] mov\t\t %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
709             break;
710         }
711         case op_not: {
712             printUnaryOp(exec, location, it, "not");
713             break;
714         }
715         case op_eq: {
716             printBinaryOp(exec, location, it, "eq");
717             break;
718         }
719         case op_eq_null: {
720             printUnaryOp(exec, location, it, "eq_null");
721             break;
722         }
723         case op_neq: {
724             printBinaryOp(exec, location, it, "neq");
725             break;
726         }
727         case op_neq_null: {
728             printUnaryOp(exec, location, it, "neq_null");
729             break;
730         }
731         case op_stricteq: {
732             printBinaryOp(exec, location, it, "stricteq");
733             break;
734         }
735         case op_nstricteq: {
736             printBinaryOp(exec, location, it, "nstricteq");
737             break;
738         }
739         case op_less: {
740             printBinaryOp(exec, location, it, "less");
741             break;
742         }
743         case op_lesseq: {
744             printBinaryOp(exec, location, it, "lesseq");
745             break;
746         }
747         case op_greater: {
748             printBinaryOp(exec, location, it, "greater");
749             break;
750         }
751         case op_greatereq: {
752             printBinaryOp(exec, location, it, "greatereq");
753             break;
754         }
755         case op_pre_inc: {
756             int r0 = (++it)->u.operand;
757             dataLog("[%4d] pre_inc\t\t %s\n", location, registerName(exec, r0).data());
758             break;
759         }
760         case op_pre_dec: {
761             int r0 = (++it)->u.operand;
762             dataLog("[%4d] pre_dec\t\t %s\n", location, registerName(exec, r0).data());
763             break;
764         }
765         case op_post_inc: {
766             printUnaryOp(exec, location, it, "post_inc");
767             break;
768         }
769         case op_post_dec: {
770             printUnaryOp(exec, location, it, "post_dec");
771             break;
772         }
773         case op_to_jsnumber: {
774             printUnaryOp(exec, location, it, "to_jsnumber");
775             break;
776         }
777         case op_negate: {
778             printUnaryOp(exec, location, it, "negate");
779             break;
780         }
781         case op_add: {
782             printBinaryOp(exec, location, it, "add");
783             ++it;
784             break;
785         }
786         case op_mul: {
787             printBinaryOp(exec, location, it, "mul");
788             ++it;
789             break;
790         }
791         case op_div: {
792             printBinaryOp(exec, location, it, "div");
793             ++it;
794             break;
795         }
796         case op_mod: {
797             printBinaryOp(exec, location, it, "mod");
798             break;
799         }
800         case op_sub: {
801             printBinaryOp(exec, location, it, "sub");
802             ++it;
803             break;
804         }
805         case op_lshift: {
806             printBinaryOp(exec, location, it, "lshift");
807             break;            
808         }
809         case op_rshift: {
810             printBinaryOp(exec, location, it, "rshift");
811             break;
812         }
813         case op_urshift: {
814             printBinaryOp(exec, location, it, "urshift");
815             break;
816         }
817         case op_bitand: {
818             printBinaryOp(exec, location, it, "bitand");
819             ++it;
820             break;
821         }
822         case op_bitxor: {
823             printBinaryOp(exec, location, it, "bitxor");
824             ++it;
825             break;
826         }
827         case op_bitor: {
828             printBinaryOp(exec, location, it, "bitor");
829             ++it;
830             break;
831         }
832         case op_check_has_instance: {
833             int base = (++it)->u.operand;
834             dataLog("[%4d] check_has_instance\t\t %s\n", location, registerName(exec, base).data());
835             break;
836         }
837         case op_instanceof: {
838             int r0 = (++it)->u.operand;
839             int r1 = (++it)->u.operand;
840             int r2 = (++it)->u.operand;
841             int r3 = (++it)->u.operand;
842             dataLog("[%4d] instanceof\t\t %s, %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data(), registerName(exec, r3).data());
843             break;
844         }
845         case op_typeof: {
846             printUnaryOp(exec, location, it, "typeof");
847             break;
848         }
849         case op_is_undefined: {
850             printUnaryOp(exec, location, it, "is_undefined");
851             break;
852         }
853         case op_is_boolean: {
854             printUnaryOp(exec, location, it, "is_boolean");
855             break;
856         }
857         case op_is_number: {
858             printUnaryOp(exec, location, it, "is_number");
859             break;
860         }
861         case op_is_string: {
862             printUnaryOp(exec, location, it, "is_string");
863             break;
864         }
865         case op_is_object: {
866             printUnaryOp(exec, location, it, "is_object");
867             break;
868         }
869         case op_is_function: {
870             printUnaryOp(exec, location, it, "is_function");
871             break;
872         }
873         case op_in: {
874             printBinaryOp(exec, location, it, "in");
875             break;
876         }
877         case op_resolve: {
878             int r0 = (++it)->u.operand;
879             int id0 = (++it)->u.operand;
880             dataLog("[%4d] resolve\t\t %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
881             it++;
882             break;
883         }
884         case op_resolve_skip: {
885             int r0 = (++it)->u.operand;
886             int id0 = (++it)->u.operand;
887             int skipLevels = (++it)->u.operand;
888             dataLog("[%4d] resolve_skip\t %s, %s, %d\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), skipLevels);
889             it++;
890             break;
891         }
892         case op_resolve_global: {
893             int r0 = (++it)->u.operand;
894             int id0 = (++it)->u.operand;
895             dataLog("[%4d] resolve_global\t %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
896             it += 3;
897             break;
898         }
899         case op_resolve_global_dynamic: {
900             int r0 = (++it)->u.operand;
901             int id0 = (++it)->u.operand;
902             JSValue scope = JSValue((++it)->u.jsCell.get());
903             ++it;
904             int depth = (++it)->u.operand;
905             dataLog("[%4d] resolve_global_dynamic\t %s, %s, %s, %d\n", location, registerName(exec, r0).data(), valueToSourceString(exec, scope).utf8().data(), idName(id0, m_identifiers[id0]).data(), depth);
906             ++it;
907             break;
908         }
909         case op_get_scoped_var: {
910             int r0 = (++it)->u.operand;
911             int index = (++it)->u.operand;
912             int skipLevels = (++it)->u.operand;
913             dataLog("[%4d] get_scoped_var\t %s, %d, %d\n", location, registerName(exec, r0).data(), index, skipLevels);
914             it++;
915             break;
916         }
917         case op_put_scoped_var: {
918             int index = (++it)->u.operand;
919             int skipLevels = (++it)->u.operand;
920             int r0 = (++it)->u.operand;
921             dataLog("[%4d] put_scoped_var\t %d, %d, %s\n", location, index, skipLevels, registerName(exec, r0).data());
922             break;
923         }
924         case op_get_global_var: {
925             int r0 = (++it)->u.operand;
926             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
927             dataLog("[%4d] get_global_var\t %s, g%d(%p)\n", location, registerName(exec, r0).data(), m_globalObject->findRegisterIndex(registerPointer), registerPointer);
928             it++;
929             break;
930         }
931         case op_put_global_var: {
932             WriteBarrier<Unknown>* registerPointer = (++it)->u.registerPointer;
933             int r0 = (++it)->u.operand;
934             dataLog("[%4d] put_global_var\t g%d(%p), %s\n", location, m_globalObject->findRegisterIndex(registerPointer), registerPointer, registerName(exec, r0).data());
935             break;
936         }
937         case op_resolve_base: {
938             int r0 = (++it)->u.operand;
939             int id0 = (++it)->u.operand;
940             int isStrict = (++it)->u.operand;
941             dataLog("[%4d] resolve_base%s\t %s, %s\n", location, isStrict ? "_strict" : "", registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
942             it++;
943             break;
944         }
945         case op_ensure_property_exists: {
946             int r0 = (++it)->u.operand;
947             int id0 = (++it)->u.operand;
948             dataLog("[%4d] ensure_property_exists\t %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data());
949             break;
950         }
951         case op_resolve_with_base: {
952             int r0 = (++it)->u.operand;
953             int r1 = (++it)->u.operand;
954             int id0 = (++it)->u.operand;
955             dataLog("[%4d] resolve_with_base %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
956             it++;
957             break;
958         }
959         case op_resolve_with_this: {
960             int r0 = (++it)->u.operand;
961             int r1 = (++it)->u.operand;
962             int id0 = (++it)->u.operand;
963             dataLog("[%4d] resolve_with_this %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
964             it++;
965             break;
966         }
967         case op_get_by_id:
968         case op_get_by_id_self:
969         case op_get_by_id_proto:
970         case op_get_by_id_chain:
971         case op_get_by_id_getter_self:
972         case op_get_by_id_getter_proto:
973         case op_get_by_id_getter_chain:
974         case op_get_by_id_custom_self:
975         case op_get_by_id_custom_proto:
976         case op_get_by_id_custom_chain:
977         case op_get_by_id_generic:
978         case op_get_array_length:
979         case op_get_string_length: {
980             printGetByIdOp(exec, location, it);
981             printGetByIdCacheStatus(exec, location);
982             dataLog("\n");
983             break;
984         }
985         case op_get_arguments_length: {
986             printUnaryOp(exec, location, it, "get_arguments_length");
987             it++;
988             break;
989         }
990         case op_put_by_id: {
991             printPutByIdOp(exec, location, it, "put_by_id");
992             break;
993         }
994         case op_put_by_id_replace: {
995             printPutByIdOp(exec, location, it, "put_by_id_replace");
996             break;
997         }
998         case op_put_by_id_transition: {
999             printPutByIdOp(exec, location, it, "put_by_id_transition");
1000             break;
1001         }
1002         case op_put_by_id_transition_direct: {
1003             printPutByIdOp(exec, location, it, "put_by_id_transition_direct");
1004             break;
1005         }
1006         case op_put_by_id_transition_normal: {
1007             printPutByIdOp(exec, location, it, "put_by_id_transition_normal");
1008             break;
1009         }
1010         case op_put_by_id_generic: {
1011             printPutByIdOp(exec, location, it, "put_by_id_generic");
1012             break;
1013         }
1014         case op_put_getter_setter: {
1015             int r0 = (++it)->u.operand;
1016             int id0 = (++it)->u.operand;
1017             int r1 = (++it)->u.operand;
1018             int r2 = (++it)->u.operand;
1019             dataLog("[%4d] put_getter_setter\t %s, %s, %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1020             break;
1021         }
1022         case op_method_check: {
1023             dataLog("[%4d] method_check", location);
1024 #if ENABLE(JIT)
1025             if (numberOfMethodCallLinkInfos()) {
1026                 MethodCallLinkInfo& methodCall = getMethodCallLinkInfo(location);
1027                 dataLog(" jit(");
1028                 if (!methodCall.seen)
1029                     dataLog("not seen");
1030                 else {
1031                     // Use the fact that MethodCallLinkStatus already does smart things
1032                     // for decoding seen method calls.
1033                     MethodCallLinkStatus status = MethodCallLinkStatus::computeFor(this, location);
1034                     if (!status)
1035                         dataLog("not set");
1036                     else {
1037                         dataLog("function = %p (executable = ", status.function());
1038                         JSCell* functionAsCell = getJSFunction(status.function());
1039                         if (functionAsCell)
1040                             dataLog("%p", jsCast<JSFunction*>(functionAsCell)->executable());
1041                         else
1042                             dataLog("N/A");
1043                         dataLog("), struct = %p", status.structure());
1044                         if (status.needsPrototypeCheck())
1045                             dataLog(", prototype = %p, struct = %p", status.prototype(), status.prototypeStructure());
1046                     }
1047                 }
1048                 dataLog(")");
1049             }
1050 #endif
1051             dataLog("\n");
1052             ++it;
1053             printGetByIdOp(exec, location, it);
1054             printGetByIdCacheStatus(exec, location);
1055             dataLog("\n");
1056             break;
1057         }
1058         case op_del_by_id: {
1059             int r0 = (++it)->u.operand;
1060             int r1 = (++it)->u.operand;
1061             int id0 = (++it)->u.operand;
1062             dataLog("[%4d] del_by_id\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), idName(id0, m_identifiers[id0]).data());
1063             break;
1064         }
1065         case op_get_by_val: {
1066             int r0 = (++it)->u.operand;
1067             int r1 = (++it)->u.operand;
1068             int r2 = (++it)->u.operand;
1069             dataLog("[%4d] get_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1070             it++;
1071             break;
1072         }
1073         case op_get_argument_by_val: {
1074             int r0 = (++it)->u.operand;
1075             int r1 = (++it)->u.operand;
1076             int r2 = (++it)->u.operand;
1077             dataLog("[%4d] get_argument_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1078             ++it;
1079             break;
1080         }
1081         case op_get_by_pname: {
1082             int r0 = (++it)->u.operand;
1083             int r1 = (++it)->u.operand;
1084             int r2 = (++it)->u.operand;
1085             int r3 = (++it)->u.operand;
1086             int r4 = (++it)->u.operand;
1087             int r5 = (++it)->u.operand;
1088             dataLog("[%4d] get_by_pname\t %s, %s, %s, %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data(), registerName(exec, r3).data(), registerName(exec, r4).data(), registerName(exec, r5).data());
1089             break;
1090         }
1091         case op_put_by_val: {
1092             int r0 = (++it)->u.operand;
1093             int r1 = (++it)->u.operand;
1094             int r2 = (++it)->u.operand;
1095             dataLog("[%4d] put_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1096             break;
1097         }
1098         case op_del_by_val: {
1099             int r0 = (++it)->u.operand;
1100             int r1 = (++it)->u.operand;
1101             int r2 = (++it)->u.operand;
1102             dataLog("[%4d] del_by_val\t %s, %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data());
1103             break;
1104         }
1105         case op_put_by_index: {
1106             int r0 = (++it)->u.operand;
1107             unsigned n0 = (++it)->u.operand;
1108             int r1 = (++it)->u.operand;
1109             dataLog("[%4d] put_by_index\t %s, %u, %s\n", location, registerName(exec, r0).data(), n0, registerName(exec, r1).data());
1110             break;
1111         }
1112         case op_jmp: {
1113             int offset = (++it)->u.operand;
1114             dataLog("[%4d] jmp\t\t %d(->%d)\n", location, offset, location + offset);
1115             break;
1116         }
1117         case op_loop: {
1118             int offset = (++it)->u.operand;
1119             dataLog("[%4d] loop\t\t %d(->%d)\n", location, offset, location + offset);
1120             break;
1121         }
1122         case op_jtrue: {
1123             printConditionalJump(exec, begin, it, location, "jtrue");
1124             break;
1125         }
1126         case op_loop_if_true: {
1127             printConditionalJump(exec, begin, it, location, "loop_if_true");
1128             break;
1129         }
1130         case op_loop_if_false: {
1131             printConditionalJump(exec, begin, it, location, "loop_if_false");
1132             break;
1133         }
1134         case op_jfalse: {
1135             printConditionalJump(exec, begin, it, location, "jfalse");
1136             break;
1137         }
1138         case op_jeq_null: {
1139             printConditionalJump(exec, begin, it, location, "jeq_null");
1140             break;
1141         }
1142         case op_jneq_null: {
1143             printConditionalJump(exec, begin, it, location, "jneq_null");
1144             break;
1145         }
1146         case op_jneq_ptr: {
1147             int r0 = (++it)->u.operand;
1148             void* pointer = (++it)->u.pointer;
1149             int offset = (++it)->u.operand;
1150             dataLog("[%4d] jneq_ptr\t\t %s, %p, %d(->%d)\n", location, registerName(exec, r0).data(), pointer, offset, location + offset);
1151             break;
1152         }
1153         case op_jless: {
1154             int r0 = (++it)->u.operand;
1155             int r1 = (++it)->u.operand;
1156             int offset = (++it)->u.operand;
1157             dataLog("[%4d] jless\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1158             break;
1159         }
1160         case op_jlesseq: {
1161             int r0 = (++it)->u.operand;
1162             int r1 = (++it)->u.operand;
1163             int offset = (++it)->u.operand;
1164             dataLog("[%4d] jlesseq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1165             break;
1166         }
1167         case op_jgreater: {
1168             int r0 = (++it)->u.operand;
1169             int r1 = (++it)->u.operand;
1170             int offset = (++it)->u.operand;
1171             dataLog("[%4d] jgreater\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1172             break;
1173         }
1174         case op_jgreatereq: {
1175             int r0 = (++it)->u.operand;
1176             int r1 = (++it)->u.operand;
1177             int offset = (++it)->u.operand;
1178             dataLog("[%4d] jgreatereq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1179             break;
1180         }
1181         case op_jnless: {
1182             int r0 = (++it)->u.operand;
1183             int r1 = (++it)->u.operand;
1184             int offset = (++it)->u.operand;
1185             dataLog("[%4d] jnless\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1186             break;
1187         }
1188         case op_jnlesseq: {
1189             int r0 = (++it)->u.operand;
1190             int r1 = (++it)->u.operand;
1191             int offset = (++it)->u.operand;
1192             dataLog("[%4d] jnlesseq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1193             break;
1194         }
1195         case op_jngreater: {
1196             int r0 = (++it)->u.operand;
1197             int r1 = (++it)->u.operand;
1198             int offset = (++it)->u.operand;
1199             dataLog("[%4d] jngreater\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1200             break;
1201         }
1202         case op_jngreatereq: {
1203             int r0 = (++it)->u.operand;
1204             int r1 = (++it)->u.operand;
1205             int offset = (++it)->u.operand;
1206             dataLog("[%4d] jngreatereq\t\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1207             break;
1208         }
1209         case op_loop_if_less: {
1210             int r0 = (++it)->u.operand;
1211             int r1 = (++it)->u.operand;
1212             int offset = (++it)->u.operand;
1213             dataLog("[%4d] loop_if_less\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1214             break;
1215         }
1216         case op_loop_if_lesseq: {
1217             int r0 = (++it)->u.operand;
1218             int r1 = (++it)->u.operand;
1219             int offset = (++it)->u.operand;
1220             dataLog("[%4d] loop_if_lesseq\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1221             break;
1222         }
1223         case op_loop_if_greater: {
1224             int r0 = (++it)->u.operand;
1225             int r1 = (++it)->u.operand;
1226             int offset = (++it)->u.operand;
1227             dataLog("[%4d] loop_if_greater\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1228             break;
1229         }
1230         case op_loop_if_greatereq: {
1231             int r0 = (++it)->u.operand;
1232             int r1 = (++it)->u.operand;
1233             int offset = (++it)->u.operand;
1234             dataLog("[%4d] loop_if_greatereq\t %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), offset, location + offset);
1235             break;
1236         }
1237         case op_loop_hint: {
1238             dataLog("[%4d] loop_hint\n", location);
1239             break;
1240         }
1241         case op_switch_imm: {
1242             int tableIndex = (++it)->u.operand;
1243             int defaultTarget = (++it)->u.operand;
1244             int scrutineeRegister = (++it)->u.operand;
1245             dataLog("[%4d] switch_imm\t %d, %d(->%d), %s\n", location, tableIndex, defaultTarget, location + defaultTarget, registerName(exec, scrutineeRegister).data());
1246             break;
1247         }
1248         case op_switch_char: {
1249             int tableIndex = (++it)->u.operand;
1250             int defaultTarget = (++it)->u.operand;
1251             int scrutineeRegister = (++it)->u.operand;
1252             dataLog("[%4d] switch_char\t %d, %d(->%d), %s\n", location, tableIndex, defaultTarget, location + defaultTarget, registerName(exec, scrutineeRegister).data());
1253             break;
1254         }
1255         case op_switch_string: {
1256             int tableIndex = (++it)->u.operand;
1257             int defaultTarget = (++it)->u.operand;
1258             int scrutineeRegister = (++it)->u.operand;
1259             dataLog("[%4d] switch_string\t %d, %d(->%d), %s\n", location, tableIndex, defaultTarget, location + defaultTarget, registerName(exec, scrutineeRegister).data());
1260             break;
1261         }
1262         case op_new_func: {
1263             int r0 = (++it)->u.operand;
1264             int f0 = (++it)->u.operand;
1265             int shouldCheck = (++it)->u.operand;
1266             dataLog("[%4d] new_func\t\t %s, f%d, %s\n", location, registerName(exec, r0).data(), f0, shouldCheck ? "<Checked>" : "<Unchecked>");
1267             break;
1268         }
1269         case op_new_func_exp: {
1270             int r0 = (++it)->u.operand;
1271             int f0 = (++it)->u.operand;
1272             dataLog("[%4d] new_func_exp\t %s, f%d\n", location, registerName(exec, r0).data(), f0);
1273             break;
1274         }
1275         case op_call: {
1276             printCallOp(exec, location, it, "call", DumpCaches);
1277             break;
1278         }
1279         case op_call_eval: {
1280             printCallOp(exec, location, it, "call_eval", DontDumpCaches);
1281             break;
1282         }
1283         case op_call_varargs: {
1284             int callee = (++it)->u.operand;
1285             int thisValue = (++it)->u.operand;
1286             int arguments = (++it)->u.operand;
1287             int firstFreeRegister = (++it)->u.operand;
1288             dataLog("[%4d] call_varargs\t %s, %s, %s, %d\n", location, registerName(exec, callee).data(), registerName(exec, thisValue).data(), registerName(exec, arguments).data(), firstFreeRegister);
1289             break;
1290         }
1291         case op_tear_off_activation: {
1292             int r0 = (++it)->u.operand;
1293             int r1 = (++it)->u.operand;
1294             dataLog("[%4d] tear_off_activation\t %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
1295             break;
1296         }
1297         case op_tear_off_arguments: {
1298             int r0 = (++it)->u.operand;
1299             dataLog("[%4d] tear_off_arguments %s\n", location, registerName(exec, r0).data());
1300             break;
1301         }
1302         case op_ret: {
1303             int r0 = (++it)->u.operand;
1304             dataLog("[%4d] ret\t\t %s\n", location, registerName(exec, r0).data());
1305             break;
1306         }
1307         case op_call_put_result: {
1308             int r0 = (++it)->u.operand;
1309             dataLog("[%4d] op_call_put_result\t\t %s\n", location, registerName(exec, r0).data());
1310             it++;
1311             break;
1312         }
1313         case op_ret_object_or_this: {
1314             int r0 = (++it)->u.operand;
1315             int r1 = (++it)->u.operand;
1316             dataLog("[%4d] constructor_ret\t\t %s %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
1317             break;
1318         }
1319         case op_construct: {
1320             printCallOp(exec, location, it, "construct", DumpCaches);
1321             break;
1322         }
1323         case op_strcat: {
1324             int r0 = (++it)->u.operand;
1325             int r1 = (++it)->u.operand;
1326             int count = (++it)->u.operand;
1327             dataLog("[%4d] strcat\t\t %s, %s, %d\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), count);
1328             break;
1329         }
1330         case op_to_primitive: {
1331             int r0 = (++it)->u.operand;
1332             int r1 = (++it)->u.operand;
1333             dataLog("[%4d] to_primitive\t %s, %s\n", location, registerName(exec, r0).data(), registerName(exec, r1).data());
1334             break;
1335         }
1336         case op_get_pnames: {
1337             int r0 = it[1].u.operand;
1338             int r1 = it[2].u.operand;
1339             int r2 = it[3].u.operand;
1340             int r3 = it[4].u.operand;
1341             int offset = it[5].u.operand;
1342             dataLog("[%4d] get_pnames\t %s, %s, %s, %s, %d(->%d)\n", location, registerName(exec, r0).data(), registerName(exec, r1).data(), registerName(exec, r2).data(), registerName(exec, r3).data(), offset, location + offset);
1343             it += OPCODE_LENGTH(op_get_pnames) - 1;
1344             break;
1345         }
1346         case op_next_pname: {
1347             int dest = it[1].u.operand;
1348             int base = it[2].u.operand;
1349             int i = it[3].u.operand;
1350             int size = it[4].u.operand;
1351             int iter = it[5].u.operand;
1352             int offset = it[6].u.operand;
1353             dataLog("[%4d] next_pname\t %s, %s, %s, %s, %s, %d(->%d)\n", location, registerName(exec, dest).data(), registerName(exec, base).data(), registerName(exec, i).data(), registerName(exec, size).data(), registerName(exec, iter).data(), offset, location + offset);
1354             it += OPCODE_LENGTH(op_next_pname) - 1;
1355             break;
1356         }
1357         case op_push_scope: {
1358             int r0 = (++it)->u.operand;
1359             dataLog("[%4d] push_scope\t %s\n", location, registerName(exec, r0).data());
1360             break;
1361         }
1362         case op_pop_scope: {
1363             dataLog("[%4d] pop_scope\n", location);
1364             break;
1365         }
1366         case op_push_new_scope: {
1367             int r0 = (++it)->u.operand;
1368             int id0 = (++it)->u.operand;
1369             int r1 = (++it)->u.operand;
1370             dataLog("[%4d] push_new_scope \t%s, %s, %s\n", location, registerName(exec, r0).data(), idName(id0, m_identifiers[id0]).data(), registerName(exec, r1).data());
1371             break;
1372         }
1373         case op_jmp_scopes: {
1374             int scopeDelta = (++it)->u.operand;
1375             int offset = (++it)->u.operand;
1376             dataLog("[%4d] jmp_scopes\t^%d, %d(->%d)\n", location, scopeDelta, offset, location + offset);
1377             break;
1378         }
1379         case op_catch: {
1380             int r0 = (++it)->u.operand;
1381             dataLog("[%4d] catch\t\t %s\n", location, registerName(exec, r0).data());
1382             break;
1383         }
1384         case op_throw: {
1385             int r0 = (++it)->u.operand;
1386             dataLog("[%4d] throw\t\t %s\n", location, registerName(exec, r0).data());
1387             break;
1388         }
1389         case op_throw_reference_error: {
1390             int k0 = (++it)->u.operand;
1391             dataLog("[%4d] throw_reference_error\t %s\n", location, constantName(exec, k0, getConstant(k0)).data());
1392             break;
1393         }
1394         case op_debug: {
1395             int debugHookID = (++it)->u.operand;
1396             int firstLine = (++it)->u.operand;
1397             int lastLine = (++it)->u.operand;
1398             dataLog("[%4d] debug\t\t %s, %d, %d\n", location, debugHookName(debugHookID), firstLine, lastLine);
1399             break;
1400         }
1401         case op_profile_will_call: {
1402             int function = (++it)->u.operand;
1403             dataLog("[%4d] profile_will_call %s\n", location, registerName(exec, function).data());
1404             break;
1405         }
1406         case op_profile_did_call: {
1407             int function = (++it)->u.operand;
1408             dataLog("[%4d] profile_did_call\t %s\n", location, registerName(exec, function).data());
1409             break;
1410         }
1411         case op_end: {
1412             int r0 = (++it)->u.operand;
1413             dataLog("[%4d] end\t\t %s\n", location, registerName(exec, r0).data());
1414             break;
1415         }
1416     }
1417 }
1418
1419 #if DUMP_CODE_BLOCK_STATISTICS
1420 static HashSet<CodeBlock*> liveCodeBlockSet;
1421 #endif
1422
1423 #define FOR_EACH_MEMBER_VECTOR(macro) \
1424     macro(instructions) \
1425     macro(globalResolveInfos) \
1426     macro(structureStubInfos) \
1427     macro(callLinkInfos) \
1428     macro(linkedCallerList) \
1429     macro(identifiers) \
1430     macro(functionExpressions) \
1431     macro(constantRegisters)
1432
1433 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1434     macro(regexps) \
1435     macro(functions) \
1436     macro(exceptionHandlers) \
1437     macro(immediateSwitchJumpTables) \
1438     macro(characterSwitchJumpTables) \
1439     macro(stringSwitchJumpTables) \
1440     macro(evalCodeCache) \
1441     macro(expressionInfo) \
1442     macro(lineInfo) \
1443     macro(callReturnIndexVector)
1444
1445 template<typename T>
1446 static size_t sizeInBytes(const Vector<T>& vector)
1447 {
1448     return vector.capacity() * sizeof(T);
1449 }
1450
1451 void CodeBlock::dumpStatistics()
1452 {
1453 #if DUMP_CODE_BLOCK_STATISTICS
1454     #define DEFINE_VARS(name) size_t name##IsNotEmpty = 0; size_t name##TotalSize = 0;
1455         FOR_EACH_MEMBER_VECTOR(DEFINE_VARS)
1456         FOR_EACH_MEMBER_VECTOR_RARE_DATA(DEFINE_VARS)
1457     #undef DEFINE_VARS
1458
1459     // Non-vector data members
1460     size_t evalCodeCacheIsNotEmpty = 0;
1461
1462     size_t symbolTableIsNotEmpty = 0;
1463     size_t symbolTableTotalSize = 0;
1464
1465     size_t hasRareData = 0;
1466
1467     size_t isFunctionCode = 0;
1468     size_t isGlobalCode = 0;
1469     size_t isEvalCode = 0;
1470
1471     HashSet<CodeBlock*>::const_iterator end = liveCodeBlockSet.end();
1472     for (HashSet<CodeBlock*>::const_iterator it = liveCodeBlockSet.begin(); it != end; ++it) {
1473         CodeBlock* codeBlock = *it;
1474
1475         #define GET_STATS(name) if (!codeBlock->m_##name.isEmpty()) { name##IsNotEmpty++; name##TotalSize += sizeInBytes(codeBlock->m_##name); }
1476             FOR_EACH_MEMBER_VECTOR(GET_STATS)
1477         #undef GET_STATS
1478
1479         if (!codeBlock->m_symbolTable.isEmpty()) {
1480             symbolTableIsNotEmpty++;
1481             symbolTableTotalSize += (codeBlock->m_symbolTable.capacity() * (sizeof(SymbolTable::KeyType) + sizeof(SymbolTable::MappedType)));
1482         }
1483
1484         if (codeBlock->m_rareData) {
1485             hasRareData++;
1486             #define GET_STATS(name) if (!codeBlock->m_rareData->m_##name.isEmpty()) { name##IsNotEmpty++; name##TotalSize += sizeInBytes(codeBlock->m_rareData->m_##name); }
1487                 FOR_EACH_MEMBER_VECTOR_RARE_DATA(GET_STATS)
1488             #undef GET_STATS
1489
1490             if (!codeBlock->m_rareData->m_evalCodeCache.isEmpty())
1491                 evalCodeCacheIsNotEmpty++;
1492         }
1493
1494         switch (codeBlock->codeType()) {
1495             case FunctionCode:
1496                 ++isFunctionCode;
1497                 break;
1498             case GlobalCode:
1499                 ++isGlobalCode;
1500                 break;
1501             case EvalCode:
1502                 ++isEvalCode;
1503                 break;
1504         }
1505     }
1506
1507     size_t totalSize = 0;
1508
1509     #define GET_TOTAL_SIZE(name) totalSize += name##TotalSize;
1510         FOR_EACH_MEMBER_VECTOR(GET_TOTAL_SIZE)
1511         FOR_EACH_MEMBER_VECTOR_RARE_DATA(GET_TOTAL_SIZE)
1512     #undef GET_TOTAL_SIZE
1513
1514     totalSize += symbolTableTotalSize;
1515     totalSize += (liveCodeBlockSet.size() * sizeof(CodeBlock));
1516
1517     dataLog("Number of live CodeBlocks: %d\n", liveCodeBlockSet.size());
1518     dataLog("Size of a single CodeBlock [sizeof(CodeBlock)]: %zu\n", sizeof(CodeBlock));
1519     dataLog("Size of all CodeBlocks: %zu\n", totalSize);
1520     dataLog("Average size of a CodeBlock: %zu\n", totalSize / liveCodeBlockSet.size());
1521
1522     dataLog("Number of FunctionCode CodeBlocks: %zu (%.3f%%)\n", isFunctionCode, static_cast<double>(isFunctionCode) * 100.0 / liveCodeBlockSet.size());
1523     dataLog("Number of GlobalCode CodeBlocks: %zu (%.3f%%)\n", isGlobalCode, static_cast<double>(isGlobalCode) * 100.0 / liveCodeBlockSet.size());
1524     dataLog("Number of EvalCode CodeBlocks: %zu (%.3f%%)\n", isEvalCode, static_cast<double>(isEvalCode) * 100.0 / liveCodeBlockSet.size());
1525
1526     dataLog("Number of CodeBlocks with rare data: %zu (%.3f%%)\n", hasRareData, static_cast<double>(hasRareData) * 100.0 / liveCodeBlockSet.size());
1527
1528     #define PRINT_STATS(name) dataLog("Number of CodeBlocks with " #name ": %zu\n", name##IsNotEmpty); dataLog("Size of all " #name ": %zu\n", name##TotalSize); 
1529         FOR_EACH_MEMBER_VECTOR(PRINT_STATS)
1530         FOR_EACH_MEMBER_VECTOR_RARE_DATA(PRINT_STATS)
1531     #undef PRINT_STATS
1532
1533     dataLog("Number of CodeBlocks with evalCodeCache: %zu\n", evalCodeCacheIsNotEmpty);
1534     dataLog("Number of CodeBlocks with symbolTable: %zu\n", symbolTableIsNotEmpty);
1535
1536     dataLog("Size of all symbolTables: %zu\n", symbolTableTotalSize);
1537
1538 #else
1539     dataLog("Dumping CodeBlock statistics is not enabled.\n");
1540 #endif
1541 }
1542
1543 CodeBlock::CodeBlock(CopyParsedBlockTag, CodeBlock& other, SymbolTable* symTab)
1544     : m_globalObject(other.m_globalObject)
1545     , m_heap(other.m_heap)
1546     , m_numCalleeRegisters(other.m_numCalleeRegisters)
1547     , m_numVars(other.m_numVars)
1548     , m_numCapturedVars(other.m_numCapturedVars)
1549     , m_isConstructor(other.m_isConstructor)
1550     , m_ownerExecutable(*other.m_globalData, other.m_ownerExecutable.get(), other.m_ownerExecutable.get())
1551     , m_globalData(other.m_globalData)
1552     , m_instructions(other.m_instructions)
1553     , m_thisRegister(other.m_thisRegister)
1554     , m_argumentsRegister(other.m_argumentsRegister)
1555     , m_activationRegister(other.m_activationRegister)
1556     , m_needsFullScopeChain(other.m_needsFullScopeChain)
1557     , m_usesEval(other.m_usesEval)
1558     , m_isNumericCompareFunction(other.m_isNumericCompareFunction)
1559     , m_isStrictMode(other.m_isStrictMode)
1560     , m_codeType(other.m_codeType)
1561     , m_source(other.m_source)
1562     , m_sourceOffset(other.m_sourceOffset)
1563 #if ENABLE(JIT)
1564     , m_globalResolveInfos(other.m_globalResolveInfos)
1565 #endif
1566 #if ENABLE(VALUE_PROFILER)
1567     , m_executionEntryCount(0)
1568 #endif
1569     , m_jumpTargets(other.m_jumpTargets)
1570     , m_loopTargets(other.m_loopTargets)
1571     , m_identifiers(other.m_identifiers)
1572     , m_constantRegisters(other.m_constantRegisters)
1573     , m_functionDecls(other.m_functionDecls)
1574     , m_functionExprs(other.m_functionExprs)
1575     , m_symbolTable(symTab)
1576     , m_speculativeSuccessCounter(0)
1577     , m_speculativeFailCounter(0)
1578     , m_forcedOSRExitCounter(0)
1579     , m_optimizationDelayCounter(0)
1580     , m_reoptimizationRetryCounter(0)
1581 #if ENABLE(JIT)
1582     , m_canCompileWithDFGState(DFG::CapabilityLevelNotSet)
1583 #endif
1584 {
1585     setNumParameters(other.numParameters());
1586     optimizeAfterWarmUp();
1587     jitAfterWarmUp();
1588     
1589     if (other.m_rareData) {
1590         createRareDataIfNecessary();
1591         
1592         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1593         m_rareData->m_regexps = other.m_rareData->m_regexps;
1594         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1595         m_rareData->m_immediateSwitchJumpTables = other.m_rareData->m_immediateSwitchJumpTables;
1596         m_rareData->m_characterSwitchJumpTables = other.m_rareData->m_characterSwitchJumpTables;
1597         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1598         m_rareData->m_expressionInfo = other.m_rareData->m_expressionInfo;
1599         m_rareData->m_lineInfo = other.m_rareData->m_lineInfo;
1600     }
1601 }
1602
1603 CodeBlock::CodeBlock(ScriptExecutable* ownerExecutable, CodeType codeType, JSGlobalObject *globalObject, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, SymbolTable* symTab, bool isConstructor, PassOwnPtr<CodeBlock> alternative)
1604     : m_globalObject(globalObject->globalData(), ownerExecutable, globalObject)
1605     , m_heap(&m_globalObject->globalData().heap)
1606     , m_numCalleeRegisters(0)
1607     , m_numVars(0)
1608     , m_isConstructor(isConstructor)
1609     , m_numParameters(0)
1610     , m_ownerExecutable(globalObject->globalData(), ownerExecutable, ownerExecutable)
1611     , m_globalData(0)
1612     , m_argumentsRegister(-1)
1613     , m_needsFullScopeChain(ownerExecutable->needsActivation())
1614     , m_usesEval(ownerExecutable->usesEval())
1615     , m_isNumericCompareFunction(false)
1616     , m_isStrictMode(ownerExecutable->isStrictMode())
1617     , m_codeType(codeType)
1618     , m_source(sourceProvider)
1619     , m_sourceOffset(sourceOffset)
1620 #if ENABLE(VALUE_PROFILER)
1621     , m_executionEntryCount(0)
1622 #endif
1623     , m_symbolTable(symTab)
1624     , m_alternative(alternative)
1625     , m_speculativeSuccessCounter(0)
1626     , m_speculativeFailCounter(0)
1627     , m_optimizationDelayCounter(0)
1628     , m_reoptimizationRetryCounter(0)
1629 {
1630     ASSERT(m_source);
1631     
1632     optimizeAfterWarmUp();
1633     jitAfterWarmUp();
1634
1635 #if DUMP_CODE_BLOCK_STATISTICS
1636     liveCodeBlockSet.add(this);
1637 #endif
1638 }
1639
1640 CodeBlock::~CodeBlock()
1641 {
1642 #if ENABLE(DFG_JIT)
1643     // Remove myself from the set of DFG code blocks. Note that I may not be in this set
1644     // (because I'm not a DFG code block), in which case this is a no-op anyway.
1645     m_globalData->heap.m_dfgCodeBlocks.m_set.remove(this);
1646 #endif
1647     
1648 #if ENABLE(VERBOSE_VALUE_PROFILE)
1649     dumpValueProfiles();
1650 #endif
1651
1652 #if ENABLE(LLINT)    
1653     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1654         m_incomingLLIntCalls.begin()->remove();
1655 #endif // ENABLE(LLINT)
1656 #if ENABLE(JIT)
1657     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
1658     // Consider that two CodeBlocks become unreachable at the same time. There
1659     // is no guarantee about the order in which the CodeBlocks are destroyed.
1660     // So, if we don't remove incoming calls, and get destroyed before the
1661     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
1662     // destructor will try to remove nodes from our (no longer valid) linked list.
1663     while (m_incomingCalls.begin() != m_incomingCalls.end())
1664         m_incomingCalls.begin()->remove();
1665     
1666     // Note that our outgoing calls will be removed from other CodeBlocks'
1667     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
1668     // destructors.
1669
1670     for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i)
1671         m_structureStubInfos[i].deref();
1672 #endif // ENABLE(JIT)
1673
1674 #if DUMP_CODE_BLOCK_STATISTICS
1675     liveCodeBlockSet.remove(this);
1676 #endif
1677 }
1678
1679 void CodeBlock::setNumParameters(int newValue)
1680 {
1681     m_numParameters = newValue;
1682
1683 #if ENABLE(VALUE_PROFILER)
1684     m_argumentValueProfiles.resize(newValue);
1685 #endif
1686 }
1687
1688 void CodeBlock::addParameter()
1689 {
1690     m_numParameters++;
1691
1692 #if ENABLE(VALUE_PROFILER)
1693     m_argumentValueProfiles.append(ValueProfile());
1694 #endif
1695 }
1696
1697 void CodeBlock::visitStructures(SlotVisitor& visitor, Instruction* vPC)
1698 {
1699     Interpreter* interpreter = m_globalData->interpreter;
1700
1701     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id) && vPC[4].u.structure) {
1702         visitor.append(&vPC[4].u.structure);
1703         return;
1704     }
1705
1706     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_self) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_getter_self) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_custom_self)) {
1707         visitor.append(&vPC[4].u.structure);
1708         return;
1709     }
1710     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_proto) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_getter_proto) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_custom_proto)) {
1711         visitor.append(&vPC[4].u.structure);
1712         visitor.append(&vPC[5].u.structure);
1713         return;
1714     }
1715     if (vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_chain) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_getter_chain) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_custom_chain)) {
1716         visitor.append(&vPC[4].u.structure);
1717         if (vPC[5].u.structureChain)
1718             visitor.append(&vPC[5].u.structureChain);
1719         return;
1720     }
1721     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_transition)) {
1722         visitor.append(&vPC[4].u.structure);
1723         visitor.append(&vPC[5].u.structure);
1724         if (vPC[6].u.structureChain)
1725             visitor.append(&vPC[6].u.structureChain);
1726         return;
1727     }
1728     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id) && vPC[4].u.structure) {
1729         visitor.append(&vPC[4].u.structure);
1730         return;
1731     }
1732     if (vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_replace)) {
1733         visitor.append(&vPC[4].u.structure);
1734         return;
1735     }
1736     if (vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global) || vPC[0].u.opcode == interpreter->getOpcode(op_resolve_global_dynamic)) {
1737         if (vPC[3].u.structure)
1738             visitor.append(&vPC[3].u.structure);
1739         return;
1740     }
1741
1742     // These instructions don't ref their Structures.
1743     ASSERT(vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id) || vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id) || vPC[0].u.opcode == interpreter->getOpcode(op_get_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_put_by_id_generic) || vPC[0].u.opcode == interpreter->getOpcode(op_get_array_length) || vPC[0].u.opcode == interpreter->getOpcode(op_get_string_length));
1744 }
1745
1746 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
1747 {
1748     EvalCacheMap::iterator end = m_cacheMap.end();
1749     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
1750         visitor.append(&ptr->second);
1751 }
1752
1753 void CodeBlock::visitAggregate(SlotVisitor& visitor)
1754 {
1755 #if ENABLE(PARALLEL_GC) && ENABLE(DFG_JIT)
1756     if (!!m_dfgData) {
1757         // I may be asked to scan myself more than once, and it may even happen concurrently.
1758         // To this end, use a CAS loop to check if I've been called already. Only one thread
1759         // may proceed past this point - whichever one wins the CAS race.
1760         unsigned oldValue;
1761         do {
1762             oldValue = m_dfgData->visitAggregateHasBeenCalled;
1763             if (oldValue) {
1764                 // Looks like someone else won! Return immediately to ensure that we don't
1765                 // trace the same CodeBlock concurrently. Doing so is hazardous since we will
1766                 // be mutating the state of ValueProfiles, which contain JSValues, which can
1767                 // have word-tearing on 32-bit, leading to awesome timing-dependent crashes
1768                 // that are nearly impossible to track down.
1769                 
1770                 // Also note that it must be safe to return early as soon as we see the
1771                 // value true (well, (unsigned)1), since once a GC thread is in this method
1772                 // and has won the CAS race (i.e. was responsible for setting the value true)
1773                 // it will definitely complete the rest of this method before declaring
1774                 // termination.
1775                 return;
1776             }
1777         } while (!WTF::weakCompareAndSwap(&m_dfgData->visitAggregateHasBeenCalled, 0, 1));
1778     }
1779 #endif // ENABLE(PARALLEL_GC) && ENABLE(DFG_JIT)
1780     
1781     if (!!m_alternative)
1782         m_alternative->visitAggregate(visitor);
1783
1784     // There are three things that may use unconditional finalizers: lazy bytecode freeing,
1785     // inline cache clearing, and jettisoning. The probability of us wanting to do at
1786     // least one of those things is probably quite close to 1. So we add one no matter what
1787     // and when it runs, it figures out whether it has any work to do.
1788     visitor.addUnconditionalFinalizer(this);
1789     
1790     if (shouldImmediatelyAssumeLivenessDuringScan()) {
1791         // This code block is live, so scan all references strongly and return.
1792         stronglyVisitStrongReferences(visitor);
1793         stronglyVisitWeakReferences(visitor);
1794         return;
1795     }
1796     
1797 #if ENABLE(DFG_JIT)
1798     // We get here if we're live in the sense that our owner executable is live,
1799     // but we're not yet live for sure in another sense: we may yet decide that this
1800     // code block should be jettisoned based on its outgoing weak references being
1801     // stale. Set a flag to indicate that we're still assuming that we're dead, and
1802     // perform one round of determining if we're live. The GC may determine, based on
1803     // either us marking additional objects, or by other objects being marked for
1804     // other reasons, that this iteration should run again; it will notify us of this
1805     // decision by calling harvestWeakReferences().
1806     
1807     m_dfgData->livenessHasBeenProved = false;
1808     m_dfgData->allTransitionsHaveBeenMarked = false;
1809     
1810     performTracingFixpointIteration(visitor);
1811
1812     // GC doesn't have enough information yet for us to decide whether to keep our DFG
1813     // data, so we need to register a handler to run again at the end of GC, when more
1814     // information is available.
1815     if (!(m_dfgData->livenessHasBeenProved && m_dfgData->allTransitionsHaveBeenMarked))
1816         visitor.addWeakReferenceHarvester(this);
1817     
1818 #else // ENABLE(DFG_JIT)
1819     ASSERT_NOT_REACHED();
1820 #endif // ENABLE(DFG_JIT)
1821 }
1822
1823 void CodeBlock::performTracingFixpointIteration(SlotVisitor& visitor)
1824 {
1825     UNUSED_PARAM(visitor);
1826     
1827 #if ENABLE(DFG_JIT)
1828     // Evaluate our weak reference transitions, if there are still some to evaluate.
1829     if (!m_dfgData->allTransitionsHaveBeenMarked) {
1830         bool allAreMarkedSoFar = true;
1831         for (unsigned i = 0; i < m_dfgData->transitions.size(); ++i) {
1832             if ((!m_dfgData->transitions[i].m_codeOrigin
1833                  || Heap::isMarked(m_dfgData->transitions[i].m_codeOrigin.get()))
1834                 && Heap::isMarked(m_dfgData->transitions[i].m_from.get())) {
1835                 // If the following three things are live, then the target of the
1836                 // transition is also live:
1837                 // - This code block. We know it's live already because otherwise
1838                 //   we wouldn't be scanning ourselves.
1839                 // - The code origin of the transition. Transitions may arise from
1840                 //   code that was inlined. They are not relevant if the user's
1841                 //   object that is required for the inlinee to run is no longer
1842                 //   live.
1843                 // - The source of the transition. The transition checks if some
1844                 //   heap location holds the source, and if so, stores the target.
1845                 //   Hence the source must be live for the transition to be live.
1846                 visitor.append(&m_dfgData->transitions[i].m_to);
1847             } else
1848                 allAreMarkedSoFar = false;
1849         }
1850         
1851         if (allAreMarkedSoFar)
1852             m_dfgData->allTransitionsHaveBeenMarked = true;
1853     }
1854     
1855     // Check if we have any remaining work to do.
1856     if (m_dfgData->livenessHasBeenProved)
1857         return;
1858     
1859     // Now check all of our weak references. If all of them are live, then we
1860     // have proved liveness and so we scan our strong references. If at end of
1861     // GC we still have not proved liveness, then this code block is toast.
1862     bool allAreLiveSoFar = true;
1863     for (unsigned i = 0; i < m_dfgData->weakReferences.size(); ++i) {
1864         if (!Heap::isMarked(m_dfgData->weakReferences[i].get())) {
1865             allAreLiveSoFar = false;
1866             break;
1867         }
1868     }
1869     
1870     // If some weak references are dead, then this fixpoint iteration was
1871     // unsuccessful.
1872     if (!allAreLiveSoFar)
1873         return;
1874     
1875     // All weak references are live. Record this information so we don't
1876     // come back here again, and scan the strong references.
1877     m_dfgData->livenessHasBeenProved = true;
1878     stronglyVisitStrongReferences(visitor);
1879 #endif // ENABLE(DFG_JIT)
1880 }
1881
1882 void CodeBlock::visitWeakReferences(SlotVisitor& visitor)
1883 {
1884     performTracingFixpointIteration(visitor);
1885 }
1886
1887 void CodeBlock::finalizeUnconditionally()
1888 {
1889 #if ENABLE(JIT)
1890 #if ENABLE(JIT_VERBOSE_OSR)
1891     static const bool verboseUnlinking = true;
1892 #else
1893     static const bool verboseUnlinking = false;
1894 #endif
1895 #endif // ENABLE(JIT)
1896     
1897 #if ENABLE(LLINT)
1898     Interpreter* interpreter = m_globalData->interpreter;
1899     // interpreter->classicEnabled() returns true if the old C++ interpreter is enabled. If that's enabled
1900     // then we're not using LLInt.
1901     if (!interpreter->classicEnabled() && !!numberOfInstructions()) {
1902         for (size_t size = m_propertyAccessInstructions.size(), i = 0; i < size; ++i) {
1903             Instruction* curInstruction = &instructions()[m_propertyAccessInstructions[i]];
1904             switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
1905             case op_get_by_id:
1906             case op_put_by_id:
1907                 if (!curInstruction[4].u.structure || Heap::isMarked(curInstruction[4].u.structure.get()))
1908                     break;
1909                 if (verboseUnlinking)
1910                     dataLog("Clearing LLInt property access with structure %p.\n", curInstruction[4].u.structure.get());
1911                 curInstruction[4].u.structure.clear();
1912                 curInstruction[5].u.operand = 0;
1913                 break;
1914             case op_put_by_id_transition_direct:
1915             case op_put_by_id_transition_normal:
1916                 if (Heap::isMarked(curInstruction[4].u.structure.get())
1917                     && Heap::isMarked(curInstruction[6].u.structure.get())
1918                     && Heap::isMarked(curInstruction[7].u.structureChain.get()))
1919                     break;
1920                 if (verboseUnlinking) {
1921                     dataLog("Clearing LLInt put transition with structures %p -> %p, chain %p.\n",
1922                             curInstruction[4].u.structure.get(),
1923                             curInstruction[6].u.structure.get(),
1924                             curInstruction[7].u.structureChain.get());
1925                 }
1926                 curInstruction[4].u.structure.clear();
1927                 curInstruction[6].u.structure.clear();
1928                 curInstruction[7].u.structureChain.clear();
1929                 curInstruction[0].u.opcode = interpreter->getOpcode(op_put_by_id);
1930                 break;
1931             default:
1932                 ASSERT_NOT_REACHED();
1933             }
1934         }
1935         for (size_t size = m_globalResolveInstructions.size(), i = 0; i < size; ++i) {
1936             Instruction* curInstruction = &instructions()[m_globalResolveInstructions[i]];
1937             ASSERT(interpreter->getOpcodeID(curInstruction[0].u.opcode) == op_resolve_global
1938                    || interpreter->getOpcodeID(curInstruction[0].u.opcode) == op_resolve_global_dynamic);
1939             if (!curInstruction[3].u.structure || Heap::isMarked(curInstruction[3].u.structure.get()))
1940                 continue;
1941             if (verboseUnlinking)
1942                 dataLog("Clearing LLInt global resolve cache with structure %p.\n", curInstruction[3].u.structure.get());
1943             curInstruction[3].u.structure.clear();
1944             curInstruction[4].u.operand = 0;
1945         }
1946         for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
1947             if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
1948                 if (verboseUnlinking)
1949                     dataLog("Clearing LLInt call from %p.\n", this);
1950                 m_llintCallLinkInfos[i].unlink();
1951             }
1952             if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
1953                 m_llintCallLinkInfos[i].lastSeenCallee.clear();
1954         }
1955     }
1956 #endif // ENABLE(LLINT)
1957
1958 #if ENABLE(DFG_JIT)
1959     // Check if we're not live. If we are, then jettison.
1960     if (!(shouldImmediatelyAssumeLivenessDuringScan() || m_dfgData->livenessHasBeenProved)) {
1961         if (verboseUnlinking)
1962             dataLog("Code block %p has dead weak references, jettisoning during GC.\n", this);
1963
1964         // Make sure that the baseline JIT knows that it should re-warm-up before
1965         // optimizing.
1966         alternative()->optimizeAfterWarmUp();
1967         
1968         jettison();
1969         return;
1970     }
1971 #endif // ENABLE(DFG_JIT)
1972     
1973 #if ENABLE(JIT)
1974     // Handle inline caches.
1975     if (!!getJITCode()) {
1976         RepatchBuffer repatchBuffer(this);
1977         for (unsigned i = 0; i < numberOfCallLinkInfos(); ++i) {
1978             if (callLinkInfo(i).isLinked() && !Heap::isMarked(callLinkInfo(i).callee.get())) {
1979                 if (verboseUnlinking)
1980                     dataLog("Clearing call from %p to %p.\n", this, callLinkInfo(i).callee.get());
1981                 callLinkInfo(i).unlink(*m_globalData, repatchBuffer);
1982             }
1983             if (!!callLinkInfo(i).lastSeenCallee
1984                 && !Heap::isMarked(callLinkInfo(i).lastSeenCallee.get()))
1985                 callLinkInfo(i).lastSeenCallee.clear();
1986         }
1987         for (size_t size = m_globalResolveInfos.size(), i = 0; i < size; ++i) {
1988             if (m_globalResolveInfos[i].structure && !Heap::isMarked(m_globalResolveInfos[i].structure.get())) {
1989                 if (verboseUnlinking)
1990                     dataLog("Clearing resolve info in %p.\n", this);
1991                 m_globalResolveInfos[i].structure.clear();
1992             }
1993         }
1994
1995         for (size_t size = m_structureStubInfos.size(), i = 0; i < size; ++i) {
1996             StructureStubInfo& stubInfo = m_structureStubInfos[i];
1997             
1998             AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
1999             
2000             if (stubInfo.visitWeakReferences())
2001                 continue;
2002             
2003             if (verboseUnlinking)
2004                 dataLog("Clearing structure cache (kind %d) in %p.\n", stubInfo.accessType, this);
2005             
2006             if (isGetByIdAccess(accessType)) {
2007                 if (getJITCode().jitType() == JITCode::DFGJIT)
2008                     DFG::dfgResetGetByID(repatchBuffer, stubInfo);
2009                 else
2010                     JIT::resetPatchGetById(repatchBuffer, &stubInfo);
2011             } else {
2012                 ASSERT(isPutByIdAccess(accessType));
2013                 if (getJITCode().jitType() == JITCode::DFGJIT)
2014                     DFG::dfgResetPutByID(repatchBuffer, stubInfo);
2015                 else 
2016                     JIT::resetPatchPutById(repatchBuffer, &stubInfo);
2017             }
2018             
2019             stubInfo.reset();
2020         }
2021
2022         for (size_t size = m_methodCallLinkInfos.size(), i = 0; i < size; ++i) {
2023             if (!m_methodCallLinkInfos[i].cachedStructure)
2024                 continue;
2025             
2026             ASSERT(m_methodCallLinkInfos[i].seenOnce());
2027             ASSERT(!!m_methodCallLinkInfos[i].cachedPrototypeStructure);
2028
2029             if (!Heap::isMarked(m_methodCallLinkInfos[i].cachedStructure.get())
2030                 || !Heap::isMarked(m_methodCallLinkInfos[i].cachedPrototypeStructure.get())
2031                 || !Heap::isMarked(m_methodCallLinkInfos[i].cachedFunction.get())
2032                 || !Heap::isMarked(m_methodCallLinkInfos[i].cachedPrototype.get())) {
2033                 if (verboseUnlinking)
2034                     dataLog("Clearing method call in %p.\n", this);
2035                 m_methodCallLinkInfos[i].reset(repatchBuffer, getJITType());
2036
2037                 StructureStubInfo& stubInfo = getStubInfo(m_methodCallLinkInfos[i].bytecodeIndex);
2038
2039                 AccessType accessType = static_cast<AccessType>(stubInfo.accessType);
2040
2041                 if (accessType != access_unset) {
2042                     ASSERT(isGetByIdAccess(accessType));
2043                     if (getJITCode().jitType() == JITCode::DFGJIT)
2044                         DFG::dfgResetGetByID(repatchBuffer, stubInfo);
2045                     else
2046                         JIT::resetPatchGetById(repatchBuffer, &stubInfo);
2047                     stubInfo.reset();
2048                 }
2049             }
2050         }
2051     }
2052 #endif
2053 }
2054
2055 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2056 {
2057     visitor.append(&m_globalObject);
2058     visitor.append(&m_ownerExecutable);
2059     if (m_rareData) {
2060         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2061         size_t regExpCount = m_rareData->m_regexps.size();
2062         WriteBarrier<RegExp>* regexps = m_rareData->m_regexps.data();
2063         for (size_t i = 0; i < regExpCount; i++)
2064             visitor.append(regexps + i);
2065     }
2066     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2067     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2068         visitor.append(&m_functionExprs[i]);
2069     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2070         visitor.append(&m_functionDecls[i]);
2071 #if ENABLE(CLASSIC_INTERPRETER)
2072     if (m_globalData->interpreter->classicEnabled() && !!numberOfInstructions()) {
2073         for (size_t size = m_propertyAccessInstructions.size(), i = 0; i < size; ++i)
2074             visitStructures(visitor, &instructions()[m_propertyAccessInstructions[i]]);
2075         for (size_t size = m_globalResolveInstructions.size(), i = 0; i < size; ++i)
2076             visitStructures(visitor, &instructions()[m_globalResolveInstructions[i]]);
2077     }
2078 #endif
2079
2080 #if ENABLE(DFG_JIT)
2081     if (hasCodeOrigins()) {
2082         // Make sure that executables that we have inlined don't die.
2083         // FIXME: If they would have otherwise died, we should probably trigger recompilation.
2084         for (size_t i = 0; i < inlineCallFrames().size(); ++i) {
2085             InlineCallFrame& inlineCallFrame = inlineCallFrames()[i];
2086             visitor.append(&inlineCallFrame.executable);
2087             visitor.append(&inlineCallFrame.callee);
2088         }
2089     }
2090     
2091     m_lazyOperandValueProfiles.computeUpdatedPredictions(Collection);
2092 #endif
2093
2094 #if ENABLE(VALUE_PROFILER)
2095     for (unsigned profileIndex = 0; profileIndex < numberOfArgumentValueProfiles(); ++profileIndex)
2096         valueProfileForArgument(profileIndex)->computeUpdatedPrediction(Collection);
2097     for (unsigned profileIndex = 0; profileIndex < numberOfValueProfiles(); ++profileIndex)
2098         valueProfile(profileIndex)->computeUpdatedPrediction(Collection);
2099 #endif
2100 }
2101
2102 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2103 {
2104     UNUSED_PARAM(visitor);
2105
2106 #if ENABLE(DFG_JIT)
2107     if (!m_dfgData)
2108         return;
2109
2110     for (unsigned i = 0; i < m_dfgData->transitions.size(); ++i) {
2111         if (!!m_dfgData->transitions[i].m_codeOrigin)
2112             visitor.append(&m_dfgData->transitions[i].m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
2113         visitor.append(&m_dfgData->transitions[i].m_from);
2114         visitor.append(&m_dfgData->transitions[i].m_to);
2115     }
2116     
2117     for (unsigned i = 0; i < m_dfgData->weakReferences.size(); ++i)
2118         visitor.append(&m_dfgData->weakReferences[i]);
2119 #endif    
2120 }
2121
2122 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset)
2123 {
2124     ASSERT(bytecodeOffset < instructions().size());
2125
2126     if (!m_rareData)
2127         return 0;
2128     
2129     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
2130     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
2131         // Handlers are ordered innermost first, so the first handler we encounter
2132         // that contains the source address is the correct handler to use.
2133         if (exceptionHandlers[i].start <= bytecodeOffset && exceptionHandlers[i].end >= bytecodeOffset)
2134             return &exceptionHandlers[i];
2135     }
2136
2137     return 0;
2138 }
2139
2140 int CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
2141 {
2142     ASSERT(bytecodeOffset < instructions().size());
2143
2144     if (!m_rareData)
2145         return m_ownerExecutable->source().firstLine();
2146
2147     Vector<LineInfo>& lineInfo = m_rareData->m_lineInfo;
2148
2149     int low = 0;
2150     int high = lineInfo.size();
2151     while (low < high) {
2152         int mid = low + (high - low) / 2;
2153         if (lineInfo[mid].instructionOffset <= bytecodeOffset)
2154             low = mid + 1;
2155         else
2156             high = mid;
2157     }
2158
2159     if (!low)
2160         return m_ownerExecutable->source().firstLine();
2161     return lineInfo[low - 1].lineNumber;
2162 }
2163
2164 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset)
2165 {
2166     ASSERT(bytecodeOffset < instructions().size());
2167
2168     if (!m_rareData) {
2169         startOffset = 0;
2170         endOffset = 0;
2171         divot = 0;
2172         return;
2173     }
2174
2175     Vector<ExpressionRangeInfo>& expressionInfo = m_rareData->m_expressionInfo;
2176
2177     int low = 0;
2178     int high = expressionInfo.size();
2179     while (low < high) {
2180         int mid = low + (high - low) / 2;
2181         if (expressionInfo[mid].instructionOffset <= bytecodeOffset)
2182             low = mid + 1;
2183         else
2184             high = mid;
2185     }
2186
2187     ASSERT(low);
2188     if (!low) {
2189         startOffset = 0;
2190         endOffset = 0;
2191         divot = 0;
2192         return;
2193     }
2194
2195     startOffset = expressionInfo[low - 1].startOffset;
2196     endOffset = expressionInfo[low - 1].endOffset;
2197     divot = expressionInfo[low - 1].divotPoint + m_sourceOffset;
2198     return;
2199 }
2200
2201 #if ENABLE(CLASSIC_INTERPRETER)
2202 bool CodeBlock::hasGlobalResolveInstructionAtBytecodeOffset(unsigned bytecodeOffset)
2203 {
2204     if (m_globalResolveInstructions.isEmpty())
2205         return false;
2206
2207     int low = 0;
2208     int high = m_globalResolveInstructions.size();
2209     while (low < high) {
2210         int mid = low + (high - low) / 2;
2211         if (m_globalResolveInstructions[mid] <= bytecodeOffset)
2212             low = mid + 1;
2213         else
2214             high = mid;
2215     }
2216
2217     if (!low || m_globalResolveInstructions[low - 1] != bytecodeOffset)
2218         return false;
2219     return true;
2220 }
2221 #endif
2222 #if ENABLE(JIT)
2223 bool CodeBlock::hasGlobalResolveInfoAtBytecodeOffset(unsigned bytecodeOffset)
2224 {
2225     if (m_globalResolveInfos.isEmpty())
2226         return false;
2227
2228     int low = 0;
2229     int high = m_globalResolveInfos.size();
2230     while (low < high) {
2231         int mid = low + (high - low) / 2;
2232         if (m_globalResolveInfos[mid].bytecodeOffset <= bytecodeOffset)
2233             low = mid + 1;
2234         else
2235             high = mid;
2236     }
2237
2238     if (!low || m_globalResolveInfos[low - 1].bytecodeOffset != bytecodeOffset)
2239         return false;
2240     return true;
2241 }
2242 #endif
2243
2244 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
2245 {
2246     m_propertyAccessInstructions.shrinkToFit();
2247     m_globalResolveInstructions.shrinkToFit();
2248 #if ENABLE(LLINT)
2249     m_llintCallLinkInfos.shrinkToFit();
2250 #endif
2251 #if ENABLE(JIT)
2252     m_structureStubInfos.shrinkToFit();
2253     m_globalResolveInfos.shrinkToFit();
2254     m_callLinkInfos.shrinkToFit();
2255     m_methodCallLinkInfos.shrinkToFit();
2256 #endif
2257 #if ENABLE(VALUE_PROFILER)
2258     if (shrinkMode == EarlyShrink)
2259         m_argumentValueProfiles.shrinkToFit();
2260     m_valueProfiles.shrinkToFit();
2261     m_rareCaseProfiles.shrinkToFit();
2262     m_specialFastCaseProfiles.shrinkToFit();
2263 #endif
2264     
2265     if (shrinkMode == EarlyShrink) {
2266         m_identifiers.shrinkToFit();
2267         m_functionDecls.shrinkToFit();
2268         m_functionExprs.shrinkToFit();
2269         m_constantRegisters.shrinkToFit();
2270     } // else don't shrink these, because we would have already pointed pointers into these tables.
2271
2272     if (m_rareData) {
2273         m_rareData->m_exceptionHandlers.shrinkToFit();
2274         m_rareData->m_regexps.shrinkToFit();
2275         m_rareData->m_immediateSwitchJumpTables.shrinkToFit();
2276         m_rareData->m_characterSwitchJumpTables.shrinkToFit();
2277         m_rareData->m_stringSwitchJumpTables.shrinkToFit();
2278         m_rareData->m_expressionInfo.shrinkToFit();
2279         m_rareData->m_lineInfo.shrinkToFit();
2280 #if ENABLE(JIT)
2281         m_rareData->m_callReturnIndexVector.shrinkToFit();
2282 #endif
2283 #if ENABLE(DFG_JIT)
2284         m_rareData->m_inlineCallFrames.shrinkToFit();
2285         m_rareData->m_codeOrigins.shrinkToFit();
2286 #endif
2287     }
2288     
2289 #if ENABLE(DFG_JIT)
2290     if (m_dfgData) {
2291         m_dfgData->osrEntry.shrinkToFit();
2292         m_dfgData->osrExit.shrinkToFit();
2293         m_dfgData->speculationRecovery.shrinkToFit();
2294         m_dfgData->weakReferences.shrinkToFit();
2295         m_dfgData->transitions.shrinkToFit();
2296     }
2297 #endif
2298 }
2299
2300 void CodeBlock::createActivation(CallFrame* callFrame)
2301 {
2302     ASSERT(codeType() == FunctionCode);
2303     ASSERT(needsFullScopeChain());
2304     ASSERT(!callFrame->uncheckedR(activationRegister()).jsValue());
2305     JSActivation* activation = JSActivation::create(callFrame->globalData(), callFrame, static_cast<FunctionExecutable*>(ownerExecutable()));
2306     callFrame->uncheckedR(activationRegister()) = JSValue(activation);
2307     callFrame->setScopeChain(callFrame->scopeChain()->push(activation));
2308 }
2309
2310 unsigned CodeBlock::addOrFindConstant(JSValue v)
2311 {
2312     unsigned numberOfConstants = numberOfConstantRegisters();
2313     for (unsigned i = 0; i < numberOfConstants; ++i) {
2314         if (getConstant(FirstConstantRegisterIndex + i) == v)
2315             return i;
2316     }
2317     return addConstant(v);
2318 }
2319
2320 #if ENABLE(JIT)
2321 void CodeBlock::unlinkCalls()
2322 {
2323     if (!!m_alternative)
2324         m_alternative->unlinkCalls();
2325 #if ENABLE(LLINT)
2326     for (size_t i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2327         if (m_llintCallLinkInfos[i].isLinked())
2328             m_llintCallLinkInfos[i].unlink();
2329     }
2330 #endif
2331     if (!(m_callLinkInfos.size() || m_methodCallLinkInfos.size()))
2332         return;
2333     if (!m_globalData->canUseJIT())
2334         return;
2335     RepatchBuffer repatchBuffer(this);
2336     for (size_t i = 0; i < m_callLinkInfos.size(); i++) {
2337         if (!m_callLinkInfos[i].isLinked())
2338             continue;
2339         m_callLinkInfos[i].unlink(*m_globalData, repatchBuffer);
2340     }
2341 }
2342
2343 void CodeBlock::unlinkIncomingCalls()
2344 {
2345 #if ENABLE(LLINT)
2346     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
2347         m_incomingLLIntCalls.begin()->unlink();
2348 #endif
2349     if (m_incomingCalls.isEmpty())
2350         return;
2351     RepatchBuffer repatchBuffer(this);
2352     while (m_incomingCalls.begin() != m_incomingCalls.end())
2353         m_incomingCalls.begin()->unlink(*m_globalData, repatchBuffer);
2354 }
2355
2356 unsigned CodeBlock::bytecodeOffset(ExecState* exec, ReturnAddressPtr returnAddress)
2357 {
2358 #if ENABLE(LLINT)
2359     if (returnAddress.value() >= bitwise_cast<void*>(&llint_begin)
2360         && returnAddress.value() <= bitwise_cast<void*>(&llint_end)) {
2361         ASSERT(exec->codeBlock());
2362         ASSERT(exec->codeBlock() == this);
2363         ASSERT(JITCode::isBaselineCode(getJITType()));
2364         Instruction* instruction = exec->currentVPC();
2365         ASSERT(instruction);
2366         
2367         // The LLInt stores the PC after the call instruction rather than the PC of
2368         // the call instruction. This requires some correcting. We rely on the fact
2369         // that the preceding instruction must be one of the call instructions, so
2370         // either it's a call_varargs or it's a call, construct, or eval.
2371         ASSERT(OPCODE_LENGTH(op_call_varargs) <= OPCODE_LENGTH(op_call));
2372         ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_construct));
2373         ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_call_eval));
2374         if (instruction[-OPCODE_LENGTH(op_call_varargs)].u.pointer == bitwise_cast<void*>(llint_op_call_varargs)) {
2375             // We know that the preceding instruction must be op_call_varargs because there is no way that
2376             // the pointer to the call_varargs could be an operand to the call.
2377             instruction -= OPCODE_LENGTH(op_call_varargs);
2378             ASSERT(instruction[-OPCODE_LENGTH(op_call)].u.pointer != bitwise_cast<void*>(llint_op_call)
2379                    && instruction[-OPCODE_LENGTH(op_call)].u.pointer != bitwise_cast<void*>(llint_op_construct)
2380                    && instruction[-OPCODE_LENGTH(op_call)].u.pointer != bitwise_cast<void*>(llint_op_call_eval));
2381         } else {
2382             // Must be that the last instruction was some op_call.
2383             ASSERT(instruction[-OPCODE_LENGTH(op_call)].u.pointer == bitwise_cast<void*>(llint_op_call)
2384                    || instruction[-OPCODE_LENGTH(op_call)].u.pointer == bitwise_cast<void*>(llint_op_construct)
2385                    || instruction[-OPCODE_LENGTH(op_call)].u.pointer == bitwise_cast<void*>(llint_op_call_eval));
2386             instruction -= OPCODE_LENGTH(op_call);
2387         }
2388         
2389         return bytecodeOffset(instruction);
2390     }
2391 #else
2392     UNUSED_PARAM(exec);
2393 #endif
2394     if (!m_rareData)
2395         return 1;
2396     Vector<CallReturnOffsetToBytecodeOffset>& callIndices = m_rareData->m_callReturnIndexVector;
2397     if (!callIndices.size())
2398         return 1;
2399     return binarySearch<CallReturnOffsetToBytecodeOffset, unsigned, getCallReturnOffset>(callIndices.begin(), callIndices.size(), getJITCode().offsetOf(returnAddress.value()))->bytecodeOffset;
2400 }
2401 #endif
2402
2403 void CodeBlock::clearEvalCache()
2404 {
2405     if (!!m_alternative)
2406         m_alternative->clearEvalCache();
2407     if (!m_rareData)
2408         return;
2409     m_rareData->m_evalCodeCache.clear();
2410 }
2411
2412 template<typename T>
2413 inline void replaceExistingEntries(Vector<T>& target, Vector<T>& source)
2414 {
2415     ASSERT(target.size() <= source.size());
2416     for (size_t i = 0; i < target.size(); ++i)
2417         target[i] = source[i];
2418 }
2419
2420 void CodeBlock::copyPostParseDataFrom(CodeBlock* alternative)
2421 {
2422     if (!alternative)
2423         return;
2424     
2425     replaceExistingEntries(m_constantRegisters, alternative->m_constantRegisters);
2426     replaceExistingEntries(m_functionDecls, alternative->m_functionDecls);
2427     replaceExistingEntries(m_functionExprs, alternative->m_functionExprs);
2428     if (!!m_rareData && !!alternative->m_rareData)
2429         replaceExistingEntries(m_rareData->m_constantBuffers, alternative->m_rareData->m_constantBuffers);
2430 }
2431
2432 void CodeBlock::copyPostParseDataFromAlternative()
2433 {
2434     copyPostParseDataFrom(m_alternative.get());
2435 }
2436
2437 #if ENABLE(JIT)
2438 CodeBlock* ProgramCodeBlock::replacement()
2439 {
2440     return &static_cast<ProgramExecutable*>(ownerExecutable())->generatedBytecode();
2441 }
2442
2443 CodeBlock* EvalCodeBlock::replacement()
2444 {
2445     return &static_cast<EvalExecutable*>(ownerExecutable())->generatedBytecode();
2446 }
2447
2448 CodeBlock* FunctionCodeBlock::replacement()
2449 {
2450     return &static_cast<FunctionExecutable*>(ownerExecutable())->generatedBytecodeFor(m_isConstructor ? CodeForConstruct : CodeForCall);
2451 }
2452
2453 JSObject* ProgramCodeBlock::compileOptimized(ExecState* exec, ScopeChainNode* scopeChainNode)
2454 {
2455     if (replacement()->getJITType() == JITCode::nextTierJIT(getJITType()))
2456         return 0;
2457     JSObject* error = static_cast<ProgramExecutable*>(ownerExecutable())->compileOptimized(exec, scopeChainNode);
2458     return error;
2459 }
2460
2461 JSObject* EvalCodeBlock::compileOptimized(ExecState* exec, ScopeChainNode* scopeChainNode)
2462 {
2463     if (replacement()->getJITType() == JITCode::nextTierJIT(getJITType()))
2464         return 0;
2465     JSObject* error = static_cast<EvalExecutable*>(ownerExecutable())->compileOptimized(exec, scopeChainNode);
2466     return error;
2467 }
2468
2469 JSObject* FunctionCodeBlock::compileOptimized(ExecState* exec, ScopeChainNode* scopeChainNode)
2470 {
2471     if (replacement()->getJITType() == JITCode::nextTierJIT(getJITType()))
2472         return 0;
2473     JSObject* error = static_cast<FunctionExecutable*>(ownerExecutable())->compileOptimizedFor(exec, scopeChainNode, m_isConstructor ? CodeForConstruct : CodeForCall);
2474     return error;
2475 }
2476
2477 DFG::CapabilityLevel ProgramCodeBlock::canCompileWithDFGInternal()
2478 {
2479     return DFG::canCompileProgram(this);
2480 }
2481
2482 DFG::CapabilityLevel EvalCodeBlock::canCompileWithDFGInternal()
2483 {
2484     return DFG::canCompileEval(this);
2485 }
2486
2487 DFG::CapabilityLevel FunctionCodeBlock::canCompileWithDFGInternal()
2488 {
2489     if (m_isConstructor)
2490         return DFG::canCompileFunctionForConstruct(this);
2491     return DFG::canCompileFunctionForCall(this);
2492 }
2493
2494 void ProgramCodeBlock::jettison()
2495 {
2496     ASSERT(JITCode::isOptimizingJIT(getJITType()));
2497     ASSERT(this == replacement());
2498     static_cast<ProgramExecutable*>(ownerExecutable())->jettisonOptimizedCode(*globalData());
2499 }
2500
2501 void EvalCodeBlock::jettison()
2502 {
2503     ASSERT(JITCode::isOptimizingJIT(getJITType()));
2504     ASSERT(this == replacement());
2505     static_cast<EvalExecutable*>(ownerExecutable())->jettisonOptimizedCode(*globalData());
2506 }
2507
2508 void FunctionCodeBlock::jettison()
2509 {
2510     ASSERT(JITCode::isOptimizingJIT(getJITType()));
2511     ASSERT(this == replacement());
2512     static_cast<FunctionExecutable*>(ownerExecutable())->jettisonOptimizedCodeFor(*globalData(), m_isConstructor ? CodeForConstruct : CodeForCall);
2513 }
2514
2515 bool ProgramCodeBlock::jitCompileImpl(ExecState* exec)
2516 {
2517     ASSERT(getJITType() == JITCode::InterpreterThunk);
2518     ASSERT(this == replacement());
2519     return static_cast<ProgramExecutable*>(ownerExecutable())->jitCompile(exec);
2520 }
2521
2522 bool EvalCodeBlock::jitCompileImpl(ExecState* exec)
2523 {
2524     ASSERT(getJITType() == JITCode::InterpreterThunk);
2525     ASSERT(this == replacement());
2526     return static_cast<EvalExecutable*>(ownerExecutable())->jitCompile(exec);
2527 }
2528
2529 bool FunctionCodeBlock::jitCompileImpl(ExecState* exec)
2530 {
2531     ASSERT(getJITType() == JITCode::InterpreterThunk);
2532     ASSERT(this == replacement());
2533     return static_cast<FunctionExecutable*>(ownerExecutable())->jitCompileFor(exec, m_isConstructor ? CodeForConstruct : CodeForCall);
2534 }
2535 #endif
2536
2537 #if ENABLE(VALUE_PROFILER)
2538 bool CodeBlock::shouldOptimizeNow()
2539 {
2540 #if ENABLE(JIT_VERBOSE_OSR)
2541     dataLog("Considering optimizing %p...\n", this);
2542 #endif
2543
2544 #if ENABLE(VERBOSE_VALUE_PROFILE)
2545     dumpValueProfiles();
2546 #endif
2547
2548     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay)
2549         return true;
2550     
2551     unsigned numberOfLiveNonArgumentValueProfiles = 0;
2552     unsigned numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
2553     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2554         ValueProfile* profile = getFromAllValueProfiles(i);
2555         unsigned numSamples = profile->totalNumberOfSamples();
2556         if (numSamples > ValueProfile::numberOfBuckets)
2557             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
2558         numberOfSamplesInProfiles += numSamples;
2559         if (profile->m_bytecodeOffset < 0) {
2560             profile->computeUpdatedPrediction();
2561             continue;
2562         }
2563         if (profile->numberOfSamples() || profile->m_prediction != SpecNone)
2564             numberOfLiveNonArgumentValueProfiles++;
2565         profile->computeUpdatedPrediction();
2566     }
2567
2568 #if ENABLE(JIT_VERBOSE_OSR)
2569     dataLog("Profile hotness: %lf, %lf\n", (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(), (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles());
2570 #endif
2571
2572     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate)
2573         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate)
2574         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay)
2575         return true;
2576     
2577     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
2578     m_optimizationDelayCounter++;
2579     optimizeAfterWarmUp();
2580     return false;
2581 }
2582 #endif
2583
2584 #if ENABLE(DFG_JIT)
2585 void CodeBlock::tallyFrequentExitSites()
2586 {
2587     ASSERT(getJITType() == JITCode::DFGJIT);
2588     ASSERT(alternative()->getJITType() == JITCode::BaselineJIT);
2589     ASSERT(!!m_dfgData);
2590     
2591     CodeBlock* profiledBlock = alternative();
2592     
2593     for (unsigned i = 0; i < m_dfgData->osrExit.size(); ++i) {
2594         DFG::OSRExit& exit = m_dfgData->osrExit[i];
2595         
2596         if (!exit.considerAddingAsFrequentExitSite(this, profiledBlock))
2597             continue;
2598         
2599 #if DFG_ENABLE(DEBUG_VERBOSE)
2600         dataLog("OSR exit #%u (bc#%u, @%u, %s) for code block %p occurred frequently; counting as frequent exit site.\n", i, exit.m_codeOrigin.bytecodeIndex, exit.m_nodeIndex, DFG::exitKindToString(exit.m_kind), this);
2601 #endif
2602     }
2603 }
2604 #endif // ENABLE(DFG_JIT)
2605
2606 #if ENABLE(VERBOSE_VALUE_PROFILE)
2607 void CodeBlock::dumpValueProfiles()
2608 {
2609     dataLog("ValueProfile for %p:\n", this);
2610     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2611         ValueProfile* profile = getFromAllValueProfiles(i);
2612         if (profile->m_bytecodeOffset < 0) {
2613             ASSERT(profile->m_bytecodeOffset == -1);
2614             dataLog("   arg = %u: ", i);
2615         } else
2616             dataLog("   bc = %d: ", profile->m_bytecodeOffset);
2617         if (!profile->numberOfSamples() && profile->m_prediction == SpecNone) {
2618             dataLog("<empty>\n");
2619             continue;
2620         }
2621         profile->dump(WTF::dataFile());
2622         dataLog("\n");
2623     }
2624     dataLog("RareCaseProfile for %p:\n", this);
2625     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
2626         RareCaseProfile* profile = rareCaseProfile(i);
2627         dataLog("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2628     }
2629     dataLog("SpecialFastCaseProfile for %p:\n", this);
2630     for (unsigned i = 0; i < numberOfSpecialFastCaseProfiles(); ++i) {
2631         RareCaseProfile* profile = specialFastCaseProfile(i);
2632         dataLog("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2633     }
2634 }
2635 #endif
2636
2637 size_t CodeBlock::predictedMachineCodeSize()
2638 {
2639     // This will be called from CodeBlock::CodeBlock before either m_globalData or the
2640     // instructions have been initialized. It's OK to return 0 because what will really
2641     // matter is the recomputation of this value when the slow path is triggered.
2642     if (!m_globalData)
2643         return 0;
2644     
2645     if (!m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT)
2646         return 0; // It's as good of a prediction as we'll get.
2647     
2648     // Be conservative: return a size that will be an overestimation 84% of the time.
2649     double multiplier = m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT.mean() +
2650         m_globalData->machineCodeBytesPerBytecodeWordForBaselineJIT.standardDeviation();
2651     
2652     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
2653     // here is OK, since this whole method is just a heuristic.
2654     if (multiplier < 0 || multiplier > 1000)
2655         return 0;
2656     
2657     double doubleResult = multiplier * m_instructions.size();
2658     
2659     // Be even more paranoid: silently reject values that won't fit into a size_t. If
2660     // the function is so huge that we can't even fit it into virtual memory then we
2661     // should probably have some other guards in place to prevent us from even getting
2662     // to this point.
2663     if (doubleResult > std::numeric_limits<size_t>::max())
2664         return 0;
2665     
2666     return static_cast<size_t>(doubleResult);
2667 }
2668
2669 bool CodeBlock::usesOpcode(OpcodeID opcodeID)
2670 {
2671     Interpreter* interpreter = globalData()->interpreter;
2672     Instruction* instructionsBegin = instructions().begin();
2673     unsigned instructionCount = instructions().size();
2674     
2675     for (unsigned bytecodeOffset = 0; bytecodeOffset < instructionCount; ) {
2676         switch (interpreter->getOpcodeID(instructionsBegin[bytecodeOffset].u.opcode)) {
2677 #define DEFINE_OP(curOpcode, length)        \
2678         case curOpcode:                     \
2679             if (curOpcode == opcodeID)      \
2680                 return true;                \
2681             bytecodeOffset += length;       \
2682             break;
2683             FOR_EACH_OPCODE_ID(DEFINE_OP)
2684 #undef DEFINE_OP
2685         default:
2686             ASSERT_NOT_REACHED();
2687             break;
2688         }
2689     }
2690     
2691     return false;
2692 }
2693
2694 } // namespace JSC