src/share/vm/opto/lcm.cpp

Wed, 02 Jun 2010 09:49:32 -0700

author
kvn
date
Wed, 02 Jun 2010 09:49:32 -0700
changeset 1930
3657cb01ffc5
parent 1586
1271af4ec18c
child 1934
e9ff18c4ace7
permissions
-rw-r--r--

6954029: Improve implicit null check generation with compressed oops
Summary: Hoist DecodeN instruction above null check
Reviewed-by: never, twisti

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

mercurial