OSDN Git Service

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