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