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