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