OSDN Git Service

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