src/share/vm/opto/split_if.cpp

Tue, 12 Jan 2010 14:37:35 -0800

author
cfang
date
Tue, 12 Jan 2010 14:37:35 -0800
changeset 1607
b2b6a9bf6238
parent 1040
98cb887364d3
child 1708
877a14af58e1
permissions
-rw-r--r--

6894779: Loop Predication for Loop Optimizer in C2
Summary: Loop predication implementation
Reviewed-by: never, kvn

     1 /*
     2  * Copyright 1999-2006 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 #include "incls/_precompiled.incl"
    26 #include "incls/_split_if.cpp.incl"
    29 //------------------------------split_thru_region------------------------------
    30 // Split Node 'n' through merge point.
    31 Node *PhaseIdealLoop::split_thru_region( Node *n, Node *region ) {
    32   uint wins = 0;
    33   assert( n->is_CFG(), "" );
    34   assert( region->is_Region(), "" );
    35   Node *r = new (C, region->req()) RegionNode( region->req() );
    36   IdealLoopTree *loop = get_loop( n );
    37   for( uint i = 1; i < region->req(); i++ ) {
    38     Node *x = n->clone();
    39     Node *in0 = n->in(0);
    40     if( in0->in(0) == region ) x->set_req( 0, in0->in(i) );
    41     for( uint j = 1; j < n->req(); j++ ) {
    42       Node *in = n->in(j);
    43       if( get_ctrl(in) == region )
    44         x->set_req( j, in->in(i) );
    45     }
    46     _igvn.register_new_node_with_optimizer(x);
    47     set_loop(x, loop);
    48     set_idom(x, x->in(0), dom_depth(x->in(0))+1);
    49     r->init_req(i, x);
    50   }
    52   // Record region
    53   r->set_req(0,region);         // Not a TRUE RegionNode
    54   _igvn.register_new_node_with_optimizer(r);
    55   set_loop(r, loop);
    56   if( !loop->_child )
    57     loop->_body.push(r);
    58   return r;
    59 }
    61 //------------------------------split_up---------------------------------------
    62 // Split block-local op up through the phis to empty the current block
    63 bool PhaseIdealLoop::split_up( Node *n, Node *blk1, Node *blk2 ) {
    64   if( n->is_CFG() ) {
    65     assert( n->in(0) != blk1, "Lousy candidate for split-if" );
    66     return false;
    67   }
    68   if( get_ctrl(n) != blk1 && get_ctrl(n) != blk2 )
    69     return false;               // Not block local
    70   if( n->is_Phi() ) return false; // Local PHIs are expected
    72   // Recursively split-up inputs
    73   for (uint i = 1; i < n->req(); i++) {
    74     if( split_up( n->in(i), blk1, blk2 ) ) {
    75       // Got split recursively and self went dead?
    76       if (n->outcnt() == 0)
    77         _igvn.remove_dead_node(n);
    78       return true;
    79     }
    80   }
    82   // Check for needing to clone-up a compare.  Can't do that, it forces
    83   // another (nested) split-if transform.  Instead, clone it "down".
    84   if( n->is_Cmp() ) {
    85     assert(get_ctrl(n) == blk2 || get_ctrl(n) == blk1, "must be in block with IF");
    86     // Check for simple Cmp/Bool/CMove which we can clone-up.  Cmp/Bool/CMove
    87     // sequence can have no other users and it must all reside in the split-if
    88     // block.  Non-simple Cmp/Bool/CMove sequences are 'cloned-down' below -
    89     // private, per-use versions of the Cmp and Bool are made.  These sink to
    90     // the CMove block.  If the CMove is in the split-if block, then in the
    91     // next iteration this will become a simple Cmp/Bool/CMove set to clone-up.
    92     Node *bol, *cmov;
    93     if( !(n->outcnt() == 1 && n->unique_out()->is_Bool() &&
    94           (bol = n->unique_out()->as_Bool()) &&
    95           (get_ctrl(bol) == blk1 ||
    96            get_ctrl(bol) == blk2) &&
    97           bol->outcnt() == 1 &&
    98           bol->unique_out()->is_CMove() &&
    99           (cmov = bol->unique_out()->as_CMove()) &&
   100           (get_ctrl(cmov) == blk1 ||
   101            get_ctrl(cmov) == blk2) ) ) {
   103       // Must clone down
   104 #ifndef PRODUCT
   105       if( PrintOpto && VerifyLoopOptimizations ) {
   106         tty->print("Cloning down: ");
   107         n->dump();
   108       }
   109 #endif
   110       // Clone down any block-local BoolNode uses of this CmpNode
   111       for (DUIterator i = n->outs(); n->has_out(i); i++) {
   112         Node* bol = n->out(i);
   113         assert( bol->is_Bool(), "" );
   114         if (bol->outcnt() == 1) {
   115           Node* use = bol->unique_out();
   116           Node *use_c = use->is_If() ? use->in(0) : get_ctrl(use);
   117           if (use_c == blk1 || use_c == blk2) {
   118             continue;
   119           }
   120         }
   121         if (get_ctrl(bol) == blk1 || get_ctrl(bol) == blk2) {
   122           // Recursively sink any BoolNode
   123 #ifndef PRODUCT
   124           if( PrintOpto && VerifyLoopOptimizations ) {
   125             tty->print("Cloning down: ");
   126             bol->dump();
   127           }
   128 #endif
   129           for (DUIterator_Last jmin, j = bol->last_outs(jmin); j >= jmin; --j) {
   130             // Uses are either IfNodes or CMoves
   131             Node* iff = bol->last_out(j);
   132             assert( iff->in(1) == bol, "" );
   133             // Get control block of either the CMove or the If input
   134             Node *iff_ctrl = iff->is_If() ? iff->in(0) : get_ctrl(iff);
   135             Node *x = bol->clone();
   136             register_new_node(x, iff_ctrl);
   137             _igvn.hash_delete(iff);
   138             iff->set_req(1, x);
   139             _igvn._worklist.push(iff);
   140           }
   141           _igvn.remove_dead_node( bol );
   142           --i;
   143         }
   144       }
   145       // Clone down this CmpNode
   146       for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin; --j) {
   147         Node* bol = n->last_out(j);
   148         assert( bol->in(1) == n, "" );
   149         Node *x = n->clone();
   150         register_new_node(x, get_ctrl(bol));
   151         _igvn.hash_delete(bol);
   152         bol->set_req(1, x);
   153         _igvn._worklist.push(bol);
   154       }
   155       _igvn.remove_dead_node( n );
   157       return true;
   158     }
   159   }
   161   // See if splitting-up a Store.  Any anti-dep loads must go up as
   162   // well.  An anti-dep load might be in the wrong block, because in
   163   // this particular layout/schedule we ignored anti-deps and allow
   164   // memory to be alive twice.  This only works if we do the same
   165   // operations on anti-dep loads as we do their killing stores.
   166   if( n->is_Store() && n->in(MemNode::Memory)->in(0) == n->in(0) ) {
   167     // Get store's memory slice
   168     int alias_idx = C->get_alias_index(_igvn.type(n->in(MemNode::Address))->is_ptr());
   170     // Get memory-phi anti-dep loads will be using
   171     Node *memphi = n->in(MemNode::Memory);
   172     assert( memphi->is_Phi(), "" );
   173     // Hoist any anti-dep load to the splitting block;
   174     // it will then "split-up".
   175     for (DUIterator_Fast imax,i = memphi->fast_outs(imax); i < imax; i++) {
   176       Node *load = memphi->fast_out(i);
   177       if( load->is_Load() && alias_idx == C->get_alias_index(_igvn.type(load->in(MemNode::Address))->is_ptr()) )
   178         set_ctrl(load,blk1);
   179     }
   180   }
   182   // Found some other Node; must clone it up
   183 #ifndef PRODUCT
   184   if( PrintOpto && VerifyLoopOptimizations ) {
   185     tty->print("Cloning up: ");
   186     n->dump();
   187   }
   188 #endif
   190   // Now actually split-up this guy.  One copy per control path merging.
   191   Node *phi = PhiNode::make_blank(blk1, n);
   192   for( uint j = 1; j < blk1->req(); j++ ) {
   193     Node *x = n->clone();
   194     if( n->in(0) && n->in(0) == blk1 )
   195       x->set_req( 0, blk1->in(j) );
   196     for( uint i = 1; i < n->req(); i++ ) {
   197       Node *m = n->in(i);
   198       if( get_ctrl(m) == blk1 ) {
   199         assert( m->in(0) == blk1, "" );
   200         x->set_req( i, m->in(j) );
   201       }
   202     }
   203     register_new_node( x, blk1->in(j) );
   204     phi->init_req( j, x );
   205   }
   206   // Announce phi to optimizer
   207   register_new_node(phi, blk1);
   209   // Remove cloned-up value from optimizer; use phi instead
   210   _igvn.hash_delete(n);
   211   _igvn.subsume_node( n, phi );
   213   // (There used to be a self-recursive call to split_up() here,
   214   // but it is not needed.  All necessary forward walking is done
   215   // by do_split_if() below.)
   217   return true;
   218 }
   220 //------------------------------register_new_node------------------------------
   221 void PhaseIdealLoop::register_new_node( Node *n, Node *blk ) {
   222   assert(!n->is_CFG(), "must be data node");
   223   _igvn.register_new_node_with_optimizer(n);
   224   set_ctrl(n, blk);
   225   IdealLoopTree *loop = get_loop(blk);
   226   if( !loop->_child )
   227     loop->_body.push(n);
   228 }
   230 //------------------------------small_cache------------------------------------
   231 struct small_cache : public Dict {
   233   small_cache() : Dict( cmpkey, hashptr ) {}
   234   Node *probe( Node *use_blk ) { return (Node*)((*this)[use_blk]); }
   235   void lru_insert( Node *use_blk, Node *new_def ) { Insert(use_blk,new_def); }
   236 };
   238 //------------------------------spinup-----------------------------------------
   239 // "Spin up" the dominator tree, starting at the use site and stopping when we
   240 // find the post-dominating point.
   242 // We must be at the merge point which post-dominates 'new_false' and
   243 // 'new_true'.  Figure out which edges into the RegionNode eventually lead up
   244 // to false and which to true.  Put in a PhiNode to merge values; plug in
   245 // the appropriate false-arm or true-arm values.  If some path leads to the
   246 // original IF, then insert a Phi recursively.
   247 Node *PhaseIdealLoop::spinup( Node *iff_dom, Node *new_false, Node *new_true, Node *use_blk, Node *def, small_cache *cache ) {
   248   if (use_blk->is_top())        // Handle dead uses
   249     return use_blk;
   250   Node *prior_n = (Node*)0xdeadbeef;
   251   Node *n = use_blk;            // Get path input
   252   assert( use_blk != iff_dom, "" );
   253   // Here's the "spinup" the dominator tree loop.  Do a cache-check
   254   // along the way, in case we've come this way before.
   255   while( n != iff_dom ) {       // Found post-dominating point?
   256     prior_n = n;
   257     n = idom(n);                // Search higher
   258     Node *s = cache->probe( prior_n ); // Check cache
   259     if( s ) return s;           // Cache hit!
   260   }
   262   Node *phi_post;
   263   if( prior_n == new_false || prior_n == new_true ) {
   264     phi_post = def->clone();
   265     phi_post->set_req(0, prior_n );
   266     register_new_node(phi_post, prior_n);
   267   } else {
   268     // This method handles both control uses (looking for Regions) or data
   269     // uses (looking for Phis).  If looking for a control use, then we need
   270     // to insert a Region instead of a Phi; however Regions always exist
   271     // previously (the hash_find_insert below would always hit) so we can
   272     // return the existing Region.
   273     if( def->is_CFG() ) {
   274       phi_post = prior_n;       // If looking for CFG, return prior
   275     } else {
   276       assert( def->is_Phi(), "" );
   277       assert( prior_n->is_Region(), "must be a post-dominating merge point" );
   279       // Need a Phi here
   280       phi_post = PhiNode::make_blank(prior_n, def);
   281       // Search for both true and false on all paths till find one.
   282       for( uint i = 1; i < phi_post->req(); i++ ) // For all paths
   283         phi_post->init_req( i, spinup( iff_dom, new_false, new_true, prior_n->in(i), def, cache ) );
   284       Node *t = _igvn.hash_find_insert(phi_post);
   285       if( t ) {                 // See if we already have this one
   286         // phi_post will not be used, so kill it
   287         _igvn.remove_dead_node(phi_post);
   288         phi_post->destruct();
   289         phi_post = t;
   290       } else {
   291         register_new_node( phi_post, prior_n );
   292       }
   293     }
   294   }
   296   // Update cache everywhere
   297   prior_n = (Node*)0xdeadbeef;  // Reset IDOM walk
   298   n = use_blk;                  // Get path input
   299   // Spin-up the idom tree again, basically doing path-compression.
   300   // Insert cache entries along the way, so that if we ever hit this
   301   // point in the IDOM tree again we'll stop immediately on a cache hit.
   302   while( n != iff_dom ) {       // Found post-dominating point?
   303     prior_n = n;
   304     n = idom(n);                // Search higher
   305     cache->lru_insert( prior_n, phi_post ); // Fill cache
   306   } // End of while not gone high enough
   308   return phi_post;
   309 }
   311 //------------------------------find_use_block---------------------------------
   312 // Find the block a USE is in.  Normally USE's are in the same block as the
   313 // using instruction.  For Phi-USE's, the USE is in the predecessor block
   314 // along the corresponding path.
   315 Node *PhaseIdealLoop::find_use_block( Node *use, Node *def, Node *old_false, Node *new_false, Node *old_true, Node *new_true ) {
   316   // CFG uses are their own block
   317   if( use->is_CFG() )
   318     return use;
   320   if( use->is_Phi() ) {         // Phi uses in prior block
   321     // Grab the first Phi use; there may be many.
   322     // Each will be handled as a separate iteration of
   323     // the "while( phi->outcnt() )" loop.
   324     uint j;
   325     for( j = 1; j < use->req(); j++ )
   326       if( use->in(j) == def )
   327         break;
   328     assert( j < use->req(), "def should be among use's inputs" );
   329     return use->in(0)->in(j);
   330   }
   331   // Normal (non-phi) use
   332   Node *use_blk = get_ctrl(use);
   333   // Some uses are directly attached to the old (and going away)
   334   // false and true branches.
   335   if( use_blk == old_false ) {
   336     use_blk = new_false;
   337     set_ctrl(use, new_false);
   338   }
   339   if( use_blk == old_true ) {
   340     use_blk = new_true;
   341     set_ctrl(use, new_true);
   342   }
   344   if (use_blk == NULL) {        // He's dead, Jim
   345     _igvn.hash_delete(use);
   346     _igvn.subsume_node(use, C->top());
   347   }
   349   return use_blk;
   350 }
   352 //------------------------------handle_use-------------------------------------
   353 // Handle uses of the merge point.  Basically, split-if makes the merge point
   354 // go away so all uses of the merge point must go away as well.  Most block
   355 // local uses have already been split-up, through the merge point.  Uses from
   356 // far below the merge point can't always be split up (e.g., phi-uses are
   357 // pinned) and it makes too much stuff live.  Instead we use a path-based
   358 // solution to move uses down.
   359 //
   360 // If the use is along the pre-split-CFG true branch, then the new use will
   361 // be from the post-split-CFG true merge point.  Vice-versa for the false
   362 // path.  Some uses will be along both paths; then we sink the use to the
   363 // post-dominating location; we may need to insert a Phi there.
   364 void PhaseIdealLoop::handle_use( Node *use, Node *def, small_cache *cache, Node *region_dom, Node *new_false, Node *new_true, Node *old_false, Node *old_true ) {
   366   Node *use_blk = find_use_block(use,def,old_false,new_false,old_true,new_true);
   367   if( !use_blk ) return;        // He's dead, Jim
   369   // Walk up the dominator tree until I hit either the old IfFalse, the old
   370   // IfTrue or the old If.  Insert Phis where needed.
   371   Node *new_def = spinup( region_dom, new_false, new_true, use_blk, def, cache );
   373   // Found where this USE goes.  Re-point him.
   374   uint i;
   375   for( i = 0; i < use->req(); i++ )
   376     if( use->in(i) == def )
   377       break;
   378   assert( i < use->req(), "def should be among use's inputs" );
   379   _igvn.hash_delete(use);
   380   use->set_req(i, new_def);
   381   _igvn._worklist.push(use);
   382 }
   384 //------------------------------do_split_if------------------------------------
   385 // Found an If getting its condition-code input from a Phi in the same block.
   386 // Split thru the Region.
   387 void PhaseIdealLoop::do_split_if( Node *iff ) {
   388 #ifndef PRODUCT
   389   if( PrintOpto && VerifyLoopOptimizations )
   390     tty->print_cr("Split-if");
   391 #endif
   392   C->set_major_progress();
   393   Node *region = iff->in(0);
   394   Node *region_dom = idom(region);
   396   // We are going to clone this test (and the control flow with it) up through
   397   // the incoming merge point.  We need to empty the current basic block.
   398   // Clone any instructions which must be in this block up through the merge
   399   // point.
   400   DUIterator i, j;
   401   bool progress = true;
   402   while (progress) {
   403     progress = false;
   404     for (i = region->outs(); region->has_out(i); i++) {
   405       Node* n = region->out(i);
   406       if( n == region ) continue;
   407       // The IF to be split is OK.
   408       if( n == iff ) continue;
   409       if( !n->is_Phi() ) {      // Found pinned memory op or such
   410         if (split_up(n, region, iff)) {
   411           i = region->refresh_out_pos(i);
   412           progress = true;
   413         }
   414         continue;
   415       }
   416       assert( n->in(0) == region, "" );
   418       // Recursively split up all users of a Phi
   419       for (j = n->outs(); n->has_out(j); j++) {
   420         Node* m = n->out(j);
   421         // If m is dead, throw it away, and declare progress
   422         if (_nodes[m->_idx] == NULL) {
   423           _igvn.remove_dead_node(m);
   424           // fall through
   425         }
   426         else if (m != iff && split_up(m, region, iff)) {
   427           // fall through
   428         } else {
   429           continue;
   430         }
   431         // Something unpredictable changed.
   432         // Tell the iterators to refresh themselves, and rerun the loop.
   433         i = region->refresh_out_pos(i);
   434         j = region->refresh_out_pos(j);
   435         progress = true;
   436       }
   437     }
   438   }
   440   // Now we have no instructions in the block containing the IF.
   441   // Split the IF.
   442   Node *new_iff = split_thru_region( iff, region );
   444   // Replace both uses of 'new_iff' with Regions merging True/False
   445   // paths.  This makes 'new_iff' go dead.
   446   Node *old_false, *old_true;
   447   Node *new_false, *new_true;
   448   for (DUIterator_Last j2min, j2 = iff->last_outs(j2min); j2 >= j2min; --j2) {
   449     Node *ifp = iff->last_out(j2);
   450     assert( ifp->Opcode() == Op_IfFalse || ifp->Opcode() == Op_IfTrue, "" );
   451     ifp->set_req(0, new_iff);
   452     Node *ifpx = split_thru_region( ifp, region );
   454     // Replace 'If' projection of a Region with a Region of
   455     // 'If' projections.
   456     ifpx->set_req(0, ifpx);       // A TRUE RegionNode
   458     // Setup dominator info
   459     set_idom(ifpx, region_dom, dom_depth(region_dom) + 1);
   461     // Check for splitting loop tails
   462     if( get_loop(iff)->tail() == ifp )
   463       get_loop(iff)->_tail = ifpx;
   465     // Replace in the graph with lazy-update mechanism
   466     new_iff->set_req(0, new_iff); // hook self so it does not go dead
   467     lazy_replace_proj( ifp, ifpx );
   468     new_iff->set_req(0, region);
   470     // Record bits for later xforms
   471     if( ifp->Opcode() == Op_IfFalse ) {
   472       old_false = ifp;
   473       new_false = ifpx;
   474     } else {
   475       old_true = ifp;
   476       new_true = ifpx;
   477     }
   478   }
   479   _igvn.remove_dead_node(new_iff);
   480   // Lazy replace IDOM info with the region's dominator
   481   lazy_replace( iff, region_dom );
   483   // Now make the original merge point go dead, by handling all its uses.
   484   small_cache region_cache;
   485   // Preload some control flow in region-cache
   486   region_cache.lru_insert( new_false, new_false );
   487   region_cache.lru_insert( new_true , new_true  );
   488   // Now handle all uses of the splitting block
   489   for (DUIterator_Last kmin, k = region->last_outs(kmin); k >= kmin; --k) {
   490     Node* phi = region->last_out(k);
   491     if( !phi->in(0) ) {         // Dead phi?  Remove it
   492       _igvn.remove_dead_node(phi);
   493       continue;
   494     }
   495     assert( phi->in(0) == region, "" );
   496     if( phi == region ) {       // Found the self-reference
   497       phi->set_req(0, NULL);
   498       continue;                 // Break the self-cycle
   499     }
   500     // Expected common case: Phi hanging off of Region
   501     if( phi->is_Phi() ) {
   502       // Need a per-def cache.  Phi represents a def, so make a cache
   503       small_cache phi_cache;
   505       // Inspect all Phi uses to make the Phi go dead
   506       for (DUIterator_Last lmin, l = phi->last_outs(lmin); l >= lmin; --l) {
   507         Node* use = phi->last_out(l);
   508         // Compute the new DEF for this USE.  New DEF depends on the path
   509         // taken from the original DEF to the USE.  The new DEF may be some
   510         // collection of PHI's merging values from different paths.  The Phis
   511         // inserted depend only on the location of the USE.  We use a
   512         // 2-element cache to handle multiple uses from the same block.
   513         handle_use( use, phi, &phi_cache, region_dom, new_false, new_true, old_false, old_true );
   514       } // End of while phi has uses
   516       // Because handle_use might relocate region->_out,
   517       // we must refresh the iterator.
   518       k = region->last_outs(kmin);
   520       // Remove the dead Phi
   521       _igvn.remove_dead_node( phi );
   523     } else {
   524       // Random memory op guarded by Region.  Compute new DEF for USE.
   525       handle_use( phi, region, &region_cache, region_dom, new_false, new_true, old_false, old_true );
   526     }
   528   } // End of while merge point has phis
   530   // Any leftover bits in the splitting block must not have depended on local
   531   // Phi inputs (these have already been split-up).  Hence it's safe to hoist
   532   // these guys to the dominating point.
   533   lazy_replace( region, region_dom );
   534 #ifndef PRODUCT
   535   if( VerifyLoopOptimizations ) verify();
   536 #endif
   537 }

mercurial