1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #ifndef SHARE_OPTO_PHASEX_HPP
26 #define SHARE_OPTO_PHASEX_HPP
27
28 #include "libadt/dict.hpp"
29 #include "libadt/vectset.hpp"
30 #include "memory/resourceArea.hpp"
31 #include "opto/memnode.hpp"
32 #include "opto/node.hpp"
33 #include "opto/phase.hpp"
34 #include "opto/type.hpp"
35 #include "utilities/globalDefinitions.hpp"
36
37 class BarrierSetC2;
38 class Compile;
39 class ConINode;
40 class ConLNode;
41 class Node;
42 class Type;
43 class PhaseTransform;
44 class PhaseGVN;
45 class PhaseIterGVN;
46 class PhaseCCP;
47 class PhasePeephole;
48 class PhaseRegAlloc;
49
50
51 //-----------------------------------------------------------------------------
52 // Expandable closed hash-table of nodes, initialized to null.
53 // Note that the constructor just zeros things
54 // Storage is reclaimed when the Arena's lifetime is over.
55 class NodeHash : public AnyObj {
56 protected:
57 Arena *_a; // Arena to allocate in
58 uint _max; // Size of table (power of 2)
59 uint _inserts; // For grow and debug, count of hash_inserts
60 uint _insert_limit; // 'grow' when _inserts reaches _insert_limit
61 Node **_table; // Hash table of Node pointers
62 Node *_sentinel; // Replaces deleted entries in hash table
63
64 public:
65 NodeHash(Arena *arena, uint est_max_size);
66 #ifdef ASSERT
67 ~NodeHash(); // Unlock all nodes upon destruction of table.
68 #endif
69 Node *hash_find(const Node*);// Find an equivalent version in hash table
70 Node *hash_find_insert(Node*);// If not in table insert else return found node
71 void hash_insert(Node*); // Insert into hash table
72 bool hash_delete(const Node*);// Replace with _sentinel in hash table
73 void check_grow() {
74 _inserts++;
75 if( _inserts == _insert_limit ) { grow(); }
76 assert( _inserts <= _insert_limit, "hash table overflow");
77 assert( _inserts < _max, "hash table overflow" );
78 }
79 static uint round_up(uint); // Round up to nearest power of 2
80 void grow(); // Grow _table to next power of 2 and rehash
81 // Return 75% of _max, rounded up.
82 uint insert_limit() const { return _max - (_max>>2); }
83
84 void clear(); // Set all entries to null, keep storage.
85 // Size of hash table
86 uint size() const { return _max; }
87 // Return Node* at index in table
88 Node *at(uint table_index) {
89 assert(table_index < _max, "Must be within table");
90 return _table[table_index];
91 }
92
93 void remove_useless_nodes(VectorSet& useful); // replace with sentinel
94 void check_no_speculative_types(); // Check no speculative part for type nodes in table
95
96 Node *sentinel() { return _sentinel; }
97
98 #ifndef PRODUCT
99 Node *find_index(uint idx); // For debugging
100 void dump(); // For debugging, dump statistics
101 uint _grows; // For debugging, count of table grow()s
102 uint _look_probes; // For debugging, count of hash probes
103 uint _lookup_hits; // For debugging, count of hash_finds
104 uint _lookup_misses; // For debugging, count of hash_finds
105 uint _insert_probes; // For debugging, count of hash probes
106 uint _delete_probes; // For debugging, count of hash probes for deletes
107 uint _delete_hits; // For debugging, count of hash probes for deletes
108 uint _delete_misses; // For debugging, count of hash probes for deletes
109 uint _total_inserts; // For debugging, total inserts into hash table
110 uint _total_insert_probes; // For debugging, total probes while inserting
111 #endif
112 NONCOPYABLE(NodeHash);
113 };
114
115
116 //-----------------------------------------------------------------------------
117 // Map dense integer indices to Types. Uses classic doubling-array trick.
118 // Abstractly provides an infinite array of Type*'s, initialized to null.
119 // Note that the constructor just zeros things, and since I use Arena
120 // allocation I do not need a destructor to reclaim storage.
121 // Despite the general name, this class is customized for use by PhaseValues.
122 class Type_Array : public AnyObj {
123 Arena *_a; // Arena to allocate in
124 uint _max;
125 const Type **_types;
126 void grow( uint i ); // Grow array node to fit
127 public:
128 Type_Array(Arena *a) : _a(a), _max(0), _types(nullptr) {}
129 const Type *operator[] ( uint i ) const // Lookup, or null for not mapped
130 { return (i<_max) ? _types[i] : (Type*)nullptr; }
131 const Type *fast_lookup(uint i) const{assert(i<_max,"oob");return _types[i];}
132 // Extend the mapping: index i maps to Type *n.
133 void map( uint i, const Type *n ) { if( i>=_max ) grow(i); _types[i] = n; }
134 uint Size() const { return _max; }
135 #ifndef PRODUCT
136 void dump() const;
137 #endif
138 void swap(Type_Array &other) {
139 if (this != &other) {
140 assert(_a == other._a, "swapping for differing arenas is probably a bad idea");
141 ::swap(_max, other._max);
142 ::swap(_types, other._types);
143 }
144 }
145 NONCOPYABLE(Type_Array);
146 };
147
148
149 //------------------------------PhaseRemoveUseless-----------------------------
150 // Remove useless nodes from GVN hash-table, worklist, and graph
151 class PhaseRemoveUseless : public Phase {
152 protected:
153 Unique_Node_List _useful; // Nodes reachable from root
154 // list is allocated from current resource area
155 public:
156 PhaseRemoveUseless(PhaseGVN* gvn, Unique_Node_List& worklist, PhaseNumber phase_num = Remove_Useless);
157
158 Unique_Node_List *get_useful() { return &_useful; }
159 };
160
161 //------------------------------PhaseRenumber----------------------------------
162 // Phase that first performs a PhaseRemoveUseless, then it renumbers compiler
163 // structures accordingly.
164 class PhaseRenumberLive : public PhaseRemoveUseless {
165 protected:
166 Type_Array _new_type_array; // Storage for the updated type information.
167 GrowableArray<int> _old2new_map;
168 Node_List _delayed;
169 bool _is_pass_finished;
170 uint _live_node_count;
171
172 int update_embedded_ids(Node* n);
173 int new_index(int old_idx);
174
175 public:
176 PhaseRenumberLive(PhaseGVN* gvn,
177 Unique_Node_List& worklist,
178 PhaseNumber phase_num = Remove_Useless_And_Renumber_Live);
179 };
180
181
182 //------------------------------PhaseTransform---------------------------------
183 // Phases that analyze, then transform. Constructing the Phase object does any
184 // global or slow analysis. The results are cached later for a fast
185 // transformation pass. When the Phase object is deleted the cached analysis
186 // results are deleted.
187 class PhaseTransform : public Phase {
188 public:
189 PhaseTransform(PhaseNumber pnum) : Phase(pnum) {
190 clear_progress();
191 #ifndef PRODUCT
192 clear_transforms();
193 set_allow_progress(true);
194 #endif
195 }
196
197 // Return a node which computes the same function as this node, but
198 // in a faster or cheaper fashion.
199 virtual Node *transform( Node *n ) = 0;
200
201 // true if CFG node d dominates CFG node n
202 virtual bool is_dominator(Node *d, Node *n) { fatal("unimplemented for this pass"); return false; };
203
204 uint64_t _count_progress; // Count transforms that make progress
205 void set_progress() { ++_count_progress; assert(allow_progress(), "No progress allowed during verification"); }
206 void clear_progress() { _count_progress = 0; }
207 uint64_t made_progress() const { return _count_progress; }
208
209 // RAII guard for speculative transforms. Restores _count_progress in the destructor
210 // unless commit() is called, so that abandoned speculative work does not count as progress.
211 // In case multiple nodes are created and only some are speculative, commit() should still be called.
212 class SpeculativeProgressGuard {
213 PhaseTransform* _phase;
214 uint64_t _saved_progress;
215 bool _committed;
216 public:
217 SpeculativeProgressGuard(PhaseTransform* phase) :
218 _phase(phase), _saved_progress(phase->made_progress()), _committed(false) {}
219 ~SpeculativeProgressGuard() {
220 if (!_committed) {
221 _phase->_count_progress = _saved_progress;
222 }
223 }
224
225 void commit() { _committed = true; }
226 };
227
228 #ifndef PRODUCT
229 uint _count_transforms; // For profiling, count transforms performed
230 void set_transforms() { ++_count_transforms; }
231 void clear_transforms() { _count_transforms = 0; }
232 uint made_transforms() const{ return _count_transforms; }
233
234 bool _allow_progress; // progress not allowed during verification pass
235 void set_allow_progress(bool allow) { _allow_progress = allow; }
236 bool allow_progress() { return _allow_progress; }
237 #endif
238 };
239
240 // Phase infrastructure required for Node::Value computations.
241 // 1) Type array, and accessor methods.
242 // 2) Constants cache, which requires access to the types.
243 // 3) NodeHash table, to find identical nodes (and remove/update the hash of a node on modification).
244 class PhaseValues : public PhaseTransform {
245 protected:
246 enum class PhaseValuesType {
247 gvn,
248 iter_gvn,
249 ccp
250 };
251
252 PhaseValuesType _phase;
253
254 // Hash table for value-numbering. Reference to "C->node_hash()",
255 NodeHash &_table;
256
257 // Type array mapping node idx to Type*. Reference to "C->types()".
258 Type_Array &_types;
259
260 // ConNode caches:
261 // Support both int and long caches because either might be an intptr_t,
262 // so they show up frequently in address computations.
263 enum { _icon_min = -1 * HeapWordSize,
264 _icon_max = 16 * HeapWordSize,
265 _lcon_min = _icon_min,
266 _lcon_max = _icon_max,
267 _zcon_max = (uint)T_CONFLICT
268 };
269 ConINode* _icons[_icon_max - _icon_min + 1]; // cached jint constant nodes
270 ConLNode* _lcons[_lcon_max - _lcon_min + 1]; // cached jlong constant nodes
271 ConNode* _zcons[_zcon_max + 1]; // cached is_zero_type nodes
272 void init_con_caches();
273
274 public:
275 PhaseValues() : PhaseTransform(GVN), _phase(PhaseValuesType::gvn),
276 _table(*C->node_hash()), _types(*C->types())
277 {
278 NOT_PRODUCT( clear_new_values(); )
279 // Force allocation for currently existing nodes
280 _types.map(C->unique(), nullptr);
281 init_con_caches();
282 }
283 NOT_PRODUCT(~PhaseValues();)
284 PhaseIterGVN* is_IterGVN();
285
286 // Some Ideal and other transforms delete --> modify --> insert values
287 bool hash_delete(Node* n) { return _table.hash_delete(n); }
288 void hash_insert(Node* n) { _table.hash_insert(n); }
289 Node* hash_find_insert(Node* n){ return _table.hash_find_insert(n); }
290 Node* hash_find(const Node* n) { return _table.hash_find(n); }
291
292 // Used after parsing to eliminate values that are no longer in program
293 void remove_useless_nodes(VectorSet &useful) {
294 _table.remove_useless_nodes(useful);
295 // this may invalidate cached cons so reset the cache
296 init_con_caches();
297 }
298
299 Type_Array& types() {
300 return _types;
301 }
302
303 // Get a previously recorded type for the node n.
304 // This type must already have been recorded.
305 // If you want the type of a very new (untransformed) node,
306 // you must use type_or_null, and test the result for null.
307 const Type* type(const Node* n) const {
308 assert(n != nullptr, "must not be null");
309 const Type* t = _types.fast_lookup(n->_idx);
310 assert(t != nullptr, "must set before get");
311 return t;
312 }
313 // Get a previously recorded type for the node n,
314 // or else return null if there is none.
315 const Type* type_or_null(const Node* n) const {
316 return _types.fast_lookup(n->_idx);
317 }
318 // Record a type for a node.
319 void set_type(const Node* n, const Type *t) {
320 assert(t != nullptr, "type must not be null");
321 _types.map(n->_idx, t);
322 }
323 void clear_type(const Node* n) {
324 if (n->_idx < _types.Size()) {
325 _types.map(n->_idx, nullptr);
326 }
327 }
328 // Record an initial type for a node, the node's bottom type.
329 void set_type_bottom(const Node* n) {
330 // Use this for initialization when bottom_type() (or better) is not handy.
331 // Usually the initialization should be to n->Value(this) instead,
332 // or a hand-optimized value like Type::MEMORY or Type::CONTROL.
333 assert(_types[n->_idx] == nullptr, "must set the initial type just once");
334 _types.map(n->_idx, n->bottom_type());
335 }
336 // Make sure the types array is big enough to record a size for the node n.
337 // (In product builds, we never want to do range checks on the types array!)
338 void ensure_type_or_null(const Node* n) {
339 if (n->_idx >= _types.Size())
340 _types.map(n->_idx, nullptr); // Grow the types array as needed.
341 }
342
343 // Utility functions:
344 const TypeInt* find_int_type( Node* n);
345 const TypeLong* find_long_type(Node* n);
346 jint find_int_con( Node* n, jint value_if_unknown) {
347 const TypeInt* t = find_int_type(n);
348 return (t != nullptr && t->is_con()) ? t->get_con() : value_if_unknown;
349 }
350 jlong find_long_con(Node* n, jlong value_if_unknown) {
351 const TypeLong* t = find_long_type(n);
352 return (t != nullptr && t->is_con()) ? t->get_con() : value_if_unknown;
353 }
354
355 // Make an idealized constant, i.e., one of ConINode, ConPNode, ConFNode, etc.
356 // Same as transform(ConNode::make(t)).
357 ConNode* makecon(const Type* t);
358 ConNode* uncached_makecon(const Type* t);
359
360 // Fast int or long constant. Same as TypeInt::make(i) or TypeLong::make(l).
361 ConINode* intcon(jint i);
362 ConLNode* longcon(jlong l);
363 ConNode* integercon(jlong l, BasicType bt);
364
365 // Fast zero or null constant. Same as makecon(Type::get_zero_type(bt)).
366 ConNode* zerocon(BasicType bt);
367
368 // For pessimistic passes, the return type must monotonically narrow.
369 // For optimistic passes, the return type must monotonically widen.
370 // It is possible to get into a "death march" in either type of pass,
371 // where the types are continually moving but it will take 2**31 or
372 // more steps to converge. This doesn't happen on most normal loops.
373 //
374 // Here is an example of a deadly loop for an optimistic pass, along
375 // with a partial trace of inferred types:
376 // x = phi(0,x'); L: x' = x+1; if (x' >= 0) goto L;
377 // 0 1 join([0..max], 1)
378 // [0..1] [1..2] join([0..max], [1..2])
379 // [0..2] [1..3] join([0..max], [1..3])
380 // ... ... ...
381 // [0..max] [min]u[1..max] join([0..max], [min..max])
382 // [0..max] ==> fixpoint
383 // We would have proven, the hard way, that the iteration space is all
384 // non-negative ints, with the loop terminating due to 32-bit overflow.
385 //
386 // Here is the corresponding example for a pessimistic pass:
387 // x = phi(0,x'); L: x' = x-1; if (x' >= 0) goto L;
388 // int int join([0..max], int)
389 // [0..max] [-1..max-1] join([0..max], [-1..max-1])
390 // [0..max-1] [-1..max-2] join([0..max], [-1..max-2])
391 // ... ... ...
392 // [0..1] [-1..0] join([0..max], [-1..0])
393 // 0 -1 join([0..max], -1)
394 // 0 == fixpoint
395 // We would have proven, the hard way, that the iteration space is {0}.
396 // (Usually, other optimizations will make the "if (x >= 0)" fold up
397 // before we get into trouble. But not always.)
398 //
399 // It's a pleasant thing to observe that the pessimistic pass
400 // will make short work of the optimistic pass's deadly loop,
401 // and vice versa. That is a good example of the complementary
402 // purposes of the CCP (optimistic) vs. GVN (pessimistic) phases.
403 //
404 // In any case, only widen or narrow a few times before going to the
405 // correct flavor of top or bottom.
406 //
407 // This call only needs to be made once as the data flows around any
408 // given cycle. We do it at Phis, and nowhere else.
409 // The types presented are the new type of a phi (computed by PhiNode::Value)
410 // and the previously computed type, last time the phi was visited.
411 //
412 // The third argument is upper limit for the saturated value,
413 // if the phase wishes to widen the new_type.
414 // If the phase is narrowing, the old type provides a lower limit.
415 // Caller guarantees that old_type and new_type are no higher than limit_type.
416 virtual const Type* saturate(const Type* new_type,
417 const Type* old_type,
418 const Type* limit_type) const {
419 return new_type;
420 }
421 virtual const Type* saturate_and_maybe_push_to_igvn_worklist(const TypeNode* n, const Type* new_type) {
422 return saturate(new_type, type_or_null(n), n->type());
423 }
424
425 #ifndef PRODUCT
426 uint _count_new_values; // For profiling, count new values produced
427 void inc_new_values() { ++_count_new_values; }
428 void clear_new_values() { _count_new_values = 0; }
429 uint made_new_values() const { return _count_new_values; }
430 #endif
431 };
432
433
434 //------------------------------PhaseGVN---------------------------------------
435 // Phase for performing local, pessimistic GVN-style optimizations.
436 class PhaseGVN : public PhaseValues {
437 protected:
438 bool is_dominator_helper(Node *d, Node *n, bool linear_only);
439
440 public:
441 // Return a node which computes the same function as this node, but
442 // in a faster or cheaper fashion.
443 Node* transform(Node* n);
444
445 virtual void record_for_igvn(Node *n) {
446 C->record_for_igvn(n);
447 }
448
449 bool is_dominator(Node *d, Node *n) { return is_dominator_helper(d, n, true); }
450
451 // Helper to call Node::Ideal() and BarrierSetC2::ideal_node().
452 Node* apply_ideal(Node* i, bool can_reshape);
453
454 #ifdef ASSERT
455 void dump_infinite_loop_info(Node* n, const char* where);
456 // Check for a simple dead loop when a data node references itself.
457 void dead_loop_check(Node *n);
458 #endif
459 };
460
461 //------------------------------PhaseIterGVN-----------------------------------
462 // Phase for iteratively performing local, pessimistic GVN-style optimizations.
463 // and ideal transformations on the graph.
464 class PhaseIterGVN : public PhaseGVN {
465 private:
466 bool _delay_transform; // When true simply register the node when calling transform
467 // instead of actually optimizing it
468 DEBUG_ONLY(uint _num_processed;) // Running count for trace_PhaseIterGVN_verbose
469
470 // Idealize old Node 'n' with respect to its inputs and its value
471 virtual Node *transform_old( Node *a_node );
472
473 // Drain the IGVN worklist: process nodes until the worklist is empty.
474 // Returns true if compilation was aborted (node limit or infinite loop),
475 // false on normal completion.
476 bool drain_worklist();
477
478 // Walk all live nodes and push deep-inspection candidates to _worklist.
479 void push_deep_revisit_candidates();
480
481 // After the main worklist drains, re-process deep-inspection nodes to
482 // catch optimization opportunities from far-away changes. Repeats until
483 // convergence (no progress made) or max rounds reached.
484 // Returns true if converged.
485 bool deep_revisit();
486
487 // Returns true for nodes that inspect the graph beyond their direct
488 // inputs, and therefore may miss optimization opportunities when
489 // changes happen far away.
490 bool needs_deep_revisit(const Node* n) const;
491
492 // Subsume users of node 'old' into node 'nn'
493 void subsume_node( Node *old, Node *nn );
494
495 protected:
496 // Shuffle worklist, for stress testing
497 void shuffle_worklist();
498
499 virtual const Type* saturate(const Type* new_type, const Type* old_type,
500 const Type* limit_type) const;
501 // Usually returns new_type. Returns old_type if new_type is only a slight
502 // improvement, such that it would take many (>>10) steps to reach 2**32.
503
504 public:
505
506 PhaseIterGVN(PhaseIterGVN* igvn); // Used by CCP constructor
507 PhaseIterGVN();
508
509 // Reset IGVN: call deconstructor, and placement new.
510 void reset() {
511 this->~PhaseIterGVN();
512 ::new (static_cast<void*>(this)) PhaseIterGVN();
513 }
514
515 // Reset IGVN with another: call deconstructor, and placement new.
516 // Achieves the same as the following (but without move constructors):
517 // igvn = PhaseIterGVN(other);
518 void reset_from_igvn(PhaseIterGVN* other) {
519 if (this != other) {
520 this->~PhaseIterGVN();
521 ::new (static_cast<void*>(this)) PhaseIterGVN(other);
522 }
523 }
524
525 // Idealize new Node 'n' with respect to its inputs and its value
526 virtual Node *transform( Node *a_node );
527 virtual void record_for_igvn(Node *n) { _worklist.push(n); }
528
529 // Iterative worklist. Reference to "C->igvn_worklist()".
530 Unique_Node_List &_worklist;
531
532 // Given def-use info and an initial worklist, apply Node::Ideal,
533 // Node::Value, Node::Identity, hash-based value numbering, Node::Ideal_DU
534 // and dominator info to a fixed point.
535 // When deep is true, after the main worklist drains, re-process
536 // nodes that inspect the graph deeply (Load, CmpP, If, RangeCheck,
537 // CountedLoopEnd, LongCountedLoopEnd) to catch optimization opportunities
538 // from changes far away that the normal notification mechanism misses.
539 void optimize(bool deep = false);
540
541 #ifdef ASSERT
542 void verify_optimize(bool deep_revisit_converged);
543 void verify_Value_for(const Node* n, bool strict = false);
544 void verify_Ideal_for(Node* n, bool can_reshape, bool deep_revisit_converged);
545 void verify_Identity_for(Node* n);
546 void verify_node_invariants_for(const Node* n);
547 void verify_empty_worklist(Node* n);
548 #endif
549
550 #ifndef PRODUCT
551 void trace_PhaseIterGVN(Node* n, Node* nn, const Type* old_type);
552 void init_verifyPhaseIterGVN();
553 void verify_PhaseIterGVN(bool deep_revisit_converged);
554 #endif
555
556 #ifdef ASSERT
557 void dump_infinite_loop_info(Node* n, const char* where);
558 void trace_PhaseIterGVN_verbose(Node* n, int num_processed);
559 #endif
560
561 // Register a new node with the iter GVN pass without transforming it.
562 // Used when we need to restructure a Region/Phi area and all the Regions
563 // and Phis need to complete this one big transform before any other
564 // transforms can be triggered on the region.
565 // Optional 'orig' is an earlier version of this node.
566 // It is significant only for debugging and profiling.
567 Node* register_new_node_with_optimizer(Node* n, Node* orig = nullptr);
568
569 // Origin of a dead node, describing why it is dying.
570 // Speculative: a temporarily created node that was never part of the graph
571 // (e.g., a speculative clone in split_if to test constant foldability).
572 // Its death does not count as progress for convergence tracking.
573 enum class NodeOrigin { Graph, Speculative };
574
575 // Kill a globally dead Node. All uses are also globally dead and are
576 // aggressively trimmed.
577 void remove_globally_dead_node(Node* dead, NodeOrigin origin);
578
579 // Kill all inputs to a dead node, recursively making more dead nodes.
580 // The Node must be dead locally, i.e., have no uses.
581 void remove_dead_node(Node* dead, NodeOrigin origin) {
582 assert(dead->outcnt() == 0 && !dead->is_top(), "node must be dead");
583 remove_globally_dead_node(dead, origin);
584 }
585
586 // Add users of 'n' to worklist
587 static void add_users_to_worklist0(Node* n, Unique_Node_List& worklist);
588
589 // Add one or more users of 'use' to the worklist if it appears that a
590 // known optimization could be applied to those users.
591 // Node 'n' is a node that was modified or is about to get replaced,
592 // and 'use' is one use of 'n'.
593 // Certain optimizations have dependencies that extend beyond a node's
594 // direct inputs, so it is necessary to ensure the appropriate
595 // notifications are made here.
596 static void add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_List& worklist);
597
598 // Add users of 'n', and any other nodes that could be directly
599 // affected by changes to 'n', to the worklist.
600 // Node 'n' may be a node that is about to get replaced. In this
601 // case, 'n' should not be considered part of the new graph.
602 // Passing the old node (as 'n'), rather than the new node,
603 // prevents unnecessary notifications when the new node already
604 // has other users.
605 void add_users_to_worklist(Node* n);
606
607 // Replace old node with new one.
608 void replace_node( Node *old, Node *nn ) {
609 add_users_to_worklist(old);
610 hash_delete(old); // Yank from hash before hacking edges
611 subsume_node(old, nn);
612 }
613
614 void replace_in_uses(Node* n, Node* m);
615
616 // Delayed node rehash: remove a node from the hash table and rehash it during
617 // next optimizing pass
618 void rehash_node_delayed(Node* n) {
619 hash_delete(n);
620 _worklist.push(n);
621 }
622
623 // Replace ith edge of "n" with "in"
624 void replace_input_of(Node* n, uint i, Node* in) {
625 rehash_node_delayed(n);
626 n->set_req_X(i, in, this);
627 }
628
629 // Add "in" as input (req) of "n"
630 void add_input_to(Node* n, Node* in) {
631 rehash_node_delayed(n);
632 n->add_req(in);
633 }
634
635 // Delete ith edge of "n"
636 void delete_input_of(Node* n, uint i) {
637 rehash_node_delayed(n);
638 n->del_req(i);
639 }
640
641 // Delete precedence edge i of "n"
642 void delete_precedence_of(Node* n, uint i) {
643 rehash_node_delayed(n);
644 n->rm_prec(i);
645 }
646
647 bool delay_transform() const { return _delay_transform; }
648
649 void set_delay_transform(bool delay) {
650 _delay_transform = delay;
651 }
652
653 void remove_speculative_types();
654 void check_no_speculative_types() {
655 _table.check_no_speculative_types();
656 }
657
658 bool is_dominator(Node *d, Node *n) { return is_dominator_helper(d, n, false); }
659
660 #ifndef PRODUCT
661 static bool is_verify_def_use() {
662 // '-XX:VerifyIterativeGVN=1'
663 return (VerifyIterativeGVN % 10) == 1;
664 }
665 static bool is_verify_Value() {
666 // '-XX:VerifyIterativeGVN=10'
667 return ((VerifyIterativeGVN % 100) / 10) == 1;
668 }
669 static bool is_verify_Ideal() {
670 // '-XX:VerifyIterativeGVN=100'
671 return ((VerifyIterativeGVN % 1000) / 100) == 1;
672 }
673 static bool is_verify_Identity() {
674 // '-XX:VerifyIterativeGVN=1000'
675 return ((VerifyIterativeGVN % 10000) / 1000) == 1;
676 }
677 static bool is_verify_invariants() {
678 // '-XX:VerifyIterativeGVN=10000'
679 return ((VerifyIterativeGVN % 100000) / 10000) == 1;
680 }
681 static bool is_verify_Ideal_return() {
682 // '-XX:VerifyIterativeGVN=100000'
683 return ((VerifyIterativeGVN % 1000000) / 100000) == 1;
684 }
685 protected:
686 // Sub-quadratic implementation of '-XX:VerifyIterativeGVN=1' (Use-Def verification).
687 julong _verify_counter;
688 julong _verify_full_passes;
689 enum { _verify_window_size = 30 };
690 Node* _verify_window[_verify_window_size];
691 void verify_step(Node* n);
692 #endif
693 };
694
695 //------------------------------PhaseCCP---------------------------------------
696 // Phase for performing global Conditional Constant Propagation.
697 // Should be replaced with combined CCP & GVN someday.
698 class PhaseCCP : public PhaseIterGVN {
699 Unique_Node_List _root_and_safepoints;
700 Unique_Node_List _maybe_top_type_nodes;
701 // Non-recursive. Use analysis to transform single Node.
702 virtual Node* transform_once(Node* n);
703
704 Node* fetch_next_node(Unique_Node_List& worklist);
705 static void dump_type_and_node(const Node* n, const Type* t) PRODUCT_RETURN;
706
707 bool not_bottom_type(Node* n) const;
708 void push_child_nodes_to_worklist(Unique_Node_List& worklist, Node* n) const;
709 void push_if_not_bottom_type(Unique_Node_List& worklist, Node* n) const;
710 void push_more_uses(Unique_Node_List& worklist, Node* parent, const Node* use) const;
711 void push_phis(Unique_Node_List& worklist, const Node* use) const;
712 static void push_catch(Unique_Node_List& worklist, const Node* use);
713 void push_cmpu(Unique_Node_List& worklist, const Node* use) const;
714 static void push_counted_loop_phi(Unique_Node_List& worklist, Node* parent, const Node* use);
715 static void push_cast(Unique_Node_List& worklist, const Node* use);
716 void push_loadp(Unique_Node_List& worklist, const Node* use) const;
717 static void push_load_barrier(Unique_Node_List& worklist, const BarrierSetC2* barrier_set, const Node* use);
718 void push_and(Unique_Node_List& worklist, const Node* parent, const Node* use) const;
719 void push_cast_ii(Unique_Node_List& worklist, const Node* parent, const Node* use) const;
720 void push_opaque_zero_trip_guard(Unique_Node_List& worklist, const Node* use) const;
721 void push_bool_with_cmpu_and_mask(Unique_Node_List& worklist, const Node* use) const;
722 void push_bool_matching_case1b(Unique_Node_List& worklist, const Node* cmpu) const;
723
724 public:
725 PhaseCCP( PhaseIterGVN *igvn ); // Compute conditional constants
726 NOT_PRODUCT( ~PhaseCCP(); )
727
728 // Worklist algorithm identifies constants
729 void analyze();
730 void analyze_step(Unique_Node_List& worklist, Node* n);
731 bool needs_revisit(Node* n) const;
732 #ifdef ASSERT
733 void verify_type(Node* n, const Type* tnew, const Type* told);
734 // For every node n on verify list, check if type(n) == n->Value()
735 void verify_analyze(Unique_Node_List& worklist_verify);
736 #endif
737 // Recursive traversal of program. Used analysis to modify program.
738 virtual Node *transform( Node *n );
739 // Do any transformation after analysis
740 void do_transform();
741
742 virtual const Type* saturate(const Type* new_type, const Type* old_type,
743 const Type* limit_type) const;
744 // Returns new_type->widen(old_type), which increments the widen bits until
745 // giving up with TypeInt::INT or TypeLong::LONG.
746 // Result is clipped to limit_type if necessary.
747 virtual const Type* saturate_and_maybe_push_to_igvn_worklist(const TypeNode* n, const Type* new_type) {
748 const Type* t = saturate(new_type, type_or_null(n), n->type());
749 if (t != new_type) {
750 // Type was widened in CCP, but IGVN may be able to make it narrower.
751 _worklist.push((Node*)n);
752 }
753 return t;
754 }
755
756 #ifndef PRODUCT
757 static uint _total_invokes; // For profiling, count invocations
758 void inc_invokes() { ++PhaseCCP::_total_invokes; }
759
760 static uint _total_constants; // For profiling, count constants found
761 uint _count_constants;
762 void clear_constants() { _count_constants = 0; }
763 void inc_constants() { ++_count_constants; }
764 uint count_constants() const { return _count_constants; }
765
766 static void print_statistics();
767 #endif
768 };
769
770
771 //------------------------------PhasePeephole----------------------------------
772 // Phase for performing peephole optimizations on register allocated basic blocks.
773 class PhasePeephole : public PhaseTransform {
774 PhaseRegAlloc *_regalloc;
775 PhaseCFG &_cfg;
776 // Recursive traversal of program. Pure function is unused in this phase
777 virtual Node *transform( Node *n );
778
779 public:
780 PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg );
781 NOT_PRODUCT( ~PhasePeephole(); )
782
783 // Do any transformation after analysis
784 void do_transform();
785
786 #ifndef PRODUCT
787 static uint _total_peepholes; // For profiling, count peephole rules applied
788 uint _count_peepholes;
789 void clear_peepholes() { _count_peepholes = 0; }
790 void inc_peepholes() { ++_count_peepholes; }
791 uint count_peepholes() const { return _count_peepholes; }
792
793 static void print_statistics();
794 #endif
795 };
796
797 #endif // SHARE_OPTO_PHASEX_HPP