1 /*
   2  * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "memory/allocation.inline.hpp"
  27 #include "opto/ad.hpp"
  28 #include "opto/block.hpp"
  29 #include "opto/c2compiler.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/cfgnode.hpp"
  32 #include "opto/machnode.hpp"
  33 #include "opto/runtime.hpp"
  34 
  35 // Optimization - Graph Style
  36 
  37 // Check whether val is not-null-decoded compressed oop,
  38 // i.e. will grab into the base of the heap if it represents NULL.
  39 static bool accesses_heap_base_zone(Node *val) {
  40   if (Universe::narrow_oop_base() > 0) { // Implies UseCompressedOops.
  41     if (val && val->is_Mach()) {
  42       if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) {
  43         // This assumes all Decodes with TypePtr::NotNull are matched to nodes that
  44         // decode NULL to point to the heap base (Decode_NN).
  45         if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) {
  46           return true;
  47         }
  48       }
  49       // Must recognize load operation with Decode matched in memory operand.
  50       // We should not reach here exept for PPC/AIX, as os::zero_page_read_protected()
  51       // returns true everywhere else. On PPC, no such memory operands
  52       // exist, therefore we did not yet implement a check for such operands.
  53       NOT_AIX(Unimplemented());
  54     }
  55   }
  56   return false;
  57 }
  58 
  59 static bool needs_explicit_null_check_for_read(Node *val) {
  60   // On some OSes (AIX) the page at address 0 is only write protected.
  61   // If so, only Store operations will trap.
  62   if (os::zero_page_read_protected()) {
  63     return false;  // Implicit null check will work.
  64   }
  65   // Also a read accessing the base of a heap-based compressed heap will trap.
  66   if (accesses_heap_base_zone(val) &&                    // Hits the base zone page.
  67       Universe::narrow_oop_use_implicit_null_checks()) { // Base zone page is protected.
  68     return false;
  69   }
  70 
  71   return true;
  72 }
  73 
  74 //------------------------------implicit_null_check----------------------------
  75 // Detect implicit-null-check opportunities.  Basically, find NULL checks
  76 // with suitable memory ops nearby.  Use the memory op to do the NULL check.
  77 // I can generate a memory op if there is not one nearby.
  78 // The proj is the control projection for the not-null case.
  79 // The val is the pointer being checked for nullness or
  80 // decodeHeapOop_not_null node if it did not fold into address.
  81 void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) {
  82   // Assume if null check need for 0 offset then always needed
  83   // Intel solaris doesn't support any null checks yet and no
  84   // mechanism exists (yet) to set the switches at an os_cpu level
  85   if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;
  86 
  87   // Make sure the ptr-is-null path appears to be uncommon!
  88   float f = block->end()->as_MachIf()->_prob;
  89   if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;
  90   if( f > PROB_UNLIKELY_MAG(4) ) return;
  91 
  92   uint bidx = 0;                // Capture index of value into memop
  93   bool was_store;               // Memory op is a store op
  94 
  95   // Get the successor block for if the test ptr is non-null
  96   Block* not_null_block;  // this one goes with the proj
  97   Block* null_block;
  98   if (block->get_node(block->number_of_nodes()-1) == proj) {
  99     null_block     = block->_succs[0];
 100     not_null_block = block->_succs[1];
 101   } else {
 102     assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other");
 103     not_null_block = block->_succs[0];
 104     null_block     = block->_succs[1];
 105   }
 106   while (null_block->is_Empty() == Block::empty_with_goto) {
 107     null_block     = null_block->_succs[0];
 108   }
 109 
 110   // Search the exception block for an uncommon trap.
 111   // (See Parse::do_if and Parse::do_ifnull for the reason
 112   // we need an uncommon trap.  Briefly, we need a way to
 113   // detect failure of this optimization, as in 6366351.)
 114   {
 115     bool found_trap = false;
 116     for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) {
 117       Node* nn = null_block->get_node(i1);
 118       if (nn->is_MachCall() &&
 119           nn->as_MachCall()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point()) {
 120         const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();
 121         if (trtype->isa_int() && trtype->is_int()->is_con()) {
 122           jint tr_con = trtype->is_int()->get_con();
 123           Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
 124           Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
 125           assert((int)reason < (int)BitsPerInt, "recode bit map");
 126           if (is_set_nth_bit(allowed_reasons, (int) reason)
 127               && action != Deoptimization::Action_none) {
 128             // This uncommon trap is sure to recompile, eventually.
 129             // When that happens, C->too_many_traps will prevent
 130             // this transformation from happening again.
 131             found_trap = true;
 132           }
 133         }
 134         break;
 135       }
 136     }
 137     if (!found_trap) {
 138       // We did not find an uncommon trap.
 139       return;
 140     }
 141   }
 142 
 143   // Check for decodeHeapOop_not_null node which did not fold into address
 144   bool is_decoden = ((intptr_t)val) & 1;
 145   val = (Node*)(((intptr_t)val) & ~1);
 146 
 147   assert(!is_decoden || (val->in(0) == NULL) && val->is_Mach() &&
 148          (val->as_Mach()->ideal_Opcode() == Op_DecodeN), "sanity");
 149 
 150   // Search the successor block for a load or store who's base value is also
 151   // the tested value.  There may be several.
 152   Node_List *out = new Node_List(Thread::current()->resource_area());
 153   MachNode *best = NULL;        // Best found so far
 154   for (DUIterator i = val->outs(); val->has_out(i); i++) {
 155     Node *m = val->out(i);
 156     if( !m->is_Mach() ) continue;
 157     MachNode *mach = m->as_Mach();
 158     was_store = false;
 159     int iop = mach->ideal_Opcode();
 160     switch( iop ) {
 161     case Op_LoadB:
 162     case Op_LoadUB:
 163     case Op_LoadUS:
 164     case Op_LoadD:
 165     case Op_LoadF:
 166     case Op_LoadI:
 167     case Op_LoadL:
 168     case Op_LoadP:
 169     case Op_LoadN:
 170     case Op_LoadS:
 171     case Op_LoadKlass:
 172     case Op_LoadNKlass:
 173     case Op_LoadRange:
 174     case Op_LoadD_unaligned:
 175     case Op_LoadL_unaligned:
 176       assert(mach->in(2) == val, "should be address");
 177       break;
 178     case Op_StoreB:
 179     case Op_StoreC:
 180     case Op_StoreCM:
 181     case Op_StoreD:
 182     case Op_StoreF:
 183     case Op_StoreI:
 184     case Op_StoreL:
 185     case Op_StoreP:
 186     case Op_StoreN:
 187     case Op_StoreNKlass:
 188       was_store = true;         // Memory op is a store op
 189       // Stores will have their address in slot 2 (memory in slot 1).
 190       // If the value being nul-checked is in another slot, it means we
 191       // are storing the checked value, which does NOT check the value!
 192       if( mach->in(2) != val ) continue;
 193       break;                    // Found a memory op?
 194     case Op_StrComp:
 195     case Op_StrEquals:
 196     case Op_StrIndexOf:
 197     case Op_AryEq:
 198     case Op_EncodeISOArray:
 199       // Not a legit memory op for implicit null check regardless of
 200       // embedded loads
 201       continue;
 202     default:                    // Also check for embedded loads
 203       if( !mach->needs_anti_dependence_check() )
 204         continue;               // Not an memory op; skip it
 205       if( must_clone[iop] ) {
 206         // Do not move nodes which produce flags because
 207         // RA will try to clone it to place near branch and
 208         // it will cause recompilation, see clone_node().
 209         continue;
 210       }
 211       {
 212         // Check that value is used in memory address in
 213         // instructions with embedded load (CmpP val1,(val2+off)).
 214         Node* base;
 215         Node* index;
 216         const MachOper* oper = mach->memory_inputs(base, index);
 217         if (oper == NULL || oper == (MachOper*)-1) {
 218           continue;             // Not an memory op; skip it
 219         }
 220         if (val == base ||
 221             val == index && val->bottom_type()->isa_narrowoop()) {
 222           break;                // Found it
 223         } else {
 224           continue;             // Skip it
 225         }
 226       }
 227       break;
 228     }
 229 
 230     // On some OSes (AIX) the page at address 0 is only write protected.
 231     // If so, only Store operations will trap.
 232     // But a read accessing the base of a heap-based compressed heap will trap.
 233     if (!was_store && needs_explicit_null_check_for_read(val)) {
 234       continue;
 235     }
 236 
 237     // check if the offset is not too high for implicit exception
 238     {
 239       intptr_t offset = 0;
 240       const TypePtr *adr_type = NULL;  // Do not need this return value here
 241       const Node* base = mach->get_base_and_disp(offset, adr_type);
 242       if (base == NULL || base == NodeSentinel) {
 243         // Narrow oop address doesn't have base, only index
 244         if( val->bottom_type()->isa_narrowoop() &&
 245             MacroAssembler::needs_explicit_null_check(offset) )
 246           continue;             // Give up if offset is beyond page size
 247         // cannot reason about it; is probably not implicit null exception
 248       } else {
 249         const TypePtr* tptr;
 250         if (UseCompressedOops && (Universe::narrow_oop_shift() == 0 ||
 251                                   Universe::narrow_klass_shift() == 0)) {
 252           // 32-bits narrow oop can be the base of address expressions
 253           tptr = base->get_ptr_type();
 254         } else {
 255           // only regular oops are expected here
 256           tptr = base->bottom_type()->is_ptr();
 257         }
 258         // Give up if offset is not a compile-time constant
 259         if( offset == Type::OffsetBot || tptr->_offset == Type::OffsetBot )
 260           continue;
 261         offset += tptr->_offset; // correct if base is offseted
 262         if( MacroAssembler::needs_explicit_null_check(offset) )
 263           continue;             // Give up is reference is beyond 4K page size
 264       }
 265     }
 266 
 267     // Check ctrl input to see if the null-check dominates the memory op
 268     Block *cb = get_block_for_node(mach);
 269     cb = cb->_idom;             // Always hoist at least 1 block
 270     if( !was_store ) {          // Stores can be hoisted only one block
 271       while( cb->_dom_depth > (block->_dom_depth + 1))
 272         cb = cb->_idom;         // Hoist loads as far as we want
 273       // The non-null-block should dominate the memory op, too. Live
 274       // range spilling will insert a spill in the non-null-block if it is
 275       // needs to spill the memory op for an implicit null check.
 276       if (cb->_dom_depth == (block->_dom_depth + 1)) {
 277         if (cb != not_null_block) continue;
 278         cb = cb->_idom;
 279       }
 280     }
 281     if( cb != block ) continue;
 282 
 283     // Found a memory user; see if it can be hoisted to check-block
 284     uint vidx = 0;              // Capture index of value into memop
 285     uint j;
 286     for( j = mach->req()-1; j > 0; j-- ) {
 287       if( mach->in(j) == val ) {
 288         vidx = j;
 289         // Ignore DecodeN val which could be hoisted to where needed.
 290         if( is_decoden ) continue;
 291       }
 292       // Block of memory-op input
 293       Block *inb = get_block_for_node(mach->in(j));
 294       Block *b = block;          // Start from nul check
 295       while( b != inb && b->_dom_depth > inb->_dom_depth )
 296         b = b->_idom;           // search upwards for input
 297       // See if input dominates null check
 298       if( b != inb )
 299         break;
 300     }
 301     if( j > 0 )
 302       continue;
 303     Block *mb = get_block_for_node(mach);
 304     // Hoisting stores requires more checks for the anti-dependence case.
 305     // Give up hoisting if we have to move the store past any load.
 306     if( was_store ) {
 307       Block *b = mb;            // Start searching here for a local load
 308       // mach use (faulting) trying to hoist
 309       // n might be blocker to hoisting
 310       while( b != block ) {
 311         uint k;
 312         for( k = 1; k < b->number_of_nodes(); k++ ) {
 313           Node *n = b->get_node(k);
 314           if( n->needs_anti_dependence_check() &&
 315               n->in(LoadNode::Memory) == mach->in(StoreNode::Memory) )
 316             break;              // Found anti-dependent load
 317         }
 318         if( k < b->number_of_nodes() )
 319           break;                // Found anti-dependent load
 320         // Make sure control does not do a merge (would have to check allpaths)
 321         if( b->num_preds() != 2 ) break;
 322         b = get_block_for_node(b->pred(1)); // Move up to predecessor block
 323       }
 324       if( b != block ) continue;
 325     }
 326 
 327     // Make sure this memory op is not already being used for a NullCheck
 328     Node *e = mb->end();
 329     if( e->is_MachNullCheck() && e->in(1) == mach )
 330       continue;                 // Already being used as a NULL check
 331 
 332     // Found a candidate!  Pick one with least dom depth - the highest
 333     // in the dom tree should be closest to the null check.
 334     if (best == NULL || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) {
 335       best = mach;
 336       bidx = vidx;
 337     }
 338   }
 339   // No candidate!
 340   if (best == NULL) {
 341     return;
 342   }
 343 
 344   // ---- Found an implicit null check
 345   extern int implicit_null_checks;
 346   implicit_null_checks++;
 347 
 348   if( is_decoden ) {
 349     // Check if we need to hoist decodeHeapOop_not_null first.
 350     Block *valb = get_block_for_node(val);
 351     if( block != valb && block->_dom_depth < valb->_dom_depth ) {
 352       // Hoist it up to the end of the test block.
 353       valb->find_remove(val);
 354       block->add_inst(val);
 355       map_node_to_block(val, block);
 356       // DecodeN on x86 may kill flags. Check for flag-killing projections
 357       // that also need to be hoisted.
 358       for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
 359         Node* n = val->fast_out(j);
 360         if( n->is_MachProj() ) {
 361           get_block_for_node(n)->find_remove(n);
 362           block->add_inst(n);
 363           map_node_to_block(n, block);
 364         }
 365       }
 366     }
 367   }
 368   // Hoist the memory candidate up to the end of the test block.
 369   Block *old_block = get_block_for_node(best);
 370   old_block->find_remove(best);
 371   block->add_inst(best);
 372   map_node_to_block(best, block);
 373 
 374   // Move the control dependence
 375   if (best->in(0) && best->in(0) == old_block->head())
 376     best->set_req(0, block->head());
 377 
 378   // Check for flag-killing projections that also need to be hoisted
 379   // Should be DU safe because no edge updates.
 380   for (DUIterator_Fast jmax, j = best->fast_outs(jmax); j < jmax; j++) {
 381     Node* n = best->fast_out(j);
 382     if( n->is_MachProj() ) {
 383       get_block_for_node(n)->find_remove(n);
 384       block->add_inst(n);
 385       map_node_to_block(n, block);
 386     }
 387   }
 388 
 389   // proj==Op_True --> ne test; proj==Op_False --> eq test.
 390   // One of two graph shapes got matched:
 391   //   (IfTrue  (If (Bool NE (CmpP ptr NULL))))
 392   //   (IfFalse (If (Bool EQ (CmpP ptr NULL))))
 393   // NULL checks are always branch-if-eq.  If we see a IfTrue projection
 394   // then we are replacing a 'ne' test with a 'eq' NULL check test.
 395   // We need to flip the projections to keep the same semantics.
 396   if( proj->Opcode() == Op_IfTrue ) {
 397     // Swap order of projections in basic block to swap branch targets
 398     Node *tmp1 = block->get_node(block->end_idx()+1);
 399     Node *tmp2 = block->get_node(block->end_idx()+2);
 400     block->map_node(tmp2, block->end_idx()+1);
 401     block->map_node(tmp1, block->end_idx()+2);
 402     Node *tmp = new Node(C->top()); // Use not NULL input
 403     tmp1->replace_by(tmp);
 404     tmp2->replace_by(tmp1);
 405     tmp->replace_by(tmp2);
 406     tmp->destruct();
 407   }
 408 
 409   // Remove the existing null check; use a new implicit null check instead.
 410   // Since schedule-local needs precise def-use info, we need to correct
 411   // it as well.
 412   Node *old_tst = proj->in(0);
 413   MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx);
 414   block->map_node(nul_chk, block->end_idx());
 415   map_node_to_block(nul_chk, block);
 416   // Redirect users of old_test to nul_chk
 417   for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)
 418     old_tst->last_out(i2)->set_req(0, nul_chk);
 419   // Clean-up any dead code
 420   for (uint i3 = 0; i3 < old_tst->req(); i3++)
 421     old_tst->set_req(i3, NULL);
 422 
 423   latency_from_uses(nul_chk);
 424   latency_from_uses(best);
 425 }
 426 
 427 
 428 //------------------------------select-----------------------------------------
 429 // Select a nice fellow from the worklist to schedule next. If there is only
 430 // one choice, then use it. Projections take top priority for correctness
 431 // reasons - if I see a projection, then it is next.  There are a number of
 432 // other special cases, for instructions that consume condition codes, et al.
 433 // These are chosen immediately. Some instructions are required to immediately
 434 // precede the last instruction in the block, and these are taken last. Of the
 435 // remaining cases (most), choose the instruction with the greatest latency
 436 // (that is, the most number of pseudo-cycles required to the end of the
 437 // routine). If there is a tie, choose the instruction with the most inputs.
 438 Node* PhaseCFG::select(Block* block, Node_List &worklist, GrowableArray<int> &ready_cnt, VectorSet &next_call, uint sched_slot) {
 439 
 440   // If only a single entry on the stack, use it
 441   uint cnt = worklist.size();
 442   if (cnt == 1) {
 443     Node *n = worklist[0];
 444     worklist.map(0,worklist.pop());
 445     return n;
 446   }
 447 
 448   uint choice  = 0; // Bigger is most important
 449   uint latency = 0; // Bigger is scheduled first
 450   uint score   = 0; // Bigger is better
 451   int idx = -1;     // Index in worklist
 452   int cand_cnt = 0; // Candidate count
 453 
 454   for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
 455     // Order in worklist is used to break ties.
 456     // See caller for how this is used to delay scheduling
 457     // of induction variable increments to after the other
 458     // uses of the phi are scheduled.
 459     Node *n = worklist[i];      // Get Node on worklist
 460 
 461     int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;
 462     if( n->is_Proj() ||         // Projections always win
 463         n->Opcode()== Op_Con || // So does constant 'Top'
 464         iop == Op_CreateEx ||   // Create-exception must start block
 465         iop == Op_CheckCastPP
 466         ) {
 467       worklist.map(i,worklist.pop());
 468       return n;
 469     }
 470 
 471     // Final call in a block must be adjacent to 'catch'
 472     Node *e = block->end();
 473     if( e->is_Catch() && e->in(0)->in(0) == n )
 474       continue;
 475 
 476     // Memory op for an implicit null check has to be at the end of the block
 477     if( e->is_MachNullCheck() && e->in(1) == n )
 478       continue;
 479 
 480     // Schedule IV increment last.
 481     if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd &&
 482         e->in(1)->in(1) == n && n->is_iteratively_computed())
 483       continue;
 484 
 485     uint n_choice  = 2;
 486 
 487     // See if this instruction is consumed by a branch. If so, then (as the
 488     // branch is the last instruction in the basic block) force it to the
 489     // end of the basic block
 490     if ( must_clone[iop] ) {
 491       // See if any use is a branch
 492       bool found_machif = false;
 493 
 494       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 495         Node* use = n->fast_out(j);
 496 
 497         // The use is a conditional branch, make them adjacent
 498         if (use->is_MachIf() && get_block_for_node(use) == block) {
 499           found_machif = true;
 500           break;
 501         }
 502 
 503         // More than this instruction pending for successor to be ready,
 504         // don't choose this if other opportunities are ready
 505         if (ready_cnt.at(use->_idx) > 1)
 506           n_choice = 1;
 507       }
 508 
 509       // loop terminated, prefer not to use this instruction
 510       if (found_machif)
 511         continue;
 512     }
 513 
 514     // See if this has a predecessor that is "must_clone", i.e. sets the
 515     // condition code. If so, choose this first
 516     for (uint j = 0; j < n->req() ; j++) {
 517       Node *inn = n->in(j);
 518       if (inn) {
 519         if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {
 520           n_choice = 3;
 521           break;
 522         }
 523       }
 524     }
 525 
 526     // MachTemps should be scheduled last so they are near their uses
 527     if (n->is_MachTemp()) {
 528       n_choice = 1;
 529     }
 530 
 531     uint n_latency = get_latency_for_node(n);
 532     uint n_score   = n->req();   // Many inputs get high score to break ties
 533 
 534     // Keep best latency found
 535     cand_cnt++;
 536     if (choice < n_choice ||
 537         (choice == n_choice &&
 538          ((StressLCM && Compile::randomized_select(cand_cnt)) ||
 539           (!StressLCM &&
 540            (latency < n_latency ||
 541             (latency == n_latency &&
 542              (score < n_score))))))) {
 543       choice  = n_choice;
 544       latency = n_latency;
 545       score   = n_score;
 546       idx     = i;               // Also keep index in worklist
 547     }
 548   } // End of for all ready nodes in worklist
 549 
 550   assert(idx >= 0, "index should be set");
 551   Node *n = worklist[(uint)idx];      // Get the winner
 552 
 553   worklist.map((uint)idx, worklist.pop());     // Compress worklist
 554   return n;
 555 }
 556 
 557 
 558 //------------------------------set_next_call----------------------------------
 559 void PhaseCFG::set_next_call(Block* block, Node* n, VectorSet& next_call) {
 560   if( next_call.test_set(n->_idx) ) return;
 561   for( uint i=0; i<n->len(); i++ ) {
 562     Node *m = n->in(i);
 563     if( !m ) continue;  // must see all nodes in block that precede call
 564     if (get_block_for_node(m) == block) {
 565       set_next_call(block, m, next_call);
 566     }
 567   }
 568 }
 569 
 570 //------------------------------needed_for_next_call---------------------------
 571 // Set the flag 'next_call' for each Node that is needed for the next call to
 572 // be scheduled.  This flag lets me bias scheduling so Nodes needed for the
 573 // next subroutine call get priority - basically it moves things NOT needed
 574 // for the next call till after the call.  This prevents me from trying to
 575 // carry lots of stuff live across a call.
 576 void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) {
 577   // Find the next control-defining Node in this block
 578   Node* call = NULL;
 579   for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {
 580     Node* m = this_call->fast_out(i);
 581     if (get_block_for_node(m) == block && // Local-block user
 582         m != this_call &&       // Not self-start node
 583         m->is_MachCall()) {
 584       call = m;
 585       break;
 586     }
 587   }
 588   if (call == NULL)  return;    // No next call (e.g., block end is near)
 589   // Set next-call for all inputs to this call
 590   set_next_call(block, call, next_call);
 591 }
 592 
 593 //------------------------------add_call_kills-------------------------------------
 594 // helper function that adds caller save registers to MachProjNode
 595 static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) {
 596   // Fill in the kill mask for the call
 597   for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
 598     if( !regs.Member(r) ) {     // Not already defined by the call
 599       // Save-on-call register?
 600       if ((save_policy[r] == 'C') ||
 601           (save_policy[r] == 'A') ||
 602           ((save_policy[r] == 'E') && exclude_soe)) {
 603         proj->_rout.Insert(r);
 604       }
 605     }
 606   }
 607 }
 608 
 609 
 610 //------------------------------sched_call-------------------------------------
 611 uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) {
 612   RegMask regs;
 613 
 614   // Schedule all the users of the call right now.  All the users are
 615   // projection Nodes, so they must be scheduled next to the call.
 616   // Collect all the defined registers.
 617   for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
 618     Node* n = mcall->fast_out(i);
 619     assert( n->is_MachProj(), "" );
 620     int n_cnt = ready_cnt.at(n->_idx)-1;
 621     ready_cnt.at_put(n->_idx, n_cnt);
 622     assert( n_cnt == 0, "" );
 623     // Schedule next to call
 624     block->map_node(n, node_cnt++);
 625     // Collect defined registers
 626     regs.OR(n->out_RegMask());
 627     // Check for scheduling the next control-definer
 628     if( n->bottom_type() == Type::CONTROL )
 629       // Warm up next pile of heuristic bits
 630       needed_for_next_call(block, n, next_call);
 631 
 632     // Children of projections are now all ready
 633     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 634       Node* m = n->fast_out(j); // Get user
 635       if(get_block_for_node(m) != block) {
 636         continue;
 637       }
 638       if( m->is_Phi() ) continue;
 639       int m_cnt = ready_cnt.at(m->_idx)-1;
 640       ready_cnt.at_put(m->_idx, m_cnt);
 641       if( m_cnt == 0 )
 642         worklist.push(m);
 643     }
 644 
 645   }
 646 
 647   // Act as if the call defines the Frame Pointer.
 648   // Certainly the FP is alive and well after the call.
 649   regs.Insert(_matcher.c_frame_pointer());
 650 
 651   // Set all registers killed and not already defined by the call.
 652   uint r_cnt = mcall->tf()->range()->cnt();
 653   int op = mcall->ideal_Opcode();
 654   MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
 655   map_node_to_block(proj, block);
 656   block->insert_node(proj, node_cnt++);
 657 
 658   // Select the right register save policy.
 659   const char * save_policy;
 660   switch (op) {
 661     case Op_CallRuntime:
 662     case Op_CallLeaf:
 663     case Op_CallLeafNoFP:
 664       // Calling C code so use C calling convention
 665       save_policy = _matcher._c_reg_save_policy;
 666       break;
 667 
 668     case Op_CallStaticJava:
 669     case Op_CallDynamicJava:
 670       // Calling Java code so use Java calling convention
 671       save_policy = _matcher._register_save_policy;
 672       break;
 673 
 674     default:
 675       ShouldNotReachHere();
 676   }
 677 
 678   // When using CallRuntime mark SOE registers as killed by the call
 679   // so values that could show up in the RegisterMap aren't live in a
 680   // callee saved register since the register wouldn't know where to
 681   // find them.  CallLeaf and CallLeafNoFP are ok because they can't
 682   // have debug info on them.  Strictly speaking this only needs to be
 683   // done for oops since idealreg2debugmask takes care of debug info
 684   // references but there no way to handle oops differently than other
 685   // pointers as far as the kill mask goes.
 686   bool exclude_soe = op == Op_CallRuntime;
 687 
 688   // If the call is a MethodHandle invoke, we need to exclude the
 689   // register which is used to save the SP value over MH invokes from
 690   // the mask.  Otherwise this register could be used for
 691   // deoptimization information.
 692   if (op == Op_CallStaticJava) {
 693     MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;
 694     if (mcallstaticjava->_method_handle_invoke)
 695       proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());
 696   }
 697 
 698   add_call_kills(proj, regs, save_policy, exclude_soe);
 699 
 700   return node_cnt;
 701 }
 702 
 703 
 704 //------------------------------schedule_local---------------------------------
 705 // Topological sort within a block.  Someday become a real scheduler.
 706 bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call) {
 707   // Already "sorted" are the block start Node (as the first entry), and
 708   // the block-ending Node and any trailing control projections.  We leave
 709   // these alone.  PhiNodes and ParmNodes are made to follow the block start
 710   // Node.  Everything else gets topo-sorted.
 711 
 712 #ifndef PRODUCT
 713     if (trace_opto_pipelining()) {
 714       tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order);
 715       for (uint i = 0;i < block->number_of_nodes(); i++) {
 716         tty->print("# ");
 717         block->get_node(i)->fast_dump();
 718       }
 719       tty->print_cr("#");
 720     }
 721 #endif
 722 
 723   // RootNode is already sorted
 724   if (block->number_of_nodes() == 1) {
 725     return true;
 726   }
 727 
 728   // Move PhiNodes and ParmNodes from 1 to cnt up to the start
 729   uint node_cnt = block->end_idx();
 730   uint phi_cnt = 1;
 731   uint i;
 732   for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
 733     Node *n = block->get_node(i);
 734     if( n->is_Phi() ||          // Found a PhiNode or ParmNode
 735         (n->is_Proj()  && n->in(0) == block->head()) ) {
 736       // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
 737       block->map_node(block->get_node(phi_cnt), i);
 738       block->map_node(n, phi_cnt++);  // swap Phi/Parm up front
 739     } else {                    // All others
 740       // Count block-local inputs to 'n'
 741       uint cnt = n->len();      // Input count
 742       uint local = 0;
 743       for( uint j=0; j<cnt; j++ ) {
 744         Node *m = n->in(j);
 745         if( m && get_block_for_node(m) == block && !m->is_top() )
 746           local++;              // One more block-local input
 747       }
 748       ready_cnt.at_put(n->_idx, local); // Count em up
 749 
 750 #ifdef ASSERT
 751       if( UseConcMarkSweepGC || UseG1GC ) {
 752         if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_StoreCM ) {
 753           // Check the precedence edges
 754           for (uint prec = n->req(); prec < n->len(); prec++) {
 755             Node* oop_store = n->in(prec);
 756             if (oop_store != NULL) {
 757               assert(get_block_for_node(oop_store)->_dom_depth <= block->_dom_depth, "oop_store must dominate card-mark");
 758             }
 759           }
 760         }
 761       }
 762 #endif
 763 
 764       // A few node types require changing a required edge to a precedence edge
 765       // before allocation.
 766       if( n->is_Mach() && n->req() > TypeFunc::Parms &&
 767           (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
 768            n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
 769         // MemBarAcquire could be created without Precedent edge.
 770         // del_req() replaces the specified edge with the last input edge
 771         // and then removes the last edge. If the specified edge > number of
 772         // edges the last edge will be moved outside of the input edges array
 773         // and the edge will be lost. This is why this code should be
 774         // executed only when Precedent (== TypeFunc::Parms) edge is present.
 775         Node *x = n->in(TypeFunc::Parms);
 776         n->del_req(TypeFunc::Parms);
 777         n->add_prec(x);
 778       }
 779     }
 780   }
 781   for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count
 782     ready_cnt.at_put(block->get_node(i2)->_idx, 0);
 783 
 784   // All the prescheduled guys do not hold back internal nodes
 785   uint i3;
 786   for(i3 = 0; i3<phi_cnt; i3++ ) {  // For all pre-scheduled
 787     Node *n = block->get_node(i3);       // Get pre-scheduled
 788     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 789       Node* m = n->fast_out(j);
 790       if (get_block_for_node(m) == block) { // Local-block user
 791         int m_cnt = ready_cnt.at(m->_idx)-1;
 792         ready_cnt.at_put(m->_idx, m_cnt);   // Fix ready count
 793       }
 794     }
 795   }
 796 
 797   Node_List delay;
 798   // Make a worklist
 799   Node_List worklist;
 800   for(uint i4=i3; i4<node_cnt; i4++ ) {    // Put ready guys on worklist
 801     Node *m = block->get_node(i4);
 802     if( !ready_cnt.at(m->_idx) ) {   // Zero ready count?
 803       if (m->is_iteratively_computed()) {
 804         // Push induction variable increments last to allow other uses
 805         // of the phi to be scheduled first. The select() method breaks
 806         // ties in scheduling by worklist order.
 807         delay.push(m);
 808       } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
 809         // Force the CreateEx to the top of the list so it's processed
 810         // first and ends up at the start of the block.
 811         worklist.insert(0, m);
 812       } else {
 813         worklist.push(m);         // Then on to worklist!
 814       }
 815     }
 816   }
 817   while (delay.size()) {
 818     Node* d = delay.pop();
 819     worklist.push(d);
 820   }
 821 
 822   // Warm up the 'next_call' heuristic bits
 823   needed_for_next_call(block, block->head(), next_call);
 824 
 825 #ifndef PRODUCT
 826     if (trace_opto_pipelining()) {
 827       for (uint j=0; j< block->number_of_nodes(); j++) {
 828         Node     *n = block->get_node(j);
 829         int     idx = n->_idx;
 830         tty->print("#   ready cnt:%3d  ", ready_cnt.at(idx));
 831         tty->print("latency:%3d  ", get_latency_for_node(n));
 832         tty->print("%4d: %s\n", idx, n->Name());
 833       }
 834     }
 835 #endif
 836 
 837   uint max_idx = (uint)ready_cnt.length();
 838   // Pull from worklist and schedule
 839   while( worklist.size() ) {    // Worklist is not ready
 840 
 841 #ifndef PRODUCT
 842     if (trace_opto_pipelining()) {
 843       tty->print("#   ready list:");
 844       for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
 845         Node *n = worklist[i];      // Get Node on worklist
 846         tty->print(" %d", n->_idx);
 847       }
 848       tty->cr();
 849     }
 850 #endif
 851 
 852     // Select and pop a ready guy from worklist
 853     Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt);
 854     block->map_node(n, phi_cnt++);    // Schedule him next
 855 
 856 #ifndef PRODUCT
 857     if (trace_opto_pipelining()) {
 858       tty->print("#    select %d: %s", n->_idx, n->Name());
 859       tty->print(", latency:%d", get_latency_for_node(n));
 860       n->dump();
 861       if (Verbose) {
 862         tty->print("#   ready list:");
 863         for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
 864           Node *n = worklist[i];      // Get Node on worklist
 865           tty->print(" %d", n->_idx);
 866         }
 867         tty->cr();
 868       }
 869     }
 870 
 871 #endif
 872     if( n->is_MachCall() ) {
 873       MachCallNode *mcall = n->as_MachCall();
 874       phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call);
 875       continue;
 876     }
 877 
 878     if (n->is_Mach() && n->as_Mach()->has_call()) {
 879       RegMask regs;
 880       regs.Insert(_matcher.c_frame_pointer());
 881       regs.OR(n->out_RegMask());
 882 
 883       MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );
 884       map_node_to_block(proj, block);
 885       block->insert_node(proj, phi_cnt++);
 886 
 887       add_call_kills(proj, regs, _matcher._c_reg_save_policy, false);
 888     }
 889 
 890     // Children are now all ready
 891     for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
 892       Node* m = n->fast_out(i5); // Get user
 893       if (get_block_for_node(m) != block) {
 894         continue;
 895       }
 896       if( m->is_Phi() ) continue;
 897       if (m->_idx >= max_idx) { // new node, skip it
 898         assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");
 899         continue;
 900       }
 901       int m_cnt = ready_cnt.at(m->_idx)-1;
 902       ready_cnt.at_put(m->_idx, m_cnt);
 903       if( m_cnt == 0 )
 904         worklist.push(m);
 905     }
 906   }
 907 
 908   if( phi_cnt != block->end_idx() ) {
 909     // did not schedule all.  Retry, Bailout, or Die
 910     if (C->subsume_loads() == true && !C->failing()) {
 911       // Retry with subsume_loads == false
 912       // If this is the first failure, the sentinel string will "stick"
 913       // to the Compile object, and the C2Compiler will see it and retry.
 914       C->record_failure(C2Compiler::retry_no_subsuming_loads());
 915     }
 916     // assert( phi_cnt == end_idx(), "did not schedule all" );
 917     return false;
 918   }
 919 
 920 #ifndef PRODUCT
 921   if (trace_opto_pipelining()) {
 922     tty->print_cr("#");
 923     tty->print_cr("# after schedule_local");
 924     for (uint i = 0;i < block->number_of_nodes();i++) {
 925       tty->print("# ");
 926       block->get_node(i)->fast_dump();
 927     }
 928     tty->cr();
 929   }
 930 #endif
 931 
 932 
 933   return true;
 934 }
 935 
 936 //--------------------------catch_cleanup_fix_all_inputs-----------------------
 937 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {
 938   for (uint l = 0; l < use->len(); l++) {
 939     if (use->in(l) == old_def) {
 940       if (l < use->req()) {
 941         use->set_req(l, new_def);
 942       } else {
 943         use->rm_prec(l);
 944         use->add_prec(new_def);
 945         l--;
 946       }
 947     }
 948   }
 949 }
 950 
 951 //------------------------------catch_cleanup_find_cloned_def------------------
 952 Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
 953   assert( use_blk != def_blk, "Inter-block cleanup only");
 954 
 955   // The use is some block below the Catch.  Find and return the clone of the def
 956   // that dominates the use. If there is no clone in a dominating block, then
 957   // create a phi for the def in a dominating block.
 958 
 959   // Find which successor block dominates this use.  The successor
 960   // blocks must all be single-entry (from the Catch only; I will have
 961   // split blocks to make this so), hence they all dominate.
 962   while( use_blk->_dom_depth > def_blk->_dom_depth+1 )
 963     use_blk = use_blk->_idom;
 964 
 965   // Find the successor
 966   Node *fixup = NULL;
 967 
 968   uint j;
 969   for( j = 0; j < def_blk->_num_succs; j++ )
 970     if( use_blk == def_blk->_succs[j] )
 971       break;
 972 
 973   if( j == def_blk->_num_succs ) {
 974     // Block at same level in dom-tree is not a successor.  It needs a
 975     // PhiNode, the PhiNode uses from the def and IT's uses need fixup.
 976     Node_Array inputs = new Node_List(Thread::current()->resource_area());
 977     for(uint k = 1; k < use_blk->num_preds(); k++) {
 978       Block* block = get_block_for_node(use_blk->pred(k));
 979       inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx));
 980     }
 981 
 982     // Check to see if the use_blk already has an identical phi inserted.
 983     // If it exists, it will be at the first position since all uses of a
 984     // def are processed together.
 985     Node *phi = use_blk->get_node(1);
 986     if( phi->is_Phi() ) {
 987       fixup = phi;
 988       for (uint k = 1; k < use_blk->num_preds(); k++) {
 989         if (phi->in(k) != inputs[k]) {
 990           // Not a match
 991           fixup = NULL;
 992           break;
 993         }
 994       }
 995     }
 996 
 997     // If an existing PhiNode was not found, make a new one.
 998     if (fixup == NULL) {
 999       Node *new_phi = PhiNode::make(use_blk->head(), def);
1000       use_blk->insert_node(new_phi, 1);
1001       map_node_to_block(new_phi, use_blk);
1002       for (uint k = 1; k < use_blk->num_preds(); k++) {
1003         new_phi->set_req(k, inputs[k]);
1004       }
1005       fixup = new_phi;
1006     }
1007 
1008   } else {
1009     // Found the use just below the Catch.  Make it use the clone.
1010     fixup = use_blk->get_node(n_clone_idx);
1011   }
1012 
1013   return fixup;
1014 }
1015 
1016 //--------------------------catch_cleanup_intra_block--------------------------
1017 // Fix all input edges in use that reference "def".  The use is in the same
1018 // block as the def and both have been cloned in each successor block.
1019 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {
1020 
1021   // Both the use and def have been cloned. For each successor block,
1022   // get the clone of the use, and make its input the clone of the def
1023   // found in that block.
1024 
1025   uint use_idx = blk->find_node(use);
1026   uint offset_idx = use_idx - beg;
1027   for( uint k = 0; k < blk->_num_succs; k++ ) {
1028     // Get clone in each successor block
1029     Block *sb = blk->_succs[k];
1030     Node *clone = sb->get_node(offset_idx+1);
1031     assert( clone->Opcode() == use->Opcode(), "" );
1032 
1033     // Make use-clone reference the def-clone
1034     catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx));
1035   }
1036 }
1037 
1038 //------------------------------catch_cleanup_inter_block---------------------
1039 // Fix all input edges in use that reference "def".  The use is in a different
1040 // block than the def.
1041 void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1042   if( !use_blk ) return;        // Can happen if the use is a precedence edge
1043 
1044   Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx);
1045   catch_cleanup_fix_all_inputs(use, def, new_def);
1046 }
1047 
1048 //------------------------------call_catch_cleanup-----------------------------
1049 // If we inserted any instructions between a Call and his CatchNode,
1050 // clone the instructions on all paths below the Catch.
1051 void PhaseCFG::call_catch_cleanup(Block* block) {
1052 
1053   // End of region to clone
1054   uint end = block->end_idx();
1055   if( !block->get_node(end)->is_Catch() ) return;
1056   // Start of region to clone
1057   uint beg = end;
1058   while(!block->get_node(beg-1)->is_MachProj() ||
1059         !block->get_node(beg-1)->in(0)->is_MachCall() ) {
1060     beg--;
1061     assert(beg > 0,"Catch cleanup walking beyond block boundary");
1062   }
1063   // Range of inserted instructions is [beg, end)
1064   if( beg == end ) return;
1065 
1066   // Clone along all Catch output paths.  Clone area between the 'beg' and
1067   // 'end' indices.
1068   for( uint i = 0; i < block->_num_succs; i++ ) {
1069     Block *sb = block->_succs[i];
1070     // Clone the entire area; ignoring the edge fixup for now.
1071     for( uint j = end; j > beg; j-- ) {
1072       // It is safe here to clone a node with anti_dependence
1073       // since clones dominate on each path.
1074       Node *clone = block->get_node(j-1)->clone();
1075       sb->insert_node(clone, 1);
1076       map_node_to_block(clone, sb);
1077     }
1078   }
1079 
1080 
1081   // Fixup edges.  Check the def-use info per cloned Node
1082   for(uint i2 = beg; i2 < end; i2++ ) {
1083     uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block
1084     Node *n = block->get_node(i2);        // Node that got cloned
1085     // Need DU safe iterator because of edge manipulation in calls.
1086     Unique_Node_List *out = new Unique_Node_List(Thread::current()->resource_area());
1087     for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {
1088       out->push(n->fast_out(j1));
1089     }
1090     uint max = out->size();
1091     for (uint j = 0; j < max; j++) {// For all users
1092       Node *use = out->pop();
1093       Block *buse = get_block_for_node(use);
1094       if( use->is_Phi() ) {
1095         for( uint k = 1; k < use->req(); k++ )
1096           if( use->in(k) == n ) {
1097             Block* b = get_block_for_node(buse->pred(k));
1098             Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx);
1099             use->set_req(k, fixup);
1100           }
1101       } else {
1102         if (block == buse) {
1103           catch_cleanup_intra_block(use, n, block, beg, n_clone_idx);
1104         } else {
1105           catch_cleanup_inter_block(use, buse, n, block, n_clone_idx);
1106         }
1107       }
1108     } // End for all users
1109 
1110   } // End of for all Nodes in cloned area
1111 
1112   // Remove the now-dead cloned ops
1113   for(uint i3 = beg; i3 < end; i3++ ) {
1114     block->get_node(beg)->disconnect_inputs(NULL, C);
1115     block->remove_node(beg);
1116   }
1117 
1118   // If the successor blocks have a CreateEx node, move it back to the top
1119   for(uint i4 = 0; i4 < block->_num_succs; i4++ ) {
1120     Block *sb = block->_succs[i4];
1121     uint new_cnt = end - beg;
1122     // Remove any newly created, but dead, nodes.
1123     for( uint j = new_cnt; j > 0; j-- ) {
1124       Node *n = sb->get_node(j);
1125       if (n->outcnt() == 0 &&
1126           (!n->is_Proj() || n->as_Proj()->in(0)->outcnt() == 1) ){
1127         n->disconnect_inputs(NULL, C);
1128         sb->remove_node(j);
1129         new_cnt--;
1130       }
1131     }
1132     // If any newly created nodes remain, move the CreateEx node to the top
1133     if (new_cnt > 0) {
1134       Node *cex = sb->get_node(1+new_cnt);
1135       if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1136         sb->remove_node(1+new_cnt);
1137         sb->insert_node(cex, 1);
1138       }
1139     }
1140   }
1141 }