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