1 /*
  2  * Copyright (c) 1997, 2025, 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 #ifndef PRODUCT
191     clear_progress();
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 #ifndef PRODUCT
205   uint   _count_progress;       // For profiling, count transforms that make progress
206   void   set_progress()        { ++_count_progress; assert( allow_progress(),"No progress allowed during verification"); }
207   void   clear_progress()      { _count_progress = 0; }
208   uint   made_progress() const { return _count_progress; }
209 
210   uint   _count_transforms;     // For profiling, count transforms performed
211   void   set_transforms()      { ++_count_transforms; }
212   void   clear_transforms()    { _count_transforms = 0; }
213   uint   made_transforms() const{ return _count_transforms; }
214 
215   bool   _allow_progress;      // progress not allowed during verification pass
216   void   set_allow_progress(bool allow) { _allow_progress = allow; }
217   bool   allow_progress()               { return _allow_progress; }
218 #endif
219 };
220 
221 // Phase infrastructure required for Node::Value computations.
222 // 1) Type array, and accessor methods.
223 // 2) Constants cache, which requires access to the types.
224 // 3) NodeHash table, to find identical nodes (and remove/update the hash of a node on modification).
225 class PhaseValues : public PhaseTransform {
226 protected:
227   enum class PhaseValuesType {
228     gvn,
229     iter_gvn,
230     ccp
231   };
232 
233   PhaseValuesType _phase;
234 
235   // Hash table for value-numbering. Reference to "C->node_hash()",
236   NodeHash &_table;
237 
238   // Type array mapping node idx to Type*. Reference to "C->types()".
239   Type_Array &_types;
240 
241   // ConNode caches:
242   // Support both int and long caches because either might be an intptr_t,
243   // so they show up frequently in address computations.
244   enum { _icon_min = -1 * HeapWordSize,
245          _icon_max = 16 * HeapWordSize,
246          _lcon_min = _icon_min,
247          _lcon_max = _icon_max,
248          _zcon_max = (uint)T_CONFLICT
249   };
250   ConINode* _icons[_icon_max - _icon_min + 1];   // cached jint constant nodes
251   ConLNode* _lcons[_lcon_max - _lcon_min + 1];   // cached jlong constant nodes
252   ConNode*  _zcons[_zcon_max + 1];               // cached is_zero_type nodes
253   void init_con_caches();
254 
255 public:
256   PhaseValues() : PhaseTransform(GVN), _phase(PhaseValuesType::gvn),
257                   _table(*C->node_hash()), _types(*C->types())
258   {
259     NOT_PRODUCT( clear_new_values(); )
260     // Force allocation for currently existing nodes
261     _types.map(C->unique(), nullptr);
262     init_con_caches();
263   }
264   NOT_PRODUCT(~PhaseValues();)
265   PhaseIterGVN* is_IterGVN();
266 
267   // Some Ideal and other transforms delete --> modify --> insert values
268   bool   hash_delete(Node* n)     { return _table.hash_delete(n); }
269   void   hash_insert(Node* n)     { _table.hash_insert(n); }
270   Node*  hash_find_insert(Node* n){ return _table.hash_find_insert(n); }
271   Node*  hash_find(const Node* n) { return _table.hash_find(n); }
272 
273   // Used after parsing to eliminate values that are no longer in program
274   void   remove_useless_nodes(VectorSet &useful) {
275     _table.remove_useless_nodes(useful);
276     // this may invalidate cached cons so reset the cache
277     init_con_caches();
278   }
279 
280   Type_Array& types() {
281     return _types;
282   }
283 
284   // Get a previously recorded type for the node n.
285   // This type must already have been recorded.
286   // If you want the type of a very new (untransformed) node,
287   // you must use type_or_null, and test the result for null.
288   const Type* type(const Node* n) const {
289     assert(n != nullptr, "must not be null");
290     const Type* t = _types.fast_lookup(n->_idx);
291     assert(t != nullptr, "must set before get");
292     return t;
293   }
294   // Get a previously recorded type for the node n,
295   // or else return null if there is none.
296   const Type* type_or_null(const Node* n) const {
297     return _types.fast_lookup(n->_idx);
298   }
299   // Record a type for a node.
300   void    set_type(const Node* n, const Type *t) {
301     assert(t != nullptr, "type must not be null");
302     _types.map(n->_idx, t);
303   }
304   void    clear_type(const Node* n) {
305     if (n->_idx < _types.Size()) {
306       _types.map(n->_idx, nullptr);
307     }
308   }
309   // Record an initial type for a node, the node's bottom type.
310   void    set_type_bottom(const Node* n) {
311     // Use this for initialization when bottom_type() (or better) is not handy.
312     // Usually the initialization should be to n->Value(this) instead,
313     // or a hand-optimized value like Type::MEMORY or Type::CONTROL.
314     assert(_types[n->_idx] == nullptr, "must set the initial type just once");
315     _types.map(n->_idx, n->bottom_type());
316   }
317   // Make sure the types array is big enough to record a size for the node n.
318   // (In product builds, we never want to do range checks on the types array!)
319   void ensure_type_or_null(const Node* n) {
320     if (n->_idx >= _types.Size())
321       _types.map(n->_idx, nullptr);   // Grow the types array as needed.
322   }
323 
324   // Utility functions:
325   const TypeInt*  find_int_type( Node* n);
326   const TypeLong* find_long_type(Node* n);
327   jint  find_int_con( Node* n, jint  value_if_unknown) {
328     const TypeInt* t = find_int_type(n);
329     return (t != nullptr && t->is_con()) ? t->get_con() : value_if_unknown;
330   }
331   jlong find_long_con(Node* n, jlong value_if_unknown) {
332     const TypeLong* t = find_long_type(n);
333     return (t != nullptr && t->is_con()) ? t->get_con() : value_if_unknown;
334   }
335 
336   // Make an idealized constant, i.e., one of ConINode, ConPNode, ConFNode, etc.
337   // Same as transform(ConNode::make(t)).
338   ConNode* makecon(const Type* t);
339   ConNode* uncached_makecon(const Type* t);
340 
341   // Fast int or long constant.  Same as TypeInt::make(i) or TypeLong::make(l).
342   ConINode* intcon(jint i);
343   ConLNode* longcon(jlong l);
344   ConNode* integercon(jlong l, BasicType bt);
345 
346   // Fast zero or null constant.  Same as makecon(Type::get_zero_type(bt)).
347   ConNode* zerocon(BasicType bt);
348 
349   // For pessimistic passes, the return type must monotonically narrow.
350   // For optimistic  passes, the return type must monotonically widen.
351   // It is possible to get into a "death march" in either type of pass,
352   // where the types are continually moving but it will take 2**31 or
353   // more steps to converge.  This doesn't happen on most normal loops.
354   //
355   // Here is an example of a deadly loop for an optimistic pass, along
356   // with a partial trace of inferred types:
357   //    x = phi(0,x'); L: x' = x+1; if (x' >= 0) goto L;
358   //    0                 1                join([0..max], 1)
359   //    [0..1]            [1..2]           join([0..max], [1..2])
360   //    [0..2]            [1..3]           join([0..max], [1..3])
361   //      ... ... ...
362   //    [0..max]          [min]u[1..max]   join([0..max], [min..max])
363   //    [0..max] ==> fixpoint
364   // We would have proven, the hard way, that the iteration space is all
365   // non-negative ints, with the loop terminating due to 32-bit overflow.
366   //
367   // Here is the corresponding example for a pessimistic pass:
368   //    x = phi(0,x'); L: x' = x-1; if (x' >= 0) goto L;
369   //    int               int              join([0..max], int)
370   //    [0..max]          [-1..max-1]      join([0..max], [-1..max-1])
371   //    [0..max-1]        [-1..max-2]      join([0..max], [-1..max-2])
372   //      ... ... ...
373   //    [0..1]            [-1..0]          join([0..max], [-1..0])
374   //    0                 -1               join([0..max], -1)
375   //    0 == fixpoint
376   // We would have proven, the hard way, that the iteration space is {0}.
377   // (Usually, other optimizations will make the "if (x >= 0)" fold up
378   // before we get into trouble.  But not always.)
379   //
380   // It's a pleasant thing to observe that the pessimistic pass
381   // will make short work of the optimistic pass's deadly loop,
382   // and vice versa.  That is a good example of the complementary
383   // purposes of the CCP (optimistic) vs. GVN (pessimistic) phases.
384   //
385   // In any case, only widen or narrow a few times before going to the
386   // correct flavor of top or bottom.
387   //
388   // This call only needs to be made once as the data flows around any
389   // given cycle.  We do it at Phis, and nowhere else.
390   // The types presented are the new type of a phi (computed by PhiNode::Value)
391   // and the previously computed type, last time the phi was visited.
392   //
393   // The third argument is upper limit for the saturated value,
394   // if the phase wishes to widen the new_type.
395   // If the phase is narrowing, the old type provides a lower limit.
396   // Caller guarantees that old_type and new_type are no higher than limit_type.
397   virtual const Type* saturate(const Type* new_type,
398                                const Type* old_type,
399                                const Type* limit_type) const {
400     return new_type;
401   }
402   virtual const Type* saturate_and_maybe_push_to_igvn_worklist(const TypeNode* n, const Type* new_type) {
403     return saturate(new_type, type_or_null(n), n->type());
404   }
405 
406 #ifndef PRODUCT
407   uint   _count_new_values;     // For profiling, count new values produced
408   void    inc_new_values()        { ++_count_new_values; }
409   void    clear_new_values()      { _count_new_values = 0; }
410   uint    made_new_values() const { return _count_new_values; }
411 #endif
412 };
413 
414 
415 //------------------------------PhaseGVN---------------------------------------
416 // Phase for performing local, pessimistic GVN-style optimizations.
417 class PhaseGVN : public PhaseValues {
418 protected:
419   bool is_dominator_helper(Node *d, Node *n, bool linear_only);
420 
421 public:
422   // Return a node which computes the same function as this node, but
423   // in a faster or cheaper fashion.
424   Node* transform(Node* n);
425 
426   virtual void record_for_igvn(Node *n) {
427     C->record_for_igvn(n);
428   }
429 
430   bool is_dominator(Node *d, Node *n) { return is_dominator_helper(d, n, true); }
431 
432   // Helper to call Node::Ideal() and BarrierSetC2::ideal_node().
433   Node* apply_ideal(Node* i, bool can_reshape);
434 
435 #ifdef ASSERT
436   void dump_infinite_loop_info(Node* n, const char* where);
437   // Check for a simple dead loop when a data node references itself.
438   void dead_loop_check(Node *n);
439 #endif
440 };
441 
442 //------------------------------PhaseIterGVN-----------------------------------
443 // Phase for iteratively performing local, pessimistic GVN-style optimizations.
444 // and ideal transformations on the graph.
445 class PhaseIterGVN : public PhaseGVN {
446 private:
447   bool _delay_transform;  // When true simply register the node when calling transform
448                           // instead of actually optimizing it
449 
450   // Idealize old Node 'n' with respect to its inputs and its value
451   virtual Node *transform_old( Node *a_node );
452 
453   // Subsume users of node 'old' into node 'nn'
454   void subsume_node( Node *old, Node *nn );
455 
456 protected:
457   // Shuffle worklist, for stress testing
458   void shuffle_worklist();
459 
460   virtual const Type* saturate(const Type* new_type, const Type* old_type,
461                                const Type* limit_type) const;
462   // Usually returns new_type.  Returns old_type if new_type is only a slight
463   // improvement, such that it would take many (>>10) steps to reach 2**32.
464 
465 public:
466 
467   PhaseIterGVN(PhaseIterGVN* igvn); // Used by CCP constructor
468   PhaseIterGVN();
469 
470   // Reset IGVN: call deconstructor, and placement new.
471   void reset() {
472     this->~PhaseIterGVN();
473     ::new (static_cast<void*>(this)) PhaseIterGVN();
474   }
475 
476   // Reset IGVN with another: call deconstructor, and placement new.
477   // Achieves the same as the following (but without move constructors):
478   // igvn = PhaseIterGVN(other);
479   void reset_from_igvn(PhaseIterGVN* other) {
480     if (this != other) {
481       this->~PhaseIterGVN();
482       ::new (static_cast<void*>(this)) PhaseIterGVN(other);
483     }
484   }
485 
486   // Idealize new Node 'n' with respect to its inputs and its value
487   virtual Node *transform( Node *a_node );
488   virtual void record_for_igvn(Node *n) { }
489 
490   // Iterative worklist. Reference to "C->igvn_worklist()".
491   Unique_Node_List &_worklist;
492 
493   // Given def-use info and an initial worklist, apply Node::Ideal,
494   // Node::Value, Node::Identity, hash-based value numbering, Node::Ideal_DU
495   // and dominator info to a fixed point.
496   void optimize();
497 #ifdef ASSERT
498   void verify_optimize();
499   void verify_Value_for(const Node* n, bool strict = false);
500   void verify_Ideal_for(Node* n, bool can_reshape);
501   void verify_Identity_for(Node* n);
502   void verify_node_invariants_for(const Node* n);
503   void verify_empty_worklist(Node* n);
504 #endif
505 
506 #ifndef PRODUCT
507   void trace_PhaseIterGVN(Node* n, Node* nn, const Type* old_type);
508   void init_verifyPhaseIterGVN();
509   void verify_PhaseIterGVN();
510 #endif
511 
512 #ifdef ASSERT
513   void dump_infinite_loop_info(Node* n, const char* where);
514   void trace_PhaseIterGVN_verbose(Node* n, int num_processed);
515 #endif
516 
517   // Register a new node with the iter GVN pass without transforming it.
518   // Used when we need to restructure a Region/Phi area and all the Regions
519   // and Phis need to complete this one big transform before any other
520   // transforms can be triggered on the region.
521   // Optional 'orig' is an earlier version of this node.
522   // It is significant only for debugging and profiling.
523   Node* register_new_node_with_optimizer(Node* n, Node* orig = nullptr);
524 
525   // Kill a globally dead Node.  All uses are also globally dead and are
526   // aggressively trimmed.
527   void remove_globally_dead_node( Node *dead );
528 
529   // Kill all inputs to a dead node, recursively making more dead nodes.
530   // The Node must be dead locally, i.e., have no uses.
531   void remove_dead_node( Node *dead ) {
532     assert(dead->outcnt() == 0 && !dead->is_top(), "node must be dead");
533     remove_globally_dead_node(dead);
534   }
535 
536   // Add users of 'n' to worklist
537   static void add_users_to_worklist0(Node* n, Unique_Node_List& worklist);
538 
539   // Add one or more users of 'use' to the worklist if it appears that a
540   // known optimization could be applied to those users.
541   // Node 'n' is a node that was modified or is about to get replaced,
542   // and 'use' is one use of 'n'.
543   // Certain optimizations have dependencies that extend beyond a node's
544   // direct inputs, so it is necessary to ensure the appropriate
545   // notifications are made here.
546   static void add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_List& worklist);
547 
548   // Add users of 'n', and any other nodes that could be directly
549   // affected by changes to 'n', to the worklist.
550   // Node 'n' may be a node that is about to get replaced. In this
551   // case, 'n' should not be considered part of the new graph.
552   // Passing the old node (as 'n'), rather than the new node,
553   // prevents unnecessary notifications when the new node already
554   // has other users.
555   void add_users_to_worklist(Node* n);
556 
557   // Replace old node with new one.
558   void replace_node( Node *old, Node *nn ) {
559     add_users_to_worklist(old);
560     hash_delete(old); // Yank from hash before hacking edges
561     subsume_node(old, nn);
562   }
563 
564   // Delayed node rehash: remove a node from the hash table and rehash it during
565   // next optimizing pass
566   void rehash_node_delayed(Node* n) {
567     hash_delete(n);
568     _worklist.push(n);
569   }
570 
571   // Replace ith edge of "n" with "in"
572   void replace_input_of(Node* n, uint i, Node* in) {
573     rehash_node_delayed(n);
574     n->set_req_X(i, in, this);
575   }
576 
577   // Add "in" as input (req) of "n"
578   void add_input_to(Node* n, Node* in) {
579     rehash_node_delayed(n);
580     n->add_req(in);
581   }
582 
583   // Delete ith edge of "n"
584   void delete_input_of(Node* n, uint i) {
585     rehash_node_delayed(n);
586     n->del_req(i);
587   }
588 
589   // Delete precedence edge i of "n"
590   void delete_precedence_of(Node* n, uint i) {
591     rehash_node_delayed(n);
592     n->rm_prec(i);
593   }
594 
595   bool delay_transform() const { return _delay_transform; }
596 
597   void set_delay_transform(bool delay) {
598     _delay_transform = delay;
599   }
600 
601   void remove_speculative_types();
602   void check_no_speculative_types() {
603     _table.check_no_speculative_types();
604   }
605 
606   bool is_dominator(Node *d, Node *n) { return is_dominator_helper(d, n, false); }
607   bool no_dependent_zero_check(Node* n) const;
608 
609 #ifndef PRODUCT
610   static bool is_verify_def_use() {
611     // '-XX:VerifyIterativeGVN=1'
612     return (VerifyIterativeGVN % 10) == 1;
613   }
614   static bool is_verify_Value() {
615     // '-XX:VerifyIterativeGVN=10'
616     return ((VerifyIterativeGVN % 100) / 10) == 1;
617   }
618   static bool is_verify_Ideal() {
619     // '-XX:VerifyIterativeGVN=100'
620     return ((VerifyIterativeGVN % 1000) / 100) == 1;
621   }
622   static bool is_verify_Identity() {
623     // '-XX:VerifyIterativeGVN=1000'
624     return ((VerifyIterativeGVN % 10000) / 1000) == 1;
625   }
626   static bool is_verify_invariants() {
627     // '-XX:VerifyIterativeGVN=10000'
628     return ((VerifyIterativeGVN % 100000) / 10000) == 1;
629   }
630 protected:
631   // Sub-quadratic implementation of '-XX:VerifyIterativeGVN=1' (Use-Def verification).
632   julong _verify_counter;
633   julong _verify_full_passes;
634   enum { _verify_window_size = 30 };
635   Node* _verify_window[_verify_window_size];
636   void verify_step(Node* n);
637 #endif
638 };
639 
640 //------------------------------PhaseCCP---------------------------------------
641 // Phase for performing global Conditional Constant Propagation.
642 // Should be replaced with combined CCP & GVN someday.
643 class PhaseCCP : public PhaseIterGVN {
644   Unique_Node_List _root_and_safepoints;
645   Unique_Node_List _maybe_top_type_nodes;
646   // Non-recursive.  Use analysis to transform single Node.
647   virtual Node* transform_once(Node* n);
648 
649   Node* fetch_next_node(Unique_Node_List& worklist);
650   static void dump_type_and_node(const Node* n, const Type* t) PRODUCT_RETURN;
651 
652   void push_child_nodes_to_worklist(Unique_Node_List& worklist, Node* n) const;
653   void push_if_not_bottom_type(Unique_Node_List& worklist, Node* n) const;
654   void push_more_uses(Unique_Node_List& worklist, Node* parent, const Node* use) const;
655   void push_phis(Unique_Node_List& worklist, const Node* use) const;
656   static void push_catch(Unique_Node_List& worklist, const Node* use);
657   void push_cmpu(Unique_Node_List& worklist, const Node* use) const;
658   static void push_counted_loop_phi(Unique_Node_List& worklist, Node* parent, const Node* use);
659   void push_loadp(Unique_Node_List& worklist, const Node* use) const;
660   void push_and(Unique_Node_List& worklist, const Node* parent, const Node* use) const;
661   void push_cast_ii(Unique_Node_List& worklist, const Node* parent, const Node* use) const;
662   void push_opaque_zero_trip_guard(Unique_Node_List& worklist, const Node* use) const;
663   void push_bool_with_cmpu_and_mask(Unique_Node_List& worklist, const Node* use) const;
664   void push_bool_matching_case1b(Unique_Node_List& worklist, const Node* cmpu) const;
665 
666  public:
667   PhaseCCP( PhaseIterGVN *igvn ); // Compute conditional constants
668   NOT_PRODUCT( ~PhaseCCP(); )
669 
670   // Worklist algorithm identifies constants
671   void analyze();
672   void analyze_step(Unique_Node_List& worklist, Node* n);
673   bool needs_revisit(Node* n) const;
674 #ifdef ASSERT
675   void verify_type(Node* n, const Type* tnew, const Type* told);
676   // For every node n on verify list, check if type(n) == n->Value()
677   void verify_analyze(Unique_Node_List& worklist_verify);
678 #endif
679   // Recursive traversal of program.  Used analysis to modify program.
680   virtual Node *transform( Node *n );
681   // Do any transformation after analysis
682   void          do_transform();
683 
684   virtual const Type* saturate(const Type* new_type, const Type* old_type,
685                                const Type* limit_type) const;
686   // Returns new_type->widen(old_type), which increments the widen bits until
687   // giving up with TypeInt::INT or TypeLong::LONG.
688   // Result is clipped to limit_type if necessary.
689   virtual const Type* saturate_and_maybe_push_to_igvn_worklist(const TypeNode* n, const Type* new_type) {
690     const Type* t = saturate(new_type, type_or_null(n), n->type());
691     if (t != new_type) {
692       // Type was widened in CCP, but IGVN may be able to make it narrower.
693       _worklist.push((Node*)n);
694     }
695     return t;
696   }
697 
698 #ifndef PRODUCT
699   static uint _total_invokes;    // For profiling, count invocations
700   void    inc_invokes()          { ++PhaseCCP::_total_invokes; }
701 
702   static uint _total_constants;  // For profiling, count constants found
703   uint   _count_constants;
704   void    clear_constants()      { _count_constants = 0; }
705   void    inc_constants()        { ++_count_constants; }
706   uint    count_constants() const { return _count_constants; }
707 
708   static void print_statistics();
709 #endif
710 };
711 
712 
713 //------------------------------PhasePeephole----------------------------------
714 // Phase for performing peephole optimizations on register allocated basic blocks.
715 class PhasePeephole : public PhaseTransform {
716   PhaseRegAlloc *_regalloc;
717   PhaseCFG     &_cfg;
718   // Recursive traversal of program.  Pure function is unused in this phase
719   virtual Node *transform( Node *n );
720 
721 public:
722   PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg );
723   NOT_PRODUCT( ~PhasePeephole(); )
724 
725   // Do any transformation after analysis
726   void          do_transform();
727 
728 #ifndef PRODUCT
729   static uint _total_peepholes;  // For profiling, count peephole rules applied
730   uint   _count_peepholes;
731   void    clear_peepholes()      { _count_peepholes = 0; }
732   void    inc_peepholes()        { ++_count_peepholes; }
733   uint    count_peepholes() const { return _count_peepholes; }
734 
735   static void print_statistics();
736 #endif
737 };
738 
739 #endif // SHARE_OPTO_PHASEX_HPP