phaseX.cpp revision 6412:53a41e7cbe05
1169689Skan/*
2169689Skan * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
3169689Skan * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4169689Skan *
5169689Skan * This code is free software; you can redistribute it and/or modify it
6169689Skan * under the terms of the GNU General Public License version 2 only, as
7169689Skan * published by the Free Software Foundation.
8169689Skan *
9169689Skan * This code is distributed in the hope that it will be useful, but WITHOUT
10169689Skan * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11169689Skan * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12169689Skan * version 2 for more details (a copy is included in the LICENSE file that
13169689Skan * accompanied this code).
14169689Skan *
15169689Skan * You should have received a copy of the GNU General Public License version
16169689Skan * 2 along with this work; if not, write to the Free Software Foundation,
17169689Skan * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18169689Skan *
19169689Skan * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20169689Skan * or visit www.oracle.com if you need additional information or have any
21169689Skan * questions.
22169689Skan *
23169689Skan */
24169689Skan
25169689Skan#include "precompiled.hpp"
26169689Skan#include "memory/allocation.inline.hpp"
27169689Skan#include "opto/block.hpp"
28169689Skan#include "opto/callnode.hpp"
29169689Skan#include "opto/cfgnode.hpp"
30169689Skan#include "opto/idealGraphPrinter.hpp"
31169689Skan#include "opto/loopnode.hpp"
32169689Skan#include "opto/machnode.hpp"
33169689Skan#include "opto/opcodes.hpp"
34169689Skan#include "opto/phaseX.hpp"
35169689Skan#include "opto/regalloc.hpp"
36169689Skan#include "opto/rootnode.hpp"
37169689Skan
38169689Skan//=============================================================================
39169689Skan#define NODE_HASH_MINIMUM_SIZE    255
40169689Skan//------------------------------NodeHash---------------------------------------
41169689SkanNodeHash::NodeHash(uint est_max_size) :
42169689Skan  _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
43169689Skan  _a(Thread::current()->resource_area()),
44169689Skan  _table( NEW_ARENA_ARRAY( _a , Node* , _max ) ), // (Node**)_a->Amalloc(_max * sizeof(Node*)) ),
45169689Skan  _inserts(0), _insert_limit( insert_limit() ),
46169689Skan  _look_probes(0), _lookup_hits(0), _lookup_misses(0),
47169689Skan  _total_insert_probes(0), _total_inserts(0),
48169689Skan  _insert_probes(0), _grows(0) {
49169689Skan  // _sentinel must be in the current node space
50169689Skan  _sentinel = new (Compile::current()) ProjNode(NULL, TypeFunc::Control);
51169689Skan  memset(_table,0,sizeof(Node*)*_max);
52169689Skan}
53169689Skan
54169689Skan//------------------------------NodeHash---------------------------------------
55169689SkanNodeHash::NodeHash(Arena *arena, uint est_max_size) :
56169689Skan  _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
57169689Skan  _a(arena),
58169689Skan  _table( NEW_ARENA_ARRAY( _a , Node* , _max ) ),
59169689Skan  _inserts(0), _insert_limit( insert_limit() ),
60169689Skan  _look_probes(0), _lookup_hits(0), _lookup_misses(0),
61169689Skan  _delete_probes(0), _delete_hits(0), _delete_misses(0),
62169689Skan  _total_insert_probes(0), _total_inserts(0),
63169689Skan  _insert_probes(0), _grows(0) {
64169689Skan  // _sentinel must be in the current node space
65169689Skan  _sentinel = new (Compile::current()) ProjNode(NULL, TypeFunc::Control);
66169689Skan  memset(_table,0,sizeof(Node*)*_max);
67169689Skan}
68169689Skan
69169689Skan//------------------------------NodeHash---------------------------------------
70169689SkanNodeHash::NodeHash(NodeHash *nh) {
71169689Skan  debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
72169689Skan  // just copy in all the fields
73169689Skan  *this = *nh;
74169689Skan  // nh->_sentinel must be in the current node space
75169689Skan}
76169689Skan
77169689Skanvoid NodeHash::replace_with(NodeHash *nh) {
78169689Skan  debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
79169689Skan  // just copy in all the fields
80169689Skan  *this = *nh;
81169689Skan  // nh->_sentinel must be in the current node space
82169689Skan}
83169689Skan
84169689Skan//------------------------------hash_find--------------------------------------
85169689Skan// Find in hash table
86169689SkanNode *NodeHash::hash_find( const Node *n ) {
87169689Skan  // ((Node*)n)->set_hash( n->hash() );
88169689Skan  uint hash = n->hash();
89169689Skan  if (hash == Node::NO_HASH) {
90169689Skan    debug_only( _lookup_misses++ );
91169689Skan    return NULL;
92169689Skan  }
93169689Skan  uint key = hash & (_max-1);
94169689Skan  uint stride = key | 0x01;
95169689Skan  debug_only( _look_probes++ );
96169689Skan  Node *k = _table[key];        // Get hashed value
97169689Skan  if( !k ) {                    // ?Miss?
98169689Skan    debug_only( _lookup_misses++ );
99169689Skan    return NULL;                // Miss!
100169689Skan  }
101169689Skan
102169689Skan  int op = n->Opcode();
103169689Skan  uint req = n->req();
104169689Skan  while( 1 ) {                  // While probing hash table
105169689Skan    if( k->req() == req &&      // Same count of inputs
106169689Skan        k->Opcode() == op ) {   // Same Opcode
107169689Skan      for( uint i=0; i<req; i++ )
108169689Skan        if( n->in(i)!=k->in(i)) // Different inputs?
109169689Skan          goto collision;       // "goto" is a speed hack...
110169689Skan      if( n->cmp(*k) ) {        // Check for any special bits
111169689Skan        debug_only( _lookup_hits++ );
112169689Skan        return k;               // Hit!
113169689Skan      }
114169689Skan    }
115169689Skan  collision:
116169689Skan    debug_only( _look_probes++ );
117169689Skan    key = (key + stride/*7*/) & (_max-1); // Stride through table with relative prime
118169689Skan    k = _table[key];            // Get hashed value
119169689Skan    if( !k ) {                  // ?Miss?
120169689Skan      debug_only( _lookup_misses++ );
121169689Skan      return NULL;              // Miss!
122169689Skan    }
123169689Skan  }
124169689Skan  ShouldNotReachHere();
125169689Skan  return NULL;
126169689Skan}
127169689Skan
128169689Skan//------------------------------hash_find_insert-------------------------------
129169689Skan// Find in hash table, insert if not already present
130169689Skan// Used to preserve unique entries in hash table
131169689SkanNode *NodeHash::hash_find_insert( Node *n ) {
132169689Skan  // n->set_hash( );
133169689Skan  uint hash = n->hash();
134169689Skan  if (hash == Node::NO_HASH) {
135169689Skan    debug_only( _lookup_misses++ );
136169689Skan    return NULL;
137169689Skan  }
138169689Skan  uint key = hash & (_max-1);
139169689Skan  uint stride = key | 0x01;     // stride must be relatively prime to table siz
140169689Skan  uint first_sentinel = 0;      // replace a sentinel if seen.
141169689Skan  debug_only( _look_probes++ );
142169689Skan  Node *k = _table[key];        // Get hashed value
143169689Skan  if( !k ) {                    // ?Miss?
144169689Skan    debug_only( _lookup_misses++ );
145169689Skan    _table[key] = n;            // Insert into table!
146169689Skan    debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
147169689Skan    check_grow();               // Grow table if insert hit limit
148169689Skan    return NULL;                // Miss!
149169689Skan  }
150169689Skan  else if( k == _sentinel ) {
151169689Skan    first_sentinel = key;      // Can insert here
152169689Skan  }
153169689Skan
154169689Skan  int op = n->Opcode();
155169689Skan  uint req = n->req();
156169689Skan  while( 1 ) {                  // While probing hash table
157169689Skan    if( k->req() == req &&      // Same count of inputs
158169689Skan        k->Opcode() == op ) {   // Same Opcode
159169689Skan      for( uint i=0; i<req; i++ )
160169689Skan        if( n->in(i)!=k->in(i)) // Different inputs?
161169689Skan          goto collision;       // "goto" is a speed hack...
162169689Skan      if( n->cmp(*k) ) {        // Check for any special bits
163169689Skan        debug_only( _lookup_hits++ );
164169689Skan        return k;               // Hit!
165169689Skan      }
166169689Skan    }
167169689Skan  collision:
168169689Skan    debug_only( _look_probes++ );
169169689Skan    key = (key + stride) & (_max-1); // Stride through table w/ relative prime
170169689Skan    k = _table[key];            // Get hashed value
171169689Skan    if( !k ) {                  // ?Miss?
172169689Skan      debug_only( _lookup_misses++ );
173169689Skan      key = (first_sentinel == 0) ? key : first_sentinel; // ?saw sentinel?
174169689Skan      _table[key] = n;          // Insert into table!
175169689Skan      debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
176169689Skan      check_grow();             // Grow table if insert hit limit
177169689Skan      return NULL;              // Miss!
178169689Skan    }
179169689Skan    else if( first_sentinel == 0 && k == _sentinel ) {
180169689Skan      first_sentinel = key;    // Can insert here
181169689Skan    }
182169689Skan
183169689Skan  }
184169689Skan  ShouldNotReachHere();
185169689Skan  return NULL;
186169689Skan}
187169689Skan
188169689Skan//------------------------------hash_insert------------------------------------
189169689Skan// Insert into hash table
190169689Skanvoid NodeHash::hash_insert( Node *n ) {
191169689Skan  // // "conflict" comments -- print nodes that conflict
192169689Skan  // bool conflict = false;
193169689Skan  // n->set_hash();
194169689Skan  uint hash = n->hash();
195169689Skan  if (hash == Node::NO_HASH) {
196169689Skan    return;
197169689Skan  }
198169689Skan  check_grow();
199169689Skan  uint key = hash & (_max-1);
200169689Skan  uint stride = key | 0x01;
201169689Skan
202169689Skan  while( 1 ) {                  // While probing hash table
203169689Skan    debug_only( _insert_probes++ );
204169689Skan    Node *k = _table[key];      // Get hashed value
205169689Skan    if( !k || (k == _sentinel) ) break;       // Found a slot
206169689Skan    assert( k != n, "already inserted" );
207169689Skan    // if( PrintCompilation && PrintOptoStatistics && Verbose ) { tty->print("  conflict: "); k->dump(); conflict = true; }
208169689Skan    key = (key + stride) & (_max-1); // Stride through table w/ relative prime
209169689Skan  }
210169689Skan  _table[key] = n;              // Insert into table!
211169689Skan  debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
212169689Skan  // if( conflict ) { n->dump(); }
213169689Skan}
214169689Skan
215169689Skan//------------------------------hash_delete------------------------------------
216169689Skan// Replace in hash table with sentinel
217169689Skanbool NodeHash::hash_delete( const Node *n ) {
218169689Skan  Node *k;
219169689Skan  uint hash = n->hash();
220169689Skan  if (hash == Node::NO_HASH) {
221169689Skan    debug_only( _delete_misses++ );
222169689Skan    return false;
223169689Skan  }
224169689Skan  uint key = hash & (_max-1);
225169689Skan  uint stride = key | 0x01;
226169689Skan  debug_only( uint counter = 0; );
227169689Skan  for( ; /* (k != NULL) && (k != _sentinel) */; ) {
228169689Skan    debug_only( counter++ );
229169689Skan    debug_only( _delete_probes++ );
230169689Skan    k = _table[key];            // Get hashed value
231169689Skan    if( !k ) {                  // Miss?
232169689Skan      debug_only( _delete_misses++ );
233169689Skan#ifdef ASSERT
234169689Skan      if( VerifyOpto ) {
235169689Skan        for( uint i=0; i < _max; i++ )
236169689Skan          assert( _table[i] != n, "changed edges with rehashing" );
237169689Skan      }
238169689Skan#endif
239169689Skan      return false;             // Miss! Not in chain
240169689Skan    }
241169689Skan    else if( n == k ) {
242169689Skan      debug_only( _delete_hits++ );
243169689Skan      _table[key] = _sentinel;  // Hit! Label as deleted entry
244169689Skan      debug_only(((Node*)n)->exit_hash_lock()); // Unlock the node upon removal from table.
245169689Skan      return true;
246169689Skan    }
247169689Skan    else {
248169689Skan      // collision: move through table with prime offset
249169689Skan      key = (key + stride/*7*/) & (_max-1);
250169689Skan      assert( counter <= _insert_limit, "Cycle in hash-table");
251169689Skan    }
252169689Skan  }
253169689Skan  ShouldNotReachHere();
254169689Skan  return false;
255169689Skan}
256169689Skan
257169689Skan//------------------------------round_up---------------------------------------
258169689Skan// Round up to nearest power of 2
259169689Skanuint NodeHash::round_up( uint x ) {
260169689Skan  x += (x>>2);                  // Add 25% slop
261169689Skan  if( x <16 ) return 16;        // Small stuff
262169689Skan  uint i=16;
263169689Skan  while( i < x ) i <<= 1;       // Double to fit
264169689Skan  return i;                     // Return hash table size
265169689Skan}
266169689Skan
267169689Skan//------------------------------grow-------------------------------------------
268169689Skan// Grow _table to next power of 2 and insert old entries
269169689Skanvoid  NodeHash::grow() {
270169689Skan  // Record old state
271169689Skan  uint   old_max   = _max;
272169689Skan  Node **old_table = _table;
273169689Skan  // Construct new table with twice the space
274169689Skan  _grows++;
275169689Skan  _total_inserts       += _inserts;
276169689Skan  _total_insert_probes += _insert_probes;
277169689Skan  _inserts         = 0;
278169689Skan  _insert_probes   = 0;
279169689Skan  _max     = _max << 1;
280169689Skan  _table   = NEW_ARENA_ARRAY( _a , Node* , _max ); // (Node**)_a->Amalloc( _max * sizeof(Node*) );
281169689Skan  memset(_table,0,sizeof(Node*)*_max);
282169689Skan  _insert_limit = insert_limit();
283169689Skan  // Insert old entries into the new table
284169689Skan  for( uint i = 0; i < old_max; i++ ) {
285169689Skan    Node *m = *old_table++;
286169689Skan    if( !m || m == _sentinel ) continue;
287169689Skan    debug_only(m->exit_hash_lock()); // Unlock the node upon removal from old table.
288169689Skan    hash_insert(m);
289169689Skan  }
290169689Skan}
291169689Skan
292169689Skan//------------------------------clear------------------------------------------
293169689Skan// Clear all entries in _table to NULL but keep storage
294169689Skanvoid  NodeHash::clear() {
295169689Skan#ifdef ASSERT
296169689Skan  // Unlock all nodes upon removal from table.
297169689Skan  for (uint i = 0; i < _max; i++) {
298169689Skan    Node* n = _table[i];
299169689Skan    if (!n || n == _sentinel)  continue;
300169689Skan    n->exit_hash_lock();
301169689Skan  }
302169689Skan#endif
303169689Skan
304169689Skan  memset( _table, 0, _max * sizeof(Node*) );
305169689Skan}
306169689Skan
307169689Skan//-----------------------remove_useless_nodes----------------------------------
308169689Skan// Remove useless nodes from value table,
309169689Skan// implementation does not depend on hash function
310169689Skanvoid NodeHash::remove_useless_nodes(VectorSet &useful) {
311169689Skan
312169689Skan  // Dead nodes in the hash table inherited from GVN should not replace
313169689Skan  // existing nodes, remove dead nodes.
314169689Skan  uint max = size();
315169689Skan  Node *sentinel_node = sentinel();
316169689Skan  for( uint i = 0; i < max; ++i ) {
317169689Skan    Node *n = at(i);
318169689Skan    if(n != NULL && n != sentinel_node && !useful.test(n->_idx)) {
319169689Skan      debug_only(n->exit_hash_lock()); // Unlock the node when removed
320169689Skan      _table[i] = sentinel_node;       // Replace with placeholder
321169689Skan    }
322169689Skan  }
323169689Skan}
324169689Skan
325169689Skan
326169689Skanvoid NodeHash::check_no_speculative_types() {
327169689Skan#ifdef ASSERT
328169689Skan  uint max = size();
329169689Skan  Node *sentinel_node = sentinel();
330169689Skan  for (uint i = 0; i < max; ++i) {
331169689Skan    Node *n = at(i);
332169689Skan    if(n != NULL && n != sentinel_node && n->is_Type() && n->outcnt() > 0) {
333169689Skan      TypeNode* tn = n->as_Type();
334169689Skan      const Type* t = tn->type();
335169689Skan      const Type* t_no_spec = t->remove_speculative();
336169689Skan      assert(t == t_no_spec, "dead node in hash table or missed node during speculative cleanup");
337169689Skan    }
338169689Skan  }
339169689Skan#endif
340169689Skan}
341169689Skan
342169689Skan#ifndef PRODUCT
343169689Skan//------------------------------dump-------------------------------------------
344169689Skan// Dump statistics for the hash table
345169689Skanvoid NodeHash::dump() {
346169689Skan  _total_inserts       += _inserts;
347169689Skan  _total_insert_probes += _insert_probes;
348169689Skan  if (PrintCompilation && PrintOptoStatistics && Verbose && (_inserts > 0)) {
349169689Skan    if (WizardMode) {
350169689Skan      for (uint i=0; i<_max; i++) {
351169689Skan        if (_table[i])
352169689Skan          tty->print("%d/%d/%d ",i,_table[i]->hash()&(_max-1),_table[i]->_idx);
353169689Skan      }
354169689Skan    }
355169689Skan    tty->print("\nGVN Hash stats:  %d grows to %d max_size\n", _grows, _max);
356169689Skan    tty->print("  %d/%d (%8.1f%% full)\n", _inserts, _max, (double)_inserts/_max*100.0);
357169689Skan    tty->print("  %dp/(%dh+%dm) (%8.2f probes/lookup)\n", _look_probes, _lookup_hits, _lookup_misses, (double)_look_probes/(_lookup_hits+_lookup_misses));
358169689Skan    tty->print("  %dp/%di (%8.2f probes/insert)\n", _total_insert_probes, _total_inserts, (double)_total_insert_probes/_total_inserts);
359169689Skan    // sentinels increase lookup cost, but not insert cost
360169689Skan    assert((_lookup_misses+_lookup_hits)*4+100 >= _look_probes, "bad hash function");
361169689Skan    assert( _inserts+(_inserts>>3) < _max, "table too full" );
362169689Skan    assert( _inserts*3+100 >= _insert_probes, "bad hash function" );
363169689Skan  }
364169689Skan}
365169689Skan
366169689SkanNode *NodeHash::find_index(uint idx) { // For debugging
367169689Skan  // Find an entry by its index value
368169689Skan  for( uint i = 0; i < _max; i++ ) {
369169689Skan    Node *m = _table[i];
370169689Skan    if( !m || m == _sentinel ) continue;
371169689Skan    if( m->_idx == (uint)idx ) return m;
372169689Skan  }
373169689Skan  return NULL;
374169689Skan}
375169689Skan#endif
376169689Skan
377169689Skan#ifdef ASSERT
378169689SkanNodeHash::~NodeHash() {
379169689Skan  // Unlock all nodes upon destruction of table.
380169689Skan  if (_table != (Node**)badAddress)  clear();
381169689Skan}
382169689Skan
383169689Skanvoid NodeHash::operator=(const NodeHash& nh) {
384169689Skan  // Unlock all nodes upon replacement of table.
385169689Skan  if (&nh == this)  return;
386169689Skan  if (_table != (Node**)badAddress)  clear();
387169689Skan  memcpy(this, &nh, sizeof(*this));
388169689Skan  // Do not increment hash_lock counts again.
389169689Skan  // Instead, be sure we never again use the source table.
390169689Skan  ((NodeHash*)&nh)->_table = (Node**)badAddress;
391169689Skan}
392169689Skan
393169689Skan
394169689Skan#endif
395169689Skan
396169689Skan
397169689Skan//=============================================================================
398169689Skan//------------------------------PhaseRemoveUseless-----------------------------
399169689Skan// 1) Use a breadthfirst walk to collect useful nodes reachable from root.
400169689SkanPhaseRemoveUseless::PhaseRemoveUseless( PhaseGVN *gvn, Unique_Node_List *worklist ) : Phase(Remove_Useless),
401169689Skan  _useful(Thread::current()->resource_area()) {
402169689Skan
403169689Skan  // Implementation requires 'UseLoopSafepoints == true' and an edge from root
404169689Skan  // to each SafePointNode at a backward branch.  Inserted in add_safepoint().
405169689Skan  if( !UseLoopSafepoints || !OptoRemoveUseless ) return;
406169689Skan
407169689Skan  // Identify nodes that are reachable from below, useful.
408169689Skan  C->identify_useful_nodes(_useful);
409169689Skan  // Update dead node list
410169689Skan  C->update_dead_node_list(_useful);
411169689Skan
412169689Skan  // Remove all useless nodes from PhaseValues' recorded types
413169689Skan  // Must be done before disconnecting nodes to preserve hash-table-invariant
414169689Skan  gvn->remove_useless_nodes(_useful.member_set());
415169689Skan
416169689Skan  // Remove all useless nodes from future worklist
417169689Skan  worklist->remove_useless_nodes(_useful.member_set());
418169689Skan
419169689Skan  // Disconnect 'useless' nodes that are adjacent to useful nodes
420169689Skan  C->remove_useless_nodes(_useful);
421169689Skan
422169689Skan  // Remove edges from "root" to each SafePoint at a backward branch.
423169689Skan  // They were inserted during parsing (see add_safepoint()) to make infinite
424169689Skan  // loops without calls or exceptions visible to root, i.e., useful.
425169689Skan  Node *root = C->root();
426169689Skan  if( root != NULL ) {
427169689Skan    for( uint i = root->req(); i < root->len(); ++i ) {
428169689Skan      Node *n = root->in(i);
429169689Skan      if( n != NULL && n->is_SafePoint() ) {
430169689Skan        root->rm_prec(i);
431169689Skan        --i;
432169689Skan      }
433169689Skan    }
434169689Skan  }
435169689Skan}
436169689Skan
437169689Skan
438169689Skan//=============================================================================
439169689Skan//------------------------------PhaseTransform---------------------------------
440169689SkanPhaseTransform::PhaseTransform( PhaseNumber pnum ) : Phase(pnum),
441169689Skan  _arena(Thread::current()->resource_area()),
442169689Skan  _nodes(_arena),
443169689Skan  _types(_arena)
444169689Skan{
445169689Skan  init_con_caches();
446169689Skan#ifndef PRODUCT
447169689Skan  clear_progress();
448169689Skan  clear_transforms();
449169689Skan  set_allow_progress(true);
450169689Skan#endif
451169689Skan  // Force allocation for currently existing nodes
452169689Skan  _types.map(C->unique(), NULL);
453169689Skan}
454169689Skan
455169689Skan//------------------------------PhaseTransform---------------------------------
456169689SkanPhaseTransform::PhaseTransform( Arena *arena, PhaseNumber pnum ) : Phase(pnum),
457169689Skan  _arena(arena),
458169689Skan  _nodes(arena),
459169689Skan  _types(arena)
460169689Skan{
461169689Skan  init_con_caches();
462169689Skan#ifndef PRODUCT
463169689Skan  clear_progress();
464169689Skan  clear_transforms();
465169689Skan  set_allow_progress(true);
466169689Skan#endif
467169689Skan  // Force allocation for currently existing nodes
468169689Skan  _types.map(C->unique(), NULL);
469169689Skan}
470169689Skan
471169689Skan//------------------------------PhaseTransform---------------------------------
472169689Skan// Initialize with previously generated type information
473169689SkanPhaseTransform::PhaseTransform( PhaseTransform *pt, PhaseNumber pnum ) : Phase(pnum),
474169689Skan  _arena(pt->_arena),
475169689Skan  _nodes(pt->_nodes),
476169689Skan  _types(pt->_types)
477169689Skan{
478169689Skan  init_con_caches();
479169689Skan#ifndef PRODUCT
480169689Skan  clear_progress();
481169689Skan  clear_transforms();
482169689Skan  set_allow_progress(true);
483169689Skan#endif
484169689Skan}
485169689Skan
486169689Skanvoid PhaseTransform::init_con_caches() {
487169689Skan  memset(_icons,0,sizeof(_icons));
488169689Skan  memset(_lcons,0,sizeof(_lcons));
489169689Skan  memset(_zcons,0,sizeof(_zcons));
490169689Skan}
491169689Skan
492169689Skan
493169689Skan//--------------------------------find_int_type--------------------------------
494169689Skanconst TypeInt* PhaseTransform::find_int_type(Node* n) {
495169689Skan  if (n == NULL)  return NULL;
496169689Skan  // Call type_or_null(n) to determine node's type since we might be in
497169689Skan  // parse phase and call n->Value() may return wrong type.
498169689Skan  // (For example, a phi node at the beginning of loop parsing is not ready.)
499169689Skan  const Type* t = type_or_null(n);
500169689Skan  if (t == NULL)  return NULL;
501169689Skan  return t->isa_int();
502169689Skan}
503169689Skan
504169689Skan
505169689Skan//-------------------------------find_long_type--------------------------------
506169689Skanconst TypeLong* PhaseTransform::find_long_type(Node* n) {
507169689Skan  if (n == NULL)  return NULL;
508169689Skan  // (See comment above on type_or_null.)
509169689Skan  const Type* t = type_or_null(n);
510169689Skan  if (t == NULL)  return NULL;
511169689Skan  return t->isa_long();
512169689Skan}
513169689Skan
514169689Skan
515169689Skan#ifndef PRODUCT
516169689Skanvoid PhaseTransform::dump_old2new_map() const {
517169689Skan  _nodes.dump();
518169689Skan}
519169689Skan
520169689Skanvoid PhaseTransform::dump_new( uint nidx ) const {
521169689Skan  for( uint i=0; i<_nodes.Size(); i++ )
522169689Skan    if( _nodes[i] && _nodes[i]->_idx == nidx ) {
523169689Skan      _nodes[i]->dump();
524169689Skan      tty->cr();
525169689Skan      tty->print_cr("Old index= %d",i);
526169689Skan      return;
527169689Skan    }
528169689Skan  tty->print_cr("Node %d not found in the new indices", nidx);
529169689Skan}
530169689Skan
531169689Skan//------------------------------dump_types-------------------------------------
532169689Skanvoid PhaseTransform::dump_types( ) const {
533169689Skan  _types.dump();
534169689Skan}
535169689Skan
536169689Skan//------------------------------dump_nodes_and_types---------------------------
537169689Skanvoid PhaseTransform::dump_nodes_and_types(const Node *root, uint depth, bool only_ctrl) {
538169689Skan  VectorSet visited(Thread::current()->resource_area());
539169689Skan  dump_nodes_and_types_recur( root, depth, only_ctrl, visited );
540169689Skan}
541169689Skan
542169689Skan//------------------------------dump_nodes_and_types_recur---------------------
543169689Skanvoid PhaseTransform::dump_nodes_and_types_recur( const Node *n, uint depth, bool only_ctrl, VectorSet &visited) {
544169689Skan  if( !n ) return;
545169689Skan  if( depth == 0 ) return;
546169689Skan  if( visited.test_set(n->_idx) ) return;
547169689Skan  for( uint i=0; i<n->len(); i++ ) {
548169689Skan    if( only_ctrl && !(n->is_Region()) && i != TypeFunc::Control ) continue;
549169689Skan    dump_nodes_and_types_recur( n->in(i), depth-1, only_ctrl, visited );
550169689Skan  }
551169689Skan  n->dump();
552169689Skan  if (type_or_null(n) != NULL) {
553169689Skan    tty->print("      "); type(n)->dump(); tty->cr();
554169689Skan  }
555169689Skan}
556169689Skan
557169689Skan#endif
558169689Skan
559169689Skan
560169689Skan//=============================================================================
561169689Skan//------------------------------PhaseValues------------------------------------
562169689Skan// Set minimum table size to "255"
563169689SkanPhaseValues::PhaseValues( Arena *arena, uint est_max_size ) : PhaseTransform(arena, GVN), _table(arena, est_max_size) {
564169689Skan  NOT_PRODUCT( clear_new_values(); )
565169689Skan}
566169689Skan
567169689Skan//------------------------------PhaseValues------------------------------------
568169689Skan// Set minimum table size to "255"
569169689SkanPhaseValues::PhaseValues( PhaseValues *ptv ) : PhaseTransform( ptv, GVN ),
570169689Skan  _table(&ptv->_table) {
571169689Skan  NOT_PRODUCT( clear_new_values(); )
572169689Skan}
573169689Skan
574169689Skan//------------------------------PhaseValues------------------------------------
575169689Skan// Used by +VerifyOpto.  Clear out hash table but copy _types array.
576169689SkanPhaseValues::PhaseValues( PhaseValues *ptv, const char *dummy ) : PhaseTransform( ptv, GVN ),
577169689Skan  _table(ptv->arena(),ptv->_table.size()) {
578169689Skan  NOT_PRODUCT( clear_new_values(); )
579169689Skan}
580169689Skan
581169689Skan//------------------------------~PhaseValues-----------------------------------
582169689Skan#ifndef PRODUCT
583169689SkanPhaseValues::~PhaseValues() {
584169689Skan  _table.dump();
585169689Skan
586169689Skan  // Statistics for value progress and efficiency
587169689Skan  if( PrintCompilation && Verbose && WizardMode ) {
588169689Skan    tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
589169689Skan      is_IterGVN() ? "Iter" : "    ", C->unique(), made_progress(), made_transforms(), made_new_values());
590169689Skan    if( made_transforms() != 0 ) {
591169689Skan      tty->print_cr("  ratio %f", made_progress()/(float)made_transforms() );
592169689Skan    } else {
593169689Skan      tty->cr();
594169689Skan    }
595169689Skan  }
596169689Skan}
597169689Skan#endif
598169689Skan
599169689Skan//------------------------------makecon----------------------------------------
600169689SkanConNode* PhaseTransform::makecon(const Type *t) {
601169689Skan  assert(t->singleton(), "must be a constant");
602169689Skan  assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
603169689Skan  switch (t->base()) {  // fast paths
604169689Skan  case Type::Half:
605169689Skan  case Type::Top:  return (ConNode*) C->top();
606169689Skan  case Type::Int:  return intcon( t->is_int()->get_con() );
607169689Skan  case Type::Long: return longcon( t->is_long()->get_con() );
608169689Skan  }
609169689Skan  if (t->is_zero_type())
610169689Skan    return zerocon(t->basic_type());
611169689Skan  return uncached_makecon(t);
612169689Skan}
613169689Skan
614169689Skan//--------------------------uncached_makecon-----------------------------------
615169689Skan// Make an idealized constant - one of ConINode, ConPNode, etc.
616169689SkanConNode* PhaseValues::uncached_makecon(const Type *t) {
617169689Skan  assert(t->singleton(), "must be a constant");
618169689Skan  ConNode* x = ConNode::make(C, t);
619169689Skan  ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
620169689Skan  if (k == NULL) {
621169689Skan    set_type(x, t);             // Missed, provide type mapping
622169689Skan    GrowableArray<Node_Notes*>* nna = C->node_note_array();
623169689Skan    if (nna != NULL) {
624169689Skan      Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
625169689Skan      loc->clear(); // do not put debug info on constants
626169689Skan    }
627169689Skan  } else {
628169689Skan    x->destruct();              // Hit, destroy duplicate constant
629169689Skan    x = k;                      // use existing constant
630169689Skan  }
631169689Skan  return x;
632169689Skan}
633169689Skan
634169689Skan//------------------------------intcon-----------------------------------------
635169689Skan// Fast integer constant.  Same as "transform(new ConINode(TypeInt::make(i)))"
636169689SkanConINode* PhaseTransform::intcon(int i) {
637169689Skan  // Small integer?  Check cache! Check that cached node is not dead
638169689Skan  if (i >= _icon_min && i <= _icon_max) {
639169689Skan    ConINode* icon = _icons[i-_icon_min];
640169689Skan    if (icon != NULL && icon->in(TypeFunc::Control) != NULL)
641169689Skan      return icon;
642169689Skan  }
643169689Skan  ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
644169689Skan  assert(icon->is_Con(), "");
645169689Skan  if (i >= _icon_min && i <= _icon_max)
646169689Skan    _icons[i-_icon_min] = icon;   // Cache small integers
647169689Skan  return icon;
648169689Skan}
649169689Skan
650169689Skan//------------------------------longcon----------------------------------------
651169689Skan// Fast long constant.
652169689SkanConLNode* PhaseTransform::longcon(jlong l) {
653169689Skan  // Small integer?  Check cache! Check that cached node is not dead
654169689Skan  if (l >= _lcon_min && l <= _lcon_max) {
655169689Skan    ConLNode* lcon = _lcons[l-_lcon_min];
656169689Skan    if (lcon != NULL && lcon->in(TypeFunc::Control) != NULL)
657169689Skan      return lcon;
658169689Skan  }
659169689Skan  ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
660169689Skan  assert(lcon->is_Con(), "");
661169689Skan  if (l >= _lcon_min && l <= _lcon_max)
662169689Skan    _lcons[l-_lcon_min] = lcon;      // Cache small integers
663169689Skan  return lcon;
664169689Skan}
665169689Skan
666169689Skan//------------------------------zerocon-----------------------------------------
667169689Skan// Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
668169689SkanConNode* PhaseTransform::zerocon(BasicType bt) {
669169689Skan  assert((uint)bt <= _zcon_max, "domain check");
670169689Skan  ConNode* zcon = _zcons[bt];
671169689Skan  if (zcon != NULL && zcon->in(TypeFunc::Control) != NULL)
672169689Skan    return zcon;
673169689Skan  zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
674169689Skan  _zcons[bt] = zcon;
675169689Skan  return zcon;
676169689Skan}
677169689Skan
678169689Skan
679169689Skan
680169689Skan//=============================================================================
681169689Skan//------------------------------transform--------------------------------------
682169689Skan// Return a node which computes the same function as this node, but in a
683169689Skan// faster or cheaper fashion.
684169689SkanNode *PhaseGVN::transform( Node *n ) {
685169689Skan  return transform_no_reclaim(n);
686169689Skan}
687169689Skan
688169689Skan//------------------------------transform--------------------------------------
689169689Skan// Return a node which computes the same function as this node, but
690169689Skan// in a faster or cheaper fashion.
691169689SkanNode *PhaseGVN::transform_no_reclaim( Node *n ) {
692169689Skan  NOT_PRODUCT( set_transforms(); )
693169689Skan
694169689Skan  // Apply the Ideal call in a loop until it no longer applies
695169689Skan  Node *k = n;
696169689Skan  NOT_PRODUCT( uint loop_count = 0; )
697169689Skan  while( 1 ) {
698169689Skan    Node *i = k->Ideal(this, /*can_reshape=*/false);
699169689Skan    if( !i ) break;
700169689Skan    assert( i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
701169689Skan    k = i;
702169689Skan    assert(loop_count++ < K, "infinite loop in PhaseGVN::transform");
703169689Skan  }
704169689Skan  NOT_PRODUCT( if( loop_count != 0 ) { set_progress(); } )
705169689Skan
706169689Skan
707169689Skan  // If brand new node, make space in type array.
708169689Skan  ensure_type_or_null(k);
709169689Skan
710169689Skan  // Since I just called 'Value' to compute the set of run-time values
711169689Skan  // for this Node, and 'Value' is non-local (and therefore expensive) I'll
712169689Skan  // cache Value.  Later requests for the local phase->type of this Node can
713169689Skan  // use the cached Value instead of suffering with 'bottom_type'.
714169689Skan  const Type *t = k->Value(this); // Get runtime Value set
715169689Skan  assert(t != NULL, "value sanity");
716169689Skan  if (type_or_null(k) != t) {
717169689Skan#ifndef PRODUCT
718169689Skan    // Do not count initial visit to node as a transformation
719169689Skan    if (type_or_null(k) == NULL) {
720169689Skan      inc_new_values();
721169689Skan      set_progress();
722169689Skan    }
723169689Skan#endif
724169689Skan    set_type(k, t);
725169689Skan    // If k is a TypeNode, capture any more-precise type permanently into Node
726169689Skan    k->raise_bottom_type(t);
727169689Skan  }
728169689Skan
729169689Skan  if( t->singleton() && !k->is_Con() ) {
730169689Skan    NOT_PRODUCT( set_progress(); )
731169689Skan    return makecon(t);          // Turn into a constant
732169689Skan  }
733169689Skan
734169689Skan  // Now check for Identities
735169689Skan  Node *i = k->Identity(this);  // Look for a nearby replacement
736169689Skan  if( i != k ) {                // Found? Return replacement!
737169689Skan    NOT_PRODUCT( set_progress(); )
738169689Skan    return i;
739169689Skan  }
740169689Skan
741169689Skan  // Global Value Numbering
742169689Skan  i = hash_find_insert(k);      // Insert if new
743169689Skan  if( i && (i != k) ) {
744169689Skan    // Return the pre-existing node
745169689Skan    NOT_PRODUCT( set_progress(); )
746169689Skan    return i;
747169689Skan  }
748169689Skan
749169689Skan  // Return Idealized original
750169689Skan  return k;
751169689Skan}
752169689Skan
753169689Skan#ifdef ASSERT
754169689Skan//------------------------------dead_loop_check--------------------------------
755169689Skan// Check for a simple dead loop when a data node references itself directly
756169689Skan// or through an other data node excluding cons and phis.
757169689Skanvoid PhaseGVN::dead_loop_check( Node *n ) {
758169689Skan  // Phi may reference itself in a loop
759169689Skan  if (n != NULL && !n->is_dead_loop_safe() && !n->is_CFG()) {
760169689Skan    // Do 2 levels check and only data inputs.
761169689Skan    bool no_dead_loop = true;
762169689Skan    uint cnt = n->req();
763169689Skan    for (uint i = 1; i < cnt && no_dead_loop; i++) {
764169689Skan      Node *in = n->in(i);
765169689Skan      if (in == n) {
766169689Skan        no_dead_loop = false;
767169689Skan      } else if (in != NULL && !in->is_dead_loop_safe()) {
768169689Skan        uint icnt = in->req();
769169689Skan        for (uint j = 1; j < icnt && no_dead_loop; j++) {
770169689Skan          if (in->in(j) == n || in->in(j) == in)
771169689Skan            no_dead_loop = false;
772169689Skan        }
773169689Skan      }
774169689Skan    }
775169689Skan    if (!no_dead_loop) n->dump(3);
776169689Skan    assert(no_dead_loop, "dead loop detected");
777169689Skan  }
778169689Skan}
779169689Skan#endif
780169689Skan
781169689Skan//=============================================================================
782169689Skan//------------------------------PhaseIterGVN-----------------------------------
783169689Skan// Initialize hash table to fresh and clean for +VerifyOpto
784169689SkanPhaseIterGVN::PhaseIterGVN( PhaseIterGVN *igvn, const char *dummy ) : PhaseGVN(igvn,dummy), _worklist( ),
785169689Skan                                                                      _stack(C->unique() >> 1),
786169689Skan                                                                      _delay_transform(false) {
787169689Skan}
788169689Skan
789169689Skan//------------------------------PhaseIterGVN-----------------------------------
790169689Skan// Initialize with previous PhaseIterGVN info; used by PhaseCCP
791169689SkanPhaseIterGVN::PhaseIterGVN( PhaseIterGVN *igvn ) : PhaseGVN(igvn),
792169689Skan                                                   _worklist( igvn->_worklist ),
793169689Skan                                                   _stack( igvn->_stack ),
794169689Skan                                                   _delay_transform(igvn->_delay_transform)
795169689Skan{
796169689Skan}
797169689Skan
798169689Skan//------------------------------PhaseIterGVN-----------------------------------
799169689Skan// Initialize with previous PhaseGVN info from Parser
800169689SkanPhaseIterGVN::PhaseIterGVN( PhaseGVN *gvn ) : PhaseGVN(gvn),
801169689Skan                                              _worklist(*C->for_igvn()),
802169689Skan                                              _stack(C->unique() >> 1),
803169689Skan                                              _delay_transform(false)
804169689Skan{
805169689Skan  uint max;
806169689Skan
807169689Skan  // Dead nodes in the hash table inherited from GVN were not treated as
808169689Skan  // roots during def-use info creation; hence they represent an invisible
809169689Skan  // use.  Clear them out.
810169689Skan  max = _table.size();
811169689Skan  for( uint i = 0; i < max; ++i ) {
812169689Skan    Node *n = _table.at(i);
813169689Skan    if(n != NULL && n != _table.sentinel() && n->outcnt() == 0) {
814169689Skan      if( n->is_top() ) continue;
815169689Skan      assert( false, "Parse::remove_useless_nodes missed this node");
816169689Skan      hash_delete(n);
817169689Skan    }
818169689Skan  }
819169689Skan
820169689Skan  // Any Phis or Regions on the worklist probably had uses that could not
821169689Skan  // make more progress because the uses were made while the Phis and Regions
822169689Skan  // were in half-built states.  Put all uses of Phis and Regions on worklist.
823169689Skan  max = _worklist.size();
824169689Skan  for( uint j = 0; j < max; j++ ) {
825169689Skan    Node *n = _worklist.at(j);
826169689Skan    uint uop = n->Opcode();
827169689Skan    if( uop == Op_Phi || uop == Op_Region ||
828169689Skan        n->is_Type() ||
829169689Skan        n->is_Mem() )
830169689Skan      add_users_to_worklist(n);
831169689Skan  }
832169689Skan}
833169689Skan
834169689Skan/**
835169689Skan * Initialize worklist for each node.
836169689Skan */
837169689Skanvoid PhaseIterGVN::init_worklist(Node* first) {
838169689Skan  Unique_Node_List to_process;
839169689Skan  to_process.push(first);
840169689Skan
841169689Skan  while (to_process.size() > 0) {
842169689Skan    Node* n = to_process.pop();
843169689Skan    if (!_worklist.member(n)) {
844169689Skan      _worklist.push(n);
845169689Skan
846169689Skan      uint cnt = n->req();
847169689Skan      for(uint i = 0; i < cnt; i++) {
848169689Skan        Node* m = n->in(i);
849169689Skan        if (m != NULL) {
850169689Skan          to_process.push(m);
851169689Skan        }
852169689Skan      }
853169689Skan    }
854169689Skan  }
855169689Skan}
856169689Skan
857169689Skan#ifndef PRODUCT
858169689Skanvoid PhaseIterGVN::verify_step(Node* n) {
859169689Skan  if (VerifyIterativeGVN) {
860169689Skan    _verify_window[_verify_counter % _verify_window_size] = n;
861169689Skan    ++_verify_counter;
862169689Skan    ResourceMark rm;
863169689Skan    ResourceArea* area = Thread::current()->resource_area();
864169689Skan    VectorSet old_space(area), new_space(area);
865169689Skan    if (C->unique() < 1000 ||
866169689Skan        0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
867169689Skan      ++_verify_full_passes;
868169689Skan      Node::verify_recur(C->root(), -1, old_space, new_space);
869169689Skan    }
870169689Skan    const int verify_depth = 4;
871169689Skan    for ( int i = 0; i < _verify_window_size; i++ ) {
872169689Skan      Node* n = _verify_window[i];
873169689Skan      if ( n == NULL )  continue;
874169689Skan      if( n->in(0) == NodeSentinel ) {  // xform_idom
875169689Skan        _verify_window[i] = n->in(1);
876169689Skan        --i; continue;
877169689Skan      }
878169689Skan      // Typical fanout is 1-2, so this call visits about 6 nodes.
879169689Skan      Node::verify_recur(n, verify_depth, old_space, new_space);
880169689Skan    }
881169689Skan  }
882169689Skan}
883169689Skan
884169689Skanvoid PhaseIterGVN::trace_PhaseIterGVN(Node* n, Node* nn, const Type* oldtype) {
885169689Skan  if (TraceIterativeGVN) {
886169689Skan    uint wlsize = _worklist.size();
887169689Skan    const Type* newtype = type_or_null(n);
888169689Skan    if (nn != n) {
889169689Skan      // print old node
890169689Skan      tty->print("< ");
891169689Skan      if (oldtype != newtype && oldtype != NULL) {
892169689Skan        oldtype->dump();
893169689Skan      }
894169689Skan      do { tty->print("\t"); } while (tty->position() < 16);
895169689Skan      tty->print("<");
896169689Skan      n->dump();
897169689Skan    }
898169689Skan    if (oldtype != newtype || nn != n) {
899169689Skan      // print new node and/or new type
900169689Skan      if (oldtype == NULL) {
901169689Skan        tty->print("* ");
902169689Skan      } else if (nn != n) {
903169689Skan        tty->print("> ");
904169689Skan      } else {
905169689Skan        tty->print("= ");
906169689Skan      }
907169689Skan      if (newtype == NULL) {
908169689Skan        tty->print("null");
909169689Skan      } else {
910169689Skan        newtype->dump();
911169689Skan      }
912169689Skan      do { tty->print("\t"); } while (tty->position() < 16);
913169689Skan      nn->dump();
914169689Skan    }
915169689Skan    if (Verbose && wlsize < _worklist.size()) {
916169689Skan      tty->print("  Push {");
917169689Skan      while (wlsize != _worklist.size()) {
918169689Skan        Node* pushed = _worklist.at(wlsize++);
919169689Skan        tty->print(" %d", pushed->_idx);
920169689Skan      }
921169689Skan      tty->print_cr(" }");
922169689Skan    }
923169689Skan    if (nn != n) {
924169689Skan      // ignore n, it might be subsumed
925169689Skan      verify_step((Node*) NULL);
926169689Skan    }
927169689Skan  }
928169689Skan}
929169689Skan
930169689Skanvoid PhaseIterGVN::init_verifyPhaseIterGVN() {
931169689Skan  _verify_counter = 0;
932169689Skan  _verify_full_passes = 0;
933169689Skan  for (int i = 0; i < _verify_window_size; i++) {
934169689Skan    _verify_window[i] = NULL;
935169689Skan  }
936169689Skan}
937169689Skan
938169689Skanvoid PhaseIterGVN::verify_PhaseIterGVN() {
939169689Skan  C->verify_graph_edges();
940169689Skan  if( VerifyOpto && allow_progress() ) {
941169689Skan    // Must turn off allow_progress to enable assert and break recursion
942169689Skan    C->root()->verify();
943169689Skan    { // Check if any progress was missed using IterGVN
944169689Skan      // Def-Use info enables transformations not attempted in wash-pass
945169689Skan      // e.g. Region/Phi cleanup, ...
946169689Skan      // Null-check elision -- may not have reached fixpoint
947169689Skan      //                       do not propagate to dominated nodes
948169689Skan      ResourceMark rm;
949169689Skan      PhaseIterGVN igvn2(this,"Verify"); // Fresh and clean!
950169689Skan      // Fill worklist completely
951169689Skan      igvn2.init_worklist(C->root());
952169689Skan
953169689Skan      igvn2.set_allow_progress(false);
954169689Skan      igvn2.optimize();
955169689Skan      igvn2.set_allow_progress(true);
956169689Skan    }
957169689Skan  }
958169689Skan  if (VerifyIterativeGVN && PrintOpto) {
959169689Skan    if (_verify_counter == _verify_full_passes) {
960169689Skan      tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
961169689Skan                    (int) _verify_full_passes);
962169689Skan    } else {
963169689Skan      tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
964169689Skan                  (int) _verify_counter, (int) _verify_full_passes);
965169689Skan    }
966169689Skan  }
967169689Skan}
968169689Skan#endif /* PRODUCT */
969169689Skan
970169689Skan#ifdef ASSERT
971169689Skan/**
972169689Skan * Dumps information that can help to debug the problem. A debug
973169689Skan * build fails with an assert.
974169689Skan */
975169689Skanvoid PhaseIterGVN::dump_infinite_loop_info(Node* n) {
976169689Skan  n->dump(4);
977169689Skan  _worklist.dump();
978169689Skan  assert(false, "infinite loop in PhaseIterGVN::optimize");
979169689Skan}
980169689Skan
981169689Skan/**
982169689Skan * Prints out information about IGVN if the 'verbose' option is used.
983169689Skan */
984169689Skanvoid PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
985169689Skan  if (TraceIterativeGVN && Verbose) {
986169689Skan    tty->print("  Pop ");
987169689Skan    n->dump();
988169689Skan    if ((num_processed % 100) == 0) {
989169689Skan      _worklist.print_set();
990169689Skan    }
991169689Skan  }
992169689Skan}
993169689Skan#endif /* ASSERT */
994169689Skan
995169689Skanvoid PhaseIterGVN::optimize() {
996169689Skan  DEBUG_ONLY(uint num_processed  = 0;)
997169689Skan  NOT_PRODUCT(init_verifyPhaseIterGVN();)
998169689Skan
999169689Skan  uint loop_count = 0;
1000169689Skan  // Pull from worklist and transform the node. If the node has changed,
1001169689Skan  // update edge info and put uses on worklist.
1002169689Skan  while(_worklist.size()) {
1003169689Skan    if (C->check_node_count(NodeLimitFudgeFactor * 2, "Out of nodes")) {
1004169689Skan      return;
1005169689Skan    }
1006169689Skan    Node* n  = _worklist.pop();
1007169689Skan    if (++loop_count >= K * C->live_nodes()) {
1008169689Skan      DEBUG_ONLY(dump_infinite_loop_info(n);)
1009169689Skan      C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1010169689Skan      return;
1011169689Skan    }
1012169689Skan    DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1013169689Skan    if (n->outcnt() != 0) {
1014169689Skan      NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1015169689Skan      // Do the transformation
1016169689Skan      Node* nn = transform_old(n);
1017169689Skan      NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1018169689Skan    } else if (!n->is_top()) {
1019169689Skan      remove_dead_node(n);
1020169689Skan    }
1021169689Skan  }
1022169689Skan  NOT_PRODUCT(verify_PhaseIterGVN();)
1023169689Skan}
1024169689Skan
1025169689Skan
1026169689Skan/**
1027169689Skan * Register a new node with the optimizer.  Update the types array, the def-use
1028169689Skan * info.  Put on worklist.
1029169689Skan */
1030169689SkanNode* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
1031169689Skan  set_type_bottom(n);
1032169689Skan  _worklist.push(n);
1033169689Skan  if (orig != NULL)  C->copy_node_notes_to(n, orig);
1034169689Skan  return n;
1035169689Skan}
1036169689Skan
1037169689Skan//------------------------------transform--------------------------------------
1038169689Skan// Non-recursive: idealize Node 'n' with respect to its inputs and its value
1039169689SkanNode *PhaseIterGVN::transform( Node *n ) {
1040169689Skan  if (_delay_transform) {
1041169689Skan    // Register the node but don't optimize for now
1042169689Skan    register_new_node_with_optimizer(n);
1043169689Skan    return n;
1044169689Skan  }
1045169689Skan
1046169689Skan  // If brand new node, make space in type array, and give it a type.
1047169689Skan  ensure_type_or_null(n);
1048169689Skan  if (type_or_null(n) == NULL) {
1049169689Skan    set_type_bottom(n);
1050169689Skan  }
1051169689Skan
1052169689Skan  return transform_old(n);
1053169689Skan}
1054169689Skan
1055169689SkanNode *PhaseIterGVN::transform_old(Node* n) {
1056169689Skan  DEBUG_ONLY(uint loop_count = 0;);
1057169689Skan  NOT_PRODUCT(set_transforms());
1058169689Skan
1059169689Skan  // Remove 'n' from hash table in case it gets modified
1060169689Skan  _table.hash_delete(n);
1061169689Skan  if (VerifyIterativeGVN) {
1062169689Skan   assert(!_table.find_index(n->_idx), "found duplicate entry in table");
1063169689Skan  }
1064169689Skan
1065169689Skan  // Apply the Ideal call in a loop until it no longer applies
1066169689Skan  Node* k = n;
1067169689Skan  DEBUG_ONLY(dead_loop_check(k);)
1068169689Skan  DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1069169689Skan  Node* i = k->Ideal(this, /*can_reshape=*/true);
1070169689Skan  assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1071169689Skan#ifndef PRODUCT
1072169689Skan  verify_step(k);
1073169689Skan  if (i && VerifyOpto ) {
1074169689Skan    if (!allow_progress()) {
1075169689Skan      if (i->is_Add() && (i->outcnt() == 1)) {
1076169689Skan        // Switched input to left side because this is the only use
1077169689Skan      } else if (i->is_If() && (i->in(0) == NULL)) {
1078169689Skan        // This IF is dead because it is dominated by an equivalent IF When
1079169689Skan        // dominating if changed, info is not propagated sparsely to 'this'
1080169689Skan        // Propagating this info further will spuriously identify other
1081169689Skan        // progress.
1082169689Skan        return i;
1083169689Skan      } else
1084169689Skan        set_progress();
1085169689Skan    } else {
1086169689Skan      set_progress();
1087169689Skan    }
1088169689Skan  }
1089169689Skan#endif
1090169689Skan
1091169689Skan  while (i != NULL) {
1092169689Skan#ifndef PRODUCT
1093169689Skan    if (loop_count >= K) {
1094169689Skan      dump_infinite_loop_info(i);
1095169689Skan    }
1096169689Skan    loop_count++;
1097169689Skan#endif
1098169689Skan    assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1099169689Skan    // Made a change; put users of original Node on worklist
1100169689Skan    add_users_to_worklist(k);
1101169689Skan    // Replacing root of transform tree?
1102169689Skan    if (k != i) {
1103169689Skan      // Make users of old Node now use new.
1104169689Skan      subsume_node(k, i);
1105169689Skan      k = i;
1106169689Skan    }
1107169689Skan    DEBUG_ONLY(dead_loop_check(k);)
1108169689Skan    // Try idealizing again
1109169689Skan    DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1110169689Skan    i = k->Ideal(this, /*can_reshape=*/true);
1111169689Skan    assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
1112169689Skan#ifndef PRODUCT
1113169689Skan    verify_step(k);
1114169689Skan    if (i && VerifyOpto) {
1115169689Skan      set_progress();
1116169689Skan    }
1117169689Skan#endif
1118169689Skan  }
1119169689Skan
1120169689Skan  // If brand new node, make space in type array.
1121169689Skan  ensure_type_or_null(k);
1122169689Skan
1123169689Skan  // See what kind of values 'k' takes on at runtime
1124169689Skan  const Type* t = k->Value(this);
1125169689Skan  assert(t != NULL, "value sanity");
1126169689Skan
1127169689Skan  // Since I just called 'Value' to compute the set of run-time values
1128169689Skan  // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1129169689Skan  // cache Value.  Later requests for the local phase->type of this Node can
1130169689Skan  // use the cached Value instead of suffering with 'bottom_type'.
1131169689Skan  if (type_or_null(k) != t) {
1132169689Skan#ifndef PRODUCT
1133169689Skan    inc_new_values();
1134169689Skan    set_progress();
1135169689Skan#endif
1136169689Skan    set_type(k, t);
1137169689Skan    // If k is a TypeNode, capture any more-precise type permanently into Node
1138169689Skan    k->raise_bottom_type(t);
1139169689Skan    // Move users of node to worklist
1140169689Skan    add_users_to_worklist(k);
1141169689Skan  }
1142169689Skan  // If 'k' computes a constant, replace it with a constant
1143169689Skan  if (t->singleton() && !k->is_Con()) {
1144169689Skan    NOT_PRODUCT(set_progress();)
1145169689Skan    Node* con = makecon(t);     // Make a constant
1146169689Skan    add_users_to_worklist(k);
1147169689Skan    subsume_node(k, con);       // Everybody using k now uses con
1148169689Skan    return con;
1149169689Skan  }
1150169689Skan
1151169689Skan  // Now check for Identities
1152169689Skan  i = k->Identity(this);      // Look for a nearby replacement
1153169689Skan  if (i != k) {                // Found? Return replacement!
1154169689Skan    NOT_PRODUCT(set_progress();)
1155169689Skan    add_users_to_worklist(k);
1156169689Skan    subsume_node(k, i);       // Everybody using k now uses i
1157169689Skan    return i;
1158169689Skan  }
1159169689Skan
1160169689Skan  // Global Value Numbering
1161169689Skan  i = hash_find_insert(k);      // Check for pre-existing node
1162169689Skan  if (i && (i != k)) {
1163169689Skan    // Return the pre-existing node if it isn't dead
1164169689Skan    NOT_PRODUCT(set_progress();)
1165169689Skan    add_users_to_worklist(k);
1166169689Skan    subsume_node(k, i);       // Everybody using k now uses i
1167169689Skan    return i;
1168169689Skan  }
1169169689Skan
1170169689Skan  // Return Idealized original
1171169689Skan  return k;
1172169689Skan}
1173169689Skan
1174169689Skan//---------------------------------saturate------------------------------------
1175169689Skanconst Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1176169689Skan                                   const Type* limit_type) const {
1177169689Skan  return new_type->narrow(old_type);
1178169689Skan}
1179169689Skan
1180169689Skan//------------------------------remove_globally_dead_node----------------------
1181169689Skan// Kill a globally dead Node.  All uses are also globally dead and are
1182169689Skan// aggressively trimmed.
1183169689Skanvoid PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1184169689Skan  enum DeleteProgress {
1185169689Skan    PROCESS_INPUTS,
1186169689Skan    PROCESS_OUTPUTS
1187169689Skan  };
1188169689Skan  assert(_stack.is_empty(), "not empty");
1189169689Skan  _stack.push(dead, PROCESS_INPUTS);
1190169689Skan
1191169689Skan  while (_stack.is_nonempty()) {
1192169689Skan    dead = _stack.node();
1193169689Skan    uint progress_state = _stack.index();
1194169689Skan    assert(dead != C->root(), "killing root, eh?");
1195169689Skan    assert(!dead->is_top(), "add check for top when pushing");
1196169689Skan    NOT_PRODUCT( set_progress(); )
1197169689Skan    if (progress_state == PROCESS_INPUTS) {
1198169689Skan      // After following inputs, continue to outputs
1199169689Skan      _stack.set_index(PROCESS_OUTPUTS);
1200169689Skan      if (!dead->is_Con()) { // Don't kill cons but uses
1201169689Skan        bool recurse = false;
1202169689Skan        // Remove from hash table
1203169689Skan        _table.hash_delete( dead );
1204169689Skan        // Smash all inputs to 'dead', isolating him completely
1205169689Skan        for (uint i = 0; i < dead->req(); i++) {
1206169689Skan          Node *in = dead->in(i);
1207169689Skan          if (in != NULL && in != C->top()) {  // Points to something?
1208169689Skan            int nrep = dead->replace_edge(in, NULL);  // Kill edges
1209169689Skan            assert((nrep > 0), "sanity");
1210169689Skan            if (in->outcnt() == 0) { // Made input go dead?
1211169689Skan              _stack.push(in, PROCESS_INPUTS); // Recursively remove
1212169689Skan              recurse = true;
1213169689Skan            } else if (in->outcnt() == 1 &&
1214169689Skan                       in->has_special_unique_user()) {
1215169689Skan              _worklist.push(in->unique_out());
1216169689Skan            } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1217169689Skan              if (in->Opcode() == Op_Region) {
1218169689Skan                _worklist.push(in);
1219169689Skan              } else if (in->is_Store()) {
1220169689Skan                DUIterator_Fast imax, i = in->fast_outs(imax);
1221169689Skan                _worklist.push(in->fast_out(i));
1222169689Skan                i++;
1223169689Skan                if (in->outcnt() == 2) {
1224169689Skan                  _worklist.push(in->fast_out(i));
1225169689Skan                  i++;
1226169689Skan                }
1227169689Skan                assert(!(i < imax), "sanity");
1228169689Skan              }
1229169689Skan            }
1230169689Skan            if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1231169689Skan                in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1232169689Skan              // A Load that directly follows an InitializeNode is
1233169689Skan              // going away. The Stores that follow are candidates
1234169689Skan              // again to be captured by the InitializeNode.
1235169689Skan              for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1236169689Skan                Node *n = in->fast_out(j);
1237169689Skan                if (n->is_Store()) {
1238169689Skan                  _worklist.push(n);
1239169689Skan                }
1240169689Skan              }
1241169689Skan            }
1242169689Skan          } // if (in != NULL && in != C->top())
1243169689Skan        } // for (uint i = 0; i < dead->req(); i++)
1244169689Skan        if (recurse) {
1245169689Skan          continue;
1246169689Skan        }
1247169689Skan      } // if (!dead->is_Con())
1248169689Skan    } // if (progress_state == PROCESS_INPUTS)
1249169689Skan
1250169689Skan    // Aggressively kill globally dead uses
1251169689Skan    // (Rather than pushing all the outs at once, we push one at a time,
1252169689Skan    // plus the parent to resume later, because of the indefinite number
1253169689Skan    // of edge deletions per loop trip.)
1254169689Skan    if (dead->outcnt() > 0) {
1255169689Skan      // Recursively remove output edges
1256169689Skan      _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1257169689Skan    } else {
1258169689Skan      // Finished disconnecting all input and output edges.
1259169689Skan      _stack.pop();
1260169689Skan      // Remove dead node from iterative worklist
1261169689Skan      _worklist.remove(dead);
1262169689Skan      // Constant node that has no out-edges and has only one in-edge from
1263169689Skan      // root is usually dead. However, sometimes reshaping walk makes
1264169689Skan      // it reachable by adding use edges. So, we will NOT count Con nodes
1265169689Skan      // as dead to be conservative about the dead node count at any
1266169689Skan      // given time.
1267169689Skan      if (!dead->is_Con()) {
1268169689Skan        C->record_dead_node(dead->_idx);
1269169689Skan      }
1270169689Skan      if (dead->is_macro()) {
1271169689Skan        C->remove_macro_node(dead);
1272169689Skan      }
1273169689Skan      if (dead->is_expensive()) {
1274169689Skan        C->remove_expensive_node(dead);
1275169689Skan      }
1276169689Skan    }
1277169689Skan  } // while (_stack.is_nonempty())
1278169689Skan}
1279169689Skan
1280169689Skan//------------------------------subsume_node-----------------------------------
1281169689Skan// Remove users from node 'old' and add them to node 'nn'.
1282169689Skanvoid PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1283169689Skan  assert( old != hash_find(old), "should already been removed" );
1284169689Skan  assert( old != C->top(), "cannot subsume top node");
1285169689Skan  // Copy debug or profile information to the new version:
1286169689Skan  C->copy_node_notes_to(nn, old);
1287169689Skan  // Move users of node 'old' to node 'nn'
1288169689Skan  for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1289169689Skan    Node* use = old->last_out(i);  // for each use...
1290169689Skan    // use might need re-hashing (but it won't if it's a new node)
1291169689Skan    bool is_in_table = _table.hash_delete( use );
1292169689Skan    // Update use-def info as well
1293169689Skan    // We remove all occurrences of old within use->in,
1294169689Skan    // so as to avoid rehashing any node more than once.
1295169689Skan    // The hash table probe swamps any outer loop overhead.
1296169689Skan    uint num_edges = 0;
1297169689Skan    for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1298169689Skan      if (use->in(j) == old) {
1299169689Skan        use->set_req(j, nn);
1300169689Skan        ++num_edges;
1301169689Skan      }
1302169689Skan    }
1303169689Skan    // Insert into GVN hash table if unique
1304169689Skan    // If a duplicate, 'use' will be cleaned up when pulled off worklist
1305169689Skan    if( is_in_table ) {
1306169689Skan      hash_find_insert(use);
1307169689Skan    }
1308169689Skan    i -= num_edges;    // we deleted 1 or more copies of this edge
1309169689Skan  }
1310169689Skan
1311169689Skan  // Smash all inputs to 'old', isolating him completely
1312169689Skan  Node *temp = new (C) Node(1);
1313169689Skan  temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
1314169689Skan  remove_dead_node( old );
1315169689Skan  temp->del_req(0);         // Yank bogus edge
1316169689Skan#ifndef PRODUCT
1317169689Skan  if( VerifyIterativeGVN ) {
1318169689Skan    for ( int i = 0; i < _verify_window_size; i++ ) {
1319169689Skan      if ( _verify_window[i] == old )
1320169689Skan        _verify_window[i] = nn;
1321169689Skan    }
1322169689Skan  }
1323169689Skan#endif
1324169689Skan  _worklist.remove(temp);   // this can be necessary
1325169689Skan  temp->destruct();         // reuse the _idx of this little guy
1326169689Skan}
1327169689Skan
1328169689Skan//------------------------------add_users_to_worklist--------------------------
1329169689Skanvoid PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1330169689Skan  for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1331169689Skan    _worklist.push(n->fast_out(i));  // Push on worklist
1332169689Skan  }
1333169689Skan}
1334169689Skan
1335169689Skanvoid PhaseIterGVN::add_users_to_worklist( Node *n ) {
1336169689Skan  add_users_to_worklist0(n);
1337169689Skan
1338169689Skan  // Move users of node to worklist
1339169689Skan  for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1340169689Skan    Node* use = n->fast_out(i); // Get use
1341169689Skan
1342169689Skan    if( use->is_Multi() ||      // Multi-definer?  Push projs on worklist
1343169689Skan        use->is_Store() )       // Enable store/load same address
1344169689Skan      add_users_to_worklist0(use);
1345169689Skan
1346169689Skan    // If we changed the receiver type to a call, we need to revisit
1347169689Skan    // the Catch following the call.  It's looking for a non-NULL
1348169689Skan    // receiver to know when to enable the regular fall-through path
1349169689Skan    // in addition to the NullPtrException path.
1350169689Skan    if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1351169689Skan      Node* p = use->as_CallDynamicJava()->proj_out(TypeFunc::Control);
1352169689Skan      if (p != NULL) {
1353169689Skan        add_users_to_worklist0(p);
1354169689Skan      }
1355169689Skan    }
1356169689Skan
1357169689Skan    if( use->is_Cmp() ) {       // Enable CMP/BOOL optimization
1358169689Skan      add_users_to_worklist(use); // Put Bool on worklist
1359169689Skan      // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1360169689Skan      // phi merging either 0 or 1 onto the worklist
1361169689Skan      if (use->outcnt() > 0) {
1362169689Skan        Node* bol = use->raw_out(0);
1363169689Skan        if (bol->outcnt() > 0) {
1364169689Skan          Node* iff = bol->raw_out(0);
1365169689Skan          if (iff->outcnt() == 2) {
1366169689Skan            Node* ifproj0 = iff->raw_out(0);
1367169689Skan            Node* ifproj1 = iff->raw_out(1);
1368169689Skan            if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1369169689Skan              Node* region0 = ifproj0->raw_out(0);
1370169689Skan              Node* region1 = ifproj1->raw_out(0);
1371169689Skan              if( region0 == region1 )
1372169689Skan                add_users_to_worklist0(region0);
1373169689Skan            }
1374169689Skan          }
1375169689Skan        }
1376169689Skan      }
1377169689Skan    }
1378169689Skan
1379169689Skan    uint use_op = use->Opcode();
1380169689Skan    // If changed Cast input, check Phi users for simple cycles
1381169689Skan    if( use->is_ConstraintCast() || use->is_CheckCastPP() ) {
1382169689Skan      for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1383169689Skan        Node* u = use->fast_out(i2);
1384169689Skan        if (u->is_Phi())
1385169689Skan          _worklist.push(u);
1386169689Skan      }
1387169689Skan    }
1388169689Skan    // If changed LShift inputs, check RShift users for useless sign-ext
1389169689Skan    if( use_op == Op_LShiftI ) {
1390169689Skan      for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1391169689Skan        Node* u = use->fast_out(i2);
1392169689Skan        if (u->Opcode() == Op_RShiftI)
1393169689Skan          _worklist.push(u);
1394169689Skan      }
1395169689Skan    }
1396169689Skan    // If changed AddP inputs, check Stores for loop invariant
1397169689Skan    if( use_op == Op_AddP ) {
1398169689Skan      for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1399169689Skan        Node* u = use->fast_out(i2);
1400169689Skan        if (u->is_Mem())
1401169689Skan          _worklist.push(u);
1402169689Skan      }
1403169689Skan    }
1404169689Skan    // If changed initialization activity, check dependent Stores
1405169689Skan    if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1406169689Skan      InitializeNode* init = use->as_Allocate()->initialization();
1407169689Skan      if (init != NULL) {
1408169689Skan        Node* imem = init->proj_out(TypeFunc::Memory);
1409169689Skan        if (imem != NULL)  add_users_to_worklist0(imem);
1410169689Skan      }
1411169689Skan    }
1412169689Skan    if (use_op == Op_Initialize) {
1413169689Skan      Node* imem = use->as_Initialize()->proj_out(TypeFunc::Memory);
1414169689Skan      if (imem != NULL)  add_users_to_worklist0(imem);
1415169689Skan    }
1416169689Skan  }
1417169689Skan}
1418169689Skan
1419169689Skan/**
1420169689Skan * Remove the speculative part of all types that we know of
1421169689Skan */
1422169689Skanvoid PhaseIterGVN::remove_speculative_types()  {
1423169689Skan  assert(UseTypeSpeculation, "speculation is off");
1424169689Skan  for (uint i = 0; i < _types.Size(); i++)  {
1425169689Skan    const Type* t = _types.fast_lookup(i);
1426169689Skan    if (t != NULL) {
1427169689Skan      _types.map(i, t->remove_speculative());
1428169689Skan    }
1429169689Skan  }
1430169689Skan  _table.check_no_speculative_types();
1431169689Skan}
1432169689Skan
1433169689Skan//=============================================================================
1434169689Skan#ifndef PRODUCT
1435169689Skanuint PhaseCCP::_total_invokes   = 0;
1436169689Skanuint PhaseCCP::_total_constants = 0;
1437169689Skan#endif
1438169689Skan//------------------------------PhaseCCP---------------------------------------
1439169689Skan// Conditional Constant Propagation, ala Wegman & Zadeck
1440169689SkanPhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
1441169689Skan  NOT_PRODUCT( clear_constants(); )
1442169689Skan  assert( _worklist.size() == 0, "" );
1443169689Skan  // Clear out _nodes from IterGVN.  Must be clear to transform call.
1444169689Skan  _nodes.clear();               // Clear out from IterGVN
1445169689Skan  analyze();
1446169689Skan}
1447169689Skan
1448169689Skan#ifndef PRODUCT
1449169689Skan//------------------------------~PhaseCCP--------------------------------------
1450169689SkanPhaseCCP::~PhaseCCP() {
1451169689Skan  inc_invokes();
1452169689Skan  _total_constants += count_constants();
1453169689Skan}
1454169689Skan#endif
1455169689Skan
1456169689Skan
1457169689Skan#ifdef ASSERT
1458169689Skanstatic bool ccp_type_widens(const Type* t, const Type* t0) {
1459169689Skan  assert(t->meet(t0) == t, "Not monotonic");
1460169689Skan  switch (t->base() == t0->base() ? t->base() : Type::Top) {
1461169689Skan  case Type::Int:
1462169689Skan    assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1463169689Skan    break;
1464169689Skan  case Type::Long:
1465169689Skan    assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1466169689Skan    break;
1467169689Skan  }
1468169689Skan  return true;
1469169689Skan}
1470169689Skan#endif //ASSERT
1471169689Skan
1472169689Skan//------------------------------analyze----------------------------------------
1473169689Skanvoid PhaseCCP::analyze() {
1474169689Skan  // Initialize all types to TOP, optimistic analysis
1475169689Skan  for (int i = C->unique() - 1; i >= 0; i--)  {
1476169689Skan    _types.map(i,Type::TOP);
1477169689Skan  }
1478169689Skan
1479169689Skan  // Push root onto worklist
1480169689Skan  Unique_Node_List worklist;
1481169689Skan  worklist.push(C->root());
1482169689Skan
1483169689Skan  // Pull from worklist; compute new value; push changes out.
1484169689Skan  // This loop is the meat of CCP.
1485169689Skan  while( worklist.size() ) {
1486169689Skan    Node *n = worklist.pop();
1487169689Skan    const Type *t = n->Value(this);
1488169689Skan    if (t != type(n)) {
1489169689Skan      assert(ccp_type_widens(t, type(n)), "ccp type must widen");
1490169689Skan#ifndef PRODUCT
1491169689Skan      if( TracePhaseCCP ) {
1492169689Skan        t->dump();
1493169689Skan        do { tty->print("\t"); } while (tty->position() < 16);
1494169689Skan        n->dump();
1495169689Skan      }
1496169689Skan#endif
1497169689Skan      set_type(n, t);
1498169689Skan      for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1499169689Skan        Node* m = n->fast_out(i);   // Get user
1500169689Skan        if( m->is_Region() ) {  // New path to Region?  Must recheck Phis too
1501169689Skan          for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1502169689Skan            Node* p = m->fast_out(i2); // Propagate changes to uses
1503169689Skan            if( p->bottom_type() != type(p) ) // If not already bottomed out
1504169689Skan              worklist.push(p); // Propagate change to user
1505169689Skan          }
1506169689Skan        }
1507169689Skan        // If we changed the receiver type to a call, we need to revisit
1508169689Skan        // the Catch following the call.  It's looking for a non-NULL
1509169689Skan        // receiver to know when to enable the regular fall-through path
1510169689Skan        // in addition to the NullPtrException path
1511169689Skan        if (m->is_Call()) {
1512169689Skan          for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1513169689Skan            Node* p = m->fast_out(i2);  // Propagate changes to uses
1514169689Skan            if (p->is_Proj() && p->as_Proj()->_con == TypeFunc::Control && p->outcnt() == 1)
1515169689Skan              worklist.push(p->unique_out());
1516169689Skan          }
1517169689Skan        }
1518169689Skan        if( m->bottom_type() != type(m) ) // If not already bottomed out
1519169689Skan          worklist.push(m);     // Propagate change to user
1520169689Skan      }
1521169689Skan    }
1522169689Skan  }
1523169689Skan}
1524169689Skan
1525169689Skan//------------------------------do_transform-----------------------------------
1526169689Skan// Top level driver for the recursive transformer
1527169689Skanvoid PhaseCCP::do_transform() {
1528169689Skan  // Correct leaves of new-space Nodes; they point to old-space.
1529169689Skan  C->set_root( transform(C->root())->as_Root() );
1530169689Skan  assert( C->top(),  "missing TOP node" );
1531169689Skan  assert( C->root(), "missing root" );
1532169689Skan
1533169689Skan  // Eagerly remove castPP nodes here. CastPP nodes might not be
1534169689Skan  // removed in the subsequent IGVN phase if a node that changes
1535169689Skan  // in(1) of a castPP is processed prior to the castPP node.
1536169689Skan  for (uint i = 0; i < _worklist.size(); i++) {
1537169689Skan    Node* n = _worklist.at(i);
1538169689Skan
1539169689Skan    if (n->is_ConstraintCast()) {
1540169689Skan      Node* nn = n->Identity(this);
1541169689Skan      if (nn != n) {
1542169689Skan        replace_node(n, nn);
1543169689Skan        --i;
1544169689Skan      }
1545169689Skan    }
1546169689Skan  }
1547169689Skan}
1548169689Skan
1549169689Skan//------------------------------transform--------------------------------------
1550169689Skan// Given a Node in old-space, clone him into new-space.
1551169689Skan// Convert any of his old-space children into new-space children.
1552169689SkanNode *PhaseCCP::transform( Node *n ) {
1553169689Skan  Node *new_node = _nodes[n->_idx]; // Check for transformed node
1554169689Skan  if( new_node != NULL )
1555169689Skan    return new_node;                // Been there, done that, return old answer
1556169689Skan  new_node = transform_once(n);     // Check for constant
1557169689Skan  _nodes.map( n->_idx, new_node );  // Flag as having been cloned
1558169689Skan
1559169689Skan  // Allocate stack of size _nodes.Size()/2 to avoid frequent realloc
1560169689Skan  GrowableArray <Node *> trstack(C->unique() >> 1);
1561169689Skan
1562169689Skan  trstack.push(new_node);           // Process children of cloned node
1563169689Skan  while ( trstack.is_nonempty() ) {
1564169689Skan    Node *clone = trstack.pop();
1565169689Skan    uint cnt = clone->req();
1566169689Skan    for( uint i = 0; i < cnt; i++ ) {          // For all inputs do
1567169689Skan      Node *input = clone->in(i);
1568169689Skan      if( input != NULL ) {                    // Ignore NULLs
1569169689Skan        Node *new_input = _nodes[input->_idx]; // Check for cloned input node
1570169689Skan        if( new_input == NULL ) {
1571169689Skan          new_input = transform_once(input);   // Check for constant
1572169689Skan          _nodes.map( input->_idx, new_input );// Flag as having been cloned
1573169689Skan          trstack.push(new_input);
1574169689Skan        }
1575169689Skan        assert( new_input == clone->in(i), "insanity check");
1576169689Skan      }
1577169689Skan    }
1578169689Skan  }
1579169689Skan  return new_node;
1580169689Skan}
1581169689Skan
1582169689Skan
1583169689Skan//------------------------------transform_once---------------------------------
1584169689Skan// For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
1585169689SkanNode *PhaseCCP::transform_once( Node *n ) {
1586169689Skan  const Type *t = type(n);
1587169689Skan  // Constant?  Use constant Node instead
1588169689Skan  if( t->singleton() ) {
1589169689Skan    Node *nn = n;               // Default is to return the original constant
1590169689Skan    if( t == Type::TOP ) {
1591169689Skan      // cache my top node on the Compile instance
1592169689Skan      if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
1593169689Skan        C->set_cached_top_node( ConNode::make(C, Type::TOP) );
1594169689Skan        set_type(C->top(), Type::TOP);
1595169689Skan      }
1596169689Skan      nn = C->top();
1597169689Skan    }
1598169689Skan    if( !n->is_Con() ) {
1599169689Skan      if( t != Type::TOP ) {
1600169689Skan        nn = makecon(t);        // ConNode::make(t);
1601169689Skan        NOT_PRODUCT( inc_constants(); )
1602169689Skan      } else if( n->is_Region() ) { // Unreachable region
1603169689Skan        // Note: nn == C->top()
1604169689Skan        n->set_req(0, NULL);        // Cut selfreference
1605169689Skan        // Eagerly remove dead phis to avoid phis copies creation.
1606169689Skan        for (DUIterator i = n->outs(); n->has_out(i); i++) {
1607169689Skan          Node* m = n->out(i);
1608169689Skan          if( m->is_Phi() ) {
1609169689Skan            assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
1610169689Skan            replace_node(m, nn);
1611169689Skan            --i; // deleted this phi; rescan starting with next position
1612169689Skan          }
1613169689Skan        }
1614169689Skan      }
1615169689Skan      replace_node(n,nn);       // Update DefUse edges for new constant
1616169689Skan    }
1617169689Skan    return nn;
1618169689Skan  }
1619169689Skan
1620169689Skan  // If x is a TypeNode, capture any more-precise type permanently into Node
1621169689Skan  if (t != n->bottom_type()) {
1622169689Skan    hash_delete(n);             // changing bottom type may force a rehash
1623169689Skan    n->raise_bottom_type(t);
1624169689Skan    _worklist.push(n);          // n re-enters the hash table via the worklist
1625169689Skan  }
1626169689Skan
1627169689Skan  // Idealize graph using DU info.  Must clone() into new-space.
1628169689Skan  // DU info is generally used to show profitability, progress or safety
1629169689Skan  // (but generally not needed for correctness).
1630169689Skan  Node *nn = n->Ideal_DU_postCCP(this);
1631169689Skan
1632169689Skan  // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
1633169689Skan  switch( n->Opcode() ) {
1634169689Skan  case Op_FastLock:      // Revisit FastLocks for lock coarsening
1635169689Skan  case Op_If:
1636169689Skan  case Op_CountedLoopEnd:
1637169689Skan  case Op_Region:
1638169689Skan  case Op_Loop:
1639169689Skan  case Op_CountedLoop:
1640169689Skan  case Op_Conv2B:
1641169689Skan  case Op_Opaque1:
1642169689Skan  case Op_Opaque2:
1643169689Skan    _worklist.push(n);
1644169689Skan    break;
1645169689Skan  default:
1646169689Skan    break;
1647169689Skan  }
1648169689Skan  if( nn ) {
1649169689Skan    _worklist.push(n);
1650169689Skan    // Put users of 'n' onto worklist for second igvn transform
1651169689Skan    add_users_to_worklist(n);
1652169689Skan    return nn;
1653169689Skan  }
1654169689Skan
1655169689Skan  return  n;
1656169689Skan}
1657169689Skan
1658169689Skan//---------------------------------saturate------------------------------------
1659169689Skanconst Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
1660169689Skan                               const Type* limit_type) const {
1661169689Skan  const Type* wide_type = new_type->widen(old_type, limit_type);
1662169689Skan  if (wide_type != new_type) {          // did we widen?
1663169689Skan    // If so, we may have widened beyond the limit type.  Clip it back down.
1664169689Skan    new_type = wide_type->filter(limit_type);
1665169689Skan  }
1666169689Skan  return new_type;
1667169689Skan}
1668169689Skan
1669169689Skan//------------------------------print_statistics-------------------------------
1670169689Skan#ifndef PRODUCT
1671169689Skanvoid PhaseCCP::print_statistics() {
1672169689Skan  tty->print_cr("CCP: %d  constants found: %d", _total_invokes, _total_constants);
1673169689Skan}
1674169689Skan#endif
1675169689Skan
1676169689Skan
1677169689Skan//=============================================================================
1678169689Skan#ifndef PRODUCT
1679169689Skanuint PhasePeephole::_total_peepholes = 0;
1680169689Skan#endif
1681169689Skan//------------------------------PhasePeephole----------------------------------
1682169689Skan// Conditional Constant Propagation, ala Wegman & Zadeck
1683169689SkanPhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
1684169689Skan  : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
1685169689Skan  NOT_PRODUCT( clear_peepholes(); )
1686169689Skan}
1687169689Skan
1688169689Skan#ifndef PRODUCT
1689169689Skan//------------------------------~PhasePeephole---------------------------------
1690169689SkanPhasePeephole::~PhasePeephole() {
1691169689Skan  _total_peepholes += count_peepholes();
1692169689Skan}
1693169689Skan#endif
1694169689Skan
1695169689Skan//------------------------------transform--------------------------------------
1696169689SkanNode *PhasePeephole::transform( Node *n ) {
1697169689Skan  ShouldNotCallThis();
1698169689Skan  return NULL;
1699169689Skan}
1700169689Skan
1701169689Skan//------------------------------do_transform-----------------------------------
1702169689Skanvoid PhasePeephole::do_transform() {
1703169689Skan  bool method_name_not_printed = true;
1704169689Skan
1705169689Skan  // Examine each basic block
1706169689Skan  for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
1707169689Skan    Block* block = _cfg.get_block(block_number);
1708169689Skan    bool block_not_printed = true;
1709169689Skan
1710169689Skan    // and each instruction within a block
1711169689Skan    uint end_index = block->number_of_nodes();
1712169689Skan    // block->end_idx() not valid after PhaseRegAlloc
1713169689Skan    for( uint instruction_index = 1; instruction_index < end_index; ++instruction_index ) {
1714169689Skan      Node     *n = block->get_node(instruction_index);
1715169689Skan      if( n->is_Mach() ) {
1716169689Skan        MachNode *m = n->as_Mach();
1717169689Skan        int deleted_count = 0;
1718169689Skan        // check for peephole opportunities
1719169689Skan        MachNode *m2 = m->peephole( block, instruction_index, _regalloc, deleted_count, C );
1720169689Skan        if( m2 != NULL ) {
1721169689Skan#ifndef PRODUCT
1722169689Skan          if( PrintOptoPeephole ) {
1723169689Skan            // Print method, first time only
1724169689Skan            if( C->method() && method_name_not_printed ) {
1725169689Skan              C->method()->print_short_name(); tty->cr();
1726169689Skan              method_name_not_printed = false;
1727169689Skan            }
1728169689Skan            // Print this block
1729169689Skan            if( Verbose && block_not_printed) {
1730169689Skan              tty->print_cr("in block");
1731169689Skan              block->dump();
1732169689Skan              block_not_printed = false;
1733169689Skan            }
1734169689Skan            // Print instructions being deleted
1735169689Skan            for( int i = (deleted_count - 1); i >= 0; --i ) {
1736169689Skan              block->get_node(instruction_index-i)->as_Mach()->format(_regalloc); tty->cr();
1737169689Skan            }
1738169689Skan            tty->print_cr("replaced with");
1739169689Skan            // Print new instruction
1740169689Skan            m2->format(_regalloc);
1741169689Skan            tty->print("\n\n");
1742169689Skan          }
1743169689Skan#endif
1744169689Skan          // Remove old nodes from basic block and update instruction_index
1745169689Skan          // (old nodes still exist and may have edges pointing to them
1746169689Skan          //  as register allocation info is stored in the allocator using
1747169689Skan          //  the node index to live range mappings.)
1748169689Skan          uint safe_instruction_index = (instruction_index - deleted_count);
1749169689Skan          for( ; (instruction_index > safe_instruction_index); --instruction_index ) {
1750169689Skan            block->remove_node( instruction_index );
1751169689Skan          }
1752169689Skan          // install new node after safe_instruction_index
1753169689Skan          block->insert_node(m2, safe_instruction_index + 1);
1754169689Skan          end_index = block->number_of_nodes() - 1; // Recompute new block size
1755169689Skan          NOT_PRODUCT( inc_peepholes(); )
1756169689Skan        }
1757169689Skan      }
1758169689Skan    }
1759169689Skan  }
1760169689Skan}
1761169689Skan
1762169689Skan//------------------------------print_statistics-------------------------------
1763169689Skan#ifndef PRODUCT
1764169689Skanvoid PhasePeephole::print_statistics() {
1765169689Skan  tty->print_cr("Peephole: peephole rules applied: %d",  _total_peepholes);
1766169689Skan}
1767169689Skan#endif
1768169689Skan
1769169689Skan
1770169689Skan//=============================================================================
1771169689Skan//------------------------------set_req_X--------------------------------------
1772169689Skanvoid Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
1773169689Skan  assert( is_not_dead(n), "can not use dead node");
1774169689Skan  assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
1775169689Skan  Node *old = in(i);
1776169689Skan  set_req(i, n);
1777169689Skan
1778169689Skan  // old goes dead?
1779169689Skan  if( old ) {
1780169689Skan    switch (old->outcnt()) {
1781169689Skan    case 0:
1782169689Skan      // Put into the worklist to kill later. We do not kill it now because the
1783169689Skan      // recursive kill will delete the current node (this) if dead-loop exists
1784169689Skan      if (!old->is_top())
1785169689Skan        igvn->_worklist.push( old );
1786169689Skan      break;
1787169689Skan    case 1:
1788169689Skan      if( old->is_Store() || old->has_special_unique_user() )
1789169689Skan        igvn->add_users_to_worklist( old );
1790169689Skan      break;
1791169689Skan    case 2:
1792169689Skan      if( old->is_Store() )
1793169689Skan        igvn->add_users_to_worklist( old );
1794169689Skan      if( old->Opcode() == Op_Region )
1795169689Skan        igvn->_worklist.push(old);
1796169689Skan      break;
1797169689Skan    case 3:
1798169689Skan      if( old->Opcode() == Op_Region ) {
1799169689Skan        igvn->_worklist.push(old);
1800169689Skan        igvn->add_users_to_worklist( old );
1801169689Skan      }
1802169689Skan      break;
1803169689Skan    default:
1804169689Skan      break;
1805169689Skan    }
1806169689Skan  }
1807169689Skan
1808169689Skan}
1809169689Skan
1810169689Skan//-------------------------------replace_by-----------------------------------
1811169689Skan// Using def-use info, replace one node for another.  Follow the def-use info
1812169689Skan// to all users of the OLD node.  Then make all uses point to the NEW node.
1813169689Skanvoid Node::replace_by(Node *new_node) {
1814169689Skan  assert(!is_top(), "top node has no DU info");
1815169689Skan  for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
1816169689Skan    Node* use = last_out(i);
1817169689Skan    uint uses_found = 0;
1818169689Skan    for (uint j = 0; j < use->len(); j++) {
1819169689Skan      if (use->in(j) == this) {
1820169689Skan        if (j < use->req())
1821169689Skan              use->set_req(j, new_node);
1822169689Skan        else  use->set_prec(j, new_node);
1823169689Skan        uses_found++;
1824169689Skan      }
1825169689Skan    }
1826169689Skan    i -= uses_found;    // we deleted 1 or more copies of this edge
1827169689Skan  }
1828169689Skan}
1829169689Skan
1830169689Skan//=============================================================================
1831169689Skan//-----------------------------------------------------------------------------
1832169689Skanvoid Type_Array::grow( uint i ) {
1833169689Skan  if( !_max ) {
1834169689Skan    _max = 1;
1835169689Skan    _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
1836169689Skan    _types[0] = NULL;
1837169689Skan  }
1838169689Skan  uint old = _max;
1839169689Skan  while( i >= _max ) _max <<= 1;        // Double to fit
1840169689Skan  _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
1841169689Skan  memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
1842169689Skan}
1843169689Skan
1844169689Skan//------------------------------dump-------------------------------------------
1845169689Skan#ifndef PRODUCT
1846169689Skanvoid Type_Array::dump() const {
1847169689Skan  uint max = Size();
1848169689Skan  for( uint i = 0; i < max; i++ ) {
1849169689Skan    if( _types[i] != NULL ) {
1850169689Skan      tty->print("  %d\t== ", i); _types[i]->dump(); tty->cr();
1851169689Skan    }
1852169689Skan  }
1853169689Skan}
1854169689Skan#endif
1855169689Skan