DFG plays fast and loose with the shadow values of a Phi
[WebKit.git] / Source / JavaScriptCore / dfg / DFGGraph.cpp
1 /*
2  * Copyright (C) 2011, 2013-2016 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 "DFGBackwardsCFG.h"
36 #include "DFGBackwardsDominators.h"
37 #include "DFGBlockWorklist.h"
38 #include "DFGCFG.h"
39 #include "DFGClobberSet.h"
40 #include "DFGClobbersExitState.h"
41 #include "DFGControlEquivalenceAnalysis.h"
42 #include "DFGDominators.h"
43 #include "DFGFlowIndexing.h"
44 #include "DFGFlowMap.h"
45 #include "DFGJITCode.h"
46 #include "DFGMayExit.h"
47 #include "DFGNaturalLoops.h"
48 #include "DFGPrePostNumbering.h"
49 #include "DFGVariableAccessDataDump.h"
50 #include "FullBytecodeLiveness.h"
51 #include "FunctionExecutableDump.h"
52 #include "GetterSetter.h"
53 #include "JIT.h"
54 #include "JSLexicalEnvironment.h"
55 #include "MaxFrameExtentForSlowPathCall.h"
56 #include "OperandsInlines.h"
57 #include "JSCInlines.h"
58 #include "StackAlignment.h"
59 #include <wtf/CommaPrinter.h>
60 #include <wtf/ListDump.h>
61
62 namespace JSC { namespace DFG {
63
64 // Creates an array of stringized names.
65 static const char* dfgOpNames[] = {
66 #define STRINGIZE_DFG_OP_ENUM(opcode, flags) #opcode ,
67     FOR_EACH_DFG_OP(STRINGIZE_DFG_OP_ENUM)
68 #undef STRINGIZE_DFG_OP_ENUM
69 };
70
71 Graph::Graph(VM& vm, Plan& plan, LongLivedState& longLivedState)
72     : m_vm(vm)
73     , m_plan(plan)
74     , m_codeBlock(m_plan.codeBlock)
75     , m_profiledBlock(m_codeBlock->alternative())
76     , m_allocator(longLivedState.m_allocator)
77     , m_cfg(std::make_unique<CFG>(*this))
78     , m_nextMachineLocal(0)
79     , m_fixpointState(BeforeFixpoint)
80     , m_structureRegistrationState(HaveNotStartedRegistering)
81     , m_form(LoadStore)
82     , m_unificationState(LocallyUnified)
83     , m_refCountState(EverythingIsLive)
84 {
85     ASSERT(m_profiledBlock);
86     
87     m_hasDebuggerEnabled = m_profiledBlock->wasCompiledWithDebuggingOpcodes() || Options::forceDebuggerBytecodeGeneration();
88     
89     m_indexingCache = std::make_unique<FlowIndexing>(*this);
90     m_abstractValuesCache = std::make_unique<FlowMap<AbstractValue>>(*this);
91 }
92
93 Graph::~Graph()
94 {
95     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
96         BasicBlock* block = this->block(blockIndex);
97         if (!block)
98             continue;
99
100         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
101             m_allocator.free(block->phis[phiIndex]);
102         for (unsigned nodeIndex = block->size(); nodeIndex--;)
103             m_allocator.free(block->at(nodeIndex));
104     }
105     m_allocator.freeAll();
106 }
107
108 const char *Graph::opName(NodeType op)
109 {
110     return dfgOpNames[op];
111 }
112
113 static void printWhiteSpace(PrintStream& out, unsigned amount)
114 {
115     while (amount-- > 0)
116         out.print(" ");
117 }
118
119 bool Graph::dumpCodeOrigin(PrintStream& out, const char* prefix, Node*& previousNodeRef, Node* currentNode, DumpContext* context)
120 {
121     if (!currentNode->origin.semantic)
122         return false;
123     
124     Node* previousNode = previousNodeRef;
125     previousNodeRef = currentNode;
126
127     if (!previousNode)
128         return false;
129     
130     if (previousNode->origin.semantic.inlineCallFrame == currentNode->origin.semantic.inlineCallFrame)
131         return false;
132     
133     Vector<CodeOrigin> previousInlineStack = previousNode->origin.semantic.inlineStack();
134     Vector<CodeOrigin> currentInlineStack = currentNode->origin.semantic.inlineStack();
135     unsigned commonSize = std::min(previousInlineStack.size(), currentInlineStack.size());
136     unsigned indexOfDivergence = commonSize;
137     for (unsigned i = 0; i < commonSize; ++i) {
138         if (previousInlineStack[i].inlineCallFrame != currentInlineStack[i].inlineCallFrame) {
139             indexOfDivergence = i;
140             break;
141         }
142     }
143     
144     bool hasPrinted = false;
145     
146     // Print the pops.
147     for (unsigned i = previousInlineStack.size(); i-- > indexOfDivergence;) {
148         out.print(prefix);
149         printWhiteSpace(out, i * 2);
150         out.print("<-- ", inContext(*previousInlineStack[i].inlineCallFrame, context), "\n");
151         hasPrinted = true;
152     }
153     
154     // Print the pushes.
155     for (unsigned i = indexOfDivergence; i < currentInlineStack.size(); ++i) {
156         out.print(prefix);
157         printWhiteSpace(out, i * 2);
158         out.print("--> ", inContext(*currentInlineStack[i].inlineCallFrame, context), "\n");
159         hasPrinted = true;
160     }
161     
162     return hasPrinted;
163 }
164
165 int Graph::amountOfNodeWhiteSpace(Node* node)
166 {
167     return (node->origin.semantic.inlineDepth() - 1) * 2;
168 }
169
170 void Graph::printNodeWhiteSpace(PrintStream& out, Node* node)
171 {
172     printWhiteSpace(out, amountOfNodeWhiteSpace(node));
173 }
174
175 void Graph::dump(PrintStream& out, const char* prefix, Node* node, DumpContext* context)
176 {
177     NodeType op = node->op();
178
179     unsigned refCount = node->refCount();
180     bool mustGenerate = node->mustGenerate();
181     if (mustGenerate)
182         --refCount;
183
184     out.print(prefix);
185     printNodeWhiteSpace(out, node);
186
187     // Example/explanation of dataflow dump output
188     //
189     //   14:   <!2:7>  GetByVal(@3, @13)
190     //   ^1     ^2 ^3     ^4       ^5
191     //
192     // (1) The nodeIndex of this operation.
193     // (2) The reference count. The number printed is the 'real' count,
194     //     not including the 'mustGenerate' ref. If the node is
195     //     'mustGenerate' then the count it prefixed with '!'.
196     // (3) The virtual register slot assigned to this node.
197     // (4) The name of the operation.
198     // (5) The arguments to the operation. The may be of the form:
199     //         @#   - a NodeIndex referencing a prior node in the graph.
200     //         arg# - an argument number.
201     //         id#  - the index in the CodeBlock of an identifier { if codeBlock is passed to dump(), the string representation is displayed }.
202     //         var# - the index of a var on the global object, used by GetGlobalVar/GetGlobalLexicalVariable/PutGlobalVariable operations.
203     out.printf("% 4d:<%c%u:", (int)node->index(), mustGenerate ? '!' : ' ', refCount);
204     if (node->hasResult() && node->hasVirtualRegister() && node->virtualRegister().isValid())
205         out.print(node->virtualRegister());
206     else
207         out.print("-");
208     out.print(">\t", opName(op), "(");
209     CommaPrinter comma;
210     if (node->flags() & NodeHasVarArgs) {
211         for (unsigned childIdx = node->firstChild(); childIdx < node->firstChild() + node->numChildren(); childIdx++) {
212             if (!m_varArgChildren[childIdx])
213                 continue;
214             out.print(comma, m_varArgChildren[childIdx]);
215         }
216     } else {
217         if (!!node->child1() || !!node->child2() || !!node->child3())
218             out.print(comma, node->child1());
219         if (!!node->child2() || !!node->child3())
220             out.print(comma, node->child2());
221         if (!!node->child3())
222             out.print(comma, node->child3());
223     }
224
225     if (toCString(NodeFlagsDump(node->flags())) != "<empty>")
226         out.print(comma, NodeFlagsDump(node->flags()));
227     if (node->prediction())
228         out.print(comma, SpeculationDump(node->prediction()));
229     if (node->hasArrayMode())
230         out.print(comma, node->arrayMode());
231     if (node->hasArithMode())
232         out.print(comma, node->arithMode());
233     if (node->hasArithRoundingMode())
234         out.print(comma, "Rounding:", node->arithRoundingMode());
235     if (node->hasScopeOffset())
236         out.print(comma, node->scopeOffset());
237     if (node->hasDirectArgumentsOffset())
238         out.print(comma, node->capturedArgumentsOffset());
239     if (node->hasRegisterPointer())
240         out.print(comma, "global", "(", RawPointer(node->variablePointer()), ")");
241     if (node->hasIdentifier())
242         out.print(comma, "id", node->identifierNumber(), "{", identifiers()[node->identifierNumber()], "}");
243     if (node->hasPromotedLocationDescriptor())
244         out.print(comma, node->promotedLocationDescriptor());
245     if (node->hasStructureSet())
246         out.print(comma, inContext(node->structureSet(), context));
247     if (node->hasStructure())
248         out.print(comma, inContext(*node->structure(), context));
249     if (node->hasTransition()) {
250         out.print(comma, pointerDumpInContext(node->transition(), context));
251 #if USE(JSVALUE64)
252         out.print(", ID:", node->transition()->next->id());
253 #else
254         out.print(", ID:", RawPointer(node->transition()->next));
255 #endif
256     }
257     if (node->hasCellOperand()) {
258         if (!node->cellOperand()->value() || !node->cellOperand()->value().isCell())
259             out.print(comma, "invalid cell operand: ", node->cellOperand()->value());
260         else {
261             out.print(comma, pointerDump(node->cellOperand()->value().asCell()));
262             if (node->cellOperand()->value().isCell()) {
263                 CallVariant variant(node->cellOperand()->value().asCell());
264                 if (ExecutableBase* executable = variant.executable()) {
265                     if (executable->isHostFunction())
266                         out.print(comma, "<host function>");
267                     else if (FunctionExecutable* functionExecutable = jsDynamicCast<FunctionExecutable*>(executable))
268                         out.print(comma, FunctionExecutableDump(functionExecutable));
269                     else
270                         out.print(comma, "<non-function executable>");
271                 }
272             }
273         }
274     }
275     if (node->hasSpeculatedTypeForQuery())
276         out.print(comma, SpeculationDump(node->speculatedTypeForQuery()));
277     if (node->hasStorageAccessData()) {
278         StorageAccessData& storageAccessData = node->storageAccessData();
279         out.print(comma, "id", storageAccessData.identifierNumber, "{", identifiers()[storageAccessData.identifierNumber], "}");
280         out.print(", ", static_cast<ptrdiff_t>(storageAccessData.offset));
281         out.print(", inferredType = ", inContext(storageAccessData.inferredType, context));
282     }
283     if (node->hasMultiGetByOffsetData()) {
284         MultiGetByOffsetData& data = node->multiGetByOffsetData();
285         out.print(comma, "id", data.identifierNumber, "{", identifiers()[data.identifierNumber], "}");
286         for (unsigned i = 0; i < data.cases.size(); ++i)
287             out.print(comma, inContext(data.cases[i], context));
288     }
289     if (node->hasMultiPutByOffsetData()) {
290         MultiPutByOffsetData& data = node->multiPutByOffsetData();
291         out.print(comma, "id", data.identifierNumber, "{", identifiers()[data.identifierNumber], "}");
292         for (unsigned i = 0; i < data.variants.size(); ++i)
293             out.print(comma, inContext(data.variants[i], context));
294     }
295     ASSERT(node->hasVariableAccessData(*this) == node->accessesStack(*this));
296     if (node->hasVariableAccessData(*this)) {
297         VariableAccessData* variableAccessData = node->tryGetVariableAccessData();
298         if (variableAccessData) {
299             VirtualRegister operand = variableAccessData->local();
300             out.print(comma, variableAccessData->local(), "(", VariableAccessDataDump(*this, variableAccessData), ")");
301             operand = variableAccessData->machineLocal();
302             if (operand.isValid())
303                 out.print(comma, "machine:", operand);
304         }
305     }
306     if (node->hasStackAccessData()) {
307         StackAccessData* data = node->stackAccessData();
308         out.print(comma, data->local);
309         if (data->machineLocal.isValid())
310             out.print(comma, "machine:", data->machineLocal);
311         out.print(comma, data->format);
312     }
313     if (node->hasUnlinkedLocal()) 
314         out.print(comma, node->unlinkedLocal());
315     if (node->hasUnlinkedMachineLocal()) {
316         VirtualRegister operand = node->unlinkedMachineLocal();
317         if (operand.isValid())
318             out.print(comma, "machine:", operand);
319     }
320     if (node->hasConstantBuffer()) {
321         out.print(comma);
322         out.print(node->startConstant(), ":[");
323         CommaPrinter anotherComma;
324         for (unsigned i = 0; i < node->numConstants(); ++i)
325             out.print(anotherComma, pointerDumpInContext(freeze(m_codeBlock->constantBuffer(node->startConstant())[i]), context));
326         out.print("]");
327     }
328     if (node->hasLazyJSValue())
329         out.print(comma, node->lazyJSValue());
330     if (node->hasIndexingType())
331         out.print(comma, IndexingTypeDump(node->indexingType()));
332     if (node->hasTypedArrayType())
333         out.print(comma, node->typedArrayType());
334     if (node->hasPhi())
335         out.print(comma, "^", node->phi()->index());
336     if (node->hasExecutionCounter())
337         out.print(comma, RawPointer(node->executionCounter()));
338     if (node->hasWatchpointSet())
339         out.print(comma, RawPointer(node->watchpointSet()));
340     if (node->hasStoragePointer())
341         out.print(comma, RawPointer(node->storagePointer()));
342     if (node->hasObjectMaterializationData())
343         out.print(comma, node->objectMaterializationData());
344     if (node->hasCallVarargsData())
345         out.print(comma, "firstVarArgOffset = ", node->callVarargsData()->firstVarArgOffset);
346     if (node->hasLoadVarargsData()) {
347         LoadVarargsData* data = node->loadVarargsData();
348         out.print(comma, "start = ", data->start, ", count = ", data->count);
349         if (data->machineStart.isValid())
350             out.print(", machineStart = ", data->machineStart);
351         if (data->machineCount.isValid())
352             out.print(", machineCount = ", data->machineCount);
353         out.print(", offset = ", data->offset, ", mandatoryMinimum = ", data->mandatoryMinimum);
354         out.print(", limit = ", data->limit);
355     }
356     if (node->hasCallDOMGetterData()) {
357         CallDOMGetterData* data = node->callDOMGetterData();
358         out.print(comma, "id", data->identifierNumber, "{", identifiers()[data->identifierNumber], "}");
359         out.print(", domJIT = ", RawPointer(data->domJIT));
360     }
361     if (node->isConstant())
362         out.print(comma, pointerDumpInContext(node->constant(), context));
363     if (node->isJump())
364         out.print(comma, "T:", *node->targetBlock());
365     if (node->isBranch())
366         out.print(comma, "T:", node->branchData()->taken, ", F:", node->branchData()->notTaken);
367     if (node->isSwitch()) {
368         SwitchData* data = node->switchData();
369         out.print(comma, data->kind);
370         for (unsigned i = 0; i < data->cases.size(); ++i)
371             out.print(comma, inContext(data->cases[i].value, context), ":", data->cases[i].target);
372         out.print(comma, "default:", data->fallThrough);
373     }
374     ClobberSet reads;
375     ClobberSet writes;
376     addReadsAndWrites(*this, node, reads, writes);
377     if (!reads.isEmpty())
378         out.print(comma, "R:", sortedListDump(reads.direct(), ","));
379     if (!writes.isEmpty())
380         out.print(comma, "W:", sortedListDump(writes.direct(), ","));
381     ExitMode exitMode = mayExit(*this, node);
382     if (exitMode != DoesNotExit)
383         out.print(comma, exitMode);
384     if (clobbersExitState(*this, node))
385         out.print(comma, "ClobbersExit");
386     if (node->origin.isSet()) {
387         out.print(comma, "bc#", node->origin.semantic.bytecodeIndex);
388         if (node->origin.semantic != node->origin.forExit && node->origin.forExit.isSet())
389             out.print(comma, "exit: ", node->origin.forExit);
390     }
391     if (!node->origin.exitOK)
392         out.print(comma, "ExitInvalid");
393     if (node->origin.wasHoisted)
394         out.print(comma, "WasHoisted");
395     out.print(")");
396
397     if (node->accessesStack(*this) && node->tryGetVariableAccessData())
398         out.print("  predicting ", SpeculationDump(node->tryGetVariableAccessData()->prediction()));
399     else if (node->hasHeapPrediction())
400         out.print("  predicting ", SpeculationDump(node->getHeapPrediction()));
401     
402     out.print("\n");
403 }
404
405 bool Graph::terminalsAreValid()
406 {
407     for (BasicBlock* block : blocksInNaturalOrder()) {
408         if (!block->terminal())
409             return false;
410     }
411     return true;
412 }
413
414 void Graph::dumpBlockHeader(PrintStream& out, const char* prefix, BasicBlock* block, PhiNodeDumpMode phiNodeDumpMode, DumpContext* context)
415 {
416     out.print(prefix, "Block ", *block, " (", inContext(block->at(0)->origin.semantic, context), "):", block->isReachable ? "" : " (skipped)", block->isOSRTarget ? " (OSR target)" : "", "\n");
417     if (block->executionCount == block->executionCount)
418         out.print(prefix, "  Execution count: ", block->executionCount, "\n");
419     out.print(prefix, "  Predecessors:");
420     for (size_t i = 0; i < block->predecessors.size(); ++i)
421         out.print(" ", *block->predecessors[i]);
422     out.print("\n");
423     out.print(prefix, "  Successors:");
424     if (block->terminal()) {
425         for (BasicBlock* successor : block->successors()) {
426             out.print(" ", *successor);
427             if (m_prePostNumbering)
428                 out.print(" (", m_prePostNumbering->edgeKind(block, successor), ")");
429         }
430     } else
431         out.print(" <invalid>");
432     out.print("\n");
433     if (m_dominators && terminalsAreValid()) {
434         out.print(prefix, "  Dominated by: ", m_dominators->dominatorsOf(block), "\n");
435         out.print(prefix, "  Dominates: ", m_dominators->blocksDominatedBy(block), "\n");
436         out.print(prefix, "  Dominance Frontier: ", m_dominators->dominanceFrontierOf(block), "\n");
437         out.print(prefix, "  Iterated Dominance Frontier: ", m_dominators->iteratedDominanceFrontierOf(BlockList(1, block)), "\n");
438     }
439     if (m_backwardsDominators && terminalsAreValid()) {
440         out.print(prefix, "  Backwards dominates by: ", m_backwardsDominators->dominatorsOf(block), "\n");
441         out.print(prefix, "  Backwards dominates: ", m_backwardsDominators->blocksDominatedBy(block), "\n");
442     }
443     if (m_controlEquivalenceAnalysis && terminalsAreValid()) {
444         out.print(prefix, "  Control equivalent to:");
445         for (BasicBlock* otherBlock : blocksInNaturalOrder()) {
446             if (m_controlEquivalenceAnalysis->areEquivalent(block, otherBlock))
447                 out.print(" ", *otherBlock);
448         }
449         out.print("\n");
450     }
451     if (m_prePostNumbering)
452         out.print(prefix, "  Pre/Post Numbering: ", m_prePostNumbering->preNumber(block), "/", m_prePostNumbering->postNumber(block), "\n");
453     if (m_naturalLoops) {
454         if (const NaturalLoop* loop = m_naturalLoops->headerOf(block)) {
455             out.print(prefix, "  Loop header, contains:");
456             Vector<BlockIndex> sortedBlockList;
457             for (unsigned i = 0; i < loop->size(); ++i)
458                 sortedBlockList.append(loop->at(i)->index);
459             std::sort(sortedBlockList.begin(), sortedBlockList.end());
460             for (unsigned i = 0; i < sortedBlockList.size(); ++i)
461                 out.print(" #", sortedBlockList[i]);
462             out.print("\n");
463         }
464         
465         Vector<const NaturalLoop*> containingLoops =
466             m_naturalLoops->loopsOf(block);
467         if (!containingLoops.isEmpty()) {
468             out.print(prefix, "  Containing loop headers:");
469             for (unsigned i = 0; i < containingLoops.size(); ++i)
470                 out.print(" ", *containingLoops[i]->header());
471             out.print("\n");
472         }
473     }
474     if (!block->phis.isEmpty()) {
475         out.print(prefix, "  Phi Nodes:");
476         for (size_t i = 0; i < block->phis.size(); ++i) {
477             Node* phiNode = block->phis[i];
478             if (!phiNode->shouldGenerate() && phiNodeDumpMode == DumpLivePhisOnly)
479                 continue;
480             out.print(" @", phiNode->index(), "<", phiNode->local(), ",", phiNode->refCount(), ">->(");
481             if (phiNode->child1()) {
482                 out.print("@", phiNode->child1()->index());
483                 if (phiNode->child2()) {
484                     out.print(", @", phiNode->child2()->index());
485                     if (phiNode->child3())
486                         out.print(", @", phiNode->child3()->index());
487                 }
488             }
489             out.print(")", i + 1 < block->phis.size() ? "," : "");
490         }
491         out.print("\n");
492     }
493 }
494
495 void Graph::dump(PrintStream& out, DumpContext* context)
496 {
497     DumpContext myContext;
498     myContext.graph = this;
499     if (!context)
500         context = &myContext;
501     
502     out.print("\n");
503     out.print("DFG for ", CodeBlockWithJITType(m_codeBlock, JITCode::DFGJIT), ":\n");
504     out.print("  Fixpoint state: ", m_fixpointState, "; Form: ", m_form, "; Unification state: ", m_unificationState, "; Ref count state: ", m_refCountState, "\n");
505     if (m_form == SSA)
506         out.print("  Argument formats: ", listDump(m_argumentFormats), "\n");
507     else
508         out.print("  Arguments: ", listDump(m_arguments), "\n");
509     out.print("\n");
510     
511     Node* lastNode = nullptr;
512     for (size_t b = 0; b < m_blocks.size(); ++b) {
513         BasicBlock* block = m_blocks[b].get();
514         if (!block)
515             continue;
516         dumpBlockHeader(out, "", block, DumpAllPhis, context);
517         out.print("  States: ", block->cfaStructureClobberStateAtHead);
518         if (!block->cfaHasVisited)
519             out.print(", CurrentlyCFAUnreachable");
520         if (!block->intersectionOfCFAHasVisited)
521             out.print(", CFAUnreachable");
522         out.print("\n");
523         switch (m_form) {
524         case LoadStore:
525         case ThreadedCPS: {
526             out.print("  Vars Before: ");
527             if (block->cfaHasVisited)
528                 out.print(inContext(block->valuesAtHead, context));
529             else
530                 out.print("<empty>");
531             out.print("\n");
532             out.print("  Intersected Vars Before: ");
533             if (block->intersectionOfCFAHasVisited)
534                 out.print(inContext(block->intersectionOfPastValuesAtHead, context));
535             else
536                 out.print("<empty>");
537             out.print("\n");
538             out.print("  Var Links: ", block->variablesAtHead, "\n");
539             break;
540         }
541             
542         case SSA: {
543             RELEASE_ASSERT(block->ssa);
544             out.print("  Availability: ", block->ssa->availabilityAtHead, "\n");
545             out.print("  Live: ", nodeListDump(block->ssa->liveAtHead), "\n");
546             out.print("  Values: ", nodeValuePairListDump(block->ssa->valuesAtHead, context), "\n");
547             break;
548         } }
549         for (size_t i = 0; i < block->size(); ++i) {
550             dumpCodeOrigin(out, "", lastNode, block->at(i), context);
551             dump(out, "", block->at(i), context);
552         }
553         out.print("  States: ", block->cfaBranchDirection, ", ", block->cfaStructureClobberStateAtTail);
554         if (!block->cfaDidFinish)
555             out.print(", CFAInvalidated");
556         out.print("\n");
557         switch (m_form) {
558         case LoadStore:
559         case ThreadedCPS: {
560             out.print("  Vars After: ");
561             if (block->cfaHasVisited)
562                 out.print(inContext(block->valuesAtTail, context));
563             else
564                 out.print("<empty>");
565             out.print("\n");
566             out.print("  Var Links: ", block->variablesAtTail, "\n");
567             break;
568         }
569             
570         case SSA: {
571             RELEASE_ASSERT(block->ssa);
572             out.print("  Availability: ", block->ssa->availabilityAtTail, "\n");
573             out.print("  Live: ", nodeListDump(block->ssa->liveAtTail), "\n");
574             out.print("  Values: ", nodeValuePairListDump(block->ssa->valuesAtTail, context), "\n");
575             break;
576         } }
577         out.print("\n");
578     }
579     
580     out.print("GC Values:\n");
581     for (FrozenValue* value : m_frozenValues) {
582         if (value->pointsToHeap())
583             out.print("    ", inContext(*value, &myContext), "\n");
584     }
585
586     out.print(inContext(watchpoints(), &myContext));
587     
588     if (!myContext.isEmpty()) {
589         myContext.dump(out);
590         out.print("\n");
591     }
592 }
593
594 void Graph::addNodeToMapByIndex(Node* node)
595 {
596     if (m_nodeIndexFreeList.isEmpty()) {
597         node->m_index = m_nodesByIndex.size();
598         m_nodesByIndex.append(node);
599         return;
600     }
601     unsigned index = m_nodeIndexFreeList.takeLast();
602     node->m_index = index;
603     ASSERT(!m_nodesByIndex[index]);
604     m_nodesByIndex[index] = node;
605 }
606
607 void Graph::deleteNode(Node* node)
608 {
609     if (validationEnabled() && m_form == SSA) {
610         for (BasicBlock* block : blocksInNaturalOrder()) {
611             DFG_ASSERT(*this, node, !block->ssa->liveAtHead.contains(node));
612             DFG_ASSERT(*this, node, !block->ssa->liveAtTail.contains(node));
613         }
614     }
615
616     RELEASE_ASSERT(m_nodesByIndex[node->m_index] == node);
617     unsigned nodeIndex = node->m_index;
618     m_nodesByIndex[nodeIndex] = nullptr;
619     m_nodeIndexFreeList.append(nodeIndex);
620
621     m_allocator.free(node);
622 }
623
624 void Graph::packNodeIndices()
625 {
626     if (m_nodeIndexFreeList.isEmpty())
627         return;
628
629     unsigned holeIndex = 0;
630     unsigned endIndex = m_nodesByIndex.size();
631
632     while (true) {
633         while (holeIndex < endIndex && m_nodesByIndex[holeIndex])
634             ++holeIndex;
635
636         if (holeIndex == endIndex)
637             break;
638         ASSERT(holeIndex < m_nodesByIndex.size());
639         ASSERT(!m_nodesByIndex[holeIndex]);
640
641         do {
642             --endIndex;
643         } while (!m_nodesByIndex[endIndex] && endIndex > holeIndex);
644
645         if (holeIndex == endIndex)
646             break;
647         ASSERT(endIndex > holeIndex);
648         ASSERT(m_nodesByIndex[endIndex]);
649
650         auto& value = m_nodesByIndex[endIndex];
651         value->m_index = holeIndex;
652         m_nodesByIndex[holeIndex] = WTFMove(value);
653         ++holeIndex;
654     }
655
656     m_nodeIndexFreeList.resize(0);
657     m_nodesByIndex.resize(endIndex);
658 }
659
660 void Graph::dethread()
661 {
662     if (m_form == LoadStore || m_form == SSA)
663         return;
664     
665     if (logCompilationChanges())
666         dataLog("Dethreading DFG graph.\n");
667     
668     for (BlockIndex blockIndex = m_blocks.size(); blockIndex--;) {
669         BasicBlock* block = m_blocks[blockIndex].get();
670         if (!block)
671             continue;
672         for (unsigned phiIndex = block->phis.size(); phiIndex--;) {
673             Node* phi = block->phis[phiIndex];
674             phi->children.reset();
675         }
676     }
677     
678     m_form = LoadStore;
679 }
680
681 void Graph::handleSuccessor(Vector<BasicBlock*, 16>& worklist, BasicBlock* block, BasicBlock* successor)
682 {
683     if (!successor->isReachable) {
684         successor->isReachable = true;
685         worklist.append(successor);
686     }
687     
688     successor->predecessors.append(block);
689 }
690
691 void Graph::determineReachability()
692 {
693     Vector<BasicBlock*, 16> worklist;
694     worklist.append(block(0));
695     block(0)->isReachable = true;
696     while (!worklist.isEmpty()) {
697         BasicBlock* block = worklist.takeLast();
698         for (unsigned i = block->numSuccessors(); i--;)
699             handleSuccessor(worklist, block, block->successor(i));
700     }
701 }
702
703 void Graph::resetReachability()
704 {
705     for (BlockIndex blockIndex = m_blocks.size(); blockIndex--;) {
706         BasicBlock* block = m_blocks[blockIndex].get();
707         if (!block)
708             continue;
709         block->isReachable = false;
710         block->predecessors.clear();
711     }
712     
713     determineReachability();
714 }
715
716 namespace {
717
718 class RefCountCalculator {
719 public:
720     RefCountCalculator(Graph& graph)
721         : m_graph(graph)
722     {
723     }
724     
725     void calculate()
726     {
727         // First reset the counts to 0 for all nodes.
728         for (BlockIndex blockIndex = 0; blockIndex < m_graph.numBlocks(); ++blockIndex) {
729             BasicBlock* block = m_graph.block(blockIndex);
730             if (!block)
731                 continue;
732             for (unsigned indexInBlock = block->size(); indexInBlock--;)
733                 block->at(indexInBlock)->setRefCount(0);
734             for (unsigned phiIndex = block->phis.size(); phiIndex--;)
735                 block->phis[phiIndex]->setRefCount(0);
736         }
737     
738         // Now find the roots:
739         // - Nodes that are must-generate.
740         // - Nodes that are reachable from type checks.
741         // Set their ref counts to 1 and put them on the worklist.
742         for (BlockIndex blockIndex = 0; blockIndex < m_graph.numBlocks(); ++blockIndex) {
743             BasicBlock* block = m_graph.block(blockIndex);
744             if (!block)
745                 continue;
746             for (unsigned indexInBlock = block->size(); indexInBlock--;) {
747                 Node* node = block->at(indexInBlock);
748                 DFG_NODE_DO_TO_CHILDREN(m_graph, node, findTypeCheckRoot);
749                 if (!(node->flags() & NodeMustGenerate))
750                     continue;
751                 if (!node->postfixRef())
752                     m_worklist.append(node);
753             }
754         }
755         
756         while (!m_worklist.isEmpty()) {
757             while (!m_worklist.isEmpty()) {
758                 Node* node = m_worklist.last();
759                 m_worklist.removeLast();
760                 ASSERT(node->shouldGenerate()); // It should not be on the worklist unless it's ref'ed.
761                 DFG_NODE_DO_TO_CHILDREN(m_graph, node, countEdge);
762             }
763             
764             if (m_graph.m_form == SSA) {
765                 // Find Phi->Upsilon edges, which are represented as meta-data in the
766                 // Upsilon.
767                 for (BlockIndex blockIndex = m_graph.numBlocks(); blockIndex--;) {
768                     BasicBlock* block = m_graph.block(blockIndex);
769                     if (!block)
770                         continue;
771                     for (unsigned nodeIndex = block->size(); nodeIndex--;) {
772                         Node* node = block->at(nodeIndex);
773                         if (node->op() != Upsilon)
774                             continue;
775                         if (node->shouldGenerate())
776                             continue;
777                         if (node->phi()->shouldGenerate())
778                             countNode(node);
779                     }
780                 }
781             }
782         }
783     }
784     
785 private:
786     void findTypeCheckRoot(Node*, Edge edge)
787     {
788         // We may have an "unproved" untyped use for code that is unreachable. The CFA
789         // will just not have gotten around to it.
790         if (edge.isProved() || edge.willNotHaveCheck())
791             return;
792         if (!edge->postfixRef())
793             m_worklist.append(edge.node());
794     }
795     
796     void countNode(Node* node)
797     {
798         if (node->postfixRef())
799             return;
800         m_worklist.append(node);
801     }
802     
803     void countEdge(Node*, Edge edge)
804     {
805         // Don't count edges that are already counted for their type checks.
806         if (!(edge.isProved() || edge.willNotHaveCheck()))
807             return;
808         countNode(edge.node());
809     }
810     
811     Graph& m_graph;
812     Vector<Node*, 128> m_worklist;
813 };
814
815 } // anonymous namespace
816
817 void Graph::computeRefCounts()
818 {
819     RefCountCalculator calculator(*this);
820     calculator.calculate();
821 }
822
823 void Graph::killBlockAndItsContents(BasicBlock* block)
824 {
825     if (auto& ssaData = block->ssa)
826         ssaData->invalidate();
827     for (unsigned phiIndex = block->phis.size(); phiIndex--;)
828         deleteNode(block->phis[phiIndex]);
829     for (Node* node : *block)
830         deleteNode(node);
831     
832     killBlock(block);
833 }
834
835 void Graph::killUnreachableBlocks()
836 {
837     invalidateNodeLiveness();
838
839     for (BlockIndex blockIndex = 0; blockIndex < numBlocks(); ++blockIndex) {
840         BasicBlock* block = this->block(blockIndex);
841         if (!block)
842             continue;
843         if (block->isReachable)
844             continue;
845         
846         killBlockAndItsContents(block);
847     }
848 }
849
850 void Graph::invalidateCFG()
851 {
852     m_dominators = nullptr;
853     m_naturalLoops = nullptr;
854     m_prePostNumbering = nullptr;
855     m_controlEquivalenceAnalysis = nullptr;
856     m_backwardsDominators = nullptr;
857     m_backwardsCFG = nullptr;
858 }
859
860 void Graph::invalidateNodeLiveness()
861 {
862     if (m_form != SSA)
863         return;
864
865     for (BasicBlock* block : blocksInNaturalOrder())
866         block->ssa->invalidate();
867 }
868
869 void Graph::substituteGetLocal(BasicBlock& block, unsigned startIndexInBlock, VariableAccessData* variableAccessData, Node* newGetLocal)
870 {
871     for (unsigned indexInBlock = startIndexInBlock; indexInBlock < block.size(); ++indexInBlock) {
872         Node* node = block[indexInBlock];
873         bool shouldContinue = true;
874         switch (node->op()) {
875         case SetLocal: {
876             if (node->local() == variableAccessData->local())
877                 shouldContinue = false;
878             break;
879         }
880                 
881         case GetLocal: {
882             if (node->variableAccessData() != variableAccessData)
883                 continue;
884             substitute(block, indexInBlock, node, newGetLocal);
885             Node* oldTailNode = block.variablesAtTail.operand(variableAccessData->local());
886             if (oldTailNode == node)
887                 block.variablesAtTail.operand(variableAccessData->local()) = newGetLocal;
888             shouldContinue = false;
889             break;
890         }
891                 
892         default:
893             break;
894         }
895         if (!shouldContinue)
896             break;
897     }
898 }
899
900 BlockList Graph::blocksInPreOrder()
901 {
902     BlockList result;
903     BlockWorklist worklist;
904     worklist.push(block(0));
905     while (BasicBlock* block = worklist.pop()) {
906         result.append(block);
907         for (unsigned i = block->numSuccessors(); i--;)
908             worklist.push(block->successor(i));
909     }
910     return result;
911 }
912
913 BlockList Graph::blocksInPostOrder()
914 {
915     BlockList result;
916     PostOrderBlockWorklist worklist;
917     worklist.push(block(0));
918     while (BlockWithOrder item = worklist.pop()) {
919         switch (item.order) {
920         case VisitOrder::Pre:
921             worklist.pushPost(item.node);
922             for (unsigned i = item.node->numSuccessors(); i--;)
923                 worklist.push(item.node->successor(i));
924             break;
925         case VisitOrder::Post:
926             result.append(item.node);
927             break;
928         }
929     }
930     return result;
931 }
932
933 void Graph::clearReplacements()
934 {
935     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
936         BasicBlock* block = m_blocks[blockIndex].get();
937         if (!block)
938             continue;
939         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
940             block->phis[phiIndex]->setReplacement(nullptr);
941         for (unsigned nodeIndex = block->size(); nodeIndex--;)
942             block->at(nodeIndex)->setReplacement(nullptr);
943     }
944 }
945
946 void Graph::clearEpochs()
947 {
948     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
949         BasicBlock* block = m_blocks[blockIndex].get();
950         if (!block)
951             continue;
952         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
953             block->phis[phiIndex]->setEpoch(Epoch());
954         for (unsigned nodeIndex = block->size(); nodeIndex--;)
955             block->at(nodeIndex)->setEpoch(Epoch());
956     }
957 }
958
959 void Graph::initializeNodeOwners()
960 {
961     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
962         BasicBlock* block = m_blocks[blockIndex].get();
963         if (!block)
964             continue;
965         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
966             block->phis[phiIndex]->owner = block;
967         for (unsigned nodeIndex = block->size(); nodeIndex--;)
968             block->at(nodeIndex)->owner = block;
969     }
970 }
971
972 void Graph::clearFlagsOnAllNodes(NodeFlags flags)
973 {
974     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
975         BasicBlock* block = m_blocks[blockIndex].get();
976         if (!block)
977             continue;
978         for (unsigned phiIndex = block->phis.size(); phiIndex--;)
979             block->phis[phiIndex]->clearFlags(flags);
980         for (unsigned nodeIndex = block->size(); nodeIndex--;)
981             block->at(nodeIndex)->clearFlags(flags);
982     }
983 }
984
985 bool Graph::watchCondition(const ObjectPropertyCondition& key)
986 {
987     if (!key.isWatchable())
988         return false;
989     
990     m_plan.weakReferences.addLazily(key.object());
991     if (key.hasPrototype())
992         m_plan.weakReferences.addLazily(key.prototype());
993     if (key.hasRequiredValue())
994         m_plan.weakReferences.addLazily(key.requiredValue());
995     
996     m_plan.watchpoints.addLazily(key);
997
998     if (key.kind() == PropertyCondition::Presence)
999         m_safeToLoad.add(std::make_pair(key.object(), key.offset()));
1000     
1001     return true;
1002 }
1003
1004 bool Graph::watchConditions(const ObjectPropertyConditionSet& keys)
1005 {
1006     if (!keys.isValid())
1007         return false;
1008
1009     for (const ObjectPropertyCondition& key : keys) {
1010         if (!watchCondition(key))
1011             return false;
1012     }
1013     return true;
1014 }
1015
1016 bool Graph::isSafeToLoad(JSObject* base, PropertyOffset offset)
1017 {
1018     return m_safeToLoad.contains(std::make_pair(base, offset));
1019 }
1020
1021 InferredType::Descriptor Graph::inferredTypeFor(const PropertyTypeKey& key)
1022 {
1023     assertIsRegistered(key.structure());
1024     
1025     auto iter = m_inferredTypes.find(key);
1026     if (iter != m_inferredTypes.end())
1027         return iter->value;
1028
1029     InferredType* typeObject = key.structure()->inferredTypeFor(key.uid());
1030     if (!typeObject) {
1031         m_inferredTypes.add(key, InferredType::Top);
1032         return InferredType::Top;
1033     }
1034
1035     InferredType::Descriptor typeDescriptor = typeObject->descriptor();
1036     if (typeDescriptor.kind() == InferredType::Top) {
1037         m_inferredTypes.add(key, InferredType::Top);
1038         return InferredType::Top;
1039     }
1040     
1041     m_inferredTypes.add(key, typeDescriptor);
1042
1043     m_plan.weakReferences.addLazily(typeObject);
1044     registerInferredType(typeDescriptor);
1045
1046     // Note that we may already be watching this desired inferred type, because multiple structures may
1047     // point to the same InferredType instance.
1048     m_plan.watchpoints.addLazily(DesiredInferredType(typeObject, typeDescriptor));
1049
1050     return typeDescriptor;
1051 }
1052
1053 FullBytecodeLiveness& Graph::livenessFor(CodeBlock* codeBlock)
1054 {
1055     HashMap<CodeBlock*, std::unique_ptr<FullBytecodeLiveness>>::iterator iter = m_bytecodeLiveness.find(codeBlock);
1056     if (iter != m_bytecodeLiveness.end())
1057         return *iter->value;
1058     
1059     std::unique_ptr<FullBytecodeLiveness> liveness = std::make_unique<FullBytecodeLiveness>();
1060     codeBlock->livenessAnalysis().computeFullLiveness(*liveness);
1061     FullBytecodeLiveness& result = *liveness;
1062     m_bytecodeLiveness.add(codeBlock, WTFMove(liveness));
1063     return result;
1064 }
1065
1066 FullBytecodeLiveness& Graph::livenessFor(InlineCallFrame* inlineCallFrame)
1067 {
1068     return livenessFor(baselineCodeBlockFor(inlineCallFrame));
1069 }
1070
1071 BytecodeKills& Graph::killsFor(CodeBlock* codeBlock)
1072 {
1073     HashMap<CodeBlock*, std::unique_ptr<BytecodeKills>>::iterator iter = m_bytecodeKills.find(codeBlock);
1074     if (iter != m_bytecodeKills.end())
1075         return *iter->value;
1076     
1077     std::unique_ptr<BytecodeKills> kills = std::make_unique<BytecodeKills>();
1078     codeBlock->livenessAnalysis().computeKills(*kills);
1079     BytecodeKills& result = *kills;
1080     m_bytecodeKills.add(codeBlock, WTFMove(kills));
1081     return result;
1082 }
1083
1084 BytecodeKills& Graph::killsFor(InlineCallFrame* inlineCallFrame)
1085 {
1086     return killsFor(baselineCodeBlockFor(inlineCallFrame));
1087 }
1088
1089 bool Graph::isLiveInBytecode(VirtualRegister operand, CodeOrigin codeOrigin)
1090 {
1091     static const bool verbose = false;
1092     
1093     if (verbose)
1094         dataLog("Checking of operand is live: ", operand, "\n");
1095     CodeOrigin* codeOriginPtr = &codeOrigin;
1096     for (;;) {
1097         VirtualRegister reg = VirtualRegister(
1098             operand.offset() - codeOriginPtr->stackOffset());
1099         
1100         if (verbose)
1101             dataLog("reg = ", reg, "\n");
1102         
1103         if (operand.offset() < codeOriginPtr->stackOffset() + CallFrame::headerSizeInRegisters) {
1104             if (reg.isArgument()) {
1105                 RELEASE_ASSERT(reg.offset() < CallFrame::headerSizeInRegisters);
1106                 
1107                 if (codeOriginPtr->inlineCallFrame->isClosureCall
1108                     && reg.offset() == CallFrameSlot::callee) {
1109                     if (verbose)
1110                         dataLog("Looks like a callee.\n");
1111                     return true;
1112                 }
1113                 
1114                 if (codeOriginPtr->inlineCallFrame->isVarargs()
1115                     && reg.offset() == CallFrameSlot::argumentCount) {
1116                     if (verbose)
1117                         dataLog("Looks like the argument count.\n");
1118                     return true;
1119                 }
1120                 
1121                 return false;
1122             }
1123
1124             if (verbose)
1125                 dataLog("Asking the bytecode liveness.\n");
1126             return livenessFor(codeOriginPtr->inlineCallFrame).operandIsLive(
1127                 reg.offset(), codeOriginPtr->bytecodeIndex);
1128         }
1129         
1130         InlineCallFrame* inlineCallFrame = codeOriginPtr->inlineCallFrame;
1131         if (!inlineCallFrame) {
1132             if (verbose)
1133                 dataLog("Ran out of stack, returning true.\n");
1134             return true;
1135         }
1136
1137         // Arguments are always live. This would be redundant if it wasn't for our
1138         // op_call_varargs inlining.
1139         if (reg.isArgument()
1140             && static_cast<size_t>(reg.toArgument()) < inlineCallFrame->arguments.size()) {
1141             if (verbose)
1142                 dataLog("Argument is live.\n");
1143             return true;
1144         }
1145         
1146         codeOriginPtr = inlineCallFrame->getCallerSkippingTailCalls();
1147
1148         // The first inline call frame could be an inline tail call
1149         if (!codeOriginPtr) {
1150             if (verbose)
1151                 dataLog("Dead because of tail inlining.\n");
1152             return false;
1153         }
1154     }
1155     
1156     RELEASE_ASSERT_NOT_REACHED();
1157 }
1158
1159 BitVector Graph::localsLiveInBytecode(CodeOrigin codeOrigin)
1160 {
1161     BitVector result;
1162     result.ensureSize(block(0)->variablesAtHead.numberOfLocals());
1163     forAllLocalsLiveInBytecode(
1164         codeOrigin,
1165         [&] (VirtualRegister reg) {
1166             ASSERT(reg.isLocal());
1167             result.quickSet(reg.toLocal());
1168         });
1169     return result;
1170 }
1171
1172 unsigned Graph::parameterSlotsForArgCount(unsigned argCount)
1173 {
1174     size_t frameSize = CallFrame::headerSizeInRegisters + argCount;
1175     size_t alignedFrameSize = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), frameSize);
1176     return alignedFrameSize - CallerFrameAndPC::sizeInRegisters;
1177 }
1178
1179 unsigned Graph::frameRegisterCount()
1180 {
1181     unsigned result = m_nextMachineLocal + std::max(m_parameterSlots, static_cast<unsigned>(maxFrameExtentForSlowPathCallInRegisters));
1182     return roundLocalRegisterCountForFramePointerOffset(result);
1183 }
1184
1185 unsigned Graph::stackPointerOffset()
1186 {
1187     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
1188 }
1189
1190 unsigned Graph::requiredRegisterCountForExit()
1191 {
1192     unsigned count = JIT::frameRegisterCountFor(m_profiledBlock);
1193     for (InlineCallFrameSet::iterator iter = m_plan.inlineCallFrames->begin(); !!iter; ++iter) {
1194         InlineCallFrame* inlineCallFrame = *iter;
1195         CodeBlock* codeBlock = baselineCodeBlockForInlineCallFrame(inlineCallFrame);
1196         unsigned requiredCount = VirtualRegister(inlineCallFrame->stackOffset).toLocal() + 1 + JIT::frameRegisterCountFor(codeBlock);
1197         count = std::max(count, requiredCount);
1198     }
1199     return count;
1200 }
1201
1202 unsigned Graph::requiredRegisterCountForExecutionAndExit()
1203 {
1204     return std::max(frameRegisterCount(), requiredRegisterCountForExit());
1205 }
1206
1207 JSValue Graph::tryGetConstantProperty(
1208     JSValue base, const StructureSet& structureSet, PropertyOffset offset)
1209 {
1210     if (!base || !base.isObject())
1211         return JSValue();
1212     
1213     JSObject* object = asObject(base);
1214     
1215     for (unsigned i = structureSet.size(); i--;) {
1216         Structure* structure = structureSet[i];
1217         assertIsRegistered(structure);
1218         
1219         WatchpointSet* set = structure->propertyReplacementWatchpointSet(offset);
1220         if (!set || !set->isStillValid())
1221             return JSValue();
1222         
1223         ASSERT(structure->isValidOffset(offset));
1224         ASSERT(!structure->isUncacheableDictionary());
1225         
1226         watchpoints().addLazily(set);
1227     }
1228     
1229     // What follows may require some extra thought. We need this load to load a valid JSValue. If
1230     // our profiling makes sense and we're still on track to generate code that won't be
1231     // invalidated, then we have nothing to worry about. We do, however, have to worry about
1232     // loading - and then using - an invalid JSValue in the case that unbeknownst to us our code
1233     // is doomed.
1234     //
1235     // One argument in favor of this code is that it should definitely work because the butterfly
1236     // is always set before the structure. However, we don't currently have a fence between those
1237     // stores. It's not clear if this matters, however. We don't ever shrink the property storage.
1238     // So, for this to fail, you'd need an access on a constant object pointer such that the inline
1239     // caches told us that the object had a structure that it did not *yet* have, and then later,
1240     // the object transitioned to that structure that the inline caches had alraedy seen. And then
1241     // the processor reordered the stores. Seems unlikely and difficult to test. I believe that
1242     // this is worth revisiting but it isn't worth losing sleep over. Filed:
1243     // https://bugs.webkit.org/show_bug.cgi?id=134641
1244     //
1245     // For now, we just do the minimal thing: defend against the structure right now being
1246     // incompatible with the getDirect we're trying to do. The easiest way to do that is to
1247     // determine if the structure belongs to the proven set.
1248     
1249     if (!structureSet.contains(object->structure()))
1250         return JSValue();
1251     
1252     return object->getDirect(offset);
1253 }
1254
1255 JSValue Graph::tryGetConstantProperty(JSValue base, Structure* structure, PropertyOffset offset)
1256 {
1257     return tryGetConstantProperty(base, StructureSet(structure), offset);
1258 }
1259
1260 JSValue Graph::tryGetConstantProperty(
1261     JSValue base, const StructureAbstractValue& structure, PropertyOffset offset)
1262 {
1263     if (structure.isInfinite()) {
1264         // FIXME: If we just converted the offset to a uid, we could do ObjectPropertyCondition
1265         // watching to constant-fold the property.
1266         // https://bugs.webkit.org/show_bug.cgi?id=147271
1267         return JSValue();
1268     }
1269     
1270     return tryGetConstantProperty(base, structure.set(), offset);
1271 }
1272
1273 JSValue Graph::tryGetConstantProperty(const AbstractValue& base, PropertyOffset offset)
1274 {
1275     return tryGetConstantProperty(base.m_value, base.m_structure, offset);
1276 }
1277
1278 AbstractValue Graph::inferredValueForProperty(
1279     const StructureSet& base, UniquedStringImpl* uid, StructureClobberState clobberState)
1280 {
1281     AbstractValue result;
1282     base.forEach(
1283         [&] (Structure* structure) {
1284             AbstractValue value;
1285             value.set(*this, inferredTypeForProperty(structure, uid));
1286             result.merge(value);
1287         });
1288     if (clobberState == StructuresAreClobbered)
1289         result.clobberStructures();
1290     return result;
1291 }
1292
1293 AbstractValue Graph::inferredValueForProperty(
1294     const AbstractValue& base, UniquedStringImpl* uid, PropertyOffset offset,
1295     StructureClobberState clobberState)
1296 {
1297     if (JSValue value = tryGetConstantProperty(base, offset)) {
1298         AbstractValue result;
1299         result.set(*this, *freeze(value), clobberState);
1300         return result;
1301     }
1302
1303     if (base.m_structure.isFinite())
1304         return inferredValueForProperty(base.m_structure.set(), uid, clobberState);
1305
1306     return AbstractValue::heapTop();
1307 }
1308
1309 JSValue Graph::tryGetConstantClosureVar(JSValue base, ScopeOffset offset)
1310 {
1311     // This has an awesome concurrency story. See comment for GetGlobalVar in ByteCodeParser.
1312     
1313     if (!base)
1314         return JSValue();
1315     
1316     JSLexicalEnvironment* activation = jsDynamicCast<JSLexicalEnvironment*>(base);
1317     if (!activation)
1318         return JSValue();
1319     
1320     SymbolTable* symbolTable = activation->symbolTable();
1321     JSValue value;
1322     WatchpointSet* set;
1323     {
1324         ConcurrentJITLocker locker(symbolTable->m_lock);
1325         
1326         SymbolTableEntry* entry = symbolTable->entryFor(locker, offset);
1327         if (!entry)
1328             return JSValue();
1329         
1330         set = entry->watchpointSet();
1331         if (!set)
1332             return JSValue();
1333         
1334         if (set->state() != IsWatched)
1335             return JSValue();
1336         
1337         ASSERT(entry->scopeOffset() == offset);
1338         value = activation->variableAt(offset).get();
1339         if (!value)
1340             return JSValue();
1341     }
1342     
1343     watchpoints().addLazily(set);
1344     
1345     return value;
1346 }
1347
1348 JSValue Graph::tryGetConstantClosureVar(const AbstractValue& value, ScopeOffset offset)
1349 {
1350     return tryGetConstantClosureVar(value.m_value, offset);
1351 }
1352
1353 JSValue Graph::tryGetConstantClosureVar(Node* node, ScopeOffset offset)
1354 {
1355     if (!node->hasConstant())
1356         return JSValue();
1357     return tryGetConstantClosureVar(node->asJSValue(), offset);
1358 }
1359
1360 JSArrayBufferView* Graph::tryGetFoldableView(JSValue value)
1361 {
1362     if (!value)
1363         return nullptr;
1364     JSArrayBufferView* view = jsDynamicCast<JSArrayBufferView*>(value);
1365     if (!value)
1366         return nullptr;
1367     if (!view->length())
1368         return nullptr;
1369     WTF::loadLoadFence();
1370     watchpoints().addLazily(view);
1371     return view;
1372 }
1373
1374 JSArrayBufferView* Graph::tryGetFoldableView(JSValue value, ArrayMode arrayMode)
1375 {
1376     if (arrayMode.type() != Array::AnyTypedArray && arrayMode.typedArrayType() == NotTypedArray)
1377         return nullptr;
1378     return tryGetFoldableView(value);
1379 }
1380
1381 void Graph::registerFrozenValues()
1382 {
1383     m_codeBlock->constants().resize(0);
1384     m_codeBlock->constantsSourceCodeRepresentation().resize(0);
1385     for (FrozenValue* value : m_frozenValues) {
1386         if (!value->pointsToHeap())
1387             continue;
1388         
1389         ASSERT(value->structure());
1390         ASSERT(m_plan.weakReferences.contains(value->structure()));
1391         
1392         switch (value->strength()) {
1393         case WeakValue: {
1394             m_plan.weakReferences.addLazily(value->value().asCell());
1395             break;
1396         }
1397         case StrongValue: {
1398             unsigned constantIndex = m_codeBlock->addConstantLazily();
1399             // We already have a barrier on the code block.
1400             m_codeBlock->constants()[constantIndex].setWithoutWriteBarrier(value->value());
1401             break;
1402         } }
1403     }
1404     m_codeBlock->constants().shrinkToFit();
1405     m_codeBlock->constantsSourceCodeRepresentation().shrinkToFit();
1406 }
1407
1408 void Graph::visitChildren(SlotVisitor& visitor)
1409 {
1410     for (FrozenValue* value : m_frozenValues) {
1411         visitor.appendUnbarrieredReadOnlyValue(value->value());
1412         visitor.appendUnbarrieredReadOnlyPointer(value->structure());
1413     }
1414     
1415     for (BlockIndex blockIndex = numBlocks(); blockIndex--;) {
1416         BasicBlock* block = this->block(blockIndex);
1417         if (!block)
1418             continue;
1419         
1420         for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1421             Node* node = block->at(nodeIndex);
1422             
1423             switch (node->op()) {
1424             case CheckStructure:
1425                 for (unsigned i = node->structureSet().size(); i--;)
1426                     visitor.appendUnbarrieredReadOnlyPointer(node->structureSet()[i]);
1427                 break;
1428                 
1429             case NewObject:
1430             case ArrayifyToStructure:
1431             case NewStringObject:
1432                 visitor.appendUnbarrieredReadOnlyPointer(node->structure());
1433                 break;
1434                 
1435             case PutStructure:
1436             case AllocatePropertyStorage:
1437             case ReallocatePropertyStorage:
1438                 visitor.appendUnbarrieredReadOnlyPointer(
1439                     node->transition()->previous);
1440                 visitor.appendUnbarrieredReadOnlyPointer(
1441                     node->transition()->next);
1442                 break;
1443                 
1444             case MultiGetByOffset:
1445                 for (const MultiGetByOffsetCase& getCase : node->multiGetByOffsetData().cases) {
1446                     for (Structure* structure : getCase.set())
1447                         visitor.appendUnbarrieredReadOnlyPointer(structure);
1448                 }
1449                 break;
1450                     
1451             case MultiPutByOffset:
1452                 for (unsigned i = node->multiPutByOffsetData().variants.size(); i--;) {
1453                     PutByIdVariant& variant = node->multiPutByOffsetData().variants[i];
1454                     const StructureSet& set = variant.oldStructure();
1455                     for (unsigned j = set.size(); j--;)
1456                         visitor.appendUnbarrieredReadOnlyPointer(set[j]);
1457                     if (variant.kind() == PutByIdVariant::Transition)
1458                         visitor.appendUnbarrieredReadOnlyPointer(variant.newStructure());
1459                 }
1460                 break;
1461                 
1462             default:
1463                 break;
1464             }
1465         }
1466     }
1467 }
1468
1469 FrozenValue* Graph::freeze(JSValue value)
1470 {
1471     if (UNLIKELY(!value))
1472         return FrozenValue::emptySingleton();
1473     
1474     auto result = m_frozenValueMap.add(JSValue::encode(value), nullptr);
1475     if (LIKELY(!result.isNewEntry))
1476         return result.iterator->value;
1477
1478     if (value.isUInt32())
1479         m_uint32ValuesInUse.append(value.asUInt32());
1480     
1481     FrozenValue frozenValue = FrozenValue::freeze(value);
1482     if (Structure* structure = frozenValue.structure())
1483         registerStructure(structure);
1484     
1485     return result.iterator->value = m_frozenValues.add(frozenValue);
1486 }
1487
1488 FrozenValue* Graph::freezeStrong(JSValue value)
1489 {
1490     FrozenValue* result = freeze(value);
1491     result->strengthenTo(StrongValue);
1492     return result;
1493 }
1494
1495 void Graph::convertToConstant(Node* node, FrozenValue* value)
1496 {
1497     if (value->structure())
1498         assertIsRegistered(value->structure());
1499     node->convertToConstant(value);
1500 }
1501
1502 void Graph::convertToConstant(Node* node, JSValue value)
1503 {
1504     convertToConstant(node, freeze(value));
1505 }
1506
1507 void Graph::convertToStrongConstant(Node* node, JSValue value)
1508 {
1509     convertToConstant(node, freezeStrong(value));
1510 }
1511
1512 StructureRegistrationResult Graph::registerStructure(Structure* structure)
1513 {
1514     m_plan.weakReferences.addLazily(structure);
1515     if (m_plan.watchpoints.consider(structure))
1516         return StructureRegisteredAndWatched;
1517     return StructureRegisteredNormally;
1518 }
1519
1520 void Graph::assertIsRegistered(Structure* structure)
1521 {
1522     // It's convenient to be able to call this with a maybe-null structure.
1523     if (!structure)
1524         return;
1525     
1526     DFG_ASSERT(*this, nullptr, m_plan.weakReferences.contains(structure));
1527     
1528     if (!structure->dfgShouldWatch())
1529         return;
1530     if (watchpoints().isWatched(structure->transitionWatchpointSet()))
1531         return;
1532     
1533     DFG_CRASH(*this, nullptr, toCString("Structure ", pointerDump(structure), " is watchable but isn't being watched.").data());
1534 }
1535
1536 NO_RETURN_DUE_TO_CRASH static void crash(
1537     Graph& graph, const CString& whileText, const char* file, int line, const char* function,
1538     const char* assertion)
1539 {
1540     startCrashing();
1541     dataLog("DFG ASSERTION FAILED: ", assertion, "\n");
1542     dataLog(file, "(", line, ") : ", function, "\n");
1543     dataLog("\n");
1544     dataLog(whileText);
1545     dataLog("Graph at time of failure:\n");
1546     graph.dump();
1547     dataLog("\n");
1548     dataLog("DFG ASSERTION FAILED: ", assertion, "\n");
1549     dataLog(file, "(", line, ") : ", function, "\n");
1550     CRASH_WITH_SECURITY_IMPLICATION();
1551 }
1552
1553 void Graph::handleAssertionFailure(
1554     std::nullptr_t, const char* file, int line, const char* function, const char* assertion)
1555 {
1556     crash(*this, "", file, line, function, assertion);
1557 }
1558
1559 void Graph::handleAssertionFailure(
1560     Node* node, const char* file, int line, const char* function, const char* assertion)
1561 {
1562     crash(*this, toCString("While handling node ", node, "\n\n"), file, line, function, assertion);
1563 }
1564
1565 void Graph::handleAssertionFailure(
1566     BasicBlock* block, const char* file, int line, const char* function, const char* assertion)
1567 {
1568     crash(*this, toCString("While handling block ", pointerDump(block), "\n\n"), file, line, function, assertion);
1569 }
1570
1571 Dominators& Graph::ensureDominators()
1572 {
1573     if (!m_dominators)
1574         m_dominators = std::make_unique<Dominators>(*this);
1575     return *m_dominators;
1576 }
1577
1578 PrePostNumbering& Graph::ensurePrePostNumbering()
1579 {
1580     if (!m_prePostNumbering)
1581         m_prePostNumbering = std::make_unique<PrePostNumbering>(*this);
1582     return *m_prePostNumbering;
1583 }
1584
1585 NaturalLoops& Graph::ensureNaturalLoops()
1586 {
1587     ensureDominators();
1588     if (!m_naturalLoops)
1589         m_naturalLoops = std::make_unique<NaturalLoops>(*this);
1590     return *m_naturalLoops;
1591 }
1592
1593 BackwardsCFG& Graph::ensureBackwardsCFG()
1594 {
1595     if (!m_backwardsCFG)
1596         m_backwardsCFG = std::make_unique<BackwardsCFG>(*this);
1597     return *m_backwardsCFG;
1598 }
1599
1600 BackwardsDominators& Graph::ensureBackwardsDominators()
1601 {
1602     if (!m_backwardsDominators)
1603         m_backwardsDominators = std::make_unique<BackwardsDominators>(*this);
1604     return *m_backwardsDominators;
1605 }
1606
1607 ControlEquivalenceAnalysis& Graph::ensureControlEquivalenceAnalysis()
1608 {
1609     if (!m_controlEquivalenceAnalysis)
1610         m_controlEquivalenceAnalysis = std::make_unique<ControlEquivalenceAnalysis>(*this);
1611     return *m_controlEquivalenceAnalysis;
1612 }
1613
1614 MethodOfGettingAValueProfile Graph::methodOfGettingAValueProfileFor(Node* node)
1615 {
1616     while (node) {
1617         CodeBlock* profiledBlock = baselineCodeBlockFor(node->origin.semantic);
1618         
1619         if (node->accessesStack(*this)) {
1620             ValueProfile* result = [&] () -> ValueProfile* {
1621                 if (!node->local().isArgument())
1622                     return nullptr;
1623                 int argument = node->local().toArgument();
1624                 Node* argumentNode = m_arguments[argument];
1625                 if (!argumentNode)
1626                     return nullptr;
1627                 if (node->variableAccessData() != argumentNode->variableAccessData())
1628                     return nullptr;
1629                 return profiledBlock->valueProfileForArgument(argument);
1630             }();
1631             if (result)
1632                 return result;
1633             
1634             if (node->op() == GetLocal) {
1635                 return MethodOfGettingAValueProfile::fromLazyOperand(
1636                     profiledBlock,
1637                     LazyOperandValueProfileKey(
1638                         node->origin.semantic.bytecodeIndex, node->local()));
1639             }
1640         }
1641         
1642         if (node->hasHeapPrediction())
1643             return profiledBlock->valueProfileForBytecodeOffset(node->origin.semantic.bytecodeIndex);
1644         
1645         {
1646             if (profiledBlock->hasBaselineJITProfiling()) {
1647                 if (ArithProfile* result = profiledBlock->arithProfileForBytecodeOffset(node->origin.semantic.bytecodeIndex))
1648                     return result;
1649             }
1650         }
1651         
1652         switch (node->op()) {
1653         case Identity:
1654         case ValueRep:
1655         case DoubleRep:
1656         case Int52Rep:
1657             node = node->child1().node();
1658             break;
1659         default:
1660             node = nullptr;
1661         }
1662     }
1663     
1664     return MethodOfGettingAValueProfile();
1665 }
1666
1667 bool Graph::getRegExpPrototypeProperty(JSObject* regExpPrototype, Structure* regExpPrototypeStructure, UniquedStringImpl* uid, JSValue& returnJSValue)
1668 {
1669     unsigned attributesUnused;
1670     PropertyOffset offset = regExpPrototypeStructure->getConcurrently(uid, attributesUnused);
1671     if (!isValidOffset(offset))
1672         return false;
1673
1674     JSValue value = tryGetConstantProperty(regExpPrototype, regExpPrototypeStructure, offset);
1675     if (!value)
1676         return false;
1677
1678     // We only care about functions and getters at this point. If you want to access other properties
1679     // you'll have to add code for those types.
1680     JSFunction* function = jsDynamicCast<JSFunction*>(value);
1681     if (!function) {
1682         GetterSetter* getterSetter = jsDynamicCast<GetterSetter*>(value);
1683
1684         if (!getterSetter)
1685             return false;
1686
1687         returnJSValue = JSValue(getterSetter);
1688         return true;
1689     }
1690
1691     returnJSValue = value;
1692     return true;
1693 }
1694
1695 bool Graph::isStringPrototypeMethodSane(JSGlobalObject* globalObject, UniquedStringImpl* uid)
1696 {
1697     ObjectPropertyConditionSet conditions = generateConditionsForPrototypeEquivalenceConcurrently(m_vm, globalObject, globalObject->stringObjectStructure(), globalObject->stringPrototype(), uid);
1698
1699     if (!conditions.isValid())
1700         return false;
1701
1702     ObjectPropertyCondition equivalenceCondition = conditions.slotBaseCondition();
1703     RELEASE_ASSERT(equivalenceCondition.hasRequiredValue());
1704     JSFunction* function = jsDynamicCast<JSFunction*>(equivalenceCondition.condition().requiredValue());
1705     if (!function)
1706         return false;
1707
1708     if (function->executable()->intrinsicFor(CodeForCall) != StringPrototypeValueOfIntrinsic)
1709         return false;
1710     
1711     return watchConditions(conditions);
1712 }
1713
1714
1715 bool Graph::canOptimizeStringObjectAccess(const CodeOrigin& codeOrigin)
1716 {
1717     if (hasExitSite(codeOrigin, NotStringObject))
1718         return false;
1719
1720     JSGlobalObject* globalObject = globalObjectFor(codeOrigin);
1721     Structure* stringObjectStructure = globalObjectFor(codeOrigin)->stringObjectStructure();
1722     registerStructure(stringObjectStructure);
1723     ASSERT(stringObjectStructure->storedPrototype().isObject());
1724     ASSERT(stringObjectStructure->storedPrototype().asCell()->classInfo() == StringPrototype::info());
1725
1726     if (!watchConditions(generateConditionsForPropertyMissConcurrently(m_vm, globalObject, stringObjectStructure, m_vm.propertyNames->toPrimitiveSymbol.impl())))
1727         return false;
1728
1729     // We're being conservative here. We want DFG's ToString on StringObject to be
1730     // used in both numeric contexts (that would call valueOf()) and string contexts
1731     // (that would call toString()). We don't want the DFG to have to distinguish
1732     // between the two, just because that seems like it would get confusing. So we
1733     // just require both methods to be sane.
1734     if (!isStringPrototypeMethodSane(globalObject, m_vm.propertyNames->valueOf.impl()))
1735         return false;
1736     return isStringPrototypeMethodSane(globalObject, m_vm.propertyNames->toString.impl());
1737 }
1738
1739 bool Graph::willCatchExceptionInMachineFrame(CodeOrigin codeOrigin, CodeOrigin& opCatchOriginOut, HandlerInfo*& catchHandlerOut)
1740 {
1741     if (!m_hasExceptionHandlers)
1742         return false;
1743
1744     unsigned bytecodeIndexToCheck = codeOrigin.bytecodeIndex;
1745     while (1) {
1746         InlineCallFrame* inlineCallFrame = codeOrigin.inlineCallFrame;
1747         CodeBlock* codeBlock = baselineCodeBlockFor(inlineCallFrame);
1748         if (HandlerInfo* handler = codeBlock->handlerForBytecodeOffset(bytecodeIndexToCheck)) {
1749             opCatchOriginOut = CodeOrigin(handler->target, inlineCallFrame);
1750             catchHandlerOut = handler;
1751             return true;
1752         }
1753
1754         if (!inlineCallFrame)
1755             return false;
1756
1757         bytecodeIndexToCheck = inlineCallFrame->directCaller.bytecodeIndex;
1758         codeOrigin = codeOrigin.inlineCallFrame->directCaller;
1759     }
1760
1761     RELEASE_ASSERT_NOT_REACHED();
1762 }
1763
1764 } } // namespace JSC::DFG
1765
1766 #endif // ENABLE(DFG_JIT)