1 /*
2 * Copyright (c) 1997, 2026, 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 "gc/shared/barrierSet.hpp"
26 #include "gc/shared/c2/barrierSetC2.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "memory/resourceArea.hpp"
29 #include "opto/addnode.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
47 //------------------------------NodeHash---------------------------------------
48 NodeHash::NodeHash(Arena *arena, uint est_max_size) :
49 _a(arena),
50 _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
51 _inserts(0), _insert_limit( insert_limit() ),
52 _table( NEW_ARENA_ARRAY( _a , Node* , _max ) )
53 #ifndef PRODUCT
54 , _grows(0),_look_probes(0), _lookup_hits(0), _lookup_misses(0),
55 _insert_probes(0), _delete_probes(0), _delete_hits(0), _delete_misses(0),
56 _total_inserts(0), _total_insert_probes(0)
57 #endif
58 {
59 // _sentinel must be in the current node space
60 _sentinel = new ProjNode(nullptr, TypeFunc::Control);
61 memset(_table,0,sizeof(Node*)*_max);
62 }
63
64 //------------------------------hash_find--------------------------------------
65 // Find in hash table
66 Node *NodeHash::hash_find( const Node *n ) {
67 // ((Node*)n)->set_hash( n->hash() );
68 uint hash = n->hash();
69 if (hash == Node::NO_HASH) {
70 NOT_PRODUCT( _lookup_misses++ );
71 return nullptr;
72 }
73 uint key = hash & (_max-1);
74 uint stride = key | 0x01;
75 NOT_PRODUCT( _look_probes++ );
76 Node *k = _table[key]; // Get hashed value
77 if( !k ) { // ?Miss?
78 NOT_PRODUCT( _lookup_misses++ );
79 return nullptr; // Miss!
80 }
81
82 int op = n->Opcode();
83 uint req = n->req();
84 while( 1 ) { // While probing hash table
85 if( k->req() == req && // Same count of inputs
86 k->Opcode() == op ) { // Same Opcode
87 for( uint i=0; i<req; i++ )
88 if( n->in(i)!=k->in(i)) // Different inputs?
89 goto collision; // "goto" is a speed hack...
90 if( n->cmp(*k) ) { // Check for any special bits
91 NOT_PRODUCT( _lookup_hits++ );
92 return k; // Hit!
93 }
94 }
95 collision:
96 NOT_PRODUCT( _look_probes++ );
97 key = (key + stride/*7*/) & (_max-1); // Stride through table with relative prime
98 k = _table[key]; // Get hashed value
99 if( !k ) { // ?Miss?
100 NOT_PRODUCT( _lookup_misses++ );
101 return nullptr; // Miss!
102 }
103 }
104 ShouldNotReachHere();
105 return nullptr;
106 }
107
108 //------------------------------hash_find_insert-------------------------------
109 // Find in hash table, insert if not already present
110 // Used to preserve unique entries in hash table
111 Node *NodeHash::hash_find_insert( Node *n ) {
112 // n->set_hash( );
113 uint hash = n->hash();
114 if (hash == Node::NO_HASH) {
115 NOT_PRODUCT( _lookup_misses++ );
116 return nullptr;
117 }
118 uint key = hash & (_max-1);
119 uint stride = key | 0x01; // stride must be relatively prime to table siz
120 uint first_sentinel = 0; // replace a sentinel if seen.
121 NOT_PRODUCT( _look_probes++ );
122 Node *k = _table[key]; // Get hashed value
123 if( !k ) { // ?Miss?
124 NOT_PRODUCT( _lookup_misses++ );
125 _table[key] = n; // Insert into table!
126 DEBUG_ONLY(n->enter_hash_lock()); // Lock down the node while in the table.
127 check_grow(); // Grow table if insert hit limit
128 return nullptr; // Miss!
129 }
130 else if( k == _sentinel ) {
131 first_sentinel = key; // Can insert here
132 }
133
134 int op = n->Opcode();
135 uint req = n->req();
136 while( 1 ) { // While probing hash table
137 if( k->req() == req && // Same count of inputs
138 k->Opcode() == op ) { // Same Opcode
139 for( uint i=0; i<req; i++ )
140 if( n->in(i)!=k->in(i)) // Different inputs?
141 goto collision; // "goto" is a speed hack...
142 if( n->cmp(*k) ) { // Check for any special bits
143 NOT_PRODUCT( _lookup_hits++ );
144 return k; // Hit!
145 }
146 }
147 collision:
148 NOT_PRODUCT( _look_probes++ );
149 key = (key + stride) & (_max-1); // Stride through table w/ relative prime
150 k = _table[key]; // Get hashed value
151 if( !k ) { // ?Miss?
152 NOT_PRODUCT( _lookup_misses++ );
153 key = (first_sentinel == 0) ? key : first_sentinel; // ?saw sentinel?
154 _table[key] = n; // Insert into table!
155 DEBUG_ONLY(n->enter_hash_lock()); // Lock down the node while in the table.
156 check_grow(); // Grow table if insert hit limit
157 return nullptr; // Miss!
158 }
159 else if( first_sentinel == 0 && k == _sentinel ) {
160 first_sentinel = key; // Can insert here
161 }
162
163 }
164 ShouldNotReachHere();
165 return nullptr;
166 }
167
168 //------------------------------hash_insert------------------------------------
169 // Insert into hash table
170 void NodeHash::hash_insert( Node *n ) {
171 // // "conflict" comments -- print nodes that conflict
172 // bool conflict = false;
173 // n->set_hash();
174 uint hash = n->hash();
175 if (hash == Node::NO_HASH) {
176 return;
177 }
178 check_grow();
179 uint key = hash & (_max-1);
180 uint stride = key | 0x01;
181
182 while( 1 ) { // While probing hash table
183 NOT_PRODUCT( _insert_probes++ );
184 Node *k = _table[key]; // Get hashed value
185 if( !k || (k == _sentinel) ) break; // Found a slot
186 assert( k != n, "already inserted" );
187 // if( PrintCompilation && PrintOptoStatistics && Verbose ) { tty->print(" conflict: "); k->dump(); conflict = true; }
188 key = (key + stride) & (_max-1); // Stride through table w/ relative prime
189 }
190 _table[key] = n; // Insert into table!
191 DEBUG_ONLY(n->enter_hash_lock()); // Lock down the node while in the table.
192 // if( conflict ) { n->dump(); }
193 }
194
195 //------------------------------hash_delete------------------------------------
196 // Replace in hash table with sentinel
197 bool NodeHash::hash_delete( const Node *n ) {
198 Node *k;
199 uint hash = n->hash();
200 if (hash == Node::NO_HASH) {
201 NOT_PRODUCT( _delete_misses++ );
202 return false;
203 }
204 uint key = hash & (_max-1);
205 uint stride = key | 0x01;
206 DEBUG_ONLY( uint counter = 0; );
207 for( ; /* (k != nullptr) && (k != _sentinel) */; ) {
208 DEBUG_ONLY( counter++ );
209 NOT_PRODUCT( _delete_probes++ );
210 k = _table[key]; // Get hashed value
211 if( !k ) { // Miss?
212 NOT_PRODUCT( _delete_misses++ );
213 return false; // Miss! Not in chain
214 }
215 else if( n == k ) {
216 NOT_PRODUCT( _delete_hits++ );
217 _table[key] = _sentinel; // Hit! Label as deleted entry
218 DEBUG_ONLY(((Node*)n)->exit_hash_lock()); // Unlock the node upon removal from table.
219 return true;
220 }
221 else {
222 // collision: move through table with prime offset
223 key = (key + stride/*7*/) & (_max-1);
224 assert( counter <= _insert_limit, "Cycle in hash-table");
225 }
226 }
227 ShouldNotReachHere();
228 return false;
229 }
230
231 //------------------------------round_up---------------------------------------
232 // Round up to nearest power of 2
233 uint NodeHash::round_up(uint x) {
234 x += (x >> 2); // Add 25% slop
235 return MAX2(16U, round_up_power_of_2(x));
236 }
237
238 //------------------------------grow-------------------------------------------
239 // Grow _table to next power of 2 and insert old entries
240 void NodeHash::grow() {
241 // Record old state
242 uint old_max = _max;
243 Node **old_table = _table;
244 // Construct new table with twice the space
245 #ifndef PRODUCT
246 _grows++;
247 _total_inserts += _inserts;
248 _total_insert_probes += _insert_probes;
249 _insert_probes = 0;
250 #endif
251 _inserts = 0;
252 _max = _max << 1;
253 _table = NEW_ARENA_ARRAY( _a , Node* , _max ); // (Node**)_a->Amalloc( _max * sizeof(Node*) );
254 memset(_table,0,sizeof(Node*)*_max);
255 _insert_limit = insert_limit();
256 // Insert old entries into the new table
257 for( uint i = 0; i < old_max; i++ ) {
258 Node *m = *old_table++;
259 if( !m || m == _sentinel ) continue;
260 DEBUG_ONLY(m->exit_hash_lock()); // Unlock the node upon removal from old table.
261 hash_insert(m);
262 }
263 }
264
265 //------------------------------clear------------------------------------------
266 // Clear all entries in _table to null but keep storage
267 void NodeHash::clear() {
268 #ifdef ASSERT
269 // Unlock all nodes upon removal from table.
270 for (uint i = 0; i < _max; i++) {
271 Node* n = _table[i];
272 if (!n || n == _sentinel) continue;
273 n->exit_hash_lock();
274 }
275 #endif
276
277 memset( _table, 0, _max * sizeof(Node*) );
278 }
279
280 //-----------------------remove_useless_nodes----------------------------------
281 // Remove useless nodes from value table,
282 // implementation does not depend on hash function
283 void NodeHash::remove_useless_nodes(VectorSet &useful) {
284
285 // Dead nodes in the hash table inherited from GVN should not replace
286 // existing nodes, remove dead nodes.
287 uint max = size();
288 Node *sentinel_node = sentinel();
289 for( uint i = 0; i < max; ++i ) {
290 Node *n = at(i);
291 if(n != nullptr && n != sentinel_node && !useful.test(n->_idx)) {
292 DEBUG_ONLY(n->exit_hash_lock()); // Unlock the node when removed
293 _table[i] = sentinel_node; // Replace with placeholder
294 }
295 }
296 }
297
298
299 void NodeHash::check_no_speculative_types() {
300 #ifdef ASSERT
301 uint max = size();
302 Unique_Node_List live_nodes;
303 Compile::current()->identify_useful_nodes(live_nodes);
304 Node *sentinel_node = sentinel();
305 for (uint i = 0; i < max; ++i) {
306 Node *n = at(i);
307 if (n != nullptr &&
308 n != sentinel_node &&
309 n->is_Type() &&
310 live_nodes.member(n)) {
311 TypeNode* tn = n->as_Type();
312 const Type* t = tn->type();
313 const Type* t_no_spec = t->remove_speculative();
314 assert(t == t_no_spec, "dead node in hash table or missed node during speculative cleanup");
315 }
316 }
317 #endif
318 }
319
320 #ifndef PRODUCT
321 //------------------------------dump-------------------------------------------
322 // Dump statistics for the hash table
323 void NodeHash::dump() {
324 _total_inserts += _inserts;
325 _total_insert_probes += _insert_probes;
326 if (PrintCompilation && PrintOptoStatistics && Verbose && (_inserts > 0)) {
327 if (WizardMode) {
328 for (uint i=0; i<_max; i++) {
329 if (_table[i])
330 tty->print("%d/%d/%d ",i,_table[i]->hash()&(_max-1),_table[i]->_idx);
331 }
332 }
333 tty->print("\nGVN Hash stats: %d grows to %d max_size\n", _grows, _max);
334 tty->print(" %d/%d (%8.1f%% full)\n", _inserts, _max, (double)_inserts/_max*100.0);
335 tty->print(" %dp/(%dh+%dm) (%8.2f probes/lookup)\n", _look_probes, _lookup_hits, _lookup_misses, (double)_look_probes/(_lookup_hits+_lookup_misses));
336 tty->print(" %dp/%di (%8.2f probes/insert)\n", _total_insert_probes, _total_inserts, (double)_total_insert_probes/_total_inserts);
337 // sentinels increase lookup cost, but not insert cost
338 assert((_lookup_misses+_lookup_hits)*4+100 >= _look_probes, "bad hash function");
339 assert( _inserts+(_inserts>>3) < _max, "table too full" );
340 assert( _inserts*3+100 >= _insert_probes, "bad hash function" );
341 }
342 }
343
344 Node *NodeHash::find_index(uint idx) { // For debugging
345 // Find an entry by its index value
346 for( uint i = 0; i < _max; i++ ) {
347 Node *m = _table[i];
348 if( !m || m == _sentinel ) continue;
349 if( m->_idx == (uint)idx ) return m;
350 }
351 return nullptr;
352 }
353 #endif
354
355 #ifdef ASSERT
356 NodeHash::~NodeHash() {
357 // Unlock all nodes upon destruction of table.
358 if (_table != (Node**)badAddress) clear();
359 }
360 #endif
361
362
363 //=============================================================================
364 //------------------------------PhaseRemoveUseless-----------------------------
365 // 1) Use a breadthfirst walk to collect useful nodes reachable from root.
366 PhaseRemoveUseless::PhaseRemoveUseless(PhaseGVN* gvn, Unique_Node_List& worklist, PhaseNumber phase_num) : Phase(phase_num) {
367 C->print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
368 // Implementation requires an edge from root to each SafePointNode
369 // at a backward branch. Inserted in add_safepoint().
370
371 // Identify nodes that are reachable from below, useful.
372 C->identify_useful_nodes(_useful);
373 // Update dead node list
374 C->update_dead_node_list(_useful);
375
376 // Remove all useless nodes from PhaseValues' recorded types
377 // Must be done before disconnecting nodes to preserve hash-table-invariant
378 gvn->remove_useless_nodes(_useful.member_set());
379
380 // Remove all useless nodes from future worklist
381 worklist.remove_useless_nodes(_useful.member_set());
382
383 // Disconnect 'useless' nodes that are adjacent to useful nodes
384 C->disconnect_useless_nodes(_useful, worklist);
385 }
386
387 //=============================================================================
388 //------------------------------PhaseRenumberLive------------------------------
389 // First, remove useless nodes (equivalent to identifying live nodes).
390 // Then, renumber live nodes.
391 //
392 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
393 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
394 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
395 // value in the range [0, x).
396 //
397 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
398 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
399 //
400 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
401 // (1) The "worklist" is "C->igvn_worklist()", which is to collect which nodes need to
402 // be processed by IGVN after removal of the useless nodes.
403 // (2) Type information "gvn->types()" (same as "C->types()") maps every node ID to
404 // the node's type. The mapping is updated to use the new node IDs as well. We
405 // create a new map, and swap it with the old one.
406 //
407 // Other data structures used by the compiler are not updated. The hash table for value
408 // numbering ("C->node_hash()", referenced by PhaseValue::_table) is not updated because
409 // computing the hash values is not based on node IDs.
410 PhaseRenumberLive::PhaseRenumberLive(PhaseGVN* gvn,
411 Unique_Node_List& worklist,
412 PhaseNumber phase_num) :
413 PhaseRemoveUseless(gvn, worklist, Remove_Useless_And_Renumber_Live),
414 _new_type_array(C->comp_arena()),
415 _old2new_map(C->unique(), C->unique(), -1),
416 _is_pass_finished(false),
417 _live_node_count(C->live_nodes())
418 {
419 assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
420 assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
421 assert(_delayed.size() == 0, "should be empty");
422 assert(&worklist == C->igvn_worklist(), "reference still same as the one from Compile");
423 assert(&gvn->types() == C->types(), "reference still same as that from Compile");
424
425 GrowableArray<Node_Notes*>* old_node_note_array = C->node_note_array();
426 if (old_node_note_array != nullptr) {
427 int new_size = (_useful.size() >> 8) + 1; // The node note array uses blocks, see C->_log2_node_notes_block_size
428 new_size = MAX2(8, new_size);
429 C->set_node_note_array(new (C->comp_arena()) GrowableArray<Node_Notes*> (C->comp_arena(), new_size, 0, nullptr));
430 C->grow_node_notes(C->node_note_array(), new_size);
431 }
432
433 assert(worklist.is_subset_of(_useful), "only useful nodes should still be in the worklist");
434
435 // Iterate over the set of live nodes.
436 for (uint current_idx = 0; current_idx < _useful.size(); current_idx++) {
437 Node* n = _useful.at(current_idx);
438
439 const Type* type = gvn->type_or_null(n);
440 _new_type_array.map(current_idx, type);
441
442 assert(_old2new_map.at(n->_idx) == -1, "already seen");
443 _old2new_map.at_put(n->_idx, current_idx);
444
445 if (old_node_note_array != nullptr) {
446 Node_Notes* nn = C->locate_node_notes(old_node_note_array, n->_idx);
447 C->set_node_notes_at(current_idx, nn);
448 }
449
450 n->set_idx(current_idx); // Update node ID.
451
452 if (update_embedded_ids(n) < 0) {
453 _delayed.push(n); // has embedded IDs; handle later
454 }
455 }
456
457 // VectorSet in Unique_Node_Set must be recomputed, since IDs have changed.
458 worklist.recompute_idx_set();
459
460 assert(_live_node_count == _useful.size(), "all live nodes must be processed");
461
462 _is_pass_finished = true; // pass finished; safe to process delayed updates
463
464 while (_delayed.size() > 0) {
465 Node* n = _delayed.pop();
466 int no_of_updates = update_embedded_ids(n);
467 assert(no_of_updates > 0, "should be updated");
468 }
469
470 // Replace the compiler's type information with the updated type information.
471 gvn->types().swap(_new_type_array);
472
473 // Update the unique node count of the compilation to the number of currently live nodes.
474 C->set_unique(_live_node_count);
475
476 // Set the dead node count to 0 and reset dead node list.
477 C->reset_dead_node_list();
478 }
479
480 int PhaseRenumberLive::new_index(int old_idx) {
481 assert(_is_pass_finished, "not finished");
482 if (_old2new_map.at(old_idx) == -1) { // absent
483 // Allocate a placeholder to preserve uniqueness
484 _old2new_map.at_put(old_idx, _live_node_count);
485 _live_node_count++;
486 }
487 return _old2new_map.at(old_idx);
488 }
489
490 int PhaseRenumberLive::update_embedded_ids(Node* n) {
491 int no_of_updates = 0;
492 if (n->is_Phi()) {
493 PhiNode* phi = n->as_Phi();
494 if (phi->_inst_id != -1) {
495 if (!_is_pass_finished) {
496 return -1; // delay
497 }
498 int new_idx = new_index(phi->_inst_id);
499 assert(new_idx != -1, "");
500 phi->_inst_id = new_idx;
501 no_of_updates++;
502 }
503 if (phi->_inst_mem_id != -1) {
504 if (!_is_pass_finished) {
505 return -1; // delay
506 }
507 int new_idx = new_index(phi->_inst_mem_id);
508 assert(new_idx != -1, "");
509 phi->_inst_mem_id = new_idx;
510 no_of_updates++;
511 }
512 }
513
514 const Type* type = _new_type_array.fast_lookup(n->_idx);
515 if (type != nullptr && type->isa_oopptr() && type->is_oopptr()->is_known_instance()) {
516 if (!_is_pass_finished) {
517 return -1; // delay
518 }
519 int old_idx = type->is_oopptr()->instance_id();
520 int new_idx = new_index(old_idx);
521 const Type* new_type = type->is_oopptr()->with_instance_id(new_idx);
522 _new_type_array.map(n->_idx, new_type);
523 no_of_updates++;
524 }
525
526 return no_of_updates;
527 }
528
529 void PhaseValues::init_con_caches() {
530 memset(_icons,0,sizeof(_icons));
531 memset(_lcons,0,sizeof(_lcons));
532 memset(_zcons,0,sizeof(_zcons));
533 }
534
535 PhaseIterGVN* PhaseValues::is_IterGVN() {
536 return (_phase == PhaseValuesType::iter_gvn || _phase == PhaseValuesType::ccp) ? static_cast<PhaseIterGVN*>(this) : nullptr;
537 }
538
539 //--------------------------------find_int_type--------------------------------
540 const TypeInt* PhaseValues::find_int_type(Node* n) {
541 if (n == nullptr) return nullptr;
542 // Call type_or_null(n) to determine node's type since we might be in
543 // parse phase and call n->Value() may return wrong type.
544 // (For example, a phi node at the beginning of loop parsing is not ready.)
545 const Type* t = type_or_null(n);
546 if (t == nullptr) return nullptr;
547 return t->isa_int();
548 }
549
550
551 //-------------------------------find_long_type--------------------------------
552 const TypeLong* PhaseValues::find_long_type(Node* n) {
553 if (n == nullptr) return nullptr;
554 // (See comment above on type_or_null.)
555 const Type* t = type_or_null(n);
556 if (t == nullptr) return nullptr;
557 return t->isa_long();
558 }
559
560 //------------------------------~PhaseValues-----------------------------------
561 #ifndef PRODUCT
562 PhaseValues::~PhaseValues() {
563 // Statistics for NodeHash
564 _table.dump();
565 // Statistics for value progress and efficiency
566 if( PrintCompilation && Verbose && WizardMode ) {
567 tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
568 is_IterGVN() ? "Iter" : " ", C->unique(), made_progress(), made_transforms(), made_new_values());
569 if( made_transforms() != 0 ) {
570 tty->print_cr(" ratio %f", made_progress()/(float)made_transforms() );
571 } else {
572 tty->cr();
573 }
574 }
575 }
576 #endif
577
578 //------------------------------makecon----------------------------------------
579 ConNode* PhaseValues::makecon(const Type* t) {
580 assert(t->singleton(), "must be a constant");
581 assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
582 switch (t->base()) { // fast paths
583 case Type::Half:
584 case Type::Top: return (ConNode*) C->top();
585 case Type::Int: return intcon( t->is_int()->get_con() );
586 case Type::Long: return longcon( t->is_long()->get_con() );
587 default: break;
588 }
589 if (t->is_zero_type())
590 return zerocon(t->basic_type());
591 return uncached_makecon(t);
592 }
593
594 //--------------------------uncached_makecon-----------------------------------
595 // Make an idealized constant - one of ConINode, ConPNode, etc.
596 ConNode* PhaseValues::uncached_makecon(const Type *t) {
597 assert(t->singleton(), "must be a constant");
598 ConNode* x = ConNode::make(t);
599 ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
600 if (k == nullptr) {
601 set_type(x, t); // Missed, provide type mapping
602 GrowableArray<Node_Notes*>* nna = C->node_note_array();
603 if (nna != nullptr) {
604 Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
605 loc->clear(); // do not put debug info on constants
606 }
607 } else {
608 x->destruct(this); // Hit, destroy duplicate constant
609 x = k; // use existing constant
610 }
611 return x;
612 }
613
614 //------------------------------intcon-----------------------------------------
615 // Fast integer constant. Same as "transform(new ConINode(TypeInt::make(i)))"
616 ConINode* PhaseValues::intcon(jint i) {
617 // Small integer? Check cache! Check that cached node is not dead
618 if (i >= _icon_min && i <= _icon_max) {
619 ConINode* icon = _icons[i-_icon_min];
620 if (icon != nullptr && icon->in(TypeFunc::Control) != nullptr)
621 return icon;
622 }
623 ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
624 assert(icon->is_Con(), "");
625 if (i >= _icon_min && i <= _icon_max)
626 _icons[i-_icon_min] = icon; // Cache small integers
627 return icon;
628 }
629
630 //------------------------------longcon----------------------------------------
631 // Fast long constant.
632 ConLNode* PhaseValues::longcon(jlong l) {
633 // Small integer? Check cache! Check that cached node is not dead
634 if (l >= _lcon_min && l <= _lcon_max) {
635 ConLNode* lcon = _lcons[l-_lcon_min];
636 if (lcon != nullptr && lcon->in(TypeFunc::Control) != nullptr)
637 return lcon;
638 }
639 ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
640 assert(lcon->is_Con(), "");
641 if (l >= _lcon_min && l <= _lcon_max)
642 _lcons[l-_lcon_min] = lcon; // Cache small integers
643 return lcon;
644 }
645 ConNode* PhaseValues::integercon(jlong l, BasicType bt) {
646 if (bt == T_INT) {
647 return intcon(checked_cast<jint>(l));
648 }
649 assert(bt == T_LONG, "not an integer");
650 return longcon(l);
651 }
652
653
654 //------------------------------zerocon-----------------------------------------
655 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
656 ConNode* PhaseValues::zerocon(BasicType bt) {
657 assert((uint)bt <= _zcon_max, "domain check");
658 ConNode* zcon = _zcons[bt];
659 if (zcon != nullptr && zcon->in(TypeFunc::Control) != nullptr)
660 return zcon;
661 zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
662 _zcons[bt] = zcon;
663 return zcon;
664 }
665
666
667
668 //=============================================================================
669 Node* PhaseGVN::apply_ideal(Node* k, bool can_reshape) {
670 Node* i = BarrierSet::barrier_set()->barrier_set_c2()->ideal_node(this, k, can_reshape);
671 if (i == nullptr) {
672 i = k->Ideal(this, can_reshape);
673 }
674 return i;
675 }
676
677 //------------------------------transform--------------------------------------
678 // Return a node which computes the same function as this node, but
679 // in a faster or cheaper fashion.
680 Node* PhaseGVN::transform(Node* n) {
681 NOT_PRODUCT( set_transforms(); )
682
683 // Apply the Ideal call in a loop until it no longer applies
684 Node* k = n;
685 Node* i = apply_ideal(k, /*can_reshape=*/false);
686 NOT_PRODUCT(uint loop_count = 1;)
687 while (i != nullptr) {
688 assert(i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
689 k = i;
690 #ifdef ASSERT
691 if (loop_count >= K + C->live_nodes()) {
692 dump_infinite_loop_info(i, "PhaseGVN::transform");
693 }
694 #endif
695 i = apply_ideal(k, /*can_reshape=*/false);
696 NOT_PRODUCT(loop_count++;)
697 }
698 NOT_PRODUCT(if (loop_count != 0) { set_progress(); })
699
700 // If brand new node, make space in type array.
701 ensure_type_or_null(k);
702
703 // Since I just called 'Value' to compute the set of run-time values
704 // for this Node, and 'Value' is non-local (and therefore expensive) I'll
705 // cache Value. Later requests for the local phase->type of this Node can
706 // use the cached Value instead of suffering with 'bottom_type'.
707 const Type* t = k->Value(this); // Get runtime Value set
708 assert(t != nullptr, "value sanity");
709 if (type_or_null(k) != t) {
710 #ifndef PRODUCT
711 // Do not count initial visit to node as a transformation
712 if (type_or_null(k) == nullptr) {
713 inc_new_values();
714 set_progress();
715 }
716 #endif
717 set_type(k, t);
718 // If k is a TypeNode, capture any more-precise type permanently into Node
719 k->raise_bottom_type(t);
720 }
721
722 if (t->singleton() && !k->is_Con()) {
723 NOT_PRODUCT(set_progress();)
724 return makecon(t); // Turn into a constant
725 }
726
727 // Now check for Identities
728 i = k->Identity(this); // Look for a nearby replacement
729 if (i != k) { // Found? Return replacement!
730 NOT_PRODUCT(set_progress();)
731 return i;
732 }
733
734 // Global Value Numbering
735 i = hash_find_insert(k); // Insert if new
736 if (i && (i != k)) {
737 // Return the pre-existing node
738 NOT_PRODUCT(set_progress();)
739 return i;
740 }
741
742 // Return Idealized original
743 return k;
744 }
745
746 bool PhaseGVN::is_dominator_helper(Node *d, Node *n, bool linear_only) {
747 if (d->is_top() || (d->is_Proj() && d->in(0)->is_top())) {
748 return false;
749 }
750 if (n->is_top() || (n->is_Proj() && n->in(0)->is_top())) {
751 return false;
752 }
753 assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
754 int i = 0;
755 while (d != n) {
756 n = IfNode::up_one_dom(n, linear_only);
757 i++;
758 if (n == nullptr || i >= 100) {
759 return false;
760 }
761 }
762 return true;
763 }
764
765 #ifdef ASSERT
766 //------------------------------dead_loop_check--------------------------------
767 // Check for a simple dead loop when a data node references itself directly
768 // or through an other data node excluding cons and phis.
769 void PhaseGVN::dead_loop_check(Node* n) {
770 // Phi may reference itself in a loop.
771 if (n == nullptr || n->is_dead_loop_safe() || n->is_CFG()) {
772 return;
773 }
774
775 // Do 2 levels check and only data inputs.
776 for (uint i = 1; i < n->req(); i++) {
777 Node* in = n->in(i);
778 if (in == n) {
779 n->dump_bfs(100, nullptr, "");
780 fatal("Dead loop detected, node references itself: %s (%d)",
781 n->Name(), n->_idx);
782 }
783
784 if (in == nullptr || in->is_dead_loop_safe()) {
785 continue;
786 }
787 for (uint j = 1; j < in->req(); j++) {
788 if (in->in(j) == n) {
789 n->dump_bfs(100, nullptr, "");
790 fatal("Dead loop detected, node input references current node: %s (%d) -> %s (%d)",
791 in->Name(), in->_idx, n->Name(), n->_idx);
792 }
793 if (in->in(j) == in) {
794 n->dump_bfs(100, nullptr, "");
795 fatal("Dead loop detected, node input references itself: %s (%d)",
796 in->Name(), in->_idx);
797 }
798 }
799 }
800 }
801
802
803 /**
804 * Dumps information that can help to debug the problem. A debug
805 * build fails with an assert.
806 */
807 void PhaseGVN::dump_infinite_loop_info(Node* n, const char* where) {
808 n->dump(4);
809 assert(false, "infinite loop in %s", where);
810 }
811 #endif
812
813 //=============================================================================
814 //------------------------------PhaseIterGVN-----------------------------------
815 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
816 PhaseIterGVN::PhaseIterGVN(PhaseIterGVN* igvn) : _delay_transform(igvn->_delay_transform),
817 _worklist(*C->igvn_worklist())
818 {
819 _phase = PhaseValuesType::iter_gvn;
820 assert(&_worklist == &igvn->_worklist, "sanity");
821 }
822
823 //------------------------------PhaseIterGVN-----------------------------------
824 // Initialize from scratch
825 PhaseIterGVN::PhaseIterGVN() : _delay_transform(false),
826 _worklist(*C->igvn_worklist())
827 {
828 _phase = PhaseValuesType::iter_gvn;
829 uint max;
830
831 // Dead nodes in the hash table inherited from GVN were not treated as
832 // roots during def-use info creation; hence they represent an invisible
833 // use. Clear them out.
834 max = _table.size();
835 for( uint i = 0; i < max; ++i ) {
836 Node *n = _table.at(i);
837 if(n != nullptr && n != _table.sentinel() && n->outcnt() == 0) {
838 if( n->is_top() ) continue;
839 // If remove_useless_nodes() has run, we expect no such nodes left.
840 assert(false, "remove_useless_nodes missed this node");
841 hash_delete(n);
842 }
843 }
844
845 // Any Phis or Regions on the worklist probably had uses that could not
846 // make more progress because the uses were made while the Phis and Regions
847 // were in half-built states. Put all uses of Phis and Regions on worklist.
848 max = _worklist.size();
849 for( uint j = 0; j < max; j++ ) {
850 Node *n = _worklist.at(j);
851 uint uop = n->Opcode();
852 if( uop == Op_Phi || uop == Op_Region ||
853 n->is_Type() ||
854 n->is_Mem() )
855 add_users_to_worklist(n);
856 }
857 }
858
859 void PhaseIterGVN::shuffle_worklist() {
860 if (_worklist.size() < 2) return;
861 for (uint i = _worklist.size() - 1; i >= 1; i--) {
862 uint j = C->random() % (i + 1);
863 swap(_worklist.adr()[i], _worklist.adr()[j]);
864 }
865 }
866
867 #ifndef PRODUCT
868 void PhaseIterGVN::verify_step(Node* n) {
869 if (is_verify_def_use()) {
870 ResourceMark rm;
871 VectorSet visited;
872 Node_List worklist;
873
874 _verify_window[_verify_counter % _verify_window_size] = n;
875 ++_verify_counter;
876 if (C->unique() < 1000 || 0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
877 ++_verify_full_passes;
878 worklist.push(C->root());
879 Node::verify(-1, visited, worklist);
880 return;
881 }
882 for (int i = 0; i < _verify_window_size; i++) {
883 Node* n = _verify_window[i];
884 if (n == nullptr) {
885 continue;
886 }
887 if (n->in(0) == NodeSentinel) { // xform_idom
888 _verify_window[i] = n->in(1);
889 --i;
890 continue;
891 }
892 // Typical fanout is 1-2, so this call visits about 6 nodes.
893 if (!visited.test_set(n->_idx)) {
894 worklist.push(n);
895 }
896 }
897 Node::verify(4, visited, worklist);
898 }
899 }
900
901 void PhaseIterGVN::trace_PhaseIterGVN(Node* n, Node* nn, const Type* oldtype) {
902 const Type* newtype = type_or_null(n);
903 if (nn != n || oldtype != newtype) {
904 C->print_method(PHASE_AFTER_ITER_GVN_STEP, 5, n);
905 }
906 if (TraceIterativeGVN) {
907 uint wlsize = _worklist.size();
908 if (nn != n) {
909 // print old node
910 tty->print("< ");
911 if (oldtype != newtype && oldtype != nullptr) {
912 oldtype->dump();
913 }
914 do { tty->print("\t"); } while (tty->position() < 16);
915 tty->print("<");
916 n->dump();
917 }
918 if (oldtype != newtype || nn != n) {
919 // print new node and/or new type
920 if (oldtype == nullptr) {
921 tty->print("* ");
922 } else if (nn != n) {
923 tty->print("> ");
924 } else {
925 tty->print("= ");
926 }
927 if (newtype == nullptr) {
928 tty->print("null");
929 } else {
930 newtype->dump();
931 }
932 do { tty->print("\t"); } while (tty->position() < 16);
933 nn->dump();
934 }
935 if (Verbose && wlsize < _worklist.size()) {
936 tty->print(" Push {");
937 while (wlsize != _worklist.size()) {
938 Node* pushed = _worklist.at(wlsize++);
939 tty->print(" %d", pushed->_idx);
940 }
941 tty->print_cr(" }");
942 }
943 if (nn != n) {
944 // ignore n, it might be subsumed
945 verify_step((Node*) nullptr);
946 }
947 }
948 }
949
950 void PhaseIterGVN::init_verifyPhaseIterGVN() {
951 _verify_counter = 0;
952 _verify_full_passes = 0;
953 for (int i = 0; i < _verify_window_size; i++) {
954 _verify_window[i] = nullptr;
955 }
956 #ifdef ASSERT
957 // Verify that all modified nodes are on _worklist
958 Unique_Node_List* modified_list = C->modified_nodes();
959 while (modified_list != nullptr && modified_list->size()) {
960 Node* n = modified_list->pop();
961 if (!n->is_Con() && !_worklist.member(n)) {
962 n->dump();
963 fatal("modified node is not on IGVN._worklist");
964 }
965 }
966 #endif
967 }
968
969 void PhaseIterGVN::verify_PhaseIterGVN() {
970 #ifdef ASSERT
971 // Verify nodes with changed inputs.
972 Unique_Node_List* modified_list = C->modified_nodes();
973 while (modified_list != nullptr && modified_list->size()) {
974 Node* n = modified_list->pop();
975 if (!n->is_Con()) { // skip Con nodes
976 n->dump();
977 fatal("modified node was not processed by IGVN.transform_old()");
978 }
979 }
980 #endif
981
982 C->verify_graph_edges();
983 if (is_verify_def_use() && PrintOpto) {
984 if (_verify_counter == _verify_full_passes) {
985 tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
986 (int) _verify_full_passes);
987 } else {
988 tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
989 (int) _verify_counter, (int) _verify_full_passes);
990 }
991 }
992
993 #ifdef ASSERT
994 if (modified_list != nullptr) {
995 while (modified_list->size() > 0) {
996 Node* n = modified_list->pop();
997 n->dump();
998 assert(false, "VerifyIterativeGVN: new modified node was added");
999 }
1000 }
1001
1002 verify_optimize();
1003 #endif
1004 }
1005 #endif /* PRODUCT */
1006
1007 #ifdef ASSERT
1008 /**
1009 * Dumps information that can help to debug the problem. A debug
1010 * build fails with an assert.
1011 */
1012 void PhaseIterGVN::dump_infinite_loop_info(Node* n, const char* where) {
1013 n->dump(4);
1014 _worklist.dump();
1015 assert(false, "infinite loop in %s", where);
1016 }
1017
1018 /**
1019 * Prints out information about IGVN if the 'verbose' option is used.
1020 */
1021 void PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
1022 if (TraceIterativeGVN && Verbose) {
1023 tty->print(" Pop ");
1024 n->dump();
1025 if ((num_processed % 100) == 0) {
1026 _worklist.print_set();
1027 }
1028 }
1029 }
1030 #endif /* ASSERT */
1031
1032 void PhaseIterGVN::optimize() {
1033 DEBUG_ONLY(uint num_processed = 0;)
1034 NOT_PRODUCT(init_verifyPhaseIterGVN();)
1035 NOT_PRODUCT(C->reset_igv_phase_iter(PHASE_AFTER_ITER_GVN_STEP);)
1036 C->print_method(PHASE_BEFORE_ITER_GVN, 3);
1037 if (StressIGVN) {
1038 shuffle_worklist();
1039 }
1040
1041 // The node count check in the loop below (check_node_count) assumes that we
1042 // increase the live node count with at most
1043 // max_live_nodes_increase_per_iteration in between checks. If this
1044 // assumption does not hold, there is a risk that we exceed the max node
1045 // limit in between checks and trigger an assert during node creation.
1046 const int max_live_nodes_increase_per_iteration = NodeLimitFudgeFactor * 5;
1047
1048 uint loop_count = 0;
1049 // Pull from worklist and transform the node. If the node has changed,
1050 // update edge info and put uses on worklist.
1051 while (_worklist.size() > 0) {
1052 if (C->check_node_count(max_live_nodes_increase_per_iteration, "Out of nodes")) {
1053 C->print_method(PHASE_AFTER_ITER_GVN, 3);
1054 return;
1055 }
1056 Node* n = _worklist.pop();
1057 if (loop_count >= K * C->live_nodes()) {
1058 DEBUG_ONLY(dump_infinite_loop_info(n, "PhaseIterGVN::optimize");)
1059 C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1060 C->print_method(PHASE_AFTER_ITER_GVN, 3);
1061 return;
1062 }
1063 DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1064 if (n->outcnt() != 0) {
1065 NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1066 // Do the transformation
1067 DEBUG_ONLY(int live_nodes_before = C->live_nodes();)
1068 Node* nn = transform_old(n);
1069 DEBUG_ONLY(int live_nodes_after = C->live_nodes();)
1070 // Ensure we did not increase the live node count with more than
1071 // max_live_nodes_increase_per_iteration during the call to transform_old
1072 DEBUG_ONLY(int increase = live_nodes_after - live_nodes_before;)
1073 assert(increase < max_live_nodes_increase_per_iteration,
1074 "excessive live node increase in single iteration of IGVN: %d "
1075 "(should be at most %d)",
1076 increase, max_live_nodes_increase_per_iteration);
1077 NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1078 } else if (!n->is_top()) {
1079 remove_dead_node(n);
1080 }
1081 loop_count++;
1082 }
1083 NOT_PRODUCT(verify_PhaseIterGVN();)
1084 C->print_method(PHASE_AFTER_ITER_GVN, 3);
1085 }
1086
1087 #ifdef ASSERT
1088 void PhaseIterGVN::verify_optimize() {
1089 assert(_worklist.size() == 0, "igvn worklist must be empty before verify");
1090
1091 if (is_verify_Value() ||
1092 is_verify_Ideal() ||
1093 is_verify_Identity() ||
1094 is_verify_invariants()) {
1095 ResourceMark rm;
1096 Unique_Node_List worklist;
1097 // BFS all nodes, starting at root
1098 worklist.push(C->root());
1099 for (uint j = 0; j < worklist.size(); ++j) {
1100 Node* n = worklist.at(j);
1101 // If we get an assert here, check why the reported node was not processed again in IGVN.
1102 // We should either make sure that this node is properly added back to the IGVN worklist
1103 // in PhaseIterGVN::add_users_to_worklist to update it again or add an exception
1104 // in the verification methods below if that is not possible for some reason (like Load nodes).
1105 if (is_verify_Value()) {
1106 verify_Value_for(n);
1107 }
1108 if (is_verify_Ideal()) {
1109 verify_Ideal_for(n, false);
1110 verify_Ideal_for(n, true);
1111 }
1112 if (is_verify_Identity()) {
1113 verify_Identity_for(n);
1114 }
1115 if (is_verify_invariants()) {
1116 verify_node_invariants_for(n);
1117 }
1118
1119 // traverse all inputs and outputs
1120 for (uint i = 0; i < n->req(); i++) {
1121 if (n->in(i) != nullptr) {
1122 worklist.push(n->in(i));
1123 }
1124 }
1125 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1126 worklist.push(n->fast_out(i));
1127 }
1128 }
1129 }
1130
1131 verify_empty_worklist(nullptr);
1132 }
1133
1134 void PhaseIterGVN::verify_empty_worklist(Node* node) {
1135 // Verify that the igvn worklist is empty. If no optimization happened, then
1136 // nothing needs to be on the worklist.
1137 if (_worklist.size() == 0) { return; }
1138
1139 stringStream ss; // Print as a block without tty lock.
1140 for (uint j = 0; j < _worklist.size(); j++) {
1141 Node* n = _worklist.at(j);
1142 ss.print("igvn.worklist[%d] ", j);
1143 n->dump("\n", false, &ss);
1144 }
1145 if (_worklist.size() != 0 && node != nullptr) {
1146 ss.print_cr("Previously optimized:");
1147 node->dump("\n", false, &ss);
1148 }
1149 tty->print_cr("%s", ss.as_string());
1150 assert(false, "igvn worklist must still be empty after verify");
1151 }
1152
1153 // Check that type(n) == n->Value(), asserts if we have a failure.
1154 // We have a list of exceptions, see detailed comments in code.
1155 // (1) Integer "widen" changes, but the range is the same.
1156 // (2) LoadNode performs deep traversals. Load is not notified for changes far away.
1157 // (3) CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
1158 void PhaseIterGVN::verify_Value_for(const Node* n, bool strict) {
1159 // If we assert inside type(n), because the type is still a null, then maybe
1160 // the node never went through gvn.transform, which would be a bug.
1161 const Type* told = type(n);
1162 const Type* tnew = n->Value(this);
1163 if (told == tnew) {
1164 return;
1165 }
1166 // Exception (1)
1167 // Integer "widen" changes, but range is the same.
1168 if (told->isa_integer(tnew->basic_type()) != nullptr) { // both either int or long
1169 const TypeInteger* t0 = told->is_integer(tnew->basic_type());
1170 const TypeInteger* t1 = tnew->is_integer(tnew->basic_type());
1171 if (t0->lo_as_long() == t1->lo_as_long() &&
1172 t0->hi_as_long() == t1->hi_as_long()) {
1173 return; // ignore integer widen
1174 }
1175 }
1176 // Exception (2)
1177 // LoadNode performs deep traversals. Load is not notified for changes far away.
1178 if (!strict && n->is_Load() && !told->singleton()) {
1179 // MemNode::can_see_stored_value looks up through many memory nodes,
1180 // which means we would need to notify modifications from far up in
1181 // the inputs all the way down to the LoadNode. We don't do that.
1182 return;
1183 }
1184 // Exception (3)
1185 // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
1186 if (!strict && n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) {
1187 // SubNode::Value
1188 // CmpPNode::sub
1189 // MemNode::detect_ptr_independence
1190 // MemNode::all_controls_dominate
1191 // We find all controls of a pointer load, and see if they dominate the control of
1192 // an allocation. If they all dominate, we know the allocation is after (independent)
1193 // of the pointer load, and we can say the pointers are different. For this we call
1194 // n->dominates(sub, nlist) to check if controls n of the pointer load dominate the
1195 // control sub of the allocation. The problems is that sometimes dominates answers
1196 // false conservatively, and later it can determine that it is indeed true. Loops with
1197 // Region heads can lead to giving up, whereas LoopNodes can be skipped easier, and
1198 // so the traversal becomes more powerful. This is difficult to remedy, we would have
1199 // to notify the CmpP of CFG updates. Luckily, we recompute CmpP::Value during CCP
1200 // after loop-opts, so that should take care of many of these cases.
1201 return;
1202 }
1203
1204 stringStream ss; // Print as a block without tty lock.
1205 ss.cr();
1206 ss.print_cr("Missed Value optimization:");
1207 n->dump_bfs(3, nullptr, "", &ss);
1208 ss.print_cr("Current type:");
1209 told->dump_on(&ss);
1210 ss.cr();
1211 ss.print_cr("Optimized type:");
1212 tnew->dump_on(&ss);
1213 ss.cr();
1214 tty->print_cr("%s", ss.as_string());
1215
1216 switch (_phase) {
1217 case PhaseValuesType::iter_gvn:
1218 assert(false, "Missed Value optimization opportunity in PhaseIterGVN for %s",n->Name());
1219 break;
1220 case PhaseValuesType::ccp:
1221 assert(false, "PhaseCCP not at fixpoint: analysis result may be unsound for %s", n->Name());
1222 break;
1223 default:
1224 assert(false, "Unexpected phase");
1225 break;
1226 }
1227 }
1228
1229 // Check that all Ideal optimizations that could be done were done.
1230 // Asserts if it found missed optimization opportunities or encountered unexpected changes, and
1231 // returns normally otherwise (no missed optimization, or skipped verification).
1232 void PhaseIterGVN::verify_Ideal_for(Node* n, bool can_reshape) {
1233 // First, we check a list of exceptions, where we skip verification,
1234 // because there are known cases where Ideal can optimize after IGVN.
1235 // Some may be expected and cannot be fixed, and others should be fixed.
1236 switch (n->Opcode()) {
1237 // RangeCheckNode::Ideal looks up the chain for about 999 nodes
1238 // (see "Range-Check scan limit"). So, it is possible that something
1239 // is optimized in that input subgraph, and the RangeCheck was not
1240 // added to the worklist because it would be too expensive to walk
1241 // down the graph for 1000 nodes and put all on the worklist.
1242 //
1243 // Found with:
1244 // java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1245 case Op_RangeCheck:
1246 return;
1247
1248 // IfNode::Ideal does:
1249 // Node* prev_dom = search_identical(dist, igvn);
1250 // which means we seach up the CFG, traversing at most up to a distance.
1251 // If anything happens rather far away from the If, we may not put the If
1252 // back on the worklist.
1253 //
1254 // Found with:
1255 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1256 case Op_If:
1257 return;
1258
1259 // IfNode::simple_subsuming
1260 // Looks for dominating test that subsumes the current test.
1261 // Notification could be difficult because of larger distance.
1262 //
1263 // Found with:
1264 // runtime/exceptionMsgs/ArrayIndexOutOfBoundsException/ArrayIndexOutOfBoundsExceptionTest.java#id1
1265 // -XX:VerifyIterativeGVN=1110
1266 case Op_CountedLoopEnd:
1267 return;
1268
1269 // LongCountedLoopEndNode::Ideal
1270 // Probably same issue as above.
1271 //
1272 // Found with:
1273 // compiler/predicates/assertion/TestAssertionPredicates.java#NoLoopPredicationXbatch
1274 // -XX:StressLongCountedLoop=2000000 -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1275 case Op_LongCountedLoopEnd:
1276 return;
1277
1278 // RegionNode::Ideal does "Skip around the useless IF diamond".
1279 // 245 IfTrue === 244
1280 // 258 If === 245 257
1281 // 259 IfTrue === 258 [[ 263 ]]
1282 // 260 IfFalse === 258 [[ 263 ]]
1283 // 263 Region === 263 260 259 [[ 263 268 ]]
1284 // to
1285 // 245 IfTrue === 244
1286 // 263 Region === 263 245 _ [[ 263 268 ]]
1287 //
1288 // "Useless" means that there is no code in either branch of the If.
1289 // I found a case where this was not done yet during IGVN.
1290 // Why does the Region not get added to IGVN worklist when the If diamond becomes useless?
1291 //
1292 // Found with:
1293 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1294 case Op_Region:
1295 return;
1296
1297 // In AddNode::Ideal, we call "commute", which swaps the inputs so
1298 // that smaller idx are first. Tracking it back, it led me to
1299 // PhaseIdealLoop::remix_address_expressions which swapped the edges.
1300 //
1301 // Example:
1302 // Before PhaseIdealLoop::remix_address_expressions
1303 // 154 AddI === _ 12 144
1304 // After PhaseIdealLoop::remix_address_expressions
1305 // 154 AddI === _ 144 12
1306 // After AddNode::Ideal
1307 // 154 AddI === _ 12 144
1308 //
1309 // I suspect that the node should be added to the IGVN worklist after
1310 // PhaseIdealLoop::remix_address_expressions
1311 //
1312 // This is the only case I looked at, there may be others. Found like this:
1313 // java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1314 //
1315 // The following hit the same logic in PhaseIdealLoop::remix_address_expressions.
1316 //
1317 // Note: currently all of these fail also for other reasons, for example
1318 // because of "commute" doing the reordering with the phi below. Once
1319 // that is resolved, we can come back to this issue here.
1320 //
1321 // case Op_AddD:
1322 // case Op_AddI:
1323 // case Op_AddL:
1324 // case Op_AddF:
1325 // case Op_MulI:
1326 // case Op_MulL:
1327 // case Op_MulF:
1328 // case Op_MulD:
1329 // if (n->in(1)->_idx > n->in(2)->_idx) {
1330 // // Expect "commute" to revert this case.
1331 // return false;
1332 // }
1333 // break; // keep verifying
1334
1335 // AddFNode::Ideal calls "commute", which can reorder the inputs for this:
1336 // Check for tight loop increments: Loop-phi of Add of loop-phi
1337 // It wants to take the phi into in(1):
1338 // 471 Phi === 435 38 390
1339 // 390 AddF === _ 471 391
1340 //
1341 // Other Associative operators are also affected equally.
1342 //
1343 // Investigate why this does not happen earlier during IGVN.
1344 //
1345 // Found with:
1346 // test/hotspot/jtreg/compiler/loopopts/superword/ReductionPerf.java
1347 // -XX:VerifyIterativeGVN=1110
1348 case Op_AddD:
1349 //case Op_AddI: // Also affected for other reasons, see case further down.
1350 //case Op_AddL: // Also affected for other reasons, see case further down.
1351 case Op_AddF:
1352 case Op_MulI:
1353 case Op_MulL:
1354 case Op_MulF:
1355 case Op_MulD:
1356 case Op_MinF:
1357 case Op_MinD:
1358 case Op_MaxF:
1359 case Op_MaxD:
1360 // XorINode::Ideal
1361 // Found with:
1362 // compiler/intrinsics/chacha/TestChaCha20.java
1363 // -XX:VerifyIterativeGVN=1110
1364 case Op_XorI:
1365 case Op_XorL:
1366 // It seems we may have similar issues with the HF cases.
1367 // Found with aarch64:
1368 // compiler/vectorization/TestFloat16VectorOperations.java
1369 // -XX:VerifyIterativeGVN=1110
1370 case Op_AddHF:
1371 case Op_MulHF:
1372 case Op_MaxHF:
1373 case Op_MinHF:
1374 return;
1375
1376 // In MulNode::Ideal the edges can be swapped to help value numbering:
1377 //
1378 // // We are OK if right is a constant, or right is a load and
1379 // // left is a non-constant.
1380 // if( !(t2->singleton() ||
1381 // (in(2)->is_Load() && !(t1->singleton() || in(1)->is_Load())) ) ) {
1382 // if( t1->singleton() || // Left input is a constant?
1383 // // Otherwise, sort inputs (commutativity) to help value numbering.
1384 // (in(1)->_idx > in(2)->_idx) ) {
1385 // swap_edges(1, 2);
1386 //
1387 // Why was this not done earlier during IGVN?
1388 //
1389 // Found with:
1390 // test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithG1.java
1391 // -XX:VerifyIterativeGVN=1110
1392 case Op_AndI:
1393 // Same for AndL.
1394 // Found with:
1395 // compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java
1396 // -XX:VerifyIterativeGVN=1110
1397 case Op_AndL:
1398 return;
1399
1400 // SubLNode::Ideal does transform like:
1401 // Convert "c1 - (y+c0)" into "(c1-c0) - y"
1402 //
1403 // In IGVN before verification:
1404 // 8423 ConvI2L === _ 3519 [[ 8424 ]] #long:-2
1405 // 8422 ConvI2L === _ 8399 [[ 8424 ]] #long:3..256:www
1406 // 8424 AddL === _ 8422 8423 [[ 8383 ]] !orig=[8382]
1407 // 8016 ConL === 0 [[ 8383 ]] #long:0
1408 // 8383 SubL === _ 8016 8424 [[ 8156 ]] !orig=[8154]
1409 //
1410 // And then in verification:
1411 // 8338 ConL === 0 [[ 8339 8424 ]] #long:-2 <----- Was constant folded.
1412 // 8422 ConvI2L === _ 8399 [[ 8424 ]] #long:3..256:www
1413 // 8424 AddL === _ 8422 8338 [[ 8383 ]] !orig=[8382]
1414 // 8016 ConL === 0 [[ 8383 ]] #long:0
1415 // 8383 SubL === _ 8016 8424 [[ 8156 ]] !orig=[8154]
1416 //
1417 // So the form changed from:
1418 // c1 - (y + [8423 ConvI2L])
1419 // to
1420 // c1 - (y + -2)
1421 // but the SubL was not added to the IGVN worklist. Investigate why.
1422 // There could be other issues too.
1423 //
1424 // There seems to be a related AddL IGVN optimization that triggers
1425 // the same SubL optimization, so investigate that too.
1426 //
1427 // Found with:
1428 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1429 case Op_SubL:
1430 return;
1431
1432 // SubINode::Ideal does
1433 // Convert "x - (y+c0)" into "(x-y) - c0" AND
1434 // Convert "c1 - (y+c0)" into "(c1-c0) - y"
1435 //
1436 // Investigate why this does not yet happen during IGVN.
1437 //
1438 // Found with:
1439 // test/hotspot/jtreg/compiler/c2/IVTest.java
1440 // -XX:VerifyIterativeGVN=1110
1441 case Op_SubI:
1442 return;
1443
1444 // AddNode::IdealIL does transform like:
1445 // Convert x + (con - y) into "(x - y) + con"
1446 //
1447 // In IGVN before verification:
1448 // 8382 ConvI2L
1449 // 8381 ConvI2L === _ 791 [[ 8383 ]] #long:0
1450 // 8383 SubL === _ 8381 8382
1451 // 8168 ConvI2L
1452 // 8156 AddL === _ 8168 8383 [[ 8158 ]]
1453 //
1454 // And then in verification:
1455 // 8424 AddL
1456 // 8016 ConL === 0 [[ 8383 ]] #long:0 <--- Was constant folded.
1457 // 8383 SubL === _ 8016 8424
1458 // 8168 ConvI2L
1459 // 8156 AddL === _ 8168 8383 [[ 8158 ]]
1460 //
1461 // So the form changed from:
1462 // x + (ConvI2L(0) - [8382 ConvI2L])
1463 // to
1464 // x + (0 - [8424 AddL])
1465 // but the AddL was not added to the IGVN worklist. Investigate why.
1466 // There could be other issues, too. For example with "commute", see above.
1467 //
1468 // Found with:
1469 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1470 case Op_AddL:
1471 return;
1472
1473 // SubTypeCheckNode::Ideal calls SubTypeCheckNode::verify_helper, which does
1474 // Node* cmp = phase->transform(new CmpPNode(subklass, in(SuperKlass)));
1475 // record_for_cleanup(cmp, phase);
1476 // This verification code in the Ideal code creates new nodes, and checks
1477 // if they fold in unexpected ways. This means some nodes are created and
1478 // added to the worklist, even if the SubTypeCheck is not optimized. This
1479 // goes agains the assumption of the verification here, which assumes that
1480 // if the node is not optimized, then no new nodes should be created, and
1481 // also no nodes should be added to the worklist.
1482 // I see two options:
1483 // 1) forbid what verify_helper does, because for each Ideal call it
1484 // uses memory and that is suboptimal. But it is not clear how that
1485 // verification can be done otherwise.
1486 // 2) Special case the verification here. Probably the new nodes that
1487 // were just created are dead, i.e. they are not connected down to
1488 // root. We could verify that, and remove those nodes from the graph
1489 // by setting all their inputs to nullptr. And of course we would
1490 // have to remove those nodes from the worklist.
1491 // Maybe there are other options too, I did not dig much deeper yet.
1492 //
1493 // Found with:
1494 // java -XX:VerifyIterativeGVN=0100 -Xbatch --version
1495 case Op_SubTypeCheck:
1496 return;
1497
1498 // LoopLimitNode::Ideal when stride is constant power-of-2, we can do a lowering
1499 // to other nodes: Conv, Add, Sub, Mul, And ...
1500 //
1501 // 107 ConI === 0 [[ ... ]] #int:2
1502 // 84 LoadRange === _ 7 83
1503 // 50 ConI === 0 [[ ... ]] #int:0
1504 // 549 LoopLimit === _ 50 84 107
1505 //
1506 // I stepped backward, to see how the node was generated, and I found that it was
1507 // created in PhaseIdealLoop::exact_limit and not changed since. It is added to the
1508 // IGVN worklist. I quickly checked when it goes into LoopLimitNode::Ideal after
1509 // that, and it seems we want to skip lowering it until after loop-opts, but never
1510 // add call record_for_post_loop_opts_igvn. This would be an easy fix, but there
1511 // could be other issues too.
1512 //
1513 // Fond with:
1514 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1515 case Op_LoopLimit:
1516 return;
1517
1518 // PhiNode::Ideal calls split_flow_path, which tries to do this:
1519 // "This optimization tries to find two or more inputs of phi with the same constant
1520 // value. It then splits them into a separate Phi, and according Region."
1521 //
1522 // Example:
1523 // 130 DecodeN === _ 129
1524 // 50 ConP === 0 [[ 18 91 99 18 ]] #null
1525 // 18 Phi === 14 50 130 50 [[ 133 ]] #java/lang/Object * Oop:java/lang/Object *
1526 //
1527 // turns into:
1528 //
1529 // 50 ConP === 0 [[ 99 91 18 ]] #null
1530 // 130 DecodeN === _ 129 [[ 18 ]]
1531 // 18 Phi === 14 130 50 [[ 133 ]] #java/lang/Object * Oop:java/lang/Object *
1532 //
1533 // We would have to investigate why this optimization does not happen during IGVN.
1534 // There could also be other issues - I did not investigate further yet.
1535 //
1536 // Found with:
1537 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1538 case Op_Phi:
1539 return;
1540
1541 // MemBarNode::Ideal does "Eliminate volatile MemBars for scalar replaced objects".
1542 // For examle "The allocated object does not escape".
1543 //
1544 // It seems the difference to earlier calls to MemBarNode::Ideal, is that there
1545 // alloc->as_Allocate()->does_not_escape_thread() returned false, but in verification
1546 // it returned true. Why does the MemBarStoreStore not get added to the IGVN
1547 // worklist when this change happens?
1548 //
1549 // Found with:
1550 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1551 case Op_MemBarStoreStore:
1552 return;
1553
1554 // ConvI2LNode::Ideal converts
1555 // 648 AddI === _ 583 645 [[ 661 ]]
1556 // 661 ConvI2L === _ 648 [[ 664 ]] #long:0..maxint-1:www
1557 // into
1558 // 772 ConvI2L === _ 645 [[ 773 ]] #long:-120..maxint-61:www
1559 // 771 ConvI2L === _ 583 [[ 773 ]] #long:60..120:www
1560 // 773 AddL === _ 771 772 [[ ]]
1561 //
1562 // We have to investigate why this does not happen during IGVN in this case.
1563 // There could also be other issues - I did not investigate further yet.
1564 //
1565 // Found with:
1566 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1567 case Op_ConvI2L:
1568 return;
1569
1570 // AddNode::IdealIL can do this transform (and similar other ones):
1571 // Convert "a*b+a*c into a*(b+c)
1572 // The example had AddI(MulI(a, b), MulI(a, c)). Why did this not happen
1573 // during IGVN? There was a mutation for one of the MulI, and only
1574 // after that the pattern was as needed for the optimization. The MulI
1575 // was added to the IGVN worklist, but not the AddI. This probably
1576 // can be fixed by adding the correct pattern in add_users_of_use_to_worklist.
1577 //
1578 // Found with:
1579 // test/hotspot/jtreg/compiler/loopopts/superword/ReductionPerf.java
1580 // -XX:VerifyIterativeGVN=1110
1581 case Op_AddI:
1582 return;
1583
1584 // ArrayCopyNode::Ideal
1585 // calls ArrayCopyNode::prepare_array_copy
1586 // calls Compile::conv_I2X_index -> is called with sizetype = intcon(0), I think that
1587 // is not expected, and we create a range int:0..-1
1588 // calls Compile::constrained_convI2L -> creates ConvI2L(intcon(1), int:0..-1)
1589 // note: the type is already empty!
1590 // calls PhaseIterGVN::transform
1591 // calls PhaseIterGVN::transform_old
1592 // calls PhaseIterGVN::subsume_node -> subsume ConvI2L with TOP
1593 // calls Unique_Node_List::push -> pushes TOP to worklist
1594 //
1595 // Once we get back to ArrayCopyNode::prepare_array_copy, we get back TOP, and
1596 // return false. This means we eventually return nullptr from ArrayCopyNode::Ideal.
1597 //
1598 // Question: is it ok to push anything to the worklist during ::Ideal, if we will
1599 // return nullptr, indicating nothing happened?
1600 // Is it smart to do transform in Compile::constrained_convI2L, and then
1601 // check for TOP in calls ArrayCopyNode::prepare_array_copy?
1602 // Should we just allow TOP to land on the worklist, as an exception?
1603 //
1604 // Found with:
1605 // compiler/arraycopy/TestArrayCopyAsLoadsStores.java
1606 // -XX:VerifyIterativeGVN=1110
1607 case Op_ArrayCopy:
1608 return;
1609
1610 // CastLLNode::Ideal
1611 // calls ConstraintCastNode::optimize_integer_cast -> pushes CastLL through SubL
1612 //
1613 // Could be a notification issue, where updates inputs of CastLL do not notify
1614 // down through SubL to CastLL.
1615 //
1616 // Found With:
1617 // compiler/c2/TestMergeStoresMemorySegment.java#byte-array
1618 // -XX:VerifyIterativeGVN=1110
1619 case Op_CastLL:
1620 return;
1621
1622 // Similar case happens to CastII
1623 //
1624 // Found With:
1625 // compiler/c2/TestScalarReplacementMaxLiveNodes.java
1626 // -XX:VerifyIterativeGVN=1110
1627 case Op_CastII:
1628 return;
1629
1630 // MaxLNode::Ideal
1631 // calls AddNode::Ideal
1632 // calls commute -> decides to swap edges
1633 //
1634 // Another notification issue, because we check inputs of inputs?
1635 // MaxL -> Phi -> Loop
1636 // MaxL -> Phi -> MaxL
1637 //
1638 // Found with:
1639 // compiler/c2/irTests/TestIfMinMax.java
1640 // -XX:VerifyIterativeGVN=1110
1641 case Op_MaxL:
1642 case Op_MinL:
1643 return;
1644
1645 // OrINode::Ideal
1646 // calls AddNode::Ideal
1647 // calls commute -> left is Load, right not -> commute.
1648 //
1649 // Not sure why notification does not work here, seems like
1650 // the depth is only 1, so it should work. Needs investigation.
1651 //
1652 // Found with:
1653 // compiler/codegen/TestCharVect2.java#id0
1654 // -XX:VerifyIterativeGVN=1110
1655 case Op_OrI:
1656 case Op_OrL:
1657 return;
1658
1659 // Bool -> constant folded to 1.
1660 // Issue with notification?
1661 //
1662 // Found with:
1663 // compiler/c2/irTests/TestVectorizationMismatchedAccess.java
1664 // -XX:VerifyIterativeGVN=1110
1665 case Op_Bool:
1666 return;
1667
1668 // LShiftLNode::Ideal
1669 // Looks at pattern: "(x + x) << c0", converts it to "x << (c0 + 1)"
1670 // Probably a notification issue.
1671 //
1672 // Found with:
1673 // compiler/conversions/TestMoveConvI2LOrCastIIThruAddIs.java
1674 // -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1675 case Op_LShiftL:
1676 return;
1677
1678 // LShiftINode::Ideal
1679 // pattern: ((x + con1) << con2) -> x << con2 + con1 << con2
1680 // Could be issue with notification of inputs of inputs
1681 //
1682 // Side-note: should cases like these not be shared between
1683 // LShiftI and LShiftL?
1684 //
1685 // Found with:
1686 // compiler/escapeAnalysis/Test6689060.java
1687 // -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110 -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1688 case Op_LShiftI:
1689 return;
1690
1691 // AddPNode::Ideal seems to do set_req without removing lock first.
1692 // Found with various vector tests tier1-tier3.
1693 case Op_AddP:
1694 return;
1695
1696 // StrIndexOfNode::Ideal
1697 // Found in tier1-3.
1698 case Op_StrIndexOf:
1699 case Op_StrIndexOfChar:
1700 return;
1701
1702 // StrEqualsNode::Identity
1703 //
1704 // Found (linux x64 only?) with:
1705 // serviceability/sa/ClhsdbThreadContext.java
1706 // -XX:+UnlockExperimentalVMOptions -XX:LockingMode=1 -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1707 // Note: The -XX:LockingMode option is not available anymore.
1708 case Op_StrEquals:
1709 return;
1710
1711 // AryEqNode::Ideal
1712 // Not investigated. Reshapes itself and adds lots of nodes to the worklist.
1713 //
1714 // Found with:
1715 // vmTestbase/vm/mlvm/meth/stress/compiler/i2c_c2i/Test.java
1716 // -XX:+UnlockDiagnosticVMOptions -XX:-TieredCompilation -XX:+StressUnstableIfTraps -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1717 case Op_AryEq:
1718 return;
1719
1720 // MergeMemNode::Ideal
1721 // Found in tier1-3. Did not investigate further yet.
1722 case Op_MergeMem:
1723 return;
1724
1725 // CMoveINode::Ideal
1726 // Found in tier1-3. Did not investigate further yet.
1727 case Op_CMoveI:
1728 return;
1729
1730 // CmpPNode::Ideal calls isa_const_java_mirror
1731 // and generates new constant nodes, even if no progress is made.
1732 // We can probably rewrite this so that only types are generated.
1733 // It seems that object types are not hashed, we could investigate
1734 // if that is an option as well.
1735 //
1736 // Found with:
1737 // java -XX:VerifyIterativeGVN=1110 -Xcomp --version
1738 case Op_CmpP:
1739 return;
1740
1741 // MinINode::Ideal
1742 // Did not investigate, but there are some patterns that might
1743 // need more notification.
1744 case Op_MinI:
1745 case Op_MaxI: // preemptively removed it as well.
1746 return;
1747 }
1748
1749 if (n->is_Load()) {
1750 // LoadNode::Ideal uses tries to find an earlier memory state, and
1751 // checks can_see_stored_value for it.
1752 //
1753 // Investigate why this was not already done during IGVN.
1754 // A similar issue happens with Identity.
1755 //
1756 // There seem to be other cases where loads go up some steps, like
1757 // LoadNode::Ideal going up 10x steps to find dominating load.
1758 //
1759 // Found with:
1760 // test/hotspot/jtreg/compiler/arraycopy/TestCloneAccess.java
1761 // -XX:VerifyIterativeGVN=1110
1762 return;
1763 }
1764
1765 if (n->is_Store()) {
1766 // StoreNode::Ideal can do this:
1767 // // Capture an unaliased, unconditional, simple store into an initializer.
1768 // // Or, if it is independent of the allocation, hoist it above the allocation.
1769 // That replaces the Store with a MergeMem.
1770 //
1771 // We have to investigate why this does not happen during IGVN in this case.
1772 // There could also be other issues - I did not investigate further yet.
1773 //
1774 // Found with:
1775 // java -XX:VerifyIterativeGVN=0100 -Xcomp --version
1776 return;
1777 }
1778
1779 if (n->is_Vector()) {
1780 // VectorNode::Ideal swaps edges, but only for ops
1781 // that are deemed commutable. But swap_edges
1782 // requires the hash to be invariant when the edges
1783 // are swapped, which is not implemented for these
1784 // vector nodes. This seems not to create any trouble
1785 // usually, but we can also get graphs where in the
1786 // end the nodes are not all commuted, so there is
1787 // definitively an issue here.
1788 //
1789 // Probably we have two options: kill the hash, or
1790 // properly make the hash commutation friendly.
1791 //
1792 // Found with:
1793 // compiler/vectorapi/TestMaskedMacroLogicVector.java
1794 // -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110 -XX:+UseParallelGC -XX:+UseNUMA
1795 return;
1796 }
1797
1798 if (n->is_Region()) {
1799 // LoopNode::Ideal calls RegionNode::Ideal.
1800 // CountedLoopNode::Ideal calls RegionNode::Ideal too.
1801 // But I got an issue because RegionNode::optimize_trichotomy
1802 // then modifies another node, and pushes nodes to the worklist
1803 // Not sure if this is ok, modifying another node like that.
1804 // Maybe it is, then we need to look into what to do with
1805 // the nodes that are now on the worklist, maybe just clear
1806 // them out again. But maybe modifying other nodes like that
1807 // is also bad design. In the end, we return nullptr for
1808 // the current CountedLoop. But the extra nodes on the worklist
1809 // trip the asserts later on.
1810 //
1811 // Found with:
1812 // compiler/eliminateAutobox/TestShortBoxing.java
1813 // -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1814 return;
1815 }
1816
1817 if (n->is_CallJava()) {
1818 // CallStaticJavaNode::Ideal
1819 // Led to a crash:
1820 // assert((is_CallStaticJava() && cg->is_mh_late_inline()) || (is_CallDynamicJava() && cg->is_virtual_late_inline())) failed: mismatch
1821 //
1822 // Did not investigate yet, could be a bug.
1823 // Or maybe it does not expect to be called during verification.
1824 //
1825 // Found with:
1826 // test/jdk/jdk/incubator/vector/VectorRuns.java
1827 // -XX:VerifyIterativeGVN=1110
1828
1829 // CallDynamicJavaNode::Ideal, and I think also for CallStaticJavaNode::Ideal
1830 // and possibly their subclasses.
1831 // During late inlining it can call CallJavaNode::register_for_late_inline
1832 // That means we do more rounds of late inlining, but might fail.
1833 // Then we do IGVN again, and register the node again for late inlining.
1834 // This creates an endless cycle. Everytime we try late inlining, we
1835 // are also creating more nodes, especially SafePoint and MergeMem.
1836 // These nodes are immediately rejected when the inlining fails in the
1837 // do_late_inline_check, but they still grow the memory, until we hit
1838 // the MemLimit and crash.
1839 // The assumption here seems that CallDynamicJavaNode::Ideal does not get
1840 // called repeatedly, and eventually we terminate. I fear this is not
1841 // a great assumption to make. We should investigate more.
1842 //
1843 // Found with:
1844 // compiler/loopopts/superword/TestDependencyOffsets.java#vanilla-U
1845 // -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
1846 return;
1847 }
1848
1849 // The number of nodes shoud not increase.
1850 uint old_unique = C->unique();
1851 // The hash of a node should not change, this would indicate different inputs
1852 uint old_hash = n->hash();
1853 // Remove 'n' from hash table in case it gets modified. We want to avoid
1854 // hitting the "Need to remove from hash before changing edges" assert if
1855 // a change occurs. Instead, we would like to proceed with the optimization,
1856 // return and finally hit the assert in PhaseIterGVN::verify_optimize to get
1857 // a more meaningful message
1858 _table.hash_delete(n);
1859 Node* i = n->Ideal(this, can_reshape);
1860 // If there was no new Idealization, we are probably happy.
1861 if (i == nullptr) {
1862 if (old_unique < C->unique()) {
1863 stringStream ss; // Print as a block without tty lock.
1864 ss.cr();
1865 ss.print_cr("Ideal optimization did not make progress but created new unused nodes.");
1866 ss.print_cr(" old_unique = %d, unique = %d", old_unique, C->unique());
1867 n->dump_bfs(1, nullptr, "", &ss);
1868 tty->print_cr("%s", ss.as_string());
1869 assert(false, "Unexpected new unused nodes from applying Ideal optimization on %s", n->Name());
1870 }
1871
1872 if (old_hash != n->hash()) {
1873 stringStream ss; // Print as a block without tty lock.
1874 ss.cr();
1875 ss.print_cr("Ideal optimization did not make progress but node hash changed.");
1876 ss.print_cr(" old_hash = %d, hash = %d", old_hash, n->hash());
1877 n->dump_bfs(1, nullptr, "", &ss);
1878 tty->print_cr("%s", ss.as_string());
1879 assert(false, "Unexpected hash change from applying Ideal optimization on %s", n->Name());
1880 }
1881
1882 verify_empty_worklist(n);
1883
1884 // Everything is good.
1885 hash_find_insert(n);
1886 return;
1887 }
1888
1889 // We just saw a new Idealization which was not done during IGVN.
1890 stringStream ss; // Print as a block without tty lock.
1891 ss.cr();
1892 ss.print_cr("Missed Ideal optimization (can_reshape=%s):", can_reshape ? "true": "false");
1893 if (i == n) {
1894 ss.print_cr("The node was reshaped by Ideal.");
1895 } else {
1896 ss.print_cr("The node was replaced by Ideal.");
1897 ss.print_cr("Old node:");
1898 n->dump_bfs(1, nullptr, "", &ss);
1899 }
1900 ss.print_cr("The result after Ideal:");
1901 i->dump_bfs(1, nullptr, "", &ss);
1902 tty->print_cr("%s", ss.as_string());
1903
1904 assert(false, "Missed Ideal optimization opportunity in PhaseIterGVN for %s", n->Name());
1905 }
1906
1907 // Check that all Identity optimizations that could be done were done.
1908 // Asserts if it found missed optimization opportunities, and
1909 // returns normally otherwise (no missed optimization, or skipped verification).
1910 void PhaseIterGVN::verify_Identity_for(Node* n) {
1911 // First, we check a list of exceptions, where we skip verification,
1912 // because there are known cases where Ideal can optimize after IGVN.
1913 // Some may be expected and cannot be fixed, and others should be fixed.
1914 switch (n->Opcode()) {
1915 // SafePointNode::Identity can remove SafePoints, but wants to wait until
1916 // after loopopts:
1917 // // Transforming long counted loops requires a safepoint node. Do not
1918 // // eliminate a safepoint until loop opts are over.
1919 // if (in(0)->is_Proj() && !phase->C->major_progress()) {
1920 //
1921 // I think the check for major_progress does delay it until after loopopts
1922 // but it does not ensure that the node is on the IGVN worklist after
1923 // loopopts. I think we should try to instead check for
1924 // phase->C->post_loop_opts_phase() and call record_for_post_loop_opts_igvn.
1925 //
1926 // Found with:
1927 // java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1928 case Op_SafePoint:
1929 return;
1930
1931 // MergeMemNode::Identity replaces the MergeMem with its base_memory if it
1932 // does not record any other memory splits.
1933 //
1934 // I did not deeply investigate, but it looks like MergeMemNode::Identity
1935 // never got called during IGVN for this node, investigate why.
1936 //
1937 // Found with:
1938 // java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1939 case Op_MergeMem:
1940 return;
1941
1942 // ConstraintCastNode::Identity finds casts that are the same, except that
1943 // the control is "higher up", i.e. dominates. The call goes via
1944 // ConstraintCastNode::dominating_cast to PhaseGVN::is_dominator_helper,
1945 // which traverses up to 100 idom steps. If anything gets optimized somewhere
1946 // away from the cast, but within 100 idom steps, the cast may not be
1947 // put on the IGVN worklist any more.
1948 //
1949 // Found with:
1950 // java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1951 case Op_CastPP:
1952 case Op_CastII:
1953 case Op_CastLL:
1954 return;
1955
1956 // Same issue for CheckCastPP, uses ConstraintCastNode::Identity and
1957 // checks dominator, which may be changed, but too far up for notification
1958 // to work.
1959 //
1960 // Found with:
1961 // compiler/c2/irTests/TestSkeletonPredicates.java
1962 // -XX:VerifyIterativeGVN=1110
1963 case Op_CheckCastPP:
1964 return;
1965
1966 // In SubNode::Identity, we do:
1967 // Convert "(X+Y) - Y" into X and "(X+Y) - X" into Y
1968 // In the example, the AddI had an input replaced, the AddI is
1969 // added to the IGVN worklist, but the SubI is one link further
1970 // down and is not added. I checked add_users_of_use_to_worklist
1971 // where I would expect the SubI would be added, and I cannot
1972 // find the pattern, only this one:
1973 // If changed AddI/SubI inputs, check CmpU for range check optimization.
1974 //
1975 // Fix this "notification" issue and check if there are any other
1976 // issues.
1977 //
1978 // Found with:
1979 // java -XX:VerifyIterativeGVN=1000 -Xcomp --version
1980 case Op_SubI:
1981 case Op_SubL:
1982 return;
1983
1984 // PhiNode::Identity checks for patterns like:
1985 // r = (x != con) ? x : con;
1986 // that can be constant folded to "x".
1987 //
1988 // Call goes through PhiNode::is_cmove_id and CMoveNode::is_cmove_id.
1989 // I suspect there was some earlier change to one of the inputs, but
1990 // not all relevant outputs were put on the IGVN worklist.
1991 //
1992 // Found with:
1993 // test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithG1.java
1994 // -XX:VerifyIterativeGVN=1110
1995 case Op_Phi:
1996 return;
1997
1998 // ConvI2LNode::Identity does
1999 // convert I2L(L2I(x)) => x
2000 //
2001 // Investigate why this did not already happen during IGVN.
2002 //
2003 // Found with:
2004 // compiler/loopopts/superword/TestDependencyOffsets.java#vanilla-A
2005 // -XX:VerifyIterativeGVN=1110
2006 case Op_ConvI2L:
2007 return;
2008
2009 // MaxNode::find_identity_operation
2010 // Finds patterns like Max(A, Max(A, B)) -> Max(A, B)
2011 // This can be a 2-hop search, so maybe notification is not
2012 // good enough.
2013 //
2014 // Found with:
2015 // compiler/codegen/TestBooleanVect.java
2016 // -XX:VerifyIterativeGVN=1110
2017 case Op_MaxL:
2018 case Op_MinL:
2019 case Op_MaxI:
2020 case Op_MinI:
2021 case Op_MaxF:
2022 case Op_MinF:
2023 case Op_MaxHF:
2024 case Op_MinHF:
2025 case Op_MaxD:
2026 case Op_MinD:
2027 return;
2028
2029
2030 // AddINode::Identity
2031 // Converts (x-y)+y to x
2032 // Could be issue with notification
2033 //
2034 // Turns out AddL does the same.
2035 //
2036 // Found with:
2037 // compiler/c2/Test6792161.java
2038 // -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
2039 case Op_AddI:
2040 case Op_AddL:
2041 return;
2042
2043 // AbsINode::Identity
2044 // Not investigated yet.
2045 case Op_AbsI:
2046 return;
2047 }
2048
2049 if (n->is_Load()) {
2050 // LoadNode::Identity tries to look for an earlier store value via
2051 // can_see_stored_value. I found an example where this led to
2052 // an Allocation, where we could assume the value was still zero.
2053 // So the LoadN can be replaced with a zerocon.
2054 //
2055 // Investigate why this was not already done during IGVN.
2056 // A similar issue happens with Ideal.
2057 //
2058 // Found with:
2059 // java -XX:VerifyIterativeGVN=1000 -Xcomp --version
2060 return;
2061 }
2062
2063 if (n->is_Store()) {
2064 // StoreNode::Identity
2065 // Not investigated, but found missing optimization for StoreI.
2066 // Looks like a StoreI is replaced with an InitializeNode.
2067 //
2068 // Found with:
2069 // applications/ctw/modules/java_base_2.java
2070 // -ea -esa -XX:CompileThreshold=100 -XX:+UnlockExperimentalVMOptions -server -XX:-TieredCompilation -Djava.awt.headless=true -XX:+IgnoreUnrecognizedVMOptions -XX:VerifyIterativeGVN=1110
2071 return;
2072 }
2073
2074 if (n->is_Vector()) {
2075 // Found with tier1-3. Not investigated yet.
2076 // The observed issue was with AndVNode::Identity
2077 return;
2078 }
2079
2080 Node* i = n->Identity(this);
2081 // If we cannot find any other Identity, we are happy.
2082 if (i == n) {
2083 verify_empty_worklist(n);
2084 return;
2085 }
2086
2087 // The verification just found a new Identity that was not found during IGVN.
2088 stringStream ss; // Print as a block without tty lock.
2089 ss.cr();
2090 ss.print_cr("Missed Identity optimization:");
2091 ss.print_cr("Old node:");
2092 n->dump_bfs(1, nullptr, "", &ss);
2093 ss.print_cr("New node:");
2094 i->dump_bfs(1, nullptr, "", &ss);
2095 tty->print_cr("%s", ss.as_string());
2096
2097 assert(false, "Missed Identity optimization opportunity in PhaseIterGVN for %s", n->Name());
2098 }
2099
2100 // Some other verifications that are not specific to a particular transformation.
2101 void PhaseIterGVN::verify_node_invariants_for(const Node* n) {
2102 if (n->is_AddP()) {
2103 if (!n->as_AddP()->address_input_has_same_base()) {
2104 stringStream ss; // Print as a block without tty lock.
2105 ss.cr();
2106 ss.print_cr("Base pointers must match for AddP chain:");
2107 n->dump_bfs(2, nullptr, "", &ss);
2108 tty->print_cr("%s", ss.as_string());
2109
2110 assert(false, "Broken node invariant for %s", n->Name());
2111 }
2112 }
2113 }
2114 #endif
2115
2116 /**
2117 * Register a new node with the optimizer. Update the types array, the def-use
2118 * info. Put on worklist.
2119 */
2120 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
2121 set_type_bottom(n);
2122 _worklist.push(n);
2123 if (orig != nullptr) C->copy_node_notes_to(n, orig);
2124 return n;
2125 }
2126
2127 //------------------------------transform--------------------------------------
2128 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
2129 Node *PhaseIterGVN::transform( Node *n ) {
2130 // If brand new node, make space in type array, and give it a type.
2131 ensure_type_or_null(n);
2132 if (type_or_null(n) == nullptr) {
2133 set_type_bottom(n);
2134 }
2135
2136 if (_delay_transform) {
2137 // Add the node to the worklist but don't optimize for now
2138 _worklist.push(n);
2139 return n;
2140 }
2141
2142 return transform_old(n);
2143 }
2144
2145 Node *PhaseIterGVN::transform_old(Node* n) {
2146 NOT_PRODUCT(set_transforms());
2147 // Remove 'n' from hash table in case it gets modified
2148 _table.hash_delete(n);
2149 #ifdef ASSERT
2150 if (is_verify_def_use()) {
2151 assert(!_table.find_index(n->_idx), "found duplicate entry in table");
2152 }
2153 #endif
2154
2155 // Allow Bool -> Cmp idealisation in late inlining intrinsics that return a bool
2156 if (n->is_Cmp()) {
2157 add_users_to_worklist(n);
2158 }
2159
2160 // Apply the Ideal call in a loop until it no longer applies
2161 Node* k = n;
2162 DEBUG_ONLY(dead_loop_check(k);)
2163 DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
2164 C->remove_modified_node(k);
2165 #ifndef PRODUCT
2166 uint hash_before = is_verify_Ideal_return() ? k->hash() : 0;
2167 #endif
2168 Node* i = apply_ideal(k, /*can_reshape=*/true);
2169 assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
2170 #ifndef PRODUCT
2171 if (is_verify_Ideal_return()) {
2172 assert(k->outcnt() == 0 || i != nullptr || hash_before == k->hash(), "hash changed after Ideal returned nullptr for %s", k->Name());
2173 }
2174 verify_step(k);
2175 #endif
2176
2177 DEBUG_ONLY(uint loop_count = 1;)
2178 while (i != nullptr) {
2179 #ifdef ASSERT
2180 if (loop_count >= K + C->live_nodes()) {
2181 dump_infinite_loop_info(i, "PhaseIterGVN::transform_old");
2182 }
2183 #endif
2184 assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
2185 // Made a change; put users of original Node on worklist
2186 add_users_to_worklist(k);
2187 // Replacing root of transform tree?
2188 if (k != i) {
2189 // Make users of old Node now use new.
2190 subsume_node(k, i);
2191 k = i;
2192 }
2193 DEBUG_ONLY(dead_loop_check(k);)
2194 // Try idealizing again
2195 DEBUG_ONLY(is_new = (k->outcnt() == 0);)
2196 C->remove_modified_node(k);
2197 #ifndef PRODUCT
2198 uint hash_before = is_verify_Ideal_return() ? k->hash() : 0;
2199 #endif
2200 i = apply_ideal(k, /*can_reshape=*/true);
2201 assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
2202 #ifndef PRODUCT
2203 if (is_verify_Ideal_return()) {
2204 assert(k->outcnt() == 0 || i != nullptr || hash_before == k->hash(), "hash changed after Ideal returned nullptr for %s", k->Name());
2205 }
2206 verify_step(k);
2207 #endif
2208 DEBUG_ONLY(loop_count++;)
2209 }
2210
2211 // If brand new node, make space in type array.
2212 ensure_type_or_null(k);
2213
2214 // See what kind of values 'k' takes on at runtime
2215 const Type* t = k->Value(this);
2216 assert(t != nullptr, "value sanity");
2217
2218 // Since I just called 'Value' to compute the set of run-time values
2219 // for this Node, and 'Value' is non-local (and therefore expensive) I'll
2220 // cache Value. Later requests for the local phase->type of this Node can
2221 // use the cached Value instead of suffering with 'bottom_type'.
2222 if (type_or_null(k) != t) {
2223 #ifndef PRODUCT
2224 inc_new_values();
2225 set_progress();
2226 #endif
2227 set_type(k, t);
2228 // If k is a TypeNode, capture any more-precise type permanently into Node
2229 k->raise_bottom_type(t);
2230 // Move users of node to worklist
2231 add_users_to_worklist(k);
2232 }
2233 // If 'k' computes a constant, replace it with a constant
2234 if (t->singleton() && !k->is_Con()) {
2235 NOT_PRODUCT(set_progress();)
2236 Node* con = makecon(t); // Make a constant
2237 add_users_to_worklist(k);
2238 subsume_node(k, con); // Everybody using k now uses con
2239 return con;
2240 }
2241
2242 // Now check for Identities
2243 i = k->Identity(this); // Look for a nearby replacement
2244 if (i != k) { // Found? Return replacement!
2245 NOT_PRODUCT(set_progress();)
2246 add_users_to_worklist(k);
2247 subsume_node(k, i); // Everybody using k now uses i
2248 return i;
2249 }
2250
2251 // Global Value Numbering
2252 i = hash_find_insert(k); // Check for pre-existing node
2253 if (i && (i != k)) {
2254 // Return the pre-existing node if it isn't dead
2255 NOT_PRODUCT(set_progress();)
2256 add_users_to_worklist(k);
2257 subsume_node(k, i); // Everybody using k now uses i
2258 return i;
2259 }
2260
2261 // Return Idealized original
2262 return k;
2263 }
2264
2265 //---------------------------------saturate------------------------------------
2266 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
2267 const Type* limit_type) const {
2268 return new_type->narrow(old_type);
2269 }
2270
2271 //------------------------------remove_globally_dead_node----------------------
2272 // Kill a globally dead Node. All uses are also globally dead and are
2273 // aggressively trimmed.
2274 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
2275 enum DeleteProgress {
2276 PROCESS_INPUTS,
2277 PROCESS_OUTPUTS
2278 };
2279 ResourceMark rm;
2280 Node_Stack stack(32);
2281 stack.push(dead, PROCESS_INPUTS);
2282
2283 while (stack.is_nonempty()) {
2284 dead = stack.node();
2285 if (dead->Opcode() == Op_SafePoint) {
2286 dead->as_SafePoint()->disconnect_from_root(this);
2287 }
2288 uint progress_state = stack.index();
2289 assert(dead != C->root(), "killing root, eh?");
2290 assert(!dead->is_top(), "add check for top when pushing");
2291 NOT_PRODUCT( set_progress(); )
2292 if (progress_state == PROCESS_INPUTS) {
2293 // After following inputs, continue to outputs
2294 stack.set_index(PROCESS_OUTPUTS);
2295 if (!dead->is_Con()) { // Don't kill cons but uses
2296 bool recurse = false;
2297 // Remove from hash table
2298 _table.hash_delete( dead );
2299 // Smash all inputs to 'dead', isolating him completely
2300 for (uint i = 0; i < dead->req(); i++) {
2301 Node *in = dead->in(i);
2302 if (in != nullptr && in != C->top()) { // Points to something?
2303 int nrep = dead->replace_edge(in, nullptr, this); // Kill edges
2304 assert((nrep > 0), "sanity");
2305 if (in->outcnt() == 0) { // Made input go dead?
2306 stack.push(in, PROCESS_INPUTS); // Recursively remove
2307 recurse = true;
2308 } else if (in->outcnt() == 1 &&
2309 in->has_special_unique_user()) {
2310 _worklist.push(in->unique_out());
2311 } else if (in->outcnt() <= 2 && dead->is_Phi()) {
2312 if (in->Opcode() == Op_Region) {
2313 _worklist.push(in);
2314 } else if (in->is_Store()) {
2315 DUIterator_Fast imax, i = in->fast_outs(imax);
2316 _worklist.push(in->fast_out(i));
2317 i++;
2318 if (in->outcnt() == 2) {
2319 _worklist.push(in->fast_out(i));
2320 i++;
2321 }
2322 assert(!(i < imax), "sanity");
2323 }
2324 } else if (dead->is_data_proj_of_pure_function(in)) {
2325 _worklist.push(in);
2326 } else {
2327 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
2328 }
2329 if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
2330 in->is_Proj() && in->in(0) != nullptr && in->in(0)->is_Initialize()) {
2331 // A Load that directly follows an InitializeNode is
2332 // going away. The Stores that follow are candidates
2333 // again to be captured by the InitializeNode.
2334 for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
2335 Node *n = in->fast_out(j);
2336 if (n->is_Store()) {
2337 _worklist.push(n);
2338 }
2339 }
2340 }
2341 } // if (in != nullptr && in != C->top())
2342 } // for (uint i = 0; i < dead->req(); i++)
2343 if (recurse) {
2344 continue;
2345 }
2346 } // if (!dead->is_Con())
2347 } // if (progress_state == PROCESS_INPUTS)
2348
2349 // Aggressively kill globally dead uses
2350 // (Rather than pushing all the outs at once, we push one at a time,
2351 // plus the parent to resume later, because of the indefinite number
2352 // of edge deletions per loop trip.)
2353 if (dead->outcnt() > 0) {
2354 // Recursively remove output edges
2355 stack.push(dead->raw_out(0), PROCESS_INPUTS);
2356 } else {
2357 // Finished disconnecting all input and output edges.
2358 stack.pop();
2359 // Remove dead node from iterative worklist
2360 _worklist.remove(dead);
2361 C->remove_useless_node(dead);
2362 }
2363 } // while (stack.is_nonempty())
2364 }
2365
2366 //------------------------------subsume_node-----------------------------------
2367 // Remove users from node 'old' and add them to node 'nn'.
2368 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
2369 if (old->Opcode() == Op_SafePoint) {
2370 old->as_SafePoint()->disconnect_from_root(this);
2371 }
2372 assert( old != hash_find(old), "should already been removed" );
2373 assert( old != C->top(), "cannot subsume top node");
2374 // Copy debug or profile information to the new version:
2375 C->copy_node_notes_to(nn, old);
2376 // Move users of node 'old' to node 'nn'
2377 for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
2378 Node* use = old->last_out(i); // for each use...
2379 // use might need re-hashing (but it won't if it's a new node)
2380 rehash_node_delayed(use);
2381 // Update use-def info as well
2382 // We remove all occurrences of old within use->in,
2383 // so as to avoid rehashing any node more than once.
2384 // The hash table probe swamps any outer loop overhead.
2385 uint num_edges = 0;
2386 for (uint jmax = use->len(), j = 0; j < jmax; j++) {
2387 if (use->in(j) == old) {
2388 use->set_req(j, nn);
2389 ++num_edges;
2390 }
2391 }
2392 i -= num_edges; // we deleted 1 or more copies of this edge
2393 }
2394
2395 // Search for instance field data PhiNodes in the same region pointing to the old
2396 // memory PhiNode and update their instance memory ids to point to the new node.
2397 if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != nullptr) {
2398 Node* region = old->in(0);
2399 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2400 PhiNode* phi = region->fast_out(i)->isa_Phi();
2401 if (phi != nullptr && phi->inst_mem_id() == (int)old->_idx) {
2402 phi->set_inst_mem_id((int)nn->_idx);
2403 }
2404 }
2405 }
2406
2407 // Smash all inputs to 'old', isolating him completely
2408 Node *temp = new Node(1);
2409 temp->init_req(0,nn); // Add a use to nn to prevent him from dying
2410 remove_dead_node( old );
2411 temp->del_req(0); // Yank bogus edge
2412 if (nn != nullptr && nn->outcnt() == 0) {
2413 _worklist.push(nn);
2414 }
2415 #ifndef PRODUCT
2416 if (is_verify_def_use()) {
2417 for ( int i = 0; i < _verify_window_size; i++ ) {
2418 if ( _verify_window[i] == old )
2419 _verify_window[i] = nn;
2420 }
2421 }
2422 #endif
2423 temp->destruct(this); // reuse the _idx of this little guy
2424 }
2425
2426 void PhaseIterGVN::replace_in_uses(Node* n, Node* m) {
2427 assert(n != nullptr, "sanity");
2428 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2429 Node* u = n->fast_out(i);
2430 if (u != n) {
2431 rehash_node_delayed(u);
2432 int nb = u->replace_edge(n, m);
2433 --i, imax -= nb;
2434 }
2435 }
2436 assert(n->outcnt() == 0, "all uses must be deleted");
2437 }
2438
2439 //------------------------------add_users_to_worklist--------------------------
2440 void PhaseIterGVN::add_users_to_worklist0(Node* n, Unique_Node_List& worklist) {
2441 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2442 worklist.push(n->fast_out(i)); // Push on worklist
2443 }
2444 }
2445
2446 // Return counted loop Phi if as a counted loop exit condition, cmp
2447 // compares the induction variable with n
2448 static PhiNode* countedloop_phi_from_cmp(CmpNode* cmp, Node* n) {
2449 for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
2450 Node* bol = cmp->fast_out(i);
2451 for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
2452 Node* iff = bol->fast_out(i2);
2453 if (iff->is_BaseCountedLoopEnd()) {
2454 BaseCountedLoopEndNode* cle = iff->as_BaseCountedLoopEnd();
2455 if (cle->limit() == n) {
2456 PhiNode* phi = cle->phi();
2457 if (phi != nullptr) {
2458 return phi;
2459 }
2460 }
2461 }
2462 }
2463 }
2464 return nullptr;
2465 }
2466
2467 void PhaseIterGVN::add_users_to_worklist(Node *n) {
2468 add_users_to_worklist0(n, _worklist);
2469
2470 Unique_Node_List& worklist = _worklist;
2471 // Move users of node to worklist
2472 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2473 Node* use = n->fast_out(i); // Get use
2474 add_users_of_use_to_worklist(n, use, worklist);
2475 }
2476 }
2477
2478 void PhaseIterGVN::add_users_of_use_to_worklist(Node* n, Node* use, Unique_Node_List& worklist) {
2479 if(use->is_Multi() || // Multi-definer? Push projs on worklist
2480 use->is_Store() ) // Enable store/load same address
2481 add_users_to_worklist0(use, worklist);
2482
2483 // If we changed the receiver type to a call, we need to revisit
2484 // the Catch following the call. It's looking for a non-null
2485 // receiver to know when to enable the regular fall-through path
2486 // in addition to the NullPtrException path.
2487 if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
2488 Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
2489 if (p != nullptr) {
2490 add_users_to_worklist0(p, worklist);
2491 }
2492 }
2493
2494 // AndLNode::Ideal folds GraphKit::mark_word_test patterns. Give it a chance to run.
2495 if (n->is_Load() && use->is_Phi()) {
2496 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2497 Node* u = use->fast_out(i);
2498 if (u->Opcode() == Op_AndL) {
2499 worklist.push(u);
2500 }
2501 }
2502 }
2503
2504 uint use_op = use->Opcode();
2505 if(use->is_Cmp()) { // Enable CMP/BOOL optimization
2506 add_users_to_worklist0(use, worklist); // Put Bool on worklist
2507 if (use->outcnt() > 0) {
2508 Node* bol = use->raw_out(0);
2509 if (bol->outcnt() > 0) {
2510 Node* iff = bol->raw_out(0);
2511 if (iff->outcnt() == 2) {
2512 // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
2513 // phi merging either 0 or 1 onto the worklist
2514 Node* ifproj0 = iff->raw_out(0);
2515 Node* ifproj1 = iff->raw_out(1);
2516 if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
2517 Node* region0 = ifproj0->raw_out(0);
2518 Node* region1 = ifproj1->raw_out(0);
2519 if( region0 == region1 )
2520 add_users_to_worklist0(region0, worklist);
2521 }
2522 }
2523 }
2524 }
2525 if (use_op == Op_CmpI || use_op == Op_CmpL) {
2526 Node* phi = countedloop_phi_from_cmp(use->as_Cmp(), n);
2527 if (phi != nullptr) {
2528 // Input to the cmp of a loop exit check has changed, thus
2529 // the loop limit may have changed, which can then change the
2530 // range values of the trip-count Phi.
2531 worklist.push(phi);
2532 }
2533 }
2534 if (use_op == Op_CmpI) {
2535 Node* cmp = use;
2536 Node* in1 = cmp->in(1);
2537 Node* in2 = cmp->in(2);
2538 // Notify CmpI / If pattern from CastIINode::Value (left pattern).
2539 // Must also notify if in1 is modified and possibly turns into X (right pattern).
2540 //
2541 // in1 in2 in1 in2
2542 // | | | |
2543 // +--- | --+ | |
2544 // | | | | |
2545 // CmpINode | CmpINode
2546 // | | |
2547 // BoolNode | BoolNode
2548 // | | OR |
2549 // IfNode | IfNode
2550 // | | |
2551 // IfProj | IfProj X
2552 // | | | |
2553 // CastIINode CastIINode
2554 //
2555 if (in1 != in2) { // if they are equal, the CmpI can fold them away
2556 if (in1 == n) {
2557 // in1 modified -> could turn into X -> do traversal based on right pattern.
2558 for (DUIterator_Fast i2max, i2 = cmp->fast_outs(i2max); i2 < i2max; i2++) {
2559 Node* bol = cmp->fast_out(i2); // For each Bool
2560 if (bol->is_Bool()) {
2561 for (DUIterator_Fast i3max, i3 = bol->fast_outs(i3max); i3 < i3max; i3++) {
2562 Node* iff = bol->fast_out(i3); // For each If
2563 if (iff->is_If()) {
2564 for (DUIterator_Fast i4max, i4 = iff->fast_outs(i4max); i4 < i4max; i4++) {
2565 Node* if_proj = iff->fast_out(i4); // For each IfProj
2566 assert(if_proj->is_IfProj(), "If only has IfTrue and IfFalse as outputs");
2567 for (DUIterator_Fast i5max, i5 = if_proj->fast_outs(i5max); i5 < i5max; i5++) {
2568 Node* castii = if_proj->fast_out(i5); // For each CastII
2569 if (castii->is_CastII() &&
2570 castii->as_CastII()->carry_dependency()) {
2571 worklist.push(castii);
2572 }
2573 }
2574 }
2575 }
2576 }
2577 }
2578 }
2579 } else {
2580 // Only in2 modified -> can assume X == in2 (left pattern).
2581 assert(n == in2, "only in2 modified");
2582 // Find all CastII with input in1.
2583 for (DUIterator_Fast jmax, j = in1->fast_outs(jmax); j < jmax; j++) {
2584 Node* castii = in1->fast_out(j);
2585 if (castii->is_CastII() && castii->as_CastII()->carry_dependency()) {
2586 // Find If.
2587 if (castii->in(0) != nullptr && castii->in(0)->in(0) != nullptr && castii->in(0)->in(0)->is_If()) {
2588 Node* ifnode = castii->in(0)->in(0);
2589 // Check that if connects to the cmp
2590 if (ifnode->in(1) != nullptr && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == cmp) {
2591 worklist.push(castii);
2592 }
2593 }
2594 }
2595 }
2596 }
2597 }
2598 }
2599 }
2600
2601 // Inline type nodes can have other inline types as users. If an input gets
2602 // updated, make sure that inline type users get a chance for optimization.
2603 if (use->is_InlineType() || use->is_DecodeN()) {
2604 auto push_the_uses_to_worklist = [&](Node* n){
2605 if (n->is_InlineType()) {
2606 worklist.push(n);
2607 }
2608 };
2609 auto is_boundary = [](Node* n){ return !n->is_InlineType(); };
2610 use->visit_uses(push_the_uses_to_worklist, is_boundary, true);
2611 }
2612 // If changed Cast input, notify down for Phi, Sub, and Xor - all do "uncast"
2613 // Patterns:
2614 // ConstraintCast+ -> Sub
2615 // ConstraintCast+ -> Phi
2616 // ConstraintCast+ -> Xor
2617 if (use->is_ConstraintCast()) {
2618 auto push_the_uses_to_worklist = [&](Node* n){
2619 if (n->is_Phi() || n->is_Sub() || n->Opcode() == Op_XorI || n->Opcode() == Op_XorL) {
2620 worklist.push(n);
2621 }
2622 };
2623 auto is_boundary = [](Node* n){ return !n->is_ConstraintCast(); };
2624 use->visit_uses(push_the_uses_to_worklist, is_boundary);
2625 }
2626 // If changed LShift inputs, check RShift/URShift users for
2627 // "(X << C) >> C" sign-ext and "(X << C) >>> C" zero-ext optimizations.
2628 if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2629 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2630 Node* u = use->fast_out(i2);
2631 if (u->Opcode() == Op_RShiftI || u->Opcode() == Op_RShiftL ||
2632 u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL) {
2633 worklist.push(u);
2634 }
2635 }
2636 }
2637 // If changed LShift inputs, check And users for shift and mask (And) operation
2638 if (use_op == Op_LShiftI || use_op == Op_LShiftL) {
2639 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2640 Node* u = use->fast_out(i2);
2641 if (u->Opcode() == Op_AndI || u->Opcode() == Op_AndL) {
2642 worklist.push(u);
2643 }
2644 }
2645 }
2646 // If changed AddI/SubI inputs, check CmpU for range check optimization.
2647 if (use_op == Op_AddI || use_op == Op_SubI) {
2648 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2649 Node* u = use->fast_out(i2);
2650 if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
2651 worklist.push(u);
2652 }
2653 }
2654 }
2655 // If changed AndI/AndL inputs, check RShift/URShift users for "(x & mask) >> shift" optimization opportunity
2656 if (use_op == Op_AndI || use_op == Op_AndL) {
2657 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2658 Node* u = use->fast_out(i2);
2659 if (u->Opcode() == Op_RShiftI || u->Opcode() == Op_RShiftL ||
2660 u->Opcode() == Op_URShiftI || u->Opcode() == Op_URShiftL) {
2661 worklist.push(u);
2662 }
2663 }
2664 }
2665 // Check for redundant conversion patterns:
2666 // ConvD2L->ConvL2D->ConvD2L
2667 // ConvF2I->ConvI2F->ConvF2I
2668 // ConvF2L->ConvL2F->ConvF2L
2669 // ConvI2F->ConvF2I->ConvI2F
2670 // Note: there may be other 3-nodes conversion chains that would require to be added here, but these
2671 // are the only ones that are known to trigger missed optimizations otherwise
2672 if (use_op == Op_ConvL2D ||
2673 use_op == Op_ConvI2F ||
2674 use_op == Op_ConvL2F ||
2675 use_op == Op_ConvF2I) {
2676 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2677 Node* u = use->fast_out(i2);
2678 if ((use_op == Op_ConvL2D && u->Opcode() == Op_ConvD2L) ||
2679 (use_op == Op_ConvI2F && u->Opcode() == Op_ConvF2I) ||
2680 (use_op == Op_ConvL2F && u->Opcode() == Op_ConvF2L) ||
2681 (use_op == Op_ConvF2I && u->Opcode() == Op_ConvI2F)) {
2682 worklist.push(u);
2683 }
2684 }
2685 }
2686 // If changed AddP inputs:
2687 // - check Stores for loop invariant, and
2688 // - if the changed input is the offset, check constant-offset AddP users for
2689 // address expression flattening.
2690 if (use_op == Op_AddP) {
2691 bool offset_changed = n == use->in(AddPNode::Offset);
2692 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2693 Node* u = use->fast_out(i2);
2694 if (u->is_Mem()) {
2695 worklist.push(u);
2696 } else if (offset_changed && u->is_AddP() && u->in(AddPNode::Offset)->is_Con()) {
2697 worklist.push(u);
2698 }
2699 }
2700 }
2701 // Check for "abs(0-x)" into "abs(x)" conversion
2702 if (use->is_Sub()) {
2703 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2704 Node* u = use->fast_out(i2);
2705 if (u->Opcode() == Op_AbsD || u->Opcode() == Op_AbsF ||
2706 u->Opcode() == Op_AbsL || u->Opcode() == Op_AbsI) {
2707 worklist.push(u);
2708 }
2709 }
2710 }
2711 // Check for Max/Min(A, Max/Min(B, C)) where A == B or A == C
2712 if (use->is_MinMax()) {
2713 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2714 Node* u = use->fast_out(i2);
2715 if (u->is_MinMax()) {
2716 worklist.push(u);
2717 }
2718 }
2719 }
2720 auto enqueue_init_mem_projs = [&](ProjNode* proj) {
2721 add_users_to_worklist0(proj, worklist);
2722 };
2723 // If changed initialization activity, check dependent Stores
2724 if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
2725 InitializeNode* init = use->as_Allocate()->initialization();
2726 if (init != nullptr) {
2727 init->for_each_proj(enqueue_init_mem_projs, TypeFunc::Memory);
2728 }
2729 }
2730 // If the ValidLengthTest input changes then the fallthrough path out of the AllocateArray may have become dead.
2731 // CatchNode::Value() is responsible for killing that path. The CatchNode has to be explicitly enqueued for igvn
2732 // to guarantee the change is not missed.
2733 if (use_op == Op_AllocateArray && n == use->in(AllocateNode::ValidLengthTest)) {
2734 Node* p = use->as_AllocateArray()->proj_out_or_null(TypeFunc::Control);
2735 if (p != nullptr) {
2736 add_users_to_worklist0(p, worklist);
2737 }
2738 }
2739
2740 if (use_op == Op_Initialize) {
2741 InitializeNode* init = use->as_Initialize();
2742 init->for_each_proj(enqueue_init_mem_projs, TypeFunc::Memory);
2743 }
2744 // Loading the java mirror from a Klass requires two loads and the type
2745 // of the mirror load depends on the type of 'n'. See LoadNode::Value().
2746 // LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
2747 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2748 bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
2749
2750 if (use_op == Op_CastP2X) {
2751 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2752 Node* u = use->fast_out(i2);
2753 // TODO 8350865 Still needed? Yes, I think this is from PhaseMacroExpand::expand_mh_intrinsic_return
2754 if (u->Opcode() == Op_AndX) {
2755 worklist.push(u);
2756 }
2757 // Search for CmpL(OrL(CastP2X(..), CastP2X(..)), 0L)
2758 if (u->Opcode() == Op_OrL) {
2759 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
2760 Node* cmp = u->fast_out(i3);
2761 if (cmp->Opcode() == Op_CmpL) {
2762 worklist.push(cmp);
2763 }
2764 }
2765 }
2766 }
2767 }
2768 if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
2769 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2770 Node* u = use->fast_out(i2);
2771 const Type* ut = u->bottom_type();
2772 if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
2773 if (has_load_barrier_nodes) {
2774 // Search for load barriers behind the load
2775 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
2776 Node* b = u->fast_out(i3);
2777 if (bs->is_gc_barrier_node(b)) {
2778 worklist.push(b);
2779 }
2780 }
2781 }
2782 worklist.push(u);
2783 }
2784 }
2785 }
2786 // Give CallStaticJavaNode::remove_useless_allocation a chance to run
2787 if (use->is_Region()) {
2788 Node* c = use;
2789 do {
2790 c = c->unique_ctrl_out_or_null();
2791 } while (c != nullptr && c->is_Region());
2792 if (c != nullptr && c->is_CallStaticJava() && c->as_CallStaticJava()->uncommon_trap_request() != 0) {
2793 worklist.push(c);
2794 }
2795 }
2796 if (use->Opcode() == Op_OpaqueZeroTripGuard) {
2797 assert(use->outcnt() <= 1, "OpaqueZeroTripGuard can't be shared");
2798 if (use->outcnt() == 1) {
2799 Node* cmp = use->unique_out();
2800 worklist.push(cmp);
2801 }
2802 }
2803
2804 // From CastX2PNode::Ideal
2805 // CastX2P(AddX(x, y))
2806 // CastX2P(SubX(x, y))
2807 if (use->Opcode() == Op_AddX || use->Opcode() == Op_SubX) {
2808 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
2809 Node* u = use->fast_out(i2);
2810 if (u->Opcode() == Op_CastX2P) {
2811 worklist.push(u);
2812 }
2813 }
2814 }
2815
2816 /* AndNode has a special handling when one of the operands is a LShiftNode:
2817 * (LHS << s) & RHS
2818 * if RHS fits in less than s bits, the value of this expression is 0.
2819 * The difficulty is that there might be a conversion node (ConvI2L) between
2820 * the LShiftINode and the AndLNode, like so:
2821 * AndLNode(ConvI2L(LShiftI(LHS, s)), RHS)
2822 * This case is handled by And[IL]Node::Value(PhaseGVN*)
2823 * (see `AndIL_min_trailing_zeros`).
2824 *
2825 * But, when the shift is updated during IGVN, pushing the user (ConvI2L)
2826 * is not enough: there might be no update happening there. We need to
2827 * directly push the And[IL]Node on the worklist, jumping over ConvI2L.
2828 *
2829 * Moreover we can have ConstraintCasts in between. It may look like
2830 * ConstraintCast+ -> ConvI2L -> ConstraintCast+ -> And
2831 * and And[IL]Node::Value(PhaseGVN*) still handles that by looking through casts.
2832 * So we must deal with that as well.
2833 */
2834 if (use->is_ConstraintCast() || use_op == Op_ConvI2L) {
2835 auto is_boundary = [](Node* n){ return !n->is_ConstraintCast() && n->Opcode() != Op_ConvI2L; };
2836 auto push_and_to_worklist = [&worklist](Node* n){
2837 if (n->Opcode() == Op_AndL || n->Opcode() == Op_AndI) {
2838 worklist.push(n);
2839 }
2840 };
2841 use->visit_uses(push_and_to_worklist, is_boundary);
2842 }
2843 }
2844
2845 /**
2846 * Remove the speculative part of all types that we know of
2847 */
2848 void PhaseIterGVN::remove_speculative_types() {
2849 assert(UseTypeSpeculation, "speculation is off");
2850 for (uint i = 0; i < _types.Size(); i++) {
2851 const Type* t = _types.fast_lookup(i);
2852 if (t != nullptr) {
2853 _types.map(i, t->remove_speculative());
2854 }
2855 }
2856 _table.check_no_speculative_types();
2857 }
2858
2859 //=============================================================================
2860 #ifndef PRODUCT
2861 uint PhaseCCP::_total_invokes = 0;
2862 uint PhaseCCP::_total_constants = 0;
2863 #endif
2864 //------------------------------PhaseCCP---------------------------------------
2865 // Conditional Constant Propagation, ala Wegman & Zadeck
2866 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
2867 NOT_PRODUCT( clear_constants(); )
2868 assert( _worklist.size() == 0, "" );
2869 _phase = PhaseValuesType::ccp;
2870 analyze();
2871 }
2872
2873 #ifndef PRODUCT
2874 //------------------------------~PhaseCCP--------------------------------------
2875 PhaseCCP::~PhaseCCP() {
2876 inc_invokes();
2877 _total_constants += count_constants();
2878 }
2879 #endif
2880
2881
2882 #ifdef ASSERT
2883 void PhaseCCP::verify_type(Node* n, const Type* tnew, const Type* told) {
2884 if (tnew->meet(told) != tnew->remove_speculative()) {
2885 n->dump(3);
2886 tty->print("told = "); told->dump(); tty->cr();
2887 tty->print("tnew = "); tnew->dump(); tty->cr();
2888 fatal("Not monotonic");
2889 }
2890 assert(!told->isa_int() || !tnew->isa_int() || told->is_int()->_widen <= tnew->is_int()->_widen, "widen increases");
2891 assert(!told->isa_long() || !tnew->isa_long() || told->is_long()->_widen <= tnew->is_long()->_widen, "widen increases");
2892 }
2893 #endif //ASSERT
2894
2895 // In this analysis, all types are initially set to TOP. We iteratively call Value() on all nodes of the graph until
2896 // we reach a fixed-point (i.e. no types change anymore). We start with a list that only contains the root node. Each time
2897 // a new type is set, we push all uses of that node back to the worklist (in some cases, we also push grandchildren
2898 // or nodes even further down back to the worklist because their type could change as a result of the current type
2899 // change).
2900 void PhaseCCP::analyze() {
2901 // Initialize all types to TOP, optimistic analysis
2902 for (uint i = 0; i < C->unique(); i++) {
2903 _types.map(i, Type::TOP);
2904 }
2905
2906 // CCP worklist is placed on a local arena, so that we can allow ResourceMarks on "Compile::current()->resource_arena()".
2907 // We also do not want to put the worklist on "Compile::current()->comp_arena()", as that one only gets de-allocated after
2908 // Compile is over. The local arena gets de-allocated at the end of its scope.
2909 ResourceArea local_arena(mtCompiler);
2910 Unique_Node_List worklist(&local_arena);
2911 Unique_Node_List worklist_revisit(&local_arena);
2912 DEBUG_ONLY(Unique_Node_List worklist_verify(&local_arena);)
2913
2914 // Push root onto worklist
2915 worklist.push(C->root());
2916
2917 assert(_root_and_safepoints.size() == 0, "must be empty (unused)");
2918 _root_and_safepoints.push(C->root());
2919
2920 // This is the meat of CCP: pull from worklist; compute new value; push changes out.
2921
2922 // Do the first round. Since all initial types are TOP, this will visit all alive nodes.
2923 while (worklist.size() != 0) {
2924 Node* n = fetch_next_node(worklist);
2925 DEBUG_ONLY(worklist_verify.push(n);)
2926 if (needs_revisit(n)) {
2927 worklist_revisit.push(n);
2928 }
2929 if (n->is_SafePoint()) {
2930 // Make sure safepoints are processed by PhaseCCP::transform even if they are
2931 // not reachable from the bottom. Otherwise, infinite loops would be removed.
2932 _root_and_safepoints.push(n);
2933 }
2934 analyze_step(worklist, n);
2935 }
2936
2937 // More rounds to catch updates far in the graph.
2938 // Revisit nodes that might be able to refine their types at the end of the round.
2939 // If so, process these nodes. If there is remaining work, start another round.
2940 do {
2941 while (worklist.size() != 0) {
2942 Node* n = fetch_next_node(worklist);
2943 analyze_step(worklist, n);
2944 }
2945 for (uint t = 0; t < worklist_revisit.size(); t++) {
2946 Node* n = worklist_revisit.at(t);
2947 analyze_step(worklist, n);
2948 }
2949 } while (worklist.size() != 0);
2950
2951 DEBUG_ONLY(verify_analyze(worklist_verify);)
2952 }
2953
2954 void PhaseCCP::analyze_step(Unique_Node_List& worklist, Node* n) {
2955 const Type* new_type = n->Value(this);
2956 if (new_type != type(n)) {
2957 DEBUG_ONLY(verify_type(n, new_type, type(n));)
2958 dump_type_and_node(n, new_type);
2959 set_type(n, new_type);
2960 push_child_nodes_to_worklist(worklist, n);
2961 }
2962 if (KillPathsReachableByDeadTypeNode && n->is_Type() && new_type == Type::TOP) {
2963 // Keep track of Type nodes to kill CFG paths that use Type
2964 // nodes that become dead.
2965 _maybe_top_type_nodes.push(n);
2966 }
2967 }
2968
2969 // Some nodes can refine their types due to type change somewhere deep
2970 // in the graph. We will need to revisit them before claiming convergence.
2971 // Add nodes here if particular *Node::Value is doing deep graph traversals
2972 // not handled by PhaseCCP::push_more_uses().
2973 bool PhaseCCP::needs_revisit(Node* n) const {
2974 // LoadNode performs deep traversals. Load is not notified for changes far away.
2975 if (n->is_Load()) {
2976 return true;
2977 }
2978 // CmpPNode performs deep traversals if it compares oopptr. CmpP is not notified for changes far away.
2979 if (n->Opcode() == Op_CmpP && type(n->in(1))->isa_oopptr() && type(n->in(2))->isa_oopptr()) {
2980 return true;
2981 }
2982 return false;
2983 }
2984
2985 #ifdef ASSERT
2986 // For every node n on verify list, check if type(n) == n->Value()
2987 // Note for CCP the non-convergence can lead to unsound analysis and mis-compilation.
2988 // Therefore, we are verifying Value convergence strictly.
2989 void PhaseCCP::verify_analyze(Unique_Node_List& worklist_verify) {
2990 while (worklist_verify.size()) {
2991 Node* n = worklist_verify.pop();
2992
2993 // An assert in verify_Value_for means that PhaseCCP is not at fixpoint
2994 // and that the analysis result may be unsound.
2995 // If this happens, check why the reported nodes were not processed again in CCP.
2996 // We should either make sure that these nodes are properly added back to the CCP worklist
2997 // in PhaseCCP::push_child_nodes_to_worklist() to update their type in the same round,
2998 // or that they are added in PhaseCCP::needs_revisit() so that analysis revisits
2999 // them at the end of the round.
3000 verify_Value_for(n, true);
3001 }
3002 }
3003 #endif
3004
3005 // Fetch next node from worklist to be examined in this iteration.
3006 Node* PhaseCCP::fetch_next_node(Unique_Node_List& worklist) {
3007 if (StressCCP) {
3008 return worklist.remove(C->random() % worklist.size());
3009 } else {
3010 return worklist.pop();
3011 }
3012 }
3013
3014 #ifndef PRODUCT
3015 void PhaseCCP::dump_type_and_node(const Node* n, const Type* t) {
3016 if (TracePhaseCCP) {
3017 t->dump();
3018 do {
3019 tty->print("\t");
3020 } while (tty->position() < 16);
3021 n->dump();
3022 }
3023 }
3024 #endif
3025
3026 // We need to propagate the type change of 'n' to all its uses. Depending on the kind of node, additional nodes
3027 // (grandchildren or even further down) need to be revisited as their types could also be improved as a result
3028 // of the new type of 'n'. Push these nodes to the worklist.
3029 void PhaseCCP::push_child_nodes_to_worklist(Unique_Node_List& worklist, Node* n) const {
3030 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3031 Node* use = n->fast_out(i);
3032 push_if_not_bottom_type(worklist, use);
3033 push_more_uses(worklist, n, use);
3034 }
3035 }
3036
3037 void PhaseCCP::push_if_not_bottom_type(Unique_Node_List& worklist, Node* n) const {
3038 if (n->bottom_type() != type(n)) {
3039 worklist.push(n);
3040 }
3041 }
3042
3043 // For some nodes, we need to propagate the type change to grandchildren or even further down.
3044 // Add them back to the worklist.
3045 void PhaseCCP::push_more_uses(Unique_Node_List& worklist, Node* parent, const Node* use) const {
3046 push_phis(worklist, use);
3047 push_catch(worklist, use);
3048 push_cmpu(worklist, use);
3049 push_counted_loop_phi(worklist, parent, use);
3050 push_cast(worklist, use);
3051 push_loadp(worklist, use);
3052 push_and(worklist, parent, use);
3053 push_cast_ii(worklist, parent, use);
3054 push_opaque_zero_trip_guard(worklist, use);
3055 push_bool_with_cmpu_and_mask(worklist, use);
3056 }
3057
3058
3059 // We must recheck Phis too if use is a Region.
3060 void PhaseCCP::push_phis(Unique_Node_List& worklist, const Node* use) const {
3061 if (use->is_Region()) {
3062 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3063 push_if_not_bottom_type(worklist, use->fast_out(i));
3064 }
3065 }
3066 }
3067
3068 // If we changed the receiver type to a call, we need to revisit the Catch node following the call. It's looking for a
3069 // non-null receiver to know when to enable the regular fall-through path in addition to the NullPtrException path.
3070 // Same is true if the type of a ValidLengthTest input to an AllocateArrayNode changes.
3071 void PhaseCCP::push_catch(Unique_Node_List& worklist, const Node* use) {
3072 if (use->is_Call()) {
3073 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3074 Node* proj = use->fast_out(i);
3075 if (proj->is_Proj() && proj->as_Proj()->_con == TypeFunc::Control) {
3076 Node* catch_node = proj->find_out_with(Op_Catch);
3077 if (catch_node != nullptr) {
3078 worklist.push(catch_node);
3079 }
3080 }
3081 }
3082 }
3083 }
3084
3085 // CmpU nodes can get their type information from two nodes up in the graph (instead of from the nodes immediately
3086 // above). Make sure they are added to the worklist if nodes they depend on are updated since they could be missed
3087 // and get wrong types otherwise.
3088 void PhaseCCP::push_cmpu(Unique_Node_List& worklist, const Node* use) const {
3089 uint use_op = use->Opcode();
3090 if (use_op == Op_AddI || use_op == Op_SubI) {
3091 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3092 Node* cmpu = use->fast_out(i);
3093 const uint cmpu_opcode = cmpu->Opcode();
3094 if (cmpu_opcode == Op_CmpU || cmpu_opcode == Op_CmpU3) {
3095 // Got a CmpU or CmpU3 which might need the new type information from node n.
3096 push_if_not_bottom_type(worklist, cmpu);
3097 }
3098 }
3099 }
3100 }
3101
3102 // Look for the following shape, which can be optimized by BoolNode::Value_cmpu_and_mask() (i.e. corresponds to case
3103 // (1b): "(m & x) <u (m + 1))".
3104 // If any of the inputs on the level (%%) change, we need to revisit Bool because we could have prematurely found that
3105 // the Bool is constant (i.e. case (1b) can be applied) which could become invalid with new type information during CCP.
3106 //
3107 // m x m 1 (%%)
3108 // \ / \ /
3109 // AndI AddI
3110 // \ /
3111 // CmpU
3112 // |
3113 // Bool
3114 //
3115 void PhaseCCP::push_bool_with_cmpu_and_mask(Unique_Node_List& worklist, const Node* use) const {
3116 uint use_op = use->Opcode();
3117 if (use_op != Op_AndI && (use_op != Op_AddI || use->in(2)->find_int_con(0) != 1)) {
3118 // Not "m & x" or "m + 1"
3119 return;
3120 }
3121 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3122 Node* cmpu = use->fast_out(i);
3123 if (cmpu->Opcode() == Op_CmpU) {
3124 push_bool_matching_case1b(worklist, cmpu);
3125 }
3126 }
3127 }
3128
3129 // Push any Bool below 'cmpu' that matches case (1b) of BoolNode::Value_cmpu_and_mask().
3130 void PhaseCCP::push_bool_matching_case1b(Unique_Node_List& worklist, const Node* cmpu) const {
3131 assert(cmpu->Opcode() == Op_CmpU, "must be");
3132 for (DUIterator_Fast imax, i = cmpu->fast_outs(imax); i < imax; i++) {
3133 Node* bol = cmpu->fast_out(i);
3134 if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::lt) {
3135 // Not a Bool with "<u"
3136 continue;
3137 }
3138 Node* andI = cmpu->in(1);
3139 Node* addI = cmpu->in(2);
3140 if (andI->Opcode() != Op_AndI || addI->Opcode() != Op_AddI || addI->in(2)->find_int_con(0) != 1) {
3141 // Not "m & x" and "m + 1"
3142 continue;
3143 }
3144
3145 Node* m = addI->in(1);
3146 if (m == andI->in(1) || m == andI->in(2)) {
3147 // Is "m" shared? Matched (1b) and thus we revisit Bool.
3148 push_if_not_bottom_type(worklist, bol);
3149 }
3150 }
3151 }
3152
3153 // If n is used in a counted loop exit condition, then the type of the counted loop's Phi depends on the type of 'n'.
3154 // Seem PhiNode::Value().
3155 void PhaseCCP::push_counted_loop_phi(Unique_Node_List& worklist, Node* parent, const Node* use) {
3156 uint use_op = use->Opcode();
3157 if (use_op == Op_CmpI || use_op == Op_CmpL) {
3158 PhiNode* phi = countedloop_phi_from_cmp(use->as_Cmp(), parent);
3159 if (phi != nullptr) {
3160 worklist.push(phi);
3161 }
3162 }
3163 }
3164
3165 // TODO 8350865 Still needed? Yes, I think this is from PhaseMacroExpand::expand_mh_intrinsic_return
3166 void PhaseCCP::push_cast(Unique_Node_List& worklist, const Node* use) {
3167 uint use_op = use->Opcode();
3168 if (use_op == Op_CastP2X) {
3169 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
3170 Node* u = use->fast_out(i2);
3171 if (u->Opcode() == Op_AndX) {
3172 worklist.push(u);
3173 }
3174 }
3175 }
3176 }
3177
3178 // Loading the java mirror from a Klass requires two loads and the type of the mirror load depends on the type of 'n'.
3179 // See LoadNode::Value().
3180 void PhaseCCP::push_loadp(Unique_Node_List& worklist, const Node* use) const {
3181 BarrierSetC2* barrier_set = BarrierSet::barrier_set()->barrier_set_c2();
3182 bool has_load_barrier_nodes = barrier_set->has_load_barrier_nodes();
3183
3184 if (use->Opcode() == Op_LoadP && use->bottom_type()->isa_rawptr()) {
3185 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3186 Node* loadp = use->fast_out(i);
3187 const Type* ut = loadp->bottom_type();
3188 if (loadp->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(loadp)) {
3189 if (has_load_barrier_nodes) {
3190 // Search for load barriers behind the load
3191 push_load_barrier(worklist, barrier_set, loadp);
3192 }
3193 worklist.push(loadp);
3194 }
3195 }
3196 }
3197 }
3198
3199 void PhaseCCP::push_load_barrier(Unique_Node_List& worklist, const BarrierSetC2* barrier_set, const Node* use) {
3200 for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
3201 Node* barrier_node = use->fast_out(i);
3202 if (barrier_set->is_gc_barrier_node(barrier_node)) {
3203 worklist.push(barrier_node);
3204 }
3205 }
3206 }
3207
3208 // AndI/L::Value() optimizes patterns similar to (v << 2) & 3, or CON & 3 to zero if they are bitwise disjoint.
3209 // Add the AndI/L nodes back to the worklist to re-apply Value() in case the value is now a constant or shift
3210 // value changed.
3211 void PhaseCCP::push_and(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
3212 const TypeInteger* parent_type = type(parent)->isa_integer(type(parent)->basic_type());
3213 uint use_op = use->Opcode();
3214 if (
3215 // Pattern: parent (now constant) -> (ConstraintCast | ConvI2L)* -> And
3216 (parent_type != nullptr && parent_type->is_con()) ||
3217 // Pattern: parent -> LShift (use) -> (ConstraintCast | ConvI2L)* -> And
3218 ((use_op == Op_LShiftI || use_op == Op_LShiftL) && use->in(2) == parent)) {
3219
3220 auto push_and_uses_to_worklist = [&](Node* n) {
3221 uint opc = n->Opcode();
3222 if (opc == Op_AndI || opc == Op_AndL) {
3223 push_if_not_bottom_type(worklist, n);
3224 }
3225 };
3226 auto is_boundary = [](Node* n) {
3227 return !(n->is_ConstraintCast() || n->Opcode() == Op_ConvI2L);
3228 };
3229 use->visit_uses(push_and_uses_to_worklist, is_boundary);
3230 }
3231 }
3232
3233 // CastII::Value() optimizes CmpI/If patterns if the right input of the CmpI has a constant type. If the CastII input is
3234 // the same node as the left input into the CmpI node, the type of the CastII node can be improved accordingly. Add the
3235 // CastII node back to the worklist to re-apply Value() to either not miss this optimization or to undo it because it
3236 // cannot be applied anymore. We could have optimized the type of the CastII before but now the type of the right input
3237 // of the CmpI (i.e. 'parent') is no longer constant. The type of the CastII must be widened in this case.
3238 void PhaseCCP::push_cast_ii(Unique_Node_List& worklist, const Node* parent, const Node* use) const {
3239 if (use->Opcode() == Op_CmpI && use->in(2) == parent) {
3240 Node* other_cmp_input = use->in(1);
3241 for (DUIterator_Fast imax, i = other_cmp_input->fast_outs(imax); i < imax; i++) {
3242 Node* cast_ii = other_cmp_input->fast_out(i);
3243 if (cast_ii->is_CastII()) {
3244 push_if_not_bottom_type(worklist, cast_ii);
3245 }
3246 }
3247 }
3248 }
3249
3250 void PhaseCCP::push_opaque_zero_trip_guard(Unique_Node_List& worklist, const Node* use) const {
3251 if (use->Opcode() == Op_OpaqueZeroTripGuard) {
3252 push_if_not_bottom_type(worklist, use->unique_out());
3253 }
3254 }
3255
3256 //------------------------------do_transform-----------------------------------
3257 // Top level driver for the recursive transformer
3258 void PhaseCCP::do_transform() {
3259 // Correct leaves of new-space Nodes; they point to old-space.
3260 C->set_root( transform(C->root())->as_Root() );
3261 assert( C->top(), "missing TOP node" );
3262 assert( C->root(), "missing root" );
3263 }
3264
3265 //------------------------------transform--------------------------------------
3266 // Given a Node in old-space, clone him into new-space.
3267 // Convert any of his old-space children into new-space children.
3268 Node *PhaseCCP::transform( Node *n ) {
3269 assert(n->is_Root(), "traversal must start at root");
3270 assert(_root_and_safepoints.member(n), "root (n) must be in list");
3271
3272 ResourceMark rm;
3273 // Map: old node idx -> node after CCP (or nullptr if not yet transformed or useless).
3274 Node_List node_map;
3275 // Pre-allocate to avoid frequent realloc
3276 GrowableArray <Node *> transform_stack(C->live_nodes() >> 1);
3277 // track all visited nodes, so that we can remove the complement
3278 Unique_Node_List useful;
3279
3280 if (KillPathsReachableByDeadTypeNode) {
3281 for (uint i = 0; i < _maybe_top_type_nodes.size(); ++i) {
3282 Node* type_node = _maybe_top_type_nodes.at(i);
3283 if (type(type_node) == Type::TOP) {
3284 ResourceMark rm;
3285 type_node->as_Type()->make_paths_from_here_dead(this, nullptr, "ccp");
3286 }
3287 }
3288 } else {
3289 assert(_maybe_top_type_nodes.size() == 0, "we don't need type nodes");
3290 }
3291
3292 // Initialize the traversal.
3293 // This CCP pass may prove that no exit test for a loop ever succeeds (i.e. the loop is infinite). In that case,
3294 // the logic below doesn't follow any path from Root to the loop body: there's at least one such path but it's proven
3295 // never taken (its type is TOP). As a consequence the node on the exit path that's input to Root (let's call it n) is
3296 // replaced by the top node and the inputs of that node n are not enqueued for further processing. If CCP only works
3297 // through the graph from Root, this causes the loop body to never be processed here even when it's not dead (that
3298 // is reachable from Root following its uses). To prevent that issue, transform() starts walking the graph from Root
3299 // and all safepoints.
3300 for (uint i = 0; i < _root_and_safepoints.size(); ++i) {
3301 Node* nn = _root_and_safepoints.at(i);
3302 Node* new_node = node_map[nn->_idx];
3303 assert(new_node == nullptr, "");
3304 new_node = transform_once(nn); // Check for constant
3305 node_map.map(nn->_idx, new_node); // Flag as having been cloned
3306 transform_stack.push(new_node); // Process children of cloned node
3307 useful.push(new_node);
3308 }
3309
3310 while (transform_stack.is_nonempty()) {
3311 Node* clone = transform_stack.pop();
3312 uint cnt = clone->req();
3313 for( uint i = 0; i < cnt; i++ ) { // For all inputs do
3314 Node *input = clone->in(i);
3315 if( input != nullptr ) { // Ignore nulls
3316 Node *new_input = node_map[input->_idx]; // Check for cloned input node
3317 if( new_input == nullptr ) {
3318 new_input = transform_once(input); // Check for constant
3319 node_map.map( input->_idx, new_input );// Flag as having been cloned
3320 transform_stack.push(new_input); // Process children of cloned node
3321 useful.push(new_input);
3322 }
3323 assert( new_input == clone->in(i), "insanity check");
3324 }
3325 }
3326 }
3327
3328 // The above transformation might lead to subgraphs becoming unreachable from the
3329 // bottom while still being reachable from the top. As a result, nodes in that
3330 // subgraph are not transformed and their bottom types are not updated, leading to
3331 // an inconsistency between bottom_type() and type(). In rare cases, LoadNodes in
3332 // such a subgraph, might be re-enqueued for IGVN indefinitely by MemNode::Ideal_common
3333 // because their address type is inconsistent. Therefore, we aggressively remove
3334 // all useless nodes here even before PhaseIdealLoop::build_loop_late gets a chance
3335 // to remove them anyway.
3336 if (C->cached_top_node()) {
3337 useful.push(C->cached_top_node());
3338 }
3339 C->update_dead_node_list(useful);
3340 remove_useless_nodes(useful.member_set());
3341 _worklist.remove_useless_nodes(useful.member_set());
3342 C->disconnect_useless_nodes(useful, _worklist, &_root_and_safepoints);
3343
3344 Node* new_root = node_map[n->_idx];
3345 assert(new_root->is_Root(), "transformed root node must be a root node");
3346 return new_root;
3347 }
3348
3349 //------------------------------transform_once---------------------------------
3350 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
3351 Node *PhaseCCP::transform_once( Node *n ) {
3352 const Type *t = type(n);
3353 // Constant? Use constant Node instead
3354 if( t->singleton() ) {
3355 Node *nn = n; // Default is to return the original constant
3356 if( t == Type::TOP ) {
3357 // cache my top node on the Compile instance
3358 if( C->cached_top_node() == nullptr || C->cached_top_node()->in(0) == nullptr ) {
3359 C->set_cached_top_node(ConNode::make(Type::TOP));
3360 set_type(C->top(), Type::TOP);
3361 }
3362 nn = C->top();
3363 }
3364 if( !n->is_Con() ) {
3365 if( t != Type::TOP ) {
3366 nn = makecon(t); // ConNode::make(t);
3367 NOT_PRODUCT( inc_constants(); )
3368 } else if( n->is_Region() ) { // Unreachable region
3369 // Note: nn == C->top()
3370 n->set_req(0, nullptr); // Cut selfreference
3371 bool progress = true;
3372 uint max = n->outcnt();
3373 DUIterator i;
3374 while (progress) {
3375 progress = false;
3376 // Eagerly remove dead phis to avoid phis copies creation.
3377 for (i = n->outs(); n->has_out(i); i++) {
3378 Node* m = n->out(i);
3379 if (m->is_Phi()) {
3380 assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
3381 replace_node(m, nn);
3382 if (max != n->outcnt()) {
3383 progress = true;
3384 i = n->refresh_out_pos(i);
3385 max = n->outcnt();
3386 }
3387 }
3388 }
3389 }
3390 }
3391 replace_node(n,nn); // Update DefUse edges for new constant
3392 }
3393 return nn;
3394 }
3395
3396 // If x is a TypeNode, capture any more-precise type permanently into Node
3397 if (t != n->bottom_type()) {
3398 hash_delete(n); // changing bottom type may force a rehash
3399 n->raise_bottom_type(t);
3400 _worklist.push(n); // n re-enters the hash table via the worklist
3401 add_users_to_worklist(n); // if ideal or identity optimizations depend on the input type, users need to be notified
3402 }
3403
3404 // TEMPORARY fix to ensure that 2nd GVN pass eliminates null checks
3405 switch( n->Opcode() ) {
3406 case Op_CallStaticJava: // Give post-parse call devirtualization a chance
3407 case Op_CallDynamicJava:
3408 case Op_FastLock: // Revisit FastLocks for lock coarsening
3409 case Op_If:
3410 case Op_CountedLoopEnd:
3411 case Op_Region:
3412 case Op_Loop:
3413 case Op_CountedLoop:
3414 case Op_Conv2B:
3415 case Op_Opaque1:
3416 _worklist.push(n);
3417 break;
3418 default:
3419 break;
3420 }
3421
3422 return n;
3423 }
3424
3425 //---------------------------------saturate------------------------------------
3426 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
3427 const Type* limit_type) const {
3428 const Type* wide_type = new_type->widen(old_type, limit_type);
3429 if (wide_type != new_type) { // did we widen?
3430 // If so, we may have widened beyond the limit type. Clip it back down.
3431 new_type = wide_type->filter(limit_type);
3432 }
3433 return new_type;
3434 }
3435
3436 //------------------------------print_statistics-------------------------------
3437 #ifndef PRODUCT
3438 void PhaseCCP::print_statistics() {
3439 tty->print_cr("CCP: %d constants found: %d", _total_invokes, _total_constants);
3440 }
3441 #endif
3442
3443
3444 //=============================================================================
3445 #ifndef PRODUCT
3446 uint PhasePeephole::_total_peepholes = 0;
3447 #endif
3448 //------------------------------PhasePeephole----------------------------------
3449 // Conditional Constant Propagation, ala Wegman & Zadeck
3450 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
3451 : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
3452 NOT_PRODUCT( clear_peepholes(); )
3453 }
3454
3455 #ifndef PRODUCT
3456 //------------------------------~PhasePeephole---------------------------------
3457 PhasePeephole::~PhasePeephole() {
3458 _total_peepholes += count_peepholes();
3459 }
3460 #endif
3461
3462 //------------------------------transform--------------------------------------
3463 Node *PhasePeephole::transform( Node *n ) {
3464 ShouldNotCallThis();
3465 return nullptr;
3466 }
3467
3468 //------------------------------do_transform-----------------------------------
3469 void PhasePeephole::do_transform() {
3470 bool method_name_not_printed = true;
3471
3472 // Examine each basic block
3473 for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
3474 Block* block = _cfg.get_block(block_number);
3475 bool block_not_printed = true;
3476
3477 for (bool progress = true; progress;) {
3478 progress = false;
3479 // block->end_idx() not valid after PhaseRegAlloc
3480 uint end_index = block->number_of_nodes();
3481 for( uint instruction_index = end_index - 1; instruction_index > 0; --instruction_index ) {
3482 Node *n = block->get_node(instruction_index);
3483 if( n->is_Mach() ) {
3484 MachNode *m = n->as_Mach();
3485 // check for peephole opportunities
3486 int result = m->peephole(block, instruction_index, &_cfg, _regalloc);
3487 if( result != -1 ) {
3488 #ifndef PRODUCT
3489 if( PrintOptoPeephole ) {
3490 // Print method, first time only
3491 if( C->method() && method_name_not_printed ) {
3492 C->method()->print_short_name(); tty->cr();
3493 method_name_not_printed = false;
3494 }
3495 // Print this block
3496 if( Verbose && block_not_printed) {
3497 tty->print_cr("in block");
3498 block->dump();
3499 block_not_printed = false;
3500 }
3501 // Print the peephole number
3502 tty->print_cr("peephole number: %d", result);
3503 }
3504 inc_peepholes();
3505 #endif
3506 // Set progress, start again
3507 progress = true;
3508 break;
3509 }
3510 }
3511 }
3512 }
3513 }
3514 }
3515
3516 //------------------------------print_statistics-------------------------------
3517 #ifndef PRODUCT
3518 void PhasePeephole::print_statistics() {
3519 tty->print_cr("Peephole: peephole rules applied: %d", _total_peepholes);
3520 }
3521 #endif
3522
3523
3524 //=============================================================================
3525 //------------------------------set_req_X--------------------------------------
3526 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
3527 assert( is_not_dead(n), "can not use dead node");
3528 #ifdef ASSERT
3529 if (igvn->hash_find(this) == this) {
3530 tty->print_cr("Need to remove from hash before changing edges");
3531 this->dump(1);
3532 tty->print_cr("Set at i = %d", i);
3533 n->dump();
3534 assert(false, "Need to remove from hash before changing edges");
3535 }
3536 #endif
3537 Node *old = in(i);
3538 set_req(i, n);
3539
3540 // old goes dead?
3541 if( old ) {
3542 switch (old->outcnt()) {
3543 case 0:
3544 // Put into the worklist to kill later. We do not kill it now because the
3545 // recursive kill will delete the current node (this) if dead-loop exists
3546 if (!old->is_top())
3547 igvn->_worklist.push( old );
3548 break;
3549 case 1:
3550 if( old->is_Store() || old->has_special_unique_user() )
3551 igvn->add_users_to_worklist( old );
3552 break;
3553 case 2:
3554 if( old->is_Store() )
3555 igvn->add_users_to_worklist( old );
3556 if( old->Opcode() == Op_Region )
3557 igvn->_worklist.push(old);
3558 break;
3559 case 3:
3560 if( old->Opcode() == Op_Region ) {
3561 igvn->_worklist.push(old);
3562 igvn->add_users_to_worklist( old );
3563 }
3564 break;
3565 default:
3566 break;
3567 }
3568
3569 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
3570 }
3571 }
3572
3573 void Node::set_req_X(uint i, Node *n, PhaseGVN *gvn) {
3574 PhaseIterGVN* igvn = gvn->is_IterGVN();
3575 if (igvn == nullptr) {
3576 set_req(i, n);
3577 return;
3578 }
3579 set_req_X(i, n, igvn);
3580 }
3581
3582 //-------------------------------replace_by-----------------------------------
3583 // Using def-use info, replace one node for another. Follow the def-use info
3584 // to all users of the OLD node. Then make all uses point to the NEW node.
3585 void Node::replace_by(Node *new_node) {
3586 assert(!is_top(), "top node has no DU info");
3587 for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
3588 Node* use = last_out(i);
3589 uint uses_found = 0;
3590 for (uint j = 0; j < use->len(); j++) {
3591 if (use->in(j) == this) {
3592 if (j < use->req())
3593 use->set_req(j, new_node);
3594 else use->set_prec(j, new_node);
3595 uses_found++;
3596 }
3597 }
3598 i -= uses_found; // we deleted 1 or more copies of this edge
3599 }
3600 }
3601
3602 //=============================================================================
3603 //-----------------------------------------------------------------------------
3604 void Type_Array::grow( uint i ) {
3605 assert(_a == Compile::current()->comp_arena(), "Should be allocated in comp_arena");
3606 if( !_max ) {
3607 _max = 1;
3608 _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
3609 _types[0] = nullptr;
3610 }
3611 uint old = _max;
3612 _max = next_power_of_2(i);
3613 _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
3614 memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
3615 }
3616
3617 //------------------------------dump-------------------------------------------
3618 #ifndef PRODUCT
3619 void Type_Array::dump() const {
3620 uint max = Size();
3621 for( uint i = 0; i < max; i++ ) {
3622 if( _types[i] != nullptr ) {
3623 tty->print(" %d\t== ", i); _types[i]->dump(); tty->cr();
3624 }
3625 }
3626 }
3627 #endif