0N/A/*
2273N/A * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
1472N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1472N/A * or visit www.oracle.com if you need additional information or have any
1472N/A * questions.
0N/A *
0N/A */
0N/A
1879N/A#include "precompiled.hpp"
1879N/A#include "libadt/vectset.hpp"
1879N/A#include "memory/allocation.inline.hpp"
1879N/A#include "opto/block.hpp"
1879N/A#include "opto/c2compiler.hpp"
1879N/A#include "opto/callnode.hpp"
1879N/A#include "opto/cfgnode.hpp"
1879N/A#include "opto/machnode.hpp"
1879N/A#include "opto/opcodes.hpp"
1879N/A#include "opto/phaseX.hpp"
1879N/A#include "opto/rootnode.hpp"
1879N/A#include "opto/runtime.hpp"
1879N/A#include "runtime/deoptimization.hpp"
1879N/A#ifdef TARGET_ARCH_MODEL_x86_32
1879N/A# include "adfiles/ad_x86_32.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_ARCH_MODEL_x86_64
1879N/A# include "adfiles/ad_x86_64.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_ARCH_MODEL_sparc
1879N/A# include "adfiles/ad_sparc.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_ARCH_MODEL_zero
1879N/A# include "adfiles/ad_zero.hpp"
1879N/A#endif
2073N/A#ifdef TARGET_ARCH_MODEL_arm
2073N/A# include "adfiles/ad_arm.hpp"
2073N/A#endif
2073N/A#ifdef TARGET_ARCH_MODEL_ppc
2073N/A# include "adfiles/ad_ppc.hpp"
2073N/A#endif
1879N/A
0N/A// Portions of code courtesy of Clifford Click
0N/A
0N/A// Optimization - Graph Style
0N/A
552N/A// To avoid float value underflow
552N/A#define MIN_BLOCK_FREQUENCY 1.e-35f
552N/A
0N/A//----------------------------schedule_node_into_block-------------------------
0N/A// Insert node n into block b. Look for projections of n and make sure they
0N/A// are in b also.
0N/Avoid PhaseCFG::schedule_node_into_block( Node *n, Block *b ) {
0N/A // Set basic block of n, Add n to b,
0N/A _bbs.map(n->_idx, b);
0N/A b->add_inst(n);
0N/A
0N/A // After Matching, nearly any old Node may have projections trailing it.
0N/A // These are usually machine-dependent flags. In any case, they might
0N/A // float to another block below this one. Move them up.
0N/A for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
0N/A Node* use = n->fast_out(i);
0N/A if (use->is_Proj()) {
0N/A Block* buse = _bbs[use->_idx];
0N/A if (buse != b) { // In wrong block?
0N/A if (buse != NULL)
0N/A buse->find_remove(use); // Remove from wrong block
0N/A _bbs.map(use->_idx, b); // Re-insert in this block
0N/A b->add_inst(use);
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
601N/A//----------------------------replace_block_proj_ctrl-------------------------
601N/A// Nodes that have is_block_proj() nodes as their control need to use
601N/A// the appropriate Region for their actual block as their control since
601N/A// the projection will be in a predecessor block.
601N/Avoid PhaseCFG::replace_block_proj_ctrl( Node *n ) {
601N/A const Node *in0 = n->in(0);
601N/A assert(in0 != NULL, "Only control-dependent");
601N/A const Node *p = in0->is_block_proj();
601N/A if (p != NULL && p != n) { // Control from a block projection?
2958N/A assert(!n->pinned() || n->is_MachConstantBase(), "only pinned MachConstantBase node is expected here");
601N/A // Find trailing Region
601N/A Block *pb = _bbs[in0->_idx]; // Block-projection already has basic block
601N/A uint j = 0;
601N/A if (pb->_num_succs != 1) { // More then 1 successor?
601N/A // Search for successor
601N/A uint max = pb->_nodes.size();
601N/A assert( max > 1, "" );
601N/A uint start = max - pb->_num_succs;
601N/A // Find which output path belongs to projection
601N/A for (j = start; j < max; j++) {
601N/A if( pb->_nodes[j] == in0 )
601N/A break;
601N/A }
601N/A assert( j < max, "must find" );
601N/A // Change control to match head of successor basic block
601N/A j -= start;
601N/A }
601N/A n->set_req(0, pb->_succs[j]->head());
601N/A }
601N/A}
601N/A
0N/A
0N/A//------------------------------schedule_pinned_nodes--------------------------
0N/A// Set the basic block for Nodes pinned into blocks
0N/Avoid PhaseCFG::schedule_pinned_nodes( VectorSet &visited ) {
0N/A // Allocate node stack of size C->unique()+8 to avoid frequent realloc
0N/A GrowableArray <Node *> spstack(C->unique()+8);
0N/A spstack.push(_root);
0N/A while ( spstack.is_nonempty() ) {
0N/A Node *n = spstack.pop();
0N/A if( !visited.test_set(n->_idx) ) { // Test node and flag it as visited
0N/A if( n->pinned() && !_bbs.lookup(n->_idx) ) { // Pinned? Nail it down!
601N/A assert( n->in(0), "pinned Node must have Control" );
601N/A // Before setting block replace block_proj control edge
601N/A replace_block_proj_ctrl(n);
0N/A Node *input = n->in(0);
0N/A while( !input->is_block_start() )
0N/A input = input->in(0);
0N/A Block *b = _bbs[input->_idx]; // Basic block of controlling input
0N/A schedule_node_into_block(n, b);
0N/A }
0N/A for( int i = n->req() - 1; i >= 0; --i ) { // For all inputs
0N/A if( n->in(i) != NULL )
0N/A spstack.push(n->in(i));
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
0N/A#ifdef ASSERT
0N/A// Assert that new input b2 is dominated by all previous inputs.
0N/A// Check this by by seeing that it is dominated by b1, the deepest
0N/A// input observed until b2.
0N/Astatic void assert_dom(Block* b1, Block* b2, Node* n, Block_Array &bbs) {
0N/A if (b1 == NULL) return;
0N/A assert(b1->_dom_depth < b2->_dom_depth, "sanity");
0N/A Block* tmp = b2;
0N/A while (tmp != b1 && tmp != NULL) {
0N/A tmp = tmp->_idom;
0N/A }
0N/A if (tmp != b1) {
0N/A // Detected an unschedulable graph. Print some nice stuff and die.
0N/A tty->print_cr("!!! Unschedulable graph !!!");
0N/A for (uint j=0; j<n->len(); j++) { // For all inputs
0N/A Node* inn = n->in(j); // Get input
0N/A if (inn == NULL) continue; // Ignore NULL, missing inputs
0N/A Block* inb = bbs[inn->_idx];
0N/A tty->print("B%d idom=B%d depth=%2d ",inb->_pre_order,
0N/A inb->_idom ? inb->_idom->_pre_order : 0, inb->_dom_depth);
0N/A inn->dump();
0N/A }
0N/A tty->print("Failing node: ");
0N/A n->dump();
0N/A assert(false, "unscheduable graph");
0N/A }
0N/A}
0N/A#endif
0N/A
0N/Astatic Block* find_deepest_input(Node* n, Block_Array &bbs) {
0N/A // Find the last input dominated by all other inputs.
0N/A Block* deepb = NULL; // Deepest block so far
0N/A int deepb_dom_depth = 0;
0N/A for (uint k = 0; k < n->len(); k++) { // For all inputs
0N/A Node* inn = n->in(k); // Get input
0N/A if (inn == NULL) continue; // Ignore NULL, missing inputs
0N/A Block* inb = bbs[inn->_idx];
0N/A assert(inb != NULL, "must already have scheduled this input");
0N/A if (deepb_dom_depth < (int) inb->_dom_depth) {
0N/A // The new inb must be dominated by the previous deepb.
0N/A // The various inputs must be linearly ordered in the dom
0N/A // tree, or else there will not be a unique deepest block.
0N/A DEBUG_ONLY(assert_dom(deepb, inb, n, bbs));
0N/A deepb = inb; // Save deepest block
0N/A deepb_dom_depth = deepb->_dom_depth;
0N/A }
0N/A }
0N/A assert(deepb != NULL, "must be at least one input to n");
0N/A return deepb;
0N/A}
0N/A
0N/A
0N/A//------------------------------schedule_early---------------------------------
0N/A// Find the earliest Block any instruction can be placed in. Some instructions
0N/A// are pinned into Blocks. Unpinned instructions can appear in last block in
0N/A// which all their inputs occur.
0N/Abool PhaseCFG::schedule_early(VectorSet &visited, Node_List &roots) {
0N/A // Allocate stack with enough space to avoid frequent realloc
0N/A Node_Stack nstack(roots.Size() + 8); // (unique >> 1) + 24 from Java2D stats
0N/A // roots.push(_root); _root will be processed among C->top() inputs
0N/A roots.push(C->top());
0N/A visited.set(C->top()->_idx);
0N/A
0N/A while (roots.size() != 0) {
0N/A // Use local variables nstack_top_n & nstack_top_i to cache values
0N/A // on stack's top.
0N/A Node *nstack_top_n = roots.pop();
0N/A uint nstack_top_i = 0;
0N/A//while_nstack_nonempty:
0N/A while (true) {
0N/A // Get parent node and next input's index from stack's top.
0N/A Node *n = nstack_top_n;
0N/A uint i = nstack_top_i;
0N/A
0N/A if (i == 0) {
601N/A // Fixup some control. Constants without control get attached
601N/A // to root and nodes that use is_block_proj() nodes should be attached
601N/A // to the region that starts their block.
0N/A const Node *in0 = n->in(0);
0N/A if (in0 != NULL) { // Control-dependent?
601N/A replace_block_proj_ctrl(n);
0N/A } else { // n->in(0) == NULL
0N/A if (n->req() == 1) { // This guy is a constant with NO inputs?
0N/A n->set_req(0, _root);
0N/A }
0N/A }
0N/A }
0N/A
0N/A // First, visit all inputs and force them to get a block. If an
0N/A // input is already in a block we quit following inputs (to avoid
0N/A // cycles). Instead we put that Node on a worklist to be handled
0N/A // later (since IT'S inputs may not have a block yet).
0N/A bool done = true; // Assume all n's inputs will be processed
0N/A while (i < n->len()) { // For all inputs
0N/A Node *in = n->in(i); // Get input
0N/A ++i;
0N/A if (in == NULL) continue; // Ignore NULL, missing inputs
0N/A int is_visited = visited.test_set(in->_idx);
0N/A if (!_bbs.lookup(in->_idx)) { // Missing block selection?
0N/A if (is_visited) {
0N/A // assert( !visited.test(in->_idx), "did not schedule early" );
0N/A return false;
0N/A }
0N/A nstack.push(n, i); // Save parent node and next input's index.
0N/A nstack_top_n = in; // Process current input now.
0N/A nstack_top_i = 0;
0N/A done = false; // Not all n's inputs processed.
0N/A break; // continue while_nstack_nonempty;
0N/A } else if (!is_visited) { // Input not yet visited?
0N/A roots.push(in); // Visit this guy later, using worklist
0N/A }
0N/A }
0N/A if (done) {
0N/A // All of n's inputs have been processed, complete post-processing.
0N/A
0N/A // Some instructions are pinned into a block. These include Region,
0N/A // Phi, Start, Return, and other control-dependent instructions and
0N/A // any projections which depend on them.
0N/A if (!n->pinned()) {
0N/A // Set earliest legal block.
0N/A _bbs.map(n->_idx, find_deepest_input(n, _bbs));
601N/A } else {
601N/A assert(_bbs[n->_idx] == _bbs[n->in(0)->_idx], "Pinned Node should be at the same block as its control edge");
0N/A }
0N/A
0N/A if (nstack.is_empty()) {
0N/A // Finished all nodes on stack.
0N/A // Process next node on the worklist 'roots'.
0N/A break;
0N/A }
0N/A // Get saved parent node and next input's index.
0N/A nstack_top_n = nstack.node();
0N/A nstack_top_i = nstack.index();
0N/A nstack.pop();
0N/A } // if (done)
0N/A } // while (true)
0N/A } // while (roots.size() != 0)
0N/A return true;
0N/A}
0N/A
0N/A//------------------------------dom_lca----------------------------------------
0N/A// Find least common ancestor in dominator tree
0N/A// LCA is a current notion of LCA, to be raised above 'this'.
0N/A// As a convenient boundary condition, return 'this' if LCA is NULL.
0N/A// Find the LCA of those two nodes.
0N/ABlock* Block::dom_lca(Block* LCA) {
0N/A if (LCA == NULL || LCA == this) return this;
0N/A
0N/A Block* anc = this;
0N/A while (anc->_dom_depth > LCA->_dom_depth)
0N/A anc = anc->_idom; // Walk up till anc is as high as LCA
0N/A
0N/A while (LCA->_dom_depth > anc->_dom_depth)
0N/A LCA = LCA->_idom; // Walk up till LCA is as high as anc
0N/A
0N/A while (LCA != anc) { // Walk both up till they are the same
0N/A LCA = LCA->_idom;
0N/A anc = anc->_idom;
0N/A }
0N/A
0N/A return LCA;
0N/A}
0N/A
0N/A//--------------------------raise_LCA_above_use--------------------------------
0N/A// We are placing a definition, and have been given a def->use edge.
0N/A// The definition must dominate the use, so move the LCA upward in the
0N/A// dominator tree to dominate the use. If the use is a phi, adjust
0N/A// the LCA only with the phi input paths which actually use this def.
0N/Astatic Block* raise_LCA_above_use(Block* LCA, Node* use, Node* def, Block_Array &bbs) {
0N/A Block* buse = bbs[use->_idx];
0N/A if (buse == NULL) return LCA; // Unused killing Projs have no use block
0N/A if (!use->is_Phi()) return buse->dom_lca(LCA);
0N/A uint pmax = use->req(); // Number of Phi inputs
0N/A // Why does not this loop just break after finding the matching input to
0N/A // the Phi? Well...it's like this. I do not have true def-use/use-def
0N/A // chains. Means I cannot distinguish, from the def-use direction, which
0N/A // of many use-defs lead from the same use to the same def. That is, this
0N/A // Phi might have several uses of the same def. Each use appears in a
0N/A // different predecessor block. But when I enter here, I cannot distinguish
0N/A // which use-def edge I should find the predecessor block for. So I find
0N/A // them all. Means I do a little extra work if a Phi uses the same value
0N/A // more than once.
0N/A for (uint j=1; j<pmax; j++) { // For all inputs
0N/A if (use->in(j) == def) { // Found matching input?
0N/A Block* pred = bbs[buse->pred(j)->_idx];
0N/A LCA = pred->dom_lca(LCA);
0N/A }
0N/A }
0N/A return LCA;
0N/A}
0N/A
0N/A//----------------------------raise_LCA_above_marks----------------------------
0N/A// Return a new LCA that dominates LCA and any of its marked predecessors.
0N/A// Search all my parents up to 'early' (exclusive), looking for predecessors
0N/A// which are marked with the given index. Return the LCA (in the dom tree)
0N/A// of all marked blocks. If there are none marked, return the original
0N/A// LCA.
0N/Astatic Block* raise_LCA_above_marks(Block* LCA, node_idx_t mark,
0N/A Block* early, Block_Array &bbs) {
0N/A Block_List worklist;
0N/A worklist.push(LCA);
0N/A while (worklist.size() > 0) {
0N/A Block* mid = worklist.pop();
0N/A if (mid == early) continue; // stop searching here
0N/A
0N/A // Test and set the visited bit.
0N/A if (mid->raise_LCA_visited() == mark) continue; // already visited
0N/A
0N/A // Don't process the current LCA, otherwise the search may terminate early
0N/A if (mid != LCA && mid->raise_LCA_mark() == mark) {
0N/A // Raise the LCA.
0N/A LCA = mid->dom_lca(LCA);
0N/A if (LCA == early) break; // stop searching everywhere
0N/A assert(early->dominates(LCA), "early is high enough");
0N/A // Resume searching at that point, skipping intermediate levels.
0N/A worklist.push(LCA);
215N/A if (LCA == mid)
215N/A continue; // Don't mark as visited to avoid early termination.
0N/A } else {
0N/A // Keep searching through this block's predecessors.
0N/A for (uint j = 1, jmax = mid->num_preds(); j < jmax; j++) {
0N/A Block* mid_parent = bbs[ mid->pred(j)->_idx ];
0N/A worklist.push(mid_parent);
0N/A }
0N/A }
215N/A mid->set_raise_LCA_visited(mark);
0N/A }
0N/A return LCA;
0N/A}
0N/A
0N/A//--------------------------memory_early_block--------------------------------
0N/A// This is a variation of find_deepest_input, the heart of schedule_early.
0N/A// Find the "early" block for a load, if we considered only memory and
0N/A// address inputs, that is, if other data inputs were ignored.
0N/A//
0N/A// Because a subset of edges are considered, the resulting block will
0N/A// be earlier (at a shallower dom_depth) than the true schedule_early
0N/A// point of the node. We compute this earlier block as a more permissive
0N/A// site for anti-dependency insertion, but only if subsume_loads is enabled.
0N/Astatic Block* memory_early_block(Node* load, Block* early, Block_Array &bbs) {
0N/A Node* base;
0N/A Node* index;
0N/A Node* store = load->in(MemNode::Memory);
0N/A load->as_Mach()->memory_inputs(base, index);
0N/A
0N/A assert(base != NodeSentinel && index != NodeSentinel,
0N/A "unexpected base/index inputs");
0N/A
0N/A Node* mem_inputs[4];
0N/A int mem_inputs_length = 0;
0N/A if (base != NULL) mem_inputs[mem_inputs_length++] = base;
0N/A if (index != NULL) mem_inputs[mem_inputs_length++] = index;
0N/A if (store != NULL) mem_inputs[mem_inputs_length++] = store;
0N/A
0N/A // In the comparision below, add one to account for the control input,
0N/A // which may be null, but always takes up a spot in the in array.
0N/A if (mem_inputs_length + 1 < (int) load->req()) {
0N/A // This "load" has more inputs than just the memory, base and index inputs.
0N/A // For purposes of checking anti-dependences, we need to start
0N/A // from the early block of only the address portion of the instruction,
0N/A // and ignore other blocks that may have factored into the wider
0N/A // schedule_early calculation.
0N/A if (load->in(0) != NULL) mem_inputs[mem_inputs_length++] = load->in(0);
0N/A
0N/A Block* deepb = NULL; // Deepest block so far
0N/A int deepb_dom_depth = 0;
0N/A for (int i = 0; i < mem_inputs_length; i++) {
0N/A Block* inb = bbs[mem_inputs[i]->_idx];
0N/A if (deepb_dom_depth < (int) inb->_dom_depth) {
0N/A // The new inb must be dominated by the previous deepb.
0N/A // The various inputs must be linearly ordered in the dom
0N/A // tree, or else there will not be a unique deepest block.
0N/A DEBUG_ONLY(assert_dom(deepb, inb, load, bbs));
0N/A deepb = inb; // Save deepest block
0N/A deepb_dom_depth = deepb->_dom_depth;
0N/A }
0N/A }
0N/A early = deepb;
0N/A }
0N/A
0N/A return early;
0N/A}
0N/A
0N/A//--------------------------insert_anti_dependences---------------------------
0N/A// A load may need to witness memory that nearby stores can overwrite.
0N/A// For each nearby store, either insert an "anti-dependence" edge
0N/A// from the load to the store, or else move LCA upward to force the
0N/A// load to (eventually) be scheduled in a block above the store.
0N/A//
0N/A// Do not add edges to stores on distinct control-flow paths;
0N/A// only add edges to stores which might interfere.
0N/A//
0N/A// Return the (updated) LCA. There will not be any possibly interfering
0N/A// store between the load's "early block" and the updated LCA.
0N/A// Any stores in the updated LCA will have new precedence edges
0N/A// back to the load. The caller is expected to schedule the load
0N/A// in the LCA, in which case the precedence edges will make LCM
0N/A// preserve anti-dependences. The caller may also hoist the load
0N/A// above the LCA, if it is not the early block.
0N/ABlock* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) {
0N/A assert(load->needs_anti_dependence_check(), "must be a load of some sort");
0N/A assert(LCA != NULL, "");
0N/A DEBUG_ONLY(Block* LCA_orig = LCA);
0N/A
0N/A // Compute the alias index. Loads and stores with different alias indices
0N/A // do not need anti-dependence edges.
0N/A uint load_alias_idx = C->get_alias_index(load->adr_type());
0N/A#ifdef ASSERT
0N/A if (load_alias_idx == Compile::AliasIdxBot && C->AliasLevel() > 0 &&
0N/A (PrintOpto || VerifyAliases ||
0N/A PrintMiscellaneous && (WizardMode || Verbose))) {
0N/A // Load nodes should not consume all of memory.
0N/A // Reporting a bottom type indicates a bug in adlc.
0N/A // If some particular type of node validly consumes all of memory,
0N/A // sharpen the preceding "if" to exclude it, so we can catch bugs here.
0N/A tty->print_cr("*** Possible Anti-Dependence Bug: Load consumes all of memory.");
0N/A load->dump(2);
0N/A if (VerifyAliases) assert(load_alias_idx != Compile::AliasIdxBot, "");
0N/A }
0N/A#endif
0N/A assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrComp),
0N/A "String compare is only known 'load' that does not conflict with any stores");
681N/A assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrEquals),
681N/A "String equals is a 'load' that does not conflict with any stores");
681N/A assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrIndexOf),
681N/A "String indexOf is a 'load' that does not conflict with any stores");
681N/A assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_AryEq),
681N/A "Arrays equals is a 'load' that do not conflict with any stores");
0N/A
0N/A if (!C->alias_type(load_alias_idx)->is_rewritable()) {
0N/A // It is impossible to spoil this load by putting stores before it,
0N/A // because we know that the stores will never update the value
0N/A // which 'load' must witness.
0N/A return LCA;
0N/A }
0N/A
0N/A node_idx_t load_index = load->_idx;
0N/A
0N/A // Note the earliest legal placement of 'load', as determined by
0N/A // by the unique point in the dom tree where all memory effects
0N/A // and other inputs are first available. (Computed by schedule_early.)
0N/A // For normal loads, 'early' is the shallowest place (dom graph wise)
0N/A // to look for anti-deps between this load and any store.
0N/A Block* early = _bbs[load_index];
0N/A
0N/A // If we are subsuming loads, compute an "early" block that only considers
0N/A // memory or address inputs. This block may be different than the
0N/A // schedule_early block in that it could be at an even shallower depth in the
0N/A // dominator tree, and allow for a broader discovery of anti-dependences.
0N/A if (C->subsume_loads()) {
0N/A early = memory_early_block(load, early, _bbs);
0N/A }
0N/A
0N/A ResourceArea *area = Thread::current()->resource_area();
0N/A Node_List worklist_mem(area); // prior memory state to store
0N/A Node_List worklist_store(area); // possible-def to explore
31N/A Node_List worklist_visited(area); // visited mergemem nodes
0N/A Node_List non_early_stores(area); // all relevant stores outside of early
0N/A bool must_raise_LCA = false;
0N/A
0N/A#ifdef TRACK_PHI_INPUTS
0N/A // %%% This extra checking fails because MergeMem nodes are not GVNed.
0N/A // Provide "phi_inputs" to check if every input to a PhiNode is from the
0N/A // original memory state. This indicates a PhiNode for which should not
0N/A // prevent the load from sinking. For such a block, set_raise_LCA_mark
0N/A // may be overly conservative.
0N/A // Mechanism: count inputs seen for each Phi encountered in worklist_store.
0N/A DEBUG_ONLY(GrowableArray<uint> phi_inputs(area, C->unique(),0,0));
0N/A#endif
0N/A
0N/A // 'load' uses some memory state; look for users of the same state.
0N/A // Recurse through MergeMem nodes to the stores that use them.
0N/A
0N/A // Each of these stores is a possible definition of memory
0N/A // that 'load' needs to use. We need to force 'load'
0N/A // to occur before each such store. When the store is in
0N/A // the same block as 'load', we insert an anti-dependence
0N/A // edge load->store.
0N/A
0N/A // The relevant stores "nearby" the load consist of a tree rooted
0N/A // at initial_mem, with internal nodes of type MergeMem.
0N/A // Therefore, the branches visited by the worklist are of this form:
0N/A // initial_mem -> (MergeMem ->)* store
0N/A // The anti-dependence constraints apply only to the fringe of this tree.
0N/A
0N/A Node* initial_mem = load->in(MemNode::Memory);
0N/A worklist_store.push(initial_mem);
31N/A worklist_visited.push(initial_mem);
0N/A worklist_mem.push(NULL);
0N/A while (worklist_store.size() > 0) {
0N/A // Examine a nearby store to see if it might interfere with our load.
0N/A Node* mem = worklist_mem.pop();
0N/A Node* store = worklist_store.pop();
0N/A uint op = store->Opcode();
0N/A
0N/A // MergeMems do not directly have anti-deps.
0N/A // Treat them as internal nodes in a forward tree of memory states,
0N/A // the leaves of which are each a 'possible-def'.
0N/A if (store == initial_mem // root (exclusive) of tree we are searching
0N/A || op == Op_MergeMem // internal node of tree we are searching
0N/A ) {
0N/A mem = store; // It's not a possibly interfering store.
31N/A if (store == initial_mem)
31N/A initial_mem = NULL; // only process initial memory once
31N/A
0N/A for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
0N/A store = mem->fast_out(i);
0N/A if (store->is_MergeMem()) {
0N/A // Be sure we don't get into combinatorial problems.
0N/A // (Allow phis to be repeated; they can merge two relevant states.)
31N/A uint j = worklist_visited.size();
31N/A for (; j > 0; j--) {
31N/A if (worklist_visited.at(j-1) == store) break;
0N/A }
31N/A if (j > 0) continue; // already on work list; do not repeat
31N/A worklist_visited.push(store);
0N/A }
0N/A worklist_mem.push(mem);
0N/A worklist_store.push(store);
0N/A }
0N/A continue;
0N/A }
0N/A
0N/A if (op == Op_MachProj || op == Op_Catch) continue;
0N/A if (store->needs_anti_dependence_check()) continue; // not really a store
0N/A
0N/A // Compute the alias index. Loads and stores with different alias
0N/A // indices do not need anti-dependence edges. Wide MemBar's are
0N/A // anti-dependent on everything (except immutable memories).
0N/A const TypePtr* adr_type = store->adr_type();
0N/A if (!C->can_alias(adr_type, load_alias_idx)) continue;
0N/A
0N/A // Most slow-path runtime calls do NOT modify Java memory, but
0N/A // they can block and so write Raw memory.
0N/A if (store->is_Mach()) {
0N/A MachNode* mstore = store->as_Mach();
0N/A if (load_alias_idx != Compile::AliasIdxRaw) {
0N/A // Check for call into the runtime using the Java calling
0N/A // convention (and from there into a wrapper); it has no
0N/A // _method. Can't do this optimization for Native calls because
0N/A // they CAN write to Java memory.
0N/A if (mstore->ideal_Opcode() == Op_CallStaticJava) {
0N/A assert(mstore->is_MachSafePoint(), "");
0N/A MachSafePointNode* ms = (MachSafePointNode*) mstore;
0N/A assert(ms->is_MachCallJava(), "");
0N/A MachCallJavaNode* mcj = (MachCallJavaNode*) ms;
0N/A if (mcj->_method == NULL) {
0N/A // These runtime calls do not write to Java visible memory
0N/A // (other than Raw) and so do not require anti-dependence edges.
0N/A continue;
0N/A }
0N/A }
0N/A // Same for SafePoints: they read/write Raw but only read otherwise.
0N/A // This is basically a workaround for SafePoints only defining control
0N/A // instead of control + memory.
0N/A if (mstore->ideal_Opcode() == Op_SafePoint)
0N/A continue;
0N/A } else {
0N/A // Some raw memory, such as the load of "top" at an allocation,
0N/A // can be control dependent on the previous safepoint. See
0N/A // comments in GraphKit::allocate_heap() about control input.
0N/A // Inserting an anti-dep between such a safepoint and a use
0N/A // creates a cycle, and will cause a subsequent failure in
0N/A // local scheduling. (BugId 4919904)
0N/A // (%%% How can a control input be a safepoint and not a projection??)
0N/A if (mstore->ideal_Opcode() == Op_SafePoint && load->in(0) == mstore)
0N/A continue;
0N/A }
0N/A }
0N/A
0N/A // Identify a block that the current load must be above,
0N/A // or else observe that 'store' is all the way up in the
0N/A // earliest legal block for 'load'. In the latter case,
0N/A // immediately insert an anti-dependence edge.
0N/A Block* store_block = _bbs[store->_idx];
0N/A assert(store_block != NULL, "unused killing projections skipped above");
0N/A
0N/A if (store->is_Phi()) {
0N/A // 'load' uses memory which is one (or more) of the Phi's inputs.
0N/A // It must be scheduled not before the Phi, but rather before
0N/A // each of the relevant Phi inputs.
0N/A //
0N/A // Instead of finding the LCA of all inputs to a Phi that match 'mem',
0N/A // we mark each corresponding predecessor block and do a combined
0N/A // hoisting operation later (raise_LCA_above_marks).
0N/A //
0N/A // Do not assert(store_block != early, "Phi merging memory after access")
0N/A // PhiNode may be at start of block 'early' with backedge to 'early'
0N/A DEBUG_ONLY(bool found_match = false);
0N/A for (uint j = PhiNode::Input, jmax = store->req(); j < jmax; j++) {
0N/A if (store->in(j) == mem) { // Found matching input?
0N/A DEBUG_ONLY(found_match = true);
0N/A Block* pred_block = _bbs[store_block->pred(j)->_idx];
0N/A if (pred_block != early) {
0N/A // If any predecessor of the Phi matches the load's "early block",
0N/A // we do not need a precedence edge between the Phi and 'load'
605N/A // since the load will be forced into a block preceding the Phi.
0N/A pred_block->set_raise_LCA_mark(load_index);
0N/A assert(!LCA_orig->dominates(pred_block) ||
0N/A early->dominates(pred_block), "early is high enough");
0N/A must_raise_LCA = true;
788N/A } else {
788N/A // anti-dependent upon PHI pinned below 'early', no edge needed
788N/A LCA = early; // but can not schedule below 'early'
0N/A }
0N/A }
0N/A }
0N/A assert(found_match, "no worklist bug");
0N/A#ifdef TRACK_PHI_INPUTS
0N/A#ifdef ASSERT
0N/A // This assert asks about correct handling of PhiNodes, which may not
0N/A // have all input edges directly from 'mem'. See BugId 4621264
0N/A int num_mem_inputs = phi_inputs.at_grow(store->_idx,0) + 1;
0N/A // Increment by exactly one even if there are multiple copies of 'mem'
0N/A // coming into the phi, because we will run this block several times
0N/A // if there are several copies of 'mem'. (That's how DU iterators work.)
0N/A phi_inputs.at_put(store->_idx, num_mem_inputs);
0N/A assert(PhiNode::Input + num_mem_inputs < store->req(),
0N/A "Expect at least one phi input will not be from original memory state");
0N/A#endif //ASSERT
0N/A#endif //TRACK_PHI_INPUTS
0N/A } else if (store_block != early) {
0N/A // 'store' is between the current LCA and earliest possible block.
0N/A // Label its block, and decide later on how to raise the LCA
0N/A // to include the effect on LCA of this store.
0N/A // If this store's block gets chosen as the raised LCA, we
0N/A // will find him on the non_early_stores list and stick him
0N/A // with a precedence edge.
0N/A // (But, don't bother if LCA is already raised all the way.)
0N/A if (LCA != early) {
0N/A store_block->set_raise_LCA_mark(load_index);
0N/A must_raise_LCA = true;
0N/A non_early_stores.push(store);
0N/A }
0N/A } else {
0N/A // Found a possibly-interfering store in the load's 'early' block.
0N/A // This means 'load' cannot sink at all in the dominator tree.
0N/A // Add an anti-dep edge, and squeeze 'load' into the highest block.
0N/A assert(store != load->in(0), "dependence cycle found");
0N/A if (verify) {
0N/A assert(store->find_edge(load) != -1, "missing precedence edge");
0N/A } else {
0N/A store->add_prec(load);
0N/A }
0N/A LCA = early;
0N/A // This turns off the process of gathering non_early_stores.
0N/A }
0N/A }
0N/A // (Worklist is now empty; all nearby stores have been visited.)
0N/A
0N/A // Finished if 'load' must be scheduled in its 'early' block.
0N/A // If we found any stores there, they have already been given
0N/A // precedence edges.
0N/A if (LCA == early) return LCA;
0N/A
0N/A // We get here only if there are no possibly-interfering stores
0N/A // in the load's 'early' block. Move LCA up above all predecessors
0N/A // which contain stores we have noted.
0N/A //
0N/A // The raised LCA block can be a home to such interfering stores,
0N/A // but its predecessors must not contain any such stores.
0N/A //
0N/A // The raised LCA will be a lower bound for placing the load,
0N/A // preventing the load from sinking past any block containing
0N/A // a store that may invalidate the memory state required by 'load'.
0N/A if (must_raise_LCA)
0N/A LCA = raise_LCA_above_marks(LCA, load->_idx, early, _bbs);
0N/A if (LCA == early) return LCA;
0N/A
0N/A // Insert anti-dependence edges from 'load' to each store
0N/A // in the non-early LCA block.
0N/A // Mine the non_early_stores list for such stores.
0N/A if (LCA->raise_LCA_mark() == load_index) {
0N/A while (non_early_stores.size() > 0) {
0N/A Node* store = non_early_stores.pop();
0N/A Block* store_block = _bbs[store->_idx];
0N/A if (store_block == LCA) {
0N/A // add anti_dependence from store to load in its own block
0N/A assert(store != load->in(0), "dependence cycle found");
0N/A if (verify) {
0N/A assert(store->find_edge(load) != -1, "missing precedence edge");
0N/A } else {
0N/A store->add_prec(load);
0N/A }
0N/A } else {
0N/A assert(store_block->raise_LCA_mark() == load_index, "block was marked");
0N/A // Any other stores we found must be either inside the new LCA
0N/A // or else outside the original LCA. In the latter case, they
0N/A // did not interfere with any use of 'load'.
0N/A assert(LCA->dominates(store_block)
0N/A || !LCA_orig->dominates(store_block), "no stray stores");
0N/A }
0N/A }
0N/A }
0N/A
0N/A // Return the highest block containing stores; any stores
0N/A // within that block have been given anti-dependence edges.
0N/A return LCA;
0N/A}
0N/A
0N/A// This class is used to iterate backwards over the nodes in the graph.
0N/A
0N/Aclass Node_Backward_Iterator {
0N/A
0N/Aprivate:
0N/A Node_Backward_Iterator();
0N/A
0N/Apublic:
0N/A // Constructor for the iterator
0N/A Node_Backward_Iterator(Node *root, VectorSet &visited, Node_List &stack, Block_Array &bbs);
0N/A
0N/A // Postincrement operator to iterate over the nodes
0N/A Node *next();
0N/A
0N/Aprivate:
0N/A VectorSet &_visited;
0N/A Node_List &_stack;
0N/A Block_Array &_bbs;
0N/A};
0N/A
0N/A// Constructor for the Node_Backward_Iterator
0N/ANode_Backward_Iterator::Node_Backward_Iterator( Node *root, VectorSet &visited, Node_List &stack, Block_Array &bbs )
0N/A : _visited(visited), _stack(stack), _bbs(bbs) {
0N/A // The stack should contain exactly the root
0N/A stack.clear();
0N/A stack.push(root);
0N/A
0N/A // Clear the visited bits
0N/A visited.Clear();
0N/A}
0N/A
0N/A// Iterator for the Node_Backward_Iterator
0N/ANode *Node_Backward_Iterator::next() {
0N/A
0N/A // If the _stack is empty, then just return NULL: finished.
0N/A if ( !_stack.size() )
0N/A return NULL;
0N/A
0N/A // '_stack' is emulating a real _stack. The 'visit-all-users' loop has been
0N/A // made stateless, so I do not need to record the index 'i' on my _stack.
0N/A // Instead I visit all users each time, scanning for unvisited users.
0N/A // I visit unvisited not-anti-dependence users first, then anti-dependent
0N/A // children next.
0N/A Node *self = _stack.pop();
0N/A
0N/A // I cycle here when I am entering a deeper level of recursion.
0N/A // The key variable 'self' was set prior to jumping here.
0N/A while( 1 ) {
0N/A
0N/A _visited.set(self->_idx);
0N/A
0N/A // Now schedule all uses as late as possible.
0N/A uint src = self->is_Proj() ? self->in(0)->_idx : self->_idx;
0N/A uint src_rpo = _bbs[src]->_rpo;
0N/A
0N/A // Schedule all nodes in a post-order visit
0N/A Node *unvisited = NULL; // Unvisited anti-dependent Node, if any
0N/A
0N/A // Scan for unvisited nodes
0N/A for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
0N/A // For all uses, schedule late
0N/A Node* n = self->fast_out(i); // Use
0N/A
0N/A // Skip already visited children
0N/A if ( _visited.test(n->_idx) )
0N/A continue;
0N/A
0N/A // do not traverse backward control edges
0N/A Node *use = n->is_Proj() ? n->in(0) : n;
0N/A uint use_rpo = _bbs[use->_idx]->_rpo;
0N/A
0N/A if ( use_rpo < src_rpo )
0N/A continue;
0N/A
0N/A // Phi nodes always precede uses in a basic block
0N/A if ( use_rpo == src_rpo && use->is_Phi() )
0N/A continue;
0N/A
0N/A unvisited = n; // Found unvisited
0N/A
0N/A // Check for possible-anti-dependent
0N/A if( !n->needs_anti_dependence_check() )
0N/A break; // Not visited, not anti-dep; schedule it NOW
0N/A }
0N/A
0N/A // Did I find an unvisited not-anti-dependent Node?
0N/A if ( !unvisited )
0N/A break; // All done with children; post-visit 'self'
0N/A
0N/A // Visit the unvisited Node. Contains the obvious push to
0N/A // indicate I'm entering a deeper level of recursion. I push the
0N/A // old state onto the _stack and set a new state and loop (recurse).
0N/A _stack.push(self);
0N/A self = unvisited;
0N/A } // End recursion loop
0N/A
0N/A return self;
0N/A}
0N/A
0N/A//------------------------------ComputeLatenciesBackwards----------------------
0N/A// Compute the latency of all the instructions.
0N/Avoid PhaseCFG::ComputeLatenciesBackwards(VectorSet &visited, Node_List &stack) {
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining())
0N/A tty->print("\n#---- ComputeLatenciesBackwards ----\n");
0N/A#endif
0N/A
0N/A Node_Backward_Iterator iter((Node *)_root, visited, stack, _bbs);
0N/A Node *n;
0N/A
0N/A // Walk over all the nodes from last to first
0N/A while (n = iter.next()) {
0N/A // Set the latency for the definitions of this instruction
0N/A partial_latency_of_defs(n);
0N/A }
0N/A} // end ComputeLatenciesBackwards
0N/A
0N/A//------------------------------partial_latency_of_defs------------------------
0N/A// Compute the latency impact of this node on all defs. This computes
0N/A// a number that increases as we approach the beginning of the routine.
0N/Avoid PhaseCFG::partial_latency_of_defs(Node *n) {
0N/A // Set the latency for this instruction
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("# latency_to_inputs: node_latency[%d] = %d for node",
1605N/A n->_idx, _node_latency->at_grow(n->_idx));
0N/A dump();
0N/A }
0N/A#endif
0N/A
0N/A if (n->is_Proj())
0N/A n = n->in(0);
0N/A
0N/A if (n->is_Root())
0N/A return;
0N/A
0N/A uint nlen = n->len();
1605N/A uint use_latency = _node_latency->at_grow(n->_idx);
0N/A uint use_pre_order = _bbs[n->_idx]->_pre_order;
0N/A
0N/A for ( uint j=0; j<nlen; j++ ) {
0N/A Node *def = n->in(j);
0N/A
0N/A if (!def || def == n)
0N/A continue;
0N/A
0N/A // Walk backwards thru projections
0N/A if (def->is_Proj())
0N/A def = def->in(0);
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("# in(%2d): ", j);
0N/A def->dump();
0N/A }
0N/A#endif
0N/A
0N/A // If the defining block is not known, assume it is ok
0N/A Block *def_block = _bbs[def->_idx];
0N/A uint def_pre_order = def_block ? def_block->_pre_order : 0;
0N/A
0N/A if ( (use_pre_order < def_pre_order) ||
0N/A (use_pre_order == def_pre_order && n->is_Phi()) )
0N/A continue;
0N/A
0N/A uint delta_latency = n->latency(j);
0N/A uint current_latency = delta_latency + use_latency;
0N/A
1605N/A if (_node_latency->at_grow(def->_idx) < current_latency) {
1605N/A _node_latency->at_put_grow(def->_idx, current_latency);
0N/A }
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print_cr("# %d + edge_latency(%d) == %d -> %d, node_latency[%d] = %d",
0N/A use_latency, j, delta_latency, current_latency, def->_idx,
1605N/A _node_latency->at_grow(def->_idx));
0N/A }
0N/A#endif
0N/A }
0N/A}
0N/A
0N/A//------------------------------latency_from_use-------------------------------
0N/A// Compute the latency of a specific use
0N/Aint PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) {
0N/A // If self-reference, return no latency
0N/A if (use == n || use->is_Root())
0N/A return 0;
0N/A
0N/A uint def_pre_order = _bbs[def->_idx]->_pre_order;
0N/A uint latency = 0;
0N/A
0N/A // If the use is not a projection, then it is simple...
0N/A if (!use->is_Proj()) {
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("# out(): ");
0N/A use->dump();
0N/A }
0N/A#endif
0N/A
0N/A uint use_pre_order = _bbs[use->_idx]->_pre_order;
0N/A
0N/A if (use_pre_order < def_pre_order)
0N/A return 0;
0N/A
0N/A if (use_pre_order == def_pre_order && use->is_Phi())
0N/A return 0;
0N/A
0N/A uint nlen = use->len();
1605N/A uint nl = _node_latency->at_grow(use->_idx);
0N/A
0N/A for ( uint j=0; j<nlen; j++ ) {
0N/A if (use->in(j) == n) {
0N/A // Change this if we want local latencies
0N/A uint ul = use->latency(j);
0N/A uint l = ul + nl;
0N/A if (latency < l) latency = l;
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print_cr("# %d + edge_latency(%d) == %d -> %d, latency = %d",
0N/A nl, j, ul, l, latency);
0N/A }
0N/A#endif
0N/A }
0N/A }
0N/A } else {
0N/A // This is a projection, just grab the latency of the use(s)
0N/A for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) {
0N/A uint l = latency_from_use(use, def, use->fast_out(j));
0N/A if (latency < l) latency = l;
0N/A }
0N/A }
0N/A
0N/A return latency;
0N/A}
0N/A
0N/A//------------------------------latency_from_uses------------------------------
0N/A// Compute the latency of this instruction relative to all of it's uses.
0N/A// This computes a number that increases as we approach the beginning of the
0N/A// routine.
0N/Avoid PhaseCFG::latency_from_uses(Node *n) {
0N/A // Set the latency for this instruction
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("# latency_from_outputs: node_latency[%d] = %d for node",
1605N/A n->_idx, _node_latency->at_grow(n->_idx));
0N/A dump();
0N/A }
0N/A#endif
0N/A uint latency=0;
0N/A const Node *def = n->is_Proj() ? n->in(0): n;
0N/A
0N/A for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
0N/A uint l = latency_from_use(n, def, n->fast_out(i));
0N/A
0N/A if (latency < l) latency = l;
0N/A }
0N/A
1605N/A _node_latency->at_put_grow(n->_idx, latency);
0N/A}
0N/A
0N/A//------------------------------hoist_to_cheaper_block-------------------------
0N/A// Pick a block for node self, between early and LCA, that is a cheaper
0N/A// alternative to LCA.
0N/ABlock* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) {
0N/A const double delta = 1+PROB_UNLIKELY_MAG(4);
0N/A Block* least = LCA;
0N/A double least_freq = least->_freq;
1605N/A uint target = _node_latency->at_grow(self->_idx);
1605N/A uint start_latency = _node_latency->at_grow(LCA->_nodes[0]->_idx);
1605N/A uint end_latency = _node_latency->at_grow(LCA->_nodes[LCA->end_idx()]->_idx);
0N/A bool in_latency = (target <= start_latency);
0N/A const Block* root_block = _bbs[_root->_idx];
0N/A
0N/A // Turn off latency scheduling if scheduling is just plain off
0N/A if (!C->do_scheduling())
0N/A in_latency = true;
0N/A
0N/A // Do not hoist (to cover latency) instructions which target a
0N/A // single register. Hoisting stretches the live range of the
0N/A // single register and may force spilling.
0N/A MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
0N/A if (mach && mach->out_RegMask().is_bound1() && mach->out_RegMask().is_NotEmpty())
0N/A in_latency = true;
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("# Find cheaper block for latency %d: ",
1605N/A _node_latency->at_grow(self->_idx));
0N/A self->dump();
0N/A tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
0N/A LCA->_pre_order,
0N/A LCA->_nodes[0]->_idx,
0N/A start_latency,
0N/A LCA->_nodes[LCA->end_idx()]->_idx,
0N/A end_latency,
0N/A least_freq);
0N/A }
0N/A#endif
0N/A
0N/A // Walk up the dominator tree from LCA (Lowest common ancestor) to
0N/A // the earliest legal location. Capture the least execution frequency.
0N/A while (LCA != early) {
0N/A LCA = LCA->_idom; // Follow up the dominator tree
0N/A
0N/A if (LCA == NULL) {
0N/A // Bailout without retry
0N/A C->record_method_not_compilable("late schedule failed: LCA == NULL");
0N/A return least;
0N/A }
0N/A
0N/A // Don't hoist machine instructions to the root basic block
0N/A if (mach && LCA == root_block)
0N/A break;
0N/A
1605N/A uint start_lat = _node_latency->at_grow(LCA->_nodes[0]->_idx);
0N/A uint end_idx = LCA->end_idx();
1605N/A uint end_lat = _node_latency->at_grow(LCA->_nodes[end_idx]->_idx);
0N/A double LCA_freq = LCA->_freq;
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
0N/A LCA->_pre_order, LCA->_nodes[0]->_idx, start_lat, end_idx, end_lat, LCA_freq);
0N/A }
0N/A#endif
0N/A if (LCA_freq < least_freq || // Better Frequency
0N/A ( !in_latency && // No block containing latency
0N/A LCA_freq < least_freq * delta && // No worse frequency
0N/A target >= end_lat && // within latency range
0N/A !self->is_iteratively_computed() ) // But don't hoist IV increments
0N/A // because they may end up above other uses of their phi forcing
0N/A // their result register to be different from their input.
0N/A ) {
0N/A least = LCA; // Found cheaper block
0N/A least_freq = LCA_freq;
0N/A start_latency = start_lat;
0N/A end_latency = end_lat;
0N/A if (target <= start_lat)
0N/A in_latency = true;
0N/A }
0N/A }
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print_cr("# Choose block B%d with start latency=%d and freq=%g",
0N/A least->_pre_order, start_latency, least_freq);
0N/A }
0N/A#endif
0N/A
0N/A // See if the latency needs to be updated
0N/A if (target < end_latency) {
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print_cr("# Change latency for [%4d] from %d to %d", self->_idx, target, end_latency);
0N/A }
0N/A#endif
1605N/A _node_latency->at_put_grow(self->_idx, end_latency);
0N/A partial_latency_of_defs(self);
0N/A }
0N/A
0N/A return least;
0N/A}
0N/A
0N/A
0N/A//------------------------------schedule_late-----------------------------------
0N/A// Now schedule all codes as LATE as possible. This is the LCA in the
0N/A// dominator tree of all USES of a value. Pick the block with the least
0N/A// loop nesting depth that is lowest in the dominator tree.
0N/Aextern const char must_clone[];
0N/Avoid PhaseCFG::schedule_late(VectorSet &visited, Node_List &stack) {
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining())
0N/A tty->print("\n#---- schedule_late ----\n");
0N/A#endif
0N/A
0N/A Node_Backward_Iterator iter((Node *)_root, visited, stack, _bbs);
0N/A Node *self;
0N/A
0N/A // Walk over all the nodes from last to first
0N/A while (self = iter.next()) {
0N/A Block* early = _bbs[self->_idx]; // Earliest legal placement
0N/A
0N/A if (self->is_top()) {
0N/A // Top node goes in bb #2 with other constants.
0N/A // It must be special-cased, because it has no out edges.
0N/A early->add_inst(self);
0N/A continue;
0N/A }
0N/A
0N/A // No uses, just terminate
0N/A if (self->outcnt() == 0) {
2667N/A assert(self->is_MachProj(), "sanity");
0N/A continue; // Must be a dead machine projection
0N/A }
0N/A
0N/A // If node is pinned in the block, then no scheduling can be done.
0N/A if( self->pinned() ) // Pinned in block?
0N/A continue;
0N/A
0N/A MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
0N/A if (mach) {
0N/A switch (mach->ideal_Opcode()) {
0N/A case Op_CreateEx:
0N/A // Don't move exception creation
0N/A early->add_inst(self);
0N/A continue;
0N/A break;
0N/A case Op_CheckCastPP:
0N/A // Don't move CheckCastPP nodes away from their input, if the input
0N/A // is a rawptr (5071820).
0N/A Node *def = self->in(1);
0N/A if (def != NULL && def->bottom_type()->base() == Type::RawPtr) {
0N/A early->add_inst(self);
833N/A#ifdef ASSERT
833N/A _raw_oops.push(def);
833N/A#endif
0N/A continue;
0N/A }
0N/A break;
0N/A }
0N/A }
0N/A
0N/A // Gather LCA of all uses
0N/A Block *LCA = NULL;
0N/A {
0N/A for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
0N/A // For all uses, find LCA
0N/A Node* use = self->fast_out(i);
0N/A LCA = raise_LCA_above_use(LCA, use, self, _bbs);
0N/A }
0N/A } // (Hide defs of imax, i from rest of block.)
0N/A
0N/A // Place temps in the block of their use. This isn't a
0N/A // requirement for correctness but it reduces useless
0N/A // interference between temps and other nodes.
0N/A if (mach != NULL && mach->is_MachTemp()) {
0N/A _bbs.map(self->_idx, LCA);
0N/A LCA->add_inst(self);
0N/A continue;
0N/A }
0N/A
0N/A // Check if 'self' could be anti-dependent on memory
0N/A if (self->needs_anti_dependence_check()) {
0N/A // Hoist LCA above possible-defs and insert anti-dependences to
0N/A // defs in new LCA block.
0N/A LCA = insert_anti_dependences(LCA, self);
0N/A }
0N/A
0N/A if (early->_dom_depth > LCA->_dom_depth) {
0N/A // Somehow the LCA has moved above the earliest legal point.
0N/A // (One way this can happen is via memory_early_block.)
0N/A if (C->subsume_loads() == true && !C->failing()) {
0N/A // Retry with subsume_loads == false
0N/A // If this is the first failure, the sentinel string will "stick"
0N/A // to the Compile object, and the C2Compiler will see it and retry.
0N/A C->record_failure(C2Compiler::retry_no_subsuming_loads());
0N/A } else {
0N/A // Bailout without retry when (early->_dom_depth > LCA->_dom_depth)
0N/A C->record_method_not_compilable("late schedule failed: incorrect graph");
0N/A }
0N/A return;
0N/A }
0N/A
0N/A // If there is no opportunity to hoist, then we're done.
0N/A bool try_to_hoist = (LCA != early);
0N/A
0N/A // Must clone guys stay next to use; no hoisting allowed.
0N/A // Also cannot hoist guys that alter memory or are otherwise not
0N/A // allocatable (hoisting can make a value live longer, leading to
0N/A // anti and output dependency problems which are normally resolved
0N/A // by the register allocator giving everyone a different register).
0N/A if (mach != NULL && must_clone[mach->ideal_Opcode()])
0N/A try_to_hoist = false;
0N/A
0N/A Block* late = NULL;
0N/A if (try_to_hoist) {
0N/A // Now find the block with the least execution frequency.
0N/A // Start at the latest schedule and work up to the earliest schedule
0N/A // in the dominator tree. Thus the Node will dominate all its uses.
0N/A late = hoist_to_cheaper_block(LCA, early, self);
0N/A } else {
0N/A // Just use the LCA of the uses.
0N/A late = LCA;
0N/A }
0N/A
0N/A // Put the node into target block
0N/A schedule_node_into_block(self, late);
0N/A
0N/A#ifdef ASSERT
0N/A if (self->needs_anti_dependence_check()) {
0N/A // since precedence edges are only inserted when we're sure they
0N/A // are needed make sure that after placement in a block we don't
0N/A // need any new precedence edges.
0N/A verify_anti_dependences(late, self);
0N/A }
0N/A#endif
0N/A } // Loop until all nodes have been visited
0N/A
0N/A} // end ScheduleLate
0N/A
0N/A//------------------------------GlobalCodeMotion-------------------------------
0N/Avoid PhaseCFG::GlobalCodeMotion( Matcher &matcher, uint unique, Node_List &proj_list ) {
0N/A ResourceMark rm;
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("\n---- Start GlobalCodeMotion ----\n");
0N/A }
0N/A#endif
0N/A
0N/A // Initialize the bbs.map for things on the proj_list
0N/A uint i;
0N/A for( i=0; i < proj_list.size(); i++ )
0N/A _bbs.map(proj_list[i]->_idx, NULL);
0N/A
0N/A // Set the basic block for Nodes pinned into blocks
0N/A Arena *a = Thread::current()->resource_area();
0N/A VectorSet visited(a);
0N/A schedule_pinned_nodes( visited );
0N/A
0N/A // Find the earliest Block any instruction can be placed in. Some
0N/A // instructions are pinned into Blocks. Unpinned instructions can
0N/A // appear in last block in which all their inputs occur.
0N/A visited.Clear();
0N/A Node_List stack(a);
0N/A stack.map( (unique >> 1) + 16, NULL); // Pre-grow the list
0N/A if (!schedule_early(visited, stack)) {
0N/A // Bailout without retry
0N/A C->record_method_not_compilable("early schedule failed");
0N/A return;
0N/A }
0N/A
0N/A // Build Def-Use edges.
0N/A proj_list.push(_root); // Add real root as another root
0N/A proj_list.pop();
0N/A
0N/A // Compute the latency information (via backwards walk) for all the
0N/A // instructions in the graph
1605N/A _node_latency = new GrowableArray<uint>(); // resource_area allocation
0N/A
0N/A if( C->do_scheduling() )
0N/A ComputeLatenciesBackwards(visited, stack);
0N/A
0N/A // Now schedule all codes as LATE as possible. This is the LCA in the
0N/A // dominator tree of all USES of a value. Pick the block with the least
0N/A // loop nesting depth that is lowest in the dominator tree.
0N/A // ( visited.Clear() called in schedule_late()->Node_Backward_Iterator() )
0N/A schedule_late(visited, stack);
0N/A if( C->failing() ) {
0N/A // schedule_late fails only when graph is incorrect.
0N/A assert(!VerifyGraphEdges, "verification should have failed");
0N/A return;
0N/A }
0N/A
0N/A unique = C->unique();
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("\n---- Detect implicit null checks ----\n");
0N/A }
0N/A#endif
0N/A
0N/A // Detect implicit-null-check opportunities. Basically, find NULL checks
0N/A // with suitable memory ops nearby. Use the memory op to do the NULL check.
0N/A // I can generate a memory op if there is not one nearby.
0N/A if (C->is_method_compilation()) {
0N/A // Don't do it for natives, adapters, or runtime stubs
0N/A int allowed_reasons = 0;
0N/A // ...and don't do it when there have been too many traps, globally.
0N/A for (int reason = (int)Deoptimization::Reason_none+1;
0N/A reason < Compile::trapHistLength; reason++) {
0N/A assert(reason < BitsPerInt, "recode bit map");
0N/A if (!C->too_many_traps((Deoptimization::DeoptReason) reason))
0N/A allowed_reasons |= nth_bit(reason);
0N/A }
0N/A // By reversing the loop direction we get a very minor gain on mpegaudio.
0N/A // Feel free to revert to a forward loop for clarity.
0N/A // for( int i=0; i < (int)matcher._null_check_tests.size(); i+=2 ) {
0N/A for( int i= matcher._null_check_tests.size()-2; i>=0; i-=2 ) {
0N/A Node *proj = matcher._null_check_tests[i ];
0N/A Node *val = matcher._null_check_tests[i+1];
0N/A _bbs[proj->_idx]->implicit_null_check(this, proj, val, allowed_reasons);
0N/A // The implicit_null_check will only perform the transformation
0N/A // if the null branch is truly uncommon, *and* it leads to an
0N/A // uncommon trap. Combined with the too_many_traps guards
0N/A // above, this prevents SEGV storms reported in 6366351,
0N/A // by recompiling offending methods without this optimization.
0N/A }
0N/A }
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("\n---- Start Local Scheduling ----\n");
0N/A }
0N/A#endif
0N/A
0N/A // Schedule locally. Right now a simple topological sort.
0N/A // Later, do a real latency aware scheduler.
3103N/A uint max_idx = C->unique();
3103N/A GrowableArray<int> ready_cnt(max_idx, max_idx, -1);
0N/A visited.Clear();
0N/A for (i = 0; i < _num_blocks; i++) {
0N/A if (!_blocks[i]->schedule_local(this, matcher, ready_cnt, visited)) {
0N/A if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
0N/A C->record_method_not_compilable("local schedule failed");
0N/A }
0N/A return;
0N/A }
0N/A }
0N/A
0N/A // If we inserted any instructions between a Call and his CatchNode,
0N/A // clone the instructions on all paths below the Catch.
0N/A for( i=0; i < _num_blocks; i++ )
4123N/A _blocks[i]->call_catch_cleanup(_bbs, C);
0N/A
0N/A#ifndef PRODUCT
0N/A if (trace_opto_pipelining()) {
0N/A tty->print("\n---- After GlobalCodeMotion ----\n");
0N/A for (uint i = 0; i < _num_blocks; i++) {
0N/A _blocks[i]->dump();
0N/A }
0N/A }
0N/A#endif
1605N/A // Dead.
1605N/A _node_latency = (GrowableArray<uint> *)0xdeadbeef;
0N/A}
0N/A
0N/A
0N/A//------------------------------Estimate_Block_Frequency-----------------------
0N/A// Estimate block frequencies based on IfNode probabilities.
0N/Avoid PhaseCFG::Estimate_Block_Frequency() {
418N/A
418N/A // Force conditional branches leading to uncommon traps to be unlikely,
418N/A // not because we get to the uncommon_trap with less relative frequency,
418N/A // but because an uncommon_trap typically causes a deopt, so we only get
418N/A // there once.
418N/A if (C->do_freq_based_layout()) {
418N/A Block_List worklist;
418N/A Block* root_blk = _blocks[0];
418N/A for (uint i = 1; i < root_blk->num_preds(); i++) {
418N/A Block *pb = _bbs[root_blk->pred(i)->_idx];
418N/A if (pb->has_uncommon_code()) {
418N/A worklist.push(pb);
418N/A }
418N/A }
418N/A while (worklist.size() > 0) {
418N/A Block* uct = worklist.pop();
418N/A if (uct == _broot) continue;
418N/A for (uint i = 1; i < uct->num_preds(); i++) {
418N/A Block *pb = _bbs[uct->pred(i)->_idx];
418N/A if (pb->_num_succs == 1) {
418N/A worklist.push(pb);
418N/A } else if (pb->num_fall_throughs() == 2) {
418N/A pb->update_uncommon_branch(uct);
418N/A }
418N/A }
418N/A }
418N/A }
0N/A
0N/A // Create the loop tree and calculate loop depth.
0N/A _root_loop = create_loop_tree();
0N/A _root_loop->compute_loop_depth(0);
0N/A
0N/A // Compute block frequency of each block, relative to a single loop entry.
0N/A _root_loop->compute_freq();
0N/A
0N/A // Adjust all frequencies to be relative to a single method entry
418N/A _root_loop->_freq = 1.0;
0N/A _root_loop->scale_freq();
0N/A
673N/A // Save outmost loop frequency for LRG frequency threshold
673N/A _outer_loop_freq = _root_loop->outer_loop_freq();
673N/A
0N/A // force paths ending at uncommon traps to be infrequent
418N/A if (!C->do_freq_based_layout()) {
418N/A Block_List worklist;
418N/A Block* root_blk = _blocks[0];
418N/A for (uint i = 1; i < root_blk->num_preds(); i++) {
418N/A Block *pb = _bbs[root_blk->pred(i)->_idx];
418N/A if (pb->has_uncommon_code()) {
418N/A worklist.push(pb);
418N/A }
0N/A }
418N/A while (worklist.size() > 0) {
418N/A Block* uct = worklist.pop();
418N/A uct->_freq = PROB_MIN;
418N/A for (uint i = 1; i < uct->num_preds(); i++) {
418N/A Block *pb = _bbs[uct->pred(i)->_idx];
418N/A if (pb->_num_succs == 1 && pb->_freq > PROB_MIN) {
418N/A worklist.push(pb);
418N/A }
0N/A }
0N/A }
0N/A }
0N/A
552N/A#ifdef ASSERT
552N/A for (uint i = 0; i < _num_blocks; i++ ) {
552N/A Block *b = _blocks[i];
605N/A assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency");
552N/A }
552N/A#endif
552N/A
0N/A#ifndef PRODUCT
0N/A if (PrintCFGBlockFreq) {
0N/A tty->print_cr("CFG Block Frequencies");
0N/A _root_loop->dump_tree();
0N/A if (Verbose) {
0N/A tty->print_cr("PhaseCFG dump");
0N/A dump();
0N/A tty->print_cr("Node dump");
0N/A _root->dump(99999);
0N/A }
0N/A }
0N/A#endif
0N/A}
0N/A
0N/A//----------------------------create_loop_tree--------------------------------
0N/A// Create a loop tree from the CFG
0N/ACFGLoop* PhaseCFG::create_loop_tree() {
0N/A
0N/A#ifdef ASSERT
0N/A assert( _blocks[0] == _broot, "" );
0N/A for (uint i = 0; i < _num_blocks; i++ ) {
0N/A Block *b = _blocks[i];
0N/A // Check that _loop field are clear...we could clear them if not.
0N/A assert(b->_loop == NULL, "clear _loop expected");
0N/A // Sanity check that the RPO numbering is reflected in the _blocks array.
0N/A // It doesn't have to be for the loop tree to be built, but if it is not,
0N/A // then the blocks have been reordered since dom graph building...which
0N/A // may question the RPO numbering
0N/A assert(b->_rpo == i, "unexpected reverse post order number");
0N/A }
0N/A#endif
0N/A
0N/A int idct = 0;
0N/A CFGLoop* root_loop = new CFGLoop(idct++);
0N/A
0N/A Block_List worklist;
0N/A
0N/A // Assign blocks to loops
0N/A for(uint i = _num_blocks - 1; i > 0; i-- ) { // skip Root block
0N/A Block *b = _blocks[i];
0N/A
0N/A if (b->head()->is_Loop()) {
0N/A Block* loop_head = b;
0N/A assert(loop_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
0N/A Node* tail_n = loop_head->pred(LoopNode::LoopBackControl);
0N/A Block* tail = _bbs[tail_n->_idx];
0N/A
0N/A // Defensively filter out Loop nodes for non-single-entry loops.
0N/A // For all reasonable loops, the head occurs before the tail in RPO.
0N/A if (i <= tail->_rpo) {
0N/A
0N/A // The tail and (recursive) predecessors of the tail
0N/A // are made members of a new loop.
0N/A
0N/A assert(worklist.size() == 0, "nonempty worklist");
0N/A CFGLoop* nloop = new CFGLoop(idct++);
0N/A assert(loop_head->_loop == NULL, "just checking");
0N/A loop_head->_loop = nloop;
0N/A // Add to nloop so push_pred() will skip over inner loops
0N/A nloop->add_member(loop_head);
0N/A nloop->push_pred(loop_head, LoopNode::LoopBackControl, worklist, _bbs);
0N/A
0N/A while (worklist.size() > 0) {
0N/A Block* member = worklist.pop();
0N/A if (member != loop_head) {
0N/A for (uint j = 1; j < member->num_preds(); j++) {
0N/A nloop->push_pred(member, j, worklist, _bbs);
0N/A }
0N/A }
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A // Create a member list for each loop consisting
0N/A // of both blocks and (immediate child) loops.
0N/A for (uint i = 0; i < _num_blocks; i++) {
0N/A Block *b = _blocks[i];
0N/A CFGLoop* lp = b->_loop;
0N/A if (lp == NULL) {
0N/A // Not assigned to a loop. Add it to the method's pseudo loop.
0N/A b->_loop = root_loop;
0N/A lp = root_loop;
0N/A }
0N/A if (lp == root_loop || b != lp->head()) { // loop heads are already members
0N/A lp->add_member(b);
0N/A }
0N/A if (lp != root_loop) {
0N/A if (lp->parent() == NULL) {
0N/A // Not a nested loop. Make it a child of the method's pseudo loop.
0N/A root_loop->add_nested_loop(lp);
0N/A }
0N/A if (b == lp->head()) {
0N/A // Add nested loop to member list of parent loop.
0N/A lp->parent()->add_member(lp);
0N/A }
0N/A }
0N/A }
0N/A
0N/A return root_loop;
0N/A}
0N/A
0N/A//------------------------------push_pred--------------------------------------
0N/Avoid CFGLoop::push_pred(Block* blk, int i, Block_List& worklist, Block_Array& node_to_blk) {
0N/A Node* pred_n = blk->pred(i);
0N/A Block* pred = node_to_blk[pred_n->_idx];
0N/A CFGLoop *pred_loop = pred->_loop;
0N/A if (pred_loop == NULL) {
0N/A // Filter out blocks for non-single-entry loops.
0N/A // For all reasonable loops, the head occurs before the tail in RPO.
0N/A if (pred->_rpo > head()->_rpo) {
0N/A pred->_loop = this;
0N/A worklist.push(pred);
0N/A }
0N/A } else if (pred_loop != this) {
0N/A // Nested loop.
0N/A while (pred_loop->_parent != NULL && pred_loop->_parent != this) {
0N/A pred_loop = pred_loop->_parent;
0N/A }
0N/A // Make pred's loop be a child
0N/A if (pred_loop->_parent == NULL) {
0N/A add_nested_loop(pred_loop);
0N/A // Continue with loop entry predecessor.
0N/A Block* pred_head = pred_loop->head();
0N/A assert(pred_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
0N/A assert(pred_head != head(), "loop head in only one loop");
0N/A push_pred(pred_head, LoopNode::EntryControl, worklist, node_to_blk);
0N/A } else {
0N/A assert(pred_loop->_parent == this && _parent == NULL, "just checking");
0N/A }
0N/A }
0N/A}
0N/A
0N/A//------------------------------add_nested_loop--------------------------------
0N/A// Make cl a child of the current loop in the loop tree.
0N/Avoid CFGLoop::add_nested_loop(CFGLoop* cl) {
0N/A assert(_parent == NULL, "no parent yet");
0N/A assert(cl != this, "not my own parent");
0N/A cl->_parent = this;
0N/A CFGLoop* ch = _child;
0N/A if (ch == NULL) {
0N/A _child = cl;
0N/A } else {
0N/A while (ch->_sibling != NULL) { ch = ch->_sibling; }
0N/A ch->_sibling = cl;
0N/A }
0N/A}
0N/A
0N/A//------------------------------compute_loop_depth-----------------------------
0N/A// Store the loop depth in each CFGLoop object.
0N/A// Recursively walk the children to do the same for them.
0N/Avoid CFGLoop::compute_loop_depth(int depth) {
0N/A _depth = depth;
0N/A CFGLoop* ch = _child;
0N/A while (ch != NULL) {
0N/A ch->compute_loop_depth(depth + 1);
0N/A ch = ch->_sibling;
0N/A }
0N/A}
0N/A
0N/A//------------------------------compute_freq-----------------------------------
0N/A// Compute the frequency of each block and loop, relative to a single entry
0N/A// into the dominating loop head.
0N/Avoid CFGLoop::compute_freq() {
0N/A // Bottom up traversal of loop tree (visit inner loops first.)
0N/A // Set loop head frequency to 1.0, then transitively
0N/A // compute frequency for all successors in the loop,
0N/A // as well as for each exit edge. Inner loops are
0N/A // treated as single blocks with loop exit targets
0N/A // as the successor blocks.
0N/A
0N/A // Nested loops first
0N/A CFGLoop* ch = _child;
0N/A while (ch != NULL) {
0N/A ch->compute_freq();
0N/A ch = ch->_sibling;
0N/A }
0N/A assert (_members.length() > 0, "no empty loops");
0N/A Block* hd = head();
0N/A hd->_freq = 1.0f;
0N/A for (int i = 0; i < _members.length(); i++) {
0N/A CFGElement* s = _members.at(i);
0N/A float freq = s->_freq;
0N/A if (s->is_block()) {
0N/A Block* b = s->as_Block();
0N/A for (uint j = 0; j < b->_num_succs; j++) {
0N/A Block* sb = b->_succs[j];
0N/A update_succ_freq(sb, freq * b->succ_prob(j));
0N/A }
0N/A } else {
0N/A CFGLoop* lp = s->as_CFGLoop();
0N/A assert(lp->_parent == this, "immediate child");
0N/A for (int k = 0; k < lp->_exits.length(); k++) {
0N/A Block* eb = lp->_exits.at(k).get_target();
0N/A float prob = lp->_exits.at(k).get_prob();
0N/A update_succ_freq(eb, freq * prob);
0N/A }
0N/A }
0N/A }
0N/A
0N/A // For all loops other than the outer, "method" loop,
0N/A // sum and normalize the exit probability. The "method" loop
0N/A // should keep the initial exit probability of 1, so that
0N/A // inner blocks do not get erroneously scaled.
0N/A if (_depth != 0) {
0N/A // Total the exit probabilities for this loop.
0N/A float exits_sum = 0.0f;
0N/A for (int i = 0; i < _exits.length(); i++) {
0N/A exits_sum += _exits.at(i).get_prob();
0N/A }
0N/A
0N/A // Normalize the exit probabilities. Until now, the
0N/A // probabilities estimate the possibility of exit per
0N/A // a single loop iteration; afterward, they estimate
0N/A // the probability of exit per loop entry.
0N/A for (int i = 0; i < _exits.length(); i++) {
0N/A Block* et = _exits.at(i).get_target();
418N/A float new_prob = 0.0f;
418N/A if (_exits.at(i).get_prob() > 0.0f) {
418N/A new_prob = _exits.at(i).get_prob() / exits_sum;
418N/A }
0N/A BlockProbPair bpp(et, new_prob);
0N/A _exits.at_put(i, bpp);
0N/A }
0N/A
418N/A // Save the total, but guard against unreasonable probability,
0N/A // as the value is used to estimate the loop trip count.
0N/A // An infinite trip count would blur relative block
0N/A // frequencies.
0N/A if (exits_sum > 1.0f) exits_sum = 1.0;
0N/A if (exits_sum < PROB_MIN) exits_sum = PROB_MIN;
0N/A _exit_prob = exits_sum;
0N/A }
0N/A}
0N/A
0N/A//------------------------------succ_prob-------------------------------------
0N/A// Determine the probability of reaching successor 'i' from the receiver block.
0N/Afloat Block::succ_prob(uint i) {
0N/A int eidx = end_idx();
0N/A Node *n = _nodes[eidx]; // Get ending Node
308N/A
308N/A int op = n->Opcode();
308N/A if (n->is_Mach()) {
308N/A if (n->is_MachNullCheck()) {
308N/A // Can only reach here if called after lcm. The original Op_If is gone,
308N/A // so we attempt to infer the probability from one or both of the
308N/A // successor blocks.
308N/A assert(_num_succs == 2, "expecting 2 successors of a null check");
308N/A // If either successor has only one predecessor, then the
605N/A // probability estimate can be derived using the
308N/A // relative frequency of the successor and this block.
308N/A if (_succs[i]->num_preds() == 2) {
308N/A return _succs[i]->_freq / _freq;
308N/A } else if (_succs[1-i]->num_preds() == 2) {
308N/A return 1 - (_succs[1-i]->_freq / _freq);
308N/A } else {
308N/A // Estimate using both successor frequencies
308N/A float freq = _succs[i]->_freq;
308N/A return freq / (freq + _succs[1-i]->_freq);
308N/A }
308N/A }
308N/A op = n->as_Mach()->ideal_Opcode();
308N/A }
308N/A
0N/A
0N/A // Switch on branch type
0N/A switch( op ) {
0N/A case Op_CountedLoopEnd:
0N/A case Op_If: {
0N/A assert (i < 2, "just checking");
0N/A // Conditionals pass on only part of their frequency
0N/A float prob = n->as_MachIf()->_prob;
0N/A assert(prob >= 0.0 && prob <= 1.0, "out of range probability");
0N/A // If succ[i] is the FALSE branch, invert path info
0N/A if( _nodes[i + eidx + 1]->Opcode() == Op_IfFalse ) {
0N/A return 1.0f - prob; // not taken
0N/A } else {
0N/A return prob; // taken
0N/A }
0N/A }
0N/A
0N/A case Op_Jump:
0N/A // Divide the frequency between all successors evenly
0N/A return 1.0f/_num_succs;
0N/A
0N/A case Op_Catch: {
0N/A const CatchProjNode *ci = _nodes[i + eidx + 1]->as_CatchProj();
0N/A if (ci->_con == CatchProjNode::fall_through_index) {
0N/A // Fall-thru path gets the lion's share.
0N/A return 1.0f - PROB_UNLIKELY_MAG(5)*_num_succs;
0N/A } else {
0N/A // Presume exceptional paths are equally unlikely
0N/A return PROB_UNLIKELY_MAG(5);
0N/A }
0N/A }
0N/A
0N/A case Op_Root:
0N/A case Op_Goto:
0N/A // Pass frequency straight thru to target
0N/A return 1.0f;
0N/A
0N/A case Op_NeverBranch:
0N/A return 0.0f;
0N/A
0N/A case Op_TailCall:
0N/A case Op_TailJump:
0N/A case Op_Return:
0N/A case Op_Halt:
0N/A case Op_Rethrow:
0N/A // Do not push out freq to root block
0N/A return 0.0f;
0N/A
0N/A default:
0N/A ShouldNotReachHere();
0N/A }
0N/A
0N/A return 0.0f;
0N/A}
0N/A
418N/A//------------------------------num_fall_throughs-----------------------------
418N/A// Return the number of fall-through candidates for a block
418N/Aint Block::num_fall_throughs() {
418N/A int eidx = end_idx();
418N/A Node *n = _nodes[eidx]; // Get ending Node
418N/A
418N/A int op = n->Opcode();
418N/A if (n->is_Mach()) {
418N/A if (n->is_MachNullCheck()) {
418N/A // In theory, either side can fall-thru, for simplicity sake,
418N/A // let's say only the false branch can now.
418N/A return 1;
418N/A }
418N/A op = n->as_Mach()->ideal_Opcode();
418N/A }
418N/A
418N/A // Switch on branch type
418N/A switch( op ) {
418N/A case Op_CountedLoopEnd:
418N/A case Op_If:
418N/A return 2;
418N/A
418N/A case Op_Root:
418N/A case Op_Goto:
418N/A return 1;
418N/A
418N/A case Op_Catch: {
418N/A for (uint i = 0; i < _num_succs; i++) {
418N/A const CatchProjNode *ci = _nodes[i + eidx + 1]->as_CatchProj();
418N/A if (ci->_con == CatchProjNode::fall_through_index) {
418N/A return 1;
418N/A }
418N/A }
418N/A return 0;
418N/A }
418N/A
418N/A case Op_Jump:
418N/A case Op_NeverBranch:
418N/A case Op_TailCall:
418N/A case Op_TailJump:
418N/A case Op_Return:
418N/A case Op_Halt:
418N/A case Op_Rethrow:
418N/A return 0;
418N/A
418N/A default:
418N/A ShouldNotReachHere();
418N/A }
418N/A
418N/A return 0;
418N/A}
418N/A
418N/A//------------------------------succ_fall_through-----------------------------
418N/A// Return true if a specific successor could be fall-through target.
418N/Abool Block::succ_fall_through(uint i) {
418N/A int eidx = end_idx();
418N/A Node *n = _nodes[eidx]; // Get ending Node
418N/A
418N/A int op = n->Opcode();
418N/A if (n->is_Mach()) {
418N/A if (n->is_MachNullCheck()) {
418N/A // In theory, either side can fall-thru, for simplicity sake,
418N/A // let's say only the false branch can now.
418N/A return _nodes[i + eidx + 1]->Opcode() == Op_IfFalse;
418N/A }
418N/A op = n->as_Mach()->ideal_Opcode();
418N/A }
418N/A
418N/A // Switch on branch type
418N/A switch( op ) {
418N/A case Op_CountedLoopEnd:
418N/A case Op_If:
418N/A case Op_Root:
418N/A case Op_Goto:
418N/A return true;
418N/A
418N/A case Op_Catch: {
418N/A const CatchProjNode *ci = _nodes[i + eidx + 1]->as_CatchProj();
418N/A return ci->_con == CatchProjNode::fall_through_index;
418N/A }
418N/A
418N/A case Op_Jump:
418N/A case Op_NeverBranch:
418N/A case Op_TailCall:
418N/A case Op_TailJump:
418N/A case Op_Return:
418N/A case Op_Halt:
418N/A case Op_Rethrow:
418N/A return false;
418N/A
418N/A default:
418N/A ShouldNotReachHere();
418N/A }
418N/A
418N/A return false;
418N/A}
418N/A
418N/A//------------------------------update_uncommon_branch------------------------
418N/A// Update the probability of a two-branch to be uncommon
418N/Avoid Block::update_uncommon_branch(Block* ub) {
418N/A int eidx = end_idx();
418N/A Node *n = _nodes[eidx]; // Get ending Node
418N/A
418N/A int op = n->as_Mach()->ideal_Opcode();
418N/A
418N/A assert(op == Op_CountedLoopEnd || op == Op_If, "must be a If");
418N/A assert(num_fall_throughs() == 2, "must be a two way branch block");
418N/A
418N/A // Which successor is ub?
418N/A uint s;
418N/A for (s = 0; s <_num_succs; s++) {
418N/A if (_succs[s] == ub) break;
418N/A }
418N/A assert(s < 2, "uncommon successor must be found");
418N/A
418N/A // If ub is the true path, make the proability small, else
418N/A // ub is the false path, and make the probability large
418N/A bool invert = (_nodes[s + eidx + 1]->Opcode() == Op_IfFalse);
418N/A
418N/A // Get existing probability
418N/A float p = n->as_MachIf()->_prob;
418N/A
418N/A if (invert) p = 1.0 - p;
418N/A if (p > PROB_MIN) {
418N/A p = PROB_MIN;
418N/A }
418N/A if (invert) p = 1.0 - p;
418N/A
418N/A n->as_MachIf()->_prob = p;
418N/A}
418N/A
0N/A//------------------------------update_succ_freq-------------------------------
605N/A// Update the appropriate frequency associated with block 'b', a successor of
0N/A// a block in this loop.
0N/Avoid CFGLoop::update_succ_freq(Block* b, float freq) {
0N/A if (b->_loop == this) {
0N/A if (b == head()) {
0N/A // back branch within the loop
0N/A // Do nothing now, the loop carried frequency will be
0N/A // adjust later in scale_freq().
0N/A } else {
0N/A // simple branch within the loop
0N/A b->_freq += freq;
0N/A }
0N/A } else if (!in_loop_nest(b)) {
0N/A // branch is exit from this loop
0N/A BlockProbPair bpp(b, freq);
0N/A _exits.append(bpp);
0N/A } else {
0N/A // branch into nested loop
0N/A CFGLoop* ch = b->_loop;
0N/A ch->_freq += freq;
0N/A }
0N/A}
0N/A
0N/A//------------------------------in_loop_nest-----------------------------------
0N/A// Determine if block b is in the receiver's loop nest.
0N/Abool CFGLoop::in_loop_nest(Block* b) {
0N/A int depth = _depth;
0N/A CFGLoop* b_loop = b->_loop;
0N/A int b_depth = b_loop->_depth;
0N/A if (depth == b_depth) {
0N/A return true;
0N/A }
0N/A while (b_depth > depth) {
0N/A b_loop = b_loop->_parent;
0N/A b_depth = b_loop->_depth;
0N/A }
0N/A return b_loop == this;
0N/A}
0N/A
0N/A//------------------------------scale_freq-------------------------------------
0N/A// Scale frequency of loops and blocks by trip counts from outer loops
0N/A// Do a top down traversal of loop tree (visit outer loops first.)
0N/Avoid CFGLoop::scale_freq() {
0N/A float loop_freq = _freq * trip_count();
673N/A _freq = loop_freq;
0N/A for (int i = 0; i < _members.length(); i++) {
0N/A CFGElement* s = _members.at(i);
552N/A float block_freq = s->_freq * loop_freq;
621N/A if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY)
621N/A block_freq = MIN_BLOCK_FREQUENCY;
552N/A s->_freq = block_freq;
0N/A }
0N/A CFGLoop* ch = _child;
0N/A while (ch != NULL) {
0N/A ch->scale_freq();
0N/A ch = ch->_sibling;
0N/A }
0N/A}
0N/A
673N/A// Frequency of outer loop
673N/Afloat CFGLoop::outer_loop_freq() const {
673N/A if (_child != NULL) {
673N/A return _child->_freq;
673N/A }
673N/A return _freq;
673N/A}
673N/A
0N/A#ifndef PRODUCT
0N/A//------------------------------dump_tree--------------------------------------
0N/Avoid CFGLoop::dump_tree() const {
0N/A dump();
0N/A if (_child != NULL) _child->dump_tree();
0N/A if (_sibling != NULL) _sibling->dump_tree();
0N/A}
0N/A
0N/A//------------------------------dump-------------------------------------------
0N/Avoid CFGLoop::dump() const {
0N/A for (int i = 0; i < _depth; i++) tty->print(" ");
0N/A tty->print("%s: %d trip_count: %6.0f freq: %6.0f\n",
0N/A _depth == 0 ? "Method" : "Loop", _id, trip_count(), _freq);
0N/A for (int i = 0; i < _depth; i++) tty->print(" ");
0N/A tty->print(" members:", _id);
0N/A int k = 0;
0N/A for (int i = 0; i < _members.length(); i++) {
0N/A if (k++ >= 6) {
0N/A tty->print("\n ");
0N/A for (int j = 0; j < _depth+1; j++) tty->print(" ");
0N/A k = 0;
0N/A }
0N/A CFGElement *s = _members.at(i);
0N/A if (s->is_block()) {
0N/A Block *b = s->as_Block();
0N/A tty->print(" B%d(%6.3f)", b->_pre_order, b->_freq);
0N/A } else {
0N/A CFGLoop* lp = s->as_CFGLoop();
0N/A tty->print(" L%d(%6.3f)", lp->_id, lp->_freq);
0N/A }
0N/A }
0N/A tty->print("\n");
0N/A for (int i = 0; i < _depth; i++) tty->print(" ");
0N/A tty->print(" exits: ");
0N/A k = 0;
0N/A for (int i = 0; i < _exits.length(); i++) {
0N/A if (k++ >= 7) {
0N/A tty->print("\n ");
0N/A for (int j = 0; j < _depth+1; j++) tty->print(" ");
0N/A k = 0;
0N/A }
0N/A Block *blk = _exits.at(i).get_target();
0N/A float prob = _exits.at(i).get_prob();
0N/A tty->print(" ->%d@%d%%", blk->_pre_order, (int)(prob*100));
0N/A }
0N/A tty->print("\n");
0N/A}
0N/A#endif