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