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