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