OSDN Git Service

2007-08-04 Andrew Pinski <andrew_pinski@playstation.sony.com>
[pf3gnuchains/gcc-fork.git] / gcc / sched-rgn.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2006, 2007
4    Free Software Foundation, Inc.
5    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
6    and currently maintained by, Jim Wilson (wilson@cygnus.com)
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
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.
27
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.
31
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.
37
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.  */
47 \f
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"
70 #include "dbgcnt.h"
71
72 #ifdef INSN_SCHEDULING
73 /* Some accessor macros for h_i_d members only used within this file.  */
74 #define INSN_REF_COUNT(INSN)    (h_i_d[INSN_UID (INSN)].ref_count)
75 #define FED_BY_SPEC_LOAD(insn)  (h_i_d[INSN_UID (insn)].fed_by_spec_load)
76 #define IS_LOAD_INSN(insn)      (h_i_d[INSN_UID (insn)].is_load_insn)
77
78 /* nr_inter/spec counts interblock/speculative motion for the function.  */
79 static int nr_inter, nr_spec;
80
81 static int is_cfg_nonregular (void);
82 static bool sched_is_disabled_for_current_region_p (void);
83
84 /* A region is the main entity for interblock scheduling: insns
85    are allowed to move between blocks in the same region, along
86    control flow graph edges, in the 'up' direction.  */
87 typedef struct
88 {
89   /* Number of extended basic blocks in region.  */
90   int rgn_nr_blocks;
91   /* cblocks in the region (actually index in rgn_bb_table).  */
92   int rgn_blocks;
93   /* Dependencies for this region are already computed.  Basically, indicates,
94      that this is a recovery block.  */
95   unsigned int dont_calc_deps : 1;
96   /* This region has at least one non-trivial ebb.  */
97   unsigned int has_real_ebb : 1;
98 }
99 region;
100
101 /* Number of regions in the procedure.  */
102 static int nr_regions;
103
104 /* Table of region descriptions.  */
105 static region *rgn_table;
106
107 /* Array of lists of regions' blocks.  */
108 static int *rgn_bb_table;
109
110 /* Topological order of blocks in the region (if b2 is reachable from
111    b1, block_to_bb[b2] > block_to_bb[b1]).  Note: A basic block is
112    always referred to by either block or b, while its topological
113    order name (in the region) is referred to by bb.  */
114 static int *block_to_bb;
115
116 /* The number of the region containing a block.  */
117 static int *containing_rgn;
118
119 /* The minimum probability of reaching a source block so that it will be
120    considered for speculative scheduling.  */
121 static int min_spec_prob;
122
123 #define RGN_NR_BLOCKS(rgn) (rgn_table[rgn].rgn_nr_blocks)
124 #define RGN_BLOCKS(rgn) (rgn_table[rgn].rgn_blocks)
125 #define RGN_DONT_CALC_DEPS(rgn) (rgn_table[rgn].dont_calc_deps)
126 #define RGN_HAS_REAL_EBB(rgn) (rgn_table[rgn].has_real_ebb)
127 #define BLOCK_TO_BB(block) (block_to_bb[block])
128 #define CONTAINING_RGN(block) (containing_rgn[block])
129
130 void debug_regions (void);
131 static void find_single_block_region (void);
132 static void find_rgns (void);
133 static void extend_rgns (int *, int *, sbitmap, int *);
134 static bool too_large (int, int *, int *);
135
136 extern void debug_live (int, int);
137
138 /* Blocks of the current region being scheduled.  */
139 static int current_nr_blocks;
140 static int current_blocks;
141
142 static int rgn_n_insns;
143
144 /* The mapping from ebb to block.  */
145 /* ebb_head [i] - is index in rgn_bb_table, while
146    EBB_HEAD (i) - is basic block index.
147    BASIC_BLOCK (EBB_HEAD (i)) - head of ebb.  */
148 #define BB_TO_BLOCK(ebb) (rgn_bb_table[ebb_head[ebb]])
149 #define EBB_FIRST_BB(ebb) BASIC_BLOCK (BB_TO_BLOCK (ebb))
150 #define EBB_LAST_BB(ebb) BASIC_BLOCK (rgn_bb_table[ebb_head[ebb + 1] - 1])
151
152 /* Target info declarations.
153
154    The block currently being scheduled is referred to as the "target" block,
155    while other blocks in the region from which insns can be moved to the
156    target are called "source" blocks.  The candidate structure holds info
157    about such sources: are they valid?  Speculative?  Etc.  */
158 typedef struct
159 {
160   basic_block *first_member;
161   int nr_members;
162 }
163 bblst;
164
165 typedef struct
166 {
167   char is_valid;
168   char is_speculative;
169   int src_prob;
170   bblst split_bbs;
171   bblst update_bbs;
172 }
173 candidate;
174
175 static candidate *candidate_table;
176
177 /* A speculative motion requires checking live information on the path
178    from 'source' to 'target'.  The split blocks are those to be checked.
179    After a speculative motion, live information should be modified in
180    the 'update' blocks.
181
182    Lists of split and update blocks for each candidate of the current
183    target are in array bblst_table.  */
184 static basic_block *bblst_table;
185 static int bblst_size, bblst_last;
186
187 #define IS_VALID(src) ( candidate_table[src].is_valid )
188 #define IS_SPECULATIVE(src) ( candidate_table[src].is_speculative )
189 #define SRC_PROB(src) ( candidate_table[src].src_prob )
190
191 /* The bb being currently scheduled.  */
192 static int target_bb;
193
194 /* List of edges.  */
195 typedef struct
196 {
197   edge *first_member;
198   int nr_members;
199 }
200 edgelst;
201
202 static edge *edgelst_table;
203 static int edgelst_last;
204
205 static void extract_edgelst (sbitmap, edgelst *);
206
207
208 /* Target info functions.  */
209 static void split_edges (int, int, edgelst *);
210 static void compute_trg_info (int);
211 void debug_candidate (int);
212 void debug_candidates (int);
213
214 /* Dominators array: dom[i] contains the sbitmap of dominators of
215    bb i in the region.  */
216 static sbitmap *dom;
217
218 /* bb 0 is the only region entry.  */
219 #define IS_RGN_ENTRY(bb) (!bb)
220
221 /* Is bb_src dominated by bb_trg.  */
222 #define IS_DOMINATED(bb_src, bb_trg)                                 \
223 ( TEST_BIT (dom[bb_src], bb_trg) )
224
225 /* Probability: Prob[i] is an int in [0, REG_BR_PROB_BASE] which is
226    the probability of bb i relative to the region entry.  */
227 static int *prob;
228
229 /* Bit-set of edges, where bit i stands for edge i.  */
230 typedef sbitmap edgeset;
231
232 /* Number of edges in the region.  */
233 static int rgn_nr_edges;
234
235 /* Array of size rgn_nr_edges.  */
236 static edge *rgn_edges;
237
238 /* Mapping from each edge in the graph to its number in the rgn.  */
239 #define EDGE_TO_BIT(edge) ((int)(size_t)(edge)->aux)
240 #define SET_EDGE_TO_BIT(edge,nr) ((edge)->aux = (void *)(size_t)(nr))
241
242 /* The split edges of a source bb is different for each target
243    bb.  In order to compute this efficiently, the 'potential-split edges'
244    are computed for each bb prior to scheduling a region.  This is actually
245    the split edges of each bb relative to the region entry.
246
247    pot_split[bb] is the set of potential split edges of bb.  */
248 static edgeset *pot_split;
249
250 /* For every bb, a set of its ancestor edges.  */
251 static edgeset *ancestor_edges;
252
253 /* Array of EBBs sizes.  Currently we can get a ebb only through 
254    splitting of currently scheduling block, therefore, we don't need
255    ebb_head array for every region, its sufficient to hold it only
256    for current one.  */
257 static int *ebb_head;
258
259 static void compute_dom_prob_ps (int);
260
261 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (BLOCK_NUM (INSN))))
262 #define IS_SPECULATIVE_INSN(INSN) (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
263 #define INSN_BB(INSN) (BLOCK_TO_BB (BLOCK_NUM (INSN)))
264
265 /* Speculative scheduling functions.  */
266 static int check_live_1 (int, rtx);
267 static void update_live_1 (int, rtx);
268 static int check_live (rtx, int);
269 static void update_live (rtx, int);
270 static void set_spec_fed (rtx);
271 static int is_pfree (rtx, int, int);
272 static int find_conditional_protection (rtx, int);
273 static int is_conditionally_protected (rtx, int, int);
274 static int is_prisky (rtx, int, int);
275 static int is_exception_free (rtx, int, int);
276
277 static bool sets_likely_spilled (rtx);
278 static void sets_likely_spilled_1 (rtx, const_rtx, void *);
279 static void add_branch_dependences (rtx, rtx);
280 static void compute_block_backward_dependences (int);
281
282 static void init_regions (void);
283 static void schedule_region (int);
284 static rtx concat_INSN_LIST (rtx, rtx);
285 static void concat_insn_mem_list (rtx, rtx, rtx *, rtx *);
286 static void propagate_deps (int, struct deps *);
287 static void free_pending_lists (void);
288
289 /* Functions for construction of the control flow graph.  */
290
291 /* Return 1 if control flow graph should not be constructed, 0 otherwise.
292
293    We decide not to build the control flow graph if there is possibly more
294    than one entry to the function, if computed branches exist, if we
295    have nonlocal gotos, or if we have an unreachable loop.  */
296
297 static int
298 is_cfg_nonregular (void)
299 {
300   basic_block b;
301   rtx insn;
302
303   /* If we have a label that could be the target of a nonlocal goto, then
304      the cfg is not well structured.  */
305   if (nonlocal_goto_handler_labels)
306     return 1;
307
308   /* If we have any forced labels, then the cfg is not well structured.  */
309   if (forced_labels)
310     return 1;
311
312   /* If we have exception handlers, then we consider the cfg not well
313      structured.  ?!?  We should be able to handle this now that we
314      compute an accurate cfg for EH.  */
315   if (current_function_has_exception_handlers ())
316     return 1;
317
318   /* If we have non-jumping insns which refer to labels, then we consider
319      the cfg not well structured.  */
320   FOR_EACH_BB (b)
321     FOR_BB_INSNS (b, insn)
322       {
323         /* Check for labels referred by non-jump insns.  */
324         if (NONJUMP_INSN_P (insn) || CALL_P (insn))
325           {
326             rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
327             if (note
328                 && ! (JUMP_P (NEXT_INSN (insn))
329                       && find_reg_note (NEXT_INSN (insn), REG_LABEL,
330                                         XEXP (note, 0))))
331               return 1;
332           }
333         /* If this function has a computed jump, then we consider the cfg
334            not well structured.  */
335         else if (JUMP_P (insn) && computed_jump_p (insn))
336           return 1;
337       }
338
339   /* Unreachable loops with more than one basic block are detected
340      during the DFS traversal in find_rgns.
341
342      Unreachable loops with a single block are detected here.  This
343      test is redundant with the one in find_rgns, but it's much
344      cheaper to go ahead and catch the trivial case here.  */
345   FOR_EACH_BB (b)
346     {
347       if (EDGE_COUNT (b->preds) == 0
348           || (single_pred_p (b)
349               && single_pred (b) == b))
350         return 1;
351     }
352
353   /* All the tests passed.  Consider the cfg well structured.  */
354   return 0;
355 }
356
357 /* Extract list of edges from a bitmap containing EDGE_TO_BIT bits.  */
358
359 static void
360 extract_edgelst (sbitmap set, edgelst *el)
361 {
362   unsigned int i = 0;
363   sbitmap_iterator sbi;
364
365   /* edgelst table space is reused in each call to extract_edgelst.  */
366   edgelst_last = 0;
367
368   el->first_member = &edgelst_table[edgelst_last];
369   el->nr_members = 0;
370
371   /* Iterate over each word in the bitset.  */
372   EXECUTE_IF_SET_IN_SBITMAP (set, 0, i, sbi)
373     {
374       edgelst_table[edgelst_last++] = rgn_edges[i];
375       el->nr_members++;
376     }
377 }
378
379 /* Functions for the construction of regions.  */
380
381 /* Print the regions, for debugging purposes.  Callable from debugger.  */
382
383 void
384 debug_regions (void)
385 {
386   int rgn, bb;
387
388   fprintf (sched_dump, "\n;;   ------------ REGIONS ----------\n\n");
389   for (rgn = 0; rgn < nr_regions; rgn++)
390     {
391       fprintf (sched_dump, ";;\trgn %d nr_blocks %d:\n", rgn,
392                rgn_table[rgn].rgn_nr_blocks);
393       fprintf (sched_dump, ";;\tbb/block: ");
394
395       /* We don't have ebb_head initialized yet, so we can't use
396          BB_TO_BLOCK ().  */
397       current_blocks = RGN_BLOCKS (rgn);
398
399       for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
400         fprintf (sched_dump, " %d/%d ", bb, rgn_bb_table[current_blocks + bb]);
401
402       fprintf (sched_dump, "\n\n");
403     }
404 }
405
406 /* Build a single block region for each basic block in the function.
407    This allows for using the same code for interblock and basic block
408    scheduling.  */
409
410 static void
411 find_single_block_region (void)
412 {
413   basic_block bb;
414
415   nr_regions = 0;
416
417   FOR_EACH_BB (bb)
418     {
419       rgn_bb_table[nr_regions] = bb->index;
420       RGN_NR_BLOCKS (nr_regions) = 1;
421       RGN_BLOCKS (nr_regions) = nr_regions;
422       RGN_DONT_CALC_DEPS (nr_regions) = 0;
423       RGN_HAS_REAL_EBB (nr_regions) = 0;
424       CONTAINING_RGN (bb->index) = nr_regions;
425       BLOCK_TO_BB (bb->index) = 0;
426       nr_regions++;
427     }
428 }
429
430 /* Update number of blocks and the estimate for number of insns
431    in the region.  Return true if the region is "too large" for interblock
432    scheduling (compile time considerations).  */
433
434 static bool
435 too_large (int block, int *num_bbs, int *num_insns)
436 {
437   (*num_bbs)++;
438   (*num_insns) += (INSN_LUID (BB_END (BASIC_BLOCK (block)))
439                    - INSN_LUID (BB_HEAD (BASIC_BLOCK (block))));
440
441   return ((*num_bbs > PARAM_VALUE (PARAM_MAX_SCHED_REGION_BLOCKS))
442           || (*num_insns > PARAM_VALUE (PARAM_MAX_SCHED_REGION_INSNS)));
443 }
444
445 /* Update_loop_relations(blk, hdr): Check if the loop headed by max_hdr[blk]
446    is still an inner loop.  Put in max_hdr[blk] the header of the most inner
447    loop containing blk.  */
448 #define UPDATE_LOOP_RELATIONS(blk, hdr)         \
449 {                                               \
450   if (max_hdr[blk] == -1)                       \
451     max_hdr[blk] = hdr;                         \
452   else if (dfs_nr[max_hdr[blk]] > dfs_nr[hdr])  \
453     RESET_BIT (inner, hdr);                     \
454   else if (dfs_nr[max_hdr[blk]] < dfs_nr[hdr])  \
455     {                                           \
456       RESET_BIT (inner,max_hdr[blk]);           \
457       max_hdr[blk] = hdr;                       \
458     }                                           \
459 }
460
461 /* Find regions for interblock scheduling.
462
463    A region for scheduling can be:
464
465      * A loop-free procedure, or
466
467      * A reducible inner loop, or
468
469      * A basic block not contained in any other region.
470
471    ?!? In theory we could build other regions based on extended basic
472    blocks or reverse extended basic blocks.  Is it worth the trouble?
473
474    Loop blocks that form a region are put into the region's block list
475    in topological order.
476
477    This procedure stores its results into the following global (ick) variables
478
479      * rgn_nr
480      * rgn_table
481      * rgn_bb_table
482      * block_to_bb
483      * containing region
484
485    We use dominator relationships to avoid making regions out of non-reducible
486    loops.
487
488    This procedure needs to be converted to work on pred/succ lists instead
489    of edge tables.  That would simplify it somewhat.  */
490
491 static void
492 find_rgns (void)
493 {
494   int *max_hdr, *dfs_nr, *degree;
495   char no_loops = 1;
496   int node, child, loop_head, i, head, tail;
497   int count = 0, sp, idx = 0;
498   edge_iterator current_edge;
499   edge_iterator *stack;
500   int num_bbs, num_insns, unreachable;
501   int too_large_failure;
502   basic_block bb;
503
504   /* Note if a block is a natural loop header.  */
505   sbitmap header;
506
507   /* Note if a block is a natural inner loop header.  */
508   sbitmap inner;
509
510   /* Note if a block is in the block queue.  */
511   sbitmap in_queue;
512
513   /* Note if a block is in the block queue.  */
514   sbitmap in_stack;
515
516   /* Perform a DFS traversal of the cfg.  Identify loop headers, inner loops
517      and a mapping from block to its loop header (if the block is contained
518      in a loop, else -1).
519
520      Store results in HEADER, INNER, and MAX_HDR respectively, these will
521      be used as inputs to the second traversal.
522
523      STACK, SP and DFS_NR are only used during the first traversal.  */
524
525   /* Allocate and initialize variables for the first traversal.  */
526   max_hdr = XNEWVEC (int, last_basic_block);
527   dfs_nr = XCNEWVEC (int, last_basic_block);
528   stack = XNEWVEC (edge_iterator, n_edges);
529
530   inner = sbitmap_alloc (last_basic_block);
531   sbitmap_ones (inner);
532
533   header = sbitmap_alloc (last_basic_block);
534   sbitmap_zero (header);
535
536   in_queue = sbitmap_alloc (last_basic_block);
537   sbitmap_zero (in_queue);
538
539   in_stack = sbitmap_alloc (last_basic_block);
540   sbitmap_zero (in_stack);
541
542   for (i = 0; i < last_basic_block; i++)
543     max_hdr[i] = -1;
544
545   #define EDGE_PASSED(E) (ei_end_p ((E)) || ei_edge ((E))->aux)
546   #define SET_EDGE_PASSED(E) (ei_edge ((E))->aux = ei_edge ((E)))
547
548   /* DFS traversal to find inner loops in the cfg.  */
549
550   current_edge = ei_start (single_succ (ENTRY_BLOCK_PTR)->succs);
551   sp = -1;
552
553   while (1)
554     {
555       if (EDGE_PASSED (current_edge))
556         {
557           /* We have reached a leaf node or a node that was already
558              processed.  Pop edges off the stack until we find
559              an edge that has not yet been processed.  */
560           while (sp >= 0 && EDGE_PASSED (current_edge))
561             {
562               /* Pop entry off the stack.  */
563               current_edge = stack[sp--];
564               node = ei_edge (current_edge)->src->index;
565               gcc_assert (node != ENTRY_BLOCK);
566               child = ei_edge (current_edge)->dest->index;
567               gcc_assert (child != EXIT_BLOCK);
568               RESET_BIT (in_stack, child);
569               if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
570                 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
571               ei_next (&current_edge);
572             }
573
574           /* See if have finished the DFS tree traversal.  */
575           if (sp < 0 && EDGE_PASSED (current_edge))
576             break;
577
578           /* Nope, continue the traversal with the popped node.  */
579           continue;
580         }
581
582       /* Process a node.  */
583       node = ei_edge (current_edge)->src->index;
584       gcc_assert (node != ENTRY_BLOCK);
585       SET_BIT (in_stack, node);
586       dfs_nr[node] = ++count;
587
588       /* We don't traverse to the exit block.  */
589       child = ei_edge (current_edge)->dest->index;
590       if (child == EXIT_BLOCK)
591         {
592           SET_EDGE_PASSED (current_edge);
593           ei_next (&current_edge);
594           continue;
595         }
596
597       /* If the successor is in the stack, then we've found a loop.
598          Mark the loop, if it is not a natural loop, then it will
599          be rejected during the second traversal.  */
600       if (TEST_BIT (in_stack, child))
601         {
602           no_loops = 0;
603           SET_BIT (header, child);
604           UPDATE_LOOP_RELATIONS (node, child);
605           SET_EDGE_PASSED (current_edge);
606           ei_next (&current_edge);
607           continue;
608         }
609
610       /* If the child was already visited, then there is no need to visit
611          it again.  Just update the loop relationships and restart
612          with a new edge.  */
613       if (dfs_nr[child])
614         {
615           if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
616             UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
617           SET_EDGE_PASSED (current_edge);
618           ei_next (&current_edge);
619           continue;
620         }
621
622       /* Push an entry on the stack and continue DFS traversal.  */
623       stack[++sp] = current_edge;
624       SET_EDGE_PASSED (current_edge);
625       current_edge = ei_start (ei_edge (current_edge)->dest->succs);
626     }
627
628   /* Reset ->aux field used by EDGE_PASSED.  */
629   FOR_ALL_BB (bb)
630     {
631       edge_iterator ei;
632       edge e;
633       FOR_EACH_EDGE (e, ei, bb->succs)
634         e->aux = NULL;
635     }
636
637
638   /* Another check for unreachable blocks.  The earlier test in
639      is_cfg_nonregular only finds unreachable blocks that do not
640      form a loop.
641
642      The DFS traversal will mark every block that is reachable from
643      the entry node by placing a nonzero value in dfs_nr.  Thus if
644      dfs_nr is zero for any block, then it must be unreachable.  */
645   unreachable = 0;
646   FOR_EACH_BB (bb)
647     if (dfs_nr[bb->index] == 0)
648       {
649         unreachable = 1;
650         break;
651       }
652
653   /* Gross.  To avoid wasting memory, the second pass uses the dfs_nr array
654      to hold degree counts.  */
655   degree = dfs_nr;
656
657   FOR_EACH_BB (bb)
658     degree[bb->index] = EDGE_COUNT (bb->preds);
659
660   /* Do not perform region scheduling if there are any unreachable
661      blocks.  */
662   if (!unreachable)
663     {
664       int *queue, *degree1 = NULL;
665       /* We use EXTENDED_RGN_HEADER as an addition to HEADER and put
666          there basic blocks, which are forced to be region heads.
667          This is done to try to assemble few smaller regions 
668          from a too_large region.  */
669       sbitmap extended_rgn_header = NULL;
670       bool extend_regions_p;
671
672       if (no_loops)
673         SET_BIT (header, 0);
674
675       /* Second traversal:find reducible inner loops and topologically sort
676          block of each region.  */
677
678       queue = XNEWVEC (int, n_basic_blocks);
679       
680       extend_regions_p = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS) > 0;
681       if (extend_regions_p)
682         {
683           degree1 = xmalloc (last_basic_block * sizeof (int));
684           extended_rgn_header = sbitmap_alloc (last_basic_block);
685           sbitmap_zero (extended_rgn_header);
686         }
687
688       /* Find blocks which are inner loop headers.  We still have non-reducible
689          loops to consider at this point.  */
690       FOR_EACH_BB (bb)
691         {
692           if (TEST_BIT (header, bb->index) && TEST_BIT (inner, bb->index))
693             {
694               edge e;
695               edge_iterator ei;
696               basic_block jbb;
697
698               /* Now check that the loop is reducible.  We do this separate
699                  from finding inner loops so that we do not find a reducible
700                  loop which contains an inner non-reducible loop.
701
702                  A simple way to find reducible/natural loops is to verify
703                  that each block in the loop is dominated by the loop
704                  header.
705
706                  If there exists a block that is not dominated by the loop
707                  header, then the block is reachable from outside the loop
708                  and thus the loop is not a natural loop.  */
709               FOR_EACH_BB (jbb)
710                 {
711                   /* First identify blocks in the loop, except for the loop
712                      entry block.  */
713                   if (bb->index == max_hdr[jbb->index] && bb != jbb)
714                     {
715                       /* Now verify that the block is dominated by the loop
716                          header.  */
717                       if (!dominated_by_p (CDI_DOMINATORS, jbb, bb))
718                         break;
719                     }
720                 }
721
722               /* If we exited the loop early, then I is the header of
723                  a non-reducible loop and we should quit processing it
724                  now.  */
725               if (jbb != EXIT_BLOCK_PTR)
726                 continue;
727
728               /* I is a header of an inner loop, or block 0 in a subroutine
729                  with no loops at all.  */
730               head = tail = -1;
731               too_large_failure = 0;
732               loop_head = max_hdr[bb->index];
733
734               if (extend_regions_p)
735                 /* We save degree in case when we meet a too_large region 
736                    and cancel it.  We need a correct degree later when 
737                    calling extend_rgns.  */
738                 memcpy (degree1, degree, last_basic_block * sizeof (int));
739               
740               /* Decrease degree of all I's successors for topological
741                  ordering.  */
742               FOR_EACH_EDGE (e, ei, bb->succs)
743                 if (e->dest != EXIT_BLOCK_PTR)
744                   --degree[e->dest->index];
745
746               /* Estimate # insns, and count # blocks in the region.  */
747               num_bbs = 1;
748               num_insns = (INSN_LUID (BB_END (bb))
749                            - INSN_LUID (BB_HEAD (bb)));
750
751               /* Find all loop latches (blocks with back edges to the loop
752                  header) or all the leaf blocks in the cfg has no loops.
753
754                  Place those blocks into the queue.  */
755               if (no_loops)
756                 {
757                   FOR_EACH_BB (jbb)
758                     /* Leaf nodes have only a single successor which must
759                        be EXIT_BLOCK.  */
760                     if (single_succ_p (jbb)
761                         && single_succ (jbb) == EXIT_BLOCK_PTR)
762                       {
763                         queue[++tail] = jbb->index;
764                         SET_BIT (in_queue, jbb->index);
765
766                         if (too_large (jbb->index, &num_bbs, &num_insns))
767                           {
768                             too_large_failure = 1;
769                             break;
770                           }
771                       }
772                 }
773               else
774                 {
775                   edge e;
776
777                   FOR_EACH_EDGE (e, ei, bb->preds)
778                     {
779                       if (e->src == ENTRY_BLOCK_PTR)
780                         continue;
781
782                       node = e->src->index;
783
784                       if (max_hdr[node] == loop_head && node != bb->index)
785                         {
786                           /* This is a loop latch.  */
787                           queue[++tail] = node;
788                           SET_BIT (in_queue, node);
789
790                           if (too_large (node, &num_bbs, &num_insns))
791                             {
792                               too_large_failure = 1;
793                               break;
794                             }
795                         }
796                     }
797                 }
798
799               /* Now add all the blocks in the loop to the queue.
800
801              We know the loop is a natural loop; however the algorithm
802              above will not always mark certain blocks as being in the
803              loop.  Consider:
804                 node   children
805                  a        b,c
806                  b        c
807                  c        a,d
808                  d        b
809
810              The algorithm in the DFS traversal may not mark B & D as part
811              of the loop (i.e. they will not have max_hdr set to A).
812
813              We know they can not be loop latches (else they would have
814              had max_hdr set since they'd have a backedge to a dominator
815              block).  So we don't need them on the initial queue.
816
817              We know they are part of the loop because they are dominated
818              by the loop header and can be reached by a backwards walk of
819              the edges starting with nodes on the initial queue.
820
821              It is safe and desirable to include those nodes in the
822              loop/scheduling region.  To do so we would need to decrease
823              the degree of a node if it is the target of a backedge
824              within the loop itself as the node is placed in the queue.
825
826              We do not do this because I'm not sure that the actual
827              scheduling code will properly handle this case. ?!? */
828
829               while (head < tail && !too_large_failure)
830                 {
831                   edge e;
832                   child = queue[++head];
833
834                   FOR_EACH_EDGE (e, ei, BASIC_BLOCK (child)->preds)
835                     {
836                       node = e->src->index;
837
838                       /* See discussion above about nodes not marked as in
839                          this loop during the initial DFS traversal.  */
840                       if (e->src == ENTRY_BLOCK_PTR
841                           || max_hdr[node] != loop_head)
842                         {
843                           tail = -1;
844                           break;
845                         }
846                       else if (!TEST_BIT (in_queue, node) && node != bb->index)
847                         {
848                           queue[++tail] = node;
849                           SET_BIT (in_queue, node);
850
851                           if (too_large (node, &num_bbs, &num_insns))
852                             {
853                               too_large_failure = 1;
854                               break;
855                             }
856                         }
857                     }
858                 }
859
860               if (tail >= 0 && !too_large_failure)
861                 {
862                   /* Place the loop header into list of region blocks.  */
863                   degree[bb->index] = -1;
864                   rgn_bb_table[idx] = bb->index;
865                   RGN_NR_BLOCKS (nr_regions) = num_bbs;
866                   RGN_BLOCKS (nr_regions) = idx++;
867                   RGN_DONT_CALC_DEPS (nr_regions) = 0;
868                   RGN_HAS_REAL_EBB (nr_regions) = 0;
869                   CONTAINING_RGN (bb->index) = nr_regions;
870                   BLOCK_TO_BB (bb->index) = count = 0;
871
872                   /* Remove blocks from queue[] when their in degree
873                      becomes zero.  Repeat until no blocks are left on the
874                      list.  This produces a topological list of blocks in
875                      the region.  */
876                   while (tail >= 0)
877                     {
878                       if (head < 0)
879                         head = tail;
880                       child = queue[head];
881                       if (degree[child] == 0)
882                         {
883                           edge e;
884
885                           degree[child] = -1;
886                           rgn_bb_table[idx++] = child;
887                           BLOCK_TO_BB (child) = ++count;
888                           CONTAINING_RGN (child) = nr_regions;
889                           queue[head] = queue[tail--];
890
891                           FOR_EACH_EDGE (e, ei, BASIC_BLOCK (child)->succs)
892                             if (e->dest != EXIT_BLOCK_PTR)
893                               --degree[e->dest->index];
894                         }
895                       else
896                         --head;
897                     }
898                   ++nr_regions;
899                 }
900               else if (extend_regions_p)
901                 {
902                   /* Restore DEGREE.  */
903                   int *t = degree;
904
905                   degree = degree1;
906                   degree1 = t;
907                   
908                   /* And force successors of BB to be region heads.
909                      This may provide several smaller regions instead
910                      of one too_large region.  */
911                   FOR_EACH_EDGE (e, ei, bb->succs)
912                     if (e->dest != EXIT_BLOCK_PTR)
913                       SET_BIT (extended_rgn_header, e->dest->index);
914                 }
915             }
916         }
917       free (queue);
918
919       if (extend_regions_p)
920         {
921           free (degree1);
922           
923           sbitmap_a_or_b (header, header, extended_rgn_header);
924           sbitmap_free (extended_rgn_header);
925  
926           extend_rgns (degree, &idx, header, max_hdr);
927         }
928     }
929
930   /* Any block that did not end up in a region is placed into a region
931      by itself.  */
932   FOR_EACH_BB (bb)
933     if (degree[bb->index] >= 0)
934       {
935         rgn_bb_table[idx] = bb->index;
936         RGN_NR_BLOCKS (nr_regions) = 1;
937         RGN_BLOCKS (nr_regions) = idx++;
938         RGN_DONT_CALC_DEPS (nr_regions) = 0;
939         RGN_HAS_REAL_EBB (nr_regions) = 0;
940         CONTAINING_RGN (bb->index) = nr_regions++;
941         BLOCK_TO_BB (bb->index) = 0;
942       }
943
944   free (max_hdr);
945   free (degree);
946   free (stack);
947   sbitmap_free (header);
948   sbitmap_free (inner);
949   sbitmap_free (in_queue);
950   sbitmap_free (in_stack);
951 }
952
953 static int gather_region_statistics (int **);
954 static void print_region_statistics (int *, int, int *, int);
955
956 /* Calculate the histogram that shows the number of regions having the 
957    given number of basic blocks, and store it in the RSP array.  Return 
958    the size of this array.  */
959 static int
960 gather_region_statistics (int **rsp)
961 {
962   int i, *a = 0, a_sz = 0;
963
964   /* a[i] is the number of regions that have (i + 1) basic blocks.  */
965   for (i = 0; i < nr_regions; i++)
966     {
967       int nr_blocks = RGN_NR_BLOCKS (i);
968
969       gcc_assert (nr_blocks >= 1);
970
971       if (nr_blocks > a_sz)
972         {        
973           a = xrealloc (a, nr_blocks * sizeof (*a));
974           do
975             a[a_sz++] = 0;
976           while (a_sz != nr_blocks);
977         }
978
979       a[nr_blocks - 1]++;
980     }
981
982   *rsp = a;
983   return a_sz;
984 }
985
986 /* Print regions statistics.  S1 and S2 denote the data before and after 
987    calling extend_rgns, respectively.  */
988 static void
989 print_region_statistics (int *s1, int s1_sz, int *s2, int s2_sz)
990 {
991   int i;
992   
993   /* We iterate until s2_sz because extend_rgns does not decrease 
994      the maximal region size.  */
995   for (i = 1; i < s2_sz; i++)
996     {
997       int n1, n2;
998
999       n2 = s2[i];
1000
1001       if (n2 == 0)
1002         continue;
1003
1004       if (i >= s1_sz)
1005         n1 = 0;
1006       else
1007         n1 = s1[i];
1008
1009       fprintf (sched_dump, ";; Region extension statistics: size %d: " \
1010                "was %d + %d more\n", i + 1, n1, n2 - n1);
1011     }
1012 }
1013
1014 /* Extend regions.
1015    DEGREE - Array of incoming edge count, considering only
1016    the edges, that don't have their sources in formed regions yet.
1017    IDXP - pointer to the next available index in rgn_bb_table.
1018    HEADER - set of all region heads.
1019    LOOP_HDR - mapping from block to the containing loop
1020    (two blocks can reside within one region if they have
1021    the same loop header).  */
1022 static void
1023 extend_rgns (int *degree, int *idxp, sbitmap header, int *loop_hdr)
1024 {
1025   int *order, i, rescan = 0, idx = *idxp, iter = 0, max_iter, *max_hdr;
1026   int nblocks = n_basic_blocks - NUM_FIXED_BLOCKS;
1027
1028   max_iter = PARAM_VALUE (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS);
1029
1030   max_hdr = xmalloc (last_basic_block * sizeof (*max_hdr));
1031
1032   order = xmalloc (last_basic_block * sizeof (*order));
1033   post_order_compute (order, false, false);
1034
1035   for (i = nblocks - 1; i >= 0; i--)
1036     {
1037       int bbn = order[i];
1038       if (degree[bbn] >= 0)
1039         {
1040           max_hdr[bbn] = bbn;
1041           rescan = 1;
1042         }
1043       else
1044         /* This block already was processed in find_rgns.  */
1045         max_hdr[bbn] = -1;
1046     }
1047   
1048   /* The idea is to topologically walk through CFG in top-down order.
1049      During the traversal, if all the predecessors of a node are
1050      marked to be in the same region (they all have the same max_hdr),
1051      then current node is also marked to be a part of that region. 
1052      Otherwise the node starts its own region.
1053      CFG should be traversed until no further changes are made.  On each 
1054      iteration the set of the region heads is extended (the set of those 
1055      blocks that have max_hdr[bbi] == bbi).  This set is upper bounded by the 
1056      set of all basic blocks, thus the algorithm is guaranteed to terminate.  */
1057
1058   while (rescan && iter < max_iter)
1059     {
1060       rescan = 0;
1061       
1062       for (i = nblocks - 1; i >= 0; i--)
1063         {
1064           edge e;
1065           edge_iterator ei;
1066           int bbn = order[i];
1067         
1068           if (max_hdr[bbn] != -1 && !TEST_BIT (header, bbn))
1069             {
1070               int hdr = -1;
1071
1072               FOR_EACH_EDGE (e, ei, BASIC_BLOCK (bbn)->preds)
1073                 {
1074                   int predn = e->src->index;
1075
1076                   if (predn != ENTRY_BLOCK
1077                       /* If pred wasn't processed in find_rgns.  */
1078                       && max_hdr[predn] != -1
1079                       /* And pred and bb reside in the same loop.
1080                          (Or out of any loop).  */
1081                       && loop_hdr[bbn] == loop_hdr[predn])
1082                     {
1083                       if (hdr == -1)
1084                         /* Then bb extends the containing region of pred.  */
1085                         hdr = max_hdr[predn];
1086                       else if (hdr != max_hdr[predn])
1087                         /* Too bad, there are at least two predecessors
1088                            that reside in different regions.  Thus, BB should
1089                            begin its own region.  */
1090                         {
1091                           hdr = bbn;
1092                           break;
1093                         }                   
1094                     }
1095                   else
1096                     /* BB starts its own region.  */
1097                     {
1098                       hdr = bbn;
1099                       break;
1100                     }           
1101                 }
1102             
1103               if (hdr == bbn)
1104                 {
1105                   /* If BB start its own region,
1106                      update set of headers with BB.  */
1107                   SET_BIT (header, bbn);
1108                   rescan = 1;
1109                 }
1110               else
1111                 gcc_assert (hdr != -1);     
1112
1113               max_hdr[bbn] = hdr;
1114             }
1115         }
1116
1117       iter++;
1118     }
1119   
1120   /* Statistics were gathered on the SPEC2000 package of tests with
1121      mainline weekly snapshot gcc-4.1-20051015 on ia64.
1122      
1123      Statistics for SPECint:
1124      1 iteration : 1751 cases (38.7%)
1125      2 iterations: 2770 cases (61.3%)
1126      Blocks wrapped in regions by find_rgns without extension: 18295 blocks
1127      Blocks wrapped in regions by 2 iterations in extend_rgns: 23821 blocks
1128      (We don't count single block regions here).
1129      
1130      Statistics for SPECfp:
1131      1 iteration : 621 cases (35.9%)
1132      2 iterations: 1110 cases (64.1%)
1133      Blocks wrapped in regions by find_rgns without extension: 6476 blocks
1134      Blocks wrapped in regions by 2 iterations in extend_rgns: 11155 blocks
1135      (We don't count single block regions here).
1136
1137      By default we do at most 2 iterations.
1138      This can be overridden with max-sched-extend-regions-iters parameter:
1139      0 - disable region extension,
1140      N > 0 - do at most N iterations.  */
1141   
1142   if (sched_verbose && iter != 0)
1143     fprintf (sched_dump, ";; Region extension iterations: %d%s\n", iter,
1144              rescan ? "... failed" : "");
1145     
1146   if (!rescan && iter != 0)
1147     {
1148       int *s1 = NULL, s1_sz = 0;
1149
1150       /* Save the old statistics for later printout.  */
1151       if (sched_verbose >= 6)
1152         s1_sz = gather_region_statistics (&s1);
1153
1154       /* We have succeeded.  Now assemble the regions.  */
1155       for (i = nblocks - 1; i >= 0; i--)
1156         {
1157           int bbn = order[i];
1158
1159           if (max_hdr[bbn] == bbn)
1160             /* BBN is a region head.  */
1161             {
1162               edge e;
1163               edge_iterator ei;
1164               int num_bbs = 0, j, num_insns = 0, large;
1165         
1166               large = too_large (bbn, &num_bbs, &num_insns);
1167
1168               degree[bbn] = -1;
1169               rgn_bb_table[idx] = bbn;
1170               RGN_BLOCKS (nr_regions) = idx++;
1171               RGN_DONT_CALC_DEPS (nr_regions) = 0;
1172               RGN_HAS_REAL_EBB (nr_regions) = 0;
1173               CONTAINING_RGN (bbn) = nr_regions;
1174               BLOCK_TO_BB (bbn) = 0;
1175
1176               FOR_EACH_EDGE (e, ei, BASIC_BLOCK (bbn)->succs)
1177                 if (e->dest != EXIT_BLOCK_PTR)
1178                   degree[e->dest->index]--;
1179
1180               if (!large)
1181                 /* Here we check whether the region is too_large.  */
1182                 for (j = i - 1; j >= 0; j--)
1183                   {
1184                     int succn = order[j];
1185                     if (max_hdr[succn] == bbn)
1186                       {
1187                         if ((large = too_large (succn, &num_bbs, &num_insns)))
1188                           break;
1189                       }
1190                   }
1191
1192               if (large)
1193                 /* If the region is too_large, then wrap every block of
1194                    the region into single block region.
1195                    Here we wrap region head only.  Other blocks are
1196                    processed in the below cycle.  */
1197                 {
1198                   RGN_NR_BLOCKS (nr_regions) = 1;
1199                   nr_regions++;
1200                 }          
1201
1202               num_bbs = 1;
1203
1204               for (j = i - 1; j >= 0; j--)
1205                 {
1206                   int succn = order[j];
1207
1208                   if (max_hdr[succn] == bbn)
1209                     /* This cycle iterates over all basic blocks, that 
1210                        are supposed to be in the region with head BBN,
1211                        and wraps them into that region (or in single
1212                        block region).  */
1213                     {
1214                       gcc_assert (degree[succn] == 0);
1215
1216                       degree[succn] = -1;
1217                       rgn_bb_table[idx] = succn;                 
1218                       BLOCK_TO_BB (succn) = large ? 0 : num_bbs++;
1219                       CONTAINING_RGN (succn) = nr_regions;
1220
1221                       if (large)
1222                         /* Wrap SUCCN into single block region.  */
1223                         {
1224                           RGN_BLOCKS (nr_regions) = idx;
1225                           RGN_NR_BLOCKS (nr_regions) = 1;
1226                           RGN_DONT_CALC_DEPS (nr_regions) = 0;
1227                           RGN_HAS_REAL_EBB (nr_regions) = 0;
1228                           nr_regions++;
1229                         }
1230
1231                       idx++;
1232                                 
1233                       FOR_EACH_EDGE (e, ei, BASIC_BLOCK (succn)->succs)
1234                         if (e->dest != EXIT_BLOCK_PTR)
1235                           degree[e->dest->index]--;
1236                     }
1237                 }
1238
1239               if (!large)
1240                 {
1241                   RGN_NR_BLOCKS (nr_regions) = num_bbs;
1242                   nr_regions++;
1243                 }
1244             }
1245         }
1246
1247       if (sched_verbose >= 6)
1248         {
1249           int *s2, s2_sz;
1250
1251           /* Get the new statistics and print the comparison with the 
1252              one before calling this function.  */
1253           s2_sz = gather_region_statistics (&s2);
1254           print_region_statistics (s1, s1_sz, s2, s2_sz);
1255           free (s1);
1256           free (s2);
1257         }
1258     }
1259   
1260   free (order);
1261   free (max_hdr);
1262
1263   *idxp = idx; 
1264 }
1265
1266 /* Functions for regions scheduling information.  */
1267
1268 /* Compute dominators, probability, and potential-split-edges of bb.
1269    Assume that these values were already computed for bb's predecessors.  */
1270
1271 static void
1272 compute_dom_prob_ps (int bb)
1273 {
1274   edge_iterator in_ei;
1275   edge in_edge;
1276
1277   /* We shouldn't have any real ebbs yet.  */
1278   gcc_assert (ebb_head [bb] == bb + current_blocks);
1279   
1280   if (IS_RGN_ENTRY (bb))
1281     {
1282       SET_BIT (dom[bb], 0);
1283       prob[bb] = REG_BR_PROB_BASE;
1284       return;
1285     }
1286
1287   prob[bb] = 0;
1288
1289   /* Initialize dom[bb] to '111..1'.  */
1290   sbitmap_ones (dom[bb]);
1291
1292   FOR_EACH_EDGE (in_edge, in_ei, BASIC_BLOCK (BB_TO_BLOCK (bb))->preds)
1293     {
1294       int pred_bb;
1295       edge out_edge;
1296       edge_iterator out_ei;
1297
1298       if (in_edge->src == ENTRY_BLOCK_PTR)
1299         continue;
1300
1301       pred_bb = BLOCK_TO_BB (in_edge->src->index);
1302       sbitmap_a_and_b (dom[bb], dom[bb], dom[pred_bb]);
1303       sbitmap_a_or_b (ancestor_edges[bb],
1304                       ancestor_edges[bb], ancestor_edges[pred_bb]);
1305
1306       SET_BIT (ancestor_edges[bb], EDGE_TO_BIT (in_edge));
1307
1308       sbitmap_a_or_b (pot_split[bb], pot_split[bb], pot_split[pred_bb]);
1309
1310       FOR_EACH_EDGE (out_edge, out_ei, in_edge->src->succs)
1311         SET_BIT (pot_split[bb], EDGE_TO_BIT (out_edge));
1312
1313       prob[bb] += ((prob[pred_bb] * in_edge->probability) / REG_BR_PROB_BASE);
1314     }
1315
1316   SET_BIT (dom[bb], bb);
1317   sbitmap_difference (pot_split[bb], pot_split[bb], ancestor_edges[bb]);
1318
1319   if (sched_verbose >= 2)
1320     fprintf (sched_dump, ";;  bb_prob(%d, %d) = %3d\n", bb, BB_TO_BLOCK (bb),
1321              (100 * prob[bb]) / REG_BR_PROB_BASE);
1322 }
1323
1324 /* Functions for target info.  */
1325
1326 /* Compute in BL the list of split-edges of bb_src relatively to bb_trg.
1327    Note that bb_trg dominates bb_src.  */
1328
1329 static void
1330 split_edges (int bb_src, int bb_trg, edgelst *bl)
1331 {
1332   sbitmap src = sbitmap_alloc (pot_split[bb_src]->n_bits);
1333   sbitmap_copy (src, pot_split[bb_src]);
1334
1335   sbitmap_difference (src, src, pot_split[bb_trg]);
1336   extract_edgelst (src, bl);
1337   sbitmap_free (src);
1338 }
1339
1340 /* Find the valid candidate-source-blocks for the target block TRG, compute
1341    their probability, and check if they are speculative or not.
1342    For speculative sources, compute their update-blocks and split-blocks.  */
1343
1344 static void
1345 compute_trg_info (int trg)
1346 {
1347   candidate *sp;
1348   edgelst el;
1349   int i, j, k, update_idx;
1350   basic_block block;
1351   sbitmap visited;
1352   edge_iterator ei;
1353   edge e;
1354
1355   /* Define some of the fields for the target bb as well.  */
1356   sp = candidate_table + trg;
1357   sp->is_valid = 1;
1358   sp->is_speculative = 0;
1359   sp->src_prob = REG_BR_PROB_BASE;
1360
1361   visited = sbitmap_alloc (last_basic_block);
1362
1363   for (i = trg + 1; i < current_nr_blocks; i++)
1364     {
1365       sp = candidate_table + i;
1366
1367       sp->is_valid = IS_DOMINATED (i, trg);
1368       if (sp->is_valid)
1369         {
1370           int tf = prob[trg], cf = prob[i];
1371
1372           /* In CFGs with low probability edges TF can possibly be zero.  */
1373           sp->src_prob = (tf ? ((cf * REG_BR_PROB_BASE) / tf) : 0);
1374           sp->is_valid = (sp->src_prob >= min_spec_prob);
1375         }
1376
1377       if (sp->is_valid)
1378         {
1379           split_edges (i, trg, &el);
1380           sp->is_speculative = (el.nr_members) ? 1 : 0;
1381           if (sp->is_speculative && !flag_schedule_speculative)
1382             sp->is_valid = 0;
1383         }
1384
1385       if (sp->is_valid)
1386         {
1387           /* Compute split blocks and store them in bblst_table.
1388              The TO block of every split edge is a split block.  */
1389           sp->split_bbs.first_member = &bblst_table[bblst_last];
1390           sp->split_bbs.nr_members = el.nr_members;
1391           for (j = 0; j < el.nr_members; bblst_last++, j++)
1392             bblst_table[bblst_last] = el.first_member[j]->dest;
1393           sp->update_bbs.first_member = &bblst_table[bblst_last];
1394
1395           /* Compute update blocks and store them in bblst_table.
1396              For every split edge, look at the FROM block, and check
1397              all out edges.  For each out edge that is not a split edge,
1398              add the TO block to the update block list.  This list can end
1399              up with a lot of duplicates.  We need to weed them out to avoid
1400              overrunning the end of the bblst_table.  */
1401
1402           update_idx = 0;
1403           sbitmap_zero (visited);
1404           for (j = 0; j < el.nr_members; j++)
1405             {
1406               block = el.first_member[j]->src;
1407               FOR_EACH_EDGE (e, ei, block->succs)
1408                 {
1409                   if (!TEST_BIT (visited, e->dest->index))
1410                     {
1411                       for (k = 0; k < el.nr_members; k++)
1412                         if (e == el.first_member[k])
1413                           break;
1414
1415                       if (k >= el.nr_members)
1416                         {
1417                           bblst_table[bblst_last++] = e->dest;
1418                           SET_BIT (visited, e->dest->index);
1419                           update_idx++;
1420                         }
1421                     }
1422                 }
1423             }
1424           sp->update_bbs.nr_members = update_idx;
1425
1426           /* Make sure we didn't overrun the end of bblst_table.  */
1427           gcc_assert (bblst_last <= bblst_size);
1428         }
1429       else
1430         {
1431           sp->split_bbs.nr_members = sp->update_bbs.nr_members = 0;
1432
1433           sp->is_speculative = 0;
1434           sp->src_prob = 0;
1435         }
1436     }
1437
1438   sbitmap_free (visited);
1439 }
1440
1441 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
1442
1443 void
1444 debug_candidate (int i)
1445 {
1446   if (!candidate_table[i].is_valid)
1447     return;
1448
1449   if (candidate_table[i].is_speculative)
1450     {
1451       int j;
1452       fprintf (sched_dump, "src b %d bb %d speculative \n", BB_TO_BLOCK (i), i);
1453
1454       fprintf (sched_dump, "split path: ");
1455       for (j = 0; j < candidate_table[i].split_bbs.nr_members; j++)
1456         {
1457           int b = candidate_table[i].split_bbs.first_member[j]->index;
1458
1459           fprintf (sched_dump, " %d ", b);
1460         }
1461       fprintf (sched_dump, "\n");
1462
1463       fprintf (sched_dump, "update path: ");
1464       for (j = 0; j < candidate_table[i].update_bbs.nr_members; j++)
1465         {
1466           int b = candidate_table[i].update_bbs.first_member[j]->index;
1467
1468           fprintf (sched_dump, " %d ", b);
1469         }
1470       fprintf (sched_dump, "\n");
1471     }
1472   else
1473     {
1474       fprintf (sched_dump, " src %d equivalent\n", BB_TO_BLOCK (i));
1475     }
1476 }
1477
1478 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
1479
1480 void
1481 debug_candidates (int trg)
1482 {
1483   int i;
1484
1485   fprintf (sched_dump, "----------- candidate table: target: b=%d bb=%d ---\n",
1486            BB_TO_BLOCK (trg), trg);
1487   for (i = trg + 1; i < current_nr_blocks; i++)
1488     debug_candidate (i);
1489 }
1490
1491 /* Functions for speculative scheduling.  */
1492
1493 static bitmap_head not_in_df;
1494
1495 /* Return 0 if x is a set of a register alive in the beginning of one
1496    of the split-blocks of src, otherwise return 1.  */
1497
1498 static int
1499 check_live_1 (int src, rtx x)
1500 {
1501   int i;
1502   int regno;
1503   rtx reg = SET_DEST (x);
1504
1505   if (reg == 0)
1506     return 1;
1507
1508   while (GET_CODE (reg) == SUBREG
1509          || GET_CODE (reg) == ZERO_EXTRACT
1510          || GET_CODE (reg) == STRICT_LOW_PART)
1511     reg = XEXP (reg, 0);
1512
1513   if (GET_CODE (reg) == PARALLEL)
1514     {
1515       int i;
1516
1517       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1518         if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1519           if (check_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0)))
1520             return 1;
1521
1522       return 0;
1523     }
1524
1525   if (!REG_P (reg))
1526     return 1;
1527
1528   regno = REGNO (reg);
1529
1530   if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
1531     {
1532       /* Global registers are assumed live.  */
1533       return 0;
1534     }
1535   else
1536     {
1537       if (regno < FIRST_PSEUDO_REGISTER)
1538         {
1539           /* Check for hard registers.  */
1540           int j = hard_regno_nregs[regno][GET_MODE (reg)];
1541           while (--j >= 0)
1542             {
1543               for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1544                 {
1545                   basic_block b = candidate_table[src].split_bbs.first_member[i];
1546                   int t = bitmap_bit_p (&not_in_df, b->index);
1547
1548                   /* We can have split blocks, that were recently generated.
1549                      such blocks are always outside current region.  */
1550                   gcc_assert (!t || (CONTAINING_RGN (b->index)
1551                                      != CONTAINING_RGN (BB_TO_BLOCK (src))));
1552
1553                   if (t || REGNO_REG_SET_P (df_get_live_in (b), regno + j))
1554                     return 0;
1555                 }
1556             }
1557         }
1558       else
1559         {
1560           /* Check for pseudo registers.  */
1561           for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
1562             {
1563               basic_block b = candidate_table[src].split_bbs.first_member[i];
1564               int t = bitmap_bit_p (&not_in_df, b->index);
1565
1566               gcc_assert (!t || (CONTAINING_RGN (b->index)
1567                                  != CONTAINING_RGN (BB_TO_BLOCK (src))));
1568
1569               if (t || REGNO_REG_SET_P (df_get_live_in (b), regno))
1570                 return 0;
1571             }
1572         }
1573     }
1574
1575   return 1;
1576 }
1577
1578 /* If x is a set of a register R, mark that R is alive in the beginning
1579    of every update-block of src.  */
1580
1581 static void
1582 update_live_1 (int src, rtx x)
1583 {
1584   int i;
1585   int regno;
1586   rtx reg = SET_DEST (x);
1587
1588   if (reg == 0)
1589     return;
1590
1591   while (GET_CODE (reg) == SUBREG
1592          || GET_CODE (reg) == ZERO_EXTRACT
1593          || GET_CODE (reg) == STRICT_LOW_PART)
1594     reg = XEXP (reg, 0);
1595
1596   if (GET_CODE (reg) == PARALLEL)
1597     {
1598       int i;
1599
1600       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
1601         if (XEXP (XVECEXP (reg, 0, i), 0) != 0)
1602           update_live_1 (src, XEXP (XVECEXP (reg, 0, i), 0));
1603
1604       return;
1605     }
1606
1607   if (!REG_P (reg))
1608     return;
1609
1610   /* Global registers are always live, so the code below does not apply
1611      to them.  */
1612
1613   regno = REGNO (reg);
1614
1615   if (regno >= FIRST_PSEUDO_REGISTER || !global_regs[regno])
1616     {
1617       if (regno < FIRST_PSEUDO_REGISTER)
1618         {
1619           int j = hard_regno_nregs[regno][GET_MODE (reg)];
1620           while (--j >= 0)
1621             {
1622               for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
1623                 {
1624                   basic_block b = candidate_table[src].update_bbs.first_member[i];
1625
1626                   SET_REGNO_REG_SET (df_get_live_in (b), regno + j);
1627                 }
1628             }
1629         }
1630       else
1631         {
1632           for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
1633             {
1634               basic_block b = candidate_table[src].update_bbs.first_member[i];
1635
1636               SET_REGNO_REG_SET (df_get_live_in (b), regno);
1637             }
1638         }
1639     }
1640 }
1641
1642 /* Return 1 if insn can be speculatively moved from block src to trg,
1643    otherwise return 0.  Called before first insertion of insn to
1644    ready-list or before the scheduling.  */
1645
1646 static int
1647 check_live (rtx insn, int src)
1648 {
1649   /* Find the registers set by instruction.  */
1650   if (GET_CODE (PATTERN (insn)) == SET
1651       || GET_CODE (PATTERN (insn)) == CLOBBER)
1652     return check_live_1 (src, PATTERN (insn));
1653   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1654     {
1655       int j;
1656       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1657         if ((GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1658              || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1659             && !check_live_1 (src, XVECEXP (PATTERN (insn), 0, j)))
1660           return 0;
1661
1662       return 1;
1663     }
1664
1665   return 1;
1666 }
1667
1668 /* Update the live registers info after insn was moved speculatively from
1669    block src to trg.  */
1670
1671 static void
1672 update_live (rtx insn, int src)
1673 {
1674   /* Find the registers set by instruction.  */
1675   if (GET_CODE (PATTERN (insn)) == SET
1676       || GET_CODE (PATTERN (insn)) == CLOBBER)
1677     update_live_1 (src, PATTERN (insn));
1678   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
1679     {
1680       int j;
1681       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
1682         if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
1683             || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
1684           update_live_1 (src, XVECEXP (PATTERN (insn), 0, j));
1685     }
1686 }
1687
1688 /* Nonzero if block bb_to is equal to, or reachable from block bb_from.  */
1689 #define IS_REACHABLE(bb_from, bb_to)                                    \
1690   (bb_from == bb_to                                                     \
1691    || IS_RGN_ENTRY (bb_from)                                            \
1692    || (TEST_BIT (ancestor_edges[bb_to],                                 \
1693          EDGE_TO_BIT (single_pred_edge (BASIC_BLOCK (BB_TO_BLOCK (bb_from)))))))
1694
1695 /* Turns on the fed_by_spec_load flag for insns fed by load_insn.  */
1696
1697 static void
1698 set_spec_fed (rtx load_insn)
1699 {
1700   dep_link_t link;
1701
1702   FOR_EACH_DEP_LINK (link, INSN_FORW_DEPS (load_insn))
1703     if (DEP_LINK_KIND (link) == REG_DEP_TRUE)
1704       FED_BY_SPEC_LOAD (DEP_LINK_CON (link)) = 1;
1705 }
1706
1707 /* On the path from the insn to load_insn_bb, find a conditional
1708 branch depending on insn, that guards the speculative load.  */
1709
1710 static int
1711 find_conditional_protection (rtx insn, int load_insn_bb)
1712 {
1713   dep_link_t link;
1714
1715   /* Iterate through DEF-USE forward dependences.  */
1716   FOR_EACH_DEP_LINK (link, INSN_FORW_DEPS (insn))
1717     {
1718       rtx next = DEP_LINK_CON (link);
1719
1720       if ((CONTAINING_RGN (BLOCK_NUM (next)) ==
1721            CONTAINING_RGN (BB_TO_BLOCK (load_insn_bb)))
1722           && IS_REACHABLE (INSN_BB (next), load_insn_bb)
1723           && load_insn_bb != INSN_BB (next)
1724           && DEP_LINK_KIND (link) == REG_DEP_TRUE
1725           && (JUMP_P (next)
1726               || find_conditional_protection (next, load_insn_bb)))
1727         return 1;
1728     }
1729   return 0;
1730 }                               /* find_conditional_protection */
1731
1732 /* Returns 1 if the same insn1 that participates in the computation
1733    of load_insn's address is feeding a conditional branch that is
1734    guarding on load_insn. This is true if we find a the two DEF-USE
1735    chains:
1736    insn1 -> ... -> conditional-branch
1737    insn1 -> ... -> load_insn,
1738    and if a flow path exist:
1739    insn1 -> ... -> conditional-branch -> ... -> load_insn,
1740    and if insn1 is on the path
1741    region-entry -> ... -> bb_trg -> ... load_insn.
1742
1743    Locate insn1 by climbing on INSN_BACK_DEPS from load_insn.
1744    Locate the branch by following INSN_FORW_DEPS from insn1.  */
1745
1746 static int
1747 is_conditionally_protected (rtx load_insn, int bb_src, int bb_trg)
1748 {
1749   dep_link_t link;
1750
1751   FOR_EACH_DEP_LINK (link, INSN_BACK_DEPS (load_insn))
1752     {
1753       rtx insn1 = DEP_LINK_PRO (link);
1754
1755       /* Must be a DEF-USE dependence upon non-branch.  */
1756       if (DEP_LINK_KIND (link) != REG_DEP_TRUE
1757           || JUMP_P (insn1))
1758         continue;
1759
1760       /* Must exist a path: region-entry -> ... -> bb_trg -> ... load_insn.  */
1761       if (INSN_BB (insn1) == bb_src
1762           || (CONTAINING_RGN (BLOCK_NUM (insn1))
1763               != CONTAINING_RGN (BB_TO_BLOCK (bb_src)))
1764           || (!IS_REACHABLE (bb_trg, INSN_BB (insn1))
1765               && !IS_REACHABLE (INSN_BB (insn1), bb_trg)))
1766         continue;
1767
1768       /* Now search for the conditional-branch.  */
1769       if (find_conditional_protection (insn1, bb_src))
1770         return 1;
1771
1772       /* Recursive step: search another insn1, "above" current insn1.  */
1773       return is_conditionally_protected (insn1, bb_src, bb_trg);
1774     }
1775
1776   /* The chain does not exist.  */
1777   return 0;
1778 }                               /* is_conditionally_protected */
1779
1780 /* Returns 1 if a clue for "similar load" 'insn2' is found, and hence
1781    load_insn can move speculatively from bb_src to bb_trg.  All the
1782    following must hold:
1783
1784    (1) both loads have 1 base register (PFREE_CANDIDATEs).
1785    (2) load_insn and load1 have a def-use dependence upon
1786    the same insn 'insn1'.
1787    (3) either load2 is in bb_trg, or:
1788    - there's only one split-block, and
1789    - load1 is on the escape path, and
1790
1791    From all these we can conclude that the two loads access memory
1792    addresses that differ at most by a constant, and hence if moving
1793    load_insn would cause an exception, it would have been caused by
1794    load2 anyhow.  */
1795
1796 static int
1797 is_pfree (rtx load_insn, int bb_src, int bb_trg)
1798 {
1799   dep_link_t back_link;
1800   candidate *candp = candidate_table + bb_src;
1801
1802   if (candp->split_bbs.nr_members != 1)
1803     /* Must have exactly one escape block.  */
1804     return 0;
1805
1806   FOR_EACH_DEP_LINK (back_link, INSN_BACK_DEPS (load_insn))
1807     {
1808       rtx insn1 = DEP_LINK_PRO (back_link);
1809
1810       if (DEP_LINK_KIND (back_link) == REG_DEP_TRUE)
1811         {
1812           /* Found a DEF-USE dependence (insn1, load_insn).  */
1813           dep_link_t fore_link;
1814
1815           FOR_EACH_DEP_LINK (fore_link, INSN_FORW_DEPS (insn1))
1816             {
1817               rtx insn2 = DEP_LINK_CON (fore_link);
1818
1819               if (DEP_LINK_KIND (fore_link) == REG_DEP_TRUE)
1820                 {
1821                   /* Found a DEF-USE dependence (insn1, insn2).  */
1822                   if (haifa_classify_insn (insn2) != PFREE_CANDIDATE)
1823                     /* insn2 not guaranteed to be a 1 base reg load.  */
1824                     continue;
1825
1826                   if (INSN_BB (insn2) == bb_trg)
1827                     /* insn2 is the similar load, in the target block.  */
1828                     return 1;
1829
1830                   if (*(candp->split_bbs.first_member) == BLOCK_FOR_INSN (insn2))
1831                     /* insn2 is a similar load, in a split-block.  */
1832                     return 1;
1833                 }
1834             }
1835         }
1836     }
1837
1838   /* Couldn't find a similar load.  */
1839   return 0;
1840 }                               /* is_pfree */
1841
1842 /* Return 1 if load_insn is prisky (i.e. if load_insn is fed by
1843    a load moved speculatively, or if load_insn is protected by
1844    a compare on load_insn's address).  */
1845
1846 static int
1847 is_prisky (rtx load_insn, int bb_src, int bb_trg)
1848 {
1849   if (FED_BY_SPEC_LOAD (load_insn))
1850     return 1;
1851
1852   if (deps_list_empty_p (INSN_BACK_DEPS (load_insn)))
1853     /* Dependence may 'hide' out of the region.  */
1854     return 1;
1855
1856   if (is_conditionally_protected (load_insn, bb_src, bb_trg))
1857     return 1;
1858
1859   return 0;
1860 }
1861
1862 /* Insn is a candidate to be moved speculatively from bb_src to bb_trg.
1863    Return 1 if insn is exception-free (and the motion is valid)
1864    and 0 otherwise.  */
1865
1866 static int
1867 is_exception_free (rtx insn, int bb_src, int bb_trg)
1868 {
1869   int insn_class = haifa_classify_insn (insn);
1870
1871   /* Handle non-load insns.  */
1872   switch (insn_class)
1873     {
1874     case TRAP_FREE:
1875       return 1;
1876     case TRAP_RISKY:
1877       return 0;
1878     default:;
1879     }
1880
1881   /* Handle loads.  */
1882   if (!flag_schedule_speculative_load)
1883     return 0;
1884   IS_LOAD_INSN (insn) = 1;
1885   switch (insn_class)
1886     {
1887     case IFREE:
1888       return (1);
1889     case IRISKY:
1890       return 0;
1891     case PFREE_CANDIDATE:
1892       if (is_pfree (insn, bb_src, bb_trg))
1893         return 1;
1894       /* Don't 'break' here: PFREE-candidate is also PRISKY-candidate.  */
1895     case PRISKY_CANDIDATE:
1896       if (!flag_schedule_speculative_load_dangerous
1897           || is_prisky (insn, bb_src, bb_trg))
1898         return 0;
1899       break;
1900     default:;
1901     }
1902
1903   return flag_schedule_speculative_load_dangerous;
1904 }
1905 \f
1906 /* The number of insns from the current block scheduled so far.  */
1907 static int sched_target_n_insns;
1908 /* The number of insns from the current block to be scheduled in total.  */
1909 static int target_n_insns;
1910 /* The number of insns from the entire region scheduled so far.  */
1911 static int sched_n_insns;
1912
1913 /* Implementations of the sched_info functions for region scheduling.  */
1914 static void init_ready_list (void);
1915 static int can_schedule_ready_p (rtx);
1916 static void begin_schedule_ready (rtx, rtx);
1917 static ds_t new_ready (rtx, ds_t);
1918 static int schedule_more_p (void);
1919 static const char *rgn_print_insn (rtx, int);
1920 static int rgn_rank (rtx, rtx);
1921 static int contributes_to_priority (rtx, rtx);
1922 static void compute_jump_reg_dependencies (rtx, regset, regset, regset);
1923
1924 /* Functions for speculative scheduling.  */
1925 static void add_remove_insn (rtx, int);
1926 static void extend_regions (void);
1927 static void add_block1 (basic_block, basic_block);
1928 static void fix_recovery_cfg (int, int, int);
1929 static basic_block advance_target_bb (basic_block, rtx);
1930
1931 static void debug_rgn_dependencies (int);
1932
1933 /* Return nonzero if there are more insns that should be scheduled.  */
1934
1935 static int
1936 schedule_more_p (void)
1937 {
1938   return sched_target_n_insns < target_n_insns;
1939 }
1940
1941 /* Add all insns that are initially ready to the ready list READY.  Called
1942    once before scheduling a set of insns.  */
1943
1944 static void
1945 init_ready_list (void)
1946 {
1947   rtx prev_head = current_sched_info->prev_head;
1948   rtx next_tail = current_sched_info->next_tail;
1949   int bb_src;
1950   rtx insn;
1951
1952   target_n_insns = 0;
1953   sched_target_n_insns = 0;
1954   sched_n_insns = 0;
1955
1956   /* Print debugging information.  */
1957   if (sched_verbose >= 5)
1958     debug_rgn_dependencies (target_bb);
1959
1960   /* Prepare current target block info.  */
1961   if (current_nr_blocks > 1)
1962     {
1963       candidate_table = XNEWVEC (candidate, current_nr_blocks);
1964
1965       bblst_last = 0;
1966       /* bblst_table holds split blocks and update blocks for each block after
1967          the current one in the region.  split blocks and update blocks are
1968          the TO blocks of region edges, so there can be at most rgn_nr_edges
1969          of them.  */
1970       bblst_size = (current_nr_blocks - target_bb) * rgn_nr_edges;
1971       bblst_table = XNEWVEC (basic_block, bblst_size);
1972
1973       edgelst_last = 0;
1974       edgelst_table = XNEWVEC (edge, rgn_nr_edges);
1975
1976       compute_trg_info (target_bb);
1977     }
1978
1979   /* Initialize ready list with all 'ready' insns in target block.
1980      Count number of insns in the target block being scheduled.  */
1981   for (insn = NEXT_INSN (prev_head); insn != next_tail; insn = NEXT_INSN (insn))
1982     {      
1983       try_ready (insn);
1984       target_n_insns++;
1985
1986       gcc_assert (!(TODO_SPEC (insn) & BEGIN_CONTROL));
1987     }
1988
1989   /* Add to ready list all 'ready' insns in valid source blocks.
1990      For speculative insns, check-live, exception-free, and
1991      issue-delay.  */
1992   for (bb_src = target_bb + 1; bb_src < current_nr_blocks; bb_src++)
1993     if (IS_VALID (bb_src))
1994       {
1995         rtx src_head;
1996         rtx src_next_tail;
1997         rtx tail, head;
1998
1999         get_ebb_head_tail (EBB_FIRST_BB (bb_src), EBB_LAST_BB (bb_src),
2000                            &head, &tail);
2001         src_next_tail = NEXT_INSN (tail);
2002         src_head = head;
2003
2004         for (insn = src_head; insn != src_next_tail; insn = NEXT_INSN (insn))
2005           if (INSN_P (insn))
2006             try_ready (insn);
2007       }
2008 }
2009
2010 /* Called after taking INSN from the ready list.  Returns nonzero if this
2011    insn can be scheduled, nonzero if we should silently discard it.  */
2012
2013 static int
2014 can_schedule_ready_p (rtx insn)
2015 {
2016   /* An interblock motion?  */
2017   if (INSN_BB (insn) != target_bb
2018       && IS_SPECULATIVE_INSN (insn)
2019       && !check_live (insn, INSN_BB (insn)))
2020     return 0;          
2021   else
2022     return 1;
2023 }
2024
2025 /* Updates counter and other information.  Split from can_schedule_ready_p ()
2026    because when we schedule insn speculatively then insn passed to
2027    can_schedule_ready_p () differs from the one passed to
2028    begin_schedule_ready ().  */
2029 static void
2030 begin_schedule_ready (rtx insn, rtx last ATTRIBUTE_UNUSED)
2031 {
2032   /* An interblock motion?  */
2033   if (INSN_BB (insn) != target_bb)
2034     {
2035       if (IS_SPECULATIVE_INSN (insn))
2036         {
2037           gcc_assert (check_live (insn, INSN_BB (insn)));
2038
2039           update_live (insn, INSN_BB (insn));
2040
2041           /* For speculative load, mark insns fed by it.  */
2042           if (IS_LOAD_INSN (insn) || FED_BY_SPEC_LOAD (insn))
2043             set_spec_fed (insn);
2044
2045           nr_spec++;
2046         }
2047       nr_inter++;
2048     }
2049   else
2050     {
2051       /* In block motion.  */
2052       sched_target_n_insns++;
2053     }
2054   sched_n_insns++;
2055 }
2056
2057 /* Called after INSN has all its hard dependencies resolved and the speculation
2058    of type TS is enough to overcome them all.
2059    Return nonzero if it should be moved to the ready list or the queue, or zero
2060    if we should silently discard it.  */
2061 static ds_t
2062 new_ready (rtx next, ds_t ts)
2063 {
2064   if (INSN_BB (next) != target_bb)
2065     {
2066       int not_ex_free = 0;
2067
2068       /* For speculative insns, before inserting to ready/queue,
2069          check live, exception-free, and issue-delay.  */       
2070       if (!IS_VALID (INSN_BB (next))
2071           || CANT_MOVE (next)
2072           || (IS_SPECULATIVE_INSN (next)
2073               && ((recog_memoized (next) >= 0
2074                    && min_insn_conflict_delay (curr_state, next, next) 
2075                    > PARAM_VALUE (PARAM_MAX_SCHED_INSN_CONFLICT_DELAY))
2076                   || IS_SPECULATION_CHECK_P (next)
2077                   || !check_live (next, INSN_BB (next))
2078                   || (not_ex_free = !is_exception_free (next, INSN_BB (next),
2079                                                         target_bb)))))
2080         {
2081           if (not_ex_free
2082               /* We are here because is_exception_free () == false.
2083                  But we possibly can handle that with control speculation.  */
2084               && current_sched_info->flags & DO_SPECULATION)
2085             /* Here we got new control-speculative instruction.  */
2086             ts = set_dep_weak (ts, BEGIN_CONTROL, MAX_DEP_WEAK);
2087           else
2088             ts = (ts & ~SPECULATIVE) | HARD_DEP;
2089         }
2090     }
2091   
2092   return ts;
2093 }
2094
2095 /* Return a string that contains the insn uid and optionally anything else
2096    necessary to identify this insn in an output.  It's valid to use a
2097    static buffer for this.  The ALIGNED parameter should cause the string
2098    to be formatted so that multiple output lines will line up nicely.  */
2099
2100 static const char *
2101 rgn_print_insn (rtx insn, int aligned)
2102 {
2103   static char tmp[80];
2104
2105   if (aligned)
2106     sprintf (tmp, "b%3d: i%4d", INSN_BB (insn), INSN_UID (insn));
2107   else
2108     {
2109       if (current_nr_blocks > 1 && INSN_BB (insn) != target_bb)
2110         sprintf (tmp, "%d/b%d", INSN_UID (insn), INSN_BB (insn));
2111       else
2112         sprintf (tmp, "%d", INSN_UID (insn));
2113     }
2114   return tmp;
2115 }
2116
2117 /* Compare priority of two insns.  Return a positive number if the second
2118    insn is to be preferred for scheduling, and a negative one if the first
2119    is to be preferred.  Zero if they are equally good.  */
2120
2121 static int
2122 rgn_rank (rtx insn1, rtx insn2)
2123 {
2124   /* Some comparison make sense in interblock scheduling only.  */
2125   if (INSN_BB (insn1) != INSN_BB (insn2))
2126     {
2127       int spec_val, prob_val;
2128
2129       /* Prefer an inblock motion on an interblock motion.  */
2130       if ((INSN_BB (insn2) == target_bb) && (INSN_BB (insn1) != target_bb))
2131         return 1;
2132       if ((INSN_BB (insn1) == target_bb) && (INSN_BB (insn2) != target_bb))
2133         return -1;
2134
2135       /* Prefer a useful motion on a speculative one.  */
2136       spec_val = IS_SPECULATIVE_INSN (insn1) - IS_SPECULATIVE_INSN (insn2);
2137       if (spec_val)
2138         return spec_val;
2139
2140       /* Prefer a more probable (speculative) insn.  */
2141       prob_val = INSN_PROBABILITY (insn2) - INSN_PROBABILITY (insn1);
2142       if (prob_val)
2143         return prob_val;
2144     }
2145   return 0;
2146 }
2147
2148 /* NEXT is an instruction that depends on INSN (a backward dependence);
2149    return nonzero if we should include this dependence in priority
2150    calculations.  */
2151
2152 static int
2153 contributes_to_priority (rtx next, rtx insn)
2154 {
2155   /* NEXT and INSN reside in one ebb.  */
2156   return BLOCK_TO_BB (BLOCK_NUM (next)) == BLOCK_TO_BB (BLOCK_NUM (insn));
2157 }
2158
2159 /* INSN is a JUMP_INSN, COND_SET is the set of registers that are
2160    conditionally set before INSN.  Store the set of registers that
2161    must be considered as used by this jump in USED and that of
2162    registers that must be considered as set in SET.  */
2163
2164 static void
2165 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
2166                                regset cond_exec ATTRIBUTE_UNUSED,
2167                                regset used ATTRIBUTE_UNUSED,
2168                                regset set ATTRIBUTE_UNUSED)
2169 {
2170   /* Nothing to do here, since we postprocess jumps in
2171      add_branch_dependences.  */
2172 }
2173
2174 /* Used in schedule_insns to initialize current_sched_info for scheduling
2175    regions (or single basic blocks).  */
2176
2177 static struct sched_info region_sched_info =
2178 {
2179   init_ready_list,
2180   can_schedule_ready_p,
2181   schedule_more_p,
2182   new_ready,
2183   rgn_rank,
2184   rgn_print_insn,
2185   contributes_to_priority,
2186   compute_jump_reg_dependencies,
2187
2188   NULL, NULL,
2189   NULL, NULL,
2190   0, 0, 0,
2191
2192   add_remove_insn,
2193   begin_schedule_ready,
2194   add_block1,
2195   advance_target_bb,
2196   fix_recovery_cfg,
2197   SCHED_RGN
2198 };
2199
2200 /* Determine if PAT sets a CLASS_LIKELY_SPILLED_P register.  */
2201
2202 static bool
2203 sets_likely_spilled (rtx pat)
2204 {
2205   bool ret = false;
2206   note_stores (pat, sets_likely_spilled_1, &ret);
2207   return ret;
2208 }
2209
2210 static void
2211 sets_likely_spilled_1 (rtx x, const_rtx pat, void *data)
2212 {
2213   bool *ret = (bool *) data;
2214
2215   if (GET_CODE (pat) == SET
2216       && REG_P (x)
2217       && REGNO (x) < FIRST_PSEUDO_REGISTER
2218       && CLASS_LIKELY_SPILLED_P (REGNO_REG_CLASS (REGNO (x))))
2219     *ret = true;
2220 }
2221
2222 /* Add dependences so that branches are scheduled to run last in their
2223    block.  */
2224
2225 static void
2226 add_branch_dependences (rtx head, rtx tail)
2227 {
2228   rtx insn, last;
2229
2230   /* For all branches, calls, uses, clobbers, cc0 setters, and instructions
2231      that can throw exceptions, force them to remain in order at the end of
2232      the block by adding dependencies and giving the last a high priority.
2233      There may be notes present, and prev_head may also be a note.
2234
2235      Branches must obviously remain at the end.  Calls should remain at the
2236      end since moving them results in worse register allocation.  Uses remain
2237      at the end to ensure proper register allocation.
2238
2239      cc0 setters remain at the end because they can't be moved away from
2240      their cc0 user.
2241
2242      COND_EXEC insns cannot be moved past a branch (see e.g. PR17808).
2243
2244      Insns setting CLASS_LIKELY_SPILLED_P registers (usually return values)
2245      are not moved before reload because we can wind up with register
2246      allocation failures.  */
2247
2248   insn = tail;
2249   last = 0;
2250   while (CALL_P (insn)
2251          || JUMP_P (insn)
2252          || (NONJUMP_INSN_P (insn)
2253              && (GET_CODE (PATTERN (insn)) == USE
2254                  || GET_CODE (PATTERN (insn)) == CLOBBER
2255                  || can_throw_internal (insn)
2256 #ifdef HAVE_cc0
2257                  || sets_cc0_p (PATTERN (insn))
2258 #endif
2259                  || (!reload_completed
2260                      && sets_likely_spilled (PATTERN (insn)))))
2261          || NOTE_P (insn))
2262     {
2263       if (!NOTE_P (insn))
2264         {
2265           if (last != 0
2266               && (find_link_by_pro_in_deps_list (INSN_BACK_DEPS (last), insn)
2267                   == NULL))
2268             {
2269               if (! sched_insns_conditions_mutex_p (last, insn))
2270                 add_dependence (last, insn, REG_DEP_ANTI);
2271               INSN_REF_COUNT (insn)++;
2272             }
2273
2274           CANT_MOVE (insn) = 1;
2275
2276           last = insn;
2277         }
2278
2279       /* Don't overrun the bounds of the basic block.  */
2280       if (insn == head)
2281         break;
2282
2283       insn = PREV_INSN (insn);
2284     }
2285
2286   /* Make sure these insns are scheduled last in their block.  */
2287   insn = last;
2288   if (insn != 0)
2289     while (insn != head)
2290       {
2291         insn = prev_nonnote_insn (insn);
2292
2293         if (INSN_REF_COUNT (insn) != 0)
2294           continue;
2295
2296         if (! sched_insns_conditions_mutex_p (last, insn))
2297           add_dependence (last, insn, REG_DEP_ANTI);
2298         INSN_REF_COUNT (insn) = 1;
2299       }
2300
2301 #ifdef HAVE_conditional_execution
2302   /* Finally, if the block ends in a jump, and we are doing intra-block
2303      scheduling, make sure that the branch depends on any COND_EXEC insns
2304      inside the block to avoid moving the COND_EXECs past the branch insn.
2305
2306      We only have to do this after reload, because (1) before reload there
2307      are no COND_EXEC insns, and (2) the region scheduler is an intra-block
2308      scheduler after reload.
2309
2310      FIXME: We could in some cases move COND_EXEC insns past the branch if
2311      this scheduler would be a little smarter.  Consider this code:
2312
2313                 T = [addr]
2314         C  ?    addr += 4
2315         !C ?    X += 12
2316         C  ?    T += 1
2317         C  ?    jump foo
2318
2319      On a target with a one cycle stall on a memory access the optimal
2320      sequence would be:
2321
2322                 T = [addr]
2323         C  ?    addr += 4
2324         C  ?    T += 1
2325         C  ?    jump foo
2326         !C ?    X += 12
2327
2328      We don't want to put the 'X += 12' before the branch because it just
2329      wastes a cycle of execution time when the branch is taken.
2330
2331      Note that in the example "!C" will always be true.  That is another
2332      possible improvement for handling COND_EXECs in this scheduler: it
2333      could remove always-true predicates.  */
2334
2335   if (!reload_completed || ! JUMP_P (tail))
2336     return;
2337
2338   insn = tail;
2339   while (insn != head)
2340     {
2341       insn = PREV_INSN (insn);
2342
2343       /* Note that we want to add this dependency even when
2344          sched_insns_conditions_mutex_p returns true.  The whole point
2345          is that we _want_ this dependency, even if these insns really
2346          are independent.  */
2347       if (INSN_P (insn) && GET_CODE (PATTERN (insn)) == COND_EXEC)
2348         add_dependence (tail, insn, REG_DEP_ANTI);
2349     }
2350 #endif
2351 }
2352
2353 /* Data structures for the computation of data dependences in a regions.  We
2354    keep one `deps' structure for every basic block.  Before analyzing the
2355    data dependences for a bb, its variables are initialized as a function of
2356    the variables of its predecessors.  When the analysis for a bb completes,
2357    we save the contents to the corresponding bb_deps[bb] variable.  */
2358
2359 static struct deps *bb_deps;
2360
2361 /* Duplicate the INSN_LIST elements of COPY and prepend them to OLD.  */
2362
2363 static rtx
2364 concat_INSN_LIST (rtx copy, rtx old)
2365 {
2366   rtx new = old;
2367   for (; copy ; copy = XEXP (copy, 1))
2368     new = alloc_INSN_LIST (XEXP (copy, 0), new);
2369   return new;
2370 }
2371
2372 static void
2373 concat_insn_mem_list (rtx copy_insns, rtx copy_mems, rtx *old_insns_p,
2374                       rtx *old_mems_p)
2375 {
2376   rtx new_insns = *old_insns_p;
2377   rtx new_mems = *old_mems_p;
2378
2379   while (copy_insns)
2380     {
2381       new_insns = alloc_INSN_LIST (XEXP (copy_insns, 0), new_insns);
2382       new_mems = alloc_EXPR_LIST (VOIDmode, XEXP (copy_mems, 0), new_mems);
2383       copy_insns = XEXP (copy_insns, 1);
2384       copy_mems = XEXP (copy_mems, 1);
2385     }
2386
2387   *old_insns_p = new_insns;
2388   *old_mems_p = new_mems;
2389 }
2390
2391 /* After computing the dependencies for block BB, propagate the dependencies
2392    found in TMP_DEPS to the successors of the block.  */
2393 static void
2394 propagate_deps (int bb, struct deps *pred_deps)
2395 {
2396   basic_block block = BASIC_BLOCK (BB_TO_BLOCK (bb));
2397   edge_iterator ei;
2398   edge e;
2399
2400   /* bb's structures are inherited by its successors.  */
2401   FOR_EACH_EDGE (e, ei, block->succs)
2402     {
2403       struct deps *succ_deps;
2404       unsigned reg;
2405       reg_set_iterator rsi;
2406
2407       /* Only bbs "below" bb, in the same region, are interesting.  */
2408       if (e->dest == EXIT_BLOCK_PTR
2409           || CONTAINING_RGN (block->index) != CONTAINING_RGN (e->dest->index)
2410           || BLOCK_TO_BB (e->dest->index) <= bb)
2411         continue;
2412
2413       succ_deps = bb_deps + BLOCK_TO_BB (e->dest->index);
2414
2415       /* The reg_last lists are inherited by successor.  */
2416       EXECUTE_IF_SET_IN_REG_SET (&pred_deps->reg_last_in_use, 0, reg, rsi)
2417         {
2418           struct deps_reg *pred_rl = &pred_deps->reg_last[reg];
2419           struct deps_reg *succ_rl = &succ_deps->reg_last[reg];
2420
2421           succ_rl->uses = concat_INSN_LIST (pred_rl->uses, succ_rl->uses);
2422           succ_rl->sets = concat_INSN_LIST (pred_rl->sets, succ_rl->sets);
2423           succ_rl->clobbers = concat_INSN_LIST (pred_rl->clobbers,
2424                                                 succ_rl->clobbers);
2425           succ_rl->uses_length += pred_rl->uses_length;
2426           succ_rl->clobbers_length += pred_rl->clobbers_length;
2427         }
2428       IOR_REG_SET (&succ_deps->reg_last_in_use, &pred_deps->reg_last_in_use);
2429
2430       /* Mem read/write lists are inherited by successor.  */
2431       concat_insn_mem_list (pred_deps->pending_read_insns,
2432                             pred_deps->pending_read_mems,
2433                             &succ_deps->pending_read_insns,
2434                             &succ_deps->pending_read_mems);
2435       concat_insn_mem_list (pred_deps->pending_write_insns,
2436                             pred_deps->pending_write_mems,
2437                             &succ_deps->pending_write_insns,
2438                             &succ_deps->pending_write_mems);
2439
2440       succ_deps->last_pending_memory_flush
2441         = concat_INSN_LIST (pred_deps->last_pending_memory_flush,
2442                             succ_deps->last_pending_memory_flush);
2443
2444       succ_deps->pending_read_list_length
2445         += pred_deps->pending_read_list_length;
2446       succ_deps->pending_write_list_length
2447         += pred_deps->pending_write_list_length;
2448       succ_deps->pending_flush_length += pred_deps->pending_flush_length;
2449
2450       /* last_function_call is inherited by successor.  */
2451       succ_deps->last_function_call
2452         = concat_INSN_LIST (pred_deps->last_function_call,
2453                               succ_deps->last_function_call);
2454
2455       /* sched_before_next_call is inherited by successor.  */
2456       succ_deps->sched_before_next_call
2457         = concat_INSN_LIST (pred_deps->sched_before_next_call,
2458                             succ_deps->sched_before_next_call);
2459     }
2460
2461   /* These lists should point to the right place, for correct
2462      freeing later.  */
2463   bb_deps[bb].pending_read_insns = pred_deps->pending_read_insns;
2464   bb_deps[bb].pending_read_mems = pred_deps->pending_read_mems;
2465   bb_deps[bb].pending_write_insns = pred_deps->pending_write_insns;
2466   bb_deps[bb].pending_write_mems = pred_deps->pending_write_mems;
2467
2468   /* Can't allow these to be freed twice.  */
2469   pred_deps->pending_read_insns = 0;
2470   pred_deps->pending_read_mems = 0;
2471   pred_deps->pending_write_insns = 0;
2472   pred_deps->pending_write_mems = 0;
2473 }
2474
2475 /* Compute backward dependences inside bb.  In a multiple blocks region:
2476    (1) a bb is analyzed after its predecessors, and (2) the lists in
2477    effect at the end of bb (after analyzing for bb) are inherited by
2478    bb's successors.
2479
2480    Specifically for reg-reg data dependences, the block insns are
2481    scanned by sched_analyze () top-to-bottom.  Two lists are
2482    maintained by sched_analyze (): reg_last[].sets for register DEFs,
2483    and reg_last[].uses for register USEs.
2484
2485    When analysis is completed for bb, we update for its successors:
2486    ;  - DEFS[succ] = Union (DEFS [succ], DEFS [bb])
2487    ;  - USES[succ] = Union (USES [succ], DEFS [bb])
2488
2489    The mechanism for computing mem-mem data dependence is very
2490    similar, and the result is interblock dependences in the region.  */
2491
2492 static void
2493 compute_block_backward_dependences (int bb)
2494 {
2495   rtx head, tail;
2496   struct deps tmp_deps;
2497
2498   tmp_deps = bb_deps[bb];
2499
2500   /* Do the analysis for this block.  */
2501   gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2502   get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2503   sched_analyze (&tmp_deps, head, tail);
2504   add_branch_dependences (head, tail);
2505
2506   if (current_nr_blocks > 1)
2507     propagate_deps (bb, &tmp_deps);
2508
2509   /* Free up the INSN_LISTs.  */
2510   free_deps (&tmp_deps);
2511 }
2512
2513 /* Remove all INSN_LISTs and EXPR_LISTs from the pending lists and add
2514    them to the unused_*_list variables, so that they can be reused.  */
2515
2516 static void
2517 free_pending_lists (void)
2518 {
2519   int bb;
2520
2521   for (bb = 0; bb < current_nr_blocks; bb++)
2522     {
2523       free_INSN_LIST_list (&bb_deps[bb].pending_read_insns);
2524       free_INSN_LIST_list (&bb_deps[bb].pending_write_insns);
2525       free_EXPR_LIST_list (&bb_deps[bb].pending_read_mems);
2526       free_EXPR_LIST_list (&bb_deps[bb].pending_write_mems);
2527     }
2528 }
2529 \f
2530
2531 /* Print dependences for debugging starting from FROM_BB.
2532    Callable from debugger.  */
2533 void
2534 debug_rgn_dependencies (int from_bb)
2535 {
2536   int bb;
2537
2538   fprintf (sched_dump,
2539            ";;   --------------- forward dependences: ------------ \n");
2540
2541   for (bb = from_bb; bb < current_nr_blocks; bb++)
2542     {
2543       rtx head, tail;
2544
2545       gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2546       get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2547       fprintf (sched_dump, "\n;;   --- Region Dependences --- b %d bb %d \n",
2548                BB_TO_BLOCK (bb), bb);
2549
2550       debug_dependencies (head, tail);
2551     }
2552 }
2553
2554 /* Print dependencies information for instructions between HEAD and TAIL.
2555    ??? This function would probably fit best in haifa-sched.c.  */
2556 void debug_dependencies (rtx head, rtx tail)
2557 {
2558   rtx insn;
2559   rtx next_tail = NEXT_INSN (tail);
2560
2561   fprintf (sched_dump, ";;   %7s%6s%6s%6s%6s%6s%14s\n",
2562            "insn", "code", "bb", "dep", "prio", "cost",
2563            "reservation");
2564   fprintf (sched_dump, ";;   %7s%6s%6s%6s%6s%6s%14s\n",
2565            "----", "----", "--", "---", "----", "----",
2566            "-----------");
2567
2568   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
2569     {
2570       dep_link_t link;
2571
2572       if (! INSN_P (insn))
2573         {
2574           int n;
2575           fprintf (sched_dump, ";;   %6d ", INSN_UID (insn));
2576           if (NOTE_P (insn))
2577             {
2578               n = NOTE_KIND (insn);
2579               fprintf (sched_dump, "%s\n", GET_NOTE_INSN_NAME (n));
2580             }
2581           else
2582             fprintf (sched_dump, " {%s}\n", GET_RTX_NAME (GET_CODE (insn)));
2583           continue;
2584         }
2585
2586       fprintf (sched_dump,
2587                ";;   %s%5d%6d%6d%6d%6d%6d   ",
2588                (SCHED_GROUP_P (insn) ? "+" : " "),
2589                INSN_UID (insn),
2590                INSN_CODE (insn),
2591                BLOCK_NUM (insn),
2592                INSN_DEP_COUNT (insn),
2593                INSN_PRIORITY (insn),
2594                insn_cost (insn));
2595
2596       if (recog_memoized (insn) < 0)
2597         fprintf (sched_dump, "nothing");
2598       else
2599         print_reservation (sched_dump, insn);
2600
2601       fprintf (sched_dump, "\t: ");
2602       FOR_EACH_DEP_LINK (link, INSN_FORW_DEPS (insn))
2603         fprintf (sched_dump, "%d ", INSN_UID (DEP_LINK_CON (link)));
2604       fprintf (sched_dump, "\n");
2605     }
2606
2607   fprintf (sched_dump, "\n");
2608 }
2609 \f
2610 /* Returns true if all the basic blocks of the current region have
2611    NOTE_DISABLE_SCHED_OF_BLOCK which means not to schedule that region.  */
2612 static bool
2613 sched_is_disabled_for_current_region_p (void)
2614 {
2615   int bb;
2616
2617   for (bb = 0; bb < current_nr_blocks; bb++)
2618     if (!(BASIC_BLOCK (BB_TO_BLOCK (bb))->flags & BB_DISABLE_SCHEDULE))
2619       return false;
2620
2621   return true;
2622 }
2623
2624 /* Schedule a region.  A region is either an inner loop, a loop-free
2625    subroutine, or a single basic block.  Each bb in the region is
2626    scheduled after its flow predecessors.  */
2627
2628 static void
2629 schedule_region (int rgn)
2630 {
2631   basic_block block;
2632   edge_iterator ei;
2633   edge e;
2634   int bb;
2635   int sched_rgn_n_insns = 0;
2636
2637   rgn_n_insns = 0;
2638   /* Set variables for the current region.  */
2639   current_nr_blocks = RGN_NR_BLOCKS (rgn);
2640   current_blocks = RGN_BLOCKS (rgn);
2641   
2642   /* See comments in add_block1, for what reasons we allocate +1 element.  */ 
2643   ebb_head = xrealloc (ebb_head, (current_nr_blocks + 1) * sizeof (*ebb_head));
2644   for (bb = 0; bb <= current_nr_blocks; bb++)
2645     ebb_head[bb] = current_blocks + bb;
2646
2647   /* Don't schedule region that is marked by
2648      NOTE_DISABLE_SCHED_OF_BLOCK.  */
2649   if (sched_is_disabled_for_current_region_p ())
2650     return;
2651
2652   if (!RGN_DONT_CALC_DEPS (rgn))
2653     {
2654       init_deps_global ();
2655
2656       /* Initializations for region data dependence analysis.  */
2657       bb_deps = XNEWVEC (struct deps, current_nr_blocks);
2658       for (bb = 0; bb < current_nr_blocks; bb++)
2659         init_deps (bb_deps + bb);
2660
2661       /* Compute backward dependencies.  */
2662       for (bb = 0; bb < current_nr_blocks; bb++)
2663         compute_block_backward_dependences (bb);
2664
2665       /* Compute forward dependencies.  */
2666       for (bb = current_nr_blocks - 1; bb >= 0; bb--)
2667         {
2668           rtx head, tail;
2669
2670           gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2671           get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2672
2673           compute_forward_dependences (head, tail);
2674
2675           if (targetm.sched.dependencies_evaluation_hook)
2676             targetm.sched.dependencies_evaluation_hook (head, tail);
2677         }
2678
2679       free_pending_lists ();
2680
2681       finish_deps_global ();
2682
2683       free (bb_deps);
2684     }
2685   else
2686     /* This is a recovery block.  It is always a single block region.  */
2687     gcc_assert (current_nr_blocks == 1);
2688       
2689   /* Set priorities.  */
2690   current_sched_info->sched_max_insns_priority = 0;
2691   for (bb = 0; bb < current_nr_blocks; bb++)
2692     {
2693       rtx head, tail;
2694       
2695       gcc_assert (EBB_FIRST_BB (bb) == EBB_LAST_BB (bb));
2696       get_ebb_head_tail (EBB_FIRST_BB (bb), EBB_LAST_BB (bb), &head, &tail);
2697
2698       rgn_n_insns += set_priorities (head, tail);
2699     }
2700   current_sched_info->sched_max_insns_priority++;
2701
2702   /* Compute interblock info: probabilities, split-edges, dominators, etc.  */
2703   if (current_nr_blocks > 1)
2704     {
2705       prob = XNEWVEC (int, current_nr_blocks);
2706
2707       dom = sbitmap_vector_alloc (current_nr_blocks, current_nr_blocks);
2708       sbitmap_vector_zero (dom, current_nr_blocks);
2709
2710       /* Use ->aux to implement EDGE_TO_BIT mapping.  */
2711       rgn_nr_edges = 0;
2712       FOR_EACH_BB (block)
2713         {
2714           if (CONTAINING_RGN (block->index) != rgn)
2715             continue;
2716           FOR_EACH_EDGE (e, ei, block->succs)
2717             SET_EDGE_TO_BIT (e, rgn_nr_edges++);
2718         }
2719
2720       rgn_edges = XNEWVEC (edge, rgn_nr_edges);
2721       rgn_nr_edges = 0;
2722       FOR_EACH_BB (block)
2723         {
2724           if (CONTAINING_RGN (block->index) != rgn)
2725             continue;
2726           FOR_EACH_EDGE (e, ei, block->succs)
2727             rgn_edges[rgn_nr_edges++] = e;
2728         }
2729
2730       /* Split edges.  */
2731       pot_split = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
2732       sbitmap_vector_zero (pot_split, current_nr_blocks);
2733       ancestor_edges = sbitmap_vector_alloc (current_nr_blocks, rgn_nr_edges);
2734       sbitmap_vector_zero (ancestor_edges, current_nr_blocks);
2735
2736       /* Compute probabilities, dominators, split_edges.  */
2737       for (bb = 0; bb < current_nr_blocks; bb++)
2738         compute_dom_prob_ps (bb);
2739
2740       /* Cleanup ->aux used for EDGE_TO_BIT mapping.  */
2741       /* We don't need them anymore.  But we want to avoid duplication of
2742          aux fields in the newly created edges.  */
2743       FOR_EACH_BB (block)
2744         {
2745           if (CONTAINING_RGN (block->index) != rgn)
2746             continue;
2747           FOR_EACH_EDGE (e, ei, block->succs)
2748             e->aux = NULL;
2749         }
2750     }
2751
2752   /* Now we can schedule all blocks.  */
2753   for (bb = 0; bb < current_nr_blocks; bb++)
2754     {
2755       basic_block first_bb, last_bb, curr_bb;
2756       rtx head, tail;
2757
2758       first_bb = EBB_FIRST_BB (bb);
2759       last_bb = EBB_LAST_BB (bb);
2760
2761       get_ebb_head_tail (first_bb, last_bb, &head, &tail);
2762
2763       if (no_real_insns_p (head, tail))
2764         {
2765           gcc_assert (first_bb == last_bb);
2766           continue;
2767         }
2768
2769       current_sched_info->prev_head = PREV_INSN (head);
2770       current_sched_info->next_tail = NEXT_INSN (tail);
2771
2772
2773       /* rm_other_notes only removes notes which are _inside_ the
2774          block---that is, it won't remove notes before the first real insn
2775          or after the last real insn of the block.  So if the first insn
2776          has a REG_SAVE_NOTE which would otherwise be emitted before the
2777          insn, it is redundant with the note before the start of the
2778          block, and so we have to take it out.  */
2779       if (INSN_P (head))
2780         {
2781           rtx note;
2782
2783           for (note = REG_NOTES (head); note; note = XEXP (note, 1))
2784             if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
2785               remove_note (head, note);
2786         }
2787       else
2788         /* This means that first block in ebb is empty.
2789            It looks to me as an impossible thing.  There at least should be
2790            a recovery check, that caused the splitting.  */
2791         gcc_unreachable ();
2792
2793       /* Remove remaining note insns from the block, save them in
2794          note_list.  These notes are restored at the end of
2795          schedule_block ().  */
2796       rm_other_notes (head, tail);
2797
2798       unlink_bb_notes (first_bb, last_bb);
2799
2800       target_bb = bb;
2801
2802       gcc_assert (flag_schedule_interblock || current_nr_blocks == 1);
2803       current_sched_info->queue_must_finish_empty = current_nr_blocks == 1;
2804
2805       curr_bb = first_bb;
2806       if (dbg_cnt (sched_block))
2807         {
2808           schedule_block (&curr_bb, rgn_n_insns);
2809           gcc_assert (EBB_FIRST_BB (bb) == first_bb);
2810           sched_rgn_n_insns += sched_n_insns;
2811         }
2812       else
2813         {
2814           sched_rgn_n_insns += rgn_n_insns;
2815         }
2816
2817       /* Clean up.  */
2818       if (current_nr_blocks > 1)
2819         {
2820           free (candidate_table);
2821           free (bblst_table);
2822           free (edgelst_table);
2823         }
2824     }
2825
2826   /* Sanity check: verify that all region insns were scheduled.  */
2827   gcc_assert (sched_rgn_n_insns == rgn_n_insns);
2828
2829
2830   /* Done with this region.  */
2831
2832   if (current_nr_blocks > 1)
2833     {
2834       free (prob);
2835       sbitmap_vector_free (dom);
2836       sbitmap_vector_free (pot_split);
2837       sbitmap_vector_free (ancestor_edges);
2838       free (rgn_edges);
2839     }
2840 }
2841
2842 /* Initialize data structures for region scheduling.  */
2843
2844 static void
2845 init_regions (void)
2846 {
2847   nr_regions = 0;
2848   rgn_table = 0;
2849   rgn_bb_table = 0;
2850   block_to_bb = 0;
2851   containing_rgn = 0;
2852   extend_regions ();
2853
2854   /* Compute regions for scheduling.  */
2855   if (reload_completed
2856       || n_basic_blocks == NUM_FIXED_BLOCKS + 1
2857       || !flag_schedule_interblock
2858       || is_cfg_nonregular ())
2859     {
2860       find_single_block_region ();
2861     }
2862   else
2863     {
2864       /* Compute the dominators and post dominators.  */
2865       calculate_dominance_info (CDI_DOMINATORS);
2866
2867       /* Find regions.  */
2868       find_rgns ();
2869
2870       if (sched_verbose >= 3)
2871         debug_regions ();
2872
2873       /* For now.  This will move as more and more of haifa is converted
2874          to using the cfg code.  */
2875       free_dominance_info (CDI_DOMINATORS);
2876     }
2877   RGN_BLOCKS (nr_regions) = RGN_BLOCKS (nr_regions - 1) +
2878     RGN_NR_BLOCKS (nr_regions - 1);
2879 }
2880
2881 /* The one entry point in this file.  */
2882
2883 void
2884 schedule_insns (void)
2885 {
2886   int rgn;
2887
2888   /* Taking care of this degenerate case makes the rest of
2889      this code simpler.  */
2890   if (n_basic_blocks == NUM_FIXED_BLOCKS)
2891     return;
2892
2893   nr_inter = 0;
2894   nr_spec = 0;
2895
2896   /* We need current_sched_info in init_dependency_caches, which is
2897      invoked via sched_init.  */
2898   current_sched_info = &region_sched_info;
2899
2900   df_set_flags (DF_LR_RUN_DCE);
2901   df_note_add_problem ();
2902   df_analyze ();
2903   regstat_compute_calls_crossed ();
2904
2905   sched_init ();
2906
2907   bitmap_initialize (&not_in_df, 0);
2908   bitmap_clear (&not_in_df);
2909
2910   min_spec_prob = ((PARAM_VALUE (PARAM_MIN_SPEC_PROB) * REG_BR_PROB_BASE)
2911                     / 100);
2912
2913   init_regions ();
2914
2915   /* EBB_HEAD is a region-scope structure.  But we realloc it for
2916      each region to save time/memory/something else.  */
2917   ebb_head = 0;
2918   
2919   /* Schedule every region in the subroutine.  */
2920   for (rgn = 0; rgn < nr_regions; rgn++)
2921     if (dbg_cnt (sched_region))
2922       schedule_region (rgn);
2923   
2924   free(ebb_head);
2925   /* Reposition the prologue and epilogue notes in case we moved the
2926      prologue/epilogue insns.  */
2927   if (reload_completed)
2928     reposition_prologue_and_epilogue_notes ();
2929
2930   if (sched_verbose)
2931     {
2932       if (reload_completed == 0 && flag_schedule_interblock)
2933         {
2934           fprintf (sched_dump,
2935                    "\n;; Procedure interblock/speculative motions == %d/%d \n",
2936                    nr_inter, nr_spec);
2937         }
2938       else
2939         gcc_assert (nr_inter <= 0);
2940       fprintf (sched_dump, "\n\n");
2941     }
2942
2943   /* Clean up.  */
2944   free (rgn_table);
2945   free (rgn_bb_table);
2946   free (block_to_bb);
2947   free (containing_rgn);
2948
2949   regstat_free_calls_crossed ();
2950
2951   bitmap_clear (&not_in_df);
2952
2953   sched_finish ();
2954 }
2955
2956 /* INSN has been added to/removed from current region.  */
2957 static void
2958 add_remove_insn (rtx insn, int remove_p)
2959 {
2960   if (!remove_p)
2961     rgn_n_insns++;
2962   else
2963     rgn_n_insns--;
2964
2965   if (INSN_BB (insn) == target_bb)
2966     {
2967       if (!remove_p)
2968         target_n_insns++;
2969       else
2970         target_n_insns--;
2971     }
2972 }
2973
2974 /* Extend internal data structures.  */
2975 static void
2976 extend_regions (void)
2977 {
2978   rgn_table = XRESIZEVEC (region, rgn_table, n_basic_blocks);
2979   rgn_bb_table = XRESIZEVEC (int, rgn_bb_table, n_basic_blocks);
2980   block_to_bb = XRESIZEVEC (int, block_to_bb, last_basic_block);
2981   containing_rgn = XRESIZEVEC (int, containing_rgn, last_basic_block);
2982 }
2983
2984 /* BB was added to ebb after AFTER.  */
2985 static void
2986 add_block1 (basic_block bb, basic_block after)
2987 {
2988   extend_regions ();
2989
2990   bitmap_set_bit (&not_in_df, bb->index);
2991
2992   if (after == 0 || after == EXIT_BLOCK_PTR)
2993     {
2994       int i;
2995       
2996       i = RGN_BLOCKS (nr_regions);
2997       /* I - first free position in rgn_bb_table.  */
2998
2999       rgn_bb_table[i] = bb->index;
3000       RGN_NR_BLOCKS (nr_regions) = 1;
3001       RGN_DONT_CALC_DEPS (nr_regions) = after == EXIT_BLOCK_PTR;
3002       RGN_HAS_REAL_EBB (nr_regions) = 0;
3003       CONTAINING_RGN (bb->index) = nr_regions;
3004       BLOCK_TO_BB (bb->index) = 0;
3005
3006       nr_regions++;
3007       
3008       RGN_BLOCKS (nr_regions) = i + 1;
3009     }
3010   else
3011     { 
3012       int i, pos;
3013
3014       /* We need to fix rgn_table, block_to_bb, containing_rgn
3015          and ebb_head.  */
3016
3017       BLOCK_TO_BB (bb->index) = BLOCK_TO_BB (after->index);
3018
3019       /* We extend ebb_head to one more position to
3020          easily find the last position of the last ebb in 
3021          the current region.  Thus, ebb_head[BLOCK_TO_BB (after) + 1]
3022          is _always_ valid for access.  */
3023
3024       i = BLOCK_TO_BB (after->index) + 1;
3025       pos = ebb_head[i] - 1;
3026       /* Now POS is the index of the last block in the region.  */
3027
3028       /* Find index of basic block AFTER.  */
3029       for (; rgn_bb_table[pos] != after->index; pos--);
3030
3031       pos++;
3032       gcc_assert (pos > ebb_head[i - 1]);
3033
3034       /* i - ebb right after "AFTER".  */
3035       /* ebb_head[i] - VALID.  */
3036
3037       /* Source position: ebb_head[i]
3038          Destination position: ebb_head[i] + 1
3039          Last position: 
3040            RGN_BLOCKS (nr_regions) - 1
3041          Number of elements to copy: (last_position) - (source_position) + 1
3042        */
3043       
3044       memmove (rgn_bb_table + pos + 1,
3045                rgn_bb_table + pos,
3046                ((RGN_BLOCKS (nr_regions) - 1) - (pos) + 1)
3047                * sizeof (*rgn_bb_table));
3048
3049       rgn_bb_table[pos] = bb->index;
3050       
3051       for (; i <= current_nr_blocks; i++)
3052         ebb_head [i]++;
3053
3054       i = CONTAINING_RGN (after->index);
3055       CONTAINING_RGN (bb->index) = i;
3056       
3057       RGN_HAS_REAL_EBB (i) = 1;
3058
3059       for (++i; i <= nr_regions; i++)
3060         RGN_BLOCKS (i)++;
3061     }
3062 }
3063
3064 /* Fix internal data after interblock movement of jump instruction.
3065    For parameter meaning please refer to
3066    sched-int.h: struct sched_info: fix_recovery_cfg.  */
3067 static void
3068 fix_recovery_cfg (int bbi, int check_bbi, int check_bb_nexti)
3069 {
3070   int old_pos, new_pos, i;
3071
3072   BLOCK_TO_BB (check_bb_nexti) = BLOCK_TO_BB (bbi);
3073   
3074   for (old_pos = ebb_head[BLOCK_TO_BB (check_bbi) + 1] - 1;
3075        rgn_bb_table[old_pos] != check_bb_nexti;
3076        old_pos--);
3077   gcc_assert (old_pos > ebb_head[BLOCK_TO_BB (check_bbi)]);
3078
3079   for (new_pos = ebb_head[BLOCK_TO_BB (bbi) + 1] - 1;
3080        rgn_bb_table[new_pos] != bbi;
3081        new_pos--);
3082   new_pos++;
3083   gcc_assert (new_pos > ebb_head[BLOCK_TO_BB (bbi)]);
3084   
3085   gcc_assert (new_pos < old_pos);
3086
3087   memmove (rgn_bb_table + new_pos + 1,
3088            rgn_bb_table + new_pos,
3089            (old_pos - new_pos) * sizeof (*rgn_bb_table));
3090
3091   rgn_bb_table[new_pos] = check_bb_nexti;
3092
3093   for (i = BLOCK_TO_BB (bbi) + 1; i <= BLOCK_TO_BB (check_bbi); i++)
3094     ebb_head[i]++;
3095 }
3096
3097 /* Return next block in ebb chain.  For parameter meaning please refer to
3098    sched-int.h: struct sched_info: advance_target_bb.  */
3099 static basic_block
3100 advance_target_bb (basic_block bb, rtx insn)
3101 {
3102   if (insn)
3103     return 0;
3104
3105   gcc_assert (BLOCK_TO_BB (bb->index) == target_bb
3106               && BLOCK_TO_BB (bb->next_bb->index) == target_bb);
3107   return bb->next_bb;
3108 }
3109
3110 #endif
3111 \f
3112 static bool
3113 gate_handle_sched (void)
3114 {
3115 #ifdef INSN_SCHEDULING
3116   return flag_schedule_insns && dbg_cnt (sched_func);
3117 #else
3118   return 0;
3119 #endif
3120 }
3121
3122 /* Run instruction scheduler.  */
3123 static unsigned int
3124 rest_of_handle_sched (void)
3125 {
3126 #ifdef INSN_SCHEDULING
3127   schedule_insns ();
3128 #endif
3129   return 0;
3130 }
3131
3132 static bool
3133 gate_handle_sched2 (void)
3134 {
3135 #ifdef INSN_SCHEDULING
3136   return optimize > 0 && flag_schedule_insns_after_reload 
3137     && dbg_cnt (sched2_func);
3138 #else
3139   return 0;
3140 #endif
3141 }
3142
3143 /* Run second scheduling pass after reload.  */
3144 static unsigned int
3145 rest_of_handle_sched2 (void)
3146 {
3147 #ifdef INSN_SCHEDULING
3148   /* Do control and data sched analysis again,
3149      and write some more of the results to dump file.  */
3150   if (flag_sched2_use_superblocks || flag_sched2_use_traces)
3151     schedule_ebbs ();
3152   else
3153     schedule_insns ();
3154 #endif
3155   return 0;
3156 }
3157
3158 struct tree_opt_pass pass_sched =
3159 {
3160   "sched1",                             /* name */
3161   gate_handle_sched,                    /* gate */
3162   rest_of_handle_sched,                 /* execute */
3163   NULL,                                 /* sub */
3164   NULL,                                 /* next */
3165   0,                                    /* static_pass_number */
3166   TV_SCHED,                             /* tv_id */
3167   0,                                    /* properties_required */
3168   0,                                    /* properties_provided */
3169   0,                                    /* properties_destroyed */
3170   0,                                    /* todo_flags_start */
3171   TODO_df_finish |
3172   TODO_dump_func |
3173   TODO_verify_flow |
3174   TODO_ggc_collect,                     /* todo_flags_finish */
3175   'S'                                   /* letter */
3176 };
3177
3178 struct tree_opt_pass pass_sched2 =
3179 {
3180   "sched2",                             /* name */
3181   gate_handle_sched2,                   /* gate */
3182   rest_of_handle_sched2,                /* execute */
3183   NULL,                                 /* sub */
3184   NULL,                                 /* next */
3185   0,                                    /* static_pass_number */
3186   TV_SCHED2,                            /* tv_id */
3187   0,                                    /* properties_required */
3188   0,                                    /* properties_provided */
3189   0,                                    /* properties_destroyed */
3190   0,                                    /* todo_flags_start */
3191   TODO_df_finish |
3192   TODO_dump_func |
3193   TODO_verify_flow |
3194   TODO_ggc_collect,                     /* todo_flags_finish */
3195   'R'                                   /* letter */
3196 };
3197