1 /*
  2  * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "memory/allocation.inline.hpp"
 27 #include "opto/mulnode.hpp"
 28 #include "opto/addnode.hpp"
 29 #include "opto/connode.hpp"
 30 #include "opto/convertnode.hpp"
 31 #include "opto/loopnode.hpp"
 32 #include "opto/opaquenode.hpp"
 33 #include "opto/predicates.hpp"
 34 #include "opto/rootnode.hpp"
 35 
 36 //================= Loop Unswitching =====================
 37 //
 38 // orig:                       transformed:
 39 //                               if (invariant-test) then
 40 //  predicates                     predicates
 41 //  loop                           loop
 42 //    stmt1                          stmt1
 43 //    if (invariant-test) then       stmt2
 44 //      stmt2                        stmt4
 45 //    else                         endloop
 46 //      stmt3                    else
 47 //    endif                        predicates [clone]
 48 //    stmt4                        loop [clone]
 49 //  endloop                          stmt1 [clone]
 50 //                                   stmt3
 51 //                                   stmt4 [clone]
 52 //                                 endloop
 53 //                               endif
 54 //
 55 // Note: the "else" clause may be empty
 56 
 57 
 58 //------------------------------policy_unswitching-----------------------------
 59 // Return TRUE or FALSE if the loop should be unswitched
 60 // (ie. clone loop with an invariant test that does not exit the loop)
 61 bool IdealLoopTree::policy_unswitching( PhaseIdealLoop *phase ) const {
 62   if (!LoopUnswitching) {
 63     return false;
 64   }
 65   if (!_head->is_Loop()) {
 66     return false;
 67   }
 68 
 69   // If nodes are depleted, some transform has miscalculated its needs.
 70   assert(!phase->exceeding_node_budget(), "sanity");
 71 
 72   // check for vectorized loops, any unswitching was already applied
 73   if (_head->is_CountedLoop() && _head->as_CountedLoop()->is_unroll_only()) {
 74     return false;
 75   }
 76 
 77   LoopNode* head = _head->as_Loop();
 78   if (head->unswitch_count() + 1 > head->unswitch_max()) {
 79     return false;
 80   }
 81 
 82   if (head->is_flat_arrays()) {
 83     return false;
 84   }
 85 
 86   Node_List unswitch_iffs;
 87   if (phase->find_unswitching_candidate(this, unswitch_iffs) == nullptr) {
 88     return false;
 89   }
 90 
 91   // Too speculative if running low on nodes.
 92   return phase->may_require_nodes(est_loop_clone_sz(2));
 93 }
 94 
 95 //------------------------------find_unswitching_candidate-----------------------------
 96 // Find candidate "if" for unswitching
 97 IfNode* PhaseIdealLoop::find_unswitching_candidate(const IdealLoopTree *loop, Node_List& unswitch_iffs) const {
 98 
 99   // Find first invariant test that doesn't exit the loop
100   LoopNode *head = loop->_head->as_Loop();
101   IfNode* unswitch_iff = nullptr;
102   Node* n = head->in(LoopNode::LoopBackControl);
103   while (n != head) {
104     Node* n_dom = idom(n);
105     if (n->is_Region()) {
106       if (n_dom->is_If()) {
107         IfNode* iff = n_dom->as_If();
108         if (iff->in(1)->is_Bool()) {
109           BoolNode* bol = iff->in(1)->as_Bool();
110           if (bol->in(1)->is_Cmp()) {
111             // If condition is invariant and not a loop exit,
112             // then found reason to unswitch.
113             if (loop->is_invariant(bol) && !loop->is_loop_exit(iff)) {
114               unswitch_iff = iff;
115             }
116           }
117         }
118       }
119     }
120     n = n_dom;
121   }
122   if (unswitch_iff != nullptr) {
123     unswitch_iffs.push(unswitch_iff);
124   }
125 
126   // Collect all non-flat array checks for unswitching to create a fast loop
127   // without checks (only non-flat array accesses) and a slow loop with checks.
128   if (unswitch_iff == nullptr || unswitch_iff->is_flat_array_check(&_igvn)) {
129     for (uint i = 0; i < loop->_body.size(); i++) {
130       IfNode* n = loop->_body.at(i)->isa_If();
131       if (n != nullptr && n != unswitch_iff && n->is_flat_array_check(&_igvn) &&
132           loop->is_invariant(n->in(1)) && !loop->is_loop_exit(n)) {
133         unswitch_iffs.push(n);
134         if (unswitch_iff == nullptr) {
135           unswitch_iff = n;
136         }
137       }
138     }
139   }
140   return unswitch_iff;
141 }
142 
143 //------------------------------do_unswitching-----------------------------
144 // Clone loop with an invariant test (that does not exit) and
145 // insert a clone of the test that selects which version to
146 // execute.
147 void PhaseIdealLoop::do_unswitching(IdealLoopTree *loop, Node_List &old_new) {
148   LoopNode* head = loop->_head->as_Loop();
149   if (has_control_dependencies_from_predicates(head)) {
150     return;
151   }
152 
153   // Find first invariant test that doesn't exit the loop
154   Node_List unswitch_iffs;
155   IfNode* unswitch_iff = find_unswitching_candidate((const IdealLoopTree *)loop, unswitch_iffs);
156   assert(unswitch_iff != nullptr && unswitch_iff == unswitch_iffs.at(0), "should be at least one");
157   bool flat_array_checks = unswitch_iffs.size() > 1;
158 
159 #ifndef PRODUCT
160   if (TraceLoopOpts) {
161     tty->print("Unswitch   %d ", head->unswitch_count()+1);
162     loop->dump_head();
163     for (uint i = 0; i < unswitch_iffs.size(); i++) {
164       unswitch_iffs.at(i)->dump(3);
165       tty->cr();
166     }
167   }
168 #endif
169 
170   // Need to revert back to normal loop
171   if (head->is_CountedLoop() && !head->as_CountedLoop()->is_normal_loop()) {
172     head->as_CountedLoop()->set_normal_loop();
173   }
174 
175   IfNode* invar_iff = create_slow_version_of_loop(loop, old_new, unswitch_iffs, CloneIncludesStripMined);
176   ProjNode* proj_true = invar_iff->proj_out(1);
177   verify_fast_loop(head, proj_true);
178 
179   // Increment unswitch count
180   LoopNode* head_clone = old_new[head->_idx]->as_Loop();
181   int nct = head->unswitch_count() + 1;
182   head->set_unswitch_count(nct);
183   head_clone->set_unswitch_count(nct);
184 
185   // Hoist invariant casts out of each loop to the appropriate control projection.
186   Node_List worklist;
187   for (uint i = 0; i < unswitch_iffs.size(); i++) {
188     IfNode* iff = unswitch_iffs.at(i)->as_If();
189     for (DUIterator_Fast imax, i = iff->fast_outs(imax); i < imax; i++) {
190       ProjNode* proj = iff->fast_out(i)->as_Proj();
191       // Copy to a worklist for easier manipulation
192       for (DUIterator_Fast jmax, j = proj->fast_outs(jmax); j < jmax; j++) {
193         Node* use = proj->fast_out(j);
194         if (use->Opcode() == Op_CheckCastPP && loop->is_invariant(use->in(1))) {
195           worklist.push(use);
196         }
197       }
198       ProjNode* invar_proj = invar_iff->proj_out(proj->_con)->as_Proj();
199       while (worklist.size() > 0) {
200         Node* use = worklist.pop();
201         Node* nuse = use->clone();
202         nuse->set_req(0, invar_proj);
203         _igvn.replace_input_of(use, 1, nuse);
204         register_new_node(nuse, invar_proj);
205         // Same for the clone if we are removing checks from the slow loop
206         if (!flat_array_checks) {
207           Node* use_clone = old_new[use->_idx];
208           _igvn.replace_input_of(use_clone, 1, nuse);
209         }
210       }
211     }
212   }
213 
214   // Hardwire the control paths in the loops into if(true) and if(false)
215   for (uint i = 0; i < unswitch_iffs.size(); i++) {
216     IfNode* iff = unswitch_iffs.at(i)->as_If();
217     _igvn.rehash_node_delayed(iff);
218     dominated_by(proj_true->as_IfProj(), iff);
219   }
220   IfNode* unswitch_iff_clone = old_new[unswitch_iff->_idx]->as_If();
221   if (!flat_array_checks) {
222     ProjNode* proj_false = invar_iff->proj_out(0)->as_Proj();
223     _igvn.rehash_node_delayed(unswitch_iff_clone);
224     dominated_by(proj_false->as_IfProj(), unswitch_iff_clone);
225   } else {
226     // Leave the flat array checks in the slow loop and
227     // prevent it from being unswitched again based on these checks.
228     head_clone->mark_flat_arrays();
229   }
230 
231   // Reoptimize loops
232   loop->record_for_igvn();
233   for(int i = loop->_body.size() - 1; i >= 0 ; i--) {
234     Node *n = loop->_body[i];
235     Node *n_clone = old_new[n->_idx];
236     _igvn._worklist.push(n_clone);
237   }
238 
239 #ifndef PRODUCT
240   if (TraceLoopUnswitching) {
241     for (uint i = 0; i < unswitch_iffs.size(); i++) {
242       tty->print_cr("Loop unswitching orig: %d @ %d  new: %d @ %d",
243                     head->_idx,                unswitch_iffs.at(i)->_idx,
244                     old_new[head->_idx]->_idx, old_new[unswitch_iffs.at(i)->_idx]->_idx);
245     }
246   }
247 #endif
248 
249   C->set_major_progress();
250 }
251 
252 bool PhaseIdealLoop::has_control_dependencies_from_predicates(LoopNode* head) const {
253   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
254   Predicates predicates(entry);
255   if (predicates.has_any()) {
256     assert(entry->is_IfProj(), "sanity - must be ifProj since there is at least one predicate");
257     if (entry->outcnt() > 1) {
258       // Bailout if there are predicates from which there are additional control dependencies (i.e. from loop
259       // entry 'entry') to previously partially peeled statements since this case is not handled and can lead
260       // to a wrong execution. Remove this bailout, once this is fixed.
261       return true;
262     }
263   }
264   return false;
265 }
266 
267 //-------------------------create_slow_version_of_loop------------------------
268 // Create a slow version of the loop by cloning the loop
269 // and inserting an if to select fast-slow versions.
270 // Return the inserted if.
271 IfNode* PhaseIdealLoop::create_slow_version_of_loop(IdealLoopTree *loop,
272                                                     Node_List &old_new,
273                                                     Node_List &unswitch_iffs,
274                                                     CloneLoopMode mode) {
275   LoopNode* head  = loop->_head->as_Loop();
276   bool counted_loop = head->is_CountedLoop();
277   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
278   _igvn.rehash_node_delayed(entry);
279   IdealLoopTree* outer_loop = loop->_parent;
280 
281   head->verify_strip_mined(1);
282 
283   // Add test to new "if" outside of loop
284   IfNode* unswitch_iff = unswitch_iffs.at(0)->as_If();
285   BoolNode* bol = unswitch_iff->in(1)->as_Bool();
286   if (unswitch_iffs.size() > 1) {
287     // Flat array checks are used on array access to switch between
288     // a legacy object array access and a flat inline type array
289     // access. We want the performance impact on legacy accesses to be
290     // as small as possible so we make two copies of the loop: a fast
291     // one where all accesses are known to be legacy, a slow one where
292     // some accesses are to flat arrays. Flat array checks
293     // can be removed from the fast loop (true proj) but not from the
294     // slow loop (false proj) as it can have a mix of flat/legacy accesses.
295     assert(bol->_test._test == BoolTest::ne, "IfTrue proj must point to flat array");
296     bol = bol->clone()->as_Bool();
297     register_new_node(bol, entry);
298     FlatArrayCheckNode* cmp = bol->in(1)->clone()->as_FlatArrayCheck();
299     register_new_node(cmp, entry);
300     bol->set_req(1, cmp);
301     // Combine all checks into a single one that fails if one array is a flat array
302     assert(cmp->req() == 3, "unexpected number of inputs for FlatArrayCheck");
303     cmp->add_req_batch(C->top(), unswitch_iffs.size() - 1);
304     for (uint i = 0; i < unswitch_iffs.size(); i++) {
305       Node* array = unswitch_iffs.at(i)->in(1)->in(1)->in(FlatArrayCheckNode::ArrayOrKlass);
306       cmp->set_req(FlatArrayCheckNode::ArrayOrKlass + i, array);
307     }
308   }
309 
310   IfNode* iff = (unswitch_iff->Opcode() == Op_RangeCheck) ? new RangeCheckNode(entry, bol, unswitch_iff->_prob, unswitch_iff->_fcnt) :
311       new IfNode(entry, bol, unswitch_iff->_prob, unswitch_iff->_fcnt);
312   register_node(iff, outer_loop, entry, dom_depth(entry));
313   IfProjNode* iffast = new IfTrueNode(iff);
314   register_node(iffast, outer_loop, iff, dom_depth(iff));
315   IfProjNode* ifslow = new IfFalseNode(iff);
316   register_node(ifslow, outer_loop, iff, dom_depth(iff));
317 
318   // Clone the loop body.  The clone becomes the slow loop.  The
319   // original pre-header will (illegally) have 3 control users
320   // (old & new loops & new if).
321   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), mode, iff);
322   assert(old_new[head->_idx]->is_Loop(), "" );
323 
324   // Fast (true) and Slow (false) control
325   IfProjNode* iffast_pred = iffast;
326   IfProjNode* ifslow_pred = ifslow;
327   clone_parse_and_assertion_predicates_to_unswitched_loop(loop, old_new, iffast_pred, ifslow_pred);
328 
329   Node* l = head->skip_strip_mined();
330   _igvn.replace_input_of(l, LoopNode::EntryControl, iffast_pred);
331   set_idom(l, iffast_pred, dom_depth(l));
332   LoopNode* slow_l = old_new[head->_idx]->as_Loop()->skip_strip_mined();
333   _igvn.replace_input_of(slow_l, LoopNode::EntryControl, ifslow_pred);
334   set_idom(slow_l, ifslow_pred, dom_depth(l));
335 
336   recompute_dom_depth();
337 
338   return iff;
339 }
340 
341 #ifdef ASSERT
342 void PhaseIdealLoop::verify_fast_loop(LoopNode* head, const ProjNode* proj_true) const {
343   assert(proj_true->is_IfTrue(), "must be true projection");
344   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
345   Predicates predicates(entry);
346   if (!predicates.has_any()) {
347     // No Parse Predicate.
348     Node* uniqc = proj_true->unique_ctrl_out();
349     assert((uniqc == head && !head->is_strip_mined()) || (uniqc == head->in(LoopNode::EntryControl)
350                                                           && head->is_strip_mined()), "must hold by construction if no predicates");
351   } else {
352     // There is at least one Parse Predicate. When skipping all predicates/predicate blocks, we should end up
353     // at 'proj_true'.
354     assert(proj_true == predicates.entry(), "must hold by construction if at least one Parse Predicate");
355   }
356 }
357 #endif // ASSERT
358