1 /*
2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "libadt/vectset.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "memory/resourceArea.hpp"
29 #include "opto/block.hpp"
30 #include "opto/c2compiler.hpp"
31 #include "opto/callnode.hpp"
32 #include "opto/cfgnode.hpp"
33 #include "opto/machnode.hpp"
34 #include "opto/opcodes.hpp"
35 #include "opto/phaseX.hpp"
36 #include "opto/rootnode.hpp"
37 #include "opto/runtime.hpp"
38 #include "opto/chaitin.hpp"
39 #include "runtime/deoptimization.hpp"
40 
41 // Portions of code courtesy of Clifford Click
42 
43 // Optimization - Graph Style
44 
45 // To avoid float value underflow
46 #define MIN_BLOCK_FREQUENCY 1.e-35f
47 
48 //----------------------------schedule_node_into_block-------------------------
49 // Insert node n into block b. Look for projections of n and make sure they
50 // are in b also.
schedule_node_into_block(Node * n,Block * b)51 void PhaseCFG::schedule_node_into_block( Node *n, Block *b ) {
52   // Set basic block of n, Add n to b,
53   map_node_to_block(n, b);
54   b->add_inst(n);
55 
56   // After Matching, nearly any old Node may have projections trailing it.
57   // These are usually machine-dependent flags.  In any case, they might
58   // float to another block below this one.  Move them up.
59   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
60     Node*  use  = n->fast_out(i);
61     if (use->is_Proj()) {
62       Block* buse = get_block_for_node(use);
63       if (buse != b) {              // In wrong block?
64         if (buse != NULL) {
65           buse->find_remove(use);   // Remove from wrong block
66         }
67         map_node_to_block(use, b);
68         b->add_inst(use);
69       }
70     }
71   }
72 }
73 
74 //----------------------------replace_block_proj_ctrl-------------------------
75 // Nodes that have is_block_proj() nodes as their control need to use
76 // the appropriate Region for their actual block as their control since
77 // the projection will be in a predecessor block.
replace_block_proj_ctrl(Node * n)78 void PhaseCFG::replace_block_proj_ctrl( Node *n ) {
79   const Node *in0 = n->in(0);
80   assert(in0 != NULL, "Only control-dependent");
81   const Node *p = in0->is_block_proj();
82   if (p != NULL && p != n) {    // Control from a block projection?
83     assert(!n->pinned() || n->is_MachConstantBase(), "only pinned MachConstantBase node is expected here");
84     // Find trailing Region
85     Block *pb = get_block_for_node(in0); // Block-projection already has basic block
86     uint j = 0;
87     if (pb->_num_succs != 1) {  // More then 1 successor?
88       // Search for successor
89       uint max = pb->number_of_nodes();
90       assert( max > 1, "" );
91       uint start = max - pb->_num_succs;
92       // Find which output path belongs to projection
93       for (j = start; j < max; j++) {
94         if( pb->get_node(j) == in0 )
95           break;
96       }
97       assert( j < max, "must find" );
98       // Change control to match head of successor basic block
99       j -= start;
100     }
101     n->set_req(0, pb->_succs[j]->head());
102   }
103 }
104 
is_dominator(Node * dom_node,Node * node)105 bool PhaseCFG::is_dominator(Node* dom_node, Node* node) {
106   assert(is_CFG(node) && is_CFG(dom_node), "node and dom_node must be CFG nodes");
107   if (dom_node == node) {
108     return true;
109   }
110   Block* d = find_block_for_node(dom_node);
111   Block* n = find_block_for_node(node);
112   assert(n != NULL && d != NULL, "blocks must exist");
113 
114   if (d == n) {
115     if (dom_node->is_block_start()) {
116       return true;
117     }
118     if (node->is_block_start()) {
119       return false;
120     }
121     if (dom_node->is_block_proj()) {
122       return false;
123     }
124     if (node->is_block_proj()) {
125       return true;
126     }
127 
128     assert(is_control_proj_or_safepoint(node), "node must be control projection or safepoint");
129     assert(is_control_proj_or_safepoint(dom_node), "dom_node must be control projection or safepoint");
130 
131     // Neither 'node' nor 'dom_node' is a block start or block projection.
132     // Check if 'dom_node' is above 'node' in the control graph.
133     if (is_dominating_control(dom_node, node)) {
134       return true;
135     }
136 
137 #ifdef ASSERT
138     // If 'dom_node' does not dominate 'node' then 'node' has to dominate 'dom_node'
139     if (!is_dominating_control(node, dom_node)) {
140       node->dump();
141       dom_node->dump();
142       assert(false, "neither dom_node nor node dominates the other");
143     }
144 #endif
145 
146     return false;
147   }
148   return d->dom_lca(n) == d;
149 }
150 
is_CFG(Node * n)151 bool PhaseCFG::is_CFG(Node* n) {
152   return n->is_block_proj() || n->is_block_start() || is_control_proj_or_safepoint(n);
153 }
154 
is_control_proj_or_safepoint(Node * n) const155 bool PhaseCFG::is_control_proj_or_safepoint(Node* n) const {
156   bool result = (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_SafePoint) || (n->is_Proj() && n->as_Proj()->bottom_type() == Type::CONTROL);
157   assert(!result || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_SafePoint)
158           || (n->is_Proj() && n->as_Proj()->_con == 0), "If control projection, it must be projection 0");
159   return result;
160 }
161 
find_block_for_node(Node * n) const162 Block* PhaseCFG::find_block_for_node(Node* n) const {
163   if (n->is_block_start() || n->is_block_proj()) {
164     return get_block_for_node(n);
165   } else {
166     // Walk the control graph up if 'n' is not a block start nor a block projection. In this case 'n' must be
167     // an unmatched control projection or a not yet matched safepoint precedence edge in the middle of a block.
168     assert(is_control_proj_or_safepoint(n), "must be control projection or safepoint");
169     Node* ctrl = n->in(0);
170     while (!ctrl->is_block_start()) {
171       ctrl = ctrl->in(0);
172     }
173     return get_block_for_node(ctrl);
174   }
175 }
176 
177 // Walk up the control graph from 'n' and check if 'dom_ctrl' is found.
is_dominating_control(Node * dom_ctrl,Node * n)178 bool PhaseCFG::is_dominating_control(Node* dom_ctrl, Node* n) {
179   Node* ctrl = n->in(0);
180   while (!ctrl->is_block_start()) {
181     if (ctrl == dom_ctrl) {
182       return true;
183     }
184     ctrl = ctrl->in(0);
185   }
186   return false;
187 }
188 
189 
190 //------------------------------schedule_pinned_nodes--------------------------
191 // Set the basic block for Nodes pinned into blocks
schedule_pinned_nodes(VectorSet & visited)192 void PhaseCFG::schedule_pinned_nodes(VectorSet &visited) {
193   // Allocate node stack of size C->live_nodes()+8 to avoid frequent realloc
194   GrowableArray <Node*> spstack(C->live_nodes() + 8);
195   spstack.push(_root);
196   while (spstack.is_nonempty()) {
197     Node* node = spstack.pop();
198     if (!visited.test_set(node->_idx)) { // Test node and flag it as visited
199       if (node->pinned() && !has_block(node)) {  // Pinned?  Nail it down!
200         assert(node->in(0), "pinned Node must have Control");
201         // Before setting block replace block_proj control edge
202         replace_block_proj_ctrl(node);
203         Node* input = node->in(0);
204         while (!input->is_block_start()) {
205           input = input->in(0);
206         }
207         Block* block = get_block_for_node(input); // Basic block of controlling input
208         schedule_node_into_block(node, block);
209       }
210 
211       // If the node has precedence edges (added when CastPP nodes are
212       // removed in final_graph_reshaping), fix the control of the
213       // node to cover the precedence edges and remove the
214       // dependencies.
215       Node* n = NULL;
216       for (uint i = node->len()-1; i >= node->req(); i--) {
217         Node* m = node->in(i);
218         if (m == NULL) continue;
219 
220         // Only process precedence edges that are CFG nodes. Safepoints and control projections can be in the middle of a block
221         if (is_CFG(m)) {
222           node->rm_prec(i);
223           if (n == NULL) {
224             n = m;
225           } else {
226             assert(is_dominator(n, m) || is_dominator(m, n), "one must dominate the other");
227             n = is_dominator(n, m) ? m : n;
228           }
229         } else {
230           assert(node->is_Mach(), "sanity");
231           assert(node->as_Mach()->ideal_Opcode() == Op_StoreCM, "must be StoreCM node");
232         }
233       }
234       if (n != NULL) {
235         assert(node->in(0), "control should have been set");
236         assert(is_dominator(n, node->in(0)) || is_dominator(node->in(0), n), "one must dominate the other");
237         if (!is_dominator(n, node->in(0))) {
238           node->set_req(0, n);
239         }
240       }
241 
242       // process all inputs that are non NULL
243       for (int i = node->req()-1; i >= 0; --i) {
244         if (node->in(i) != NULL) {
245           spstack.push(node->in(i));
246         }
247       }
248     }
249   }
250 }
251 
252 #ifdef ASSERT
253 // Assert that new input b2 is dominated by all previous inputs.
254 // Check this by by seeing that it is dominated by b1, the deepest
255 // input observed until b2.
assert_dom(Block * b1,Block * b2,Node * n,const PhaseCFG * cfg)256 static void assert_dom(Block* b1, Block* b2, Node* n, const PhaseCFG* cfg) {
257   if (b1 == NULL)  return;
258   assert(b1->_dom_depth < b2->_dom_depth, "sanity");
259   Block* tmp = b2;
260   while (tmp != b1 && tmp != NULL) {
261     tmp = tmp->_idom;
262   }
263   if (tmp != b1) {
264     // Detected an unschedulable graph.  Print some nice stuff and die.
265     tty->print_cr("!!! Unschedulable graph !!!");
266     for (uint j=0; j<n->len(); j++) { // For all inputs
267       Node* inn = n->in(j); // Get input
268       if (inn == NULL)  continue;  // Ignore NULL, missing inputs
269       Block* inb = cfg->get_block_for_node(inn);
270       tty->print("B%d idom=B%d depth=%2d ",inb->_pre_order,
271                  inb->_idom ? inb->_idom->_pre_order : 0, inb->_dom_depth);
272       inn->dump();
273     }
274     tty->print("Failing node: ");
275     n->dump();
276     assert(false, "unscheduable graph");
277   }
278 }
279 #endif
280 
find_deepest_input(Node * n,const PhaseCFG * cfg)281 static Block* find_deepest_input(Node* n, const PhaseCFG* cfg) {
282   // Find the last input dominated by all other inputs.
283   Block* deepb           = NULL;        // Deepest block so far
284   int    deepb_dom_depth = 0;
285   for (uint k = 0; k < n->len(); k++) { // For all inputs
286     Node* inn = n->in(k);               // Get input
287     if (inn == NULL)  continue;         // Ignore NULL, missing inputs
288     Block* inb = cfg->get_block_for_node(inn);
289     assert(inb != NULL, "must already have scheduled this input");
290     if (deepb_dom_depth < (int) inb->_dom_depth) {
291       // The new inb must be dominated by the previous deepb.
292       // The various inputs must be linearly ordered in the dom
293       // tree, or else there will not be a unique deepest block.
294       DEBUG_ONLY(assert_dom(deepb, inb, n, cfg));
295       deepb = inb;                      // Save deepest block
296       deepb_dom_depth = deepb->_dom_depth;
297     }
298   }
299   assert(deepb != NULL, "must be at least one input to n");
300   return deepb;
301 }
302 
303 
304 //------------------------------schedule_early---------------------------------
305 // Find the earliest Block any instruction can be placed in.  Some instructions
306 // are pinned into Blocks.  Unpinned instructions can appear in last block in
307 // which all their inputs occur.
schedule_early(VectorSet & visited,Node_Stack & roots)308 bool PhaseCFG::schedule_early(VectorSet &visited, Node_Stack &roots) {
309   // Allocate stack with enough space to avoid frequent realloc
310   Node_Stack nstack(roots.size() + 8);
311   // _root will be processed among C->top() inputs
312   roots.push(C->top(), 0);
313   visited.set(C->top()->_idx);
314 
315   while (roots.size() != 0) {
316     // Use local variables nstack_top_n & nstack_top_i to cache values
317     // on stack's top.
318     Node* parent_node = roots.node();
319     uint  input_index = 0;
320     roots.pop();
321 
322     while (true) {
323       if (input_index == 0) {
324         // Fixup some control.  Constants without control get attached
325         // to root and nodes that use is_block_proj() nodes should be attached
326         // to the region that starts their block.
327         const Node* control_input = parent_node->in(0);
328         if (control_input != NULL) {
329           replace_block_proj_ctrl(parent_node);
330         } else {
331           // Is a constant with NO inputs?
332           if (parent_node->req() == 1) {
333             parent_node->set_req(0, _root);
334           }
335         }
336       }
337 
338       // First, visit all inputs and force them to get a block.  If an
339       // input is already in a block we quit following inputs (to avoid
340       // cycles). Instead we put that Node on a worklist to be handled
341       // later (since IT'S inputs may not have a block yet).
342 
343       // Assume all n's inputs will be processed
344       bool done = true;
345 
346       while (input_index < parent_node->len()) {
347         Node* in = parent_node->in(input_index++);
348         if (in == NULL) {
349           continue;
350         }
351 
352         int is_visited = visited.test_set(in->_idx);
353         if (!has_block(in)) {
354           if (is_visited) {
355             assert(false, "graph should be schedulable");
356             return false;
357           }
358           // Save parent node and next input's index.
359           nstack.push(parent_node, input_index);
360           // Process current input now.
361           parent_node = in;
362           input_index = 0;
363           // Not all n's inputs processed.
364           done = false;
365           break;
366         } else if (!is_visited) {
367           // Visit this guy later, using worklist
368           roots.push(in, 0);
369         }
370       }
371 
372       if (done) {
373         // All of n's inputs have been processed, complete post-processing.
374 
375         // Some instructions are pinned into a block.  These include Region,
376         // Phi, Start, Return, and other control-dependent instructions and
377         // any projections which depend on them.
378         if (!parent_node->pinned()) {
379           // Set earliest legal block.
380           Block* earliest_block = find_deepest_input(parent_node, this);
381           map_node_to_block(parent_node, earliest_block);
382         } else {
383           assert(get_block_for_node(parent_node) == get_block_for_node(parent_node->in(0)), "Pinned Node should be at the same block as its control edge");
384         }
385 
386         if (nstack.is_empty()) {
387           // Finished all nodes on stack.
388           // Process next node on the worklist 'roots'.
389           break;
390         }
391         // Get saved parent node and next input's index.
392         parent_node = nstack.node();
393         input_index = nstack.index();
394         nstack.pop();
395       }
396     }
397   }
398   return true;
399 }
400 
401 //------------------------------dom_lca----------------------------------------
402 // Find least common ancestor in dominator tree
403 // LCA is a current notion of LCA, to be raised above 'this'.
404 // As a convenient boundary condition, return 'this' if LCA is NULL.
405 // Find the LCA of those two nodes.
dom_lca(Block * LCA)406 Block* Block::dom_lca(Block* LCA) {
407   if (LCA == NULL || LCA == this)  return this;
408 
409   Block* anc = this;
410   while (anc->_dom_depth > LCA->_dom_depth)
411     anc = anc->_idom;           // Walk up till anc is as high as LCA
412 
413   while (LCA->_dom_depth > anc->_dom_depth)
414     LCA = LCA->_idom;           // Walk up till LCA is as high as anc
415 
416   while (LCA != anc) {          // Walk both up till they are the same
417     LCA = LCA->_idom;
418     anc = anc->_idom;
419   }
420 
421   return LCA;
422 }
423 
424 //--------------------------raise_LCA_above_use--------------------------------
425 // We are placing a definition, and have been given a def->use edge.
426 // The definition must dominate the use, so move the LCA upward in the
427 // dominator tree to dominate the use.  If the use is a phi, adjust
428 // the LCA only with the phi input paths which actually use this def.
raise_LCA_above_use(Block * LCA,Node * use,Node * def,const PhaseCFG * cfg)429 static Block* raise_LCA_above_use(Block* LCA, Node* use, Node* def, const PhaseCFG* cfg) {
430   Block* buse = cfg->get_block_for_node(use);
431   if (buse == NULL)    return LCA;   // Unused killing Projs have no use block
432   if (!use->is_Phi())  return buse->dom_lca(LCA);
433   uint pmax = use->req();       // Number of Phi inputs
434   // Why does not this loop just break after finding the matching input to
435   // the Phi?  Well...it's like this.  I do not have true def-use/use-def
436   // chains.  Means I cannot distinguish, from the def-use direction, which
437   // of many use-defs lead from the same use to the same def.  That is, this
438   // Phi might have several uses of the same def.  Each use appears in a
439   // different predecessor block.  But when I enter here, I cannot distinguish
440   // which use-def edge I should find the predecessor block for.  So I find
441   // them all.  Means I do a little extra work if a Phi uses the same value
442   // more than once.
443   for (uint j=1; j<pmax; j++) { // For all inputs
444     if (use->in(j) == def) {    // Found matching input?
445       Block* pred = cfg->get_block_for_node(buse->pred(j));
446       LCA = pred->dom_lca(LCA);
447     }
448   }
449   return LCA;
450 }
451 
452 //----------------------------raise_LCA_above_marks----------------------------
453 // Return a new LCA that dominates LCA and any of its marked predecessors.
454 // Search all my parents up to 'early' (exclusive), looking for predecessors
455 // which are marked with the given index.  Return the LCA (in the dom tree)
456 // of all marked blocks.  If there are none marked, return the original
457 // LCA.
raise_LCA_above_marks(Block * LCA,node_idx_t mark,Block * early,const PhaseCFG * cfg)458 static Block* raise_LCA_above_marks(Block* LCA, node_idx_t mark, Block* early, const PhaseCFG* cfg) {
459   Block_List worklist;
460   worklist.push(LCA);
461   while (worklist.size() > 0) {
462     Block* mid = worklist.pop();
463     if (mid == early)  continue;  // stop searching here
464 
465     // Test and set the visited bit.
466     if (mid->raise_LCA_visited() == mark)  continue;  // already visited
467 
468     // Don't process the current LCA, otherwise the search may terminate early
469     if (mid != LCA && mid->raise_LCA_mark() == mark) {
470       // Raise the LCA.
471       LCA = mid->dom_lca(LCA);
472       if (LCA == early)  break;   // stop searching everywhere
473       assert(early->dominates(LCA), "early is high enough");
474       // Resume searching at that point, skipping intermediate levels.
475       worklist.push(LCA);
476       if (LCA == mid)
477         continue; // Don't mark as visited to avoid early termination.
478     } else {
479       // Keep searching through this block's predecessors.
480       for (uint j = 1, jmax = mid->num_preds(); j < jmax; j++) {
481         Block* mid_parent = cfg->get_block_for_node(mid->pred(j));
482         worklist.push(mid_parent);
483       }
484     }
485     mid->set_raise_LCA_visited(mark);
486   }
487   return LCA;
488 }
489 
490 //--------------------------memory_early_block--------------------------------
491 // This is a variation of find_deepest_input, the heart of schedule_early.
492 // Find the "early" block for a load, if we considered only memory and
493 // address inputs, that is, if other data inputs were ignored.
494 //
495 // Because a subset of edges are considered, the resulting block will
496 // be earlier (at a shallower dom_depth) than the true schedule_early
497 // point of the node. We compute this earlier block as a more permissive
498 // site for anti-dependency insertion, but only if subsume_loads is enabled.
memory_early_block(Node * load,Block * early,const PhaseCFG * cfg)499 static Block* memory_early_block(Node* load, Block* early, const PhaseCFG* cfg) {
500   Node* base;
501   Node* index;
502   Node* store = load->in(MemNode::Memory);
503   load->as_Mach()->memory_inputs(base, index);
504 
505   assert(base != NodeSentinel && index != NodeSentinel,
506          "unexpected base/index inputs");
507 
508   Node* mem_inputs[4];
509   int mem_inputs_length = 0;
510   if (base != NULL)  mem_inputs[mem_inputs_length++] = base;
511   if (index != NULL) mem_inputs[mem_inputs_length++] = index;
512   if (store != NULL) mem_inputs[mem_inputs_length++] = store;
513 
514   // In the comparision below, add one to account for the control input,
515   // which may be null, but always takes up a spot in the in array.
516   if (mem_inputs_length + 1 < (int) load->req()) {
517     // This "load" has more inputs than just the memory, base and index inputs.
518     // For purposes of checking anti-dependences, we need to start
519     // from the early block of only the address portion of the instruction,
520     // and ignore other blocks that may have factored into the wider
521     // schedule_early calculation.
522     if (load->in(0) != NULL) mem_inputs[mem_inputs_length++] = load->in(0);
523 
524     Block* deepb           = NULL;        // Deepest block so far
525     int    deepb_dom_depth = 0;
526     for (int i = 0; i < mem_inputs_length; i++) {
527       Block* inb = cfg->get_block_for_node(mem_inputs[i]);
528       if (deepb_dom_depth < (int) inb->_dom_depth) {
529         // The new inb must be dominated by the previous deepb.
530         // The various inputs must be linearly ordered in the dom
531         // tree, or else there will not be a unique deepest block.
532         DEBUG_ONLY(assert_dom(deepb, inb, load, cfg));
533         deepb = inb;                      // Save deepest block
534         deepb_dom_depth = deepb->_dom_depth;
535       }
536     }
537     early = deepb;
538   }
539 
540   return early;
541 }
542 
543 //--------------------------insert_anti_dependences---------------------------
544 // A load may need to witness memory that nearby stores can overwrite.
545 // For each nearby store, either insert an "anti-dependence" edge
546 // from the load to the store, or else move LCA upward to force the
547 // load to (eventually) be scheduled in a block above the store.
548 //
549 // Do not add edges to stores on distinct control-flow paths;
550 // only add edges to stores which might interfere.
551 //
552 // Return the (updated) LCA.  There will not be any possibly interfering
553 // store between the load's "early block" and the updated LCA.
554 // Any stores in the updated LCA will have new precedence edges
555 // back to the load.  The caller is expected to schedule the load
556 // in the LCA, in which case the precedence edges will make LCM
557 // preserve anti-dependences.  The caller may also hoist the load
558 // above the LCA, if it is not the early block.
insert_anti_dependences(Block * LCA,Node * load,bool verify)559 Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) {
560   assert(load->needs_anti_dependence_check(), "must be a load of some sort");
561   assert(LCA != NULL, "");
562   DEBUG_ONLY(Block* LCA_orig = LCA);
563 
564   // Compute the alias index.  Loads and stores with different alias indices
565   // do not need anti-dependence edges.
566   int load_alias_idx = C->get_alias_index(load->adr_type());
567 #ifdef ASSERT
568   assert(Compile::AliasIdxTop <= load_alias_idx && load_alias_idx < C->num_alias_types(), "Invalid alias index");
569   if (load_alias_idx == Compile::AliasIdxBot && C->AliasLevel() > 0 &&
570       (PrintOpto || VerifyAliases ||
571        (PrintMiscellaneous && (WizardMode || Verbose)))) {
572     // Load nodes should not consume all of memory.
573     // Reporting a bottom type indicates a bug in adlc.
574     // If some particular type of node validly consumes all of memory,
575     // sharpen the preceding "if" to exclude it, so we can catch bugs here.
576     tty->print_cr("*** Possible Anti-Dependence Bug:  Load consumes all of memory.");
577     load->dump(2);
578     if (VerifyAliases)  assert(load_alias_idx != Compile::AliasIdxBot, "");
579   }
580 #endif
581 
582   if (!C->alias_type(load_alias_idx)->is_rewritable()) {
583     // It is impossible to spoil this load by putting stores before it,
584     // because we know that the stores will never update the value
585     // which 'load' must witness.
586     return LCA;
587   }
588 
589   node_idx_t load_index = load->_idx;
590 
591   // Note the earliest legal placement of 'load', as determined by
592   // by the unique point in the dom tree where all memory effects
593   // and other inputs are first available.  (Computed by schedule_early.)
594   // For normal loads, 'early' is the shallowest place (dom graph wise)
595   // to look for anti-deps between this load and any store.
596   Block* early = get_block_for_node(load);
597 
598   // If we are subsuming loads, compute an "early" block that only considers
599   // memory or address inputs. This block may be different than the
600   // schedule_early block in that it could be at an even shallower depth in the
601   // dominator tree, and allow for a broader discovery of anti-dependences.
602   if (C->subsume_loads()) {
603     early = memory_early_block(load, early, this);
604   }
605 
606   ResourceArea *area = Thread::current()->resource_area();
607   Node_List worklist_mem(area);     // prior memory state to store
608   Node_List worklist_store(area);   // possible-def to explore
609   Node_List worklist_visited(area); // visited mergemem nodes
610   Node_List non_early_stores(area); // all relevant stores outside of early
611   bool must_raise_LCA = false;
612 
613   // 'load' uses some memory state; look for users of the same state.
614   // Recurse through MergeMem nodes to the stores that use them.
615 
616   // Each of these stores is a possible definition of memory
617   // that 'load' needs to use.  We need to force 'load'
618   // to occur before each such store.  When the store is in
619   // the same block as 'load', we insert an anti-dependence
620   // edge load->store.
621 
622   // The relevant stores "nearby" the load consist of a tree rooted
623   // at initial_mem, with internal nodes of type MergeMem.
624   // Therefore, the branches visited by the worklist are of this form:
625   //    initial_mem -> (MergeMem ->)* store
626   // The anti-dependence constraints apply only to the fringe of this tree.
627 
628   Node* initial_mem = load->in(MemNode::Memory);
629   worklist_store.push(initial_mem);
630   worklist_visited.push(initial_mem);
631   worklist_mem.push(NULL);
632   while (worklist_store.size() > 0) {
633     // Examine a nearby store to see if it might interfere with our load.
634     Node* mem   = worklist_mem.pop();
635     Node* store = worklist_store.pop();
636     uint op = store->Opcode();
637 
638     // MergeMems do not directly have anti-deps.
639     // Treat them as internal nodes in a forward tree of memory states,
640     // the leaves of which are each a 'possible-def'.
641     if (store == initial_mem    // root (exclusive) of tree we are searching
642         || op == Op_MergeMem    // internal node of tree we are searching
643         ) {
644       mem = store;   // It's not a possibly interfering store.
645       if (store == initial_mem)
646         initial_mem = NULL;  // only process initial memory once
647 
648       for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
649         store = mem->fast_out(i);
650         if (store->is_MergeMem()) {
651           // Be sure we don't get into combinatorial problems.
652           // (Allow phis to be repeated; they can merge two relevant states.)
653           uint j = worklist_visited.size();
654           for (; j > 0; j--) {
655             if (worklist_visited.at(j-1) == store)  break;
656           }
657           if (j > 0)  continue; // already on work list; do not repeat
658           worklist_visited.push(store);
659         }
660         worklist_mem.push(mem);
661         worklist_store.push(store);
662       }
663       continue;
664     }
665 
666     if (op == Op_MachProj || op == Op_Catch)   continue;
667     if (store->needs_anti_dependence_check())  continue;  // not really a store
668 
669     // Compute the alias index.  Loads and stores with different alias
670     // indices do not need anti-dependence edges.  Wide MemBar's are
671     // anti-dependent on everything (except immutable memories).
672     const TypePtr* adr_type = store->adr_type();
673     if (!C->can_alias(adr_type, load_alias_idx))  continue;
674 
675     // Most slow-path runtime calls do NOT modify Java memory, but
676     // they can block and so write Raw memory.
677     if (store->is_Mach()) {
678       MachNode* mstore = store->as_Mach();
679       if (load_alias_idx != Compile::AliasIdxRaw) {
680         // Check for call into the runtime using the Java calling
681         // convention (and from there into a wrapper); it has no
682         // _method.  Can't do this optimization for Native calls because
683         // they CAN write to Java memory.
684         if (mstore->ideal_Opcode() == Op_CallStaticJava) {
685           assert(mstore->is_MachSafePoint(), "");
686           MachSafePointNode* ms = (MachSafePointNode*) mstore;
687           assert(ms->is_MachCallJava(), "");
688           MachCallJavaNode* mcj = (MachCallJavaNode*) ms;
689           if (mcj->_method == NULL) {
690             // These runtime calls do not write to Java visible memory
691             // (other than Raw) and so do not require anti-dependence edges.
692             continue;
693           }
694         }
695         // Same for SafePoints: they read/write Raw but only read otherwise.
696         // This is basically a workaround for SafePoints only defining control
697         // instead of control + memory.
698         if (mstore->ideal_Opcode() == Op_SafePoint)
699           continue;
700       } else {
701         // Some raw memory, such as the load of "top" at an allocation,
702         // can be control dependent on the previous safepoint. See
703         // comments in GraphKit::allocate_heap() about control input.
704         // Inserting an anti-dep between such a safepoint and a use
705         // creates a cycle, and will cause a subsequent failure in
706         // local scheduling.  (BugId 4919904)
707         // (%%% How can a control input be a safepoint and not a projection??)
708         if (mstore->ideal_Opcode() == Op_SafePoint && load->in(0) == mstore)
709           continue;
710       }
711     }
712 
713     // Identify a block that the current load must be above,
714     // or else observe that 'store' is all the way up in the
715     // earliest legal block for 'load'.  In the latter case,
716     // immediately insert an anti-dependence edge.
717     Block* store_block = get_block_for_node(store);
718     assert(store_block != NULL, "unused killing projections skipped above");
719 
720     if (store->is_Phi()) {
721       // Loop-phis need to raise load before input. (Other phis are treated
722       // as store below.)
723       //
724       // 'load' uses memory which is one (or more) of the Phi's inputs.
725       // It must be scheduled not before the Phi, but rather before
726       // each of the relevant Phi inputs.
727       //
728       // Instead of finding the LCA of all inputs to a Phi that match 'mem',
729       // we mark each corresponding predecessor block and do a combined
730       // hoisting operation later (raise_LCA_above_marks).
731       //
732       // Do not assert(store_block != early, "Phi merging memory after access")
733       // PhiNode may be at start of block 'early' with backedge to 'early'
734       DEBUG_ONLY(bool found_match = false);
735       for (uint j = PhiNode::Input, jmax = store->req(); j < jmax; j++) {
736         if (store->in(j) == mem) {   // Found matching input?
737           DEBUG_ONLY(found_match = true);
738           Block* pred_block = get_block_for_node(store_block->pred(j));
739           if (pred_block != early) {
740             // If any predecessor of the Phi matches the load's "early block",
741             // we do not need a precedence edge between the Phi and 'load'
742             // since the load will be forced into a block preceding the Phi.
743             pred_block->set_raise_LCA_mark(load_index);
744             assert(!LCA_orig->dominates(pred_block) ||
745                    early->dominates(pred_block), "early is high enough");
746             must_raise_LCA = true;
747           } else {
748             // anti-dependent upon PHI pinned below 'early', no edge needed
749             LCA = early;             // but can not schedule below 'early'
750           }
751         }
752       }
753       assert(found_match, "no worklist bug");
754     } else if (store_block != early) {
755       // 'store' is between the current LCA and earliest possible block.
756       // Label its block, and decide later on how to raise the LCA
757       // to include the effect on LCA of this store.
758       // If this store's block gets chosen as the raised LCA, we
759       // will find him on the non_early_stores list and stick him
760       // with a precedence edge.
761       // (But, don't bother if LCA is already raised all the way.)
762       if (LCA != early) {
763         store_block->set_raise_LCA_mark(load_index);
764         must_raise_LCA = true;
765         non_early_stores.push(store);
766       }
767     } else {
768       // Found a possibly-interfering store in the load's 'early' block.
769       // This means 'load' cannot sink at all in the dominator tree.
770       // Add an anti-dep edge, and squeeze 'load' into the highest block.
771       assert(store != load->find_exact_control(load->in(0)), "dependence cycle found");
772       if (verify) {
773         assert(store->find_edge(load) != -1, "missing precedence edge");
774       } else {
775         store->add_prec(load);
776       }
777       LCA = early;
778       // This turns off the process of gathering non_early_stores.
779     }
780   }
781   // (Worklist is now empty; all nearby stores have been visited.)
782 
783   // Finished if 'load' must be scheduled in its 'early' block.
784   // If we found any stores there, they have already been given
785   // precedence edges.
786   if (LCA == early)  return LCA;
787 
788   // We get here only if there are no possibly-interfering stores
789   // in the load's 'early' block.  Move LCA up above all predecessors
790   // which contain stores we have noted.
791   //
792   // The raised LCA block can be a home to such interfering stores,
793   // but its predecessors must not contain any such stores.
794   //
795   // The raised LCA will be a lower bound for placing the load,
796   // preventing the load from sinking past any block containing
797   // a store that may invalidate the memory state required by 'load'.
798   if (must_raise_LCA)
799     LCA = raise_LCA_above_marks(LCA, load->_idx, early, this);
800   if (LCA == early)  return LCA;
801 
802   // Insert anti-dependence edges from 'load' to each store
803   // in the non-early LCA block.
804   // Mine the non_early_stores list for such stores.
805   if (LCA->raise_LCA_mark() == load_index) {
806     while (non_early_stores.size() > 0) {
807       Node* store = non_early_stores.pop();
808       Block* store_block = get_block_for_node(store);
809       if (store_block == LCA) {
810         // add anti_dependence from store to load in its own block
811         assert(store != load->find_exact_control(load->in(0)), "dependence cycle found");
812         if (verify) {
813           assert(store->find_edge(load) != -1, "missing precedence edge");
814         } else {
815           store->add_prec(load);
816         }
817       } else {
818         assert(store_block->raise_LCA_mark() == load_index, "block was marked");
819         // Any other stores we found must be either inside the new LCA
820         // or else outside the original LCA.  In the latter case, they
821         // did not interfere with any use of 'load'.
822         assert(LCA->dominates(store_block)
823                || !LCA_orig->dominates(store_block), "no stray stores");
824       }
825     }
826   }
827 
828   // Return the highest block containing stores; any stores
829   // within that block have been given anti-dependence edges.
830   return LCA;
831 }
832 
833 // This class is used to iterate backwards over the nodes in the graph.
834 
835 class Node_Backward_Iterator {
836 
837 private:
838   Node_Backward_Iterator();
839 
840 public:
841   // Constructor for the iterator
842   Node_Backward_Iterator(Node *root, VectorSet &visited, Node_Stack &stack, PhaseCFG &cfg);
843 
844   // Postincrement operator to iterate over the nodes
845   Node *next();
846 
847 private:
848   VectorSet   &_visited;
849   Node_Stack  &_stack;
850   PhaseCFG &_cfg;
851 };
852 
853 // Constructor for the Node_Backward_Iterator
Node_Backward_Iterator(Node * root,VectorSet & visited,Node_Stack & stack,PhaseCFG & cfg)854 Node_Backward_Iterator::Node_Backward_Iterator( Node *root, VectorSet &visited, Node_Stack &stack, PhaseCFG &cfg)
855   : _visited(visited), _stack(stack), _cfg(cfg) {
856   // The stack should contain exactly the root
857   stack.clear();
858   stack.push(root, root->outcnt());
859 
860   // Clear the visited bits
861   visited.clear();
862 }
863 
864 // Iterator for the Node_Backward_Iterator
next()865 Node *Node_Backward_Iterator::next() {
866 
867   // If the _stack is empty, then just return NULL: finished.
868   if ( !_stack.size() )
869     return NULL;
870 
871   // I visit unvisited not-anti-dependence users first, then anti-dependent
872   // children next. I iterate backwards to support removal of nodes.
873   // The stack holds states consisting of 3 values:
874   // current Def node, flag which indicates 1st/2nd pass, index of current out edge
875   Node *self = (Node*)(((uintptr_t)_stack.node()) & ~1);
876   bool iterate_anti_dep = (((uintptr_t)_stack.node()) & 1);
877   uint idx = MIN2(_stack.index(), self->outcnt()); // Support removal of nodes.
878   _stack.pop();
879 
880   // I cycle here when I am entering a deeper level of recursion.
881   // The key variable 'self' was set prior to jumping here.
882   while( 1 ) {
883 
884     _visited.set(self->_idx);
885 
886     // Now schedule all uses as late as possible.
887     const Node* src = self->is_Proj() ? self->in(0) : self;
888     uint src_rpo = _cfg.get_block_for_node(src)->_rpo;
889 
890     // Schedule all nodes in a post-order visit
891     Node *unvisited = NULL;  // Unvisited anti-dependent Node, if any
892 
893     // Scan for unvisited nodes
894     while (idx > 0) {
895       // For all uses, schedule late
896       Node* n = self->raw_out(--idx); // Use
897 
898       // Skip already visited children
899       if ( _visited.test(n->_idx) )
900         continue;
901 
902       // do not traverse backward control edges
903       Node *use = n->is_Proj() ? n->in(0) : n;
904       uint use_rpo = _cfg.get_block_for_node(use)->_rpo;
905 
906       if ( use_rpo < src_rpo )
907         continue;
908 
909       // Phi nodes always precede uses in a basic block
910       if ( use_rpo == src_rpo && use->is_Phi() )
911         continue;
912 
913       unvisited = n;      // Found unvisited
914 
915       // Check for possible-anti-dependent
916       // 1st pass: No such nodes, 2nd pass: Only such nodes.
917       if (n->needs_anti_dependence_check() == iterate_anti_dep) {
918         unvisited = n;      // Found unvisited
919         break;
920       }
921     }
922 
923     // Did I find an unvisited not-anti-dependent Node?
924     if (!unvisited) {
925       if (!iterate_anti_dep) {
926         // 2nd pass: Iterate over nodes which needs_anti_dependence_check.
927         iterate_anti_dep = true;
928         idx = self->outcnt();
929         continue;
930       }
931       break;                  // All done with children; post-visit 'self'
932     }
933 
934     // Visit the unvisited Node.  Contains the obvious push to
935     // indicate I'm entering a deeper level of recursion.  I push the
936     // old state onto the _stack and set a new state and loop (recurse).
937     _stack.push((Node*)((uintptr_t)self | (uintptr_t)iterate_anti_dep), idx);
938     self = unvisited;
939     iterate_anti_dep = false;
940     idx = self->outcnt();
941   } // End recursion loop
942 
943   return self;
944 }
945 
946 //------------------------------ComputeLatenciesBackwards----------------------
947 // Compute the latency of all the instructions.
compute_latencies_backwards(VectorSet & visited,Node_Stack & stack)948 void PhaseCFG::compute_latencies_backwards(VectorSet &visited, Node_Stack &stack) {
949 #ifndef PRODUCT
950   if (trace_opto_pipelining())
951     tty->print("\n#---- ComputeLatenciesBackwards ----\n");
952 #endif
953 
954   Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);
955   Node *n;
956 
957   // Walk over all the nodes from last to first
958   while ((n = iter.next())) {
959     // Set the latency for the definitions of this instruction
960     partial_latency_of_defs(n);
961   }
962 } // end ComputeLatenciesBackwards
963 
964 //------------------------------partial_latency_of_defs------------------------
965 // Compute the latency impact of this node on all defs.  This computes
966 // a number that increases as we approach the beginning of the routine.
partial_latency_of_defs(Node * n)967 void PhaseCFG::partial_latency_of_defs(Node *n) {
968   // Set the latency for this instruction
969 #ifndef PRODUCT
970   if (trace_opto_pipelining()) {
971     tty->print("# latency_to_inputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));
972     dump();
973   }
974 #endif
975 
976   if (n->is_Proj()) {
977     n = n->in(0);
978   }
979 
980   if (n->is_Root()) {
981     return;
982   }
983 
984   uint nlen = n->len();
985   uint use_latency = get_latency_for_node(n);
986   uint use_pre_order = get_block_for_node(n)->_pre_order;
987 
988   for (uint j = 0; j < nlen; j++) {
989     Node *def = n->in(j);
990 
991     if (!def || def == n) {
992       continue;
993     }
994 
995     // Walk backwards thru projections
996     if (def->is_Proj()) {
997       def = def->in(0);
998     }
999 
1000 #ifndef PRODUCT
1001     if (trace_opto_pipelining()) {
1002       tty->print("#    in(%2d): ", j);
1003       def->dump();
1004     }
1005 #endif
1006 
1007     // If the defining block is not known, assume it is ok
1008     Block *def_block = get_block_for_node(def);
1009     uint def_pre_order = def_block ? def_block->_pre_order : 0;
1010 
1011     if ((use_pre_order <  def_pre_order) || (use_pre_order == def_pre_order && n->is_Phi())) {
1012       continue;
1013     }
1014 
1015     uint delta_latency = n->latency(j);
1016     uint current_latency = delta_latency + use_latency;
1017 
1018     if (get_latency_for_node(def) < current_latency) {
1019       set_latency_for_node(def, current_latency);
1020     }
1021 
1022 #ifndef PRODUCT
1023     if (trace_opto_pipelining()) {
1024       tty->print_cr("#      %d + edge_latency(%d) == %d -> %d, node_latency[%d] = %d", use_latency, j, delta_latency, current_latency, def->_idx, get_latency_for_node(def));
1025     }
1026 #endif
1027   }
1028 }
1029 
1030 //------------------------------latency_from_use-------------------------------
1031 // Compute the latency of a specific use
latency_from_use(Node * n,const Node * def,Node * use)1032 int PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) {
1033   // If self-reference, return no latency
1034   if (use == n || use->is_Root()) {
1035     return 0;
1036   }
1037 
1038   uint def_pre_order = get_block_for_node(def)->_pre_order;
1039   uint latency = 0;
1040 
1041   // If the use is not a projection, then it is simple...
1042   if (!use->is_Proj()) {
1043 #ifndef PRODUCT
1044     if (trace_opto_pipelining()) {
1045       tty->print("#    out(): ");
1046       use->dump();
1047     }
1048 #endif
1049 
1050     uint use_pre_order = get_block_for_node(use)->_pre_order;
1051 
1052     if (use_pre_order < def_pre_order)
1053       return 0;
1054 
1055     if (use_pre_order == def_pre_order && use->is_Phi())
1056       return 0;
1057 
1058     uint nlen = use->len();
1059     uint nl = get_latency_for_node(use);
1060 
1061     for ( uint j=0; j<nlen; j++ ) {
1062       if (use->in(j) == n) {
1063         // Change this if we want local latencies
1064         uint ul = use->latency(j);
1065         uint  l = ul + nl;
1066         if (latency < l) latency = l;
1067 #ifndef PRODUCT
1068         if (trace_opto_pipelining()) {
1069           tty->print_cr("#      %d + edge_latency(%d) == %d -> %d, latency = %d",
1070                         nl, j, ul, l, latency);
1071         }
1072 #endif
1073       }
1074     }
1075   } else {
1076     // This is a projection, just grab the latency of the use(s)
1077     for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) {
1078       uint l = latency_from_use(use, def, use->fast_out(j));
1079       if (latency < l) latency = l;
1080     }
1081   }
1082 
1083   return latency;
1084 }
1085 
1086 //------------------------------latency_from_uses------------------------------
1087 // Compute the latency of this instruction relative to all of it's uses.
1088 // This computes a number that increases as we approach the beginning of the
1089 // routine.
latency_from_uses(Node * n)1090 void PhaseCFG::latency_from_uses(Node *n) {
1091   // Set the latency for this instruction
1092 #ifndef PRODUCT
1093   if (trace_opto_pipelining()) {
1094     tty->print("# latency_from_outputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));
1095     dump();
1096   }
1097 #endif
1098   uint latency=0;
1099   const Node *def = n->is_Proj() ? n->in(0): n;
1100 
1101   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1102     uint l = latency_from_use(n, def, n->fast_out(i));
1103 
1104     if (latency < l) latency = l;
1105   }
1106 
1107   set_latency_for_node(n, latency);
1108 }
1109 
1110 //------------------------------hoist_to_cheaper_block-------------------------
1111 // Pick a block for node self, between early and LCA, that is a cheaper
1112 // alternative to LCA.
hoist_to_cheaper_block(Block * LCA,Block * early,Node * self)1113 Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) {
1114   const double delta = 1+PROB_UNLIKELY_MAG(4);
1115   Block* least       = LCA;
1116   double least_freq  = least->_freq;
1117   uint target        = get_latency_for_node(self);
1118   uint start_latency = get_latency_for_node(LCA->head());
1119   uint end_latency   = get_latency_for_node(LCA->get_node(LCA->end_idx()));
1120   bool in_latency    = (target <= start_latency);
1121   const Block* root_block = get_block_for_node(_root);
1122 
1123   // Turn off latency scheduling if scheduling is just plain off
1124   if (!C->do_scheduling())
1125     in_latency = true;
1126 
1127   // Do not hoist (to cover latency) instructions which target a
1128   // single register.  Hoisting stretches the live range of the
1129   // single register and may force spilling.
1130   MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
1131   if (mach && mach->out_RegMask().is_bound1() && mach->out_RegMask().is_NotEmpty())
1132     in_latency = true;
1133 
1134 #ifndef PRODUCT
1135   if (trace_opto_pipelining()) {
1136     tty->print("# Find cheaper block for latency %d: ", get_latency_for_node(self));
1137     self->dump();
1138     tty->print_cr("#   B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
1139       LCA->_pre_order,
1140       LCA->head()->_idx,
1141       start_latency,
1142       LCA->get_node(LCA->end_idx())->_idx,
1143       end_latency,
1144       least_freq);
1145   }
1146 #endif
1147 
1148   int cand_cnt = 0;  // number of candidates tried
1149 
1150   // Walk up the dominator tree from LCA (Lowest common ancestor) to
1151   // the earliest legal location.  Capture the least execution frequency.
1152   while (LCA != early) {
1153     LCA = LCA->_idom;         // Follow up the dominator tree
1154 
1155     if (LCA == NULL) {
1156       // Bailout without retry
1157       assert(false, "graph should be schedulable");
1158       C->record_method_not_compilable("late schedule failed: LCA == NULL");
1159       return least;
1160     }
1161 
1162     // Don't hoist machine instructions to the root basic block
1163     if (mach && LCA == root_block)
1164       break;
1165 
1166     uint start_lat = get_latency_for_node(LCA->head());
1167     uint end_idx   = LCA->end_idx();
1168     uint end_lat   = get_latency_for_node(LCA->get_node(end_idx));
1169     double LCA_freq = LCA->_freq;
1170 #ifndef PRODUCT
1171     if (trace_opto_pipelining()) {
1172       tty->print_cr("#   B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
1173         LCA->_pre_order, LCA->head()->_idx, start_lat, end_idx, end_lat, LCA_freq);
1174     }
1175 #endif
1176     cand_cnt++;
1177     if (LCA_freq < least_freq              || // Better Frequency
1178         (StressGCM && C->randomized_select(cand_cnt)) || // Should be randomly accepted in stress mode
1179          (!StressGCM                    &&    // Otherwise, choose with latency
1180           !in_latency                   &&    // No block containing latency
1181           LCA_freq < least_freq * delta &&    // No worse frequency
1182           target >= end_lat             &&    // within latency range
1183           !self->is_iteratively_computed() )  // But don't hoist IV increments
1184              // because they may end up above other uses of their phi forcing
1185              // their result register to be different from their input.
1186        ) {
1187       least = LCA;            // Found cheaper block
1188       least_freq = LCA_freq;
1189       start_latency = start_lat;
1190       end_latency = end_lat;
1191       if (target <= start_lat)
1192         in_latency = true;
1193     }
1194   }
1195 
1196 #ifndef PRODUCT
1197   if (trace_opto_pipelining()) {
1198     tty->print_cr("#  Choose block B%d with start latency=%d and freq=%g",
1199       least->_pre_order, start_latency, least_freq);
1200   }
1201 #endif
1202 
1203   // See if the latency needs to be updated
1204   if (target < end_latency) {
1205 #ifndef PRODUCT
1206     if (trace_opto_pipelining()) {
1207       tty->print_cr("#  Change latency for [%4d] from %d to %d", self->_idx, target, end_latency);
1208     }
1209 #endif
1210     set_latency_for_node(self, end_latency);
1211     partial_latency_of_defs(self);
1212   }
1213 
1214   return least;
1215 }
1216 
1217 
1218 //------------------------------schedule_late-----------------------------------
1219 // Now schedule all codes as LATE as possible.  This is the LCA in the
1220 // dominator tree of all USES of a value.  Pick the block with the least
1221 // loop nesting depth that is lowest in the dominator tree.
1222 extern const char must_clone[];
schedule_late(VectorSet & visited,Node_Stack & stack)1223 void PhaseCFG::schedule_late(VectorSet &visited, Node_Stack &stack) {
1224 #ifndef PRODUCT
1225   if (trace_opto_pipelining())
1226     tty->print("\n#---- schedule_late ----\n");
1227 #endif
1228 
1229   Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);
1230   Node *self;
1231 
1232   // Walk over all the nodes from last to first
1233   while ((self = iter.next())) {
1234     Block* early = get_block_for_node(self); // Earliest legal placement
1235 
1236     if (self->is_top()) {
1237       // Top node goes in bb #2 with other constants.
1238       // It must be special-cased, because it has no out edges.
1239       early->add_inst(self);
1240       continue;
1241     }
1242 
1243     // No uses, just terminate
1244     if (self->outcnt() == 0) {
1245       assert(self->is_MachProj(), "sanity");
1246       continue;                   // Must be a dead machine projection
1247     }
1248 
1249     // If node is pinned in the block, then no scheduling can be done.
1250     if( self->pinned() )          // Pinned in block?
1251       continue;
1252 
1253     MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
1254     if (mach) {
1255       switch (mach->ideal_Opcode()) {
1256       case Op_CreateEx:
1257         // Don't move exception creation
1258         early->add_inst(self);
1259         continue;
1260         break;
1261       case Op_CheckCastPP: {
1262         // Don't move CheckCastPP nodes away from their input, if the input
1263         // is a rawptr (5071820).
1264         Node *def = self->in(1);
1265         if (def != NULL && def->bottom_type()->base() == Type::RawPtr) {
1266           early->add_inst(self);
1267 #ifdef ASSERT
1268           _raw_oops.push(def);
1269 #endif
1270           continue;
1271         }
1272         break;
1273       }
1274       default:
1275         break;
1276       }
1277       if (C->has_irreducible_loop() && self->bottom_type()->has_memory()) {
1278         // If the CFG is irreducible, keep memory-writing nodes as close as
1279         // possible to their original block (given by the control input). This
1280         // prevents PhaseCFG::hoist_to_cheaper_block() from placing such nodes
1281         // into descendants of their original loop, as in the following example:
1282         //
1283         // Original placement of store in B1 (loop L1):
1284         //
1285         // B1 (L1):
1286         //   m1 <- ..
1287         //   m2 <- store m1, ..
1288         // B2 (L2):
1289         //   jump B2
1290         // B3 (L1):
1291         //   .. <- .. m2, ..
1292         //
1293         // Wrong "hoisting" of store to B2 (in loop L2, child of L1):
1294         //
1295         // B1 (L1):
1296         //   m1 <- ..
1297         // B2 (L2):
1298         //   m2 <- store m1, ..
1299         //   # Wrong: m1 and m2 interfere at this point.
1300         //   jump B2
1301         // B3 (L1):
1302         //   .. <- .. m2, ..
1303         //
1304         // This "hoist inversion" can happen due to CFGLoop::compute_freq()'s
1305         // inaccurate estimation of frequencies for irreducible CFGs, which can
1306         // lead to for example assigning B1 and B3 a higher frequency than B2.
1307 #ifndef PRODUCT
1308         if (trace_opto_pipelining()) {
1309           tty->print_cr("# Irreducible loops: schedule in earliest block B%d:",
1310                         early->_pre_order);
1311           self->dump();
1312         }
1313 #endif
1314         schedule_node_into_block(self, early);
1315         continue;
1316       }
1317     }
1318 
1319     // Gather LCA of all uses
1320     Block *LCA = NULL;
1321     {
1322       for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
1323         // For all uses, find LCA
1324         Node* use = self->fast_out(i);
1325         LCA = raise_LCA_above_use(LCA, use, self, this);
1326       }
1327       guarantee(LCA != NULL, "There must be a LCA");
1328     }  // (Hide defs of imax, i from rest of block.)
1329 
1330     // Place temps in the block of their use.  This isn't a
1331     // requirement for correctness but it reduces useless
1332     // interference between temps and other nodes.
1333     if (mach != NULL && mach->is_MachTemp()) {
1334       map_node_to_block(self, LCA);
1335       LCA->add_inst(self);
1336       continue;
1337     }
1338 
1339     // Check if 'self' could be anti-dependent on memory
1340     if (self->needs_anti_dependence_check()) {
1341       // Hoist LCA above possible-defs and insert anti-dependences to
1342       // defs in new LCA block.
1343       LCA = insert_anti_dependences(LCA, self);
1344     }
1345 
1346     if (early->_dom_depth > LCA->_dom_depth) {
1347       // Somehow the LCA has moved above the earliest legal point.
1348       // (One way this can happen is via memory_early_block.)
1349       if (C->subsume_loads() == true && !C->failing()) {
1350         // Retry with subsume_loads == false
1351         // If this is the first failure, the sentinel string will "stick"
1352         // to the Compile object, and the C2Compiler will see it and retry.
1353         C->record_failure(C2Compiler::retry_no_subsuming_loads());
1354       } else {
1355         // Bailout without retry when (early->_dom_depth > LCA->_dom_depth)
1356         assert(false, "graph should be schedulable");
1357         C->record_method_not_compilable("late schedule failed: incorrect graph");
1358       }
1359       return;
1360     }
1361 
1362     // If there is no opportunity to hoist, then we're done.
1363     // In stress mode, try to hoist even the single operations.
1364     bool try_to_hoist = StressGCM || (LCA != early);
1365 
1366     // Must clone guys stay next to use; no hoisting allowed.
1367     // Also cannot hoist guys that alter memory or are otherwise not
1368     // allocatable (hoisting can make a value live longer, leading to
1369     // anti and output dependency problems which are normally resolved
1370     // by the register allocator giving everyone a different register).
1371     if (mach != NULL && must_clone[mach->ideal_Opcode()])
1372       try_to_hoist = false;
1373 
1374     Block* late = NULL;
1375     if (try_to_hoist) {
1376       // Now find the block with the least execution frequency.
1377       // Start at the latest schedule and work up to the earliest schedule
1378       // in the dominator tree.  Thus the Node will dominate all its uses.
1379       late = hoist_to_cheaper_block(LCA, early, self);
1380     } else {
1381       // Just use the LCA of the uses.
1382       late = LCA;
1383     }
1384 
1385     // Put the node into target block
1386     schedule_node_into_block(self, late);
1387 
1388 #ifdef ASSERT
1389     if (self->needs_anti_dependence_check()) {
1390       // since precedence edges are only inserted when we're sure they
1391       // are needed make sure that after placement in a block we don't
1392       // need any new precedence edges.
1393       verify_anti_dependences(late, self);
1394     }
1395 #endif
1396   } // Loop until all nodes have been visited
1397 
1398 } // end ScheduleLate
1399 
1400 //------------------------------GlobalCodeMotion-------------------------------
global_code_motion()1401 void PhaseCFG::global_code_motion() {
1402   ResourceMark rm;
1403 
1404 #ifndef PRODUCT
1405   if (trace_opto_pipelining()) {
1406     tty->print("\n---- Start GlobalCodeMotion ----\n");
1407   }
1408 #endif
1409 
1410   // Initialize the node to block mapping for things on the proj_list
1411   for (uint i = 0; i < _matcher.number_of_projections(); i++) {
1412     unmap_node_from_block(_matcher.get_projection(i));
1413   }
1414 
1415   // Set the basic block for Nodes pinned into blocks
1416   VectorSet visited;
1417   schedule_pinned_nodes(visited);
1418 
1419   // Find the earliest Block any instruction can be placed in.  Some
1420   // instructions are pinned into Blocks.  Unpinned instructions can
1421   // appear in last block in which all their inputs occur.
1422   visited.clear();
1423   Node_Stack stack((C->live_nodes() >> 2) + 16); // pre-grow
1424   if (!schedule_early(visited, stack)) {
1425     // Bailout without retry
1426     C->record_method_not_compilable("early schedule failed");
1427     return;
1428   }
1429 
1430   // Build Def-Use edges.
1431   // Compute the latency information (via backwards walk) for all the
1432   // instructions in the graph
1433   _node_latency = new GrowableArray<uint>(); // resource_area allocation
1434 
1435   if (C->do_scheduling()) {
1436     compute_latencies_backwards(visited, stack);
1437   }
1438 
1439   // Now schedule all codes as LATE as possible.  This is the LCA in the
1440   // dominator tree of all USES of a value.  Pick the block with the least
1441   // loop nesting depth that is lowest in the dominator tree.
1442   // ( visited.clear() called in schedule_late()->Node_Backward_Iterator() )
1443   schedule_late(visited, stack);
1444   if (C->failing()) {
1445     return;
1446   }
1447 
1448 #ifndef PRODUCT
1449   if (trace_opto_pipelining()) {
1450     tty->print("\n---- Detect implicit null checks ----\n");
1451   }
1452 #endif
1453 
1454   // Detect implicit-null-check opportunities.  Basically, find NULL checks
1455   // with suitable memory ops nearby.  Use the memory op to do the NULL check.
1456   // I can generate a memory op if there is not one nearby.
1457   if (C->is_method_compilation()) {
1458     // By reversing the loop direction we get a very minor gain on mpegaudio.
1459     // Feel free to revert to a forward loop for clarity.
1460     // for( int i=0; i < (int)matcher._null_check_tests.size(); i+=2 ) {
1461     for (int i = _matcher._null_check_tests.size() - 2; i >= 0; i -= 2) {
1462       Node* proj = _matcher._null_check_tests[i];
1463       Node* val  = _matcher._null_check_tests[i + 1];
1464       Block* block = get_block_for_node(proj);
1465       implicit_null_check(block, proj, val, C->allowed_deopt_reasons());
1466       // The implicit_null_check will only perform the transformation
1467       // if the null branch is truly uncommon, *and* it leads to an
1468       // uncommon trap.  Combined with the too_many_traps guards
1469       // above, this prevents SEGV storms reported in 6366351,
1470       // by recompiling offending methods without this optimization.
1471     }
1472   }
1473 
1474   bool block_size_threshold_ok = false;
1475   intptr_t *recalc_pressure_nodes = NULL;
1476   if (OptoRegScheduling) {
1477     for (uint i = 0; i < number_of_blocks(); i++) {
1478       Block* block = get_block(i);
1479       if (block->number_of_nodes() > 10) {
1480         block_size_threshold_ok = true;
1481         break;
1482       }
1483     }
1484   }
1485 
1486   // Enabling the scheduler for register pressure plus finding blocks of size to schedule for it
1487   // is key to enabling this feature.
1488   PhaseChaitin regalloc(C->unique(), *this, _matcher, true);
1489   ResourceArea live_arena(mtCompiler);      // Arena for liveness
1490   ResourceMark rm_live(&live_arena);
1491   PhaseLive live(*this, regalloc._lrg_map.names(), &live_arena, true);
1492   PhaseIFG ifg(&live_arena);
1493   if (OptoRegScheduling && block_size_threshold_ok) {
1494     regalloc.mark_ssa();
1495     Compile::TracePhase tp("computeLive", &timers[_t_computeLive]);
1496     rm_live.reset_to_mark();           // Reclaim working storage
1497     IndexSet::reset_memory(C, &live_arena);
1498     uint node_size = regalloc._lrg_map.max_lrg_id();
1499     ifg.init(node_size); // Empty IFG
1500     regalloc.set_ifg(ifg);
1501     regalloc.set_live(live);
1502     regalloc.gather_lrg_masks(false);    // Collect LRG masks
1503     live.compute(node_size); // Compute liveness
1504 
1505     recalc_pressure_nodes = NEW_RESOURCE_ARRAY(intptr_t, node_size);
1506     for (uint i = 0; i < node_size; i++) {
1507       recalc_pressure_nodes[i] = 0;
1508     }
1509   }
1510   _regalloc = &regalloc;
1511 
1512 #ifndef PRODUCT
1513   if (trace_opto_pipelining()) {
1514     tty->print("\n---- Start Local Scheduling ----\n");
1515   }
1516 #endif
1517 
1518   // Schedule locally.  Right now a simple topological sort.
1519   // Later, do a real latency aware scheduler.
1520   GrowableArray<int> ready_cnt(C->unique(), C->unique(), -1);
1521   visited.reset();
1522   for (uint i = 0; i < number_of_blocks(); i++) {
1523     Block* block = get_block(i);
1524     if (!schedule_local(block, ready_cnt, visited, recalc_pressure_nodes)) {
1525       if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
1526         C->record_method_not_compilable("local schedule failed");
1527       }
1528       _regalloc = NULL;
1529       return;
1530     }
1531   }
1532   _regalloc = NULL;
1533 
1534   // If we inserted any instructions between a Call and his CatchNode,
1535   // clone the instructions on all paths below the Catch.
1536   for (uint i = 0; i < number_of_blocks(); i++) {
1537     Block* block = get_block(i);
1538     call_catch_cleanup(block);
1539   }
1540 
1541 #ifndef PRODUCT
1542   if (trace_opto_pipelining()) {
1543     tty->print("\n---- After GlobalCodeMotion ----\n");
1544     for (uint i = 0; i < number_of_blocks(); i++) {
1545       Block* block = get_block(i);
1546       block->dump();
1547     }
1548   }
1549 #endif
1550   // Dead.
1551   _node_latency = (GrowableArray<uint> *)((intptr_t)0xdeadbeef);
1552 }
1553 
do_global_code_motion()1554 bool PhaseCFG::do_global_code_motion() {
1555 
1556   build_dominator_tree();
1557   if (C->failing()) {
1558     return false;
1559   }
1560 
1561   NOT_PRODUCT( C->verify_graph_edges(); )
1562 
1563   estimate_block_frequency();
1564 
1565   global_code_motion();
1566 
1567   if (C->failing()) {
1568     return false;
1569   }
1570 
1571   return true;
1572 }
1573 
1574 //------------------------------Estimate_Block_Frequency-----------------------
1575 // Estimate block frequencies based on IfNode probabilities.
estimate_block_frequency()1576 void PhaseCFG::estimate_block_frequency() {
1577 
1578   // Force conditional branches leading to uncommon traps to be unlikely,
1579   // not because we get to the uncommon_trap with less relative frequency,
1580   // but because an uncommon_trap typically causes a deopt, so we only get
1581   // there once.
1582   if (C->do_freq_based_layout()) {
1583     Block_List worklist;
1584     Block* root_blk = get_block(0);
1585     for (uint i = 1; i < root_blk->num_preds(); i++) {
1586       Block *pb = get_block_for_node(root_blk->pred(i));
1587       if (pb->has_uncommon_code()) {
1588         worklist.push(pb);
1589       }
1590     }
1591     while (worklist.size() > 0) {
1592       Block* uct = worklist.pop();
1593       if (uct == get_root_block()) {
1594         continue;
1595       }
1596       for (uint i = 1; i < uct->num_preds(); i++) {
1597         Block *pb = get_block_for_node(uct->pred(i));
1598         if (pb->_num_succs == 1) {
1599           worklist.push(pb);
1600         } else if (pb->num_fall_throughs() == 2) {
1601           pb->update_uncommon_branch(uct);
1602         }
1603       }
1604     }
1605   }
1606 
1607   // Create the loop tree and calculate loop depth.
1608   _root_loop = create_loop_tree();
1609   _root_loop->compute_loop_depth(0);
1610 
1611   // Compute block frequency of each block, relative to a single loop entry.
1612   _root_loop->compute_freq();
1613 
1614   // Adjust all frequencies to be relative to a single method entry
1615   _root_loop->_freq = 1.0;
1616   _root_loop->scale_freq();
1617 
1618   // Save outmost loop frequency for LRG frequency threshold
1619   _outer_loop_frequency = _root_loop->outer_loop_freq();
1620 
1621   // force paths ending at uncommon traps to be infrequent
1622   if (!C->do_freq_based_layout()) {
1623     Block_List worklist;
1624     Block* root_blk = get_block(0);
1625     for (uint i = 1; i < root_blk->num_preds(); i++) {
1626       Block *pb = get_block_for_node(root_blk->pred(i));
1627       if (pb->has_uncommon_code()) {
1628         worklist.push(pb);
1629       }
1630     }
1631     while (worklist.size() > 0) {
1632       Block* uct = worklist.pop();
1633       uct->_freq = PROB_MIN;
1634       for (uint i = 1; i < uct->num_preds(); i++) {
1635         Block *pb = get_block_for_node(uct->pred(i));
1636         if (pb->_num_succs == 1 && pb->_freq > PROB_MIN) {
1637           worklist.push(pb);
1638         }
1639       }
1640     }
1641   }
1642 
1643 #ifdef ASSERT
1644   for (uint i = 0; i < number_of_blocks(); i++) {
1645     Block* b = get_block(i);
1646     assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency");
1647   }
1648 #endif
1649 
1650 #ifndef PRODUCT
1651   if (PrintCFGBlockFreq) {
1652     tty->print_cr("CFG Block Frequencies");
1653     _root_loop->dump_tree();
1654     if (Verbose) {
1655       tty->print_cr("PhaseCFG dump");
1656       dump();
1657       tty->print_cr("Node dump");
1658       _root->dump(99999);
1659     }
1660   }
1661 #endif
1662 }
1663 
1664 //----------------------------create_loop_tree--------------------------------
1665 // Create a loop tree from the CFG
create_loop_tree()1666 CFGLoop* PhaseCFG::create_loop_tree() {
1667 
1668 #ifdef ASSERT
1669   assert(get_block(0) == get_root_block(), "first block should be root block");
1670   for (uint i = 0; i < number_of_blocks(); i++) {
1671     Block* block = get_block(i);
1672     // Check that _loop field are clear...we could clear them if not.
1673     assert(block->_loop == NULL, "clear _loop expected");
1674     // Sanity check that the RPO numbering is reflected in the _blocks array.
1675     // It doesn't have to be for the loop tree to be built, but if it is not,
1676     // then the blocks have been reordered since dom graph building...which
1677     // may question the RPO numbering
1678     assert(block->_rpo == i, "unexpected reverse post order number");
1679   }
1680 #endif
1681 
1682   int idct = 0;
1683   CFGLoop* root_loop = new CFGLoop(idct++);
1684 
1685   Block_List worklist;
1686 
1687   // Assign blocks to loops
1688   for(uint i = number_of_blocks() - 1; i > 0; i-- ) { // skip Root block
1689     Block* block = get_block(i);
1690 
1691     if (block->head()->is_Loop()) {
1692       Block* loop_head = block;
1693       assert(loop_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
1694       Node* tail_n = loop_head->pred(LoopNode::LoopBackControl);
1695       Block* tail = get_block_for_node(tail_n);
1696 
1697       // Defensively filter out Loop nodes for non-single-entry loops.
1698       // For all reasonable loops, the head occurs before the tail in RPO.
1699       if (i <= tail->_rpo) {
1700 
1701         // The tail and (recursive) predecessors of the tail
1702         // are made members of a new loop.
1703 
1704         assert(worklist.size() == 0, "nonempty worklist");
1705         CFGLoop* nloop = new CFGLoop(idct++);
1706         assert(loop_head->_loop == NULL, "just checking");
1707         loop_head->_loop = nloop;
1708         // Add to nloop so push_pred() will skip over inner loops
1709         nloop->add_member(loop_head);
1710         nloop->push_pred(loop_head, LoopNode::LoopBackControl, worklist, this);
1711 
1712         while (worklist.size() > 0) {
1713           Block* member = worklist.pop();
1714           if (member != loop_head) {
1715             for (uint j = 1; j < member->num_preds(); j++) {
1716               nloop->push_pred(member, j, worklist, this);
1717             }
1718           }
1719         }
1720       }
1721     }
1722   }
1723 
1724   // Create a member list for each loop consisting
1725   // of both blocks and (immediate child) loops.
1726   for (uint i = 0; i < number_of_blocks(); i++) {
1727     Block* block = get_block(i);
1728     CFGLoop* lp = block->_loop;
1729     if (lp == NULL) {
1730       // Not assigned to a loop. Add it to the method's pseudo loop.
1731       block->_loop = root_loop;
1732       lp = root_loop;
1733     }
1734     if (lp == root_loop || block != lp->head()) { // loop heads are already members
1735       lp->add_member(block);
1736     }
1737     if (lp != root_loop) {
1738       if (lp->parent() == NULL) {
1739         // Not a nested loop. Make it a child of the method's pseudo loop.
1740         root_loop->add_nested_loop(lp);
1741       }
1742       if (block == lp->head()) {
1743         // Add nested loop to member list of parent loop.
1744         lp->parent()->add_member(lp);
1745       }
1746     }
1747   }
1748 
1749   return root_loop;
1750 }
1751 
1752 //------------------------------push_pred--------------------------------------
push_pred(Block * blk,int i,Block_List & worklist,PhaseCFG * cfg)1753 void CFGLoop::push_pred(Block* blk, int i, Block_List& worklist, PhaseCFG* cfg) {
1754   Node* pred_n = blk->pred(i);
1755   Block* pred = cfg->get_block_for_node(pred_n);
1756   CFGLoop *pred_loop = pred->_loop;
1757   if (pred_loop == NULL) {
1758     // Filter out blocks for non-single-entry loops.
1759     // For all reasonable loops, the head occurs before the tail in RPO.
1760     if (pred->_rpo > head()->_rpo) {
1761       pred->_loop = this;
1762       worklist.push(pred);
1763     }
1764   } else if (pred_loop != this) {
1765     // Nested loop.
1766     while (pred_loop->_parent != NULL && pred_loop->_parent != this) {
1767       pred_loop = pred_loop->_parent;
1768     }
1769     // Make pred's loop be a child
1770     if (pred_loop->_parent == NULL) {
1771       add_nested_loop(pred_loop);
1772       // Continue with loop entry predecessor.
1773       Block* pred_head = pred_loop->head();
1774       assert(pred_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
1775       assert(pred_head != head(), "loop head in only one loop");
1776       push_pred(pred_head, LoopNode::EntryControl, worklist, cfg);
1777     } else {
1778       assert(pred_loop->_parent == this && _parent == NULL, "just checking");
1779     }
1780   }
1781 }
1782 
1783 //------------------------------add_nested_loop--------------------------------
1784 // Make cl a child of the current loop in the loop tree.
add_nested_loop(CFGLoop * cl)1785 void CFGLoop::add_nested_loop(CFGLoop* cl) {
1786   assert(_parent == NULL, "no parent yet");
1787   assert(cl != this, "not my own parent");
1788   cl->_parent = this;
1789   CFGLoop* ch = _child;
1790   if (ch == NULL) {
1791     _child = cl;
1792   } else {
1793     while (ch->_sibling != NULL) { ch = ch->_sibling; }
1794     ch->_sibling = cl;
1795   }
1796 }
1797 
1798 //------------------------------compute_loop_depth-----------------------------
1799 // Store the loop depth in each CFGLoop object.
1800 // Recursively walk the children to do the same for them.
compute_loop_depth(int depth)1801 void CFGLoop::compute_loop_depth(int depth) {
1802   _depth = depth;
1803   CFGLoop* ch = _child;
1804   while (ch != NULL) {
1805     ch->compute_loop_depth(depth + 1);
1806     ch = ch->_sibling;
1807   }
1808 }
1809 
1810 //------------------------------compute_freq-----------------------------------
1811 // Compute the frequency of each block and loop, relative to a single entry
1812 // into the dominating loop head.
compute_freq()1813 void CFGLoop::compute_freq() {
1814   // Bottom up traversal of loop tree (visit inner loops first.)
1815   // Set loop head frequency to 1.0, then transitively
1816   // compute frequency for all successors in the loop,
1817   // as well as for each exit edge.  Inner loops are
1818   // treated as single blocks with loop exit targets
1819   // as the successor blocks.
1820 
1821   // Nested loops first
1822   CFGLoop* ch = _child;
1823   while (ch != NULL) {
1824     ch->compute_freq();
1825     ch = ch->_sibling;
1826   }
1827   assert (_members.length() > 0, "no empty loops");
1828   Block* hd = head();
1829   hd->_freq = 1.0;
1830   for (int i = 0; i < _members.length(); i++) {
1831     CFGElement* s = _members.at(i);
1832     double freq = s->_freq;
1833     if (s->is_block()) {
1834       Block* b = s->as_Block();
1835       for (uint j = 0; j < b->_num_succs; j++) {
1836         Block* sb = b->_succs[j];
1837         update_succ_freq(sb, freq * b->succ_prob(j));
1838       }
1839     } else {
1840       CFGLoop* lp = s->as_CFGLoop();
1841       assert(lp->_parent == this, "immediate child");
1842       for (int k = 0; k < lp->_exits.length(); k++) {
1843         Block* eb = lp->_exits.at(k).get_target();
1844         double prob = lp->_exits.at(k).get_prob();
1845         update_succ_freq(eb, freq * prob);
1846       }
1847     }
1848   }
1849 
1850   // For all loops other than the outer, "method" loop,
1851   // sum and normalize the exit probability. The "method" loop
1852   // should keep the initial exit probability of 1, so that
1853   // inner blocks do not get erroneously scaled.
1854   if (_depth != 0) {
1855     // Total the exit probabilities for this loop.
1856     double exits_sum = 0.0f;
1857     for (int i = 0; i < _exits.length(); i++) {
1858       exits_sum += _exits.at(i).get_prob();
1859     }
1860 
1861     // Normalize the exit probabilities. Until now, the
1862     // probabilities estimate the possibility of exit per
1863     // a single loop iteration; afterward, they estimate
1864     // the probability of exit per loop entry.
1865     for (int i = 0; i < _exits.length(); i++) {
1866       Block* et = _exits.at(i).get_target();
1867       float new_prob = 0.0f;
1868       if (_exits.at(i).get_prob() > 0.0f) {
1869         new_prob = _exits.at(i).get_prob() / exits_sum;
1870       }
1871       BlockProbPair bpp(et, new_prob);
1872       _exits.at_put(i, bpp);
1873     }
1874 
1875     // Save the total, but guard against unreasonable probability,
1876     // as the value is used to estimate the loop trip count.
1877     // An infinite trip count would blur relative block
1878     // frequencies.
1879     if (exits_sum > 1.0f) exits_sum = 1.0;
1880     if (exits_sum < PROB_MIN) exits_sum = PROB_MIN;
1881     _exit_prob = exits_sum;
1882   }
1883 }
1884 
1885 //------------------------------succ_prob-------------------------------------
1886 // Determine the probability of reaching successor 'i' from the receiver block.
succ_prob(uint i)1887 float Block::succ_prob(uint i) {
1888   int eidx = end_idx();
1889   Node *n = get_node(eidx);  // Get ending Node
1890 
1891   int op = n->Opcode();
1892   if (n->is_Mach()) {
1893     if (n->is_MachNullCheck()) {
1894       // Can only reach here if called after lcm. The original Op_If is gone,
1895       // so we attempt to infer the probability from one or both of the
1896       // successor blocks.
1897       assert(_num_succs == 2, "expecting 2 successors of a null check");
1898       // If either successor has only one predecessor, then the
1899       // probability estimate can be derived using the
1900       // relative frequency of the successor and this block.
1901       if (_succs[i]->num_preds() == 2) {
1902         return _succs[i]->_freq / _freq;
1903       } else if (_succs[1-i]->num_preds() == 2) {
1904         return 1 - (_succs[1-i]->_freq / _freq);
1905       } else {
1906         // Estimate using both successor frequencies
1907         float freq = _succs[i]->_freq;
1908         return freq / (freq + _succs[1-i]->_freq);
1909       }
1910     }
1911     op = n->as_Mach()->ideal_Opcode();
1912   }
1913 
1914 
1915   // Switch on branch type
1916   switch( op ) {
1917   case Op_CountedLoopEnd:
1918   case Op_If: {
1919     assert (i < 2, "just checking");
1920     // Conditionals pass on only part of their frequency
1921     float prob  = n->as_MachIf()->_prob;
1922     assert(prob >= 0.0 && prob <= 1.0, "out of range probability");
1923     // If succ[i] is the FALSE branch, invert path info
1924     if( get_node(i + eidx + 1)->Opcode() == Op_IfFalse ) {
1925       return 1.0f - prob; // not taken
1926     } else {
1927       return prob; // taken
1928     }
1929   }
1930 
1931   case Op_Jump:
1932     return n->as_MachJump()->_probs[get_node(i + eidx + 1)->as_JumpProj()->_con];
1933 
1934   case Op_Catch: {
1935     const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1936     if (ci->_con == CatchProjNode::fall_through_index) {
1937       // Fall-thru path gets the lion's share.
1938       return 1.0f - PROB_UNLIKELY_MAG(5)*_num_succs;
1939     } else {
1940       // Presume exceptional paths are equally unlikely
1941       return PROB_UNLIKELY_MAG(5);
1942     }
1943   }
1944 
1945   case Op_Root:
1946   case Op_Goto:
1947     // Pass frequency straight thru to target
1948     return 1.0f;
1949 
1950   case Op_NeverBranch:
1951     return 0.0f;
1952 
1953   case Op_TailCall:
1954   case Op_TailJump:
1955   case Op_Return:
1956   case Op_Halt:
1957   case Op_Rethrow:
1958     // Do not push out freq to root block
1959     return 0.0f;
1960 
1961   default:
1962     ShouldNotReachHere();
1963   }
1964 
1965   return 0.0f;
1966 }
1967 
1968 //------------------------------num_fall_throughs-----------------------------
1969 // Return the number of fall-through candidates for a block
num_fall_throughs()1970 int Block::num_fall_throughs() {
1971   int eidx = end_idx();
1972   Node *n = get_node(eidx);  // Get ending Node
1973 
1974   int op = n->Opcode();
1975   if (n->is_Mach()) {
1976     if (n->is_MachNullCheck()) {
1977       // In theory, either side can fall-thru, for simplicity sake,
1978       // let's say only the false branch can now.
1979       return 1;
1980     }
1981     op = n->as_Mach()->ideal_Opcode();
1982   }
1983 
1984   // Switch on branch type
1985   switch( op ) {
1986   case Op_CountedLoopEnd:
1987   case Op_If:
1988     return 2;
1989 
1990   case Op_Root:
1991   case Op_Goto:
1992     return 1;
1993 
1994   case Op_Catch: {
1995     for (uint i = 0; i < _num_succs; i++) {
1996       const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1997       if (ci->_con == CatchProjNode::fall_through_index) {
1998         return 1;
1999       }
2000     }
2001     return 0;
2002   }
2003 
2004   case Op_Jump:
2005   case Op_NeverBranch:
2006   case Op_TailCall:
2007   case Op_TailJump:
2008   case Op_Return:
2009   case Op_Halt:
2010   case Op_Rethrow:
2011     return 0;
2012 
2013   default:
2014     ShouldNotReachHere();
2015   }
2016 
2017   return 0;
2018 }
2019 
2020 //------------------------------succ_fall_through-----------------------------
2021 // Return true if a specific successor could be fall-through target.
succ_fall_through(uint i)2022 bool Block::succ_fall_through(uint i) {
2023   int eidx = end_idx();
2024   Node *n = get_node(eidx);  // Get ending Node
2025 
2026   int op = n->Opcode();
2027   if (n->is_Mach()) {
2028     if (n->is_MachNullCheck()) {
2029       // In theory, either side can fall-thru, for simplicity sake,
2030       // let's say only the false branch can now.
2031       return get_node(i + eidx + 1)->Opcode() == Op_IfFalse;
2032     }
2033     op = n->as_Mach()->ideal_Opcode();
2034   }
2035 
2036   // Switch on branch type
2037   switch( op ) {
2038   case Op_CountedLoopEnd:
2039   case Op_If:
2040   case Op_Root:
2041   case Op_Goto:
2042     return true;
2043 
2044   case Op_Catch: {
2045     const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
2046     return ci->_con == CatchProjNode::fall_through_index;
2047   }
2048 
2049   case Op_Jump:
2050   case Op_NeverBranch:
2051   case Op_TailCall:
2052   case Op_TailJump:
2053   case Op_Return:
2054   case Op_Halt:
2055   case Op_Rethrow:
2056     return false;
2057 
2058   default:
2059     ShouldNotReachHere();
2060   }
2061 
2062   return false;
2063 }
2064 
2065 //------------------------------update_uncommon_branch------------------------
2066 // Update the probability of a two-branch to be uncommon
update_uncommon_branch(Block * ub)2067 void Block::update_uncommon_branch(Block* ub) {
2068   int eidx = end_idx();
2069   Node *n = get_node(eidx);  // Get ending Node
2070 
2071   int op = n->as_Mach()->ideal_Opcode();
2072 
2073   assert(op == Op_CountedLoopEnd || op == Op_If, "must be a If");
2074   assert(num_fall_throughs() == 2, "must be a two way branch block");
2075 
2076   // Which successor is ub?
2077   uint s;
2078   for (s = 0; s <_num_succs; s++) {
2079     if (_succs[s] == ub) break;
2080   }
2081   assert(s < 2, "uncommon successor must be found");
2082 
2083   // If ub is the true path, make the proability small, else
2084   // ub is the false path, and make the probability large
2085   bool invert = (get_node(s + eidx + 1)->Opcode() == Op_IfFalse);
2086 
2087   // Get existing probability
2088   float p = n->as_MachIf()->_prob;
2089 
2090   if (invert) p = 1.0 - p;
2091   if (p > PROB_MIN) {
2092     p = PROB_MIN;
2093   }
2094   if (invert) p = 1.0 - p;
2095 
2096   n->as_MachIf()->_prob = p;
2097 }
2098 
2099 //------------------------------update_succ_freq-------------------------------
2100 // Update the appropriate frequency associated with block 'b', a successor of
2101 // a block in this loop.
update_succ_freq(Block * b,double freq)2102 void CFGLoop::update_succ_freq(Block* b, double freq) {
2103   if (b->_loop == this) {
2104     if (b == head()) {
2105       // back branch within the loop
2106       // Do nothing now, the loop carried frequency will be
2107       // adjust later in scale_freq().
2108     } else {
2109       // simple branch within the loop
2110       b->_freq += freq;
2111     }
2112   } else if (!in_loop_nest(b)) {
2113     // branch is exit from this loop
2114     BlockProbPair bpp(b, freq);
2115     _exits.append(bpp);
2116   } else {
2117     // branch into nested loop
2118     CFGLoop* ch = b->_loop;
2119     ch->_freq += freq;
2120   }
2121 }
2122 
2123 //------------------------------in_loop_nest-----------------------------------
2124 // Determine if block b is in the receiver's loop nest.
in_loop_nest(Block * b)2125 bool CFGLoop::in_loop_nest(Block* b) {
2126   int depth = _depth;
2127   CFGLoop* b_loop = b->_loop;
2128   int b_depth = b_loop->_depth;
2129   if (depth == b_depth) {
2130     return true;
2131   }
2132   while (b_depth > depth) {
2133     b_loop = b_loop->_parent;
2134     b_depth = b_loop->_depth;
2135   }
2136   return b_loop == this;
2137 }
2138 
2139 //------------------------------scale_freq-------------------------------------
2140 // Scale frequency of loops and blocks by trip counts from outer loops
2141 // Do a top down traversal of loop tree (visit outer loops first.)
scale_freq()2142 void CFGLoop::scale_freq() {
2143   double loop_freq = _freq * trip_count();
2144   _freq = loop_freq;
2145   for (int i = 0; i < _members.length(); i++) {
2146     CFGElement* s = _members.at(i);
2147     double block_freq = s->_freq * loop_freq;
2148     if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY)
2149       block_freq = MIN_BLOCK_FREQUENCY;
2150     s->_freq = block_freq;
2151   }
2152   CFGLoop* ch = _child;
2153   while (ch != NULL) {
2154     ch->scale_freq();
2155     ch = ch->_sibling;
2156   }
2157 }
2158 
2159 // Frequency of outer loop
outer_loop_freq() const2160 double CFGLoop::outer_loop_freq() const {
2161   if (_child != NULL) {
2162     return _child->_freq;
2163   }
2164   return _freq;
2165 }
2166 
2167 #ifndef PRODUCT
2168 //------------------------------dump_tree--------------------------------------
dump_tree() const2169 void CFGLoop::dump_tree() const {
2170   dump();
2171   if (_child != NULL)   _child->dump_tree();
2172   if (_sibling != NULL) _sibling->dump_tree();
2173 }
2174 
2175 //------------------------------dump-------------------------------------------
dump() const2176 void CFGLoop::dump() const {
2177   for (int i = 0; i < _depth; i++) tty->print("   ");
2178   tty->print("%s: %d  trip_count: %6.0f freq: %6.0f\n",
2179              _depth == 0 ? "Method" : "Loop", _id, trip_count(), _freq);
2180   for (int i = 0; i < _depth; i++) tty->print("   ");
2181   tty->print("         members:");
2182   int k = 0;
2183   for (int i = 0; i < _members.length(); i++) {
2184     if (k++ >= 6) {
2185       tty->print("\n              ");
2186       for (int j = 0; j < _depth+1; j++) tty->print("   ");
2187       k = 0;
2188     }
2189     CFGElement *s = _members.at(i);
2190     if (s->is_block()) {
2191       Block *b = s->as_Block();
2192       tty->print(" B%d(%6.3f)", b->_pre_order, b->_freq);
2193     } else {
2194       CFGLoop* lp = s->as_CFGLoop();
2195       tty->print(" L%d(%6.3f)", lp->_id, lp->_freq);
2196     }
2197   }
2198   tty->print("\n");
2199   for (int i = 0; i < _depth; i++) tty->print("   ");
2200   tty->print("         exits:  ");
2201   k = 0;
2202   for (int i = 0; i < _exits.length(); i++) {
2203     if (k++ >= 7) {
2204       tty->print("\n              ");
2205       for (int j = 0; j < _depth+1; j++) tty->print("   ");
2206       k = 0;
2207     }
2208     Block *blk = _exits.at(i).get_target();
2209     double prob = _exits.at(i).get_prob();
2210     tty->print(" ->%d@%d%%", blk->_pre_order, (int)(prob*100));
2211   }
2212   tty->print("\n");
2213 }
2214 #endif
2215