12ab163733fa1841cb8bc4292195ad435a52296c
[WebKit-https.git] / Source / JavaScriptCore / dfg / DFGObjectAllocationSinkingPhase.cpp
1 /*
2  * Copyright (C) 2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "DFGObjectAllocationSinkingPhase.h"
28
29 #if ENABLE(DFG_JIT)
30
31 #include "DFGBlockMapInlines.h"
32 #include "DFGClobbersExitState.h"
33 #include "DFGCombinedLiveness.h"
34 #include "DFGGraph.h"
35 #include "DFGInsertionSet.h"
36 #include "DFGLazyNode.h"
37 #include "DFGLivenessAnalysisPhase.h"
38 #include "DFGOSRAvailabilityAnalysisPhase.h"
39 #include "DFGPhase.h"
40 #include "DFGPromotedHeapLocation.h"
41 #include "DFGSSACalculator.h"
42 #include "DFGValidate.h"
43 #include "JSCInlines.h"
44
45 #include <list>
46
47 namespace JSC { namespace DFG {
48
49 namespace {
50
51 bool verbose = false;
52
53 // In order to sink object cycles, we use a points-to analysis coupled
54 // with an escape analysis. This analysis is actually similar to an
55 // abstract interpreter focused on local allocations and ignoring
56 // everything else.
57 //
58 // We represent the local heap using two mappings:
59 //
60 // - A set of the local allocations present in the function, where
61 //   each of those have a further mapping from
62 //   PromotedLocationDescriptor to local allocations they must point
63 //   to.
64 //
65 // - A "pointer" mapping from nodes to local allocations, if they must
66 //   be equal to said local allocation and are currently live. This
67 //   can be because the node is the actual node that created the
68 //   allocation, or any other node that must currently point to it -
69 //   we don't make a difference.
70 //
71 // The following graph is a motivation for why we separate allocations
72 // from pointers:
73 //
74 // Block #0
75 //  0: NewObject({})
76 //  1: NewObject({})
77 //  -: PutByOffset(@0, @1, x)
78 //  -: PutStructure(@0, {x:0})
79 //  2: GetByOffset(@0, x)
80 //  -: Jump(#1)
81 //
82 // Block #1
83 //  -: Return(@2)
84 //
85 // Here, we need to remember in block #1 that @2 points to a local
86 // allocation with appropriate fields and structures information
87 // (because we should be able to place a materialization on top of
88 // block #1 here), even though @1 is dead. We *could* just keep @1
89 // artificially alive here, but there is no real reason to do it:
90 // after all, by the end of block #0, @1 and @2 should be completely
91 // interchangeable, and there is no reason for us to artificially make
92 // @1 more important.
93 //
94 // An important point to consider to understand this separation is
95 // that we should think of the local heap as follow: we have a
96 // bunch of nodes that are pointers to "allocations" that live
97 // someplace on the heap, and those allocations can have pointers in
98 // between themselves as well. We shouldn't care about whatever
99 // names we give to the allocations ; what matters when
100 // comparing/merging two heaps is the isomorphism/comparison between
101 // the allocation graphs as seen by the nodes.
102 //
103 // For instance, in the following graph:
104 //
105 // Block #0
106 //  0: NewObject({})
107 //  -: Branch(#1, #2)
108 //
109 // Block #1
110 //  1: NewObject({})
111 //  -: PutByOffset(@0, @1, x)
112 //  -: PutStructure(@0, {x:0})
113 //  -: Jump(#3)
114 //
115 // Block #2
116 //  2: NewObject({})
117 //  -: PutByOffset(@2, undefined, x)
118 //  -: PutStructure(@2, {x:0})
119 //  -: PutByOffset(@0, @2, x)
120 //  -: PutStructure(@0, {x:0})
121 //  -: Jump(#3)
122 //
123 // Block #3
124 //  -: Return(@0)
125 //
126 // we should think of the heaps at tail of blocks #1 and #2 as being
127 // exactly the same, even though one has @0.x pointing to @1 and the
128 // other has @0.x pointing to @2, because in essence this should not
129 // be different from the graph where we hoisted @1 and @2 into a
130 // single allocation in block #0. We currently will not handle this
131 // case, because we merge allocations based on the node they are
132 // coming from, but this is only a technicality for the sake of
133 // simplicity that shouldn't hide the deeper idea outlined here.
134
135 class Allocation {
136 public:
137     // We use Escaped as a special allocation kind because when we
138     // decide to sink an allocation, we still need to keep track of it
139     // once it is escaped if it still has pointers to it in order to
140     // replace any use of those pointers by the corresponding
141     // materialization
142     enum class Kind { Escaped, Object, Activation, Function, NewArrowFunction };
143
144     explicit Allocation(Node* identifier = nullptr, Kind kind = Kind::Escaped)
145         : m_identifier(identifier)
146         , m_kind(kind)
147     {
148     }
149
150
151     const HashMap<PromotedLocationDescriptor, Node*>& fields() const
152     {
153         return m_fields;
154     }
155
156     Node* get(PromotedLocationDescriptor descriptor)
157     {
158         return m_fields.get(descriptor);
159     }
160
161     Allocation& set(PromotedLocationDescriptor descriptor, Node* value)
162     {
163         // Pointing to anything else than an unescaped local
164         // allocation is represented by simply not having the
165         // field
166         if (value)
167             m_fields.set(descriptor, value);
168         else
169             m_fields.remove(descriptor);
170         return *this;
171     }
172
173     void remove(PromotedLocationDescriptor descriptor)
174     {
175         set(descriptor, nullptr);
176     }
177
178     bool hasStructures() const
179     {
180         switch (kind()) {
181         case Kind::Object:
182             return true;
183
184         default:
185             return false;
186         }
187     }
188
189     Allocation& setStructures(const StructureSet& structures)
190     {
191         ASSERT(hasStructures() && !structures.isEmpty());
192         m_structures = structures;
193         return *this;
194     }
195
196     Allocation& mergeStructures(const StructureSet& structures)
197     {
198         ASSERT(hasStructures() || structures.isEmpty());
199         m_structures.merge(structures);
200         return *this;
201     }
202
203     Allocation& filterStructures(const StructureSet& structures)
204     {
205         ASSERT(hasStructures());
206         m_structures.filter(structures);
207         return *this;
208     }
209
210     const StructureSet& structures() const
211     {
212         return m_structures;
213     }
214
215     Node* identifier() const { return m_identifier; }
216
217     Kind kind() const { return m_kind; }
218
219     bool isEscapedAllocation() const
220     {
221         return kind() == Kind::Escaped;
222     }
223
224     bool isObjectAllocation() const
225     {
226         return m_kind == Kind::Object;
227     }
228
229     bool isActivationAllocation() const
230     {
231         return m_kind == Kind::Activation;
232     }
233
234     bool isFunctionAllocation() const
235     {
236         return m_kind == Kind::Function || m_kind == Kind::NewArrowFunction;
237     }
238     
239     bool isArrowFunctionAllocation() const
240     {
241         return m_kind == Kind::NewArrowFunction;
242     }
243
244     bool operator==(const Allocation& other) const
245     {
246         return m_identifier == other.m_identifier
247             && m_kind == other.m_kind
248             && m_fields == other.m_fields
249             && m_structures == other.m_structures;
250     }
251
252     bool operator!=(const Allocation& other) const
253     {
254         return !(*this == other);
255     }
256
257     void dump(PrintStream& out) const
258     {
259         dumpInContext(out, nullptr);
260     }
261
262     void dumpInContext(PrintStream& out, DumpContext* context) const
263     {
264         switch (m_kind) {
265         case Kind::Escaped:
266             out.print("Escaped");
267             break;
268
269         case Kind::Object:
270             out.print("Object");
271             break;
272
273         case Kind::Function:
274             out.print("Function");
275             break;
276                 
277         case Kind::NewArrowFunction:
278             out.print("NewArrowFunction");
279             break;
280
281         case Kind::Activation:
282             out.print("Activation");
283             break;
284         }
285         out.print("Allocation(");
286         if (!m_structures.isEmpty())
287             out.print(inContext(m_structures, context));
288         if (!m_fields.isEmpty()) {
289             if (!m_structures.isEmpty())
290                 out.print(", ");
291             out.print(mapDump(m_fields, " => #", ", "));
292         }
293         out.print(")");
294     }
295
296 private:
297     Node* m_identifier; // This is the actual node that created the allocation
298     Kind m_kind;
299     HashMap<PromotedLocationDescriptor, Node*> m_fields;
300     StructureSet m_structures;
301 };
302
303 class LocalHeap {
304 public:
305     Allocation& newAllocation(Node* node, Allocation::Kind kind)
306     {
307         ASSERT(!m_pointers.contains(node) && !isAllocation(node));
308         m_pointers.add(node, node);
309         return m_allocations.set(node, Allocation(node, kind)).iterator->value;
310     }
311
312     bool isAllocation(Node* identifier) const
313     {
314         return m_allocations.contains(identifier);
315     }
316
317     // Note that this is fundamentally different from
318     // onlyLocalAllocation() below. getAllocation() takes as argument
319     // a node-as-identifier, that is, an allocation node. This
320     // allocation node doesn't have to be alive; it may only be
321     // pointed to by other nodes or allocation fields.
322     // For instance, in the following graph:
323     //
324     // Block #0
325     //  0: NewObject({})
326     //  1: NewObject({})
327     //  -: PutByOffset(@0, @1, x)
328     //  -: PutStructure(@0, {x:0})
329     //  2: GetByOffset(@0, x)
330     //  -: Jump(#1)
331     //
332     // Block #1
333     //  -: Return(@2)
334     //
335     // At head of block #1, the only reachable allocation is #@1,
336     // which can be reached through node @2. Thus, getAllocation(#@1)
337     // contains the appropriate metadata for this allocation, but
338     // onlyLocalAllocation(@1) is null, as @1 is no longer a pointer
339     // to #@1 (since it is dead). Conversely, onlyLocalAllocation(@2)
340     // is the same as getAllocation(#@1), while getAllocation(#@2)
341     // does not make sense since @2 is not an allocation node.
342     //
343     // This is meant to be used when the node is already known to be
344     // an identifier (i.e. an allocation) - probably because it was
345     // found as value of a field or pointer in the current heap, or
346     // was the result of a call to follow(). In any other cases (such
347     // as when doing anything while traversing the graph), the
348     // appropriate function to call is probably onlyLocalAllocation.
349     Allocation& getAllocation(Node* identifier)
350     {
351         auto iter = m_allocations.find(identifier);
352         ASSERT(iter != m_allocations.end());
353         return iter->value;
354     }
355
356     void newPointer(Node* node, Node* identifier)
357     {
358         ASSERT(!m_allocations.contains(node) && !m_pointers.contains(node));
359         ASSERT(isAllocation(identifier));
360         m_pointers.add(node, identifier);
361     }
362
363     // follow solves the points-to problem. Given a live node, which
364     // may be either an allocation itself or a heap read (e.g. a
365     // GetByOffset node), it returns the corresponding allocation
366     // node, if there is one. If the argument node is neither an
367     // allocation or a heap read, or may point to different nodes,
368     // nullptr will be returned. Note that a node that points to
369     // different nodes can never point to an unescaped local
370     // allocation.
371     Node* follow(Node* node) const
372     {
373         auto iter = m_pointers.find(node);
374         ASSERT(iter == m_pointers.end() || m_allocations.contains(iter->value));
375         return iter == m_pointers.end() ? nullptr : iter->value;
376     }
377
378     Node* follow(PromotedHeapLocation location) const
379     {
380         const Allocation& base = m_allocations.find(location.base())->value;
381         auto iter = base.fields().find(location.descriptor());
382
383         if (iter == base.fields().end())
384             return nullptr;
385
386         return iter->value;
387     }
388
389     // onlyLocalAllocation find the corresponding allocation metadata
390     // for any live node. onlyLocalAllocation(node) is essentially
391     // getAllocation(follow(node)), with appropriate null handling.
392     Allocation* onlyLocalAllocation(Node* node)
393     {
394         Node* identifier = follow(node);
395         if (!identifier)
396             return nullptr;
397
398         return &getAllocation(identifier);
399     }
400
401     Allocation* onlyLocalAllocation(PromotedHeapLocation location)
402     {
403         Node* identifier = follow(location);
404         if (!identifier)
405             return nullptr;
406
407         return &getAllocation(identifier);
408     }
409
410     // This allows us to store the escapees only when necessary. If
411     // set, the current escapees can be retrieved at any time using
412     // takeEscapees(), which will clear the cached set of escapees;
413     // otherwise the heap won't remember escaping allocations.
414     void setWantEscapees()
415     {
416         m_wantEscapees = true;
417     }
418
419     HashMap<Node*, Allocation> takeEscapees()
420     {
421         return WTF::move(m_escapees);
422     }
423
424     void escape(Node* node)
425     {
426         Node* identifier = follow(node);
427         if (!identifier)
428             return;
429
430         escapeAllocation(identifier);
431     }
432
433     void merge(const LocalHeap& other)
434     {
435         assertIsValid();
436         other.assertIsValid();
437         ASSERT(!m_wantEscapees);
438
439         if (!reached()) {
440             ASSERT(other.reached());
441             *this = other;
442             return;
443         }
444
445         HashSet<Node*> toEscape;
446
447         for (auto& allocationEntry : other.m_allocations)
448             m_allocations.add(allocationEntry.key, allocationEntry.value);
449         for (auto& allocationEntry : m_allocations) {
450             auto allocationIter = other.m_allocations.find(allocationEntry.key);
451
452             // If we have it and they don't, it died for them but we
453             // are keeping it alive from another field somewhere.
454             // There is nothing to do - we will be escaped
455             // automatically when we handle that other field.
456             // This will also happen for allocation that we have and
457             // they don't, and all of those will get pruned.
458             if (allocationIter == other.m_allocations.end())
459                 continue;
460
461             if (allocationEntry.value.kind() != allocationIter->value.kind()) {
462                 toEscape.add(allocationEntry.key);
463                 for (const auto& fieldEntry : allocationIter->value.fields())
464                     toEscape.add(fieldEntry.value);
465             } else {
466                 mergePointerSets(
467                     allocationEntry.value.fields(), allocationIter->value.fields(),
468                     [&] (Node* identifier) {
469                         toEscape.add(identifier);
470                     },
471                     [&] (PromotedLocationDescriptor field) {
472                         allocationEntry.value.remove(field);
473                     });
474                 allocationEntry.value.mergeStructures(allocationIter->value.structures());
475             }
476         }
477
478         mergePointerSets(m_pointers, other.m_pointers,
479             [&] (Node* identifier) {
480                 toEscape.add(identifier);
481             },
482             [&] (Node* field) {
483                 m_pointers.remove(field);
484             });
485
486         for (Node* identifier : toEscape)
487             escapeAllocation(identifier);
488
489         if (!ASSERT_DISABLED) {
490             for (const auto& entry : m_allocations)
491                 ASSERT_UNUSED(entry, entry.value.isEscapedAllocation() || other.m_allocations.contains(entry.key));
492         }
493
494         // If there is no remaining pointer to an allocation, we can
495         // remove it. This should only happen for escaped allocations,
496         // because we only merge liveness-pruned heaps in the first
497         // place.
498         prune();
499
500         assertIsValid();
501     }
502
503     void pruneByLiveness(const HashSet<Node*>& live)
504     {
505         Vector<Node*> toRemove;
506         for (const auto& entry : m_pointers) {
507             if (!live.contains(entry.key))
508                 toRemove.append(entry.key);
509         }
510         for (Node* node : toRemove)
511             m_pointers.remove(node);
512
513         prune();
514     }
515
516     void assertIsValid() const
517     {
518         if (ASSERT_DISABLED)
519             return;
520
521         // Pointers should point to an actual allocation
522         for (const auto& entry : m_pointers) {
523             ASSERT_UNUSED(entry, entry.value);
524             ASSERT(m_allocations.contains(entry.value));
525         }
526
527         for (const auto& allocationEntry : m_allocations) {
528             // Fields should point to an actual allocation
529             for (const auto& fieldEntry : allocationEntry.value.fields()) {
530                 ASSERT_UNUSED(fieldEntry, fieldEntry.value);
531                 ASSERT(m_allocations.contains(fieldEntry.value));
532             }
533         }
534     }
535
536     bool operator==(const LocalHeap& other) const
537     {
538         assertIsValid();
539         other.assertIsValid();
540         return m_allocations == other.m_allocations
541             && m_pointers == other.m_pointers;
542     }
543
544     bool operator!=(const LocalHeap& other) const
545     {
546         return !(*this == other);
547     }
548
549     const HashMap<Node*, Allocation>& allocations() const
550     {
551         return m_allocations;
552     }
553
554     const HashMap<Node*, Node*>& pointers() const
555     {
556         return m_pointers;
557     }
558
559     void dump(PrintStream& out) const
560     {
561         out.print("  Allocations:\n");
562         for (const auto& entry : m_allocations)
563             out.print("    #", entry.key, ": ", entry.value, "\n");
564         out.print("  Pointers:\n");
565         for (const auto& entry : m_pointers)
566             out.print("    ", entry.key, " => #", entry.value, "\n");
567     }
568
569     bool reached() const
570     {
571         return m_reached;
572     }
573
574     void setReached()
575     {
576         m_reached = true;
577     }
578
579 private:
580     // When we merge two heaps, we escape all fields of allocations,
581     // unless they point to the same thing in both heaps.
582     // The reason for this is that it allows us not to do extra work
583     // for diamond graphs where we would otherwise have to check
584     // whether we have a single definition or not, which would be
585     // cumbersome.
586     //
587     // Note that we should try to unify nodes even when they are not
588     // from the same allocation; for instance we should be able to
589     // completely eliminate all allocations from the following graph:
590     //
591     // Block #0
592     //  0: NewObject({})
593     //  -: Branch(#1, #2)
594     //
595     // Block #1
596     //  1: NewObject({})
597     //  -: PutByOffset(@1, "left", val)
598     //  -: PutStructure(@1, {val:0})
599     //  -: PutByOffset(@0, @1, x)
600     //  -: PutStructure(@0, {x:0})
601     //  -: Jump(#3)
602     //
603     // Block #2
604     //  2: NewObject({})
605     //  -: PutByOffset(@2, "right", val)
606     //  -: PutStructure(@2, {val:0})
607     //  -: PutByOffset(@0, @2, x)
608     //  -: PutStructure(@0, {x:0})
609     //  -: Jump(#3)
610     //
611     // Block #3:
612     //  3: GetByOffset(@0, x)
613     //  4: GetByOffset(@3, val)
614     //  -: Return(@4)
615     template<typename Key, typename EscapeFunctor, typename RemoveFunctor>
616     void mergePointerSets(
617         const HashMap<Key, Node*>& my, const HashMap<Key, Node*>& their,
618         const EscapeFunctor& escape, const RemoveFunctor& remove)
619     {
620         Vector<Key> toRemove;
621         for (const auto& entry : my) {
622             auto iter = their.find(entry.key);
623             if (iter == their.end()) {
624                 toRemove.append(entry.key);
625                 escape(entry.value);
626             } else if (iter->value != entry.value) {
627                 toRemove.append(entry.key);
628                 escape(entry.value);
629                 escape(iter->value);
630             }
631         }
632         for (const auto& entry : their) {
633             if (my.contains(entry.key))
634                 continue;
635             escape(entry.value);
636         }
637         for (Key key : toRemove)
638             remove(key);
639     }
640
641     void escapeAllocation(Node* identifier)
642     {
643         Allocation& allocation = getAllocation(identifier);
644         if (allocation.isEscapedAllocation())
645             return;
646
647         Allocation unescaped = WTF::move(allocation);
648         allocation = Allocation(unescaped.identifier(), Allocation::Kind::Escaped);
649
650         for (const auto& entry : unescaped.fields())
651             escapeAllocation(entry.value);
652
653         if (m_wantEscapees)
654             m_escapees.add(unescaped.identifier(), WTF::move(unescaped));
655     }
656
657     void prune()
658     {
659         HashSet<Node*> reachable;
660         for (const auto& entry : m_pointers)
661             reachable.add(entry.value);
662
663         // Repeatedly mark as reachable allocations in fields of other
664         // reachable allocations
665         {
666             Vector<Node*> worklist;
667             worklist.appendRange(reachable.begin(), reachable.end());
668
669             while (!worklist.isEmpty()) {
670                 Node* identifier = worklist.takeLast();
671                 Allocation& allocation = m_allocations.find(identifier)->value;
672                 for (const auto& entry : allocation.fields()) {
673                     if (reachable.add(entry.value).isNewEntry)
674                         worklist.append(entry.value);
675                 }
676             }
677         }
678
679         // Remove unreachable allocations
680         {
681             Vector<Node*> toRemove;
682             for (const auto& entry : m_allocations) {
683                 if (!reachable.contains(entry.key))
684                     toRemove.append(entry.key);
685             }
686             for (Node* identifier : toRemove)
687                 m_allocations.remove(identifier);
688         }
689     }
690
691     bool m_reached = false;
692     HashMap<Node*, Node*> m_pointers;
693     HashMap<Node*, Allocation> m_allocations;
694
695     bool m_wantEscapees = false;
696     HashMap<Node*, Allocation> m_escapees;
697 };
698
699 class ObjectAllocationSinkingPhase : public Phase {
700 public:
701     ObjectAllocationSinkingPhase(Graph& graph)
702         : Phase(graph, "object allocation elimination")
703         , m_pointerSSA(graph)
704         , m_allocationSSA(graph)
705         , m_insertionSet(graph)
706     {
707     }
708
709     bool run()
710     {
711         ASSERT(m_graph.m_form == SSA);
712         ASSERT(m_graph.m_fixpointState == FixpointNotConverged);
713
714         if (!performSinking())
715             return false;
716
717         if (verbose) {
718             dataLog("Graph after elimination:\n");
719             m_graph.dump();
720         }
721
722         return true;
723     }
724
725 private:
726     bool performSinking()
727     {
728         m_graph.computeRefCounts();
729         m_graph.initializeNodeOwners();
730         m_graph.ensureDominators();
731         performLivenessAnalysis(m_graph);
732         performOSRAvailabilityAnalysis(m_graph);
733         m_combinedLiveness = CombinedLiveness(m_graph);
734
735         CString graphBeforeSinking;
736         if (Options::verboseValidationFailure() && Options::validateGraphAtEachPhase()) {
737             StringPrintStream out;
738             m_graph.dump(out);
739             graphBeforeSinking = out.toCString();
740         }
741
742         if (verbose) {
743             dataLog("Graph before elimination:\n");
744             m_graph.dump();
745         }
746
747         performAnalysis();
748
749         if (!determineSinkCandidates())
750             return false;
751
752         if (verbose) {
753             for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
754                 dataLog("Heap at head of ", *block, ": \n", m_heapAtHead[block]);
755                 dataLog("Heap at tail of ", *block, ": \n", m_heapAtTail[block]);
756             }
757         }
758
759         promoteLocalHeap();
760
761         if (Options::validateGraphAtEachPhase())
762             DFG::validate(m_graph, DumpGraph, graphBeforeSinking);
763         return true;
764     }
765
766     void performAnalysis()
767     {
768         m_heapAtHead = BlockMap<LocalHeap>(m_graph);
769         m_heapAtTail = BlockMap<LocalHeap>(m_graph);
770
771         bool changed;
772         do {
773             if (verbose)
774                 dataLog("Doing iteration of escape analysis.\n");
775             changed = false;
776
777             for (BasicBlock* block : m_graph.blocksInPreOrder()) {
778                 m_heapAtHead[block].setReached();
779                 m_heap = m_heapAtHead[block];
780
781                 for (Node* node : *block) {
782                     handleNode(
783                         node,
784                         [] (PromotedHeapLocation, LazyNode) { },
785                         [&] (PromotedHeapLocation) -> Node* {
786                             return nullptr;
787                         });
788                 }
789
790                 if (m_heap == m_heapAtTail[block])
791                     continue;
792
793                 m_heapAtTail[block] = m_heap;
794                 changed = true;
795
796                 m_heap.assertIsValid();
797
798                 // We keep only pointers that are live, and only
799                 // allocations that are either live, pointed to by a
800                 // live pointer, or (recursively) stored in a field of
801                 // a live allocation.
802                 //
803                 // This means we can accidentaly leak non-dominating
804                 // nodes into the successor. However, due to the
805                 // non-dominance property, we are guaranteed that the
806                 // successor has at least one predecessor that is not
807                 // dominated either: this means any reference to a
808                 // non-dominating allocation in the successor will
809                 // trigger an escape and get pruned during the merge.
810                 m_heap.pruneByLiveness(m_combinedLiveness.liveAtTail[block]);
811
812                 for (BasicBlock* successorBlock : block->successors())
813                     m_heapAtHead[successorBlock].merge(m_heap);
814             }
815         } while (changed);
816     }
817
818     template<typename WriteFunctor, typename ResolveFunctor>
819     void handleNode(
820         Node* node,
821         const WriteFunctor& heapWrite,
822         const ResolveFunctor& heapResolve)
823     {
824         m_heap.assertIsValid();
825         ASSERT(m_heap.takeEscapees().isEmpty());
826
827         Allocation* target = nullptr;
828         HashMap<PromotedLocationDescriptor, LazyNode> writes;
829         PromotedLocationDescriptor exactRead;
830
831         switch (node->op()) {
832         case NewObject:
833             target = &m_heap.newAllocation(node, Allocation::Kind::Object);
834             target->setStructures(node->structure());
835             writes.add(
836                 StructurePLoc, LazyNode(m_graph.freeze(node->structure())));
837             break;
838
839         case NewFunction:
840         case NewArrowFunction: {
841             if (node->castOperand<FunctionExecutable*>()->singletonFunction()->isStillValid()) {
842                 m_heap.escape(node->child1().node());
843                 break;
844             }
845             
846             target = &m_heap.newAllocation(node, Allocation::Kind::Function);
847             writes.add(FunctionExecutablePLoc, LazyNode(node->cellOperand()));
848             writes.add(FunctionActivationPLoc, LazyNode(node->child1().node()));
849             break;
850         }
851
852         case CreateActivation: {
853             if (node->castOperand<SymbolTable*>()->singletonScope()->isStillValid()) {
854                 m_heap.escape(node->child1().node());
855                 break;
856             }
857             target = &m_heap.newAllocation(node, Allocation::Kind::Activation);
858             writes.add(ActivationSymbolTablePLoc, LazyNode(node->cellOperand()));
859             writes.add(ActivationScopePLoc, LazyNode(node->child1().node()));
860             {
861                 SymbolTable* symbolTable = node->castOperand<SymbolTable*>();
862                 ConcurrentJITLocker locker(symbolTable->m_lock);
863                 LazyNode initialValue(m_graph.freeze(node->initializationValueForActivation()));
864                 for (auto iter = symbolTable->begin(locker), end = symbolTable->end(locker); iter != end; ++iter) {
865                     writes.add(
866                         PromotedLocationDescriptor(ClosureVarPLoc, iter->value.scopeOffset().offset()),
867                         initialValue);
868                 }
869             }
870             break;
871         }
872
873         case PutStructure:
874             target = m_heap.onlyLocalAllocation(node->child1().node());
875             if (target && target->isObjectAllocation()) {
876                 writes.add(StructurePLoc, LazyNode(m_graph.freeze(JSValue(node->transition()->next))));
877                 target->setStructures(node->transition()->next);
878             } else
879                 m_heap.escape(node->child1().node());
880             break;
881
882         case CheckStructure: {
883             Allocation* allocation = m_heap.onlyLocalAllocation(node->child1().node());
884             if (allocation && allocation->isObjectAllocation()) {
885                 allocation->filterStructures(node->structureSet());
886                 if (Node* value = heapResolve(PromotedHeapLocation(allocation->identifier(), StructurePLoc)))
887                     node->convertToCheckStructureImmediate(value);
888             } else
889                 m_heap.escape(node->child1().node());
890             break;
891         }
892
893         case GetByOffset:
894         case GetGetterSetterByOffset:
895             target = m_heap.onlyLocalAllocation(node->child2().node());
896             if (target && target->isObjectAllocation()) {
897                 unsigned identifierNumber = node->storageAccessData().identifierNumber;
898                 exactRead = PromotedLocationDescriptor(NamedPropertyPLoc, identifierNumber);
899             } else {
900                 m_heap.escape(node->child1().node());
901                 m_heap.escape(node->child2().node());
902             }
903             break;
904
905         case MultiGetByOffset: {
906             Allocation* allocation = m_heap.onlyLocalAllocation(node->child1().node());
907             if (allocation && allocation->isObjectAllocation()) {
908                 MultiGetByOffsetData& data = node->multiGetByOffsetData();
909                 StructureSet validStructures;
910                 bool hasInvalidStructures = false;
911                 for (const auto& multiGetByOffsetCase : data.cases) {
912                     if (!allocation->structures().overlaps(multiGetByOffsetCase.set()))
913                         continue;
914
915                     switch (multiGetByOffsetCase.method().kind()) {
916                     case GetByOffsetMethod::LoadFromPrototype: // We need to escape those
917                     case GetByOffsetMethod::Constant: // We don't really have a way of expressing this
918                         hasInvalidStructures = true;
919                         break;
920
921                     case GetByOffsetMethod::Load: // We're good
922                         validStructures.merge(multiGetByOffsetCase.set());
923                         break;
924
925                     default:
926                         RELEASE_ASSERT_NOT_REACHED();
927                     }
928                 }
929                 if (hasInvalidStructures) {
930                     m_heap.escape(node->child1().node());
931                     break;
932                 }
933                 unsigned identifierNumber = data.identifierNumber;
934                 PromotedHeapLocation location(NamedPropertyPLoc, allocation->identifier(), identifierNumber);
935                 if (Node* value = heapResolve(location)) {
936                     if (allocation->structures().isSubsetOf(validStructures))
937                         node->replaceWith(value);
938                     else {
939                         Node* structure = heapResolve(PromotedHeapLocation(allocation->identifier(), StructurePLoc));
940                         ASSERT(structure);
941                         allocation->filterStructures(validStructures);
942                         node->convertToCheckStructure(m_graph.addStructureSet(allocation->structures()));
943                         node->convertToCheckStructureImmediate(structure);
944                         node->setReplacement(value);
945                     }
946                 } else if (!allocation->structures().isSubsetOf(validStructures)) {
947                     // Even though we don't need the result here, we still need
948                     // to make the call to tell our caller that we could need
949                     // the StructurePLoc.
950                     // The reason for this is that when we decide not to sink a
951                     // node, we will still lower any read to its fields before
952                     // it escapes (which are usually reads across a function
953                     // call that DFGClobberize can't handle) - but we only do
954                     // this for PromotedHeapLocations that we have seen read
955                     // during the analysis!
956                     heapResolve(PromotedHeapLocation(allocation->identifier(), StructurePLoc));
957                     allocation->filterStructures(validStructures);
958                 }
959                 Node* identifier = allocation->get(location.descriptor());
960                 if (identifier)
961                     m_heap.newPointer(node, identifier);
962             } else
963                 m_heap.escape(node->child1().node());
964             break;
965         }
966
967         case PutByOffset:
968             target = m_heap.onlyLocalAllocation(node->child2().node());
969             if (target && target->isObjectAllocation()) {
970                 unsigned identifierNumber = node->storageAccessData().identifierNumber;
971                 writes.add(
972                     PromotedLocationDescriptor(NamedPropertyPLoc, identifierNumber),
973                     LazyNode(node->child3().node()));
974             } else {
975                 m_heap.escape(node->child1().node());
976                 m_heap.escape(node->child2().node());
977                 m_heap.escape(node->child3().node());
978             }
979             break;
980
981         case GetClosureVar:
982             target = m_heap.onlyLocalAllocation(node->child1().node());
983             if (target && target->isActivationAllocation()) {
984                 exactRead =
985                     PromotedLocationDescriptor(ClosureVarPLoc, node->scopeOffset().offset());
986             } else
987                 m_heap.escape(node->child1().node());
988             break;
989
990         case PutClosureVar:
991             target = m_heap.onlyLocalAllocation(node->child1().node());
992             if (target && target->isActivationAllocation()) {
993                 writes.add(
994                     PromotedLocationDescriptor(ClosureVarPLoc, node->scopeOffset().offset()),
995                     LazyNode(node->child2().node()));
996             } else {
997                 m_heap.escape(node->child1().node());
998                 m_heap.escape(node->child2().node());
999             }
1000             break;
1001
1002         case SkipScope:
1003             target = m_heap.onlyLocalAllocation(node->child1().node());
1004             if (target && target->isActivationAllocation())
1005                 exactRead = ActivationScopePLoc;
1006             else
1007                 m_heap.escape(node->child1().node());
1008             break;
1009
1010         case GetExecutable:
1011             target = m_heap.onlyLocalAllocation(node->child1().node());
1012             if (target && target->isFunctionAllocation())
1013                 exactRead = FunctionExecutablePLoc;
1014             else
1015                 m_heap.escape(node->child1().node());
1016             break;
1017
1018         case GetScope:
1019             target = m_heap.onlyLocalAllocation(node->child1().node());
1020             if (target && target->isFunctionAllocation())
1021                 exactRead = FunctionActivationPLoc;
1022             else
1023                 m_heap.escape(node->child1().node());
1024             break;
1025
1026         case Check:
1027             m_graph.doToChildren(
1028                 node,
1029                 [&] (Edge edge) {
1030                     if (edge.willNotHaveCheck())
1031                         return;
1032
1033                     if (alreadyChecked(edge.useKind(), SpecObject))
1034                         return;
1035
1036                     m_heap.escape(edge.node());
1037                 });
1038             break;
1039
1040         case MovHint:
1041         case PutHint:
1042             // Handled by OSR availability analysis
1043             break;
1044
1045         default:
1046             m_graph.doToChildren(
1047                 node,
1048                 [&] (Edge edge) {
1049                     m_heap.escape(edge.node());
1050                 });
1051             break;
1052         }
1053
1054         if (exactRead) {
1055             ASSERT(target);
1056             ASSERT(writes.isEmpty());
1057             if (Node* value = heapResolve(PromotedHeapLocation(target->identifier(), exactRead))) {
1058                 ASSERT(!value->replacement());
1059                 node->replaceWith(value);
1060             }
1061             Node* identifier = target->get(exactRead);
1062             if (identifier)
1063                 m_heap.newPointer(node, identifier);
1064         }
1065
1066         for (auto entry : writes) {
1067             ASSERT(target);
1068             if (entry.value.isNode())
1069                 target->set(entry.key, m_heap.follow(entry.value.asNode()));
1070             else
1071                 target->remove(entry.key);
1072             heapWrite(PromotedHeapLocation(target->identifier(), entry.key), entry.value);
1073         }
1074
1075         m_heap.assertIsValid();
1076     }
1077
1078     bool determineSinkCandidates()
1079     {
1080         m_sinkCandidates.clear();
1081         m_materializationToEscapee.clear();
1082         m_materializationSiteToMaterializations.clear();
1083         m_materializationSiteToRecoveries.clear();
1084
1085         // Logically we wish to consider every allocation and sink
1086         // it. However, it is probably not profitable to sink an
1087         // allocation that will always escape. So, we only sink an
1088         // allocation if one of the following is true:
1089         //
1090         // 1) There exists a basic block with only backwards outgoing
1091         //    edges (or no outgoing edges) in which the node wasn't
1092         //    materialized. This is meant to catch
1093         //    effectively-infinite loops in which we don't need to
1094         //    have allocated the object.
1095         //
1096         // 2) There exists a basic block at the tail of which the node
1097         //    is dead and not materialized.
1098         //
1099         // 3) The sum of execution counts of the materializations is
1100         //    less than the sum of execution counts of the original
1101         //    node.
1102         //
1103         // We currently implement only rule #2.
1104         // FIXME: Implement the two other rules.
1105         // https://bugs.webkit.org/show_bug.cgi?id=137073 (rule #1)
1106         // https://bugs.webkit.org/show_bug.cgi?id=137074 (rule #3)
1107         //
1108         // However, these rules allow for a sunk object to be put into
1109         // a non-sunk one, which we don't support. We could solve this
1110         // by supporting PutHints on local allocations, making these
1111         // objects only partially correct, and we would need to adapt
1112         // the OSR availability analysis and OSR exit to handle
1113         // this. This would be totally doable, but would create a
1114         // super rare, and thus bug-prone, code path.
1115         // So, instead, we need to implement one of the following
1116         // closure rules:
1117         //
1118         // 1) If we put a sink candidate into a local allocation that
1119         //    is not a sink candidate, change our minds and don't
1120         //    actually sink the sink candidate.
1121         //
1122         // 2) If we put a sink candidate into a local allocation, that
1123         //    allocation becomes a sink candidate as well.
1124         //
1125         // We currently choose to implement closure rule #2.
1126         HashMap<Node*, Vector<Node*>> dependencies;
1127         bool hasUnescapedReads = false;
1128         for (BasicBlock* block : m_graph.blocksInPreOrder()) {
1129             m_heap = m_heapAtHead[block];
1130
1131             for (Node* node : *block) {
1132                 handleNode(
1133                     node,
1134                     [&] (PromotedHeapLocation location, LazyNode value) {
1135                         if (!value.isNode())
1136                             return;
1137
1138                         Allocation* allocation = m_heap.onlyLocalAllocation(value.asNode());
1139                         if (allocation && !allocation->isEscapedAllocation())
1140                             dependencies.add(allocation->identifier(), Vector<Node*>()).iterator->value.append(location.base());
1141                     },
1142                     [&] (PromotedHeapLocation) -> Node* {
1143                         hasUnescapedReads = true;
1144                         return nullptr;
1145                     });
1146             }
1147
1148             // The sink candidates are initially the unescaped
1149             // allocations dying at tail of blocks
1150             HashSet<Node*> allocations;
1151             for (const auto& entry : m_heap.allocations()) {
1152                 if (!entry.value.isEscapedAllocation())
1153                     allocations.add(entry.key);
1154             }
1155
1156             m_heap.pruneByLiveness(m_combinedLiveness.liveAtTail[block]);
1157
1158             for (Node* identifier : allocations) {
1159                 if (!m_heap.isAllocation(identifier))
1160                     m_sinkCandidates.add(identifier);
1161             }
1162         }
1163
1164         // Ensure that the set of sink candidates is closed for put operations
1165         Vector<Node*> worklist;
1166         worklist.appendRange(m_sinkCandidates.begin(), m_sinkCandidates.end());
1167
1168         while (!worklist.isEmpty()) {
1169             for (Node* identifier : dependencies.get(worklist.takeLast())) {
1170                 if (m_sinkCandidates.add(identifier).isNewEntry)
1171                     worklist.append(identifier);
1172             }
1173         }
1174
1175         if (m_sinkCandidates.isEmpty())
1176             return hasUnescapedReads;
1177
1178         if (verbose)
1179             dataLog("Candidates: ", listDump(m_sinkCandidates), "\n");
1180
1181         // Create the materialization nodes
1182         for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
1183             m_heap = m_heapAtHead[block];
1184             m_heap.setWantEscapees();
1185
1186             for (Node* node : *block) {
1187                 handleNode(
1188                     node,
1189                     [] (PromotedHeapLocation, LazyNode) { },
1190                     [] (PromotedHeapLocation) -> Node* {
1191                         return nullptr;
1192                     });
1193                 auto escapees = m_heap.takeEscapees();
1194                 if (!escapees.isEmpty())
1195                     placeMaterializations(escapees, node);
1196             }
1197
1198             m_heap.pruneByLiveness(m_combinedLiveness.liveAtTail[block]);
1199
1200             {
1201                 HashMap<Node*, Allocation> escapingOnEdge;
1202                 for (const auto& entry : m_heap.allocations()) {
1203                     if (entry.value.isEscapedAllocation())
1204                         continue;
1205
1206                     bool mustEscape = false;
1207                     for (BasicBlock* successorBlock : block->successors()) {
1208                         if (!m_heapAtHead[successorBlock].isAllocation(entry.key)
1209                             || m_heapAtHead[successorBlock].getAllocation(entry.key).isEscapedAllocation())
1210                             mustEscape = true;
1211                     }
1212
1213                     if (mustEscape)
1214                         escapingOnEdge.add(entry.key, entry.value);
1215                 }
1216                 placeMaterializations(WTF::move(escapingOnEdge), block->terminal());
1217             }
1218         }
1219
1220         return hasUnescapedReads || !m_sinkCandidates.isEmpty();
1221     }
1222
1223     void placeMaterializations(HashMap<Node*, Allocation> escapees, Node* where)
1224     {
1225         // We don't create materializations if the escapee is not a
1226         // sink candidate
1227         Vector<Node*> toRemove;
1228         for (const auto& entry : escapees) {
1229             if (!m_sinkCandidates.contains(entry.key))
1230                 toRemove.append(entry.key);
1231         }
1232         for (Node* identifier : toRemove)
1233             escapees.remove(identifier);
1234
1235         if (escapees.isEmpty())
1236             return;
1237
1238         // First collect the hints that will be needed when the node
1239         // we materialize is still stored into other unescaped sink candidates
1240         Vector<PromotedHeapLocation> hints;
1241         for (const auto& entry : m_heap.allocations()) {
1242             if (escapees.contains(entry.key))
1243                 continue;
1244
1245             for (const auto& field : entry.value.fields()) {
1246                 ASSERT(m_sinkCandidates.contains(entry.key) || !escapees.contains(field.value));
1247                 if (escapees.contains(field.value) && !field.key.neededForMaterialization())
1248                     hints.append(PromotedHeapLocation(entry.key, field.key));
1249             }
1250         }
1251
1252         // Now we need to order the materialization. Any order is
1253         // valid (as long as we materialize a node first if it is
1254         // needed for the materialization of another node, e.g. a
1255         // function's activation must be materialized before the
1256         // function itself), but we want to try minimizing the number
1257         // of times we have to place Puts to close cycles after a
1258         // materialization. In other words, we are trying to find the
1259         // minimum number of materializations to remove from the
1260         // materialization graph to make it a DAG, known as the
1261         // (vertex) feedback set problem. Unfortunately, this is a
1262         // NP-hard problem, which we don't want to solve exactly.
1263         //
1264         // Instead, we use a simple greedy procedure, that procedes as
1265         // follow:
1266         //  - While there is at least one node with no outgoing edge
1267         //    amongst the remaining materializations, materialize it
1268         //    first
1269         //
1270         //  - Similarily, while there is at least one node with no
1271         //    incoming edge amongst the remaining materializations,
1272         //    materialize it last.
1273         //
1274         //  - When both previous conditions are false, we have an
1275         //    actual cycle, and we need to pick a node to
1276         //    materialize. We try greedily to remove the "pressure" on
1277         //    the remaining nodes by choosing the node with maximum
1278         //    |incoming edges| * |outgoing edges| as a measure of how
1279         //    "central" to the graph it is. We materialize it first,
1280         //    so that all the recoveries will be Puts of things into
1281         //    it (rather than Puts of the materialization into other
1282         //    objects), which means we will have a single
1283         //    StoreBarrier.
1284
1285
1286         // Compute dependencies between materializations
1287         HashMap<Node*, HashSet<Node*>> dependencies;
1288         HashMap<Node*, HashSet<Node*>> reverseDependencies;
1289         HashMap<Node*, HashSet<Node*>> forMaterialization;
1290         for (const auto& entry : escapees) {
1291             auto& myDependencies = dependencies.add(entry.key, HashSet<Node*>()).iterator->value;
1292             auto& myDependenciesForMaterialization = forMaterialization.add(entry.key, HashSet<Node*>()).iterator->value;
1293             reverseDependencies.add(entry.key, HashSet<Node*>());
1294             for (const auto& field : entry.value.fields()) {
1295                 if (escapees.contains(field.value) && field.value != entry.key) {
1296                     myDependencies.add(field.value);
1297                     reverseDependencies.add(field.value, HashSet<Node*>()).iterator->value.add(entry.key);
1298                     if (field.key.neededForMaterialization())
1299                         myDependenciesForMaterialization.add(field.value);
1300                 }
1301             }
1302         }
1303
1304         // Helper function to update the materialized set and the
1305         // dependencies
1306         HashSet<Node*> materialized;
1307         auto materialize = [&] (Node* identifier) {
1308             materialized.add(identifier);
1309             for (Node* dep : dependencies.get(identifier))
1310                 reverseDependencies.find(dep)->value.remove(identifier);
1311             for (Node* rdep : reverseDependencies.get(identifier)) {
1312                 dependencies.find(rdep)->value.remove(identifier);
1313                 forMaterialization.find(rdep)->value.remove(identifier);
1314             }
1315             dependencies.remove(identifier);
1316             reverseDependencies.remove(identifier);
1317             forMaterialization.remove(identifier);
1318         };
1319
1320         // Nodes without remaining unmaterialized fields will be
1321         // materialized first - amongst the remaining unmaterialized
1322         // nodes
1323         std::list<Allocation> toMaterialize;
1324         auto firstPos = toMaterialize.begin();
1325         auto materializeFirst = [&] (Allocation&& allocation) {
1326             materialize(allocation.identifier());
1327             // We need to insert *after* the current position
1328             if (firstPos != toMaterialize.end())
1329                 ++firstPos;
1330             firstPos = toMaterialize.insert(firstPos, WTF::move(allocation));
1331         };
1332
1333         // Nodes that no other unmaterialized node points to will be
1334         // materialized last - amongst the remaining unmaterialized
1335         // nodes
1336         auto lastPos = toMaterialize.end();
1337         auto materializeLast = [&] (Allocation&& allocation) {
1338             materialize(allocation.identifier());
1339             lastPos = toMaterialize.insert(lastPos, WTF::move(allocation));
1340         };
1341
1342         // These are the promoted locations that contains some of the
1343         // allocations we are currently escaping. If they are a location on
1344         // some other allocation we are currently materializing, we will need
1345         // to "recover" their value with a real put once the corresponding
1346         // allocation is materialized; if they are a location on some other
1347         // not-yet-materialized allocation, we will need a PutHint.
1348         Vector<PromotedHeapLocation> toRecover;
1349
1350         // This loop does the actual cycle breaking
1351         while (!escapees.isEmpty()) {
1352             materialized.clear();
1353
1354             // Materialize nodes that won't require recoveries if we can
1355             for (auto& entry : escapees) {
1356                 if (!forMaterialization.find(entry.key)->value.isEmpty())
1357                     continue;
1358
1359                 if (dependencies.find(entry.key)->value.isEmpty()) {
1360                     materializeFirst(WTF::move(entry.value));
1361                     continue;
1362                 }
1363
1364                 if (reverseDependencies.find(entry.key)->value.isEmpty()) {
1365                     materializeLast(WTF::move(entry.value));
1366                     continue;
1367                 }
1368             }
1369
1370             // We reach this only if there is an actual cycle that needs
1371             // breaking. Because we do not want to solve a NP-hard problem
1372             // here, we just heuristically pick a node and materialize it
1373             // first.
1374             if (materialized.isEmpty()) {
1375                 uint64_t maxEvaluation = 0;
1376                 Allocation* bestAllocation;
1377                 for (auto& entry : escapees) {
1378                     if (!forMaterialization.find(entry.key)->value.isEmpty())
1379                         continue;
1380
1381                     uint64_t evaluation =
1382                         static_cast<uint64_t>(dependencies.get(entry.key).size()) * reverseDependencies.get(entry.key).size();
1383                     if (evaluation > maxEvaluation) {
1384                         maxEvaluation = evaluation;
1385                         bestAllocation = &entry.value;
1386                     }
1387                 }
1388                 RELEASE_ASSERT(maxEvaluation > 0);
1389
1390                 materializeFirst(WTF::move(*bestAllocation));
1391             }
1392             RELEASE_ASSERT(!materialized.isEmpty());
1393
1394             for (Node* identifier : materialized)
1395                 escapees.remove(identifier);
1396         }
1397
1398         materialized.clear();
1399
1400         HashSet<Node*> escaped;
1401         for (const Allocation& allocation : toMaterialize)
1402             escaped.add(allocation.identifier());
1403         for (const Allocation& allocation : toMaterialize) {
1404             for (const auto& field : allocation.fields()) {
1405                 if (escaped.contains(field.value) && !materialized.contains(field.value))
1406                     toRecover.append(PromotedHeapLocation(allocation.identifier(), field.key));
1407             }
1408             materialized.add(allocation.identifier());
1409         }
1410
1411         Vector<Node*>& materializations = m_materializationSiteToMaterializations.add(
1412             where, Vector<Node*>()).iterator->value;
1413
1414         for (const Allocation& allocation : toMaterialize) {
1415             Node* materialization = createMaterialization(allocation, where);
1416             materializations.append(materialization);
1417             m_materializationToEscapee.add(materialization, allocation.identifier());
1418         }
1419
1420         if (!toRecover.isEmpty()) {
1421             m_materializationSiteToRecoveries.add(
1422                 where, Vector<PromotedHeapLocation>()).iterator->value.appendVector(toRecover);
1423         }
1424
1425         // The hints need to be after the "real" recoveries so that we
1426         // don't hint not-yet-complete objects
1427         if (!hints.isEmpty()) {
1428             m_materializationSiteToRecoveries.add(
1429                 where, Vector<PromotedHeapLocation>()).iterator->value.appendVector(hints);
1430         }
1431     }
1432
1433     Node* createMaterialization(const Allocation& allocation, Node* where)
1434     {
1435         // FIXME: This is the only place where we actually use the
1436         // fact that an allocation's identifier is indeed the node
1437         // that created the allocation.
1438         switch (allocation.kind()) {
1439         case Allocation::Kind::Object: {
1440             ObjectMaterializationData* data = m_graph.m_objectMaterializationData.add();
1441             StructureSet* set = m_graph.addStructureSet(allocation.structures());
1442
1443             return m_graph.addNode(
1444                 allocation.identifier()->prediction(), Node::VarArg, MaterializeNewObject,
1445                 where->origin.withSemantic(allocation.identifier()->origin.semantic),
1446                 OpInfo(set), OpInfo(data), 0, 0);
1447         }
1448
1449         case Allocation::Kind::NewArrowFunction:
1450         case Allocation::Kind::Function: {
1451             FrozenValue* executable = allocation.identifier()->cellOperand();
1452             
1453             NodeType nodeType = allocation.kind() == Allocation::Kind::NewArrowFunction ? NewArrowFunction : NewFunction;
1454             
1455             return m_graph.addNode(
1456                 allocation.identifier()->prediction(), nodeType,
1457                 where->origin.withSemantic(
1458                     allocation.identifier()->origin.semantic),
1459                 OpInfo(executable));
1460             break;
1461         }
1462
1463         case Allocation::Kind::Activation: {
1464             ObjectMaterializationData* data = m_graph.m_objectMaterializationData.add();
1465             FrozenValue* symbolTable = allocation.identifier()->cellOperand();
1466
1467             return m_graph.addNode(
1468                 allocation.identifier()->prediction(), Node::VarArg, MaterializeCreateActivation,
1469                 where->origin.withSemantic(
1470                     allocation.identifier()->origin.semantic),
1471                 OpInfo(symbolTable), OpInfo(data), 0, 0);
1472         }
1473
1474         default:
1475             DFG_CRASH(m_graph, allocation.identifier(), "Bad allocation kind");
1476         }
1477     }
1478
1479     void promoteLocalHeap()
1480     {
1481         // Collect the set of heap locations that we will be operating
1482         // over.
1483         HashSet<PromotedHeapLocation> locations;
1484         for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
1485             m_heap = m_heapAtHead[block];
1486
1487             for (Node* node : *block) {
1488                 handleNode(
1489                     node,
1490                     [&] (PromotedHeapLocation location, LazyNode) {
1491                         // If the location is not on a sink candidate,
1492                         // we only sink it if it is read
1493                         if (m_sinkCandidates.contains(location.base()))
1494                             locations.add(location);
1495                     },
1496                     [&] (PromotedHeapLocation location) -> Node* {
1497                         locations.add(location);
1498                         return nullptr;
1499                     });
1500             }
1501         }
1502
1503         // Figure out which locations belong to which allocations.
1504         m_locationsForAllocation.clear();
1505         for (PromotedHeapLocation location : locations) {
1506             auto result = m_locationsForAllocation.add(
1507                 location.base(),
1508                 Vector<PromotedHeapLocation>());
1509             ASSERT(!result.iterator->value.contains(location));
1510             result.iterator->value.append(location);
1511         }
1512
1513         m_pointerSSA.reset();
1514         m_allocationSSA.reset();
1515
1516         // Collect the set of "variables" that we will be sinking.
1517         m_locationToVariable.clear();
1518         m_nodeToVariable.clear();
1519         Vector<Node*> indexToNode;
1520         Vector<PromotedHeapLocation> indexToLocation;
1521
1522         for (Node* index : m_sinkCandidates) {
1523             SSACalculator::Variable* variable = m_allocationSSA.newVariable();
1524             m_nodeToVariable.add(index, variable);
1525             ASSERT(indexToNode.size() == variable->index());
1526             indexToNode.append(index);
1527         }
1528
1529         for (PromotedHeapLocation location : locations) {
1530             SSACalculator::Variable* variable = m_pointerSSA.newVariable();
1531             m_locationToVariable.add(location, variable);
1532             ASSERT(indexToLocation.size() == variable->index());
1533             indexToLocation.append(location);
1534         }
1535
1536         // We insert all required constants at top of block 0 so that
1537         // they are inserted only once and we don't clutter the graph
1538         // with useless constants everywhere
1539         HashMap<FrozenValue*, Node*> lazyMapping;
1540         if (!m_bottom)
1541             m_bottom = m_insertionSet.insertConstant(0, m_graph.block(0)->at(0)->origin, jsNumber(1927));
1542         for (BasicBlock* block : m_graph.blocksInNaturalOrder()) {
1543             m_heap = m_heapAtHead[block];
1544
1545             for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1546                 Node* node = block->at(nodeIndex);
1547
1548                 // Some named properties can be added conditionally,
1549                 // and that would necessitate bottoms
1550                 for (PromotedHeapLocation location : m_locationsForAllocation.get(node)) {
1551                     if (location.kind() != NamedPropertyPLoc)
1552                         continue;
1553
1554                     SSACalculator::Variable* variable = m_locationToVariable.get(location);
1555                     m_pointerSSA.newDef(variable, block, m_bottom);
1556                 }
1557
1558                 for (Node* materialization : m_materializationSiteToMaterializations.get(node)) {
1559                     Node* escapee = m_materializationToEscapee.get(materialization);
1560                     m_allocationSSA.newDef(m_nodeToVariable.get(escapee), block, materialization);
1561                 }
1562
1563                 if (m_sinkCandidates.contains(node))
1564                     m_allocationSSA.newDef(m_nodeToVariable.get(node), block, node);
1565
1566                 handleNode(
1567                     node,
1568                     [&] (PromotedHeapLocation location, LazyNode value) {
1569                         if (!locations.contains(location))
1570                             return;
1571
1572                         Node* nodeValue;
1573                         if (value.isNode())
1574                             nodeValue = value.asNode();
1575                         else {
1576                             auto iter = lazyMapping.find(value.asValue());
1577                             if (iter != lazyMapping.end())
1578                                 nodeValue = iter->value;
1579                             else {
1580                                 nodeValue = value.ensureIsNode(
1581                                     m_insertionSet, m_graph.block(0), 0);
1582                                 lazyMapping.add(value.asValue(), nodeValue);
1583                             }
1584                         }
1585
1586                         SSACalculator::Variable* variable = m_locationToVariable.get(location);
1587                         m_pointerSSA.newDef(variable, block, nodeValue);
1588                     },
1589                     [] (PromotedHeapLocation) -> Node* {
1590                         return nullptr;
1591                     });
1592             }
1593         }
1594         m_insertionSet.execute(m_graph.block(0));
1595
1596         // Run the SSA calculators to create Phis
1597         m_pointerSSA.computePhis(
1598             [&] (SSACalculator::Variable* variable, BasicBlock* block) -> Node* {
1599                 PromotedHeapLocation location = indexToLocation[variable->index()];
1600
1601                 // Don't create Phi nodes for fields of dead allocations
1602                 if (!m_heapAtHead[block].isAllocation(location.base()))
1603                     return nullptr;
1604
1605                 // Don't create Phi nodes once we are escaped
1606                 if (m_heapAtHead[block].getAllocation(location.base()).isEscapedAllocation())
1607                     return nullptr;
1608
1609                 // If we point to a single allocation, we will
1610                 // directly use its materialization
1611                 if (m_heapAtHead[block].follow(location))
1612                     return nullptr;
1613
1614                 Node* phiNode = m_graph.addNode(SpecHeapTop, Phi, block->at(0)->origin.withInvalidExit());
1615                 phiNode->mergeFlags(NodeResultJS);
1616                 return phiNode;
1617             });
1618
1619         m_allocationSSA.computePhis(
1620             [&] (SSACalculator::Variable* variable, BasicBlock* block) -> Node* {
1621                 Node* identifier = indexToNode[variable->index()];
1622
1623                 // Don't create Phi nodes for dead allocations
1624                 if (!m_heapAtHead[block].isAllocation(identifier))
1625                     return nullptr;
1626
1627                 // Don't create Phi nodes until we are escaped
1628                 if (!m_heapAtHead[block].getAllocation(identifier).isEscapedAllocation())
1629                     return nullptr;
1630
1631                 Node* phiNode = m_graph.addNode(SpecHeapTop, Phi, block->at(0)->origin.withInvalidExit());
1632                 phiNode->mergeFlags(NodeResultJS);
1633                 return phiNode;
1634             });
1635
1636         // Place Phis in the right places, replace all uses of any load with the appropriate
1637         // value, and create the materialization nodes.
1638         LocalOSRAvailabilityCalculator availabilityCalculator;
1639         m_graph.clearReplacements();
1640         for (BasicBlock* block : m_graph.blocksInPreOrder()) {
1641             m_heap = m_heapAtHead[block];
1642             availabilityCalculator.beginBlock(block);
1643
1644             // These mapping tables are intended to be lazy. If
1645             // something is omitted from the table, it means that
1646             // there haven't been any local stores to the promoted
1647             // heap location (or any local materialization).
1648             m_localMapping.clear();
1649             m_escapeeToMaterialization.clear();
1650
1651             // Insert the Phi functions that we had previously
1652             // created.
1653             for (SSACalculator::Def* phiDef : m_pointerSSA.phisForBlock(block)) {
1654                 SSACalculator::Variable* variable = phiDef->variable();
1655                 m_insertionSet.insert(0, phiDef->value());
1656
1657                 PromotedHeapLocation location = indexToLocation[variable->index()];
1658                 m_localMapping.set(location, phiDef->value());
1659
1660                 if (m_sinkCandidates.contains(location.base())) {
1661                     m_insertionSet.insert(
1662                         0,
1663                         location.createHint(
1664                             m_graph, block->at(0)->origin.withInvalidExit(), phiDef->value()));
1665                 }
1666             }
1667
1668             for (SSACalculator::Def* phiDef : m_allocationSSA.phisForBlock(block)) {
1669                 SSACalculator::Variable* variable = phiDef->variable();
1670                 m_insertionSet.insert(0, phiDef->value());
1671
1672                 Node* identifier = indexToNode[variable->index()];
1673                 m_escapeeToMaterialization.add(identifier, phiDef->value());
1674                 bool canExit = false;
1675                 insertOSRHintsForUpdate(
1676                     0, block->at(0)->origin, canExit,
1677                     availabilityCalculator.m_availability, identifier, phiDef->value());
1678             }
1679
1680             if (verbose) {
1681                 dataLog("Local mapping at ", pointerDump(block), ": ", mapDump(m_localMapping), "\n");
1682                 dataLog("Local materializations at ", pointerDump(block), ": ", mapDump(m_escapeeToMaterialization), "\n");
1683             }
1684
1685             for (unsigned nodeIndex = 0; nodeIndex < block->size(); ++nodeIndex) {
1686                 Node* node = block->at(nodeIndex);
1687                 bool canExit = true;
1688                 bool nextCanExit = node->origin.exitOK;
1689                 for (PromotedHeapLocation location : m_locationsForAllocation.get(node)) {
1690                     if (location.kind() != NamedPropertyPLoc)
1691                         continue;
1692
1693                     m_localMapping.set(location, m_bottom);
1694
1695                     if (m_sinkCandidates.contains(node)) {
1696                         m_insertionSet.insert(
1697                             nodeIndex + 1,
1698                             location.createHint(
1699                                 m_graph, node->origin.takeValidExit(nextCanExit), m_bottom));
1700                     }
1701                 }
1702
1703                 for (Node* materialization : m_materializationSiteToMaterializations.get(node)) {
1704                     materialization->origin.exitOK &= canExit;
1705                     Node* escapee = m_materializationToEscapee.get(materialization);
1706                     populateMaterialization(block, materialization, escapee);
1707                     m_escapeeToMaterialization.set(escapee, materialization);
1708                     m_insertionSet.insert(nodeIndex, materialization);
1709                     if (verbose)
1710                         dataLog("Materializing ", escapee, " => ", materialization, " at ", node, "\n");
1711                 }
1712
1713                 for (PromotedHeapLocation location : m_materializationSiteToRecoveries.get(node))
1714                     m_insertionSet.insert(nodeIndex, createRecovery(block, location, node, canExit));
1715
1716                 // We need to put the OSR hints after the recoveries,
1717                 // because we only want the hints once the object is
1718                 // complete
1719                 for (Node* materialization : m_materializationSiteToMaterializations.get(node)) {
1720                     Node* escapee = m_materializationToEscapee.get(materialization);
1721                     insertOSRHintsForUpdate(
1722                         nodeIndex, node->origin, canExit,
1723                         availabilityCalculator.m_availability, escapee, materialization);
1724                 }
1725
1726                 if (node->origin.exitOK && !canExit) {
1727                     // We indicate that the exit state is fine now. It is OK because we updated the
1728                     // state above. We need to indicate this manually because the validation doesn't
1729                     // have enough information to infer that the exit state is fine.
1730                     m_insertionSet.insertNode(nodeIndex, SpecNone, ExitOK, node->origin);
1731                 }
1732
1733                 if (m_sinkCandidates.contains(node))
1734                     m_escapeeToMaterialization.set(node, node);
1735
1736                 availabilityCalculator.executeNode(node);
1737
1738                 bool desiredNextExitOK = node->origin.exitOK && !clobbersExitState(m_graph, node);
1739
1740                 bool doLower = false;
1741                 handleNode(
1742                     node,
1743                     [&] (PromotedHeapLocation location, LazyNode value) {
1744                         if (!locations.contains(location))
1745                             return;
1746
1747                         Node* nodeValue;
1748                         if (value.isNode())
1749                             nodeValue = value.asNode();
1750                         else
1751                             nodeValue = lazyMapping.get(value.asValue());
1752
1753                         nodeValue = resolve(block, nodeValue);
1754
1755                         m_localMapping.set(location, nodeValue);
1756
1757                         if (!m_sinkCandidates.contains(location.base()))
1758                             return;
1759
1760                         doLower = true;
1761
1762                         m_insertionSet.insert(
1763                             nodeIndex + 1,
1764                             location.createHint(
1765                                 m_graph, node->origin.takeValidExit(nextCanExit), nodeValue));
1766                     },
1767                     [&] (PromotedHeapLocation location) -> Node* {
1768                         return resolve(block, location);
1769                     });
1770
1771                 if (!nextCanExit && desiredNextExitOK) {
1772                     // We indicate that the exit state is fine now. We need to do this because we
1773                     // emitted hints that appear to invalidate the exit state.
1774                     m_insertionSet.insertNode(nodeIndex + 1, SpecNone, ExitOK, node->origin);
1775                 }
1776
1777                 if (m_sinkCandidates.contains(node) || doLower) {
1778                     switch (node->op()) {
1779                     case NewObject:
1780                         node->convertToPhantomNewObject();
1781                         break;
1782
1783                     case NewArrowFunction:
1784                     case NewFunction:
1785                         node->convertToPhantomNewFunction();
1786                         break;
1787
1788                     case CreateActivation:
1789                         node->convertToPhantomCreateActivation();
1790                         break;
1791
1792                     default:
1793                         node->remove();
1794                         break;
1795                     }
1796                 }
1797
1798                 m_graph.doToChildren(
1799                     node,
1800                     [&] (Edge& edge) {
1801                         edge.setNode(resolve(block, edge.node()));
1802                     });
1803             }
1804
1805             // Gotta drop some Upsilons.
1806             NodeAndIndex terminal = block->findTerminal();
1807             size_t upsilonInsertionPoint = terminal.index;
1808             NodeOrigin upsilonOrigin = terminal.node->origin;
1809             for (BasicBlock* successorBlock : block->successors()) {
1810                 for (SSACalculator::Def* phiDef : m_pointerSSA.phisForBlock(successorBlock)) {
1811                     Node* phiNode = phiDef->value();
1812                     SSACalculator::Variable* variable = phiDef->variable();
1813                     PromotedHeapLocation location = indexToLocation[variable->index()];
1814                     Node* incoming = resolve(block, location);
1815
1816                     m_insertionSet.insertNode(
1817                         upsilonInsertionPoint, SpecNone, Upsilon, upsilonOrigin,
1818                         OpInfo(phiNode), incoming->defaultEdge());
1819                 }
1820
1821                 for (SSACalculator::Def* phiDef : m_allocationSSA.phisForBlock(successorBlock)) {
1822                     Node* phiNode = phiDef->value();
1823                     SSACalculator::Variable* variable = phiDef->variable();
1824                     Node* incoming = getMaterialization(block, indexToNode[variable->index()]);
1825
1826                     m_insertionSet.insertNode(
1827                         upsilonInsertionPoint, SpecNone, Upsilon, upsilonOrigin,
1828                         OpInfo(phiNode), incoming->defaultEdge());
1829                 }
1830             }
1831
1832             m_insertionSet.execute(block);
1833         }
1834     }
1835
1836     Node* resolve(BasicBlock* block, PromotedHeapLocation location)
1837     {
1838         // If we are currently pointing to a single local allocation,
1839         // simply return the associated materialization.
1840         if (Node* identifier = m_heap.follow(location))
1841             return getMaterialization(block, identifier);
1842
1843         if (Node* result = m_localMapping.get(location))
1844             return result;
1845
1846         // This implies that there is no local mapping. Find a non-local mapping.
1847         SSACalculator::Def* def = m_pointerSSA.nonLocalReachingDef(
1848             block, m_locationToVariable.get(location));
1849         ASSERT(def);
1850         ASSERT(def->value());
1851
1852         Node* result = def->value();
1853
1854         ASSERT(!result->replacement());
1855
1856         m_localMapping.add(location, result);
1857         return result;
1858     }
1859
1860     Node* resolve(BasicBlock* block, Node* node)
1861     {
1862         // If we are currently pointing to a single local allocation,
1863         // simply return the associated materialization.
1864         if (Node* identifier = m_heap.follow(node))
1865             return getMaterialization(block, identifier);
1866
1867         if (node->replacement())
1868             node = node->replacement();
1869         ASSERT(!node->replacement());
1870
1871         return node;
1872     }
1873
1874     Node* getMaterialization(BasicBlock* block, Node* identifier)
1875     {
1876         ASSERT(m_heap.isAllocation(identifier));
1877         if (!m_sinkCandidates.contains(identifier))
1878             return identifier;
1879
1880         if (Node* materialization = m_escapeeToMaterialization.get(identifier))
1881             return materialization;
1882
1883         SSACalculator::Def* def = m_allocationSSA.nonLocalReachingDef(
1884             block, m_nodeToVariable.get(identifier));
1885         ASSERT(def && def->value());
1886         m_escapeeToMaterialization.add(identifier, def->value());
1887         ASSERT(!def->value()->replacement());
1888         return def->value();
1889     }
1890
1891     void insertOSRHintsForUpdate(unsigned nodeIndex, NodeOrigin origin, bool& canExit, AvailabilityMap& availability, Node* escapee, Node* materialization)
1892     {
1893         // We need to follow() the value in the heap.
1894         // Consider the following graph:
1895         //
1896         // Block #0
1897         //   0: NewObject({})
1898         //   1: NewObject({})
1899         //   -: PutByOffset(@0, @1, x:0)
1900         //   -: PutStructure(@0, {x:0})
1901         //   2: GetByOffset(@0, x:0)
1902         //   -: MovHint(@2, loc1)
1903         //   -: Branch(#1, #2)
1904         //
1905         // Block #1
1906         //   3: Call(f, @1)
1907         //   4: Return(@0)
1908         //
1909         // Block #2
1910         //   -: Return(undefined)
1911         //
1912         // We need to materialize @1 at @3, and when doing so we need
1913         // to insert a MovHint for the materialization into loc1 as
1914         // well.
1915         // In order to do this, we say that we need to insert an
1916         // update hint for any availability whose node resolve()s to
1917         // the materialization.
1918         for (auto entry : availability.m_heap) {
1919             if (!entry.value.hasNode())
1920                 continue;
1921             if (m_heap.follow(entry.value.node()) != escapee)
1922                 continue;
1923
1924             m_insertionSet.insert(
1925                 nodeIndex,
1926                 entry.key.createHint(m_graph, origin.takeValidExit(canExit), materialization));
1927         }
1928
1929         for (unsigned i = availability.m_locals.size(); i--;) {
1930             if (!availability.m_locals[i].hasNode())
1931                 continue;
1932             if (m_heap.follow(availability.m_locals[i].node()) != escapee)
1933                 continue;
1934
1935             int operand = availability.m_locals.operandForIndex(i);
1936             m_insertionSet.insertNode(
1937                 nodeIndex, SpecNone, MovHint, origin.takeValidExit(canExit), OpInfo(operand),
1938                 materialization->defaultEdge());
1939         }
1940     }
1941
1942     void populateMaterialization(BasicBlock* block, Node* node, Node* escapee)
1943     {
1944         Allocation& allocation = m_heap.getAllocation(escapee);
1945         switch (node->op()) {
1946         case MaterializeNewObject: {
1947             ObjectMaterializationData& data = node->objectMaterializationData();
1948             unsigned firstChild = m_graph.m_varArgChildren.size();
1949
1950             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
1951
1952             PromotedHeapLocation structure(StructurePLoc, allocation.identifier());
1953             ASSERT(locations.contains(structure));
1954
1955             m_graph.m_varArgChildren.append(Edge(resolve(block, structure), KnownCellUse));
1956
1957             for (PromotedHeapLocation location : locations) {
1958                 switch (location.kind()) {
1959                 case StructurePLoc:
1960                     ASSERT(location == structure);
1961                     break;
1962
1963                 case NamedPropertyPLoc: {
1964                     ASSERT(location.base() == allocation.identifier());
1965                     data.m_properties.append(PhantomPropertyValue(location.info()));
1966                     Node* value = resolve(block, location);
1967                     if (m_sinkCandidates.contains(value))
1968                         m_graph.m_varArgChildren.append(m_bottom);
1969                     else
1970                         m_graph.m_varArgChildren.append(value);
1971                     break;
1972                 }
1973
1974                 default:
1975                     DFG_CRASH(m_graph, node, "Bad location kind");
1976                 }
1977             }
1978
1979             node->children = AdjacencyList(
1980                 AdjacencyList::Variable,
1981                 firstChild, m_graph.m_varArgChildren.size() - firstChild);
1982             break;
1983         }
1984
1985         case MaterializeCreateActivation: {
1986             ObjectMaterializationData& data = node->objectMaterializationData();
1987
1988             unsigned firstChild = m_graph.m_varArgChildren.size();
1989
1990             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
1991
1992             PromotedHeapLocation symbolTable(ActivationSymbolTablePLoc, allocation.identifier());
1993             ASSERT(locations.contains(symbolTable));
1994             ASSERT(node->cellOperand() == resolve(block, symbolTable)->constant());
1995             m_graph.m_varArgChildren.append(Edge(resolve(block, symbolTable), KnownCellUse));
1996
1997             PromotedHeapLocation scope(ActivationScopePLoc, allocation.identifier());
1998             ASSERT(locations.contains(scope));
1999             m_graph.m_varArgChildren.append(Edge(resolve(block, scope), KnownCellUse));
2000
2001             for (PromotedHeapLocation location : locations) {
2002                 switch (location.kind()) {
2003                 case ActivationScopePLoc: {
2004                     ASSERT(location == scope);
2005                     break;
2006                 }
2007
2008                 case ActivationSymbolTablePLoc: {
2009                     ASSERT(location == symbolTable);
2010                     break;
2011                 }
2012
2013                 case ClosureVarPLoc: {
2014                     ASSERT(location.base() == allocation.identifier());
2015                     data.m_properties.append(PhantomPropertyValue(location.info()));
2016                     Node* value = resolve(block, location);
2017                     if (m_sinkCandidates.contains(value))
2018                         m_graph.m_varArgChildren.append(m_bottom);
2019                     else
2020                         m_graph.m_varArgChildren.append(value);
2021                     break;
2022                 }
2023
2024                 default:
2025                     DFG_CRASH(m_graph, node, "Bad location kind");
2026                 }
2027             }
2028
2029             node->children = AdjacencyList(
2030                 AdjacencyList::Variable,
2031                 firstChild, m_graph.m_varArgChildren.size() - firstChild);
2032             break;
2033         }
2034         
2035         case NewFunction:
2036         case NewArrowFunction: {
2037             Vector<PromotedHeapLocation> locations = m_locationsForAllocation.get(escapee);
2038             ASSERT(locations.size() == 2);
2039                 
2040             PromotedHeapLocation executable(FunctionExecutablePLoc, allocation.identifier());
2041             ASSERT_UNUSED(executable, locations.contains(executable));
2042                 
2043             PromotedHeapLocation activation(FunctionActivationPLoc, allocation.identifier());
2044             ASSERT(locations.contains(activation));
2045
2046             node->child1() = Edge(resolve(block, activation), KnownCellUse);
2047             break;
2048         }
2049
2050         default:
2051             DFG_CRASH(m_graph, node, "Bad materialize op");
2052         }
2053     }
2054
2055     Node* createRecovery(BasicBlock* block, PromotedHeapLocation location, Node* where, bool& canExit)
2056     {
2057         if (verbose)
2058             dataLog("Recovering ", location, " at ", where, "\n");
2059         ASSERT(location.base()->isPhantomAllocation());
2060         Node* base = getMaterialization(block, location.base());
2061         Node* value = resolve(block, location);
2062
2063         NodeOrigin origin = where->origin.withSemantic(base->origin.semantic);
2064
2065         if (verbose)
2066             dataLog("Base is ", base, " and value is ", value, "\n");
2067
2068         if (base->isPhantomAllocation()) {
2069             return PromotedHeapLocation(base, location.descriptor()).createHint(
2070                 m_graph, origin.takeValidExit(canExit), value);
2071         }
2072
2073         switch (location.kind()) {
2074         case NamedPropertyPLoc: {
2075             Allocation& allocation = m_heap.getAllocation(location.base());
2076
2077             Vector<Structure*> structures;
2078             structures.appendRange(allocation.structures().begin(), allocation.structures().end());
2079             unsigned identifierNumber = location.info();
2080             UniquedStringImpl* uid = m_graph.identifiers()[identifierNumber];
2081
2082             std::sort(
2083                 structures.begin(),
2084                 structures.end(),
2085                 [uid] (Structure *a, Structure* b) -> bool {
2086                     return a->getConcurrently(uid) < b->getConcurrently(uid);
2087                 });
2088
2089             PropertyOffset firstOffset = structures[0]->getConcurrently(uid);
2090
2091             if (firstOffset == structures.last()->getConcurrently(uid)) {
2092                 Node* storage = base;
2093                 // FIXME: When we decide to sink objects with a
2094                 // property storage, we should handle non-inline offsets.
2095                 RELEASE_ASSERT(isInlineOffset(firstOffset));
2096
2097                 StorageAccessData* data = m_graph.m_storageAccessData.add();
2098                 data->offset = firstOffset;
2099                 data->identifierNumber = identifierNumber;
2100
2101                 return m_graph.addNode(
2102                     SpecNone,
2103                     PutByOffset,
2104                     origin.takeValidExit(canExit),
2105                     OpInfo(data),
2106                     Edge(storage, KnownCellUse),
2107                     Edge(base, KnownCellUse),
2108                     value->defaultEdge());
2109             }
2110
2111             MultiPutByOffsetData* data = m_graph.m_multiPutByOffsetData.add();
2112             data->identifierNumber = identifierNumber;
2113
2114             {
2115                 PropertyOffset currentOffset = firstOffset;
2116                 StructureSet currentSet;
2117                 for (Structure* structure : structures) {
2118                     PropertyOffset offset = structure->getConcurrently(uid);
2119                     if (offset != currentOffset) {
2120                         // Because our analysis treats MultiPutByOffset like an escape, we only have to
2121                         // deal with storing results that would have been previously stored by PutByOffset
2122                         // nodes. Those nodes were guarded by the appropriate type checks. This means that
2123                         // at this point, we can simply trust that the incoming value has the right type
2124                         // for whatever structure we are using.
2125                         data->variants.append(
2126                             PutByIdVariant::replace(currentSet, currentOffset, InferredType::Top));
2127                         currentOffset = offset;
2128                         currentSet.clear();
2129                     }
2130                     currentSet.add(structure);
2131                 }
2132                 data->variants.append(
2133                     PutByIdVariant::replace(currentSet, currentOffset, InferredType::Top));
2134             }
2135
2136             return m_graph.addNode(
2137                 SpecNone,
2138                 MultiPutByOffset,
2139                 origin.takeValidExit(canExit),
2140                 OpInfo(data),
2141                 Edge(base, KnownCellUse),
2142                 value->defaultEdge());
2143             break;
2144         }
2145
2146         case ClosureVarPLoc: {
2147             return m_graph.addNode(
2148                 SpecNone,
2149                 PutClosureVar,
2150                 origin.takeValidExit(canExit),
2151                 OpInfo(location.info()),
2152                 Edge(base, KnownCellUse),
2153                 value->defaultEdge());
2154             break;
2155         }
2156
2157         default:
2158             DFG_CRASH(m_graph, base, "Bad location kind");
2159             break;
2160         }
2161     }
2162
2163     SSACalculator m_pointerSSA;
2164     SSACalculator m_allocationSSA;
2165     HashSet<Node*> m_sinkCandidates;
2166     HashMap<PromotedHeapLocation, SSACalculator::Variable*> m_locationToVariable;
2167     HashMap<Node*, SSACalculator::Variable*> m_nodeToVariable;
2168     HashMap<PromotedHeapLocation, Node*> m_localMapping;
2169     HashMap<Node*, Node*> m_escapeeToMaterialization;
2170     InsertionSet m_insertionSet;
2171     CombinedLiveness m_combinedLiveness;
2172
2173     HashMap<Node*, Node*> m_materializationToEscapee;
2174     HashMap<Node*, Vector<Node*>> m_materializationSiteToMaterializations;
2175     HashMap<Node*, Vector<PromotedHeapLocation>> m_materializationSiteToRecoveries;
2176
2177     HashMap<Node*, Vector<PromotedHeapLocation>> m_locationsForAllocation;
2178
2179     BlockMap<LocalHeap> m_heapAtHead;
2180     BlockMap<LocalHeap> m_heapAtTail;
2181     LocalHeap m_heap;
2182
2183     Node* m_bottom = nullptr;
2184 };
2185
2186 }
2187
2188 bool performObjectAllocationSinking(Graph& graph)
2189 {
2190     SamplingRegion samplingRegion("DFG Object Allocation Sinking Phase");
2191     return runPhase<ObjectAllocationSinkingPhase>(graph);
2192 }
2193
2194 } } // namespace JSC::DFG
2195
2196 #endif // ENABLE(DFG_JIT)