1 /*
   2  * Copyright (c) 2011, 2018, 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 "opto/loopnode.hpp"
  27 #include "opto/addnode.hpp"
  28 #include "opto/callnode.hpp"
  29 #include "opto/connode.hpp"
  30 #include "opto/convertnode.hpp"
  31 #include "opto/loopnode.hpp"
  32 #include "opto/matcher.hpp"
  33 #include "opto/mulnode.hpp"
  34 #include "opto/opaquenode.hpp"
  35 #include "opto/rootnode.hpp"
  36 #include "opto/subnode.hpp"
  37 #include <fenv.h>
  38 #include <math.h>
  39 
  40 /*
  41  * The general idea of Loop Predication is to insert a predicate on the entry
  42  * path to a loop, and raise a uncommon trap if the check of the condition fails.
  43  * The condition checks are promoted from inside the loop body, and thus
  44  * the checks inside the loop could be eliminated. Currently, loop predication
  45  * optimization has been applied to remove array range check and loop invariant
  46  * checks (such as null checks).
  47 */
  48 
  49 //-------------------------------register_control-------------------------
  50 void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred) {
  51   assert(n->is_CFG(), "must be control node");
  52   _igvn.register_new_node_with_optimizer(n);
  53   loop->_body.push(n);
  54   set_loop(n, loop);
  55   // When called from beautify_loops() idom is not constructed yet.
  56   if (_idom != NULL) {
  57     set_idom(n, pred, dom_depth(pred));
  58   }
  59 }
  60 
  61 //------------------------------create_new_if_for_predicate------------------------
  62 // create a new if above the uct_if_pattern for the predicate to be promoted.
  63 //
  64 //          before                                after
  65 //        ----------                           ----------
  66 //           ctrl                                 ctrl
  67 //            |                                     |
  68 //            |                                     |
  69 //            v                                     v
  70 //           iff                                 new_iff
  71 //          /    \                                /      \
  72 //         /      \                              /        \
  73 //        v        v                            v          v
  74 //  uncommon_proj cont_proj                   if_uct     if_cont
  75 // \      |        |                           |          |
  76 //  \     |        |                           |          |
  77 //   v    v        v                           |          v
  78 //     rgn       loop                          |         iff
  79 //      |                                      |        /     \
  80 //      |                                      |       /       \
  81 //      v                                      |      v         v
  82 // uncommon_trap                               | uncommon_proj cont_proj
  83 //                                           \  \    |           |
  84 //                                            \  \   |           |
  85 //                                             v  v  v           v
  86 //                                               rgn           loop
  87 //                                                |
  88 //                                                |
  89 //                                                v
  90 //                                           uncommon_trap
  91 //
  92 //
  93 // We will create a region to guard the uct call if there is no one there.
  94 // The true projection (if_cont) of the new_iff is returned.
  95 // This code is also used to clone predicates to cloned loops.
  96 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
  97                                                       Deoptimization::DeoptReason reason,
  98                                                       int opcode) {
  99   assert(cont_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!");
 100   IfNode* iff = cont_proj->in(0)->as_If();
 101 
 102   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
 103   Node     *rgn   = uncommon_proj->unique_ctrl_out();
 104   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
 105 
 106   uint proj_index = 1; // region's edge corresponding to uncommon_proj
 107   if (!rgn->is_Region()) { // create a region to guard the call
 108     assert(rgn->is_Call(), "must be call uct");
 109     CallNode* call = rgn->as_Call();
 110     IdealLoopTree* loop = get_loop(call);
 111     rgn = new RegionNode(1);
 112     rgn->add_req(uncommon_proj);
 113     register_control(rgn, loop, uncommon_proj);
 114     _igvn.replace_input_of(call, 0, rgn);
 115     // When called from beautify_loops() idom is not constructed yet.
 116     if (_idom != NULL) {
 117       set_idom(call, rgn, dom_depth(rgn));
 118     }
 119     for (DUIterator_Fast imax, i = uncommon_proj->fast_outs(imax); i < imax; i++) {
 120       Node* n = uncommon_proj->fast_out(i);
 121       if (n->is_Load() || n->is_Store()) {
 122         _igvn.replace_input_of(n, 0, rgn);
 123         --i; --imax;
 124       }
 125     }
 126   } else {
 127     // Find region's edge corresponding to uncommon_proj
 128     for (; proj_index < rgn->req(); proj_index++)
 129       if (rgn->in(proj_index) == uncommon_proj) break;
 130     assert(proj_index < rgn->req(), "sanity");
 131   }
 132 
 133   Node* entry = iff->in(0);
 134   if (new_entry != NULL) {
 135     // Clonning the predicate to new location.
 136     entry = new_entry;
 137   }
 138   // Create new_iff
 139   IdealLoopTree* lp = get_loop(entry);
 140   IfNode* new_iff = NULL;
 141   if (opcode == Op_If) {
 142     new_iff = new IfNode(entry, iff->in(1), iff->_prob, iff->_fcnt);
 143   } else {
 144     assert(opcode == Op_RangeCheck, "no other if variant here");
 145     new_iff = new RangeCheckNode(entry, iff->in(1), iff->_prob, iff->_fcnt);
 146   }
 147   register_control(new_iff, lp, entry);
 148   Node *if_cont = new IfTrueNode(new_iff);
 149   Node *if_uct  = new IfFalseNode(new_iff);
 150   if (cont_proj->is_IfFalse()) {
 151     // Swap
 152     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
 153   }
 154   register_control(if_cont, lp, new_iff);
 155   register_control(if_uct, get_loop(rgn), new_iff);
 156 
 157   // if_uct to rgn
 158   _igvn.hash_delete(rgn);
 159   rgn->add_req(if_uct);
 160   // When called from beautify_loops() idom is not constructed yet.
 161   if (_idom != NULL) {
 162     Node* ridom = idom(rgn);
 163     Node* nrdom = dom_lca(ridom, new_iff);
 164     set_idom(rgn, nrdom, dom_depth(rgn));
 165   }
 166 
 167   // If rgn has phis add new edges which has the same
 168   // value as on original uncommon_proj pass.
 169   assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
 170   bool has_phi = false;
 171   for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
 172     Node* use = rgn->fast_out(i);
 173     if (use->is_Phi() && use->outcnt() > 0) {
 174       assert(use->in(0) == rgn, "");
 175       _igvn.rehash_node_delayed(use);
 176       use->add_req(use->in(proj_index));
 177       has_phi = true;
 178     }
 179   }
 180   assert(!has_phi || rgn->req() > 3, "no phis when region is created");
 181 
 182   if (new_entry == NULL) {
 183     // Attach if_cont to iff
 184     _igvn.replace_input_of(iff, 0, if_cont);
 185     if (_idom != NULL) {
 186       set_idom(iff, if_cont, dom_depth(iff));
 187     }
 188   }
 189   return if_cont->as_Proj();
 190 }
 191 
 192 //------------------------------create_new_if_for_predicate------------------------
 193 // Create a new if below new_entry for the predicate to be cloned (IGVN optimization)
 194 ProjNode* PhaseIterGVN::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
 195                                                     Deoptimization::DeoptReason reason,
 196                                                     int opcode) {
 197   assert(new_entry != 0, "only used for clone predicate");
 198   assert(cont_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!");
 199   IfNode* iff = cont_proj->in(0)->as_If();
 200 
 201   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
 202   Node     *rgn   = uncommon_proj->unique_ctrl_out();
 203   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
 204 
 205   uint proj_index = 1; // region's edge corresponding to uncommon_proj
 206   if (!rgn->is_Region()) { // create a region to guard the call
 207     assert(rgn->is_Call(), "must be call uct");
 208     CallNode* call = rgn->as_Call();
 209     rgn = new RegionNode(1);
 210     register_new_node_with_optimizer(rgn);
 211     rgn->add_req(uncommon_proj);
 212     replace_input_of(call, 0, rgn);
 213   } else {
 214     // Find region's edge corresponding to uncommon_proj
 215     for (; proj_index < rgn->req(); proj_index++)
 216       if (rgn->in(proj_index) == uncommon_proj) break;
 217     assert(proj_index < rgn->req(), "sanity");
 218   }
 219 
 220   // Create new_iff in new location.
 221   IfNode* new_iff = NULL;
 222   if (opcode == Op_If) {
 223     new_iff = new IfNode(new_entry, iff->in(1), iff->_prob, iff->_fcnt);
 224   } else {
 225     assert(opcode == Op_RangeCheck, "no other if variant here");
 226     new_iff = new RangeCheckNode(new_entry, iff->in(1), iff->_prob, iff->_fcnt);
 227   }
 228 
 229   register_new_node_with_optimizer(new_iff);
 230   Node *if_cont = new IfTrueNode(new_iff);
 231   Node *if_uct  = new IfFalseNode(new_iff);
 232   if (cont_proj->is_IfFalse()) {
 233     // Swap
 234     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
 235   }
 236   register_new_node_with_optimizer(if_cont);
 237   register_new_node_with_optimizer(if_uct);
 238 
 239   // if_uct to rgn
 240   hash_delete(rgn);
 241   rgn->add_req(if_uct);
 242 
 243   // If rgn has phis add corresponding new edges which has the same
 244   // value as on original uncommon_proj pass.
 245   assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
 246   bool has_phi = false;
 247   for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
 248     Node* use = rgn->fast_out(i);
 249     if (use->is_Phi() && use->outcnt() > 0) {
 250       rehash_node_delayed(use);
 251       use->add_req(use->in(proj_index));
 252       has_phi = true;
 253     }
 254   }
 255   assert(!has_phi || rgn->req() > 3, "no phis when region is created");
 256 
 257   return if_cont->as_Proj();
 258 }
 259 
 260 //--------------------------clone_predicate-----------------------
 261 ProjNode* PhaseIdealLoop::clone_predicate(ProjNode* predicate_proj, Node* new_entry,
 262                                           Deoptimization::DeoptReason reason,
 263                                           PhaseIdealLoop* loop_phase,
 264                                           PhaseIterGVN* igvn) {
 265   ProjNode* new_predicate_proj;
 266   if (loop_phase != NULL) {
 267     new_predicate_proj = loop_phase->create_new_if_for_predicate(predicate_proj, new_entry, reason, Op_If);
 268   } else {
 269     new_predicate_proj =       igvn->create_new_if_for_predicate(predicate_proj, new_entry, reason, Op_If);
 270   }
 271   IfNode* iff = new_predicate_proj->in(0)->as_If();
 272   Node* ctrl  = iff->in(0);
 273 
 274   // Match original condition since predicate's projections could be swapped.
 275   assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
 276   Node* opq = new Opaque1Node(igvn->C, predicate_proj->in(0)->in(1)->in(1)->in(1));
 277   igvn->C->add_predicate_opaq(opq);
 278 
 279   Node* bol = new Conv2BNode(opq);
 280   if (loop_phase != NULL) {
 281     loop_phase->register_new_node(opq, ctrl);
 282     loop_phase->register_new_node(bol, ctrl);
 283   } else {
 284     igvn->register_new_node_with_optimizer(opq);
 285     igvn->register_new_node_with_optimizer(bol);
 286   }
 287   igvn->hash_delete(iff);
 288   iff->set_req(1, bol);
 289   return new_predicate_proj;
 290 }
 291 
 292 
 293 //--------------------------clone_loop_predicates-----------------------
 294 // Interface from IGVN
 295 Node* PhaseIterGVN::clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check) {
 296   return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, clone_limit_check, NULL, this);
 297 }
 298 
 299 // Interface from PhaseIdealLoop
 300 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check) {
 301   return clone_loop_predicates(old_entry, new_entry, clone_limit_check, this, &this->_igvn);
 302 }
 303 
 304 void PhaseIdealLoop::clone_loop_predicates_fix_mem(ProjNode* dom_proj , ProjNode* proj,
 305                                                    PhaseIdealLoop* loop_phase,
 306                                                    PhaseIterGVN* igvn) {
 307   Compile* C = NULL;
 308   if (loop_phase != NULL) {
 309     igvn = &loop_phase->igvn();
 310   }
 311   C = igvn->C;
 312   ProjNode* other_dom_proj = dom_proj->in(0)->as_Multi()->proj_out(1-dom_proj->_con);
 313   Node* dom_r = other_dom_proj->unique_ctrl_out();
 314   if (dom_r->is_Region()) {
 315     assert(dom_r->unique_ctrl_out()->is_Call(), "unc expected");
 316     ProjNode* other_proj = proj->in(0)->as_Multi()->proj_out(1-proj->_con);
 317     Node* r = other_proj->unique_ctrl_out();
 318     assert(r->is_Region() && r->unique_ctrl_out()->is_Call(), "cloned predicate should have caused region to be added");
 319     for (DUIterator_Fast imax, i = dom_r->fast_outs(imax); i < imax; i++) {
 320       Node* dom_use = dom_r->fast_out(i);
 321       if (dom_use->is_Phi() && dom_use->bottom_type() == Type::MEMORY) {
 322         assert(dom_use->in(0) == dom_r, "");
 323         Node* phi = NULL;
 324         for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) {
 325           Node* use = r->fast_out(j);
 326           if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
 327               use->adr_type() == dom_use->adr_type()) {
 328             assert(use->in(0) == r, "");
 329             assert(phi == NULL, "only one phi");
 330             phi = use;
 331           }
 332         }
 333         if (phi == NULL) {
 334           Node* call = r->unique_ctrl_out();
 335           Node* mem = call->in(TypeFunc::Memory);
 336           MergeMemNode* mm = NULL;
 337           if (mem->is_MergeMem()) {
 338             mm = mem->clone()->as_MergeMem();
 339           } else {
 340             mm = MergeMemNode::make(mem);
 341           }
 342           phi = PhiNode::make(r, mem, Type::MEMORY, dom_use->adr_type());
 343           mm->set_memory_at(C->get_alias_index(phi->adr_type()), phi);
 344           if (loop_phase != NULL) {
 345             loop_phase->register_new_node(mm, r);
 346             loop_phase->register_new_node(phi, r);
 347           } else {
 348             igvn->register_new_node_with_optimizer(mm);
 349             igvn->register_new_node_with_optimizer(phi);
 350           }
 351           igvn->replace_input_of(call, TypeFunc::Memory, mm);
 352         }
 353         igvn->replace_input_of(phi, r->req()-1, dom_use->in(dom_r->find_edge(other_dom_proj)));
 354       }
 355     }
 356   }
 357 }
 358 
 359 
 360 // Clone loop predicates to cloned loops (peeled, unswitched, split_if).
 361 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry,
 362                                                 bool clone_limit_check,
 363                                                 PhaseIdealLoop* loop_phase,
 364                                                 PhaseIterGVN* igvn) {
 365 #ifdef ASSERT
 366   if (new_entry == NULL || !(new_entry->is_Proj() || new_entry->is_Region() || new_entry->is_SafePoint())) {
 367     if (new_entry != NULL)
 368       new_entry->dump();
 369     assert(false, "not IfTrue, IfFalse, Region or SafePoint");
 370   }
 371 #endif
 372   // Search original predicates
 373   Node* entry = old_entry;
 374   ProjNode* limit_check_proj = NULL;
 375   limit_check_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
 376   if (limit_check_proj != NULL) {
 377     entry = entry->in(0)->in(0);
 378   }
 379   ProjNode* profile_predicate_proj = NULL;
 380   ProjNode* predicate_proj = NULL;
 381   if (UseProfiledLoopPredicate) {
 382     profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
 383     if (profile_predicate_proj != NULL) {
 384       entry = skip_loop_predicates(entry);
 385     }
 386   }
 387   if (UseLoopPredicate) {
 388     predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
 389   }
 390   if (predicate_proj != NULL) { // right pattern that can be used by loop predication
 391     // clone predicate
 392     ProjNode* proj = clone_predicate(predicate_proj, new_entry,
 393                                 Deoptimization::Reason_predicate,
 394                                 loop_phase, igvn);
 395     assert(proj != NULL, "IfTrue or IfFalse after clone predicate");
 396     new_entry = proj;
 397     if (TraceLoopPredicate) {
 398       tty->print("Loop Predicate cloned: ");
 399       debug_only( new_entry->in(0)->dump(); );
 400     }
 401     if (profile_predicate_proj != NULL) {
 402       // A node that produces memory may be out of loop and depend on
 403       // a profiled predicates. In that case the memory state at the
 404       // end of profiled predicates and at the end of predicates are
 405       // not the same. The cloned predicates are dominated by the
 406       // profiled predicates but may have the wrong memory
 407       // state. Update it.
 408       clone_loop_predicates_fix_mem(profile_predicate_proj, proj, loop_phase, igvn);
 409     }
 410   }
 411   if (profile_predicate_proj != NULL) { // right pattern that can be used by loop predication
 412     // clone predicate
 413     new_entry = clone_predicate(profile_predicate_proj, new_entry,
 414                                 Deoptimization::Reason_profile_predicate,
 415                                 loop_phase, igvn);
 416     assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
 417     if (TraceLoopPredicate) {
 418       tty->print("Loop Predicate cloned: ");
 419       debug_only( new_entry->in(0)->dump(); );
 420     }
 421   }
 422   if (limit_check_proj != NULL && clone_limit_check) {
 423     // Clone loop limit check last to insert it before loop.
 424     // Don't clone a limit check which was already finalized
 425     // for this counted loop (only one limit check is needed).
 426     new_entry = clone_predicate(limit_check_proj, new_entry,
 427                                 Deoptimization::Reason_loop_limit_check,
 428                                 loop_phase, igvn);
 429     assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone limit check");
 430     if (TraceLoopLimitCheck) {
 431       tty->print("Loop Limit Check cloned: ");
 432       debug_only( new_entry->in(0)->dump(); )
 433     }
 434   }
 435   return new_entry;
 436 }
 437 
 438 //--------------------------skip_loop_predicates------------------------------
 439 // Skip related predicates.
 440 Node* PhaseIdealLoop::skip_loop_predicates(Node* entry) {
 441   IfNode* iff = entry->in(0)->as_If();
 442   ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
 443   Node* rgn = uncommon_proj->unique_ctrl_out();
 444   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
 445   entry = entry->in(0)->in(0);
 446   while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
 447     uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
 448     if (uncommon_proj->unique_ctrl_out() != rgn)
 449       break;
 450     entry = entry->in(0)->in(0);
 451   }
 452   return entry;
 453 }
 454 
 455 Node* PhaseIdealLoop::skip_all_loop_predicates(Node* entry) {
 456   Node* predicate = NULL;
 457   predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
 458   if (predicate != NULL) {
 459     entry = entry->in(0)->in(0);
 460   }
 461   if (UseProfiledLoopPredicate) {
 462     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
 463     if (predicate != NULL) { // right pattern that can be used by loop predication
 464       entry = skip_loop_predicates(entry);
 465     }
 466   }
 467   if (UseLoopPredicate) {
 468     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
 469     if (predicate != NULL) { // right pattern that can be used by loop predication
 470       entry = skip_loop_predicates(entry);
 471     }
 472   }
 473   return entry;
 474 }
 475 
 476 //--------------------------find_predicate_insertion_point-------------------
 477 // Find a good location to insert a predicate
 478 ProjNode* PhaseIdealLoop::find_predicate_insertion_point(Node* start_c, Deoptimization::DeoptReason reason) {
 479   if (start_c == NULL || !start_c->is_Proj())
 480     return NULL;
 481   if (start_c->as_Proj()->is_uncommon_trap_if_pattern(reason)) {
 482     return start_c->as_Proj();
 483   }
 484   return NULL;
 485 }
 486 
 487 //--------------------------find_predicate------------------------------------
 488 // Find a predicate
 489 Node* PhaseIdealLoop::find_predicate(Node* entry) {
 490   Node* predicate = NULL;
 491   predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
 492   if (predicate != NULL) { // right pattern that can be used by loop predication
 493     return entry;
 494   }
 495   if (UseLoopPredicate) {
 496     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
 497     if (predicate != NULL) { // right pattern that can be used by loop predication
 498       return entry;
 499     }
 500   }
 501   if (UseProfiledLoopPredicate) {
 502     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
 503     if (predicate != NULL) { // right pattern that can be used by loop predication
 504       return entry;
 505     }
 506   }
 507   return NULL;
 508 }
 509 
 510 //------------------------------Invariance-----------------------------------
 511 // Helper class for loop_predication_impl to compute invariance on the fly and
 512 // clone invariants.
 513 class Invariance : public StackObj {
 514   VectorSet _visited, _invariant;
 515   Node_Stack _stack;
 516   VectorSet _clone_visited;
 517   Node_List _old_new; // map of old to new (clone)
 518   IdealLoopTree* _lpt;
 519   PhaseIdealLoop* _phase;
 520 
 521   // Helper function to set up the invariance for invariance computation
 522   // If n is a known invariant, set up directly. Otherwise, look up the
 523   // the possibility to push n onto the stack for further processing.
 524   void visit(Node* use, Node* n) {
 525     if (_lpt->is_invariant(n)) { // known invariant
 526       _invariant.set(n->_idx);
 527     } else if (!n->is_CFG()) {
 528       Node *n_ctrl = _phase->ctrl_or_self(n);
 529       Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG
 530       if (_phase->is_dominator(n_ctrl, u_ctrl)) {
 531         _stack.push(n, n->in(0) == NULL ? 1 : 0);
 532       }
 533     }
 534   }
 535 
 536   // Compute invariance for "the_node" and (possibly) all its inputs recursively
 537   // on the fly
 538   void compute_invariance(Node* n) {
 539     assert(_visited.test(n->_idx), "must be");
 540     visit(n, n);
 541     while (_stack.is_nonempty()) {
 542       Node*  n = _stack.node();
 543       uint idx = _stack.index();
 544       if (idx == n->req()) { // all inputs are processed
 545         _stack.pop();
 546         // n is invariant if it's inputs are all invariant
 547         bool all_inputs_invariant = true;
 548         for (uint i = 0; i < n->req(); i++) {
 549           Node* in = n->in(i);
 550           if (in == NULL) continue;
 551           assert(_visited.test(in->_idx), "must have visited input");
 552           if (!_invariant.test(in->_idx)) { // bad guy
 553             all_inputs_invariant = false;
 554             break;
 555           }
 556         }
 557         if (all_inputs_invariant) {
 558           // If n's control is a predicate that was moved out of the
 559           // loop, it was marked invariant but n is only invariant if
 560           // it depends only on that test. Otherwise, unless that test
 561           // is out of the loop, it's not invariant.
 562           if (n->is_CFG() || n->depends_only_on_test() || n->in(0) == NULL || !_phase->is_member(_lpt, n->in(0))) {
 563             _invariant.set(n->_idx); // I am a invariant too
 564           }
 565         }
 566       } else { // process next input
 567         _stack.set_index(idx + 1);
 568         Node* m = n->in(idx);
 569         if (m != NULL && !_visited.test_set(m->_idx)) {
 570           visit(n, m);
 571         }
 572       }
 573     }
 574   }
 575 
 576   // Helper function to set up _old_new map for clone_nodes.
 577   // If n is a known invariant, set up directly ("clone" of n == n).
 578   // Otherwise, push n onto the stack for real cloning.
 579   void clone_visit(Node* n) {
 580     assert(_invariant.test(n->_idx), "must be invariant");
 581     if (_lpt->is_invariant(n)) { // known invariant
 582       _old_new.map(n->_idx, n);
 583     } else { // to be cloned
 584       assert(!n->is_CFG(), "should not see CFG here");
 585       _stack.push(n, n->in(0) == NULL ? 1 : 0);
 586     }
 587   }
 588 
 589   // Clone "n" and (possibly) all its inputs recursively
 590   void clone_nodes(Node* n, Node* ctrl) {
 591     clone_visit(n);
 592     while (_stack.is_nonempty()) {
 593       Node*  n = _stack.node();
 594       uint idx = _stack.index();
 595       if (idx == n->req()) { // all inputs processed, clone n!
 596         _stack.pop();
 597         // clone invariant node
 598         Node* n_cl = n->clone();
 599         _old_new.map(n->_idx, n_cl);
 600         _phase->register_new_node(n_cl, ctrl);
 601         for (uint i = 0; i < n->req(); i++) {
 602           Node* in = n_cl->in(i);
 603           if (in == NULL) continue;
 604           n_cl->set_req(i, _old_new[in->_idx]);
 605         }
 606       } else { // process next input
 607         _stack.set_index(idx + 1);
 608         Node* m = n->in(idx);
 609         if (m != NULL && !_clone_visited.test_set(m->_idx)) {
 610           clone_visit(m); // visit the input
 611         }
 612       }
 613     }
 614   }
 615 
 616  public:
 617   Invariance(Arena* area, IdealLoopTree* lpt) :
 618     _visited(area), _invariant(area),
 619     _stack(area, 10 /* guess */),
 620     _clone_visited(area), _old_new(area),
 621     _lpt(lpt), _phase(lpt->_phase)
 622   {
 623     LoopNode* head = _lpt->_head->as_Loop();
 624     Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
 625     if (entry->outcnt() != 1) {
 626       // If a node is pinned between the predicates and the loop
 627       // entry, we won't be able to move any node in the loop that
 628       // depends on it above it in a predicate. Mark all those nodes
 629       // as non loop invariatnt.
 630       Unique_Node_List wq;
 631       wq.push(entry);
 632       for (uint next = 0; next < wq.size(); ++next) {
 633         Node *n = wq.at(next);
 634         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 635           Node* u = n->fast_out(i);
 636           if (!u->is_CFG()) {
 637             Node* c = _phase->get_ctrl(u);
 638             if (_lpt->is_member(_phase->get_loop(c)) || _phase->is_dominator(c, head)) {
 639               _visited.set(u->_idx);
 640               wq.push(u);
 641             }
 642           }
 643         }
 644       }
 645     }
 646   }
 647 
 648   // Map old to n for invariance computation and clone
 649   void map_ctrl(Node* old, Node* n) {
 650     assert(old->is_CFG() && n->is_CFG(), "must be");
 651     _old_new.map(old->_idx, n); // "clone" of old is n
 652     _invariant.set(old->_idx);  // old is invariant
 653     _clone_visited.set(old->_idx);
 654   }
 655 
 656   // Driver function to compute invariance
 657   bool is_invariant(Node* n) {
 658     if (!_visited.test_set(n->_idx))
 659       compute_invariance(n);
 660     return (_invariant.test(n->_idx) != 0);
 661   }
 662 
 663   // Driver function to clone invariant
 664   Node* clone(Node* n, Node* ctrl) {
 665     assert(ctrl->is_CFG(), "must be");
 666     assert(_invariant.test(n->_idx), "must be an invariant");
 667     if (!_clone_visited.test(n->_idx))
 668       clone_nodes(n, ctrl);
 669     return _old_new[n->_idx];
 670   }
 671 };
 672 
 673 //------------------------------is_range_check_if -----------------------------------
 674 // Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format
 675 // Note: this function is particularly designed for loop predication. We require load_range
 676 //       and offset to be loop invariant computed on the fly by "invar"
 677 bool IdealLoopTree::is_range_check_if(IfNode *iff, PhaseIdealLoop *phase, Invariance& invar) const {
 678   if (!is_loop_exit(iff)) {
 679     return false;
 680   }
 681   if (!iff->in(1)->is_Bool()) {
 682     return false;
 683   }
 684   const BoolNode *bol = iff->in(1)->as_Bool();
 685   if (bol->_test._test != BoolTest::lt) {
 686     return false;
 687   }
 688   if (!bol->in(1)->is_Cmp()) {
 689     return false;
 690   }
 691   const CmpNode *cmp = bol->in(1)->as_Cmp();
 692   if (cmp->Opcode() != Op_CmpU) {
 693     return false;
 694   }
 695   Node* range = cmp->in(2);
 696   if (range->Opcode() != Op_LoadRange && !iff->is_RangeCheck()) {
 697     const TypeInt* tint = phase->_igvn.type(range)->isa_int();
 698     if (tint == NULL || tint->empty() || tint->_lo < 0) {
 699       // Allow predication on positive values that aren't LoadRanges.
 700       // This allows optimization of loops where the length of the
 701       // array is a known value and doesn't need to be loaded back
 702       // from the array.
 703       return false;
 704     }
 705   }
 706   if (!invar.is_invariant(range)) {
 707     return false;
 708   }
 709   Node *iv     = _head->as_CountedLoop()->phi();
 710   int   scale  = 0;
 711   Node *offset = NULL;
 712   if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, &scale, &offset)) {
 713     return false;
 714   }
 715   if (offset && !invar.is_invariant(offset)) { // offset must be invariant
 716     return false;
 717   }
 718   return true;
 719 }
 720 
 721 //------------------------------rc_predicate-----------------------------------
 722 // Create a range check predicate
 723 //
 724 // for (i = init; i < limit; i += stride) {
 725 //    a[scale*i+offset]
 726 // }
 727 //
 728 // Compute max(scale*i + offset) for init <= i < limit and build the predicate
 729 // as "max(scale*i + offset) u< a.length".
 730 //
 731 // There are two cases for max(scale*i + offset):
 732 // (1) stride*scale > 0
 733 //   max(scale*i + offset) = scale*(limit-stride) + offset
 734 // (2) stride*scale < 0
 735 //   max(scale*i + offset) = scale*init + offset
 736 BoolNode* PhaseIdealLoop::rc_predicate(IdealLoopTree *loop, Node* ctrl,
 737                                        int scale, Node* offset,
 738                                        Node* init, Node* limit, jint stride,
 739                                        Node* range, bool upper, bool &overflow) {
 740   jint con_limit  = (limit != NULL && limit->is_Con())  ? limit->get_int()  : 0;
 741   jint con_init   = init->is_Con()   ? init->get_int()   : 0;
 742   jint con_offset = offset->is_Con() ? offset->get_int() : 0;
 743 
 744   stringStream* predString = NULL;
 745   if (TraceLoopPredicate) {
 746     predString = new stringStream();
 747     predString->print("rc_predicate ");
 748   }
 749 
 750   overflow = false;
 751   Node* max_idx_expr = NULL;
 752   const TypeInt* idx_type = TypeInt::INT;
 753   if ((stride > 0) == (scale > 0) == upper) {
 754     guarantee(limit != NULL, "sanity");
 755     if (TraceLoopPredicate) {
 756       if (limit->is_Con()) {
 757         predString->print("(%d ", con_limit);
 758       } else {
 759         predString->print("(limit ");
 760       }
 761       predString->print("- %d) ", stride);
 762     }
 763     // Check if (limit - stride) may overflow
 764     const TypeInt* limit_type = _igvn.type(limit)->isa_int();
 765     jint limit_lo = limit_type->_lo;
 766     jint limit_hi = limit_type->_hi;
 767     if ((stride > 0 && (java_subtract(limit_lo, stride) < limit_lo)) ||
 768         (stride < 0 && (java_subtract(limit_hi, stride) > limit_hi))) {
 769       // No overflow possible
 770       ConINode* con_stride = _igvn.intcon(stride);
 771       set_ctrl(con_stride, C->root());
 772       max_idx_expr = new SubINode(limit, con_stride);
 773       idx_type = TypeInt::make(limit_lo - stride, limit_hi - stride, limit_type->_widen);
 774     } else {
 775       // May overflow
 776       overflow = true;
 777       limit = new ConvI2LNode(limit);
 778       register_new_node(limit, ctrl);
 779       ConLNode* con_stride = _igvn.longcon(stride);
 780       set_ctrl(con_stride, C->root());
 781       max_idx_expr = new SubLNode(limit, con_stride);
 782     }
 783     register_new_node(max_idx_expr, ctrl);
 784   } else {
 785     if (TraceLoopPredicate) {
 786       if (init->is_Con()) {
 787         predString->print("%d ", con_init);
 788       } else {
 789         predString->print("init ");
 790       }
 791     }
 792     idx_type = _igvn.type(init)->isa_int();
 793     max_idx_expr = init;
 794   }
 795 
 796   if (scale != 1) {
 797     ConNode* con_scale = _igvn.intcon(scale);
 798     set_ctrl(con_scale, C->root());
 799     if (TraceLoopPredicate) {
 800       predString->print("* %d ", scale);
 801     }
 802     // Check if (scale * max_idx_expr) may overflow
 803     const TypeInt* scale_type = TypeInt::make(scale);
 804     MulINode* mul = new MulINode(max_idx_expr, con_scale);
 805     idx_type = (TypeInt*)mul->mul_ring(idx_type, scale_type);
 806     if (overflow || TypeInt::INT->higher_equal(idx_type)) {
 807       // May overflow
 808       mul->destruct();
 809       if (!overflow) {
 810         max_idx_expr = new ConvI2LNode(max_idx_expr);
 811         register_new_node(max_idx_expr, ctrl);
 812       }
 813       overflow = true;
 814       con_scale = _igvn.longcon(scale);
 815       set_ctrl(con_scale, C->root());
 816       max_idx_expr = new MulLNode(max_idx_expr, con_scale);
 817     } else {
 818       // No overflow possible
 819       max_idx_expr = mul;
 820     }
 821     register_new_node(max_idx_expr, ctrl);
 822   }
 823 
 824   if (offset && (!offset->is_Con() || con_offset != 0)){
 825     if (TraceLoopPredicate) {
 826       if (offset->is_Con()) {
 827         predString->print("+ %d ", con_offset);
 828       } else {
 829         predString->print("+ offset");
 830       }
 831     }
 832     // Check if (max_idx_expr + offset) may overflow
 833     const TypeInt* offset_type = _igvn.type(offset)->isa_int();
 834     jint lo = java_add(idx_type->_lo, offset_type->_lo);
 835     jint hi = java_add(idx_type->_hi, offset_type->_hi);
 836     if (overflow || (lo > hi) ||
 837         ((idx_type->_lo & offset_type->_lo) < 0 && lo >= 0) ||
 838         ((~(idx_type->_hi | offset_type->_hi)) < 0 && hi < 0)) {
 839       // May overflow
 840       if (!overflow) {
 841         max_idx_expr = new ConvI2LNode(max_idx_expr);
 842         register_new_node(max_idx_expr, ctrl);
 843       }
 844       overflow = true;
 845       offset = new ConvI2LNode(offset);
 846       register_new_node(offset, ctrl);
 847       max_idx_expr = new AddLNode(max_idx_expr, offset);
 848     } else {
 849       // No overflow possible
 850       max_idx_expr = new AddINode(max_idx_expr, offset);
 851     }
 852     register_new_node(max_idx_expr, ctrl);
 853   }
 854 
 855   CmpNode* cmp = NULL;
 856   if (overflow) {
 857     // Integer expressions may overflow, do long comparison
 858     range = new ConvI2LNode(range);
 859     register_new_node(range, ctrl);
 860     cmp = new CmpULNode(max_idx_expr, range);
 861   } else {
 862     cmp = new CmpUNode(max_idx_expr, range);
 863   }
 864   register_new_node(cmp, ctrl);
 865   BoolNode* bol = new BoolNode(cmp, BoolTest::lt);
 866   register_new_node(bol, ctrl);
 867 
 868   if (TraceLoopPredicate) {
 869     predString->print_cr("<u range");
 870     tty->print("%s", predString->as_string());
 871   }
 872   return bol;
 873 }
 874 
 875 // Should loop predication look not only in the path from tail to head
 876 // but also in branches of the loop body?
 877 bool PhaseIdealLoop::loop_predication_should_follow_branches(IdealLoopTree *loop, ProjNode *predicate_proj, float& loop_trip_cnt) {
 878   if (!UseProfiledLoopPredicate) {
 879     return false;
 880   }
 881 
 882   if (predicate_proj == NULL) {
 883     return false;
 884   }
 885 
 886   LoopNode* head = loop->_head->as_Loop();
 887   bool follow_branches = true;
 888   IdealLoopTree* l = loop->_child;
 889   // For leaf loops and loops with a single inner loop
 890   while (l != NULL && follow_branches) {
 891     IdealLoopTree* child = l;
 892     if (child->_child != NULL &&
 893         child->_head->is_OuterStripMinedLoop()) {
 894       assert(child->_child->_next == NULL, "only one inner loop for strip mined loop");
 895       assert(child->_child->_head->is_CountedLoop() && child->_child->_head->as_CountedLoop()->is_strip_mined(), "inner loop should be strip mined");
 896       child = child->_child;
 897     }
 898     if (child->_child != NULL || child->_irreducible) {
 899       follow_branches = false;
 900     }
 901     l = l->_next;
 902   }
 903   if (follow_branches) {
 904     loop->compute_profile_trip_cnt(this);
 905     if (head->is_profile_trip_failed()) {
 906       follow_branches = false;
 907     } else {
 908       loop_trip_cnt = head->profile_trip_cnt();
 909       if (head->is_CountedLoop()) {
 910         CountedLoopNode* cl = head->as_CountedLoop();
 911         if (cl->phi() != NULL) {
 912           const TypeInt* t = _igvn.type(cl->phi())->is_int();
 913           float worst_case_trip_cnt = ((float)t->_hi - t->_lo) / ABS(cl->stride_con());
 914           if (worst_case_trip_cnt < loop_trip_cnt) {
 915             loop_trip_cnt = worst_case_trip_cnt;
 916           }
 917         }
 918       }
 919     }
 920   }
 921   return follow_branches;
 922 }
 923 
 924 // Compute probability of reaching some CFG node from a fixed
 925 // dominating CFG node
 926 class PathFrequency {
 927 private:
 928   Node* _dom; // frequencies are computed relative to this node
 929   Node_Stack _stack;
 930   GrowableArray<float> _freqs_stack; // keep track of intermediate result at regions
 931   GrowableArray<float> _freqs; // cache frequencies
 932   PhaseIdealLoop* _phase;
 933 
 934 public:
 935   PathFrequency(Node* dom, PhaseIdealLoop* phase)
 936     : _dom(dom), _stack(0), _phase(phase) {
 937   }
 938 
 939   float to(Node* n) {
 940     // post order walk on the CFG graph from n to _dom
 941     fesetround(FE_TOWARDZERO); // make sure rounding doesn't push frequency above 1
 942     IdealLoopTree* loop = _phase->get_loop(_dom);
 943     Node* c = n;
 944     for (;;) {
 945       assert(_phase->get_loop(c) == loop, "have to be in the same loop");
 946       if (c == _dom || _freqs.at_grow(c->_idx, -1) >= 0) {
 947         float f = c == _dom ? 1 : _freqs.at(c->_idx);
 948         Node* prev = c;
 949         while (_stack.size() > 0 && prev == c) {
 950           Node* n = _stack.node();
 951           if (!n->is_Region()) {
 952             if (_phase->get_loop(n) != _phase->get_loop(n->in(0))) {
 953               // Found an inner loop: compute frequency of reaching this
 954               // exit from the loop head by looking at the number of
 955               // times each loop exit was taken
 956               IdealLoopTree* inner_loop = _phase->get_loop(n->in(0));
 957               LoopNode* inner_head = inner_loop->_head->as_Loop();
 958               assert(_phase->get_loop(n) == loop, "only 1 inner loop");
 959               if (inner_head->is_OuterStripMinedLoop()) {
 960                 inner_head->verify_strip_mined(1);
 961                 if (n->in(0) == inner_head->in(LoopNode::LoopBackControl)->in(0)) {
 962                   n = n->in(0)->in(0)->in(0);
 963                 }
 964                 inner_loop = inner_loop->_child;
 965                 inner_head = inner_loop->_head->as_Loop();
 966                 inner_head->verify_strip_mined(1);
 967               }
 968               fesetround(FE_UPWARD);  // make sure rounding doesn't push frequency above 1
 969               float loop_exit_cnt = 0.0f;
 970               for (uint i = 0; i < inner_loop->_body.size(); i++) {
 971                 Node *n = inner_loop->_body[i];
 972                 float c = inner_loop->compute_profile_trip_cnt_helper(n);
 973                 loop_exit_cnt += c;
 974               }
 975               fesetround(FE_TOWARDZERO);
 976               float cnt = -1;
 977               if (n->in(0)->is_If()) {
 978                 IfNode* iff = n->in(0)->as_If();
 979                 float p = n->in(0)->as_If()->_prob;
 980                 if (n->Opcode() == Op_IfFalse) {
 981                   p = 1 - p;
 982                 }
 983                 if (p > PROB_MIN) {
 984                   cnt = p * iff->_fcnt;
 985                 } else {
 986                   cnt = 0;
 987                 }
 988               } else {
 989                 assert(n->in(0)->is_Jump(), "unsupported node kind");
 990                 JumpNode* jmp = n->in(0)->as_Jump();
 991                 float p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
 992                 cnt = p * jmp->_fcnt;
 993               }
 994               float this_exit_f = cnt > 0 ? cnt / loop_exit_cnt : 0;
 995               assert(this_exit_f <= 1 && this_exit_f >= 0, "Incorrect frequency");
 996               f = f * this_exit_f;
 997               assert(f <= 1 && f >= 0, "Incorrect frequency");
 998             } else {
 999               float p = -1;
1000               if (n->in(0)->is_If()) {
1001                 p = n->in(0)->as_If()->_prob;
1002                 if (n->Opcode() == Op_IfFalse) {
1003                   p = 1 - p;
1004                 }
1005               } else {
1006                 assert(n->in(0)->is_Jump(), "unsupported node kind");
1007                 p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
1008               }
1009               f = f * p;
1010               assert(f <= 1 && f >= 0, "Incorrect frequency");
1011             }
1012             _freqs.at_put_grow(n->_idx, (float)f, -1);
1013             _stack.pop();
1014           } else {
1015             float prev_f = _freqs_stack.pop();
1016             float new_f = f;
1017             f = new_f + prev_f;
1018             assert(f <= 1 && f >= 0, "Incorrect frequency");
1019             uint i = _stack.index();
1020             if (i < n->req()) {
1021               c = n->in(i);
1022               _stack.set_index(i+1);
1023               _freqs_stack.push(f);
1024             } else {
1025               _freqs.at_put_grow(n->_idx, f, -1);
1026               _stack.pop();
1027             }
1028           }
1029         }
1030         if (_stack.size() == 0) {
1031           fesetround(FE_TONEAREST);
1032           assert(f >= 0 && f <= 1, "should have been computed");
1033           return f;
1034         }
1035       } else if (c->is_Loop()) {
1036         ShouldNotReachHere();
1037         c = c->in(LoopNode::EntryControl);
1038       } else if (c->is_Region()) {
1039         _freqs_stack.push(0);
1040         _stack.push(c, 2);
1041         c = c->in(1);
1042       } else {
1043         if (c->is_IfProj()) {
1044           IfNode* iff = c->in(0)->as_If();
1045           if (iff->_prob == PROB_UNKNOWN) {
1046             // assume never taken
1047             _freqs.at_put_grow(c->_idx, 0, -1);
1048           } else if (_phase->get_loop(c) != _phase->get_loop(iff)) {
1049             if (iff->_fcnt == COUNT_UNKNOWN) {
1050               // assume never taken
1051               _freqs.at_put_grow(c->_idx, 0, -1);
1052             } else {
1053               // skip over loop
1054               _stack.push(c, 1);
1055               c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
1056             }
1057           } else {
1058             _stack.push(c, 1);
1059             c = iff;
1060           }
1061         } else if (c->is_JumpProj()) {
1062           JumpNode* jmp = c->in(0)->as_Jump();
1063           if (_phase->get_loop(c) != _phase->get_loop(jmp)) {
1064             if (jmp->_fcnt == COUNT_UNKNOWN) {
1065               // assume never taken
1066               _freqs.at_put_grow(c->_idx, 0, -1);
1067             } else {
1068               // skip over loop
1069               _stack.push(c, 1);
1070               c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
1071             }
1072           } else {
1073             _stack.push(c, 1);
1074             c = jmp;
1075           }
1076         } else if (c->Opcode() == Op_CatchProj &&
1077                    c->in(0)->Opcode() == Op_Catch &&
1078                    c->in(0)->in(0)->is_Proj() &&
1079                    c->in(0)->in(0)->in(0)->is_Call()) {
1080           // assume exceptions are never thrown
1081           uint con = c->as_Proj()->_con;
1082           if (con == CatchProjNode::fall_through_index) {
1083             Node* call = c->in(0)->in(0)->in(0)->in(0);
1084             if (_phase->get_loop(call) != _phase->get_loop(c)) {
1085               _freqs.at_put_grow(c->_idx, 0, -1);
1086             } else {
1087               c = call;
1088             }
1089           } else {
1090             assert(con >= CatchProjNode::catch_all_index, "what else?");
1091             _freqs.at_put_grow(c->_idx, 0, -1);
1092           }
1093         } else if (c->unique_ctrl_out() == NULL && !c->is_If() && !c->is_Jump()) {
1094           ShouldNotReachHere();
1095         } else {
1096           c = c->in(0);
1097         }
1098       }
1099     }
1100     ShouldNotReachHere();
1101     return -1;
1102   }
1103 };
1104 
1105 void PhaseIdealLoop::loop_predication_follow_branches(Node *n, IdealLoopTree *loop, float loop_trip_cnt,
1106                                                       PathFrequency& pf, Node_Stack& stack, VectorSet& seen,
1107                                                       Node_List& if_proj_list) {
1108   assert(n->is_Region(), "start from a region");
1109   Node* tail = loop->tail();
1110   stack.push(n, 1);
1111   do {
1112     Node* c = stack.node();
1113     assert(c->is_Region() || c->is_IfProj(), "only region here");
1114     uint i = stack.index();
1115 
1116     if (i < c->req()) {
1117       stack.set_index(i+1);
1118       Node* in = c->in(i);
1119       while (!is_dominator(in, tail) && !seen.test_set(in->_idx)) {
1120         IdealLoopTree* in_loop = get_loop(in);
1121         if (in_loop != loop) {
1122           in = in_loop->_head->in(LoopNode::EntryControl);
1123         } else if (in->is_Region()) {
1124           stack.push(in, 1);
1125           break;
1126         } else if (in->is_IfProj() &&
1127                    in->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1128                    (in->in(0)->Opcode() == Op_If ||
1129                     in->in(0)->Opcode() == Op_RangeCheck)) {
1130           if (pf.to(in) * loop_trip_cnt >= 1) {
1131             stack.push(in, 1);
1132           }
1133           in = in->in(0);
1134         } else {
1135           in = in->in(0);
1136         }
1137       }
1138     } else {
1139       if (c->is_IfProj()) {
1140         if_proj_list.push(c);
1141       }
1142       stack.pop();
1143     }
1144 
1145   } while (stack.size() > 0);
1146 }
1147 
1148 
1149 bool PhaseIdealLoop::loop_predication_impl_helper(IdealLoopTree *loop, ProjNode* proj, ProjNode *predicate_proj,
1150                                                   CountedLoopNode *cl, ConNode* zero, Invariance& invar,
1151                                                   Deoptimization::DeoptReason reason) {
1152   // Following are changed to nonnull when a predicate can be hoisted
1153   ProjNode* new_predicate_proj = NULL;
1154   IfNode*   iff  = proj->in(0)->as_If();
1155   Node*     test = iff->in(1);
1156   if (!test->is_Bool()){ //Conv2B, ...
1157     return false;
1158   }
1159   BoolNode* bol = test->as_Bool();
1160   if (invar.is_invariant(bol)) {
1161     // Invariant test
1162     new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
1163                                                      reason,
1164                                                      iff->Opcode());
1165     Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
1166     BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
1167 
1168     // Negate test if necessary
1169     bool negated = false;
1170     if (proj->_con != predicate_proj->_con) {
1171       new_predicate_bol = new BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
1172       register_new_node(new_predicate_bol, ctrl);
1173       negated = true;
1174     }
1175     IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
1176     _igvn.hash_delete(new_predicate_iff);
1177     new_predicate_iff->set_req(1, new_predicate_bol);
1178 #ifndef PRODUCT
1179     if (TraceLoopPredicate) {
1180       tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
1181       loop->dump_head();
1182     } else if (TraceLoopOpts) {
1183       tty->print("Predicate IC ");
1184       loop->dump_head();
1185     }
1186 #endif
1187   } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
1188     // Range check for counted loops
1189     const Node*    cmp    = bol->in(1)->as_Cmp();
1190     Node*          idx    = cmp->in(1);
1191     assert(!invar.is_invariant(idx), "index is variant");
1192     Node* rng = cmp->in(2);
1193     assert(rng->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(rng)->is_int()->_lo >= 0, "must be");
1194     assert(invar.is_invariant(rng), "range must be invariant");
1195     int scale    = 1;
1196     Node* offset = zero;
1197     bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
1198     assert(ok, "must be index expression");
1199 
1200     Node* init    = cl->init_trip();
1201     // Limit is not exact.
1202     // Calculate exact limit here.
1203     // Note, counted loop's test is '<' or '>'.
1204     Node* limit   = exact_limit(loop);
1205     int  stride   = cl->stride()->get_int();
1206 
1207     // Build if's for the upper and lower bound tests.  The
1208     // lower_bound test will dominate the upper bound test and all
1209     // cloned or created nodes will use the lower bound test as
1210     // their declared control.
1211 
1212     // Perform cloning to keep Invariance state correct since the
1213     // late schedule will place invariant things in the loop.
1214     Node *ctrl = predicate_proj->in(0)->as_If()->in(0);
1215     rng = invar.clone(rng, ctrl);
1216     if (offset && offset != zero) {
1217       assert(invar.is_invariant(offset), "offset must be loop invariant");
1218       offset = invar.clone(offset, ctrl);
1219     }
1220     // If predicate expressions may overflow in the integer range, longs are used.
1221     bool overflow = false;
1222 
1223     // Test the lower bound
1224     BoolNode* lower_bound_bol = rc_predicate(loop, ctrl, scale, offset, init, limit, stride, rng, false, overflow);
1225     // Negate test if necessary
1226     bool negated = false;
1227     if (proj->_con != predicate_proj->_con) {
1228       lower_bound_bol = new BoolNode(lower_bound_bol->in(1), lower_bound_bol->_test.negate());
1229       register_new_node(lower_bound_bol, ctrl);
1230       negated = true;
1231     }
1232     ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
1233     IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
1234     _igvn.hash_delete(lower_bound_iff);
1235     lower_bound_iff->set_req(1, lower_bound_bol);
1236     if (TraceLoopPredicate) tty->print_cr("lower bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
1237 
1238     // Test the upper bound
1239     BoolNode* upper_bound_bol = rc_predicate(loop, lower_bound_proj, scale, offset, init, limit, stride, rng, true, overflow);
1240     negated = false;
1241     if (proj->_con != predicate_proj->_con) {
1242       upper_bound_bol = new BoolNode(upper_bound_bol->in(1), upper_bound_bol->_test.negate());
1243       register_new_node(upper_bound_bol, ctrl);
1244       negated = true;
1245     }
1246     ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
1247     assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
1248     IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
1249     _igvn.hash_delete(upper_bound_iff);
1250     upper_bound_iff->set_req(1, upper_bound_bol);
1251     if (TraceLoopPredicate) tty->print_cr("upper bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
1252 
1253     // Fall through into rest of the clean up code which will move
1254     // any dependent nodes onto the upper bound test.
1255     new_predicate_proj = upper_bound_proj;
1256 
1257     if (iff->is_RangeCheck()) {
1258       new_predicate_proj = insert_skeleton_predicate(iff, loop, proj, predicate_proj, upper_bound_proj, scale, offset, init, limit, stride, rng, overflow, reason);
1259     }
1260 
1261 #ifndef PRODUCT
1262     if (TraceLoopOpts && !TraceLoopPredicate) {
1263       tty->print("Predicate RC ");
1264       loop->dump_head();
1265     }
1266 #endif
1267   } else {
1268     // Loop variant check (for example, range check in non-counted loop)
1269     // with uncommon trap.
1270     return false;
1271   }
1272   assert(new_predicate_proj != NULL, "sanity");
1273   // Success - attach condition (new_predicate_bol) to predicate if
1274   invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
1275 
1276   // Eliminate the old If in the loop body
1277   dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
1278 
1279   C->set_major_progress();
1280   return true;
1281 }
1282 
1283 
1284 // After pre/main/post loops are created, we'll put a copy of some
1285 // range checks between the pre and main loop to validate the value
1286 // of the main loop induction variable. Make a copy of the predicates
1287 // here with an opaque node as a place holder for the value (will be
1288 // updated by PhaseIdealLoop::update_skeleton_predicate()).
1289 ProjNode* PhaseIdealLoop::insert_skeleton_predicate(IfNode* iff, IdealLoopTree *loop,
1290                                                     ProjNode* proj, ProjNode *predicate_proj,
1291                                                     ProjNode* upper_bound_proj,
1292                                                     int scale, Node* offset,
1293                                                     Node* init, Node* limit, jint stride,
1294                                                     Node* rng, bool &overflow,
1295                                                     Deoptimization::DeoptReason reason) {
1296   assert(proj->_con && predicate_proj->_con, "not a range check?");
1297   Node* opaque_init = new Opaque1Node(C, init);
1298   register_new_node(opaque_init, upper_bound_proj);
1299   BoolNode* bol = rc_predicate(loop, upper_bound_proj, scale, offset, opaque_init, limit, stride, rng, (stride > 0) != (scale > 0), overflow);
1300   Node* opaque_bol = new Opaque4Node(C, bol, _igvn.intcon(1)); // This will go away once loop opts are over
1301   register_new_node(opaque_bol, upper_bound_proj);
1302   ProjNode* new_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
1303   _igvn.replace_input_of(new_proj->in(0), 1, opaque_bol);
1304   assert(opaque_init->outcnt() > 0, "should be used");
1305   return new_proj;
1306 }
1307 
1308 //------------------------------ loop_predication_impl--------------------------
1309 // Insert loop predicates for null checks and range checks
1310 bool PhaseIdealLoop::loop_predication_impl(IdealLoopTree *loop) {
1311   if (!UseLoopPredicate) return false;
1312 
1313   if (!loop->_head->is_Loop()) {
1314     // Could be a simple region when irreducible loops are present.
1315     return false;
1316   }
1317   LoopNode* head = loop->_head->as_Loop();
1318 
1319   if (head->unique_ctrl_out()->Opcode() == Op_NeverBranch) {
1320     // do nothing for infinite loops
1321     return false;
1322   }
1323 
1324   if (head->is_OuterStripMinedLoop()) {
1325     return false;
1326   }
1327 
1328   CountedLoopNode *cl = NULL;
1329   if (head->is_valid_counted_loop()) {
1330     cl = head->as_CountedLoop();
1331     // do nothing for iteration-splitted loops
1332     if (!cl->is_normal_loop()) return false;
1333     // Avoid RCE if Counted loop's test is '!='.
1334     BoolTest::mask bt = cl->loopexit()->test_trip();
1335     if (bt != BoolTest::lt && bt != BoolTest::gt)
1336       cl = NULL;
1337   }
1338 
1339   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
1340   ProjNode *loop_limit_proj = NULL;
1341   ProjNode *predicate_proj = NULL;
1342   ProjNode *profile_predicate_proj = NULL;
1343   // Loop limit check predicate should be near the loop.
1344   loop_limit_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
1345   if (loop_limit_proj != NULL) {
1346     entry = loop_limit_proj->in(0)->in(0);
1347   }
1348   bool has_profile_predicates = false;
1349   profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
1350   if (profile_predicate_proj != NULL) {
1351     Node* n = skip_loop_predicates(entry);
1352     // Check if predicates were already added to the profile predicate
1353     // block
1354     if (n != entry->in(0)->in(0) || n->outcnt() != 1) {
1355       has_profile_predicates = true;
1356     }
1357     entry = n;
1358   }
1359   predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
1360 
1361   float loop_trip_cnt = -1;
1362   bool follow_branches = loop_predication_should_follow_branches(loop, profile_predicate_proj, loop_trip_cnt);
1363   assert(!follow_branches || loop_trip_cnt >= 0, "negative trip count?");
1364 
1365   if (predicate_proj == NULL && !follow_branches) {
1366 #ifndef PRODUCT
1367     if (TraceLoopPredicate) {
1368       tty->print("missing predicate:");
1369       loop->dump_head();
1370       head->dump(1);
1371     }
1372 #endif
1373     return false;
1374   }
1375   ConNode* zero = _igvn.intcon(0);
1376   set_ctrl(zero, C->root());
1377 
1378   ResourceArea *area = Thread::current()->resource_area();
1379   Invariance invar(area, loop);
1380 
1381   // Create list of if-projs such that a newer proj dominates all older
1382   // projs in the list, and they all dominate loop->tail()
1383   Node_List if_proj_list(area);
1384   Node_List regions(area);
1385   Node *current_proj = loop->tail(); //start from tail
1386 
1387 
1388   Node_List controls(area);
1389   while (current_proj != head) {
1390     if (loop == get_loop(current_proj) && // still in the loop ?
1391         current_proj->is_Proj()        && // is a projection  ?
1392         (current_proj->in(0)->Opcode() == Op_If ||
1393          current_proj->in(0)->Opcode() == Op_RangeCheck)) { // is a if projection ?
1394       if_proj_list.push(current_proj);
1395     }
1396     if (follow_branches &&
1397         current_proj->Opcode() == Op_Region &&
1398         loop == get_loop(current_proj)) {
1399       regions.push(current_proj);
1400     }
1401     current_proj = idom(current_proj);
1402   }
1403 
1404   bool hoisted = false; // true if at least one proj is promoted
1405 
1406   if (!has_profile_predicates) {
1407     while (if_proj_list.size() > 0) {
1408       Node* n = if_proj_list.pop();
1409 
1410       ProjNode* proj = n->as_Proj();
1411       IfNode*   iff  = proj->in(0)->as_If();
1412 
1413       CallStaticJavaNode* call = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1414       if (call == NULL) {
1415         if (loop->is_loop_exit(iff)) {
1416           // stop processing the remaining projs in the list because the execution of them
1417           // depends on the condition of "iff" (iff->in(1)).
1418           break;
1419         } else {
1420           // Both arms are inside the loop. There are two cases:
1421           // (1) there is one backward branch. In this case, any remaining proj
1422           //     in the if_proj list post-dominates "iff". So, the condition of "iff"
1423           //     does not determine the execution the remining projs directly, and we
1424           //     can safely continue.
1425           // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
1426           //     does not dominate loop->tail(), so it can not be in the if_proj list.
1427           continue;
1428         }
1429       }
1430       Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(call->uncommon_trap_request());
1431       if (reason == Deoptimization::Reason_predicate) {
1432         break;
1433       }
1434 
1435       if (predicate_proj != NULL) {
1436         hoisted = loop_predication_impl_helper(loop, proj, predicate_proj, cl, zero, invar, Deoptimization::Reason_predicate) | hoisted;
1437       }
1438     } // end while
1439   }
1440 
1441   Node_List if_proj_list_freq(area);
1442   if (follow_branches) {
1443     PathFrequency pf(loop->_head, this);
1444 
1445     // Some projections were skipped by regular predicates because of
1446     // an early loop exit. Try them with profile data.
1447     while (if_proj_list.size() > 0) {
1448       Node* proj = if_proj_list.pop();
1449       float f = pf.to(proj);
1450       if (proj->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1451           f * loop_trip_cnt >= 1) {
1452         hoisted = loop_predication_impl_helper(loop, proj->as_Proj(), profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted;
1453       }
1454     }
1455 
1456     // And look into all branches
1457     Node_Stack stack(0);
1458     VectorSet seen(Thread::current()->resource_area());
1459     while (regions.size() > 0) {
1460       Node* c = regions.pop();
1461       loop_predication_follow_branches(c, loop, loop_trip_cnt, pf, stack, seen, if_proj_list_freq);
1462     }
1463 
1464     for (uint i = 0; i < if_proj_list_freq.size(); i++) {
1465       ProjNode* proj = if_proj_list_freq.at(i)->as_Proj();
1466       hoisted = loop_predication_impl_helper(loop, proj, profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted;
1467     }
1468   }
1469 
1470 #ifndef PRODUCT
1471   // report that the loop predication has been actually performed
1472   // for this loop
1473   if (TraceLoopPredicate && hoisted) {
1474     tty->print("Loop Predication Performed:");
1475     loop->dump_head();
1476   }
1477 #endif
1478 
1479   head->verify_strip_mined(1);
1480 
1481   return hoisted;
1482 }
1483 
1484 //------------------------------loop_predication--------------------------------
1485 // driver routine for loop predication optimization
1486 bool IdealLoopTree::loop_predication( PhaseIdealLoop *phase) {
1487   bool hoisted = false;
1488   // Recursively promote predicates
1489   if (_child) {
1490     hoisted = _child->loop_predication( phase);
1491   }
1492 
1493   // self
1494   if (!_irreducible && !tail()->is_top()) {
1495     hoisted |= phase->loop_predication_impl(this);
1496   }
1497 
1498   if (_next) { //sibling
1499     hoisted |= _next->loop_predication( phase);
1500   }
1501 
1502   return hoisted;
1503 }