2007-05-22 H.J. Lu <hongjiu.lu@intel.com>
[official-gcc.git] / gcc / sched-rgn.c
blob47842c57a40ce92a5ef4c0232589db5ca7474f41
1 /* Instruction scheduling pass.
2 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4 Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
5 and currently maintained by, Jim Wilson (wilson@cygnus.com)
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING. If not, write to the Free
21 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
22 02110-1301, USA. */
24 /* This pass implements list scheduling within basic blocks. It is
25 run twice: (1) after flow analysis, but before register allocation,
26 and (2) after register allocation.
28 The first run performs interblock scheduling, moving insns between
29 different blocks in the same "region", and the second runs only
30 basic block scheduling.
32 Interblock motions performed are useful motions and speculative
33 motions, including speculative loads. Motions requiring code
34 duplication are not supported. The identification of motion type
35 and the check for validity of speculative motions requires
36 construction and analysis of the function's control flow graph.
38 The main entry point for this pass is schedule_insns(), called for
39 each function. The work of the scheduler is organized in three
40 levels: (1) function level: insns are subject to splitting,
41 control-flow-graph is constructed, regions are computed (after
42 reload, each region is of one block), (2) region level: control
43 flow graph attributes required for interblock scheduling are
44 computed (dominators, reachability, etc.), data dependences and
45 priorities are computed, and (3) block level: insns in the block
46 are actually scheduled. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "tm.h"
52 #include "toplev.h"
53 #include "rtl.h"
54 #include "tm_p.h"
55 #include "hard-reg-set.h"
56 #include "regs.h"
57 #include "function.h"
58 #include "flags.h"
59 #include "insn-config.h"
60 #include "insn-attr.h"
61 #include "except.h"
62 #include "toplev.h"
63 #include "recog.h"
64 #include "cfglayout.h"
65 #include "params.h"
66 #include "sched-int.h"
67 #include "target.h"
68 #include "timevar.h"
69 #include "tree-pass.h"
71 /* Define when we want to do count REG_DEAD notes before and after scheduling
72 for sanity checking. We can't do that when conditional execution is used,
73 as REG_DEAD exist only for unconditional deaths. */
75 #if !defined (HAVE_conditional_execution) && defined (ENABLE_CHECKING)
76 #define CHECK_DEAD_NOTES 1
77 #else
78 #define CHECK_DEAD_NOTES 0
79 #endif
82 #ifdef INSN_SCHEDULING
83 /* Some accessor macros for h_i_d members only used within this file. */
84 #define INSN_REF_COUNT(INSN) (h_i_d[INSN_UID (INSN)].ref_count)
85 #define FED_BY_SPEC_LOAD(insn) (h_i_d[INSN_UID (insn)].fed_by_spec_load)
86 #define IS_LOAD_INSN(insn) (h_i_d[INSN_UID (insn)].is_load_insn)
88 /* nr_inter/spec counts interblock/speculative motion for the function. */
89 static int nr_inter, nr_spec;
91 static int is_cfg_nonregular (void);
92 static bool sched_is_disabled_for_current_region_p (void);
94 /* A region is the main entity for interblock scheduling: insns
95 are allowed to move between blocks in the same region, along
96 control flow graph edges, in the 'up' direction. */
97 typedef struct
99 /* Number of extended basic blocks in region. */
100 int rgn_nr_blocks;
101 /* cblocks in the region (actually index in rgn_bb_table). */
102 int rgn_blocks;
103 /* Dependencies for this region are already computed. Basically, indicates,
104 that this is a recovery block. */
105 unsigned int dont_calc_deps : 1;
106 /* This region has at least one non-trivial ebb. */
107 unsigned int has_real_ebb : 1;
109 region;
111 /* Number of regions in the procedure. */
112 static int nr_regions;
114 /* Table of region descriptions. */
115 static region *rgn_table;
117 /* Array of lists of regions' blocks. */
118 static int *rgn_bb_table;
120 /* Topological order of blocks in the region (if b2 is reachable from
121 b1, block_to_bb[b2] > block_to_bb[b1]). Note: A basic block is
122 always referred to by either block or b, while its topological
123 order name (in the region) is referred to by bb. */
124 static int *block_to_bb;
126 /* The number of the region containing a block. */
127 static int *containing_rgn;
129 /* The minimum probability of reaching a source block so that it will be
130 considered for speculative scheduling. */
131 static int min_spec_prob;
133 #define RGN_NR_BLOCKS(rgn) (rgn_table[rgn].rgn_nr_blocks)
134 #define RGN_BLOCKS(rgn) (rgn_table[rgn].rgn_blocks)
135 #define RGN_DONT_CALC_DEPS(rgn) (rgn_table[rgn].dont_calc_deps)
136 #define RGN_HAS_REAL_EBB(rgn) (rgn_table[rgn].has_real_ebb)
137 #define BLOCK_TO_BB(block) (block_to_bb[block])
138 #define CONTAINING_RGN(block) (containing_rgn[block])
140 void debug_regions (void);
141 static void find_single_block_region (void);
142 static void find_rgns (void);
143 static void extend_rgns (int *, int *, sbitmap, int *);
144 static bool too_large (int, int *, int *);
146 extern void debug_live (int, int);
148 /* Blocks of the current region being scheduled. */
149 static int current_nr_blocks;
150 static int current_blocks;
152 static int rgn_n_insns;
154 /* The mapping from ebb to block. */
155 /* ebb_head [i] - is index in rgn_bb_table, while
156 EBB_HEAD (i) - is basic block index.
157 BASIC_BLOCK (EBB_HEAD (i)) - head of ebb. */
158 #define BB_TO_BLOCK(ebb) (rgn_bb_table[ebb_head[ebb]])
159 #define EBB_FIRST_BB(ebb) BASIC_BLOCK (BB_TO_BLOCK (ebb))
160 #define EBB_LAST_BB(ebb) BASIC_BLOCK (rgn_bb_table[ebb_head[ebb + 1] - 1])
162 /* Target info declarations.
164 The block currently being scheduled is referred to as the "target" block,
165 while other blocks in the region from which insns can be moved to the
166 target are called "source" blocks. The candidate structure holds info
167 about such sources: are they valid? Speculative? Etc. */
168 typedef struct
170 basic_block *first_member;
171 int nr_members;
173 bblst;
175 typedef struct
177 char is_valid;
178 char is_speculative;
179 int src_prob;
180 bblst split_bbs;
181 bblst update_bbs;
183 candidate;
185 static candidate *candidate_table;
187 /* A speculative motion requires checking live information on the path
188 from 'source' to 'target'. The split blocks are those to be checked.
189 After a speculative motion, live information should be modified in
190 the 'update' blocks.
192 Lists of split and update blocks for each candidate of the current
193 target are in array bblst_table. */
194 static basic_block *bblst_table;
195 static int bblst_size, bblst_last;
197 #define IS_VALID(src) ( candidate_table[src].is_valid )
198 #define IS_SPECULATIVE(src) ( candidate_table[src].is_speculative )
199 #define SRC_PROB(src) ( candidate_table[src].src_prob )
201 /* The bb being currently scheduled. */
202 static int target_bb;
204 /* List of edges. */
205 typedef struct
207 edge *first_member;
208 int nr_members;
210 edgelst;
212 static edge *edgelst_table;
213 static int edgelst_last;
215 static void extract_edgelst (sbitmap, edgelst *);
218 /* Target info functions. */
219 static void split_edges (int, int, edgelst *);
220 static void compute_trg_info (int);
221 void debug_candidate (int);
222 void debug_candidates (int);
224 /* Dominators array: dom[i] contains the sbitmap of dominators of
225 bb i in the region. */
226 static sbitmap *dom;
228 /* bb 0 is the only region entry. */
229 #define IS_RGN_ENTRY(bb) (!bb)
231 /* Is bb_src dominated by bb_trg. */
232 #define IS_DOMINATED(bb_src, bb_trg) \
233 ( TEST_BIT (dom[bb_src], bb_trg) )
235 /* Probability: Prob[i] is an int in [0, REG_BR_PROB_BASE] which is
236 the probability of bb i relative to the region entry. */
237 static int *prob;
239 /* Bit-set of edges, where bit i stands for edge i. */
240 typedef sbitmap edgeset;
242 /* Number of edges in the region. */
243 static int rgn_nr_edges;
245 /* Array of size rgn_nr_edges. */
246 static edge *rgn_edges;
248 /* Mapping from each edge in the graph to its number in the rgn. */
249 #define EDGE_TO_BIT(edge) ((int)(size_t)(edge)->aux)
250 #define SET_EDGE_TO_BIT(edge,nr) ((edge)->aux = (void *)(size_t)(nr))
252 /* The split edges of a source bb is different for each target
253 bb. In order to compute this efficiently, the 'potential-split edges'
254 are computed for each bb prior to scheduling a region. This is actually
255 the split edges of each bb relative to the region entry.
257 pot_split[bb] is the set of potential split edges of bb. */
258 static edgeset *pot_split;
260 /* For every bb, a set of its ancestor edges. */
261 static edgeset *ancestor_edges;
263 /* Array of EBBs sizes. Currently we can get a ebb only through
264 splitting of currently scheduling block, therefore, we don't need
265 ebb_head array for every region, its sufficient to hold it only
266 for current one. */
267 static int *ebb_head;
269 static void compute_dom_prob_ps (int);
271 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (BLOCK_NUM (INSN))))
272 #define IS_SPECULATIVE_INSN(INSN) (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
273 #define INSN_BB(INSN) (BLOCK_TO_BB (BLOCK_NUM (INSN)))
275 /* Speculative scheduling functions. */
276 static int check_live_1 (int, rtx);
277 static void update_live_1 (int, rtx);
278 static int check_live (rtx, int);
279 static void update_live (rtx, int);
280 static void set_spec_fed (rtx);
281 static int is_pfree (rtx, int, int);
282 static int find_conditional_protection (rtx, int);
283 static int is_conditionally_protected (rtx, int, int);
284 static int is_prisky (rtx, int, int);
285 static int is_exception_free (rtx, int, int);
287 static bool sets_likely_spilled (rtx);
288 static void sets_likely_spilled_1 (rtx, rtx, void *);
289 static void add_branch_dependences (rtx, rtx);
290 static void compute_block_backward_dependences (int);
292 static void init_regions (void);
293 static void schedule_region (int);
294 static rtx concat_INSN_LIST (rtx, rtx);
295 static void concat_insn_mem_list (rtx, rtx, rtx *, rtx *);
296 static void propagate_deps (int, struct deps *);
297 static void free_pending_lists (void);
299 /* Functions for construction of the control flow graph. */
301 /* Return 1 if control flow graph should not be constructed, 0 otherwise.
303 We decide not to build the control flow graph if there is possibly more
304 than one entry to the function, if computed branches exist, if we
305 have nonlocal gotos, or if we have an unreachable loop. */
307 static int
308 is_cfg_nonregular (void)
310 basic_block b;
311 rtx insn;
313 /* If we have a label that could be the target of a nonlocal goto, then
314 the cfg is not well structured. */
315 if (nonlocal_goto_handler_labels)
316 return 1;
318 /* If we have any forced labels, then the cfg is not well structured. */
319 if (forced_labels)
320 return 1;
322 /* If we have exception handlers, then we consider the cfg not well
323 structured. ?!? We should be able to handle this now that flow.c
324 computes an accurate cfg for EH. */
325 if (current_function_has_exception_handlers ())
326 return 1;
328 /* If we have non-jumping insns which refer to labels, then we consider
329 the cfg not well structured. */
330 FOR_EACH_BB (b)
331 FOR_BB_INSNS (b, insn)
333 /* Check for labels referred by non-jump insns. */
334 if (NONJUMP_INSN_P (insn) || CALL_P (insn))
336 rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
337 if (note
338 && ! (JUMP_P (NEXT_INSN (insn))
339 && find_reg_note (NEXT_INSN (insn), REG_LABEL,
340 XEXP (note, 0))))
341 return 1;
343 /* If this function has a computed jump, then we consider the cfg
344 not well structured. */
345 else if (JUMP_P (insn) && computed_jump_p (insn))
346 return 1;
349 /* Unreachable loops with more than one basic block are detected
350 during the DFS traversal in find_rgns.
352 Unreachable loops with a single block are detected here. This
353 test is redundant with the one in find_rgns, but it's much
354 cheaper to go ahead and catch the trivial case here. */
355 FOR_EACH_BB (b)
357 if (EDGE_COUNT (b->preds) == 0
358 || (single_pred_p (b)
359 && single_pred (b) == b))
360 return 1;
363 /* All the tests passed. Consider the cfg well structured. */
364 return 0;
367 /* Extract list of edges from a bitmap containing EDGE_TO_BIT bits. */
369 static void
370 extract_edgelst (sbitmap set, edgelst *el)
372 unsigned int i = 0;
373 sbitmap_iterator sbi;
375 /* edgelst table space is reused in each call to extract_edgelst. */
376 edgelst_last = 0;
378 el->first_member = &edgelst_table[edgelst_last];
379 el->nr_members = 0;
381 /* Iterate over each word in the bitset. */
382 EXECUTE_IF_SET_IN_SBITMAP (set, 0, i, sbi)
384 edgelst_table[edgelst_last++] = rgn_edges[i];
385 el->nr_members++;
389 /* Functions for the construction of regions. */
391 /* Print the regions, for debugging purposes. Callable from debugger. */
393 void
394 debug_regions (void)
396 int rgn, bb;
398 fprintf (sched_dump, "\n;; ------------ REGIONS ----------\n\n");
399 for (rgn = 0; rgn < nr_regions; rgn++)
401 fprintf (sched_dump, ";;\trgn %d nr_blocks %d:\n", rgn,
402 rgn_table[rgn].rgn_nr_blocks);
403 fprintf (sched_dump, ";;\tbb/block: ");
405 /* We don't have ebb_head initialized yet, so we can't use
406 BB_TO_BLOCK (). */
407 current_blocks = RGN_BLOCKS (rgn);
409 for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
410 fprintf (sched_dump, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
412 fprintf (sched_dump, "\n\n");
416 /* Build a single block region for each basic block in the function.
417 This allows for using the same code for interblock and basic block
418 scheduling. */
420 static void
421 find_single_block_region (void)
423 basic_block bb;
425 nr_regions = 0;
427 FOR_EACH_BB (bb)
429 rgn_bb_table[nr_regions] = bb->index;
430 RGN_NR_BLOCKS (nr_regions) = 1;
431 RGN_BLOCKS (nr_regions) = nr_regions;
432 RGN_DONT_CALC_DEPS (nr_regions) = 0;
433 RGN_HAS_REAL_EBB (nr_regions) = 0;
434 CONTAINING_RGN (bb->index) = nr_regions;
435 BLOCK_TO_BB (bb->index) = 0;
436 nr_regions++;
440 /* Update number of blocks and the estimate for number of insns
441 in the region. Return true if the region is "too large" for interblock
442 scheduling (compile time considerations). */
444 static bool
445 too_large (int block, int *num_bbs, int *num_insns)
447 (*num_bbs)++;
448 (*num_insns) += (INSN_LUID (BB_END (BASIC_BLOCK (block)))
449 - INSN_LUID (BB_HEAD (BASIC_BLOCK (block))));
451 return ((*num_bbs > PARAM_VALUE (PARAM_MAX_SCHED_REGION_BLOCKS))
452 || (*num_insns > PARAM_VALUE (PARAM_MAX_SCHED_REGION_INSNS)));
455 /* Update_loop_relations(blk, hdr): Check if the loop headed by max_hdr[blk]
456 is still an inner loop. Put in max_hdr[blk] the header of the most inner
457 loop containing blk. */
458 #define UPDATE_LOOP_RELATIONS(blk, hdr) \
460 if (max_hdr[blk] == -1) \
461 max_hdr[blk] = hdr; \
462 else if (dfs_nr[max_hdr[blk]] > dfs_nr[hdr]) \
463 RESET_BIT (inner, hdr); \
464 else if (dfs_nr[max_hdr[blk]] < dfs_nr[hdr]) \
466 RESET_BIT (inner,max_hdr[blk]); \
467 max_hdr[blk] = hdr; \
471 /* Find regions for interblock scheduling.
473 A region for scheduling can be:
475 * A loop-free procedure, or
477 * A reducible inner loop, or
479 * A basic block not contained in any other region.
481 ?!? In theory we could build other regions based on extended basic
482 blocks or reverse extended basic blocks. Is it worth the trouble?
484 Loop blocks that form a region are put into the region's block list
485 in topological order.
487 This procedure stores its results into the following global (ick) variables
489 * rgn_nr
490 * rgn_table
491 * rgn_bb_table
492 * block_to_bb
493 * containing region
495 We use dominator relationships to avoid making regions out of non-reducible
496 loops.
498 This procedure needs to be converted to work on pred/succ lists instead
499 of edge tables. That would simplify it somewhat. */
501 static void
502 find_rgns (void)
504 int *max_hdr, *dfs_nr, *degree;
505 char no_loops = 1;
506 int node, child, loop_head, i, head, tail;
507 int count = 0, sp, idx = 0;
508 edge_iterator current_edge;
509 edge_iterator *stack;
510 int num_bbs, num_insns, unreachable;
511 int too_large_failure;
512 basic_block bb;
514 /* Note if a block is a natural loop header. */
515 sbitmap header;
517 /* Note if a block is a natural inner loop header. */
518 sbitmap inner;
520 /* Note if a block is in the block queue. */
521 sbitmap in_queue;
523 /* Note if a block is in the block queue. */
524 sbitmap in_stack;
526 /* Perform a DFS traversal of the cfg. Identify loop headers, inner loops
527 and a mapping from block to its loop header (if the block is contained
528 in a loop, else -1).
530 Store results in HEADER, INNER, and MAX_HDR respectively, these will
531 be used as inputs to the second traversal.
533 STACK, SP and DFS_NR are only used during the first traversal. */
535 /* Allocate and initialize variables for the first traversal. */
536 max_hdr = XNEWVEC (int, last_basic_block);
537 dfs_nr = XCNEWVEC (int, last_basic_block);
538 stack = XNEWVEC (edge_iterator, n_edges);
540 inner = sbitmap_alloc (last_basic_block);
541 sbitmap_ones (inner);
543 header = sbitmap_alloc (last_basic_block);
544 sbitmap_zero (header);
546 in_queue = sbitmap_alloc (last_basic_block);
547 sbitmap_zero (in_queue);
549 in_stack = sbitmap_alloc (last_basic_block);
550 sbitmap_zero (in_stack);
552 for (i = 0; i < last_basic_block; i++)
553 max_hdr[i] = -1;
555 #define EDGE_PASSED(E) (ei_end_p ((E)) || ei_edge ((E))->aux)
556 #define SET_EDGE_PASSED(E) (ei_edge ((E))->aux = ei_edge ((E)))
558 /* DFS traversal to find inner loops in the cfg. */
560 current_edge = ei_start (single_succ (ENTRY_BLOCK_PTR)->succs);
561 sp = -1;
563 while (1)
565 if (EDGE_PASSED (current_edge))
567 /* We have reached a leaf node or a node that was already
568 processed. Pop edges off the stack until we find
569 an edge that has not yet been processed. */
570 while (sp >= 0 && EDGE_PASSED (current_edge))
572 /* Pop entry off the stack. */
573 current_edge = stack[sp--];
574 node = ei_edge (current_edge)->src->index;
575 gcc_assert (node != ENTRY_BLOCK);
576 child = ei_edge (current_edge)->dest->index;
577 gcc_assert (child != EXIT_BLOCK);
578 RESET_BIT (in_stack, child);
579 if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
580 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
581 ei_next (&current_edge);
584 /* See if have finished the DFS tree traversal. */
585 if (sp < 0 && EDGE_PASSED (current_edge))
586 break;
588 /* Nope, continue the traversal with the popped node. */
589 continue;
592 /* Process a node. */
593 node = ei_edge (current_edge)->src->index;
594 gcc_assert (node != ENTRY_BLOCK);
595 SET_BIT (in_stack, node);
596 dfs_nr[node] = ++count;
598 /* We don't traverse to the exit block. */
599 child = ei_edge (current_edge)->dest->index;
600 if (child == EXIT_BLOCK)
602 SET_EDGE_PASSED (current_edge);
603 ei_next (&current_edge);
604 continue;
607 /* If the successor is in the stack, then we've found a loop.
608 Mark the loop, if it is not a natural loop, then it will
609 be rejected during the second traversal. */
610 if (TEST_BIT (in_stack, child))
612 no_loops = 0;
613 SET_BIT (header, child);
614 UPDATE_LOOP_RELATIONS (node, child);
615 SET_EDGE_PASSED (current_edge);
616 ei_next (&current_edge);
617 continue;
620 /* If the child was already visited, then there is no need to visit
621 it again. Just update the loop relationships and restart
622 with a new edge. */
623 if (dfs_nr[child])
625 if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
626 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
627 SET_EDGE_PASSED (current_edge);
628 ei_next (&current_edge);
629 continue;
632 /* Push an entry on the stack and continue DFS traversal. */
633 stack[++sp] = current_edge;
634 SET_EDGE_PASSED (current_edge);
635 current_edge = ei_start (ei_edge (current_edge)->dest->succs);
638 /* Reset ->aux field used by EDGE_PASSED. */
639 FOR_ALL_BB (bb)
641 edge_iterator ei;
642 edge e;
643 FOR_EACH_EDGE (e, ei, bb->succs)
644 e->aux = NULL;
648 /* Another check for unreachable blocks. The earlier test in
649 is_cfg_nonregular only finds unreachable blocks that do not
650 form a loop.
652 The DFS traversal will mark every block that is reachable from
653 the entry node by placing a nonzero value in dfs_nr. Thus if
654 dfs_nr is zero for any block, then it must be unreachable. */
655 unreachable = 0;
656 FOR_EACH_BB (bb)
657 if (dfs_nr[bb->index] == 0)
659 unreachable = 1;
660 break;
663 /* Gross. To avoid wasting memory, the second pass uses the dfs_nr array
664 to hold degree counts. */
665 degree = dfs_nr;
667 FOR_EACH_BB (bb)
668 degree[bb->index] = EDGE_COUNT (bb->preds);
670 /* Do not perform region scheduling if there are any unreachable
671 blocks. */
672 if (!unreachable)
674 int *queue, *degree1 = NULL;
675 /* We use EXTENDED_RGN_HEADER as an addition to HEADER and put
676 there basic blocks, which are forced to be region heads.
677 This is done to try to assemble few smaller regions
678 from a too_large region. */
679 sbitmap extended_rgn_header = NULL;
680 bool extend_regions_p;
682 if (no_loops)
683 SET_BIT (header, 0);
685 /* Second traversal:find reducible inner loops and topologically sort
686 block of each region. */
688 queue = XNEWVEC (int, n_basic_blocks);
690 extend_regions_p = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS) > 0;
691 if (extend_regions_p)
693 degree1 = xmalloc (last_basic_block * sizeof (int));
694 extended_rgn_header = sbitmap_alloc (last_basic_block);
695 sbitmap_zero (extended_rgn_header);
698 /* Find blocks which are inner loop headers. We still have non-reducible
699 loops to consider at this point. */
700 FOR_EACH_BB (bb)
702 if (TEST_BIT (header, bb->index) && TEST_BIT (inner, bb->index))
704 edge e;
705 edge_iterator ei;
706 basic_block jbb;
708 /* Now check that the loop is reducible. We do this separate
709 from finding inner loops so that we do not find a reducible
710 loop which contains an inner non-reducible loop.
712 A simple way to find reducible/natural loops is to verify
713 that each block in the loop is dominated by the loop
714 header.
716 If there exists a block that is not dominated by the loop
717 header, then the block is reachable from outside the loop
718 and thus the loop is not a natural loop. */
719 FOR_EACH_BB (jbb)
721 /* First identify blocks in the loop, except for the loop
722 entry block. */
723 if (bb->index == max_hdr[jbb->index] && bb != jbb)
725 /* Now verify that the block is dominated by the loop
726 header. */
727 if (!dominated_by_p (CDI_DOMINATORS, jbb, bb))
728 break;
732 /* If we exited the loop early, then I is the header of
733 a non-reducible loop and we should quit processing it
734 now. */
735 if (jbb != EXIT_BLOCK_PTR)
736 continue;
738 /* I is a header of an inner loop, or block 0 in a subroutine
739 with no loops at all. */
740 head = tail = -1;
741 too_large_failure = 0;
742 loop_head = max_hdr[bb->index];
744 if (extend_regions_p)
745 /* We save degree in case when we meet a too_large region
746 and cancel it. We need a correct degree later when
747 calling extend_rgns. */
748 memcpy (degree1, degree, last_basic_block * sizeof (int));
750 /* Decrease degree of all I's successors for topological
751 ordering. */
752 FOR_EACH_EDGE (e, ei, bb->succs)
753 if (e->dest != EXIT_BLOCK_PTR)
754 --degree[e->dest->index];
756 /* Estimate # insns, and count # blocks in the region. */
757 num_bbs = 1;
758 num_insns = (INSN_LUID (BB_END (bb))
759 - INSN_LUID (BB_HEAD (bb)));
761 /* Find all loop latches (blocks with back edges to the loop
762 header) or all the leaf blocks in the cfg has no loops.
764 Place those blocks into the queue. */
765 if (no_loops)
767 FOR_EACH_BB (jbb)
768 /* Leaf nodes have only a single successor which must
769 be EXIT_BLOCK. */
770 if (single_succ_p (jbb)
771 && single_succ (jbb) == EXIT_BLOCK_PTR)
773 queue[++tail] = jbb->index;
774 SET_BIT (in_queue, jbb->index);
776 if (too_large (jbb->index, &num_bbs, &num_insns))
778 too_large_failure = 1;
779 break;
783 else
785 edge e;
787 FOR_EACH_EDGE (e, ei, bb->preds)
789 if (e->src == ENTRY_BLOCK_PTR)
790 continue;
792 node = e->src->index;
794 if (max_hdr[node] == loop_head && node != bb->index)
796 /* This is a loop latch. */
797 queue[++tail] = node;
798 SET_BIT (in_queue, node);
800 if (too_large (node, &num_bbs, &num_insns))
802 too_large_failure = 1;
803 break;
809 /* Now add all the blocks in the loop to the queue.
811 We know the loop is a natural loop; however the algorithm
812 above will not always mark certain blocks as being in the
813 loop. Consider:
814 node children
815 a b,c
817 c a,d
820 The algorithm in the DFS traversal may not mark B & D as part
821 of the loop (i.e. they will not have max_hdr set to A).
823 We know they can not be loop latches (else they would have
824 had max_hdr set since they'd have a backedge to a dominator
825 block). So we don't need them on the initial queue.
827 We know they are part of the loop because they are dominated
828 by the loop header and can be reached by a backwards walk of
829 the edges starting with nodes on the initial queue.
831 It is safe and desirable to include those nodes in the
832 loop/scheduling region. To do so we would need to decrease
833 the degree of a node if it is the target of a backedge
834 within the loop itself as the node is placed in the queue.
836 We do not do this because I'm not sure that the actual
837 scheduling code will properly handle this case. ?!? */
839 while (head < tail && !too_large_failure)
841 edge e;
842 child = queue[++head];
844 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (child)->preds)
846 node = e->src->index;
848 /* See discussion above about nodes not marked as in
849 this loop during the initial DFS traversal. */
850 if (e->src == ENTRY_BLOCK_PTR
851 || max_hdr[node] != loop_head)
853 tail = -1;
854 break;
856 else if (!TEST_BIT (in_queue, node) && node != bb->index)
858 queue[++tail] = node;
859 SET_BIT (in_queue, node);
861 if (too_large (node, &num_bbs, &num_insns))
863 too_large_failure = 1;
864 break;
870 if (tail >= 0 && !too_large_failure)
872 /* Place the loop header into list of region blocks. */
873 degree[bb->index] = -1;
874 rgn_bb_table[idx] = bb->index;
875 RGN_NR_BLOCKS (nr_regions) = num_bbs;
876 RGN_BLOCKS (nr_regions) = idx++;
877 RGN_DONT_CALC_DEPS (nr_regions) = 0;
878 RGN_HAS_REAL_EBB (nr_regions) = 0;
879 CONTAINING_RGN (bb->index) = nr_regions;
880 BLOCK_TO_BB (bb->index) = count = 0;
882 /* Remove blocks from queue[] when their in degree
883 becomes zero. Repeat until no blocks are left on the
884 list. This produces a topological list of blocks in
885 the region. */
886 while (tail >= 0)
888 if (head < 0)
889 head = tail;
890 child = queue[head];
891 if (degree[child] == 0)
893 edge e;
895 degree[child] = -1;
896 rgn_bb_table[idx++] = child;
897 BLOCK_TO_BB (child) = ++count;
898 CONTAINING_RGN (child) = nr_regions;
899 queue[head] = queue[tail--];
901 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (child)->succs)
902 if (e->dest != EXIT_BLOCK_PTR)
903 --degree[e->dest->index];
905 else
906 --head;
908 ++nr_regions;
910 else if (extend_regions_p)
912 /* Restore DEGREE. */
913 int *t = degree;
915 degree = degree1;
916 degree1 = t;
918 /* And force successors of BB to be region heads.
919 This may provide several smaller regions instead
920 of one too_large region. */
921 FOR_EACH_EDGE (e, ei, bb->succs)
922 if (e->dest != EXIT_BLOCK_PTR)
923 SET_BIT (extended_rgn_header, e->dest->index);
927 free (queue);
929 if (extend_regions_p)
931 free (degree1);
933 sbitmap_a_or_b (header, header, extended_rgn_header);
934 sbitmap_free (extended_rgn_header);
936 extend_rgns (degree, &idx, header, max_hdr);
940 /* Any block that did not end up in a region is placed into a region
941 by itself. */
942 FOR_EACH_BB (bb)
943 if (degree[bb->index] >= 0)
945 rgn_bb_table[idx] = bb->index;
946 RGN_NR_BLOCKS (nr_regions) = 1;
947 RGN_BLOCKS (nr_regions) = idx++;
948 RGN_DONT_CALC_DEPS (nr_regions) = 0;
949 RGN_HAS_REAL_EBB (nr_regions) = 0;
950 CONTAINING_RGN (bb->index) = nr_regions++;
951 BLOCK_TO_BB (bb->index) = 0;
954 free (max_hdr);
955 free (degree);
956 free (stack);
957 sbitmap_free (header);
958 sbitmap_free (inner);
959 sbitmap_free (in_queue);
960 sbitmap_free (in_stack);
963 static int gather_region_statistics (int **);
964 static void print_region_statistics (int *, int, int *, int);
966 /* Calculate the histogram that shows the number of regions having the
967 given number of basic blocks, and store it in the RSP array. Return
968 the size of this array. */
969 static int
970 gather_region_statistics (int **rsp)
972 int i, *a = 0, a_sz = 0;
974 /* a[i] is the number of regions that have (i + 1) basic blocks. */
975 for (i = 0; i < nr_regions; i++)
977 int nr_blocks = RGN_NR_BLOCKS (i);
979 gcc_assert (nr_blocks >= 1);
981 if (nr_blocks > a_sz)
983 a = xrealloc (a, nr_blocks * sizeof (*a));
985 a[a_sz++] = 0;
986 while (a_sz != nr_blocks);
989 a[nr_blocks - 1]++;
992 *rsp = a;
993 return a_sz;
996 /* Print regions statistics. S1 and S2 denote the data before and after
997 calling extend_rgns, respectively. */
998 static void
999 print_region_statistics (int *s1, int s1_sz, int *s2, int s2_sz)
1001 int i;
1003 /* We iterate until s2_sz because extend_rgns does not decrease
1004 the maximal region size. */
1005 for (i = 1; i < s2_sz; i++)
1007 int n1, n2;
1009 n2 = s2[i];
1011 if (n2 == 0)
1012 continue;
1014 if (i >= s1_sz)
1015 n1 = 0;
1016 else
1017 n1 = s1[i];
1019 fprintf (sched_dump, ";; Region extension statistics: size %d: " \
1020 "was %d + %d more\n", i + 1, n1, n2 - n1);
1024 /* Extend regions.
1025 DEGREE - Array of incoming edge count, considering only
1026 the edges, that don't have their sources in formed regions yet.
1027 IDXP - pointer to the next available index in rgn_bb_table.
1028 HEADER - set of all region heads.
1029 LOOP_HDR - mapping from block to the containing loop
1030 (two blocks can reside within one region if they have
1031 the same loop header). */
1032 static void
1033 extend_rgns (int *degree, int *idxp, sbitmap header, int *loop_hdr)
1035 int *order, i, rescan = 0, idx = *idxp, iter = 0, max_iter, *max_hdr;
1036 int nblocks = n_basic_blocks - NUM_FIXED_BLOCKS;
1038 max_iter = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS);
1040 max_hdr = xmalloc (last_basic_block * sizeof (*max_hdr));
1042 order = xmalloc (last_basic_block * sizeof (*order));
1043 post_order_compute (order, false);
1045 for (i = nblocks - 1; i >= 0; i--)
1047 int bbn = order[i];
1048 if (degree[bbn] >= 0)
1050 max_hdr[bbn] = bbn;
1051 rescan = 1;
1053 else
1054 /* This block already was processed in find_rgns. */
1055 max_hdr[bbn] = -1;
1058 /* The idea is to topologically walk through CFG in top-down order.
1059 During the traversal, if all the predecessors of a node are
1060 marked to be in the same region (they all have the same max_hdr),
1061 then current node is also marked to be a part of that region.
1062 Otherwise the node starts its own region.
1063 CFG should be traversed until no further changes are made. On each
1064 iteration the set of the region heads is extended (the set of those
1065 blocks that have max_hdr[bbi] == bbi). This set is upper bounded by the
1066 set of all basic blocks, thus the algorithm is guaranteed to terminate. */
1068 while (rescan && iter < max_iter)
1070 rescan = 0;
1072 for (i = nblocks - 1; i >= 0; i--)
1074 edge e;
1075 edge_iterator ei;
1076 int bbn = order[i];
1078 if (max_hdr[bbn] != -1 && !TEST_BIT (header, bbn))
1080 int hdr = -1;
1082 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (bbn)->preds)
1084 int predn = e->src->index;
1086 if (predn != ENTRY_BLOCK
1087 /* If pred wasn't processed in find_rgns. */
1088 && max_hdr[predn] != -1
1089 /* And pred and bb reside in the same loop.
1090 (Or out of any loop). */
1091 && loop_hdr[bbn] == loop_hdr[predn])
1093 if (hdr == -1)
1094 /* Then bb extends the containing region of pred. */
1095 hdr = max_hdr[predn];
1096 else if (hdr != max_hdr[predn])
1097 /* Too bad, there are at least two predecessors
1098 that reside in different regions. Thus, BB should
1099 begin its own region. */
1101 hdr = bbn;
1102 break;
1105 else
1106 /* BB starts its own region. */
1108 hdr = bbn;
1109 break;
1113 if (hdr == bbn)
1115 /* If BB start its own region,
1116 update set of headers with BB. */
1117 SET_BIT (header, bbn);
1118 rescan = 1;
1120 else
1121 gcc_assert (hdr != -1);
1123 max_hdr[bbn] = hdr;
1127 iter++;
1130 /* Statistics were gathered on the SPEC2000 package of tests with
1131 mainline weekly snapshot gcc-4.1-20051015 on ia64.
1133 Statistics for SPECint:
1134 1 iteration : 1751 cases (38.7%)
1135 2 iterations: 2770 cases (61.3%)
1136 Blocks wrapped in regions by find_rgns without extension: 18295 blocks
1137 Blocks wrapped in regions by 2 iterations in extend_rgns: 23821 blocks
1138 (We don't count single block regions here).
1140 Statistics for SPECfp:
1141 1 iteration : 621 cases (35.9%)
1142 2 iterations: 1110 cases (64.1%)
1143 Blocks wrapped in regions by find_rgns without extension: 6476 blocks
1144 Blocks wrapped in regions by 2 iterations in extend_rgns: 11155 blocks
1145 (We don't count single block regions here).
1147 By default we do at most 2 iterations.
1148 This can be overridden with max-sched-extend-regions-iters parameter:
1149 0 - disable region extension,
1150 N > 0 - do at most N iterations. */
1152 if (sched_verbose && iter != 0)
1153 fprintf (sched_dump, ";; Region extension iterations: %d%s\n", iter,
1154 rescan ? "... failed" : "");
1156 if (!rescan && iter != 0)
1158 int *s1 = NULL, s1_sz = 0;
1160 /* Save the old statistics for later printout. */
1161 if (sched_verbose >= 6)
1162 s1_sz = gather_region_statistics (&s1);
1164 /* We have succeeded. Now assemble the regions. */
1165 for (i = nblocks - 1; i >= 0; i--)
1167 int bbn = order[i];
1169 if (max_hdr[bbn] == bbn)
1170 /* BBN is a region head. */
1172 edge e;
1173 edge_iterator ei;
1174 int num_bbs = 0, j, num_insns = 0, large;
1176 large = too_large (bbn, &num_bbs, &num_insns);
1178 degree[bbn] = -1;
1179 rgn_bb_table[idx] = bbn;
1180 RGN_BLOCKS (nr_regions) = idx++;
1181 RGN_DONT_CALC_DEPS (nr_regions) = 0;
1182 RGN_HAS_REAL_EBB (nr_regions) = 0;
1183 CONTAINING_RGN (bbn) = nr_regions;
1184 BLOCK_TO_BB (bbn) = 0;
1186 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (bbn)->succs)
1187 if (e->dest != EXIT_BLOCK_PTR)
1188 degree[e->dest->index]--;
1190 if (!large)
1191 /* Here we check whether the region is too_large. */
1192 for (j = i - 1; j >= 0; j--)
1194 int succn = order[j];
1195 if (max_hdr[succn] == bbn)
1197 if ((large = too_large (succn, &num_bbs, &num_insns)))
1198 break;
1202 if (large)
1203 /* If the region is too_large, then wrap every block of
1204 the region into single block region.
1205 Here we wrap region head only. Other blocks are
1206 processed in the below cycle. */
1208 RGN_NR_BLOCKS (nr_regions) = 1;
1209 nr_regions++;
1212 num_bbs = 1;
1214 for (j = i - 1; j >= 0; j--)
1216 int succn = order[j];
1218 if (max_hdr[succn] == bbn)
1219 /* This cycle iterates over all basic blocks, that
1220 are supposed to be in the region with head BBN,
1221 and wraps them into that region (or in single
1222 block region). */
1224 gcc_assert (degree[succn] == 0);
1226 degree[succn] = -1;
1227 rgn_bb_table[idx] = succn;
1228 BLOCK_TO_BB (succn) = large ? 0 : num_bbs++;
1229 CONTAINING_RGN (succn) = nr_regions;
1231 if (large)
1232 /* Wrap SUCCN into single block region. */
1234 RGN_BLOCKS (nr_regions) = idx;
1235 RGN_NR_BLOCKS (nr_regions) = 1;
1236 RGN_DONT_CALC_DEPS (nr_regions) = 0;
1237 RGN_HAS_REAL_EBB (nr_regions) = 0;
1238 nr_regions++;
1241 idx++;
1243 FOR_EACH_EDGE (e, ei, BASIC_BLOCK (succn)->succs)
1244 if (e->dest != EXIT_BLOCK_PTR)
1245 degree[e->dest->index]--;
1249 if (!large)
1251 RGN_NR_BLOCKS (nr_regions) = num_bbs;
1252 nr_regions++;
1257 if (sched_verbose >= 6)
1259 int *s2, s2_sz;
1261 /* Get the new statistics and print the comparison with the
1262 one before calling this function. */
1263 s2_sz = gather_region_statistics (&s2);
1264 print_region_statistics (s1, s1_sz, s2, s2_sz);
1265 free (s1);
1266 free (s2);
1270 free (order);
1271 free (max_hdr);
1273 *idxp = idx;
1276 /* Functions for regions scheduling information. */
1278 /* Compute dominators, probability, and potential-split-edges of bb.
1279 Assume that these values were already computed for bb's predecessors. */
1281 static void
1282 compute_dom_prob_ps (int bb)
1284 edge_iterator in_ei;
1285 edge in_edge;
1287 /* We shouldn't have any real ebbs yet. */
1288 gcc_assert (ebb_head [bb] == bb + current_blocks);
1290 if (IS_RGN_ENTRY (bb))
1292 SET_BIT (dom[bb], 0);
1293 prob[bb] = REG_BR_PROB_BASE;
1294 return;
1297 prob[bb] = 0;
1299 /* Initialize dom[bb] to '111..1'. */
1300 sbitmap_ones (dom[bb]);
1302 FOR_EACH_EDGE (in_edge, in_ei, BASIC_BLOCK (BB_TO_BLOCK (bb))->preds)
1304 int pred_bb;
1305 edge out_edge;
1306 edge_iterator out_ei;
1308 if (in_edge->src == ENTRY_BLOCK_PTR)
1309 continue;
1311 pred_bb = BLOCK_TO_BB (in_edge->src->index);
1312 sbitmap_a_and_b (dom[bb], dom[bb], dom[pred_bb]);
1313 sbitmap_a_or_b (ancestor_edges[bb],
1314 ancestor_edges[bb], ancestor_edges[pred_bb]);
1316 SET_BIT (ancestor_edges[bb], EDGE_TO_BIT (in_edge));
1318 sbitmap_a_or_b (pot_split[bb], pot_split[bb], pot_split[pred_bb]);
1320 FOR_EACH_EDGE (out_edge, out_ei, in_edge->src->succs)
1321 SET_BIT (pot_split[bb], EDGE_TO_BIT (out_edge));
1323 prob[bb] += ((prob[pred_bb] * in_edge->probability) / REG_BR_PROB_BASE);
1326 SET_BIT (dom[bb], bb);
1327 sbitmap_difference (pot_split[bb], pot_split[bb], ancestor_edges[bb]);
1329 if (sched_verbose >= 2)
1330 fprintf (sched_dump, ";; bb_prob(%d, %d) = %3d\n", bb, BB_TO_BLOCK (bb),
1331 (100 * prob[bb]) / REG_BR_PROB_BASE);
1334 /* Functions for target info. */
1336 /* Compute in BL the list of split-edges of bb_src relatively to bb_trg.
1337 Note that bb_trg dominates bb_src. */
1339 static void
1340 split_edges (int bb_src, int bb_trg, edgelst *bl)
1342 sbitmap src = sbitmap_alloc (pot_split[bb_src]->n_bits);
1343 sbitmap_copy (src, pot_split[bb_src]);
1345 sbitmap_difference (src, src, pot_split[bb_trg]);
1346 extract_edgelst (src, bl);
1347 sbitmap_free (src);
1350 /* Find the valid candidate-source-blocks for the target block TRG, compute
1351 their probability, and check if they are speculative or not.
1352 For speculative sources, compute their update-blocks and split-blocks. */
1354 static void
1355 compute_trg_info (int trg)
1357 candidate *sp;
1358 edgelst el;
1359 int i, j, k, update_idx;
1360 basic_block block;
1361 sbitmap visited;
1362 edge_iterator ei;
1363 edge e;
1365 /* Define some of the fields for the target bb as well. */
1366 sp = candidate_table + trg;
1367 sp->is_valid = 1;
1368 sp->is_speculative = 0;
1369 sp->src_prob = REG_BR_PROB_BASE;
1371 visited = sbitmap_alloc (last_basic_block);
1373 for (i = trg + 1; i < current_nr_blocks; i++)
1375 sp = candidate_table + i;
1377 sp->is_valid = IS_DOMINATED (i, trg);
1378 if (sp->is_valid)
1380 int tf = prob[trg], cf = prob[i];
1382 /* In CFGs with low probability edges TF can possibly be zero. */
1383 sp->src_prob = (tf ? ((cf * REG_BR_PROB_BASE) / tf) : 0);
1384 sp->is_valid = (sp->src_prob >= min_spec_prob);
1387 if (sp->is_valid)
1389 split_edges (i, trg, &el);
1390 sp->is_speculative = (el.nr_members) ? 1 : 0;
1391 if (sp->is_speculative && !flag_schedule_speculative)
1392 sp->is_valid = 0;
1395 if (sp->is_valid)
1397 /* Compute split blocks and store them in bblst_table.
1398 The TO block of every split edge is a split block. */
1399 sp->split_bbs.first_member = &bblst_table[bblst_last];
1400 sp->split_bbs.nr_members = el.nr_members;
1401 for (j = 0; j < el.nr_members; bblst_last++, j++)
1402 bblst_table[bblst_last] = el.first_member[j]->dest;
1403 sp->update_bbs.first_member = &bblst_table[bblst_last];
1405 /* Compute update blocks and store them in bblst_table.
1406 For every split edge, look at the FROM block, and check
1407 all out edges. For each out edge that is not a split edge,
1408 add the TO block to the update block list. This list can end
1409 up with a lot of duplicates. We need to weed them out to avoid
1410 overrunning the end of the bblst_table. */
1412 update_idx = 0;
1413 sbitmap_zero (visited);
1414 for (j = 0; j < el.nr_members; j++)
1416 block = el.first_member[j]->src;
1417 FOR_EACH_EDGE (e, ei, block->succs)
1419 if (!TEST_BIT (visited, e->dest->index))
1421 for (k = 0; k < el.nr_members; k++)
1422 if (e == el.first_member[k])
1423 break;
1425 if (k >= el.nr_members)
1427 bblst_table[bblst_last++] = e->dest;
1428 SET_BIT (visited, e->dest->index);
1429 update_idx++;
1434 sp->update_bbs.nr_members = update_idx;
1436 /* Make sure we didn't overrun the end of bblst_table. */
1437 gcc_assert (bblst_last <= bblst_size);
1439 else
1441 sp->split_bbs.nr_members = sp->update_bbs.nr_members = 0;
1443 sp->is_speculative = 0;
1444 sp->src_prob = 0;
1448 sbitmap_free (visited);
1451 /* Print candidates info, for debugging purposes. Callable from debugger. */
1453 void
1454 debug_candidate (int i)
1456 if (!candidate_table[i].is_valid)
1457 return;
1459 if (candidate_table[i].is_speculative)
1461 int j;
1462 fprintf (sched_dump, "src b %d bb %d speculative \n", BB_TO_BLOCK (i), i);
1464 fprintf (sched_dump, "split path: ");
1465 for (j = 0; j < candidate_table[i].split_bbs.nr_members; j++)
1467 int b = candidate_table[i].split_bbs.first_member[j]->index;
1469 fprintf (sched_dump, " %d ", b);
1471 fprintf (sched_dump, "\n");
1473 fprintf (sched_dump, "update path: ");
1474 for (j = 0; j < candidate_table[i].update_bbs.nr_members; j++)
1476 int b = candidate_table[i].update_bbs.first_member[j]->index;
1478 fprintf (sched_dump, " %d ", b);
1480 fprintf (sched_dump, "\n");
1482 else
1484 fprintf (sched_dump, " src %d equivalent\n", BB_TO_BLOCK (i));
1488 /* Print candidates info, for debugging purposes. Callable from debugger. */
1490 void
1491 debug_candidates (int trg)
1493 int i;
1495 fprintf (sched_dump, "----------- candidate table: target: b=%d bb=%d ---\n",
1496 BB_TO_BLOCK (trg), trg);
1497 for (i = trg + 1; i < current_nr_blocks; i++)
1498 debug_candidate (i);
1501 /* Functions for speculative scheduling. */
1503 /* Return 0 if x is a set of a register alive in the beginning of one
1504 of the split-blocks of src, otherwise return 1. */
1506 static int
1507 check_live_1 (int src, rtx x)
1509 int i;
1510 int regno;
1511 rtx reg = SET_DEST (x);
1513 if (reg == 0)
1514 return 1;
1516 while (GET_CODE (reg) == SUBREG
1517 || GET_CODE (reg) == ZERO_EXTRACT
1518 || GET_CODE (reg) == STRICT_LOW_PART)
1519 reg = XEXP (reg, 0);
1521 if (GET_CODE (reg) == PARALLEL)
1523 int i;
1525 for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1526 if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1527 if (check_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0)))
1528 return 1;
1530 return 0;
1533 if (!REG_P (reg))
1534 return 1;
1536 regno = REGNO (reg);
1538 if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
1540 /* Global registers are assumed live. */
1541 return 0;
1543 else
1545 if (regno < FIRST_PSEUDO_REGISTER)
1547 /* Check for hard registers. */
1548 int j = hard_regno_nregs[regno][GET_MODE (reg)];
1549 while (--j >= 0)
1551 for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1553 basic_block b = candidate_table[src].split_bbs.first_member[i];
1555 /* We can have split blocks, that were recently generated.
1556 such blocks are always outside current region. */
1557 gcc_assert (glat_start[b->index]
1558 || CONTAINING_RGN (b->index)
1559 != CONTAINING_RGN (BB_TO_BLOCK (src)));
1560 if (!glat_start[b->index]
1561 || REGNO_REG_SET_P (glat_start[b->index],
1562 regno + j))
1564 return 0;
1569 else
1571 /* Check for pseudo registers. */
1572 for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1574 basic_block b = candidate_table[src].split_bbs.first_member[i];
1576 gcc_assert (glat_start[b->index]
1577 || CONTAINING_RGN (b->index)
1578 != CONTAINING_RGN (BB_TO_BLOCK (src)));
1579 if (!glat_start[b->index]
1580 || REGNO_REG_SET_P (glat_start[b->index], regno))
1582 return 0;
1588 return 1;
1591 /* If x is a set of a register R, mark that R is alive in the beginning
1592 of every update-block of src. */
1594 static void
1595 update_live_1 (int src, rtx x)
1597 int i;
1598 int regno;
1599 rtx reg = SET_DEST (x);
1601 if (reg == 0)
1602 return;
1604 while (GET_CODE (reg) == SUBREG
1605 || GET_CODE (reg) == ZERO_EXTRACT
1606 || GET_CODE (reg) == STRICT_LOW_PART)
1607 reg = XEXP (reg, 0);
1609 if (GET_CODE (reg) == PARALLEL)
1611 int i;
1613 for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1614 if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1615 update_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0));
1617 return;
1620 if (!REG_P (reg))
1621 return;
1623 /* Global registers are always live, so the code below does not apply
1624 to them. */
1626 regno = REGNO (reg);
1628 if (regno >= FIRST_PSEUDO_REGISTER || !global_regs[regno])
1630 if (regno < FIRST_PSEUDO_REGISTER)
1632 int j = hard_regno_nregs[regno][GET_MODE (reg)];
1633 while (--j >= 0)
1635 for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
1637 basic_block b = candidate_table[src].update_bbs.first_member[i];
1639 SET_REGNO_REG_SET (glat_start[b->index], regno + j);
1643 else
1645 for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
1647 basic_block b = candidate_table[src].update_bbs.first_member[i];
1649 SET_REGNO_REG_SET (glat_start[b->index], regno);
1655 /* Return 1 if insn can be speculatively moved from block src to trg,
1656 otherwise return 0. Called before first insertion of insn to
1657 ready-list or before the scheduling. */
1659 static int
1660 check_live (rtx insn, int src)
1662 /* Find the registers set by instruction. */
1663 if (GET_CODE (PATTERN (insn)) == SET
1664 || GET_CODE (PATTERN (insn)) == CLOBBER)
1665 return check_live_1 (src, PATTERN (insn));
1666 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1668 int j;
1669 for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1670 if ((GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1671 || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1672 && !check_live_1 (src, XVECEXP (PATTERN (insn), 0, j)))
1673 return 0;
1675 return 1;
1678 return 1;
1681 /* Update the live registers info after insn was moved speculatively from
1682 block src to trg. */
1684 static void
1685 update_live (rtx insn, int src)
1687 /* Find the registers set by instruction. */
1688 if (GET_CODE (PATTERN (insn)) == SET
1689 || GET_CODE (PATTERN (insn)) == CLOBBER)
1690 update_live_1 (src, PATTERN (insn));
1691 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1693 int j;
1694 for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1695 if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1696 || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1697 update_live_1 (src, XVECEXP (PATTERN (insn), 0, j));
1701 /* Nonzero if block bb_to is equal to, or reachable from block bb_from. */
1702 #define IS_REACHABLE(bb_from, bb_to) \
1703 (bb_from == bb_to \
1704 || IS_RGN_ENTRY (bb_from) \
1705 || (TEST_BIT (ancestor_edges[bb_to], \
1706 EDGE_TO_BIT (single_pred_edge (BASIC_BLOCK (BB_TO_BLOCK (bb_from)))))))
1708 /* Turns on the fed_by_spec_load flag for insns fed by load_insn. */
1710 static void
1711 set_spec_fed (rtx load_insn)
1713 dep_link_t link;
1715 FOR_EACH_DEP_LINK (link, INSN_FORW_DEPS (load_insn))
1716 if (DEP_LINK_KIND (link) == REG_DEP_TRUE)
1717 FED_BY_SPEC_LOAD (DEP_LINK_CON (link)) = 1;
1720 /* On the path from the insn to load_insn_bb, find a conditional
1721 branch depending on insn, that guards the speculative load. */
1723 static int
1724 find_conditional_protection (rtx insn, int load_insn_bb)
1726 dep_link_t link;
1728 /* Iterate through DEF-USE forward dependences. */
1729 FOR_EACH_DEP_LINK (link, INSN_FORW_DEPS (insn))
1731 rtx next = DEP_LINK_CON (link);
1733 if ((CONTAINING_RGN (BLOCK_NUM (next)) ==
1734 CONTAINING_RGN (BB_TO_BLOCK (load_insn_bb)))
1735 && IS_REACHABLE (INSN_BB (next), load_insn_bb)
1736 && load_insn_bb != INSN_BB (next)
1737 && DEP_LINK_KIND (link) == REG_DEP_TRUE
1738 && (JUMP_P (next)
1739 || find_conditional_protection (next, load_insn_bb)))
1740 return 1;
1742 return 0;
1743 } /* find_conditional_protection */
1745 /* Returns 1 if the same insn1 that participates in the computation
1746 of load_insn's address is feeding a conditional branch that is
1747 guarding on load_insn. This is true if we find a the two DEF-USE
1748 chains:
1749 insn1 -> ... -> conditional-branch
1750 insn1 -> ... -> load_insn,
1751 and if a flow path exist:
1752 insn1 -> ... -> conditional-branch -> ... -> load_insn,
1753 and if insn1 is on the path
1754 region-entry -> ... -> bb_trg -> ... load_insn.
1756 Locate insn1 by climbing on INSN_BACK_DEPS from load_insn.
1757 Locate the branch by following INSN_FORW_DEPS from insn1. */
1759 static int
1760 is_conditionally_protected (rtx load_insn, int bb_src, int bb_trg)
1762 dep_link_t link;
1764 FOR_EACH_DEP_LINK (link, INSN_BACK_DEPS (load_insn))
1766 rtx insn1 = DEP_LINK_PRO (link);
1768 /* Must be a DEF-USE dependence upon non-branch. */
1769 if (DEP_LINK_KIND (link) != REG_DEP_TRUE
1770 || JUMP_P (insn1))
1771 continue;
1773 /* Must exist a path: region-entry -> ... -> bb_trg -> ... load_insn. */
1774 if (INSN_BB (insn1) == bb_src
1775 || (CONTAINING_RGN (BLOCK_NUM (insn1))
1776 != CONTAINING_RGN (BB_TO_BLOCK (bb_src)))
1777 || (!IS_REACHABLE (bb_trg, INSN_BB (insn1))
1778 && !IS_REACHABLE (INSN_BB (insn1), bb_trg)))
1779 continue;
1781 /* Now search for the conditional-branch. */
1782 if (find_conditional_protection (insn1, bb_src))
1783 return 1;
1785 /* Recursive step: search another insn1, "above" current insn1. */
1786 return is_conditionally_protected (insn1, bb_src, bb_trg);
1789 /* The chain does not exist. */
1790 return 0;
1791 } /* is_conditionally_protected */
1793 /* Returns 1 if a clue for "similar load" 'insn2' is found, and hence
1794 load_insn can move speculatively from bb_src to bb_trg. All the
1795 following must hold:
1797 (1) both loads have 1 base register (PFREE_CANDIDATEs).
1798 (2) load_insn and load1 have a def-use dependence upon
1799 the same insn 'insn1'.
1800 (3) either load2 is in bb_trg, or:
1801 - there's only one split-block, and
1802 - load1 is on the escape path, and
1804 From all these we can conclude that the two loads access memory
1805 addresses that differ at most by a constant, and hence if moving
1806 load_insn would cause an exception, it would have been caused by
1807 load2 anyhow. */
1809 static int
1810 is_pfree (rtx load_insn, int bb_src, int bb_trg)
1812 dep_link_t back_link;
1813 candidate *candp = candidate_table + bb_src;
1815 if (candp->split_bbs.nr_members != 1)
1816 /* Must have exactly one escape block. */
1817 return 0;
1819 FOR_EACH_DEP_LINK (back_link, INSN_BACK_DEPS (load_insn))
1821 rtx insn1 = DEP_LINK_PRO (back_link);
1823 if (DEP_LINK_KIND (back_link) == REG_DEP_TRUE)
1825 /* Found a DEF-USE dependence (insn1, load_insn). */
1826 dep_link_t fore_link;
1828 FOR_EACH_DEP_LINK (fore_link, INSN_FORW_DEPS (insn1))
1830 rtx insn2 = DEP_LINK_CON (fore_link);
1832 if (DEP_LINK_KIND (fore_link) == REG_DEP_TRUE)
1834 /* Found a DEF-USE dependence (insn1, insn2). */
1835 if (haifa_classify_insn (insn2) != PFREE_CANDIDATE)
1836 /* insn2 not guaranteed to be a 1 base reg load. */
1837 continue;
1839 if (INSN_BB (insn2) == bb_trg)
1840 /* insn2 is the similar load, in the target block. */
1841 return 1;
1843 if (*(candp->split_bbs.first_member) == BLOCK_FOR_INSN (insn2))
1844 /* insn2 is a similar load, in a split-block. */
1845 return 1;
1851 /* Couldn't find a similar load. */
1852 return 0;
1853 } /* is_pfree */
1855 /* Return 1 if load_insn is prisky (i.e. if load_insn is fed by
1856 a load moved speculatively, or if load_insn is protected by
1857 a compare on load_insn's address). */
1859 static int
1860 is_prisky (rtx load_insn, int bb_src, int bb_trg)
1862 if (FED_BY_SPEC_LOAD (load_insn))
1863 return 1;
1865 if (deps_list_empty_p (INSN_BACK_DEPS (load_insn)))
1866 /* Dependence may 'hide' out of the region. */
1867 return 1;
1869 if (is_conditionally_protected (load_insn, bb_src, bb_trg))
1870 return 1;
1872 return 0;
1875 /* Insn is a candidate to be moved speculatively from bb_src to bb_trg.
1876 Return 1 if insn is exception-free (and the motion is valid)
1877 and 0 otherwise. */
1879 static int
1880 is_exception_free (rtx insn, int bb_src, int bb_trg)
1882 int insn_class = haifa_classify_insn (insn);
1884 /* Handle non-load insns. */
1885 switch (insn_class)
1887 case TRAP_FREE:
1888 return 1;
1889 case TRAP_RISKY:
1890 return 0;
1891 default:;
1894 /* Handle loads. */
1895 if (!flag_schedule_speculative_load)
1896 return 0;
1897 IS_LOAD_INSN (insn) = 1;
1898 switch (insn_class)
1900 case IFREE:
1901 return (1);
1902 case IRISKY:
1903 return 0;
1904 case PFREE_CANDIDATE:
1905 if (is_pfree (insn, bb_src, bb_trg))
1906 return 1;
1907 /* Don't 'break' here: PFREE-candidate is also PRISKY-candidate. */
1908 case PRISKY_CANDIDATE:
1909 if (!flag_schedule_speculative_load_dangerous
1910 || is_prisky (insn, bb_src, bb_trg))
1911 return 0;
1912 break;
1913 default:;
1916 return flag_schedule_speculative_load_dangerous;
1919 /* The number of insns from the current block scheduled so far. */
1920 static int sched_target_n_insns;
1921 /* The number of insns from the current block to be scheduled in total. */
1922 static int target_n_insns;
1923 /* The number of insns from the entire region scheduled so far. */
1924 static int sched_n_insns;
1926 /* Implementations of the sched_info functions for region scheduling. */
1927 static void init_ready_list (void);
1928 static int can_schedule_ready_p (rtx);
1929 static void begin_schedule_ready (rtx, rtx);
1930 static ds_t new_ready (rtx, ds_t);
1931 static int schedule_more_p (void);
1932 static const char *rgn_print_insn (rtx, int);
1933 static int rgn_rank (rtx, rtx);
1934 static int contributes_to_priority (rtx, rtx);
1935 static void compute_jump_reg_dependencies (rtx, regset, regset, regset);
1937 /* Functions for speculative scheduling. */
1938 static void add_remove_insn (rtx, int);
1939 static void extend_regions (void);
1940 static void add_block1 (basic_block, basic_block);
1941 static void fix_recovery_cfg (int, int, int);
1942 static basic_block advance_target_bb (basic_block, rtx);
1943 static void check_dead_notes1 (int, sbitmap);
1944 #ifdef ENABLE_CHECKING
1945 static int region_head_or_leaf_p (basic_block, int);
1946 #endif
1948 static void debug_rgn_dependencies (int);
1950 /* Return nonzero if there are more insns that should be scheduled. */
1952 static int
1953 schedule_more_p (void)
1955 return sched_target_n_insns < target_n_insns;
1958 /* Add all insns that are initially ready to the ready list READY. Called
1959 once before scheduling a set of insns. */
1961 static void
1962 init_ready_list (void)
1964 rtx prev_head = current_sched_info->prev_head;
1965 rtx next_tail = current_sched_info->next_tail;
1966 int bb_src;
1967 rtx insn;
1969 target_n_insns = 0;
1970 sched_target_n_insns = 0;
1971 sched_n_insns = 0;
1973 /* Print debugging information. */
1974 if (sched_verbose >= 5)
1975 debug_rgn_dependencies (target_bb);
1977 /* Prepare current target block info. */
1978 if (current_nr_blocks > 1)
1980 candidate_table = XNEWVEC (candidate, current_nr_blocks);
1982 bblst_last = 0;
1983 /* bblst_table holds split blocks and update blocks for each block after
1984 the current one in the region. split blocks and update blocks are
1985 the TO blocks of region edges, so there can be at most rgn_nr_edges
1986 of them. */
1987 bblst_size = (current_nr_blocks - target_bb) * rgn_nr_edges;
1988 bblst_table = XNEWVEC (basic_block, bblst_size);
1990 edgelst_last = 0;
1991 edgelst_table = XNEWVEC (edge, rgn_nr_edges);
1993 compute_trg_info (target_bb);
1996 /* Initialize ready list with all 'ready' insns in target block.
1997 Count number of insns in the target block being scheduled. */
1998 for (insn = NEXT_INSN (prev_head); insn != next_tail; insn = NEXT_INSN (insn))
2000 try_ready (insn);
2001 target_n_insns++;
2003 gcc_assert (!(TODO_SPEC (insn) & BEGIN_CONTROL));
2006 /* Add to ready list all 'ready' insns in valid source blocks.
2007 For speculative insns, check-live, exception-free, and
2008 issue-delay. */
2009 for (bb_src = target_bb + 1; bb_src < current_nr_blocks; bb_src++)
2010 if (IS_VALID (bb_src))
2012 rtx src_head;
2013 rtx src_next_tail;
2014 rtx tail, head;
2016 get_ebb_head_tail (EBB_FIRST_BB (bb_src), EBB_LAST_BB (bb_src),
2017 &head, &tail);
2018 src_next_tail = NEXT_INSN (tail);
2019 src_head = head;
2021 for (insn = src_head; insn != src_next_tail; insn = NEXT_INSN (insn))
2022 if (INSN_P (insn))
2023 try_ready (insn);
2027 /* Called after taking INSN from the ready list. Returns nonzero if this
2028 insn can be scheduled, nonzero if we should silently discard it. */
2030 static int
2031 can_schedule_ready_p (rtx insn)
2033 /* An interblock motion? */
2034 if (INSN_BB (insn) != target_bb
2035 && IS_SPECULATIVE_INSN (insn)
2036 && !check_live (insn, INSN_BB (insn)))
2037 return 0;
2038 else
2039 return 1;
2042 /* Updates counter and other information. Split from can_schedule_ready_p ()
2043 because when we schedule insn speculatively then insn passed to
2044 can_schedule_ready_p () differs from the one passed to
2045 begin_schedule_ready (). */
2046 static void
2047 begin_schedule_ready (rtx insn, rtx last ATTRIBUTE_UNUSED)
2049 /* An interblock motion? */
2050 if (INSN_BB (insn) != target_bb)
2052 if (IS_SPECULATIVE_INSN (insn))
2054 gcc_assert (check_live (insn, INSN_BB (insn)));
2056 update_live (insn, INSN_BB (insn));
2058 /* For speculative load, mark insns fed by it. */
2059 if (IS_LOAD_INSN (insn) || FED_BY_SPEC_LOAD (insn))
2060 set_spec_fed (insn);
2062 nr_spec++;
2064 nr_inter++;
2066 else
2068 /* In block motion. */
2069 sched_target_n_insns++;
2071 sched_n_insns++;
2074 /* Called after INSN has all its hard dependencies resolved and the speculation
2075 of type TS is enough to overcome them all.
2076 Return nonzero if it should be moved to the ready list or the queue, or zero
2077 if we should silently discard it. */
2078 static ds_t
2079 new_ready (rtx next, ds_t ts)
2081 if (INSN_BB (next) != target_bb)
2083 int not_ex_free = 0;
2085 /* For speculative insns, before inserting to ready/queue,
2086 check live, exception-free, and issue-delay. */
2087 if (!IS_VALID (INSN_BB (next))
2088 || CANT_MOVE (next)
2089 || (IS_SPECULATIVE_INSN (next)
2090 && ((recog_memoized (next) >= 0
2091 && min_insn_conflict_delay (curr_state, next, next)
2092 > PARAM_VALUE (PARAM_MAX_SCHED_INSN_CONFLICT_DELAY))
2093 || IS_SPECULATION_CHECK_P (next)
2094 || !check_live (next, INSN_BB (next))
2095 || (not_ex_free = !is_exception_free (next, INSN_BB (next),
2096 target_bb)))))
2098 if (not_ex_free
2099 /* We are here because is_exception_free () == false.
2100 But we possibly can handle that with control speculation. */
2101 && current_sched_info->flags & DO_SPECULATION)
2102 /* Here we got new control-speculative instruction. */
2103 ts = set_dep_weak (ts, BEGIN_CONTROL, MAX_DEP_WEAK);
2104 else
2105 ts = (ts & ~SPECULATIVE) | HARD_DEP;
2109 return ts;
2112 /* Return a string that contains the insn uid and optionally anything else
2113 necessary to identify this insn in an output. It's valid to use a
2114 static buffer for this. The ALIGNED parameter should cause the string
2115 to be formatted so that multiple output lines will line up nicely. */
2117 static const char *
2118 rgn_print_insn (rtx insn, int aligned)
2120 static char tmp[80];
2122 if (aligned)
2123 sprintf (tmp, "b%3d: i%4d", INSN_BB (insn), INSN_UID (insn));
2124 else
2126 if (current_nr_blocks > 1 && INSN_BB (insn) != target_bb)
2127 sprintf (tmp, "%d/b%d", INSN_UID (insn), INSN_BB (insn));
2128 else
2129 sprintf (tmp, "%d", INSN_UID (insn));
2131 return tmp;
2134 /* Compare priority of two insns. Return a positive number if the second
2135 insn is to be preferred for scheduling, and a negative one if the first
2136 is to be preferred. Zero if they are equally good. */
2138 static int
2139 rgn_rank (rtx insn1, rtx insn2)
2141 /* Some comparison make sense in interblock scheduling only. */
2142 if (INSN_BB (insn1) != INSN_BB (insn2))
2144 int spec_val, prob_val;
2146 /* Prefer an inblock motion on an interblock motion. */
2147 if ((INSN_BB (insn2) == target_bb) && (INSN_BB (insn1) != target_bb))
2148 return 1;
2149 if ((INSN_BB (insn1) == target_bb) && (INSN_BB (insn2) != target_bb))
2150 return -1;
2152 /* Prefer a useful motion on a speculative one. */
2153 spec_val = IS_SPECULATIVE_INSN (insn1) - IS_SPECULATIVE_INSN (insn2);
2154 if (spec_val)
2155 return spec_val;
2157 /* Prefer a more probable (speculative) insn. */
2158 prob_val = INSN_PROBABILITY (insn2) - INSN_PROBABILITY (insn1);
2159 if (prob_val)
2160 return prob_val;
2162 return 0;
2165 /* NEXT is an instruction that depends on INSN (a backward dependence);
2166 return nonzero if we should include this dependence in priority
2167 calculations. */
2169 static int
2170 contributes_to_priority (rtx next, rtx insn)
2172 /* NEXT and INSN reside in one ebb. */
2173 return BLOCK_TO_BB (BLOCK_NUM (next)) == BLOCK_TO_BB (BLOCK_NUM (insn));
2176 /* INSN is a JUMP_INSN, COND_SET is the set of registers that are
2177 conditionally set before INSN. Store the set of registers that
2178 must be considered as used by this jump in USED and that of
2179 registers that must be considered as set in SET. */
2181 static void
2182 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
2183 regset cond_exec ATTRIBUTE_UNUSED,
2184 regset used ATTRIBUTE_UNUSED,
2185 regset set ATTRIBUTE_UNUSED)
2187 /* Nothing to do here, since we postprocess jumps in
2188 add_branch_dependences. */
2191 /* Used in schedule_insns to initialize current_sched_info for scheduling
2192 regions (or single basic blocks). */
2194 static struct sched_info region_sched_info =
2196 init_ready_list,
2197 can_schedule_ready_p,
2198 schedule_more_p,
2199 new_ready,
2200 rgn_rank,
2201 rgn_print_insn,
2202 contributes_to_priority,
2203 compute_jump_reg_dependencies,
2205 NULL, NULL,
2206 NULL, NULL,
2207 0, 0, 0,
2209 add_remove_insn,
2210 begin_schedule_ready,
2211 add_block1,
2212 advance_target_bb,
2213 fix_recovery_cfg,
2214 #ifdef ENABLE_CHECKING
2215 region_head_or_leaf_p,
2216 #endif
2217 SCHED_RGN | USE_GLAT
2218 #ifdef ENABLE_CHECKING
2219 | DETACH_LIFE_INFO
2220 #endif
2223 /* Determine if PAT sets a CLASS_LIKELY_SPILLED_P register. */
2225 static bool
2226 sets_likely_spilled (rtx pat)
2228 bool ret = false;
2229 note_stores (pat, sets_likely_spilled_1, &ret);
2230 return ret;
2233 static void
2234 sets_likely_spilled_1 (rtx x, rtx pat, void *data)
2236 bool *ret = (bool *) data;
2238 if (GET_CODE (pat) == SET
2239 && REG_P (x)
2240 && REGNO (x) < FIRST_PSEUDO_REGISTER
2241 && CLASS_LIKELY_SPILLED_P (REGNO_REG_CLASS (REGNO (x))))
2242 *ret = true;
2245 /* Add dependences so that branches are scheduled to run last in their
2246 block. */
2248 static void
2249 add_branch_dependences (rtx head, rtx tail)
2251 rtx insn, last;
2253 /* For all branches, calls, uses, clobbers, cc0 setters, and instructions
2254 that can throw exceptions, force them to remain in order at the end of
2255 the block by adding dependencies and giving the last a high priority.
2256 There may be notes present, and prev_head may also be a note.
2258 Branches must obviously remain at the end. Calls should remain at the
2259 end since moving them results in worse register allocation. Uses remain
2260 at the end to ensure proper register allocation.
2262 cc0 setters remain at the end because they can't be moved away from
2263 their cc0 user.
2265 COND_EXEC insns cannot be moved past a branch (see e.g. PR17808).
2267 Insns setting CLASS_LIKELY_SPILLED_P registers (usually return values)
2268 are not moved before reload because we can wind up with register
2269 allocation failures. */
2271 insn = tail;
2272 last = 0;
2273 while (CALL_P (insn)
2274 || JUMP_P (insn)
2275 || (NONJUMP_INSN_P (insn)
2276 && (GET_CODE (PATTERN (insn)) == USE
2277 || GET_CODE (PATTERN (insn)) == CLOBBER
2278 || can_throw_internal (insn)
2279 #ifdef HAVE_cc0
2280 || sets_cc0_p (PATTERN (insn))
2281 #endif
2282 || (!reload_completed
2283 && sets_likely_spilled (PATTERN (insn)))))
2284 || NOTE_P (insn))
2286 if (!NOTE_P (insn))
2288 if (last != 0
2289 && (find_link_by_pro_in_deps_list (INSN_BACK_DEPS (last), insn)
2290 == NULL))
2292 if (! sched_insns_conditions_mutex_p (last, insn))
2293 add_dependence (last, insn, REG_DEP_ANTI);
2294 INSN_REF_COUNT (insn)++;
2297 CANT_MOVE (insn) = 1;
2299 last = insn;
2302 /* Don't overrun the bounds of the basic block. */
2303 if (insn == head)
2304 break;
2306 insn = PREV_INSN (insn);
2309 /* Make sure these insns are scheduled last in their block. */
2310 insn = last;
2311 if (insn != 0)
2312 while (insn != head)
2314 insn = prev_nonnote_insn (insn);
2316 if (INSN_REF_COUNT (insn) != 0)
2317 continue;
2319 if (! sched_insns_conditions_mutex_p (last, insn))
2320 add_dependence (last, insn, REG_DEP_ANTI);
2321 INSN_REF_COUNT (insn) = 1;
2324 #ifdef HAVE_conditional_execution
2325 /* Finally, if the block ends in a jump, and we are doing intra-block
2326 scheduling, make sure that the branch depends on any COND_EXEC insns
2327 inside the block to avoid moving the COND_EXECs past the branch insn.
2329 We only have to do this after reload, because (1) before reload there
2330 are no COND_EXEC insns, and (2) the region scheduler is an intra-block
2331 scheduler after reload.
2333 FIXME: We could in some cases move COND_EXEC insns past the branch if
2334 this scheduler would be a little smarter. Consider this code:
2336 T = [addr]
2337 C ? addr += 4
2338 !C ? X += 12
2339 C ? T += 1
2340 C ? jump foo
2342 On a target with a one cycle stall on a memory access the optimal
2343 sequence would be:
2345 T = [addr]
2346 C ? addr += 4
2347 C ? T += 1
2348 C ? jump foo
2349 !C ? X += 12
2351 We don't want to put the 'X += 12' before the branch because it just
2352 wastes a cycle of execution time when the branch is taken.
2354 Note that in the example "!C" will always be true. That is another
2355 possible improvement for handling COND_EXECs in this scheduler: it
2356 could remove always-true predicates. */
2358 if (!reload_completed || ! JUMP_P (tail))
2359 return;
2361 insn = tail;
2362 while (insn != head)
2364 insn = PREV_INSN (insn);
2366 /* Note that we want to add this dependency even when
2367 sched_insns_conditions_mutex_p returns true. The whole point
2368 is that we _want_ this dependency, even if these insns really
2369 are independent. */
2370 if (INSN_P (insn) && GET_CODE (PATTERN (insn)) == COND_EXEC)
2371 add_dependence (tail, insn, REG_DEP_ANTI);
2373 #endif
2376 /* Data structures for the computation of data dependences in a regions. We
2377 keep one `deps' structure for every basic block. Before analyzing the
2378 data dependences for a bb, its variables are initialized as a function of
2379 the variables of its predecessors. When the analysis for a bb completes,
2380 we save the contents to the corresponding bb_deps[bb] variable. */
2382 static struct deps *bb_deps;
2384 /* Duplicate the INSN_LIST elements of COPY and prepend them to OLD. */
2386 static rtx
2387 concat_INSN_LIST (rtx copy, rtx old)
2389 rtx new = old;
2390 for (; copy ; copy = XEXP (copy, 1))
2391 new = alloc_INSN_LIST (XEXP (copy, 0), new);
2392 return new;
2395 static void
2396 concat_insn_mem_list (rtx copy_insns, rtx copy_mems, rtx *old_insns_p,
2397 rtx *old_mems_p)
2399 rtx new_insns = *old_insns_p;
2400 rtx new_mems = *old_mems_p;
2402 while (copy_insns)
2404 new_insns = alloc_INSN_LIST (XEXP (copy_insns, 0), new_insns);
2405 new_mems = alloc_EXPR_LIST (VOIDmode, XEXP (copy_mems, 0), new_mems);
2406 copy_insns = XEXP (copy_insns, 1);
2407 copy_mems = XEXP (copy_mems, 1);
2410 *old_insns_p = new_insns;
2411 *old_mems_p = new_mems;
2414 /* After computing the dependencies for block BB, propagate the dependencies
2415 found in TMP_DEPS to the successors of the block. */
2416 static void
2417 propagate_deps (int bb, struct deps *pred_deps)
2419 basic_block block = BASIC_BLOCK (BB_TO_BLOCK (bb));
2420 edge_iterator ei;
2421 edge e;
2423 /* bb's structures are inherited by its successors. */
2424 FOR_EACH_EDGE (e, ei, block->succs)
2426 struct deps *succ_deps;
2427 unsigned reg;
2428 reg_set_iterator rsi;
2430 /* Only bbs "below" bb, in the same region, are interesting. */
2431 if (e->dest == EXIT_BLOCK_PTR
2432 || CONTAINING_RGN (block->index) != CONTAINING_RGN (e->dest->index)
2433 || BLOCK_TO_BB (e->dest->index) <= bb)
2434 continue;
2436 succ_deps = bb_deps + BLOCK_TO_BB (e->dest->index);
2438 /* The reg_last lists are inherited by successor. */
2439 EXECUTE_IF_SET_IN_REG_SET (&pred_deps->reg_last_in_use, 0, reg, rsi)
2441 struct deps_reg *pred_rl = &pred_deps->reg_last[reg];
2442 struct deps_reg *succ_rl = &succ_deps->reg_last[reg];
2444 succ_rl->uses = concat_INSN_LIST (pred_rl->uses, succ_rl->uses);
2445 succ_rl->sets = concat_INSN_LIST (pred_rl->sets, succ_rl->sets);
2446 succ_rl->clobbers = concat_INSN_LIST (pred_rl->clobbers,
2447 succ_rl->clobbers);
2448 succ_rl->uses_length += pred_rl->uses_length;
2449 succ_rl->clobbers_length += pred_rl->clobbers_length;
2451 IOR_REG_SET (&succ_deps->reg_last_in_use, &pred_deps->reg_last_in_use);
2453 /* Mem read/write lists are inherited by successor. */
2454 concat_insn_mem_list (pred_deps->pending_read_insns,
2455 pred_deps->pending_read_mems,
2456 &succ_deps->pending_read_insns,
2457 &succ_deps->pending_read_mems);
2458 concat_insn_mem_list (pred_deps->pending_write_insns,
2459 pred_deps->pending_write_mems,
2460 &succ_deps->pending_write_insns,
2461 &succ_deps->pending_write_mems);
2463 succ_deps->last_pending_memory_flush
2464 = concat_INSN_LIST (pred_deps->last_pending_memory_flush,
2465 succ_deps->last_pending_memory_flush);
2467 succ_deps->pending_read_list_length
2468 += pred_deps->pending_read_list_length;
2469 succ_deps->pending_write_list_length
2470 += pred_deps->pending_write_list_length;
2471 succ_deps->pending_flush_length += pred_deps->pending_flush_length;
2473 /* last_function_call is inherited by successor. */
2474 succ_deps->last_function_call
2475 = concat_INSN_LIST (pred_deps->last_function_call,
2476 succ_deps->last_function_call);
2478 /* sched_before_next_call is inherited by successor. */
2479 succ_deps->sched_before_next_call
2480 = concat_INSN_LIST (pred_deps->sched_before_next_call,
2481 succ_deps->sched_before_next_call);
2484 /* These lists should point to the right place, for correct
2485 freeing later. */
2486 bb_deps[bb].pending_read_insns = pred_deps->pending_read_insns;
2487 bb_deps[bb].pending_read_mems = pred_deps->pending_read_mems;
2488 bb_deps[bb].pending_write_insns = pred_deps->pending_write_insns;
2489 bb_deps[bb].pending_write_mems = pred_deps->pending_write_mems;
2491 /* Can't allow these to be freed twice. */
2492 pred_deps->pending_read_insns = 0;
2493 pred_deps->pending_read_mems = 0;
2494 pred_deps->pending_write_insns = 0;
2495 pred_deps->pending_write_mems = 0;
2498 /* Compute backward dependences inside bb. In a multiple blocks region:
2499 (1) a bb is analyzed after its predecessors, and (2) the lists in
2500 effect at the end of bb (after analyzing for bb) are inherited by
2501 bb's successors.
2503 Specifically for reg-reg data dependences, the block insns are
2504 scanned by sched_analyze () top-to-bottom. Two lists are
2505 maintained by sched_analyze (): reg_last[].sets for register DEFs,
2506 and reg_last[].uses for register USEs.
2508 When analysis is completed for bb, we update for its successors:
2509 ; - DEFS[succ] = Union (DEFS [succ], DEFS [bb])
2510 ; - USES[succ] = Union (USES [succ], DEFS [bb])
2512 The mechanism for computing mem-mem data dependence is very
2513 similar, and the result is interblock dependences in the region. */
2515 static void
2516 compute_block_backward_dependences (int bb)
2518 rtx head, tail;
2519 struct deps tmp_deps;
2521 tmp_deps = bb_deps[bb];
2523 /* Do the analysis for this block. */
2524 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2525 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2526 sched_analyze (&tmp_deps, head, tail);
2527 add_branch_dependences (head, tail);
2529 if (current_nr_blocks > 1)
2530 propagate_deps (bb, &tmp_deps);
2532 /* Free up the INSN_LISTs. */
2533 free_deps (&tmp_deps);
2536 /* Remove all INSN_LISTs and EXPR_LISTs from the pending lists and add
2537 them to the unused_*_list variables, so that they can be reused. */
2539 static void
2540 free_pending_lists (void)
2542 int bb;
2544 for (bb = 0; bb < current_nr_blocks; bb++)
2546 free_INSN_LIST_list (&bb_deps[bb].pending_read_insns);
2547 free_INSN_LIST_list (&bb_deps[bb].pending_write_insns);
2548 free_EXPR_LIST_list (&bb_deps[bb].pending_read_mems);
2549 free_EXPR_LIST_list (&bb_deps[bb].pending_write_mems);
2554 /* Print dependences for debugging starting from FROM_BB.
2555 Callable from debugger. */
2556 void
2557 debug_rgn_dependencies (int from_bb)
2559 int bb;
2561 fprintf (sched_dump,
2562 ";; --------------- forward dependences: ------------ \n");
2564 for (bb = from_bb; bb < current_nr_blocks; bb++)
2566 rtx head, tail;
2568 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2569 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2570 fprintf (sched_dump, "\n;; --- Region Dependences --- b %d bb %d \n",
2571 BB_TO_BLOCK (bb), bb);
2573 debug_dependencies (head, tail);
2577 /* Print dependencies information for instructions between HEAD and TAIL.
2578 ??? This function would probably fit best in haifa-sched.c. */
2579 void debug_dependencies (rtx head, rtx tail)
2581 rtx insn;
2582 rtx next_tail = NEXT_INSN (tail);
2584 fprintf (sched_dump, ";; %7s%6s%6s%6s%6s%6s%14s\n",
2585 "insn", "code", "bb", "dep", "prio", "cost",
2586 "reservation");
2587 fprintf (sched_dump, ";; %7s%6s%6s%6s%6s%6s%14s\n",
2588 "----", "----", "--", "---", "----", "----",
2589 "-----------");
2591 for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
2593 dep_link_t link;
2595 if (! INSN_P (insn))
2597 int n;
2598 fprintf (sched_dump, ";; %6d ", INSN_UID (insn));
2599 if (NOTE_P (insn))
2601 n = NOTE_KIND (insn);
2602 fprintf (sched_dump, "%s\n", GET_NOTE_INSN_NAME (n));
2604 else
2605 fprintf (sched_dump, " {%s}\n", GET_RTX_NAME (GET_CODE (insn)));
2606 continue;
2609 fprintf (sched_dump,
2610 ";; %s%5d%6d%6d%6d%6d%6d ",
2611 (SCHED_GROUP_P (insn) ? "+" : " "),
2612 INSN_UID (insn),
2613 INSN_CODE (insn),
2614 BLOCK_NUM (insn),
2615 INSN_DEP_COUNT (insn),
2616 INSN_PRIORITY (insn),
2617 insn_cost (insn));
2619 if (recog_memoized (insn) < 0)
2620 fprintf (sched_dump, "nothing");
2621 else
2622 print_reservation (sched_dump, insn);
2624 fprintf (sched_dump, "\t: ");
2625 FOR_EACH_DEP_LINK (link, INSN_FORW_DEPS (insn))
2626 fprintf (sched_dump, "%d ", INSN_UID (DEP_LINK_CON (link)));
2627 fprintf (sched_dump, "\n");
2630 fprintf (sched_dump, "\n");
2633 /* Returns true if all the basic blocks of the current region have
2634 NOTE_DISABLE_SCHED_OF_BLOCK which means not to schedule that region. */
2635 static bool
2636 sched_is_disabled_for_current_region_p (void)
2638 int bb;
2640 for (bb = 0; bb < current_nr_blocks; bb++)
2641 if (!(BASIC_BLOCK (BB_TO_BLOCK (bb))->flags & BB_DISABLE_SCHEDULE))
2642 return false;
2644 return true;
2647 /* Schedule a region. A region is either an inner loop, a loop-free
2648 subroutine, or a single basic block. Each bb in the region is
2649 scheduled after its flow predecessors. */
2651 static void
2652 schedule_region (int rgn)
2654 basic_block block;
2655 edge_iterator ei;
2656 edge e;
2657 int bb;
2658 int sched_rgn_n_insns = 0;
2660 rgn_n_insns = 0;
2661 /* Set variables for the current region. */
2662 current_nr_blocks = RGN_NR_BLOCKS (rgn);
2663 current_blocks = RGN_BLOCKS (rgn);
2665 /* See comments in add_block1, for what reasons we allocate +1 element. */
2666 ebb_head = xrealloc (ebb_head, (current_nr_blocks + 1) * sizeof (*ebb_head));
2667 for (bb = 0; bb <= current_nr_blocks; bb++)
2668 ebb_head[bb] = current_blocks + bb;
2670 /* Don't schedule region that is marked by
2671 NOTE_DISABLE_SCHED_OF_BLOCK. */
2672 if (sched_is_disabled_for_current_region_p ())
2673 return;
2675 if (!RGN_DONT_CALC_DEPS (rgn))
2677 init_deps_global ();
2679 /* Initializations for region data dependence analysis. */
2680 bb_deps = XNEWVEC (struct deps, current_nr_blocks);
2681 for (bb = 0; bb < current_nr_blocks; bb++)
2682 init_deps (bb_deps + bb);
2684 /* Compute backward dependencies. */
2685 for (bb = 0; bb < current_nr_blocks; bb++)
2686 compute_block_backward_dependences (bb);
2688 /* Compute forward dependencies. */
2689 for (bb = current_nr_blocks - 1; bb >= 0; bb--)
2691 rtx head, tail;
2693 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2694 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2696 compute_forward_dependences (head, tail);
2698 if (targetm.sched.dependencies_evaluation_hook)
2699 targetm.sched.dependencies_evaluation_hook (head, tail);
2702 free_pending_lists ();
2704 finish_deps_global ();
2706 free (bb_deps);
2708 else
2709 /* This is a recovery block. It is always a single block region. */
2710 gcc_assert (current_nr_blocks == 1);
2712 /* Set priorities. */
2713 current_sched_info->sched_max_insns_priority = 0;
2714 for (bb = 0; bb < current_nr_blocks; bb++)
2716 rtx head, tail;
2718 gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2719 get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2721 rgn_n_insns += set_priorities (head, tail);
2723 current_sched_info->sched_max_insns_priority++;
2725 /* Compute interblock info: probabilities, split-edges, dominators, etc. */
2726 if (current_nr_blocks > 1)
2728 prob = XNEWVEC (int, current_nr_blocks);
2730 dom = sbitmap_vector_alloc (current_nr_blocks, current_nr_blocks);
2731 sbitmap_vector_zero (dom, current_nr_blocks);
2733 /* Use ->aux to implement EDGE_TO_BIT mapping. */
2734 rgn_nr_edges = 0;
2735 FOR_EACH_BB (block)
2737 if (CONTAINING_RGN (block->index) != rgn)
2738 continue;
2739 FOR_EACH_EDGE (e, ei, block->succs)
2740 SET_EDGE_TO_BIT (e, rgn_nr_edges++);
2743 rgn_edges = XNEWVEC (edge, rgn_nr_edges);
2744 rgn_nr_edges = 0;
2745 FOR_EACH_BB (block)
2747 if (CONTAINING_RGN (block->index) != rgn)
2748 continue;
2749 FOR_EACH_EDGE (e, ei, block->succs)
2750 rgn_edges[rgn_nr_edges++] = e;
2753 /* Split edges. */
2754 pot_split = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
2755 sbitmap_vector_zero (pot_split, current_nr_blocks);
2756 ancestor_edges = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
2757 sbitmap_vector_zero (ancestor_edges, current_nr_blocks);
2759 /* Compute probabilities, dominators, split_edges. */
2760 for (bb = 0; bb < current_nr_blocks; bb++)
2761 compute_dom_prob_ps (bb);
2763 /* Cleanup ->aux used for EDGE_TO_BIT mapping. */
2764 /* We don't need them anymore. But we want to avoid duplication of
2765 aux fields in the newly created edges. */
2766 FOR_EACH_BB (block)
2768 if (CONTAINING_RGN (block->index) != rgn)
2769 continue;
2770 FOR_EACH_EDGE (e, ei, block->succs)
2771 e->aux = NULL;
2775 /* Now we can schedule all blocks. */
2776 for (bb = 0; bb < current_nr_blocks; bb++)
2778 basic_block first_bb, last_bb, curr_bb;
2779 rtx head, tail;
2781 first_bb = EBB_FIRST_BB (bb);
2782 last_bb = EBB_LAST_BB (bb);
2784 get_ebb_head_tail (first_bb, last_bb, &head, &tail);
2786 if (no_real_insns_p (head, tail))
2788 gcc_assert (first_bb == last_bb);
2789 continue;
2792 current_sched_info->prev_head = PREV_INSN (head);
2793 current_sched_info->next_tail = NEXT_INSN (tail);
2796 /* rm_other_notes only removes notes which are _inside_ the
2797 block---that is, it won't remove notes before the first real insn
2798 or after the last real insn of the block. So if the first insn
2799 has a REG_SAVE_NOTE which would otherwise be emitted before the
2800 insn, it is redundant with the note before the start of the
2801 block, and so we have to take it out. */
2802 if (INSN_P (head))
2804 rtx note;
2806 for (note = REG_NOTES (head); note; note = XEXP (note, 1))
2807 if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
2808 remove_note (head, note);
2810 else
2811 /* This means that first block in ebb is empty.
2812 It looks to me as an impossible thing. There at least should be
2813 a recovery check, that caused the splitting. */
2814 gcc_unreachable ();
2816 /* Remove remaining note insns from the block, save them in
2817 note_list. These notes are restored at the end of
2818 schedule_block (). */
2819 rm_other_notes (head, tail);
2821 unlink_bb_notes (first_bb, last_bb);
2823 target_bb = bb;
2825 gcc_assert (flag_schedule_interblock || current_nr_blocks == 1);
2826 current_sched_info->queue_must_finish_empty = current_nr_blocks == 1;
2828 curr_bb = first_bb;
2829 schedule_block (&curr_bb, rgn_n_insns);
2830 gcc_assert (EBB_FIRST_BB (bb) == first_bb);
2831 sched_rgn_n_insns += sched_n_insns;
2833 /* Clean up. */
2834 if (current_nr_blocks > 1)
2836 free (candidate_table);
2837 free (bblst_table);
2838 free (edgelst_table);
2842 /* Sanity check: verify that all region insns were scheduled. */
2843 gcc_assert (sched_rgn_n_insns == rgn_n_insns);
2846 /* Done with this region. */
2848 if (current_nr_blocks > 1)
2850 free (prob);
2851 sbitmap_vector_free (dom);
2852 sbitmap_vector_free (pot_split);
2853 sbitmap_vector_free (ancestor_edges);
2854 free (rgn_edges);
2858 /* Indexed by region, holds the number of death notes found in that region.
2859 Used for consistency checks. */
2860 static int *deaths_in_region;
2862 /* Initialize data structures for region scheduling. */
2864 static void
2865 init_regions (void)
2867 sbitmap blocks;
2868 int rgn;
2870 nr_regions = 0;
2871 rgn_table = 0;
2872 rgn_bb_table = 0;
2873 block_to_bb = 0;
2874 containing_rgn = 0;
2875 extend_regions ();
2877 /* Compute regions for scheduling. */
2878 if (reload_completed
2879 || n_basic_blocks == NUM_FIXED_BLOCKS + 1
2880 || !flag_schedule_interblock
2881 || is_cfg_nonregular ())
2883 find_single_block_region ();
2885 else
2887 /* Compute the dominators and post dominators. */
2888 calculate_dominance_info (CDI_DOMINATORS);
2890 /* Find regions. */
2891 find_rgns ();
2893 if (sched_verbose >= 3)
2894 debug_regions ();
2896 /* For now. This will move as more and more of haifa is converted
2897 to using the cfg code in flow.c. */
2898 free_dominance_info (CDI_DOMINATORS);
2900 RGN_BLOCKS (nr_regions) = RGN_BLOCKS (nr_regions - 1) +
2901 RGN_NR_BLOCKS (nr_regions - 1);
2904 if (CHECK_DEAD_NOTES)
2906 blocks = sbitmap_alloc (last_basic_block);
2907 deaths_in_region = XNEWVEC (int, nr_regions);
2908 /* Remove all death notes from the subroutine. */
2909 for (rgn = 0; rgn < nr_regions; rgn++)
2910 check_dead_notes1 (rgn, blocks);
2912 sbitmap_free (blocks);
2914 else
2915 count_or_remove_death_notes (NULL, 1);
2918 /* The one entry point in this file. */
2920 void
2921 schedule_insns (void)
2923 sbitmap large_region_blocks, blocks;
2924 int rgn;
2925 int any_large_regions;
2926 basic_block bb;
2928 /* Taking care of this degenerate case makes the rest of
2929 this code simpler. */
2930 if (n_basic_blocks == NUM_FIXED_BLOCKS)
2931 return;
2933 nr_inter = 0;
2934 nr_spec = 0;
2936 /* We need current_sched_info in init_dependency_caches, which is
2937 invoked via sched_init. */
2938 current_sched_info = &region_sched_info;
2940 sched_init ();
2942 min_spec_prob = ((PARAM_VALUE (PARAM_MIN_SPEC_PROB) * REG_BR_PROB_BASE)
2943 / 100);
2945 init_regions ();
2947 /* EBB_HEAD is a region-scope structure. But we realloc it for
2948 each region to save time/memory/something else. */
2949 ebb_head = 0;
2951 /* Schedule every region in the subroutine. */
2952 for (rgn = 0; rgn < nr_regions; rgn++)
2953 schedule_region (rgn);
2955 free(ebb_head);
2957 /* Update life analysis for the subroutine. Do single block regions
2958 first so that we can verify that live_at_start didn't change. Then
2959 do all other blocks. */
2960 /* ??? There is an outside possibility that update_life_info, or more
2961 to the point propagate_block, could get called with nonzero flags
2962 more than once for one basic block. This would be kinda bad if it
2963 were to happen, since REG_INFO would be accumulated twice for the
2964 block, and we'd have twice the REG_DEAD notes.
2966 I'm fairly certain that this _shouldn't_ happen, since I don't think
2967 that live_at_start should change at region heads. Not sure what the
2968 best way to test for this kind of thing... */
2970 if (current_sched_info->flags & DETACH_LIFE_INFO)
2971 /* this flag can be set either by the target or by ENABLE_CHECKING. */
2972 attach_life_info ();
2974 allocate_reg_life_data ();
2976 any_large_regions = 0;
2977 large_region_blocks = sbitmap_alloc (last_basic_block);
2978 sbitmap_zero (large_region_blocks);
2979 FOR_EACH_BB (bb)
2980 SET_BIT (large_region_blocks, bb->index);
2982 blocks = sbitmap_alloc (last_basic_block);
2983 sbitmap_zero (blocks);
2985 /* Update life information. For regions consisting of multiple blocks
2986 we've possibly done interblock scheduling that affects global liveness.
2987 For regions consisting of single blocks we need to do only local
2988 liveness. */
2989 for (rgn = 0; rgn < nr_regions; rgn++)
2990 if (RGN_NR_BLOCKS (rgn) > 1
2991 /* Or the only block of this region has been split. */
2992 || RGN_HAS_REAL_EBB (rgn)
2993 /* New blocks (e.g. recovery blocks) should be processed
2994 as parts of large regions. */
2995 || !glat_start[rgn_bb_table[RGN_BLOCKS (rgn)]])
2996 any_large_regions = 1;
2997 else
2999 SET_BIT (blocks, rgn_bb_table[RGN_BLOCKS (rgn)]);
3000 RESET_BIT (large_region_blocks, rgn_bb_table[RGN_BLOCKS (rgn)]);
3003 /* Don't update reg info after reload, since that affects
3004 regs_ever_live, which should not change after reload. */
3005 update_life_info (blocks, UPDATE_LIFE_LOCAL,
3006 (reload_completed ? PROP_DEATH_NOTES
3007 : (PROP_DEATH_NOTES | PROP_REG_INFO)));
3008 if (any_large_regions)
3010 update_life_info (large_region_blocks, UPDATE_LIFE_GLOBAL,
3011 (reload_completed ? PROP_DEATH_NOTES
3012 : (PROP_DEATH_NOTES | PROP_REG_INFO)));
3014 #ifdef ENABLE_CHECKING
3015 check_reg_live (true);
3016 #endif
3019 if (CHECK_DEAD_NOTES)
3021 /* Verify the counts of basic block notes in single basic block
3022 regions. */
3023 for (rgn = 0; rgn < nr_regions; rgn++)
3024 if (RGN_NR_BLOCKS (rgn) == 1)
3026 sbitmap_zero (blocks);
3027 SET_BIT (blocks, rgn_bb_table[RGN_BLOCKS (rgn)]);
3029 gcc_assert (deaths_in_region[rgn]
3030 == count_or_remove_death_notes (blocks, 0));
3032 free (deaths_in_region);
3035 /* Reposition the prologue and epilogue notes in case we moved the
3036 prologue/epilogue insns. */
3037 if (reload_completed)
3038 reposition_prologue_and_epilogue_notes (get_insns ());
3040 if (sched_verbose)
3042 if (reload_completed == 0 && flag_schedule_interblock)
3044 fprintf (sched_dump,
3045 "\n;; Procedure interblock/speculative motions == %d/%d \n",
3046 nr_inter, nr_spec);
3048 else
3049 gcc_assert (nr_inter <= 0);
3050 fprintf (sched_dump, "\n\n");
3053 /* Clean up. */
3054 free (rgn_table);
3055 free (rgn_bb_table);
3056 free (block_to_bb);
3057 free (containing_rgn);
3059 sched_finish ();
3061 sbitmap_free (blocks);
3062 sbitmap_free (large_region_blocks);
3065 /* INSN has been added to/removed from current region. */
3066 static void
3067 add_remove_insn (rtx insn, int remove_p)
3069 if (!remove_p)
3070 rgn_n_insns++;
3071 else
3072 rgn_n_insns--;
3074 if (INSN_BB (insn) == target_bb)
3076 if (!remove_p)
3077 target_n_insns++;
3078 else
3079 target_n_insns--;
3083 /* Extend internal data structures. */
3084 static void
3085 extend_regions (void)
3087 rgn_table = XRESIZEVEC (region, rgn_table, n_basic_blocks);
3088 rgn_bb_table = XRESIZEVEC (int, rgn_bb_table, n_basic_blocks);
3089 block_to_bb = XRESIZEVEC (int, block_to_bb, last_basic_block);
3090 containing_rgn = XRESIZEVEC (int, containing_rgn, last_basic_block);
3093 /* BB was added to ebb after AFTER. */
3094 static void
3095 add_block1 (basic_block bb, basic_block after)
3097 extend_regions ();
3099 if (after == 0 || after == EXIT_BLOCK_PTR)
3101 int i;
3103 i = RGN_BLOCKS (nr_regions);
3104 /* I - first free position in rgn_bb_table. */
3106 rgn_bb_table[i] = bb->index;
3107 RGN_NR_BLOCKS (nr_regions) = 1;
3108 RGN_DONT_CALC_DEPS (nr_regions) = after == EXIT_BLOCK_PTR;
3109 RGN_HAS_REAL_EBB (nr_regions) = 0;
3110 CONTAINING_RGN (bb->index) = nr_regions;
3111 BLOCK_TO_BB (bb->index) = 0;
3113 nr_regions++;
3115 RGN_BLOCKS (nr_regions) = i + 1;
3117 if (CHECK_DEAD_NOTES)
3119 sbitmap blocks = sbitmap_alloc (last_basic_block);
3120 deaths_in_region = xrealloc (deaths_in_region, nr_regions *
3121 sizeof (*deaths_in_region));
3123 check_dead_notes1 (nr_regions - 1, blocks);
3125 sbitmap_free (blocks);
3128 else
3130 int i, pos;
3132 /* We need to fix rgn_table, block_to_bb, containing_rgn
3133 and ebb_head. */
3135 BLOCK_TO_BB (bb->index) = BLOCK_TO_BB (after->index);
3137 /* We extend ebb_head to one more position to
3138 easily find the last position of the last ebb in
3139 the current region. Thus, ebb_head[BLOCK_TO_BB (after) + 1]
3140 is _always_ valid for access. */
3142 i = BLOCK_TO_BB (after->index) + 1;
3143 pos = ebb_head[i] - 1;
3144 /* Now POS is the index of the last block in the region. */
3146 /* Find index of basic block AFTER. */
3147 for (; rgn_bb_table[pos] != after->index; pos--);
3149 pos++;
3150 gcc_assert (pos > ebb_head[i - 1]);
3152 /* i - ebb right after "AFTER". */
3153 /* ebb_head[i] - VALID. */
3155 /* Source position: ebb_head[i]
3156 Destination position: ebb_head[i] + 1
3157 Last position:
3158 RGN_BLOCKS (nr_regions) - 1
3159 Number of elements to copy: (last_position) - (source_position) + 1
3162 memmove (rgn_bb_table + pos + 1,
3163 rgn_bb_table + pos,
3164 ((RGN_BLOCKS (nr_regions) - 1) - (pos) + 1)
3165 * sizeof (*rgn_bb_table));
3167 rgn_bb_table[pos] = bb->index;
3169 for (; i <= current_nr_blocks; i++)
3170 ebb_head [i]++;
3172 i = CONTAINING_RGN (after->index);
3173 CONTAINING_RGN (bb->index) = i;
3175 RGN_HAS_REAL_EBB (i) = 1;
3177 for (++i; i <= nr_regions; i++)
3178 RGN_BLOCKS (i)++;
3180 /* We don't need to call check_dead_notes1 () because this new block
3181 is just a split of the old. We don't want to count anything twice. */
3185 /* Fix internal data after interblock movement of jump instruction.
3186 For parameter meaning please refer to
3187 sched-int.h: struct sched_info: fix_recovery_cfg. */
3188 static void
3189 fix_recovery_cfg (int bbi, int check_bbi, int check_bb_nexti)
3191 int old_pos, new_pos, i;
3193 BLOCK_TO_BB (check_bb_nexti) = BLOCK_TO_BB (bbi);
3195 for (old_pos = ebb_head[BLOCK_TO_BB (check_bbi) + 1] - 1;
3196 rgn_bb_table[old_pos] != check_bb_nexti;
3197 old_pos--);
3198 gcc_assert (old_pos > ebb_head[BLOCK_TO_BB (check_bbi)]);
3200 for (new_pos = ebb_head[BLOCK_TO_BB (bbi) + 1] - 1;
3201 rgn_bb_table[new_pos] != bbi;
3202 new_pos--);
3203 new_pos++;
3204 gcc_assert (new_pos > ebb_head[BLOCK_TO_BB (bbi)]);
3206 gcc_assert (new_pos < old_pos);
3208 memmove (rgn_bb_table + new_pos + 1,
3209 rgn_bb_table + new_pos,
3210 (old_pos - new_pos) * sizeof (*rgn_bb_table));
3212 rgn_bb_table[new_pos] = check_bb_nexti;
3214 for (i = BLOCK_TO_BB (bbi) + 1; i <= BLOCK_TO_BB (check_bbi); i++)
3215 ebb_head[i]++;
3218 /* Return next block in ebb chain. For parameter meaning please refer to
3219 sched-int.h: struct sched_info: advance_target_bb. */
3220 static basic_block
3221 advance_target_bb (basic_block bb, rtx insn)
3223 if (insn)
3224 return 0;
3226 gcc_assert (BLOCK_TO_BB (bb->index) == target_bb
3227 && BLOCK_TO_BB (bb->next_bb->index) == target_bb);
3228 return bb->next_bb;
3231 /* Count and remove death notes in region RGN, which consists of blocks
3232 with indecies in BLOCKS. */
3233 static void
3234 check_dead_notes1 (int rgn, sbitmap blocks)
3236 int b;
3238 sbitmap_zero (blocks);
3239 for (b = RGN_NR_BLOCKS (rgn) - 1; b >= 0; --b)
3240 SET_BIT (blocks, rgn_bb_table[RGN_BLOCKS (rgn) + b]);
3242 deaths_in_region[rgn] = count_or_remove_death_notes (blocks, 1);
3245 #ifdef ENABLE_CHECKING
3246 /* Return non zero, if BB is head or leaf (depending of LEAF_P) block in
3247 current region. For more information please refer to
3248 sched-int.h: struct sched_info: region_head_or_leaf_p. */
3249 static int
3250 region_head_or_leaf_p (basic_block bb, int leaf_p)
3252 if (!leaf_p)
3253 return bb->index == rgn_bb_table[RGN_BLOCKS (CONTAINING_RGN (bb->index))];
3254 else
3256 int i;
3257 edge e;
3258 edge_iterator ei;
3260 i = CONTAINING_RGN (bb->index);
3262 FOR_EACH_EDGE (e, ei, bb->succs)
3263 if (e->dest != EXIT_BLOCK_PTR
3264 && CONTAINING_RGN (e->dest->index) == i
3265 /* except self-loop. */
3266 && e->dest != bb)
3267 return 0;
3269 return 1;
3272 #endif /* ENABLE_CHECKING */
3274 #endif
3276 static bool
3277 gate_handle_sched (void)
3279 #ifdef INSN_SCHEDULING
3280 return flag_schedule_insns;
3281 #else
3282 return 0;
3283 #endif
3286 /* Run instruction scheduler. */
3287 static unsigned int
3288 rest_of_handle_sched (void)
3290 #ifdef INSN_SCHEDULING
3291 /* Do control and data sched analysis,
3292 and write some of the results to dump file. */
3294 schedule_insns ();
3295 #endif
3296 return 0;
3299 static bool
3300 gate_handle_sched2 (void)
3302 #ifdef INSN_SCHEDULING
3303 return optimize > 0 && flag_schedule_insns_after_reload;
3304 #else
3305 return 0;
3306 #endif
3309 /* Run second scheduling pass after reload. */
3310 static unsigned int
3311 rest_of_handle_sched2 (void)
3313 #ifdef INSN_SCHEDULING
3314 /* Do control and data sched analysis again,
3315 and write some more of the results to dump file. */
3317 split_all_insns (1);
3319 if (flag_sched2_use_superblocks || flag_sched2_use_traces)
3321 schedule_ebbs ();
3322 /* No liveness updating code yet, but it should be easy to do.
3323 reg-stack recomputes the liveness when needed for now. */
3324 count_or_remove_death_notes (NULL, 1);
3325 cleanup_cfg (CLEANUP_EXPENSIVE);
3327 else
3328 schedule_insns ();
3329 #endif
3330 return 0;
3333 struct tree_opt_pass pass_sched =
3335 "sched1", /* name */
3336 gate_handle_sched, /* gate */
3337 rest_of_handle_sched, /* execute */
3338 NULL, /* sub */
3339 NULL, /* next */
3340 0, /* static_pass_number */
3341 TV_SCHED, /* tv_id */
3342 0, /* properties_required */
3343 0, /* properties_provided */
3344 0, /* properties_destroyed */
3345 0, /* todo_flags_start */
3346 TODO_dump_func |
3347 TODO_ggc_collect, /* todo_flags_finish */
3348 'S' /* letter */
3351 struct tree_opt_pass pass_sched2 =
3353 "sched2", /* name */
3354 gate_handle_sched2, /* gate */
3355 rest_of_handle_sched2, /* execute */
3356 NULL, /* sub */
3357 NULL, /* next */
3358 0, /* static_pass_number */
3359 TV_SCHED2, /* tv_id */
3360 0, /* properties_required */
3361 0, /* properties_provided */
3362 0, /* properties_destroyed */
3363 0, /* todo_flags_start */
3364 TODO_dump_func |
3365 TODO_ggc_collect, /* todo_flags_finish */
3366 'R' /* letter */