1 /*
   2  * Copyright (c) 1997, 2022, 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 #include "precompiled.hpp"
  26 #include "gc/shared/barrierSet.hpp"
  27 #include "gc/shared/c2/barrierSetC2.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "opto/block.hpp"
  31 #include "opto/callnode.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/idealGraphPrinter.hpp"
  35 #include "opto/loopnode.hpp"
  36 #include "opto/machnode.hpp"
  37 #include "opto/opcodes.hpp"
  38 #include "opto/phaseX.hpp"
  39 #include "opto/regalloc.hpp"
  40 #include "opto/rootnode.hpp"
  41 #include "utilities/macros.hpp"
  42 #include "utilities/powerOfTwo.hpp"
  43 
  44 //=============================================================================
  45 #define NODE_HASH_MINIMUM_SIZE    255
  46 //------------------------------NodeHash---------------------------------------
  47 NodeHash::NodeHash(uint est_max_size) :
  48   _a(Thread::current()->resource_area()),
  49   _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
  50   _inserts(0), _insert_limit( insert_limit() ),
  51   _table( NEW_ARENA_ARRAY( _a , Node* , _max ) ) // (Node**)_a->Amalloc(_max * sizeof(Node*)) ),
  52 #ifndef PRODUCT
  53   , _grows(0),_look_probes(0), _lookup_hits(0), _lookup_misses(0),
  54   _insert_probes(0), _delete_probes(0), _delete_hits(0), _delete_misses(0),
  55    _total_inserts(0), _total_insert_probes(0)
  56 #endif
  57 {
  58   // _sentinel must be in the current node space
  59   _sentinel = new ProjNode(NULL, TypeFunc::Control);
  60   memset(_table,0,sizeof(Node*)*_max);
  61 }
  62 
  63 //------------------------------NodeHash---------------------------------------
  64 NodeHash::NodeHash(Arena *arena, uint est_max_size) :
  65   _a(arena),
  66   _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
  67   _inserts(0), _insert_limit( insert_limit() ),
  68   _table( NEW_ARENA_ARRAY( _a , Node* , _max ) )
  69 #ifndef PRODUCT
  70   , _grows(0),_look_probes(0), _lookup_hits(0), _lookup_misses(0),
  71   _insert_probes(0), _delete_probes(0), _delete_hits(0), _delete_misses(0),
  72    _total_inserts(0), _total_insert_probes(0)
  73 #endif
  74 {
  75   // _sentinel must be in the current node space
  76   _sentinel = new ProjNode(NULL, TypeFunc::Control);
  77   memset(_table,0,sizeof(Node*)*_max);
  78 }
  79 
  80 //------------------------------NodeHash---------------------------------------
  81 NodeHash::NodeHash(NodeHash *nh) {
  82   debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
  83   // just copy in all the fields
  84   *this = *nh;
  85   // nh->_sentinel must be in the current node space
  86 }
  87 
  88 void NodeHash::replace_with(NodeHash *nh) {
  89   debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
  90   // just copy in all the fields
  91   *this = *nh;
  92   // nh->_sentinel must be in the current node space
  93 }
  94 
  95 //------------------------------hash_find--------------------------------------
  96 // Find in hash table
  97 Node *NodeHash::hash_find( const Node *n ) {
  98   // ((Node*)n)->set_hash( n->hash() );
  99   uint hash = n->hash();
 100   if (hash == Node::NO_HASH) {
 101     NOT_PRODUCT( _lookup_misses++ );
 102     return NULL;
 103   }
 104   uint key = hash & (_max-1);
 105   uint stride = key | 0x01;
 106   NOT_PRODUCT( _look_probes++ );
 107   Node *k = _table[key];        // Get hashed value
 108   if( !k ) {                    // ?Miss?
 109     NOT_PRODUCT( _lookup_misses++ );
 110     return NULL;                // Miss!
 111   }
 112 
 113   int op = n->Opcode();
 114   uint req = n->req();
 115   while( 1 ) {                  // While probing hash table
 116     if( k->req() == req &&      // Same count of inputs
 117         k->Opcode() == op ) {   // Same Opcode
 118       for( uint i=0; i<req; i++ )
 119         if( n->in(i)!=k->in(i)) // Different inputs?
 120           goto collision;       // "goto" is a speed hack...
 121       if( n->cmp(*k) ) {        // Check for any special bits
 122         NOT_PRODUCT( _lookup_hits++ );
 123         return k;               // Hit!
 124       }
 125     }
 126   collision:
 127     NOT_PRODUCT( _look_probes++ );
 128     key = (key + stride/*7*/) & (_max-1); // Stride through table with relative prime
 129     k = _table[key];            // Get hashed value
 130     if( !k ) {                  // ?Miss?
 131       NOT_PRODUCT( _lookup_misses++ );
 132       return NULL;              // Miss!
 133     }
 134   }
 135   ShouldNotReachHere();
 136   return NULL;
 137 }
 138 
 139 //------------------------------hash_find_insert-------------------------------
 140 // Find in hash table, insert if not already present
 141 // Used to preserve unique entries in hash table
 142 Node *NodeHash::hash_find_insert( Node *n ) {
 143   // n->set_hash( );
 144   uint hash = n->hash();
 145   if (hash == Node::NO_HASH) {
 146     NOT_PRODUCT( _lookup_misses++ );
 147     return NULL;
 148   }
 149   uint key = hash & (_max-1);
 150   uint stride = key | 0x01;     // stride must be relatively prime to table siz
 151   uint first_sentinel = 0;      // replace a sentinel if seen.
 152   NOT_PRODUCT( _look_probes++ );
 153   Node *k = _table[key];        // Get hashed value
 154   if( !k ) {                    // ?Miss?
 155     NOT_PRODUCT( _lookup_misses++ );
 156     _table[key] = n;            // Insert into table!
 157     debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
 158     check_grow();               // Grow table if insert hit limit
 159     return NULL;                // Miss!
 160   }
 161   else if( k == _sentinel ) {
 162     first_sentinel = key;      // Can insert here
 163   }
 164 
 165   int op = n->Opcode();
 166   uint req = n->req();
 167   while( 1 ) {                  // While probing hash table
 168     if( k->req() == req &&      // Same count of inputs
 169         k->Opcode() == op ) {   // Same Opcode
 170       for( uint i=0; i<req; i++ )
 171         if( n->in(i)!=k->in(i)) // Different inputs?
 172           goto collision;       // "goto" is a speed hack...
 173       if( n->cmp(*k) ) {        // Check for any special bits
 174         NOT_PRODUCT( _lookup_hits++ );
 175         return k;               // Hit!
 176       }
 177     }
 178   collision:
 179     NOT_PRODUCT( _look_probes++ );
 180     key = (key + stride) & (_max-1); // Stride through table w/ relative prime
 181     k = _table[key];            // Get hashed value
 182     if( !k ) {                  // ?Miss?
 183       NOT_PRODUCT( _lookup_misses++ );
 184       key = (first_sentinel == 0) ? key : first_sentinel; // ?saw sentinel?
 185       _table[key] = n;          // Insert into table!
 186       debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
 187       check_grow();             // Grow table if insert hit limit
 188       return NULL;              // Miss!
 189     }
 190     else if( first_sentinel == 0 && k == _sentinel ) {
 191       first_sentinel = key;    // Can insert here
 192     }
 193 
 194   }
 195   ShouldNotReachHere();
 196   return NULL;
 197 }
 198 
 199 //------------------------------hash_insert------------------------------------
 200 // Insert into hash table
 201 void NodeHash::hash_insert( Node *n ) {
 202   // // "conflict" comments -- print nodes that conflict
 203   // bool conflict = false;
 204   // n->set_hash();
 205   uint hash = n->hash();
 206   if (hash == Node::NO_HASH) {
 207     return;
 208   }
 209   check_grow();
 210   uint key = hash & (_max-1);
 211   uint stride = key | 0x01;
 212 
 213   while( 1 ) {                  // While probing hash table
 214     NOT_PRODUCT( _insert_probes++ );
 215     Node *k = _table[key];      // Get hashed value
 216     if( !k || (k == _sentinel) ) break;       // Found a slot
 217     assert( k != n, "already inserted" );
 218     // if( PrintCompilation && PrintOptoStatistics && Verbose ) { tty->print("  conflict: "); k->dump(); conflict = true; }
 219     key = (key + stride) & (_max-1); // Stride through table w/ relative prime
 220   }
 221   _table[key] = n;              // Insert into table!
 222   debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
 223   // if( conflict ) { n->dump(); }
 224 }
 225 
 226 //------------------------------hash_delete------------------------------------
 227 // Replace in hash table with sentinel
 228 bool NodeHash::hash_delete( const Node *n ) {
 229   Node *k;
 230   uint hash = n->hash();
 231   if (hash == Node::NO_HASH) {
 232     NOT_PRODUCT( _delete_misses++ );
 233     return false;
 234   }
 235   uint key = hash & (_max-1);
 236   uint stride = key | 0x01;
 237   debug_only( uint counter = 0; );
 238   for( ; /* (k != NULL) && (k != _sentinel) */; ) {
 239     debug_only( counter++ );
 240     NOT_PRODUCT( _delete_probes++ );
 241     k = _table[key];            // Get hashed value
 242     if( !k ) {                  // Miss?
 243       NOT_PRODUCT( _delete_misses++ );
 244       return false;             // Miss! Not in chain
 245     }
 246     else if( n == k ) {
 247       NOT_PRODUCT( _delete_hits++ );
 248       _table[key] = _sentinel;  // Hit! Label as deleted entry
 249       debug_only(((Node*)n)->exit_hash_lock()); // Unlock the node upon removal from table.
 250       return true;
 251     }
 252     else {
 253       // collision: move through table with prime offset
 254       key = (key + stride/*7*/) & (_max-1);
 255       assert( counter <= _insert_limit, "Cycle in hash-table");
 256     }
 257   }
 258   ShouldNotReachHere();
 259   return false;
 260 }
 261 
 262 //------------------------------round_up---------------------------------------
 263 // Round up to nearest power of 2
 264 uint NodeHash::round_up(uint x) {
 265   x += (x >> 2);                  // Add 25% slop
 266   return MAX2(16U, round_up_power_of_2(x));
 267 }
 268 
 269 //------------------------------grow-------------------------------------------
 270 // Grow _table to next power of 2 and insert old entries
 271 void  NodeHash::grow() {
 272   // Record old state
 273   uint   old_max   = _max;
 274   Node **old_table = _table;
 275   // Construct new table with twice the space
 276 #ifndef PRODUCT
 277   _grows++;
 278   _total_inserts       += _inserts;
 279   _total_insert_probes += _insert_probes;
 280   _insert_probes   = 0;
 281 #endif
 282   _inserts         = 0;
 283   _max     = _max << 1;
 284   _table   = NEW_ARENA_ARRAY( _a , Node* , _max ); // (Node**)_a->Amalloc( _max * sizeof(Node*) );
 285   memset(_table,0,sizeof(Node*)*_max);
 286   _insert_limit = insert_limit();
 287   // Insert old entries into the new table
 288   for( uint i = 0; i < old_max; i++ ) {
 289     Node *m = *old_table++;
 290     if( !m || m == _sentinel ) continue;
 291     debug_only(m->exit_hash_lock()); // Unlock the node upon removal from old table.
 292     hash_insert(m);
 293   }
 294 }
 295 
 296 //------------------------------clear------------------------------------------
 297 // Clear all entries in _table to NULL but keep storage
 298 void  NodeHash::clear() {
 299 #ifdef ASSERT
 300   // Unlock all nodes upon removal from table.
 301   for (uint i = 0; i < _max; i++) {
 302     Node* n = _table[i];
 303     if (!n || n == _sentinel)  continue;
 304     n->exit_hash_lock();
 305   }
 306 #endif
 307 
 308   memset( _table, 0, _max * sizeof(Node*) );
 309 }
 310 
 311 //-----------------------remove_useless_nodes----------------------------------
 312 // Remove useless nodes from value table,
 313 // implementation does not depend on hash function
 314 void NodeHash::remove_useless_nodes(VectorSet &useful) {
 315 
 316   // Dead nodes in the hash table inherited from GVN should not replace
 317   // existing nodes, remove dead nodes.
 318   uint max = size();
 319   Node *sentinel_node = sentinel();
 320   for( uint i = 0; i < max; ++i ) {
 321     Node *n = at(i);
 322     if(n != NULL && n != sentinel_node && !useful.test(n->_idx)) {
 323       debug_only(n->exit_hash_lock()); // Unlock the node when removed
 324       _table[i] = sentinel_node;       // Replace with placeholder
 325     }
 326   }
 327 }
 328 
 329 
 330 void NodeHash::check_no_speculative_types() {
 331 #ifdef ASSERT
 332   uint max = size();
 333   Unique_Node_List live_nodes;
 334   Compile::current()->identify_useful_nodes(live_nodes);
 335   Node *sentinel_node = sentinel();
 336   for (uint i = 0; i < max; ++i) {
 337     Node *n = at(i);
 338     if (n != NULL &&
 339         n != sentinel_node &&
 340         n->is_Type() &&
 341         live_nodes.member(n)) {
 342       TypeNode* tn = n->as_Type();
 343       const Type* t = tn->type();
 344       const Type* t_no_spec = t->remove_speculative();
 345       assert(t == t_no_spec, "dead node in hash table or missed node during speculative cleanup");
 346     }
 347   }
 348 #endif
 349 }
 350 
 351 #ifndef PRODUCT
 352 //------------------------------dump-------------------------------------------
 353 // Dump statistics for the hash table
 354 void NodeHash::dump() {
 355   _total_inserts       += _inserts;
 356   _total_insert_probes += _insert_probes;
 357   if (PrintCompilation && PrintOptoStatistics && Verbose && (_inserts > 0)) {
 358     if (WizardMode) {
 359       for (uint i=0; i<_max; i++) {
 360         if (_table[i])
 361           tty->print("%d/%d/%d ",i,_table[i]->hash()&(_max-1),_table[i]->_idx);
 362       }
 363     }
 364     tty->print("\nGVN Hash stats:  %d grows to %d max_size\n", _grows, _max);
 365     tty->print("  %d/%d (%8.1f%% full)\n", _inserts, _max, (double)_inserts/_max*100.0);
 366     tty->print("  %dp/(%dh+%dm) (%8.2f probes/lookup)\n", _look_probes, _lookup_hits, _lookup_misses, (double)_look_probes/(_lookup_hits+_lookup_misses));
 367     tty->print("  %dp/%di (%8.2f probes/insert)\n", _total_insert_probes, _total_inserts, (double)_total_insert_probes/_total_inserts);
 368     // sentinels increase lookup cost, but not insert cost
 369     assert((_lookup_misses+_lookup_hits)*4+100 >= _look_probes, "bad hash function");
 370     assert( _inserts+(_inserts>>3) < _max, "table too full" );
 371     assert( _inserts*3+100 >= _insert_probes, "bad hash function" );
 372   }
 373 }
 374 
 375 Node *NodeHash::find_index(uint idx) { // For debugging
 376   // Find an entry by its index value
 377   for( uint i = 0; i < _max; i++ ) {
 378     Node *m = _table[i];
 379     if( !m || m == _sentinel ) continue;
 380     if( m->_idx == (uint)idx ) return m;
 381   }
 382   return NULL;
 383 }
 384 #endif
 385 
 386 #ifdef ASSERT
 387 NodeHash::~NodeHash() {
 388   // Unlock all nodes upon destruction of table.
 389   if (_table != (Node**)badAddress)  clear();
 390 }
 391 
 392 void NodeHash::operator=(const NodeHash& nh) {
 393   // Unlock all nodes upon replacement of table.
 394   if (&nh == this)  return;
 395   if (_table != (Node**)badAddress)  clear();
 396   memcpy((void*)this, (void*)&nh, sizeof(*this));
 397   // Do not increment hash_lock counts again.
 398   // Instead, be sure we never again use the source table.
 399   ((NodeHash*)&nh)->_table = (Node**)badAddress;
 400 }
 401 
 402 
 403 #endif
 404 
 405 
 406 //=============================================================================
 407 //------------------------------PhaseRemoveUseless-----------------------------
 408 // 1) Use a breadthfirst walk to collect useful nodes reachable from root.
 409 PhaseRemoveUseless::PhaseRemoveUseless(PhaseGVN* gvn, Unique_Node_List* worklist, PhaseNumber phase_num) : Phase(phase_num) {
 410   // Implementation requires an edge from root to each SafePointNode
 411   // at a backward branch. Inserted in add_safepoint().
 412 
 413   // Identify nodes that are reachable from below, useful.
 414   C->identify_useful_nodes(_useful);
 415   // Update dead node list
 416   C->update_dead_node_list(_useful);
 417 
 418   // Remove all useless nodes from PhaseValues' recorded types
 419   // Must be done before disconnecting nodes to preserve hash-table-invariant
 420   gvn->remove_useless_nodes(_useful.member_set());
 421 
 422   // Remove all useless nodes from future worklist
 423   worklist->remove_useless_nodes(_useful.member_set());
 424 
 425   // Disconnect 'useless' nodes that are adjacent to useful nodes
 426   C->disconnect_useless_nodes(_useful, worklist);
 427 }
 428 
 429 //=============================================================================
 430 //------------------------------PhaseRenumberLive------------------------------
 431 // First, remove useless nodes (equivalent to identifying live nodes).
 432 // Then, renumber live nodes.
 433 //
 434 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
 435 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
 436 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
 437 // value in the range [0, x).
 438 //
 439 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
 440 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
 441 //
 442 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
 443 // (1) The worklist is used by the PhaseIterGVN phase to identify nodes that must be
 444 // processed. A new worklist (with the updated node IDs) is returned in 'new_worklist'.
 445 // 'worklist' is cleared upon returning.
 446 // (2) Type information (the field PhaseGVN::_types) maps type information to each
 447 // node ID. The mapping is updated to use the new node IDs as well. Updated type
 448 // information is returned in PhaseGVN::_types.
 449 //
 450 // The PhaseRenumberLive phase does not preserve the order of elements in the worklist.
 451 //
 452 // Other data structures used by the compiler are not updated. The hash table for value
 453 // numbering (the field PhaseGVN::_table) is not updated because computing the hash
 454 // values is not based on node IDs. The field PhaseGVN::_nodes is not updated either
 455 // because it is empty wherever PhaseRenumberLive is used.
 456 PhaseRenumberLive::PhaseRenumberLive(PhaseGVN* gvn,
 457                                      Unique_Node_List* worklist, Unique_Node_List* new_worklist,
 458                                      PhaseNumber phase_num) :
 459   PhaseRemoveUseless(gvn, worklist, Remove_Useless_And_Renumber_Live),
 460   _new_type_array(C->comp_arena()),
 461   _old2new_map(C->unique(), C->unique(), -1),
 462   _is_pass_finished(false),
 463   _live_node_count(C->live_nodes())
 464 {
 465   assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
 466   assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
 467   assert(gvn->nodes_size() == 0, "GVN must not contain any nodes at this point");
 468   assert(_delayed.size() == 0, "should be empty");
 469 
 470   uint worklist_size = worklist->size();
 471 
 472   // Iterate over the set of live nodes.
 473   for (uint current_idx = 0; current_idx < _useful.size(); current_idx++) {
 474     Node* n = _useful.at(current_idx);
 475 
 476     bool in_worklist = false;
 477     if (worklist->member(n)) {
 478       in_worklist = true;
 479     }
 480 
 481     const Type* type = gvn->type_or_null(n);
 482     _new_type_array.map(current_idx, type);
 483 
 484     assert(_old2new_map.at(n->_idx) == -1, "already seen");
 485     _old2new_map.at_put(n->_idx, current_idx);
 486 
 487     n->set_idx(current_idx); // Update node ID.
 488 
 489     if (in_worklist) {
 490       new_worklist->push(n);
 491     }
 492 
 493     if (update_embedded_ids(n) < 0) {
 494       _delayed.push(n); // has embedded IDs; handle later
 495     }
 496   }
 497 
 498   assert(worklist_size == new_worklist->size(), "the new worklist must have the same size as the original worklist");
 499   assert(_live_node_count == _useful.size(), "all live nodes must be processed");
 500 
 501   _is_pass_finished = true; // pass finished; safe to process delayed updates
 502 
 503   while (_delayed.size() > 0) {
 504     Node* n = _delayed.pop();
 505     int no_of_updates = update_embedded_ids(n);
 506     assert(no_of_updates > 0, "should be updated");
 507   }
 508 
 509   // Replace the compiler's type information with the updated type information.
 510   gvn->replace_types(_new_type_array);
 511 
 512   // Update the unique node count of the compilation to the number of currently live nodes.
 513   C->set_unique(_live_node_count);
 514 
 515   // Set the dead node count to 0 and reset dead node list.
 516   C->reset_dead_node_list();
 517 
 518   // Clear the original worklist
 519   worklist->clear();
 520 }
 521 
 522 int PhaseRenumberLive::new_index(int old_idx) {
 523   assert(_is_pass_finished, "not finished");
 524   if (_old2new_map.at(old_idx) == -1) { // absent
 525     // Allocate a placeholder to preserve uniqueness
 526     _old2new_map.at_put(old_idx, _live_node_count);
 527     _live_node_count++;
 528   }
 529   return _old2new_map.at(old_idx);
 530 }
 531 
 532 int PhaseRenumberLive::update_embedded_ids(Node* n) {
 533   int no_of_updates = 0;
 534   if (n->is_Phi()) {
 535     PhiNode* phi = n->as_Phi();
 536     if (phi->_inst_id != -1) {
 537       if (!_is_pass_finished) {
 538         return -1; // delay
 539       }
 540       int new_idx = new_index(phi->_inst_id);
 541       assert(new_idx != -1, "");
 542       phi->_inst_id = new_idx;
 543       no_of_updates++;
 544     }
 545     if (phi->_inst_mem_id != -1) {
 546       if (!_is_pass_finished) {
 547         return -1; // delay
 548       }
 549       int new_idx = new_index(phi->_inst_mem_id);
 550       assert(new_idx != -1, "");
 551       phi->_inst_mem_id = new_idx;
 552       no_of_updates++;
 553     }
 554   }
 555 
 556   const Type* type = _new_type_array.fast_lookup(n->_idx);
 557   if (type != NULL && type->isa_oopptr() && type->is_oopptr()->is_known_instance()) {
 558     if (!_is_pass_finished) {
 559         return -1; // delay
 560     }
 561     int old_idx = type->is_oopptr()->instance_id();
 562     int new_idx = new_index(old_idx);
 563     const Type* new_type = type->is_oopptr()->with_instance_id(new_idx);
 564     _new_type_array.map(n->_idx, new_type);
 565     no_of_updates++;
 566   }
 567 
 568   return no_of_updates;
 569 }
 570 
 571 //=============================================================================
 572 //------------------------------PhaseTransform---------------------------------
 573 PhaseTransform::PhaseTransform( PhaseNumber pnum ) : Phase(pnum),
 574   _arena(Thread::current()->resource_area()),
 575   _nodes(_arena),
 576   _types(_arena)
 577 {
 578   init_con_caches();
 579 #ifndef PRODUCT
 580   clear_progress();
 581   clear_transforms();
 582   set_allow_progress(true);
 583 #endif
 584   // Force allocation for currently existing nodes
 585   _types.map(C->unique(), NULL);
 586 }
 587 
 588 //------------------------------PhaseTransform---------------------------------
 589 PhaseTransform::PhaseTransform( Arena *arena, PhaseNumber pnum ) : Phase(pnum),
 590   _arena(arena),
 591   _nodes(arena),
 592   _types(arena)
 593 {
 594   init_con_caches();
 595 #ifndef PRODUCT
 596   clear_progress();
 597   clear_transforms();
 598   set_allow_progress(true);
 599 #endif
 600   // Force allocation for currently existing nodes
 601   _types.map(C->unique(), NULL);
 602 }
 603 
 604 //------------------------------PhaseTransform---------------------------------
 605 // Initialize with previously generated type information
 606 PhaseTransform::PhaseTransform( PhaseTransform *pt, PhaseNumber pnum ) : Phase(pnum),
 607   _arena(pt->_arena),
 608   _nodes(pt->_nodes),
 609   _types(pt->_types)
 610 {
 611   init_con_caches();
 612 #ifndef PRODUCT
 613   clear_progress();
 614   clear_transforms();
 615   set_allow_progress(true);
 616 #endif
 617 }
 618 
 619 void PhaseTransform::init_con_caches() {
 620   memset(_icons,0,sizeof(_icons));
 621   memset(_lcons,0,sizeof(_lcons));
 622   memset(_zcons,0,sizeof(_zcons));
 623 }
 624 
 625 
 626 //--------------------------------find_int_type--------------------------------
 627 const TypeInt* PhaseTransform::find_int_type(Node* n) {
 628   if (n == NULL)  return NULL;
 629   // Call type_or_null(n) to determine node's type since we might be in
 630   // parse phase and call n->Value() may return wrong type.
 631   // (For example, a phi node at the beginning of loop parsing is not ready.)
 632   const Type* t = type_or_null(n);
 633   if (t == NULL)  return NULL;
 634   return t->isa_int();
 635 }
 636 
 637 
 638 //-------------------------------find_long_type--------------------------------
 639 const TypeLong* PhaseTransform::find_long_type(Node* n) {
 640   if (n == NULL)  return NULL;
 641   // (See comment above on type_or_null.)
 642   const Type* t = type_or_null(n);
 643   if (t == NULL)  return NULL;
 644   return t->isa_long();
 645 }
 646 
 647 
 648 #ifndef PRODUCT
 649 void PhaseTransform::dump_old2new_map() const {
 650   _nodes.dump();
 651 }
 652 
 653 void PhaseTransform::dump_new( uint nidx ) const {
 654   for( uint i=0; i<_nodes.Size(); i++ )
 655     if( _nodes[i] && _nodes[i]->_idx == nidx ) {
 656       _nodes[i]->dump();
 657       tty->cr();
 658       tty->print_cr("Old index= %d",i);
 659       return;
 660     }
 661   tty->print_cr("Node %d not found in the new indices", nidx);
 662 }
 663 
 664 //------------------------------dump_types-------------------------------------
 665 void PhaseTransform::dump_types( ) const {
 666   _types.dump();
 667 }
 668 
 669 //------------------------------dump_nodes_and_types---------------------------
 670 void PhaseTransform::dump_nodes_and_types(const Node* root, uint depth, bool only_ctrl) {
 671   VectorSet visited;
 672   dump_nodes_and_types_recur(root, depth, only_ctrl, visited);
 673 }
 674 
 675 //------------------------------dump_nodes_and_types_recur---------------------
 676 void PhaseTransform::dump_nodes_and_types_recur( const Node *n, uint depth, bool only_ctrl, VectorSet &visited) {
 677   if( !n ) return;
 678   if( depth == 0 ) return;
 679   if( visited.test_set(n->_idx) ) return;
 680   for( uint i=0; i<n->len(); i++ ) {
 681     if( only_ctrl && !(n->is_Region()) && i != TypeFunc::Control ) continue;
 682     dump_nodes_and_types_recur( n->in(i), depth-1, only_ctrl, visited );
 683   }
 684   n->dump();
 685   if (type_or_null(n) != NULL) {
 686     tty->print("      "); type(n)->dump(); tty->cr();
 687   }
 688 }
 689 
 690 #endif
 691 
 692 
 693 //=============================================================================
 694 //------------------------------PhaseValues------------------------------------
 695 // Set minimum table size to "255"
 696 PhaseValues::PhaseValues( Arena *arena, uint est_max_size )
 697   : PhaseTransform(arena, GVN), _table(arena, est_max_size), _iterGVN(false) {
 698   NOT_PRODUCT( clear_new_values(); )
 699 }
 700 
 701 //------------------------------PhaseValues------------------------------------
 702 // Set minimum table size to "255"
 703 PhaseValues::PhaseValues(PhaseValues* ptv)
 704   : PhaseTransform(ptv, GVN), _table(&ptv->_table), _iterGVN(false) {
 705   NOT_PRODUCT( clear_new_values(); )
 706 }
 707 
 708 //------------------------------~PhaseValues-----------------------------------
 709 #ifndef PRODUCT
 710 PhaseValues::~PhaseValues() {
 711   _table.dump();
 712 
 713   // Statistics for value progress and efficiency
 714   if( PrintCompilation && Verbose && WizardMode ) {
 715     tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
 716       is_IterGVN() ? "Iter" : "    ", C->unique(), made_progress(), made_transforms(), made_new_values());
 717     if( made_transforms() != 0 ) {
 718       tty->print_cr("  ratio %f", made_progress()/(float)made_transforms() );
 719     } else {
 720       tty->cr();
 721     }
 722   }
 723 }
 724 #endif
 725 
 726 //------------------------------makecon----------------------------------------
 727 ConNode* PhaseTransform::makecon(const Type *t) {
 728   assert(t->singleton(), "must be a constant");
 729   assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
 730   switch (t->base()) {  // fast paths
 731   case Type::Half:
 732   case Type::Top:  return (ConNode*) C->top();
 733   case Type::Int:  return intcon( t->is_int()->get_con() );
 734   case Type::Long: return longcon( t->is_long()->get_con() );
 735   default:         break;
 736   }
 737   if (t->is_zero_type())
 738     return zerocon(t->basic_type());
 739   return uncached_makecon(t);
 740 }
 741 
 742 //--------------------------uncached_makecon-----------------------------------
 743 // Make an idealized constant - one of ConINode, ConPNode, etc.
 744 ConNode* PhaseValues::uncached_makecon(const Type *t) {
 745   assert(t->singleton(), "must be a constant");
 746   ConNode* x = ConNode::make(t);
 747   ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
 748   if (k == NULL) {
 749     set_type(x, t);             // Missed, provide type mapping
 750     GrowableArray<Node_Notes*>* nna = C->node_note_array();
 751     if (nna != NULL) {
 752       Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
 753       loc->clear(); // do not put debug info on constants
 754     }
 755   } else {
 756     x->destruct(this);          // Hit, destroy duplicate constant
 757     x = k;                      // use existing constant
 758   }
 759   return x;
 760 }
 761 
 762 //------------------------------intcon-----------------------------------------
 763 // Fast integer constant.  Same as "transform(new ConINode(TypeInt::make(i)))"
 764 ConINode* PhaseTransform::intcon(jint i) {
 765   // Small integer?  Check cache! Check that cached node is not dead
 766   if (i >= _icon_min && i <= _icon_max) {
 767     ConINode* icon = _icons[i-_icon_min];
 768     if (icon != NULL && icon->in(TypeFunc::Control) != NULL)
 769       return icon;
 770   }
 771   ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
 772   assert(icon->is_Con(), "");
 773   if (i >= _icon_min && i <= _icon_max)
 774     _icons[i-_icon_min] = icon;   // Cache small integers
 775   return icon;
 776 }
 777 
 778 //------------------------------longcon----------------------------------------
 779 // Fast long constant.
 780 ConLNode* PhaseTransform::longcon(jlong l) {
 781   // Small integer?  Check cache! Check that cached node is not dead
 782   if (l >= _lcon_min && l <= _lcon_max) {
 783     ConLNode* lcon = _lcons[l-_lcon_min];
 784     if (lcon != NULL && lcon->in(TypeFunc::Control) != NULL)
 785       return lcon;
 786   }
 787   ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
 788   assert(lcon->is_Con(), "");
 789   if (l >= _lcon_min && l <= _lcon_max)
 790     _lcons[l-_lcon_min] = lcon;      // Cache small integers
 791   return lcon;
 792 }
 793 ConNode* PhaseTransform::integercon(jlong l, BasicType bt) {
 794   if (bt == T_INT) {
 795     return intcon(checked_cast<jint>(l));
 796   }
 797   assert(bt == T_LONG, "not an integer");
 798   return longcon(l);
 799 }
 800 
 801 
 802 //------------------------------zerocon-----------------------------------------
 803 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
 804 ConNode* PhaseTransform::zerocon(BasicType bt) {
 805   assert((uint)bt <= _zcon_max, "domain check");
 806   ConNode* zcon = _zcons[bt];
 807   if (zcon != NULL && zcon->in(TypeFunc::Control) != NULL)
 808     return zcon;
 809   zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
 810   _zcons[bt] = zcon;
 811   return zcon;
 812 }
 813 
 814 
 815 
 816 //=============================================================================
 817 Node* PhaseGVN::apply_ideal(Node* k, bool can_reshape) {
 818   Node* i = BarrierSet::barrier_set()->barrier_set_c2()->ideal_node(this, k, can_reshape);
 819   if (i == NULL) {
 820     i = k->Ideal(this, can_reshape);
 821   }
 822   return i;
 823 }
 824 
 825 //------------------------------transform--------------------------------------
 826 // Return a node which computes the same function as this node, but in a
 827 // faster or cheaper fashion.
 828 Node *PhaseGVN::transform( Node *n ) {
 829   return transform_no_reclaim(n);
 830 }
 831 
 832 //------------------------------transform--------------------------------------
 833 // Return a node which computes the same function as this node, but
 834 // in a faster or cheaper fashion.
 835 Node *PhaseGVN::transform_no_reclaim(Node *n) {
 836   NOT_PRODUCT( set_transforms(); )
 837 
 838   // Apply the Ideal call in a loop until it no longer applies
 839   Node* k = n;
 840   Node* i = apply_ideal(k, /*can_reshape=*/false);
 841   NOT_PRODUCT(uint loop_count = 1;)
 842   while (i != NULL) {
 843     assert(i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
 844     k = i;
 845 #ifdef ASSERT
 846     if (loop_count >= K + C->live_nodes()) {
 847       dump_infinite_loop_info(i, "PhaseGVN::transform_no_reclaim");
 848     }
 849 #endif
 850     i = apply_ideal(k, /*can_reshape=*/false);
 851     NOT_PRODUCT(loop_count++;)
 852   }
 853   NOT_PRODUCT(if (loop_count != 0) { set_progress(); })
 854 
 855   // If brand new node, make space in type array.
 856   ensure_type_or_null(k);
 857 
 858   // Since I just called 'Value' to compute the set of run-time values
 859   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
 860   // cache Value.  Later requests for the local phase->type of this Node can
 861   // use the cached Value instead of suffering with 'bottom_type'.
 862   const Type* t = k->Value(this); // Get runtime Value set
 863   assert(t != NULL, "value sanity");
 864   if (type_or_null(k) != t) {
 865 #ifndef PRODUCT
 866     // Do not count initial visit to node as a transformation
 867     if (type_or_null(k) == NULL) {
 868       inc_new_values();
 869       set_progress();
 870     }
 871 #endif
 872     set_type(k, t);
 873     // If k is a TypeNode, capture any more-precise type permanently into Node
 874     k->raise_bottom_type(t);
 875   }
 876 
 877   if (t->singleton() && !k->is_Con()) {
 878     NOT_PRODUCT(set_progress();)
 879     return makecon(t);          // Turn into a constant
 880   }
 881 
 882   // Now check for Identities
 883   i = k->Identity(this);        // Look for a nearby replacement
 884   if (i != k) {                 // Found? Return replacement!
 885     NOT_PRODUCT(set_progress();)
 886     return i;
 887   }
 888 
 889   // Global Value Numbering
 890   i = hash_find_insert(k);      // Insert if new
 891   if (i && (i != k)) {
 892     // Return the pre-existing node
 893     NOT_PRODUCT(set_progress();)
 894     return i;
 895   }
 896 
 897   // Return Idealized original
 898   return k;
 899 }
 900 
 901 bool PhaseGVN::is_dominator_helper(Node *d, Node *n, bool linear_only) {
 902   if (d->is_top() || (d->is_Proj() && d->in(0)->is_top())) {
 903     return false;
 904   }
 905   if (n->is_top() || (n->is_Proj() && n->in(0)->is_top())) {
 906     return false;
 907   }
 908   assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
 909   int i = 0;
 910   while (d != n) {
 911     n = IfNode::up_one_dom(n, linear_only);
 912     i++;
 913     if (n == NULL || i >= 100) {
 914       return false;
 915     }
 916   }
 917   return true;
 918 }
 919 
 920 #ifdef ASSERT
 921 //------------------------------dead_loop_check--------------------------------
 922 // Check for a simple dead loop when a data node references itself directly
 923 // or through an other data node excluding cons and phis.
 924 void PhaseGVN::dead_loop_check( Node *n ) {
 925   // Phi may reference itself in a loop
 926   if (n != NULL && !n->is_dead_loop_safe() && !n->is_CFG()) {
 927     // Do 2 levels check and only data inputs.
 928     bool no_dead_loop = true;
 929     uint cnt = n->req();
 930     for (uint i = 1; i < cnt && no_dead_loop; i++) {
 931       Node *in = n->in(i);
 932       if (in == n) {
 933         no_dead_loop = false;
 934       } else if (in != NULL && !in->is_dead_loop_safe()) {
 935         uint icnt = in->req();
 936         for (uint j = 1; j < icnt && no_dead_loop; j++) {
 937           if (in->in(j) == n || in->in(j) == in)
 938             no_dead_loop = false;
 939         }
 940       }
 941     }
 942     if (!no_dead_loop) n->dump(3);
 943     assert(no_dead_loop, "dead loop detected");
 944   }
 945 }
 946 
 947 
 948 /**
 949  * Dumps information that can help to debug the problem. A debug
 950  * build fails with an assert.
 951  */
 952 void PhaseGVN::dump_infinite_loop_info(Node* n, const char* where) {
 953   n->dump(4);
 954   assert(false, "infinite loop in %s", where);
 955 }
 956 #endif
 957 
 958 //=============================================================================
 959 //------------------------------PhaseIterGVN-----------------------------------
 960 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
 961 PhaseIterGVN::PhaseIterGVN(PhaseIterGVN* igvn) : PhaseGVN(igvn),
 962                                                  _delay_transform(igvn->_delay_transform),
 963                                                  _stack(igvn->_stack ),
 964                                                  _worklist(igvn->_worklist)
 965 {
 966   _iterGVN = true;
 967 }
 968 
 969 //------------------------------PhaseIterGVN-----------------------------------
 970 // Initialize with previous PhaseGVN info from Parser
 971 PhaseIterGVN::PhaseIterGVN(PhaseGVN* gvn) : PhaseGVN(gvn),
 972                                             _delay_transform(false),
 973 // TODO: Before incremental inlining it was allocated only once and it was fine. Now that
 974 //       the constructor is used in incremental inlining, this consumes too much memory:
 975 //                                            _stack(C->live_nodes() >> 1),
 976 //       So, as a band-aid, we replace this by:
 977                                             _stack(C->comp_arena(), 32),
 978                                             _worklist(*C->for_igvn())
 979 {
 980   _iterGVN = true;
 981   uint max;
 982 
 983   // Dead nodes in the hash table inherited from GVN were not treated as
 984   // roots during def-use info creation; hence they represent an invisible
 985   // use.  Clear them out.
 986   max = _table.size();
 987   for( uint i = 0; i < max; ++i ) {
 988     Node *n = _table.at(i);
 989     if(n != NULL && n != _table.sentinel() && n->outcnt() == 0) {
 990       if( n->is_top() ) continue;
 991       // If remove_useless_nodes() has run, we expect no such nodes left.
 992       assert(false, "remove_useless_nodes missed this node");
 993       hash_delete(n);
 994     }
 995   }
 996 
 997   // Any Phis or Regions on the worklist probably had uses that could not
 998   // make more progress because the uses were made while the Phis and Regions
 999   // were in half-built states.  Put all uses of Phis and Regions on worklist.
1000   max = _worklist.size();
1001   for( uint j = 0; j < max; j++ ) {
1002     Node *n = _worklist.at(j);
1003     uint uop = n->Opcode();
1004     if( uop == Op_Phi || uop == Op_Region ||
1005         n->is_Type() ||
1006         n->is_Mem() )
1007       add_users_to_worklist(n);
1008   }
1009 }
1010 
1011 void PhaseIterGVN::shuffle_worklist() {
1012   if (_worklist.size() < 2) return;
1013   for (uint i = _worklist.size() - 1; i >= 1; i--) {
1014     uint j = C->random() % (i + 1);
1015     swap(_worklist.adr()[i], _worklist.adr()[j]);
1016   }
1017 }
1018 
1019 #ifndef PRODUCT
1020 void PhaseIterGVN::verify_step(Node* n) {
1021   if (VerifyIterativeGVN) {
1022     ResourceMark rm;
1023     VectorSet visited;
1024     Node_List worklist;
1025 
1026     _verify_window[_verify_counter % _verify_window_size] = n;
1027     ++_verify_counter;
1028     if (C->unique() < 1000 || 0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
1029       ++_verify_full_passes;
1030       worklist.push(C->root());
1031       Node::verify(-1, visited, worklist);
1032       return;
1033     }
1034     for (int i = 0; i < _verify_window_size; i++) {
1035       Node* n = _verify_window[i];
1036       if (n == NULL) {
1037         continue;
1038       }
1039       if (n->in(0) == NodeSentinel) { // xform_idom
1040         _verify_window[i] = n->in(1);
1041         --i;
1042         continue;
1043       }
1044       // Typical fanout is 1-2, so this call visits about 6 nodes.
1045       if (!visited.test_set(n->_idx)) {
1046         worklist.push(n);
1047       }
1048     }
1049     Node::verify(4, visited, worklist);
1050   }
1051 }
1052 
1053 void PhaseIterGVN::trace_PhaseIterGVN(Node* n, Node* nn, const Type* oldtype) {
1054   if (TraceIterativeGVN) {
1055     uint wlsize = _worklist.size();
1056     const Type* newtype = type_or_null(n);
1057     if (nn != n) {
1058       // print old node
1059       tty->print("< ");
1060       if (oldtype != newtype && oldtype != NULL) {
1061         oldtype->dump();
1062       }
1063       do { tty->print("\t"); } while (tty->position() < 16);
1064       tty->print("<");
1065       n->dump();
1066     }
1067     if (oldtype != newtype || nn != n) {
1068       // print new node and/or new type
1069       if (oldtype == NULL) {
1070         tty->print("* ");
1071       } else if (nn != n) {
1072         tty->print("> ");
1073       } else {
1074         tty->print("= ");
1075       }
1076       if (newtype == NULL) {
1077         tty->print("null");
1078       } else {
1079         newtype->dump();
1080       }
1081       do { tty->print("\t"); } while (tty->position() < 16);
1082       nn->dump();
1083     }
1084     if (Verbose && wlsize < _worklist.size()) {
1085       tty->print("  Push {");
1086       while (wlsize != _worklist.size()) {
1087         Node* pushed = _worklist.at(wlsize++);
1088         tty->print(" %d", pushed->_idx);
1089       }
1090       tty->print_cr(" }");
1091     }
1092     if (nn != n) {
1093       // ignore n, it might be subsumed
1094       verify_step((Node*) NULL);
1095     }
1096   }
1097 }
1098 
1099 void PhaseIterGVN::init_verifyPhaseIterGVN() {
1100   _verify_counter = 0;
1101   _verify_full_passes = 0;
1102   for (int i = 0; i < _verify_window_size; i++) {
1103     _verify_window[i] = NULL;
1104   }
1105 #ifdef ASSERT
1106   // Verify that all modified nodes are on _worklist
1107   Unique_Node_List* modified_list = C->modified_nodes();
1108   while (modified_list != NULL && modified_list->size()) {
1109     Node* n = modified_list->pop();
1110     if (!n->is_Con() && !_worklist.member(n)) {
1111       n->dump();
1112       fatal("modified node is not on IGVN._worklist");
1113     }
1114   }
1115 #endif
1116 }
1117 
1118 void PhaseIterGVN::verify_PhaseIterGVN() {
1119 #ifdef ASSERT
1120   // Verify nodes with changed inputs.
1121   Unique_Node_List* modified_list = C->modified_nodes();
1122   while (modified_list != NULL && modified_list->size()) {
1123     Node* n = modified_list->pop();
1124     if (!n->is_Con()) { // skip Con nodes
1125       n->dump();
1126       fatal("modified node was not processed by IGVN.transform_old()");
1127     }
1128   }
1129 #endif
1130 
1131   C->verify_graph_edges();
1132   if (VerifyIterativeGVN && PrintOpto) {
1133     if (_verify_counter == _verify_full_passes) {
1134       tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
1135                     (int) _verify_full_passes);
1136     } else {
1137       tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
1138                   (int) _verify_counter, (int) _verify_full_passes);
1139     }
1140   }
1141 
1142 #ifdef ASSERT
1143   if (modified_list != NULL) {
1144     while (modified_list->size() > 0) {
1145       Node* n = modified_list->pop();
1146       n->dump();
1147       assert(false, "VerifyIterativeGVN: new modified node was added");
1148     }
1149   }
1150 #endif
1151 }
1152 #endif /* PRODUCT */
1153 
1154 #ifdef ASSERT
1155 /**
1156  * Dumps information that can help to debug the problem. A debug
1157  * build fails with an assert.
1158  */
1159 void PhaseIterGVN::dump_infinite_loop_info(Node* n, const char* where) {
1160   n->dump(4);
1161   _worklist.dump();
1162   assert(false, "infinite loop in %s", where);
1163 }
1164 
1165 /**
1166  * Prints out information about IGVN if the 'verbose' option is used.
1167  */
1168 void PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
1169   if (TraceIterativeGVN && Verbose) {
1170     tty->print("  Pop ");
1171     n->dump();
1172     if ((num_processed % 100) == 0) {
1173       _worklist.print_set();
1174     }
1175   }
1176 }
1177 #endif /* ASSERT */
1178 
1179 void PhaseIterGVN::optimize() {
1180   DEBUG_ONLY(uint num_processed  = 0;)
1181   NOT_PRODUCT(init_verifyPhaseIterGVN();)
1182   if (StressIGVN) {
1183     shuffle_worklist();
1184   }
1185 
1186   uint loop_count = 0;
1187   // Pull from worklist and transform the node. If the node has changed,
1188   // update edge info and put uses on worklist.
1189   while(_worklist.size()) {
1190     if (C->check_node_count(NodeLimitFudgeFactor * 2, "Out of nodes")) {
1191       return;
1192     }
1193     Node* n  = _worklist.pop();
1194     if (loop_count >= K * C->live_nodes()) {
1195       DEBUG_ONLY(dump_infinite_loop_info(n, "PhaseIterGVN::optimize");)
1196       C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1197       return;
1198     }
1199     DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1200     if (n->outcnt() != 0) {
1201       NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1202       // Do the transformation
1203       Node* nn = transform_old(n);
1204       NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1205     } else if (!n->is_top()) {
1206       remove_dead_node(n);
1207     }
1208     loop_count++;
1209   }
1210   NOT_PRODUCT(verify_PhaseIterGVN();)
1211 }
1212 
1213 
1214 /**
1215  * Register a new node with the optimizer.  Update the types array, the def-use
1216  * info.  Put on worklist.
1217  */
1218 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
1219   set_type_bottom(n);
1220   _worklist.push(n);
1221   if (orig != NULL)  C->copy_node_notes_to(n, orig);
1222   return n;
1223 }
1224 
1225 //------------------------------transform--------------------------------------
1226 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
1227 Node *PhaseIterGVN::transform( Node *n ) {
1228   // If brand new node, make space in type array, and give it a type.
1229   ensure_type_or_null(n);
1230   if (type_or_null(n) == NULL) {
1231     set_type_bottom(n);
1232   }
1233 
1234   if (_delay_transform) {
1235     // Add the node to the worklist but don't optimize for now
1236     _worklist.push(n);
1237     return n;
1238   }
1239 
1240   return transform_old(n);
1241 }
1242 
1243 Node *PhaseIterGVN::transform_old(Node* n) {
1244   NOT_PRODUCT(set_transforms());
1245   // Remove 'n' from hash table in case it gets modified
1246   _table.hash_delete(n);
1247   if (VerifyIterativeGVN) {
1248     assert(!_table.find_index(n->_idx), "found duplicate entry in table");
1249   }
1250 
1251   // Allow Bool -> Cmp idealisation in late inlining intrinsics that return a bool
1252   if (n->is_Cmp()) {
1253     add_users_to_worklist(n);
1254   }
1255 
1256   // Apply the Ideal call in a loop until it no longer applies
1257   Node* k = n;
1258   DEBUG_ONLY(dead_loop_check(k);)
1259   DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1260   C->remove_modified_node(k);
1261   Node* i = apply_ideal(k, /*can_reshape=*/true);
1262   assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1263 #ifndef PRODUCT
1264   verify_step(k);
1265 #endif
1266 
1267   DEBUG_ONLY(uint loop_count = 1;)
1268   while (i != NULL) {
1269 #ifdef ASSERT
1270     if (loop_count >= K + C->live_nodes()) {
1271       dump_infinite_loop_info(i, "PhaseIterGVN::transform_old");
1272     }
1273 #endif
1274     assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1275     // Made a change; put users of original Node on worklist
1276     add_users_to_worklist(k);
1277     // Replacing root of transform tree?
1278     if (k != i) {
1279       // Make users of old Node now use new.
1280       subsume_node(k, i);
1281       k = i;
1282     }
1283     DEBUG_ONLY(dead_loop_check(k);)
1284     // Try idealizing again
1285     DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1286     C->remove_modified_node(k);
1287     i = apply_ideal(k, /*can_reshape=*/true);
1288     assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
1289 #ifndef PRODUCT
1290     verify_step(k);
1291 #endif
1292     DEBUG_ONLY(loop_count++;)
1293   }
1294 
1295   // If brand new node, make space in type array.
1296   ensure_type_or_null(k);
1297 
1298   // See what kind of values 'k' takes on at runtime
1299   const Type* t = k->Value(this);
1300   assert(t != NULL, "value sanity");
1301 
1302   // Since I just called 'Value' to compute the set of run-time values
1303   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1304   // cache Value.  Later requests for the local phase->type of this Node can
1305   // use the cached Value instead of suffering with 'bottom_type'.
1306   if (type_or_null(k) != t) {
1307 #ifndef PRODUCT
1308     inc_new_values();
1309     set_progress();
1310 #endif
1311     set_type(k, t);
1312     // If k is a TypeNode, capture any more-precise type permanently into Node
1313     k->raise_bottom_type(t);
1314     // Move users of node to worklist
1315     add_users_to_worklist(k);
1316   }
1317   // If 'k' computes a constant, replace it with a constant
1318   if (t->singleton() && !k->is_Con()) {
1319     NOT_PRODUCT(set_progress();)
1320     Node* con = makecon(t);     // Make a constant
1321     add_users_to_worklist(k);
1322     subsume_node(k, con);       // Everybody using k now uses con
1323     return con;
1324   }
1325 
1326   // Now check for Identities
1327   i = k->Identity(this);      // Look for a nearby replacement
1328   if (i != k) {                // Found? Return replacement!
1329     NOT_PRODUCT(set_progress();)
1330     add_users_to_worklist(k);
1331     subsume_node(k, i);       // Everybody using k now uses i
1332     return i;
1333   }
1334 
1335   // Global Value Numbering
1336   i = hash_find_insert(k);      // Check for pre-existing node
1337   if (i && (i != k)) {
1338     // Return the pre-existing node if it isn't dead
1339     NOT_PRODUCT(set_progress();)
1340     add_users_to_worklist(k);
1341     subsume_node(k, i);       // Everybody using k now uses i
1342     return i;
1343   }
1344 
1345   // Return Idealized original
1346   return k;
1347 }
1348 
1349 //---------------------------------saturate------------------------------------
1350 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1351                                    const Type* limit_type) const {
1352   return new_type->narrow(old_type);
1353 }
1354 
1355 //------------------------------remove_globally_dead_node----------------------
1356 // Kill a globally dead Node.  All uses are also globally dead and are
1357 // aggressively trimmed.
1358 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1359   enum DeleteProgress {
1360     PROCESS_INPUTS,
1361     PROCESS_OUTPUTS
1362   };
1363   assert(_stack.is_empty(), "not empty");
1364   _stack.push(dead, PROCESS_INPUTS);
1365 
1366   while (_stack.is_nonempty()) {
1367     dead = _stack.node();
1368     if (dead->Opcode() == Op_SafePoint) {
1369       dead->as_SafePoint()->disconnect_from_root(this);
1370     }
1371     uint progress_state = _stack.index();
1372     assert(dead != C->root(), "killing root, eh?");
1373     assert(!dead->is_top(), "add check for top when pushing");
1374     NOT_PRODUCT( set_progress(); )
1375     if (progress_state == PROCESS_INPUTS) {
1376       // After following inputs, continue to outputs
1377       _stack.set_index(PROCESS_OUTPUTS);
1378       if (!dead->is_Con()) { // Don't kill cons but uses
1379         bool recurse = false;
1380         // Remove from hash table
1381         _table.hash_delete( dead );
1382         // Smash all inputs to 'dead', isolating him completely
1383         for (uint i = 0; i < dead->req(); i++) {
1384           Node *in = dead->in(i);
1385           if (in != NULL && in != C->top()) {  // Points to something?
1386             int nrep = dead->replace_edge(in, NULL, this);  // Kill edges
1387             assert((nrep > 0), "sanity");
1388             if (in->outcnt() == 0) { // Made input go dead?
1389               _stack.push(in, PROCESS_INPUTS); // Recursively remove
1390               recurse = true;
1391             } else if (in->outcnt() == 1 &&
1392                        in->has_special_unique_user()) {
1393               _worklist.push(in->unique_out());
1394             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1395               if (in->Opcode() == Op_Region) {
1396                 _worklist.push(in);
1397               } else if (in->is_Store()) {
1398                 DUIterator_Fast imax, i = in->fast_outs(imax);
1399                 _worklist.push(in->fast_out(i));
1400                 i++;
1401                 if (in->outcnt() == 2) {
1402                   _worklist.push(in->fast_out(i));
1403                   i++;
1404                 }
1405                 assert(!(i < imax), "sanity");
1406               }
1407             } else {
1408               BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
1409             }
1410             if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1411                 in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1412               // A Load that directly follows an InitializeNode is
1413               // going away. The Stores that follow are candidates
1414               // again to be captured by the InitializeNode.
1415               for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1416                 Node *n = in->fast_out(j);
1417                 if (n->is_Store()) {
1418                   _worklist.push(n);
1419                 }
1420               }
1421             }
1422           } // if (in != NULL && in != C->top())
1423         } // for (uint i = 0; i < dead->req(); i++)
1424         if (recurse) {
1425           continue;
1426         }
1427       } // if (!dead->is_Con())
1428     } // if (progress_state == PROCESS_INPUTS)
1429 
1430     // Aggressively kill globally dead uses
1431     // (Rather than pushing all the outs at once, we push one at a time,
1432     // plus the parent to resume later, because of the indefinite number
1433     // of edge deletions per loop trip.)
1434     if (dead->outcnt() > 0) {
1435       // Recursively remove output edges
1436       _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1437     } else {
1438       // Finished disconnecting all input and output edges.
1439       _stack.pop();
1440       // Remove dead node from iterative worklist
1441       _worklist.remove(dead);
1442       C->remove_useless_node(dead);
1443     }
1444   } // while (_stack.is_nonempty())
1445 }
1446 
1447 //------------------------------subsume_node-----------------------------------
1448 // Remove users from node 'old' and add them to node 'nn'.
1449 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1450   if (old->Opcode() == Op_SafePoint) {
1451     old->as_SafePoint()->disconnect_from_root(this);
1452   }
1453   assert( old != hash_find(old), "should already been removed" );
1454   assert( old != C->top(), "cannot subsume top node");
1455   // Copy debug or profile information to the new version:
1456   C->copy_node_notes_to(nn, old);
1457   // Move users of node 'old' to node 'nn'
1458   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1459     Node* use = old->last_out(i);  // for each use...
1460     // use might need re-hashing (but it won't if it's a new node)
1461     rehash_node_delayed(use);
1462     // Update use-def info as well
1463     // We remove all occurrences of old within use->in,
1464     // so as to avoid rehashing any node more than once.
1465     // The hash table probe swamps any outer loop overhead.
1466     uint num_edges = 0;
1467     for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1468       if (use->in(j) == old) {
1469         use->set_req(j, nn);
1470         ++num_edges;
1471       }
1472     }
1473     i -= num_edges;    // we deleted 1 or more copies of this edge
1474   }
1475 
1476   // Search for instance field data PhiNodes in the same region pointing to the old
1477   // memory PhiNode and update their instance memory ids to point to the new node.
1478   if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
1479     Node* region = old->in(0);
1480     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1481       PhiNode* phi = region->fast_out(i)->isa_Phi();
1482       if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
1483         phi->set_inst_mem_id((int)nn->_idx);
1484       }
1485     }
1486   }
1487 
1488   // Smash all inputs to 'old', isolating him completely
1489   Node *temp = new Node(1);
1490   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
1491   remove_dead_node( old );
1492   temp->del_req(0);         // Yank bogus edge
1493   if (nn != NULL && nn->outcnt() == 0) {
1494     _worklist.push(nn);
1495   }
1496 #ifndef PRODUCT
1497   if( VerifyIterativeGVN ) {
1498     for ( int i = 0; i < _verify_window_size; i++ ) {
1499       if ( _verify_window[i] == old )
1500         _verify_window[i] = nn;
1501     }
1502   }
1503 #endif
1504   temp->destruct(this);     // reuse the _idx of this little guy
1505 }
1506 
1507 void PhaseIterGVN::replace_in_uses(Node* n, Node* m) {
1508   assert(n != NULL, "sanity");
1509   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1510     Node* u = n->fast_out(i);
1511     if (u != n) {
1512       rehash_node_delayed(u);
1513       int nb = u->replace_edge(n, m);
1514       --i, imax -= nb;
1515     }
1516   }
1517   assert(n->outcnt() == 0, "all uses must be deleted");
1518 }
1519 
1520 //------------------------------add_users_to_worklist--------------------------
1521 void PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1522   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1523     _worklist.push(n->fast_out(i));  // Push on worklist
1524   }
1525 }
1526 
1527 // Return counted loop Phi if as a counted loop exit condition, cmp
1528 // compares the induction variable with n
1529 static PhiNode* countedloop_phi_from_cmp(CmpNode* cmp, Node* n) {
1530   for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
1531     Node* bol = cmp->fast_out(i);
1532     for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
1533       Node* iff = bol->fast_out(i2);
1534       if (iff->is_BaseCountedLoopEnd()) {
1535         BaseCountedLoopEndNode* cle = iff->as_BaseCountedLoopEnd();
1536         if (cle->limit() == n) {
1537           PhiNode* phi = cle->phi();
1538           if (phi != NULL) {
1539             return phi;
1540           }
1541         }
1542       }
1543     }
1544   }
1545   return NULL;
1546 }
1547 
1548 void PhaseIterGVN::add_users_to_worklist( Node *n ) {
1549   add_users_to_worklist0(n);
1550 
1551   // Move users of node to worklist
1552   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1553     Node* use = n->fast_out(i); // Get use
1554 
1555     if( use->is_Multi() ||      // Multi-definer?  Push projs on worklist
1556         use->is_Store() )       // Enable store/load same address
1557       add_users_to_worklist0(use);
1558 
1559     // If we changed the receiver type to a call, we need to revisit
1560     // the Catch following the call.  It's looking for a non-NULL
1561     // receiver to know when to enable the regular fall-through path
1562     // in addition to the NullPtrException path.
1563     if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1564       Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
1565       if (p != NULL) {
1566         add_users_to_worklist0(p);
1567       }
1568     }
1569 
1570     uint use_op = use->Opcode();
1571     if(use->is_Cmp()) {       // Enable CMP/BOOL optimization
1572       add_users_to_worklist(use); // Put Bool on worklist
1573       if (use->outcnt() > 0) {
1574         Node* bol = use->raw_out(0);
1575         if (bol->outcnt() > 0) {
1576           Node* iff = bol->raw_out(0);
1577           if (iff->outcnt() == 2) {
1578             // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1579             // phi merging either 0 or 1 onto the worklist
1580             Node* ifproj0 = iff->raw_out(0);
1581             Node* ifproj1 = iff->raw_out(1);
1582             if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1583               Node* region0 = ifproj0->raw_out(0);
1584               Node* region1 = ifproj1->raw_out(0);
1585               if( region0 == region1 )
1586                 add_users_to_worklist0(region0);
1587             }
1588           }
1589         }
1590       }
1591       if (use_op == Op_CmpI) {
1592         Node* phi = countedloop_phi_from_cmp((CmpINode*)use, n);
1593         if (phi != NULL) {
1594           // If an opaque node feeds into the limit condition of a
1595           // CountedLoop, we need to process the Phi node for the
1596           // induction variable when the opaque node is removed:
1597           // the range of values taken by the Phi is now known and
1598           // so its type is also known.
1599           _worklist.push(phi);
1600         }
1601         Node* in1 = use->in(1);
1602         for (uint i = 0; i < in1->outcnt(); i++) {
1603           if (in1->raw_out(i)->Opcode() == Op_CastII) {
1604             Node* castii = in1->raw_out(i);
1605             if (castii->in(0) != NULL && castii->in(0)->in(0) != NULL && castii->in(0)->in(0)->is_If()) {
1606               Node* ifnode = castii->in(0)->in(0);
1607               if (ifnode->in(1) != NULL && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == use) {
1608                 // Reprocess a CastII node that may depend on an
1609                 // opaque node value when the opaque node is
1610                 // removed. In case it carries a dependency we can do
1611                 // a better job of computing its type.
1612                 _worklist.push(castii);
1613               }
1614             }
1615           }
1616         }
1617       }
1618     }
1619 
1620     // Inline type nodes can have other inline types as users. If an input gets
1621     // updated, make sure that inline type users get a chance for optimization.
1622     if (use->is_InlineType()) {
1623       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1624         Node* u = use->fast_out(i2);
1625         if (u->is_InlineType())
1626           _worklist.push(u);
1627       }
1628     }
1629     // If changed Cast input, check Phi users for simple cycles
1630     if (use->is_ConstraintCast()) {
1631       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1632         Node* u = use->fast_out(i2);
1633         if (u->is_Phi())
1634           _worklist.push(u);
1635       }
1636     }
1637     // If changed LShift inputs, check RShift users for useless sign-ext
1638     if( use_op == Op_LShiftI ) {
1639       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1640         Node* u = use->fast_out(i2);
1641         if (u->Opcode() == Op_RShiftI)
1642           _worklist.push(u);
1643       }
1644     }
1645     // If changed AddI/SubI inputs, check CmpU for range check optimization.
1646     if (use_op == Op_AddI || use_op == Op_SubI) {
1647       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1648         Node* u = use->fast_out(i2);
1649         if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
1650           _worklist.push(u);
1651         }
1652       }
1653     }
1654     // If changed AddP inputs, check Stores for loop invariant
1655     if( use_op == Op_AddP ) {
1656       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1657         Node* u = use->fast_out(i2);
1658         if (u->is_Mem())
1659           _worklist.push(u);
1660       }
1661     }
1662     // If changed initialization activity, check dependent Stores
1663     if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1664       InitializeNode* init = use->as_Allocate()->initialization();
1665       if (init != NULL) {
1666         Node* imem = init->proj_out_or_null(TypeFunc::Memory);
1667         if (imem != NULL)  add_users_to_worklist0(imem);
1668       }
1669     }
1670     // If the ValidLengthTest input changes then the fallthrough path out of the AllocateArray may have become dead.
1671     // CatchNode::Value() is responsible for killing that path. The CatchNode has to be explicitly enqueued for igvn
1672     // to guarantee the change is not missed.
1673     if (use_op == Op_AllocateArray && n == use->in(AllocateNode::ValidLengthTest)) {
1674       Node* p = use->as_AllocateArray()->proj_out_or_null(TypeFunc::Control);
1675       if (p != NULL) {
1676         add_users_to_worklist0(p);
1677       }
1678     }
1679 
1680     if (use_op == Op_Initialize) {
1681       Node* imem = use->as_Initialize()->proj_out_or_null(TypeFunc::Memory);
1682       if (imem != NULL)  add_users_to_worklist0(imem);
1683     }
1684     if (use_op == Op_CastP2X) {
1685       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1686         Node* u = use->fast_out(i2);
1687         if (u->Opcode() == Op_AndX) {
1688           _worklist.push(u);
1689         }
1690       }
1691     }
1692     // Loading the java mirror from a Klass requires two loads and the type
1693     // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1694     //   LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
1695     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1696     bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1697 
1698     if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
1699       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1700         Node* u = use->fast_out(i2);
1701         const Type* ut = u->bottom_type();
1702         if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
1703           if (has_load_barrier_nodes) {
1704             // Search for load barriers behind the load
1705             for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1706               Node* b = u->fast_out(i3);
1707               if (bs->is_gc_barrier_node(b)) {
1708                 _worklist.push(b);
1709               }
1710             }
1711           }
1712           _worklist.push(u);
1713         }
1714       }
1715     }
1716 
1717     // Give CallStaticJavaNode::remove_useless_allocation a chance to run
1718     if (use->is_Region()) {
1719       Node* c = use;
1720       do {
1721         c = c->unique_ctrl_out_or_null();
1722       } while (c != NULL && c->is_Region());
1723       if (c != NULL && c->is_CallStaticJava() && c->as_CallStaticJava()->uncommon_trap_request() != 0) {
1724         _worklist.push(c);
1725       }
1726     }
1727     if (use->Opcode() == Op_OpaqueZeroTripGuard) {
1728       assert(use->outcnt() <= 1, "OpaqueZeroTripGuard can't be shared");
1729       if (use->outcnt() == 1) {
1730         Node* cmp = use->unique_out();
1731         _worklist.push(cmp);
1732       }
1733     }
1734   }
1735 }
1736 
1737 /**
1738  * Remove the speculative part of all types that we know of
1739  */
1740 void PhaseIterGVN::remove_speculative_types()  {
1741   assert(UseTypeSpeculation, "speculation is off");
1742   for (uint i = 0; i < _types.Size(); i++)  {
1743     const Type* t = _types.fast_lookup(i);
1744     if (t != NULL) {
1745       _types.map(i, t->remove_speculative());
1746     }
1747   }
1748   _table.check_no_speculative_types();
1749 }
1750 
1751 // Check if the type of a divisor of a Div or Mod node includes zero.
1752 bool PhaseIterGVN::no_dependent_zero_check(Node* n) const {
1753   switch (n->Opcode()) {
1754     case Op_DivI:
1755     case Op_ModI: {
1756       // Type of divisor includes 0?
1757       if (type(n->in(2)) == Type::TOP) {
1758         // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1759         return false;
1760       }
1761       const TypeInt* type_divisor = type(n->in(2))->is_int();
1762       return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1763     }
1764     case Op_DivL:
1765     case Op_ModL: {
1766       // Type of divisor includes 0?
1767       if (type(n->in(2)) == Type::TOP) {
1768         // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1769         return false;
1770       }
1771       const TypeLong* type_divisor = type(n->in(2))->is_long();
1772       return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1773     }
1774   }
1775   return true;
1776 }
1777 
1778 //=============================================================================
1779 #ifndef PRODUCT
1780 uint PhaseCCP::_total_invokes   = 0;
1781 uint PhaseCCP::_total_constants = 0;
1782 #endif
1783 //------------------------------PhaseCCP---------------------------------------
1784 // Conditional Constant Propagation, ala Wegman & Zadeck
1785 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
1786   NOT_PRODUCT( clear_constants(); )
1787   assert( _worklist.size() == 0, "" );
1788   // Clear out _nodes from IterGVN.  Must be clear to transform call.
1789   _nodes.clear();               // Clear out from IterGVN
1790   analyze();
1791 }
1792 
1793 #ifndef PRODUCT
1794 //------------------------------~PhaseCCP--------------------------------------
1795 PhaseCCP::~PhaseCCP() {
1796   inc_invokes();
1797   _total_constants += count_constants();
1798 }
1799 #endif
1800 
1801 
1802 #ifdef ASSERT
1803 static bool ccp_type_widens(const Type* t, const Type* t0) {
1804   assert(t->meet(t0) == t->remove_speculative(), "Not monotonic");
1805   switch (t->base() == t0->base() ? t->base() : Type::Top) {
1806   case Type::Int:
1807     assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1808     break;
1809   case Type::Long:
1810     assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1811     break;
1812   default:
1813     break;
1814   }
1815   return true;
1816 }
1817 #endif //ASSERT
1818 
1819 // In this analysis, all types are initially set to TOP. We iteratively call Value() on all nodes of the graph until
1820 // we reach a fixed-point (i.e. no types change anymore). We start with a list that only contains the root node. Each time
1821 // a new type is set, we push all uses of that node back to the worklist (in some cases, we also push grandchildren
1822 // or nodes even further down back to the worklist because their type could change as a result of the current type
1823 // change).
1824 void PhaseCCP::analyze() {
1825   // Initialize all types to TOP, optimistic analysis
1826   for (uint i = 0; i < C->unique(); i++)  {
1827     _types.map(i, Type::TOP);
1828   }
1829 
1830   // Push root onto worklist
1831   Unique_Node_List worklist;
1832   worklist.push(C->root());
1833   DEBUG_ONLY(Unique_Node_List worklist_verify;)
1834 
1835   assert(_root_and_safepoints.size() == 0, "must be empty (unused)");
1836   _root_and_safepoints.push(C->root());
1837 
1838   // Pull from worklist; compute new value; push changes out.
1839   // This loop is the meat of CCP.
1840   while (worklist.size() != 0) {
1841     Node* n = fetch_next_node(worklist);
1842     DEBUG_ONLY(worklist_verify.push(n);)
1843     if (n->is_SafePoint()) {
1844       // Make sure safepoints are processed by PhaseCCP::transform even if they are
1845       // not reachable from the bottom. Otherwise, infinite loops would be removed.
1846       _root_and_safepoints.push(n);
1847     }
1848     const Type* new_type = n->Value(this);
1849     if (new_type != type(n)) {
1850       assert(ccp_type_widens(new_type, type(n)), "ccp type must widen");
1851       dump_type_and_node(n, new_type);
1852       set_type(n, new_type);
1853       push_child_nodes_to_worklist(worklist, n);
1854     }
1855   }
1856   DEBUG_ONLY(verify_analyze(worklist_verify);)
1857 }
1858 
1859 #ifdef ASSERT
1860 // For every node n on verify list, check if type(n) == n->Value()
1861 // We have a list of exceptions, see comments in code.
1862 void PhaseCCP::verify_analyze(Unique_Node_List& worklist_verify) {
1863   bool failure = false;
1864   while (worklist_verify.size()) {
1865     Node* n = worklist_verify.pop();
1866     const Type* told = type(n);
1867     const Type* tnew = n->Value(this);
1868     if (told != tnew) {
1869       // Check special cases that are ok
1870       if (told->isa_integer(tnew->basic_type()) != nullptr) { // both either int or long
1871         const TypeInteger* t0 = told->is_integer(tnew->basic_type());
1872         const TypeInteger* t1 = tnew->is_integer(tnew->basic_type());
1873         if (t0->lo_as_long() == t1->lo_as_long() &&
1874             t0->hi_as_long() == t1->hi_as_long()) {
1875           continue; // ignore integer widen
1876         }
1877       }
1878       if (n->is_Load()) {
1879         // MemNode::can_see_stored_value looks up through many memory nodes,
1880         // which means we would need to notify modifications from far up in
1881         // the inputs all the way down to the LoadNode. We don't do that.
1882         continue;
1883       }
1884       tty->cr();
1885       tty->print_cr("Missed optimization (PhaseCCP):");
1886       n->dump_bfs(1, 0, "");
1887       tty->print_cr("Current type:");
1888       told->dump_on(tty);
1889       tty->cr();
1890       tty->print_cr("Optimized type:");
1891       tnew->dump_on(tty);
1892       tty->cr();
1893       failure = true;
1894     }
1895   }
1896   // If we get this assert, check why the reported nodes were not processed again in CCP.
1897   // We should either make sure that these nodes are properly added back to the CCP worklist
1898   // in PhaseCCP::push_child_nodes_to_worklist() to update their type or add an exception
1899   // in the verification code above if that is not possible for some reason (like Load nodes).
1900   assert(!failure, "Missed optimization opportunity in PhaseCCP");
1901 }
1902 #endif
1903 
1904 // Fetch next node from worklist to be examined in this iteration.
1905 Node* PhaseCCP::fetch_next_node(Unique_Node_List& worklist) {
1906   if (StressCCP) {
1907     return worklist.remove(C->random() % worklist.size());
1908   } else {
1909     return worklist.pop();
1910   }
1911 }
1912 
1913 #ifndef PRODUCT
1914 void PhaseCCP::dump_type_and_node(const Node* n, const Type* t) {
1915   if (TracePhaseCCP) {
1916     t->dump();
1917     do {
1918       tty->print("\t");
1919     } while (tty->position() < 16);
1920     n->dump();
1921   }
1922 }
1923 #endif
1924 
1925 // We need to propagate the type change of 'n' to all its uses. Depending on the kind of node, additional nodes
1926 // (grandchildren or even further down) need to be revisited as their types could also be improved as a result
1927 // of the new type of 'n'. Push these nodes to the worklist.
1928 void PhaseCCP::push_child_nodes_to_worklist(Unique_Node_List& worklist, Node* n) const {
1929   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1930     Node* use = n->fast_out(i);
1931     push_if_not_bottom_type(worklist, use);
1932     push_more_uses(worklist, n, use);
1933   }
1934 }
1935 
1936 void PhaseCCP::push_if_not_bottom_type(Unique_Node_List& worklist, Node* n) const {
1937   if (n->bottom_type() != type(n)) {
1938     worklist.push(n);
1939   }
1940 }
1941 
1942 // For some nodes, we need to propagate the type change to grandchildren or even further down.
1943 // Add them back to the worklist.
1944 void PhaseCCP::push_more_uses(Unique_Node_List& worklist, Node* parent, const Node* use) const {
1945   push_phis(worklist, use);
1946   push_catch(worklist, use);
1947   push_cmpu(worklist, use);
1948   push_counted_loop_phi(worklist, parent, use);
1949   push_cast(worklist, use);
1950   push_loadp(worklist, use);
1951   push_and(worklist, parent, use);
1952   push_cast_ii(worklist, parent, use);
1953   push_opaque_zero_trip_guard(worklist, use);
1954 }
1955 
1956 
1957 // We must recheck Phis too if use is a Region.
1958 void PhaseCCP::push_phis(Unique_Node_List& worklist, const Node* use) const {
1959   if (use->is_Region()) {
1960     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
1961       push_if_not_bottom_type(worklist, use->fast_out(i));
1962     }
1963   }
1964 }
1965 
1966 // If we changed the receiver type to a call, we need to revisit the Catch node following the call. It's looking for a
1967 // non-NULL receiver to know when to enable the regular fall-through path in addition to the NullPtrException path.
1968 // Same is true if the type of a ValidLengthTest input to an AllocateArrayNode changes.
1969 void PhaseCCP::push_catch(Unique_Node_List& worklist, const Node* use) {
1970   if (use->is_Call()) {
1971     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
1972       Node* proj = use->fast_out(i);
1973       if (proj->is_Proj() && proj->as_Proj()->_con == TypeFunc::Control) {
1974         Node* catch_node = proj->find_out_with(Op_Catch);
1975         if (catch_node != NULL) {
1976           worklist.push(catch_node);
1977         }
1978       }
1979     }
1980   }
1981 }
1982 
1983 // CmpU nodes can get their type information from two nodes up in the graph (instead of from the nodes immediately
1984 // above). Make sure they are added to the worklist if nodes they depend on are updated since they could be missed
1985 // and get wrong types otherwise.
1986 void PhaseCCP::push_cmpu(Unique_Node_List& worklist, const Node* use) const {
1987   uint use_op = use->Opcode();
1988   if (use_op == Op_AddI || use_op == Op_SubI) {
1989     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
1990       Node* cmpu = use->fast_out(i);
1991       if (cmpu->Opcode() == Op_CmpU) {
1992         // Got a CmpU which might need the new type information from node n.
1993         push_if_not_bottom_type(worklist, cmpu);
1994       }
1995     }
1996   }
1997 }
1998 
1999 // If n is used in a counted loop exit condition, then the type of the counted loop's Phi depends on the type of 'n'.
2000 // Seem PhiNode::Value().
2001 void PhaseCCP::push_counted_loop_phi(Unique_Node_List& worklist, Node* parent, const Node* use) {
2002   uint use_op = use->Opcode();
2003   if (use_op == Op_CmpI || use_op == Op_CmpL) {
2004     PhiNode* phi = countedloop_phi_from_cmp(use->as_Cmp(), parent);
2005     if (phi != NULL) {
2006       worklist.push(phi);
2007     }
2008   }
2009 }
2010 
2011 void PhaseCCP::push_cast(Unique_Node_List& worklist, const Node* use) {
2012   uint use_op = use->Opcode();
2013   if (use_op == Op_CastP2X) {
2014     for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2015       Node* u = use->fast_out(i2);
2016       if (u->Opcode() == Op_AndX) {
2017         worklist.push(u);
2018       }
2019     }
2020   }
2021 }
2022 
2023 // Loading the java mirror from a Klass requires two loads and the type of the mirror load depends on the type of 'n'.
2024 // See LoadNode::Value().
2025 void PhaseCCP::push_loadp(Unique_Node_List& worklist, const Node* use) const {
2026   BarrierSetC2* barrier_set = BarrierSet::barrier_set()->barrier_set_c2();
2027   bool has_load_barrier_nodes = barrier_set->has_load_barrier_nodes();
2028 
2029   if (use->Opcode() == Op_LoadP && use->bottom_type()->isa_rawptr()) {
2030     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2031       Node* loadp = use->fast_out(i);
2032       const Type* ut = loadp->bottom_type();
2033       if (loadp->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(loadp)) {
2034         if (has_load_barrier_nodes) {
2035           // Search for load barriers behind the load
2036           push_load_barrier(worklist, barrier_set, loadp);
2037         }
2038         worklist.push(loadp);
2039       }
2040     }
2041   }
2042 }
2043 
2044 void PhaseCCP::push_load_barrier(Unique_Node_List& worklist, const BarrierSetC2* barrier_set, const Node* use) {
2045   for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2046     Node* barrier_node = use->fast_out(i);
2047     if (barrier_set->is_gc_barrier_node(barrier_node)) {
2048       worklist.push(barrier_node);
2049     }
2050   }
2051 }
2052 
2053 // AndI/L::Value() optimizes patterns similar to (v << 2) & 3 to zero if they are bitwise disjoint.
2054 // Add the AndI/L nodes back to the worklist to re-apply Value() in case the shift value changed.
2055 void PhaseCCP::push_and(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
2056   uint use_op = use->Opcode();
2057   if ((use_op == Op_LShiftI || use_op == Op_LShiftL)
2058       && use->in(2) == parent) { // is shift value (right-hand side of LShift)
2059     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2060       Node* and_node = use->fast_out(i);
2061       uint and_node_op = and_node->Opcode();
2062       if (and_node_op == Op_AndI || and_node_op == Op_AndL) {
2063         push_if_not_bottom_type(worklist, and_node);
2064       }
2065     }
2066   }
2067 }
2068 
2069 // CastII::Value() optimizes CmpI/If patterns if the right input of the CmpI has a constant type. If the CastII input is
2070 // the same node as the left input into the CmpI node, the type of the CastII node can be improved accordingly. Add the
2071 // CastII node back to the worklist to re-apply Value() to either not miss this optimization or to undo it because it
2072 // cannot be applied anymore. We could have optimized the type of the CastII before but now the type of the right input
2073 // of the CmpI (i.e. 'parent') is no longer constant. The type of the CastII must be widened in this case.
2074 void PhaseCCP::push_cast_ii(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
2075   if (use->Opcode() == Op_CmpI && use->in(2) == parent) {
2076     Node* other_cmp_input = use->in(1);
2077     for (DUIterator_Fast imax, i = other_cmp_input->fast_outs(imax); i < imax; i++) {
2078       Node* cast_ii = other_cmp_input->fast_out(i);
2079       if (cast_ii->is_CastII()) {
2080         push_if_not_bottom_type(worklist, cast_ii);
2081       }
2082     }
2083   }
2084 }
2085 
2086 void PhaseCCP::push_opaque_zero_trip_guard(Unique_Node_List& worklist, const Node* use) const {
2087   if (use->Opcode() == Op_OpaqueZeroTripGuard) {
2088     push_if_not_bottom_type(worklist, use->unique_out());
2089   }
2090 }
2091 
2092 //------------------------------do_transform-----------------------------------
2093 // Top level driver for the recursive transformer
2094 void PhaseCCP::do_transform() {
2095   // Correct leaves of new-space Nodes; they point to old-space.
2096   C->set_root( transform(C->root())->as_Root() );
2097   assert( C->top(),  "missing TOP node" );
2098   assert( C->root(), "missing root" );
2099 }
2100 
2101 //------------------------------transform--------------------------------------
2102 // Given a Node in old-space, clone him into new-space.
2103 // Convert any of his old-space children into new-space children.
2104 Node *PhaseCCP::transform( Node *n ) {
2105   Node *new_node = _nodes[n->_idx]; // Check for transformed node
2106   if( new_node != NULL )
2107     return new_node;                // Been there, done that, return old answer
2108 
2109   assert(n->is_Root(), "traversal must start at root");
2110   assert(_root_and_safepoints.member(n), "root (n) must be in list");
2111 
2112   // Allocate stack of size _nodes.Size()/2 to avoid frequent realloc
2113   GrowableArray <Node *> transform_stack(C->live_nodes() >> 1);
2114   Unique_Node_List useful; // track all visited nodes, so that we can remove the complement
2115 
2116   // Initialize the traversal.
2117   // This CCP pass may prove that no exit test for a loop ever succeeds (i.e. the loop is infinite). In that case,
2118   // the logic below doesn't follow any path from Root to the loop body: there's at least one such path but it's proven
2119   // never taken (its type is TOP). As a consequence the node on the exit path that's input to Root (let's call it n) is
2120   // replaced by the top node and the inputs of that node n are not enqueued for further processing. If CCP only works
2121   // through the graph from Root, this causes the loop body to never be processed here even when it's not dead (that
2122   // is reachable from Root following its uses). To prevent that issue, transform() starts walking the graph from Root
2123   // and all safepoints.
2124   for (uint i = 0; i < _root_and_safepoints.size(); ++i) {
2125     Node* nn = _root_and_safepoints.at(i);
2126     Node* new_node = _nodes[nn->_idx];
2127     assert(new_node == NULL, "");
2128     new_node = transform_once(nn);  // Check for constant
2129     _nodes.map(nn->_idx, new_node); // Flag as having been cloned
2130     transform_stack.push(new_node); // Process children of cloned node
2131     useful.push(new_node);
2132   }
2133 
2134   while (transform_stack.is_nonempty()) {
2135     Node* clone = transform_stack.pop();
2136     uint cnt = clone->req();
2137     for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
2138       Node *input = clone->in(i);
2139       if( input != NULL ) {                    // Ignore NULLs
2140         Node *new_input = _nodes[input->_idx]; // Check for cloned input node
2141         if( new_input == NULL ) {
2142           new_input = transform_once(input);   // Check for constant
2143           _nodes.map( input->_idx, new_input );// Flag as having been cloned
2144           transform_stack.push(new_input);     // Process children of cloned node
2145           useful.push(new_input);
2146         }
2147         assert( new_input == clone->in(i), "insanity check");
2148       }
2149     }
2150   }
2151 
2152   // The above transformation might lead to subgraphs becoming unreachable from the
2153   // bottom while still being reachable from the top. As a result, nodes in that
2154   // subgraph are not transformed and their bottom types are not updated, leading to
2155   // an inconsistency between bottom_type() and type(). In rare cases, LoadNodes in
2156   // such a subgraph, might be re-enqueued for IGVN indefinitely by MemNode::Ideal_common
2157   // because their address type is inconsistent. Therefore, we aggressively remove
2158   // all useless nodes here even before PhaseIdealLoop::build_loop_late gets a chance
2159   // to remove them anyway.
2160   if (C->cached_top_node()) {
2161     useful.push(C->cached_top_node());
2162   }
2163   C->update_dead_node_list(useful);
2164   remove_useless_nodes(useful.member_set());
2165   _worklist.remove_useless_nodes(useful.member_set());
2166   C->disconnect_useless_nodes(useful, &_worklist);
2167 
2168   Node* new_root = _nodes[n->_idx];
2169   assert(new_root->is_Root(), "transformed root node must be a root node");
2170   return new_root;
2171 }
2172 
2173 
2174 //------------------------------transform_once---------------------------------
2175 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
2176 Node *PhaseCCP::transform_once( Node *n ) {
2177   const Type *t = type(n);
2178   // Constant?  Use constant Node instead
2179   if( t->singleton() ) {
2180     Node *nn = n;               // Default is to return the original constant
2181     if( t == Type::TOP ) {
2182       // cache my top node on the Compile instance
2183       if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
2184         C->set_cached_top_node(ConNode::make(Type::TOP));
2185         set_type(C->top(), Type::TOP);
2186       }
2187       nn = C->top();
2188     }
2189     if( !n->is_Con() ) {
2190       if( t != Type::TOP ) {
2191         nn = makecon(t);        // ConNode::make(t);
2192         NOT_PRODUCT( inc_constants(); )
2193       } else if( n->is_Region() ) { // Unreachable region
2194         // Note: nn == C->top()
2195         n->set_req(0, NULL);        // Cut selfreference
2196         bool progress = true;
2197         uint max = n->outcnt();
2198         DUIterator i;
2199         while (progress) {
2200           progress = false;
2201           // Eagerly remove dead phis to avoid phis copies creation.
2202           for (i = n->outs(); n->has_out(i); i++) {
2203             Node* m = n->out(i);
2204             if (m->is_Phi()) {
2205               assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
2206               replace_node(m, nn);
2207               if (max != n->outcnt()) {
2208                 progress = true;
2209                 i = n->refresh_out_pos(i);
2210                 max = n->outcnt();
2211               }
2212             }
2213           }
2214         }
2215       }
2216       replace_node(n,nn);       // Update DefUse edges for new constant
2217     }
2218     return nn;
2219   }
2220 
2221   // If x is a TypeNode, capture any more-precise type permanently into Node
2222   if (t != n->bottom_type()) {
2223     hash_delete(n);             // changing bottom type may force a rehash
2224     n->raise_bottom_type(t);
2225     _worklist.push(n);          // n re-enters the hash table via the worklist
2226   }
2227 
2228   // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
2229   switch( n->Opcode() ) {
2230   case Op_CallStaticJava:  // Give post-parse call devirtualization a chance
2231   case Op_CallDynamicJava:
2232   case Op_FastLock:        // Revisit FastLocks for lock coarsening
2233   case Op_If:
2234   case Op_CountedLoopEnd:
2235   case Op_Region:
2236   case Op_Loop:
2237   case Op_CountedLoop:
2238   case Op_Conv2B:
2239   case Op_Opaque1:
2240     _worklist.push(n);
2241     break;
2242   default:
2243     break;
2244   }
2245 
2246   return  n;
2247 }
2248 
2249 //---------------------------------saturate------------------------------------
2250 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
2251                                const Type* limit_type) const {
2252   const Type* wide_type = new_type->widen(old_type, limit_type);
2253   if (wide_type != new_type) {          // did we widen?
2254     // If so, we may have widened beyond the limit type.  Clip it back down.
2255     new_type = wide_type->filter(limit_type);
2256   }
2257   return new_type;
2258 }
2259 
2260 //------------------------------print_statistics-------------------------------
2261 #ifndef PRODUCT
2262 void PhaseCCP::print_statistics() {
2263   tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
2264 }
2265 #endif
2266 
2267 
2268 //=============================================================================
2269 #ifndef PRODUCT
2270 uint PhasePeephole::_total_peepholes = 0;
2271 #endif
2272 //------------------------------PhasePeephole----------------------------------
2273 // Conditional Constant Propagation, ala Wegman & Zadeck
2274 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
2275   : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
2276   NOT_PRODUCT( clear_peepholes(); )
2277 }
2278 
2279 #ifndef PRODUCT
2280 //------------------------------~PhasePeephole---------------------------------
2281 PhasePeephole::~PhasePeephole() {
2282   _total_peepholes += count_peepholes();
2283 }
2284 #endif
2285 
2286 //------------------------------transform--------------------------------------
2287 Node *PhasePeephole::transform( Node *n ) {
2288   ShouldNotCallThis();
2289   return NULL;
2290 }
2291 
2292 //------------------------------do_transform-----------------------------------
2293 void PhasePeephole::do_transform() {
2294   bool method_name_not_printed = true;
2295 
2296   // Examine each basic block
2297   for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
2298     Block* block = _cfg.get_block(block_number);
2299     bool block_not_printed = true;
2300 
2301     for (bool progress = true; progress;) {
2302       progress = false;
2303       // block->end_idx() not valid after PhaseRegAlloc
2304       uint end_index = block->number_of_nodes();
2305       for( uint instruction_index = end_index - 1; instruction_index > 0; --instruction_index ) {
2306         Node     *n = block->get_node(instruction_index);
2307         if( n->is_Mach() ) {
2308           MachNode *m = n->as_Mach();
2309           // check for peephole opportunities
2310           int result = m->peephole(block, instruction_index, &_cfg, _regalloc);
2311           if( result != -1 ) {
2312 #ifndef PRODUCT
2313             if( PrintOptoPeephole ) {
2314               // Print method, first time only
2315               if( C->method() && method_name_not_printed ) {
2316                 C->method()->print_short_name(); tty->cr();
2317                 method_name_not_printed = false;
2318               }
2319               // Print this block
2320               if( Verbose && block_not_printed) {
2321                 tty->print_cr("in block");
2322                 block->dump();
2323                 block_not_printed = false;
2324               }
2325               // Print the peephole number
2326               tty->print_cr("peephole number: %d", result);
2327             }
2328             inc_peepholes();
2329 #endif
2330             // Set progress, start again
2331             progress = true;
2332             break;
2333           }
2334         }
2335       }
2336     }
2337   }
2338 }
2339 
2340 //------------------------------print_statistics-------------------------------
2341 #ifndef PRODUCT
2342 void PhasePeephole::print_statistics() {
2343   tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
2344 }
2345 #endif
2346 
2347 
2348 //=============================================================================
2349 //------------------------------set_req_X--------------------------------------
2350 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
2351   assert( is_not_dead(n), "can not use dead node");
2352   assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
2353   Node *old = in(i);
2354   set_req(i, n);
2355 
2356   // old goes dead?
2357   if( old ) {
2358     switch (old->outcnt()) {
2359     case 0:
2360       // Put into the worklist to kill later. We do not kill it now because the
2361       // recursive kill will delete the current node (this) if dead-loop exists
2362       if (!old->is_top())
2363         igvn->_worklist.push( old );
2364       break;
2365     case 1:
2366       if( old->is_Store() || old->has_special_unique_user() )
2367         igvn->add_users_to_worklist( old );
2368       break;
2369     case 2:
2370       if( old->is_Store() )
2371         igvn->add_users_to_worklist( old );
2372       if( old->Opcode() == Op_Region )
2373         igvn->_worklist.push(old);
2374       break;
2375     case 3:
2376       if( old->Opcode() == Op_Region ) {
2377         igvn->_worklist.push(old);
2378         igvn->add_users_to_worklist( old );
2379       }
2380       break;
2381     default:
2382       break;
2383     }
2384 
2385     BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
2386   }
2387 }
2388 
2389 void Node::set_req_X(uint i, Node *n, PhaseGVN *gvn) {
2390   PhaseIterGVN* igvn = gvn->is_IterGVN();
2391   if (igvn == NULL) {
2392     set_req(i, n);
2393     return;
2394   }
2395   set_req_X(i, n, igvn);
2396 }
2397 
2398 //-------------------------------replace_by-----------------------------------
2399 // Using def-use info, replace one node for another.  Follow the def-use info
2400 // to all users of the OLD node.  Then make all uses point to the NEW node.
2401 void Node::replace_by(Node *new_node) {
2402   assert(!is_top(), "top node has no DU info");
2403   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
2404     Node* use = last_out(i);
2405     uint uses_found = 0;
2406     for (uint j = 0; j < use->len(); j++) {
2407       if (use->in(j) == this) {
2408         if (j < use->req())
2409               use->set_req(j, new_node);
2410         else  use->set_prec(j, new_node);
2411         uses_found++;
2412       }
2413     }
2414     i -= uses_found;    // we deleted 1 or more copies of this edge
2415   }
2416 }
2417 
2418 //=============================================================================
2419 //-----------------------------------------------------------------------------
2420 void Type_Array::grow( uint i ) {
2421   if( !_max ) {
2422     _max = 1;
2423     _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
2424     _types[0] = NULL;
2425   }
2426   uint old = _max;
2427   _max = next_power_of_2(i);
2428   _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
2429   memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
2430 }
2431 
2432 //------------------------------dump-------------------------------------------
2433 #ifndef PRODUCT
2434 void Type_Array::dump() const {
2435   uint max = Size();
2436   for( uint i = 0; i < max; i++ ) {
2437     if( _types[i] != NULL ) {
2438       tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
2439     }
2440   }
2441 }
2442 #endif