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/connode.hpp"
 28 #include "opto/convertnode.hpp"
 29 #include "opto/loopnode.hpp"
 30 #include "opto/opaquenode.hpp"
 31 #include "opto/predicates.hpp"
 32 #include "opto/rootnode.hpp"
 33 
 34 //================= Loop Unswitching =====================
 35 //
 36 // orig:                       transformed:
 37 //                               if (invariant-test) then
 38 //  predicates                     predicates
 39 //  loop                           loop
 40 //    stmt1                          stmt1
 41 //    if (invariant-test) then       stmt2
 42 //      stmt2                        stmt4
 43 //    else                         endloop
 44 //      stmt3                    else
 45 //    endif                        predicates [clone]
 46 //    stmt4                        loop [clone]
 47 //  endloop                          stmt1 [clone]
 48 //                                   stmt3
 49 //                                   stmt4 [clone]
 50 //                                 endloop
 51 //                               endif
 52 //
 53 // Note: the "else" clause may be empty
 54 
 55 //------------------------------policy_unswitching-----------------------------
 56 // Return TRUE or FALSE if the loop should be unswitched
 57 // (ie. clone loop with an invariant test that does not exit the loop)
 58 bool IdealLoopTree::policy_unswitching( PhaseIdealLoop *phase ) const {
 59   if (!LoopUnswitching) {
 60     return false;
 61   }
 62   if (!_head->is_Loop()) {
 63     return false;
 64   }
 65 
 66   // If nodes are depleted, some transform has miscalculated its needs.
 67   assert(!phase->exceeding_node_budget(), "sanity");
 68 
 69   // check for vectorized loops, any unswitching was already applied
 70   if (_head->is_CountedLoop() && _head->as_CountedLoop()->is_unroll_only()) {
 71     return false;
 72   }
 73 
 74   LoopNode* head = _head->as_Loop();
 75   if (head->unswitch_count() + 1 > head->unswitch_max()) {
 76     return false;
 77   }
 78   if (phase->find_unswitching_candidate(this) == nullptr) {
 79     return false;
 80   }
 81 
 82   // Too speculative if running low on nodes.
 83   return phase->may_require_nodes(est_loop_clone_sz(2));
 84 }
 85 
 86 //------------------------------find_unswitching_candidate-----------------------------
 87 // Find candidate "if" for unswitching
 88 IfNode* PhaseIdealLoop::find_unswitching_candidate(const IdealLoopTree *loop) const {
 89 
 90   // Find first invariant test that doesn't exit the loop
 91   LoopNode *head = loop->_head->as_Loop();
 92   IfNode* unswitch_iff = nullptr;
 93   Node* n = head->in(LoopNode::LoopBackControl);
 94   while (n != head) {
 95     Node* n_dom = idom(n);
 96     if (n->is_Region()) {
 97       if (n_dom->is_If()) {
 98         IfNode* iff = n_dom->as_If();
 99         if (iff->in(1)->is_Bool()) {
100           BoolNode* bol = iff->in(1)->as_Bool();
101           if (bol->in(1)->is_Cmp()) {
102             // If condition is invariant and not a loop exit,
103             // then found reason to unswitch.
104             if (loop->is_invariant(bol) && !loop->is_loop_exit(iff)) {
105               unswitch_iff = iff;
106             }
107           }
108         }
109       }
110     }
111     n = n_dom;
112   }
113   return unswitch_iff;
114 }
115 
116 //------------------------------do_unswitching-----------------------------
117 // Clone loop with an invariant test (that does not exit) and
118 // insert a clone of the test that selects which version to
119 // execute.
120 void PhaseIdealLoop::do_unswitching(IdealLoopTree *loop, Node_List &old_new) {
121   LoopNode* head = loop->_head->as_Loop();
122   if (has_control_dependencies_from_predicates(head)) {
123     return;
124   }
125 
126   // Find first invariant test that doesn't exit the loop
127   IfNode* unswitch_iff = find_unswitching_candidate((const IdealLoopTree *)loop);
128   assert(unswitch_iff != nullptr, "should be at least one");
129 
130 #ifndef PRODUCT
131   if (TraceLoopOpts) {
132     tty->print("Unswitch   %d ", head->unswitch_count()+1);
133     loop->dump_head();
134   }
135 #endif
136 
137   // Need to revert back to normal loop
138   if (head->is_CountedLoop() && !head->as_CountedLoop()->is_normal_loop()) {
139     head->as_CountedLoop()->set_normal_loop();
140   }
141 
142   IfNode* invar_iff = create_slow_version_of_loop(loop, old_new, unswitch_iff, CloneIncludesStripMined);
143   ProjNode* proj_true = invar_iff->proj_out(1);
144   verify_fast_loop(head, proj_true);
145 
146   // Increment unswitch count
147   LoopNode* head_clone = old_new[head->_idx]->as_Loop();
148   int nct = head->unswitch_count() + 1;
149   head->set_unswitch_count(nct);
150   head_clone->set_unswitch_count(nct);
151 
152   // Hoist invariant casts out of each loop to the appropriate
153   // control projection.
154 
155   Node_List worklist;
156   for (DUIterator_Fast imax, i = unswitch_iff->fast_outs(imax); i < imax; i++) {
157     ProjNode* proj= unswitch_iff->fast_out(i)->as_Proj();
158     // Copy to a worklist for easier manipulation
159     for (DUIterator_Fast jmax, j = proj->fast_outs(jmax); j < jmax; j++) {
160       Node* use = proj->fast_out(j);
161       if (use->Opcode() == Op_CheckCastPP && loop->is_invariant(use->in(1))) {
162         worklist.push(use);
163       }
164     }
165     ProjNode* invar_proj = invar_iff->proj_out(proj->_con)->as_Proj();
166     while (worklist.size() > 0) {
167       Node* use = worklist.pop();
168       Node* nuse = use->clone();
169       nuse->set_req(0, invar_proj);
170       _igvn.replace_input_of(use, 1, nuse);
171       register_new_node(nuse, invar_proj);
172       // Same for the clone
173       Node* use_clone = old_new[use->_idx];
174       _igvn.replace_input_of(use_clone, 1, nuse);
175     }
176   }
177 
178   // Hardwire the control paths in the loops into if(true) and if(false)
179   _igvn.rehash_node_delayed(unswitch_iff);
180   dominated_by(proj_true->as_IfProj(), unswitch_iff, false, false);
181 
182   IfNode* unswitch_iff_clone = old_new[unswitch_iff->_idx]->as_If();
183   _igvn.rehash_node_delayed(unswitch_iff_clone);
184   ProjNode* proj_false = invar_iff->proj_out(0);
185   dominated_by(proj_false->as_IfProj(), unswitch_iff_clone, false, false);
186 
187   // Reoptimize loops
188   loop->record_for_igvn();
189   for(int i = loop->_body.size() - 1; i >= 0 ; i--) {
190     Node *n = loop->_body[i];
191     Node *n_clone = old_new[n->_idx];
192     _igvn._worklist.push(n_clone);
193   }
194 
195 #ifndef PRODUCT
196   if (TraceLoopUnswitching) {
197     tty->print_cr("Loop unswitching orig: %d @ %d  new: %d @ %d",
198                   head->_idx,                unswitch_iff->_idx,
199                   old_new[head->_idx]->_idx, unswitch_iff_clone->_idx);
200   }
201 #endif
202 
203   C->set_major_progress();
204 }
205 
206 bool PhaseIdealLoop::has_control_dependencies_from_predicates(LoopNode* head) const {
207   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
208   Predicates predicates(entry);
209   if (predicates.has_any()) {
210     assert(entry->is_IfProj(), "sanity - must be ifProj since there is at least one predicate");
211     if (entry->outcnt() > 1) {
212       // Bailout if there are predicates from which there are additional control dependencies (i.e. from loop
213       // entry 'entry') to previously partially peeled statements since this case is not handled and can lead
214       // to a wrong execution. Remove this bailout, once this is fixed.
215       return true;
216     }
217   }
218   return false;
219 }
220 
221 //-------------------------create_slow_version_of_loop------------------------
222 // Create a slow version of the loop by cloning the loop
223 // and inserting an if to select fast-slow versions.
224 // Return the inserted if.
225 IfNode* PhaseIdealLoop::create_slow_version_of_loop(IdealLoopTree *loop,
226                                                       Node_List &old_new,
227                                                       IfNode* unswitch_iff,
228                                                       CloneLoopMode mode) {
229   LoopNode* head  = loop->_head->as_Loop();
230   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
231   _igvn.rehash_node_delayed(entry);
232   IdealLoopTree* outer_loop = loop->_parent;
233 
234   head->verify_strip_mined(1);
235 
236   // Add test to new "if" outside of loop
237   Node *bol   = unswitch_iff->in(1)->as_Bool();
238   IfNode* iff = (unswitch_iff->Opcode() == Op_RangeCheck) ? new RangeCheckNode(entry, bol, unswitch_iff->_prob, unswitch_iff->_fcnt) :
239     new IfNode(entry, bol, unswitch_iff->_prob, unswitch_iff->_fcnt);
240   register_node(iff, outer_loop, entry, dom_depth(entry));
241   IfProjNode* iffast = new IfTrueNode(iff);
242   register_node(iffast, outer_loop, iff, dom_depth(iff));
243   IfProjNode* ifslow = new IfFalseNode(iff);
244   register_node(ifslow, outer_loop, iff, dom_depth(iff));
245 
246   // Clone the loop body.  The clone becomes the slow loop.  The
247   // original pre-header will (illegally) have 3 control users
248   // (old & new loops & new if).
249   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), mode, iff);
250   assert(old_new[head->_idx]->is_Loop(), "" );
251 
252   // Fast (true) and Slow (false) control
253   IfProjNode* iffast_pred = iffast;
254   IfProjNode* ifslow_pred = ifslow;
255   clone_parse_and_assertion_predicates_to_unswitched_loop(loop, old_new, iffast_pred, ifslow_pred);
256 
257   Node* l = head->skip_strip_mined();
258   _igvn.replace_input_of(l, LoopNode::EntryControl, iffast_pred);
259   set_idom(l, iffast_pred, dom_depth(l));
260   LoopNode* slow_l = old_new[head->_idx]->as_Loop()->skip_strip_mined();
261   _igvn.replace_input_of(slow_l, LoopNode::EntryControl, ifslow_pred);
262   set_idom(slow_l, ifslow_pred, dom_depth(l));
263 
264   recompute_dom_depth();
265 
266   return iff;
267 }
268 
269 #ifdef ASSERT
270 void PhaseIdealLoop::verify_fast_loop(LoopNode* head, const ProjNode* proj_true) const {
271   assert(proj_true->is_IfTrue(), "must be true projection");
272   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
273   Predicates predicates(entry);
274   if (!predicates.has_any()) {
275     // No Parse Predicate.
276     Node* uniqc = proj_true->unique_ctrl_out();
277     assert((uniqc == head && !head->is_strip_mined()) || (uniqc == head->in(LoopNode::EntryControl)
278                                                           && head->is_strip_mined()), "must hold by construction if no predicates");
279   } else {
280     // There is at least one Parse Predicate. When skipping all predicates/predicate blocks, we should end up
281     // at 'proj_true'.
282     assert(proj_true == predicates.entry(), "must hold by construction if at least one Parse Predicate");
283   }
284 }
285 #endif // ASSERT
286