1 /*
   2  * Copyright (c) 1998, 2021, 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 "asm/macroAssembler.inline.hpp"
  27 #include "gc/shared/gc_globals.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "oops/compressedOops.hpp"
  30 #include "opto/ad.hpp"
  31 #include "opto/block.hpp"
  32 #include "opto/c2compiler.hpp"
  33 #include "opto/callnode.hpp"
  34 #include "opto/cfgnode.hpp"
  35 #include "opto/machnode.hpp"
  36 #include "opto/runtime.hpp"
  37 #include "opto/chaitin.hpp"
  38 #include "runtime/sharedRuntime.hpp"
  39 
  40 // Optimization - Graph Style
  41 
  42 // Check whether val is not-null-decoded compressed oop,
  43 // i.e. will grab into the base of the heap if it represents NULL.
  44 static bool accesses_heap_base_zone(Node *val) {
  45   if (CompressedOops::base() != NULL) { // Implies UseCompressedOops.
  46     if (val && val->is_Mach()) {
  47       if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) {
  48         // This assumes all Decodes with TypePtr::NotNull are matched to nodes that
  49         // decode NULL to point to the heap base (Decode_NN).
  50         if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) {
  51           return true;
  52         }
  53       }
  54       // Must recognize load operation with Decode matched in memory operand.
  55       // We should not reach here exept for PPC/AIX, as os::zero_page_read_protected()
  56       // returns true everywhere else. On PPC, no such memory operands
  57       // exist, therefore we did not yet implement a check for such operands.
  58       NOT_AIX(Unimplemented());
  59     }
  60   }
  61   return false;
  62 }
  63 
  64 static bool needs_explicit_null_check_for_read(Node *val) {
  65   // On some OSes (AIX) the page at address 0 is only write protected.
  66   // If so, only Store operations will trap.
  67   if (os::zero_page_read_protected()) {
  68     return false;  // Implicit null check will work.
  69   }
  70   // Also a read accessing the base of a heap-based compressed heap will trap.
  71   if (accesses_heap_base_zone(val) &&         // Hits the base zone page.
  72       CompressedOops::use_implicit_null_checks()) { // Base zone page is protected.
  73     return false;
  74   }
  75 
  76   return true;
  77 }
  78 
  79 //------------------------------implicit_null_check----------------------------
  80 // Detect implicit-null-check opportunities.  Basically, find NULL checks
  81 // with suitable memory ops nearby.  Use the memory op to do the NULL check.
  82 // I can generate a memory op if there is not one nearby.
  83 // The proj is the control projection for the not-null case.
  84 // The val is the pointer being checked for nullness or
  85 // decodeHeapOop_not_null node if it did not fold into address.
  86 void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) {
  87   // Assume if null check need for 0 offset then always needed
  88   // Intel solaris doesn't support any null checks yet and no
  89   // mechanism exists (yet) to set the switches at an os_cpu level
  90   if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;
  91 
  92   // Make sure the ptr-is-null path appears to be uncommon!
  93   float f = block->end()->as_MachIf()->_prob;
  94   if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;
  95   if( f > PROB_UNLIKELY_MAG(4) ) return;
  96 
  97   uint bidx = 0;                // Capture index of value into memop
  98   bool was_store;               // Memory op is a store op
  99 
 100   // Get the successor block for if the test ptr is non-null
 101   Block* not_null_block;  // this one goes with the proj
 102   Block* null_block;
 103   if (block->get_node(block->number_of_nodes()-1) == proj) {
 104     null_block     = block->_succs[0];
 105     not_null_block = block->_succs[1];
 106   } else {
 107     assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other");
 108     not_null_block = block->_succs[0];
 109     null_block     = block->_succs[1];
 110   }
 111   while (null_block->is_Empty() == Block::empty_with_goto) {
 112     null_block     = null_block->_succs[0];
 113   }
 114 
 115   // Search the exception block for an uncommon trap.
 116   // (See Parse::do_if and Parse::do_ifnull for the reason
 117   // we need an uncommon trap.  Briefly, we need a way to
 118   // detect failure of this optimization, as in 6366351.)
 119   {
 120     bool found_trap = false;
 121     for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) {
 122       Node* nn = null_block->get_node(i1);
 123       if (nn->is_MachCall() &&
 124           nn->as_MachCall()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point()) {
 125         const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();
 126         if (trtype->isa_int() && trtype->is_int()->is_con()) {
 127           jint tr_con = trtype->is_int()->get_con();
 128           Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
 129           Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
 130           assert((int)reason < (int)BitsPerInt, "recode bit map");
 131           if (is_set_nth_bit(allowed_reasons, (int) reason)
 132               && action != Deoptimization::Action_none) {
 133             // This uncommon trap is sure to recompile, eventually.
 134             // When that happens, C->too_many_traps will prevent
 135             // this transformation from happening again.
 136             found_trap = true;
 137           }
 138         }
 139         break;
 140       }
 141     }
 142     if (!found_trap) {
 143       // We did not find an uncommon trap.
 144       return;
 145     }
 146   }
 147 
 148   // Check for decodeHeapOop_not_null node which did not fold into address
 149   bool is_decoden = ((intptr_t)val) & 1;
 150   val = (Node*)(((intptr_t)val) & ~1);
 151 
 152   assert(!is_decoden || (val->in(0) == NULL) && val->is_Mach() &&
 153          (val->as_Mach()->ideal_Opcode() == Op_DecodeN), "sanity");
 154 
 155   // Search the successor block for a load or store who's base value is also
 156   // the tested value.  There may be several.
 157   MachNode *best = NULL;        // Best found so far
 158   for (DUIterator i = val->outs(); val->has_out(i); i++) {
 159     Node *m = val->out(i);
 160     if( !m->is_Mach() ) continue;
 161     MachNode *mach = m->as_Mach();
 162     was_store = false;
 163     int iop = mach->ideal_Opcode();
 164     switch( iop ) {
 165     case Op_LoadB:
 166     case Op_LoadUB:
 167     case Op_LoadUS:
 168     case Op_LoadD:
 169     case Op_LoadF:
 170     case Op_LoadI:
 171     case Op_LoadL:
 172     case Op_LoadP:
 173     case Op_LoadN:
 174     case Op_LoadS:
 175     case Op_LoadKlass:
 176     case Op_LoadNKlass:
 177     case Op_LoadRange:
 178     case Op_LoadD_unaligned:
 179     case Op_LoadL_unaligned:
 180       assert(mach->in(2) == val, "should be address");
 181       break;
 182     case Op_StoreB:
 183     case Op_StoreC:
 184     case Op_StoreCM:
 185     case Op_StoreD:
 186     case Op_StoreF:
 187     case Op_StoreI:
 188     case Op_StoreL:
 189     case Op_StoreP:
 190     case Op_StoreN:
 191     case Op_StoreNKlass:
 192       was_store = true;         // Memory op is a store op
 193       // Stores will have their address in slot 2 (memory in slot 1).
 194       // If the value being nul-checked is in another slot, it means we
 195       // are storing the checked value, which does NOT check the value!
 196       if( mach->in(2) != val ) continue;
 197       break;                    // Found a memory op?
 198     case Op_StrComp:
 199     case Op_StrEquals:
 200     case Op_StrIndexOf:
 201     case Op_StrIndexOfChar:
 202     case Op_AryEq:
 203     case Op_StrInflatedCopy:
 204     case Op_StrCompressedCopy:
 205     case Op_EncodeISOArray:
 206     case Op_HasNegatives:
 207       // Not a legit memory op for implicit null check regardless of
 208       // embedded loads
 209       continue;
 210     default:                    // Also check for embedded loads
 211       if( !mach->needs_anti_dependence_check() )
 212         continue;               // Not an memory op; skip it
 213       if( must_clone[iop] ) {
 214         // Do not move nodes which produce flags because
 215         // RA will try to clone it to place near branch and
 216         // it will cause recompilation, see clone_node().
 217         continue;
 218       }
 219       {
 220         // Check that value is used in memory address in
 221         // instructions with embedded load (CmpP val1,(val2+off)).
 222         Node* base;
 223         Node* index;
 224         const MachOper* oper = mach->memory_inputs(base, index);
 225         if (oper == NULL || oper == (MachOper*)-1) {
 226           continue;             // Not an memory op; skip it
 227         }
 228         if (val == base ||
 229             (val == index && val->bottom_type()->isa_narrowoop())) {
 230           break;                // Found it
 231         } else {
 232           continue;             // Skip it
 233         }
 234       }
 235       break;
 236     }
 237 
 238     // On some OSes (AIX) the page at address 0 is only write protected.
 239     // If so, only Store operations will trap.
 240     // But a read accessing the base of a heap-based compressed heap will trap.
 241     if (!was_store && needs_explicit_null_check_for_read(val)) {
 242       continue;
 243     }
 244 
 245     // Check that node's control edge is not-null block's head or dominates it,
 246     // otherwise we can't hoist it because there are other control dependencies.
 247     Node* ctrl = mach->in(0);
 248     if (ctrl != NULL && !(ctrl == not_null_block->head() ||
 249         get_block_for_node(ctrl)->dominates(not_null_block))) {
 250       continue;
 251     }
 252 
 253     // check if the offset is not too high for implicit exception
 254     {
 255       intptr_t offset = 0;
 256       const TypePtr *adr_type = NULL;  // Do not need this return value here
 257       const Node* base = mach->get_base_and_disp(offset, adr_type);
 258       if (base == NULL || base == NodeSentinel) {
 259         // Narrow oop address doesn't have base, only index.
 260         // Give up if offset is beyond page size or if heap base is not protected.
 261         if (val->bottom_type()->isa_narrowoop() &&
 262             (MacroAssembler::needs_explicit_null_check(offset) ||
 263              !CompressedOops::use_implicit_null_checks()))
 264           continue;
 265         // cannot reason about it; is probably not implicit null exception
 266       } else {
 267         const TypePtr* tptr;
 268         if ((UseCompressedOops || UseCompressedClassPointers) &&
 269             (CompressedOops::shift() == 0 || CompressedKlassPointers::shift() == 0)) {
 270           // 32-bits narrow oop can be the base of address expressions
 271           tptr = base->get_ptr_type();
 272         } else {
 273           // only regular oops are expected here
 274           tptr = base->bottom_type()->is_ptr();
 275         }
 276         // Give up if offset is not a compile-time constant.
 277         if (offset == Type::OffsetBot || tptr->offset() == Type::OffsetBot)
 278           continue;
 279         offset += tptr->offset(); // correct if base is offseted
 280         // Give up if reference is beyond page size.
 281         if (MacroAssembler::needs_explicit_null_check(offset))
 282           continue;
 283         // Give up if base is a decode node and the heap base is not protected.
 284         if (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_DecodeN &&
 285             !CompressedOops::use_implicit_null_checks())
 286           continue;
 287       }
 288     }
 289 
 290     // Check ctrl input to see if the null-check dominates the memory op
 291     Block *cb = get_block_for_node(mach);
 292     cb = cb->_idom;             // Always hoist at least 1 block
 293     if( !was_store ) {          // Stores can be hoisted only one block
 294       while( cb->_dom_depth > (block->_dom_depth + 1))
 295         cb = cb->_idom;         // Hoist loads as far as we want
 296       // The non-null-block should dominate the memory op, too. Live
 297       // range spilling will insert a spill in the non-null-block if it is
 298       // needs to spill the memory op for an implicit null check.
 299       if (cb->_dom_depth == (block->_dom_depth + 1)) {
 300         if (cb != not_null_block) continue;
 301         cb = cb->_idom;
 302       }
 303     }
 304     if( cb != block ) continue;
 305 
 306     // Found a memory user; see if it can be hoisted to check-block
 307     uint vidx = 0;              // Capture index of value into memop
 308     uint j;
 309     for( j = mach->req()-1; j > 0; j-- ) {
 310       if( mach->in(j) == val ) {
 311         vidx = j;
 312         // Ignore DecodeN val which could be hoisted to where needed.
 313         if( is_decoden ) continue;
 314       }
 315       // Block of memory-op input
 316       Block* inb = get_block_for_node(mach->in(j));
 317       if (mach->in(j)->is_Con() && mach->in(j)->req() == 1 && inb == get_block_for_node(mach)) {
 318         // Ignore constant loads scheduled in the same block (we can simply hoist them as well)
 319         continue;
 320       }
 321       Block *b = block;          // Start from nul check
 322       while( b != inb && b->_dom_depth > inb->_dom_depth )
 323         b = b->_idom;           // search upwards for input
 324       // See if input dominates null check
 325       if( b != inb )
 326         break;
 327     }
 328     if( j > 0 )
 329       continue;
 330     Block *mb = get_block_for_node(mach);
 331     // Hoisting stores requires more checks for the anti-dependence case.
 332     // Give up hoisting if we have to move the store past any load.
 333     if( was_store ) {
 334       Block *b = mb;            // Start searching here for a local load
 335       // mach use (faulting) trying to hoist
 336       // n might be blocker to hoisting
 337       while( b != block ) {
 338         uint k;
 339         for( k = 1; k < b->number_of_nodes(); k++ ) {
 340           Node *n = b->get_node(k);
 341           if( n->needs_anti_dependence_check() &&
 342               n->in(LoadNode::Memory) == mach->in(StoreNode::Memory) )
 343             break;              // Found anti-dependent load
 344         }
 345         if( k < b->number_of_nodes() )
 346           break;                // Found anti-dependent load
 347         // Make sure control does not do a merge (would have to check allpaths)
 348         if( b->num_preds() != 2 ) break;
 349         b = get_block_for_node(b->pred(1)); // Move up to predecessor block
 350       }
 351       if( b != block ) continue;
 352     }
 353 
 354     // Make sure this memory op is not already being used for a NullCheck
 355     Node *e = mb->end();
 356     if( e->is_MachNullCheck() && e->in(1) == mach )
 357       continue;                 // Already being used as a NULL check
 358 
 359     // Found a candidate!  Pick one with least dom depth - the highest
 360     // in the dom tree should be closest to the null check.
 361     if (best == NULL || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) {
 362       best = mach;
 363       bidx = vidx;
 364     }
 365   }
 366   // No candidate!
 367   if (best == NULL) {
 368     return;
 369   }
 370 
 371   // ---- Found an implicit null check
 372 #ifndef PRODUCT
 373   extern int implicit_null_checks;
 374   implicit_null_checks++;
 375 #endif
 376 
 377   if( is_decoden ) {
 378     // Check if we need to hoist decodeHeapOop_not_null first.
 379     Block *valb = get_block_for_node(val);
 380     if( block != valb && block->_dom_depth < valb->_dom_depth ) {
 381       // Hoist it up to the end of the test block together with its inputs if they exist.
 382       for (uint i = 2; i < val->req(); i++) {
 383         // DecodeN has 2 regular inputs + optional MachTemp or load Base inputs.
 384         Node *temp = val->in(i);
 385         Block *tempb = get_block_for_node(temp);
 386         if (!tempb->dominates(block)) {
 387           assert(block->dominates(tempb), "sanity check: temp node placement");
 388           // We only expect nodes without further inputs, like MachTemp or load Base.
 389           assert(temp->req() == 0 || (temp->req() == 1 && temp->in(0) == (Node*)C->root()),
 390                  "need for recursive hoisting not expected");
 391           tempb->find_remove(temp);
 392           block->add_inst(temp);
 393           map_node_to_block(temp, block);
 394         }
 395       }
 396       valb->find_remove(val);
 397       block->add_inst(val);
 398       map_node_to_block(val, block);
 399       // DecodeN on x86 may kill flags. Check for flag-killing projections
 400       // that also need to be hoisted.
 401       for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
 402         Node* n = val->fast_out(j);
 403         if( n->is_MachProj() ) {
 404           get_block_for_node(n)->find_remove(n);
 405           block->add_inst(n);
 406           map_node_to_block(n, block);
 407         }
 408       }
 409     }
 410   }
 411 
 412   // Hoist constant load inputs as well.
 413   for (uint i = 1; i < best->req(); ++i) {
 414     Node* n = best->in(i);
 415     if (n->is_Con() && get_block_for_node(n) == get_block_for_node(best)) {
 416       get_block_for_node(n)->find_remove(n);
 417       block->add_inst(n);
 418       map_node_to_block(n, block);
 419       // Constant loads may kill flags (for example, when XORing a register).
 420       // Check for flag-killing projections that also need to be hoisted.
 421       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 422         Node* proj = n->fast_out(j);
 423         if (proj->is_MachProj()) {
 424           get_block_for_node(proj)->find_remove(proj);
 425           block->add_inst(proj);
 426           map_node_to_block(proj, block);
 427         }
 428       }
 429     }
 430   }
 431 
 432   // Hoist the memory candidate up to the end of the test block.
 433   Block *old_block = get_block_for_node(best);
 434   old_block->find_remove(best);
 435   block->add_inst(best);
 436   map_node_to_block(best, block);
 437 
 438   // Move the control dependence if it is pinned to not-null block.
 439   // Don't change it in other cases: NULL or dominating control.
 440   Node* ctrl = best->in(0);
 441   if (ctrl != NULL && get_block_for_node(ctrl) == not_null_block) {
 442     // Set it to control edge of null check.
 443     best->set_req(0, proj->in(0)->in(0));
 444   }
 445 
 446   // Check for flag-killing projections that also need to be hoisted
 447   // Should be DU safe because no edge updates.
 448   for (DUIterator_Fast jmax, j = best->fast_outs(jmax); j < jmax; j++) {
 449     Node* n = best->fast_out(j);
 450     if( n->is_MachProj() ) {
 451       get_block_for_node(n)->find_remove(n);
 452       block->add_inst(n);
 453       map_node_to_block(n, block);
 454     }
 455   }
 456 
 457   // proj==Op_True --> ne test; proj==Op_False --> eq test.
 458   // One of two graph shapes got matched:
 459   //   (IfTrue  (If (Bool NE (CmpP ptr NULL))))
 460   //   (IfFalse (If (Bool EQ (CmpP ptr NULL))))
 461   // NULL checks are always branch-if-eq.  If we see a IfTrue projection
 462   // then we are replacing a 'ne' test with a 'eq' NULL check test.
 463   // We need to flip the projections to keep the same semantics.
 464   if( proj->Opcode() == Op_IfTrue ) {
 465     // Swap order of projections in basic block to swap branch targets
 466     Node *tmp1 = block->get_node(block->end_idx()+1);
 467     Node *tmp2 = block->get_node(block->end_idx()+2);
 468     block->map_node(tmp2, block->end_idx()+1);
 469     block->map_node(tmp1, block->end_idx()+2);
 470     Node *tmp = new Node(C->top()); // Use not NULL input
 471     tmp1->replace_by(tmp);
 472     tmp2->replace_by(tmp1);
 473     tmp->replace_by(tmp2);
 474     tmp->destruct(NULL);
 475   }
 476 
 477   // Remove the existing null check; use a new implicit null check instead.
 478   // Since schedule-local needs precise def-use info, we need to correct
 479   // it as well.
 480   Node *old_tst = proj->in(0);
 481   MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx);
 482   block->map_node(nul_chk, block->end_idx());
 483   map_node_to_block(nul_chk, block);
 484   // Redirect users of old_test to nul_chk
 485   for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)
 486     old_tst->last_out(i2)->set_req(0, nul_chk);
 487   // Clean-up any dead code
 488   for (uint i3 = 0; i3 < old_tst->req(); i3++) {
 489     Node* in = old_tst->in(i3);
 490     old_tst->set_req(i3, NULL);
 491     if (in->outcnt() == 0) {
 492       // Remove dead input node
 493       in->disconnect_inputs(C);
 494       block->find_remove(in);
 495     }
 496   }
 497 
 498   latency_from_uses(nul_chk);
 499   latency_from_uses(best);
 500 
 501   // insert anti-dependences to defs in this block
 502   if (! best->needs_anti_dependence_check()) {
 503     for (uint k = 1; k < block->number_of_nodes(); k++) {
 504       Node *n = block->get_node(k);
 505       if (n->needs_anti_dependence_check() &&
 506           n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {
 507         // Found anti-dependent load
 508         insert_anti_dependences(block, n);
 509       }
 510     }
 511   }
 512 }
 513 
 514 
 515 //------------------------------select-----------------------------------------
 516 // Select a nice fellow from the worklist to schedule next. If there is only
 517 // one choice, then use it. Projections take top priority for correctness
 518 // reasons - if I see a projection, then it is next.  There are a number of
 519 // other special cases, for instructions that consume condition codes, et al.
 520 // These are chosen immediately. Some instructions are required to immediately
 521 // precede the last instruction in the block, and these are taken last. Of the
 522 // remaining cases (most), choose the instruction with the greatest latency
 523 // (that is, the most number of pseudo-cycles required to the end of the
 524 // routine). If there is a tie, choose the instruction with the most inputs.
 525 Node* PhaseCFG::select(
 526   Block* block,
 527   Node_List &worklist,
 528   GrowableArray<int> &ready_cnt,
 529   VectorSet &next_call,
 530   uint sched_slot,
 531   intptr_t* recalc_pressure_nodes) {
 532 
 533   // If only a single entry on the stack, use it
 534   uint cnt = worklist.size();
 535   if (cnt == 1) {
 536     Node *n = worklist[0];
 537     worklist.map(0,worklist.pop());
 538     return n;
 539   }
 540 
 541   uint choice  = 0; // Bigger is most important
 542   uint latency = 0; // Bigger is scheduled first
 543   uint score   = 0; // Bigger is better
 544   int idx = -1;     // Index in worklist
 545   int cand_cnt = 0; // Candidate count
 546   bool block_size_threshold_ok = (recalc_pressure_nodes != NULL) && (block->number_of_nodes() > 10);
 547 
 548   for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
 549     // Order in worklist is used to break ties.
 550     // See caller for how this is used to delay scheduling
 551     // of induction variable increments to after the other
 552     // uses of the phi are scheduled.
 553     Node *n = worklist[i];      // Get Node on worklist
 554 
 555     int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;
 556     if( n->is_Proj() ||         // Projections always win
 557         n->Opcode()== Op_Con || // So does constant 'Top'
 558         iop == Op_CreateEx ||   // Create-exception must start block
 559         iop == Op_CheckCastPP
 560         ) {
 561       worklist.map(i,worklist.pop());
 562       return n;
 563     }
 564 
 565     // Final call in a block must be adjacent to 'catch'
 566     Node *e = block->end();
 567     if( e->is_Catch() && e->in(0)->in(0) == n )
 568       continue;
 569 
 570     // Memory op for an implicit null check has to be at the end of the block
 571     if( e->is_MachNullCheck() && e->in(1) == n )
 572       continue;
 573 
 574     // Schedule IV increment last.
 575     if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd) {
 576       // Cmp might be matched into CountedLoopEnd node.
 577       Node *cmp = (e->in(1)->ideal_reg() == Op_RegFlags) ? e->in(1) : e;
 578       if (cmp->req() > 1 && cmp->in(1) == n && n->is_iteratively_computed()) {
 579         continue;
 580       }
 581     }
 582 
 583     uint n_choice  = 2;
 584 
 585     // See if this instruction is consumed by a branch. If so, then (as the
 586     // branch is the last instruction in the basic block) force it to the
 587     // end of the basic block
 588     if ( must_clone[iop] ) {
 589       // See if any use is a branch
 590       bool found_machif = false;
 591 
 592       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 593         Node* use = n->fast_out(j);
 594 
 595         // The use is a conditional branch, make them adjacent
 596         if (use->is_MachIf() && get_block_for_node(use) == block) {
 597           found_machif = true;
 598           break;
 599         }
 600 
 601         // More than this instruction pending for successor to be ready,
 602         // don't choose this if other opportunities are ready
 603         if (ready_cnt.at(use->_idx) > 1)
 604           n_choice = 1;
 605       }
 606 
 607       // loop terminated, prefer not to use this instruction
 608       if (found_machif)
 609         continue;
 610     }
 611 
 612     // See if this has a predecessor that is "must_clone", i.e. sets the
 613     // condition code. If so, choose this first
 614     for (uint j = 0; j < n->req() ; j++) {
 615       Node *inn = n->in(j);
 616       if (inn) {
 617         if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {
 618           n_choice = 3;
 619           break;
 620         }
 621       }
 622     }
 623 
 624     // MachTemps should be scheduled last so they are near their uses
 625     if (n->is_MachTemp()) {
 626       n_choice = 1;
 627     }
 628 
 629     uint n_latency = get_latency_for_node(n);
 630     uint n_score = n->req();   // Many inputs get high score to break ties
 631 
 632     if (OptoRegScheduling && block_size_threshold_ok) {
 633       if (recalc_pressure_nodes[n->_idx] == 0x7fff7fff) {
 634         _regalloc->_scratch_int_pressure.init(_regalloc->_sched_int_pressure.high_pressure_limit());
 635         _regalloc->_scratch_float_pressure.init(_regalloc->_sched_float_pressure.high_pressure_limit());
 636         // simulate the notion that we just picked this node to schedule
 637         n->add_flag(Node::Flag_is_scheduled);
 638         // now caculate its effect upon the graph if we did
 639         adjust_register_pressure(n, block, recalc_pressure_nodes, false);
 640         // return its state for finalize in case somebody else wins
 641         n->remove_flag(Node::Flag_is_scheduled);
 642         // now save the two final pressure components of register pressure, limiting pressure calcs to short size
 643         short int_pressure = (short)_regalloc->_scratch_int_pressure.current_pressure();
 644         short float_pressure = (short)_regalloc->_scratch_float_pressure.current_pressure();
 645         recalc_pressure_nodes[n->_idx] = int_pressure;
 646         recalc_pressure_nodes[n->_idx] |= (float_pressure << 16);
 647       }
 648 
 649       if (_scheduling_for_pressure) {
 650         latency = n_latency;
 651         if (n_choice != 3) {
 652           // Now evaluate each register pressure component based on threshold in the score.
 653           // In general the defining register type will dominate the score, ergo we will not see register pressure grow on both banks
 654           // on a single instruction, but we might see it shrink on both banks.
 655           // For each use of register that has a register class that is over the high pressure limit, we build n_score up for
 656           // live ranges that terminate on this instruction.
 657           if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
 658             short int_pressure = (short)recalc_pressure_nodes[n->_idx];
 659             n_score = (int_pressure < 0) ? ((score + n_score) - int_pressure) : (int_pressure > 0) ? 1 : n_score;
 660           }
 661           if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
 662             short float_pressure = (short)(recalc_pressure_nodes[n->_idx] >> 16);
 663             n_score = (float_pressure < 0) ? ((score + n_score) - float_pressure) : (float_pressure > 0) ? 1 : n_score;
 664           }
 665         } else {
 666           // make sure we choose these candidates
 667           score = 0;
 668         }
 669       }
 670     }
 671 
 672     // Keep best latency found
 673     cand_cnt++;
 674     if (choice < n_choice ||
 675         (choice == n_choice &&
 676          ((StressLCM && C->randomized_select(cand_cnt)) ||
 677           (!StressLCM &&
 678            (latency < n_latency ||
 679             (latency == n_latency &&
 680              (score < n_score))))))) {
 681       choice  = n_choice;
 682       latency = n_latency;
 683       score   = n_score;
 684       idx     = i;               // Also keep index in worklist
 685     }
 686   } // End of for all ready nodes in worklist
 687 
 688   guarantee(idx >= 0, "index should be set");
 689   Node *n = worklist[(uint)idx];      // Get the winner
 690 
 691   worklist.map((uint)idx, worklist.pop());     // Compress worklist
 692   return n;
 693 }
 694 
 695 //-------------------------adjust_register_pressure----------------------------
 696 void PhaseCFG::adjust_register_pressure(Node* n, Block* block, intptr_t* recalc_pressure_nodes, bool finalize_mode) {
 697   PhaseLive* liveinfo = _regalloc->get_live();
 698   IndexSet* liveout = liveinfo->live(block);
 699   // first adjust the register pressure for the sources
 700   for (uint i = 1; i < n->req(); i++) {
 701     bool lrg_ends = false;
 702     Node *src_n = n->in(i);
 703     if (src_n == NULL) continue;
 704     if (!src_n->is_Mach()) continue;
 705     uint src = _regalloc->_lrg_map.find(src_n);
 706     if (src == 0) continue;
 707     LRG& lrg_src = _regalloc->lrgs(src);
 708     // detect if the live range ends or not
 709     if (liveout->member(src) == false) {
 710       lrg_ends = true;
 711       for (DUIterator_Fast jmax, j = src_n->fast_outs(jmax); j < jmax; j++) {
 712         Node* m = src_n->fast_out(j); // Get user
 713         if (m == n) continue;
 714         if (!m->is_Mach()) continue;
 715         MachNode *mach = m->as_Mach();
 716         bool src_matches = false;
 717         int iop = mach->ideal_Opcode();
 718 
 719         switch (iop) {
 720         case Op_StoreB:
 721         case Op_StoreC:
 722         case Op_StoreCM:
 723         case Op_StoreD:
 724         case Op_StoreF:
 725         case Op_StoreI:
 726         case Op_StoreL:
 727         case Op_StoreP:
 728         case Op_StoreN:
 729         case Op_StoreVector:
 730         case Op_StoreVectorScatter:
 731         case Op_StoreVectorMasked:
 732         case Op_StoreNKlass:
 733           for (uint k = 1; k < m->req(); k++) {
 734             Node *in = m->in(k);
 735             if (in == src_n) {
 736               src_matches = true;
 737               break;
 738             }
 739           }
 740           break;
 741 
 742         default:
 743           src_matches = true;
 744           break;
 745         }
 746 
 747         // If we have a store as our use, ignore the non source operands
 748         if (src_matches == false) continue;
 749 
 750         // Mark every unscheduled use which is not n with a recalculation
 751         if ((get_block_for_node(m) == block) && (!m->is_scheduled())) {
 752           if (finalize_mode && !m->is_Phi()) {
 753             recalc_pressure_nodes[m->_idx] = 0x7fff7fff;
 754           }
 755           lrg_ends = false;
 756         }
 757       }
 758     }
 759     // if none, this live range ends and we can adjust register pressure
 760     if (lrg_ends) {
 761       if (finalize_mode) {
 762         _regalloc->lower_pressure(block, 0, lrg_src, NULL, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
 763       } else {
 764         _regalloc->lower_pressure(block, 0, lrg_src, NULL, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
 765       }
 766     }
 767   }
 768 
 769   // now add the register pressure from the dest and evaluate which heuristic we should use:
 770   // 1.) The default, latency scheduling
 771   // 2.) Register pressure scheduling based on the high pressure limit threshold for int or float register stacks
 772   uint dst = _regalloc->_lrg_map.find(n);
 773   if (dst != 0) {
 774     LRG& lrg_dst = _regalloc->lrgs(dst);
 775     if (finalize_mode) {
 776       _regalloc->raise_pressure(block, lrg_dst, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
 777       // check to see if we fall over the register pressure cliff here
 778       if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
 779         _scheduling_for_pressure = true;
 780       } else if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
 781         _scheduling_for_pressure = true;
 782       } else {
 783         // restore latency scheduling mode
 784         _scheduling_for_pressure = false;
 785       }
 786     } else {
 787       _regalloc->raise_pressure(block, lrg_dst, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
 788     }
 789   }
 790 }
 791 
 792 //------------------------------set_next_call----------------------------------
 793 void PhaseCFG::set_next_call(Block* block, Node* n, VectorSet& next_call) {
 794   if( next_call.test_set(n->_idx) ) return;
 795   for( uint i=0; i<n->len(); i++ ) {
 796     Node *m = n->in(i);
 797     if( !m ) continue;  // must see all nodes in block that precede call
 798     if (get_block_for_node(m) == block) {
 799       set_next_call(block, m, next_call);
 800     }
 801   }
 802 }
 803 
 804 //------------------------------needed_for_next_call---------------------------
 805 // Set the flag 'next_call' for each Node that is needed for the next call to
 806 // be scheduled.  This flag lets me bias scheduling so Nodes needed for the
 807 // next subroutine call get priority - basically it moves things NOT needed
 808 // for the next call till after the call.  This prevents me from trying to
 809 // carry lots of stuff live across a call.
 810 void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) {
 811   // Find the next control-defining Node in this block
 812   Node* call = NULL;
 813   for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {
 814     Node* m = this_call->fast_out(i);
 815     if (get_block_for_node(m) == block && // Local-block user
 816         m != this_call &&       // Not self-start node
 817         m->is_MachCall()) {
 818       call = m;
 819       break;
 820     }
 821   }
 822   if (call == NULL)  return;    // No next call (e.g., block end is near)
 823   // Set next-call for all inputs to this call
 824   set_next_call(block, call, next_call);
 825 }
 826 
 827 //------------------------------add_call_kills-------------------------------------
 828 // helper function that adds caller save registers to MachProjNode
 829 static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) {
 830   // Fill in the kill mask for the call
 831   for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
 832     if( !regs.Member(r) ) {     // Not already defined by the call
 833       // Save-on-call register?
 834       if ((save_policy[r] == 'C') ||
 835           (save_policy[r] == 'A') ||
 836           ((save_policy[r] == 'E') && exclude_soe)) {
 837         proj->_rout.Insert(r);
 838       }
 839     }
 840   }
 841 }
 842 
 843 
 844 //------------------------------sched_call-------------------------------------
 845 uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) {
 846   RegMask regs;
 847 
 848   // Schedule all the users of the call right now.  All the users are
 849   // projection Nodes, so they must be scheduled next to the call.
 850   // Collect all the defined registers.
 851   for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
 852     Node* n = mcall->fast_out(i);
 853     assert( n->is_MachProj(), "" );
 854     int n_cnt = ready_cnt.at(n->_idx)-1;
 855     ready_cnt.at_put(n->_idx, n_cnt);
 856     assert( n_cnt == 0, "" );
 857     // Schedule next to call
 858     block->map_node(n, node_cnt++);
 859     // Collect defined registers
 860     regs.OR(n->out_RegMask());
 861     // Check for scheduling the next control-definer
 862     if( n->bottom_type() == Type::CONTROL )
 863       // Warm up next pile of heuristic bits
 864       needed_for_next_call(block, n, next_call);
 865 
 866     // Children of projections are now all ready
 867     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 868       Node* m = n->fast_out(j); // Get user
 869       if(get_block_for_node(m) != block) {
 870         continue;
 871       }
 872       if( m->is_Phi() ) continue;
 873       int m_cnt = ready_cnt.at(m->_idx) - 1;
 874       ready_cnt.at_put(m->_idx, m_cnt);
 875       if( m_cnt == 0 )
 876         worklist.push(m);
 877     }
 878 
 879   }
 880 
 881   // Act as if the call defines the Frame Pointer.
 882   // Certainly the FP is alive and well after the call.
 883   regs.Insert(_matcher.c_frame_pointer());
 884 
 885   // Set all registers killed and not already defined by the call.
 886   uint r_cnt = mcall->tf()->range_cc()->cnt();
 887   int op = mcall->ideal_Opcode();
 888   MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
 889   map_node_to_block(proj, block);
 890   block->insert_node(proj, node_cnt++);
 891 
 892   // Select the right register save policy.
 893   const char *save_policy = NULL;
 894   switch (op) {
 895     case Op_CallRuntime:
 896     case Op_CallLeaf:
 897     case Op_CallLeafNoFP:
 898     case Op_CallLeafVector:
 899       // Calling C code so use C calling convention
 900       save_policy = _matcher._c_reg_save_policy;
 901       break;
 902 
 903     case Op_CallStaticJava:
 904     case Op_CallDynamicJava:
 905       // Calling Java code so use Java calling convention
 906       save_policy = _matcher._register_save_policy;
 907       break;
 908     case Op_CallNative:
 909       // We use the c reg save policy here since Foreign Linker
 910       // only supports the C ABI currently.
 911       // TODO compute actual save policy based on nep->abi
 912       save_policy = _matcher._c_reg_save_policy;
 913       break;
 914 
 915     default:
 916       ShouldNotReachHere();
 917   }
 918 
 919   // When using CallRuntime mark SOE registers as killed by the call
 920   // so values that could show up in the RegisterMap aren't live in a
 921   // callee saved register since the register wouldn't know where to
 922   // find them.  CallLeaf and CallLeafNoFP are ok because they can't
 923   // have debug info on them.  Strictly speaking this only needs to be
 924   // done for oops since idealreg2debugmask takes care of debug info
 925   // references but there no way to handle oops differently than other
 926   // pointers as far as the kill mask goes.
 927   //
 928   // Also, native callees can not save oops, so we kill the SOE registers
 929   // here in case a native call has a safepoint. This doesn't work for
 930   // RBP though, which seems to be special-cased elsewhere to always be
 931   // treated as alive, so we instead manually save the location of RBP
 932   // before doing the native call (see NativeInvokerGenerator::generate).
 933   bool exclude_soe = op == Op_CallRuntime
 934     || (op == Op_CallNative && mcall->guaranteed_safepoint());
 935 
 936   // If the call is a MethodHandle invoke, we need to exclude the
 937   // register which is used to save the SP value over MH invokes from
 938   // the mask.  Otherwise this register could be used for
 939   // deoptimization information.
 940   if (op == Op_CallStaticJava) {
 941     MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;
 942     if (mcallstaticjava->_method_handle_invoke)
 943       proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());
 944   }
 945 
 946   add_call_kills(proj, regs, save_policy, exclude_soe);
 947 
 948   return node_cnt;
 949 }
 950 
 951 
 952 //------------------------------schedule_local---------------------------------
 953 // Topological sort within a block.  Someday become a real scheduler.
 954 bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t *recalc_pressure_nodes) {
 955   // Already "sorted" are the block start Node (as the first entry), and
 956   // the block-ending Node and any trailing control projections.  We leave
 957   // these alone.  PhiNodes and ParmNodes are made to follow the block start
 958   // Node.  Everything else gets topo-sorted.
 959 
 960 #ifndef PRODUCT
 961     if (trace_opto_pipelining()) {
 962       tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order);
 963       for (uint i = 0;i < block->number_of_nodes(); i++) {
 964         tty->print("# ");
 965         block->get_node(i)->fast_dump();
 966       }
 967       tty->print_cr("#");
 968     }
 969 #endif
 970 
 971   // RootNode is already sorted
 972   if (block->number_of_nodes() == 1) {
 973     return true;
 974   }
 975 
 976   bool block_size_threshold_ok = (recalc_pressure_nodes != NULL) && (block->number_of_nodes() > 10);
 977 
 978   // We track the uses of local definitions as input dependences so that
 979   // we know when a given instruction is avialable to be scheduled.
 980   uint i;
 981   if (OptoRegScheduling && block_size_threshold_ok) {
 982     for (i = 1; i < block->number_of_nodes(); i++) { // setup nodes for pressure calc
 983       Node *n = block->get_node(i);
 984       n->remove_flag(Node::Flag_is_scheduled);
 985       if (!n->is_Phi()) {
 986         recalc_pressure_nodes[n->_idx] = 0x7fff7fff;
 987       }
 988     }
 989   }
 990 
 991   // Move PhiNodes and ParmNodes from 1 to cnt up to the start
 992   uint node_cnt = block->end_idx();
 993   uint phi_cnt = 1;
 994   for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
 995     Node *n = block->get_node(i);
 996     if( n->is_Phi() ||          // Found a PhiNode or ParmNode
 997         (n->is_Proj()  && n->in(0) == block->head()) ) {
 998       // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
 999       block->map_node(block->get_node(phi_cnt), i);
1000       block->map_node(n, phi_cnt++);  // swap Phi/Parm up front
1001       if (OptoRegScheduling && block_size_threshold_ok) {
1002         // mark n as scheduled
1003         n->add_flag(Node::Flag_is_scheduled);
1004       }
1005     } else {                    // All others
1006       // Count block-local inputs to 'n'
1007       uint cnt = n->len();      // Input count
1008       uint local = 0;
1009       for( uint j=0; j<cnt; j++ ) {
1010         Node *m = n->in(j);
1011         if( m && get_block_for_node(m) == block && !m->is_top() )
1012           local++;              // One more block-local input
1013       }
1014       ready_cnt.at_put(n->_idx, local); // Count em up
1015 
1016 #ifdef ASSERT
1017       if (UseG1GC) {
1018         if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_StoreCM ) {
1019           // Check the precedence edges
1020           for (uint prec = n->req(); prec < n->len(); prec++) {
1021             Node* oop_store = n->in(prec);
1022             if (oop_store != NULL) {
1023               assert(get_block_for_node(oop_store)->_dom_depth <= block->_dom_depth, "oop_store must dominate card-mark");
1024             }
1025           }
1026         }
1027       }
1028 #endif
1029 
1030       // A few node types require changing a required edge to a precedence edge
1031       // before allocation.
1032       if( n->is_Mach() && n->req() > TypeFunc::Parms &&
1033           (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
1034            n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
1035         // MemBarAcquire could be created without Precedent edge.
1036         // del_req() replaces the specified edge with the last input edge
1037         // and then removes the last edge. If the specified edge > number of
1038         // edges the last edge will be moved outside of the input edges array
1039         // and the edge will be lost. This is why this code should be
1040         // executed only when Precedent (== TypeFunc::Parms) edge is present.
1041         Node *x = n->in(TypeFunc::Parms);
1042         if (x != NULL && get_block_for_node(x) == block && n->find_prec_edge(x) != -1) {
1043           // Old edge to node within same block will get removed, but no precedence
1044           // edge will get added because it already exists. Update ready count.
1045           int cnt = ready_cnt.at(n->_idx);
1046           assert(cnt > 1, "MemBar node %d must not get ready here", n->_idx);
1047           ready_cnt.at_put(n->_idx, cnt-1);
1048         }
1049         n->del_req(TypeFunc::Parms);
1050         n->add_prec(x);
1051       }
1052     }
1053   }
1054   for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count
1055     ready_cnt.at_put(block->get_node(i2)->_idx, 0);
1056 
1057   // All the prescheduled guys do not hold back internal nodes
1058   uint i3;
1059   for (i3 = 0; i3 < phi_cnt; i3++) {  // For all pre-scheduled
1060     Node *n = block->get_node(i3);       // Get pre-scheduled
1061     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1062       Node* m = n->fast_out(j);
1063       if (get_block_for_node(m) == block) { // Local-block user
1064         int m_cnt = ready_cnt.at(m->_idx)-1;
1065         if (OptoRegScheduling && block_size_threshold_ok) {
1066           // mark m as scheduled
1067           if (m_cnt < 0) {
1068             m->add_flag(Node::Flag_is_scheduled);
1069           }
1070         }
1071         ready_cnt.at_put(m->_idx, m_cnt);   // Fix ready count
1072       }
1073     }
1074   }
1075 
1076   Node_List delay;
1077   // Make a worklist
1078   Node_List worklist;
1079   for(uint i4=i3; i4<node_cnt; i4++ ) {    // Put ready guys on worklist
1080     Node *m = block->get_node(i4);
1081     if( !ready_cnt.at(m->_idx) ) {   // Zero ready count?
1082       if (m->is_iteratively_computed()) {
1083         // Push induction variable increments last to allow other uses
1084         // of the phi to be scheduled first. The select() method breaks
1085         // ties in scheduling by worklist order.
1086         delay.push(m);
1087       } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
1088         // Force the CreateEx to the top of the list so it's processed
1089         // first and ends up at the start of the block.
1090         worklist.insert(0, m);
1091       } else {
1092         worklist.push(m);         // Then on to worklist!
1093       }
1094     }
1095   }
1096   while (delay.size()) {
1097     Node* d = delay.pop();
1098     worklist.push(d);
1099   }
1100 
1101   if (OptoRegScheduling && block_size_threshold_ok) {
1102     // To stage register pressure calculations we need to examine the live set variables
1103     // breaking them up by register class to compartmentalize the calculations.
1104     _regalloc->_sched_int_pressure.init(Matcher::int_pressure_limit());
1105     _regalloc->_sched_float_pressure.init(Matcher::float_pressure_limit());
1106     _regalloc->_scratch_int_pressure.init(Matcher::int_pressure_limit());
1107     _regalloc->_scratch_float_pressure.init(Matcher::float_pressure_limit());
1108 
1109     _regalloc->compute_entry_block_pressure(block);
1110   }
1111 
1112   // Warm up the 'next_call' heuristic bits
1113   needed_for_next_call(block, block->head(), next_call);
1114 
1115 #ifndef PRODUCT
1116     if (trace_opto_pipelining()) {
1117       for (uint j=0; j< block->number_of_nodes(); j++) {
1118         Node     *n = block->get_node(j);
1119         int     idx = n->_idx;
1120         tty->print("#   ready cnt:%3d  ", ready_cnt.at(idx));
1121         tty->print("latency:%3d  ", get_latency_for_node(n));
1122         tty->print("%4d: %s\n", idx, n->Name());
1123       }
1124     }
1125 #endif
1126 
1127   uint max_idx = (uint)ready_cnt.length();
1128   // Pull from worklist and schedule
1129   while( worklist.size() ) {    // Worklist is not ready
1130 
1131 #ifndef PRODUCT
1132     if (trace_opto_pipelining()) {
1133       tty->print("#   ready list:");
1134       for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1135         Node *n = worklist[i];      // Get Node on worklist
1136         tty->print(" %d", n->_idx);
1137       }
1138       tty->cr();
1139     }
1140 #endif
1141 
1142     // Select and pop a ready guy from worklist
1143     Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt, recalc_pressure_nodes);
1144     block->map_node(n, phi_cnt++);    // Schedule him next
1145 
1146     if (OptoRegScheduling && block_size_threshold_ok) {
1147       n->add_flag(Node::Flag_is_scheduled);
1148 
1149       // Now adjust the resister pressure with the node we selected
1150       if (!n->is_Phi()) {
1151         adjust_register_pressure(n, block, recalc_pressure_nodes, true);
1152       }
1153     }
1154 
1155 #ifndef PRODUCT
1156     if (trace_opto_pipelining()) {
1157       tty->print("#    select %d: %s", n->_idx, n->Name());
1158       tty->print(", latency:%d", get_latency_for_node(n));
1159       n->dump();
1160       if (Verbose) {
1161         tty->print("#   ready list:");
1162         for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1163           Node *n = worklist[i];      // Get Node on worklist
1164           tty->print(" %d", n->_idx);
1165         }
1166         tty->cr();
1167       }
1168     }
1169 
1170 #endif
1171     if( n->is_MachCall() ) {
1172       MachCallNode *mcall = n->as_MachCall();
1173       phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call);
1174       continue;
1175     }
1176 
1177     if (n->is_Mach() && n->as_Mach()->has_call()) {
1178       RegMask regs;
1179       regs.Insert(_matcher.c_frame_pointer());
1180       regs.OR(n->out_RegMask());
1181 
1182       MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );
1183       map_node_to_block(proj, block);
1184       block->insert_node(proj, phi_cnt++);
1185 
1186       add_call_kills(proj, regs, _matcher._c_reg_save_policy, false);
1187     }
1188 
1189     // Children are now all ready
1190     for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
1191       Node* m = n->fast_out(i5); // Get user
1192       if (get_block_for_node(m) != block) {
1193         continue;
1194       }
1195       if( m->is_Phi() ) continue;
1196       if (m->_idx >= max_idx) { // new node, skip it
1197         assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");
1198         continue;
1199       }
1200       int m_cnt = ready_cnt.at(m->_idx) - 1;
1201       ready_cnt.at_put(m->_idx, m_cnt);
1202       if( m_cnt == 0 )
1203         worklist.push(m);
1204     }
1205   }
1206 
1207   if( phi_cnt != block->end_idx() ) {
1208     // did not schedule all.  Retry, Bailout, or Die
1209     if (C->subsume_loads() == true && !C->failing()) {
1210       // Retry with subsume_loads == false
1211       // If this is the first failure, the sentinel string will "stick"
1212       // to the Compile object, and the C2Compiler will see it and retry.
1213       C->record_failure(C2Compiler::retry_no_subsuming_loads());
1214     } else {
1215       assert(false, "graph should be schedulable");
1216     }
1217     // assert( phi_cnt == end_idx(), "did not schedule all" );
1218     return false;
1219   }
1220 
1221   if (OptoRegScheduling && block_size_threshold_ok) {
1222     _regalloc->compute_exit_block_pressure(block);
1223     block->_reg_pressure = _regalloc->_sched_int_pressure.final_pressure();
1224     block->_freg_pressure = _regalloc->_sched_float_pressure.final_pressure();
1225   }
1226 
1227 #ifndef PRODUCT
1228   if (trace_opto_pipelining()) {
1229     tty->print_cr("#");
1230     tty->print_cr("# after schedule_local");
1231     for (uint i = 0;i < block->number_of_nodes();i++) {
1232       tty->print("# ");
1233       block->get_node(i)->fast_dump();
1234     }
1235     tty->print_cr("# ");
1236 
1237     if (OptoRegScheduling && block_size_threshold_ok) {
1238       tty->print_cr("# pressure info : %d", block->_pre_order);
1239       _regalloc->print_pressure_info(_regalloc->_sched_int_pressure, "int register info");
1240       _regalloc->print_pressure_info(_regalloc->_sched_float_pressure, "float register info");
1241     }
1242     tty->cr();
1243   }
1244 #endif
1245 
1246   return true;
1247 }
1248 
1249 //--------------------------catch_cleanup_fix_all_inputs-----------------------
1250 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {
1251   for (uint l = 0; l < use->len(); l++) {
1252     if (use->in(l) == old_def) {
1253       if (l < use->req()) {
1254         use->set_req(l, new_def);
1255       } else {
1256         use->rm_prec(l);
1257         use->add_prec(new_def);
1258         l--;
1259       }
1260     }
1261   }
1262 }
1263 
1264 //------------------------------catch_cleanup_find_cloned_def------------------
1265 Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1266   assert( use_blk != def_blk, "Inter-block cleanup only");
1267 
1268   // The use is some block below the Catch.  Find and return the clone of the def
1269   // that dominates the use. If there is no clone in a dominating block, then
1270   // create a phi for the def in a dominating block.
1271 
1272   // Find which successor block dominates this use.  The successor
1273   // blocks must all be single-entry (from the Catch only; I will have
1274   // split blocks to make this so), hence they all dominate.
1275   while( use_blk->_dom_depth > def_blk->_dom_depth+1 )
1276     use_blk = use_blk->_idom;
1277 
1278   // Find the successor
1279   Node *fixup = NULL;
1280 
1281   uint j;
1282   for( j = 0; j < def_blk->_num_succs; j++ )
1283     if( use_blk == def_blk->_succs[j] )
1284       break;
1285 
1286   if( j == def_blk->_num_succs ) {
1287     // Block at same level in dom-tree is not a successor.  It needs a
1288     // PhiNode, the PhiNode uses from the def and IT's uses need fixup.
1289     Node_Array inputs = new Node_List();
1290     for(uint k = 1; k < use_blk->num_preds(); k++) {
1291       Block* block = get_block_for_node(use_blk->pred(k));
1292       inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx));
1293     }
1294 
1295     // Check to see if the use_blk already has an identical phi inserted.
1296     // If it exists, it will be at the first position since all uses of a
1297     // def are processed together.
1298     Node *phi = use_blk->get_node(1);
1299     if( phi->is_Phi() ) {
1300       fixup = phi;
1301       for (uint k = 1; k < use_blk->num_preds(); k++) {
1302         if (phi->in(k) != inputs[k]) {
1303           // Not a match
1304           fixup = NULL;
1305           break;
1306         }
1307       }
1308     }
1309 
1310     // If an existing PhiNode was not found, make a new one.
1311     if (fixup == NULL) {
1312       Node *new_phi = PhiNode::make(use_blk->head(), def);
1313       use_blk->insert_node(new_phi, 1);
1314       map_node_to_block(new_phi, use_blk);
1315       for (uint k = 1; k < use_blk->num_preds(); k++) {
1316         new_phi->set_req(k, inputs[k]);
1317       }
1318       fixup = new_phi;
1319     }
1320 
1321   } else {
1322     // Found the use just below the Catch.  Make it use the clone.
1323     fixup = use_blk->get_node(n_clone_idx);
1324   }
1325 
1326   return fixup;
1327 }
1328 
1329 //--------------------------catch_cleanup_intra_block--------------------------
1330 // Fix all input edges in use that reference "def".  The use is in the same
1331 // block as the def and both have been cloned in each successor block.
1332 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {
1333 
1334   // Both the use and def have been cloned. For each successor block,
1335   // get the clone of the use, and make its input the clone of the def
1336   // found in that block.
1337 
1338   uint use_idx = blk->find_node(use);
1339   uint offset_idx = use_idx - beg;
1340   for( uint k = 0; k < blk->_num_succs; k++ ) {
1341     // Get clone in each successor block
1342     Block *sb = blk->_succs[k];
1343     Node *clone = sb->get_node(offset_idx+1);
1344     assert( clone->Opcode() == use->Opcode(), "" );
1345 
1346     // Make use-clone reference the def-clone
1347     catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx));
1348   }
1349 }
1350 
1351 //------------------------------catch_cleanup_inter_block---------------------
1352 // Fix all input edges in use that reference "def".  The use is in a different
1353 // block than the def.
1354 void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1355   if( !use_blk ) return;        // Can happen if the use is a precedence edge
1356 
1357   Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx);
1358   catch_cleanup_fix_all_inputs(use, def, new_def);
1359 }
1360 
1361 //------------------------------call_catch_cleanup-----------------------------
1362 // If we inserted any instructions between a Call and his CatchNode,
1363 // clone the instructions on all paths below the Catch.
1364 void PhaseCFG::call_catch_cleanup(Block* block) {
1365 
1366   // End of region to clone
1367   uint end = block->end_idx();
1368   if( !block->get_node(end)->is_Catch() ) return;
1369   // Start of region to clone
1370   uint beg = end;
1371   while(!block->get_node(beg-1)->is_MachProj() ||
1372         !block->get_node(beg-1)->in(0)->is_MachCall() ) {
1373     beg--;
1374     assert(beg > 0,"Catch cleanup walking beyond block boundary");
1375   }
1376   // Range of inserted instructions is [beg, end)
1377   if( beg == end ) return;
1378 
1379   // Clone along all Catch output paths.  Clone area between the 'beg' and
1380   // 'end' indices.
1381   for( uint i = 0; i < block->_num_succs; i++ ) {
1382     Block *sb = block->_succs[i];
1383     // Clone the entire area; ignoring the edge fixup for now.
1384     for( uint j = end; j > beg; j-- ) {
1385       Node *clone = block->get_node(j-1)->clone();
1386       sb->insert_node(clone, 1);
1387       map_node_to_block(clone, sb);
1388       if (clone->needs_anti_dependence_check()) {
1389         insert_anti_dependences(sb, clone);
1390       }
1391     }
1392   }
1393 
1394 
1395   // Fixup edges.  Check the def-use info per cloned Node
1396   for(uint i2 = beg; i2 < end; i2++ ) {
1397     uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block
1398     Node *n = block->get_node(i2);        // Node that got cloned
1399     // Need DU safe iterator because of edge manipulation in calls.
1400     Unique_Node_List* out = new Unique_Node_List();
1401     for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {
1402       out->push(n->fast_out(j1));
1403     }
1404     uint max = out->size();
1405     for (uint j = 0; j < max; j++) {// For all users
1406       Node *use = out->pop();
1407       Block *buse = get_block_for_node(use);
1408       if( use->is_Phi() ) {
1409         for( uint k = 1; k < use->req(); k++ )
1410           if( use->in(k) == n ) {
1411             Block* b = get_block_for_node(buse->pred(k));
1412             Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx);
1413             use->set_req(k, fixup);
1414           }
1415       } else {
1416         if (block == buse) {
1417           catch_cleanup_intra_block(use, n, block, beg, n_clone_idx);
1418         } else {
1419           catch_cleanup_inter_block(use, buse, n, block, n_clone_idx);
1420         }
1421       }
1422     } // End for all users
1423 
1424   } // End of for all Nodes in cloned area
1425 
1426   // Remove the now-dead cloned ops
1427   for(uint i3 = beg; i3 < end; i3++ ) {
1428     block->get_node(beg)->disconnect_inputs(C);
1429     block->remove_node(beg);
1430   }
1431 
1432   // If the successor blocks have a CreateEx node, move it back to the top
1433   for (uint i4 = 0; i4 < block->_num_succs; i4++) {
1434     Block *sb = block->_succs[i4];
1435     uint new_cnt = end - beg;
1436     // Remove any newly created, but dead, nodes by traversing their schedule
1437     // backwards. Here, a dead node is a node whose only outputs (if any) are
1438     // unused projections.
1439     for (uint j = new_cnt; j > 0; j--) {
1440       Node *n = sb->get_node(j);
1441       // Individual projections are examined together with all siblings when
1442       // their parent is visited.
1443       if (n->is_Proj()) {
1444         continue;
1445       }
1446       bool dead = true;
1447       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1448         Node* out = n->fast_out(i);
1449         // n is live if it has a non-projection output or a used projection.
1450         if (!out->is_Proj() || out->outcnt() > 0) {
1451           dead = false;
1452           break;
1453         }
1454       }
1455       if (dead) {
1456         // n's only outputs (if any) are unused projections scheduled next to n
1457         // (see PhaseCFG::select()). Remove these projections backwards.
1458         for (uint k = j + n->outcnt(); k > j; k--) {
1459           Node* proj = sb->get_node(k);
1460           assert(proj->is_Proj() && proj->in(0) == n,
1461                  "projection should correspond to dead node");
1462           proj->disconnect_inputs(C);
1463           sb->remove_node(k);
1464           new_cnt--;
1465         }
1466         // Now remove the node itself.
1467         n->disconnect_inputs(C);
1468         sb->remove_node(j);
1469         new_cnt--;
1470       }
1471     }
1472     // If any newly created nodes remain, move the CreateEx node to the top
1473     if (new_cnt > 0) {
1474       Node *cex = sb->get_node(1+new_cnt);
1475       if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1476         sb->remove_node(1+new_cnt);
1477         sb->insert_node(cex, 1);
1478       }
1479     }
1480   }
1481 }