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