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   C->print_method(PHASE_BEFORE_LOOP_UNSWITCHING, 4, head);
138 
139   // Need to revert back to normal loop
140   if (head->is_CountedLoop() && !head->as_CountedLoop()->is_normal_loop()) {
141     head->as_CountedLoop()->set_normal_loop();
142   }
143 
144   IfNode* invar_iff = create_slow_version_of_loop(loop, old_new, unswitch_iff, CloneIncludesStripMined);
145   ProjNode* proj_true = invar_iff->proj_out(1);
146   verify_fast_loop(head, proj_true);
147 
148   // Increment unswitch count
149   LoopNode* head_clone = old_new[head->_idx]->as_Loop();
150   int nct = head->unswitch_count() + 1;
151   head->set_unswitch_count(nct);
152   head_clone->set_unswitch_count(nct);
153 
154   // Hoist invariant casts out of each loop to the appropriate
155   // control projection.
156 
157   Node_List worklist;
158   for (DUIterator_Fast imax, i = unswitch_iff->fast_outs(imax); i < imax; i++) {
159     ProjNode* proj= unswitch_iff->fast_out(i)->as_Proj();
160     // Copy to a worklist for easier manipulation
161     for (DUIterator_Fast jmax, j = proj->fast_outs(jmax); j < jmax; j++) {
162       Node* use = proj->fast_out(j);
163       if (use->Opcode() == Op_CheckCastPP && loop->is_invariant(use->in(1))) {
164         worklist.push(use);
165       }
166     }
167     ProjNode* invar_proj = invar_iff->proj_out(proj->_con)->as_Proj();
168     while (worklist.size() > 0) {
169       Node* use = worklist.pop();
170       Node* nuse = use->clone();
171       nuse->set_req(0, invar_proj);
172       _igvn.replace_input_of(use, 1, nuse);
173       register_new_node(nuse, invar_proj);
174       // Same for the clone
175       Node* use_clone = old_new[use->_idx];
176       _igvn.replace_input_of(use_clone, 1, nuse);
177     }
178   }
179 
180   // Hardwire the control paths in the loops into if(true) and if(false)
181   _igvn.rehash_node_delayed(unswitch_iff);
182   dominated_by(proj_true->as_IfProj(), unswitch_iff);
183 
184   IfNode* unswitch_iff_clone = old_new[unswitch_iff->_idx]->as_If();
185   _igvn.rehash_node_delayed(unswitch_iff_clone);
186   ProjNode* proj_false = invar_iff->proj_out(0);
187   dominated_by(proj_false->as_IfProj(), unswitch_iff_clone);
188 
189   // Reoptimize loops
190   loop->record_for_igvn();
191   for(int i = loop->_body.size() - 1; i >= 0 ; i--) {
192     Node *n = loop->_body[i];
193     Node *n_clone = old_new[n->_idx];
194     _igvn._worklist.push(n_clone);
195   }
196 
197 #ifndef PRODUCT
198   if (TraceLoopUnswitching) {
199     tty->print_cr("Loop unswitching orig: %d @ %d  new: %d @ %d",
200                   head->_idx,                unswitch_iff->_idx,
201                   old_new[head->_idx]->_idx, unswitch_iff_clone->_idx);
202   }
203 #endif
204 
205   C->print_method(PHASE_AFTER_LOOP_UNSWITCHING, 4, head_clone);
206 
207   C->set_major_progress();
208 }
209 
210 bool PhaseIdealLoop::has_control_dependencies_from_predicates(LoopNode* head) const {
211   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
212   Predicates predicates(entry);
213   if (predicates.has_any()) {
214     assert(entry->is_IfProj(), "sanity - must be ifProj since there is at least one predicate");
215     if (entry->outcnt() > 1) {
216       // Bailout if there are predicates from which there are additional control dependencies (i.e. from loop
217       // entry 'entry') to previously partially peeled statements since this case is not handled and can lead
218       // to a wrong execution. Remove this bailout, once this is fixed.
219       return true;
220     }
221   }
222   return false;
223 }
224 
225 //-------------------------create_slow_version_of_loop------------------------
226 // Create a slow version of the loop by cloning the loop
227 // and inserting an if to select fast-slow versions.
228 // Return the inserted if.
229 IfNode* PhaseIdealLoop::create_slow_version_of_loop(IdealLoopTree *loop,
230                                                       Node_List &old_new,
231                                                       IfNode* unswitch_iff,
232                                                       CloneLoopMode mode) {
233   LoopNode* head  = loop->_head->as_Loop();
234   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
235   _igvn.rehash_node_delayed(entry);
236   IdealLoopTree* outer_loop = loop->_parent;
237 
238   head->verify_strip_mined(1);
239 
240   // Add test to new "if" outside of loop
241   Node *bol   = unswitch_iff->in(1)->as_Bool();
242   IfNode* iff = (unswitch_iff->Opcode() == Op_RangeCheck) ? new RangeCheckNode(entry, bol, unswitch_iff->_prob, unswitch_iff->_fcnt) :
243     new IfNode(entry, bol, unswitch_iff->_prob, unswitch_iff->_fcnt);
244   register_node(iff, outer_loop, entry, dom_depth(entry));
245   IfProjNode* iffast = new IfTrueNode(iff);
246   register_node(iffast, outer_loop, iff, dom_depth(iff));
247   IfProjNode* ifslow = new IfFalseNode(iff);
248   register_node(ifslow, outer_loop, iff, dom_depth(iff));
249 
250   // Clone the loop body.  The clone becomes the slow loop.  The
251   // original pre-header will (illegally) have 3 control users
252   // (old & new loops & new if).
253   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), mode, iff);
254   assert(old_new[head->_idx]->is_Loop(), "" );
255 
256   // Fast (true) and Slow (false) control
257   IfProjNode* iffast_pred = iffast;
258   IfProjNode* ifslow_pred = ifslow;
259   clone_parse_and_assertion_predicates_to_unswitched_loop(loop, old_new, iffast_pred, ifslow_pred);
260 
261   Node* l = head->skip_strip_mined();
262   _igvn.replace_input_of(l, LoopNode::EntryControl, iffast_pred);
263   set_idom(l, iffast_pred, dom_depth(l));
264   LoopNode* slow_l = old_new[head->_idx]->as_Loop()->skip_strip_mined();
265   _igvn.replace_input_of(slow_l, LoopNode::EntryControl, ifslow_pred);
266   set_idom(slow_l, ifslow_pred, dom_depth(l));
267 
268   recompute_dom_depth();
269 
270   return iff;
271 }
272 
273 #ifdef ASSERT
274 void PhaseIdealLoop::verify_fast_loop(LoopNode* head, const ProjNode* proj_true) const {
275   assert(proj_true->is_IfTrue(), "must be true projection");
276   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
277   Predicates predicates(entry);
278   if (!predicates.has_any()) {
279     // No Parse Predicate.
280     Node* uniqc = proj_true->unique_ctrl_out();
281     assert((uniqc == head && !head->is_strip_mined()) || (uniqc == head->in(LoopNode::EntryControl)
282                                                           && head->is_strip_mined()), "must hold by construction if no predicates");
283   } else {
284     // There is at least one Parse Predicate. When skipping all predicates/predicate blocks, we should end up
285     // at 'proj_true'.
286     assert(proj_true == predicates.entry(), "must hold by construction if at least one Parse Predicate");
287   }
288 }
289 #endif // ASSERT
290