Constant folding of typed array properties should be handled by AI rather than streng...
[WebKit.git] / Source / JavaScriptCore / dfg / DFGGraph.cpp
1 /*
2  * Copyright (C) 2011, 2013-2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "DFGGraph.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "BytecodeKills.h"
32 #include "BytecodeLivenessAnalysisInlines.h"
33 #include "CodeBlock.h"
34 #include "CodeBlockWithJITType.h"
35 #include "DFGBlockWorklist.h"
36 #include "DFGClobberSet.h"
37 #include "DFGJITCode.h"
38 #include "DFGVariableAccessDataDump.h"
39 #include "FullBytecodeLiveness.h"
40 #include "FunctionExecutableDump.h"
41 #include "JIT.h"
42 #include "JSLexicalEnvironment.h"
43 #include "MaxFrameExtentForSlowPathCall.h"
44 #include "OperandsInlines.h"
45 #include "JSCInlines.h"
46 #include "StackAlignment.h"
47 #include <wtf/CommaPrinter.h>
48 #include <wtf/ListDump.h>
49
50 namespace JSC { namespace DFG {
51
52 // Creates an array of stringized names.
53 static const char* dfgOpNames[] = {
54 #define STRINGIZE_DFG_OP_ENUM(opcode, flags) #opcode ,
55     FOR_EACH_DFG_OP(STRINGIZE_DFG_OP_ENUM)
56 #undef STRINGIZE_DFG_OP_ENUM
57 };
58
59 Graph::Graph(VM& vm, Plan& plan, LongLivedState& longLivedState)
60     : m_vm(vm)
61     , m_plan(plan)
62     , m_codeBlock(m_plan.codeBlock.get())
63     , m_profiledBlock(m_codeBlock->alternative())
64     , m_allocator(longLivedState.m_allocator)
65     , m_mustHandleValues(OperandsLike, plan.mustHandleValues)
66     , m_nextMachineLocal(0)
67     , m_fixpointState(BeforeFixpoint)
68     , m_structureRegistrationState(HaveNotStartedRegistering)
69     , m_form(LoadStore)
70     , m_unificationState(LocallyUnified)
71     , m_refCountState(EverythingIsLive)
72 {
73     ASSERT(m_profiledBlock);
74     
75     for (unsigned i = m_mustHandleValues.size(); i--;)
76         m_mustHandleValues[i] = freezeFragile(plan.mustHandleValues[i]);
77
78     m_hasDebuggerEnabled = m_profiledBlock->globalObject()->hasDebugger()
79         || Options::forceDebuggerBytecodeGeneration();
80 }
81
82 Graph::~Graph()
83 {
84     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
85         BasicBlock* block = this->block(blockIndex);
86         if (!block)
87             continue;
88
89         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
90             m_allocator.free(block->phis[phiIndex]);
91         for (unsigned nodeIndex = block->size(); nodeIndex--;)
92             m_allocator.free(block->at(nodeIndex));
93     }
94     m_allocator.freeAll();
95 }
96
97 const char *Graph::opName(NodeType op)
98 {
99     return dfgOpNames[op];
100 }
101
102 static void printWhiteSpace(PrintStream& out, unsigned amount)
103 {
104     while (amount-- > 0)
105         out.print(" ");
106 }
107
108 bool Graph::dumpCodeOrigin(PrintStream& out, const char* prefix, Node* previousNode, Node* currentNode, DumpContext* context)
109 {
110     if (!previousNode)
111         return false;
112     
113     if (previousNode->origin.semantic.inlineCallFrame == currentNode->origin.semantic.inlineCallFrame)
114         return false;
115     
116     Vector<CodeOrigin> previousInlineStack = previousNode->origin.semantic.inlineStack();
117     Vector<CodeOrigin> currentInlineStack = currentNode->origin.semantic.inlineStack();
118     unsigned commonSize = std::min(previousInlineStack.size(), currentInlineStack.size());
119     unsigned indexOfDivergence = commonSize;
120     for (unsigned i = 0; i < commonSize; ++i) {
121         if (previousInlineStack[i].inlineCallFrame != currentInlineStack[i].inlineCallFrame) {
122             indexOfDivergence = i;
123             break;
124         }
125     }
126     
127     bool hasPrinted = false;
128     
129     // Print the pops.
130     for (unsigned i = previousInlineStack.size(); i-- > indexOfDivergence;) {
131         out.print(prefix);
132         printWhiteSpace(out, i * 2);
133         out.print("<-- ", inContext(*previousInlineStack[i].inlineCallFrame, context), "\n");
134         hasPrinted = true;
135     }
136     
137     // Print the pushes.
138     for (unsigned i = indexOfDivergence; i < currentInlineStack.size(); ++i) {
139         out.print(prefix);
140         printWhiteSpace(out, i * 2);
141         out.print("--> ", inContext(*currentInlineStack[i].inlineCallFrame, context), "\n");
142         hasPrinted = true;
143     }
144     
145     return hasPrinted;
146 }
147
148 int Graph::amountOfNodeWhiteSpace(Node* node)
149 {
150     return (node->origin.semantic.inlineDepth() - 1) * 2;
151 }
152
153 void Graph::printNodeWhiteSpace(PrintStream& out, Node* node)
154 {
155     printWhiteSpace(out, amountOfNodeWhiteSpace(node));
156 }
157
158 void Graph::dump(PrintStream& out, const char* prefix, Node* node, DumpContext* context)
159 {
160     NodeType op = node->op();
161
162     unsigned refCount = node->refCount();
163     bool mustGenerate = node->mustGenerate();
164     if (mustGenerate)
165         --refCount;
166
167     out.print(prefix);
168     printNodeWhiteSpace(out, node);
169
170     // Example/explanation of dataflow dump output
171     //
172     //   14:   <!2:7>  GetByVal(@3, @13)
173     //   ^1     ^2 ^3     ^4       ^5
174     //
175     // (1) The nodeIndex of this operation.
176     // (2) The reference count. The number printed is the 'real' count,
177     //     not including the 'mustGenerate' ref. If the node is
178     //     'mustGenerate' then the count it prefixed with '!'.
179     // (3) The virtual register slot assigned to this node.
180     // (4) The name of the operation.
181     // (5) The arguments to the operation. The may be of the form:
182     //         @#   - a NodeIndex referencing a prior node in the graph.
183     //         arg# - an argument number.
184     //         id#  - the index in the CodeBlock of an identifier { if codeBlock is passed to dump(), the string representation is displayed }.
185     //         var# - the index of a var on the global object, used by GetGlobalVar/PutGlobalVar operations.
186     out.printf("% 4d:<%c%u:", (int)node->index(), mustGenerate ? '!' : ' ', refCount);
187     if (node->hasResult() && node->hasVirtualRegister() && node->virtualRegister().isValid())
188         out.print(node->virtualRegister());
189     else
190         out.print("-");
191     out.print(">\t", opName(op), "(");
192     CommaPrinter comma;
193     if (node->flags() & NodeHasVarArgs) {
194         for (unsigned childIdx = node->firstChild(); childIdx < node->firstChild() + node->numChildren(); childIdx++) {
195             if (!m_varArgChildren[childIdx])
196                 continue;
197             out.print(comma, m_varArgChildren[childIdx]);
198         }
199     } else {
200         if (!!node->child1() || !!node->child2() || !!node->child3())
201             out.print(comma, node->child1());
202         if (!!node->child2() || !!node->child3())
203             out.print(comma, node->child2());
204         if (!!node->child3())
205             out.print(comma, node->child3());
206     }
207
208     if (toCString(NodeFlagsDump(node->flags())) != "<empty>")
209         out.print(comma, NodeFlagsDump(node->flags()));
210     if (node->prediction())
211         out.print(comma, SpeculationDump(node->prediction()));
212     if (node->hasArrayMode())
213         out.print(comma, node->arrayMode());
214     if (node->hasArithMode())
215         out.print(comma, node->arithMode());
216     if (node->hasScopeOffset())
217         out.print(comma, node->scopeOffset());
218     if (node->hasDirectArgumentsOffset())
219         out.print(comma, node->capturedArgumentsOffset());
220     if (node->hasRegisterPointer())
221         out.print(comma, "global", globalObjectFor(node->origin.semantic)->findVariableIndex(node->variablePointer()), "(", RawPointer(node->variablePointer()), ")");
222     if (node->hasIdentifier())
223         out.print(comma, "id", node->identifierNumber(), "{", identifiers()[node->identifierNumber()], "}");
224     if (node->hasPromotedLocationDescriptor())
225         out.print(comma, node->promotedLocationDescriptor());
226     if (node->hasStructureSet())
227         out.print(comma, inContext(node->structureSet(), context));
228     if (node->hasStructure())
229         out.print(comma, inContext(*node->structure(), context));
230     if (node->hasTransition()) {
231         out.print(comma, pointerDumpInContext(node->transition(), context));
232 #if USE(JSVALUE64)
233         out.print(", ID:", node->transition()->next->id());
234 #else
235         out.print(", ID:", RawPointer(node->transition()->next));
236 #endif
237     }
238     if (node->hasCellOperand()) {
239         if (!node->cellOperand()->value() || !node->cellOperand()->value().isCell())
240             out.print(comma, "invalid cell operand: ", node->cellOperand()->value());
241         else {
242             out.print(comma, pointerDump(node->cellOperand()->value().asCell()));
243             if (node->cellOperand()->value().isCell()) {
244                 CallVariant variant(node->cellOperand()->value().asCell());
245                 if (ExecutableBase* executable = variant.executable()) {
246                     if (executable->isHostFunction())
247                         out.print(comma, "<host function>");
248                     else if (FunctionExecutable* functionExecutable = jsDynamicCast<FunctionExecutable*>(executable))
249                         out.print(comma, FunctionExecutableDump(functionExecutable));
250                     else
251                         out.print(comma, "<non-function executable>");
252                 }
253             }
254         }
255     }
256     if (node->hasStorageAccessData()) {
257         StorageAccessData& storageAccessData = node->storageAccessData();
258         out.print(comma, "id", storageAccessData.identifierNumber, "{", identifiers()[storageAccessData.identifierNumber], "}");
259         out.print(", ", static_cast<ptrdiff_t>(storageAccessData.offset));
260     }
261     if (node->hasMultiGetByOffsetData()) {
262         MultiGetByOffsetData& data = node->multiGetByOffsetData();
263         out.print(comma, "id", data.identifierNumber, "{", identifiers()[data.identifierNumber], "}");
264         for (unsigned i = 0; i < data.variants.size(); ++i)
265             out.print(comma, inContext(data.variants[i], context));
266     }
267     if (node->hasMultiPutByOffsetData()) {
268         MultiPutByOffsetData& data = node->multiPutByOffsetData();
269         out.print(comma, "id", data.identifierNumber, "{", identifiers()[data.identifierNumber], "}");
270         for (unsigned i = 0; i < data.variants.size(); ++i)
271             out.print(comma, inContext(data.variants[i], context));
272     }
273     ASSERT(node->hasVariableAccessData(*this) == node->hasLocal(*this));
274     if (node->hasVariableAccessData(*this)) {
275         VariableAccessData* variableAccessData = node->tryGetVariableAccessData();
276         if (variableAccessData) {
277             VirtualRegister operand = variableAccessData->local();
278             out.print(comma, variableAccessData->local(), "(", VariableAccessDataDump(*this, variableAccessData), ")");
279             operand = variableAccessData->machineLocal();
280             if (operand.isValid())
281                 out.print(comma, "machine:", operand);
282         }
283     }
284     if (node->hasStackAccessData()) {
285         StackAccessData* data = node->stackAccessData();
286         out.print(comma, data->local);
287         if (data->machineLocal.isValid())
288             out.print(comma, "machine:", data->machineLocal);
289         out.print(comma, data->format);
290     }
291     if (node->hasUnlinkedLocal()) 
292         out.print(comma, node->unlinkedLocal());
293     if (node->hasUnlinkedMachineLocal()) {
294         VirtualRegister operand = node->unlinkedMachineLocal();
295         if (operand.isValid())
296             out.print(comma, "machine:", operand);
297     }
298     if (node->hasConstantBuffer()) {
299         out.print(comma);
300         out.print(node->startConstant(), ":[");
301         CommaPrinter anotherComma;
302         for (unsigned i = 0; i < node->numConstants(); ++i)
303             out.print(anotherComma, pointerDumpInContext(freeze(m_codeBlock->constantBuffer(node->startConstant())[i]), context));
304         out.print("]");
305     }
306     if (node->hasIndexingType())
307         out.print(comma, IndexingTypeDump(node->indexingType()));
308     if (node->hasTypedArrayType())
309         out.print(comma, node->typedArrayType());
310     if (node->hasPhi())
311         out.print(comma, "^", node->phi()->index());
312     if (node->hasExecutionCounter())
313         out.print(comma, RawPointer(node->executionCounter()));
314     if (node->hasVariableWatchpointSet())
315         out.print(comma, RawPointer(node->variableWatchpointSet()));
316     if (node->hasStoragePointer())
317         out.print(comma, RawPointer(node->storagePointer()));
318     if (node->hasObjectMaterializationData())
319         out.print(comma, node->objectMaterializationData());
320     if (node->hasCallVarargsData())
321         out.print(comma, "firstVarArgOffset = ", node->callVarargsData()->firstVarArgOffset);
322     if (node->hasLoadVarargsData()) {
323         LoadVarargsData* data = node->loadVarargsData();
324         out.print(comma, "start = ", data->start, ", count = ", data->count);
325         if (data->machineStart.isValid())
326             out.print(", machineStart = ", data->machineStart);
327         if (data->machineCount.isValid())
328             out.print(", machineCount = ", data->machineCount);
329         out.print(", offset = ", data->offset, ", mandatoryMinimum = ", data->mandatoryMinimum);
330         out.print(", limit = ", data->limit);
331     }
332     if (node->isConstant())
333         out.print(comma, pointerDumpInContext(node->constant(), context));
334     if (node->isJump())
335         out.print(comma, "T:", *node->targetBlock());
336     if (node->isBranch())
337         out.print(comma, "T:", node->branchData()->taken, ", F:", node->branchData()->notTaken);
338     if (node->isSwitch()) {
339         SwitchData* data = node->switchData();
340         out.print(comma, data->kind);
341         for (unsigned i = 0; i < data->cases.size(); ++i)
342             out.print(comma, inContext(data->cases[i].value, context), ":", data->cases[i].target);
343         out.print(comma, "default:", data->fallThrough);
344     }
345     ClobberSet reads;
346     ClobberSet writes;
347     addReadsAndWrites(*this, node, reads, writes);
348     if (!reads.isEmpty())
349         out.print(comma, "R:", sortedListDump(reads.direct(), ","));
350     if (!writes.isEmpty())
351         out.print(comma, "W:", sortedListDump(writes.direct(), ","));
352     if (node->origin.isSet()) {
353         out.print(comma, "bc#", node->origin.semantic.bytecodeIndex);
354         if (node->origin.semantic != node->origin.forExit)
355             out.print(comma, "exit: ", node->origin.forExit);
356     }
357     
358     out.print(")");
359
360     if (node->hasVariableAccessData(*this) && node->tryGetVariableAccessData())
361         out.print("  predicting ", SpeculationDump(node->tryGetVariableAccessData()->prediction()));
362     else if (node->hasHeapPrediction())
363         out.print("  predicting ", SpeculationDump(node->getHeapPrediction()));
364     
365     out.print("\n");
366 }
367
368 void Graph::dumpBlockHeader(PrintStream& out, const char* prefix, BasicBlock* block, PhiNodeDumpMode phiNodeDumpMode, DumpContext* context)
369 {
370     out.print(prefix, "Block ", *block, " (", inContext(block->at(0)->origin.semantic, context), "):", block->isReachable ? "" : " (skipped)", block->isOSRTarget ? " (OSR target)" : "", "\n");
371     if (block->executionCount == block->executionCount)
372         out.print(prefix, "  Execution count: ", block->executionCount, "\n");
373     out.print(prefix, "  Predecessors:");
374     for (size_t i = 0; i < block->predecessors.size(); ++i)
375         out.print(" ", *block->predecessors[i]);
376     out.print("\n");
377     out.print(prefix, "  Successors:");
378     for (BasicBlock* successor : block->successors()) {
379         out.print(" ", *successor);
380         if (m_prePostNumbering.isValid())
381             out.print(" (", m_prePostNumbering.edgeKind(block, successor), ")");
382     }
383     out.print("\n");
384     if (m_dominators.isValid()) {
385         out.print(prefix, "  Dominated by: ", m_dominators.dominatorsOf(block), "\n");
386         out.print(prefix, "  Dominates: ", m_dominators.blocksDominatedBy(block), "\n");
387         out.print(prefix, "  Dominance Frontier: ", m_dominators.dominanceFrontierOf(block), "\n");
388         out.print(prefix, "  Iterated Dominance Frontier: ", m_dominators.iteratedDominanceFrontierOf(BlockList(1, block)), "\n");
389     }
390     if (m_prePostNumbering.isValid())
391         out.print(prefix, "  Pre/Post Numbering: ", m_prePostNumbering.preNumber(block), "/", m_prePostNumbering.postNumber(block), "\n");
392     if (m_naturalLoops.isValid()) {
393         if (const NaturalLoop* loop = m_naturalLoops.headerOf(block)) {
394             out.print(prefix, "  Loop header, contains:");
395             Vector<BlockIndex> sortedBlockList;
396             for (unsigned i = 0; i < loop->size(); ++i)
397                 sortedBlockList.append(loop->at(i)->index);
398             std::sort(sortedBlockList.begin(), sortedBlockList.end());
399             for (unsigned i = 0; i < sortedBlockList.size(); ++i)
400                 out.print(" #", sortedBlockList[i]);
401             out.print("\n");
402         }
403         
404         Vector<const NaturalLoop*> containingLoops =
405             m_naturalLoops.loopsOf(block);
406         if (!containingLoops.isEmpty()) {
407             out.print(prefix, "  Containing loop headers:");
408             for (unsigned i = 0; i < containingLoops.size(); ++i)
409                 out.print(" ", *containingLoops[i]->header());
410             out.print("\n");
411         }
412     }
413     if (!block->phis.isEmpty()) {
414         out.print(prefix, "  Phi Nodes:");
415         for (size_t i = 0; i < block->phis.size(); ++i) {
416             Node* phiNode = block->phis[i];
417             if (!phiNode->shouldGenerate() && phiNodeDumpMode == DumpLivePhisOnly)
418                 continue;
419             out.print(" @", phiNode->index(), "<", phiNode->local(), ",", phiNode->refCount(), ">->(");
420             if (phiNode->child1()) {
421                 out.print("@", phiNode->child1()->index());
422                 if (phiNode->child2()) {
423                     out.print(", @", phiNode->child2()->index());
424                     if (phiNode->child3())
425                         out.print(", @", phiNode->child3()->index());
426                 }
427             }
428             out.print(")", i + 1 < block->phis.size() ? "," : "");
429         }
430         out.print("\n");
431     }
432 }
433
434 void Graph::dump(PrintStream& out, DumpContext* context)
435 {
436     DumpContext myContext;
437     myContext.graph = this;
438     if (!context)
439         context = &myContext;
440     
441     out.print("\n");
442     out.print("DFG for ", CodeBlockWithJITType(m_codeBlock, JITCode::DFGJIT), ":\n");
443     out.print("  Fixpoint state: ", m_fixpointState, "; Form: ", m_form, "; Unification state: ", m_unificationState, "; Ref count state: ", m_refCountState, "\n");
444     if (m_form == SSA)
445         out.print("  Argument formats: ", listDump(m_argumentFormats), "\n");
446     else
447         out.print("  Arguments: ", listDump(m_arguments), "\n");
448     out.print("\n");
449     
450     Node* lastNode = 0;
451     for (size_t b = 0; b < m_blocks.size(); ++b) {
452         BasicBlock* block = m_blocks[b].get();
453         if (!block)
454             continue;
455         dumpBlockHeader(out, "", block, DumpAllPhis, context);
456         out.print("  States: ", block->cfaStructureClobberStateAtHead);
457         if (!block->cfaHasVisited)
458             out.print(", CurrentlyCFAUnreachable");
459         if (!block->intersectionOfCFAHasVisited)
460             out.print(", CFAUnreachable");
461         out.print("\n");
462         switch (m_form) {
463         case LoadStore:
464         case ThreadedCPS: {
465             out.print("  Vars Before: ");
466             if (block->cfaHasVisited)
467                 out.print(inContext(block->valuesAtHead, context));
468             else
469                 out.print("<empty>");
470             out.print("\n");
471             out.print("  Intersected Vars Before: ");
472             if (block->intersectionOfCFAHasVisited)
473                 out.print(inContext(block->intersectionOfPastValuesAtHead, context));
474             else
475                 out.print("<empty>");
476             out.print("\n");
477             out.print("  Var Links: ", block->variablesAtHead, "\n");
478             break;
479         }
480             
481         case SSA: {
482             RELEASE_ASSERT(block->ssa);
483             out.print("  Availability: ", block->ssa->availabilityAtHead, "\n");
484             out.print("  Live: ", nodeListDump(block->ssa->liveAtHead), "\n");
485             out.print("  Values: ", nodeMapDump(block->ssa->valuesAtHead, context), "\n");
486             break;
487         } }
488         for (size_t i = 0; i < block->size(); ++i) {
489             dumpCodeOrigin(out, "", lastNode, block->at(i), context);
490             dump(out, "", block->at(i), context);
491             lastNode = block->at(i);
492         }
493         out.print("  States: ", block->cfaBranchDirection, ", ", block->cfaStructureClobberStateAtTail);
494         if (!block->cfaDidFinish)
495             out.print(", CFAInvalidated");
496         out.print("\n");
497         switch (m_form) {
498         case LoadStore:
499         case ThreadedCPS: {
500             out.print("  Vars After: ");
501             if (block->cfaHasVisited)
502                 out.print(inContext(block->valuesAtTail, context));
503             else
504                 out.print("<empty>");
505             out.print("\n");
506             out.print("  Var Links: ", block->variablesAtTail, "\n");
507             break;
508         }
509             
510         case SSA: {
511             RELEASE_ASSERT(block->ssa);
512             out.print("  Availability: ", block->ssa->availabilityAtTail, "\n");
513             out.print("  Live: ", nodeListDump(block->ssa->liveAtTail), "\n");
514             out.print("  Values: ", nodeMapDump(block->ssa->valuesAtTail, context), "\n");
515             break;
516         } }
517         out.print("\n");
518     }
519     
520     if (!myContext.isEmpty()) {
521         myContext.dump(out);
522         out.print("\n");
523     }
524 }
525
526 void Graph::dethread()
527 {
528     if (m_form == LoadStore || m_form == SSA)
529         return;
530     
531     if (logCompilationChanges())
532         dataLog("Dethreading DFG graph.\n");
533     
534     SamplingRegion samplingRegion("DFG Dethreading");
535     
536     for (BlockIndex blockIndex = m_blocks.size(); blockIndex--;) {
537         BasicBlock* block = m_blocks[blockIndex].get();
538         if (!block)
539             continue;
540         for (unsigned phiIndex = block->phis.size(); phiIndex--;) {
541             Node* phi = block->phis[phiIndex];
542             phi->children.reset();
543         }
544     }
545     
546     m_form = LoadStore;
547 }
548
549 void Graph::handleSuccessor(Vector<BasicBlock*, 16>& worklist, BasicBlock* block, BasicBlock* successor)
550 {
551     if (!successor->isReachable) {
552         successor->isReachable = true;
553         worklist.append(successor);
554     }
555     
556     successor->predecessors.append(block);
557 }
558
559 void Graph::determineReachability()
560 {
561     Vector<BasicBlock*, 16> worklist;
562     worklist.append(block(0));
563     block(0)->isReachable = true;
564     while (!worklist.isEmpty()) {
565         BasicBlock* block = worklist.takeLast();
566         for (unsigned i = block->numSuccessors(); i--;)
567             handleSuccessor(worklist, block, block->successor(i));
568     }
569 }
570
571 void Graph::resetReachability()
572 {
573     for (BlockIndex blockIndex = m_blocks.size(); blockIndex--;) {
574         BasicBlock* block = m_blocks[blockIndex].get();
575         if (!block)
576             continue;
577         block->isReachable = false;
578         block->predecessors.clear();
579     }
580     
581     determineReachability();
582 }
583
584 void Graph::mergeRelevantToOSR()
585 {
586     for (BasicBlock* block : blocksInNaturalOrder()) {
587         for (Node* node : *block) {
588             switch (node->op()) {
589             case MovHint:
590                 node->child1()->mergeFlags(NodeRelevantToOSR);
591                 break;
592                 
593             case PutHint:
594                 node->child2()->mergeFlags(NodeRelevantToOSR);
595                 break;
596                 
597             default:
598                 break;
599             }
600         }
601     }
602 }
603
604 namespace {
605
606 class RefCountCalculator {
607 public:
608     RefCountCalculator(Graph& graph)
609         : m_graph(graph)
610     {
611     }
612     
613     void calculate()
614     {
615         // First reset the counts to 0 for all nodes.
616         //
617         // Also take this opportunity to pretend that Check nodes are not NodeMustGenerate. Check
618         // nodes are MustGenerate because they are executed for effect, but they follow the same
619         // DCE rules as nodes that aren't MustGenerate: they only contribute to the ref count of
620         // their children if the edges require checks. Non-checking edges are removed. Note that
621         // for any Checks left over, this phase will turn them back into NodeMustGenerate.
622         for (BlockIndex blockIndex = 0; blockIndex < m_graph.numBlocks(); ++blockIndex) {
623             BasicBlock* block = m_graph.block(blockIndex);
624             if (!block)
625                 continue;
626             for (unsigned indexInBlock = block->size(); indexInBlock--;)
627                 block->at(indexInBlock)->setRefCount(0);
628             for (unsigned phiIndex = block->phis.size(); phiIndex--;)
629                 block->phis[phiIndex]->setRefCount(0);
630         }
631     
632         // Now find the roots:
633         // - Nodes that are must-generate.
634         // - Nodes that are reachable from type checks.
635         // Set their ref counts to 1 and put them on the worklist.
636         for (BlockIndex blockIndex = 0; blockIndex < m_graph.numBlocks(); ++blockIndex) {
637             BasicBlock* block = m_graph.block(blockIndex);
638             if (!block)
639                 continue;
640             for (unsigned indexInBlock = block->size(); indexInBlock--;) {
641                 Node* node = block->at(indexInBlock);
642                 DFG_NODE_DO_TO_CHILDREN(m_graph, node, findTypeCheckRoot);
643                 if (!(node->flags() & NodeMustGenerate))
644                     continue;
645                 if (node->op() == Check) {
646                     // We don't treat Check nodes as MustGenerate. We will gladly
647                     // kill them off in this phase.
648                     continue;
649                 }
650                 if (!node->postfixRef())
651                     m_worklist.append(node);
652             }
653         }
654         
655         while (!m_worklist.isEmpty()) {
656             while (!m_worklist.isEmpty()) {
657                 Node* node = m_worklist.last();
658                 m_worklist.removeLast();
659                 ASSERT(node->shouldGenerate()); // It should not be on the worklist unless it's ref'ed.
660                 DFG_NODE_DO_TO_CHILDREN(m_graph, node, countEdge);
661             }
662             
663             if (m_graph.m_form == SSA) {
664                 // Find Phi->Upsilon edges, which are represented as meta-data in the
665                 // Upsilon.
666                 for (BlockIndex blockIndex = m_graph.numBlocks(); blockIndex--;) {
667                     BasicBlock* block = m_graph.block(blockIndex);
668                     if (!block)
669                         continue;
670                     for (unsigned nodeIndex = block->size(); nodeIndex--;) {
671                         Node* node = block->at(nodeIndex);
672                         if (node->op() != Upsilon)
673                             continue;
674                         if (node->shouldGenerate())
675                             continue;
676                         if (node->phi()->shouldGenerate())
677                             countNode(node);
678                     }
679                 }
680             }
681         }
682     }
683     
684 private:
685     void findTypeCheckRoot(Node*, Edge edge)
686     {
687         // We may have an "unproved" untyped use for code that is unreachable. The CFA
688         // will just not have gotten around to it.
689         if (edge.isProved() || edge.willNotHaveCheck())
690             return;
691         if (!edge->postfixRef())
692             m_worklist.append(edge.node());
693     }
694     
695     void countNode(Node* node)
696     {
697         if (node->postfixRef())
698             return;
699         m_worklist.append(node);
700     }
701     
702     void countEdge(Node*, Edge edge)
703     {
704         // Don't count edges that are already counted for their type checks.
705         if (!(edge.isProved() || edge.willNotHaveCheck()))
706             return;
707         countNode(edge.node());
708     }
709     
710     Graph& m_graph;
711     Vector<Node*, 128> m_worklist;
712 };
713
714 } // anonymous namespace
715
716 void Graph::computeRefCounts()
717 {
718     RefCountCalculator calculator(*this);
719     calculator.calculate();
720 }
721
722 void Graph::killBlockAndItsContents(BasicBlock* block)
723 {
724     for (unsigned phiIndex = block->phis.size(); phiIndex--;)
725         m_allocator.free(block->phis[phiIndex]);
726     for (unsigned nodeIndex = block->size(); nodeIndex--;)
727         m_allocator.free(block->at(nodeIndex));
728     
729     killBlock(block);
730 }
731
732 void Graph::killUnreachableBlocks()
733 {
734     for (BlockIndex blockIndex = 0; blockIndex < numBlocks(); ++blockIndex) {
735         BasicBlock* block = this->block(blockIndex);
736         if (!block)
737             continue;
738         if (block->isReachable)
739             continue;
740         
741         killBlockAndItsContents(block);
742     }
743 }
744
745 void Graph::invalidateCFG()
746 {
747     m_dominators.invalidate();
748     m_naturalLoops.invalidate();
749     m_prePostNumbering.invalidate();
750 }
751
752 void Graph::substituteGetLocal(BasicBlock& block, unsigned startIndexInBlock, VariableAccessData* variableAccessData, Node* newGetLocal)
753 {
754     for (unsigned indexInBlock = startIndexInBlock; indexInBlock < block.size(); ++indexInBlock) {
755         Node* node = block[indexInBlock];
756         bool shouldContinue = true;
757         switch (node->op()) {
758         case SetLocal: {
759             if (node->local() == variableAccessData->local())
760                 shouldContinue = false;
761             break;
762         }
763                 
764         case GetLocal: {
765             if (node->variableAccessData() != variableAccessData)
766                 continue;
767             substitute(block, indexInBlock, node, newGetLocal);
768             Node* oldTailNode = block.variablesAtTail.operand(variableAccessData->local());
769             if (oldTailNode == node)
770                 block.variablesAtTail.operand(variableAccessData->local()) = newGetLocal;
771             shouldContinue = false;
772             break;
773         }
774                 
775         default:
776             break;
777         }
778         if (!shouldContinue)
779             break;
780     }
781 }
782
783 BlockList Graph::blocksInPreOrder()
784 {
785     BlockList result;
786     BlockWorklist worklist;
787     worklist.push(block(0));
788     while (BasicBlock* block = worklist.pop()) {
789         result.append(block);
790         for (unsigned i = block->numSuccessors(); i--;)
791             worklist.push(block->successor(i));
792     }
793     return result;
794 }
795
796 BlockList Graph::blocksInPostOrder()
797 {
798     BlockList result;
799     PostOrderBlockWorklist worklist;
800     worklist.push(block(0));
801     while (BlockWithOrder item = worklist.pop()) {
802         switch (item.order) {
803         case PreOrder:
804             worklist.pushPost(item.block);
805             for (unsigned i = item.block->numSuccessors(); i--;)
806                 worklist.push(item.block->successor(i));
807             break;
808         case PostOrder:
809             result.append(item.block);
810             break;
811         }
812     }
813     return result;
814 }
815
816 void Graph::clearReplacements()
817 {
818     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
819         BasicBlock* block = m_blocks[blockIndex].get();
820         if (!block)
821             continue;
822         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
823             block->phis[phiIndex]->replacement = 0;
824         for (unsigned nodeIndex = block->size(); nodeIndex--;)
825             block->at(nodeIndex)->replacement = 0;
826     }
827 }
828
829 void Graph::initializeNodeOwners()
830 {
831     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
832         BasicBlock* block = m_blocks[blockIndex].get();
833         if (!block)
834             continue;
835         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
836             block->phis[phiIndex]->owner = block;
837         for (unsigned nodeIndex = block->size(); nodeIndex--;)
838             block->at(nodeIndex)->owner = block;
839     }
840 }
841
842 void Graph::clearFlagsOnAllNodes(NodeFlags flags)
843 {
844     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
845         BasicBlock* block = m_blocks[blockIndex].get();
846         if (!block)
847             continue;
848         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
849             block->phis[phiIndex]->clearFlags(flags);
850         for (unsigned nodeIndex = block->size(); nodeIndex--;)
851             block->at(nodeIndex)->clearFlags(flags);
852     }
853 }
854
855 FullBytecodeLiveness& Graph::livenessFor(CodeBlock* codeBlock)
856 {
857     HashMap<CodeBlock*, std::unique_ptr<FullBytecodeLiveness>>::iterator iter = m_bytecodeLiveness.find(codeBlock);
858     if (iter != m_bytecodeLiveness.end())
859         return *iter->value;
860     
861     std::unique_ptr<FullBytecodeLiveness> liveness = std::make_unique<FullBytecodeLiveness>();
862     codeBlock->livenessAnalysis().computeFullLiveness(*liveness);
863     FullBytecodeLiveness& result = *liveness;
864     m_bytecodeLiveness.add(codeBlock, WTF::move(liveness));
865     return result;
866 }
867
868 FullBytecodeLiveness& Graph::livenessFor(InlineCallFrame* inlineCallFrame)
869 {
870     return livenessFor(baselineCodeBlockFor(inlineCallFrame));
871 }
872
873 BytecodeKills& Graph::killsFor(CodeBlock* codeBlock)
874 {
875     HashMap<CodeBlock*, std::unique_ptr<BytecodeKills>>::iterator iter = m_bytecodeKills.find(codeBlock);
876     if (iter != m_bytecodeKills.end())
877         return *iter->value;
878     
879     std::unique_ptr<BytecodeKills> kills = std::make_unique<BytecodeKills>();
880     codeBlock->livenessAnalysis().computeKills(*kills);
881     BytecodeKills& result = *kills;
882     m_bytecodeKills.add(codeBlock, WTF::move(kills));
883     return result;
884 }
885
886 BytecodeKills& Graph::killsFor(InlineCallFrame* inlineCallFrame)
887 {
888     return killsFor(baselineCodeBlockFor(inlineCallFrame));
889 }
890
891 bool Graph::isLiveInBytecode(VirtualRegister operand, CodeOrigin codeOrigin)
892 {
893     for (;;) {
894         VirtualRegister reg = VirtualRegister(
895             operand.offset() - codeOrigin.stackOffset());
896         
897         if (operand.offset() < codeOrigin.stackOffset() + JSStack::CallFrameHeaderSize) {
898             if (reg.isArgument()) {
899                 RELEASE_ASSERT(reg.offset() < JSStack::CallFrameHeaderSize);
900                 
901                 if (codeOrigin.inlineCallFrame->isClosureCall
902                     && reg.offset() == JSStack::Callee)
903                     return true;
904                 
905                 if (codeOrigin.inlineCallFrame->isVarargs()
906                     && reg.offset() == JSStack::ArgumentCount)
907                     return true;
908                 
909                 return false;
910             }
911             
912             return livenessFor(codeOrigin.inlineCallFrame).operandIsLive(
913                 reg.offset(), codeOrigin.bytecodeIndex);
914         }
915         
916         InlineCallFrame* inlineCallFrame = codeOrigin.inlineCallFrame;
917         if (!inlineCallFrame)
918             break;
919
920         // Arguments are always live. This would be redundant if it wasn't for our
921         // op_call_varargs inlining.
922         // FIXME: 'this' might not be live, but we don't have a way of knowing.
923         // https://bugs.webkit.org/show_bug.cgi?id=128519
924         if (reg.isArgument()
925             && static_cast<size_t>(reg.toArgument()) < inlineCallFrame->arguments.size())
926             return true;
927         
928         codeOrigin = inlineCallFrame->caller;
929     }
930     
931     return true;
932 }
933
934 unsigned Graph::frameRegisterCount()
935 {
936     unsigned result = m_nextMachineLocal + std::max(m_parameterSlots, static_cast<unsigned>(maxFrameExtentForSlowPathCallInRegisters));
937     return roundLocalRegisterCountForFramePointerOffset(result);
938 }
939
940 unsigned Graph::stackPointerOffset()
941 {
942     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
943 }
944
945 unsigned Graph::requiredRegisterCountForExit()
946 {
947     unsigned count = JIT::frameRegisterCountFor(m_profiledBlock);
948     for (InlineCallFrameSet::iterator iter = m_plan.inlineCallFrames->begin(); !!iter; ++iter) {
949         InlineCallFrame* inlineCallFrame = *iter;
950         CodeBlock* codeBlock = baselineCodeBlockForInlineCallFrame(inlineCallFrame);
951         unsigned requiredCount = VirtualRegister(inlineCallFrame->stackOffset).toLocal() + 1 + JIT::frameRegisterCountFor(codeBlock);
952         count = std::max(count, requiredCount);
953     }
954     return count;
955 }
956
957 unsigned Graph::requiredRegisterCountForExecutionAndExit()
958 {
959     return std::max(frameRegisterCount(), requiredRegisterCountForExit());
960 }
961
962 JSValue Graph::tryGetConstantProperty(
963     JSValue base, const StructureSet& structureSet, PropertyOffset offset)
964 {
965     if (!base || !base.isObject())
966         return JSValue();
967     
968     JSObject* object = asObject(base);
969     
970     for (unsigned i = structureSet.size(); i--;) {
971         Structure* structure = structureSet[i];
972         WatchpointSet* set = structure->propertyReplacementWatchpointSet(offset);
973         if (!set || !set->isStillValid())
974             return JSValue();
975         
976         ASSERT(structure->isValidOffset(offset));
977         ASSERT(!structure->isUncacheableDictionary());
978         
979         watchpoints().addLazily(set);
980     }
981     
982     // What follows may require some extra thought. We need this load to load a valid JSValue. If
983     // our profiling makes sense and we're still on track to generate code that won't be
984     // invalidated, then we have nothing to worry about. We do, however, have to worry about
985     // loading - and then using - an invalid JSValue in the case that unbeknownst to us our code
986     // is doomed.
987     //
988     // One argument in favor of this code is that it should definitely work because the butterfly
989     // is always set before the structure. However, we don't currently have a fence between those
990     // stores. It's not clear if this matters, however. We don't ever shrink the property storage.
991     // So, for this to fail, you'd need an access on a constant object pointer such that the inline
992     // caches told us that the object had a structure that it did not *yet* have, and then later,
993     // the object transitioned to that structure that the inline caches had alraedy seen. And then
994     // the processor reordered the stores. Seems unlikely and difficult to test. I believe that
995     // this is worth revisiting but it isn't worth losing sleep over. Filed:
996     // https://bugs.webkit.org/show_bug.cgi?id=134641
997     //
998     // For now, we just do the minimal thing: defend against the structure right now being
999     // incompatible with the getDirect we're trying to do. The easiest way to do that is to
1000     // determine if the structure belongs to the proven set.
1001     
1002     if (!structureSet.contains(object->structure()))
1003         return JSValue();
1004     
1005     return object->getDirect(offset);
1006 }
1007
1008 JSValue Graph::tryGetConstantProperty(JSValue base, Structure* structure, PropertyOffset offset)
1009 {
1010     return tryGetConstantProperty(base, StructureSet(structure), offset);
1011 }
1012
1013 JSValue Graph::tryGetConstantProperty(
1014     JSValue base, const StructureAbstractValue& structure, PropertyOffset offset)
1015 {
1016     if (structure.isTop() || structure.isClobbered())
1017         return JSValue();
1018     
1019     return tryGetConstantProperty(base, structure.set(), offset);
1020 }
1021
1022 JSValue Graph::tryGetConstantProperty(const AbstractValue& base, PropertyOffset offset)
1023 {
1024     return tryGetConstantProperty(base.m_value, base.m_structure, offset);
1025 }
1026
1027 JSValue Graph::tryGetConstantClosureVar(JSValue base, ScopeOffset offset)
1028 {
1029     if (!base)
1030         return JSValue();
1031     
1032     JSLexicalEnvironment* activation = jsDynamicCast<JSLexicalEnvironment*>(base);
1033     if (!activation)
1034         return JSValue();
1035     
1036     SymbolTable* symbolTable = activation->symbolTable();
1037     ConcurrentJITLocker locker(symbolTable->m_lock);
1038     
1039     if (symbolTable->m_functionEnteredOnce.hasBeenInvalidated())
1040         return JSValue();
1041     
1042     SymbolTableEntry* entry = symbolTable->entryFor(locker, offset);
1043     if (!entry)
1044         return JSValue();
1045     
1046     VariableWatchpointSet* set = entry->watchpointSet();
1047     if (!set)
1048         return JSValue();
1049     
1050     JSValue value = set->inferredValue();
1051     if (!value)
1052         return JSValue();
1053     
1054     watchpoints().addLazily(symbolTable->m_functionEnteredOnce);
1055     watchpoints().addLazily(set);
1056     
1057     return value;
1058 }
1059
1060 JSValue Graph::tryGetConstantClosureVar(const AbstractValue& value, ScopeOffset offset)
1061 {
1062     return tryGetConstantClosureVar(value.m_value, offset);
1063 }
1064
1065 JSValue Graph::tryGetConstantClosureVar(Node* node, ScopeOffset offset)
1066 {
1067     if (!node->hasConstant())
1068         return JSValue();
1069     return tryGetConstantClosureVar(node->asJSValue(), offset);
1070 }
1071
1072 JSArrayBufferView* Graph::tryGetFoldableView(JSValue value)
1073 {
1074     if (!value)
1075         return nullptr;
1076     JSArrayBufferView* view = jsDynamicCast<JSArrayBufferView*>(value);
1077     if (!value)
1078         return nullptr;
1079     if (!view->length())
1080         return nullptr;
1081     WTF::loadLoadFence();
1082     watchpoints().addLazily(view);
1083     return view;
1084 }
1085
1086 JSArrayBufferView* Graph::tryGetFoldableView(JSValue value, ArrayMode arrayMode)
1087 {
1088     if (arrayMode.typedArrayType() == NotTypedArray)
1089         return nullptr;
1090     return tryGetFoldableView(value);
1091 }
1092
1093 void Graph::registerFrozenValues()
1094 {
1095     m_codeBlock->constants().resize(0);
1096     m_codeBlock->constantsSourceCodeRepresentation().resize(0);
1097     for (FrozenValue* value : m_frozenValues) {
1098         if (value->structure())
1099             ASSERT(m_plan.weakReferences.contains(value->structure()));
1100         
1101         switch (value->strength()) {
1102         case FragileValue: {
1103             break;
1104         }
1105         case WeakValue: {
1106             m_plan.weakReferences.addLazily(value->value().asCell());
1107             break;
1108         }
1109         case StrongValue: {
1110             unsigned constantIndex = m_codeBlock->addConstantLazily();
1111             initializeLazyWriteBarrierForConstant(
1112                 m_plan.writeBarriers,
1113                 m_codeBlock->constants()[constantIndex],
1114                 m_codeBlock,
1115                 constantIndex,
1116                 m_codeBlock->ownerExecutable(),
1117                 value->value());
1118             break;
1119         } }
1120     }
1121     m_codeBlock->constants().shrinkToFit();
1122     m_codeBlock->constantsSourceCodeRepresentation().shrinkToFit();
1123     
1124     // We have no use DFG IR have no need for FunctionExecutable*'s in the CodeBlock, since we
1125     // use frozen values to refer to them.
1126     m_codeBlock->jettisonFunctionDeclsAndExprs();
1127 }
1128
1129 void Graph::visitChildren(SlotVisitor& visitor)
1130 {
1131     for (FrozenValue* value : m_frozenValues) {
1132         visitor.appendUnbarrieredReadOnlyValue(value->value());
1133         visitor.appendUnbarrieredReadOnlyPointer(value->structure());
1134     }
1135     
1136     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
1137         BasicBlock* block = this->block(blockIndex);
1138         if (!block)
1139             continue;
1140         
1141         for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1142             Node* node = block->at(nodeIndex);
1143             
1144             switch (node->op()) {
1145             case CheckStructure:
1146                 for (unsigned i = node->structureSet().size(); i--;)
1147                     visitor.appendUnbarrieredReadOnlyPointer(node->structureSet()[i]);
1148                 break;
1149                 
1150             case NewObject:
1151             case ArrayifyToStructure:
1152             case NewStringObject:
1153                 visitor.appendUnbarrieredReadOnlyPointer(node->structure());
1154                 break;
1155                 
1156             case PutStructure:
1157             case AllocatePropertyStorage:
1158             case ReallocatePropertyStorage:
1159                 visitor.appendUnbarrieredReadOnlyPointer(
1160                     node->transition()->previous);
1161                 visitor.appendUnbarrieredReadOnlyPointer(
1162                     node->transition()->next);
1163                 break;
1164                 
1165             case MultiGetByOffset:
1166                 for (unsigned i = node->multiGetByOffsetData().variants.size(); i--;) {
1167                     GetByIdVariant& variant = node->multiGetByOffsetData().variants[i];
1168                     const StructureSet& set = variant.structureSet();
1169                     for (unsigned j = set.size(); j--;)
1170                         visitor.appendUnbarrieredReadOnlyPointer(set[j]);
1171
1172                     // Don't need to mark anything in the structure chain because that would
1173                     // have been decomposed into CheckStructure's. Don't need to mark the
1174                     // callLinkStatus because we wouldn't use MultiGetByOffset if any of the
1175                     // variants did that.
1176                     ASSERT(!variant.callLinkStatus());
1177                 }
1178                 break;
1179                     
1180             case MultiPutByOffset:
1181                 for (unsigned i = node->multiPutByOffsetData().variants.size(); i--;) {
1182                     PutByIdVariant& variant = node->multiPutByOffsetData().variants[i];
1183                     const StructureSet& set = variant.oldStructure();
1184                     for (unsigned j = set.size(); j--;)
1185                         visitor.appendUnbarrieredReadOnlyPointer(set[j]);
1186                     if (variant.kind() == PutByIdVariant::Transition)
1187                         visitor.appendUnbarrieredReadOnlyPointer(variant.newStructure());
1188                 }
1189                 break;
1190                 
1191             default:
1192                 break;
1193             }
1194         }
1195     }
1196 }
1197
1198 FrozenValue* Graph::freezeFragile(JSValue value)
1199 {
1200     if (UNLIKELY(!value))
1201         return FrozenValue::emptySingleton();
1202     
1203     auto result = m_frozenValueMap.add(JSValue::encode(value), nullptr);
1204     if (LIKELY(!result.isNewEntry))
1205         return result.iterator->value;
1206     
1207     return result.iterator->value = m_frozenValues.add(FrozenValue::freeze(value));
1208 }
1209
1210 FrozenValue* Graph::freeze(JSValue value)
1211 {
1212     FrozenValue* result = freezeFragile(value);
1213     result->strengthenTo(WeakValue);
1214     return result;
1215 }
1216
1217 FrozenValue* Graph::freezeStrong(JSValue value)
1218 {
1219     FrozenValue* result = freezeFragile(value);
1220     result->strengthenTo(StrongValue);
1221     return result;
1222 }
1223
1224 void Graph::convertToConstant(Node* node, FrozenValue* value)
1225 {
1226     if (value->structure())
1227         assertIsRegistered(value->structure());
1228     if (m_form == ThreadedCPS) {
1229         if (node->op() == GetLocal)
1230             dethread();
1231         else
1232             ASSERT(!node->hasVariableAccessData(*this));
1233     }
1234     node->convertToConstant(value);
1235 }
1236
1237 void Graph::convertToConstant(Node* node, JSValue value)
1238 {
1239     convertToConstant(node, freeze(value));
1240 }
1241
1242 void Graph::convertToStrongConstant(Node* node, JSValue value)
1243 {
1244     convertToConstant(node, freezeStrong(value));
1245 }
1246
1247 StructureRegistrationResult Graph::registerStructure(Structure* structure)
1248 {
1249     m_plan.weakReferences.addLazily(structure);
1250     if (m_plan.watchpoints.consider(structure))
1251         return StructureRegisteredAndWatched;
1252     return StructureRegisteredNormally;
1253 }
1254
1255 void Graph::assertIsRegistered(Structure* structure)
1256 {
1257     if (m_structureRegistrationState == HaveNotStartedRegistering)
1258         return;
1259     
1260     DFG_ASSERT(*this, nullptr, m_plan.weakReferences.contains(structure));
1261     
1262     if (!structure->dfgShouldWatch())
1263         return;
1264     if (watchpoints().isWatched(structure->transitionWatchpointSet()))
1265         return;
1266     
1267     DFG_CRASH(*this, nullptr, toCString("Structure ", pointerDump(structure), " is watchable but isn't being watched.").data());
1268 }
1269
1270 NO_RETURN_DUE_TO_CRASH static void crash(
1271     Graph& graph, const CString& whileText, const char* file, int line, const char* function,
1272     const char* assertion)
1273 {
1274     startCrashing();
1275     dataLog("DFG ASSERTION FAILED: ", assertion, "\n");
1276     dataLog(file, "(", line, ") : ", function, "\n");
1277     dataLog("\n");
1278     dataLog(whileText);
1279     dataLog("Graph at time of failure:\n");
1280     graph.dump();
1281     dataLog("\n");
1282     dataLog("DFG ASSERTION FAILED: ", assertion, "\n");
1283     dataLog(file, "(", line, ") : ", function, "\n");
1284     CRASH_WITH_SECURITY_IMPLICATION();
1285 }
1286
1287 void Graph::handleAssertionFailure(
1288     std::nullptr_t, const char* file, int line, const char* function, const char* assertion)
1289 {
1290     crash(*this, "", file, line, function, assertion);
1291 }
1292
1293 void Graph::handleAssertionFailure(
1294     Node* node, const char* file, int line, const char* function, const char* assertion)
1295 {
1296     crash(*this, toCString("While handling node ", node, "\n\n"), file, line, function, assertion);
1297 }
1298
1299 void Graph::handleAssertionFailure(
1300     BasicBlock* block, const char* file, int line, const char* function, const char* assertion)
1301 {
1302     crash(*this, toCString("While handling block ", pointerDump(block), "\n\n"), file, line, function, assertion);
1303 }
1304
1305 ValueProfile* Graph::valueProfileFor(Node* node)
1306 {
1307     if (!node)
1308         return nullptr;
1309         
1310     CodeBlock* profiledBlock = baselineCodeBlockFor(node->origin.semantic);
1311         
1312     if (node->hasLocal(*this)) {
1313         if (!node->local().isArgument())
1314             return nullptr;
1315         int argument = node->local().toArgument();
1316         Node* argumentNode = m_arguments[argument];
1317         if (!argumentNode)
1318             return nullptr;
1319         if (node->variableAccessData() != argumentNode->variableAccessData())
1320             return nullptr;
1321         return profiledBlock->valueProfileForArgument(argument);
1322     }
1323         
1324     if (node->hasHeapPrediction())
1325         return profiledBlock->valueProfileForBytecodeOffset(node->origin.semantic.bytecodeIndex);
1326         
1327     return nullptr;
1328 }
1329
1330 MethodOfGettingAValueProfile Graph::methodOfGettingAValueProfileFor(Node* node)
1331 {
1332     if (!node)
1333         return MethodOfGettingAValueProfile();
1334     
1335     if (ValueProfile* valueProfile = valueProfileFor(node))
1336         return MethodOfGettingAValueProfile(valueProfile);
1337     
1338     if (node->op() == GetLocal) {
1339         CodeBlock* profiledBlock = baselineCodeBlockFor(node->origin.semantic);
1340         
1341         return MethodOfGettingAValueProfile::fromLazyOperand(
1342             profiledBlock,
1343             LazyOperandValueProfileKey(
1344                 node->origin.semantic.bytecodeIndex, node->local()));
1345     }
1346     
1347     return MethodOfGettingAValueProfile();
1348 }
1349
1350 } } // namespace JSC::DFG
1351
1352 #endif // ENABLE(DFG_JIT)