1 /*
2 * Copyright (c) 1997, 2020, 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
406 // Implementation requires 'UseLoopSafepoints == true' and an edge from root
407 // to each SafePointNode at a backward branch. Inserted in add_safepoint().
408 if( !UseLoopSafepoints || !OptoRemoveUseless ) return;
409
410 // Identify nodes that are reachable from below, useful.
411 C->identify_useful_nodes(_useful);
412 // Update dead node list
413 C->update_dead_node_list(_useful);
414
415 // Remove all useless nodes from PhaseValues' recorded types
416 // Must be done before disconnecting nodes to preserve hash-table-invariant
417 gvn->remove_useless_nodes(_useful.member_set());
418
419 // Remove all useless nodes from future worklist
420 worklist->remove_useless_nodes(_useful.member_set());
421
422 // Disconnect 'useless' nodes that are adjacent to useful nodes
423 C->remove_useless_nodes(_useful);
424 }
425
426 //=============================================================================
427 //------------------------------PhaseRenumberLive------------------------------
428 // First, remove useless nodes (equivalent to identifying live nodes).
429 // Then, renumber live nodes.
430 //
431 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
432 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
433 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
434 // value in the range [0, x).
435 //
436 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
437 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
438 //
439 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
440 // (1) The worklist is used by the PhaseIterGVN phase to identify nodes that must be
441 // processed. A new worklist (with the updated node IDs) is returned in 'new_worklist'.
442 // 'worklist' is cleared upon returning.
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 _is_pass_finished(false),
460 _live_node_count(C->live_nodes())
461 {
462 assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
463 assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
464 assert(gvn->nodes_size() == 0, "GVN must not contain any nodes at this point");
465 assert(_delayed.size() == 0, "should be empty");
466
467 uint worklist_size = worklist->size();
468
469 // Iterate over the set of live nodes.
470 for (uint current_idx = 0; current_idx < _useful.size(); current_idx++) {
471 Node* n = _useful.at(current_idx);
472
473 bool in_worklist = false;
474 if (worklist->member(n)) {
475 in_worklist = true;
476 }
477
478 const Type* type = gvn->type_or_null(n);
479 _new_type_array.map(current_idx, type);
480
481 assert(_old2new_map.at(n->_idx) == -1, "already seen");
482 _old2new_map.at_put(n->_idx, current_idx);
483
484 n->set_idx(current_idx); // Update node ID.
485
486 if (in_worklist) {
487 new_worklist->push(n);
488 }
489
490 if (update_embedded_ids(n) < 0) {
491 _delayed.push(n); // has embedded IDs; handle later
492 }
493 }
494
495 assert(worklist_size == new_worklist->size(), "the new worklist must have the same size as the original worklist");
496 assert(_live_node_count == _useful.size(), "all live nodes must be processed");
497
498 _is_pass_finished = true; // pass finished; safe to process delayed updates
499
500 while (_delayed.size() > 0) {
501 Node* n = _delayed.pop();
502 int no_of_updates = update_embedded_ids(n);
503 assert(no_of_updates > 0, "should be updated");
504 }
505
506 // Replace the compiler's type information with the updated type information.
507 gvn->replace_types(_new_type_array);
508
509 // Update the unique node count of the compilation to the number of currently live nodes.
510 C->set_unique(_live_node_count);
511
512 // Set the dead node count to 0 and reset dead node list.
513 C->reset_dead_node_list();
514
515 // Clear the original worklist
516 worklist->clear();
517 }
518
new_index(int old_idx)519 int PhaseRenumberLive::new_index(int old_idx) {
520 assert(_is_pass_finished, "not finished");
521 if (_old2new_map.at(old_idx) == -1) { // absent
522 // Allocate a placeholder to preserve uniqueness
523 _old2new_map.at_put(old_idx, _live_node_count);
524 _live_node_count++;
525 }
526 return _old2new_map.at(old_idx);
527 }
528
update_embedded_ids(Node * n)529 int PhaseRenumberLive::update_embedded_ids(Node* n) {
530 int no_of_updates = 0;
531 if (n->is_Phi()) {
532 PhiNode* phi = n->as_Phi();
533 if (phi->_inst_id != -1) {
534 if (!_is_pass_finished) {
535 return -1; // delay
536 }
537 int new_idx = new_index(phi->_inst_id);
538 assert(new_idx != -1, "");
539 phi->_inst_id = new_idx;
540 no_of_updates++;
541 }
542 if (phi->_inst_mem_id != -1) {
543 if (!_is_pass_finished) {
544 return -1; // delay
545 }
546 int new_idx = new_index(phi->_inst_mem_id);
547 assert(new_idx != -1, "");
548 phi->_inst_mem_id = new_idx;
549 no_of_updates++;
550 }
551 }
552
553 const Type* type = _new_type_array.fast_lookup(n->_idx);
554 if (type != NULL && type->isa_oopptr() && type->is_oopptr()->is_known_instance()) {
555 if (!_is_pass_finished) {
556 return -1; // delay
557 }
558 int old_idx = type->is_oopptr()->instance_id();
559 int new_idx = new_index(old_idx);
560 const Type* new_type = type->is_oopptr()->with_instance_id(new_idx);
561 _new_type_array.map(n->_idx, new_type);
562 no_of_updates++;
563 }
564
565 return no_of_updates;
566 }
567
568 //=============================================================================
569 //------------------------------PhaseTransform---------------------------------
PhaseTransform(PhaseNumber pnum)570 PhaseTransform::PhaseTransform( PhaseNumber pnum ) : Phase(pnum),
571 _arena(Thread::current()->resource_area()),
572 _nodes(_arena),
573 _types(_arena)
574 {
575 init_con_caches();
576 #ifndef PRODUCT
577 clear_progress();
578 clear_transforms();
579 set_allow_progress(true);
580 #endif
581 // Force allocation for currently existing nodes
582 _types.map(C->unique(), NULL);
583 }
584
585 //------------------------------PhaseTransform---------------------------------
PhaseTransform(Arena * arena,PhaseNumber pnum)586 PhaseTransform::PhaseTransform( Arena *arena, PhaseNumber pnum ) : Phase(pnum),
587 _arena(arena),
588 _nodes(arena),
589 _types(arena)
590 {
591 init_con_caches();
592 #ifndef PRODUCT
593 clear_progress();
594 clear_transforms();
595 set_allow_progress(true);
596 #endif
597 // Force allocation for currently existing nodes
598 _types.map(C->unique(), NULL);
599 }
600
601 //------------------------------PhaseTransform---------------------------------
602 // Initialize with previously generated type information
PhaseTransform(PhaseTransform * pt,PhaseNumber pnum)603 PhaseTransform::PhaseTransform( PhaseTransform *pt, PhaseNumber pnum ) : Phase(pnum),
604 _arena(pt->_arena),
605 _nodes(pt->_nodes),
606 _types(pt->_types)
607 {
608 init_con_caches();
609 #ifndef PRODUCT
610 clear_progress();
611 clear_transforms();
612 set_allow_progress(true);
613 #endif
614 }
615
init_con_caches()616 void PhaseTransform::init_con_caches() {
617 memset(_icons,0,sizeof(_icons));
618 memset(_lcons,0,sizeof(_lcons));
619 memset(_zcons,0,sizeof(_zcons));
620 }
621
622
623 //--------------------------------find_int_type--------------------------------
find_int_type(Node * n)624 const TypeInt* PhaseTransform::find_int_type(Node* n) {
625 if (n == NULL) return NULL;
626 // Call type_or_null(n) to determine node's type since we might be in
627 // parse phase and call n->Value() may return wrong type.
628 // (For example, a phi node at the beginning of loop parsing is not ready.)
629 const Type* t = type_or_null(n);
630 if (t == NULL) return NULL;
631 return t->isa_int();
632 }
633
634
635 //-------------------------------find_long_type--------------------------------
find_long_type(Node * n)636 const TypeLong* PhaseTransform::find_long_type(Node* n) {
637 if (n == NULL) return NULL;
638 // (See comment above on type_or_null.)
639 const Type* t = type_or_null(n);
640 if (t == NULL) return NULL;
641 return t->isa_long();
642 }
643
644
645 #ifndef PRODUCT
dump_old2new_map() const646 void PhaseTransform::dump_old2new_map() const {
647 _nodes.dump();
648 }
649
dump_new(uint nidx) const650 void PhaseTransform::dump_new( uint nidx ) const {
651 for( uint i=0; i<_nodes.Size(); i++ )
652 if( _nodes[i] && _nodes[i]->_idx == nidx ) {
653 _nodes[i]->dump();
654 tty->cr();
655 tty->print_cr("Old index= %d",i);
656 return;
657 }
658 tty->print_cr("Node %d not found in the new indices", nidx);
659 }
660
661 //------------------------------dump_types-------------------------------------
dump_types() const662 void PhaseTransform::dump_types( ) const {
663 _types.dump();
664 }
665
666 //------------------------------dump_nodes_and_types---------------------------
dump_nodes_and_types(const Node * root,uint depth,bool only_ctrl)667 void PhaseTransform::dump_nodes_and_types(const Node* root, uint depth, bool only_ctrl) {
668 VectorSet visited;
669 dump_nodes_and_types_recur(root, depth, only_ctrl, visited);
670 }
671
672 //------------------------------dump_nodes_and_types_recur---------------------
dump_nodes_and_types_recur(const Node * n,uint depth,bool only_ctrl,VectorSet & visited)673 void PhaseTransform::dump_nodes_and_types_recur( const Node *n, uint depth, bool only_ctrl, VectorSet &visited) {
674 if( !n ) return;
675 if( depth == 0 ) return;
676 if( visited.test_set(n->_idx) ) return;
677 for( uint i=0; i<n->len(); i++ ) {
678 if( only_ctrl && !(n->is_Region()) && i != TypeFunc::Control ) continue;
679 dump_nodes_and_types_recur( n->in(i), depth-1, only_ctrl, visited );
680 }
681 n->dump();
682 if (type_or_null(n) != NULL) {
683 tty->print(" "); type(n)->dump(); tty->cr();
684 }
685 }
686
687 #endif
688
689
690 //=============================================================================
691 //------------------------------PhaseValues------------------------------------
692 // Set minimum table size to "255"
PhaseValues(Arena * arena,uint est_max_size)693 PhaseValues::PhaseValues( Arena *arena, uint est_max_size )
694 : PhaseTransform(arena, GVN), _table(arena, est_max_size), _iterGVN(false) {
695 NOT_PRODUCT( clear_new_values(); )
696 }
697
698 //------------------------------PhaseValues------------------------------------
699 // Set minimum table size to "255"
PhaseValues(PhaseValues * ptv)700 PhaseValues::PhaseValues(PhaseValues* ptv)
701 : PhaseTransform(ptv, GVN), _table(&ptv->_table), _iterGVN(false) {
702 NOT_PRODUCT( clear_new_values(); )
703 }
704
705 //------------------------------~PhaseValues-----------------------------------
706 #ifndef PRODUCT
~PhaseValues()707 PhaseValues::~PhaseValues() {
708 _table.dump();
709
710 // Statistics for value progress and efficiency
711 if( PrintCompilation && Verbose && WizardMode ) {
712 tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
713 is_IterGVN() ? "Iter" : " ", C->unique(), made_progress(), made_transforms(), made_new_values());
714 if( made_transforms() != 0 ) {
715 tty->print_cr(" ratio %f", made_progress()/(float)made_transforms() );
716 } else {
717 tty->cr();
718 }
719 }
720 }
721 #endif
722
723 //------------------------------makecon----------------------------------------
makecon(const Type * t)724 ConNode* PhaseTransform::makecon(const Type *t) {
725 assert(t->singleton(), "must be a constant");
726 assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
727 switch (t->base()) { // fast paths
728 case Type::Half:
729 case Type::Top: return (ConNode*) C->top();
730 case Type::Int: return intcon( t->is_int()->get_con() );
731 case Type::Long: return longcon( t->is_long()->get_con() );
732 default: break;
733 }
734 if (t->is_zero_type())
735 return zerocon(t->basic_type());
736 return uncached_makecon(t);
737 }
738
739 //--------------------------uncached_makecon-----------------------------------
740 // Make an idealized constant - one of ConINode, ConPNode, etc.
uncached_makecon(const Type * t)741 ConNode* PhaseValues::uncached_makecon(const Type *t) {
742 assert(t->singleton(), "must be a constant");
743 ConNode* x = ConNode::make(t);
744 ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
745 if (k == NULL) {
746 set_type(x, t); // Missed, provide type mapping
747 GrowableArray<Node_Notes*>* nna = C->node_note_array();
748 if (nna != NULL) {
749 Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
750 loc->clear(); // do not put debug info on constants
751 }
752 } else {
753 x->destruct(this); // Hit, destroy duplicate constant
754 x = k; // use existing constant
755 }
756 return x;
757 }
758
759 //------------------------------intcon-----------------------------------------
760 // Fast integer constant. Same as "transform(new ConINode(TypeInt::make(i)))"
intcon(jint i)761 ConINode* PhaseTransform::intcon(jint i) {
762 // Small integer? Check cache! Check that cached node is not dead
763 if (i >= _icon_min && i <= _icon_max) {
764 ConINode* icon = _icons[i-_icon_min];
765 if (icon != NULL && icon->in(TypeFunc::Control) != NULL)
766 return icon;
767 }
768 ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
769 assert(icon->is_Con(), "");
770 if (i >= _icon_min && i <= _icon_max)
771 _icons[i-_icon_min] = icon; // Cache small integers
772 return icon;
773 }
774
775 //------------------------------longcon----------------------------------------
776 // Fast long constant.
longcon(jlong l)777 ConLNode* PhaseTransform::longcon(jlong l) {
778 // Small integer? Check cache! Check that cached node is not dead
779 if (l >= _lcon_min && l <= _lcon_max) {
780 ConLNode* lcon = _lcons[l-_lcon_min];
781 if (lcon != NULL && lcon->in(TypeFunc::Control) != NULL)
782 return lcon;
783 }
784 ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
785 assert(lcon->is_Con(), "");
786 if (l >= _lcon_min && l <= _lcon_max)
787 _lcons[l-_lcon_min] = lcon; // Cache small integers
788 return lcon;
789 }
integercon(jlong l,BasicType bt)790 ConNode* PhaseTransform::integercon(jlong l, BasicType bt) {
791 if (bt == T_INT) {
792 jint int_con = (jint)l;
793 assert(((long)int_con) == l, "not an int");
794 return intcon(int_con);
795 }
796 assert(bt == T_LONG, "not an integer");
797 return longcon(l);
798 }
799
800
801 //------------------------------zerocon-----------------------------------------
802 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
zerocon(BasicType bt)803 ConNode* PhaseTransform::zerocon(BasicType bt) {
804 assert((uint)bt <= _zcon_max, "domain check");
805 ConNode* zcon = _zcons[bt];
806 if (zcon != NULL && zcon->in(TypeFunc::Control) != NULL)
807 return zcon;
808 zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
809 _zcons[bt] = zcon;
810 return zcon;
811 }
812
813
814
815 //=============================================================================
apply_ideal(Node * k,bool can_reshape)816 Node* PhaseGVN::apply_ideal(Node* k, bool can_reshape) {
817 Node* i = BarrierSet::barrier_set()->barrier_set_c2()->ideal_node(this, k, can_reshape);
818 if (i == NULL) {
819 i = k->Ideal(this, can_reshape);
820 }
821 return i;
822 }
823
824 //------------------------------transform--------------------------------------
825 // Return a node which computes the same function as this node, but in a
826 // faster or cheaper fashion.
transform(Node * n)827 Node *PhaseGVN::transform( Node *n ) {
828 return transform_no_reclaim(n);
829 }
830
831 //------------------------------transform--------------------------------------
832 // Return a node which computes the same function as this node, but
833 // in a faster or cheaper fashion.
transform_no_reclaim(Node * n)834 Node *PhaseGVN::transform_no_reclaim( Node *n ) {
835 NOT_PRODUCT( set_transforms(); )
836
837 // Apply the Ideal call in a loop until it no longer applies
838 Node *k = n;
839 NOT_PRODUCT( uint loop_count = 0; )
840 while( 1 ) {
841 Node *i = apply_ideal(k, /*can_reshape=*/false);
842 if( !i ) break;
843 assert( i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
844 k = i;
845 assert(loop_count++ < K, "infinite loop in PhaseGVN::transform");
846 }
847 NOT_PRODUCT( if( loop_count != 0 ) { set_progress(); } )
848
849
850 // If brand new node, make space in type array.
851 ensure_type_or_null(k);
852
853 // Since I just called 'Value' to compute the set of run-time values
854 // for this Node, and 'Value' is non-local (and therefore expensive) I'll
855 // cache Value. Later requests for the local phase->type of this Node can
856 // use the cached Value instead of suffering with 'bottom_type'.
857 const Type *t = k->Value(this); // Get runtime Value set
858 assert(t != NULL, "value sanity");
859 if (type_or_null(k) != t) {
860 #ifndef PRODUCT
861 // Do not count initial visit to node as a transformation
862 if (type_or_null(k) == NULL) {
863 inc_new_values();
864 set_progress();
865 }
866 #endif
867 set_type(k, t);
868 // If k is a TypeNode, capture any more-precise type permanently into Node
869 k->raise_bottom_type(t);
870 }
871
872 if( t->singleton() && !k->is_Con() ) {
873 NOT_PRODUCT( set_progress(); )
874 return makecon(t); // Turn into a constant
875 }
876
877 // Now check for Identities
878 Node *i = k->Identity(this); // Look for a nearby replacement
879 if( i != k ) { // Found? Return replacement!
880 NOT_PRODUCT( set_progress(); )
881 return i;
882 }
883
884 // Global Value Numbering
885 i = hash_find_insert(k); // Insert if new
886 if( i && (i != k) ) {
887 // Return the pre-existing node
888 NOT_PRODUCT( set_progress(); )
889 return i;
890 }
891
892 // Return Idealized original
893 return k;
894 }
895
is_dominator_helper(Node * d,Node * n,bool linear_only)896 bool PhaseGVN::is_dominator_helper(Node *d, Node *n, bool linear_only) {
897 if (d->is_top() || (d->is_Proj() && d->in(0)->is_top())) {
898 return false;
899 }
900 if (n->is_top() || (n->is_Proj() && n->in(0)->is_top())) {
901 return false;
902 }
903 assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
904 int i = 0;
905 while (d != n) {
906 n = IfNode::up_one_dom(n, linear_only);
907 i++;
908 if (n == NULL || i >= 100) {
909 return false;
910 }
911 }
912 return true;
913 }
914
915 #ifdef ASSERT
916 //------------------------------dead_loop_check--------------------------------
917 // Check for a simple dead loop when a data node references itself directly
918 // or through an other data node excluding cons and phis.
dead_loop_check(Node * n)919 void PhaseGVN::dead_loop_check( Node *n ) {
920 // Phi may reference itself in a loop
921 if (n != NULL && !n->is_dead_loop_safe() && !n->is_CFG()) {
922 // Do 2 levels check and only data inputs.
923 bool no_dead_loop = true;
924 uint cnt = n->req();
925 for (uint i = 1; i < cnt && no_dead_loop; i++) {
926 Node *in = n->in(i);
927 if (in == n) {
928 no_dead_loop = false;
929 } else if (in != NULL && !in->is_dead_loop_safe()) {
930 uint icnt = in->req();
931 for (uint j = 1; j < icnt && no_dead_loop; j++) {
932 if (in->in(j) == n || in->in(j) == in)
933 no_dead_loop = false;
934 }
935 }
936 }
937 if (!no_dead_loop) n->dump(3);
938 assert(no_dead_loop, "dead loop detected");
939 }
940 }
941 #endif
942
943 //=============================================================================
944 //------------------------------PhaseIterGVN-----------------------------------
945 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
PhaseIterGVN(PhaseIterGVN * igvn)946 PhaseIterGVN::PhaseIterGVN(PhaseIterGVN* igvn) : PhaseGVN(igvn),
947 _delay_transform(igvn->_delay_transform),
948 _stack(igvn->_stack ),
949 _worklist(igvn->_worklist)
950 {
951 _iterGVN = true;
952 }
953
954 //------------------------------PhaseIterGVN-----------------------------------
955 // Initialize with previous PhaseGVN info from Parser
PhaseIterGVN(PhaseGVN * gvn)956 PhaseIterGVN::PhaseIterGVN(PhaseGVN* gvn) : PhaseGVN(gvn),
957 _delay_transform(false),
958 // TODO: Before incremental inlining it was allocated only once and it was fine. Now that
959 // the constructor is used in incremental inlining, this consumes too much memory:
960 // _stack(C->live_nodes() >> 1),
961 // So, as a band-aid, we replace this by:
962 _stack(C->comp_arena(), 32),
963 _worklist(*C->for_igvn())
964 {
965 _iterGVN = true;
966 uint max;
967
968 // Dead nodes in the hash table inherited from GVN were not treated as
969 // roots during def-use info creation; hence they represent an invisible
970 // use. Clear them out.
971 max = _table.size();
972 for( uint i = 0; i < max; ++i ) {
973 Node *n = _table.at(i);
974 if(n != NULL && n != _table.sentinel() && n->outcnt() == 0) {
975 if( n->is_top() ) continue;
976 // If remove_useless_nodes() has run, we expect no such nodes left.
977 assert(!UseLoopSafepoints || !OptoRemoveUseless,
978 "remove_useless_nodes missed this node");
979 hash_delete(n);
980 }
981 }
982
983 // Any Phis or Regions on the worklist probably had uses that could not
984 // make more progress because the uses were made while the Phis and Regions
985 // were in half-built states. Put all uses of Phis and Regions on worklist.
986 max = _worklist.size();
987 for( uint j = 0; j < max; j++ ) {
988 Node *n = _worklist.at(j);
989 uint uop = n->Opcode();
990 if( uop == Op_Phi || uop == Op_Region ||
991 n->is_Type() ||
992 n->is_Mem() )
993 add_users_to_worklist(n);
994 }
995 }
996
shuffle_worklist()997 void PhaseIterGVN::shuffle_worklist() {
998 if (_worklist.size() < 2) return;
999 for (uint i = _worklist.size() - 1; i >= 1; i--) {
1000 uint j = C->random() % (i + 1);
1001 swap(_worklist.adr()[i], _worklist.adr()[j]);
1002 }
1003 }
1004
1005 #ifndef PRODUCT
verify_step(Node * n)1006 void PhaseIterGVN::verify_step(Node* n) {
1007 if (VerifyIterativeGVN) {
1008 _verify_window[_verify_counter % _verify_window_size] = n;
1009 ++_verify_counter;
1010 if (C->unique() < 1000 || 0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
1011 ++_verify_full_passes;
1012 Node::verify(C->root(), -1);
1013 }
1014 for (int i = 0; i < _verify_window_size; i++) {
1015 Node* n = _verify_window[i];
1016 if (n == NULL) {
1017 continue;
1018 }
1019 if (n->in(0) == NodeSentinel) { // xform_idom
1020 _verify_window[i] = n->in(1);
1021 --i;
1022 continue;
1023 }
1024 // Typical fanout is 1-2, so this call visits about 6 nodes.
1025 Node::verify(n, 4);
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->is_Con() && !_worklist.member(n)) {
1088 n->dump();
1089 fatal("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->is_Con()) { // skip Con nodes
1102 n->dump();
1103 fatal("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 if (modified_list != NULL) {
1121 while (modified_list->size() > 0) {
1122 Node* n = modified_list->pop();
1123 n->dump();
1124 assert(false, "VerifyIterativeGVN: new modified node was added");
1125 }
1126 }
1127 #endif
1128 }
1129 #endif /* PRODUCT */
1130
1131 #ifdef ASSERT
1132 /**
1133 * Dumps information that can help to debug the problem. A debug
1134 * build fails with an assert.
1135 */
dump_infinite_loop_info(Node * n)1136 void PhaseIterGVN::dump_infinite_loop_info(Node* n) {
1137 n->dump(4);
1138 _worklist.dump();
1139 assert(false, "infinite loop in PhaseIterGVN::optimize");
1140 }
1141
1142 /**
1143 * Prints out information about IGVN if the 'verbose' option is used.
1144 */
trace_PhaseIterGVN_verbose(Node * n,int num_processed)1145 void PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
1146 if (TraceIterativeGVN && Verbose) {
1147 tty->print(" Pop ");
1148 n->dump();
1149 if ((num_processed % 100) == 0) {
1150 _worklist.print_set();
1151 }
1152 }
1153 }
1154 #endif /* ASSERT */
1155
optimize()1156 void PhaseIterGVN::optimize() {
1157 DEBUG_ONLY(uint num_processed = 0;)
1158 NOT_PRODUCT(init_verifyPhaseIterGVN();)
1159 if (StressIGVN) {
1160 shuffle_worklist();
1161 }
1162
1163 uint loop_count = 0;
1164 // Pull from worklist and transform the node. If the node has changed,
1165 // update edge info and put uses on worklist.
1166 while(_worklist.size()) {
1167 if (C->check_node_count(NodeLimitFudgeFactor * 2, "Out of nodes")) {
1168 return;
1169 }
1170 Node* n = _worklist.pop();
1171 if (++loop_count >= K * C->live_nodes()) {
1172 DEBUG_ONLY(dump_infinite_loop_info(n);)
1173 C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1174 return;
1175 }
1176 DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1177 if (n->outcnt() != 0) {
1178 NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1179 // Do the transformation
1180 Node* nn = transform_old(n);
1181 NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1182 } else if (!n->is_top()) {
1183 remove_dead_node(n);
1184 }
1185 }
1186 NOT_PRODUCT(verify_PhaseIterGVN();)
1187 }
1188
1189
1190 /**
1191 * Register a new node with the optimizer. Update the types array, the def-use
1192 * info. Put on worklist.
1193 */
register_new_node_with_optimizer(Node * n,Node * orig)1194 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
1195 set_type_bottom(n);
1196 _worklist.push(n);
1197 if (orig != NULL) C->copy_node_notes_to(n, orig);
1198 return n;
1199 }
1200
1201 //------------------------------transform--------------------------------------
1202 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
transform(Node * n)1203 Node *PhaseIterGVN::transform( Node *n ) {
1204 if (_delay_transform) {
1205 // Register the node but don't optimize for now
1206 register_new_node_with_optimizer(n);
1207 return n;
1208 }
1209
1210 // If brand new node, make space in type array, and give it a type.
1211 ensure_type_or_null(n);
1212 if (type_or_null(n) == NULL) {
1213 set_type_bottom(n);
1214 }
1215
1216 return transform_old(n);
1217 }
1218
transform_old(Node * n)1219 Node *PhaseIterGVN::transform_old(Node* n) {
1220 DEBUG_ONLY(uint loop_count = 0;);
1221 NOT_PRODUCT(set_transforms());
1222
1223 // Remove 'n' from hash table in case it gets modified
1224 _table.hash_delete(n);
1225 if (VerifyIterativeGVN) {
1226 assert(!_table.find_index(n->_idx), "found duplicate entry in table");
1227 }
1228
1229 // Apply the Ideal call in a loop until it no longer applies
1230 Node* k = n;
1231 DEBUG_ONLY(dead_loop_check(k);)
1232 DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1233 C->remove_modified_node(k);
1234 Node* i = apply_ideal(k, /*can_reshape=*/true);
1235 assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1236 #ifndef PRODUCT
1237 verify_step(k);
1238 #endif
1239
1240 while (i != NULL) {
1241 #ifdef ASSERT
1242 if (loop_count >= K) {
1243 dump_infinite_loop_info(i);
1244 }
1245 loop_count++;
1246 #endif
1247 assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1248 // Made a change; put users of original Node on worklist
1249 add_users_to_worklist(k);
1250 // Replacing root of transform tree?
1251 if (k != i) {
1252 // Make users of old Node now use new.
1253 subsume_node(k, i);
1254 k = i;
1255 }
1256 DEBUG_ONLY(dead_loop_check(k);)
1257 // Try idealizing again
1258 DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1259 C->remove_modified_node(k);
1260 i = apply_ideal(k, /*can_reshape=*/true);
1261 assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
1262 #ifndef PRODUCT
1263 verify_step(k);
1264 #endif
1265 }
1266
1267 // If brand new node, make space in type array.
1268 ensure_type_or_null(k);
1269
1270 // See what kind of values 'k' takes on at runtime
1271 const Type* t = k->Value(this);
1272 assert(t != NULL, "value sanity");
1273
1274 // Since I just called 'Value' to compute the set of run-time values
1275 // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1276 // cache Value. Later requests for the local phase->type of this Node can
1277 // use the cached Value instead of suffering with 'bottom_type'.
1278 if (type_or_null(k) != t) {
1279 #ifndef PRODUCT
1280 inc_new_values();
1281 set_progress();
1282 #endif
1283 set_type(k, t);
1284 // If k is a TypeNode, capture any more-precise type permanently into Node
1285 k->raise_bottom_type(t);
1286 // Move users of node to worklist
1287 add_users_to_worklist(k);
1288 }
1289 // If 'k' computes a constant, replace it with a constant
1290 if (t->singleton() && !k->is_Con()) {
1291 NOT_PRODUCT(set_progress();)
1292 Node* con = makecon(t); // Make a constant
1293 add_users_to_worklist(k);
1294 subsume_node(k, con); // Everybody using k now uses con
1295 return con;
1296 }
1297
1298 // Now check for Identities
1299 i = k->Identity(this); // Look for a nearby replacement
1300 if (i != k) { // Found? Return replacement!
1301 NOT_PRODUCT(set_progress();)
1302 add_users_to_worklist(k);
1303 subsume_node(k, i); // Everybody using k now uses i
1304 return i;
1305 }
1306
1307 // Global Value Numbering
1308 i = hash_find_insert(k); // Check for pre-existing node
1309 if (i && (i != k)) {
1310 // Return the pre-existing node if it isn't dead
1311 NOT_PRODUCT(set_progress();)
1312 add_users_to_worklist(k);
1313 subsume_node(k, i); // Everybody using k now uses i
1314 return i;
1315 }
1316
1317 // Return Idealized original
1318 return k;
1319 }
1320
1321 //---------------------------------saturate------------------------------------
saturate(const Type * new_type,const Type * old_type,const Type * limit_type) const1322 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1323 const Type* limit_type) const {
1324 return new_type->narrow(old_type);
1325 }
1326
1327 //------------------------------remove_globally_dead_node----------------------
1328 // Kill a globally dead Node. All uses are also globally dead and are
1329 // aggressively trimmed.
remove_globally_dead_node(Node * dead)1330 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1331 enum DeleteProgress {
1332 PROCESS_INPUTS,
1333 PROCESS_OUTPUTS
1334 };
1335 assert(_stack.is_empty(), "not empty");
1336 _stack.push(dead, PROCESS_INPUTS);
1337
1338 while (_stack.is_nonempty()) {
1339 dead = _stack.node();
1340 if (dead->Opcode() == Op_SafePoint) {
1341 dead->as_SafePoint()->disconnect_from_root(this);
1342 }
1343 uint progress_state = _stack.index();
1344 assert(dead != C->root(), "killing root, eh?");
1345 assert(!dead->is_top(), "add check for top when pushing");
1346 NOT_PRODUCT( set_progress(); )
1347 if (progress_state == PROCESS_INPUTS) {
1348 // After following inputs, continue to outputs
1349 _stack.set_index(PROCESS_OUTPUTS);
1350 if (!dead->is_Con()) { // Don't kill cons but uses
1351 bool recurse = false;
1352 // Remove from hash table
1353 _table.hash_delete( dead );
1354 // Smash all inputs to 'dead', isolating him completely
1355 for (uint i = 0; i < dead->req(); i++) {
1356 Node *in = dead->in(i);
1357 if (in != NULL && in != C->top()) { // Points to something?
1358 int nrep = dead->replace_edge(in, NULL); // Kill edges
1359 assert((nrep > 0), "sanity");
1360 if (in->outcnt() == 0) { // Made input go dead?
1361 _stack.push(in, PROCESS_INPUTS); // Recursively remove
1362 recurse = true;
1363 } else if (in->outcnt() == 1 &&
1364 in->has_special_unique_user()) {
1365 _worklist.push(in->unique_out());
1366 } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1367 if (in->Opcode() == Op_Region) {
1368 _worklist.push(in);
1369 } else if (in->is_Store()) {
1370 DUIterator_Fast imax, i = in->fast_outs(imax);
1371 _worklist.push(in->fast_out(i));
1372 i++;
1373 if (in->outcnt() == 2) {
1374 _worklist.push(in->fast_out(i));
1375 i++;
1376 }
1377 assert(!(i < imax), "sanity");
1378 }
1379 } else {
1380 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
1381 }
1382 if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1383 in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1384 // A Load that directly follows an InitializeNode is
1385 // going away. The Stores that follow are candidates
1386 // again to be captured by the InitializeNode.
1387 for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1388 Node *n = in->fast_out(j);
1389 if (n->is_Store()) {
1390 _worklist.push(n);
1391 }
1392 }
1393 }
1394 } // if (in != NULL && in != C->top())
1395 } // for (uint i = 0; i < dead->req(); i++)
1396 if (recurse) {
1397 continue;
1398 }
1399 } // if (!dead->is_Con())
1400 } // if (progress_state == PROCESS_INPUTS)
1401
1402 // Aggressively kill globally dead uses
1403 // (Rather than pushing all the outs at once, we push one at a time,
1404 // plus the parent to resume later, because of the indefinite number
1405 // of edge deletions per loop trip.)
1406 if (dead->outcnt() > 0) {
1407 // Recursively remove output edges
1408 _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1409 } else {
1410 // Finished disconnecting all input and output edges.
1411 _stack.pop();
1412 // Remove dead node from iterative worklist
1413 _worklist.remove(dead);
1414 C->remove_useless_node(dead);
1415 }
1416 } // while (_stack.is_nonempty())
1417 }
1418
1419 //------------------------------subsume_node-----------------------------------
1420 // Remove users from node 'old' and add them to node 'nn'.
subsume_node(Node * old,Node * nn)1421 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1422 if (old->Opcode() == Op_SafePoint) {
1423 old->as_SafePoint()->disconnect_from_root(this);
1424 }
1425 assert( old != hash_find(old), "should already been removed" );
1426 assert( old != C->top(), "cannot subsume top node");
1427 // Copy debug or profile information to the new version:
1428 C->copy_node_notes_to(nn, old);
1429 // Move users of node 'old' to node 'nn'
1430 for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1431 Node* use = old->last_out(i); // for each use...
1432 // use might need re-hashing (but it won't if it's a new node)
1433 rehash_node_delayed(use);
1434 // Update use-def info as well
1435 // We remove all occurrences of old within use->in,
1436 // so as to avoid rehashing any node more than once.
1437 // The hash table probe swamps any outer loop overhead.
1438 uint num_edges = 0;
1439 for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1440 if (use->in(j) == old) {
1441 use->set_req(j, nn);
1442 ++num_edges;
1443 }
1444 }
1445 i -= num_edges; // we deleted 1 or more copies of this edge
1446 }
1447
1448 // Search for instance field data PhiNodes in the same region pointing to the old
1449 // memory PhiNode and update their instance memory ids to point to the new node.
1450 if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
1451 Node* region = old->in(0);
1452 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1453 PhiNode* phi = region->fast_out(i)->isa_Phi();
1454 if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
1455 phi->set_inst_mem_id((int)nn->_idx);
1456 }
1457 }
1458 }
1459
1460 // Smash all inputs to 'old', isolating him completely
1461 Node *temp = new Node(1);
1462 temp->init_req(0,nn); // Add a use to nn to prevent him from dying
1463 remove_dead_node( old );
1464 temp->del_req(0); // Yank bogus edge
1465 #ifndef PRODUCT
1466 if( VerifyIterativeGVN ) {
1467 for ( int i = 0; i < _verify_window_size; i++ ) {
1468 if ( _verify_window[i] == old )
1469 _verify_window[i] = nn;
1470 }
1471 }
1472 #endif
1473 temp->destruct(this); // reuse the _idx of this little guy
1474 }
1475
1476 //------------------------------add_users_to_worklist--------------------------
add_users_to_worklist0(Node * n)1477 void PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1478 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1479 _worklist.push(n->fast_out(i)); // Push on worklist
1480 }
1481 }
1482
1483 // Return counted loop Phi if as a counted loop exit condition, cmp
1484 // compares the the induction variable with n
countedloop_phi_from_cmp(CmpINode * cmp,Node * n)1485 static PhiNode* countedloop_phi_from_cmp(CmpINode* cmp, Node* n) {
1486 for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
1487 Node* bol = cmp->fast_out(i);
1488 for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
1489 Node* iff = bol->fast_out(i2);
1490 if (iff->is_CountedLoopEnd()) {
1491 CountedLoopEndNode* cle = iff->as_CountedLoopEnd();
1492 if (cle->limit() == n) {
1493 PhiNode* phi = cle->phi();
1494 if (phi != NULL) {
1495 return phi;
1496 }
1497 }
1498 }
1499 }
1500 }
1501 return NULL;
1502 }
1503
add_users_to_worklist(Node * n)1504 void PhaseIterGVN::add_users_to_worklist( Node *n ) {
1505 add_users_to_worklist0(n);
1506
1507 // Move users of node to worklist
1508 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1509 Node* use = n->fast_out(i); // Get use
1510
1511 if( use->is_Multi() || // Multi-definer? Push projs on worklist
1512 use->is_Store() ) // Enable store/load same address
1513 add_users_to_worklist0(use);
1514
1515 // If we changed the receiver type to a call, we need to revisit
1516 // the Catch following the call. It's looking for a non-NULL
1517 // receiver to know when to enable the regular fall-through path
1518 // in addition to the NullPtrException path.
1519 if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1520 Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
1521 if (p != NULL) {
1522 add_users_to_worklist0(p);
1523 }
1524 }
1525
1526 uint use_op = use->Opcode();
1527 if(use->is_Cmp()) { // Enable CMP/BOOL optimization
1528 add_users_to_worklist(use); // Put Bool on worklist
1529 if (use->outcnt() > 0) {
1530 Node* bol = use->raw_out(0);
1531 if (bol->outcnt() > 0) {
1532 Node* iff = bol->raw_out(0);
1533 if (iff->outcnt() == 2) {
1534 // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1535 // phi merging either 0 or 1 onto the worklist
1536 Node* ifproj0 = iff->raw_out(0);
1537 Node* ifproj1 = iff->raw_out(1);
1538 if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1539 Node* region0 = ifproj0->raw_out(0);
1540 Node* region1 = ifproj1->raw_out(0);
1541 if( region0 == region1 )
1542 add_users_to_worklist0(region0);
1543 }
1544 }
1545 }
1546 }
1547 if (use_op == Op_CmpI) {
1548 Node* phi = countedloop_phi_from_cmp((CmpINode*)use, n);
1549 if (phi != NULL) {
1550 // If an opaque node feeds into the limit condition of a
1551 // CountedLoop, we need to process the Phi node for the
1552 // induction variable when the opaque node is removed:
1553 // the range of values taken by the Phi is now known and
1554 // so its type is also known.
1555 _worklist.push(phi);
1556 }
1557 Node* in1 = use->in(1);
1558 for (uint i = 0; i < in1->outcnt(); i++) {
1559 if (in1->raw_out(i)->Opcode() == Op_CastII) {
1560 Node* castii = in1->raw_out(i);
1561 if (castii->in(0) != NULL && castii->in(0)->in(0) != NULL && castii->in(0)->in(0)->is_If()) {
1562 Node* ifnode = castii->in(0)->in(0);
1563 if (ifnode->in(1) != NULL && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == use) {
1564 // Reprocess a CastII node that may depend on an
1565 // opaque node value when the opaque node is
1566 // removed. In case it carries a dependency we can do
1567 // a better job of computing its type.
1568 _worklist.push(castii);
1569 }
1570 }
1571 }
1572 }
1573 }
1574 }
1575
1576 // If changed Cast input, check Phi users for simple cycles
1577 if (use->is_ConstraintCast()) {
1578 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1579 Node* u = use->fast_out(i2);
1580 if (u->is_Phi())
1581 _worklist.push(u);
1582 }
1583 }
1584 // If changed LShift inputs, check RShift users for useless sign-ext
1585 if( use_op == Op_LShiftI ) {
1586 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1587 Node* u = use->fast_out(i2);
1588 if (u->Opcode() == Op_RShiftI)
1589 _worklist.push(u);
1590 }
1591 }
1592 // If changed AddI/SubI inputs, check CmpU for range check optimization.
1593 if (use_op == Op_AddI || use_op == Op_SubI) {
1594 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1595 Node* u = use->fast_out(i2);
1596 if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
1597 _worklist.push(u);
1598 }
1599 }
1600 }
1601 // If changed AddP inputs, check Stores for loop invariant
1602 if( use_op == Op_AddP ) {
1603 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1604 Node* u = use->fast_out(i2);
1605 if (u->is_Mem())
1606 _worklist.push(u);
1607 }
1608 }
1609 // If changed initialization activity, check dependent Stores
1610 if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1611 InitializeNode* init = use->as_Allocate()->initialization();
1612 if (init != NULL) {
1613 Node* imem = init->proj_out_or_null(TypeFunc::Memory);
1614 if (imem != NULL) add_users_to_worklist0(imem);
1615 }
1616 }
1617 if (use_op == Op_Initialize) {
1618 Node* imem = use->as_Initialize()->proj_out_or_null(TypeFunc::Memory);
1619 if (imem != NULL) add_users_to_worklist0(imem);
1620 }
1621 // Loading the java mirror from a Klass requires two loads and the type
1622 // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1623 // LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
1624 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1625 bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1626
1627 if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
1628 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1629 Node* u = use->fast_out(i2);
1630 const Type* ut = u->bottom_type();
1631 if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
1632 if (has_load_barrier_nodes) {
1633 // Search for load barriers behind the load
1634 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1635 Node* b = u->fast_out(i3);
1636 if (bs->is_gc_barrier_node(b)) {
1637 _worklist.push(b);
1638 }
1639 }
1640 }
1641 _worklist.push(u);
1642 }
1643 }
1644 }
1645 }
1646 }
1647
1648 /**
1649 * Remove the speculative part of all types that we know of
1650 */
remove_speculative_types()1651 void PhaseIterGVN::remove_speculative_types() {
1652 assert(UseTypeSpeculation, "speculation is off");
1653 for (uint i = 0; i < _types.Size(); i++) {
1654 const Type* t = _types.fast_lookup(i);
1655 if (t != NULL) {
1656 _types.map(i, t->remove_speculative());
1657 }
1658 }
1659 _table.check_no_speculative_types();
1660 }
1661
1662 // Check if the type of a divisor of a Div or Mod node includes zero.
no_dependent_zero_check(Node * n) const1663 bool PhaseIterGVN::no_dependent_zero_check(Node* n) const {
1664 switch (n->Opcode()) {
1665 case Op_DivI:
1666 case Op_ModI: {
1667 // Type of divisor includes 0?
1668 if (n->in(2)->is_top()) {
1669 // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1670 return false;
1671 }
1672 const TypeInt* type_divisor = type(n->in(2))->is_int();
1673 return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1674 }
1675 case Op_DivL:
1676 case Op_ModL: {
1677 // Type of divisor includes 0?
1678 if (n->in(2)->is_top()) {
1679 // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1680 return false;
1681 }
1682 const TypeLong* type_divisor = type(n->in(2))->is_long();
1683 return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1684 }
1685 }
1686 return true;
1687 }
1688
1689 //=============================================================================
1690 #ifndef PRODUCT
1691 uint PhaseCCP::_total_invokes = 0;
1692 uint PhaseCCP::_total_constants = 0;
1693 #endif
1694 //------------------------------PhaseCCP---------------------------------------
1695 // Conditional Constant Propagation, ala Wegman & Zadeck
PhaseCCP(PhaseIterGVN * igvn)1696 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
1697 NOT_PRODUCT( clear_constants(); )
1698 assert( _worklist.size() == 0, "" );
1699 // Clear out _nodes from IterGVN. Must be clear to transform call.
1700 _nodes.clear(); // Clear out from IterGVN
1701 analyze();
1702 }
1703
1704 #ifndef PRODUCT
1705 //------------------------------~PhaseCCP--------------------------------------
~PhaseCCP()1706 PhaseCCP::~PhaseCCP() {
1707 inc_invokes();
1708 _total_constants += count_constants();
1709 }
1710 #endif
1711
1712
1713 #ifdef ASSERT
ccp_type_widens(const Type * t,const Type * t0)1714 static bool ccp_type_widens(const Type* t, const Type* t0) {
1715 assert(t->meet(t0) == t, "Not monotonic");
1716 switch (t->base() == t0->base() ? t->base() : Type::Top) {
1717 case Type::Int:
1718 assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1719 break;
1720 case Type::Long:
1721 assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1722 break;
1723 default:
1724 break;
1725 }
1726 return true;
1727 }
1728 #endif //ASSERT
1729
1730 //------------------------------analyze----------------------------------------
analyze()1731 void PhaseCCP::analyze() {
1732 // Initialize all types to TOP, optimistic analysis
1733 for (int i = C->unique() - 1; i >= 0; i--) {
1734 _types.map(i,Type::TOP);
1735 }
1736
1737 // Push root onto worklist
1738 Unique_Node_List worklist;
1739 worklist.push(C->root());
1740
1741 // Pull from worklist; compute new value; push changes out.
1742 // This loop is the meat of CCP.
1743 while( worklist.size() ) {
1744 Node *n = worklist.pop();
1745 const Type *t = n->Value(this);
1746 if (t != type(n)) {
1747 assert(ccp_type_widens(t, type(n)), "ccp type must widen");
1748 #ifndef PRODUCT
1749 if( TracePhaseCCP ) {
1750 t->dump();
1751 do { tty->print("\t"); } while (tty->position() < 16);
1752 n->dump();
1753 }
1754 #endif
1755 set_type(n, t);
1756 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1757 Node* m = n->fast_out(i); // Get user
1758 if (m->is_Region()) { // New path to Region? Must recheck Phis too
1759 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1760 Node* p = m->fast_out(i2); // Propagate changes to uses
1761 if (p->bottom_type() != type(p)) { // If not already bottomed out
1762 worklist.push(p); // Propagate change to user
1763 }
1764 }
1765 }
1766 // If we changed the receiver type to a call, we need to revisit
1767 // the Catch following the call. It's looking for a non-NULL
1768 // receiver to know when to enable the regular fall-through path
1769 // in addition to the NullPtrException path
1770 if (m->is_Call()) {
1771 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1772 Node* p = m->fast_out(i2); // Propagate changes to uses
1773 if (p->is_Proj() && p->as_Proj()->_con == TypeFunc::Control) {
1774 Node* catch_node = p->find_out_with(Op_Catch);
1775 if (catch_node != NULL) {
1776 worklist.push(catch_node);
1777 }
1778 }
1779 }
1780 }
1781 if (m->bottom_type() != type(m)) { // If not already bottomed out
1782 worklist.push(m); // Propagate change to user
1783 }
1784
1785 // CmpU nodes can get their type information from two nodes up in the
1786 // graph (instead of from the nodes immediately above). Make sure they
1787 // are added to the worklist if nodes they depend on are updated, since
1788 // they could be missed and get wrong types otherwise.
1789 uint m_op = m->Opcode();
1790 if (m_op == Op_AddI || m_op == Op_SubI) {
1791 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1792 Node* p = m->fast_out(i2); // Propagate changes to uses
1793 if (p->Opcode() == Op_CmpU) {
1794 // Got a CmpU which might need the new type information from node n.
1795 if(p->bottom_type() != type(p)) { // If not already bottomed out
1796 worklist.push(p); // Propagate change to user
1797 }
1798 }
1799 }
1800 }
1801 // If n is used in a counted loop exit condition then the type
1802 // of the counted loop's Phi depends on the type of n. See
1803 // PhiNode::Value().
1804 if (m_op == Op_CmpI) {
1805 PhiNode* phi = countedloop_phi_from_cmp((CmpINode*)m, n);
1806 if (phi != NULL) {
1807 worklist.push(phi);
1808 }
1809 }
1810 // Loading the java mirror from a Klass requires two loads and the type
1811 // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1812 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1813 bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1814
1815 if (m_op == Op_LoadP && m->bottom_type()->isa_rawptr()) {
1816 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1817 Node* u = m->fast_out(i2);
1818 const Type* ut = u->bottom_type();
1819 if (u->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(u)) {
1820 if (has_load_barrier_nodes) {
1821 // Search for load barriers behind the load
1822 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1823 Node* b = u->fast_out(i3);
1824 if (bs->is_gc_barrier_node(b)) {
1825 worklist.push(b);
1826 }
1827 }
1828 }
1829 worklist.push(u);
1830 }
1831 }
1832 }
1833 }
1834 }
1835 }
1836 }
1837
1838 //------------------------------do_transform-----------------------------------
1839 // Top level driver for the recursive transformer
do_transform()1840 void PhaseCCP::do_transform() {
1841 // Correct leaves of new-space Nodes; they point to old-space.
1842 C->set_root( transform(C->root())->as_Root() );
1843 assert( C->top(), "missing TOP node" );
1844 assert( C->root(), "missing root" );
1845 }
1846
1847 //------------------------------transform--------------------------------------
1848 // Given a Node in old-space, clone him into new-space.
1849 // Convert any of his old-space children into new-space children.
transform(Node * n)1850 Node *PhaseCCP::transform( Node *n ) {
1851 Node *new_node = _nodes[n->_idx]; // Check for transformed node
1852 if( new_node != NULL )
1853 return new_node; // Been there, done that, return old answer
1854 new_node = transform_once(n); // Check for constant
1855 _nodes.map( n->_idx, new_node ); // Flag as having been cloned
1856
1857 // Allocate stack of size _nodes.Size()/2 to avoid frequent realloc
1858 GrowableArray <Node *> trstack(C->live_nodes() >> 1);
1859
1860 trstack.push(new_node); // Process children of cloned node
1861 while ( trstack.is_nonempty() ) {
1862 Node *clone = trstack.pop();
1863 uint cnt = clone->req();
1864 for( uint i = 0; i < cnt; i++ ) { // For all inputs do
1865 Node *input = clone->in(i);
1866 if( input != NULL ) { // Ignore NULLs
1867 Node *new_input = _nodes[input->_idx]; // Check for cloned input node
1868 if( new_input == NULL ) {
1869 new_input = transform_once(input); // Check for constant
1870 _nodes.map( input->_idx, new_input );// Flag as having been cloned
1871 trstack.push(new_input);
1872 }
1873 assert( new_input == clone->in(i), "insanity check");
1874 }
1875 }
1876 }
1877 return new_node;
1878 }
1879
1880
1881 //------------------------------transform_once---------------------------------
1882 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
transform_once(Node * n)1883 Node *PhaseCCP::transform_once( Node *n ) {
1884 const Type *t = type(n);
1885 // Constant? Use constant Node instead
1886 if( t->singleton() ) {
1887 Node *nn = n; // Default is to return the original constant
1888 if( t == Type::TOP ) {
1889 // cache my top node on the Compile instance
1890 if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
1891 C->set_cached_top_node(ConNode::make(Type::TOP));
1892 set_type(C->top(), Type::TOP);
1893 }
1894 nn = C->top();
1895 }
1896 if( !n->is_Con() ) {
1897 if( t != Type::TOP ) {
1898 nn = makecon(t); // ConNode::make(t);
1899 NOT_PRODUCT( inc_constants(); )
1900 } else if( n->is_Region() ) { // Unreachable region
1901 // Note: nn == C->top()
1902 n->set_req(0, NULL); // Cut selfreference
1903 bool progress = true;
1904 uint max = n->outcnt();
1905 DUIterator i;
1906 while (progress) {
1907 progress = false;
1908 // Eagerly remove dead phis to avoid phis copies creation.
1909 for (i = n->outs(); n->has_out(i); i++) {
1910 Node* m = n->out(i);
1911 if (m->is_Phi()) {
1912 assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
1913 replace_node(m, nn);
1914 if (max != n->outcnt()) {
1915 progress = true;
1916 i = n->refresh_out_pos(i);
1917 max = n->outcnt();
1918 }
1919 }
1920 }
1921 }
1922 }
1923 replace_node(n,nn); // Update DefUse edges for new constant
1924 }
1925 return nn;
1926 }
1927
1928 // If x is a TypeNode, capture any more-precise type permanently into Node
1929 if (t != n->bottom_type()) {
1930 hash_delete(n); // changing bottom type may force a rehash
1931 n->raise_bottom_type(t);
1932 _worklist.push(n); // n re-enters the hash table via the worklist
1933 }
1934
1935 // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
1936 switch( n->Opcode() ) {
1937 case Op_FastLock: // Revisit FastLocks for lock coarsening
1938 case Op_If:
1939 case Op_CountedLoopEnd:
1940 case Op_Region:
1941 case Op_Loop:
1942 case Op_CountedLoop:
1943 case Op_Conv2B:
1944 case Op_Opaque1:
1945 case Op_Opaque2:
1946 _worklist.push(n);
1947 break;
1948 default:
1949 break;
1950 }
1951
1952 return n;
1953 }
1954
1955 //---------------------------------saturate------------------------------------
saturate(const Type * new_type,const Type * old_type,const Type * limit_type) const1956 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
1957 const Type* limit_type) const {
1958 const Type* wide_type = new_type->widen(old_type, limit_type);
1959 if (wide_type != new_type) { // did we widen?
1960 // If so, we may have widened beyond the limit type. Clip it back down.
1961 new_type = wide_type->filter(limit_type);
1962 }
1963 return new_type;
1964 }
1965
1966 //------------------------------print_statistics-------------------------------
1967 #ifndef PRODUCT
print_statistics()1968 void PhaseCCP::print_statistics() {
1969 tty->print_cr("CCP: %d constants found: %d", _total_invokes, _total_constants);
1970 }
1971 #endif
1972
1973
1974 //=============================================================================
1975 #ifndef PRODUCT
1976 uint PhasePeephole::_total_peepholes = 0;
1977 #endif
1978 //------------------------------PhasePeephole----------------------------------
1979 // Conditional Constant Propagation, ala Wegman & Zadeck
PhasePeephole(PhaseRegAlloc * regalloc,PhaseCFG & cfg)1980 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
1981 : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
1982 NOT_PRODUCT( clear_peepholes(); )
1983 }
1984
1985 #ifndef PRODUCT
1986 //------------------------------~PhasePeephole---------------------------------
~PhasePeephole()1987 PhasePeephole::~PhasePeephole() {
1988 _total_peepholes += count_peepholes();
1989 }
1990 #endif
1991
1992 //------------------------------transform--------------------------------------
transform(Node * n)1993 Node *PhasePeephole::transform( Node *n ) {
1994 ShouldNotCallThis();
1995 return NULL;
1996 }
1997
1998 //------------------------------do_transform-----------------------------------
do_transform()1999 void PhasePeephole::do_transform() {
2000 bool method_name_not_printed = true;
2001
2002 // Examine each basic block
2003 for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
2004 Block* block = _cfg.get_block(block_number);
2005 bool block_not_printed = true;
2006
2007 // and each instruction within a block
2008 uint end_index = block->number_of_nodes();
2009 // block->end_idx() not valid after PhaseRegAlloc
2010 for( uint instruction_index = 1; instruction_index < end_index; ++instruction_index ) {
2011 Node *n = block->get_node(instruction_index);
2012 if( n->is_Mach() ) {
2013 MachNode *m = n->as_Mach();
2014 int deleted_count = 0;
2015 // check for peephole opportunities
2016 MachNode *m2 = m->peephole(block, instruction_index, _regalloc, deleted_count);
2017 if( m2 != NULL ) {
2018 #ifndef PRODUCT
2019 if( PrintOptoPeephole ) {
2020 // Print method, first time only
2021 if( C->method() && method_name_not_printed ) {
2022 C->method()->print_short_name(); tty->cr();
2023 method_name_not_printed = false;
2024 }
2025 // Print this block
2026 if( Verbose && block_not_printed) {
2027 tty->print_cr("in block");
2028 block->dump();
2029 block_not_printed = false;
2030 }
2031 // Print instructions being deleted
2032 for( int i = (deleted_count - 1); i >= 0; --i ) {
2033 block->get_node(instruction_index-i)->as_Mach()->format(_regalloc); tty->cr();
2034 }
2035 tty->print_cr("replaced with");
2036 // Print new instruction
2037 m2->format(_regalloc);
2038 tty->print("\n\n");
2039 }
2040 #endif
2041 // Remove old nodes from basic block and update instruction_index
2042 // (old nodes still exist and may have edges pointing to them
2043 // as register allocation info is stored in the allocator using
2044 // the node index to live range mappings.)
2045 uint safe_instruction_index = (instruction_index - deleted_count);
2046 for( ; (instruction_index > safe_instruction_index); --instruction_index ) {
2047 block->remove_node( instruction_index );
2048 }
2049 // install new node after safe_instruction_index
2050 block->insert_node(m2, safe_instruction_index + 1);
2051 end_index = block->number_of_nodes() - 1; // Recompute new block size
2052 NOT_PRODUCT( inc_peepholes(); )
2053 }
2054 }
2055 }
2056 }
2057 }
2058
2059 //------------------------------print_statistics-------------------------------
2060 #ifndef PRODUCT
print_statistics()2061 void PhasePeephole::print_statistics() {
2062 tty->print_cr("Peephole: peephole rules applied: %d", _total_peepholes);
2063 }
2064 #endif
2065
2066
2067 //=============================================================================
2068 //------------------------------set_req_X--------------------------------------
set_req_X(uint i,Node * n,PhaseIterGVN * igvn)2069 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
2070 assert( is_not_dead(n), "can not use dead node");
2071 assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
2072 Node *old = in(i);
2073 set_req(i, n);
2074
2075 // old goes dead?
2076 if( old ) {
2077 switch (old->outcnt()) {
2078 case 0:
2079 // Put into the worklist to kill later. We do not kill it now because the
2080 // recursive kill will delete the current node (this) if dead-loop exists
2081 if (!old->is_top())
2082 igvn->_worklist.push( old );
2083 break;
2084 case 1:
2085 if( old->is_Store() || old->has_special_unique_user() )
2086 igvn->add_users_to_worklist( old );
2087 break;
2088 case 2:
2089 if( old->is_Store() )
2090 igvn->add_users_to_worklist( old );
2091 if( old->Opcode() == Op_Region )
2092 igvn->_worklist.push(old);
2093 break;
2094 case 3:
2095 if( old->Opcode() == Op_Region ) {
2096 igvn->_worklist.push(old);
2097 igvn->add_users_to_worklist( old );
2098 }
2099 break;
2100 default:
2101 break;
2102 }
2103
2104 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
2105 }
2106
2107 }
2108
2109 //-------------------------------replace_by-----------------------------------
2110 // Using def-use info, replace one node for another. Follow the def-use info
2111 // to all users of the OLD node. Then make all uses point to the NEW node.
replace_by(Node * new_node)2112 void Node::replace_by(Node *new_node) {
2113 assert(!is_top(), "top node has no DU info");
2114 for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
2115 Node* use = last_out(i);
2116 uint uses_found = 0;
2117 for (uint j = 0; j < use->len(); j++) {
2118 if (use->in(j) == this) {
2119 if (j < use->req())
2120 use->set_req(j, new_node);
2121 else use->set_prec(j, new_node);
2122 uses_found++;
2123 }
2124 }
2125 i -= uses_found; // we deleted 1 or more copies of this edge
2126 }
2127 }
2128
2129 //=============================================================================
2130 //-----------------------------------------------------------------------------
grow(uint i)2131 void Type_Array::grow( uint i ) {
2132 if( !_max ) {
2133 _max = 1;
2134 _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
2135 _types[0] = NULL;
2136 }
2137 uint old = _max;
2138 _max = next_power_of_2(i);
2139 _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
2140 memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
2141 }
2142
2143 //------------------------------dump-------------------------------------------
2144 #ifndef PRODUCT
dump() const2145 void Type_Array::dump() const {
2146 uint max = Size();
2147 for( uint i = 0; i < max; i++ ) {
2148 if( _types[i] != NULL ) {
2149 tty->print(" %d\t== ", i); _types[i]->dump(); tty->cr();
2150 }
2151 }
2152 }
2153 #endif
2154