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