src/share/vm/opto/lcm.cpp

Thu, 05 Sep 2013 11:04:39 -0700

author
kvn
date
Thu, 05 Sep 2013 11:04:39 -0700
changeset 6462
e2722a66aba7
parent 6441
d2907f74462e
parent 5539
adb9a7d94cb5
child 6472
2b8e28fdf503
permissions
-rw-r--r--

Merge

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

mercurial