Tue, 10 Mar 2020 10:46:35 +0100
8146612: C2: Precedence edges specification violated
Reviewed-by: kvn
1 /*
2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #ifndef SHARE_VM_OPTO_BLOCK_HPP
26 #define SHARE_VM_OPTO_BLOCK_HPP
28 #include "opto/multnode.hpp"
29 #include "opto/node.hpp"
30 #include "opto/phase.hpp"
32 // Optimization - Graph Style
34 class Block;
35 class CFGLoop;
36 class MachCallNode;
37 class Matcher;
38 class RootNode;
39 class VectorSet;
40 struct Tarjan;
42 //------------------------------Block_Array------------------------------------
43 // Map dense integer indices to Blocks. Uses classic doubling-array trick.
44 // Abstractly provides an infinite array of Block*'s, initialized to NULL.
45 // Note that the constructor just zeros things, and since I use Arena
46 // allocation I do not need a destructor to reclaim storage.
47 class Block_Array : public ResourceObj {
48 friend class VMStructs;
49 uint _size; // allocated size, as opposed to formal limit
50 debug_only(uint _limit;) // limit to formal domain
51 Arena *_arena; // Arena to allocate in
52 protected:
53 Block **_blocks;
54 void grow( uint i ); // Grow array node to fit
56 public:
57 Block_Array(Arena *a) : _arena(a), _size(OptoBlockListSize) {
58 debug_only(_limit=0);
59 _blocks = NEW_ARENA_ARRAY( a, Block *, OptoBlockListSize );
60 for( int i = 0; i < OptoBlockListSize; i++ ) {
61 _blocks[i] = NULL;
62 }
63 }
64 Block *lookup( uint i ) const // Lookup, or NULL for not mapped
65 { return (i<Max()) ? _blocks[i] : (Block*)NULL; }
66 Block *operator[] ( uint i ) const // Lookup, or assert for not mapped
67 { assert( i < Max(), "oob" ); return _blocks[i]; }
68 // Extend the mapping: index i maps to Block *n.
69 void map( uint i, Block *n ) { if( i>=Max() ) grow(i); _blocks[i] = n; }
70 uint Max() const { debug_only(return _limit); return _size; }
71 };
74 class Block_List : public Block_Array {
75 friend class VMStructs;
76 public:
77 uint _cnt;
78 Block_List() : Block_Array(Thread::current()->resource_area()), _cnt(0) {}
79 void push( Block *b ) { map(_cnt++,b); }
80 Block *pop() { return _blocks[--_cnt]; }
81 Block *rpop() { Block *b = _blocks[0]; _blocks[0]=_blocks[--_cnt]; return b;}
82 void remove( uint i );
83 void insert( uint i, Block *n );
84 uint size() const { return _cnt; }
85 void reset() { _cnt = 0; }
86 void print();
87 };
90 class CFGElement : public ResourceObj {
91 friend class VMStructs;
92 public:
93 float _freq; // Execution frequency (estimate)
95 CFGElement() : _freq(0.0f) {}
96 virtual bool is_block() { return false; }
97 virtual bool is_loop() { return false; }
98 Block* as_Block() { assert(is_block(), "must be block"); return (Block*)this; }
99 CFGLoop* as_CFGLoop() { assert(is_loop(), "must be loop"); return (CFGLoop*)this; }
100 };
102 //------------------------------Block------------------------------------------
103 // This class defines a Basic Block.
104 // Basic blocks are used during the output routines, and are not used during
105 // any optimization pass. They are created late in the game.
106 class Block : public CFGElement {
107 friend class VMStructs;
109 private:
110 // Nodes in this block, in order
111 Node_List _nodes;
113 public:
115 // Get the node at index 'at_index', if 'at_index' is out of bounds return NULL
116 Node* get_node(uint at_index) const {
117 return _nodes[at_index];
118 }
120 // Get the number of nodes in this block
121 uint number_of_nodes() const {
122 return _nodes.size();
123 }
125 // Map a node 'node' to index 'to_index' in the block, if the index is out of bounds the size of the node list is increased
126 void map_node(Node* node, uint to_index) {
127 _nodes.map(to_index, node);
128 }
130 // Insert a node 'node' at index 'at_index', moving all nodes that are on a higher index one step, if 'at_index' is out of bounds we crash
131 void insert_node(Node* node, uint at_index) {
132 _nodes.insert(at_index, node);
133 }
135 // Remove a node at index 'at_index'
136 void remove_node(uint at_index) {
137 _nodes.remove(at_index);
138 }
140 // Push a node 'node' onto the node list
141 void push_node(Node* node) {
142 _nodes.push(node);
143 }
145 // Pop the last node off the node list
146 Node* pop_node() {
147 return _nodes.pop();
148 }
150 // Basic blocks have a Node which defines Control for all Nodes pinned in
151 // this block. This Node is a RegionNode. Exception-causing Nodes
152 // (division, subroutines) and Phi functions are always pinned. Later,
153 // every Node will get pinned to some block.
154 Node *head() const { return get_node(0); }
156 // CAUTION: num_preds() is ONE based, so that predecessor numbers match
157 // input edges to Regions and Phis.
158 uint num_preds() const { return head()->req(); }
159 Node *pred(uint i) const { return head()->in(i); }
161 // Array of successor blocks, same size as projs array
162 Block_Array _succs;
164 // Basic blocks have some number of Nodes which split control to all
165 // following blocks. These Nodes are always Projections. The field in
166 // the Projection and the block-ending Node determine which Block follows.
167 uint _num_succs;
169 // Basic blocks also carry all sorts of good old fashioned DFS information
170 // used to find loops, loop nesting depth, dominators, etc.
171 uint _pre_order; // Pre-order DFS number
173 // Dominator tree
174 uint _dom_depth; // Depth in dominator tree for fast LCA
175 Block* _idom; // Immediate dominator block
177 CFGLoop *_loop; // Loop to which this block belongs
178 uint _rpo; // Number in reverse post order walk
180 virtual bool is_block() { return true; }
181 float succ_prob(uint i); // return probability of i'th successor
182 int num_fall_throughs(); // How many fall-through candidate this block has
183 void update_uncommon_branch(Block* un); // Lower branch prob to uncommon code
184 bool succ_fall_through(uint i); // Is successor "i" is a fall-through candidate
185 Block* lone_fall_through(); // Return lone fall-through Block or null
187 Block* dom_lca(Block* that); // Compute LCA in dominator tree.
189 bool dominates(Block* that) {
190 int dom_diff = this->_dom_depth - that->_dom_depth;
191 if (dom_diff > 0) return false;
192 for (; dom_diff < 0; dom_diff++) that = that->_idom;
193 return this == that;
194 }
196 // Report the alignment required by this block. Must be a power of 2.
197 // The previous block will insert nops to get this alignment.
198 uint code_alignment();
199 uint compute_loop_alignment();
201 // BLOCK_FREQUENCY is a sentinel to mark uses of constant block frequencies.
202 // It is currently also used to scale such frequencies relative to
203 // FreqCountInvocations relative to the old value of 1500.
204 #define BLOCK_FREQUENCY(f) ((f * (float) 1500) / FreqCountInvocations)
206 // Register Pressure (estimate) for Splitting heuristic
207 uint _reg_pressure;
208 uint _ihrp_index;
209 uint _freg_pressure;
210 uint _fhrp_index;
212 // Mark and visited bits for an LCA calculation in insert_anti_dependences.
213 // Since they hold unique node indexes, they do not need reinitialization.
214 node_idx_t _raise_LCA_mark;
215 void set_raise_LCA_mark(node_idx_t x) { _raise_LCA_mark = x; }
216 node_idx_t raise_LCA_mark() const { return _raise_LCA_mark; }
217 node_idx_t _raise_LCA_visited;
218 void set_raise_LCA_visited(node_idx_t x) { _raise_LCA_visited = x; }
219 node_idx_t raise_LCA_visited() const { return _raise_LCA_visited; }
221 // Estimated size in bytes of first instructions in a loop.
222 uint _first_inst_size;
223 uint first_inst_size() const { return _first_inst_size; }
224 void set_first_inst_size(uint s) { _first_inst_size = s; }
226 // Compute the size of first instructions in this block.
227 uint compute_first_inst_size(uint& sum_size, uint inst_cnt, PhaseRegAlloc* ra);
229 // Compute alignment padding if the block needs it.
230 // Align a loop if loop's padding is less or equal to padding limit
231 // or the size of first instructions in the loop > padding.
232 uint alignment_padding(int current_offset) {
233 int block_alignment = code_alignment();
234 int max_pad = block_alignment-relocInfo::addr_unit();
235 if( max_pad > 0 ) {
236 assert(is_power_of_2(max_pad+relocInfo::addr_unit()), "");
237 int current_alignment = current_offset & max_pad;
238 if( current_alignment != 0 ) {
239 uint padding = (block_alignment-current_alignment) & max_pad;
240 if( has_loop_alignment() &&
241 padding > (uint)MaxLoopPad &&
242 first_inst_size() <= padding ) {
243 return 0;
244 }
245 return padding;
246 }
247 }
248 return 0;
249 }
251 // Connector blocks. Connector blocks are basic blocks devoid of
252 // instructions, but may have relevant non-instruction Nodes, such as
253 // Phis or MergeMems. Such blocks are discovered and marked during the
254 // RemoveEmpty phase, and elided during Output.
255 bool _connector;
256 void set_connector() { _connector = true; }
257 bool is_connector() const { return _connector; };
259 // Loop_alignment will be set for blocks which are at the top of loops.
260 // The block layout pass may rotate loops such that the loop head may not
261 // be the sequentially first block of the loop encountered in the linear
262 // list of blocks. If the layout pass is not run, loop alignment is set
263 // for each block which is the head of a loop.
264 uint _loop_alignment;
265 void set_loop_alignment(Block *loop_top) {
266 uint new_alignment = loop_top->compute_loop_alignment();
267 if (new_alignment > _loop_alignment) {
268 _loop_alignment = new_alignment;
269 }
270 }
271 uint loop_alignment() const { return _loop_alignment; }
272 bool has_loop_alignment() const { return loop_alignment() > 0; }
274 // Create a new Block with given head Node.
275 // Creates the (empty) predecessor arrays.
276 Block( Arena *a, Node *headnode )
277 : CFGElement(),
278 _nodes(a),
279 _succs(a),
280 _num_succs(0),
281 _pre_order(0),
282 _idom(0),
283 _loop(NULL),
284 _reg_pressure(0),
285 _ihrp_index(1),
286 _freg_pressure(0),
287 _fhrp_index(1),
288 _raise_LCA_mark(0),
289 _raise_LCA_visited(0),
290 _first_inst_size(999999),
291 _connector(false),
292 _loop_alignment(0) {
293 _nodes.push(headnode);
294 }
296 // Index of 'end' Node
297 uint end_idx() const {
298 // %%%%% add a proj after every goto
299 // so (last->is_block_proj() != last) always, then simplify this code
300 // This will not give correct end_idx for block 0 when it only contains root.
301 int last_idx = _nodes.size() - 1;
302 Node *last = _nodes[last_idx];
303 assert(last->is_block_proj() == last || last->is_block_proj() == _nodes[last_idx - _num_succs], "");
304 return (last->is_block_proj() == last) ? last_idx : (last_idx - _num_succs);
305 }
307 // Basic blocks have a Node which ends them. This Node determines which
308 // basic block follows this one in the program flow. This Node is either an
309 // IfNode, a GotoNode, a JmpNode, or a ReturnNode.
310 Node *end() const { return _nodes[end_idx()]; }
312 // Add an instruction to an existing block. It must go after the head
313 // instruction and before the end instruction.
314 void add_inst( Node *n ) { insert_node(n, end_idx()); }
315 // Find node in block. Fails if node not in block.
316 uint find_node( const Node *n ) const;
317 // Find and remove n from block list
318 void find_remove( const Node *n );
319 // Check wether the node is in the block.
320 bool contains (const Node *n) const;
322 // Return the empty status of a block
323 enum { not_empty, empty_with_goto, completely_empty };
324 int is_Empty() const;
326 // Forward through connectors
327 Block* non_connector() {
328 Block* s = this;
329 while (s->is_connector()) {
330 s = s->_succs[0];
331 }
332 return s;
333 }
335 // Return true if b is a successor of this block
336 bool has_successor(Block* b) const {
337 for (uint i = 0; i < _num_succs; i++ ) {
338 if (non_connector_successor(i) == b) {
339 return true;
340 }
341 }
342 return false;
343 }
345 // Successor block, after forwarding through connectors
346 Block* non_connector_successor(int i) const {
347 return _succs[i]->non_connector();
348 }
350 // Examine block's code shape to predict if it is not commonly executed.
351 bool has_uncommon_code() const;
353 #ifndef PRODUCT
354 // Debugging print of basic block
355 void dump_bidx(const Block* orig, outputStream* st = tty) const;
356 void dump_pred(const PhaseCFG* cfg, Block* orig, outputStream* st = tty) const;
357 void dump_head(const PhaseCFG* cfg, outputStream* st = tty) const;
358 void dump() const;
359 void dump(const PhaseCFG* cfg) const;
360 #endif
361 };
364 //------------------------------PhaseCFG---------------------------------------
365 // Build an array of Basic Block pointers, one per Node.
366 class PhaseCFG : public Phase {
367 friend class VMStructs;
368 private:
370 // Root of whole program
371 RootNode* _root;
373 // The block containing the root node
374 Block* _root_block;
376 // List of basic blocks that are created during CFG creation
377 Block_List _blocks;
379 // Count of basic blocks
380 uint _number_of_blocks;
382 // Arena for the blocks to be stored in
383 Arena* _block_arena;
385 // The matcher for this compilation
386 Matcher& _matcher;
388 // Map nodes to owning basic block
389 Block_Array _node_to_block_mapping;
391 // Loop from the root
392 CFGLoop* _root_loop;
394 // Outmost loop frequency
395 float _outer_loop_frequency;
397 // Per node latency estimation, valid only during GCM
398 GrowableArray<uint>* _node_latency;
400 // Build a proper looking cfg. Return count of basic blocks
401 uint build_cfg();
403 // Build the dominator tree so that we know where we can move instructions
404 void build_dominator_tree();
406 // Estimate block frequencies based on IfNode probabilities, so that we know where we want to move instructions
407 void estimate_block_frequency();
409 // Global Code Motion. See Click's PLDI95 paper. Place Nodes in specific
410 // basic blocks; i.e. _node_to_block_mapping now maps _idx for all Nodes to some Block.
411 // Move nodes to ensure correctness from GVN and also try to move nodes out of loops.
412 void global_code_motion();
414 // Schedule Nodes early in their basic blocks.
415 bool schedule_early(VectorSet &visited, Node_List &roots);
417 // For each node, find the latest block it can be scheduled into
418 // and then select the cheapest block between the latest and earliest
419 // block to place the node.
420 void schedule_late(VectorSet &visited, Node_List &stack);
422 // Compute the (backwards) latency of a node from a single use
423 int latency_from_use(Node *n, const Node *def, Node *use);
425 // Compute the (backwards) latency of a node from the uses of this instruction
426 void partial_latency_of_defs(Node *n);
428 // Compute the instruction global latency with a backwards walk
429 void compute_latencies_backwards(VectorSet &visited, Node_List &stack);
431 // Pick a block between early and late that is a cheaper alternative
432 // to late. Helper for schedule_late.
433 Block* hoist_to_cheaper_block(Block* LCA, Block* early, Node* self);
435 bool schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call);
436 void set_next_call(Block* block, Node* n, VectorSet& next_call);
437 void needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call);
439 // Perform basic-block local scheduling
440 Node* select(Block* block, Node_List& worklist, GrowableArray<int>& ready_cnt, VectorSet& next_call, uint sched_slot);
442 // Schedule a call next in the block
443 uint sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call);
445 // Cleanup if any code lands between a Call and his Catch
446 void call_catch_cleanup(Block* block);
448 Node* catch_cleanup_find_cloned_def(Block* use_blk, Node* def, Block* def_blk, int n_clone_idx);
449 void catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx);
451 // Detect implicit-null-check opportunities. Basically, find NULL checks
452 // with suitable memory ops nearby. Use the memory op to do the NULL check.
453 // I can generate a memory op if there is not one nearby.
454 void implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons);
456 // Perform a Depth First Search (DFS).
457 // Setup 'vertex' as DFS to vertex mapping.
458 // Setup 'semi' as vertex to DFS mapping.
459 // Set 'parent' to DFS parent.
460 uint do_DFS(Tarjan* tarjan, uint rpo_counter);
462 // Helper function to insert a node into a block
463 void schedule_node_into_block( Node *n, Block *b );
465 void replace_block_proj_ctrl( Node *n );
467 // Set the basic block for pinned Nodes
468 void schedule_pinned_nodes( VectorSet &visited );
470 // I'll need a few machine-specific GotoNodes. Clone from this one.
471 // Used when building the CFG and creating end nodes for blocks.
472 MachNode* _goto;
474 Block* insert_anti_dependences(Block* LCA, Node* load, bool verify = false);
475 void verify_anti_dependences(Block* LCA, Node* load) const {
476 assert(LCA == get_block_for_node(load), "should already be scheduled");
477 const_cast<PhaseCFG*>(this)->insert_anti_dependences(LCA, load, true);
478 }
480 bool move_to_next(Block* bx, uint b_index);
481 void move_to_end(Block* bx, uint b_index);
483 void insert_goto_at(uint block_no, uint succ_no);
485 // Check for NeverBranch at block end. This needs to become a GOTO to the
486 // true target. NeverBranch are treated as a conditional branch that always
487 // goes the same direction for most of the optimizer and are used to give a
488 // fake exit path to infinite loops. At this late stage they need to turn
489 // into Goto's so that when you enter the infinite loop you indeed hang.
490 void convert_NeverBranch_to_Goto(Block *b);
492 CFGLoop* create_loop_tree();
494 #ifndef PRODUCT
495 bool _trace_opto_pipelining; // tracing flag
496 #endif
498 public:
499 PhaseCFG(Arena* arena, RootNode* root, Matcher& matcher);
501 void set_latency_for_node(Node* node, int latency) {
502 _node_latency->at_put_grow(node->_idx, latency);
503 }
505 uint get_latency_for_node(Node* node) {
506 return _node_latency->at_grow(node->_idx);
507 }
509 // Get the outer most frequency
510 float get_outer_loop_frequency() const {
511 return _outer_loop_frequency;
512 }
514 // Get the root node of the CFG
515 RootNode* get_root_node() const {
516 return _root;
517 }
519 // Get the block of the root node
520 Block* get_root_block() const {
521 return _root_block;
522 }
524 // Add a block at a position and moves the later ones one step
525 void add_block_at(uint pos, Block* block) {
526 _blocks.insert(pos, block);
527 _number_of_blocks++;
528 }
530 // Adds a block to the top of the block list
531 void add_block(Block* block) {
532 _blocks.push(block);
533 _number_of_blocks++;
534 }
536 // Clear the list of blocks
537 void clear_blocks() {
538 _blocks.reset();
539 _number_of_blocks = 0;
540 }
542 // Get the block at position pos in _blocks
543 Block* get_block(uint pos) const {
544 return _blocks[pos];
545 }
547 // Number of blocks
548 uint number_of_blocks() const {
549 return _number_of_blocks;
550 }
552 // set which block this node should reside in
553 void map_node_to_block(const Node* node, Block* block) {
554 _node_to_block_mapping.map(node->_idx, block);
555 }
557 // removes the mapping from a node to a block
558 void unmap_node_from_block(const Node* node) {
559 _node_to_block_mapping.map(node->_idx, NULL);
560 }
562 // get the block in which this node resides
563 Block* get_block_for_node(const Node* node) const {
564 return _node_to_block_mapping[node->_idx];
565 }
567 // does this node reside in a block; return true
568 bool has_block(const Node* node) const {
569 return (_node_to_block_mapping.lookup(node->_idx) != NULL);
570 }
572 // Use frequency calculations and code shape to predict if the block
573 // is uncommon.
574 bool is_uncommon(const Block* block);
576 #ifdef ASSERT
577 Unique_Node_List _raw_oops;
578 #endif
580 // Do global code motion by first building dominator tree and estimate block frequency
581 // Returns true on success
582 bool do_global_code_motion();
584 // Compute the (backwards) latency of a node from the uses
585 void latency_from_uses(Node *n);
587 // Set loop alignment
588 void set_loop_alignment();
590 // Remove empty basic blocks
591 void remove_empty_blocks();
592 Block *fixup_trap_based_check(Node *branch, Block *block, int block_pos, Block *bnext);
593 void fixup_flow();
595 // Insert a node into a block at index and map the node to the block
596 void insert(Block *b, uint idx, Node *n) {
597 b->insert_node(n , idx);
598 map_node_to_block(n, b);
599 }
601 // Check all nodes and postalloc_expand them if necessary.
602 void postalloc_expand(PhaseRegAlloc* _ra);
604 #ifndef PRODUCT
605 bool trace_opto_pipelining() const { return _trace_opto_pipelining; }
607 // Debugging print of CFG
608 void dump( ) const; // CFG only
609 void _dump_cfg( const Node *end, VectorSet &visited ) const;
610 void verify() const;
611 void dump_headers();
612 #else
613 bool trace_opto_pipelining() const { return false; }
614 #endif
615 };
618 //------------------------------UnionFind--------------------------------------
619 // Map Block indices to a block-index for a cfg-cover.
620 // Array lookup in the optimized case.
621 class UnionFind : public ResourceObj {
622 uint _cnt, _max;
623 uint* _indices;
624 ReallocMark _nesting; // assertion check for reallocations
625 public:
626 UnionFind( uint max );
627 void reset( uint max ); // Reset to identity map for [0..max]
629 uint lookup( uint nidx ) const {
630 return _indices[nidx];
631 }
632 uint operator[] (uint nidx) const { return lookup(nidx); }
634 void map( uint from_idx, uint to_idx ) {
635 assert( from_idx < _cnt, "oob" );
636 _indices[from_idx] = to_idx;
637 }
638 void extend( uint from_idx, uint to_idx );
640 uint Size() const { return _cnt; }
642 uint Find( uint idx ) {
643 assert( idx < 65536, "Must fit into uint");
644 uint uf_idx = lookup(idx);
645 return (uf_idx == idx) ? uf_idx : Find_compress(idx);
646 }
647 uint Find_compress( uint idx );
648 uint Find_const( uint idx ) const;
649 void Union( uint idx1, uint idx2 );
651 };
653 //----------------------------BlockProbPair---------------------------
654 // Ordered pair of Node*.
655 class BlockProbPair VALUE_OBJ_CLASS_SPEC {
656 protected:
657 Block* _target; // block target
658 float _prob; // probability of edge to block
659 public:
660 BlockProbPair() : _target(NULL), _prob(0.0) {}
661 BlockProbPair(Block* b, float p) : _target(b), _prob(p) {}
663 Block* get_target() const { return _target; }
664 float get_prob() const { return _prob; }
665 };
667 //------------------------------CFGLoop-------------------------------------------
668 class CFGLoop : public CFGElement {
669 friend class VMStructs;
670 int _id;
671 int _depth;
672 CFGLoop *_parent; // root of loop tree is the method level "pseudo" loop, it's parent is null
673 CFGLoop *_sibling; // null terminated list
674 CFGLoop *_child; // first child, use child's sibling to visit all immediately nested loops
675 GrowableArray<CFGElement*> _members; // list of members of loop
676 GrowableArray<BlockProbPair> _exits; // list of successor blocks and their probabilities
677 float _exit_prob; // probability any loop exit is taken on a single loop iteration
678 void update_succ_freq(Block* b, float freq);
680 public:
681 CFGLoop(int id) :
682 CFGElement(),
683 _id(id),
684 _depth(0),
685 _parent(NULL),
686 _sibling(NULL),
687 _child(NULL),
688 _exit_prob(1.0f) {}
689 CFGLoop* parent() { return _parent; }
690 void push_pred(Block* blk, int i, Block_List& worklist, PhaseCFG* cfg);
691 void add_member(CFGElement *s) { _members.push(s); }
692 void add_nested_loop(CFGLoop* cl);
693 Block* head() {
694 assert(_members.at(0)->is_block(), "head must be a block");
695 Block* hd = _members.at(0)->as_Block();
696 assert(hd->_loop == this, "just checking");
697 assert(hd->head()->is_Loop(), "must begin with loop head node");
698 return hd;
699 }
700 Block* backedge_block(); // Return the block on the backedge of the loop (else NULL)
701 void compute_loop_depth(int depth);
702 void compute_freq(); // compute frequency with loop assuming head freq 1.0f
703 void scale_freq(); // scale frequency by loop trip count (including outer loops)
704 float outer_loop_freq() const; // frequency of outer loop
705 bool in_loop_nest(Block* b);
706 float trip_count() const { return 1.0f / _exit_prob; }
707 virtual bool is_loop() { return true; }
708 int id() { return _id; }
710 #ifndef PRODUCT
711 void dump( ) const;
712 void dump_tree() const;
713 #endif
714 };
717 //----------------------------------CFGEdge------------------------------------
718 // A edge between two basic blocks that will be embodied by a branch or a
719 // fall-through.
720 class CFGEdge : public ResourceObj {
721 friend class VMStructs;
722 private:
723 Block * _from; // Source basic block
724 Block * _to; // Destination basic block
725 float _freq; // Execution frequency (estimate)
726 int _state;
727 bool _infrequent;
728 int _from_pct;
729 int _to_pct;
731 // Private accessors
732 int from_pct() const { return _from_pct; }
733 int to_pct() const { return _to_pct; }
734 int from_infrequent() const { return from_pct() < BlockLayoutMinDiamondPercentage; }
735 int to_infrequent() const { return to_pct() < BlockLayoutMinDiamondPercentage; }
737 public:
738 enum {
739 open, // initial edge state; unprocessed
740 connected, // edge used to connect two traces together
741 interior // edge is interior to trace (could be backedge)
742 };
744 CFGEdge(Block *from, Block *to, float freq, int from_pct, int to_pct) :
745 _from(from), _to(to), _freq(freq),
746 _from_pct(from_pct), _to_pct(to_pct), _state(open) {
747 _infrequent = from_infrequent() || to_infrequent();
748 }
750 float freq() const { return _freq; }
751 Block* from() const { return _from; }
752 Block* to () const { return _to; }
753 int infrequent() const { return _infrequent; }
754 int state() const { return _state; }
756 void set_state(int state) { _state = state; }
758 #ifndef PRODUCT
759 void dump( ) const;
760 #endif
761 };
764 //-----------------------------------Trace-------------------------------------
765 // An ordered list of basic blocks.
766 class Trace : public ResourceObj {
767 private:
768 uint _id; // Unique Trace id (derived from initial block)
769 Block ** _next_list; // Array mapping index to next block
770 Block ** _prev_list; // Array mapping index to previous block
771 Block * _first; // First block in the trace
772 Block * _last; // Last block in the trace
774 // Return the block that follows "b" in the trace.
775 Block * next(Block *b) const { return _next_list[b->_pre_order]; }
776 void set_next(Block *b, Block *n) const { _next_list[b->_pre_order] = n; }
778 // Return the block that precedes "b" in the trace.
779 Block * prev(Block *b) const { return _prev_list[b->_pre_order]; }
780 void set_prev(Block *b, Block *p) const { _prev_list[b->_pre_order] = p; }
782 // We've discovered a loop in this trace. Reset last to be "b", and first as
783 // the block following "b
784 void break_loop_after(Block *b) {
785 _last = b;
786 _first = next(b);
787 set_prev(_first, NULL);
788 set_next(_last, NULL);
789 }
791 public:
793 Trace(Block *b, Block **next_list, Block **prev_list) :
794 _first(b),
795 _last(b),
796 _next_list(next_list),
797 _prev_list(prev_list),
798 _id(b->_pre_order) {
799 set_next(b, NULL);
800 set_prev(b, NULL);
801 };
803 // Return the id number
804 uint id() const { return _id; }
805 void set_id(uint id) { _id = id; }
807 // Return the first block in the trace
808 Block * first_block() const { return _first; }
810 // Return the last block in the trace
811 Block * last_block() const { return _last; }
813 // Insert a trace in the middle of this one after b
814 void insert_after(Block *b, Trace *tr) {
815 set_next(tr->last_block(), next(b));
816 if (next(b) != NULL) {
817 set_prev(next(b), tr->last_block());
818 }
820 set_next(b, tr->first_block());
821 set_prev(tr->first_block(), b);
823 if (b == _last) {
824 _last = tr->last_block();
825 }
826 }
828 void insert_before(Block *b, Trace *tr) {
829 Block *p = prev(b);
830 assert(p != NULL, "use append instead");
831 insert_after(p, tr);
832 }
834 // Append another trace to this one.
835 void append(Trace *tr) {
836 insert_after(_last, tr);
837 }
839 // Append a block at the end of this trace
840 void append(Block *b) {
841 set_next(_last, b);
842 set_prev(b, _last);
843 _last = b;
844 }
846 // Adjust the the blocks in this trace
847 void fixup_blocks(PhaseCFG &cfg);
848 bool backedge(CFGEdge *e);
850 #ifndef PRODUCT
851 void dump( ) const;
852 #endif
853 };
855 //------------------------------PhaseBlockLayout-------------------------------
856 // Rearrange blocks into some canonical order, based on edges and their frequencies
857 class PhaseBlockLayout : public Phase {
858 friend class VMStructs;
859 PhaseCFG &_cfg; // Control flow graph
861 GrowableArray<CFGEdge *> *edges;
862 Trace **traces;
863 Block **next;
864 Block **prev;
865 UnionFind *uf;
867 // Given a block, find its encompassing Trace
868 Trace * trace(Block *b) {
869 return traces[uf->Find_compress(b->_pre_order)];
870 }
871 public:
872 PhaseBlockLayout(PhaseCFG &cfg);
874 void find_edges();
875 void grow_traces();
876 void merge_traces(bool loose_connections);
877 void reorder_traces(int count);
878 void union_traces(Trace* from, Trace* to);
879 };
881 #endif // SHARE_VM_OPTO_BLOCK_HPP