1 /*
2  * Copyright (c) 2006, 2019, 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/rootnode.hpp"
32 
33 //================= Loop Unswitching =====================
34 //
35 // orig:                       transformed:
36 //                               if (invariant-test) then
37 //  predicate                      predicate
38 //  loop                           loop
39 //    stmt1                          stmt1
40 //    if (invariant-test) then       stmt2
41 //      stmt2                        stmt4
42 //    else                         endloop
43 //      stmt3                    else
44 //    endif                        predicate [clone]
45 //    stmt4                        loop [clone]
46 //  endloop                          stmt1 [clone]
47 //                                   stmt3
48 //                                   stmt4 [clone]
49 //                                 endloop
50 //                               endif
51 //
52 // Note: the "else" clause may be empty
53 
54 //------------------------------policy_unswitching-----------------------------
55 // Return TRUE or FALSE if the loop should be unswitched
56 // (ie. clone loop with an invariant test that does not exit the loop)
policy_unswitching(PhaseIdealLoop * phase) const57 bool IdealLoopTree::policy_unswitching( PhaseIdealLoop *phase ) const {
58   if (!LoopUnswitching) {
59     return false;
60   }
61   if (!_head->is_Loop()) {
62     return false;
63   }
64 
65   // If nodes are depleted, some transform has miscalculated its needs.
66   assert(!phase->exceeding_node_budget(), "sanity");
67 
68   // check for vectorized loops, any unswitching was already applied
69   if (_head->is_CountedLoop() && _head->as_CountedLoop()->is_unroll_only()) {
70     return false;
71   }
72 
73   LoopNode* head = _head->as_Loop();
74   if (head->unswitch_count() + 1 > head->unswitch_max()) {
75     return false;
76   }
77   if (phase->find_unswitching_candidate(this) == NULL) {
78     return false;
79   }
80 
81   // Too speculative if running low on nodes.
82   return phase->may_require_nodes(est_loop_clone_sz(2));
83 }
84 
85 //------------------------------find_unswitching_candidate-----------------------------
86 // Find candidate "if" for unswitching
find_unswitching_candidate(const IdealLoopTree * loop) const87 IfNode* PhaseIdealLoop::find_unswitching_candidate(const IdealLoopTree *loop) const {
88 
89   // Find first invariant test that doesn't exit the loop
90   LoopNode *head = loop->_head->as_Loop();
91   IfNode* unswitch_iff = NULL;
92   Node* n = head->in(LoopNode::LoopBackControl);
93   while (n != head) {
94     Node* n_dom = idom(n);
95     if (n->is_Region()) {
96       if (n_dom->is_If()) {
97         IfNode* iff = n_dom->as_If();
98         if (iff->in(1)->is_Bool()) {
99           BoolNode* bol = iff->in(1)->as_Bool();
100           if (bol->in(1)->is_Cmp()) {
101             // If condition is invariant and not a loop exit,
102             // then found reason to unswitch.
103             if (loop->is_invariant(bol) && !loop->is_loop_exit(iff)) {
104               unswitch_iff = iff;
105             }
106           }
107         }
108       }
109     }
110     n = n_dom;
111   }
112   return unswitch_iff;
113 }
114 
115 //------------------------------do_unswitching-----------------------------
116 // Clone loop with an invariant test (that does not exit) and
117 // insert a clone of the test that selects which version to
118 // execute.
do_unswitching(IdealLoopTree * loop,Node_List & old_new)119 void PhaseIdealLoop::do_unswitching(IdealLoopTree *loop, Node_List &old_new) {
120 
121   LoopNode *head = loop->_head->as_Loop();
122   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
123   if (find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check) != NULL
124       || (UseProfiledLoopPredicate && find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate) != NULL)
125       || (UseLoopPredicate && find_predicate_insertion_point(entry, Deoptimization::Reason_predicate) != NULL)) {
126     assert(entry->is_IfProj(), "sanity - must be ifProj since there is at least one predicate");
127     if (entry->outcnt() > 1) {
128       // Bailout if there are loop predicates from which there are additional control dependencies (i.e. from
129       // loop entry 'entry') to previously partially peeled statements since this case is not handled and can lead
130       // to wrong execution. Remove this bailout, once this is fixed.
131       return;
132     }
133   }
134   // Find first invariant test that doesn't exit the loop
135   IfNode* unswitch_iff = find_unswitching_candidate((const IdealLoopTree *)loop);
136   assert(unswitch_iff != NULL, "should be at least one");
137 
138 #ifndef PRODUCT
139   if (TraceLoopOpts) {
140     tty->print("Unswitch   %d ", head->unswitch_count()+1);
141     loop->dump_head();
142   }
143 #endif
144 
145   // Need to revert back to normal loop
146   if (head->is_CountedLoop() && !head->as_CountedLoop()->is_normal_loop()) {
147     head->as_CountedLoop()->set_normal_loop();
148   }
149 
150   ProjNode* proj_true = create_slow_version_of_loop(loop, old_new, unswitch_iff->Opcode(), CloneIncludesStripMined);
151 
152 #ifdef ASSERT
153   assert(proj_true->is_IfTrue(), "must be true projection");
154   entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
155   Node* predicate = find_predicate(entry);
156   if (predicate == NULL) {
157     // No empty predicate
158     Node* uniqc = proj_true->unique_ctrl_out();
159     assert((uniqc == head && !head->is_strip_mined()) || (uniqc == head->in(LoopNode::EntryControl)
160            && head->is_strip_mined()), "must hold by construction if no predicates");
161   } else {
162     // There is at least one empty predicate. When calling 'skip_loop_predicates' on each found empty predicate,
163     // we should end up at 'proj_true'.
164     Node* proj_before_first_empty_predicate = skip_loop_predicates(entry);
165     if (UseProfiledLoopPredicate) {
166       predicate = find_predicate(proj_before_first_empty_predicate);
167       if (predicate != NULL) {
168         proj_before_first_empty_predicate = skip_loop_predicates(predicate);
169       }
170     }
171     if (UseLoopPredicate) {
172       predicate = find_predicate(proj_before_first_empty_predicate);
173       if (predicate != NULL) {
174         proj_before_first_empty_predicate = skip_loop_predicates(predicate);
175       }
176     }
177     assert(proj_true == proj_before_first_empty_predicate, "must hold by construction if at least one predicate");
178   }
179 #endif
180   // Increment unswitch count
181   LoopNode* head_clone = old_new[head->_idx]->as_Loop();
182   int nct = head->unswitch_count() + 1;
183   head->set_unswitch_count(nct);
184   head_clone->set_unswitch_count(nct);
185 
186   // Add test to new "if" outside of loop
187   IfNode* invar_iff   = proj_true->in(0)->as_If();
188   Node* invar_iff_c   = invar_iff->in(0);
189   BoolNode* bol       = unswitch_iff->in(1)->as_Bool();
190   invar_iff->set_req(1, bol);
191   invar_iff->_prob    = unswitch_iff->_prob;
192 
193   ProjNode* proj_false = invar_iff->proj_out(0)->as_Proj();
194 
195   // Hoist invariant casts out of each loop to the appropriate
196   // control projection.
197 
198   Node_List worklist;
199 
200   for (DUIterator_Fast imax, i = unswitch_iff->fast_outs(imax); i < imax; i++) {
201     ProjNode* proj= unswitch_iff->fast_out(i)->as_Proj();
202     // Copy to a worklist for easier manipulation
203     for (DUIterator_Fast jmax, j = proj->fast_outs(jmax); j < jmax; j++) {
204       Node* use = proj->fast_out(j);
205       if (use->Opcode() == Op_CheckCastPP && loop->is_invariant(use->in(1))) {
206         worklist.push(use);
207       }
208     }
209     ProjNode* invar_proj = invar_iff->proj_out(proj->_con)->as_Proj();
210     while (worklist.size() > 0) {
211       Node* use = worklist.pop();
212       Node* nuse = use->clone();
213       nuse->set_req(0, invar_proj);
214       _igvn.replace_input_of(use, 1, nuse);
215       register_new_node(nuse, invar_proj);
216       // Same for the clone
217       Node* use_clone = old_new[use->_idx];
218       _igvn.replace_input_of(use_clone, 1, nuse);
219     }
220   }
221 
222   // Hardwire the control paths in the loops into if(true) and if(false)
223   _igvn.rehash_node_delayed(unswitch_iff);
224   dominated_by(proj_true, unswitch_iff, false, false);
225 
226   IfNode* unswitch_iff_clone = old_new[unswitch_iff->_idx]->as_If();
227   _igvn.rehash_node_delayed(unswitch_iff_clone);
228   dominated_by(proj_false, unswitch_iff_clone, false, false);
229 
230   // Reoptimize loops
231   loop->record_for_igvn();
232   for(int i = loop->_body.size() - 1; i >= 0 ; i--) {
233     Node *n = loop->_body[i];
234     Node *n_clone = old_new[n->_idx];
235     _igvn._worklist.push(n_clone);
236   }
237 
238 #ifndef PRODUCT
239   if (TraceLoopUnswitching) {
240     tty->print_cr("Loop unswitching orig: %d @ %d  new: %d @ %d",
241                   head->_idx,                unswitch_iff->_idx,
242                   old_new[head->_idx]->_idx, unswitch_iff_clone->_idx);
243   }
244 #endif
245 
246   C->set_major_progress();
247 }
248 
249 //-------------------------create_slow_version_of_loop------------------------
250 // Create a slow version of the loop by cloning the loop
251 // and inserting an if to select fast-slow versions.
252 // Return control projection of the entry to the fast version.
create_slow_version_of_loop(IdealLoopTree * loop,Node_List & old_new,int opcode,CloneLoopMode mode)253 ProjNode* PhaseIdealLoop::create_slow_version_of_loop(IdealLoopTree *loop,
254                                                       Node_List &old_new,
255                                                       int opcode,
256                                                       CloneLoopMode mode) {
257   LoopNode* head  = loop->_head->as_Loop();
258   bool counted_loop = head->is_CountedLoop();
259   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
260   _igvn.rehash_node_delayed(entry);
261   IdealLoopTree* outer_loop = loop->_parent;
262 
263   head->verify_strip_mined(1);
264 
265   Node *cont      = _igvn.intcon(1);
266   set_ctrl(cont, C->root());
267   Node* opq       = new Opaque1Node(C, cont);
268   register_node(opq, outer_loop, entry, dom_depth(entry));
269   Node *bol       = new Conv2BNode(opq);
270   register_node(bol, outer_loop, entry, dom_depth(entry));
271   IfNode* iff = (opcode == Op_RangeCheck) ? new RangeCheckNode(entry, bol, PROB_MAX, COUNT_UNKNOWN) :
272     new IfNode(entry, bol, PROB_MAX, COUNT_UNKNOWN);
273   register_node(iff, outer_loop, entry, dom_depth(entry));
274   ProjNode* iffast = new IfTrueNode(iff);
275   register_node(iffast, outer_loop, iff, dom_depth(iff));
276   ProjNode* ifslow = new IfFalseNode(iff);
277   register_node(ifslow, outer_loop, iff, dom_depth(iff));
278 
279   // Clone the loop body.  The clone becomes the slow loop.  The
280   // original pre-header will (illegally) have 3 control users
281   // (old & new loops & new if).
282   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), mode, iff);
283   assert(old_new[head->_idx]->is_Loop(), "" );
284 
285   // Fast (true) and Slow (false) control
286   ProjNode* iffast_pred = iffast;
287   ProjNode* ifslow_pred = ifslow;
288   clone_predicates_to_unswitched_loop(loop, old_new, iffast_pred, ifslow_pred);
289 
290   Node* l = head->skip_strip_mined();
291   _igvn.replace_input_of(l, LoopNode::EntryControl, iffast_pred);
292   set_idom(l, iffast_pred, dom_depth(l));
293   LoopNode* slow_l = old_new[head->_idx]->as_Loop()->skip_strip_mined();
294   _igvn.replace_input_of(slow_l, LoopNode::EntryControl, ifslow_pred);
295   set_idom(slow_l, ifslow_pred, dom_depth(l));
296 
297   recompute_dom_depth();
298 
299   return iffast;
300 }
301 
create_reserve_version_of_loop(IdealLoopTree * loop,CountedLoopReserveKit * lk)302 LoopNode* PhaseIdealLoop::create_reserve_version_of_loop(IdealLoopTree *loop, CountedLoopReserveKit* lk) {
303   Node_List old_new;
304   LoopNode* head  = loop->_head->as_Loop();
305   bool counted_loop = head->is_CountedLoop();
306   Node*     entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
307   _igvn.rehash_node_delayed(entry);
308   IdealLoopTree* outer_loop = head->is_strip_mined() ? loop->_parent->_parent : loop->_parent;
309 
310   ConINode* const_1 = _igvn.intcon(1);
311   set_ctrl(const_1, C->root());
312   IfNode* iff = new IfNode(entry, const_1, PROB_MAX, COUNT_UNKNOWN);
313   register_node(iff, outer_loop, entry, dom_depth(entry));
314   ProjNode* iffast = new IfTrueNode(iff);
315   register_node(iffast, outer_loop, iff, dom_depth(iff));
316   ProjNode* ifslow = new IfFalseNode(iff);
317   register_node(ifslow, outer_loop, iff, dom_depth(iff));
318 
319   // Clone the loop body.  The clone becomes the slow loop.  The
320   // original pre-header will (illegally) have 3 control users
321   // (old & new loops & new if).
322   clone_loop(loop, old_new, dom_depth(head), CloneIncludesStripMined, iff);
323   assert(old_new[head->_idx]->is_Loop(), "" );
324 
325   LoopNode* slow_head = old_new[head->_idx]->as_Loop();
326 
327 #ifndef PRODUCT
328   if (TraceLoopOpts) {
329     tty->print_cr("PhaseIdealLoop::create_reserve_version_of_loop:");
330     tty->print("\t iff = %d, ", iff->_idx); iff->dump();
331     tty->print("\t iffast = %d, ", iffast->_idx); iffast->dump();
332     tty->print("\t ifslow = %d, ", ifslow->_idx); ifslow->dump();
333     tty->print("\t before replace_input_of: head = %d, ", head->_idx); head->dump();
334     tty->print("\t before replace_input_of: slow_head = %d, ", slow_head->_idx); slow_head->dump();
335   }
336 #endif
337 
338   // Fast (true) control
339   _igvn.replace_input_of(head->skip_strip_mined(), LoopNode::EntryControl, iffast);
340   // Slow (false) control
341   _igvn.replace_input_of(slow_head->skip_strip_mined(), LoopNode::EntryControl, ifslow);
342 
343   recompute_dom_depth();
344 
345   lk->set_iff(iff);
346 
347 #ifndef PRODUCT
348   if (TraceLoopOpts ) {
349     tty->print("\t after  replace_input_of: head = %d, ", head->_idx); head->dump();
350     tty->print("\t after  replace_input_of: slow_head = %d, ", slow_head->_idx); slow_head->dump();
351   }
352 #endif
353 
354   return slow_head->as_Loop();
355 }
356 
CountedLoopReserveKit(PhaseIdealLoop * phase,IdealLoopTree * loop,bool active=true)357 CountedLoopReserveKit::CountedLoopReserveKit(PhaseIdealLoop* phase, IdealLoopTree *loop, bool active = true) :
358   _phase(phase),
359   _lpt(loop),
360   _lp(NULL),
361   _iff(NULL),
362   _lp_reserved(NULL),
363   _has_reserved(false),
364   _use_new(false),
365   _active(active)
366   {
367     create_reserve();
368   };
369 
~CountedLoopReserveKit()370 CountedLoopReserveKit::~CountedLoopReserveKit() {
371   if (!_active) {
372     return;
373   }
374 
375   if (_has_reserved && !_use_new) {
376     // intcon(0)->iff-node reverts CF to the reserved copy
377     ConINode* const_0 = _phase->_igvn.intcon(0);
378     _phase->set_ctrl(const_0, _phase->C->root());
379     _iff->set_req(1, const_0);
380 
381     #ifndef PRODUCT
382       if (TraceLoopOpts) {
383         tty->print_cr("CountedLoopReserveKit::~CountedLoopReserveKit()");
384         tty->print("\t discard loop %d and revert to the reserved loop clone %d: ", _lp->_idx, _lp_reserved->_idx);
385         _lp_reserved->dump();
386       }
387     #endif
388   }
389 }
390 
create_reserve()391 bool CountedLoopReserveKit::create_reserve() {
392   if (!_active) {
393     return false;
394   }
395 
396   if(!_lpt->_head->is_CountedLoop()) {
397     if (TraceLoopOpts) {
398       tty->print_cr("CountedLoopReserveKit::create_reserve: %d not counted loop", _lpt->_head->_idx);
399     }
400     return false;
401   }
402   CountedLoopNode *cl = _lpt->_head->as_CountedLoop();
403   if (!cl->is_valid_counted_loop(T_INT)) {
404     if (TraceLoopOpts) {
405       tty->print_cr("CountedLoopReserveKit::create_reserve: %d not valid counted loop", cl->_idx);
406     }
407     return false; // skip malformed counted loop
408   }
409   if (!cl->is_main_loop()) {
410     bool loop_not_canonical = true;
411     if (cl->is_post_loop() && (cl->slp_max_unroll() > 0)) {
412       loop_not_canonical = false;
413     }
414     // only reject some loop forms
415     if (loop_not_canonical) {
416       if (TraceLoopOpts) {
417         tty->print_cr("CountedLoopReserveKit::create_reserve: %d not canonical loop", cl->_idx);
418       }
419       return false; // skip normal, pre, and post (conditionally) loops
420     }
421   }
422 
423   _lp = _lpt->_head->as_Loop();
424   _lp_reserved = _phase->create_reserve_version_of_loop(_lpt, this);
425 
426   if (!_lp_reserved->is_CountedLoop()) {
427     return false;
428   }
429 
430   Node* ifslow_pred = _lp_reserved->skip_strip_mined()->in(LoopNode::EntryControl);
431 
432   if (!ifslow_pred->is_IfFalse()) {
433     return false;
434   }
435 
436   Node* iff = ifslow_pred->in(0);
437   if (!iff->is_If() || iff != _iff) {
438     return false;
439   }
440 
441   if (iff->in(1)->Opcode() != Op_ConI) {
442     return false;
443   }
444 
445   _has_reserved = true;
446   return true;
447 }
448