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