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, PhaseNumber phase_num) : Phase(phase_num),
 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 //------------------------------PhaseRenumberLive------------------------------
 440 // First, remove useless nodes (equivalent to identifying live nodes).
 441 // Then, renumber live nodes.
 442 //
 443 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
 444 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
 445 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
 446 // value in the range [0, x).
 447 //
 448 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
 449 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
 450 //
 451 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
 452 // (1) The worklist is used by the PhaseIterGVN phase to identify nodes that must be
 453 // processed. A new worklist (with the updated node IDs) is returned in 'new_worklist'.
 454 // (2) Type information (the field PhaseGVN::_types) maps type information to each
 455 // node ID. The mapping is updated to use the new node IDs as well. Updated type
 456 // information is returned in PhaseGVN::_types.
 457 //
 458 // The PhaseRenumberLive phase does not preserve the order of elements in the worklist.
 459 //
 460 // Other data structures used by the compiler are not updated. The hash table for value
 461 // numbering (the field PhaseGVN::_table) is not updated because computing the hash
 462 // values is not based on node IDs. The field PhaseGVN::_nodes is not updated either
 463 // because it is empty wherever PhaseRenumberLive is used.
 464 PhaseRenumberLive::PhaseRenumberLive(PhaseGVN* gvn,
 465                                      Unique_Node_List* worklist, Unique_Node_List* new_worklist,
 466                                      PhaseNumber phase_num) :
 467   PhaseRemoveUseless(gvn, worklist, Remove_Useless_And_Renumber_Live) {
 468 
 469   assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
 470   assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
 471   assert(gvn->nodes_size() == 0, "GVN must not contain any nodes at this point");
 472 
 473   uint old_unique_count = C->unique();
 474   uint live_node_count = C->live_nodes();
 475   uint worklist_size = worklist->size();
 476 
 477   // Storage for the updated type information.
 478   Type_Array new_type_array(C->comp_arena());
 479 
 480   // Iterate over the set of live nodes.
 481   uint current_idx = 0; // The current new node ID. Incremented after every assignment.
 482   for (uint i = 0; i < _useful.size(); i++) {
 483     Node* n = _useful.at(i);
 484     // Sanity check that fails if we ever decide to execute this phase after EA
 485     assert(!n->is_Phi() || n->as_Phi()->inst_mem_id() == -1, "should not be linked to data Phi");
 486     const Type* type = gvn->type_or_null(n);
 487     new_type_array.map(current_idx, type);
 488 
 489     bool in_worklist = false;
 490     if (worklist->member(n)) {
 491       in_worklist = true;
 492     }
 493 
 494     n->set_idx(current_idx); // Update node ID.
 495 
 496     if (in_worklist) {
 497       new_worklist->push(n);
 498     }
 499 
 500     current_idx++;
 501   }
 502 
 503   assert(worklist_size == new_worklist->size(), "the new worklist must have the same size as the original worklist");
 504   assert(live_node_count == current_idx, "all live nodes must be processed");
 505 
 506   // Replace the compiler's type information with the updated type information.
 507   gvn->replace_types(new_type_array);
 508 
 509   // Update the unique node count of the compilation to the number of currently live nodes.
 510   C->set_unique(live_node_count);
 511 
 512   // Set the dead node count to 0 and reset dead node list.
 513   C->reset_dead_node_list();
 514 }
 515 
 516 
 517 //=============================================================================
 518 //------------------------------PhaseTransform---------------------------------
 519 PhaseTransform::PhaseTransform( PhaseNumber pnum ) : Phase(pnum),
 520   _arena(Thread::current()->resource_area()),
 521   _nodes(_arena),
 522   _types(_arena)
 523 {
 524   init_con_caches();
 525 #ifndef PRODUCT
 526   clear_progress();
 527   clear_transforms();
 528   set_allow_progress(true);
 529 #endif
 530   // Force allocation for currently existing nodes
 531   _types.map(C->unique(), NULL);
 532 }
 533 
 534 //------------------------------PhaseTransform---------------------------------
 535 PhaseTransform::PhaseTransform( Arena *arena, PhaseNumber pnum ) : Phase(pnum),
 536   _arena(arena),
 537   _nodes(arena),
 538   _types(arena)
 539 {
 540   init_con_caches();
 541 #ifndef PRODUCT
 542   clear_progress();
 543   clear_transforms();
 544   set_allow_progress(true);
 545 #endif
 546   // Force allocation for currently existing nodes
 547   _types.map(C->unique(), NULL);
 548 }
 549 
 550 //------------------------------PhaseTransform---------------------------------
 551 // Initialize with previously generated type information
 552 PhaseTransform::PhaseTransform( PhaseTransform *pt, PhaseNumber pnum ) : Phase(pnum),
 553   _arena(pt->_arena),
 554   _nodes(pt->_nodes),
 555   _types(pt->_types)
 556 {
 557   init_con_caches();
 558 #ifndef PRODUCT
 559   clear_progress();
 560   clear_transforms();
 561   set_allow_progress(true);
 562 #endif
 563 }
 564 
 565 void PhaseTransform::init_con_caches() {
 566   memset(_icons,0,sizeof(_icons));
 567   memset(_lcons,0,sizeof(_lcons));
 568   memset(_zcons,0,sizeof(_zcons));
 569 }
 570 
 571 
 572 //--------------------------------find_int_type--------------------------------
 573 const TypeInt* PhaseTransform::find_int_type(Node* n) {
 574   if (n == NULL)  return NULL;
 575   // Call type_or_null(n) to determine node's type since we might be in
 576   // parse phase and call n->Value() may return wrong type.
 577   // (For example, a phi node at the beginning of loop parsing is not ready.)
 578   const Type* t = type_or_null(n);
 579   if (t == NULL)  return NULL;
 580   return t->isa_int();
 581 }
 582 
 583 
 584 //-------------------------------find_long_type--------------------------------
 585 const TypeLong* PhaseTransform::find_long_type(Node* n) {
 586   if (n == NULL)  return NULL;
 587   // (See comment above on type_or_null.)
 588   const Type* t = type_or_null(n);
 589   if (t == NULL)  return NULL;
 590   return t->isa_long();
 591 }
 592 
 593 
 594 #ifndef PRODUCT
 595 void PhaseTransform::dump_old2new_map() const {
 596   _nodes.dump();
 597 }
 598 
 599 void PhaseTransform::dump_new( uint nidx ) const {
 600   for( uint i=0; i<_nodes.Size(); i++ )
 601     if( _nodes[i] && _nodes[i]->_idx == nidx ) {
 602       _nodes[i]->dump();
 603       tty->cr();
 604       tty->print_cr("Old index= %d",i);
 605       return;
 606     }
 607   tty->print_cr("Node %d not found in the new indices", nidx);
 608 }
 609 
 610 //------------------------------dump_types-------------------------------------
 611 void PhaseTransform::dump_types( ) const {
 612   _types.dump();
 613 }
 614 
 615 //------------------------------dump_nodes_and_types---------------------------
 616 void PhaseTransform::dump_nodes_and_types(const Node *root, uint depth, bool only_ctrl) {
 617   VectorSet visited(Thread::current()->resource_area());
 618   dump_nodes_and_types_recur( root, depth, only_ctrl, visited );
 619 }
 620 
 621 //------------------------------dump_nodes_and_types_recur---------------------
 622 void PhaseTransform::dump_nodes_and_types_recur( const Node *n, uint depth, bool only_ctrl, VectorSet &visited) {
 623   if( !n ) return;
 624   if( depth == 0 ) return;
 625   if( visited.test_set(n->_idx) ) return;
 626   for( uint i=0; i<n->len(); i++ ) {
 627     if( only_ctrl && !(n->is_Region()) && i != TypeFunc::Control ) continue;
 628     dump_nodes_and_types_recur( n->in(i), depth-1, only_ctrl, visited );
 629   }
 630   n->dump();
 631   if (type_or_null(n) != NULL) {
 632     tty->print("      "); type(n)->dump(); tty->cr();
 633   }
 634 }
 635 
 636 #endif
 637 
 638 
 639 //=============================================================================
 640 //------------------------------PhaseValues------------------------------------
 641 // Set minimum table size to "255"
 642 PhaseValues::PhaseValues( Arena *arena, uint est_max_size ) : PhaseTransform(arena, GVN), _table(arena, est_max_size) {
 643   NOT_PRODUCT( clear_new_values(); )
 644 }
 645 
 646 //------------------------------PhaseValues------------------------------------
 647 // Set minimum table size to "255"
 648 PhaseValues::PhaseValues( PhaseValues *ptv ) : PhaseTransform( ptv, GVN ),
 649   _table(&ptv->_table) {
 650   NOT_PRODUCT( clear_new_values(); )
 651 }
 652 
 653 //------------------------------PhaseValues------------------------------------
 654 // Used by +VerifyOpto.  Clear out hash table but copy _types array.
 655 PhaseValues::PhaseValues( PhaseValues *ptv, const char *dummy ) : PhaseTransform( ptv, GVN ),
 656   _table(ptv->arena(),ptv->_table.size()) {
 657   NOT_PRODUCT( clear_new_values(); )
 658 }
 659 
 660 //------------------------------~PhaseValues-----------------------------------
 661 #ifndef PRODUCT
 662 PhaseValues::~PhaseValues() {
 663   _table.dump();
 664 
 665   // Statistics for value progress and efficiency
 666   if( PrintCompilation && Verbose && WizardMode ) {
 667     tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
 668       is_IterGVN() ? "Iter" : "    ", C->unique(), made_progress(), made_transforms(), made_new_values());
 669     if( made_transforms() != 0 ) {
 670       tty->print_cr("  ratio %f", made_progress()/(float)made_transforms() );
 671     } else {
 672       tty->cr();
 673     }
 674   }
 675 }
 676 #endif
 677 
 678 //------------------------------makecon----------------------------------------
 679 ConNode* PhaseTransform::makecon(const Type *t) {
 680   assert(t->singleton(), "must be a constant");
 681   assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
 682   switch (t->base()) {  // fast paths
 683   case Type::Half:
 684   case Type::Top:  return (ConNode*) C->top();
 685   case Type::Int:  return intcon( t->is_int()->get_con() );
 686   case Type::Long: return longcon( t->is_long()->get_con() );
 687   }
 688   if (t->is_zero_type())
 689     return zerocon(t->basic_type());
 690   return uncached_makecon(t);
 691 }
 692 
 693 //--------------------------uncached_makecon-----------------------------------
 694 // Make an idealized constant - one of ConINode, ConPNode, etc.
 695 ConNode* PhaseValues::uncached_makecon(const Type *t) {
 696   assert(t->singleton(), "must be a constant");
 697   ConNode* x = ConNode::make(C, t);
 698   ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
 699   if (k == NULL) {
 700     set_type(x, t);             // Missed, provide type mapping
 701     GrowableArray<Node_Notes*>* nna = C->node_note_array();
 702     if (nna != NULL) {
 703       Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
 704       loc->clear(); // do not put debug info on constants
 705     }
 706   } else {
 707     x->destruct();              // Hit, destroy duplicate constant
 708     x = k;                      // use existing constant
 709   }
 710   return x;
 711 }
 712 
 713 //------------------------------intcon-----------------------------------------
 714 // Fast integer constant.  Same as "transform(new ConINode(TypeInt::make(i)))"
 715 ConINode* PhaseTransform::intcon(int i) {
 716   // Small integer?  Check cache! Check that cached node is not dead
 717   if (i >= _icon_min && i <= _icon_max) {
 718     ConINode* icon = _icons[i-_icon_min];
 719     if (icon != NULL && icon->in(TypeFunc::Control) != NULL)
 720       return icon;
 721   }
 722   ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
 723   assert(icon->is_Con(), "");
 724   if (i >= _icon_min && i <= _icon_max)
 725     _icons[i-_icon_min] = icon;   // Cache small integers
 726   return icon;
 727 }
 728 
 729 //------------------------------longcon----------------------------------------
 730 // Fast long constant.
 731 ConLNode* PhaseTransform::longcon(jlong l) {
 732   // Small integer?  Check cache! Check that cached node is not dead
 733   if (l >= _lcon_min && l <= _lcon_max) {
 734     ConLNode* lcon = _lcons[l-_lcon_min];
 735     if (lcon != NULL && lcon->in(TypeFunc::Control) != NULL)
 736       return lcon;
 737   }
 738   ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
 739   assert(lcon->is_Con(), "");
 740   if (l >= _lcon_min && l <= _lcon_max)
 741     _lcons[l-_lcon_min] = lcon;      // Cache small integers
 742   return lcon;
 743 }
 744 
 745 //------------------------------zerocon-----------------------------------------
 746 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
 747 ConNode* PhaseTransform::zerocon(BasicType bt) {
 748   assert((uint)bt <= _zcon_max, "domain check");
 749   ConNode* zcon = _zcons[bt];
 750   if (zcon != NULL && zcon->in(TypeFunc::Control) != NULL)
 751     return zcon;
 752   zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
 753   _zcons[bt] = zcon;
 754   return zcon;
 755 }
 756 
 757 
 758 
 759 //=============================================================================
 760 //------------------------------transform--------------------------------------
 761 // Return a node which computes the same function as this node, but in a
 762 // faster or cheaper fashion.
 763 Node *PhaseGVN::transform( Node *n ) {
 764   return transform_no_reclaim(n);
 765 }
 766 
 767 //------------------------------transform--------------------------------------
 768 // Return a node which computes the same function as this node, but
 769 // in a faster or cheaper fashion.
 770 Node *PhaseGVN::transform_no_reclaim( Node *n ) {
 771   NOT_PRODUCT( set_transforms(); )
 772 
 773   // Apply the Ideal call in a loop until it no longer applies
 774   Node *k = n;
 775   NOT_PRODUCT( uint loop_count = 0; )
 776   while( 1 ) {
 777     Node *i = k->Ideal(this, /*can_reshape=*/false);
 778     if( !i ) break;
 779     assert( i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
 780     k = i;
 781     assert(loop_count++ < K, "infinite loop in PhaseGVN::transform");
 782   }
 783   NOT_PRODUCT( if( loop_count != 0 ) { set_progress(); } )
 784 
 785 
 786   // If brand new node, make space in type array.
 787   ensure_type_or_null(k);
 788 
 789   // Since I just called 'Value' to compute the set of run-time values
 790   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
 791   // cache Value.  Later requests for the local phase->type of this Node can
 792   // use the cached Value instead of suffering with 'bottom_type'.
 793   const Type *t = k->Value(this); // Get runtime Value set
 794   assert(t != NULL, "value sanity");
 795   if (type_or_null(k) != t) {
 796 #ifndef PRODUCT
 797     // Do not count initial visit to node as a transformation
 798     if (type_or_null(k) == NULL) {
 799       inc_new_values();
 800       set_progress();
 801     }
 802 #endif
 803     set_type(k, t);
 804     // If k is a TypeNode, capture any more-precise type permanently into Node
 805     k->raise_bottom_type(t);
 806   }
 807 
 808   if( t->singleton() && !k->is_Con() ) {
 809     NOT_PRODUCT( set_progress(); )
 810     return makecon(t);          // Turn into a constant
 811   }
 812 
 813   // Now check for Identities
 814   Node *i = k->Identity(this);  // Look for a nearby replacement
 815   if( i != k ) {                // Found? Return replacement!
 816     NOT_PRODUCT( set_progress(); )
 817     return i;
 818   }
 819 
 820   // Global Value Numbering
 821   i = hash_find_insert(k);      // Insert if new
 822   if( i && (i != k) ) {
 823     // Return the pre-existing node
 824     NOT_PRODUCT( set_progress(); )
 825     return i;
 826   }
 827 
 828   // Return Idealized original
 829   return k;
 830 }
 831 
 832 #ifdef ASSERT
 833 //------------------------------dead_loop_check--------------------------------
 834 // Check for a simple dead loop when a data node references itself directly
 835 // or through an other data node excluding cons and phis.
 836 void PhaseGVN::dead_loop_check( Node *n ) {
 837   // Phi may reference itself in a loop
 838   if (n != NULL && !n->is_dead_loop_safe() && !n->is_CFG()) {
 839     // Do 2 levels check and only data inputs.
 840     bool no_dead_loop = true;
 841     uint cnt = n->req();
 842     for (uint i = 1; i < cnt && no_dead_loop; i++) {
 843       Node *in = n->in(i);
 844       if (in == n) {
 845         no_dead_loop = false;
 846       } else if (in != NULL && !in->is_dead_loop_safe()) {
 847         uint icnt = in->req();
 848         for (uint j = 1; j < icnt && no_dead_loop; j++) {
 849           if (in->in(j) == n || in->in(j) == in)
 850             no_dead_loop = false;
 851         }
 852       }
 853     }
 854     if (!no_dead_loop) n->dump(3);
 855     assert(no_dead_loop, "dead loop detected");
 856   }
 857 }
 858 #endif
 859 
 860 //=============================================================================
 861 //------------------------------PhaseIterGVN-----------------------------------
 862 // Initialize hash table to fresh and clean for +VerifyOpto
 863 PhaseIterGVN::PhaseIterGVN( PhaseIterGVN *igvn, const char *dummy ) : PhaseGVN(igvn,dummy), _worklist( ),
 864                                                                       _stack(C->live_nodes() >> 1),
 865                                                                       _delay_transform(false) {
 866 }
 867 
 868 //------------------------------PhaseIterGVN-----------------------------------
 869 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
 870 PhaseIterGVN::PhaseIterGVN( PhaseIterGVN *igvn ) : PhaseGVN(igvn),
 871                                                    _worklist( igvn->_worklist ),
 872                                                    _stack( igvn->_stack ),
 873                                                    _delay_transform(igvn->_delay_transform)
 874 {
 875 }
 876 
 877 //------------------------------PhaseIterGVN-----------------------------------
 878 // Initialize with previous PhaseGVN info from Parser
 879 PhaseIterGVN::PhaseIterGVN( PhaseGVN *gvn ) : PhaseGVN(gvn),
 880                                               _worklist(*C->for_igvn()),
 881 // TODO: Before incremental inlining it was allocated only once and it was fine. Now that
 882 //       the constructor is used in incremental inlining, this consumes too much memory:
 883 //                                            _stack(C->live_nodes() >> 1),
 884 //       So, as a band-aid, we replace this by:
 885                                               _stack(C->comp_arena(), 32),
 886                                               _delay_transform(false)
 887 {
 888   uint max;
 889 
 890   // Dead nodes in the hash table inherited from GVN were not treated as
 891   // roots during def-use info creation; hence they represent an invisible
 892   // use.  Clear them out.
 893   max = _table.size();
 894   for( uint i = 0; i < max; ++i ) {
 895     Node *n = _table.at(i);
 896     if(n != NULL && n != _table.sentinel() && n->outcnt() == 0) {
 897       if( n->is_top() ) continue;
 898       assert( false, "Parse::remove_useless_nodes missed this node");
 899       hash_delete(n);
 900     }
 901   }
 902 
 903   // Any Phis or Regions on the worklist probably had uses that could not
 904   // make more progress because the uses were made while the Phis and Regions
 905   // were in half-built states.  Put all uses of Phis and Regions on worklist.
 906   max = _worklist.size();
 907   for( uint j = 0; j < max; j++ ) {
 908     Node *n = _worklist.at(j);
 909     uint uop = n->Opcode();
 910     if( uop == Op_Phi || uop == Op_Region ||
 911         n->is_Type() ||
 912         n->is_Mem() )
 913       add_users_to_worklist(n);
 914   }
 915 }
 916 
 917 
 918 #ifndef PRODUCT
 919 void PhaseIterGVN::verify_step(Node* n) {
 920   _verify_window[_verify_counter % _verify_window_size] = n;
 921   ++_verify_counter;
 922   ResourceMark rm;
 923   ResourceArea *area = Thread::current()->resource_area();
 924   VectorSet old_space(area), new_space(area);
 925   if (C->unique() < 1000 ||
 926       0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
 927     ++_verify_full_passes;
 928     Node::verify_recur(C->root(), -1, old_space, new_space);
 929   }
 930   const int verify_depth = 4;
 931   for ( int i = 0; i < _verify_window_size; i++ ) {
 932     Node* n = _verify_window[i];
 933     if ( n == NULL )  continue;
 934     if( n->in(0) == NodeSentinel ) {  // xform_idom
 935       _verify_window[i] = n->in(1);
 936       --i; continue;
 937     }
 938     // Typical fanout is 1-2, so this call visits about 6 nodes.
 939     Node::verify_recur(n, verify_depth, old_space, new_space);
 940   }
 941 }
 942 #endif
 943 
 944 
 945 //------------------------------init_worklist----------------------------------
 946 // Initialize worklist for each node.
 947 void PhaseIterGVN::init_worklist( Node *n ) {
 948   if( _worklist.member(n) ) return;
 949   _worklist.push(n);
 950   uint cnt = n->req();
 951   for( uint i =0 ; i < cnt; i++ ) {
 952     Node *m = n->in(i);
 953     if( m ) init_worklist(m);
 954   }
 955 }
 956 
 957 //------------------------------optimize---------------------------------------
 958 void PhaseIterGVN::optimize() {
 959   debug_only(uint num_processed  = 0;);
 960 #ifndef PRODUCT
 961   {
 962     _verify_counter = 0;
 963     _verify_full_passes = 0;
 964     for ( int i = 0; i < _verify_window_size; i++ ) {
 965       _verify_window[i] = NULL;
 966     }
 967   }
 968 #endif
 969 
 970 #ifdef ASSERT
 971   Node* prev = NULL;
 972   uint rep_cnt = 0;
 973 #endif
 974   uint loop_count = 0;
 975 
 976   // Pull from worklist; transform node;
 977   // If node has changed: update edge info and put uses on worklist.
 978   while( _worklist.size() ) {
 979     if (C->check_node_count(NodeLimitFudgeFactor * 2,
 980                             "out of nodes optimizing method")) {
 981       return;
 982     }
 983     Node *n  = _worklist.pop();
 984     if (++loop_count >= K * C->live_nodes()) {
 985       debug_only(n->dump(4);)
 986       assert(false, "infinite loop in PhaseIterGVN::optimize");
 987       C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
 988       return;
 989     }
 990 #ifdef ASSERT
 991     if (n == prev) {
 992       if (++rep_cnt > 3) {
 993         n->dump(4);
 994         assert(false, "loop in Ideal transformation");
 995       }
 996     } else {
 997       rep_cnt = 0;
 998     }
 999     prev = n;
1000 #endif
1001     if (TraceIterativeGVN && Verbose) {
1002       tty->print("  Pop ");
1003       NOT_PRODUCT( n->dump(); )
1004       debug_only(if( (num_processed++ % 100) == 0 ) _worklist.print_set();)
1005     }
1006 
1007     if (n->outcnt() != 0) {
1008 
1009 #ifndef PRODUCT
1010       uint wlsize = _worklist.size();
1011       const Type* oldtype = type_or_null(n);
1012 #endif //PRODUCT
1013 
1014       Node *nn = transform_old(n);
1015 
1016 #ifndef PRODUCT
1017       if (TraceIterativeGVN) {
1018         const Type* newtype = type_or_null(n);
1019         if (nn != n) {
1020           // print old node
1021           tty->print("< ");
1022           if (oldtype != newtype && oldtype != NULL) {
1023             oldtype->dump();
1024           }
1025           do { tty->print("\t"); } while (tty->position() < 16);
1026           tty->print("<");
1027           n->dump();
1028         }
1029         if (oldtype != newtype || nn != n) {
1030           // print new node and/or new type
1031           if (oldtype == NULL) {
1032             tty->print("* ");
1033           } else if (nn != n) {
1034             tty->print("> ");
1035           } else {
1036             tty->print("= ");
1037           }
1038           if (newtype == NULL) {
1039             tty->print("null");
1040           } else {
1041             newtype->dump();
1042           }
1043           do { tty->print("\t"); } while (tty->position() < 16);
1044           nn->dump();
1045         }
1046         if (Verbose && wlsize < _worklist.size()) {
1047           tty->print("  Push {");
1048           while (wlsize != _worklist.size()) {
1049             Node* pushed = _worklist.at(wlsize++);
1050             tty->print(" %d", pushed->_idx);
1051           }
1052           tty->print_cr(" }");
1053         }
1054       }
1055       if( VerifyIterativeGVN && nn != n ) {
1056         verify_step((Node*) NULL);  // ignore n, it might be subsumed
1057       }
1058 #endif
1059     } else if (!n->is_top()) {
1060       remove_dead_node(n);
1061     }
1062   }
1063 
1064 #ifndef PRODUCT
1065   C->verify_graph_edges();
1066   if( VerifyOpto && allow_progress() ) {
1067     // Must turn off allow_progress to enable assert and break recursion
1068     C->root()->verify();
1069     { // Check if any progress was missed using IterGVN
1070       // Def-Use info enables transformations not attempted in wash-pass
1071       // e.g. Region/Phi cleanup, ...
1072       // Null-check elision -- may not have reached fixpoint
1073       //                       do not propagate to dominated nodes
1074       ResourceMark rm;
1075       PhaseIterGVN igvn2(this,"Verify"); // Fresh and clean!
1076       // Fill worklist completely
1077       igvn2.init_worklist(C->root());
1078 
1079       igvn2.set_allow_progress(false);
1080       igvn2.optimize();
1081       igvn2.set_allow_progress(true);
1082     }
1083   }
1084   if ( VerifyIterativeGVN && PrintOpto ) {
1085     if ( _verify_counter == _verify_full_passes )
1086       tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
1087                     (int) _verify_full_passes);
1088     else
1089       tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
1090                   (int) _verify_counter, (int) _verify_full_passes);
1091   }
1092 #endif
1093 }
1094 
1095 
1096 //------------------register_new_node_with_optimizer---------------------------
1097 // Register a new node with the optimizer.  Update the types array, the def-use
1098 // info.  Put on worklist.
1099 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
1100   set_type_bottom(n);
1101   _worklist.push(n);
1102   if (orig != NULL)  C->copy_node_notes_to(n, orig);
1103   return n;
1104 }
1105 
1106 //------------------------------transform--------------------------------------
1107 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
1108 Node *PhaseIterGVN::transform( Node *n ) {
1109   if (_delay_transform) {
1110     // Register the node but don't optimize for now
1111     register_new_node_with_optimizer(n);
1112     return n;
1113   }
1114 
1115   // If brand new node, make space in type array, and give it a type.
1116   ensure_type_or_null(n);
1117   if (type_or_null(n) == NULL) {
1118     set_type_bottom(n);
1119   }
1120 
1121   return transform_old(n);
1122 }
1123 
1124 //------------------------------transform_old----------------------------------
1125 Node *PhaseIterGVN::transform_old( Node *n ) {
1126 #ifndef PRODUCT
1127   debug_only(uint loop_count = 0;);
1128   set_transforms();
1129 #endif
1130   // Remove 'n' from hash table in case it gets modified
1131   _table.hash_delete(n);
1132   if( VerifyIterativeGVN ) {
1133    assert( !_table.find_index(n->_idx), "found duplicate entry in table");
1134   }
1135 
1136   // Apply the Ideal call in a loop until it no longer applies
1137   Node *k = n;
1138   DEBUG_ONLY(dead_loop_check(k);)
1139   DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1140   Node *i = k->Ideal(this, /*can_reshape=*/true);
1141   assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1142 #ifndef PRODUCT
1143   if( VerifyIterativeGVN )
1144     verify_step(k);
1145   if( i && VerifyOpto ) {
1146     if( !allow_progress() ) {
1147       if (i->is_Add() && i->outcnt() == 1) {
1148         // Switched input to left side because this is the only use
1149       } else if( i->is_If() && (i->in(0) == NULL) ) {
1150         // This IF is dead because it is dominated by an equivalent IF When
1151         // dominating if changed, info is not propagated sparsely to 'this'
1152         // Propagating this info further will spuriously identify other
1153         // progress.
1154         return i;
1155       } else
1156         set_progress();
1157     } else
1158       set_progress();
1159   }
1160 #endif
1161 
1162   while( i ) {
1163 #ifndef PRODUCT
1164     debug_only( if( loop_count >= K ) i->dump(4); )
1165     assert(loop_count < K, "infinite loop in PhaseIterGVN::transform");
1166     debug_only( loop_count++; )
1167 #endif
1168     assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1169     // Made a change; put users of original Node on worklist
1170     add_users_to_worklist( k );
1171     // Replacing root of transform tree?
1172     if( k != i ) {
1173       // Make users of old Node now use new.
1174       subsume_node( k, i );
1175       k = i;
1176     }
1177     DEBUG_ONLY(dead_loop_check(k);)
1178     // Try idealizing again
1179     DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1180     i = k->Ideal(this, /*can_reshape=*/true);
1181     assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1182 #ifndef PRODUCT
1183     if( VerifyIterativeGVN )
1184       verify_step(k);
1185     if( i && VerifyOpto ) set_progress();
1186 #endif
1187   }
1188 
1189   // If brand new node, make space in type array.
1190   ensure_type_or_null(k);
1191 
1192   // See what kind of values 'k' takes on at runtime
1193   const Type *t = k->Value(this);
1194   assert(t != NULL, "value sanity");
1195 
1196   // Since I just called 'Value' to compute the set of run-time values
1197   // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1198   // cache Value.  Later requests for the local phase->type of this Node can
1199   // use the cached Value instead of suffering with 'bottom_type'.
1200   if (t != type_or_null(k)) {
1201     NOT_PRODUCT( set_progress(); )
1202     NOT_PRODUCT( inc_new_values();)
1203     set_type(k, t);
1204     // If k is a TypeNode, capture any more-precise type permanently into Node
1205     k->raise_bottom_type(t);
1206     // Move users of node to worklist
1207     add_users_to_worklist( k );
1208   }
1209 
1210   // If 'k' computes a constant, replace it with a constant
1211   if( t->singleton() && !k->is_Con() ) {
1212     NOT_PRODUCT( set_progress(); )
1213     Node *con = makecon(t);     // Make a constant
1214     add_users_to_worklist( k );
1215     subsume_node( k, con );     // Everybody using k now uses con
1216     return con;
1217   }
1218 
1219   // Now check for Identities
1220   i = k->Identity(this);        // Look for a nearby replacement
1221   if( i != k ) {                // Found? Return replacement!
1222     NOT_PRODUCT( set_progress(); )
1223     add_users_to_worklist( k );
1224     subsume_node( k, i );       // Everybody using k now uses i
1225     return i;
1226   }
1227 
1228   // Global Value Numbering
1229   i = hash_find_insert(k);      // Check for pre-existing node
1230   if( i && (i != k) ) {
1231     // Return the pre-existing node if it isn't dead
1232     NOT_PRODUCT( set_progress(); )
1233     add_users_to_worklist( k );
1234     subsume_node( k, i );       // Everybody using k now uses i
1235     return i;
1236   }
1237 
1238   // Return Idealized original
1239   return k;
1240 }
1241 
1242 //---------------------------------saturate------------------------------------
1243 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1244                                    const Type* limit_type) const {
1245   return new_type->narrow(old_type);
1246 }
1247 
1248 //------------------------------remove_globally_dead_node----------------------
1249 // Kill a globally dead Node.  All uses are also globally dead and are
1250 // aggressively trimmed.
1251 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1252   enum DeleteProgress {
1253     PROCESS_INPUTS,
1254     PROCESS_OUTPUTS
1255   };
1256   assert(_stack.is_empty(), "not empty");
1257   _stack.push(dead, PROCESS_INPUTS);
1258 
1259   while (_stack.is_nonempty()) {
1260     dead = _stack.node();
1261     uint progress_state = _stack.index();
1262     assert(dead != C->root(), "killing root, eh?");
1263     assert(!dead->is_top(), "add check for top when pushing");
1264     NOT_PRODUCT( set_progress(); )
1265     if (progress_state == PROCESS_INPUTS) {
1266       // After following inputs, continue to outputs
1267       _stack.set_index(PROCESS_OUTPUTS);
1268       if (!dead->is_Con()) { // Don't kill cons but uses
1269         bool recurse = false;
1270         // Remove from hash table
1271         _table.hash_delete( dead );
1272         // Smash all inputs to 'dead', isolating him completely
1273         for (uint i = 0; i < dead->req(); i++) {
1274           Node *in = dead->in(i);
1275           if (in != NULL && in != C->top()) {  // Points to something?
1276             int nrep = dead->replace_edge(in, NULL);  // Kill edges
1277             assert((nrep > 0), "sanity");
1278             if (in->outcnt() == 0) { // Made input go dead?
1279               _stack.push(in, PROCESS_INPUTS); // Recursively remove
1280               recurse = true;
1281             } else if (in->outcnt() == 1 &&
1282                        in->has_special_unique_user()) {
1283               _worklist.push(in->unique_out());
1284             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1285               if (in->Opcode() == Op_Region) {
1286                 _worklist.push(in);
1287               } else if (in->is_Store()) {
1288                 DUIterator_Fast imax, i = in->fast_outs(imax);
1289                 _worklist.push(in->fast_out(i));
1290                 i++;
1291                 if (in->outcnt() == 2) {
1292                   _worklist.push(in->fast_out(i));
1293                   i++;
1294                 }
1295                 assert(!(i < imax), "sanity");
1296               }
1297             }
1298             if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1299                 in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1300               // A Load that directly follows an InitializeNode is
1301               // going away. The Stores that follow are candidates
1302               // again to be captured by the InitializeNode.
1303               for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1304                 Node *n = in->fast_out(j);
1305                 if (n->is_Store()) {
1306                   _worklist.push(n);
1307                 }
1308               }
1309             }
1310           } // if (in != NULL && in != C->top())
1311         } // for (uint i = 0; i < dead->req(); i++)
1312         if (recurse) {
1313           continue;
1314         }
1315       } // if (!dead->is_Con())
1316     } // if (progress_state == PROCESS_INPUTS)
1317 
1318     // Aggressively kill globally dead uses
1319     // (Rather than pushing all the outs at once, we push one at a time,
1320     // plus the parent to resume later, because of the indefinite number
1321     // of edge deletions per loop trip.)
1322     if (dead->outcnt() > 0) {
1323       // Recursively remove output edges
1324       _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1325     } else {
1326       // Finished disconnecting all input and output edges.
1327       _stack.pop();
1328       // Remove dead node from iterative worklist
1329       _worklist.remove(dead);
1330       // Constant node that has no out-edges and has only one in-edge from
1331       // root is usually dead. However, sometimes reshaping walk makes
1332       // it reachable by adding use edges. So, we will NOT count Con nodes
1333       // as dead to be conservative about the dead node count at any
1334       // given time.
1335       if (!dead->is_Con()) {
1336         C->record_dead_node(dead->_idx);
1337       }
1338       if (dead->is_macro()) {
1339         C->remove_macro_node(dead);
1340       }
1341       if (dead->is_expensive()) {
1342         C->remove_expensive_node(dead);
1343       }
1344       CastIINode* cast = dead->isa_CastII();
1345       if (cast != NULL && cast->has_range_check()) {
1346         C->remove_range_check_cast(cast);
1347       }
1348     }
1349   } // while (_stack.is_nonempty())
1350 }
1351 
1352 //------------------------------subsume_node-----------------------------------
1353 // Remove users from node 'old' and add them to node 'nn'.
1354 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1355   assert( old != hash_find(old), "should already been removed" );
1356   assert( old != C->top(), "cannot subsume top node");
1357   // Copy debug or profile information to the new version:
1358   C->copy_node_notes_to(nn, old);
1359   // Move users of node 'old' to node 'nn'
1360   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1361     Node* use = old->last_out(i);  // for each use...
1362     // use might need re-hashing (but it won't if it's a new node)
1363     bool is_in_table = _table.hash_delete( use );
1364     // Update use-def info as well
1365     // We remove all occurrences of old within use->in,
1366     // so as to avoid rehashing any node more than once.
1367     // The hash table probe swamps any outer loop overhead.
1368     uint num_edges = 0;
1369     for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1370       if (use->in(j) == old) {
1371         use->set_req(j, nn);
1372         ++num_edges;
1373       }
1374     }
1375     // Insert into GVN hash table if unique
1376     // If a duplicate, 'use' will be cleaned up when pulled off worklist
1377     if( is_in_table ) {
1378       hash_find_insert(use);
1379     }
1380     i -= num_edges;    // we deleted 1 or more copies of this edge
1381   }
1382 
1383   // Search for instance field data PhiNodes in the same region pointing to the old
1384   // memory PhiNode and update their instance memory ids to point to the new node.
1385   if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
1386     Node* region = old->in(0);
1387     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1388       PhiNode* phi = region->fast_out(i)->isa_Phi();
1389       if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
1390         phi->set_inst_mem_id((int)nn->_idx);
1391       }
1392     }
1393   }
1394 
1395   // Smash all inputs to 'old', isolating him completely
1396   Node *temp = new (C) Node(1);
1397   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
1398   remove_dead_node( old );
1399   temp->del_req(0);         // Yank bogus edge
1400 #ifndef PRODUCT
1401   if( VerifyIterativeGVN ) {
1402     for ( int i = 0; i < _verify_window_size; i++ ) {
1403       if ( _verify_window[i] == old )
1404         _verify_window[i] = nn;
1405     }
1406   }
1407 #endif
1408   _worklist.remove(temp);   // this can be necessary
1409   temp->destruct();         // reuse the _idx of this little guy
1410 }
1411 
1412 //------------------------------add_users_to_worklist--------------------------
1413 void PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1414   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1415     _worklist.push(n->fast_out(i));  // Push on worklist
1416   }
1417 }
1418 
1419 void PhaseIterGVN::add_users_to_worklist( Node *n ) {
1420   add_users_to_worklist0(n);
1421 
1422   // Move users of node to worklist
1423   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1424     Node* use = n->fast_out(i); // Get use
1425 
1426     if( use->is_Multi() ||      // Multi-definer?  Push projs on worklist
1427         use->is_Store() )       // Enable store/load same address
1428       add_users_to_worklist0(use);
1429 
1430     // If we changed the receiver type to a call, we need to revisit
1431     // the Catch following the call.  It's looking for a non-NULL
1432     // receiver to know when to enable the regular fall-through path
1433     // in addition to the NullPtrException path.
1434     if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1435       Node* p = use->as_CallDynamicJava()->proj_out(TypeFunc::Control);
1436       if (p != NULL) {
1437         add_users_to_worklist0(p);
1438       }
1439     }
1440 
1441     uint use_op = use->Opcode();
1442     if(use->is_Cmp()) {       // Enable CMP/BOOL optimization
1443       add_users_to_worklist(use); // Put Bool on worklist
1444       if (use->outcnt() > 0) {
1445         Node* bol = use->raw_out(0);
1446         if (bol->outcnt() > 0) {
1447           Node* iff = bol->raw_out(0);
1448           if (use_op == Op_CmpI &&
1449               iff->is_CountedLoopEnd()) {
1450             CountedLoopEndNode* cle = iff->as_CountedLoopEnd();
1451             if (cle->limit() == n && cle->phi() != NULL) {
1452               // If an opaque node feeds into the limit condition of a
1453               // CountedLoop, we need to process the Phi node for the
1454               // induction variable when the opaque node is removed:
1455               // the range of values taken by the Phi is now known and
1456               // so its type is also known.
1457               _worklist.push(cle->phi());
1458             }
1459           } else if (iff->outcnt() == 2) {
1460             // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1461             // phi merging either 0 or 1 onto the worklist
1462             Node* ifproj0 = iff->raw_out(0);
1463             Node* ifproj1 = iff->raw_out(1);
1464             if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1465               Node* region0 = ifproj0->raw_out(0);
1466               Node* region1 = ifproj1->raw_out(0);
1467               if( region0 == region1 )
1468                 add_users_to_worklist0(region0);
1469             }
1470           }
1471         }
1472       }
1473       if (use_op == Op_CmpI) {
1474         Node* in1 = use->in(1);
1475         for (uint i = 0; i < in1->outcnt(); i++) {
1476           if (in1->raw_out(i)->Opcode() == Op_CastII) {
1477             Node* castii = in1->raw_out(i);
1478             if (castii->in(0) != NULL && castii->in(0)->in(0) != NULL && castii->in(0)->in(0)->is_If()) {
1479               Node* ifnode = castii->in(0)->in(0);
1480               if (ifnode->in(1) != NULL && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == use) {
1481                 // Reprocess a CastII node that may depend on an
1482                 // opaque node value when the opaque node is
1483                 // removed. In case it carries a dependency we can do
1484                 // a better job of computing its type.
1485                 _worklist.push(castii);
1486               }
1487             }
1488           }
1489         }
1490       }
1491     }
1492 
1493     // If changed Cast input, check Phi users for simple cycles
1494     if( use->is_ConstraintCast() || use->is_CheckCastPP() ) {
1495       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1496         Node* u = use->fast_out(i2);
1497         if (u->is_Phi())
1498           _worklist.push(u);
1499       }
1500     }
1501     // If changed LShift inputs, check RShift users for useless sign-ext
1502     if( use_op == Op_LShiftI ) {
1503       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1504         Node* u = use->fast_out(i2);
1505         if (u->Opcode() == Op_RShiftI)
1506           _worklist.push(u);
1507       }
1508     }
1509     // If changed AddI/SubI inputs, check CmpU for range check optimization.
1510     if (use_op == Op_AddI || use_op == Op_SubI) {
1511       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1512         Node* u = use->fast_out(i2);
1513         if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
1514           _worklist.push(u);
1515         }
1516       }
1517     }
1518     // If changed AddP inputs, check Stores for loop invariant
1519     if( use_op == Op_AddP ) {
1520       for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1521         Node* u = use->fast_out(i2);
1522         if (u->is_Mem())
1523           _worklist.push(u);
1524       }
1525     }
1526     // If changed initialization activity, check dependent Stores
1527     if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1528       InitializeNode* init = use->as_Allocate()->initialization();
1529       if (init != NULL) {
1530         Node* imem = init->proj_out(TypeFunc::Memory);
1531         if (imem != NULL)  add_users_to_worklist0(imem);
1532       }
1533     }
1534     if (use_op == Op_Initialize) {
1535       Node* imem = use->as_Initialize()->proj_out(TypeFunc::Memory);
1536       if (imem != NULL)  add_users_to_worklist0(imem);
1537     }
1538   }
1539 }
1540 
1541 /**
1542  * Remove the speculative part of all types that we know of
1543  */
1544 void PhaseIterGVN::remove_speculative_types()  {
1545   assert(UseTypeSpeculation, "speculation is off");
1546   for (uint i = 0; i < _types.Size(); i++)  {
1547     const Type* t = _types.fast_lookup(i);
1548     if (t != NULL) {
1549       _types.map(i, t->remove_speculative());
1550     }
1551   }
1552   _table.check_no_speculative_types();
1553 }
1554 
1555 //=============================================================================
1556 #ifndef PRODUCT
1557 uint PhaseCCP::_total_invokes   = 0;
1558 uint PhaseCCP::_total_constants = 0;
1559 #endif
1560 //------------------------------PhaseCCP---------------------------------------
1561 // Conditional Constant Propagation, ala Wegman & Zadeck
1562 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
1563   NOT_PRODUCT( clear_constants(); )
1564   assert( _worklist.size() == 0, "" );
1565   // Clear out _nodes from IterGVN.  Must be clear to transform call.
1566   _nodes.clear();               // Clear out from IterGVN
1567   analyze();
1568 }
1569 
1570 #ifndef PRODUCT
1571 //------------------------------~PhaseCCP--------------------------------------
1572 PhaseCCP::~PhaseCCP() {
1573   inc_invokes();
1574   _total_constants += count_constants();
1575 }
1576 #endif
1577 
1578 
1579 #ifdef ASSERT
1580 static bool ccp_type_widens(const Type* t, const Type* t0) {
1581   assert(t->meet(t0) == t, "Not monotonic");
1582   switch (t->base() == t0->base() ? t->base() : Type::Top) {
1583   case Type::Int:
1584     assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1585     break;
1586   case Type::Long:
1587     assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1588     break;
1589   }
1590   return true;
1591 }
1592 #endif //ASSERT
1593 
1594 //------------------------------analyze----------------------------------------
1595 void PhaseCCP::analyze() {
1596   // Initialize all types to TOP, optimistic analysis
1597   for (int i = C->unique() - 1; i >= 0; i--)  {
1598     _types.map(i,Type::TOP);
1599   }
1600 
1601   // Push root onto worklist
1602   Unique_Node_List worklist;
1603   worklist.push(C->root());
1604 
1605   // Pull from worklist; compute new value; push changes out.
1606   // This loop is the meat of CCP.
1607   while( worklist.size() ) {
1608     Node *n = worklist.pop();
1609     const Type *t = n->Value(this);
1610     if (t != type(n)) {
1611       assert(ccp_type_widens(t, type(n)), "ccp type must widen");
1612 #ifndef PRODUCT
1613       if( TracePhaseCCP ) {
1614         t->dump();
1615         do { tty->print("\t"); } while (tty->position() < 16);
1616         n->dump();
1617       }
1618 #endif
1619       set_type(n, t);
1620       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1621         Node* m = n->fast_out(i);   // Get user
1622         if (m->is_Region()) {  // New path to Region?  Must recheck Phis too
1623           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1624             Node* p = m->fast_out(i2); // Propagate changes to uses
1625             if (p->bottom_type() != type(p)) { // If not already bottomed out
1626               worklist.push(p); // Propagate change to user
1627             }
1628           }
1629         }
1630         // If we changed the receiver type to a call, we need to revisit
1631         // the Catch following the call.  It's looking for a non-NULL
1632         // receiver to know when to enable the regular fall-through path
1633         // in addition to the NullPtrException path
1634         if (m->is_Call()) {
1635           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1636             Node* p = m->fast_out(i2);  // Propagate changes to uses
1637             if (p->is_Proj() && p->as_Proj()->_con == TypeFunc::Control && p->outcnt() == 1) {
1638               worklist.push(p->unique_out());
1639             }
1640           }
1641         }
1642         if (m->bottom_type() != type(m)) { // If not already bottomed out
1643           worklist.push(m);     // Propagate change to user
1644         }
1645 
1646         // CmpU nodes can get their type information from two nodes up in the
1647         // graph (instead of from the nodes immediately above). Make sure they
1648         // are added to the worklist if nodes they depend on are updated, since
1649         // they could be missed and get wrong types otherwise.
1650         uint m_op = m->Opcode();
1651         if (m_op == Op_AddI || m_op == Op_SubI) {
1652           for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1653             Node* p = m->fast_out(i2); // Propagate changes to uses
1654             if (p->Opcode() == Op_CmpU) {
1655               // Got a CmpU which might need the new type information from node n.
1656               if(p->bottom_type() != type(p)) { // If not already bottomed out
1657                 worklist.push(p); // Propagate change to user
1658               }
1659             }
1660           }
1661         }
1662       }
1663     }
1664   }
1665 }
1666 
1667 //------------------------------do_transform-----------------------------------
1668 // Top level driver for the recursive transformer
1669 void PhaseCCP::do_transform() {
1670   // Correct leaves of new-space Nodes; they point to old-space.
1671   C->set_root( transform(C->root())->as_Root() );
1672   assert( C->top(),  "missing TOP node" );
1673   assert( C->root(), "missing root" );
1674 }
1675 
1676 //------------------------------transform--------------------------------------
1677 // Given a Node in old-space, clone him into new-space.
1678 // Convert any of his old-space children into new-space children.
1679 Node *PhaseCCP::transform( Node *n ) {
1680   Node *new_node = _nodes[n->_idx]; // Check for transformed node
1681   if( new_node != NULL )
1682     return new_node;                // Been there, done that, return old answer
1683   new_node = transform_once(n);     // Check for constant
1684   _nodes.map( n->_idx, new_node );  // Flag as having been cloned
1685 
1686   // Allocate stack of size _nodes.Size()/2 to avoid frequent realloc
1687   GrowableArray <Node *> trstack(C->live_nodes() >> 1);
1688 
1689   trstack.push(new_node);           // Process children of cloned node
1690   while ( trstack.is_nonempty() ) {
1691     Node *clone = trstack.pop();
1692     uint cnt = clone->req();
1693     for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
1694       Node *input = clone->in(i);
1695       if( input != NULL ) {                    // Ignore NULLs
1696         Node *new_input = _nodes[input->_idx]; // Check for cloned input node
1697         if( new_input == NULL ) {
1698           new_input = transform_once(input);   // Check for constant
1699           _nodes.map( input->_idx, new_input );// Flag as having been cloned
1700           trstack.push(new_input);
1701         }
1702         assert( new_input == clone->in(i), "insanity check");
1703       }
1704     }
1705   }
1706   return new_node;
1707 }
1708 
1709 
1710 //------------------------------transform_once---------------------------------
1711 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
1712 Node *PhaseCCP::transform_once( Node *n ) {
1713   const Type *t = type(n);
1714   // Constant?  Use constant Node instead
1715   if( t->singleton() ) {
1716     Node *nn = n;               // Default is to return the original constant
1717     if( t == Type::TOP ) {
1718       // cache my top node on the Compile instance
1719       if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
1720         C->set_cached_top_node( ConNode::make(C, Type::TOP) );
1721         set_type(C->top(), Type::TOP);
1722       }
1723       nn = C->top();
1724     }
1725     if( !n->is_Con() ) {
1726       if( t != Type::TOP ) {
1727         nn = makecon(t);        // ConNode::make(t);
1728         NOT_PRODUCT( inc_constants(); )
1729       } else if( n->is_Region() ) { // Unreachable region
1730         // Note: nn == C->top()
1731         n->set_req(0, NULL);        // Cut selfreference
1732         // Eagerly remove dead phis to avoid phis copies creation.
1733         for (DUIterator i = n->outs(); n->has_out(i); i++) {
1734           Node* m = n->out(i);
1735           if( m->is_Phi() ) {
1736             assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
1737             replace_node(m, nn);
1738             --i; // deleted this phi; rescan starting with next position
1739           }
1740         }
1741       }
1742       replace_node(n,nn);       // Update DefUse edges for new constant
1743     }
1744     return nn;
1745   }
1746 
1747   // If x is a TypeNode, capture any more-precise type permanently into Node
1748   if (t != n->bottom_type()) {
1749     hash_delete(n);             // changing bottom type may force a rehash
1750     n->raise_bottom_type(t);
1751     _worklist.push(n);          // n re-enters the hash table via the worklist
1752   }
1753 
1754   // Idealize graph using DU info.  Must clone() into new-space.
1755   // DU info is generally used to show profitability, progress or safety
1756   // (but generally not needed for correctness).
1757   Node *nn = n->Ideal_DU_postCCP(this);
1758 
1759   // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
1760   switch( n->Opcode() ) {
1761   case Op_FastLock:      // Revisit FastLocks for lock coarsening
1762   case Op_If:
1763   case Op_CountedLoopEnd:
1764   case Op_Region:
1765   case Op_Loop:
1766   case Op_CountedLoop:
1767   case Op_Conv2B:
1768   case Op_Opaque1:
1769   case Op_Opaque2:
1770     _worklist.push(n);
1771     break;
1772   default:
1773     break;
1774   }
1775   if( nn ) {
1776     _worklist.push(n);
1777     // Put users of 'n' onto worklist for second igvn transform
1778     add_users_to_worklist(n);
1779     return nn;
1780   }
1781 
1782   return  n;
1783 }
1784 
1785 //---------------------------------saturate------------------------------------
1786 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
1787                                const Type* limit_type) const {
1788   const Type* wide_type = new_type->widen(old_type, limit_type);
1789   if (wide_type != new_type) {          // did we widen?
1790     // If so, we may have widened beyond the limit type.  Clip it back down.
1791     new_type = wide_type->filter(limit_type);
1792   }
1793   return new_type;
1794 }
1795 
1796 //------------------------------print_statistics-------------------------------
1797 #ifndef PRODUCT
1798 void PhaseCCP::print_statistics() {
1799   tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
1800 }
1801 #endif
1802 
1803 
1804 //=============================================================================
1805 #ifndef PRODUCT
1806 uint PhasePeephole::_total_peepholes = 0;
1807 #endif
1808 //------------------------------PhasePeephole----------------------------------
1809 // Conditional Constant Propagation, ala Wegman & Zadeck
1810 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
1811   : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
1812   NOT_PRODUCT( clear_peepholes(); )
1813 }
1814 
1815 #ifndef PRODUCT
1816 //------------------------------~PhasePeephole---------------------------------
1817 PhasePeephole::~PhasePeephole() {
1818   _total_peepholes += count_peepholes();
1819 }
1820 #endif
1821 
1822 //------------------------------transform--------------------------------------
1823 Node *PhasePeephole::transform( Node *n ) {
1824   ShouldNotCallThis();
1825   return NULL;
1826 }
1827 
1828 //------------------------------do_transform-----------------------------------
1829 void PhasePeephole::do_transform() {
1830   bool method_name_not_printed = true;
1831 
1832   // Examine each basic block
1833   for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
1834     Block* block = _cfg.get_block(block_number);
1835     bool block_not_printed = true;
1836 
1837     // and each instruction within a block
1838     uint end_index = block->number_of_nodes();
1839     // block->end_idx() not valid after PhaseRegAlloc
1840     for( uint instruction_index = 1; instruction_index < end_index; ++instruction_index ) {
1841       Node     *n = block->get_node(instruction_index);
1842       if( n->is_Mach() ) {
1843         MachNode *m = n->as_Mach();
1844         int deleted_count = 0;
1845         // check for peephole opportunities
1846         MachNode *m2 = m->peephole( block, instruction_index, _regalloc, deleted_count, C );
1847         if( m2 != NULL ) {
1848 #ifndef PRODUCT
1849           if( PrintOptoPeephole ) {
1850             // Print method, first time only
1851             if( C->method() && method_name_not_printed ) {
1852               C->method()->print_short_name(); tty->cr();
1853               method_name_not_printed = false;
1854             }
1855             // Print this block
1856             if( Verbose && block_not_printed) {
1857               tty->print_cr("in block");
1858               block->dump();
1859               block_not_printed = false;
1860             }
1861             // Print instructions being deleted
1862             for( int i = (deleted_count - 1); i >= 0; --i ) {
1863               block->get_node(instruction_index-i)->as_Mach()->format(_regalloc); tty->cr();
1864             }
1865             tty->print_cr("replaced with");
1866             // Print new instruction
1867             m2->format(_regalloc);
1868             tty->print("\n\n");
1869           }
1870 #endif
1871           // Remove old nodes from basic block and update instruction_index
1872           // (old nodes still exist and may have edges pointing to them
1873           //  as register allocation info is stored in the allocator using
1874           //  the node index to live range mappings.)
1875           uint safe_instruction_index = (instruction_index - deleted_count);
1876           for( ; (instruction_index > safe_instruction_index); --instruction_index ) {
1877             block->remove_node( instruction_index );
1878           }
1879           // install new node after safe_instruction_index
1880           block->insert_node(m2, safe_instruction_index + 1);
1881           end_index = block->number_of_nodes() - 1; // Recompute new block size
1882           NOT_PRODUCT( inc_peepholes(); )
1883         }
1884       }
1885     }
1886   }
1887 }
1888 
1889 //------------------------------print_statistics-------------------------------
1890 #ifndef PRODUCT
1891 void PhasePeephole::print_statistics() {
1892   tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
1893 }
1894 #endif
1895 
1896 
1897 //=============================================================================
1898 //------------------------------set_req_X--------------------------------------
1899 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
1900   assert( is_not_dead(n), "can not use dead node");
1901   assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
1902   Node *old = in(i);
1903   set_req(i, n);
1904 
1905   // old goes dead?
1906   if( old ) {
1907     switch (old->outcnt()) {
1908     case 0:
1909       // Put into the worklist to kill later. We do not kill it now because the
1910       // recursive kill will delete the current node (this) if dead-loop exists
1911       if (!old->is_top())
1912         igvn->_worklist.push( old );
1913       break;
1914     case 1:
1915       if( old->is_Store() || old->has_special_unique_user() )
1916         igvn->add_users_to_worklist( old );
1917       break;
1918     case 2:
1919       if( old->is_Store() )
1920         igvn->add_users_to_worklist( old );
1921       if( old->Opcode() == Op_Region )
1922         igvn->_worklist.push(old);
1923       break;
1924     case 3:
1925       if( old->Opcode() == Op_Region ) {
1926         igvn->_worklist.push(old);
1927         igvn->add_users_to_worklist( old );
1928       }
1929       break;
1930     default:
1931       break;
1932     }
1933   }
1934 
1935 }
1936 
1937 //-------------------------------replace_by-----------------------------------
1938 // Using def-use info, replace one node for another.  Follow the def-use info
1939 // to all users of the OLD node.  Then make all uses point to the NEW node.
1940 void Node::replace_by(Node *new_node) {
1941   assert(!is_top(), "top node has no DU info");
1942   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
1943     Node* use = last_out(i);
1944     uint uses_found = 0;
1945     for (uint j = 0; j < use->len(); j++) {
1946       if (use->in(j) == this) {
1947         if (j < use->req())
1948               use->set_req(j, new_node);
1949         else  use->set_prec(j, new_node);
1950         uses_found++;
1951       }
1952     }
1953     i -= uses_found;    // we deleted 1 or more copies of this edge
1954   }
1955 }
1956 
1957 //=============================================================================
1958 //-----------------------------------------------------------------------------
1959 void Type_Array::grow( uint i ) {
1960   if( !_max ) {
1961     _max = 1;
1962     _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
1963     _types[0] = NULL;
1964   }
1965   uint old = _max;
1966   while( i >= _max ) _max <<= 1;        // Double to fit
1967   _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
1968   memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
1969 }
1970 
1971 //------------------------------dump-------------------------------------------
1972 #ifndef PRODUCT
1973 void Type_Array::dump() const {
1974   uint max = Size();
1975   for( uint i = 0; i < max; i++ ) {
1976     if( _types[i] != NULL ) {
1977       tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
1978     }
1979   }
1980 }
1981 #endif