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