1 /*
   2  * Copyright (c) 1997, 2021, 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   // Apply the Ideal call in a loop until it no longer applies
1252   Node* k = n;
1253   DEBUG_ONLY(dead_loop_check(k);)
1254   DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1255   C->remove_modified_node(k);
1256   Node* i = apply_ideal(k, /*can_reshape=*/true);
1257   assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1258 #ifndef PRODUCT
1259   verify_step(k);
1260 #endif
1261 
1262   DEBUG_ONLY(uint loop_count = 1;)
1263   while (i != NULL) {
1264 #ifdef ASSERT
1265     if (loop_count >= K + C->live_nodes()) {
1266       dump_infinite_loop_info(i, "PhaseIterGVN::transform_old");
1267     }
1268 #endif
1269     assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1270     // Made a change; put users of original Node on worklist
1271     add_users_to_worklist(k);
1272     // Replacing root of transform tree?
1273     if (k != i) {
1274       // Make users of old Node now use new.
1275       subsume_node(k, i);
1276       k = i;
1277     }
1278     DEBUG_ONLY(dead_loop_check(k);)
1279     // Try idealizing again
1280     DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1281     C->remove_modified_node(k);
1282     i = apply_ideal(k, /*can_reshape=*/true);
1283     assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
1284 #ifndef PRODUCT
1285     verify_step(k);
1286 #endif
1287     DEBUG_ONLY(loop_count++;)
1288   }
1289 
1290   // If brand new node, make space in type array.
1291   ensure_type_or_null(k);
1292 
1293   // See what kind of values 'k' takes on at runtime
1294   const Type* t = k->Value(this);
1295   assert(t != NULL, "value sanity");
1296 
1297   // Since I just called 'Value' to compute the set of run-time values
1298   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1299   // cache Value.  Later requests for the local phase->type of this Node can
1300   // use the cached Value instead of suffering with 'bottom_type'.
1301   if (type_or_null(k) != t) {
1302 #ifndef PRODUCT
1303     inc_new_values();
1304     set_progress();
1305 #endif
1306     set_type(k, t);
1307     // If k is a TypeNode, capture any more-precise type permanently into Node
1308     k->raise_bottom_type(t);
1309     // Move users of node to worklist
1310     add_users_to_worklist(k);
1311   }
1312   // If 'k' computes a constant, replace it with a constant
1313   if (t->singleton() && !k->is_Con()) {
1314     NOT_PRODUCT(set_progress();)
1315     Node* con = makecon(t);     // Make a constant
1316     add_users_to_worklist(k);
1317     subsume_node(k, con);       // Everybody using k now uses con
1318     return con;
1319   }
1320 
1321   // Now check for Identities
1322   i = k->Identity(this);      // Look for a nearby replacement
1323   if (i != k) {                // Found? Return replacement!
1324     NOT_PRODUCT(set_progress();)
1325     add_users_to_worklist(k);
1326     subsume_node(k, i);       // Everybody using k now uses i
1327     return i;
1328   }
1329 
1330   // Global Value Numbering
1331   i = hash_find_insert(k);      // Check for pre-existing node
1332   if (i && (i != k)) {
1333     // Return the pre-existing node if it isn't dead
1334     NOT_PRODUCT(set_progress();)
1335     add_users_to_worklist(k);
1336     subsume_node(k, i);       // Everybody using k now uses i
1337     return i;
1338   }
1339 
1340   // Return Idealized original
1341   return k;
1342 }
1343 
1344 //---------------------------------saturate------------------------------------
1345 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1346                                    const Type* limit_type) const {
1347   return new_type->narrow(old_type);
1348 }
1349 
1350 //------------------------------remove_globally_dead_node----------------------
1351 // Kill a globally dead Node.  All uses are also globally dead and are
1352 // aggressively trimmed.
1353 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1354   enum DeleteProgress {
1355     PROCESS_INPUTS,
1356     PROCESS_OUTPUTS
1357   };
1358   assert(_stack.is_empty(), "not empty");
1359   _stack.push(dead, PROCESS_INPUTS);
1360 
1361   while (_stack.is_nonempty()) {
1362     dead = _stack.node();
1363     if (dead->Opcode() == Op_SafePoint) {
1364       dead->as_SafePoint()->disconnect_from_root(this);
1365     }
1366     uint progress_state = _stack.index();
1367     assert(dead != C->root(), "killing root, eh?");
1368     assert(!dead->is_top(), "add check for top when pushing");
1369     NOT_PRODUCT( set_progress(); )
1370     if (progress_state == PROCESS_INPUTS) {
1371       // After following inputs, continue to outputs
1372       _stack.set_index(PROCESS_OUTPUTS);
1373       if (!dead->is_Con()) { // Don't kill cons but uses
1374         bool recurse = false;
1375         // Remove from hash table
1376         _table.hash_delete( dead );
1377         // Smash all inputs to 'dead', isolating him completely
1378         for (uint i = 0; i < dead->req(); i++) {
1379           Node *in = dead->in(i);
1380           if (in != NULL && in != C->top()) {  // Points to something?
1381             int nrep = dead->replace_edge(in, NULL, this);  // Kill edges
1382             assert((nrep > 0), "sanity");
1383             if (in->outcnt() == 0) { // Made input go dead?
1384               _stack.push(in, PROCESS_INPUTS); // Recursively remove
1385               recurse = true;
1386             } else if (in->outcnt() == 1 &&
1387                        in->has_special_unique_user()) {
1388               _worklist.push(in->unique_out());
1389             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1390               if (in->Opcode() == Op_Region) {
1391                 _worklist.push(in);
1392               } else if (in->is_Store()) {
1393                 DUIterator_Fast imax, i = in->fast_outs(imax);
1394                 _worklist.push(in->fast_out(i));
1395                 i++;
1396                 if (in->outcnt() == 2) {
1397                   _worklist.push(in->fast_out(i));
1398                   i++;
1399                 }
1400                 assert(!(i < imax), "sanity");
1401               }
1402             } else {
1403               BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
1404             }
1405             if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1406                 in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1407               // A Load that directly follows an InitializeNode is
1408               // going away. The Stores that follow are candidates
1409               // again to be captured by the InitializeNode.
1410               for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1411                 Node *n = in->fast_out(j);
1412                 if (n->is_Store()) {
1413                   _worklist.push(n);
1414                 }
1415               }
1416             }
1417           } // if (in != NULL && in != C->top())
1418         } // for (uint i = 0; i < dead->req(); i++)
1419         if (recurse) {
1420           continue;
1421         }
1422       } // if (!dead->is_Con())
1423     } // if (progress_state == PROCESS_INPUTS)
1424 
1425     // Aggressively kill globally dead uses
1426     // (Rather than pushing all the outs at once, we push one at a time,
1427     // plus the parent to resume later, because of the indefinite number
1428     // of edge deletions per loop trip.)
1429     if (dead->outcnt() > 0) {
1430       // Recursively remove output edges
1431       _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1432     } else {
1433       // Finished disconnecting all input and output edges.
1434       _stack.pop();
1435       // Remove dead node from iterative worklist
1436       _worklist.remove(dead);
1437       C->remove_useless_node(dead);
1438     }
1439   } // while (_stack.is_nonempty())
1440 }
1441 
1442 //------------------------------subsume_node-----------------------------------
1443 // Remove users from node 'old' and add them to node 'nn'.
1444 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1445   if (old->Opcode() == Op_SafePoint) {
1446     old->as_SafePoint()->disconnect_from_root(this);
1447   }
1448   assert( old != hash_find(old), "should already been removed" );
1449   assert( old != C->top(), "cannot subsume top node");
1450   // Copy debug or profile information to the new version:
1451   C->copy_node_notes_to(nn, old);
1452   // Move users of node 'old' to node 'nn'
1453   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1454     Node* use = old->last_out(i);  // for each use...
1455     // use might need re-hashing (but it won't if it's a new node)
1456     rehash_node_delayed(use);
1457     // Update use-def info as well
1458     // We remove all occurrences of old within use->in,
1459     // so as to avoid rehashing any node more than once.
1460     // The hash table probe swamps any outer loop overhead.
1461     uint num_edges = 0;
1462     for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1463       if (use->in(j) == old) {
1464         use->set_req(j, nn);
1465         ++num_edges;
1466       }
1467     }
1468     i -= num_edges;    // we deleted 1 or more copies of this edge
1469   }
1470 
1471   // Search for instance field data PhiNodes in the same region pointing to the old
1472   // memory PhiNode and update their instance memory ids to point to the new node.
1473   if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
1474     Node* region = old->in(0);
1475     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1476       PhiNode* phi = region->fast_out(i)->isa_Phi();
1477       if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
1478         phi->set_inst_mem_id((int)nn->_idx);
1479       }
1480     }
1481   }
1482 
1483   // Smash all inputs to 'old', isolating him completely
1484   Node *temp = new Node(1);
1485   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
1486   remove_dead_node( old );
1487   temp->del_req(0);         // Yank bogus edge
1488   if (nn != NULL && nn->outcnt() == 0) {
1489     _worklist.push(nn);
1490   }
1491 #ifndef PRODUCT
1492   if( VerifyIterativeGVN ) {
1493     for ( int i = 0; i < _verify_window_size; i++ ) {
1494       if ( _verify_window[i] == old )
1495         _verify_window[i] = nn;
1496     }
1497   }
1498 #endif
1499   temp->destruct(this);     // reuse the _idx of this little guy
1500 }
1501 
1502 void PhaseIterGVN::replace_in_uses(Node* n, Node* m) {
1503   assert(n != NULL, "sanity");
1504   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1505     Node* u = n->fast_out(i);
1506     if (u != n) {
1507       rehash_node_delayed(u);
1508       int nb = u->replace_edge(n, m);
1509       --i, imax -= nb;
1510     }
1511   }
1512   assert(n->outcnt() == 0, "all uses must be deleted");
1513 }
1514 
1515 //------------------------------add_users_to_worklist--------------------------
1516 void PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1517   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1518     _worklist.push(n->fast_out(i));  // Push on worklist
1519   }
1520 }
1521 
1522 // Return counted loop Phi if as a counted loop exit condition, cmp
1523 // compares the the induction variable with n
1524 static PhiNode* countedloop_phi_from_cmp(CmpNode* cmp, Node* n) {
1525   for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
1526     Node* bol = cmp->fast_out(i);
1527     for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
1528       Node* iff = bol->fast_out(i2);
1529       if (iff->is_BaseCountedLoopEnd()) {
1530         BaseCountedLoopEndNode* cle = iff->as_BaseCountedLoopEnd();
1531         if (cle->limit() == n) {
1532           PhiNode* phi = cle->phi();
1533           if (phi != NULL) {
1534             return phi;
1535           }
1536         }
1537       }
1538     }
1539   }
1540   return NULL;
1541 }
1542 
1543 void PhaseIterGVN::add_users_to_worklist( Node *n ) {
1544   add_users_to_worklist0(n);
1545 
1546   // Move users of node to worklist
1547   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1548     Node* use = n->fast_out(i); // Get use
1549 
1550     if( use->is_Multi() ||      // Multi-definer?  Push projs on worklist
1551         use->is_Store() )       // Enable store/load same address
1552       add_users_to_worklist0(use);
1553 
1554     // If we changed the receiver type to a call, we need to revisit
1555     // the Catch following the call.  It's looking for a non-NULL
1556     // receiver to know when to enable the regular fall-through path
1557     // in addition to the NullPtrException path.
1558     if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1559       Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
1560       if (p != NULL) {
1561         add_users_to_worklist0(p);
1562       }
1563     }
1564 
1565     uint use_op = use->Opcode();
1566     if(use->is_Cmp()) {       // Enable CMP/BOOL optimization
1567       add_users_to_worklist(use); // Put Bool on worklist
1568       if (use->outcnt() > 0) {
1569         Node* bol = use->raw_out(0);
1570         if (bol->outcnt() > 0) {
1571           Node* iff = bol->raw_out(0);
1572           if (iff->outcnt() == 2) {
1573             // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1574             // phi merging either 0 or 1 onto the worklist
1575             Node* ifproj0 = iff->raw_out(0);
1576             Node* ifproj1 = iff->raw_out(1);
1577             if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1578               Node* region0 = ifproj0->raw_out(0);
1579               Node* region1 = ifproj1->raw_out(0);
1580               if( region0 == region1 )
1581                 add_users_to_worklist0(region0);
1582             }
1583           }
1584         }
1585       }
1586       if (use_op == Op_CmpI) {
1587         Node* phi = countedloop_phi_from_cmp((CmpINode*)use, n);
1588         if (phi != NULL) {
1589           // If an opaque node feeds into the limit condition of a
1590           // CountedLoop, we need to process the Phi node for the
1591           // induction variable when the opaque node is removed:
1592           // the range of values taken by the Phi is now known and
1593           // so its type is also known.
1594           _worklist.push(phi);
1595         }
1596         Node* in1 = use->in(1);
1597         for (uint i = 0; i < in1->outcnt(); i++) {
1598           if (in1->raw_out(i)->Opcode() == Op_CastII) {
1599             Node* castii = in1->raw_out(i);
1600             if (castii->in(0) != NULL && castii->in(0)->in(0) != NULL && castii->in(0)->in(0)->is_If()) {
1601               Node* ifnode = castii->in(0)->in(0);
1602               if (ifnode->in(1) != NULL && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == use) {
1603                 // Reprocess a CastII node that may depend on an
1604                 // opaque node value when the opaque node is
1605                 // removed. In case it carries a dependency we can do
1606                 // a better job of computing its type.
1607                 _worklist.push(castii);
1608               }
1609             }
1610           }
1611         }
1612       }
1613     }
1614 
1615     // Inline type nodes can have other inline types as users. If an input gets
1616     // updated, make sure that inline type users get a chance for optimization.
1617     if (use->is_InlineTypeBase()) {
1618       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1619         Node* u = use->fast_out(i2);
1620         if (u->is_InlineTypeBase())
1621           _worklist.push(u);
1622       }
1623     }
1624     // If changed Cast input, check Phi users for simple cycles
1625     if (use->is_ConstraintCast()) {
1626       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1627         Node* u = use->fast_out(i2);
1628         if (u->is_Phi())
1629           _worklist.push(u);
1630       }
1631     }
1632     // If changed LShift inputs, check RShift users for useless sign-ext
1633     if( use_op == Op_LShiftI ) {
1634       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1635         Node* u = use->fast_out(i2);
1636         if (u->Opcode() == Op_RShiftI)
1637           _worklist.push(u);
1638       }
1639     }
1640     // If changed AddI/SubI inputs, check CmpU for range check optimization.
1641     if (use_op == Op_AddI || use_op == Op_SubI) {
1642       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1643         Node* u = use->fast_out(i2);
1644         if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
1645           _worklist.push(u);
1646         }
1647       }
1648     }
1649     // If changed AddP inputs, check Stores for loop invariant
1650     if( use_op == Op_AddP ) {
1651       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1652         Node* u = use->fast_out(i2);
1653         if (u->is_Mem())
1654           _worklist.push(u);
1655       }
1656     }
1657     // If changed initialization activity, check dependent Stores
1658     if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1659       InitializeNode* init = use->as_Allocate()->initialization();
1660       if (init != NULL) {
1661         Node* imem = init->proj_out_or_null(TypeFunc::Memory);
1662         if (imem != NULL)  add_users_to_worklist0(imem);
1663       }
1664     }
1665     if (use_op == Op_Initialize) {
1666       Node* imem = use->as_Initialize()->proj_out_or_null(TypeFunc::Memory);
1667       if (imem != NULL)  add_users_to_worklist0(imem);
1668     }
1669     if (use_op == Op_CastP2X) {
1670       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1671         Node* u = use->fast_out(i2);
1672         if (u->Opcode() == Op_AndX) {
1673           _worklist.push(u);
1674         }
1675       }
1676     }
1677     // Loading the java mirror from a Klass requires two loads and the type
1678     // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1679     //   LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
1680     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1681     bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1682 
1683     if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
1684       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1685         Node* u = use->fast_out(i2);
1686         const Type* ut = u->bottom_type();
1687         if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
1688           if (has_load_barrier_nodes) {
1689             // Search for load barriers behind the load
1690             for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1691               Node* b = u->fast_out(i3);
1692               if (bs->is_gc_barrier_node(b)) {
1693                 _worklist.push(b);
1694               }
1695             }
1696           }
1697           _worklist.push(u);
1698         }
1699       }
1700     }
1701 
1702     // Give CallStaticJavaNode::remove_useless_allocation a chance to run
1703     if (use->is_Region()) {
1704       Node* c = use;
1705       do {
1706         c = c->unique_ctrl_out_or_null();
1707       } while (c != NULL && c->is_Region());
1708       if (c != NULL && c->is_CallStaticJava() && c->as_CallStaticJava()->uncommon_trap_request() != 0) {
1709         _worklist.push(c);
1710       }
1711     }
1712   }
1713 }
1714 
1715 /**
1716  * Remove the speculative part of all types that we know of
1717  */
1718 void PhaseIterGVN::remove_speculative_types()  {
1719   assert(UseTypeSpeculation, "speculation is off");
1720   for (uint i = 0; i < _types.Size(); i++)  {
1721     const Type* t = _types.fast_lookup(i);
1722     if (t != NULL) {
1723       _types.map(i, t->remove_speculative());
1724     }
1725   }
1726   _table.check_no_speculative_types();
1727 }
1728 
1729 // Check if the type of a divisor of a Div or Mod node includes zero.
1730 bool PhaseIterGVN::no_dependent_zero_check(Node* n) const {
1731   switch (n->Opcode()) {
1732     case Op_DivI:
1733     case Op_ModI: {
1734       // Type of divisor includes 0?
1735       if (type(n->in(2)) == Type::TOP) {
1736         // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1737         return false;
1738       }
1739       const TypeInt* type_divisor = type(n->in(2))->is_int();
1740       return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1741     }
1742     case Op_DivL:
1743     case Op_ModL: {
1744       // Type of divisor includes 0?
1745       if (type(n->in(2)) == Type::TOP) {
1746         // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1747         return false;
1748       }
1749       const TypeLong* type_divisor = type(n->in(2))->is_long();
1750       return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1751     }
1752   }
1753   return true;
1754 }
1755 
1756 //=============================================================================
1757 #ifndef PRODUCT
1758 uint PhaseCCP::_total_invokes   = 0;
1759 uint PhaseCCP::_total_constants = 0;
1760 #endif
1761 //------------------------------PhaseCCP---------------------------------------
1762 // Conditional Constant Propagation, ala Wegman & Zadeck
1763 PhaseCCP::PhaseCCP(PhaseIterGVN* igvn) : PhaseIterGVN(igvn), _trstack(C->live_nodes() >> 1) {
1764   NOT_PRODUCT( clear_constants(); )
1765   assert( _worklist.size() == 0, "" );
1766   // Clear out _nodes from IterGVN.  Must be clear to transform call.
1767   _nodes.clear();               // Clear out from IterGVN
1768   analyze();
1769 }
1770 
1771 #ifndef PRODUCT
1772 //------------------------------~PhaseCCP--------------------------------------
1773 PhaseCCP::~PhaseCCP() {
1774   inc_invokes();
1775   _total_constants += count_constants();
1776 }
1777 #endif
1778 
1779 
1780 #ifdef ASSERT
1781 static bool ccp_type_widens(const Type* t, const Type* t0) {
1782   assert(t->meet(t0) == t, "Not monotonic");
1783   switch (t->base() == t0->base() ? t->base() : Type::Top) {
1784   case Type::Int:
1785     assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1786     break;
1787   case Type::Long:
1788     assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1789     break;
1790   default:
1791     break;
1792   }
1793   return true;
1794 }
1795 #endif //ASSERT
1796 
1797 //------------------------------analyze----------------------------------------
1798 void PhaseCCP::analyze() {
1799   // Initialize all types to TOP, optimistic analysis
1800   for (int i = C->unique() - 1; i >= 0; i--)  {
1801     _types.map(i,Type::TOP);
1802   }
1803 
1804   // Push root onto worklist
1805   Unique_Node_List worklist;
1806   worklist.push(C->root());
1807 
1808   // Pull from worklist; compute new value; push changes out.
1809   // This loop is the meat of CCP.
1810   while( worklist.size() ) {
1811     Node* n; // Node to be examined in this iteration
1812     if (StressCCP) {
1813       n = worklist.remove(C->random() % worklist.size());
1814     } else {
1815       n = worklist.pop();
1816     }
1817     if (n->is_SafePoint()) {
1818       // Make sure safepoints are processed by PhaseCCP::transform even if they are
1819       // not reachable from the bottom. Otherwise, infinite loops would be removed.
1820       _trstack.push(n);
1821     }
1822     const Type *t = n->Value(this);
1823     if (t != type(n)) {
1824       assert(ccp_type_widens(t, type(n)), "ccp type must widen");
1825 #ifndef PRODUCT
1826       if( TracePhaseCCP ) {
1827         t->dump();
1828         do { tty->print("\t"); } while (tty->position() < 16);
1829         n->dump();
1830       }
1831 #endif
1832       set_type(n, t);
1833       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1834         Node* m = n->fast_out(i);   // Get user
1835         if (m->is_Region()) {  // New path to Region?  Must recheck Phis too
1836           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1837             Node* p = m->fast_out(i2); // Propagate changes to uses
1838             if (p->bottom_type() != type(p)) { // If not already bottomed out
1839               worklist.push(p); // Propagate change to user
1840             }
1841           }
1842         }
1843         // If we changed the receiver type to a call, we need to revisit
1844         // the Catch following the call.  It's looking for a non-NULL
1845         // receiver to know when to enable the regular fall-through path
1846         // in addition to the NullPtrException path
1847         if (m->is_Call()) {
1848           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1849             Node* p = m->fast_out(i2);  // Propagate changes to uses
1850             if (p->is_Proj() && p->as_Proj()->_con == TypeFunc::Control) {
1851               Node* catch_node = p->find_out_with(Op_Catch);
1852               if (catch_node != NULL) {
1853                 worklist.push(catch_node);
1854               }
1855             }
1856           }
1857         }
1858         if (m->bottom_type() != type(m)) { // If not already bottomed out
1859           worklist.push(m);     // Propagate change to user
1860         }
1861 
1862         // CmpU nodes can get their type information from two nodes up in the
1863         // graph (instead of from the nodes immediately above). Make sure they
1864         // are added to the worklist if nodes they depend on are updated, since
1865         // they could be missed and get wrong types otherwise.
1866         uint m_op = m->Opcode();
1867         if (m_op == Op_AddI || m_op == Op_SubI) {
1868           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1869             Node* p = m->fast_out(i2); // Propagate changes to uses
1870             if (p->Opcode() == Op_CmpU) {
1871               // Got a CmpU which might need the new type information from node n.
1872               if(p->bottom_type() != type(p)) { // If not already bottomed out
1873                 worklist.push(p); // Propagate change to user
1874               }
1875             }
1876           }
1877         }
1878         // If n is used in a counted loop exit condition then the type
1879         // of the counted loop's Phi depends on the type of n. See
1880         // PhiNode::Value().
1881         if (m_op == Op_CmpI || m_op == Op_CmpL) {
1882           PhiNode* phi = countedloop_phi_from_cmp(m->as_Cmp(), n);
1883           if (phi != NULL) {
1884             worklist.push(phi);
1885           }
1886         }
1887         if (m_op == Op_CastP2X) {
1888           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1889             Node* u = m->fast_out(i2);
1890             if (u->Opcode() == Op_AndX) {
1891               worklist.push(u);
1892             }
1893           }
1894         }
1895         // Loading the java mirror from a Klass requires two loads and the type
1896         // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1897         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1898         bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1899 
1900         if (m_op == Op_LoadP && m->bottom_type()->isa_rawptr()) {
1901           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1902             Node* u = m->fast_out(i2);
1903             const Type* ut = u->bottom_type();
1904             if (u->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(u)) {
1905               if (has_load_barrier_nodes) {
1906                 // Search for load barriers behind the load
1907                 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1908                   Node* b = u->fast_out(i3);
1909                   if (bs->is_gc_barrier_node(b)) {
1910                     worklist.push(b);
1911                   }
1912                 }
1913               }
1914               worklist.push(u);
1915             }
1916           }
1917         }
1918       }
1919     }
1920   }
1921 }
1922 
1923 //------------------------------do_transform-----------------------------------
1924 // Top level driver for the recursive transformer
1925 void PhaseCCP::do_transform() {
1926   // Correct leaves of new-space Nodes; they point to old-space.
1927   C->set_root( transform(C->root())->as_Root() );
1928   assert( C->top(),  "missing TOP node" );
1929   assert( C->root(), "missing root" );
1930 }
1931 
1932 //------------------------------transform--------------------------------------
1933 // Given a Node in old-space, clone him into new-space.
1934 // Convert any of his old-space children into new-space children.
1935 Node *PhaseCCP::transform( Node *n ) {
1936   Node *new_node = _nodes[n->_idx]; // Check for transformed node
1937   if( new_node != NULL )
1938     return new_node;                // Been there, done that, return old answer
1939   new_node = transform_once(n);     // Check for constant
1940   _nodes.map( n->_idx, new_node );  // Flag as having been cloned
1941   _useful.push(new_node); // Keep track of nodes that are reachable from the bottom
1942 
1943   _trstack.push(new_node);           // Process children of cloned node
1944   while (_trstack.is_nonempty()) {
1945     Node* clone = _trstack.pop();
1946     uint cnt = clone->req();
1947     for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
1948       Node *input = clone->in(i);
1949       if( input != NULL ) {                    // Ignore NULLs
1950         Node *new_input = _nodes[input->_idx]; // Check for cloned input node
1951         if( new_input == NULL ) {
1952           new_input = transform_once(input);   // Check for constant
1953           _nodes.map( input->_idx, new_input );// Flag as having been cloned
1954           _useful.push(new_input);
1955           _trstack.push(new_input);
1956         }
1957         assert( new_input == clone->in(i), "insanity check");
1958       }
1959     }
1960   }
1961 
1962   // The above transformation might lead to subgraphs becoming unreachable from the
1963   // bottom while still being reachable from the top. As a result, nodes in that
1964   // subgraph are not transformed and their bottom types are not updated, leading to
1965   // an inconsistency between bottom_type() and type(). In rare cases, LoadNodes in
1966   // such a subgraph, kept alive by InlineTypePtrNodes, might be re-enqueued for IGVN
1967   // indefinitely by MemNode::Ideal_common because their address type is inconsistent.
1968   // Therefore, we aggressively remove all useless nodes here even before
1969   // PhaseIdealLoop::build_loop_late gets a chance to remove them anyway.
1970   if (C->cached_top_node()) {
1971     _useful.push(C->cached_top_node());
1972   }
1973   C->update_dead_node_list(_useful);
1974   remove_useless_nodes(_useful.member_set());
1975   _worklist.remove_useless_nodes(_useful.member_set());
1976   C->disconnect_useless_nodes(_useful, &_worklist);
1977 
1978   return new_node;
1979 }
1980 
1981 
1982 //------------------------------transform_once---------------------------------
1983 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
1984 Node *PhaseCCP::transform_once( Node *n ) {
1985   const Type *t = type(n);
1986   // Constant?  Use constant Node instead
1987   if( t->singleton() ) {
1988     Node *nn = n;               // Default is to return the original constant
1989     if( t == Type::TOP ) {
1990       // cache my top node on the Compile instance
1991       if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
1992         C->set_cached_top_node(ConNode::make(Type::TOP));
1993         set_type(C->top(), Type::TOP);
1994       }
1995       nn = C->top();
1996     }
1997     if( !n->is_Con() ) {
1998       if( t != Type::TOP ) {
1999         nn = makecon(t);        // ConNode::make(t);
2000         NOT_PRODUCT( inc_constants(); )
2001       } else if( n->is_Region() ) { // Unreachable region
2002         // Note: nn == C->top()
2003         n->set_req(0, NULL);        // Cut selfreference
2004         bool progress = true;
2005         uint max = n->outcnt();
2006         DUIterator i;
2007         while (progress) {
2008           progress = false;
2009           // Eagerly remove dead phis to avoid phis copies creation.
2010           for (i = n->outs(); n->has_out(i); i++) {
2011             Node* m = n->out(i);
2012             if (m->is_Phi()) {
2013               assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
2014               replace_node(m, nn);
2015               if (max != n->outcnt()) {
2016                 progress = true;
2017                 i = n->refresh_out_pos(i);
2018                 max = n->outcnt();
2019               }
2020             }
2021           }
2022         }
2023       }
2024       replace_node(n,nn);       // Update DefUse edges for new constant
2025     }
2026     return nn;
2027   }
2028 
2029   // If x is a TypeNode, capture any more-precise type permanently into Node
2030   if (t != n->bottom_type()) {
2031     hash_delete(n);             // changing bottom type may force a rehash
2032     n->raise_bottom_type(t);
2033     _worklist.push(n);          // n re-enters the hash table via the worklist
2034   }
2035 
2036   // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
2037   switch( n->Opcode() ) {
2038   case Op_CallStaticJava:  // Give post-parse call devirtualization a chance
2039   case Op_CallDynamicJava:
2040   case Op_FastLock:        // Revisit FastLocks for lock coarsening
2041   case Op_If:
2042   case Op_CountedLoopEnd:
2043   case Op_Region:
2044   case Op_Loop:
2045   case Op_CountedLoop:
2046   case Op_Conv2B:
2047   case Op_Opaque1:
2048   case Op_Opaque2:
2049     _worklist.push(n);
2050     break;
2051   default:
2052     break;
2053   }
2054 
2055   return  n;
2056 }
2057 
2058 //---------------------------------saturate------------------------------------
2059 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
2060                                const Type* limit_type) const {
2061   const Type* wide_type = new_type->widen(old_type, limit_type);
2062   if (wide_type != new_type) {          // did we widen?
2063     // If so, we may have widened beyond the limit type.  Clip it back down.
2064     new_type = wide_type->filter(limit_type);
2065   }
2066   return new_type;
2067 }
2068 
2069 //------------------------------print_statistics-------------------------------
2070 #ifndef PRODUCT
2071 void PhaseCCP::print_statistics() {
2072   tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
2073 }
2074 #endif
2075 
2076 
2077 //=============================================================================
2078 #ifndef PRODUCT
2079 uint PhasePeephole::_total_peepholes = 0;
2080 #endif
2081 //------------------------------PhasePeephole----------------------------------
2082 // Conditional Constant Propagation, ala Wegman & Zadeck
2083 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
2084   : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
2085   NOT_PRODUCT( clear_peepholes(); )
2086 }
2087 
2088 #ifndef PRODUCT
2089 //------------------------------~PhasePeephole---------------------------------
2090 PhasePeephole::~PhasePeephole() {
2091   _total_peepholes += count_peepholes();
2092 }
2093 #endif
2094 
2095 //------------------------------transform--------------------------------------
2096 Node *PhasePeephole::transform( Node *n ) {
2097   ShouldNotCallThis();
2098   return NULL;
2099 }
2100 
2101 //------------------------------do_transform-----------------------------------
2102 void PhasePeephole::do_transform() {
2103   bool method_name_not_printed = true;
2104 
2105   // Examine each basic block
2106   for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
2107     Block* block = _cfg.get_block(block_number);
2108     bool block_not_printed = true;
2109 
2110     // and each instruction within a block
2111     uint end_index = block->number_of_nodes();
2112     // block->end_idx() not valid after PhaseRegAlloc
2113     for( uint instruction_index = 1; instruction_index < end_index; ++instruction_index ) {
2114       Node     *n = block->get_node(instruction_index);
2115       if( n->is_Mach() ) {
2116         MachNode *m = n->as_Mach();
2117         int deleted_count = 0;
2118         // check for peephole opportunities
2119         MachNode *m2 = m->peephole(block, instruction_index, _regalloc, deleted_count);
2120         if( m2 != NULL ) {
2121 #ifndef PRODUCT
2122           if( PrintOptoPeephole ) {
2123             // Print method, first time only
2124             if( C->method() && method_name_not_printed ) {
2125               C->method()->print_short_name(); tty->cr();
2126               method_name_not_printed = false;
2127             }
2128             // Print this block
2129             if( Verbose && block_not_printed) {
2130               tty->print_cr("in block");
2131               block->dump();
2132               block_not_printed = false;
2133             }
2134             // Print instructions being deleted
2135             for( int i = (deleted_count - 1); i >= 0; --i ) {
2136               block->get_node(instruction_index-i)->as_Mach()->format(_regalloc); tty->cr();
2137             }
2138             tty->print_cr("replaced with");
2139             // Print new instruction
2140             m2->format(_regalloc);
2141             tty->print("\n\n");
2142           }
2143 #endif
2144           // Remove old nodes from basic block and update instruction_index
2145           // (old nodes still exist and may have edges pointing to them
2146           //  as register allocation info is stored in the allocator using
2147           //  the node index to live range mappings.)
2148           uint safe_instruction_index = (instruction_index - deleted_count);
2149           for( ; (instruction_index > safe_instruction_index); --instruction_index ) {
2150             block->remove_node( instruction_index );
2151           }
2152           // install new node after safe_instruction_index
2153           block->insert_node(m2, safe_instruction_index + 1);
2154           end_index = block->number_of_nodes() - 1; // Recompute new block size
2155           NOT_PRODUCT( inc_peepholes(); )
2156         }
2157       }
2158     }
2159   }
2160 }
2161 
2162 //------------------------------print_statistics-------------------------------
2163 #ifndef PRODUCT
2164 void PhasePeephole::print_statistics() {
2165   tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
2166 }
2167 #endif
2168 
2169 
2170 //=============================================================================
2171 //------------------------------set_req_X--------------------------------------
2172 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
2173   assert( is_not_dead(n), "can not use dead node");
2174   assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
2175   Node *old = in(i);
2176   set_req(i, n);
2177 
2178   // old goes dead?
2179   if( old ) {
2180     switch (old->outcnt()) {
2181     case 0:
2182       // Put into the worklist to kill later. We do not kill it now because the
2183       // recursive kill will delete the current node (this) if dead-loop exists
2184       if (!old->is_top())
2185         igvn->_worklist.push( old );
2186       break;
2187     case 1:
2188       if( old->is_Store() || old->has_special_unique_user() )
2189         igvn->add_users_to_worklist( old );
2190       break;
2191     case 2:
2192       if( old->is_Store() )
2193         igvn->add_users_to_worklist( old );
2194       if( old->Opcode() == Op_Region )
2195         igvn->_worklist.push(old);
2196       break;
2197     case 3:
2198       if( old->Opcode() == Op_Region ) {
2199         igvn->_worklist.push(old);
2200         igvn->add_users_to_worklist( old );
2201       }
2202       break;
2203     default:
2204       break;
2205     }
2206 
2207     BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
2208   }
2209 }
2210 
2211 void Node::set_req_X(uint i, Node *n, PhaseGVN *gvn) {
2212   PhaseIterGVN* igvn = gvn->is_IterGVN();
2213   if (igvn == NULL) {
2214     set_req(i, n);
2215     return;
2216   }
2217   set_req_X(i, n, igvn);
2218 }
2219 
2220 //-------------------------------replace_by-----------------------------------
2221 // Using def-use info, replace one node for another.  Follow the def-use info
2222 // to all users of the OLD node.  Then make all uses point to the NEW node.
2223 void Node::replace_by(Node *new_node) {
2224   assert(!is_top(), "top node has no DU info");
2225   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
2226     Node* use = last_out(i);
2227     uint uses_found = 0;
2228     for (uint j = 0; j < use->len(); j++) {
2229       if (use->in(j) == this) {
2230         if (j < use->req())
2231               use->set_req(j, new_node);
2232         else  use->set_prec(j, new_node);
2233         uses_found++;
2234       }
2235     }
2236     i -= uses_found;    // we deleted 1 or more copies of this edge
2237   }
2238 }
2239 
2240 //=============================================================================
2241 //-----------------------------------------------------------------------------
2242 void Type_Array::grow( uint i ) {
2243   if( !_max ) {
2244     _max = 1;
2245     _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
2246     _types[0] = NULL;
2247   }
2248   uint old = _max;
2249   _max = next_power_of_2(i);
2250   _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
2251   memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
2252 }
2253 
2254 //------------------------------dump-------------------------------------------
2255 #ifndef PRODUCT
2256 void Type_Array::dump() const {
2257   uint max = Size();
2258   for( uint i = 0; i < max; i++ ) {
2259     if( _types[i] != NULL ) {
2260       tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
2261     }
2262   }
2263 }
2264 #endif