1 /*
   2  * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/shared/barrierSet.hpp"
  27 #include "gc/shared/c2/barrierSetC2.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "oops/objArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/connode.hpp"
  35 #include "opto/convertnode.hpp"
  36 #include "opto/inlinetypenode.hpp"
  37 #include "opto/loopnode.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/movenode.hpp"
  40 #include "opto/narrowptrnode.hpp"
  41 #include "opto/mulnode.hpp"
  42 #include "opto/phaseX.hpp"
  43 #include "opto/regalloc.hpp"
  44 #include "opto/regmask.hpp"
  45 #include "opto/runtime.hpp"
  46 #include "opto/subnode.hpp"
  47 #include "opto/vectornode.hpp"
  48 #include "utilities/vmError.hpp"
  49 
  50 // Portions of code courtesy of Clifford Click
  51 
  52 // Optimization - Graph Style
  53 
  54 //=============================================================================
  55 //------------------------------Value------------------------------------------
  56 // Compute the type of the RegionNode.
  57 const Type* RegionNode::Value(PhaseGVN* phase) const {
  58   for( uint i=1; i<req(); ++i ) {       // For all paths in
  59     Node *n = in(i);            // Get Control source
  60     if( !n ) continue;          // Missing inputs are TOP
  61     if( phase->type(n) == Type::CONTROL )
  62       return Type::CONTROL;
  63   }
  64   return Type::TOP;             // All paths dead?  Then so are we
  65 }
  66 
  67 //------------------------------Identity---------------------------------------
  68 // Check for Region being Identity.
  69 Node* RegionNode::Identity(PhaseGVN* phase) {
  70   // Cannot have Region be an identity, even if it has only 1 input.
  71   // Phi users cannot have their Region input folded away for them,
  72   // since they need to select the proper data input
  73   return this;
  74 }
  75 
  76 //------------------------------merge_region-----------------------------------
  77 // If a Region flows into a Region, merge into one big happy merge.  This is
  78 // hard to do if there is stuff that has to happen
  79 static Node *merge_region(RegionNode *region, PhaseGVN *phase) {
  80   if( region->Opcode() != Op_Region ) // Do not do to LoopNodes
  81     return nullptr;
  82   Node *progress = nullptr;        // Progress flag
  83   PhaseIterGVN *igvn = phase->is_IterGVN();
  84 
  85   uint rreq = region->req();
  86   for( uint i = 1; i < rreq; i++ ) {
  87     Node *r = region->in(i);
  88     if( r && r->Opcode() == Op_Region && // Found a region?
  89         r->in(0) == r &&        // Not already collapsed?
  90         r != region &&          // Avoid stupid situations
  91         r->outcnt() == 2 ) {    // Self user and 'region' user only?
  92       assert(!r->as_Region()->has_phi(), "no phi users");
  93       if( !progress ) {         // No progress
  94         if (region->has_phi()) {
  95           return nullptr;        // Only flatten if no Phi users
  96           // igvn->hash_delete( phi );
  97         }
  98         igvn->hash_delete( region );
  99         progress = region;      // Making progress
 100       }
 101       igvn->hash_delete( r );
 102 
 103       // Append inputs to 'r' onto 'region'
 104       for( uint j = 1; j < r->req(); j++ ) {
 105         // Move an input from 'r' to 'region'
 106         region->add_req(r->in(j));
 107         r->set_req(j, phase->C->top());
 108         // Update phis of 'region'
 109         //for( uint k = 0; k < max; k++ ) {
 110         //  Node *phi = region->out(k);
 111         //  if( phi->is_Phi() ) {
 112         //    phi->add_req(phi->in(i));
 113         //  }
 114         //}
 115 
 116         rreq++;                 // One more input to Region
 117       } // Found a region to merge into Region
 118       igvn->_worklist.push(r);
 119       // Clobber pointer to the now dead 'r'
 120       region->set_req(i, phase->C->top());
 121     }
 122   }
 123 
 124   return progress;
 125 }
 126 
 127 
 128 
 129 //--------------------------------has_phi--------------------------------------
 130 // Helper function: Return any PhiNode that uses this region or null
 131 PhiNode* RegionNode::has_phi() const {
 132   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 133     Node* phi = fast_out(i);
 134     if (phi->is_Phi()) {   // Check for Phi users
 135       assert(phi->in(0) == (Node*)this, "phi uses region only via in(0)");
 136       return phi->as_Phi();  // this one is good enough
 137     }
 138   }
 139 
 140   return nullptr;
 141 }
 142 
 143 
 144 //-----------------------------has_unique_phi----------------------------------
 145 // Helper function: Return the only PhiNode that uses this region or null
 146 PhiNode* RegionNode::has_unique_phi() const {
 147   // Check that only one use is a Phi
 148   PhiNode* only_phi = nullptr;
 149   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 150     Node* phi = fast_out(i);
 151     if (phi->is_Phi()) {   // Check for Phi users
 152       assert(phi->in(0) == (Node*)this, "phi uses region only via in(0)");
 153       if (only_phi == nullptr) {
 154         only_phi = phi->as_Phi();
 155       } else {
 156         return nullptr;  // multiple phis
 157       }
 158     }
 159   }
 160 
 161   return only_phi;
 162 }
 163 
 164 
 165 //------------------------------check_phi_clipping-----------------------------
 166 // Helper function for RegionNode's identification of FP clipping
 167 // Check inputs to the Phi
 168 static bool check_phi_clipping( PhiNode *phi, ConNode * &min, uint &min_idx, ConNode * &max, uint &max_idx, Node * &val, uint &val_idx ) {
 169   min     = nullptr;
 170   max     = nullptr;
 171   val     = nullptr;
 172   min_idx = 0;
 173   max_idx = 0;
 174   val_idx = 0;
 175   uint  phi_max = phi->req();
 176   if( phi_max == 4 ) {
 177     for( uint j = 1; j < phi_max; ++j ) {
 178       Node *n = phi->in(j);
 179       int opcode = n->Opcode();
 180       switch( opcode ) {
 181       case Op_ConI:
 182         {
 183           if( min == nullptr ) {
 184             min     = n->Opcode() == Op_ConI ? (ConNode*)n : nullptr;
 185             min_idx = j;
 186           } else {
 187             max     = n->Opcode() == Op_ConI ? (ConNode*)n : nullptr;
 188             max_idx = j;
 189             if( min->get_int() > max->get_int() ) {
 190               // Swap min and max
 191               ConNode *temp;
 192               uint     temp_idx;
 193               temp     = min;     min     = max;     max     = temp;
 194               temp_idx = min_idx; min_idx = max_idx; max_idx = temp_idx;
 195             }
 196           }
 197         }
 198         break;
 199       default:
 200         {
 201           val = n;
 202           val_idx = j;
 203         }
 204         break;
 205       }
 206     }
 207   }
 208   return ( min && max && val && (min->get_int() <= 0) && (max->get_int() >=0) );
 209 }
 210 
 211 
 212 //------------------------------check_if_clipping------------------------------
 213 // Helper function for RegionNode's identification of FP clipping
 214 // Check that inputs to Region come from two IfNodes,
 215 //
 216 //            If
 217 //      False    True
 218 //       If        |
 219 //  False  True    |
 220 //    |      |     |
 221 //  RegionNode_inputs
 222 //
 223 static bool check_if_clipping( const RegionNode *region, IfNode * &bot_if, IfNode * &top_if ) {
 224   top_if = nullptr;
 225   bot_if = nullptr;
 226 
 227   // Check control structure above RegionNode for (if  ( if  ) )
 228   Node *in1 = region->in(1);
 229   Node *in2 = region->in(2);
 230   Node *in3 = region->in(3);
 231   // Check that all inputs are projections
 232   if( in1->is_Proj() && in2->is_Proj() && in3->is_Proj() ) {
 233     Node *in10 = in1->in(0);
 234     Node *in20 = in2->in(0);
 235     Node *in30 = in3->in(0);
 236     // Check that #1 and #2 are ifTrue and ifFalse from same If
 237     if( in10 != nullptr && in10->is_If() &&
 238         in20 != nullptr && in20->is_If() &&
 239         in30 != nullptr && in30->is_If() && in10 == in20 &&
 240         (in1->Opcode() != in2->Opcode()) ) {
 241       Node  *in100 = in10->in(0);
 242       Node *in1000 = (in100 != nullptr && in100->is_Proj()) ? in100->in(0) : nullptr;
 243       // Check that control for in10 comes from other branch of IF from in3
 244       if( in1000 != nullptr && in1000->is_If() &&
 245           in30 == in1000 && (in3->Opcode() != in100->Opcode()) ) {
 246         // Control pattern checks
 247         top_if = (IfNode*)in1000;
 248         bot_if = (IfNode*)in10;
 249       }
 250     }
 251   }
 252 
 253   return (top_if != nullptr);
 254 }
 255 
 256 
 257 //------------------------------check_convf2i_clipping-------------------------
 258 // Helper function for RegionNode's identification of FP clipping
 259 // Verify that the value input to the phi comes from "ConvF2I; LShift; RShift"
 260 static bool check_convf2i_clipping( PhiNode *phi, uint idx, ConvF2INode * &convf2i, Node *min, Node *max) {
 261   convf2i = nullptr;
 262 
 263   // Check for the RShiftNode
 264   Node *rshift = phi->in(idx);
 265   assert( rshift, "Previous checks ensure phi input is present");
 266   if( rshift->Opcode() != Op_RShiftI )  { return false; }
 267 
 268   // Check for the LShiftNode
 269   Node *lshift = rshift->in(1);
 270   assert( lshift, "Previous checks ensure phi input is present");
 271   if( lshift->Opcode() != Op_LShiftI )  { return false; }
 272 
 273   // Check for the ConvF2INode
 274   Node *conv = lshift->in(1);
 275   if( conv->Opcode() != Op_ConvF2I ) { return false; }
 276 
 277   // Check that shift amounts are only to get sign bits set after F2I
 278   jint max_cutoff     = max->get_int();
 279   jint min_cutoff     = min->get_int();
 280   jint left_shift     = lshift->in(2)->get_int();
 281   jint right_shift    = rshift->in(2)->get_int();
 282   jint max_post_shift = nth_bit(BitsPerJavaInteger - left_shift - 1);
 283   if( left_shift != right_shift ||
 284       0 > left_shift || left_shift >= BitsPerJavaInteger ||
 285       max_post_shift < max_cutoff ||
 286       max_post_shift < -min_cutoff ) {
 287     // Shifts are necessary but current transformation eliminates them
 288     return false;
 289   }
 290 
 291   // OK to return the result of ConvF2I without shifting
 292   convf2i = (ConvF2INode*)conv;
 293   return true;
 294 }
 295 
 296 
 297 //------------------------------check_compare_clipping-------------------------
 298 // Helper function for RegionNode's identification of FP clipping
 299 static bool check_compare_clipping( bool less_than, IfNode *iff, ConNode *limit, Node * & input ) {
 300   Node *i1 = iff->in(1);
 301   if ( !i1->is_Bool() ) { return false; }
 302   BoolNode *bool1 = i1->as_Bool();
 303   if(       less_than && bool1->_test._test != BoolTest::le ) { return false; }
 304   else if( !less_than && bool1->_test._test != BoolTest::lt ) { return false; }
 305   const Node *cmpF = bool1->in(1);
 306   if( cmpF->Opcode() != Op_CmpF )      { return false; }
 307   // Test that the float value being compared against
 308   // is equivalent to the int value used as a limit
 309   Node *nodef = cmpF->in(2);
 310   if( nodef->Opcode() != Op_ConF ) { return false; }
 311   jfloat conf = nodef->getf();
 312   jint   coni = limit->get_int();
 313   if( ((int)conf) != coni )        { return false; }
 314   input = cmpF->in(1);
 315   return true;
 316 }
 317 
 318 //------------------------------is_unreachable_region--------------------------
 319 // Check if the RegionNode is part of an unsafe loop and unreachable from root.
 320 bool RegionNode::is_unreachable_region(const PhaseGVN* phase) {
 321   Node* top = phase->C->top();
 322   assert(req() == 2 || (req() == 3 && in(1) != nullptr && in(2) == top), "sanity check arguments");
 323   if (_is_unreachable_region) {
 324     // Return cached result from previous evaluation which should still be valid
 325     assert(is_unreachable_from_root(phase), "walk the graph again and check if its indeed unreachable");
 326     return true;
 327   }
 328 
 329   // First, cut the simple case of fallthrough region when NONE of
 330   // region's phis references itself directly or through a data node.
 331   if (is_possible_unsafe_loop(phase)) {
 332     // If we have a possible unsafe loop, check if the region node is actually unreachable from root.
 333     if (is_unreachable_from_root(phase)) {
 334       _is_unreachable_region = true;
 335       return true;
 336     }
 337   }
 338   return false;
 339 }
 340 
 341 bool RegionNode::is_possible_unsafe_loop(const PhaseGVN* phase) const {
 342   uint max = outcnt();
 343   uint i;
 344   for (i = 0; i < max; i++) {
 345     Node* n = raw_out(i);
 346     if (n != nullptr && n->is_Phi()) {
 347       PhiNode* phi = n->as_Phi();
 348       assert(phi->in(0) == this, "sanity check phi");
 349       if (phi->outcnt() == 0) {
 350         continue; // Safe case - no loops
 351       }
 352       if (phi->outcnt() == 1) {
 353         Node* u = phi->raw_out(0);
 354         // Skip if only one use is an other Phi or Call or Uncommon trap.
 355         // It is safe to consider this case as fallthrough.
 356         if (u != nullptr && (u->is_Phi() || u->is_CFG())) {
 357           continue;
 358         }
 359       }
 360       // Check when phi references itself directly or through an other node.
 361       if (phi->as_Phi()->simple_data_loop_check(phi->in(1)) >= PhiNode::Unsafe) {
 362         break; // Found possible unsafe data loop.
 363       }
 364     }
 365   }
 366   if (i >= max) {
 367     return false; // An unsafe case was NOT found - don't need graph walk.
 368   }
 369   return true;
 370 }
 371 
 372 bool RegionNode::is_unreachable_from_root(const PhaseGVN* phase) const {
 373   ResourceMark rm;
 374   Node_List nstack;
 375   VectorSet visited;
 376 
 377   // Mark all control nodes reachable from root outputs
 378   Node* n = (Node*)phase->C->root();
 379   nstack.push(n);
 380   visited.set(n->_idx);
 381   while (nstack.size() != 0) {
 382     n = nstack.pop();
 383     uint max = n->outcnt();
 384     for (uint i = 0; i < max; i++) {
 385       Node* m = n->raw_out(i);
 386       if (m != nullptr && m->is_CFG()) {
 387         if (m == this) {
 388           return false; // We reached the Region node - it is not dead.
 389         }
 390         if (!visited.test_set(m->_idx))
 391           nstack.push(m);
 392       }
 393     }
 394   }
 395   return true; // The Region node is unreachable - it is dead.
 396 }
 397 
 398 #ifdef ASSERT
 399 // Is this region in an infinite subgraph?
 400 // (no path to root except through false NeverBranch exit)
 401 bool RegionNode::is_in_infinite_subgraph() {
 402   ResourceMark rm;
 403   Unique_Node_List worklist;
 404   worklist.push(this);
 405   return RegionNode::are_all_nodes_in_infinite_subgraph(worklist);
 406 }
 407 
 408 // Are all nodes in worklist in infinite subgraph?
 409 // (no path to root except through false NeverBranch exit)
 410 // worklist is directly used for the traversal
 411 bool RegionNode::are_all_nodes_in_infinite_subgraph(Unique_Node_List& worklist) {
 412   // BFS traversal down the CFG, except through NeverBranch exits
 413   for (uint i = 0; i < worklist.size(); ++i) {
 414     Node* n = worklist.at(i);
 415     assert(n->is_CFG(), "only traverse CFG");
 416     if (n->is_Root()) {
 417       // Found root -> there was an exit!
 418       return false;
 419     } else if (n->is_NeverBranch()) {
 420       // Only follow the loop-internal projection, not the NeverBranch exit
 421       ProjNode* proj = n->as_NeverBranch()->proj_out_or_null(0);
 422       assert(proj != nullptr, "must find loop-internal projection of NeverBranch");
 423       worklist.push(proj);
 424     } else {
 425       // Traverse all CFG outputs
 426       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 427         Node* use = n->fast_out(i);
 428         if (use->is_CFG()) {
 429           worklist.push(use);
 430         }
 431       }
 432     }
 433   }
 434   // No exit found for any loop -> all are infinite
 435   return true;
 436 }
 437 #endif //ASSERT
 438 
 439 void RegionNode::set_loop_status(RegionNode::LoopStatus status) {
 440   assert(loop_status() == RegionNode::LoopStatus::NeverIrreducibleEntry, "why set our status again?");
 441   _loop_status = status;
 442 }
 443 
 444 #ifdef ASSERT
 445 void RegionNode::verify_can_be_irreducible_entry() const {
 446   assert(loop_status() == RegionNode::LoopStatus::MaybeIrreducibleEntry, "must be marked irreducible");
 447   assert(!is_Loop(), "LoopNode cannot be irreducible loop entry");
 448 }
 449 #endif //ASSERT
 450 
 451 void RegionNode::try_clean_mem_phis(PhaseIterGVN* igvn) {
 452   // Incremental inlining + PhaseStringOpts sometimes produce:
 453   //
 454   // cmpP with 1 top input
 455   //           |
 456   //          If
 457   //         /  \
 458   //   IfFalse  IfTrue  /- Some Node
 459   //         \  /      /    /
 460   //        Region    / /-MergeMem
 461   //             \---Phi
 462   //
 463   //
 464   // It's expected by PhaseStringOpts that the Region goes away and is
 465   // replaced by If's control input but because there's still a Phi,
 466   // the Region stays in the graph. The top input from the cmpP is
 467   // propagated forward and a subgraph that is useful goes away. The
 468   // code in PhiNode::try_clean_memory_phi() replaces the Phi with the
 469   // MergeMem in order to remove the Region if its last phi dies.
 470 
 471   if (!is_diamond()) {
 472     return;
 473   }
 474 
 475   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 476     Node* phi = fast_out(i);
 477     if (phi->is_Phi() && phi->as_Phi()->try_clean_memory_phi(igvn)) {
 478       --i;
 479       --imax;
 480     }
 481   }
 482 }
 483 
 484 // Does this region merge a simple diamond formed by a proper IfNode?
 485 //
 486 //              Cmp
 487 //              /
 488 //     ctrl   Bool
 489 //       \    /
 490 //       IfNode
 491 //      /      \
 492 //  IfFalse   IfTrue
 493 //      \      /
 494 //       Region
 495 bool RegionNode::is_diamond() const {
 496   if (req() != 3) {
 497     return false;
 498   }
 499 
 500   Node* left_path = in(1);
 501   Node* right_path = in(2);
 502   if (left_path == nullptr || right_path == nullptr) {
 503     return false;
 504   }
 505   Node* diamond_if = left_path->in(0);
 506   if (diamond_if == nullptr || !diamond_if->is_If() || diamond_if != right_path->in(0)) {
 507     // Not an IfNode merging a diamond or TOP.
 508     return false;
 509   }
 510 
 511   // Check for a proper bool/cmp
 512   const Node* bol = diamond_if->in(1);
 513   if (!bol->is_Bool()) {
 514     return false;
 515   }
 516   const Node* cmp = bol->in(1);
 517   if (!cmp->is_Cmp()) {
 518     return false;
 519   }
 520   return true;
 521 }
 522 
 523 //------------------------------Ideal------------------------------------------
 524 // Return a node which is more "ideal" than the current node.  Must preserve
 525 // the CFG, but we can still strip out dead paths.
 526 Node *RegionNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 527   if( !can_reshape && !in(0) ) return nullptr;     // Already degraded to a Copy
 528   assert(!in(0) || !in(0)->is_Root(), "not a specially hidden merge");
 529 
 530   // Check for RegionNode with no Phi users and both inputs come from either
 531   // arm of the same IF.  If found, then the control-flow split is useless.
 532   bool has_phis = false;
 533   if (can_reshape) {            // Need DU info to check for Phi users
 534     try_clean_mem_phis(phase->is_IterGVN());
 535     has_phis = (has_phi() != nullptr);       // Cache result
 536 
 537     if (!has_phis) {            // No Phi users?  Nothing merging?
 538       for (uint i = 1; i < req()-1; i++) {
 539         Node *if1 = in(i);
 540         if( !if1 ) continue;
 541         Node *iff = if1->in(0);
 542         if( !iff || !iff->is_If() ) continue;
 543         for( uint j=i+1; j<req(); j++ ) {
 544           if( in(j) && in(j)->in(0) == iff &&
 545               if1->Opcode() != in(j)->Opcode() ) {
 546             // Add the IF Projections to the worklist. They (and the IF itself)
 547             // will be eliminated if dead.
 548             phase->is_IterGVN()->add_users_to_worklist(iff);
 549             set_req(i, iff->in(0));// Skip around the useless IF diamond
 550             set_req(j, nullptr);
 551             return this;      // Record progress
 552           }
 553         }
 554       }
 555     }
 556   }
 557 
 558   // Remove TOP or null input paths. If only 1 input path remains, this Region
 559   // degrades to a copy.
 560   bool add_to_worklist = true;
 561   bool modified = false;
 562   int cnt = 0;                  // Count of values merging
 563   DEBUG_ONLY( int cnt_orig = req(); ) // Save original inputs count
 564   DEBUG_ONLY( uint outcnt_orig = outcnt(); )
 565   int del_it = 0;               // The last input path we delete
 566   bool found_top = false; // irreducible loops need to check reachability if we find TOP
 567   // For all inputs...
 568   for( uint i=1; i<req(); ++i ){// For all paths in
 569     Node *n = in(i);            // Get the input
 570     if( n != nullptr ) {
 571       // Remove useless control copy inputs
 572       if( n->is_Region() && n->as_Region()->is_copy() ) {
 573         set_req(i, n->nonnull_req());
 574         modified = true;
 575         i--;
 576         continue;
 577       }
 578       if( n->is_Proj() ) {      // Remove useless rethrows
 579         Node *call = n->in(0);
 580         if (call->is_Call() && call->as_Call()->entry_point() == OptoRuntime::rethrow_stub()) {
 581           set_req(i, call->in(0));
 582           modified = true;
 583           i--;
 584           continue;
 585         }
 586       }
 587       if( phase->type(n) == Type::TOP ) {
 588         set_req_X(i, nullptr, phase); // Ignore TOP inputs
 589         modified = true;
 590         found_top = true;
 591         i--;
 592         continue;
 593       }
 594       cnt++;                    // One more value merging
 595     } else if (can_reshape) {   // Else found dead path with DU info
 596       PhaseIterGVN *igvn = phase->is_IterGVN();
 597       del_req(i);               // Yank path from self
 598       del_it = i;
 599 
 600       for (DUIterator_Fast jmax, j = fast_outs(jmax); j < jmax; j++) {
 601         Node* use = fast_out(j);
 602 
 603         if (use->req() != req() && use->is_Phi()) {
 604           assert(use->in(0) == this, "unexpected control input");
 605           igvn->hash_delete(use);          // Yank from hash before hacking edges
 606           use->set_req_X(i, nullptr, igvn);// Correct DU info
 607           use->del_req(i);                 // Yank path from Phis
 608         }
 609       }
 610 
 611       if (add_to_worklist) {
 612         igvn->add_users_to_worklist(this);
 613         add_to_worklist = false;
 614       }
 615 
 616       i--;
 617     }
 618   }
 619 
 620   assert(outcnt() == outcnt_orig, "not expect to remove any use");
 621 
 622   if (can_reshape && found_top && loop_status() == RegionNode::LoopStatus::MaybeIrreducibleEntry) {
 623     // Is it a dead irreducible loop?
 624     // If an irreducible loop loses one of the multiple entries
 625     // that went into the loop head, or any secondary entries,
 626     // we need to verify if the irreducible loop is still reachable,
 627     // as the special logic in is_unreachable_region only works
 628     // for reducible loops.
 629     if (is_unreachable_from_root(phase)) {
 630       // The irreducible loop is dead - must remove it
 631       PhaseIterGVN* igvn = phase->is_IterGVN();
 632       remove_unreachable_subgraph(igvn);
 633       return nullptr;
 634     }
 635   } else if (can_reshape && cnt == 1) {
 636     // Is it dead loop?
 637     // If it is LoopNopde it had 2 (+1 itself) inputs and
 638     // one of them was cut. The loop is dead if it was EntryContol.
 639     // Loop node may have only one input because entry path
 640     // is removed in PhaseIdealLoop::Dominators().
 641     assert(!this->is_Loop() || cnt_orig <= 3, "Loop node should have 3 or less inputs");
 642     if ((this->is_Loop() && (del_it == LoopNode::EntryControl ||
 643                              (del_it == 0 && is_unreachable_region(phase)))) ||
 644         (!this->is_Loop() && has_phis && is_unreachable_region(phase))) {
 645       PhaseIterGVN* igvn = phase->is_IterGVN();
 646       remove_unreachable_subgraph(igvn);
 647       return nullptr;
 648     }
 649   }
 650 
 651   if( cnt <= 1 ) {              // Only 1 path in?
 652     set_req(0, nullptr);        // Null control input for region copy
 653     if( cnt == 0 && !can_reshape) { // Parse phase - leave the node as it is.
 654       // No inputs or all inputs are null.
 655       return nullptr;
 656     } else if (can_reshape) {   // Optimization phase - remove the node
 657       PhaseIterGVN *igvn = phase->is_IterGVN();
 658       // Strip mined (inner) loop is going away, remove outer loop.
 659       if (is_CountedLoop() &&
 660           as_Loop()->is_strip_mined()) {
 661         Node* outer_sfpt = as_CountedLoop()->outer_safepoint();
 662         Node* outer_out = as_CountedLoop()->outer_loop_exit();
 663         if (outer_sfpt != nullptr && outer_out != nullptr) {
 664           Node* in = outer_sfpt->in(0);
 665           igvn->replace_node(outer_out, in);
 666           LoopNode* outer = as_CountedLoop()->outer_loop();
 667           igvn->replace_input_of(outer, LoopNode::LoopBackControl, igvn->C->top());
 668         }
 669       }
 670       if (is_CountedLoop()) {
 671         Node* opaq = as_CountedLoop()->is_canonical_loop_entry();
 672         if (opaq != nullptr) {
 673           // This is not a loop anymore. No need to keep the Opaque1 node on the test that guards the loop as it won't be
 674           // subject to further loop opts.
 675           assert(opaq->Opcode() == Op_OpaqueZeroTripGuard, "");
 676           igvn->replace_node(opaq, opaq->in(1));
 677         }
 678       }
 679       Node *parent_ctrl;
 680       if( cnt == 0 ) {
 681         assert( req() == 1, "no inputs expected" );
 682         // During IGVN phase such region will be subsumed by TOP node
 683         // so region's phis will have TOP as control node.
 684         // Kill phis here to avoid it.
 685         // Also set other user's input to top.
 686         parent_ctrl = phase->C->top();
 687       } else {
 688         // The fallthrough case since we already checked dead loops above.
 689         parent_ctrl = in(1);
 690         assert(parent_ctrl != nullptr, "Region is a copy of some non-null control");
 691         assert(parent_ctrl != this, "Close dead loop");
 692       }
 693       if (add_to_worklist) {
 694         igvn->add_users_to_worklist(this); // Check for further allowed opts
 695       }
 696       for (DUIterator_Last imin, i = last_outs(imin); i >= imin; --i) {
 697         Node* n = last_out(i);
 698         igvn->hash_delete(n); // Remove from worklist before modifying edges
 699         if (n->outcnt() == 0) {
 700           int uses_found = n->replace_edge(this, phase->C->top(), igvn);
 701           if (uses_found > 1) { // (--i) done at the end of the loop.
 702             i -= (uses_found - 1);
 703           }
 704           continue;
 705         }
 706         if( n->is_Phi() ) {   // Collapse all Phis
 707           // Eagerly replace phis to avoid regionless phis.
 708           Node* in;
 709           if( cnt == 0 ) {
 710             assert( n->req() == 1, "No data inputs expected" );
 711             in = parent_ctrl; // replaced by top
 712           } else {
 713             assert( n->req() == 2 &&  n->in(1) != nullptr, "Only one data input expected" );
 714             in = n->in(1);               // replaced by unique input
 715             if( n->as_Phi()->is_unsafe_data_reference(in) )
 716               in = phase->C->top();      // replaced by top
 717           }
 718           igvn->replace_node(n, in);
 719         }
 720         else if( n->is_Region() ) { // Update all incoming edges
 721           assert(n != this, "Must be removed from DefUse edges");
 722           int uses_found = n->replace_edge(this, parent_ctrl, igvn);
 723           if (uses_found > 1) { // (--i) done at the end of the loop.
 724             i -= (uses_found - 1);
 725           }
 726         }
 727         else {
 728           assert(n->in(0) == this, "Expect RegionNode to be control parent");
 729           n->set_req(0, parent_ctrl);
 730         }
 731 #ifdef ASSERT
 732         for( uint k=0; k < n->req(); k++ ) {
 733           assert(n->in(k) != this, "All uses of RegionNode should be gone");
 734         }
 735 #endif
 736       }
 737       // Remove the RegionNode itself from DefUse info
 738       igvn->remove_dead_node(this);
 739       return nullptr;
 740     }
 741     return this;                // Record progress
 742   }
 743 
 744 
 745   // If a Region flows into a Region, merge into one big happy merge.
 746   if (can_reshape) {
 747     Node *m = merge_region(this, phase);
 748     if (m != nullptr)  return m;
 749   }
 750 
 751   // Check if this region is the root of a clipping idiom on floats
 752   if( ConvertFloat2IntClipping && can_reshape && req() == 4 ) {
 753     // Check that only one use is a Phi and that it simplifies to two constants +
 754     PhiNode* phi = has_unique_phi();
 755     if (phi != nullptr) {          // One Phi user
 756       // Check inputs to the Phi
 757       ConNode *min;
 758       ConNode *max;
 759       Node    *val;
 760       uint     min_idx;
 761       uint     max_idx;
 762       uint     val_idx;
 763       if( check_phi_clipping( phi, min, min_idx, max, max_idx, val, val_idx )  ) {
 764         IfNode *top_if;
 765         IfNode *bot_if;
 766         if( check_if_clipping( this, bot_if, top_if ) ) {
 767           // Control pattern checks, now verify compares
 768           Node   *top_in = nullptr;   // value being compared against
 769           Node   *bot_in = nullptr;
 770           if( check_compare_clipping( true,  bot_if, min, bot_in ) &&
 771               check_compare_clipping( false, top_if, max, top_in ) ) {
 772             if( bot_in == top_in ) {
 773               PhaseIterGVN *gvn = phase->is_IterGVN();
 774               assert( gvn != nullptr, "Only had DefUse info in IterGVN");
 775               // Only remaining check is that bot_in == top_in == (Phi's val + mods)
 776 
 777               // Check for the ConvF2INode
 778               ConvF2INode *convf2i;
 779               if( check_convf2i_clipping( phi, val_idx, convf2i, min, max ) &&
 780                 convf2i->in(1) == bot_in ) {
 781                 // Matched pattern, including LShiftI; RShiftI, replace with integer compares
 782                 // max test
 783                 Node *cmp   = gvn->register_new_node_with_optimizer(new CmpINode( convf2i, min ));
 784                 Node *boo   = gvn->register_new_node_with_optimizer(new BoolNode( cmp, BoolTest::lt ));
 785                 IfNode *iff = (IfNode*)gvn->register_new_node_with_optimizer(new IfNode( top_if->in(0), boo, PROB_UNLIKELY_MAG(5), top_if->_fcnt ));
 786                 Node *if_min= gvn->register_new_node_with_optimizer(new IfTrueNode (iff));
 787                 Node *ifF   = gvn->register_new_node_with_optimizer(new IfFalseNode(iff));
 788                 // min test
 789                 cmp         = gvn->register_new_node_with_optimizer(new CmpINode( convf2i, max ));
 790                 boo         = gvn->register_new_node_with_optimizer(new BoolNode( cmp, BoolTest::gt ));
 791                 iff         = (IfNode*)gvn->register_new_node_with_optimizer(new IfNode( ifF, boo, PROB_UNLIKELY_MAG(5), bot_if->_fcnt ));
 792                 Node *if_max= gvn->register_new_node_with_optimizer(new IfTrueNode (iff));
 793                 ifF         = gvn->register_new_node_with_optimizer(new IfFalseNode(iff));
 794                 // update input edges to region node
 795                 set_req_X( min_idx, if_min, gvn );
 796                 set_req_X( max_idx, if_max, gvn );
 797                 set_req_X( val_idx, ifF,    gvn );
 798                 // remove unnecessary 'LShiftI; RShiftI' idiom
 799                 gvn->hash_delete(phi);
 800                 phi->set_req_X( val_idx, convf2i, gvn );
 801                 gvn->hash_find_insert(phi);
 802                 // Return transformed region node
 803                 return this;
 804               }
 805             }
 806           }
 807         }
 808       }
 809     }
 810   }
 811 
 812   if (can_reshape) {
 813     modified |= optimize_trichotomy(phase->is_IterGVN());
 814   }
 815 
 816   return modified ? this : nullptr;
 817 }
 818 
 819 //--------------------------remove_unreachable_subgraph----------------------
 820 // This region and therefore all nodes on the input control path(s) are unreachable
 821 // from root. To avoid incomplete removal of unreachable subgraphs, walk up the CFG
 822 // and aggressively replace all nodes by top.
 823 // If a control node "def" with a single control output "use" has its single output
 824 // "use" replaced with top, then "use" removes itself. This has the consequence that
 825 // when we visit "use", it already has all inputs removed. They are lost and we cannot
 826 // traverse them. This is why we fist find all unreachable nodes, and then remove
 827 // them in a second step.
 828 void RegionNode::remove_unreachable_subgraph(PhaseIterGVN* igvn) {
 829   Node* top = igvn->C->top();
 830   ResourceMark rm;
 831   Unique_Node_List unreachable; // visit each only once
 832   unreachable.push(this);
 833   // Recursively find all control inputs.
 834   for (uint i = 0; i < unreachable.size(); i++) {
 835     Node* n = unreachable.at(i);
 836     for (uint i = 0; i < n->req(); ++i) {
 837       Node* m = n->in(i);
 838       assert(m == nullptr || !m->is_Root(), "Should be unreachable from root");
 839       if (m != nullptr && m->is_CFG()) {
 840         unreachable.push(m);
 841       }
 842     }
 843   }
 844   // Remove all unreachable nodes.
 845   for (uint i = 0; i < unreachable.size(); i++) {
 846     Node* n = unreachable.at(i);
 847     if (n->is_Region()) {
 848       // Eagerly replace phis with top to avoid regionless phis.
 849       n->set_req(0, nullptr);
 850       bool progress = true;
 851       uint max = n->outcnt();
 852       DUIterator j;
 853       while (progress) {
 854         progress = false;
 855         for (j = n->outs(); n->has_out(j); j++) {
 856           Node* u = n->out(j);
 857           if (u->is_Phi()) {
 858             igvn->replace_node(u, top);
 859             if (max != n->outcnt()) {
 860               progress = true;
 861               j = n->refresh_out_pos(j);
 862               max = n->outcnt();
 863             }
 864           }
 865         }
 866       }
 867     }
 868     igvn->replace_node(n, top);
 869   }
 870 }
 871 
 872 //------------------------------optimize_trichotomy--------------------------
 873 // Optimize nested comparisons of the following kind:
 874 //
 875 // int compare(int a, int b) {
 876 //   return (a < b) ? -1 : (a == b) ? 0 : 1;
 877 // }
 878 //
 879 // Shape 1:
 880 // if (compare(a, b) == 1) { ... } -> if (a > b) { ... }
 881 //
 882 // Shape 2:
 883 // if (compare(a, b) == 0) { ... } -> if (a == b) { ... }
 884 //
 885 // Above code leads to the following IR shapes where both Ifs compare the
 886 // same value and two out of three region inputs idx1 and idx2 map to
 887 // the same value and control flow.
 888 //
 889 // (1)   If                 (2)   If
 890 //      /  \                     /  \
 891 //   Proj  Proj               Proj  Proj
 892 //     |      \                |      \
 893 //     |       If              |      If                      If
 894 //     |      /  \             |     /  \                    /  \
 895 //     |   Proj  Proj          |  Proj  Proj      ==>     Proj  Proj
 896 //     |   /      /            \    |    /                  |    /
 897 //    Region     /              \   |   /                   |   /
 898 //         \    /                \  |  /                    |  /
 899 //         Region                Region                    Region
 900 //
 901 // The method returns true if 'this' is modified and false otherwise.
 902 bool RegionNode::optimize_trichotomy(PhaseIterGVN* igvn) {
 903   int idx1 = 1, idx2 = 2;
 904   Node* region = nullptr;
 905   if (req() == 3 && in(1) != nullptr && in(2) != nullptr) {
 906     // Shape 1: Check if one of the inputs is a region that merges two control
 907     // inputs and has no other users (especially no Phi users).
 908     region = in(1)->isa_Region() ? in(1) : in(2)->isa_Region();
 909     if (region == nullptr || region->outcnt() != 2 || region->req() != 3) {
 910       return false; // No suitable region input found
 911     }
 912   } else if (req() == 4) {
 913     // Shape 2: Check if two control inputs map to the same value of the unique phi
 914     // user and treat these as if they would come from another region (shape (1)).
 915     PhiNode* phi = has_unique_phi();
 916     if (phi == nullptr) {
 917       return false; // No unique phi user
 918     }
 919     if (phi->in(idx1) != phi->in(idx2)) {
 920       idx2 = 3;
 921       if (phi->in(idx1) != phi->in(idx2)) {
 922         idx1 = 2;
 923         if (phi->in(idx1) != phi->in(idx2)) {
 924           return false; // No equal phi inputs found
 925         }
 926       }
 927     }
 928     assert(phi->in(idx1) == phi->in(idx2), "must be"); // Region is merging same value
 929     region = this;
 930   }
 931   if (region == nullptr || region->in(idx1) == nullptr || region->in(idx2) == nullptr) {
 932     return false; // Region does not merge two control inputs
 933   }
 934   // At this point we know that region->in(idx1) and region->(idx2) map to the same
 935   // value and control flow. Now search for ifs that feed into these region inputs.
 936   ProjNode* proj1 = region->in(idx1)->isa_Proj();
 937   ProjNode* proj2 = region->in(idx2)->isa_Proj();
 938   if (proj1 == nullptr || proj1->outcnt() != 1 ||
 939       proj2 == nullptr || proj2->outcnt() != 1) {
 940     return false; // No projection inputs with region as unique user found
 941   }
 942   assert(proj1 != proj2, "should be different projections");
 943   IfNode* iff1 = proj1->in(0)->isa_If();
 944   IfNode* iff2 = proj2->in(0)->isa_If();
 945   if (iff1 == nullptr || iff1->outcnt() != 2 ||
 946       iff2 == nullptr || iff2->outcnt() != 2) {
 947     return false; // No ifs found
 948   }
 949   if (iff1 == iff2) {
 950     igvn->add_users_to_worklist(iff1); // Make sure dead if is eliminated
 951     igvn->replace_input_of(region, idx1, iff1->in(0));
 952     igvn->replace_input_of(region, idx2, igvn->C->top());
 953     return (region == this); // Remove useless if (both projections map to the same control/value)
 954   }
 955   BoolNode* bol1 = iff1->in(1)->isa_Bool();
 956   BoolNode* bol2 = iff2->in(1)->isa_Bool();
 957   if (bol1 == nullptr || bol2 == nullptr) {
 958     return false; // No bool inputs found
 959   }
 960   Node* cmp1 = bol1->in(1);
 961   Node* cmp2 = bol2->in(1);
 962   bool commute = false;
 963   if (!cmp1->is_Cmp() || !cmp2->is_Cmp()) {
 964     return false; // No comparison
 965   } else if (cmp1->Opcode() == Op_CmpF || cmp1->Opcode() == Op_CmpD ||
 966              cmp2->Opcode() == Op_CmpF || cmp2->Opcode() == Op_CmpD ||
 967              cmp1->Opcode() == Op_CmpP || cmp1->Opcode() == Op_CmpN ||
 968              cmp2->Opcode() == Op_CmpP || cmp2->Opcode() == Op_CmpN ||
 969              cmp1->is_SubTypeCheck() || cmp2->is_SubTypeCheck() ||
 970              cmp1->is_FlatArrayCheck() || cmp2->is_FlatArrayCheck()) {
 971     // Floats and pointers don't exactly obey trichotomy. To be on the safe side, don't transform their tests.
 972     // SubTypeCheck is not commutative
 973     return false;
 974   } else if (cmp1 != cmp2) {
 975     if (cmp1->in(1) == cmp2->in(2) &&
 976         cmp1->in(2) == cmp2->in(1)) {
 977       commute = true; // Same but swapped inputs, commute the test
 978     } else {
 979       return false; // Ifs are not comparing the same values
 980     }
 981   }
 982   proj1 = proj1->other_if_proj();
 983   proj2 = proj2->other_if_proj();
 984   if (!((proj1->unique_ctrl_out_or_null() == iff2 &&
 985          proj2->unique_ctrl_out_or_null() == this) ||
 986         (proj2->unique_ctrl_out_or_null() == iff1 &&
 987          proj1->unique_ctrl_out_or_null() == this))) {
 988     return false; // Ifs are not connected through other projs
 989   }
 990   // Found 'iff -> proj -> iff -> proj -> this' shape where all other projs are merged
 991   // through 'region' and map to the same value. Merge the boolean tests and replace
 992   // the ifs by a single comparison.
 993   BoolTest test1 = (proj1->_con == 1) ? bol1->_test : bol1->_test.negate();
 994   BoolTest test2 = (proj2->_con == 1) ? bol2->_test : bol2->_test.negate();
 995   test1 = commute ? test1.commute() : test1;
 996   // After possibly commuting test1, if we can merge test1 & test2, then proj2/iff2/bol2 are the nodes to refine.
 997   BoolTest::mask res = test1.merge(test2);
 998   if (res == BoolTest::illegal) {
 999     return false; // Unable to merge tests
1000   }
1001   // Adjust iff1 to always pass (only iff2 will remain)
1002   igvn->replace_input_of(iff1, 1, igvn->intcon(proj1->_con));
1003   if (res == BoolTest::never) {
1004     // Merged test is always false, adjust iff2 to always fail
1005     igvn->replace_input_of(iff2, 1, igvn->intcon(1 - proj2->_con));
1006   } else {
1007     // Replace bool input of iff2 with merged test
1008     BoolNode* new_bol = new BoolNode(bol2->in(1), res);
1009     igvn->replace_input_of(iff2, 1, igvn->transform((proj2->_con == 1) ? new_bol : new_bol->negate(igvn)));
1010     if (new_bol->outcnt() == 0) {
1011       igvn->remove_dead_node(new_bol);
1012     }
1013   }
1014   return false;
1015 }
1016 
1017 const RegMask &RegionNode::out_RegMask() const {
1018   return RegMask::Empty;
1019 }
1020 
1021 #ifndef PRODUCT
1022 void RegionNode::dump_spec(outputStream* st) const {
1023   Node::dump_spec(st);
1024   switch (loop_status()) {
1025   case RegionNode::LoopStatus::MaybeIrreducibleEntry:
1026     st->print("#irreducible ");
1027     break;
1028   case RegionNode::LoopStatus::Reducible:
1029     st->print("#reducible ");
1030     break;
1031   case RegionNode::LoopStatus::NeverIrreducibleEntry:
1032     break; // nothing
1033   }
1034 }
1035 #endif
1036 
1037 // Find the one non-null required input.  RegionNode only
1038 Node *Node::nonnull_req() const {
1039   assert( is_Region(), "" );
1040   for( uint i = 1; i < _cnt; i++ )
1041     if( in(i) )
1042       return in(i);
1043   ShouldNotReachHere();
1044   return nullptr;
1045 }
1046 
1047 
1048 //=============================================================================
1049 // note that these functions assume that the _adr_type field is flat
1050 uint PhiNode::hash() const {
1051   const Type* at = _adr_type;
1052   return TypeNode::hash() + (at ? at->hash() : 0);
1053 }
1054 bool PhiNode::cmp( const Node &n ) const {
1055   return TypeNode::cmp(n) && _adr_type == ((PhiNode&)n)._adr_type;
1056 }
1057 static inline
1058 const TypePtr* flatten_phi_adr_type(const TypePtr* at) {
1059   if (at == nullptr || at == TypePtr::BOTTOM)  return at;
1060   return Compile::current()->alias_type(at)->adr_type();
1061 }
1062 
1063 //----------------------------make---------------------------------------------
1064 // create a new phi with edges matching r and set (initially) to x
1065 PhiNode* PhiNode::make(Node* r, Node* x, const Type *t, const TypePtr* at) {
1066   uint preds = r->req();   // Number of predecessor paths
1067   assert(t != Type::MEMORY || at == flatten_phi_adr_type(at) || (flatten_phi_adr_type(at) == TypeAryPtr::INLINES && Compile::current()->flat_accesses_share_alias()), "flatten at");
1068   PhiNode* p = new PhiNode(r, t, at);
1069   for (uint j = 1; j < preds; j++) {
1070     // Fill in all inputs, except those which the region does not yet have
1071     if (r->in(j) != nullptr)
1072       p->init_req(j, x);
1073   }
1074   return p;
1075 }
1076 PhiNode* PhiNode::make(Node* r, Node* x) {
1077   const Type*    t  = x->bottom_type();
1078   const TypePtr* at = nullptr;
1079   if (t == Type::MEMORY)  at = flatten_phi_adr_type(x->adr_type());
1080   return make(r, x, t, at);
1081 }
1082 PhiNode* PhiNode::make_blank(Node* r, Node* x) {
1083   const Type*    t  = x->bottom_type();
1084   const TypePtr* at = nullptr;
1085   if (t == Type::MEMORY)  at = flatten_phi_adr_type(x->adr_type());
1086   return new PhiNode(r, t, at);
1087 }
1088 
1089 
1090 //------------------------slice_memory-----------------------------------------
1091 // create a new phi with narrowed memory type
1092 PhiNode* PhiNode::slice_memory(const TypePtr* adr_type) const {
1093   PhiNode* mem = (PhiNode*) clone();
1094   *(const TypePtr**)&mem->_adr_type = adr_type;
1095   // convert self-loops, or else we get a bad graph
1096   for (uint i = 1; i < req(); i++) {
1097     if ((const Node*)in(i) == this)  mem->set_req(i, mem);
1098   }
1099   mem->verify_adr_type();
1100   return mem;
1101 }
1102 
1103 //------------------------split_out_instance-----------------------------------
1104 // Split out an instance type from a bottom phi.
1105 PhiNode* PhiNode::split_out_instance(const TypePtr* at, PhaseIterGVN *igvn) const {
1106   const TypeOopPtr *t_oop = at->isa_oopptr();
1107   assert(t_oop != nullptr && t_oop->is_known_instance(), "expecting instance oopptr");
1108 
1109   // Check if an appropriate node already exists.
1110   Node *region = in(0);
1111   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
1112     Node* use = region->fast_out(k);
1113     if( use->is_Phi()) {
1114       PhiNode *phi2 = use->as_Phi();
1115       if (phi2->type() == Type::MEMORY && phi2->adr_type() == at) {
1116         return phi2;
1117       }
1118     }
1119   }
1120   Compile *C = igvn->C;
1121   Node_Array node_map;
1122   Node_Stack stack(C->live_nodes() >> 4);
1123   PhiNode *nphi = slice_memory(at);
1124   igvn->register_new_node_with_optimizer( nphi );
1125   node_map.map(_idx, nphi);
1126   stack.push((Node *)this, 1);
1127   while(!stack.is_empty()) {
1128     PhiNode *ophi = stack.node()->as_Phi();
1129     uint i = stack.index();
1130     assert(i >= 1, "not control edge");
1131     stack.pop();
1132     nphi = node_map[ophi->_idx]->as_Phi();
1133     for (; i < ophi->req(); i++) {
1134       Node *in = ophi->in(i);
1135       if (in == nullptr || igvn->type(in) == Type::TOP)
1136         continue;
1137       Node *opt = MemNode::optimize_simple_memory_chain(in, t_oop, nullptr, igvn);
1138       PhiNode *optphi = opt->is_Phi() ? opt->as_Phi() : nullptr;
1139       if (optphi != nullptr && optphi->adr_type() == TypePtr::BOTTOM) {
1140         opt = node_map[optphi->_idx];
1141         if (opt == nullptr) {
1142           stack.push(ophi, i);
1143           nphi = optphi->slice_memory(at);
1144           igvn->register_new_node_with_optimizer( nphi );
1145           node_map.map(optphi->_idx, nphi);
1146           ophi = optphi;
1147           i = 0; // will get incremented at top of loop
1148           continue;
1149         }
1150       }
1151       nphi->set_req(i, opt);
1152     }
1153   }
1154   return nphi;
1155 }
1156 
1157 //------------------------verify_adr_type--------------------------------------
1158 #ifdef ASSERT
1159 void PhiNode::verify_adr_type(VectorSet& visited, const TypePtr* at) const {
1160   if (visited.test_set(_idx))  return;  //already visited
1161 
1162   // recheck constructor invariants:
1163   verify_adr_type(false);
1164 
1165   // recheck local phi/phi consistency:
1166   assert(_adr_type == at || _adr_type == TypePtr::BOTTOM,
1167          "adr_type must be consistent across phi nest");
1168 
1169   // walk around
1170   for (uint i = 1; i < req(); i++) {
1171     Node* n = in(i);
1172     if (n == nullptr)  continue;
1173     const Node* np = in(i);
1174     if (np->is_Phi()) {
1175       np->as_Phi()->verify_adr_type(visited, at);
1176     } else if (n->bottom_type() == Type::TOP
1177                || (n->is_Mem() && n->in(MemNode::Address)->bottom_type() == Type::TOP)) {
1178       // ignore top inputs
1179     } else {
1180       const TypePtr* nat = flatten_phi_adr_type(n->adr_type());
1181       // recheck phi/non-phi consistency at leaves:
1182       assert((nat != nullptr) == (at != nullptr), "");
1183       assert(nat == at || nat == TypePtr::BOTTOM,
1184              "adr_type must be consistent at leaves of phi nest");
1185     }
1186   }
1187 }
1188 
1189 // Verify a whole nest of phis rooted at this one.
1190 void PhiNode::verify_adr_type(bool recursive) const {
1191   if (VMError::is_error_reported())  return;  // muzzle asserts when debugging an error
1192   if (Node::in_dump())               return;  // muzzle asserts when printing
1193 
1194   assert((_type == Type::MEMORY) == (_adr_type != nullptr), "adr_type for memory phis only");
1195   // Flat array element shouldn't get their own memory slice until flat_accesses_share_alias is cleared.
1196   // It could be the graph has no loads/stores and flat_accesses_share_alias is never cleared. EA could still
1197   // creates per element Phis but that wouldn't be a problem as there are no memory accesses for that array.
1198   assert(_adr_type == nullptr || _adr_type->isa_aryptr() == nullptr ||
1199          _adr_type->is_aryptr()->is_known_instance() ||
1200          !_adr_type->is_aryptr()->is_flat() ||
1201          !Compile::current()->flat_accesses_share_alias() ||
1202          _adr_type == TypeAryPtr::INLINES, "flat array element shouldn't get its own slice yet");
1203 
1204   if (!VerifyAliases)       return;  // verify thoroughly only if requested
1205 
1206   assert(_adr_type == flatten_phi_adr_type(_adr_type),
1207          "Phi::adr_type must be pre-normalized");
1208 
1209   if (recursive) {
1210     VectorSet visited;
1211     verify_adr_type(visited, _adr_type);
1212   }
1213 }
1214 #endif
1215 
1216 
1217 //------------------------------Value------------------------------------------
1218 // Compute the type of the PhiNode
1219 const Type* PhiNode::Value(PhaseGVN* phase) const {
1220   Node *r = in(0);              // RegionNode
1221   if( !r )                      // Copy or dead
1222     return in(1) ? phase->type(in(1)) : Type::TOP;
1223 
1224   // Note: During parsing, phis are often transformed before their regions.
1225   // This means we have to use type_or_null to defend against untyped regions.
1226   if( phase->type_or_null(r) == Type::TOP )  // Dead code?
1227     return Type::TOP;
1228 
1229   // Check for trip-counted loop.  If so, be smarter.
1230   BaseCountedLoopNode* l = r->is_BaseCountedLoop() ? r->as_BaseCountedLoop() : nullptr;
1231   if (l && ((const Node*)l->phi() == this)) { // Trip counted loop!
1232     // protect against init_trip() or limit() returning null
1233     if (l->can_be_counted_loop(phase)) {
1234       const Node* init = l->init_trip();
1235       const Node* limit = l->limit();
1236       const Node* stride = l->stride();
1237       if (init != nullptr && limit != nullptr && stride != nullptr) {
1238         const TypeInteger* lo = phase->type(init)->isa_integer(l->bt());
1239         const TypeInteger* hi = phase->type(limit)->isa_integer(l->bt());
1240         const TypeInteger* stride_t = phase->type(stride)->isa_integer(l->bt());
1241         if (lo != nullptr && hi != nullptr && stride_t != nullptr) { // Dying loops might have TOP here
1242           assert(stride_t->is_con(), "bad stride type");
1243           BoolTest::mask bt = l->loopexit()->test_trip();
1244           // If the loop exit condition is "not equal", the condition
1245           // would not trigger if init > limit (if stride > 0) or if
1246           // init < limit if (stride > 0) so we can't deduce bounds
1247           // for the iv from the exit condition.
1248           if (bt != BoolTest::ne) {
1249             jlong stride_con = stride_t->get_con_as_long(l->bt());
1250             if (stride_con < 0) {          // Down-counter loop
1251               swap(lo, hi);
1252               jlong iv_range_lower_limit = lo->lo_as_long();
1253               // Prevent overflow when adding one below
1254               if (iv_range_lower_limit < max_signed_integer(l->bt())) {
1255                 // The loop exit condition is: iv + stride > limit (iv is this Phi). So the loop iterates until
1256                 // iv + stride <= limit
1257                 // We know that: limit >= lo->lo_as_long() and stride <= -1
1258                 // So when the loop exits, iv has to be at most lo->lo_as_long() + 1
1259                 iv_range_lower_limit += 1; // lo is after decrement
1260                 // Exact bounds for the phi can be computed when ABS(stride) greater than 1 if bounds are constant.
1261                 if (lo->is_con() && hi->is_con() && hi->lo_as_long() > lo->hi_as_long() && stride_con != -1) {
1262                   julong uhi = static_cast<julong>(hi->lo_as_long());
1263                   julong ulo = static_cast<julong>(lo->hi_as_long());
1264                   julong diff = ((uhi - ulo - 1) / (-stride_con)) * (-stride_con);
1265                   julong ufirst = hi->lo_as_long() - diff;
1266                   iv_range_lower_limit = reinterpret_cast<jlong &>(ufirst);
1267                   assert(iv_range_lower_limit >= lo->lo_as_long() + 1, "should end up with narrower range");
1268                 }
1269               }
1270               return TypeInteger::make(MIN2(iv_range_lower_limit, hi->lo_as_long()), hi->hi_as_long(), 3, l->bt())->filter_speculative(_type);
1271             } else if (stride_con >= 0) {
1272               jlong iv_range_upper_limit = hi->hi_as_long();
1273               // Prevent overflow when subtracting one below
1274               if (iv_range_upper_limit > min_signed_integer(l->bt())) {
1275                 // The loop exit condition is: iv + stride < limit (iv is this Phi). So the loop iterates until
1276                 // iv + stride >= limit
1277                 // We know that: limit <= hi->hi_as_long() and stride >= 1
1278                 // So when the loop exits, iv has to be at most hi->hi_as_long() - 1
1279                 iv_range_upper_limit -= 1;
1280                 // Exact bounds for the phi can be computed when ABS(stride) greater than 1 if bounds are constant.
1281                 if (lo->is_con() && hi->is_con() && hi->lo_as_long() > lo->hi_as_long() && stride_con != 1) {
1282                   julong uhi = static_cast<julong>(hi->lo_as_long());
1283                   julong ulo = static_cast<julong>(lo->hi_as_long());
1284                   julong diff = ((uhi - ulo - 1) / stride_con) * stride_con;
1285                   julong ulast = lo->hi_as_long() + diff;
1286                   iv_range_upper_limit = reinterpret_cast<jlong &>(ulast);
1287                   assert(iv_range_upper_limit <= hi->hi_as_long() - 1, "should end up with narrower range");
1288                 }
1289               }
1290               return TypeInteger::make(lo->lo_as_long(), MAX2(lo->hi_as_long(), iv_range_upper_limit), 3, l->bt())->filter_speculative(_type);
1291             }
1292           }
1293         }
1294       }
1295     } else if (l->in(LoopNode::LoopBackControl) != nullptr &&
1296                in(LoopNode::EntryControl) != nullptr &&
1297                phase->type(l->in(LoopNode::LoopBackControl)) == Type::TOP) {
1298       // During CCP, if we saturate the type of a counted loop's Phi
1299       // before the special code for counted loop above has a chance
1300       // to run (that is as long as the type of the backedge's control
1301       // is top), we might end up with non monotonic types
1302       return phase->type(in(LoopNode::EntryControl))->filter_speculative(_type);
1303     }
1304   }
1305 
1306   // Default case: merge all inputs
1307   const Type *t = Type::TOP;        // Merged type starting value
1308   for (uint i = 1; i < req(); ++i) {// For all paths in
1309     // Reachable control path?
1310     if (r->in(i) && phase->type(r->in(i)) == Type::CONTROL) {
1311       const Type* ti = phase->type(in(i));
1312       t = t->meet_speculative(ti);
1313     }
1314   }
1315 
1316   // The worst-case type (from ciTypeFlow) should be consistent with "t".
1317   // That is, we expect that "t->higher_equal(_type)" holds true.
1318   // There are various exceptions:
1319   // - Inputs which are phis might in fact be widened unnecessarily.
1320   //   For example, an input might be a widened int while the phi is a short.
1321   // - Inputs might be BotPtrs but this phi is dependent on a null check,
1322   //   and postCCP has removed the cast which encodes the result of the check.
1323   // - The type of this phi is an interface, and the inputs are classes.
1324   // - Value calls on inputs might produce fuzzy results.
1325   //   (Occurrences of this case suggest improvements to Value methods.)
1326   //
1327   // It is not possible to see Type::BOTTOM values as phi inputs,
1328   // because the ciTypeFlow pre-pass produces verifier-quality types.
1329   const Type* ft = t->filter_speculative(_type);  // Worst case type
1330 
1331 #ifdef ASSERT
1332   // The following logic has been moved into TypeOopPtr::filter.
1333   const Type* jt = t->join_speculative(_type);
1334   if (jt->empty()) {           // Emptied out???
1335     // Otherwise it's something stupid like non-overlapping int ranges
1336     // found on dying counted loops.
1337     assert(ft == Type::TOP, ""); // Canonical empty value
1338   }
1339 
1340   else {
1341 
1342     if (jt != ft && jt->base() == ft->base()) {
1343       if (jt->isa_int() &&
1344           jt->is_int()->_lo == ft->is_int()->_lo &&
1345           jt->is_int()->_hi == ft->is_int()->_hi)
1346         jt = ft;
1347       if (jt->isa_long() &&
1348           jt->is_long()->_lo == ft->is_long()->_lo &&
1349           jt->is_long()->_hi == ft->is_long()->_hi)
1350         jt = ft;
1351     }
1352     if (jt != ft) {
1353       tty->print("merge type:  "); t->dump(); tty->cr();
1354       tty->print("kill type:   "); _type->dump(); tty->cr();
1355       tty->print("join type:   "); jt->dump(); tty->cr();
1356       tty->print("filter type: "); ft->dump(); tty->cr();
1357     }
1358     assert(jt == ft, "");
1359   }
1360 #endif //ASSERT
1361 
1362   // Deal with conversion problems found in data loops.
1363   ft = phase->saturate_and_maybe_push_to_igvn_worklist(this, ft);
1364   return ft;
1365 }
1366 
1367 // Does this Phi represent a simple well-shaped diamond merge?  Return the
1368 // index of the true path or 0 otherwise.
1369 int PhiNode::is_diamond_phi() const {
1370   Node* region = in(0);
1371   assert(region != nullptr && region->is_Region(), "phi must have region");
1372   if (!region->as_Region()->is_diamond()) {
1373     return 0;
1374   }
1375 
1376   if (region->in(1)->is_IfTrue()) {
1377     assert(region->in(2)->is_IfFalse(), "bad If");
1378     return 1;
1379   } else {
1380     // Flipped projections.
1381     assert(region->in(2)->is_IfTrue(), "bad If");
1382     return 2;
1383   }
1384 }
1385 
1386 // Do the following transformation if we find the corresponding graph shape, remove the involved memory phi and return
1387 // true. Otherwise, return false if the transformation cannot be applied.
1388 //
1389 //           If                                     If
1390 //          /  \                                   /  \
1391 //    IfFalse  IfTrue  /- Some Node          IfFalse  IfTrue
1392 //          \  /      /    /                       \  /        Some Node
1393 //         Region    / /-MergeMem     ===>        Region          |
1394 //          /   \---Phi                             |          MergeMem
1395 // [other phis]      \                        [other phis]        |
1396 //                   use                                         use
1397 bool PhiNode::try_clean_memory_phi(PhaseIterGVN* igvn) {
1398   if (_type != Type::MEMORY) {
1399     return false;
1400   }
1401   assert(is_diamond_phi() > 0, "sanity");
1402   assert(req() == 3, "same as region");
1403   const Node* region = in(0);
1404   for (uint i = 1; i < 3; i++) {
1405     Node* phi_input = in(i);
1406     if (phi_input != nullptr && phi_input->is_MergeMem() && region->in(i)->outcnt() == 1) {
1407       // Nothing is control-dependent on path #i except the region itself.
1408       MergeMemNode* merge_mem = phi_input->as_MergeMem();
1409       uint j = 3 - i;
1410       Node* other_phi_input = in(j);
1411       if (other_phi_input != nullptr && other_phi_input == merge_mem->base_memory()) {
1412         // merge_mem is a successor memory to other_phi_input, and is not pinned inside the diamond, so push it out.
1413         // This will allow the diamond to collapse completely if there are no other phis left.
1414         igvn->replace_node(this, merge_mem);
1415         return true;
1416       }
1417     }
1418   }
1419   return false;
1420 }
1421 
1422 //----------------------------check_cmove_id-----------------------------------
1423 // Check for CMove'ing a constant after comparing against the constant.
1424 // Happens all the time now, since if we compare equality vs a constant in
1425 // the parser, we "know" the variable is constant on one path and we force
1426 // it.  Thus code like "if( x==0 ) {/*EMPTY*/}" ends up inserting a
1427 // conditional move: "x = (x==0)?0:x;".  Yucko.  This fix is slightly more
1428 // general in that we don't need constants.  Since CMove's are only inserted
1429 // in very special circumstances, we do it here on generic Phi's.
1430 Node* PhiNode::is_cmove_id(PhaseTransform* phase, int true_path) {
1431   assert(true_path !=0, "only diamond shape graph expected");
1432 
1433   // is_diamond_phi() has guaranteed the correctness of the nodes sequence:
1434   // phi->region->if_proj->ifnode->bool->cmp
1435   Node*     region = in(0);
1436   Node*     iff    = region->in(1)->in(0);
1437   BoolNode* b      = iff->in(1)->as_Bool();
1438   Node*     cmp    = b->in(1);
1439   Node*     tval   = in(true_path);
1440   Node*     fval   = in(3-true_path);
1441   Node*     id     = CMoveNode::is_cmove_id(phase, cmp, tval, fval, b);
1442   if (id == nullptr)
1443     return nullptr;
1444 
1445   // Either value might be a cast that depends on a branch of 'iff'.
1446   // Since the 'id' value will float free of the diamond, either
1447   // decast or return failure.
1448   Node* ctl = id->in(0);
1449   if (ctl != nullptr && ctl->in(0) == iff) {
1450     if (id->is_ConstraintCast()) {
1451       return id->in(1);
1452     } else {
1453       // Don't know how to disentangle this value.
1454       return nullptr;
1455     }
1456   }
1457 
1458   return id;
1459 }
1460 
1461 //------------------------------Identity---------------------------------------
1462 // Check for Region being Identity.
1463 Node* PhiNode::Identity(PhaseGVN* phase) {
1464   if (must_wait_for_region_in_irreducible_loop(phase)) {
1465     return this;
1466   }
1467   // Check for no merging going on
1468   // (There used to be special-case code here when this->region->is_Loop.
1469   // It would check for a tributary phi on the backedge that the main phi
1470   // trivially, perhaps with a single cast.  The unique_input method
1471   // does all this and more, by reducing such tributaries to 'this'.)
1472   Node* uin = unique_input(phase, false);
1473   if (uin != nullptr) {
1474     return uin;
1475   }
1476 
1477   int true_path = is_diamond_phi();
1478   // Delay CMove'ing identity if Ideal has not had the chance to handle unsafe cases, yet.
1479   if (true_path != 0 && !(phase->is_IterGVN() && wait_for_region_igvn(phase))) {
1480     Node* id = is_cmove_id(phase, true_path);
1481     if (id != nullptr) {
1482       return id;
1483     }
1484   }
1485 
1486   // Looking for phis with identical inputs.  If we find one that has
1487   // type TypePtr::BOTTOM, replace the current phi with the bottom phi.
1488   if (phase->is_IterGVN() && type() == Type::MEMORY && adr_type() !=
1489       TypePtr::BOTTOM && !adr_type()->is_known_instance()) {
1490     uint phi_len = req();
1491     Node* phi_reg = region();
1492     for (DUIterator_Fast imax, i = phi_reg->fast_outs(imax); i < imax; i++) {
1493       Node* u = phi_reg->fast_out(i);
1494       if (u->is_Phi() && u->as_Phi()->type() == Type::MEMORY &&
1495           u->adr_type() == TypePtr::BOTTOM && u->in(0) == phi_reg &&
1496           u->req() == phi_len) {
1497         for (uint j = 1; j < phi_len; j++) {
1498           if (in(j) != u->in(j)) {
1499             u = nullptr;
1500             break;
1501           }
1502         }
1503         if (u != nullptr) {
1504           return u;
1505         }
1506       }
1507     }
1508   }
1509 
1510   return this;                     // No identity
1511 }
1512 
1513 //-----------------------------unique_input------------------------------------
1514 // Find the unique value, discounting top, self-loops, and casts.
1515 // Return top if there are no inputs, and self if there are multiple.
1516 Node* PhiNode::unique_input(PhaseValues* phase, bool uncast) {
1517   //  1) One unique direct input,
1518   // or if uncast is true:
1519   //  2) some of the inputs have an intervening ConstraintCast
1520   //  3) an input is a self loop
1521   //
1522   //  1) input   or   2) input     or   3) input __
1523   //     /   \           /   \               \  /  \
1524   //     \   /          |    cast             phi  cast
1525   //      phi            \   /               /  \  /
1526   //                      phi               /    --
1527 
1528   Node* r = in(0);                      // RegionNode
1529   Node* input = nullptr; // The unique direct input (maybe uncasted = ConstraintCasts removed)
1530 
1531   for (uint i = 1, cnt = req(); i < cnt; ++i) {
1532     Node* rc = r->in(i);
1533     if (rc == nullptr || phase->type(rc) == Type::TOP)
1534       continue;                 // ignore unreachable control path
1535     Node* n = in(i);
1536     if (n == nullptr)
1537       continue;
1538     Node* un = n;
1539     if (uncast) {
1540 #ifdef ASSERT
1541       Node* m = un->uncast();
1542 #endif
1543       while (un != nullptr && un->req() == 2 && un->is_ConstraintCast()) {
1544         Node* next = un->in(1);
1545         if (phase->type(next)->isa_rawptr() && phase->type(un)->isa_oopptr()) {
1546           // risk exposing raw ptr at safepoint
1547           break;
1548         }
1549         un = next;
1550       }
1551       assert(m == un || un->in(1) == m, "Only expected at CheckCastPP from allocation");
1552     }
1553     if (un == nullptr || un == this || phase->type(un) == Type::TOP) {
1554       continue; // ignore if top, or in(i) and "this" are in a data cycle
1555     }
1556     // Check for a unique input (maybe uncasted)
1557     if (input == nullptr) {
1558       input = un;
1559     } else if (input != un) {
1560       input = NodeSentinel; // no unique input
1561     }
1562   }
1563   if (input == nullptr) {
1564     return phase->C->top();        // no inputs
1565   }
1566 
1567   if (input != NodeSentinel) {
1568     return input;           // one unique direct input
1569   }
1570 
1571   // Nothing.
1572   return nullptr;
1573 }
1574 
1575 //------------------------------is_x2logic-------------------------------------
1576 // Check for simple convert-to-boolean pattern
1577 // If:(C Bool) Region:(IfF IfT) Phi:(Region 0 1)
1578 // Convert Phi to an ConvIB.
1579 static Node *is_x2logic( PhaseGVN *phase, PhiNode *phi, int true_path ) {
1580   assert(true_path !=0, "only diamond shape graph expected");
1581 
1582   // If we're late in the optimization process, we may have already expanded Conv2B nodes
1583   if (phase->C->post_loop_opts_phase() && !Matcher::match_rule_supported(Op_Conv2B)) {
1584     return nullptr;
1585   }
1586 
1587   // Convert the true/false index into an expected 0/1 return.
1588   // Map 2->0 and 1->1.
1589   int flipped = 2-true_path;
1590 
1591   // is_diamond_phi() has guaranteed the correctness of the nodes sequence:
1592   // phi->region->if_proj->ifnode->bool->cmp
1593   Node *region = phi->in(0);
1594   Node *iff = region->in(1)->in(0);
1595   BoolNode *b = (BoolNode*)iff->in(1);
1596   const CmpNode *cmp = (CmpNode*)b->in(1);
1597 
1598   Node *zero = phi->in(1);
1599   Node *one  = phi->in(2);
1600   const Type *tzero = phase->type( zero );
1601   const Type *tone  = phase->type( one  );
1602 
1603   // Check for compare vs 0
1604   const Type *tcmp = phase->type(cmp->in(2));
1605   if( tcmp != TypeInt::ZERO && tcmp != TypePtr::NULL_PTR ) {
1606     // Allow cmp-vs-1 if the other input is bounded by 0-1
1607     if( !(tcmp == TypeInt::ONE && phase->type(cmp->in(1)) == TypeInt::BOOL) )
1608       return nullptr;
1609     flipped = 1-flipped;        // Test is vs 1 instead of 0!
1610   }
1611 
1612   // Check for setting zero/one opposite expected
1613   if( tzero == TypeInt::ZERO ) {
1614     if( tone == TypeInt::ONE ) {
1615     } else return nullptr;
1616   } else if( tzero == TypeInt::ONE ) {
1617     if( tone == TypeInt::ZERO ) {
1618       flipped = 1-flipped;
1619     } else return nullptr;
1620   } else return nullptr;
1621 
1622   // Check for boolean test backwards
1623   if( b->_test._test == BoolTest::ne ) {
1624   } else if( b->_test._test == BoolTest::eq ) {
1625     flipped = 1-flipped;
1626   } else return nullptr;
1627 
1628   // Build int->bool conversion
1629   Node* n = new Conv2BNode(cmp->in(1));
1630   if (flipped) {
1631     n = new XorINode(phase->transform(n), phase->intcon(1));
1632   }
1633 
1634   return n;
1635 }
1636 
1637 //------------------------------is_cond_add------------------------------------
1638 // Check for simple conditional add pattern:  "(P < Q) ? X+Y : X;"
1639 // To be profitable the control flow has to disappear; there can be no other
1640 // values merging here.  We replace the test-and-branch with:
1641 // "(sgn(P-Q))&Y) + X".  Basically, convert "(P < Q)" into 0 or -1 by
1642 // moving the carry bit from (P-Q) into a register with 'sbb EAX,EAX'.
1643 // Then convert Y to 0-or-Y and finally add.
1644 // This is a key transform for SpecJava _201_compress.
1645 static Node* is_cond_add(PhaseGVN *phase, PhiNode *phi, int true_path) {
1646   assert(true_path !=0, "only diamond shape graph expected");
1647 
1648   // is_diamond_phi() has guaranteed the correctness of the nodes sequence:
1649   // phi->region->if_proj->ifnode->bool->cmp
1650   RegionNode *region = (RegionNode*)phi->in(0);
1651   Node *iff = region->in(1)->in(0);
1652   BoolNode* b = iff->in(1)->as_Bool();
1653   const CmpNode *cmp = (CmpNode*)b->in(1);
1654 
1655   // Make sure only merging this one phi here
1656   if (region->has_unique_phi() != phi)  return nullptr;
1657 
1658   // Make sure each arm of the diamond has exactly one output, which we assume
1659   // is the region.  Otherwise, the control flow won't disappear.
1660   if (region->in(1)->outcnt() != 1) return nullptr;
1661   if (region->in(2)->outcnt() != 1) return nullptr;
1662 
1663   // Check for "(P < Q)" of type signed int
1664   if (b->_test._test != BoolTest::lt)  return nullptr;
1665   if (cmp->Opcode() != Op_CmpI)        return nullptr;
1666 
1667   Node *p = cmp->in(1);
1668   Node *q = cmp->in(2);
1669   Node *n1 = phi->in(  true_path);
1670   Node *n2 = phi->in(3-true_path);
1671 
1672   int op = n1->Opcode();
1673   if( op != Op_AddI           // Need zero as additive identity
1674       /*&&op != Op_SubI &&
1675       op != Op_AddP &&
1676       op != Op_XorI &&
1677       op != Op_OrI*/ )
1678     return nullptr;
1679 
1680   Node *x = n2;
1681   Node *y = nullptr;
1682   if( x == n1->in(1) ) {
1683     y = n1->in(2);
1684   } else if( x == n1->in(2) ) {
1685     y = n1->in(1);
1686   } else return nullptr;
1687 
1688   // Not so profitable if compare and add are constants
1689   if( q->is_Con() && phase->type(q) != TypeInt::ZERO && y->is_Con() )
1690     return nullptr;
1691 
1692   Node *cmplt = phase->transform( new CmpLTMaskNode(p,q) );
1693   Node *j_and   = phase->transform( new AndINode(cmplt,y) );
1694   return new AddINode(j_and,x);
1695 }
1696 
1697 //------------------------------is_absolute------------------------------------
1698 // Check for absolute value.
1699 static Node* is_absolute( PhaseGVN *phase, PhiNode *phi_root, int true_path) {
1700   assert(true_path !=0, "only diamond shape graph expected");
1701 
1702   int  cmp_zero_idx = 0;        // Index of compare input where to look for zero
1703   int  phi_x_idx = 0;           // Index of phi input where to find naked x
1704 
1705   // ABS ends with the merge of 2 control flow paths.
1706   // Find the false path from the true path. With only 2 inputs, 3 - x works nicely.
1707   int false_path = 3 - true_path;
1708 
1709   // is_diamond_phi() has guaranteed the correctness of the nodes sequence:
1710   // phi->region->if_proj->ifnode->bool->cmp
1711   BoolNode *bol = phi_root->in(0)->in(1)->in(0)->in(1)->as_Bool();
1712   Node *cmp = bol->in(1);
1713 
1714   // Check bool sense
1715   if (cmp->Opcode() == Op_CmpF || cmp->Opcode() == Op_CmpD) {
1716     switch (bol->_test._test) {
1717     case BoolTest::lt: cmp_zero_idx = 1; phi_x_idx = true_path;  break;
1718     case BoolTest::le: cmp_zero_idx = 2; phi_x_idx = false_path; break;
1719     case BoolTest::gt: cmp_zero_idx = 2; phi_x_idx = true_path;  break;
1720     case BoolTest::ge: cmp_zero_idx = 1; phi_x_idx = false_path; break;
1721     default:           return nullptr;                           break;
1722     }
1723   } else if (cmp->Opcode() == Op_CmpI || cmp->Opcode() == Op_CmpL) {
1724     switch (bol->_test._test) {
1725     case BoolTest::lt:
1726     case BoolTest::le: cmp_zero_idx = 2; phi_x_idx = false_path; break;
1727     case BoolTest::gt:
1728     case BoolTest::ge: cmp_zero_idx = 2; phi_x_idx = true_path;  break;
1729     default:           return nullptr;                           break;
1730     }
1731   }
1732 
1733   // Test is next
1734   const Type *tzero = nullptr;
1735   switch (cmp->Opcode()) {
1736   case Op_CmpI:    tzero = TypeInt::ZERO; break;  // Integer ABS
1737   case Op_CmpL:    tzero = TypeLong::ZERO; break; // Long ABS
1738   case Op_CmpF:    tzero = TypeF::ZERO; break; // Float ABS
1739   case Op_CmpD:    tzero = TypeD::ZERO; break; // Double ABS
1740   default: return nullptr;
1741   }
1742 
1743   // Find zero input of compare; the other input is being abs'd
1744   Node *x = nullptr;
1745   bool flip = false;
1746   if( phase->type(cmp->in(cmp_zero_idx)) == tzero ) {
1747     x = cmp->in(3 - cmp_zero_idx);
1748   } else if( phase->type(cmp->in(3 - cmp_zero_idx)) == tzero ) {
1749     // The test is inverted, we should invert the result...
1750     x = cmp->in(cmp_zero_idx);
1751     flip = true;
1752   } else {
1753     return nullptr;
1754   }
1755 
1756   // Next get the 2 pieces being selected, one is the original value
1757   // and the other is the negated value.
1758   if( phi_root->in(phi_x_idx) != x ) return nullptr;
1759 
1760   // Check other phi input for subtract node
1761   Node *sub = phi_root->in(3 - phi_x_idx);
1762 
1763   bool is_sub = sub->Opcode() == Op_SubF || sub->Opcode() == Op_SubD ||
1764                 sub->Opcode() == Op_SubI || sub->Opcode() == Op_SubL;
1765 
1766   // Allow only Sub(0,X) and fail out for all others; Neg is not OK
1767   if (!is_sub || phase->type(sub->in(1)) != tzero || sub->in(2) != x) return nullptr;
1768 
1769   if (tzero == TypeF::ZERO) {
1770     x = new AbsFNode(x);
1771     if (flip) {
1772       x = new SubFNode(sub->in(1), phase->transform(x));
1773     }
1774   } else if (tzero == TypeD::ZERO) {
1775     x = new AbsDNode(x);
1776     if (flip) {
1777       x = new SubDNode(sub->in(1), phase->transform(x));
1778     }
1779   } else if (tzero == TypeInt::ZERO && Matcher::match_rule_supported(Op_AbsI)) {
1780     x = new AbsINode(x);
1781     if (flip) {
1782       x = new SubINode(sub->in(1), phase->transform(x));
1783     }
1784   } else if (tzero == TypeLong::ZERO && Matcher::match_rule_supported(Op_AbsL)) {
1785     x = new AbsLNode(x);
1786     if (flip) {
1787       x = new SubLNode(sub->in(1), phase->transform(x));
1788     }
1789   } else return nullptr;
1790 
1791   return x;
1792 }
1793 
1794 //------------------------------split_once-------------------------------------
1795 // Helper for split_flow_path
1796 static void split_once(PhaseIterGVN *igvn, Node *phi, Node *val, Node *n, Node *newn) {
1797   igvn->hash_delete(n);         // Remove from hash before hacking edges
1798 
1799   uint j = 1;
1800   for (uint i = phi->req()-1; i > 0; i--) {
1801     if (phi->in(i) == val) {   // Found a path with val?
1802       // Add to NEW Region/Phi, no DU info
1803       newn->set_req( j++, n->in(i) );
1804       // Remove from OLD Region/Phi
1805       n->del_req(i);
1806     }
1807   }
1808 
1809   // Register the new node but do not transform it.  Cannot transform until the
1810   // entire Region/Phi conglomerate has been hacked as a single huge transform.
1811   igvn->register_new_node_with_optimizer( newn );
1812 
1813   // Now I can point to the new node.
1814   n->add_req(newn);
1815   igvn->_worklist.push(n);
1816 }
1817 
1818 //------------------------------split_flow_path--------------------------------
1819 // Check for merging identical values and split flow paths
1820 static Node* split_flow_path(PhaseGVN *phase, PhiNode *phi) {
1821   // This optimization tries to find two or more inputs of phi with the same constant value
1822   // It then splits them into a separate Phi, and according Region. If this is a loop-entry,
1823   // and the loop entry has multiple fall-in edges, and some of those fall-in edges have that
1824   // constant, and others not, we may split the fall-in edges into separate Phi's, and create
1825   // an irreducible loop. For reducible loops, this never seems to happen, as the multiple
1826   // fall-in edges are already merged before the loop head during parsing. But with irreducible
1827   // loops present the order or merging during parsing can sometimes prevent this.
1828   if (phase->C->has_irreducible_loop()) {
1829     // Avoid this optimization if any irreducible loops are present. Else we may create
1830     // an irreducible loop that we do not detect.
1831     return nullptr;
1832   }
1833   BasicType bt = phi->type()->basic_type();
1834   if( bt == T_ILLEGAL || type2size[bt] <= 0 )
1835     return nullptr;             // Bail out on funny non-value stuff
1836   if( phi->req() <= 3 )         // Need at least 2 matched inputs and a
1837     return nullptr;             // third unequal input to be worth doing
1838 
1839   // Scan for a constant
1840   uint i;
1841   for( i = 1; i < phi->req()-1; i++ ) {
1842     Node *n = phi->in(i);
1843     if( !n ) return nullptr;
1844     if( phase->type(n) == Type::TOP ) return nullptr;
1845     if( n->Opcode() == Op_ConP || n->Opcode() == Op_ConN || n->Opcode() == Op_ConNKlass )
1846       break;
1847   }
1848   if( i >= phi->req() )         // Only split for constants
1849     return nullptr;
1850 
1851   Node *val = phi->in(i);       // Constant to split for
1852   uint hit = 0;                 // Number of times it occurs
1853   Node *r = phi->region();
1854 
1855   for( ; i < phi->req(); i++ ){ // Count occurrences of constant
1856     Node *n = phi->in(i);
1857     if( !n ) return nullptr;
1858     if( phase->type(n) == Type::TOP ) return nullptr;
1859     if( phi->in(i) == val ) {
1860       hit++;
1861       if (Node::may_be_loop_entry(r->in(i))) {
1862         return nullptr; // don't split loop entry path
1863       }
1864     }
1865   }
1866 
1867   if( hit <= 1 ||               // Make sure we find 2 or more
1868       hit == phi->req()-1 )     // and not ALL the same value
1869     return nullptr;
1870 
1871   // Now start splitting out the flow paths that merge the same value.
1872   // Split first the RegionNode.
1873   PhaseIterGVN *igvn = phase->is_IterGVN();
1874   RegionNode *newr = new RegionNode(hit+1);
1875   split_once(igvn, phi, val, r, newr);
1876 
1877   // Now split all other Phis than this one
1878   for (DUIterator_Fast kmax, k = r->fast_outs(kmax); k < kmax; k++) {
1879     Node* phi2 = r->fast_out(k);
1880     if( phi2->is_Phi() && phi2->as_Phi() != phi ) {
1881       PhiNode *newphi = PhiNode::make_blank(newr, phi2);
1882       split_once(igvn, phi, val, phi2, newphi);
1883     }
1884   }
1885 
1886   // Clean up this guy
1887   igvn->hash_delete(phi);
1888   for( i = phi->req()-1; i > 0; i-- ) {
1889     if( phi->in(i) == val ) {
1890       phi->del_req(i);
1891     }
1892   }
1893   phi->add_req(val);
1894 
1895   return phi;
1896 }
1897 
1898 //=============================================================================
1899 //------------------------------simple_data_loop_check-------------------------
1900 //  Try to determining if the phi node in a simple safe/unsafe data loop.
1901 //  Returns:
1902 // enum LoopSafety { Safe = 0, Unsafe, UnsafeLoop };
1903 // Safe       - safe case when the phi and it's inputs reference only safe data
1904 //              nodes;
1905 // Unsafe     - the phi and it's inputs reference unsafe data nodes but there
1906 //              is no reference back to the phi - need a graph walk
1907 //              to determine if it is in a loop;
1908 // UnsafeLoop - unsafe case when the phi references itself directly or through
1909 //              unsafe data node.
1910 //  Note: a safe data node is a node which could/never reference itself during
1911 //  GVN transformations. For now it is Con, Proj, Phi, CastPP, CheckCastPP.
1912 //  I mark Phi nodes as safe node not only because they can reference itself
1913 //  but also to prevent mistaking the fallthrough case inside an outer loop
1914 //  as dead loop when the phi references itself through an other phi.
1915 PhiNode::LoopSafety PhiNode::simple_data_loop_check(Node *in) const {
1916   // It is unsafe loop if the phi node references itself directly.
1917   if (in == (Node*)this)
1918     return UnsafeLoop; // Unsafe loop
1919   // Unsafe loop if the phi node references itself through an unsafe data node.
1920   // Exclude cases with null inputs or data nodes which could reference
1921   // itself (safe for dead loops).
1922   if (in != nullptr && !in->is_dead_loop_safe()) {
1923     // Check inputs of phi's inputs also.
1924     // It is much less expensive then full graph walk.
1925     uint cnt = in->req();
1926     uint i = (in->is_Proj() && !in->is_CFG())  ? 0 : 1;
1927     for (; i < cnt; ++i) {
1928       Node* m = in->in(i);
1929       if (m == (Node*)this)
1930         return UnsafeLoop; // Unsafe loop
1931       if (m != nullptr && !m->is_dead_loop_safe()) {
1932         // Check the most common case (about 30% of all cases):
1933         // phi->Load/Store->AddP->(ConP ConP Con)/(Parm Parm Con).
1934         Node *m1 = (m->is_AddP() && m->req() > 3) ? m->in(1) : nullptr;
1935         if (m1 == (Node*)this)
1936           return UnsafeLoop; // Unsafe loop
1937         if (m1 != nullptr && m1 == m->in(2) &&
1938             m1->is_dead_loop_safe() && m->in(3)->is_Con()) {
1939           continue; // Safe case
1940         }
1941         // The phi references an unsafe node - need full analysis.
1942         return Unsafe;
1943       }
1944     }
1945   }
1946   return Safe; // Safe case - we can optimize the phi node.
1947 }
1948 
1949 //------------------------------is_unsafe_data_reference-----------------------
1950 // If phi can be reached through the data input - it is data loop.
1951 bool PhiNode::is_unsafe_data_reference(Node *in) const {
1952   assert(req() > 1, "");
1953   // First, check simple cases when phi references itself directly or
1954   // through an other node.
1955   LoopSafety safety = simple_data_loop_check(in);
1956   if (safety == UnsafeLoop)
1957     return true;  // phi references itself - unsafe loop
1958   else if (safety == Safe)
1959     return false; // Safe case - phi could be replaced with the unique input.
1960 
1961   // Unsafe case when we should go through data graph to determine
1962   // if the phi references itself.
1963 
1964   ResourceMark rm;
1965 
1966   Node_List nstack;
1967   VectorSet visited;
1968 
1969   nstack.push(in); // Start with unique input.
1970   visited.set(in->_idx);
1971   while (nstack.size() != 0) {
1972     Node* n = nstack.pop();
1973     uint cnt = n->req();
1974     uint i = (n->is_Proj() && !n->is_CFG()) ? 0 : 1;
1975     for (; i < cnt; i++) {
1976       Node* m = n->in(i);
1977       if (m == (Node*)this) {
1978         return true;    // Data loop
1979       }
1980       if (m != nullptr && !m->is_dead_loop_safe()) { // Only look for unsafe cases.
1981         if (!visited.test_set(m->_idx))
1982           nstack.push(m);
1983       }
1984     }
1985   }
1986   return false; // The phi is not reachable from its inputs
1987 }
1988 
1989 // Is this Phi's region or some inputs to the region enqueued for IGVN
1990 // and so could cause the region to be optimized out?
1991 bool PhiNode::wait_for_region_igvn(PhaseGVN* phase) {
1992   PhaseIterGVN* igvn = phase->is_IterGVN();
1993   Unique_Node_List& worklist = igvn->_worklist;
1994   bool delay = false;
1995   Node* r = in(0);
1996   for (uint j = 1; j < req(); j++) {
1997     Node* rc = r->in(j);
1998     Node* n = in(j);
1999 
2000     if (rc == nullptr || !rc->is_Proj()) { continue; }
2001     if (worklist.member(rc)) {
2002       delay = true;
2003       break;
2004     }
2005 
2006     if (rc->in(0) == nullptr || !rc->in(0)->is_If()) { continue; }
2007     if (worklist.member(rc->in(0))) {
2008       delay = true;
2009       break;
2010     }
2011 
2012     if (rc->in(0)->in(1) == nullptr || !rc->in(0)->in(1)->is_Bool()) { continue; }
2013     if (worklist.member(rc->in(0)->in(1))) {
2014       delay = true;
2015       break;
2016     }
2017 
2018     if (rc->in(0)->in(1)->in(1) == nullptr || !rc->in(0)->in(1)->in(1)->is_Cmp()) { continue; }
2019     if (worklist.member(rc->in(0)->in(1)->in(1))) {
2020       delay = true;
2021       break;
2022     }
2023   }
2024 
2025   if (delay) {
2026     worklist.push(this);
2027   }
2028   return delay;
2029 }
2030 
2031 // Push inline type input nodes (and null) down through the phi recursively (can handle data loops).
2032 InlineTypeNode* PhiNode::push_inline_types_through(PhaseGVN* phase, bool can_reshape, ciInlineKlass* vk) {
2033   InlineTypeNode* vt = InlineTypeNode::make_null(*phase, vk)->clone_with_phis(phase, in(0), !_type->maybe_null());
2034   if (can_reshape) {
2035     // Replace phi right away to be able to use the inline
2036     // type node when reaching the phi again through data loops.
2037     PhaseIterGVN* igvn = phase->is_IterGVN();
2038     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2039       Node* u = fast_out(i);
2040       igvn->rehash_node_delayed(u);
2041       imax -= u->replace_edge(this, vt);
2042       --i;
2043     }
2044     igvn->rehash_node_delayed(this);
2045     assert(outcnt() == 0, "should be dead now");
2046   }
2047   ResourceMark rm;
2048   Node_List casts;
2049   for (uint i = 1; i < req(); ++i) {
2050     Node* n = in(i);
2051     while (n->is_ConstraintCast()) {
2052       casts.push(n);
2053       n = n->in(1);
2054     }
2055     if (phase->type(n)->is_zero_type()) {
2056       n = InlineTypeNode::make_null(*phase, vk);
2057     } else if (n->is_Phi()) {
2058       assert(can_reshape, "can only handle phis during IGVN");
2059       n = phase->transform(n->as_Phi()->push_inline_types_through(phase, can_reshape, vk));
2060     }
2061     while (casts.size() != 0) {
2062       // Push the cast(s) through the InlineTypeNode
2063       Node* cast = casts.pop()->clone();
2064       cast->set_req_X(1, n->as_InlineType()->get_oop(), phase);
2065       n = n->clone();
2066       n->as_InlineType()->set_oop(phase->transform(cast));
2067       n = phase->transform(n);
2068     }
2069     bool transform = !can_reshape && (i == (req()-1)); // Transform phis on last merge
2070     vt->merge_with(phase, n->as_InlineType(), i, transform);
2071   }
2072   return vt;
2073 }
2074 
2075 // If the Phi's Region is in an irreducible loop, and the Region
2076 // has had an input removed, but not yet transformed, it could be
2077 // that the Region (and this Phi) are not reachable from Root.
2078 // If we allow the Phi to collapse before the Region, this may lead
2079 // to dead-loop data. Wait for the Region to check for reachability,
2080 // and potentially remove the dead code.
2081 bool PhiNode::must_wait_for_region_in_irreducible_loop(PhaseGVN* phase) const {
2082   RegionNode* region = in(0)->as_Region();
2083   if (region->loop_status() == RegionNode::LoopStatus::MaybeIrreducibleEntry) {
2084     Node* top = phase->C->top();
2085     for (uint j = 1; j < req(); j++) {
2086       Node* rc = region->in(j); // for each control input
2087       if (rc == nullptr || phase->type(rc) == Type::TOP) {
2088         // Region is missing a control input
2089         Node* n = in(j);
2090         if (n != nullptr && n != top) {
2091           // Phi still has its input, so region just lost its input
2092           return true;
2093         }
2094       }
2095     }
2096   }
2097   return false;
2098 }
2099 
2100 //------------------------------Ideal------------------------------------------
2101 // Return a node which is more "ideal" than the current node.  Must preserve
2102 // the CFG, but we can still strip out dead paths.
2103 Node *PhiNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2104   Node *r = in(0);              // RegionNode
2105   assert(r != nullptr && r->is_Region(), "this phi must have a region");
2106   assert(r->in(0) == nullptr || !r->in(0)->is_Root(), "not a specially hidden merge");
2107 
2108   // Note: During parsing, phis are often transformed before their regions.
2109   // This means we have to use type_or_null to defend against untyped regions.
2110   if( phase->type_or_null(r) == Type::TOP ) // Dead code?
2111     return nullptr;                // No change
2112 
2113   Node *top = phase->C->top();
2114   bool new_phi = (outcnt() == 0); // transforming new Phi
2115   // No change for igvn if new phi is not hooked
2116   if (new_phi && can_reshape)
2117     return nullptr;
2118 
2119   if (must_wait_for_region_in_irreducible_loop(phase)) {
2120     return nullptr;
2121   }
2122 
2123   // The are 2 situations when only one valid phi's input is left
2124   // (in addition to Region input).
2125   // One: region is not loop - replace phi with this input.
2126   // Two: region is loop - replace phi with top since this data path is dead
2127   //                       and we need to break the dead data loop.
2128   Node* progress = nullptr;        // Record if any progress made
2129   for( uint j = 1; j < req(); ++j ){ // For all paths in
2130     // Check unreachable control paths
2131     Node* rc = r->in(j);
2132     Node* n = in(j);            // Get the input
2133     if (rc == nullptr || phase->type(rc) == Type::TOP) {
2134       if (n != top) {           // Not already top?
2135         PhaseIterGVN *igvn = phase->is_IterGVN();
2136         if (can_reshape && igvn != nullptr) {
2137           igvn->_worklist.push(r);
2138         }
2139         // Nuke it down
2140         set_req_X(j, top, phase);
2141         progress = this;        // Record progress
2142       }
2143     }
2144   }
2145 
2146   if (can_reshape && outcnt() == 0) {
2147     // set_req() above may kill outputs if Phi is referenced
2148     // only by itself on the dead (top) control path.
2149     return top;
2150   }
2151 
2152   bool uncasted = false;
2153   Node* uin = unique_input(phase, false);
2154   if (uin == nullptr && can_reshape &&
2155       // If there is a chance that the region can be optimized out do
2156       // not add a cast node that we can't remove yet.
2157       !wait_for_region_igvn(phase)) {
2158     uncasted = true;
2159     uin = unique_input(phase, true);
2160   }
2161   if (uin == top) {             // Simplest case: no alive inputs.
2162     if (can_reshape)            // IGVN transformation
2163       return top;
2164     else
2165       return nullptr;              // Identity will return TOP
2166   } else if (uin != nullptr) {
2167     // Only one not-null unique input path is left.
2168     // Determine if this input is backedge of a loop.
2169     // (Skip new phis which have no uses and dead regions).
2170     if (outcnt() > 0 && r->in(0) != nullptr) {
2171       if (is_data_loop(r->as_Region(), uin, phase)) {
2172         // Break this data loop to avoid creation of a dead loop.
2173         if (can_reshape) {
2174           return top;
2175         } else {
2176           // We can't return top if we are in Parse phase - cut inputs only
2177           // let Identity to handle the case.
2178           replace_edge(uin, top, phase);
2179           return nullptr;
2180         }
2181       }
2182     }
2183 
2184     if (uncasted) {
2185       // Add cast nodes between the phi to be removed and its unique input.
2186       // Wait until after parsing for the type information to propagate from the casts.
2187       assert(can_reshape, "Invalid during parsing");
2188       const Type* phi_type = bottom_type();
2189       // Add casts to carry the control dependency of the Phi that is
2190       // going away
2191       Node* cast = nullptr;
2192       if (phi_type->isa_ptr()) {
2193         const Type* uin_type = phase->type(uin);
2194         if (!phi_type->isa_oopptr() && !uin_type->isa_oopptr()) {
2195           cast = ConstraintCastNode::make_cast(Op_CastPP, r, uin, phi_type, ConstraintCastNode::StrongDependency);
2196         } else {
2197           // Use a CastPP for a cast to not null and a CheckCastPP for
2198           // a cast to a new klass (and both if both null-ness and
2199           // klass change).
2200 
2201           // If the type of phi is not null but the type of uin may be
2202           // null, uin's type must be casted to not null
2203           if (phi_type->join(TypePtr::NOTNULL) == phi_type->remove_speculative() &&
2204               uin_type->join(TypePtr::NOTNULL) != uin_type->remove_speculative()) {
2205             cast = ConstraintCastNode::make_cast(Op_CastPP, r, uin, TypePtr::NOTNULL, ConstraintCastNode::StrongDependency);
2206           }
2207 
2208           // If the type of phi and uin, both casted to not null,
2209           // differ the klass of uin must be (check)cast'ed to match
2210           // that of phi
2211           if (phi_type->join_speculative(TypePtr::NOTNULL) != uin_type->join_speculative(TypePtr::NOTNULL)) {
2212             Node* n = uin;
2213             if (cast != nullptr) {
2214               cast = phase->transform(cast);
2215               n = cast;
2216             }
2217             cast = ConstraintCastNode::make_cast(Op_CheckCastPP, r, n, phi_type, ConstraintCastNode::StrongDependency);
2218           }
2219           if (cast == nullptr) {
2220             cast = ConstraintCastNode::make_cast(Op_CastPP, r, uin, phi_type, ConstraintCastNode::StrongDependency);
2221           }
2222         }
2223       } else {
2224         cast = ConstraintCastNode::make_cast_for_type(r, uin, phi_type, ConstraintCastNode::StrongDependency);
2225       }
2226       assert(cast != nullptr, "cast should be set");
2227       cast = phase->transform(cast);
2228       // set all inputs to the new cast(s) so the Phi is removed by Identity
2229       PhaseIterGVN* igvn = phase->is_IterGVN();
2230       for (uint i = 1; i < req(); i++) {
2231         set_req_X(i, cast, igvn);
2232       }
2233       uin = cast;
2234     }
2235 
2236     // One unique input.
2237     debug_only(Node* ident = Identity(phase));
2238     // The unique input must eventually be detected by the Identity call.
2239 #ifdef ASSERT
2240     if (ident != uin && !ident->is_top() && !must_wait_for_region_in_irreducible_loop(phase)) {
2241       // print this output before failing assert
2242       r->dump(3);
2243       this->dump(3);
2244       ident->dump();
2245       uin->dump();
2246     }
2247 #endif
2248     // Identity may not return the expected uin, if it has to wait for the region, in irreducible case
2249     assert(ident == uin || ident->is_top() || must_wait_for_region_in_irreducible_loop(phase), "Identity must clean this up");
2250     return nullptr;
2251   }
2252 
2253   Node* opt = nullptr;
2254   int true_path = is_diamond_phi();
2255   if (true_path != 0 &&
2256       // If one of the diamond's branch is in the process of dying then, the Phi's input for that branch might transform
2257       // to top. If that happens replacing the Phi with an operation that consumes the Phi's inputs will cause the Phi
2258       // to be replaced by top. To prevent that, delay the transformation until the branch has a chance to be removed.
2259       !(can_reshape && wait_for_region_igvn(phase))) {
2260     // Check for CMove'ing identity. If it would be unsafe,
2261     // handle it here. In the safe case, let Identity handle it.
2262     Node* unsafe_id = is_cmove_id(phase, true_path);
2263     if( unsafe_id != nullptr && is_unsafe_data_reference(unsafe_id) )
2264       opt = unsafe_id;
2265 
2266     // Check for simple convert-to-boolean pattern
2267     if( opt == nullptr )
2268       opt = is_x2logic(phase, this, true_path);
2269 
2270     // Check for absolute value
2271     if( opt == nullptr )
2272       opt = is_absolute(phase, this, true_path);
2273 
2274     // Check for conditional add
2275     if( opt == nullptr && can_reshape )
2276       opt = is_cond_add(phase, this, true_path);
2277 
2278     // These 4 optimizations could subsume the phi:
2279     // have to check for a dead data loop creation.
2280     if( opt != nullptr ) {
2281       if( opt == unsafe_id || is_unsafe_data_reference(opt) ) {
2282         // Found dead loop.
2283         if( can_reshape )
2284           return top;
2285         // We can't return top if we are in Parse phase - cut inputs only
2286         // to stop further optimizations for this phi. Identity will return TOP.
2287         assert(req() == 3, "only diamond merge phi here");
2288         set_req(1, top);
2289         set_req(2, top);
2290         return nullptr;
2291       } else {
2292         return opt;
2293       }
2294     }
2295   }
2296 
2297   // Check for merging identical values and split flow paths
2298   if (can_reshape) {
2299     opt = split_flow_path(phase, this);
2300     // This optimization only modifies phi - don't need to check for dead loop.
2301     assert(opt == nullptr || opt == this, "do not elide phi");
2302     if (opt != nullptr)  return opt;
2303   }
2304 
2305   if (in(1) != nullptr && in(1)->Opcode() == Op_AddP && can_reshape) {
2306     // Try to undo Phi of AddP:
2307     // (Phi (AddP base address offset) (AddP base2 address2 offset2))
2308     // becomes:
2309     // newbase := (Phi base base2)
2310     // newaddress := (Phi address address2)
2311     // newoffset := (Phi offset offset2)
2312     // (AddP newbase newaddress newoffset)
2313     //
2314     // This occurs as a result of unsuccessful split_thru_phi and
2315     // interferes with taking advantage of addressing modes. See the
2316     // clone_shift_expressions code in matcher.cpp
2317     Node* addp = in(1);
2318     Node* base = addp->in(AddPNode::Base);
2319     Node* address = addp->in(AddPNode::Address);
2320     Node* offset = addp->in(AddPNode::Offset);
2321     if (base != nullptr && address != nullptr && offset != nullptr &&
2322         !base->is_top() && !address->is_top() && !offset->is_top()) {
2323       const Type* base_type = base->bottom_type();
2324       const Type* address_type = address->bottom_type();
2325       // make sure that all the inputs are similar to the first one,
2326       // i.e. AddP with base == address and same offset as first AddP
2327       bool doit = true;
2328       for (uint i = 2; i < req(); i++) {
2329         if (in(i) == nullptr ||
2330             in(i)->Opcode() != Op_AddP ||
2331             in(i)->in(AddPNode::Base) == nullptr ||
2332             in(i)->in(AddPNode::Address) == nullptr ||
2333             in(i)->in(AddPNode::Offset) == nullptr ||
2334             in(i)->in(AddPNode::Base)->is_top() ||
2335             in(i)->in(AddPNode::Address)->is_top() ||
2336             in(i)->in(AddPNode::Offset)->is_top()) {
2337           doit = false;
2338           break;
2339         }
2340         if (in(i)->in(AddPNode::Base) != base) {
2341           base = nullptr;
2342         }
2343         if (in(i)->in(AddPNode::Offset) != offset) {
2344           offset = nullptr;
2345         }
2346         if (in(i)->in(AddPNode::Address) != address) {
2347           address = nullptr;
2348         }
2349         // Accumulate type for resulting Phi
2350         base_type = base_type->meet_speculative(in(i)->in(AddPNode::Base)->bottom_type());
2351         address_type = address_type->meet_speculative(in(i)->in(AddPNode::Address)->bottom_type());
2352       }
2353       if (doit && base == nullptr) {
2354         // Check for neighboring AddP nodes in a tree.
2355         // If they have a base, use that it.
2356         for (DUIterator_Fast kmax, k = this->fast_outs(kmax); k < kmax; k++) {
2357           Node* u = this->fast_out(k);
2358           if (u->is_AddP()) {
2359             Node* base2 = u->in(AddPNode::Base);
2360             if (base2 != nullptr && !base2->is_top()) {
2361               if (base == nullptr)
2362                 base = base2;
2363               else if (base != base2)
2364                 { doit = false; break; }
2365             }
2366           }
2367         }
2368       }
2369       if (doit) {
2370         if (base == nullptr) {
2371           base = new PhiNode(in(0), base_type, nullptr);
2372           for (uint i = 1; i < req(); i++) {
2373             base->init_req(i, in(i)->in(AddPNode::Base));
2374           }
2375           phase->is_IterGVN()->register_new_node_with_optimizer(base);
2376         }
2377         if (address == nullptr) {
2378           address = new PhiNode(in(0), address_type, nullptr);
2379           for (uint i = 1; i < req(); i++) {
2380             address->init_req(i, in(i)->in(AddPNode::Address));
2381           }
2382           phase->is_IterGVN()->register_new_node_with_optimizer(address);
2383         }
2384         if (offset == nullptr) {
2385           offset = new PhiNode(in(0), TypeX_X, nullptr);
2386           for (uint i = 1; i < req(); i++) {
2387             offset->init_req(i, in(i)->in(AddPNode::Offset));
2388           }
2389           phase->is_IterGVN()->register_new_node_with_optimizer(offset);
2390         }
2391         return new AddPNode(base, address, offset);
2392       }
2393     }
2394   }
2395 
2396   // Split phis through memory merges, so that the memory merges will go away.
2397   // Piggy-back this transformation on the search for a unique input....
2398   // It will be as if the merged memory is the unique value of the phi.
2399   // (Do not attempt this optimization unless parsing is complete.
2400   // It would make the parser's memory-merge logic sick.)
2401   // (MergeMemNode is not dead_loop_safe - need to check for dead loop.)
2402   if (progress == nullptr && can_reshape && type() == Type::MEMORY) {
2403     // see if this phi should be sliced
2404     uint merge_width = 0;
2405     bool saw_self = false;
2406     // TODO revisit this with JDK-8247216
2407     bool mergemem_only = true;
2408     for( uint i=1; i<req(); ++i ) {// For all paths in
2409       Node *ii = in(i);
2410       // TOP inputs should not be counted as safe inputs because if the
2411       // Phi references itself through all other inputs then splitting the
2412       // Phi through memory merges would create dead loop at later stage.
2413       if (ii == top) {
2414         return nullptr; // Delay optimization until graph is cleaned.
2415       }
2416       if (ii->is_MergeMem()) {
2417         MergeMemNode* n = ii->as_MergeMem();
2418         merge_width = MAX2(merge_width, n->req());
2419         saw_self = saw_self || (n->base_memory() == this);
2420       } else {
2421         mergemem_only = false;
2422       }
2423     }
2424 
2425     // This restriction is temporarily necessary to ensure termination:
2426     if (!mergemem_only && !saw_self && adr_type() == TypePtr::BOTTOM)  merge_width = 0;
2427 
2428     if (merge_width > Compile::AliasIdxRaw) {
2429       // found at least one non-empty MergeMem
2430       const TypePtr* at = adr_type();
2431       if (at != TypePtr::BOTTOM) {
2432         // Patch the existing phi to select an input from the merge:
2433         // Phi:AT1(...MergeMem(m0, m1, m2)...) into
2434         //     Phi:AT1(...m1...)
2435         int alias_idx = phase->C->get_alias_index(at);
2436         for (uint i=1; i<req(); ++i) {
2437           Node *ii = in(i);
2438           if (ii->is_MergeMem()) {
2439             MergeMemNode* n = ii->as_MergeMem();
2440             // compress paths and change unreachable cycles to TOP
2441             // If not, we can update the input infinitely along a MergeMem cycle
2442             // Equivalent code is in MemNode::Ideal_common
2443             Node *m  = phase->transform(n);
2444             if (outcnt() == 0) {  // Above transform() may kill us!
2445               return top;
2446             }
2447             // If transformed to a MergeMem, get the desired slice
2448             // Otherwise the returned node represents memory for every slice
2449             Node *new_mem = (m->is_MergeMem()) ?
2450                              m->as_MergeMem()->memory_at(alias_idx) : m;
2451             // Update input if it is progress over what we have now
2452             if (new_mem != ii) {
2453               set_req_X(i, new_mem, phase->is_IterGVN());
2454               progress = this;
2455             }
2456           }
2457         }
2458       } else {
2459         // We know that at least one MergeMem->base_memory() == this
2460         // (saw_self == true). If all other inputs also references this phi
2461         // (directly or through data nodes) - it is a dead loop.
2462         bool saw_safe_input = false;
2463         for (uint j = 1; j < req(); ++j) {
2464           Node* n = in(j);
2465           if (n->is_MergeMem()) {
2466             MergeMemNode* mm = n->as_MergeMem();
2467             if (mm->base_memory() == this || mm->base_memory() == mm->empty_memory()) {
2468               // Skip this input if it references back to this phi or if the memory path is dead
2469               continue;
2470             }
2471           }
2472           if (!is_unsafe_data_reference(n)) {
2473             saw_safe_input = true; // found safe input
2474             break;
2475           }
2476         }
2477         if (!saw_safe_input) {
2478           // There is a dead loop: All inputs are either dead or reference back to this phi
2479           return top;
2480         }
2481 
2482         // Phi(...MergeMem(m0, m1:AT1, m2:AT2)...) into
2483         //     MergeMem(Phi(...m0...), Phi:AT1(...m1...), Phi:AT2(...m2...))
2484         PhaseIterGVN* igvn = phase->is_IterGVN();
2485         assert(igvn != nullptr, "sanity check");
2486         Node* hook = new Node(1);
2487         PhiNode* new_base = (PhiNode*) clone();
2488         // Must eagerly register phis, since they participate in loops.
2489         igvn->register_new_node_with_optimizer(new_base);
2490         hook->add_req(new_base);
2491 
2492         MergeMemNode* result = MergeMemNode::make(new_base);
2493         for (uint i = 1; i < req(); ++i) {
2494           Node *ii = in(i);
2495           if (ii->is_MergeMem()) {
2496             MergeMemNode* n = ii->as_MergeMem();
2497             if (igvn) {
2498               // TODO revisit this with JDK-8247216
2499               // Put 'n' on the worklist because it might be modified by MergeMemStream::iteration_setup
2500               igvn->_worklist.push(n);
2501             }
2502             for (MergeMemStream mms(result, n); mms.next_non_empty2(); ) {
2503               // If we have not seen this slice yet, make a phi for it.
2504               bool made_new_phi = false;
2505               if (mms.is_empty()) {
2506                 Node* new_phi = new_base->slice_memory(mms.adr_type(phase->C));
2507                 made_new_phi = true;
2508                 igvn->register_new_node_with_optimizer(new_phi);
2509                 hook->add_req(new_phi);
2510                 mms.set_memory(new_phi);
2511               }
2512               Node* phi = mms.memory();
2513               assert(made_new_phi || phi->in(i) == n, "replace the i-th merge by a slice");
2514               phi->set_req(i, mms.memory2());
2515             }
2516           }
2517         }
2518         // Distribute all self-loops.
2519         { // (Extra braces to hide mms.)
2520           for (MergeMemStream mms(result); mms.next_non_empty(); ) {
2521             Node* phi = mms.memory();
2522             for (uint i = 1; i < req(); ++i) {
2523               if (phi->in(i) == this)  phi->set_req(i, phi);
2524             }
2525           }
2526         }
2527         // Already replace this phi node to cut it off from the graph to not interfere in dead loop checks during the
2528         // transformations of the new phi nodes below. Otherwise, we could wrongly conclude that there is no dead loop
2529         // because we are finding this phi node again. Also set the type of the new MergeMem node in case we are also
2530         // visiting it in the transformations below.
2531         igvn->replace_node(this, result);
2532         igvn->set_type(result, result->bottom_type());
2533 
2534         // now transform the new nodes, and return the mergemem
2535         for (MergeMemStream mms(result); mms.next_non_empty(); ) {
2536           Node* phi = mms.memory();
2537           mms.set_memory(phase->transform(phi));
2538         }
2539         hook->destruct(igvn);
2540         // Replace self with the result.
2541         return result;
2542       }
2543     }
2544     //
2545     // Other optimizations on the memory chain
2546     //
2547     const TypePtr* at = adr_type();
2548     for( uint i=1; i<req(); ++i ) {// For all paths in
2549       Node *ii = in(i);
2550       Node *new_in = MemNode::optimize_memory_chain(ii, at, nullptr, phase);
2551       if (ii != new_in ) {
2552         set_req(i, new_in);
2553         progress = this;
2554       }
2555     }
2556   }
2557 
2558 #ifdef _LP64
2559   // Push DecodeN/DecodeNKlass down through phi.
2560   // The rest of phi graph will transform by split EncodeP node though phis up.
2561   if ((UseCompressedOops || UseCompressedClassPointers) && can_reshape && progress == nullptr) {
2562     bool may_push = true;
2563     bool has_decodeN = false;
2564     bool is_decodeN = false;
2565     for (uint i=1; i<req(); ++i) {// For all paths in
2566       Node *ii = in(i);
2567       if (ii->is_DecodeNarrowPtr() && ii->bottom_type() == bottom_type()) {
2568         // Do optimization if a non dead path exist.
2569         if (ii->in(1)->bottom_type() != Type::TOP) {
2570           has_decodeN = true;
2571           is_decodeN = ii->is_DecodeN();
2572         }
2573       } else if (!ii->is_Phi()) {
2574         may_push = false;
2575       }
2576     }
2577 
2578     if (has_decodeN && may_push) {
2579       PhaseIterGVN *igvn = phase->is_IterGVN();
2580       // Make narrow type for new phi.
2581       const Type* narrow_t;
2582       if (is_decodeN) {
2583         narrow_t = TypeNarrowOop::make(this->bottom_type()->is_ptr());
2584       } else {
2585         narrow_t = TypeNarrowKlass::make(this->bottom_type()->is_ptr());
2586       }
2587       PhiNode* new_phi = new PhiNode(r, narrow_t);
2588       uint orig_cnt = req();
2589       for (uint i=1; i<req(); ++i) {// For all paths in
2590         Node *ii = in(i);
2591         Node* new_ii = nullptr;
2592         if (ii->is_DecodeNarrowPtr()) {
2593           assert(ii->bottom_type() == bottom_type(), "sanity");
2594           new_ii = ii->in(1);
2595         } else {
2596           assert(ii->is_Phi(), "sanity");
2597           if (ii->as_Phi() == this) {
2598             new_ii = new_phi;
2599           } else {
2600             if (is_decodeN) {
2601               new_ii = new EncodePNode(ii, narrow_t);
2602             } else {
2603               new_ii = new EncodePKlassNode(ii, narrow_t);
2604             }
2605             igvn->register_new_node_with_optimizer(new_ii);
2606           }
2607         }
2608         new_phi->set_req(i, new_ii);
2609       }
2610       igvn->register_new_node_with_optimizer(new_phi, this);
2611       if (is_decodeN) {
2612         progress = new DecodeNNode(new_phi, bottom_type());
2613       } else {
2614         progress = new DecodeNKlassNode(new_phi, bottom_type());
2615       }
2616     }
2617   }
2618 #endif
2619 
2620   // Check recursively if inputs are either an inline type, constant null
2621   // or another Phi (including self references through data loops). If so,
2622   // push the inline types down through the phis to enable folding of loads.
2623   if (EnableValhalla && _type->isa_ptr() && req() > 2) {
2624     ResourceMark rm;
2625     Unique_Node_List worklist;
2626     worklist.push(this);
2627     bool can_optimize = true;
2628     ciInlineKlass* vk = nullptr;
2629     Node_List casts;
2630 
2631     // TODO 8302217 We need to prevent endless pushing through
2632     bool only_phi = (outcnt() != 0);
2633     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
2634       Node* n = fast_out(i);
2635       if (n->is_InlineType() && n->in(1) == this) {
2636         can_optimize = false;
2637         break;
2638       }
2639       if (!n->is_Phi()) {
2640         only_phi = false;
2641       }
2642     }
2643     if (only_phi) {
2644       can_optimize = false;
2645     }
2646     for (uint next = 0; next < worklist.size() && can_optimize; next++) {
2647       Node* phi = worklist.at(next);
2648       for (uint i = 1; i < phi->req() && can_optimize; i++) {
2649         Node* n = phi->in(i);
2650         if (n == nullptr) {
2651           can_optimize = false;
2652           break;
2653         }
2654         while (n->is_ConstraintCast()) {
2655           if (n->in(0) != nullptr && n->in(0)->is_top()) {
2656             // Will die, don't optimize
2657             can_optimize = false;
2658             break;
2659           }
2660           casts.push(n);
2661           n = n->in(1);
2662         }
2663         const Type* t = phase->type(n);
2664         if (n->is_InlineType() && (vk == nullptr || vk == t->inline_klass())) {
2665           vk = (vk == nullptr) ? t->inline_klass() : vk;
2666         } else if (n->is_Phi() && can_reshape && n->bottom_type()->isa_ptr()) {
2667           worklist.push(n);
2668         } else if (!t->is_zero_type()) {
2669           can_optimize = false;
2670         }
2671       }
2672     }
2673     // Check if cast nodes can be pushed through
2674     const Type* t = Type::get_const_type(vk);
2675     while (casts.size() != 0 && can_optimize && t != nullptr) {
2676       Node* cast = casts.pop();
2677       if (t->filter(cast->bottom_type()) == Type::TOP) {
2678         can_optimize = false;
2679       }
2680     }
2681     if (can_optimize && vk != nullptr) {
2682       return push_inline_types_through(phase, can_reshape, vk);
2683     }
2684   }
2685 
2686   // Phi (VB ... VB) => VB (Phi ...) (Phi ...)
2687   if (EnableVectorReboxing && can_reshape && progress == nullptr && type()->isa_oopptr()) {
2688     progress = merge_through_phi(this, phase->is_IterGVN());
2689   }
2690 
2691   return progress;              // Return any progress
2692 }
2693 
2694 Node* PhiNode::clone_through_phi(Node* root_phi, const Type* t, uint c, PhaseIterGVN* igvn) {
2695   Node_Stack stack(1);
2696   VectorSet  visited;
2697   Node_List  node_map;
2698 
2699   stack.push(root_phi, 1); // ignore control
2700   visited.set(root_phi->_idx);
2701 
2702   Node* new_phi = new PhiNode(root_phi->in(0), t);
2703   node_map.map(root_phi->_idx, new_phi);
2704 
2705   while (stack.is_nonempty()) {
2706     Node* n   = stack.node();
2707     uint  idx = stack.index();
2708     assert(n->is_Phi(), "not a phi");
2709     if (idx < n->req()) {
2710       stack.set_index(idx + 1);
2711       Node* def = n->in(idx);
2712       if (def == nullptr) {
2713         continue; // ignore dead path
2714       } else if (def->is_Phi()) { // inner node
2715         Node* new_phi = node_map[n->_idx];
2716         if (!visited.test_set(def->_idx)) { // not visited yet
2717           node_map.map(def->_idx, new PhiNode(def->in(0), t));
2718           stack.push(def, 1); // ignore control
2719         }
2720         Node* new_in = node_map[def->_idx];
2721         new_phi->set_req(idx, new_in);
2722       } else if (def->Opcode() == Op_VectorBox) { // leaf
2723         assert(n->is_Phi(), "not a phi");
2724         Node* new_phi = node_map[n->_idx];
2725         new_phi->set_req(idx, def->in(c));
2726       } else {
2727         assert(false, "not optimizeable");
2728         return nullptr;
2729       }
2730     } else {
2731       Node* new_phi = node_map[n->_idx];
2732       igvn->register_new_node_with_optimizer(new_phi, n);
2733       stack.pop();
2734     }
2735   }
2736   return new_phi;
2737 }
2738 
2739 Node* PhiNode::merge_through_phi(Node* root_phi, PhaseIterGVN* igvn) {
2740   Node_Stack stack(1);
2741   VectorSet  visited;
2742 
2743   stack.push(root_phi, 1); // ignore control
2744   visited.set(root_phi->_idx);
2745 
2746   VectorBoxNode* cached_vbox = nullptr;
2747   while (stack.is_nonempty()) {
2748     Node* n   = stack.node();
2749     uint  idx = stack.index();
2750     if (idx < n->req()) {
2751       stack.set_index(idx + 1);
2752       Node* in = n->in(idx);
2753       if (in == nullptr) {
2754         continue; // ignore dead path
2755       } else if (in->isa_Phi()) {
2756         if (!visited.test_set(in->_idx)) {
2757           stack.push(in, 1); // ignore control
2758         }
2759       } else if (in->Opcode() == Op_VectorBox) {
2760         VectorBoxNode* vbox = static_cast<VectorBoxNode*>(in);
2761         if (cached_vbox == nullptr) {
2762           cached_vbox = vbox;
2763         } else if (vbox->vec_type() != cached_vbox->vec_type()) {
2764           // TODO: vector type mismatch can be handled with additional reinterpret casts
2765           assert(Type::cmp(vbox->vec_type(), cached_vbox->vec_type()) != 0, "inconsistent");
2766           return nullptr; // not optimizable: vector type mismatch
2767         } else if (vbox->box_type() != cached_vbox->box_type()) {
2768           assert(Type::cmp(vbox->box_type(), cached_vbox->box_type()) != 0, "inconsistent");
2769           return nullptr; // not optimizable: box type mismatch
2770         }
2771       } else {
2772         return nullptr; // not optimizable: neither Phi nor VectorBox
2773       }
2774     } else {
2775       stack.pop();
2776     }
2777   }
2778   if (cached_vbox == nullptr) {
2779     // We have a Phi dead-loop (no data-input). Phi nodes are considered safe,
2780     // so just avoid this optimization.
2781     return nullptr;
2782   }
2783   const TypeInstPtr* btype = cached_vbox->box_type();
2784   const TypeVect*    vtype = cached_vbox->vec_type();
2785   Node* new_vbox_phi = clone_through_phi(root_phi, btype, VectorBoxNode::Box,   igvn);
2786   Node* new_vect_phi = clone_through_phi(root_phi, vtype, VectorBoxNode::Value, igvn);
2787   return new VectorBoxNode(igvn->C, new_vbox_phi, new_vect_phi, btype, vtype);
2788 }
2789 
2790 bool PhiNode::is_data_loop(RegionNode* r, Node* uin, const PhaseGVN* phase) {
2791   // First, take the short cut when we know it is a loop and the EntryControl data path is dead.
2792   // The loop node may only have one input because the entry path was removed in PhaseIdealLoop::Dominators().
2793   // Then, check if there is a data loop when the phi references itself directly or through other data nodes.
2794   assert(!r->is_Loop() || r->req() <= 3, "Loop node should have 3 or less inputs");
2795   const bool is_loop = (r->is_Loop() && r->req() == 3);
2796   const Node* top = phase->C->top();
2797   if (is_loop) {
2798     return !uin->eqv_uncast(in(LoopNode::EntryControl));
2799   } else {
2800     // We have a data loop either with an unsafe data reference or if a region is unreachable.
2801     return is_unsafe_data_reference(uin)
2802            || (r->req() == 3 && (r->in(1) != top && r->in(2) == top && r->is_unreachable_region(phase)));
2803   }
2804 }
2805 
2806 //------------------------------is_tripcount-----------------------------------
2807 bool PhiNode::is_tripcount(BasicType bt) const {
2808   return (in(0) != nullptr && in(0)->is_BaseCountedLoop() &&
2809           in(0)->as_BaseCountedLoop()->bt() == bt &&
2810           in(0)->as_BaseCountedLoop()->phi() == this);
2811 }
2812 
2813 //------------------------------out_RegMask------------------------------------
2814 const RegMask &PhiNode::in_RegMask(uint i) const {
2815   return i ? out_RegMask() : RegMask::Empty;
2816 }
2817 
2818 const RegMask &PhiNode::out_RegMask() const {
2819   uint ideal_reg = _type->ideal_reg();
2820   assert( ideal_reg != Node::NotAMachineReg, "invalid type at Phi" );
2821   if( ideal_reg == 0 ) return RegMask::Empty;
2822   assert(ideal_reg != Op_RegFlags, "flags register is not spillable");
2823   return *(Compile::current()->matcher()->idealreg2spillmask[ideal_reg]);
2824 }
2825 
2826 #ifndef PRODUCT
2827 void PhiNode::dump_spec(outputStream *st) const {
2828   TypeNode::dump_spec(st);
2829   if (is_tripcount(T_INT) || is_tripcount(T_LONG)) {
2830     st->print(" #tripcount");
2831   }
2832 }
2833 #endif
2834 
2835 
2836 //=============================================================================
2837 const Type* GotoNode::Value(PhaseGVN* phase) const {
2838   // If the input is reachable, then we are executed.
2839   // If the input is not reachable, then we are not executed.
2840   return phase->type(in(0));
2841 }
2842 
2843 Node* GotoNode::Identity(PhaseGVN* phase) {
2844   return in(0);                // Simple copy of incoming control
2845 }
2846 
2847 const RegMask &GotoNode::out_RegMask() const {
2848   return RegMask::Empty;
2849 }
2850 
2851 //=============================================================================
2852 const RegMask &JumpNode::out_RegMask() const {
2853   return RegMask::Empty;
2854 }
2855 
2856 //=============================================================================
2857 const RegMask &JProjNode::out_RegMask() const {
2858   return RegMask::Empty;
2859 }
2860 
2861 //=============================================================================
2862 const RegMask &CProjNode::out_RegMask() const {
2863   return RegMask::Empty;
2864 }
2865 
2866 
2867 
2868 //=============================================================================
2869 
2870 uint PCTableNode::hash() const { return Node::hash() + _size; }
2871 bool PCTableNode::cmp( const Node &n ) const
2872 { return _size == ((PCTableNode&)n)._size; }
2873 
2874 const Type *PCTableNode::bottom_type() const {
2875   const Type** f = TypeTuple::fields(_size);
2876   for( uint i = 0; i < _size; i++ ) f[i] = Type::CONTROL;
2877   return TypeTuple::make(_size, f);
2878 }
2879 
2880 //------------------------------Value------------------------------------------
2881 // Compute the type of the PCTableNode.  If reachable it is a tuple of
2882 // Control, otherwise the table targets are not reachable
2883 const Type* PCTableNode::Value(PhaseGVN* phase) const {
2884   if( phase->type(in(0)) == Type::CONTROL )
2885     return bottom_type();
2886   return Type::TOP;             // All paths dead?  Then so are we
2887 }
2888 
2889 //------------------------------Ideal------------------------------------------
2890 // Return a node which is more "ideal" than the current node.  Strip out
2891 // control copies
2892 Node *PCTableNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2893   return remove_dead_region(phase, can_reshape) ? this : nullptr;
2894 }
2895 
2896 //=============================================================================
2897 uint JumpProjNode::hash() const {
2898   return Node::hash() + _dest_bci;
2899 }
2900 
2901 bool JumpProjNode::cmp( const Node &n ) const {
2902   return ProjNode::cmp(n) &&
2903     _dest_bci == ((JumpProjNode&)n)._dest_bci;
2904 }
2905 
2906 #ifndef PRODUCT
2907 void JumpProjNode::dump_spec(outputStream *st) const {
2908   ProjNode::dump_spec(st);
2909   st->print("@bci %d ",_dest_bci);
2910 }
2911 
2912 void JumpProjNode::dump_compact_spec(outputStream *st) const {
2913   ProjNode::dump_compact_spec(st);
2914   st->print("(%d)%d@%d", _switch_val, _proj_no, _dest_bci);
2915 }
2916 #endif
2917 
2918 //=============================================================================
2919 //------------------------------Value------------------------------------------
2920 // Check for being unreachable, or for coming from a Rethrow.  Rethrow's cannot
2921 // have the default "fall_through_index" path.
2922 const Type* CatchNode::Value(PhaseGVN* phase) const {
2923   // Unreachable?  Then so are all paths from here.
2924   if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
2925   // First assume all paths are reachable
2926   const Type** f = TypeTuple::fields(_size);
2927   for( uint i = 0; i < _size; i++ ) f[i] = Type::CONTROL;
2928   // Identify cases that will always throw an exception
2929   // () rethrow call
2930   // () virtual or interface call with null receiver
2931   // () call is a check cast with incompatible arguments
2932   if( in(1)->is_Proj() ) {
2933     Node *i10 = in(1)->in(0);
2934     if( i10->is_Call() ) {
2935       CallNode *call = i10->as_Call();
2936       // Rethrows always throw exceptions, never return
2937       if (call->entry_point() == OptoRuntime::rethrow_stub()) {
2938         f[CatchProjNode::fall_through_index] = Type::TOP;
2939       } else if (call->is_AllocateArray()) {
2940         Node* klass_node = call->in(AllocateNode::KlassNode);
2941         Node* length = call->in(AllocateNode::ALength);
2942         const Type* length_type = phase->type(length);
2943         const Type* klass_type = phase->type(klass_node);
2944         Node* valid_length_test = call->in(AllocateNode::ValidLengthTest);
2945         const Type* valid_length_test_t = phase->type(valid_length_test);
2946         if (length_type == Type::TOP || klass_type == Type::TOP || valid_length_test_t == Type::TOP ||
2947             valid_length_test_t->is_int()->is_con(0)) {
2948           f[CatchProjNode::fall_through_index] = Type::TOP;
2949         }
2950       } else if( call->req() > TypeFunc::Parms ) {
2951         const Type *arg0 = phase->type( call->in(TypeFunc::Parms) );
2952         // Check for null receiver to virtual or interface calls
2953         if( call->is_CallDynamicJava() &&
2954             arg0->higher_equal(TypePtr::NULL_PTR) ) {
2955           f[CatchProjNode::fall_through_index] = Type::TOP;
2956         }
2957       } // End of if not a runtime stub
2958     } // End of if have call above me
2959   } // End of slot 1 is not a projection
2960   return TypeTuple::make(_size, f);
2961 }
2962 
2963 //=============================================================================
2964 uint CatchProjNode::hash() const {
2965   return Node::hash() + _handler_bci;
2966 }
2967 
2968 
2969 bool CatchProjNode::cmp( const Node &n ) const {
2970   return ProjNode::cmp(n) &&
2971     _handler_bci == ((CatchProjNode&)n)._handler_bci;
2972 }
2973 
2974 
2975 //------------------------------Identity---------------------------------------
2976 // If only 1 target is possible, choose it if it is the main control
2977 Node* CatchProjNode::Identity(PhaseGVN* phase) {
2978   // If my value is control and no other value is, then treat as ID
2979   const TypeTuple *t = phase->type(in(0))->is_tuple();
2980   if (t->field_at(_con) != Type::CONTROL)  return this;
2981   // If we remove the last CatchProj and elide the Catch/CatchProj, then we
2982   // also remove any exception table entry.  Thus we must know the call
2983   // feeding the Catch will not really throw an exception.  This is ok for
2984   // the main fall-thru control (happens when we know a call can never throw
2985   // an exception) or for "rethrow", because a further optimization will
2986   // yank the rethrow (happens when we inline a function that can throw an
2987   // exception and the caller has no handler).  Not legal, e.g., for passing
2988   // a null receiver to a v-call, or passing bad types to a slow-check-cast.
2989   // These cases MUST throw an exception via the runtime system, so the VM
2990   // will be looking for a table entry.
2991   Node *proj = in(0)->in(1);    // Expect a proj feeding CatchNode
2992   CallNode *call;
2993   if (_con != TypeFunc::Control && // Bail out if not the main control.
2994       !(proj->is_Proj() &&      // AND NOT a rethrow
2995         proj->in(0)->is_Call() &&
2996         (call = proj->in(0)->as_Call()) &&
2997         call->entry_point() == OptoRuntime::rethrow_stub()))
2998     return this;
2999 
3000   // Search for any other path being control
3001   for (uint i = 0; i < t->cnt(); i++) {
3002     if (i != _con && t->field_at(i) == Type::CONTROL)
3003       return this;
3004   }
3005   // Only my path is possible; I am identity on control to the jump
3006   return in(0)->in(0);
3007 }
3008 
3009 
3010 #ifndef PRODUCT
3011 void CatchProjNode::dump_spec(outputStream *st) const {
3012   ProjNode::dump_spec(st);
3013   st->print("@bci %d ",_handler_bci);
3014 }
3015 #endif
3016 
3017 //=============================================================================
3018 //------------------------------Identity---------------------------------------
3019 // Check for CreateEx being Identity.
3020 Node* CreateExNode::Identity(PhaseGVN* phase) {
3021   if( phase->type(in(1)) == Type::TOP ) return in(1);
3022   if( phase->type(in(0)) == Type::TOP ) return in(0);
3023   if (phase->type(in(0)->in(0)) == Type::TOP) {
3024     assert(in(0)->is_CatchProj(), "control is CatchProj");
3025     return phase->C->top(); // dead code
3026   }
3027   // We only come from CatchProj, unless the CatchProj goes away.
3028   // If the CatchProj is optimized away, then we just carry the
3029   // exception oop through.
3030 
3031   // CheckCastPPNode::Ideal() for inline types reuses the exception
3032   // paths of a call to perform an allocation: we can see a Phi here.
3033   if (in(1)->is_Phi()) {
3034     return this;
3035   }
3036   CallNode *call = in(1)->in(0)->as_Call();
3037 
3038   return (in(0)->is_CatchProj() && in(0)->in(0)->is_Catch() &&
3039           in(0)->in(0)->in(1) == in(1)) ? this : call->in(TypeFunc::Parms);
3040 }
3041 
3042 //=============================================================================
3043 //------------------------------Value------------------------------------------
3044 // Check for being unreachable.
3045 const Type* NeverBranchNode::Value(PhaseGVN* phase) const {
3046   if (!in(0) || in(0)->is_top()) return Type::TOP;
3047   return bottom_type();
3048 }
3049 
3050 //------------------------------Ideal------------------------------------------
3051 // Check for no longer being part of a loop
3052 Node *NeverBranchNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3053   if (can_reshape && !in(0)->is_Region()) {
3054     // Dead code elimination can sometimes delete this projection so
3055     // if it's not there, there's nothing to do.
3056     Node* fallthru = proj_out_or_null(0);
3057     if (fallthru != nullptr) {
3058       phase->is_IterGVN()->replace_node(fallthru, in(0));
3059     }
3060     return phase->C->top();
3061   }
3062   return nullptr;
3063 }
3064 
3065 #ifndef PRODUCT
3066 void NeverBranchNode::format( PhaseRegAlloc *ra_, outputStream *st) const {
3067   st->print("%s", Name());
3068 }
3069 #endif
3070 
3071 #ifndef PRODUCT
3072 void BlackholeNode::format(PhaseRegAlloc* ra, outputStream* st) const {
3073   st->print("blackhole ");
3074   bool first = true;
3075   for (uint i = 0; i < req(); i++) {
3076     Node* n = in(i);
3077     if (n != nullptr && OptoReg::is_valid(ra->get_reg_first(n))) {
3078       if (first) {
3079         first = false;
3080       } else {
3081         st->print(", ");
3082       }
3083       char buf[128];
3084       ra->dump_register(n, buf, sizeof(buf));
3085       st->print("%s", buf);
3086     }
3087   }
3088   st->cr();
3089 }
3090 #endif
3091