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