OSDN Git Service

* haifa-sched.c (sched_analyze_1, sched_analyze_2, sched_analyze):
[pf3gnuchains/gcc-fork.git] / gcc / haifa-sched.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000 Free Software Foundation, Inc.
4    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
5    and currently maintained by, Jim Wilson (wilson@cygnus.com)
6
7 This file is part of GNU CC.
8
9 GNU CC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 GNU CC is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GNU CC; see the file COPYING.  If not, write to the Free
21 the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 02111-1307, USA.  */
23
24 /* Instruction scheduling pass.
25
26    This pass implements list scheduling within basic blocks.  It is
27    run twice: (1) after flow analysis, but before register allocation,
28    and (2) after register allocation.
29
30    The first run performs interblock scheduling, moving insns between
31    different blocks in the same "region", and the second runs only
32    basic block scheduling.
33
34    Interblock motions performed are useful motions and speculative
35    motions, including speculative loads.  Motions requiring code
36    duplication are not supported.  The identification of motion type
37    and the check for validity of speculative motions requires
38    construction and analysis of the function's control flow graph.
39    The scheduler works as follows:
40
41    We compute insn priorities based on data dependencies.  Flow
42    analysis only creates a fraction of the data-dependencies we must
43    observe: namely, only those dependencies which the combiner can be
44    expected to use.  For this pass, we must therefore create the
45    remaining dependencies we need to observe: register dependencies,
46    memory dependencies, dependencies to keep function calls in order,
47    and the dependence between a conditional branch and the setting of
48    condition codes are all dealt with here.
49
50    The scheduler first traverses the data flow graph, starting with
51    the last instruction, and proceeding to the first, assigning values
52    to insn_priority as it goes.  This sorts the instructions
53    topologically by data dependence.
54
55    Once priorities have been established, we order the insns using
56    list scheduling.  This works as follows: starting with a list of
57    all the ready insns, and sorted according to priority number, we
58    schedule the insn from the end of the list by placing its
59    predecessors in the list according to their priority order.  We
60    consider this insn scheduled by setting the pointer to the "end" of
61    the list to point to the previous insn.  When an insn has no
62    predecessors, we either queue it until sufficient time has elapsed
63    or add it to the ready list.  As the instructions are scheduled or
64    when stalls are introduced, the queue advances and dumps insns into
65    the ready list.  When all insns down to the lowest priority have
66    been scheduled, the critical path of the basic block has been made
67    as short as possible.  The remaining insns are then scheduled in
68    remaining slots.
69
70    Function unit conflicts are resolved during forward list scheduling
71    by tracking the time when each insn is committed to the schedule
72    and from that, the time the function units it uses must be free.
73    As insns on the ready list are considered for scheduling, those
74    that would result in a blockage of the already committed insns are
75    queued until no blockage will result.
76
77    The following list shows the order in which we want to break ties
78    among insns in the ready list:
79
80    1.  choose insn with the longest path to end of bb, ties
81    broken by
82    2.  choose insn with least contribution to register pressure,
83    ties broken by
84    3.  prefer in-block upon interblock motion, ties broken by
85    4.  prefer useful upon speculative motion, ties broken by
86    5.  choose insn with largest control flow probability, ties
87    broken by
88    6.  choose insn with the least dependences upon the previously
89    scheduled insn, or finally
90    7   choose the insn which has the most insns dependent on it.
91    8.  choose insn with lowest UID.
92
93    Memory references complicate matters.  Only if we can be certain
94    that memory references are not part of the data dependency graph
95    (via true, anti, or output dependence), can we move operations past
96    memory references.  To first approximation, reads can be done
97    independently, while writes introduce dependencies.  Better
98    approximations will yield fewer dependencies.
99
100    Before reload, an extended analysis of interblock data dependences
101    is required for interblock scheduling.  This is performed in
102    compute_block_backward_dependences ().
103
104    Dependencies set up by memory references are treated in exactly the
105    same way as other dependencies, by using LOG_LINKS backward
106    dependences.  LOG_LINKS are translated into INSN_DEPEND forward
107    dependences for the purpose of forward list scheduling.
108
109    Having optimized the critical path, we may have also unduly
110    extended the lifetimes of some registers.  If an operation requires
111    that constants be loaded into registers, it is certainly desirable
112    to load those constants as early as necessary, but no earlier.
113    I.e., it will not do to load up a bunch of registers at the
114    beginning of a basic block only to use them at the end, if they
115    could be loaded later, since this may result in excessive register
116    utilization.
117
118    Note that since branches are never in basic blocks, but only end
119    basic blocks, this pass will not move branches.  But that is ok,
120    since we can use GNU's delayed branch scheduling pass to take care
121    of this case.
122
123    Also note that no further optimizations based on algebraic
124    identities are performed, so this pass would be a good one to
125    perform instruction splitting, such as breaking up a multiply
126    instruction into shifts and adds where that is profitable.
127
128    Given the memory aliasing analysis that this pass should perform,
129    it should be possible to remove redundant stores to memory, and to
130    load values from registers instead of hitting memory.
131
132    Before reload, speculative insns are moved only if a 'proof' exists
133    that no exception will be caused by this, and if no live registers
134    exist that inhibit the motion (live registers constraints are not
135    represented by data dependence edges).
136
137    This pass must update information that subsequent passes expect to
138    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
139    reg_n_calls_crossed, and reg_live_length.  Also, BLOCK_HEAD,
140    BLOCK_END.
141
142    The information in the line number notes is carefully retained by
143    this pass.  Notes that refer to the starting and ending of
144    exception regions are also carefully retained by this pass.  All
145    other NOTE insns are grouped in their same relative order at the
146    beginning of basic blocks and regions that have been scheduled.
147
148    The main entry point for this pass is schedule_insns(), called for
149    each function.  The work of the scheduler is organized in three
150    levels: (1) function level: insns are subject to splitting,
151    control-flow-graph is constructed, regions are computed (after
152    reload, each region is of one block), (2) region level: control
153    flow graph attributes required for interblock scheduling are
154    computed (dominators, reachability, etc.), data dependences and
155    priorities are computed, and (3) block level: insns in the block
156    are actually scheduled.  */
157 \f
158 #include "config.h"
159 #include "system.h"
160 #include "toplev.h"
161 #include "rtl.h"
162 #include "tm_p.h"
163 #include "hard-reg-set.h"
164 #include "basic-block.h"
165 #include "regs.h"
166 #include "function.h"
167 #include "flags.h"
168 #include "insn-config.h"
169 #include "insn-attr.h"
170 #include "except.h"
171 #include "toplev.h"
172 #include "recog.h"
173
174 extern char *reg_known_equiv_p;
175 extern rtx *reg_known_value;
176
177 #ifdef INSN_SCHEDULING
178
179 /* target_units bitmask has 1 for each unit in the cpu.  It should be
180    possible to compute this variable from the machine description.
181    But currently it is computed by examining the insn list.  Since
182    this is only needed for visualization, it seems an acceptable
183    solution.  (For understanding the mapping of bits to units, see
184    definition of function_units[] in "insn-attrtab.c".)  */
185
186 static int target_units = 0;
187
188 /* issue_rate is the number of insns that can be scheduled in the same
189    machine cycle.  It can be defined in the config/mach/mach.h file,
190    otherwise we set it to 1.  */
191
192 static int issue_rate;
193
194 #ifndef ISSUE_RATE
195 #define ISSUE_RATE 1
196 #endif
197
198 /* sched-verbose controls the amount of debugging output the
199    scheduler prints.  It is controlled by -fsched-verbose=N:
200    N>0 and no -DSR : the output is directed to stderr.
201    N>=10 will direct the printouts to stderr (regardless of -dSR).
202    N=1: same as -dSR.
203    N=2: bb's probabilities, detailed ready list info, unit/insn info.
204    N=3: rtl at abort point, control-flow, regions info.
205    N=5: dependences info.  */
206
207 #define MAX_RGN_BLOCKS 10
208 #define MAX_RGN_INSNS 100
209
210 static int sched_verbose_param = 0;
211 static int sched_verbose = 0;
212
213 /* nr_inter/spec counts interblock/speculative motion for the function.  */
214 static int nr_inter, nr_spec;
215
216 /* Debugging file.  All printouts are sent to dump, which is always set,
217    either to stderr, or to the dump listing file (-dRS).  */
218 static FILE *dump = 0;
219
220 /* fix_sched_param() is called from toplev.c upon detection
221    of the -fsched-verbose=N option.  */
222
223 void
224 fix_sched_param (param, val)
225      const char *param, *val;
226 {
227   if (!strcmp (param, "verbose"))
228     sched_verbose_param = atoi (val);
229   else
230     warning ("fix_sched_param: unknown param: %s", param);
231 }
232
233 /* Describe state of dependencies used during sched_analyze phase.  */
234 struct deps
235 {
236   /* The *_insns and *_mems are paired lists.  Each pending memory operation
237      will have a pointer to the MEM rtx on one list and a pointer to the
238      containing insn on the other list in the same place in the list.  */
239
240   /* We can't use add_dependence like the old code did, because a single insn
241      may have multiple memory accesses, and hence needs to be on the list
242      once for each memory access.  Add_dependence won't let you add an insn
243      to a list more than once.  */
244
245   /* An INSN_LIST containing all insns with pending read operations.  */
246   rtx pending_read_insns;
247
248   /* An EXPR_LIST containing all MEM rtx's which are pending reads.  */
249   rtx pending_read_mems;
250
251   /* An INSN_LIST containing all insns with pending write operations.  */
252   rtx pending_write_insns;
253
254   /* An EXPR_LIST containing all MEM rtx's which are pending writes.  */
255   rtx pending_write_mems;
256
257   /* Indicates the combined length of the two pending lists.  We must prevent
258      these lists from ever growing too large since the number of dependencies
259      produced is at least O(N*N), and execution time is at least O(4*N*N), as
260      a function of the length of these pending lists.  */
261   int pending_lists_length;
262
263   /* The last insn upon which all memory references must depend.
264      This is an insn which flushed the pending lists, creating a dependency
265      between it and all previously pending memory references.  This creates
266      a barrier (or a checkpoint) which no memory reference is allowed to cross.
267
268      This includes all non constant CALL_INSNs.  When we do interprocedural
269      alias analysis, this restriction can be relaxed.
270      This may also be an INSN that writes memory if the pending lists grow
271      too large.  */
272   rtx last_pending_memory_flush;
273
274   /* The last function call we have seen.  All hard regs, and, of course,
275      the last function call, must depend on this.  */
276   rtx last_function_call;
277
278   /* Used to keep post-call psuedo/hard reg movements together with
279      the call.  */
280   int in_post_call_group_p;
281
282   /* The LOG_LINKS field of this is a list of insns which use a pseudo
283      register that does not already cross a call.  We create
284      dependencies between each of those insn and the next call insn,
285      to ensure that they won't cross a call after scheduling is done.  */
286   rtx sched_before_next_call;
287
288   /* Element N is the next insn that sets (hard or pseudo) register
289      N within the current basic block; or zero, if there is no
290      such insn.  Needed for new registers which may be introduced
291      by splitting insns.  */
292   rtx *reg_last_uses;
293   rtx *reg_last_sets;
294   rtx *reg_last_clobbers;
295 };
296
297 static regset reg_pending_sets;
298 static regset reg_pending_clobbers;
299 static int reg_pending_sets_all;
300
301 /* To speed up the test for duplicate dependency links we keep a
302    record of dependencies created by add_dependence when the average
303    number of instructions in a basic block is very large.
304
305    Studies have shown that there is typically around 5 instructions between
306    branches for typical C code.  So we can make a guess that the average
307    basic block is approximately 5 instructions long; we will choose 100X
308    the average size as a very large basic block.
309
310    Each insn has associated bitmaps for its dependencies.  Each bitmap
311    has enough entries to represent a dependency on any other insn in
312    the insn chain.  All bitmap for true dependencies cache is
313    allocated then the rest two ones are also allocated. */
314 static sbitmap *true_dependency_cache;
315 static sbitmap *anti_dependency_cache;
316 static sbitmap *output_dependency_cache;
317
318 /* To speed up checking consistency of formed forward insn
319    dependencies we use the following cache.  Another possible solution
320    could be switching off checking duplication of insns in forward
321    dependencies. */
322 #ifdef ENABLE_CHECKING
323 static sbitmap *forward_dependency_cache;
324 #endif
325
326 /* Indexed by INSN_UID, the collection of all data associated with
327    a single instruction.  */
328
329 struct haifa_insn_data
330 {
331   /* A list of insns which depend on the instruction.  Unlike LOG_LINKS,
332      it represents forward dependancies.  */
333   rtx depend;
334
335   /* The line number note in effect for each insn.  For line number
336      notes, this indicates whether the note may be reused.  */
337   rtx line_note;
338
339   /* Logical uid gives the original ordering of the insns.  */
340   int luid;
341
342   /* A priority for each insn.  */
343   int priority;
344
345   /* The number of incoming edges in the forward dependency graph.
346      As scheduling proceds, counts are decreased.  An insn moves to
347      the ready queue when its counter reaches zero.  */
348   int dep_count;
349
350   /* An encoding of the blockage range function.  Both unit and range
351      are coded.  */
352   unsigned int blockage;
353
354   /* Number of instructions referring to this insn.  */
355   int ref_count;
356
357   /* The minimum clock tick at which the insn becomes ready.  This is
358      used to note timing constraints for the insns in the pending list.  */
359   int tick;
360
361   short cost;
362
363   /* An encoding of the function units used.  */
364   short units;
365
366   /* This weight is an estimation of the insn's contribution to
367      register pressure.  */
368   short reg_weight;
369
370   /* Some insns (e.g. call) are not allowed to move across blocks.  */
371   unsigned int cant_move : 1;
372
373   /* Set if there's DEF-USE dependance between some speculatively
374      moved load insn and this one.  */
375   unsigned int fed_by_spec_load : 1;
376   unsigned int is_load_insn : 1;
377 };
378
379 static struct haifa_insn_data *h_i_d;
380
381 #define INSN_DEPEND(INSN)       (h_i_d[INSN_UID (INSN)].depend)
382 #define INSN_LUID(INSN)         (h_i_d[INSN_UID (INSN)].luid)
383 #define INSN_PRIORITY(INSN)     (h_i_d[INSN_UID (INSN)].priority)
384 #define INSN_DEP_COUNT(INSN)    (h_i_d[INSN_UID (INSN)].dep_count)
385 #define INSN_COST(INSN)         (h_i_d[INSN_UID (INSN)].cost)
386 #define INSN_UNIT(INSN)         (h_i_d[INSN_UID (INSN)].units)
387 #define INSN_REG_WEIGHT(INSN)   (h_i_d[INSN_UID (INSN)].reg_weight)
388
389 #define INSN_BLOCKAGE(INSN)     (h_i_d[INSN_UID (INSN)].blockage)
390 #define UNIT_BITS               5
391 #define BLOCKAGE_MASK           ((1 << BLOCKAGE_BITS) - 1)
392 #define ENCODE_BLOCKAGE(U, R)                   \
393   (((U) << BLOCKAGE_BITS                        \
394     | MIN_BLOCKAGE_COST (R)) << BLOCKAGE_BITS   \
395    | MAX_BLOCKAGE_COST (R))
396 #define UNIT_BLOCKED(B)         ((B) >> (2 * BLOCKAGE_BITS))
397 #define BLOCKAGE_RANGE(B)                                                \
398   (((((B) >> BLOCKAGE_BITS) & BLOCKAGE_MASK) << (HOST_BITS_PER_INT / 2)) \
399    | ((B) & BLOCKAGE_MASK))
400
401 /* Encodings of the `<name>_unit_blockage_range' function.  */
402 #define MIN_BLOCKAGE_COST(R) ((R) >> (HOST_BITS_PER_INT / 2))
403 #define MAX_BLOCKAGE_COST(R) ((R) & ((1 << (HOST_BITS_PER_INT / 2)) - 1))
404
405 #define DONE_PRIORITY   -1
406 #define MAX_PRIORITY    0x7fffffff
407 #define TAIL_PRIORITY   0x7ffffffe
408 #define LAUNCH_PRIORITY 0x7f000001
409 #define DONE_PRIORITY_P(INSN) (INSN_PRIORITY (INSN) < 0)
410 #define LOW_PRIORITY_P(INSN) ((INSN_PRIORITY (INSN) & 0x7f000000) == 0)
411
412 #define INSN_REF_COUNT(INSN)    (h_i_d[INSN_UID (INSN)].ref_count)
413 #define LINE_NOTE(INSN)         (h_i_d[INSN_UID (INSN)].line_note)
414 #define INSN_TICK(INSN)         (h_i_d[INSN_UID (INSN)].tick)
415 #define CANT_MOVE(insn)         (h_i_d[INSN_UID (insn)].cant_move)
416 #define FED_BY_SPEC_LOAD(insn)  (h_i_d[INSN_UID (insn)].fed_by_spec_load)
417 #define IS_LOAD_INSN(insn)      (h_i_d[INSN_UID (insn)].is_load_insn)
418
419 /* Vector indexed by basic block number giving the starting line-number
420    for each basic block.  */
421 static rtx *line_note_head;
422
423 /* List of important notes we must keep around.  This is a pointer to the
424    last element in the list.  */
425 static rtx note_list;
426
427 /* Queues, etc.  */
428
429 /* An instruction is ready to be scheduled when all insns preceding it
430    have already been scheduled.  It is important to ensure that all
431    insns which use its result will not be executed until its result
432    has been computed.  An insn is maintained in one of four structures:
433
434    (P) the "Pending" set of insns which cannot be scheduled until
435    their dependencies have been satisfied.
436    (Q) the "Queued" set of insns that can be scheduled when sufficient
437    time has passed.
438    (R) the "Ready" list of unscheduled, uncommitted insns.
439    (S) the "Scheduled" list of insns.
440
441    Initially, all insns are either "Pending" or "Ready" depending on
442    whether their dependencies are satisfied.
443
444    Insns move from the "Ready" list to the "Scheduled" list as they
445    are committed to the schedule.  As this occurs, the insns in the
446    "Pending" list have their dependencies satisfied and move to either
447    the "Ready" list or the "Queued" set depending on whether
448    sufficient time has passed to make them ready.  As time passes,
449    insns move from the "Queued" set to the "Ready" list.  Insns may
450    move from the "Ready" list to the "Queued" set if they are blocked
451    due to a function unit conflict.
452
453    The "Pending" list (P) are the insns in the INSN_DEPEND of the unscheduled
454    insns, i.e., those that are ready, queued, and pending.
455    The "Queued" set (Q) is implemented by the variable `insn_queue'.
456    The "Ready" list (R) is implemented by the variables `ready' and
457    `n_ready'.
458    The "Scheduled" list (S) is the new insn chain built by this pass.
459
460    The transition (R->S) is implemented in the scheduling loop in
461    `schedule_block' when the best insn to schedule is chosen.
462    The transition (R->Q) is implemented in `queue_insn' when an
463    insn is found to have a function unit conflict with the already
464    committed insns.
465    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
466    insns move from the ready list to the scheduled list.
467    The transition (Q->R) is implemented in 'queue_to_insn' as time
468    passes or stalls are introduced.  */
469
470 /* Implement a circular buffer to delay instructions until sufficient
471    time has passed.  INSN_QUEUE_SIZE is a power of two larger than
472    MAX_BLOCKAGE and MAX_READY_COST computed by genattr.c.  This is the
473    longest time an isnsn may be queued.  */
474 static rtx insn_queue[INSN_QUEUE_SIZE];
475 static int q_ptr = 0;
476 static int q_size = 0;
477 #define NEXT_Q(X) (((X)+1) & (INSN_QUEUE_SIZE-1))
478 #define NEXT_Q_AFTER(X, C) (((X)+C) & (INSN_QUEUE_SIZE-1))
479
480 /* Describe the ready list of the scheduler.
481    VEC holds space enough for all insns in the current region.  VECLEN
482    says how many exactly.
483    FIRST is the index of the element with the highest priority; i.e. the
484    last one in the ready list, since elements are ordered by ascending
485    priority.
486    N_READY determines how many insns are on the ready list.  */
487
488 struct ready_list
489 {
490   rtx *vec;
491   int veclen;
492   int first;
493   int n_ready;
494 };
495
496 /* Forward declarations.  */
497 static void add_dependence PARAMS ((rtx, rtx, enum reg_note));
498 static void remove_dependence PARAMS ((rtx, rtx));
499 static rtx find_insn_list PARAMS ((rtx, rtx));
500 static void set_sched_group_p PARAMS ((rtx));
501 static int insn_unit PARAMS ((rtx));
502 static unsigned int blockage_range PARAMS ((int, rtx));
503 static void clear_units PARAMS ((void));
504 static int actual_hazard_this_instance PARAMS ((int, int, rtx, int, int));
505 static void schedule_unit PARAMS ((int, rtx, int));
506 static int actual_hazard PARAMS ((int, rtx, int, int));
507 static int potential_hazard PARAMS ((int, rtx, int));
508 static int insn_cost PARAMS ((rtx, rtx, rtx));
509 static int priority PARAMS ((rtx));
510 static void free_pending_lists PARAMS ((void));
511 static void add_insn_mem_dependence PARAMS ((struct deps *, rtx *, rtx *, rtx,
512                                              rtx));
513 static void flush_pending_lists PARAMS ((struct deps *, rtx, int));
514 static void sched_analyze_1 PARAMS ((struct deps *, rtx, rtx));
515 static void sched_analyze_2 PARAMS ((struct deps *, rtx, rtx));
516 static void sched_analyze_insn PARAMS ((struct deps *, rtx, rtx, rtx));
517 static void sched_analyze PARAMS ((struct deps *, rtx, rtx));
518 static int rank_for_schedule PARAMS ((const PTR, const PTR));
519 static void swap_sort PARAMS ((rtx *, int));
520 static void queue_insn PARAMS ((rtx, int));
521 static void schedule_insn PARAMS ((rtx, struct ready_list *, int));
522 static void find_insn_reg_weight PARAMS ((int));
523 static int schedule_block PARAMS ((int, int));
524 static char *safe_concat PARAMS ((char *, char *, const char *));
525 static int insn_issue_delay PARAMS ((rtx));
526 static void adjust_priority PARAMS ((rtx));
527
528 /* Control flow graph edges are kept in circular lists.  */
529 typedef struct
530 {
531   int from_block;
532   int to_block;
533   int next_in;
534   int next_out;
535 }
536 haifa_edge;
537 static haifa_edge *edge_table;
538
539 #define NEXT_IN(edge) (edge_table[edge].next_in)
540 #define NEXT_OUT(edge) (edge_table[edge].next_out)
541 #define FROM_BLOCK(edge) (edge_table[edge].from_block)
542 #define TO_BLOCK(edge) (edge_table[edge].to_block)
543
544 /* Number of edges in the control flow graph.  (In fact, larger than
545    that by 1, since edge 0 is unused.)  */
546 static int nr_edges;
547
548 /* Circular list of incoming/outgoing edges of a block.  */
549 static int *in_edges;
550 static int *out_edges;
551
552 #define IN_EDGES(block) (in_edges[block])
553 #define OUT_EDGES(block) (out_edges[block])
554
555 static int is_cfg_nonregular PARAMS ((void));
556 static int build_control_flow PARAMS ((struct edge_list *));
557 static void new_edge PARAMS ((int, int));
558
559 /* A region is the main entity for interblock scheduling: insns
560    are allowed to move between blocks in the same region, along
561    control flow graph edges, in the 'up' direction.  */
562 typedef struct
563 {
564   int rgn_nr_blocks;            /* Number of blocks in region.  */
565   int rgn_blocks;               /* cblocks in the region (actually index in rgn_bb_table).  */
566 }
567 region;
568
569 /* Number of regions in the procedure.  */
570 static int nr_regions;
571
572 /* Table of region descriptions.  */
573 static region *rgn_table;
574
575 /* Array of lists of regions' blocks.  */
576 static int *rgn_bb_table;
577
578 /* Topological order of blocks in the region (if b2 is reachable from
579    b1, block_to_bb[b2] > block_to_bb[b1]).  Note: A basic block is
580    always referred to by either block or b, while its topological
581    order name (in the region) is refered to by bb.  */
582 static int *block_to_bb;
583
584 /* The number of the region containing a block.  */
585 static int *containing_rgn;
586
587 #define RGN_NR_BLOCKS(rgn) (rgn_table[rgn].rgn_nr_blocks)
588 #define RGN_BLOCKS(rgn) (rgn_table[rgn].rgn_blocks)
589 #define BLOCK_TO_BB(block) (block_to_bb[block])
590 #define CONTAINING_RGN(block) (containing_rgn[block])
591
592 void debug_regions PARAMS ((void));
593 static void find_single_block_region PARAMS ((void));
594 static void find_rgns PARAMS ((struct edge_list *, sbitmap *));
595 static int too_large PARAMS ((int, int *, int *));
596
597 extern void debug_live PARAMS ((int, int));
598
599 /* Blocks of the current region being scheduled.  */
600 static int current_nr_blocks;
601 static int current_blocks;
602
603 /* The mapping from bb to block.  */
604 #define BB_TO_BLOCK(bb) (rgn_bb_table[current_blocks + (bb)])
605
606 /* Bit vectors and bitset operations are needed for computations on
607    the control flow graph.  */
608
609 typedef unsigned HOST_WIDE_INT *bitset;
610 typedef struct
611 {
612   int *first_member;            /* Pointer to the list start in bitlst_table.  */
613   int nr_members;               /* The number of members of the bit list.  */
614 }
615 bitlst;
616
617 static int bitlst_table_last;
618 static int bitlst_table_size;
619 static int *bitlst_table;
620
621 static char bitset_member PARAMS ((bitset, int, int));
622 static void extract_bitlst PARAMS ((bitset, int, int, bitlst *));
623
624 /* Target info declarations.
625
626    The block currently being scheduled is referred to as the "target" block,
627    while other blocks in the region from which insns can be moved to the
628    target are called "source" blocks.  The candidate structure holds info
629    about such sources: are they valid?  Speculative?  Etc.  */
630 typedef bitlst bblst;
631 typedef struct
632 {
633   char is_valid;
634   char is_speculative;
635   int src_prob;
636   bblst split_bbs;
637   bblst update_bbs;
638 }
639 candidate;
640
641 static candidate *candidate_table;
642
643 /* A speculative motion requires checking live information on the path
644    from 'source' to 'target'.  The split blocks are those to be checked.
645    After a speculative motion, live information should be modified in
646    the 'update' blocks.
647
648    Lists of split and update blocks for each candidate of the current
649    target are in array bblst_table.  */
650 static int *bblst_table, bblst_size, bblst_last;
651
652 #define IS_VALID(src) ( candidate_table[src].is_valid )
653 #define IS_SPECULATIVE(src) ( candidate_table[src].is_speculative )
654 #define SRC_PROB(src) ( candidate_table[src].src_prob )
655
656 /* The bb being currently scheduled.  */
657 static int target_bb;
658
659 /* List of edges.  */
660 typedef bitlst edgelst;
661
662 /* Target info functions.  */
663 static void split_edges PARAMS ((int, int, edgelst *));
664 static void compute_trg_info PARAMS ((int));
665 void debug_candidate PARAMS ((int));
666 void debug_candidates PARAMS ((int));
667
668 /* Bit-set of bbs, where bit 'i' stands for bb 'i'.  */
669 typedef bitset bbset;
670
671 /* Number of words of the bbset.  */
672 static int bbset_size;
673
674 /* Dominators array: dom[i] contains the bbset of dominators of
675    bb i in the region.  */
676 static bbset *dom;
677
678 /* bb 0 is the only region entry.  */
679 #define IS_RGN_ENTRY(bb) (!bb)
680
681 /* Is bb_src dominated by bb_trg.  */
682 #define IS_DOMINATED(bb_src, bb_trg)                                 \
683 ( bitset_member (dom[bb_src], bb_trg, bbset_size) )
684
685 /* Probability: Prob[i] is a float in [0, 1] which is the probability
686    of bb i relative to the region entry.  */
687 static float *prob;
688
689 /* The probability of bb_src, relative to bb_trg.  Note, that while the
690    'prob[bb]' is a float in [0, 1], this macro returns an integer
691    in [0, 100].  */
692 #define GET_SRC_PROB(bb_src, bb_trg) ((int) (100.0 * (prob[bb_src] / \
693                                                       prob[bb_trg])))
694
695 /* Bit-set of edges, where bit i stands for edge i.  */
696 typedef bitset edgeset;
697
698 /* Number of edges in the region.  */
699 static int rgn_nr_edges;
700
701 /* Array of size rgn_nr_edges.  */
702 static int *rgn_edges;
703
704 /* Number of words in an edgeset.  */
705 static int edgeset_size;
706
707 /* Number of bits in an edgeset.  */
708 static int edgeset_bitsize;
709
710 /* Mapping from each edge in the graph to its number in the rgn.  */
711 static int *edge_to_bit;
712 #define EDGE_TO_BIT(edge) (edge_to_bit[edge])
713
714 /* The split edges of a source bb is different for each target
715    bb.  In order to compute this efficiently, the 'potential-split edges'
716    are computed for each bb prior to scheduling a region.  This is actually
717    the split edges of each bb relative to the region entry.
718
719    pot_split[bb] is the set of potential split edges of bb.  */
720 static edgeset *pot_split;
721
722 /* For every bb, a set of its ancestor edges.  */
723 static edgeset *ancestor_edges;
724
725 static void compute_dom_prob_ps PARAMS ((int));
726
727 #define ABS_VALUE(x) (((x)<0)?(-(x)):(x))
728 #define INSN_PROBABILITY(INSN) (SRC_PROB (BLOCK_TO_BB (BLOCK_NUM (INSN))))
729 #define IS_SPECULATIVE_INSN(INSN) (IS_SPECULATIVE (BLOCK_TO_BB (BLOCK_NUM (INSN))))
730 #define INSN_BB(INSN) (BLOCK_TO_BB (BLOCK_NUM (INSN)))
731
732 /* Parameters affecting the decision of rank_for_schedule().  */
733 #define MIN_DIFF_PRIORITY 2
734 #define MIN_PROBABILITY 40
735 #define MIN_PROB_DIFF 10
736
737 /* Speculative scheduling functions.  */
738 static int check_live_1 PARAMS ((int, rtx));
739 static void update_live_1 PARAMS ((int, rtx));
740 static int check_live PARAMS ((rtx, int));
741 static void update_live PARAMS ((rtx, int));
742 static void set_spec_fed PARAMS ((rtx));
743 static int is_pfree PARAMS ((rtx, int, int));
744 static int find_conditional_protection PARAMS ((rtx, int));
745 static int is_conditionally_protected PARAMS ((rtx, int, int));
746 static int may_trap_exp PARAMS ((rtx, int));
747 static int haifa_classify_insn PARAMS ((rtx));
748 static int is_prisky PARAMS ((rtx, int, int));
749 static int is_exception_free PARAMS ((rtx, int, int));
750
751 static char find_insn_mem_list PARAMS ((rtx, rtx, rtx, rtx));
752 static void compute_block_forward_dependences PARAMS ((int));
753 static void add_branch_dependences PARAMS ((rtx, rtx));
754 static void compute_block_backward_dependences PARAMS ((int));
755 void debug_dependencies PARAMS ((void));
756
757 /* Notes handling mechanism:
758    =========================
759    Generally, NOTES are saved before scheduling and restored after scheduling.
760    The scheduler distinguishes between three types of notes:
761
762    (1) LINE_NUMBER notes, generated and used for debugging.  Here,
763    before scheduling a region, a pointer to the LINE_NUMBER note is
764    added to the insn following it (in save_line_notes()), and the note
765    is removed (in rm_line_notes() and unlink_line_notes()).  After
766    scheduling the region, this pointer is used for regeneration of
767    the LINE_NUMBER note (in restore_line_notes()).
768
769    (2) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
770    Before scheduling a region, a pointer to the note is added to the insn
771    that follows or precedes it.  (This happens as part of the data dependence
772    computation).  After scheduling an insn, the pointer contained in it is
773    used for regenerating the corresponding note (in reemit_notes).
774
775    (3) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
776    these notes are put in a list (in rm_other_notes() and
777    unlink_other_notes ()).  After scheduling the block, these notes are
778    inserted at the beginning of the block (in schedule_block()).  */
779
780 static rtx unlink_other_notes PARAMS ((rtx, rtx));
781 static rtx unlink_line_notes PARAMS ((rtx, rtx));
782 static void rm_line_notes PARAMS ((int));
783 static void save_line_notes PARAMS ((int));
784 static void restore_line_notes PARAMS ((int));
785 static void rm_redundant_line_notes PARAMS ((void));
786 static void rm_other_notes PARAMS ((rtx, rtx));
787 static rtx reemit_notes PARAMS ((rtx, rtx));
788
789 static void get_block_head_tail PARAMS ((int, rtx *, rtx *));
790 static void get_bb_head_tail PARAMS ((int, rtx *, rtx *));
791
792 static void ready_add PARAMS ((struct ready_list *, rtx));
793 static rtx *ready_lastpos PARAMS ((struct ready_list *));
794 static void ready_sort PARAMS ((struct ready_list *));
795 static rtx ready_remove_first PARAMS ((struct ready_list *));
796
797 static void queue_to_ready PARAMS ((struct ready_list *));
798
799 static void debug_ready_list PARAMS ((struct ready_list *));
800 static void init_target_units PARAMS ((void));
801 static void insn_print_units PARAMS ((rtx));
802 static int get_visual_tbl_length PARAMS ((void));
803 static void init_block_visualization PARAMS ((void));
804 static void print_block_visualization PARAMS ((int, const char *));
805 static void visualize_scheduled_insns PARAMS ((int, int));
806 static void visualize_no_unit PARAMS ((rtx));
807 static void visualize_stall_cycles PARAMS ((int, int));
808 static void print_exp PARAMS ((char *, rtx, int));
809 static void print_value PARAMS ((char *, rtx, int));
810 static void print_pattern PARAMS ((char *, rtx, int));
811 static void print_insn PARAMS ((char *, rtx, int));
812 void debug_reg_vector PARAMS ((regset));
813
814 static rtx move_insn1 PARAMS ((rtx, rtx));
815 static rtx move_insn PARAMS ((rtx, rtx));
816 static rtx group_leader PARAMS ((rtx));
817 static int set_priorities PARAMS ((int));
818 static void init_deps PARAMS ((struct deps *));
819 static void schedule_region PARAMS ((int));
820 static void propagate_deps PARAMS ((int, struct deps *, int));
821
822 #endif /* INSN_SCHEDULING */
823 \f
824 #define SIZE_FOR_MODE(X) (GET_MODE_SIZE (GET_MODE (X)))
825
826 /* Add ELEM wrapped in an INSN_LIST with reg note kind DEP_TYPE to the
827    LOG_LINKS of INSN, if not already there.  DEP_TYPE indicates the type
828    of dependence that this link represents.  */
829
830 static void
831 add_dependence (insn, elem, dep_type)
832      rtx insn;
833      rtx elem;
834      enum reg_note dep_type;
835 {
836   rtx link, next;
837   int present_p;
838   enum reg_note present_dep_type;
839
840   /* Don't depend an insn on itself.  */
841   if (insn == elem)
842     return;
843
844   /* We can get a dependency on deleted insns due to optimizations in
845      the register allocation and reloading or due to splitting.  Any
846      such dependency is useless and can be ignored.  */
847   if (GET_CODE (elem) == NOTE)
848     return;
849
850   /* If elem is part of a sequence that must be scheduled together, then
851      make the dependence point to the last insn of the sequence.
852      When HAVE_cc0, it is possible for NOTEs to exist between users and
853      setters of the condition codes, so we must skip past notes here.
854      Otherwise, NOTEs are impossible here.  */
855   next = next_nonnote_insn (elem);
856   if (next && SCHED_GROUP_P (next)
857       && GET_CODE (next) != CODE_LABEL)
858     {
859       /* Notes will never intervene here though, so don't bother checking
860          for them.  */
861       /* Hah!  Wrong.  */
862       /* We must reject CODE_LABELs, so that we don't get confused by one
863          that has LABEL_PRESERVE_P set, which is represented by the same
864          bit in the rtl as SCHED_GROUP_P.  A CODE_LABEL can never be
865          SCHED_GROUP_P.  */
866
867       rtx nnext;
868       while ((nnext = next_nonnote_insn (next)) != NULL
869              && SCHED_GROUP_P (nnext)
870              && GET_CODE (nnext) != CODE_LABEL)
871         next = nnext;
872
873       /* Again, don't depend an insn on itself.  */
874       if (insn == next)
875         return;
876
877       /* Make the dependence to NEXT, the last insn of the group, instead
878          of the original ELEM.  */
879       elem = next;
880     }
881
882   present_p = 1;
883 #ifdef INSN_SCHEDULING
884   /* (This code is guarded by INSN_SCHEDULING, otherwise INSN_BB is undefined.)
885      No need for interblock dependences with calls, since
886      calls are not moved between blocks.   Note: the edge where
887      elem is a CALL is still required.  */
888   if (GET_CODE (insn) == CALL_INSN
889       && (INSN_BB (elem) != INSN_BB (insn)))
890     return;
891
892   /* If we already have a dependency for ELEM, then we do not need to
893      do anything.  Avoiding the list walk below can cut compile times
894      dramatically for some code.  */
895   if (true_dependency_cache != NULL)
896     {
897       if (anti_dependency_cache == NULL || output_dependency_cache == NULL)
898         abort ();
899       if (TEST_BIT (true_dependency_cache[INSN_LUID (insn)], INSN_LUID (elem)))
900         present_dep_type = 0;
901       else if (TEST_BIT (anti_dependency_cache[INSN_LUID (insn)],
902                          INSN_LUID (elem)))
903         present_dep_type = REG_DEP_ANTI;
904       else if (TEST_BIT (output_dependency_cache[INSN_LUID (insn)],
905                          INSN_LUID (elem)))
906         present_dep_type = REG_DEP_OUTPUT;
907       else 
908         present_p = 0;
909       if (present_p && (int) dep_type >= (int) present_dep_type)
910         return;
911     }
912 #endif
913
914   /* Check that we don't already have this dependence.  */
915   if (present_p)
916     for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
917       if (XEXP (link, 0) == elem)
918         {
919 #ifdef INSN_SCHEDULING
920           /* Clear corresponding cache entry because type of the link
921              may be changed. */
922           if (true_dependency_cache != NULL)
923             {
924               if (REG_NOTE_KIND (link) == REG_DEP_ANTI)
925                 RESET_BIT (anti_dependency_cache[INSN_LUID (insn)],
926                            INSN_LUID (elem));
927               else if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT
928                        && output_dependency_cache)
929                 RESET_BIT (output_dependency_cache[INSN_LUID (insn)],
930                            INSN_LUID (elem));
931               else
932                 abort ();
933             }
934 #endif
935
936           /* If this is a more restrictive type of dependence than the existing
937              one, then change the existing dependence to this type.  */
938           if ((int) dep_type < (int) REG_NOTE_KIND (link))
939             PUT_REG_NOTE_KIND (link, dep_type);
940           
941 #ifdef INSN_SCHEDULING
942           /* If we are adding a dependency to INSN's LOG_LINKs, then
943              note that in the bitmap caches of dependency information. */
944           if (true_dependency_cache != NULL)
945             {
946               if ((int)REG_NOTE_KIND (link) == 0)
947                 SET_BIT (true_dependency_cache[INSN_LUID (insn)],
948                          INSN_LUID (elem));
949               else if (REG_NOTE_KIND (link) == REG_DEP_ANTI)
950                 SET_BIT (anti_dependency_cache[INSN_LUID (insn)],
951                          INSN_LUID (elem));
952               else if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
953                 SET_BIT (output_dependency_cache[INSN_LUID (insn)],
954                          INSN_LUID (elem));
955             }
956 #endif
957           return;
958       }
959   /* Might want to check one level of transitivity to save conses.  */
960
961   link = alloc_INSN_LIST (elem, LOG_LINKS (insn));
962   LOG_LINKS (insn) = link;
963
964   /* Insn dependency, not data dependency.  */
965   PUT_REG_NOTE_KIND (link, dep_type);
966
967 #ifdef INSN_SCHEDULING
968   /* If we are adding a dependency to INSN's LOG_LINKs, then note that
969      in the bitmap caches of dependency information. */
970   if (true_dependency_cache != NULL)
971     {
972       if ((int)dep_type == 0)
973         SET_BIT (true_dependency_cache[INSN_LUID (insn)], INSN_LUID (elem));
974       else if (dep_type == REG_DEP_ANTI)
975         SET_BIT (anti_dependency_cache[INSN_LUID (insn)], INSN_LUID (elem));
976       else if (dep_type == REG_DEP_OUTPUT)
977         SET_BIT (output_dependency_cache[INSN_LUID (insn)], INSN_LUID (elem));
978     }
979 #endif
980 }
981
982 /* Remove ELEM wrapped in an INSN_LIST from the LOG_LINKS
983    of INSN.  Abort if not found.  */
984
985 static void
986 remove_dependence (insn, elem)
987      rtx insn;
988      rtx elem;
989 {
990   rtx prev, link, next;
991   int found = 0;
992
993   for (prev = 0, link = LOG_LINKS (insn); link; link = next)
994     {
995       next = XEXP (link, 1);
996       if (XEXP (link, 0) == elem)
997         {
998           if (prev)
999             XEXP (prev, 1) = next;
1000           else
1001             LOG_LINKS (insn) = next;
1002
1003 #ifdef INSN_SCHEDULING
1004           /* If we are removing a dependency from the LOG_LINKS list,
1005              make sure to remove it from the cache too.  */
1006           if (true_dependency_cache != NULL)
1007             {
1008               if (REG_NOTE_KIND (link) == 0)
1009                 RESET_BIT (true_dependency_cache[INSN_LUID (insn)],
1010                            INSN_LUID (elem));
1011               else if (REG_NOTE_KIND (link) == REG_DEP_ANTI)
1012                 RESET_BIT (anti_dependency_cache[INSN_LUID (insn)],
1013                            INSN_LUID (elem));
1014               else if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
1015                 RESET_BIT (output_dependency_cache[INSN_LUID (insn)],
1016                            INSN_LUID (elem));
1017             }
1018 #endif
1019
1020           free_INSN_LIST_node (link);
1021
1022           found = 1;
1023         }
1024       else
1025         prev = link;
1026     }
1027
1028   if (!found)
1029     abort ();
1030   return;
1031 }
1032
1033 /* Return the INSN_LIST containing INSN in LIST, or NULL
1034    if LIST does not contain INSN.  */
1035
1036 static inline rtx
1037 find_insn_list (insn, list)
1038      rtx insn;
1039      rtx list;
1040 {
1041   while (list)
1042     {
1043       if (XEXP (list, 0) == insn)
1044         return list;
1045       list = XEXP (list, 1);
1046     }
1047   return 0;
1048 }
1049
1050 /* Set SCHED_GROUP_P and care for the rest of the bookkeeping that
1051    goes along with that.  */
1052
1053 static void
1054 set_sched_group_p (insn)
1055      rtx insn;
1056 {
1057   rtx link, prev;
1058
1059   SCHED_GROUP_P (insn) = 1;
1060
1061   /* There may be a note before this insn now, but all notes will
1062      be removed before we actually try to schedule the insns, so
1063      it won't cause a problem later.  We must avoid it here though.  */
1064   prev = prev_nonnote_insn (insn);
1065
1066   /* Make a copy of all dependencies on the immediately previous insn,
1067      and add to this insn.  This is so that all the dependencies will
1068      apply to the group.  Remove an explicit dependence on this insn
1069      as SCHED_GROUP_P now represents it.  */
1070
1071   if (find_insn_list (prev, LOG_LINKS (insn)))
1072     remove_dependence (insn, prev);
1073
1074   for (link = LOG_LINKS (prev); link; link = XEXP (link, 1))
1075     add_dependence (insn, XEXP (link, 0), REG_NOTE_KIND (link));
1076 }
1077 \f
1078 #ifndef INSN_SCHEDULING
1079 void
1080 schedule_insns (dump_file)
1081      FILE *dump_file ATTRIBUTE_UNUSED;
1082 {
1083 }
1084 #else
1085 #ifndef __GNUC__
1086 #define __inline
1087 #endif
1088
1089 #ifndef HAIFA_INLINE
1090 #define HAIFA_INLINE __inline
1091 #endif
1092
1093 /* Computation of memory dependencies.  */
1094
1095 /* Data structures for the computation of data dependences in a regions.  We
1096    keep one mem_deps structure for every basic block.  Before analyzing the
1097    data dependences for a bb, its variables are initialized as a function of
1098    the variables of its predecessors.  When the analysis for a bb completes,
1099    we save the contents to the corresponding bb_mem_deps[bb] variable.  */
1100
1101 static struct deps *bb_deps;
1102
1103 /* Pointer to the last instruction scheduled.  Used by rank_for_schedule,
1104    so that insns independent of the last scheduled insn will be preferred
1105    over dependent instructions.  */
1106
1107 static rtx last_scheduled_insn;
1108
1109 /* Functions for construction of the control flow graph.  */
1110
1111 /* Return 1 if control flow graph should not be constructed, 0 otherwise.
1112
1113    We decide not to build the control flow graph if there is possibly more
1114    than one entry to the function, if computed branches exist, of if we
1115    have nonlocal gotos.  */
1116
1117 static int
1118 is_cfg_nonregular ()
1119 {
1120   int b;
1121   rtx insn;
1122   RTX_CODE code;
1123
1124   /* If we have a label that could be the target of a nonlocal goto, then
1125      the cfg is not well structured.  */
1126   if (nonlocal_goto_handler_labels)
1127     return 1;
1128
1129   /* If we have any forced labels, then the cfg is not well structured.  */
1130   if (forced_labels)
1131     return 1;
1132
1133   /* If this function has a computed jump, then we consider the cfg
1134      not well structured.  */
1135   if (current_function_has_computed_jump)
1136     return 1;
1137
1138   /* If we have exception handlers, then we consider the cfg not well
1139      structured.  ?!?  We should be able to handle this now that flow.c
1140      computes an accurate cfg for EH.  */
1141   if (exception_handler_labels)
1142     return 1;
1143
1144   /* If we have non-jumping insns which refer to labels, then we consider
1145      the cfg not well structured.  */
1146   /* Check for labels referred to other thn by jumps.  */
1147   for (b = 0; b < n_basic_blocks; b++)
1148     for (insn = BLOCK_HEAD (b);; insn = NEXT_INSN (insn))
1149       {
1150         code = GET_CODE (insn);
1151         if (GET_RTX_CLASS (code) == 'i')
1152           {
1153             rtx note;
1154
1155             for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
1156               if (REG_NOTE_KIND (note) == REG_LABEL)
1157                 return 1;
1158           }
1159
1160         if (insn == BLOCK_END (b))
1161           break;
1162       }
1163
1164   /* All the tests passed.  Consider the cfg well structured.  */
1165   return 0;
1166 }
1167
1168 /* Build the control flow graph and set nr_edges.
1169
1170    Instead of trying to build a cfg ourselves, we rely on flow to
1171    do it for us.  Stamp out useless code (and bug) duplication.
1172
1173    Return nonzero if an irregularity in the cfg is found which would
1174    prevent cross block scheduling.  */
1175
1176 static int
1177 build_control_flow (edge_list)
1178      struct edge_list *edge_list;
1179 {
1180   int i, unreachable, num_edges;
1181
1182   /* This already accounts for entry/exit edges.  */
1183   num_edges = NUM_EDGES (edge_list);
1184
1185   /* Unreachable loops with more than one basic block are detected
1186      during the DFS traversal in find_rgns.
1187
1188      Unreachable loops with a single block are detected here.  This
1189      test is redundant with the one in find_rgns, but it's much
1190     cheaper to go ahead and catch the trivial case here.  */
1191   unreachable = 0;
1192   for (i = 0; i < n_basic_blocks; i++)
1193     {
1194       basic_block b = BASIC_BLOCK (i);
1195
1196       if (b->pred == NULL
1197           || (b->pred->src == b
1198               && b->pred->pred_next == NULL))
1199         unreachable = 1;
1200     }
1201
1202   /* ??? We can kill these soon.  */
1203   in_edges = (int *) xcalloc (n_basic_blocks, sizeof (int));
1204   out_edges = (int *) xcalloc (n_basic_blocks, sizeof (int));
1205   edge_table = (haifa_edge *) xcalloc (num_edges, sizeof (haifa_edge));
1206
1207   nr_edges = 0;
1208   for (i = 0; i < num_edges; i++)
1209     {
1210       edge e = INDEX_EDGE (edge_list, i);
1211
1212       if (e->dest != EXIT_BLOCK_PTR
1213           && e->src != ENTRY_BLOCK_PTR)
1214         new_edge (e->src->index, e->dest->index);
1215     }
1216
1217   /* Increment by 1, since edge 0 is unused.  */
1218   nr_edges++;
1219
1220   return unreachable;
1221 }
1222
1223 /* Record an edge in the control flow graph from SOURCE to TARGET.
1224
1225    In theory, this is redundant with the s_succs computed above, but
1226    we have not converted all of haifa to use information from the
1227    integer lists.  */
1228
1229 static void
1230 new_edge (source, target)
1231      int source, target;
1232 {
1233   int e, next_edge;
1234   int curr_edge, fst_edge;
1235
1236   /* Check for duplicates.  */
1237   fst_edge = curr_edge = OUT_EDGES (source);
1238   while (curr_edge)
1239     {
1240       if (FROM_BLOCK (curr_edge) == source
1241           && TO_BLOCK (curr_edge) == target)
1242         {
1243           return;
1244         }
1245
1246       curr_edge = NEXT_OUT (curr_edge);
1247
1248       if (fst_edge == curr_edge)
1249         break;
1250     }
1251
1252   e = ++nr_edges;
1253
1254   FROM_BLOCK (e) = source;
1255   TO_BLOCK (e) = target;
1256
1257   if (OUT_EDGES (source))
1258     {
1259       next_edge = NEXT_OUT (OUT_EDGES (source));
1260       NEXT_OUT (OUT_EDGES (source)) = e;
1261       NEXT_OUT (e) = next_edge;
1262     }
1263   else
1264     {
1265       OUT_EDGES (source) = e;
1266       NEXT_OUT (e) = e;
1267     }
1268
1269   if (IN_EDGES (target))
1270     {
1271       next_edge = NEXT_IN (IN_EDGES (target));
1272       NEXT_IN (IN_EDGES (target)) = e;
1273       NEXT_IN (e) = next_edge;
1274     }
1275   else
1276     {
1277       IN_EDGES (target) = e;
1278       NEXT_IN (e) = e;
1279     }
1280 }
1281
1282 /* BITSET macros for operations on the control flow graph.  */
1283
1284 /* Compute bitwise union of two bitsets.  */
1285 #define BITSET_UNION(set1, set2, len)                                \
1286 do { register bitset tp = set1, sp = set2;                           \
1287      register int i;                                                 \
1288      for (i = 0; i < len; i++)                                       \
1289        *(tp++) |= *(sp++); } while (0)
1290
1291 /* Compute bitwise intersection of two bitsets.  */
1292 #define BITSET_INTER(set1, set2, len)                                \
1293 do { register bitset tp = set1, sp = set2;                           \
1294      register int i;                                                 \
1295      for (i = 0; i < len; i++)                                       \
1296        *(tp++) &= *(sp++); } while (0)
1297
1298 /* Compute bitwise difference of two bitsets.  */
1299 #define BITSET_DIFFER(set1, set2, len)                               \
1300 do { register bitset tp = set1, sp = set2;                           \
1301      register int i;                                                 \
1302      for (i = 0; i < len; i++)                                       \
1303        *(tp++) &= ~*(sp++); } while (0)
1304
1305 /* Inverts every bit of bitset 'set'.  */
1306 #define BITSET_INVERT(set, len)                                      \
1307 do { register bitset tmpset = set;                                   \
1308      register int i;                                                 \
1309      for (i = 0; i < len; i++, tmpset++)                             \
1310        *tmpset = ~*tmpset; } while (0)
1311
1312 /* Turn on the index'th bit in bitset set.  */
1313 #define BITSET_ADD(set, index, len)                                  \
1314 {                                                                    \
1315   if (index >= HOST_BITS_PER_WIDE_INT * len)                         \
1316     abort ();                                                        \
1317   else                                                               \
1318     set[index/HOST_BITS_PER_WIDE_INT] |=                             \
1319       1 << (index % HOST_BITS_PER_WIDE_INT);                         \
1320 }
1321
1322 /* Turn off the index'th bit in set.  */
1323 #define BITSET_REMOVE(set, index, len)                               \
1324 {                                                                    \
1325   if (index >= HOST_BITS_PER_WIDE_INT * len)                         \
1326     abort ();                                                        \
1327   else                                                               \
1328     set[index/HOST_BITS_PER_WIDE_INT] &=                             \
1329       ~(1 << (index%HOST_BITS_PER_WIDE_INT));                        \
1330 }
1331
1332 /* Check if the index'th bit in bitset set is on.  */
1333
1334 static char
1335 bitset_member (set, index, len)
1336      bitset set;
1337      int index, len;
1338 {
1339   if (index >= HOST_BITS_PER_WIDE_INT * len)
1340     abort ();
1341   return (set[index / HOST_BITS_PER_WIDE_INT] &
1342           1 << (index % HOST_BITS_PER_WIDE_INT)) ? 1 : 0;
1343 }
1344
1345 /* Translate a bit-set SET to a list BL of the bit-set members.  */
1346
1347 static void
1348 extract_bitlst (set, len, bitlen, bl)
1349      bitset set;
1350      int len;
1351      int bitlen;
1352      bitlst *bl;
1353 {
1354   int i, j, offset;
1355   unsigned HOST_WIDE_INT word;
1356
1357   /* bblst table space is reused in each call to extract_bitlst.  */
1358   bitlst_table_last = 0;
1359
1360   bl->first_member = &bitlst_table[bitlst_table_last];
1361   bl->nr_members = 0;
1362
1363   /* Iterate over each word in the bitset.  */
1364   for (i = 0; i < len; i++)
1365     {
1366       word = set[i];
1367       offset = i * HOST_BITS_PER_WIDE_INT;
1368
1369       /* Iterate over each bit in the word, but do not
1370          go beyond the end of the defined bits.  */
1371       for (j = 0; offset < bitlen && word; j++)
1372         {
1373           if (word & 1)
1374             {
1375               bitlst_table[bitlst_table_last++] = offset;
1376               (bl->nr_members)++;
1377             }
1378           word >>= 1;
1379           ++offset;
1380         }
1381     }
1382
1383 }
1384
1385 /* Functions for the construction of regions.  */
1386
1387 /* Print the regions, for debugging purposes.  Callable from debugger.  */
1388
1389 void
1390 debug_regions ()
1391 {
1392   int rgn, bb;
1393
1394   fprintf (dump, "\n;;   ------------ REGIONS ----------\n\n");
1395   for (rgn = 0; rgn < nr_regions; rgn++)
1396     {
1397       fprintf (dump, ";;\trgn %d nr_blocks %d:\n", rgn,
1398                rgn_table[rgn].rgn_nr_blocks);
1399       fprintf (dump, ";;\tbb/block: ");
1400
1401       for (bb = 0; bb < rgn_table[rgn].rgn_nr_blocks; bb++)
1402         {
1403           current_blocks = RGN_BLOCKS (rgn);
1404
1405           if (bb != BLOCK_TO_BB (BB_TO_BLOCK (bb)))
1406             abort ();
1407
1408           fprintf (dump, " %d/%d ", bb, BB_TO_BLOCK (bb));
1409         }
1410
1411       fprintf (dump, "\n\n");
1412     }
1413 }
1414
1415 /* Build a single block region for each basic block in the function.
1416    This allows for using the same code for interblock and basic block
1417    scheduling.  */
1418
1419 static void
1420 find_single_block_region ()
1421 {
1422   int i;
1423
1424   for (i = 0; i < n_basic_blocks; i++)
1425     {
1426       rgn_bb_table[i] = i;
1427       RGN_NR_BLOCKS (i) = 1;
1428       RGN_BLOCKS (i) = i;
1429       CONTAINING_RGN (i) = i;
1430       BLOCK_TO_BB (i) = 0;
1431     }
1432   nr_regions = n_basic_blocks;
1433 }
1434
1435 /* Update number of blocks and the estimate for number of insns
1436    in the region.  Return 1 if the region is "too large" for interblock
1437    scheduling (compile time considerations), otherwise return 0.  */
1438
1439 static int
1440 too_large (block, num_bbs, num_insns)
1441      int block, *num_bbs, *num_insns;
1442 {
1443   (*num_bbs)++;
1444   (*num_insns) += (INSN_LUID (BLOCK_END (block)) -
1445                    INSN_LUID (BLOCK_HEAD (block)));
1446   if ((*num_bbs > MAX_RGN_BLOCKS) || (*num_insns > MAX_RGN_INSNS))
1447     return 1;
1448   else
1449     return 0;
1450 }
1451
1452 /* Update_loop_relations(blk, hdr): Check if the loop headed by max_hdr[blk]
1453    is still an inner loop.  Put in max_hdr[blk] the header of the most inner
1454    loop containing blk.  */
1455 #define UPDATE_LOOP_RELATIONS(blk, hdr)                              \
1456 {                                                                    \
1457   if (max_hdr[blk] == -1)                                            \
1458     max_hdr[blk] = hdr;                                              \
1459   else if (dfs_nr[max_hdr[blk]] > dfs_nr[hdr])                       \
1460          RESET_BIT (inner, hdr);                                     \
1461   else if (dfs_nr[max_hdr[blk]] < dfs_nr[hdr])                       \
1462          {                                                           \
1463             RESET_BIT (inner,max_hdr[blk]);                          \
1464             max_hdr[blk] = hdr;                                      \
1465          }                                                           \
1466 }
1467
1468 /* Find regions for interblock scheduling.
1469
1470    A region for scheduling can be:
1471
1472      * A loop-free procedure, or
1473
1474      * A reducible inner loop, or
1475
1476      * A basic block not contained in any other region.
1477
1478    ?!? In theory we could build other regions based on extended basic
1479    blocks or reverse extended basic blocks.  Is it worth the trouble?
1480
1481    Loop blocks that form a region are put into the region's block list
1482    in topological order.
1483
1484    This procedure stores its results into the following global (ick) variables
1485
1486      * rgn_nr
1487      * rgn_table
1488      * rgn_bb_table
1489      * block_to_bb
1490      * containing region
1491
1492    We use dominator relationships to avoid making regions out of non-reducible
1493    loops.
1494
1495    This procedure needs to be converted to work on pred/succ lists instead
1496    of edge tables.  That would simplify it somewhat.  */
1497
1498 static void
1499 find_rgns (edge_list, dom)
1500      struct edge_list *edge_list;
1501      sbitmap *dom;
1502 {
1503   int *max_hdr, *dfs_nr, *stack, *degree;
1504   char no_loops = 1;
1505   int node, child, loop_head, i, head, tail;
1506   int count = 0, sp, idx = 0, current_edge = out_edges[0];
1507   int num_bbs, num_insns, unreachable;
1508   int too_large_failure;
1509
1510   /* Note if an edge has been passed.  */
1511   sbitmap passed;
1512
1513   /* Note if a block is a natural loop header.  */
1514   sbitmap header;
1515
1516   /* Note if a block is an natural inner loop header.  */
1517   sbitmap inner;
1518
1519   /* Note if a block is in the block queue.  */
1520   sbitmap in_queue;
1521
1522   /* Note if a block is in the block queue.  */
1523   sbitmap in_stack;
1524
1525   int num_edges = NUM_EDGES (edge_list);
1526
1527   /* Perform a DFS traversal of the cfg.  Identify loop headers, inner loops
1528      and a mapping from block to its loop header (if the block is contained
1529      in a loop, else -1).
1530
1531      Store results in HEADER, INNER, and MAX_HDR respectively, these will
1532      be used as inputs to the second traversal.
1533
1534      STACK, SP and DFS_NR are only used during the first traversal.  */
1535
1536   /* Allocate and initialize variables for the first traversal.  */
1537   max_hdr = (int *) xmalloc (n_basic_blocks * sizeof (int));
1538   dfs_nr = (int *) xcalloc (n_basic_blocks, sizeof (int));
1539   stack = (int *) xmalloc (nr_edges * sizeof (int));
1540
1541   inner = sbitmap_alloc (n_basic_blocks);
1542   sbitmap_ones (inner);
1543
1544   header = sbitmap_alloc (n_basic_blocks);
1545   sbitmap_zero (header);
1546
1547   passed = sbitmap_alloc (nr_edges);
1548   sbitmap_zero (passed);
1549
1550   in_queue = sbitmap_alloc (n_basic_blocks);
1551   sbitmap_zero (in_queue);
1552
1553   in_stack = sbitmap_alloc (n_basic_blocks);
1554   sbitmap_zero (in_stack);
1555
1556   for (i = 0; i < n_basic_blocks; i++)
1557     max_hdr[i] = -1;
1558
1559   /* DFS traversal to find inner loops in the cfg.  */
1560
1561   sp = -1;
1562   while (1)
1563     {
1564       if (current_edge == 0 || TEST_BIT (passed, current_edge))
1565         {
1566           /* We have reached a leaf node or a node that was already
1567              processed.  Pop edges off the stack until we find
1568              an edge that has not yet been processed.  */
1569           while (sp >= 0
1570                  && (current_edge == 0 || TEST_BIT (passed, current_edge)))
1571             {
1572               /* Pop entry off the stack.  */
1573               current_edge = stack[sp--];
1574               node = FROM_BLOCK (current_edge);
1575               child = TO_BLOCK (current_edge);
1576               RESET_BIT (in_stack, child);
1577               if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
1578                 UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
1579               current_edge = NEXT_OUT (current_edge);
1580             }
1581
1582           /* See if have finished the DFS tree traversal.  */
1583           if (sp < 0 && TEST_BIT (passed, current_edge))
1584             break;
1585
1586           /* Nope, continue the traversal with the popped node.  */
1587           continue;
1588         }
1589
1590       /* Process a node.  */
1591       node = FROM_BLOCK (current_edge);
1592       child = TO_BLOCK (current_edge);
1593       SET_BIT (in_stack, node);
1594       dfs_nr[node] = ++count;
1595
1596       /* If the successor is in the stack, then we've found a loop.
1597          Mark the loop, if it is not a natural loop, then it will
1598          be rejected during the second traversal.  */
1599       if (TEST_BIT (in_stack, child))
1600         {
1601           no_loops = 0;
1602           SET_BIT (header, child);
1603           UPDATE_LOOP_RELATIONS (node, child);
1604           SET_BIT (passed, current_edge);
1605           current_edge = NEXT_OUT (current_edge);
1606           continue;
1607         }
1608
1609       /* If the child was already visited, then there is no need to visit
1610          it again.  Just update the loop relationships and restart
1611          with a new edge.  */
1612       if (dfs_nr[child])
1613         {
1614           if (max_hdr[child] >= 0 && TEST_BIT (in_stack, max_hdr[child]))
1615             UPDATE_LOOP_RELATIONS (node, max_hdr[child]);
1616           SET_BIT (passed, current_edge);
1617           current_edge = NEXT_OUT (current_edge);
1618           continue;
1619         }
1620
1621       /* Push an entry on the stack and continue DFS traversal.  */
1622       stack[++sp] = current_edge;
1623       SET_BIT (passed, current_edge);
1624       current_edge = OUT_EDGES (child);
1625
1626       /* This is temporary until haifa is converted to use rth's new
1627          cfg routines which have true entry/exit blocks and the
1628          appropriate edges from/to those blocks.
1629
1630          Generally we update dfs_nr for a node when we process its
1631          out edge.  However, if the node has no out edge then we will
1632          not set dfs_nr for that node.  This can confuse the scheduler
1633          into thinking that we have unreachable blocks, which in turn
1634          disables cross block scheduling.
1635
1636          So, if we have a node with no out edges, go ahead and mark it
1637          as reachable now.  */
1638       if (current_edge == 0)
1639         dfs_nr[child] = ++count;
1640     }
1641
1642   /* Another check for unreachable blocks.  The earlier test in
1643      is_cfg_nonregular only finds unreachable blocks that do not
1644      form a loop.
1645
1646      The DFS traversal will mark every block that is reachable from
1647      the entry node by placing a nonzero value in dfs_nr.  Thus if
1648      dfs_nr is zero for any block, then it must be unreachable.  */
1649   unreachable = 0;
1650   for (i = 0; i < n_basic_blocks; i++)
1651     if (dfs_nr[i] == 0)
1652       {
1653         unreachable = 1;
1654         break;
1655       }
1656
1657   /* Gross.  To avoid wasting memory, the second pass uses the dfs_nr array
1658      to hold degree counts.  */
1659   degree = dfs_nr;
1660
1661   for (i = 0; i < n_basic_blocks; i++)
1662     degree[i] = 0;
1663   for (i = 0; i < num_edges; i++)
1664     {
1665       edge e = INDEX_EDGE (edge_list, i);
1666
1667       if (e->dest != EXIT_BLOCK_PTR)
1668         degree[e->dest->index]++;
1669     }
1670
1671   /* Do not perform region scheduling if there are any unreachable
1672      blocks.  */
1673   if (!unreachable)
1674     {
1675       int *queue;
1676
1677       if (no_loops)
1678         SET_BIT (header, 0);
1679
1680       /* Second travsersal:find reducible inner loops and topologically sort
1681          block of each region.  */
1682
1683       queue = (int *) xmalloc (n_basic_blocks * sizeof (int));
1684
1685       /* Find blocks which are inner loop headers.  We still have non-reducible
1686          loops to consider at this point.  */
1687       for (i = 0; i < n_basic_blocks; i++)
1688         {
1689           if (TEST_BIT (header, i) && TEST_BIT (inner, i))
1690             {
1691               edge e;
1692               int j;
1693
1694               /* Now check that the loop is reducible.  We do this separate
1695                  from finding inner loops so that we do not find a reducible
1696                  loop which contains an inner non-reducible loop.
1697
1698                  A simple way to find reducible/natural loops is to verify
1699                  that each block in the loop is dominated by the loop
1700                  header.
1701
1702                  If there exists a block that is not dominated by the loop
1703                  header, then the block is reachable from outside the loop
1704                  and thus the loop is not a natural loop.  */
1705               for (j = 0; j < n_basic_blocks; j++)
1706                 {
1707                   /* First identify blocks in the loop, except for the loop
1708                      entry block.  */
1709                   if (i == max_hdr[j] && i != j)
1710                     {
1711                       /* Now verify that the block is dominated by the loop
1712                          header.  */
1713                       if (!TEST_BIT (dom[j], i))
1714                         break;
1715                     }
1716                 }
1717
1718               /* If we exited the loop early, then I is the header of
1719                  a non-reducible loop and we should quit processing it
1720                  now.  */
1721               if (j != n_basic_blocks)
1722                 continue;
1723
1724               /* I is a header of an inner loop, or block 0 in a subroutine
1725                  with no loops at all.  */
1726               head = tail = -1;
1727               too_large_failure = 0;
1728               loop_head = max_hdr[i];
1729
1730               /* Decrease degree of all I's successors for topological
1731                  ordering.  */
1732               for (e = BASIC_BLOCK (i)->succ; e; e = e->succ_next)
1733                 if (e->dest != EXIT_BLOCK_PTR)
1734                   --degree[e->dest->index];
1735
1736               /* Estimate # insns, and count # blocks in the region.  */
1737               num_bbs = 1;
1738               num_insns = (INSN_LUID (BLOCK_END (i))
1739                            - INSN_LUID (BLOCK_HEAD (i)));
1740
1741               /* Find all loop latches (blocks with back edges to the loop
1742                  header) or all the leaf blocks in the cfg has no loops.
1743
1744                  Place those blocks into the queue.  */
1745               if (no_loops)
1746                 {
1747                   for (j = 0; j < n_basic_blocks; j++)
1748                     /* Leaf nodes have only a single successor which must
1749                        be EXIT_BLOCK.  */
1750                     if (BASIC_BLOCK (j)->succ
1751                         && BASIC_BLOCK (j)->succ->dest == EXIT_BLOCK_PTR
1752                         && BASIC_BLOCK (j)->succ->succ_next == NULL)
1753                       {
1754                         queue[++tail] = j;
1755                         SET_BIT (in_queue, j);
1756
1757                         if (too_large (j, &num_bbs, &num_insns))
1758                           {
1759                             too_large_failure = 1;
1760                             break;
1761                           }
1762                       }
1763                 }
1764               else
1765                 {
1766                   edge e;
1767
1768                   for (e = BASIC_BLOCK (i)->pred; e; e = e->pred_next)
1769                     {
1770                       if (e->src == ENTRY_BLOCK_PTR)
1771                         continue;
1772
1773                       node = e->src->index;
1774
1775                       if (max_hdr[node] == loop_head && node != i)
1776                         {
1777                           /* This is a loop latch.  */
1778                           queue[++tail] = node;
1779                           SET_BIT (in_queue, node);
1780
1781                           if (too_large (node, &num_bbs, &num_insns))
1782                             {
1783                               too_large_failure = 1;
1784                               break;
1785                             }
1786                         }
1787                     }
1788                 }
1789
1790               /* Now add all the blocks in the loop to the queue.
1791
1792              We know the loop is a natural loop; however the algorithm
1793              above will not always mark certain blocks as being in the
1794              loop.  Consider:
1795                 node   children
1796                  a        b,c
1797                  b        c
1798                  c        a,d
1799                  d        b
1800
1801              The algorithm in the DFS traversal may not mark B & D as part
1802              of the loop (ie they will not have max_hdr set to A).
1803
1804              We know they can not be loop latches (else they would have
1805              had max_hdr set since they'd have a backedge to a dominator
1806              block).  So we don't need them on the initial queue.
1807
1808              We know they are part of the loop because they are dominated
1809              by the loop header and can be reached by a backwards walk of
1810              the edges starting with nodes on the initial queue.
1811
1812              It is safe and desirable to include those nodes in the
1813              loop/scheduling region.  To do so we would need to decrease
1814              the degree of a node if it is the target of a backedge
1815              within the loop itself as the node is placed in the queue.
1816
1817              We do not do this because I'm not sure that the actual
1818              scheduling code will properly handle this case. ?!? */
1819
1820               while (head < tail && !too_large_failure)
1821                 {
1822                   edge e;
1823                   child = queue[++head];
1824
1825                   for (e = BASIC_BLOCK (child)->pred; e; e = e->pred_next)
1826                     {
1827                       node = e->src->index;
1828
1829                       /* See discussion above about nodes not marked as in
1830                          this loop during the initial DFS traversal.  */
1831                       if (e->src == ENTRY_BLOCK_PTR
1832                           || max_hdr[node] != loop_head)
1833                         {
1834                           tail = -1;
1835                           break;
1836                         }
1837                       else if (!TEST_BIT (in_queue, node) && node != i)
1838                         {
1839                           queue[++tail] = node;
1840                           SET_BIT (in_queue, node);
1841
1842                           if (too_large (node, &num_bbs, &num_insns))
1843                             {
1844                               too_large_failure = 1;
1845                               break;
1846                             }
1847                         }
1848                     }
1849                 }
1850
1851               if (tail >= 0 && !too_large_failure)
1852                 {
1853                   /* Place the loop header into list of region blocks.  */
1854                   degree[i] = -1;
1855                   rgn_bb_table[idx] = i;
1856                   RGN_NR_BLOCKS (nr_regions) = num_bbs;
1857                   RGN_BLOCKS (nr_regions) = idx++;
1858                   CONTAINING_RGN (i) = nr_regions;
1859                   BLOCK_TO_BB (i) = count = 0;
1860
1861                   /* Remove blocks from queue[] when their in degree
1862                      becomes zero.  Repeat until no blocks are left on the
1863                      list.  This produces a topological list of blocks in
1864                      the region.  */
1865                   while (tail >= 0)
1866                     {
1867                       if (head < 0)
1868                         head = tail;
1869                       child = queue[head];
1870                       if (degree[child] == 0)
1871                         {
1872                           edge e;
1873
1874                           degree[child] = -1;
1875                           rgn_bb_table[idx++] = child;
1876                           BLOCK_TO_BB (child) = ++count;
1877                           CONTAINING_RGN (child) = nr_regions;
1878                           queue[head] = queue[tail--];
1879
1880                           for (e = BASIC_BLOCK (child)->succ;
1881                                e;
1882                                e = e->succ_next)
1883                             if (e->dest != EXIT_BLOCK_PTR)
1884                               --degree[e->dest->index];
1885                         }
1886                       else
1887                         --head;
1888                     }
1889                   ++nr_regions;
1890                 }
1891             }
1892         }
1893       free (queue);
1894     }
1895
1896   /* Any block that did not end up in a region is placed into a region
1897      by itself.  */
1898   for (i = 0; i < n_basic_blocks; i++)
1899     if (degree[i] >= 0)
1900       {
1901         rgn_bb_table[idx] = i;
1902         RGN_NR_BLOCKS (nr_regions) = 1;
1903         RGN_BLOCKS (nr_regions) = idx++;
1904         CONTAINING_RGN (i) = nr_regions++;
1905         BLOCK_TO_BB (i) = 0;
1906       }
1907
1908   free (max_hdr);
1909   free (dfs_nr);
1910   free (stack);
1911   free (passed);
1912   free (header);
1913   free (inner);
1914   free (in_queue);
1915   free (in_stack);
1916 }
1917
1918 /* Functions for regions scheduling information.  */
1919
1920 /* Compute dominators, probability, and potential-split-edges of bb.
1921    Assume that these values were already computed for bb's predecessors.  */
1922
1923 static void
1924 compute_dom_prob_ps (bb)
1925      int bb;
1926 {
1927   int nxt_in_edge, fst_in_edge, pred;
1928   int fst_out_edge, nxt_out_edge, nr_out_edges, nr_rgn_out_edges;
1929
1930   prob[bb] = 0.0;
1931   if (IS_RGN_ENTRY (bb))
1932     {
1933       BITSET_ADD (dom[bb], 0, bbset_size);
1934       prob[bb] = 1.0;
1935       return;
1936     }
1937
1938   fst_in_edge = nxt_in_edge = IN_EDGES (BB_TO_BLOCK (bb));
1939
1940   /* Intialize dom[bb] to '111..1'.  */
1941   BITSET_INVERT (dom[bb], bbset_size);
1942
1943   do
1944     {
1945       pred = FROM_BLOCK (nxt_in_edge);
1946       BITSET_INTER (dom[bb], dom[BLOCK_TO_BB (pred)], bbset_size);
1947
1948       BITSET_UNION (ancestor_edges[bb], ancestor_edges[BLOCK_TO_BB (pred)],
1949                     edgeset_size);
1950
1951       BITSET_ADD (ancestor_edges[bb], EDGE_TO_BIT (nxt_in_edge), edgeset_size);
1952
1953       nr_out_edges = 1;
1954       nr_rgn_out_edges = 0;
1955       fst_out_edge = OUT_EDGES (pred);
1956       nxt_out_edge = NEXT_OUT (fst_out_edge);
1957       BITSET_UNION (pot_split[bb], pot_split[BLOCK_TO_BB (pred)],
1958                     edgeset_size);
1959
1960       BITSET_ADD (pot_split[bb], EDGE_TO_BIT (fst_out_edge), edgeset_size);
1961
1962       /* The successor doesn't belong in the region?  */
1963       if (CONTAINING_RGN (TO_BLOCK (fst_out_edge)) !=
1964           CONTAINING_RGN (BB_TO_BLOCK (bb)))
1965         ++nr_rgn_out_edges;
1966
1967       while (fst_out_edge != nxt_out_edge)
1968         {
1969           ++nr_out_edges;
1970           /* The successor doesn't belong in the region?  */
1971           if (CONTAINING_RGN (TO_BLOCK (nxt_out_edge)) !=
1972               CONTAINING_RGN (BB_TO_BLOCK (bb)))
1973             ++nr_rgn_out_edges;
1974           BITSET_ADD (pot_split[bb], EDGE_TO_BIT (nxt_out_edge), edgeset_size);
1975           nxt_out_edge = NEXT_OUT (nxt_out_edge);
1976
1977         }
1978
1979       /* Now nr_rgn_out_edges is the number of region-exit edges from
1980          pred, and nr_out_edges will be the number of pred out edges
1981          not leaving the region.  */
1982       nr_out_edges -= nr_rgn_out_edges;
1983       if (nr_rgn_out_edges > 0)
1984         prob[bb] += 0.9 * prob[BLOCK_TO_BB (pred)] / nr_out_edges;
1985       else
1986         prob[bb] += prob[BLOCK_TO_BB (pred)] / nr_out_edges;
1987       nxt_in_edge = NEXT_IN (nxt_in_edge);
1988     }
1989   while (fst_in_edge != nxt_in_edge);
1990
1991   BITSET_ADD (dom[bb], bb, bbset_size);
1992   BITSET_DIFFER (pot_split[bb], ancestor_edges[bb], edgeset_size);
1993
1994   if (sched_verbose >= 2)
1995     fprintf (dump, ";;  bb_prob(%d, %d) = %3d\n", bb, BB_TO_BLOCK (bb),
1996              (int) (100.0 * prob[bb]));
1997 }
1998
1999 /* Functions for target info.  */
2000
2001 /* Compute in BL the list of split-edges of bb_src relatively to bb_trg.
2002    Note that bb_trg dominates bb_src.  */
2003
2004 static void
2005 split_edges (bb_src, bb_trg, bl)
2006      int bb_src;
2007      int bb_trg;
2008      edgelst *bl;
2009 {
2010   int es = edgeset_size;
2011   edgeset src = (edgeset) xcalloc (es, sizeof (HOST_WIDE_INT));
2012
2013   while (es--)
2014     src[es] = (pot_split[bb_src])[es];
2015   BITSET_DIFFER (src, pot_split[bb_trg], edgeset_size);
2016   extract_bitlst (src, edgeset_size, edgeset_bitsize, bl);
2017   free (src);
2018 }
2019
2020 /* Find the valid candidate-source-blocks for the target block TRG, compute
2021    their probability, and check if they are speculative or not.
2022    For speculative sources, compute their update-blocks and split-blocks.  */
2023
2024 static void
2025 compute_trg_info (trg)
2026      int trg;
2027 {
2028   register candidate *sp;
2029   edgelst el;
2030   int check_block, update_idx;
2031   int i, j, k, fst_edge, nxt_edge;
2032
2033   /* Define some of the fields for the target bb as well.  */
2034   sp = candidate_table + trg;
2035   sp->is_valid = 1;
2036   sp->is_speculative = 0;
2037   sp->src_prob = 100;
2038
2039   for (i = trg + 1; i < current_nr_blocks; i++)
2040     {
2041       sp = candidate_table + i;
2042
2043       sp->is_valid = IS_DOMINATED (i, trg);
2044       if (sp->is_valid)
2045         {
2046           sp->src_prob = GET_SRC_PROB (i, trg);
2047           sp->is_valid = (sp->src_prob >= MIN_PROBABILITY);
2048         }
2049
2050       if (sp->is_valid)
2051         {
2052           split_edges (i, trg, &el);
2053           sp->is_speculative = (el.nr_members) ? 1 : 0;
2054           if (sp->is_speculative && !flag_schedule_speculative)
2055             sp->is_valid = 0;
2056         }
2057
2058       if (sp->is_valid)
2059         {
2060           char *update_blocks;
2061
2062           /* Compute split blocks and store them in bblst_table.
2063              The TO block of every split edge is a split block.  */
2064           sp->split_bbs.first_member = &bblst_table[bblst_last];
2065           sp->split_bbs.nr_members = el.nr_members;
2066           for (j = 0; j < el.nr_members; bblst_last++, j++)
2067             bblst_table[bblst_last] =
2068               TO_BLOCK (rgn_edges[el.first_member[j]]);
2069           sp->update_bbs.first_member = &bblst_table[bblst_last];
2070
2071           /* Compute update blocks and store them in bblst_table.
2072              For every split edge, look at the FROM block, and check
2073              all out edges.  For each out edge that is not a split edge,
2074              add the TO block to the update block list.  This list can end
2075              up with a lot of duplicates.  We need to weed them out to avoid
2076              overrunning the end of the bblst_table.  */
2077           update_blocks = (char *) alloca (n_basic_blocks);
2078           memset (update_blocks, 0, n_basic_blocks);
2079
2080           update_idx = 0;
2081           for (j = 0; j < el.nr_members; j++)
2082             {
2083               check_block = FROM_BLOCK (rgn_edges[el.first_member[j]]);
2084               fst_edge = nxt_edge = OUT_EDGES (check_block);
2085               do
2086                 {
2087                   if (! update_blocks[TO_BLOCK (nxt_edge)])
2088                     {
2089                       for (k = 0; k < el.nr_members; k++)
2090                         if (EDGE_TO_BIT (nxt_edge) == el.first_member[k])
2091                           break;
2092
2093                       if (k >= el.nr_members)
2094                         {
2095                           bblst_table[bblst_last++] = TO_BLOCK (nxt_edge);
2096                           update_blocks[TO_BLOCK (nxt_edge)] = 1;
2097                           update_idx++;
2098                         }
2099                     }
2100
2101                   nxt_edge = NEXT_OUT (nxt_edge);
2102                 }
2103               while (fst_edge != nxt_edge);
2104             }
2105           sp->update_bbs.nr_members = update_idx;
2106
2107           /* Make sure we didn't overrun the end of bblst_table.  */
2108           if (bblst_last > bblst_size)
2109             abort ();
2110         }
2111       else
2112         {
2113           sp->split_bbs.nr_members = sp->update_bbs.nr_members = 0;
2114
2115           sp->is_speculative = 0;
2116           sp->src_prob = 0;
2117         }
2118     }
2119 }
2120
2121 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
2122
2123 void
2124 debug_candidate (i)
2125      int i;
2126 {
2127   if (!candidate_table[i].is_valid)
2128     return;
2129
2130   if (candidate_table[i].is_speculative)
2131     {
2132       int j;
2133       fprintf (dump, "src b %d bb %d speculative \n", BB_TO_BLOCK (i), i);
2134
2135       fprintf (dump, "split path: ");
2136       for (j = 0; j < candidate_table[i].split_bbs.nr_members; j++)
2137         {
2138           int b = candidate_table[i].split_bbs.first_member[j];
2139
2140           fprintf (dump, " %d ", b);
2141         }
2142       fprintf (dump, "\n");
2143
2144       fprintf (dump, "update path: ");
2145       for (j = 0; j < candidate_table[i].update_bbs.nr_members; j++)
2146         {
2147           int b = candidate_table[i].update_bbs.first_member[j];
2148
2149           fprintf (dump, " %d ", b);
2150         }
2151       fprintf (dump, "\n");
2152     }
2153   else
2154     {
2155       fprintf (dump, " src %d equivalent\n", BB_TO_BLOCK (i));
2156     }
2157 }
2158
2159 /* Print candidates info, for debugging purposes.  Callable from debugger.  */
2160
2161 void
2162 debug_candidates (trg)
2163      int trg;
2164 {
2165   int i;
2166
2167   fprintf (dump, "----------- candidate table: target: b=%d bb=%d ---\n",
2168            BB_TO_BLOCK (trg), trg);
2169   for (i = trg + 1; i < current_nr_blocks; i++)
2170     debug_candidate (i);
2171 }
2172
2173 /* Functions for speculative scheduing.  */
2174
2175 /* Return 0 if x is a set of a register alive in the beginning of one
2176    of the split-blocks of src, otherwise return 1.  */
2177
2178 static int
2179 check_live_1 (src, x)
2180      int src;
2181      rtx x;
2182 {
2183   register int i;
2184   register int regno;
2185   register rtx reg = SET_DEST (x);
2186
2187   if (reg == 0)
2188     return 1;
2189
2190   while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == ZERO_EXTRACT
2191          || GET_CODE (reg) == SIGN_EXTRACT
2192          || GET_CODE (reg) == STRICT_LOW_PART)
2193     reg = XEXP (reg, 0);
2194
2195   if (GET_CODE (reg) == PARALLEL
2196       && GET_MODE (reg) == BLKmode)
2197     {
2198       register int i;
2199       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
2200         if (check_live_1 (src, XVECEXP (reg, 0, i)))
2201           return 1;
2202       return 0;
2203     }
2204
2205   if (GET_CODE (reg) != REG)
2206     return 1;
2207
2208   regno = REGNO (reg);
2209
2210   if (regno < FIRST_PSEUDO_REGISTER && global_regs[regno])
2211     {
2212       /* Global registers are assumed live.  */
2213       return 0;
2214     }
2215   else
2216     {
2217       if (regno < FIRST_PSEUDO_REGISTER)
2218         {
2219           /* Check for hard registers.  */
2220           int j = HARD_REGNO_NREGS (regno, GET_MODE (reg));
2221           while (--j >= 0)
2222             {
2223               for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
2224                 {
2225                   int b = candidate_table[src].split_bbs.first_member[i];
2226
2227                   if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start,
2228                                        regno + j))
2229                     {
2230                       return 0;
2231                     }
2232                 }
2233             }
2234         }
2235       else
2236         {
2237           /* Check for psuedo registers.  */
2238           for (i = 0; i < candidate_table[src].split_bbs.nr_members; i++)
2239             {
2240               int b = candidate_table[src].split_bbs.first_member[i];
2241
2242               if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start, regno))
2243                 {
2244                   return 0;
2245                 }
2246             }
2247         }
2248     }
2249
2250   return 1;
2251 }
2252
2253 /* If x is a set of a register R, mark that R is alive in the beginning
2254    of every update-block of src.  */
2255
2256 static void
2257 update_live_1 (src, x)
2258      int src;
2259      rtx x;
2260 {
2261   register int i;
2262   register int regno;
2263   register rtx reg = SET_DEST (x);
2264
2265   if (reg == 0)
2266     return;
2267
2268   while (GET_CODE (reg) == SUBREG || GET_CODE (reg) == ZERO_EXTRACT
2269          || GET_CODE (reg) == SIGN_EXTRACT
2270          || GET_CODE (reg) == STRICT_LOW_PART)
2271     reg = XEXP (reg, 0);
2272
2273   if (GET_CODE (reg) == PARALLEL
2274       && GET_MODE (reg) == BLKmode)
2275     {
2276       register int i;
2277       for (i = XVECLEN (reg, 0) - 1; i >= 0; i--)
2278         update_live_1 (src, XVECEXP (reg, 0, i));
2279       return;
2280     }
2281
2282   if (GET_CODE (reg) != REG)
2283     return;
2284
2285   /* Global registers are always live, so the code below does not apply
2286      to them.  */
2287
2288   regno = REGNO (reg);
2289
2290   if (regno >= FIRST_PSEUDO_REGISTER || !global_regs[regno])
2291     {
2292       if (regno < FIRST_PSEUDO_REGISTER)
2293         {
2294           int j = HARD_REGNO_NREGS (regno, GET_MODE (reg));
2295           while (--j >= 0)
2296             {
2297               for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
2298                 {
2299                   int b = candidate_table[src].update_bbs.first_member[i];
2300
2301                   SET_REGNO_REG_SET (BASIC_BLOCK (b)->global_live_at_start,
2302                                      regno + j);
2303                 }
2304             }
2305         }
2306       else
2307         {
2308           for (i = 0; i < candidate_table[src].update_bbs.nr_members; i++)
2309             {
2310               int b = candidate_table[src].update_bbs.first_member[i];
2311
2312               SET_REGNO_REG_SET (BASIC_BLOCK (b)->global_live_at_start, regno);
2313             }
2314         }
2315     }
2316 }
2317
2318 /* Return 1 if insn can be speculatively moved from block src to trg,
2319    otherwise return 0.  Called before first insertion of insn to
2320    ready-list or before the scheduling.  */
2321
2322 static int
2323 check_live (insn, src)
2324      rtx insn;
2325      int src;
2326 {
2327   /* Find the registers set by instruction.  */
2328   if (GET_CODE (PATTERN (insn)) == SET
2329       || GET_CODE (PATTERN (insn)) == CLOBBER)
2330     return check_live_1 (src, PATTERN (insn));
2331   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
2332     {
2333       int j;
2334       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
2335         if ((GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
2336              || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
2337             && !check_live_1 (src, XVECEXP (PATTERN (insn), 0, j)))
2338           return 0;
2339
2340       return 1;
2341     }
2342
2343   return 1;
2344 }
2345
2346 /* Update the live registers info after insn was moved speculatively from
2347    block src to trg.  */
2348
2349 static void
2350 update_live (insn, src)
2351      rtx insn;
2352      int src;
2353 {
2354   /* Find the registers set by instruction.  */
2355   if (GET_CODE (PATTERN (insn)) == SET
2356       || GET_CODE (PATTERN (insn)) == CLOBBER)
2357     update_live_1 (src, PATTERN (insn));
2358   else if (GET_CODE (PATTERN (insn)) == PARALLEL)
2359     {
2360       int j;
2361       for (j = XVECLEN (PATTERN (insn), 0) - 1; j >= 0; j--)
2362         if (GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == SET
2363             || GET_CODE (XVECEXP (PATTERN (insn), 0, j)) == CLOBBER)
2364           update_live_1 (src, XVECEXP (PATTERN (insn), 0, j));
2365     }
2366 }
2367
2368 /* Exception Free Loads:
2369
2370    We define five classes of speculative loads: IFREE, IRISKY,
2371    PFREE, PRISKY, and MFREE.
2372
2373    IFREE loads are loads that are proved to be exception-free, just
2374    by examining the load insn.  Examples for such loads are loads
2375    from TOC and loads of global data.
2376
2377    IRISKY loads are loads that are proved to be exception-risky,
2378    just by examining the load insn.  Examples for such loads are
2379    volatile loads and loads from shared memory.
2380
2381    PFREE loads are loads for which we can prove, by examining other
2382    insns, that they are exception-free.  Currently, this class consists
2383    of loads for which we are able to find a "similar load", either in
2384    the target block, or, if only one split-block exists, in that split
2385    block.  Load2 is similar to load1 if both have same single base
2386    register.  We identify only part of the similar loads, by finding
2387    an insn upon which both load1 and load2 have a DEF-USE dependence.
2388
2389    PRISKY loads are loads for which we can prove, by examining other
2390    insns, that they are exception-risky.  Currently we have two proofs for
2391    such loads.  The first proof detects loads that are probably guarded by a
2392    test on the memory address.  This proof is based on the
2393    backward and forward data dependence information for the region.
2394    Let load-insn be the examined load.
2395    Load-insn is PRISKY iff ALL the following hold:
2396
2397    - insn1 is not in the same block as load-insn
2398    - there is a DEF-USE dependence chain (insn1, ..., load-insn)
2399    - test-insn is either a compare or a branch, not in the same block
2400      as load-insn
2401    - load-insn is reachable from test-insn
2402    - there is a DEF-USE dependence chain (insn1, ..., test-insn)
2403
2404    This proof might fail when the compare and the load are fed
2405    by an insn not in the region.  To solve this, we will add to this
2406    group all loads that have no input DEF-USE dependence.
2407
2408    The second proof detects loads that are directly or indirectly
2409    fed by a speculative load.  This proof is affected by the
2410    scheduling process.  We will use the flag  fed_by_spec_load.
2411    Initially, all insns have this flag reset.  After a speculative
2412    motion of an insn, if insn is either a load, or marked as
2413    fed_by_spec_load, we will also mark as fed_by_spec_load every
2414    insn1 for which a DEF-USE dependence (insn, insn1) exists.  A
2415    load which is fed_by_spec_load is also PRISKY.
2416
2417    MFREE (maybe-free) loads are all the remaining loads. They may be
2418    exception-free, but we cannot prove it.
2419
2420    Now, all loads in IFREE and PFREE classes are considered
2421    exception-free, while all loads in IRISKY and PRISKY classes are
2422    considered exception-risky.  As for loads in the MFREE class,
2423    these are considered either exception-free or exception-risky,
2424    depending on whether we are pessimistic or optimistic.  We have
2425    to take the pessimistic approach to assure the safety of
2426    speculative scheduling, but we can take the optimistic approach
2427    by invoking the -fsched_spec_load_dangerous option.  */
2428
2429 enum INSN_TRAP_CLASS
2430 {
2431   TRAP_FREE = 0, IFREE = 1, PFREE_CANDIDATE = 2,
2432   PRISKY_CANDIDATE = 3, IRISKY = 4, TRAP_RISKY = 5
2433 };
2434
2435 #define WORST_CLASS(class1, class2) \
2436 ((class1 > class2) ? class1 : class2)
2437
2438 /* Non-zero if block bb_to is equal to, or reachable from block bb_from.  */
2439 #define IS_REACHABLE(bb_from, bb_to)                                    \
2440 (bb_from == bb_to                                                       \
2441    || IS_RGN_ENTRY (bb_from)                                            \
2442    || (bitset_member (ancestor_edges[bb_to],                            \
2443                       EDGE_TO_BIT (IN_EDGES (BB_TO_BLOCK (bb_from))),   \
2444                       edgeset_size)))
2445
2446 /* Non-zero iff the address is comprised from at most 1 register.  */
2447 #define CONST_BASED_ADDRESS_P(x)                        \
2448   (GET_CODE (x) == REG                                  \
2449    || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS   \
2450         || (GET_CODE (x) == LO_SUM))                    \
2451        && (GET_CODE (XEXP (x, 0)) == CONST_INT          \
2452            || GET_CODE (XEXP (x, 1)) == CONST_INT)))
2453
2454 /* Turns on the fed_by_spec_load flag for insns fed by load_insn.  */
2455
2456 static void
2457 set_spec_fed (load_insn)
2458      rtx load_insn;
2459 {
2460   rtx link;
2461
2462   for (link = INSN_DEPEND (load_insn); link; link = XEXP (link, 1))
2463     if (GET_MODE (link) == VOIDmode)
2464       FED_BY_SPEC_LOAD (XEXP (link, 0)) = 1;
2465 }                               /* set_spec_fed */
2466
2467 /* On the path from the insn to load_insn_bb, find a conditional
2468 branch depending on insn, that guards the speculative load.  */
2469
2470 static int
2471 find_conditional_protection (insn, load_insn_bb)
2472      rtx insn;
2473      int load_insn_bb;
2474 {
2475   rtx link;
2476
2477   /* Iterate through DEF-USE forward dependences.  */
2478   for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
2479     {
2480       rtx next = XEXP (link, 0);
2481       if ((CONTAINING_RGN (BLOCK_NUM (next)) ==
2482            CONTAINING_RGN (BB_TO_BLOCK (load_insn_bb)))
2483           && IS_REACHABLE (INSN_BB (next), load_insn_bb)
2484           && load_insn_bb != INSN_BB (next)
2485           && GET_MODE (link) == VOIDmode
2486           && (GET_CODE (next) == JUMP_INSN
2487               || find_conditional_protection (next, load_insn_bb)))
2488         return 1;
2489     }
2490   return 0;
2491 }                               /* find_conditional_protection */
2492
2493 /* Returns 1 if the same insn1 that participates in the computation
2494    of load_insn's address is feeding a conditional branch that is
2495    guarding on load_insn. This is true if we find a the two DEF-USE
2496    chains:
2497    insn1 -> ... -> conditional-branch
2498    insn1 -> ... -> load_insn,
2499    and if a flow path exist:
2500    insn1 -> ... -> conditional-branch -> ... -> load_insn,
2501    and if insn1 is on the path
2502    region-entry -> ... -> bb_trg -> ... load_insn.
2503
2504    Locate insn1 by climbing on LOG_LINKS from load_insn.
2505    Locate the branch by following INSN_DEPEND from insn1.  */
2506
2507 static int
2508 is_conditionally_protected (load_insn, bb_src, bb_trg)
2509      rtx load_insn;
2510      int bb_src, bb_trg;
2511 {
2512   rtx link;
2513
2514   for (link = LOG_LINKS (load_insn); link; link = XEXP (link, 1))
2515     {
2516       rtx insn1 = XEXP (link, 0);
2517
2518       /* Must be a DEF-USE dependence upon non-branch.  */
2519       if (GET_MODE (link) != VOIDmode
2520           || GET_CODE (insn1) == JUMP_INSN)
2521         continue;
2522
2523       /* Must exist a path: region-entry -> ... -> bb_trg -> ... load_insn.  */
2524       if (INSN_BB (insn1) == bb_src
2525           || (CONTAINING_RGN (BLOCK_NUM (insn1))
2526               != CONTAINING_RGN (BB_TO_BLOCK (bb_src)))
2527           || (!IS_REACHABLE (bb_trg, INSN_BB (insn1))
2528               && !IS_REACHABLE (INSN_BB (insn1), bb_trg)))
2529         continue;
2530
2531       /* Now search for the conditional-branch.  */
2532       if (find_conditional_protection (insn1, bb_src))
2533         return 1;
2534
2535       /* Recursive step: search another insn1, "above" current insn1.  */
2536       return is_conditionally_protected (insn1, bb_src, bb_trg);
2537     }
2538
2539   /* The chain does not exist.  */
2540   return 0;
2541 }                               /* is_conditionally_protected */
2542
2543 /* Returns 1 if a clue for "similar load" 'insn2' is found, and hence
2544    load_insn can move speculatively from bb_src to bb_trg.  All the
2545    following must hold:
2546
2547    (1) both loads have 1 base register (PFREE_CANDIDATEs).
2548    (2) load_insn and load1 have a def-use dependence upon
2549    the same insn 'insn1'.
2550    (3) either load2 is in bb_trg, or:
2551    - there's only one split-block, and
2552    - load1 is on the escape path, and
2553
2554    From all these we can conclude that the two loads access memory
2555    addresses that differ at most by a constant, and hence if moving
2556    load_insn would cause an exception, it would have been caused by
2557    load2 anyhow.  */
2558
2559 static int
2560 is_pfree (load_insn, bb_src, bb_trg)
2561      rtx load_insn;
2562      int bb_src, bb_trg;
2563 {
2564   rtx back_link;
2565   register candidate *candp = candidate_table + bb_src;
2566
2567   if (candp->split_bbs.nr_members != 1)
2568     /* Must have exactly one escape block.  */
2569     return 0;
2570
2571   for (back_link = LOG_LINKS (load_insn);
2572        back_link; back_link = XEXP (back_link, 1))
2573     {
2574       rtx insn1 = XEXP (back_link, 0);
2575
2576       if (GET_MODE (back_link) == VOIDmode)
2577         {
2578           /* Found a DEF-USE dependence (insn1, load_insn).  */
2579           rtx fore_link;
2580
2581           for (fore_link = INSN_DEPEND (insn1);
2582                fore_link; fore_link = XEXP (fore_link, 1))
2583             {
2584               rtx insn2 = XEXP (fore_link, 0);
2585               if (GET_MODE (fore_link) == VOIDmode)
2586                 {
2587                   /* Found a DEF-USE dependence (insn1, insn2).  */
2588                   if (haifa_classify_insn (insn2) != PFREE_CANDIDATE)
2589                     /* insn2 not guaranteed to be a 1 base reg load.  */
2590                     continue;
2591
2592                   if (INSN_BB (insn2) == bb_trg)
2593                     /* insn2 is the similar load, in the target block.  */
2594                     return 1;
2595
2596                   if (*(candp->split_bbs.first_member) == BLOCK_NUM (insn2))
2597                     /* insn2 is a similar load, in a split-block.  */
2598                     return 1;
2599                 }
2600             }
2601         }
2602     }
2603
2604   /* Couldn't find a similar load.  */
2605   return 0;
2606 }                               /* is_pfree */
2607
2608 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
2609    as found by analyzing insn's expression.  */
2610
2611 static int
2612 may_trap_exp (x, is_store)
2613      rtx x;
2614      int is_store;
2615 {
2616   enum rtx_code code;
2617
2618   if (x == 0)
2619     return TRAP_FREE;
2620   code = GET_CODE (x);
2621   if (is_store)
2622     {
2623       if (code == MEM)
2624         return TRAP_RISKY;
2625       else
2626         return TRAP_FREE;
2627     }
2628   if (code == MEM)
2629     {
2630       /* The insn uses memory:  a volatile load.  */
2631       if (MEM_VOLATILE_P (x))
2632         return IRISKY;
2633       /* An exception-free load.  */
2634       if (!may_trap_p (x))
2635         return IFREE;
2636       /* A load with 1 base register, to be further checked.  */
2637       if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
2638         return PFREE_CANDIDATE;
2639       /* No info on the load, to be further checked.  */
2640       return PRISKY_CANDIDATE;
2641     }
2642   else
2643     {
2644       const char *fmt;
2645       int i, insn_class = TRAP_FREE;
2646
2647       /* Neither store nor load, check if it may cause a trap.  */
2648       if (may_trap_p (x))
2649         return TRAP_RISKY;
2650       /* Recursive step: walk the insn...  */
2651       fmt = GET_RTX_FORMAT (code);
2652       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2653         {
2654           if (fmt[i] == 'e')
2655             {
2656               int tmp_class = may_trap_exp (XEXP (x, i), is_store);
2657               insn_class = WORST_CLASS (insn_class, tmp_class);
2658             }
2659           else if (fmt[i] == 'E')
2660             {
2661               int j;
2662               for (j = 0; j < XVECLEN (x, i); j++)
2663                 {
2664                   int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
2665                   insn_class = WORST_CLASS (insn_class, tmp_class);
2666                   if (insn_class == TRAP_RISKY || insn_class == IRISKY)
2667                     break;
2668                 }
2669             }
2670           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
2671             break;
2672         }
2673       return insn_class;
2674     }
2675 }
2676
2677 /* Classifies insn for the purpose of verifying that it can be
2678    moved speculatively, by examining it's patterns, returning:
2679    TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
2680    TRAP_FREE: non-load insn.
2681    IFREE: load from a globaly safe location.
2682    IRISKY: volatile load.
2683    PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
2684    being either PFREE or PRISKY.  */
2685
2686 static int
2687 haifa_classify_insn (insn)
2688      rtx insn;
2689 {
2690   rtx pat = PATTERN (insn);
2691   int tmp_class = TRAP_FREE;
2692   int insn_class = TRAP_FREE;
2693   enum rtx_code code;
2694
2695   if (GET_CODE (pat) == PARALLEL)
2696     {
2697       int i, len = XVECLEN (pat, 0);
2698
2699       for (i = len - 1; i >= 0; i--)
2700         {
2701           code = GET_CODE (XVECEXP (pat, 0, i));
2702           switch (code)
2703             {
2704             case CLOBBER:
2705               /* Test if it is a 'store'.  */
2706               tmp_class = may_trap_exp (XEXP (XVECEXP (pat, 0, i), 0), 1);
2707               break;
2708             case SET:
2709               /* Test if it is a store.  */
2710               tmp_class = may_trap_exp (SET_DEST (XVECEXP (pat, 0, i)), 1);
2711               if (tmp_class == TRAP_RISKY)
2712                 break;
2713               /* Test if it is a load.  */
2714               tmp_class =
2715                 WORST_CLASS (tmp_class,
2716                              may_trap_exp (SET_SRC (XVECEXP (pat, 0, i)), 0));
2717               break;
2718             case COND_EXEC:
2719             case TRAP_IF:
2720               tmp_class = TRAP_RISKY;
2721               break;
2722             default:;
2723             }
2724           insn_class = WORST_CLASS (insn_class, tmp_class);
2725           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
2726             break;
2727         }
2728     }
2729   else
2730     {
2731       code = GET_CODE (pat);
2732       switch (code)
2733         {
2734         case CLOBBER:
2735           /* Test if it is a 'store'.  */
2736           tmp_class = may_trap_exp (XEXP (pat, 0), 1);
2737           break;
2738         case SET:
2739           /* Test if it is a store.  */
2740           tmp_class = may_trap_exp (SET_DEST (pat), 1);
2741           if (tmp_class == TRAP_RISKY)
2742             break;
2743           /* Test if it is a load.  */
2744           tmp_class =
2745             WORST_CLASS (tmp_class,
2746                          may_trap_exp (SET_SRC (pat), 0));
2747           break;
2748         case COND_EXEC:
2749         case TRAP_IF:
2750           tmp_class = TRAP_RISKY;
2751           break;
2752         default:;
2753         }
2754       insn_class = tmp_class;
2755     }
2756
2757   return insn_class;
2758 }
2759
2760 /* Return 1 if load_insn is prisky (i.e. if load_insn is fed by
2761    a load moved speculatively, or if load_insn is protected by
2762    a compare on load_insn's address).  */
2763
2764 static int
2765 is_prisky (load_insn, bb_src, bb_trg)
2766      rtx load_insn;
2767      int bb_src, bb_trg;
2768 {
2769   if (FED_BY_SPEC_LOAD (load_insn))
2770     return 1;
2771
2772   if (LOG_LINKS (load_insn) == NULL)
2773     /* Dependence may 'hide' out of the region.  */
2774     return 1;
2775
2776   if (is_conditionally_protected (load_insn, bb_src, bb_trg))
2777     return 1;
2778
2779   return 0;
2780 }
2781
2782 /* Insn is a candidate to be moved speculatively from bb_src to bb_trg.
2783    Return 1 if insn is exception-free (and the motion is valid)
2784    and 0 otherwise.  */
2785
2786 static int
2787 is_exception_free (insn, bb_src, bb_trg)
2788      rtx insn;
2789      int bb_src, bb_trg;
2790 {
2791   int insn_class = haifa_classify_insn (insn);
2792
2793   /* Handle non-load insns.  */
2794   switch (insn_class)
2795     {
2796     case TRAP_FREE:
2797       return 1;
2798     case TRAP_RISKY:
2799       return 0;
2800     default:;
2801     }
2802
2803   /* Handle loads.  */
2804   if (!flag_schedule_speculative_load)
2805     return 0;
2806   IS_LOAD_INSN (insn) = 1;
2807   switch (insn_class)
2808     {
2809     case IFREE:
2810       return (1);
2811     case IRISKY:
2812       return 0;
2813     case PFREE_CANDIDATE:
2814       if (is_pfree (insn, bb_src, bb_trg))
2815         return 1;
2816       /* Don't 'break' here: PFREE-candidate is also PRISKY-candidate.  */
2817     case PRISKY_CANDIDATE:
2818       if (!flag_schedule_speculative_load_dangerous
2819           || is_prisky (insn, bb_src, bb_trg))
2820         return 0;
2821       break;
2822     default:;
2823     }
2824
2825   return flag_schedule_speculative_load_dangerous;
2826 }
2827
2828 /* Process an insn's memory dependencies.  There are four kinds of
2829    dependencies:
2830
2831    (0) read dependence: read follows read
2832    (1) true dependence: read follows write
2833    (2) anti dependence: write follows read
2834    (3) output dependence: write follows write
2835
2836    We are careful to build only dependencies which actually exist, and
2837    use transitivity to avoid building too many links.  */
2838 \f
2839 /* Return 1 if the pair (insn, x) is found in (LIST, LIST1), or 0
2840    otherwise.  */
2841
2842 HAIFA_INLINE static char
2843 find_insn_mem_list (insn, x, list, list1)
2844      rtx insn, x;
2845      rtx list, list1;
2846 {
2847   while (list)
2848     {
2849       if (XEXP (list, 0) == insn
2850           && XEXP (list1, 0) == x)
2851         return 1;
2852       list = XEXP (list, 1);
2853       list1 = XEXP (list1, 1);
2854     }
2855   return 0;
2856 }
2857
2858 /* Compute the function units used by INSN.  This caches the value
2859    returned by function_units_used.  A function unit is encoded as the
2860    unit number if the value is non-negative and the compliment of a
2861    mask if the value is negative.  A function unit index is the
2862    non-negative encoding.  */
2863
2864 HAIFA_INLINE static int
2865 insn_unit (insn)
2866      rtx insn;
2867 {
2868   register int unit = INSN_UNIT (insn);
2869
2870   if (unit == 0)
2871     {
2872       recog_memoized (insn);
2873
2874       /* A USE insn, or something else we don't need to understand.
2875          We can't pass these directly to function_units_used because it will
2876          trigger a fatal error for unrecognizable insns.  */
2877       if (INSN_CODE (insn) < 0)
2878         unit = -1;
2879       else
2880         {
2881           unit = function_units_used (insn);
2882           /* Increment non-negative values so we can cache zero.  */
2883           if (unit >= 0)
2884             unit++;
2885         }
2886       /* We only cache 16 bits of the result, so if the value is out of
2887          range, don't cache it.  */
2888       if (FUNCTION_UNITS_SIZE < HOST_BITS_PER_SHORT
2889           || unit >= 0
2890           || (unit & ~((1 << (HOST_BITS_PER_SHORT - 1)) - 1)) == 0)
2891         INSN_UNIT (insn) = unit;
2892     }
2893   return (unit > 0 ? unit - 1 : unit);
2894 }
2895
2896 /* Compute the blockage range for executing INSN on UNIT.  This caches
2897    the value returned by the blockage_range_function for the unit.
2898    These values are encoded in an int where the upper half gives the
2899    minimum value and the lower half gives the maximum value.  */
2900
2901 HAIFA_INLINE static unsigned int
2902 blockage_range (unit, insn)
2903      int unit;
2904      rtx insn;
2905 {
2906   unsigned int blockage = INSN_BLOCKAGE (insn);
2907   unsigned int range;
2908
2909   if ((int) UNIT_BLOCKED (blockage) != unit + 1)
2910     {
2911       range = function_units[unit].blockage_range_function (insn);
2912       /* We only cache the blockage range for one unit and then only if
2913          the values fit.  */
2914       if (HOST_BITS_PER_INT >= UNIT_BITS + 2 * BLOCKAGE_BITS)
2915         INSN_BLOCKAGE (insn) = ENCODE_BLOCKAGE (unit + 1, range);
2916     }
2917   else
2918     range = BLOCKAGE_RANGE (blockage);
2919
2920   return range;
2921 }
2922
2923 /* A vector indexed by function unit instance giving the last insn to use
2924    the unit.  The value of the function unit instance index for unit U
2925    instance I is (U + I * FUNCTION_UNITS_SIZE).  */
2926 static rtx unit_last_insn[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
2927
2928 /* A vector indexed by function unit instance giving the minimum time when
2929    the unit will unblock based on the maximum blockage cost.  */
2930 static int unit_tick[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
2931
2932 /* A vector indexed by function unit number giving the number of insns
2933    that remain to use the unit.  */
2934 static int unit_n_insns[FUNCTION_UNITS_SIZE];
2935
2936 /* Reset the function unit state to the null state.  */
2937
2938 static void
2939 clear_units ()
2940 {
2941   memset ((char *) unit_last_insn, 0, sizeof (unit_last_insn));
2942   memset ((char *) unit_tick, 0, sizeof (unit_tick));
2943   memset ((char *) unit_n_insns, 0, sizeof (unit_n_insns));
2944 }
2945
2946 /* Return the issue-delay of an insn.  */
2947
2948 HAIFA_INLINE static int
2949 insn_issue_delay (insn)
2950      rtx insn;
2951 {
2952   int i, delay = 0;
2953   int unit = insn_unit (insn);
2954
2955   /* Efficiency note: in fact, we are working 'hard' to compute a
2956      value that was available in md file, and is not available in
2957      function_units[] structure.  It would be nice to have this
2958      value there, too.  */
2959   if (unit >= 0)
2960     {
2961       if (function_units[unit].blockage_range_function &&
2962           function_units[unit].blockage_function)
2963         delay = function_units[unit].blockage_function (insn, insn);
2964     }
2965   else
2966     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
2967       if ((unit & 1) != 0 && function_units[i].blockage_range_function
2968           && function_units[i].blockage_function)
2969         delay = MAX (delay, function_units[i].blockage_function (insn, insn));
2970
2971   return delay;
2972 }
2973
2974 /* Return the actual hazard cost of executing INSN on the unit UNIT,
2975    instance INSTANCE at time CLOCK if the previous actual hazard cost
2976    was COST.  */
2977
2978 HAIFA_INLINE static int
2979 actual_hazard_this_instance (unit, instance, insn, clock, cost)
2980      int unit, instance, clock, cost;
2981      rtx insn;
2982 {
2983   int tick = unit_tick[instance]; /* Issue time of the last issued insn.  */
2984
2985   if (tick - clock > cost)
2986     {
2987       /* The scheduler is operating forward, so unit's last insn is the
2988          executing insn and INSN is the candidate insn.  We want a
2989          more exact measure of the blockage if we execute INSN at CLOCK
2990          given when we committed the execution of the unit's last insn.
2991
2992          The blockage value is given by either the unit's max blockage
2993          constant, blockage range function, or blockage function.  Use
2994          the most exact form for the given unit.  */
2995
2996       if (function_units[unit].blockage_range_function)
2997         {
2998           if (function_units[unit].blockage_function)
2999             tick += (function_units[unit].blockage_function
3000                      (unit_last_insn[instance], insn)
3001                      - function_units[unit].max_blockage);
3002           else
3003             tick += ((int) MAX_BLOCKAGE_COST (blockage_range (unit, insn))
3004                      - function_units[unit].max_blockage);
3005         }
3006       if (tick - clock > cost)
3007         cost = tick - clock;
3008     }
3009   return cost;
3010 }
3011
3012 /* Record INSN as having begun execution on the units encoded by UNIT at
3013    time CLOCK.  */
3014
3015 HAIFA_INLINE static void
3016 schedule_unit (unit, insn, clock)
3017      int unit, clock;
3018      rtx insn;
3019 {
3020   int i;
3021
3022   if (unit >= 0)
3023     {
3024       int instance = unit;
3025 #if MAX_MULTIPLICITY > 1
3026       /* Find the first free instance of the function unit and use that
3027          one.  We assume that one is free.  */
3028       for (i = function_units[unit].multiplicity - 1; i > 0; i--)
3029         {
3030           if (!actual_hazard_this_instance (unit, instance, insn, clock, 0))
3031             break;
3032           instance += FUNCTION_UNITS_SIZE;
3033         }
3034 #endif
3035       unit_last_insn[instance] = insn;
3036       unit_tick[instance] = (clock + function_units[unit].max_blockage);
3037     }
3038   else
3039     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
3040       if ((unit & 1) != 0)
3041         schedule_unit (i, insn, clock);
3042 }
3043
3044 /* Return the actual hazard cost of executing INSN on the units encoded by
3045    UNIT at time CLOCK if the previous actual hazard cost was COST.  */
3046
3047 HAIFA_INLINE static int
3048 actual_hazard (unit, insn, clock, cost)
3049      int unit, clock, cost;
3050      rtx insn;
3051 {
3052   int i;
3053
3054   if (unit >= 0)
3055     {
3056       /* Find the instance of the function unit with the minimum hazard.  */
3057       int instance = unit;
3058       int best_cost = actual_hazard_this_instance (unit, instance, insn,
3059                                                    clock, cost);
3060 #if MAX_MULTIPLICITY > 1
3061       int this_cost;
3062
3063       if (best_cost > cost)
3064         {
3065           for (i = function_units[unit].multiplicity - 1; i > 0; i--)
3066             {
3067               instance += FUNCTION_UNITS_SIZE;
3068               this_cost = actual_hazard_this_instance (unit, instance, insn,
3069                                                        clock, cost);
3070               if (this_cost < best_cost)
3071                 {
3072                   best_cost = this_cost;
3073                   if (this_cost <= cost)
3074                     break;
3075                 }
3076             }
3077         }
3078 #endif
3079       cost = MAX (cost, best_cost);
3080     }
3081   else
3082     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
3083       if ((unit & 1) != 0)
3084         cost = actual_hazard (i, insn, clock, cost);
3085
3086   return cost;
3087 }
3088
3089 /* Return the potential hazard cost of executing an instruction on the
3090    units encoded by UNIT if the previous potential hazard cost was COST.
3091    An insn with a large blockage time is chosen in preference to one
3092    with a smaller time; an insn that uses a unit that is more likely
3093    to be used is chosen in preference to one with a unit that is less
3094    used.  We are trying to minimize a subsequent actual hazard.  */
3095
3096 HAIFA_INLINE static int
3097 potential_hazard (unit, insn, cost)
3098      int unit, cost;
3099      rtx insn;
3100 {
3101   int i, ncost;
3102   unsigned int minb, maxb;
3103
3104   if (unit >= 0)
3105     {
3106       minb = maxb = function_units[unit].max_blockage;
3107       if (maxb > 1)
3108         {
3109           if (function_units[unit].blockage_range_function)
3110             {
3111               maxb = minb = blockage_range (unit, insn);
3112               maxb = MAX_BLOCKAGE_COST (maxb);
3113               minb = MIN_BLOCKAGE_COST (minb);
3114             }
3115
3116           if (maxb > 1)
3117             {
3118               /* Make the number of instructions left dominate.  Make the
3119                  minimum delay dominate the maximum delay.  If all these
3120                  are the same, use the unit number to add an arbitrary
3121                  ordering.  Other terms can be added.  */
3122               ncost = minb * 0x40 + maxb;
3123               ncost *= (unit_n_insns[unit] - 1) * 0x1000 + unit;
3124               if (ncost > cost)
3125                 cost = ncost;
3126             }
3127         }
3128     }
3129   else
3130     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
3131       if ((unit & 1) != 0)
3132         cost = potential_hazard (i, insn, cost);
3133
3134   return cost;
3135 }
3136
3137 /* Compute cost of executing INSN given the dependence LINK on the insn USED.
3138    This is the number of cycles between instruction issue and
3139    instruction results.  */
3140
3141 HAIFA_INLINE static int
3142 insn_cost (insn, link, used)
3143      rtx insn, link, used;
3144 {
3145   register int cost = INSN_COST (insn);
3146
3147   if (cost == 0)
3148     {
3149       recog_memoized (insn);
3150
3151       /* A USE insn, or something else we don't need to understand.
3152          We can't pass these directly to result_ready_cost because it will
3153          trigger a fatal error for unrecognizable insns.  */
3154       if (INSN_CODE (insn) < 0)
3155         {
3156           INSN_COST (insn) = 1;
3157           return 1;
3158         }
3159       else
3160         {
3161           cost = result_ready_cost (insn);
3162
3163           if (cost < 1)
3164             cost = 1;
3165
3166           INSN_COST (insn) = cost;
3167         }
3168     }
3169
3170   /* In this case estimate cost without caring how insn is used.  */
3171   if (link == 0 && used == 0)
3172     return cost;
3173
3174   /* A USE insn should never require the value used to be computed.  This
3175      allows the computation of a function's result and parameter values to
3176      overlap the return and call.  */
3177   recog_memoized (used);
3178   if (INSN_CODE (used) < 0)
3179     LINK_COST_FREE (link) = 1;
3180
3181   /* If some dependencies vary the cost, compute the adjustment.  Most
3182      commonly, the adjustment is complete: either the cost is ignored
3183      (in the case of an output- or anti-dependence), or the cost is
3184      unchanged.  These values are cached in the link as LINK_COST_FREE
3185      and LINK_COST_ZERO.  */
3186
3187   if (LINK_COST_FREE (link))
3188     cost = 0;
3189 #ifdef ADJUST_COST
3190   else if (!LINK_COST_ZERO (link))
3191     {
3192       int ncost = cost;
3193
3194       ADJUST_COST (used, link, insn, ncost);
3195       if (ncost < 1)
3196         {
3197           LINK_COST_FREE (link) = 1;
3198           ncost = 0;
3199         }
3200       if (cost == ncost)
3201         LINK_COST_ZERO (link) = 1;
3202       cost = ncost;
3203     }
3204 #endif
3205   return cost;
3206 }
3207
3208 /* Compute the priority number for INSN.  */
3209
3210 static int
3211 priority (insn)
3212      rtx insn;
3213 {
3214   int this_priority;
3215   rtx link;
3216
3217   if (! INSN_P (insn))
3218     return 0;
3219
3220   if ((this_priority = INSN_PRIORITY (insn)) == 0)
3221     {
3222       if (INSN_DEPEND (insn) == 0)
3223         this_priority = insn_cost (insn, 0, 0);
3224       else
3225         for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
3226           {
3227             rtx next;
3228             int next_priority;
3229
3230             if (RTX_INTEGRATED_P (link))
3231               continue;
3232
3233             next = XEXP (link, 0);
3234
3235             /* Critical path is meaningful in block boundaries only.  */
3236             if (BLOCK_NUM (next) != BLOCK_NUM (insn))
3237               continue;
3238
3239             next_priority = insn_cost (insn, link, next) + priority (next);
3240             if (next_priority > this_priority)
3241               this_priority = next_priority;
3242           }
3243       INSN_PRIORITY (insn) = this_priority;
3244     }
3245   return this_priority;
3246 }
3247 \f
3248 /* Remove all INSN_LISTs and EXPR_LISTs from the pending lists and add
3249    them to the unused_*_list variables, so that they can be reused.  */
3250
3251 static void
3252 free_pending_lists ()
3253 {
3254   int bb;
3255
3256   for (bb = 0; bb < current_nr_blocks; bb++)
3257     {
3258       free_INSN_LIST_list (&bb_deps[bb].pending_read_insns);
3259       free_INSN_LIST_list (&bb_deps[bb].pending_write_insns);
3260       free_EXPR_LIST_list (&bb_deps[bb].pending_read_mems);
3261       free_EXPR_LIST_list (&bb_deps[bb].pending_write_mems);
3262     }
3263 }
3264
3265 /* Add an INSN and MEM reference pair to a pending INSN_LIST and MEM_LIST.
3266    The MEM is a memory reference contained within INSN, which we are saving
3267    so that we can do memory aliasing on it.  */
3268
3269 static void
3270 add_insn_mem_dependence (deps, insn_list, mem_list, insn, mem)
3271      struct deps *deps;
3272      rtx *insn_list, *mem_list, insn, mem;
3273 {
3274   register rtx link;
3275
3276   link = alloc_INSN_LIST (insn, *insn_list);
3277   *insn_list = link;
3278
3279   link = alloc_EXPR_LIST (VOIDmode, mem, *mem_list);
3280   *mem_list = link;
3281
3282   deps->pending_lists_length++;
3283 }
3284 \f
3285 /* Make a dependency between every memory reference on the pending lists
3286    and INSN, thus flushing the pending lists.  If ONLY_WRITE, don't flush
3287    the read list.  */
3288
3289 static void
3290 flush_pending_lists (deps, insn, only_write)
3291      struct deps *deps;
3292      rtx insn;
3293      int only_write;
3294 {
3295   rtx u;
3296   rtx link;
3297
3298   while (deps->pending_read_insns && ! only_write)
3299     {
3300       add_dependence (insn, XEXP (deps->pending_read_insns, 0),
3301                       REG_DEP_ANTI);
3302
3303       link = deps->pending_read_insns;
3304       deps->pending_read_insns = XEXP (deps->pending_read_insns, 1);
3305       free_INSN_LIST_node (link);
3306
3307       link = deps->pending_read_mems;
3308       deps->pending_read_mems = XEXP (deps->pending_read_mems, 1);
3309       free_EXPR_LIST_node (link);
3310     }
3311   while (deps->pending_write_insns)
3312     {
3313       add_dependence (insn, XEXP (deps->pending_write_insns, 0),
3314                       REG_DEP_ANTI);
3315
3316       link = deps->pending_write_insns;
3317       deps->pending_write_insns = XEXP (deps->pending_write_insns, 1);
3318       free_INSN_LIST_node (link);
3319
3320       link = deps->pending_write_mems;
3321       deps->pending_write_mems = XEXP (deps->pending_write_mems, 1);
3322       free_EXPR_LIST_node (link);
3323     }
3324   deps->pending_lists_length = 0;
3325
3326   /* last_pending_memory_flush is now a list of insns.  */
3327   for (u = deps->last_pending_memory_flush; u; u = XEXP (u, 1))
3328     add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3329
3330   free_INSN_LIST_list (&deps->last_pending_memory_flush);
3331   deps->last_pending_memory_flush = alloc_INSN_LIST (insn, NULL_RTX);
3332 }
3333
3334 /* Analyze a single SET, CLOBBER, PRE_DEC, POST_DEC, PRE_INC or POST_INC
3335    rtx, X, creating all dependencies generated by the write to the
3336    destination of X, and reads of everything mentioned.  */
3337
3338 static void
3339 sched_analyze_1 (deps, x, insn)
3340      struct deps *deps;
3341      rtx x;
3342      rtx insn;
3343 {
3344   register int regno;
3345   register rtx dest = XEXP (x, 0);
3346   enum rtx_code code = GET_CODE (x);
3347
3348   if (dest == 0)
3349     return;
3350
3351   if (GET_CODE (dest) == PARALLEL
3352       && GET_MODE (dest) == BLKmode)
3353     {
3354       register int i;
3355       for (i = XVECLEN (dest, 0) - 1; i >= 0; i--)
3356         sched_analyze_1 (deps, XVECEXP (dest, 0, i), insn);
3357       if (GET_CODE (x) == SET)
3358         sched_analyze_2 (deps, SET_SRC (x), insn);
3359       return;
3360     }
3361
3362   while (GET_CODE (dest) == STRICT_LOW_PART || GET_CODE (dest) == SUBREG
3363          || GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SIGN_EXTRACT)
3364     {
3365       if (GET_CODE (dest) == ZERO_EXTRACT || GET_CODE (dest) == SIGN_EXTRACT)
3366         {
3367           /* The second and third arguments are values read by this insn.  */
3368           sched_analyze_2 (deps, XEXP (dest, 1), insn);
3369           sched_analyze_2 (deps, XEXP (dest, 2), insn);
3370         }
3371       dest = XEXP (dest, 0);
3372     }
3373
3374   if (GET_CODE (dest) == REG)
3375     {
3376       register int i;
3377
3378       regno = REGNO (dest);
3379
3380       /* A hard reg in a wide mode may really be multiple registers.
3381          If so, mark all of them just like the first.  */
3382       if (regno < FIRST_PSEUDO_REGISTER)
3383         {
3384           i = HARD_REGNO_NREGS (regno, GET_MODE (dest));
3385           while (--i >= 0)
3386             {
3387               int r = regno + i;
3388               rtx u;
3389
3390               for (u = deps->reg_last_uses[r]; u; u = XEXP (u, 1))
3391                 add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3392
3393               for (u = deps->reg_last_sets[r]; u; u = XEXP (u, 1))
3394                 add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3395
3396               /* Clobbers need not be ordered with respect to one
3397                  another, but sets must be ordered with respect to a
3398                  pending clobber.  */
3399               if (code == SET)
3400                 {
3401                   free_INSN_LIST_list (&deps->reg_last_uses[r]);
3402                   for (u = deps->reg_last_clobbers[r]; u; u = XEXP (u, 1))
3403                     add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3404                   SET_REGNO_REG_SET (reg_pending_sets, r);
3405                 }
3406               else
3407                 SET_REGNO_REG_SET (reg_pending_clobbers, r);
3408
3409               /* Function calls clobber all call_used regs.  */
3410               if (global_regs[r] || (code == SET && call_used_regs[r]))
3411                 for (u = deps->last_function_call; u; u = XEXP (u, 1))
3412                   add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3413             }
3414         }
3415       else
3416         {
3417           rtx u;
3418
3419           for (u = deps->reg_last_uses[regno]; u; u = XEXP (u, 1))
3420             add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3421
3422           for (u = deps->reg_last_sets[regno]; u; u = XEXP (u, 1))
3423             add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3424
3425           if (code == SET)
3426             {
3427               free_INSN_LIST_list (&deps->reg_last_uses[regno]);
3428               for (u = deps->reg_last_clobbers[regno]; u; u = XEXP (u, 1))
3429                 add_dependence (insn, XEXP (u, 0), REG_DEP_OUTPUT);
3430               SET_REGNO_REG_SET (reg_pending_sets, regno);
3431             }
3432           else
3433             SET_REGNO_REG_SET (reg_pending_clobbers, regno);
3434
3435           /* Pseudos that are REG_EQUIV to something may be replaced
3436              by that during reloading.  We need only add dependencies for
3437              the address in the REG_EQUIV note.  */
3438           if (!reload_completed
3439               && reg_known_equiv_p[regno]
3440               && GET_CODE (reg_known_value[regno]) == MEM)
3441             sched_analyze_2 (deps, XEXP (reg_known_value[regno], 0), insn);
3442
3443           /* Don't let it cross a call after scheduling if it doesn't
3444              already cross one.  */
3445
3446           if (REG_N_CALLS_CROSSED (regno) == 0)
3447             for (u = deps->last_function_call; u; u = XEXP (u, 1))
3448               add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3449         }
3450     }
3451   else if (GET_CODE (dest) == MEM)
3452     {
3453       /* Writing memory.  */
3454
3455       if (deps->pending_lists_length > 32)
3456         {
3457           /* Flush all pending reads and writes to prevent the pending lists
3458              from getting any larger.  Insn scheduling runs too slowly when
3459              these lists get long.  The number 32 was chosen because it
3460              seems like a reasonable number.  When compiling GCC with itself,
3461              this flush occurs 8 times for sparc, and 10 times for m88k using
3462              the number 32.  */
3463           flush_pending_lists (deps, insn, 0);
3464         }
3465       else
3466         {
3467           rtx u;
3468           rtx pending, pending_mem;
3469
3470           pending = deps->pending_read_insns;
3471           pending_mem = deps->pending_read_mems;
3472           while (pending)
3473             {
3474               if (anti_dependence (XEXP (pending_mem, 0), dest))
3475                 add_dependence (insn, XEXP (pending, 0), REG_DEP_ANTI);
3476
3477               pending = XEXP (pending, 1);
3478               pending_mem = XEXP (pending_mem, 1);
3479             }
3480
3481           pending = deps->pending_write_insns;
3482           pending_mem = deps->pending_write_mems;
3483           while (pending)
3484             {
3485               if (output_dependence (XEXP (pending_mem, 0), dest))
3486                 add_dependence (insn, XEXP (pending, 0), REG_DEP_OUTPUT);
3487
3488               pending = XEXP (pending, 1);
3489               pending_mem = XEXP (pending_mem, 1);
3490             }
3491
3492           for (u = deps->last_pending_memory_flush; u; u = XEXP (u, 1))
3493             add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3494
3495           add_insn_mem_dependence (deps, &deps->pending_write_insns,
3496                                    &deps->pending_write_mems, insn, dest);
3497         }
3498       sched_analyze_2 (deps, XEXP (dest, 0), insn);
3499     }
3500
3501   /* Analyze reads.  */
3502   if (GET_CODE (x) == SET)
3503     sched_analyze_2 (deps, SET_SRC (x), insn);
3504 }
3505
3506 /* Analyze the uses of memory and registers in rtx X in INSN.  */
3507
3508 static void
3509 sched_analyze_2 (deps, x, insn)
3510      struct deps *deps;
3511      rtx x;
3512      rtx insn;
3513 {
3514   register int i;
3515   register int j;
3516   register enum rtx_code code;
3517   register const char *fmt;
3518
3519   if (x == 0)
3520     return;
3521
3522   code = GET_CODE (x);
3523
3524   switch (code)
3525     {
3526     case CONST_INT:
3527     case CONST_DOUBLE:
3528     case SYMBOL_REF:
3529     case CONST:
3530     case LABEL_REF:
3531       /* Ignore constants.  Note that we must handle CONST_DOUBLE here
3532          because it may have a cc0_rtx in its CONST_DOUBLE_CHAIN field, but
3533          this does not mean that this insn is using cc0.  */
3534       return;
3535
3536 #ifdef HAVE_cc0
3537     case CC0:
3538       /* User of CC0 depends on immediately preceding insn.  */
3539       set_sched_group_p (insn);
3540       return;
3541 #endif
3542
3543     case REG:
3544       {
3545         rtx u;
3546         int regno = REGNO (x);
3547         if (regno < FIRST_PSEUDO_REGISTER)
3548           {
3549             int i;
3550
3551             i = HARD_REGNO_NREGS (regno, GET_MODE (x));
3552             while (--i >= 0)
3553               {
3554                 int r = regno + i;
3555                 deps->reg_last_uses[r]
3556                   = alloc_INSN_LIST (insn, deps->reg_last_uses[r]);
3557
3558                 for (u = deps->reg_last_sets[r]; u; u = XEXP (u, 1))
3559                   add_dependence (insn, XEXP (u, 0), 0);
3560
3561                 /* ??? This should never happen.  */
3562                 for (u = deps->reg_last_clobbers[r]; u; u = XEXP (u, 1))
3563                   add_dependence (insn, XEXP (u, 0), 0);
3564
3565                 if (call_used_regs[r] || global_regs[r])
3566                   /* Function calls clobber all call_used regs.  */
3567                   for (u = deps->last_function_call; u; u = XEXP (u, 1))
3568                     add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3569               }
3570           }
3571         else
3572           {
3573             deps->reg_last_uses[regno]
3574               = alloc_INSN_LIST (insn, deps->reg_last_uses[regno]);
3575
3576             for (u = deps->reg_last_sets[regno]; u; u = XEXP (u, 1))
3577               add_dependence (insn, XEXP (u, 0), 0);
3578
3579             /* ??? This should never happen.  */
3580             for (u = deps->reg_last_clobbers[regno]; u; u = XEXP (u, 1))
3581               add_dependence (insn, XEXP (u, 0), 0);
3582
3583             /* Pseudos that are REG_EQUIV to something may be replaced
3584                by that during reloading.  We need only add dependencies for
3585                the address in the REG_EQUIV note.  */
3586             if (!reload_completed
3587                 && reg_known_equiv_p[regno]
3588                 && GET_CODE (reg_known_value[regno]) == MEM)
3589               sched_analyze_2 (deps, XEXP (reg_known_value[regno], 0), insn);
3590
3591             /* If the register does not already cross any calls, then add this
3592                insn to the sched_before_next_call list so that it will still
3593                not cross calls after scheduling.  */
3594             if (REG_N_CALLS_CROSSED (regno) == 0)
3595               add_dependence (deps->sched_before_next_call, insn,
3596                               REG_DEP_ANTI);
3597           }
3598         return;
3599       }
3600
3601     case MEM:
3602       {
3603         /* Reading memory.  */
3604         rtx u;
3605         rtx pending, pending_mem;
3606
3607         pending = deps->pending_read_insns;
3608         pending_mem = deps->pending_read_mems;
3609         while (pending)
3610           {
3611             if (read_dependence (XEXP (pending_mem, 0), x))
3612               add_dependence (insn, XEXP (pending, 0), REG_DEP_ANTI);
3613
3614             pending = XEXP (pending, 1);
3615             pending_mem = XEXP (pending_mem, 1);
3616           }
3617
3618         pending = deps->pending_write_insns;
3619         pending_mem = deps->pending_write_mems;
3620         while (pending)
3621           {
3622             if (true_dependence (XEXP (pending_mem, 0), VOIDmode,
3623                                  x, rtx_varies_p))
3624               add_dependence (insn, XEXP (pending, 0), 0);
3625
3626             pending = XEXP (pending, 1);
3627             pending_mem = XEXP (pending_mem, 1);
3628           }
3629
3630         for (u = deps->last_pending_memory_flush; u; u = XEXP (u, 1))
3631           add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3632
3633         /* Always add these dependencies to pending_reads, since
3634            this insn may be followed by a write.  */
3635         add_insn_mem_dependence (deps, &deps->pending_read_insns,
3636                                  &deps->pending_read_mems, insn, x);
3637
3638         /* Take advantage of tail recursion here.  */
3639         sched_analyze_2 (deps, XEXP (x, 0), insn);
3640         return;
3641       }
3642
3643     /* Force pending stores to memory in case a trap handler needs them.  */
3644     case TRAP_IF:
3645       flush_pending_lists (deps, insn, 1);
3646       break;
3647
3648     case ASM_OPERANDS:
3649     case ASM_INPUT:
3650     case UNSPEC_VOLATILE:
3651       {
3652         rtx u;
3653
3654         /* Traditional and volatile asm instructions must be considered to use
3655            and clobber all hard registers, all pseudo-registers and all of
3656            memory.  So must TRAP_IF and UNSPEC_VOLATILE operations.
3657
3658            Consider for instance a volatile asm that changes the fpu rounding
3659            mode.  An insn should not be moved across this even if it only uses
3660            pseudo-regs because it might give an incorrectly rounded result.  */
3661         if (code != ASM_OPERANDS || MEM_VOLATILE_P (x))
3662           {
3663             int max_reg = max_reg_num ();
3664             for (i = 0; i < max_reg; i++)
3665               {
3666                 for (u = deps->reg_last_uses[i]; u; u = XEXP (u, 1))
3667                   add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3668                 free_INSN_LIST_list (&deps->reg_last_uses[i]);
3669
3670                 for (u = deps->reg_last_sets[i]; u; u = XEXP (u, 1))
3671                   add_dependence (insn, XEXP (u, 0), 0);
3672
3673                 for (u = deps->reg_last_clobbers[i]; u; u = XEXP (u, 1))
3674                   add_dependence (insn, XEXP (u, 0), 0);
3675               }
3676             reg_pending_sets_all = 1;
3677
3678             flush_pending_lists (deps, insn, 0);
3679           }
3680
3681         /* For all ASM_OPERANDS, we must traverse the vector of input operands.
3682            We can not just fall through here since then we would be confused
3683            by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
3684            traditional asms unlike their normal usage.  */
3685
3686         if (code == ASM_OPERANDS)
3687           {
3688             for (j = 0; j < ASM_OPERANDS_INPUT_LENGTH (x); j++)
3689               sched_analyze_2 (deps, ASM_OPERANDS_INPUT (x, j), insn);
3690             return;
3691           }
3692         break;
3693       }
3694
3695     case PRE_DEC:
3696     case POST_DEC:
3697     case PRE_INC:
3698     case POST_INC:
3699       /* These both read and modify the result.  We must handle them as writes
3700          to get proper dependencies for following instructions.  We must handle
3701          them as reads to get proper dependencies from this to previous
3702          instructions.  Thus we need to pass them to both sched_analyze_1
3703          and sched_analyze_2.  We must call sched_analyze_2 first in order
3704          to get the proper antecedent for the read.  */
3705       sched_analyze_2 (deps, XEXP (x, 0), insn);
3706       sched_analyze_1 (deps, x, insn);
3707       return;
3708
3709     case POST_MODIFY:
3710     case PRE_MODIFY:
3711       /* op0 = op0 + op1 */
3712       sched_analyze_2 (deps, XEXP (x, 0), insn);
3713       sched_analyze_2 (deps, XEXP (x, 1), insn);
3714       sched_analyze_1 (deps, x, insn);
3715       return;
3716
3717     default:
3718       break;
3719     }
3720
3721   /* Other cases: walk the insn.  */
3722   fmt = GET_RTX_FORMAT (code);
3723   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3724     {
3725       if (fmt[i] == 'e')
3726         sched_analyze_2 (deps, XEXP (x, i), insn);
3727       else if (fmt[i] == 'E')
3728         for (j = 0; j < XVECLEN (x, i); j++)
3729           sched_analyze_2 (deps, XVECEXP (x, i, j), insn);
3730     }
3731 }
3732
3733 /* Analyze an INSN with pattern X to find all dependencies.  */
3734
3735 static void
3736 sched_analyze_insn (deps, x, insn, loop_notes)
3737      struct deps *deps;
3738      rtx x, insn;
3739      rtx loop_notes;
3740 {
3741   register RTX_CODE code = GET_CODE (x);
3742   rtx link;
3743   int maxreg = max_reg_num ();
3744   int i;
3745
3746   if (code == COND_EXEC)
3747     {
3748       sched_analyze_2 (deps, COND_EXEC_TEST (x), insn);
3749
3750       /* ??? Should be recording conditions so we reduce the number of
3751          false dependancies.  */
3752       x = COND_EXEC_CODE (x);
3753       code = GET_CODE (x);
3754     }
3755   if (code == SET || code == CLOBBER)
3756     sched_analyze_1 (deps, x, insn);
3757   else if (code == PARALLEL)
3758     {
3759       register int i;
3760       for (i = XVECLEN (x, 0) - 1; i >= 0; i--)
3761         {
3762           rtx sub = XVECEXP (x, 0, i);
3763           code = GET_CODE (sub);
3764
3765           if (code == COND_EXEC)
3766             {
3767               sched_analyze_2 (deps, COND_EXEC_TEST (sub), insn);
3768               sub = COND_EXEC_CODE (sub);
3769               code = GET_CODE (sub);
3770             }
3771           if (code == SET || code == CLOBBER)
3772             sched_analyze_1 (deps, sub, insn);
3773           else
3774             sched_analyze_2 (deps, sub, insn);
3775         }
3776     }
3777   else
3778     sched_analyze_2 (deps, x, insn);
3779
3780   /* Mark registers CLOBBERED or used by called function.  */
3781   if (GET_CODE (insn) == CALL_INSN)
3782     for (link = CALL_INSN_FUNCTION_USAGE (insn); link; link = XEXP (link, 1))
3783       {
3784         if (GET_CODE (XEXP (link, 0)) == CLOBBER)
3785           sched_analyze_1 (deps, XEXP (link, 0), insn);
3786         else
3787           sched_analyze_2 (deps, XEXP (link, 0), insn);
3788       }
3789
3790   /* If there is a {LOOP,EHREGION}_{BEG,END} note in the middle of a basic
3791      block, then we must be sure that no instructions are scheduled across it.
3792      Otherwise, the reg_n_refs info (which depends on loop_depth) would
3793      become incorrect.  */
3794
3795   if (loop_notes)
3796     {
3797       int max_reg = max_reg_num ();
3798       int schedule_barrier_found = 0;
3799       rtx link;
3800
3801       /* Update loop_notes with any notes from this insn.  Also determine
3802          if any of the notes on the list correspond to instruction scheduling
3803          barriers (loop, eh & setjmp notes, but not range notes.  */
3804       link = loop_notes;
3805       while (XEXP (link, 1))
3806         {
3807           if (INTVAL (XEXP (link, 0)) == NOTE_INSN_LOOP_BEG
3808               || INTVAL (XEXP (link, 0)) == NOTE_INSN_LOOP_END
3809               || INTVAL (XEXP (link, 0)) == NOTE_INSN_EH_REGION_BEG
3810               || INTVAL (XEXP (link, 0)) == NOTE_INSN_EH_REGION_END
3811               || INTVAL (XEXP (link, 0)) == NOTE_INSN_SETJMP)
3812             schedule_barrier_found = 1;
3813
3814           link = XEXP (link, 1);
3815         }
3816       XEXP (link, 1) = REG_NOTES (insn);
3817       REG_NOTES (insn) = loop_notes;
3818
3819       /* Add dependencies if a scheduling barrier was found.  */
3820       if (schedule_barrier_found)
3821         {
3822           for (i = 0; i < max_reg; i++)
3823             {
3824               rtx u;
3825               for (u = deps->reg_last_uses[i]; u; u = XEXP (u, 1))
3826                 add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3827               free_INSN_LIST_list (&deps->reg_last_uses[i]);
3828
3829               for (u = deps->reg_last_sets[i]; u; u = XEXP (u, 1))
3830                 add_dependence (insn, XEXP (u, 0), 0);
3831
3832               for (u = deps->reg_last_clobbers[i]; u; u = XEXP (u, 1))
3833                 add_dependence (insn, XEXP (u, 0), 0);
3834             }
3835           reg_pending_sets_all = 1;
3836
3837           flush_pending_lists (deps, insn, 0);
3838         }
3839
3840     }
3841
3842   /* Accumulate clobbers until the next set so that it will be output dependent
3843      on all of them.  At the next set we can clear the clobber list, since
3844      subsequent sets will be output dependent on it.  */
3845   EXECUTE_IF_SET_IN_REG_SET
3846     (reg_pending_sets, 0, i,
3847      {
3848        free_INSN_LIST_list (&deps->reg_last_sets[i]);
3849        free_INSN_LIST_list (&deps->reg_last_clobbers[i]);
3850        deps->reg_last_sets[i] = alloc_INSN_LIST (insn, NULL_RTX);
3851      });
3852   EXECUTE_IF_SET_IN_REG_SET
3853     (reg_pending_clobbers, 0, i,
3854      {
3855        deps->reg_last_clobbers[i]
3856          = alloc_INSN_LIST (insn, deps->reg_last_clobbers[i]);
3857      });
3858   CLEAR_REG_SET (reg_pending_sets);
3859   CLEAR_REG_SET (reg_pending_clobbers);
3860
3861   if (reg_pending_sets_all)
3862     {
3863       for (i = 0; i < maxreg; i++)
3864         {
3865           free_INSN_LIST_list (&deps->reg_last_sets[i]);
3866           free_INSN_LIST_list (&deps->reg_last_clobbers[i]);
3867           deps->reg_last_sets[i] = alloc_INSN_LIST (insn, NULL_RTX);
3868         }
3869
3870       reg_pending_sets_all = 0;
3871     }
3872
3873   /* If a post-call group is still open, see if it should remain so.
3874      This insn must be a simple move of a hard reg to a pseudo or
3875      vice-versa.
3876
3877      We must avoid moving these insns for correctness on
3878      SMALL_REGISTER_CLASS machines, and for special registers like
3879      PIC_OFFSET_TABLE_REGNUM.  For simplicity, extend this to all
3880      hard regs for all targets.  */
3881
3882   if (deps->in_post_call_group_p)
3883     {
3884       rtx tmp, set = single_set (insn);
3885       int src_regno, dest_regno;
3886
3887       if (set == NULL)
3888         goto end_call_group;
3889
3890       tmp = SET_DEST (set);
3891       if (GET_CODE (tmp) == SUBREG)
3892         tmp = SUBREG_REG (tmp);
3893       if (GET_CODE (tmp) == REG)
3894         dest_regno = REGNO (tmp);
3895       else
3896         goto end_call_group;
3897
3898       tmp = SET_SRC (set);
3899       if (GET_CODE (tmp) == SUBREG)
3900         tmp = SUBREG_REG (tmp);
3901       if (GET_CODE (tmp) == REG)
3902         src_regno = REGNO (tmp);
3903       else
3904         goto end_call_group;
3905
3906       if (src_regno < FIRST_PSEUDO_REGISTER
3907           || dest_regno < FIRST_PSEUDO_REGISTER)
3908         {
3909           set_sched_group_p (insn);
3910           CANT_MOVE (insn) = 1;
3911         }
3912       else
3913         {
3914         end_call_group:
3915           deps->in_post_call_group_p = 0;
3916         }
3917     }
3918 }
3919
3920 /* Analyze every insn between HEAD and TAIL inclusive, creating LOG_LINKS
3921    for every dependency.  */
3922
3923 static void
3924 sched_analyze (deps, head, tail)
3925      struct deps *deps;
3926      rtx head, tail;
3927 {
3928   register rtx insn;
3929   register rtx u;
3930   rtx loop_notes = 0;
3931
3932   for (insn = head;; insn = NEXT_INSN (insn))
3933     {
3934       if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
3935         {
3936           /* Clear out the stale LOG_LINKS from flow.  */
3937           free_INSN_LIST_list (&LOG_LINKS (insn));
3938
3939           /* Clear out stale SCHED_GROUP_P.  */
3940           SCHED_GROUP_P (insn) = 0;
3941
3942           /* Make each JUMP_INSN a scheduling barrier for memory
3943              references.  */
3944           if (GET_CODE (insn) == JUMP_INSN)
3945             deps->last_pending_memory_flush
3946               = alloc_INSN_LIST (insn, deps->last_pending_memory_flush);
3947           sched_analyze_insn (deps, PATTERN (insn), insn, loop_notes);
3948           loop_notes = 0;
3949         }
3950       else if (GET_CODE (insn) == CALL_INSN)
3951         {
3952           rtx x;
3953           register int i;
3954
3955           /* Clear out stale SCHED_GROUP_P.  */
3956           SCHED_GROUP_P (insn) = 0;
3957
3958           CANT_MOVE (insn) = 1;
3959
3960           /* Clear out the stale LOG_LINKS from flow.  */
3961           free_INSN_LIST_list (&LOG_LINKS (insn));
3962
3963           /* Any instruction using a hard register which may get clobbered
3964              by a call needs to be marked as dependent on this call.
3965              This prevents a use of a hard return reg from being moved
3966              past a void call (i.e. it does not explicitly set the hard
3967              return reg).  */
3968
3969           /* If this call is followed by a NOTE_INSN_SETJMP, then assume that
3970              all registers, not just hard registers, may be clobbered by this
3971              call.  */
3972
3973           /* Insn, being a CALL_INSN, magically depends on
3974              `last_function_call' already.  */
3975
3976           if (NEXT_INSN (insn) && GET_CODE (NEXT_INSN (insn)) == NOTE
3977               && NOTE_LINE_NUMBER (NEXT_INSN (insn)) == NOTE_INSN_SETJMP)
3978             {
3979               int max_reg = max_reg_num ();
3980               for (i = 0; i < max_reg; i++)
3981                 {
3982                   for (u = deps->reg_last_uses[i]; u; u = XEXP (u, 1))
3983                     add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
3984                   free_INSN_LIST_list (&deps->reg_last_uses[i]);
3985
3986                   for (u = deps->reg_last_sets[i]; u; u = XEXP (u, 1))
3987                     add_dependence (insn, XEXP (u, 0), 0);
3988
3989                   for (u = deps->reg_last_clobbers[i]; u; u = XEXP (u, 1))
3990                     add_dependence (insn, XEXP (u, 0), 0);
3991                 }
3992               reg_pending_sets_all = 1;
3993
3994               /* Add a pair of REG_SAVE_NOTEs which we will later
3995                  convert back into a NOTE_INSN_SETJMP note.  See
3996                  reemit_notes for why we use a pair of NOTEs.  */
3997               REG_NOTES (insn) = alloc_EXPR_LIST (REG_SAVE_NOTE,
3998                                                   GEN_INT (0),
3999                                                   REG_NOTES (insn));
4000               REG_NOTES (insn) = alloc_EXPR_LIST (REG_SAVE_NOTE,
4001                                                   GEN_INT (NOTE_INSN_SETJMP),
4002                                                   REG_NOTES (insn));
4003             }
4004           else
4005             {
4006               for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4007                 if (call_used_regs[i] || global_regs[i])
4008                   {
4009                     for (u = deps->reg_last_uses[i]; u; u = XEXP (u, 1))
4010                       add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
4011
4012                     for (u = deps->reg_last_sets[i]; u; u = XEXP (u, 1))
4013                       add_dependence (insn, XEXP (u, 0), REG_DEP_ANTI);
4014
4015                     SET_REGNO_REG_SET (reg_pending_clobbers, i);
4016                   }
4017             }
4018
4019           /* For each insn which shouldn't cross a call, add a dependence
4020              between that insn and this call insn.  */
4021           x = LOG_LINKS (deps->sched_before_next_call);
4022           while (x)
4023             {
4024               add_dependence (insn, XEXP (x, 0), REG_DEP_ANTI);
4025               x = XEXP (x, 1);
4026             }
4027           free_INSN_LIST_list (&LOG_LINKS (deps->sched_before_next_call));
4028
4029           sched_analyze_insn (deps, PATTERN (insn), insn, loop_notes);
4030           loop_notes = 0;
4031
4032           /* In the absence of interprocedural alias analysis, we must flush
4033              all pending reads and writes, and start new dependencies starting
4034              from here.  But only flush writes for constant calls (which may
4035              be passed a pointer to something we haven't written yet).  */
4036           flush_pending_lists (deps, insn, CONST_CALL_P (insn));
4037
4038           /* Depend this function call (actually, the user of this
4039              function call) on all hard register clobberage.  */
4040
4041           /* last_function_call is now a list of insns.  */
4042           free_INSN_LIST_list (&deps->last_function_call);
4043           deps->last_function_call = alloc_INSN_LIST (insn, NULL_RTX);
4044
4045           /* Before reload, begin a post-call group, so as to keep the
4046              lifetimes of hard registers correct.  */
4047           if (! reload_completed)
4048             deps->in_post_call_group_p = 1;
4049         }
4050
4051       /* See comments on reemit_notes as to why we do this.
4052          ??? Actually, the reemit_notes just say what is done, not why.  */
4053
4054       else if (GET_CODE (insn) == NOTE
4055                && (NOTE_LINE_NUMBER (insn) == NOTE_INSN_RANGE_BEG
4056                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_RANGE_END))
4057         {
4058           loop_notes = alloc_EXPR_LIST (REG_SAVE_NOTE, NOTE_RANGE_INFO (insn),
4059                                         loop_notes);
4060           loop_notes = alloc_EXPR_LIST (REG_SAVE_NOTE,
4061                                         GEN_INT (NOTE_LINE_NUMBER (insn)),
4062                                         loop_notes);
4063         }
4064       else if (GET_CODE (insn) == NOTE
4065                && (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG
4066                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END
4067                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG
4068                    || NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END
4069                    || (NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP
4070                        && GET_CODE (PREV_INSN (insn)) != CALL_INSN)))
4071         {
4072           rtx rtx_region;
4073
4074           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_BEG
4075               || NOTE_LINE_NUMBER (insn) == NOTE_INSN_EH_REGION_END)
4076             rtx_region = GEN_INT (NOTE_EH_HANDLER (insn));
4077           else
4078             rtx_region = GEN_INT (0);
4079
4080           loop_notes = alloc_EXPR_LIST (REG_SAVE_NOTE,
4081                                         rtx_region,
4082                                         loop_notes);
4083           loop_notes = alloc_EXPR_LIST (REG_SAVE_NOTE,
4084                                         GEN_INT (NOTE_LINE_NUMBER (insn)),
4085                                         loop_notes);
4086           CONST_CALL_P (loop_notes) = CONST_CALL_P (insn);
4087         }
4088
4089       if (insn == tail)
4090         return;
4091     }
4092   abort ();
4093 }
4094 \f
4095 /* Macros and functions for keeping the priority queue sorted, and
4096    dealing with queueing and dequeueing of instructions.  */
4097
4098 #define SCHED_SORT(READY, N_READY)                                   \
4099 do { if ((N_READY) == 2)                                             \
4100        swap_sort (READY, N_READY);                                   \
4101      else if ((N_READY) > 2)                                         \
4102          qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); }  \
4103 while (0)
4104
4105 /* Returns a positive value if x is preferred; returns a negative value if
4106    y is preferred.  Should never return 0, since that will make the sort
4107    unstable.  */
4108
4109 static int
4110 rank_for_schedule (x, y)
4111      const PTR x;
4112      const PTR y;
4113 {
4114   rtx tmp = *(const rtx *) y;
4115   rtx tmp2 = *(const rtx *) x;
4116   rtx link;
4117   int tmp_class, tmp2_class, depend_count1, depend_count2;
4118   int val, priority_val, spec_val, prob_val, weight_val;
4119
4120   /* Prefer insn with higher priority.  */
4121   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
4122   if (priority_val)
4123     return priority_val;
4124
4125   /* Prefer an insn with smaller contribution to registers-pressure.  */
4126   if (!reload_completed &&
4127       (weight_val = INSN_REG_WEIGHT (tmp) - INSN_REG_WEIGHT (tmp2)))
4128     return (weight_val);
4129
4130   /* Some comparison make sense in interblock scheduling only.  */
4131   if (INSN_BB (tmp) != INSN_BB (tmp2))
4132     {
4133       /* Prefer an inblock motion on an interblock motion.  */
4134       if ((INSN_BB (tmp2) == target_bb) && (INSN_BB (tmp) != target_bb))
4135         return 1;
4136       if ((INSN_BB (tmp) == target_bb) && (INSN_BB (tmp2) != target_bb))
4137         return -1;
4138
4139       /* Prefer a useful motion on a speculative one.  */
4140       if ((spec_val = IS_SPECULATIVE_INSN (tmp) - IS_SPECULATIVE_INSN (tmp2)))
4141         return (spec_val);
4142
4143       /* Prefer a more probable (speculative) insn.  */
4144       prob_val = INSN_PROBABILITY (tmp2) - INSN_PROBABILITY (tmp);
4145       if (prob_val)
4146         return (prob_val);
4147     }
4148
4149   /* Compare insns based on their relation to the last-scheduled-insn.  */
4150   if (last_scheduled_insn)
4151     {
4152       /* Classify the instructions into three classes:
4153          1) Data dependent on last schedule insn.
4154          2) Anti/Output dependent on last scheduled insn.
4155          3) Independent of last scheduled insn, or has latency of one.
4156          Choose the insn from the highest numbered class if different.  */
4157       link = find_insn_list (tmp, INSN_DEPEND (last_scheduled_insn));
4158       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp) == 1)
4159         tmp_class = 3;
4160       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
4161         tmp_class = 1;
4162       else
4163         tmp_class = 2;
4164
4165       link = find_insn_list (tmp2, INSN_DEPEND (last_scheduled_insn));
4166       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp2) == 1)
4167         tmp2_class = 3;
4168       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
4169         tmp2_class = 1;
4170       else
4171         tmp2_class = 2;
4172
4173       if ((val = tmp2_class - tmp_class))
4174         return val;
4175     }
4176
4177   /* Prefer the insn which has more later insns that depend on it.
4178      This gives the scheduler more freedom when scheduling later
4179      instructions at the expense of added register pressure.  */
4180   depend_count1 = 0;
4181   for (link = INSN_DEPEND (tmp); link; link = XEXP (link, 1))
4182     depend_count1++;
4183
4184   depend_count2 = 0;
4185   for (link = INSN_DEPEND (tmp2); link; link = XEXP (link, 1))
4186     depend_count2++;
4187
4188   val = depend_count2 - depend_count1;
4189   if (val)
4190     return val;
4191
4192   /* If insns are equally good, sort by INSN_LUID (original insn order),
4193      so that we make the sort stable.  This minimizes instruction movement,
4194      thus minimizing sched's effect on debugging and cross-jumping.  */
4195   return INSN_LUID (tmp) - INSN_LUID (tmp2);
4196 }
4197
4198 /* Resort the array A in which only element at index N may be out of order.  */
4199
4200 HAIFA_INLINE static void
4201 swap_sort (a, n)
4202      rtx *a;
4203      int n;
4204 {
4205   rtx insn = a[n - 1];
4206   int i = n - 2;
4207
4208   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
4209     {
4210       a[i + 1] = a[i];
4211       i -= 1;
4212     }
4213   a[i + 1] = insn;
4214 }
4215
4216 /* Add INSN to the insn queue so that it can be executed at least
4217    N_CYCLES after the currently executing insn.  Preserve insns
4218    chain for debugging purposes.  */
4219
4220 HAIFA_INLINE static void
4221 queue_insn (insn, n_cycles)
4222      rtx insn;
4223      int n_cycles;
4224 {
4225   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
4226   rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
4227   insn_queue[next_q] = link;
4228   q_size += 1;
4229
4230   if (sched_verbose >= 2)
4231     {
4232       fprintf (dump, ";;\t\tReady-->Q: insn %d: ", INSN_UID (insn));
4233
4234       if (INSN_BB (insn) != target_bb)
4235         fprintf (dump, "(b%d) ", BLOCK_NUM (insn));
4236
4237       fprintf (dump, "queued for %d cycles.\n", n_cycles);
4238     }
4239 }
4240
4241 /* Return a pointer to the bottom of the ready list, i.e. the insn
4242    with the lowest priority.  */
4243
4244 HAIFA_INLINE static rtx *
4245 ready_lastpos (ready)
4246      struct ready_list *ready;
4247 {
4248   if (ready->n_ready == 0)
4249     abort ();
4250   return ready->vec + ready->first - ready->n_ready + 1;
4251 }
4252
4253 /* Add an element INSN to the ready list so that it ends up with the lowest
4254    priority.  */
4255
4256 HAIFA_INLINE static void
4257 ready_add (ready, insn)
4258      struct ready_list *ready;
4259      rtx insn;
4260 {
4261   if (ready->first == ready->n_ready)
4262     {
4263       memmove (ready->vec + ready->veclen - ready->n_ready,
4264                ready_lastpos (ready),
4265                ready->n_ready * sizeof (rtx));
4266       ready->first = ready->veclen - 1;
4267     }
4268   ready->vec[ready->first - ready->n_ready] = insn;
4269   ready->n_ready++;
4270 }
4271
4272 /* Remove the element with the highest priority from the ready list and
4273    return it.  */
4274
4275 HAIFA_INLINE static rtx
4276 ready_remove_first (ready)
4277      struct ready_list *ready;
4278 {
4279   rtx t;
4280   if (ready->n_ready == 0)
4281     abort ();
4282   t = ready->vec[ready->first--];
4283   ready->n_ready--;
4284   /* If the queue becomes empty, reset it.  */
4285   if (ready->n_ready == 0)
4286     ready->first = ready->veclen - 1;
4287   return t;
4288 }
4289
4290 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
4291    macro.  */
4292
4293 HAIFA_INLINE static void
4294 ready_sort (ready)
4295      struct ready_list *ready;
4296 {
4297   rtx *first = ready_lastpos (ready);
4298   SCHED_SORT (first, ready->n_ready);
4299 }
4300
4301 /* PREV is an insn that is ready to execute.  Adjust its priority if that
4302    will help shorten or lengthen register lifetimes as appropriate.  Also
4303    provide a hook for the target to tweek itself.  */
4304
4305 HAIFA_INLINE static void
4306 adjust_priority (prev)
4307      rtx prev ATTRIBUTE_UNUSED;
4308 {
4309   /* ??? There used to be code here to try and estimate how an insn
4310      affected register lifetimes, but it did it by looking at REG_DEAD
4311      notes, which we removed in schedule_region.  Nor did it try to
4312      take into account register pressure or anything useful like that.
4313
4314      Revisit when we have a machine model to work with and not before.  */
4315
4316 #ifdef ADJUST_PRIORITY
4317   ADJUST_PRIORITY (prev);
4318 #endif
4319 }
4320
4321 /* Clock at which the previous instruction was issued.  */
4322 static int last_clock_var;
4323
4324 /* INSN is the "currently executing insn".  Launch each insn which was
4325    waiting on INSN.  READY is the ready list which contains the insns
4326    that are ready to fire.  CLOCK is the current cycle.
4327    */
4328
4329 static void
4330 schedule_insn (insn, ready, clock)
4331      rtx insn;
4332      struct ready_list *ready;
4333      int clock;
4334 {
4335   rtx link;
4336   int unit;
4337
4338   unit = insn_unit (insn);
4339
4340   if (sched_verbose >= 2)
4341     {
4342       fprintf (dump, ";;\t\t--> scheduling insn <<<%d>>> on unit ",
4343                INSN_UID (insn));
4344       insn_print_units (insn);
4345       fprintf (dump, "\n");
4346     }
4347
4348   if (sched_verbose && unit == -1)
4349     visualize_no_unit (insn);
4350
4351   if (MAX_BLOCKAGE > 1 || issue_rate > 1 || sched_verbose)
4352     schedule_unit (unit, insn, clock);
4353
4354   if (INSN_DEPEND (insn) == 0)
4355     return;
4356
4357   for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
4358     {
4359       rtx next = XEXP (link, 0);
4360       int cost = insn_cost (insn, link, next);
4361
4362       INSN_TICK (next) = MAX (INSN_TICK (next), clock + cost);
4363
4364       if ((INSN_DEP_COUNT (next) -= 1) == 0)
4365         {
4366           int effective_cost = INSN_TICK (next) - clock;
4367
4368           /* For speculative insns, before inserting to ready/queue,
4369              check live, exception-free, and issue-delay.  */
4370           if (INSN_BB (next) != target_bb
4371               && (!IS_VALID (INSN_BB (next))
4372                   || CANT_MOVE (next)
4373                   || (IS_SPECULATIVE_INSN (next)
4374                       && (insn_issue_delay (next) > 3
4375                           || !check_live (next, INSN_BB (next))
4376                  || !is_exception_free (next, INSN_BB (next), target_bb)))))
4377             continue;
4378
4379           if (sched_verbose >= 2)
4380             {
4381               fprintf (dump, ";;\t\tdependences resolved: insn %d ",
4382                        INSN_UID (next));
4383
4384               if (current_nr_blocks > 1 && INSN_BB (next) != target_bb)
4385                 fprintf (dump, "/b%d ", BLOCK_NUM (next));
4386
4387               if (effective_cost < 1)
4388                 fprintf (dump, "into ready\n");
4389               else
4390                 fprintf (dump, "into queue with cost=%d\n", effective_cost);
4391             }
4392
4393           /* Adjust the priority of NEXT and either put it on the ready
4394              list or queue it.  */
4395           adjust_priority (next);
4396           if (effective_cost < 1)
4397             ready_add (ready, next);
4398           else
4399             queue_insn (next, effective_cost);
4400         }
4401     }
4402
4403   /* Annotate the instruction with issue information -- TImode
4404      indicates that the instruction is expected not to be able
4405      to issue on the same cycle as the previous insn.  A machine
4406      may use this information to decide how the instruction should
4407      be aligned.  */
4408   if (reload_completed && issue_rate > 1)
4409     {
4410       PUT_MODE (insn, clock > last_clock_var ? TImode : VOIDmode);
4411       last_clock_var = clock;
4412     }
4413 }
4414
4415 /* Functions for handling of notes.  */
4416
4417 /* Delete notes beginning with INSN and put them in the chain
4418    of notes ended by NOTE_LIST.
4419    Returns the insn following the notes.  */
4420
4421 static rtx
4422 unlink_other_notes (insn, tail)
4423      rtx insn, tail;
4424 {
4425   rtx prev = PREV_INSN (insn);
4426
4427   while (insn != tail && GET_CODE (insn) == NOTE)
4428     {
4429       rtx next = NEXT_INSN (insn);
4430       /* Delete the note from its current position.  */
4431       if (prev)
4432         NEXT_INSN (prev) = next;
4433       if (next)
4434         PREV_INSN (next) = prev;
4435
4436       /* See sched_analyze to see how these are handled.  */
4437       if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_SETJMP
4438           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG
4439           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_END
4440           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_RANGE_BEG
4441           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_RANGE_END
4442           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_BEG
4443           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_END)
4444         {
4445           /* Insert the note at the end of the notes list.  */
4446           PREV_INSN (insn) = note_list;
4447           if (note_list)
4448             NEXT_INSN (note_list) = insn;
4449           note_list = insn;
4450         }
4451
4452       insn = next;
4453     }
4454   return insn;
4455 }
4456
4457 /* Delete line notes beginning with INSN. Record line-number notes so
4458    they can be reused.  Returns the insn following the notes.  */
4459
4460 static rtx
4461 unlink_line_notes (insn, tail)
4462      rtx insn, tail;
4463 {
4464   rtx prev = PREV_INSN (insn);
4465
4466   while (insn != tail && GET_CODE (insn) == NOTE)
4467     {
4468       rtx next = NEXT_INSN (insn);
4469
4470       if (write_symbols != NO_DEBUG && NOTE_LINE_NUMBER (insn) > 0)
4471         {
4472           /* Delete the note from its current position.  */
4473           if (prev)
4474             NEXT_INSN (prev) = next;
4475           if (next)
4476             PREV_INSN (next) = prev;
4477
4478           /* Record line-number notes so they can be reused.  */
4479           LINE_NOTE (insn) = insn;
4480         }
4481       else
4482         prev = insn;
4483
4484       insn = next;
4485     }
4486   return insn;
4487 }
4488
4489 /* Return the head and tail pointers of BB.  */
4490
4491 HAIFA_INLINE static void
4492 get_block_head_tail (b, headp, tailp)
4493      int b;
4494      rtx *headp;
4495      rtx *tailp;
4496 {
4497
4498   rtx head;
4499   rtx tail;
4500
4501   /* HEAD and TAIL delimit the basic block being scheduled.  */
4502   head = BLOCK_HEAD (b);
4503   tail = BLOCK_END (b);
4504
4505   /* Don't include any notes or labels at the beginning of the
4506      basic block, or notes at the ends of basic blocks.  */
4507   while (head != tail)
4508     {
4509       if (GET_CODE (head) == NOTE)
4510         head = NEXT_INSN (head);
4511       else if (GET_CODE (tail) == NOTE)
4512         tail = PREV_INSN (tail);
4513       else if (GET_CODE (head) == CODE_LABEL)
4514         head = NEXT_INSN (head);
4515       else
4516         break;
4517     }
4518
4519   *headp = head;
4520   *tailp = tail;
4521 }
4522
4523 HAIFA_INLINE static void
4524 get_bb_head_tail (bb, headp, tailp)
4525      int bb;
4526      rtx *headp;
4527      rtx *tailp;
4528 {
4529   get_block_head_tail (BB_TO_BLOCK (bb), headp, tailp);
4530 }
4531
4532 /* Delete line notes from bb. Save them so they can be later restored
4533    (in restore_line_notes ()).  */
4534
4535 static void
4536 rm_line_notes (bb)
4537      int bb;
4538 {
4539   rtx next_tail;
4540   rtx tail;
4541   rtx head;
4542   rtx insn;
4543
4544   get_bb_head_tail (bb, &head, &tail);
4545
4546   if (head == tail && (! INSN_P (head)))
4547     return;
4548
4549   next_tail = NEXT_INSN (tail);
4550   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
4551     {
4552       rtx prev;
4553
4554       /* Farm out notes, and maybe save them in NOTE_LIST.
4555          This is needed to keep the debugger from
4556          getting completely deranged.  */
4557       if (GET_CODE (insn) == NOTE)
4558         {
4559           prev = insn;
4560           insn = unlink_line_notes (insn, next_tail);
4561
4562           if (prev == tail)
4563             abort ();
4564           if (prev == head)
4565             abort ();
4566           if (insn == next_tail)
4567             abort ();
4568         }
4569     }
4570 }
4571
4572 /* Save line number notes for each insn in bb.  */
4573
4574 static void
4575 save_line_notes (bb)
4576      int bb;
4577 {
4578   rtx head, tail;
4579   rtx next_tail;
4580
4581   /* We must use the true line number for the first insn in the block
4582      that was computed and saved at the start of this pass.  We can't
4583      use the current line number, because scheduling of the previous
4584      block may have changed the current line number.  */
4585
4586   rtx line = line_note_head[BB_TO_BLOCK (bb)];
4587   rtx insn;
4588
4589   get_bb_head_tail (bb, &head, &tail);
4590   next_tail = NEXT_INSN (tail);
4591
4592   for (insn = BLOCK_HEAD (BB_TO_BLOCK (bb));
4593        insn != next_tail;
4594        insn = NEXT_INSN (insn))
4595     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
4596       line = insn;
4597     else
4598       LINE_NOTE (insn) = line;
4599 }
4600
4601 /* After bb was scheduled, insert line notes into the insns list.  */
4602
4603 static void
4604 restore_line_notes (bb)
4605      int bb;
4606 {
4607   rtx line, note, prev, new;
4608   int added_notes = 0;
4609   int b;
4610   rtx head, next_tail, insn;
4611
4612   b = BB_TO_BLOCK (bb);
4613
4614   head = BLOCK_HEAD (b);
4615   next_tail = NEXT_INSN (BLOCK_END (b));
4616
4617   /* Determine the current line-number.  We want to know the current
4618      line number of the first insn of the block here, in case it is
4619      different from the true line number that was saved earlier.  If
4620      different, then we need a line number note before the first insn
4621      of this block.  If it happens to be the same, then we don't want to
4622      emit another line number note here.  */
4623   for (line = head; line; line = PREV_INSN (line))
4624     if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
4625       break;
4626
4627   /* Walk the insns keeping track of the current line-number and inserting
4628      the line-number notes as needed.  */
4629   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
4630     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
4631       line = insn;
4632   /* This used to emit line number notes before every non-deleted note.
4633      However, this confuses a debugger, because line notes not separated
4634      by real instructions all end up at the same address.  I can find no
4635      use for line number notes before other notes, so none are emitted.  */
4636     else if (GET_CODE (insn) != NOTE
4637              && (note = LINE_NOTE (insn)) != 0
4638              && note != line
4639              && (line == 0
4640                  || NOTE_LINE_NUMBER (note) != NOTE_LINE_NUMBER (line)
4641                  || NOTE_SOURCE_FILE (note) != NOTE_SOURCE_FILE (line)))
4642       {
4643         line = note;
4644         prev = PREV_INSN (insn);
4645         if (LINE_NOTE (note))
4646           {
4647             /* Re-use the original line-number note.  */
4648             LINE_NOTE (note) = 0;
4649             PREV_INSN (note) = prev;
4650             NEXT_INSN (prev) = note;
4651             PREV_INSN (insn) = note;
4652             NEXT_INSN (note) = insn;
4653           }
4654         else
4655           {
4656             added_notes++;
4657             new = emit_note_after (NOTE_LINE_NUMBER (note), prev);
4658             NOTE_SOURCE_FILE (new) = NOTE_SOURCE_FILE (note);
4659             RTX_INTEGRATED_P (new) = RTX_INTEGRATED_P (note);
4660           }
4661       }
4662   if (sched_verbose && added_notes)
4663     fprintf (dump, ";; added %d line-number notes\n", added_notes);
4664 }
4665
4666 /* After scheduling the function, delete redundant line notes from the
4667    insns list.  */
4668
4669 static void
4670 rm_redundant_line_notes ()
4671 {
4672   rtx line = 0;
4673   rtx insn = get_insns ();
4674   int active_insn = 0;
4675   int notes = 0;
4676
4677   /* Walk the insns deleting redundant line-number notes.  Many of these
4678      are already present.  The remainder tend to occur at basic
4679      block boundaries.  */
4680   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
4681     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
4682       {
4683         /* If there are no active insns following, INSN is redundant.  */
4684         if (active_insn == 0)
4685           {
4686             notes++;
4687             NOTE_SOURCE_FILE (insn) = 0;
4688             NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
4689           }
4690         /* If the line number is unchanged, LINE is redundant.  */
4691         else if (line
4692                  && NOTE_LINE_NUMBER (line) == NOTE_LINE_NUMBER (insn)
4693                  && NOTE_SOURCE_FILE (line) == NOTE_SOURCE_FILE (insn))
4694           {
4695             notes++;
4696             NOTE_SOURCE_FILE (line) = 0;
4697             NOTE_LINE_NUMBER (line) = NOTE_INSN_DELETED;
4698             line = insn;
4699           }
4700         else
4701           line = insn;
4702         active_insn = 0;
4703       }
4704     else if (!((GET_CODE (insn) == NOTE
4705                 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED)
4706                || (GET_CODE (insn) == INSN
4707                    && (GET_CODE (PATTERN (insn)) == USE
4708                        || GET_CODE (PATTERN (insn)) == CLOBBER))))
4709       active_insn++;
4710
4711   if (sched_verbose && notes)
4712     fprintf (dump, ";; deleted %d line-number notes\n", notes);
4713 }
4714
4715 /* Delete notes between head and tail and put them in the chain
4716    of notes ended by NOTE_LIST.  */
4717
4718 static void
4719 rm_other_notes (head, tail)
4720      rtx head;
4721      rtx tail;
4722 {
4723   rtx next_tail;
4724   rtx insn;
4725
4726   if (head == tail && (! INSN_P (head)))
4727     return;
4728
4729   next_tail = NEXT_INSN (tail);
4730   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
4731     {
4732       rtx prev;
4733
4734       /* Farm out notes, and maybe save them in NOTE_LIST.
4735          This is needed to keep the debugger from
4736          getting completely deranged.  */
4737       if (GET_CODE (insn) == NOTE)
4738         {
4739           prev = insn;
4740
4741           insn = unlink_other_notes (insn, next_tail);
4742
4743           if (prev == tail)
4744             abort ();
4745           if (prev == head)
4746             abort ();
4747           if (insn == next_tail)
4748             abort ();
4749         }
4750     }
4751 }
4752
4753 /* Functions for computation of registers live/usage info.  */
4754
4755 /* Calculate INSN_REG_WEIGHT for all insns of a block.  */
4756
4757 static void
4758 find_insn_reg_weight (b)
4759      int b;
4760 {
4761   rtx insn, next_tail, head, tail;
4762
4763   get_block_head_tail (b, &head, &tail);
4764   next_tail = NEXT_INSN (tail);
4765
4766   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
4767     {
4768       int reg_weight = 0;
4769       rtx x;
4770
4771       /* Handle register life information.  */
4772       if (! INSN_P (insn))
4773         continue;
4774
4775       /* Increment weight for each register born here.  */
4776       x = PATTERN (insn);
4777       if ((GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
4778           && register_operand (SET_DEST (x), VOIDmode))
4779         reg_weight++;
4780       else if (GET_CODE (x) == PARALLEL)
4781         {
4782           int j;
4783           for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
4784             {
4785               x = XVECEXP (PATTERN (insn), 0, j);
4786               if ((GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
4787                   && register_operand (SET_DEST (x), VOIDmode))
4788                 reg_weight++;
4789             }
4790         }
4791
4792       /* Decrement weight for each register that dies here.  */
4793       for (x = REG_NOTES (insn); x; x = XEXP (x, 1))
4794         {
4795           if (REG_NOTE_KIND (x) == REG_DEAD
4796               || REG_NOTE_KIND (x) == REG_UNUSED)
4797             reg_weight--;
4798         }
4799
4800       INSN_REG_WEIGHT (insn) = reg_weight;
4801     }
4802 }
4803
4804 /* Scheduling clock, modified in schedule_block() and queue_to_ready ().  */
4805 static int clock_var;
4806
4807 /* Move insns that became ready to fire from queue to ready list.  */
4808
4809 static void
4810 queue_to_ready (ready)
4811      struct ready_list *ready;
4812 {
4813   rtx insn;
4814   rtx link;
4815
4816   q_ptr = NEXT_Q (q_ptr);
4817
4818   /* Add all pending insns that can be scheduled without stalls to the
4819      ready list.  */
4820   for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
4821     {
4822       insn = XEXP (link, 0);
4823       q_size -= 1;
4824
4825       if (sched_verbose >= 2)
4826         fprintf (dump, ";;\t\tQ-->Ready: insn %d: ", INSN_UID (insn));
4827
4828       if (sched_verbose >= 2 && INSN_BB (insn) != target_bb)
4829         fprintf (dump, "(b%d) ", BLOCK_NUM (insn));
4830
4831       ready_add (ready, insn);
4832       if (sched_verbose >= 2)
4833         fprintf (dump, "moving to ready without stalls\n");
4834     }
4835   insn_queue[q_ptr] = 0;
4836
4837   /* If there are no ready insns, stall until one is ready and add all
4838      of the pending insns at that point to the ready list.  */
4839   if (ready->n_ready == 0)
4840     {
4841       register int stalls;
4842
4843       for (stalls = 1; stalls < INSN_QUEUE_SIZE; stalls++)
4844         {
4845           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
4846             {
4847               for (; link; link = XEXP (link, 1))
4848                 {
4849                   insn = XEXP (link, 0);
4850                   q_size -= 1;
4851
4852                   if (sched_verbose >= 2)
4853                     fprintf (dump, ";;\t\tQ-->Ready: insn %d: ",
4854                              INSN_UID (insn));
4855
4856                   if (sched_verbose >= 2 && INSN_BB (insn) != target_bb)
4857                     fprintf (dump, "(b%d) ", BLOCK_NUM (insn));
4858
4859                   ready_add (ready, insn);
4860                   if (sched_verbose >= 2)
4861                     fprintf (dump, "moving to ready with %d stalls\n", stalls);
4862                 }
4863               insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = 0;
4864
4865               if (ready->n_ready)
4866                 break;
4867             }
4868         }
4869
4870       if (sched_verbose && stalls)
4871         visualize_stall_cycles (BB_TO_BLOCK (target_bb), stalls);
4872       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
4873       clock_var += stalls;
4874     }
4875 }
4876
4877 /* Print the ready list for debugging purposes.  Callable from debugger.  */
4878
4879 static void
4880 debug_ready_list (ready)
4881      struct ready_list *ready;
4882 {
4883   rtx *p;
4884   int i;
4885
4886   if (ready->n_ready == 0)
4887     return;
4888
4889   p = ready_lastpos (ready);
4890   for (i = 0; i < ready->n_ready; i++)
4891     {
4892       fprintf (dump, "  %d", INSN_UID (p[i]));
4893       if (current_nr_blocks > 1 && INSN_BB (p[i]) != target_bb)
4894         fprintf (dump, "/b%d", BLOCK_NUM (p[i]));
4895     }
4896   fprintf (dump, "\n");
4897 }
4898
4899 /* Print names of units on which insn can/should execute, for debugging.  */
4900
4901 static void
4902 insn_print_units (insn)
4903      rtx insn;
4904 {
4905   int i;
4906   int unit = insn_unit (insn);
4907
4908   if (unit == -1)
4909     fprintf (dump, "none");
4910   else if (unit >= 0)
4911     fprintf (dump, "%s", function_units[unit].name);
4912   else
4913     {
4914       fprintf (dump, "[");
4915       for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
4916         if (unit & 1)
4917           {
4918             fprintf (dump, "%s", function_units[i].name);
4919             if (unit != 1)
4920               fprintf (dump, " ");
4921           }
4922       fprintf (dump, "]");
4923     }
4924 }
4925
4926 /* MAX_VISUAL_LINES is the maximum number of lines in visualization table
4927    of a basic block.  If more lines are needed, table is splitted to two.
4928    n_visual_lines is the number of lines printed so far for a block.
4929    visual_tbl contains the block visualization info.
4930    vis_no_unit holds insns in a cycle that are not mapped to any unit.  */
4931 #define MAX_VISUAL_LINES 100
4932 #define INSN_LEN 30
4933 int n_visual_lines;
4934 char *visual_tbl;
4935 int n_vis_no_unit;
4936 rtx vis_no_unit[10];
4937
4938 /* Finds units that are in use in this fuction.  Required only
4939    for visualization.  */
4940
4941 static void
4942 init_target_units ()
4943 {
4944   rtx insn;
4945   int unit;
4946
4947   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
4948     {
4949       if (! INSN_P (insn))
4950         continue;
4951
4952       unit = insn_unit (insn);
4953
4954       if (unit < 0)
4955         target_units |= ~unit;
4956       else
4957         target_units |= (1 << unit);
4958     }
4959 }
4960
4961 /* Return the length of the visualization table.  */
4962
4963 static int
4964 get_visual_tbl_length ()
4965 {
4966   int unit, i;
4967   int n, n1;
4968   char *s;
4969
4970   /* Compute length of one field in line.  */
4971   s = (char *) alloca (INSN_LEN + 6);
4972   sprintf (s, "  %33s", "uname");
4973   n1 = strlen (s);
4974
4975   /* Compute length of one line.  */
4976   n = strlen (";; ");
4977   n += n1;
4978   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
4979     if (function_units[unit].bitmask & target_units)
4980       for (i = 0; i < function_units[unit].multiplicity; i++)
4981         n += n1;
4982   n += n1;
4983   n += strlen ("\n") + 2;
4984
4985   /* Compute length of visualization string.  */
4986   return (MAX_VISUAL_LINES * n);
4987 }
4988
4989 /* Init block visualization debugging info.  */
4990
4991 static void
4992 init_block_visualization ()
4993 {
4994   strcpy (visual_tbl, "");
4995   n_visual_lines = 0;
4996   n_vis_no_unit = 0;
4997 }
4998
4999 #define BUF_LEN 2048
5000
5001 static char *
5002 safe_concat (buf, cur, str)
5003      char *buf;
5004      char *cur;
5005      const char *str;
5006 {
5007   char *end = buf + BUF_LEN - 2;        /* Leave room for null.  */
5008   int c;
5009
5010   if (cur > end)
5011     {
5012       *end = '\0';
5013       return end;
5014     }
5015
5016   while (cur < end && (c = *str++) != '\0')
5017     *cur++ = c;
5018
5019   *cur = '\0';
5020   return cur;
5021 }
5022
5023 /* This recognizes rtx, I classified as expressions.  These are always
5024    represent some action on values or results of other expression, that
5025    may be stored in objects representing values.  */
5026
5027 static void
5028 print_exp (buf, x, verbose)
5029      char *buf;
5030      rtx x;
5031      int verbose;
5032 {
5033   char tmp[BUF_LEN];
5034   const char *st[4];
5035   char *cur = buf;
5036   const char *fun = (char *) 0;
5037   const char *sep;
5038   rtx op[4];
5039   int i;
5040
5041   for (i = 0; i < 4; i++)
5042     {
5043       st[i] = (char *) 0;
5044       op[i] = NULL_RTX;
5045     }
5046
5047   switch (GET_CODE (x))
5048     {
5049     case PLUS:
5050       op[0] = XEXP (x, 0);
5051       if (GET_CODE (XEXP (x, 1)) == CONST_INT
5052           && INTVAL (XEXP (x, 1)) < 0)
5053         {
5054           st[1] = "-";
5055           op[1] = GEN_INT (-INTVAL (XEXP (x, 1)));
5056         }
5057       else
5058         {
5059           st[1] = "+";
5060           op[1] = XEXP (x, 1);
5061         }
5062       break;
5063     case LO_SUM:
5064       op[0] = XEXP (x, 0);
5065       st[1] = "+low(";
5066       op[1] = XEXP (x, 1);
5067       st[2] = ")";
5068       break;
5069     case MINUS:
5070       op[0] = XEXP (x, 0);
5071       st[1] = "-";
5072       op[1] = XEXP (x, 1);
5073       break;
5074     case COMPARE:
5075       fun = "cmp";
5076       op[0] = XEXP (x, 0);
5077       op[1] = XEXP (x, 1);
5078       break;
5079     case NEG:
5080       st[0] = "-";
5081       op[0] = XEXP (x, 0);
5082       break;
5083     case MULT:
5084       op[0] = XEXP (x, 0);
5085       st[1] = "*";
5086       op[1] = XEXP (x, 1);
5087       break;
5088     case DIV:
5089       op[0] = XEXP (x, 0);
5090       st[1] = "/";
5091       op[1] = XEXP (x, 1);
5092       break;
5093     case UDIV:
5094       fun = "udiv";
5095       op[0] = XEXP (x, 0);
5096       op[1] = XEXP (x, 1);
5097       break;
5098     case MOD:
5099       op[0] = XEXP (x, 0);
5100       st[1] = "%";
5101       op[1] = XEXP (x, 1);
5102       break;
5103     case UMOD:
5104       fun = "umod";
5105       op[0] = XEXP (x, 0);
5106       op[1] = XEXP (x, 1);
5107       break;
5108     case SMIN:
5109       fun = "smin";
5110       op[0] = XEXP (x, 0);
5111       op[1] = XEXP (x, 1);
5112       break;
5113     case SMAX:
5114       fun = "smax";
5115       op[0] = XEXP (x, 0);
5116       op[1] = XEXP (x, 1);
5117       break;
5118     case UMIN:
5119       fun = "umin";
5120       op[0] = XEXP (x, 0);
5121       op[1] = XEXP (x, 1);
5122       break;
5123     case UMAX:
5124       fun = "umax";
5125       op[0] = XEXP (x, 0);
5126       op[1] = XEXP (x, 1);
5127       break;
5128     case NOT:
5129       st[0] = "!";
5130       op[0] = XEXP (x, 0);
5131       break;
5132     case AND:
5133       op[0] = XEXP (x, 0);
5134       st[1] = "&";
5135       op[1] = XEXP (x, 1);
5136       break;
5137     case IOR:
5138       op[0] = XEXP (x, 0);
5139       st[1] = "|";
5140       op[1] = XEXP (x, 1);
5141       break;
5142     case XOR:
5143       op[0] = XEXP (x, 0);
5144       st[1] = "^";
5145       op[1] = XEXP (x, 1);
5146       break;
5147     case ASHIFT:
5148       op[0] = XEXP (x, 0);
5149       st[1] = "<<";
5150       op[1] = XEXP (x, 1);
5151       break;
5152     case LSHIFTRT:
5153       op[0] = XEXP (x, 0);
5154       st[1] = " 0>>";
5155       op[1] = XEXP (x, 1);
5156       break;
5157     case ASHIFTRT:
5158       op[0] = XEXP (x, 0);
5159       st[1] = ">>";
5160       op[1] = XEXP (x, 1);
5161       break;
5162     case ROTATE:
5163       op[0] = XEXP (x, 0);
5164       st[1] = "<-<";
5165       op[1] = XEXP (x, 1);
5166       break;
5167     case ROTATERT:
5168       op[0] = XEXP (x, 0);
5169       st[1] = ">->";
5170       op[1] = XEXP (x, 1);
5171       break;
5172     case ABS:
5173       fun = "abs";
5174       op[0] = XEXP (x, 0);
5175       break;
5176     case SQRT:
5177       fun = "sqrt";
5178       op[0] = XEXP (x, 0);
5179       break;
5180     case FFS:
5181       fun = "ffs";
5182       op[0] = XEXP (x, 0);
5183       break;
5184     case EQ:
5185       op[0] = XEXP (x, 0);
5186       st[1] = "==";
5187       op[1] = XEXP (x, 1);
5188       break;
5189     case NE:
5190       op[0] = XEXP (x, 0);
5191       st[1] = "!=";
5192       op[1] = XEXP (x, 1);
5193       break;
5194     case GT:
5195       op[0] = XEXP (x, 0);
5196       st[1] = ">";
5197       op[1] = XEXP (x, 1);
5198       break;
5199     case GTU:
5200       fun = "gtu";
5201       op[0] = XEXP (x, 0);
5202       op[1] = XEXP (x, 1);
5203       break;
5204     case LT:
5205       op[0] = XEXP (x, 0);
5206       st[1] = "<";
5207       op[1] = XEXP (x, 1);
5208       break;
5209     case LTU:
5210       fun = "ltu";
5211       op[0] = XEXP (x, 0);
5212       op[1] = XEXP (x, 1);
5213       break;
5214     case GE:
5215       op[0] = XEXP (x, 0);
5216       st[1] = ">=";
5217       op[1] = XEXP (x, 1);
5218       break;
5219     case GEU:
5220       fun = "geu";
5221       op[0] = XEXP (x, 0);
5222       op[1] = XEXP (x, 1);
5223       break;
5224     case LE:
5225       op[0] = XEXP (x, 0);
5226       st[1] = "<=";
5227       op[1] = XEXP (x, 1);
5228       break;
5229     case LEU:
5230       fun = "leu";
5231       op[0] = XEXP (x, 0);
5232       op[1] = XEXP (x, 1);
5233       break;
5234     case SIGN_EXTRACT:
5235       fun = (verbose) ? "sign_extract" : "sxt";
5236       op[0] = XEXP (x, 0);
5237       op[1] = XEXP (x, 1);
5238       op[2] = XEXP (x, 2);
5239       break;
5240     case ZERO_EXTRACT:
5241       fun = (verbose) ? "zero_extract" : "zxt";
5242       op[0] = XEXP (x, 0);
5243       op[1] = XEXP (x, 1);
5244       op[2] = XEXP (x, 2);
5245       break;
5246     case SIGN_EXTEND:
5247       fun = (verbose) ? "sign_extend" : "sxn";
5248       op[0] = XEXP (x, 0);
5249       break;
5250     case ZERO_EXTEND:
5251       fun = (verbose) ? "zero_extend" : "zxn";
5252       op[0] = XEXP (x, 0);
5253       break;
5254     case FLOAT_EXTEND:
5255       fun = (verbose) ? "float_extend" : "fxn";
5256       op[0] = XEXP (x, 0);
5257       break;
5258     case TRUNCATE:
5259       fun = (verbose) ? "trunc" : "trn";
5260       op[0] = XEXP (x, 0);
5261       break;
5262     case FLOAT_TRUNCATE:
5263       fun = (verbose) ? "float_trunc" : "ftr";
5264       op[0] = XEXP (x, 0);
5265       break;
5266     case FLOAT:
5267       fun = (verbose) ? "float" : "flt";
5268       op[0] = XEXP (x, 0);
5269       break;
5270     case UNSIGNED_FLOAT:
5271       fun = (verbose) ? "uns_float" : "ufl";
5272       op[0] = XEXP (x, 0);
5273       break;
5274     case FIX:
5275       fun = "fix";
5276       op[0] = XEXP (x, 0);
5277       break;
5278     case UNSIGNED_FIX:
5279       fun = (verbose) ? "uns_fix" : "ufx";
5280       op[0] = XEXP (x, 0);
5281       break;
5282     case PRE_DEC:
5283       st[0] = "--";
5284       op[0] = XEXP (x, 0);
5285       break;
5286     case PRE_INC:
5287       st[0] = "++";
5288       op[0] = XEXP (x, 0);
5289       break;
5290     case POST_DEC:
5291       op[0] = XEXP (x, 0);
5292       st[1] = "--";
5293       break;
5294     case POST_INC:
5295       op[0] = XEXP (x, 0);
5296       st[1] = "++";
5297       break;
5298     case CALL:
5299       st[0] = "call ";
5300       op[0] = XEXP (x, 0);
5301       if (verbose)
5302         {
5303           st[1] = " argc:";
5304           op[1] = XEXP (x, 1);
5305         }
5306       break;
5307     case IF_THEN_ELSE:
5308       st[0] = "{(";
5309       op[0] = XEXP (x, 0);
5310       st[1] = ")?";
5311       op[1] = XEXP (x, 1);
5312       st[2] = ":";
5313       op[2] = XEXP (x, 2);
5314       st[3] = "}";
5315       break;
5316     case TRAP_IF:
5317       fun = "trap_if";
5318       op[0] = TRAP_CONDITION (x);
5319       break;
5320     case UNSPEC:
5321     case UNSPEC_VOLATILE:
5322       {
5323         cur = safe_concat (buf, cur, "unspec");
5324         if (GET_CODE (x) == UNSPEC_VOLATILE)
5325           cur = safe_concat (buf, cur, "/v");
5326         cur = safe_concat (buf, cur, "[");
5327         sep = "";
5328         for (i = 0; i < XVECLEN (x, 0); i++)
5329           {
5330             print_pattern (tmp, XVECEXP (x, 0, i), verbose);
5331             cur = safe_concat (buf, cur, sep);
5332             cur = safe_concat (buf, cur, tmp);
5333             sep = ",";
5334           }
5335         cur = safe_concat (buf, cur, "] ");
5336         sprintf (tmp, "%d", XINT (x, 1));
5337         cur = safe_concat (buf, cur, tmp);
5338       }
5339       break;
5340     default:
5341       /* If (verbose) debug_rtx (x);  */
5342       st[0] = GET_RTX_NAME (GET_CODE (x));
5343       break;
5344     }
5345
5346   /* Print this as a function?  */
5347   if (fun)
5348     {
5349       cur = safe_concat (buf, cur, fun);
5350       cur = safe_concat (buf, cur, "(");
5351     }
5352
5353   for (i = 0; i < 4; i++)
5354     {
5355       if (st[i])
5356         cur = safe_concat (buf, cur, st[i]);
5357
5358       if (op[i])
5359         {
5360           if (fun && i != 0)
5361             cur = safe_concat (buf, cur, ",");
5362
5363           print_value (tmp, op[i], verbose);
5364           cur = safe_concat (buf, cur, tmp);
5365         }
5366     }
5367
5368   if (fun)
5369     cur = safe_concat (buf, cur, ")");
5370 }               /* print_exp */
5371
5372 /* Prints rtxes, I customly classified as values.  They're constants,
5373    registers, labels, symbols and memory accesses.  */
5374
5375 static void
5376 print_value (buf, x, verbose)
5377      char *buf;
5378      rtx x;
5379      int verbose;
5380 {
5381   char t[BUF_LEN];
5382   char *cur = buf;
5383
5384   switch (GET_CODE (x))
5385     {
5386     case CONST_INT:
5387       sprintf (t, HOST_WIDE_INT_PRINT_HEX, INTVAL (x));
5388       cur = safe_concat (buf, cur, t);
5389       break;
5390     case CONST_DOUBLE:
5391       sprintf (t, "<0x%lx,0x%lx>", (long) XWINT (x, 2), (long) XWINT (x, 3));
5392       cur = safe_concat (buf, cur, t);
5393       break;
5394     case CONST_STRING:
5395       cur = safe_concat (buf, cur, "\"");
5396       cur = safe_concat (buf, cur, XSTR (x, 0));
5397       cur = safe_concat (buf, cur, "\"");
5398       break;
5399     case SYMBOL_REF:
5400       cur = safe_concat (buf, cur, "`");
5401       cur = safe_concat (buf, cur, XSTR (x, 0));
5402       cur = safe_concat (buf, cur, "'");
5403       break;
5404     case LABEL_REF:
5405       sprintf (t, "L%d", INSN_UID (XEXP (x, 0)));
5406       cur = safe_concat (buf, cur, t);
5407       break;
5408     case CONST:
5409       print_value (t, XEXP (x, 0), verbose);
5410       cur = safe_concat (buf, cur, "const(");
5411       cur = safe_concat (buf, cur, t);
5412       cur = safe_concat (buf, cur, ")");
5413       break;
5414     case HIGH:
5415       print_value (t, XEXP (x, 0), verbose);
5416       cur = safe_concat (buf, cur, "high(");
5417       cur = safe_concat (buf, cur, t);
5418       cur = safe_concat (buf, cur, ")");
5419       break;
5420     case REG:
5421       if (REGNO (x) < FIRST_PSEUDO_REGISTER)
5422         {
5423           int c = reg_names[REGNO (x)][0];
5424           if (c >= '0' && c <= '9')
5425             cur = safe_concat (buf, cur, "%");
5426
5427           cur = safe_concat (buf, cur, reg_names[REGNO (x)]);
5428         }
5429       else
5430         {
5431           sprintf (t, "r%d", REGNO (x));
5432           cur = safe_concat (buf, cur, t);
5433         }
5434       break;
5435     case SUBREG:
5436       print_value (t, SUBREG_REG (x), verbose);
5437       cur = safe_concat (buf, cur, t);
5438       sprintf (t, "#%d", SUBREG_WORD (x));
5439       cur = safe_concat (buf, cur, t);
5440       break;
5441     case SCRATCH:
5442       cur = safe_concat (buf, cur, "scratch");
5443       break;
5444     case CC0:
5445       cur = safe_concat (buf, cur, "cc0");
5446       break;
5447     case PC:
5448       cur = safe_concat (buf, cur, "pc");
5449       break;
5450     case MEM:
5451       print_value (t, XEXP (x, 0), verbose);
5452       cur = safe_concat (buf, cur, "[");
5453       cur = safe_concat (buf, cur, t);
5454       cur = safe_concat (buf, cur, "]");
5455       break;
5456     default:
5457       print_exp (t, x, verbose);
5458       cur = safe_concat (buf, cur, t);
5459       break;
5460     }
5461 }                               /* print_value */
5462
5463 /* The next step in insn detalization, its pattern recognition.  */
5464
5465 static void
5466 print_pattern (buf, x, verbose)
5467      char *buf;
5468      rtx x;
5469      int verbose;
5470 {
5471   char t1[BUF_LEN], t2[BUF_LEN], t3[BUF_LEN];
5472
5473   switch (GET_CODE (x))
5474     {
5475     case SET:
5476       print_value (t1, SET_DEST (x), verbose);
5477       print_value (t2, SET_SRC (x), verbose);
5478       sprintf (buf, "%s=%s", t1, t2);
5479       break;
5480     case RETURN:
5481       sprintf (buf, "return");
5482       break;
5483     case CALL:
5484       print_exp (buf, x, verbose);
5485       break;
5486     case CLOBBER:
5487       print_value (t1, XEXP (x, 0), verbose);
5488       sprintf (buf, "clobber %s", t1);
5489       break;
5490     case USE:
5491       print_value (t1, XEXP (x, 0), verbose);
5492       sprintf (buf, "use %s", t1);
5493       break;
5494     case COND_EXEC:
5495       print_value (t1, COND_EXEC_CODE (x), verbose);
5496       print_value (t2, COND_EXEC_TEST (x), verbose);
5497       sprintf (buf, "cond_exec %s %s", t1, t2);
5498       break;
5499     case PARALLEL:
5500       {
5501         int i;
5502
5503         sprintf (t1, "{");
5504         for (i = 0; i < XVECLEN (x, 0); i++)
5505           {
5506             print_pattern (t2, XVECEXP (x, 0, i), verbose);
5507             sprintf (t3, "%s%s;", t1, t2);
5508             strcpy (t1, t3);
5509           }
5510         sprintf (buf, "%s}", t1);
5511       }
5512       break;
5513     case SEQUENCE:
5514       {
5515         int i;
5516
5517         sprintf (t1, "%%{");
5518         for (i = 0; i < XVECLEN (x, 0); i++)
5519           {
5520             print_insn (t2, XVECEXP (x, 0, i), verbose);
5521             sprintf (t3, "%s%s;", t1, t2);
5522             strcpy (t1, t3);
5523           }
5524         sprintf (buf, "%s%%}", t1);
5525       }
5526       break;
5527     case ASM_INPUT:
5528       sprintf (buf, "asm {%s}", XSTR (x, 0));
5529       break;
5530     case ADDR_VEC:
5531       break;
5532     case ADDR_DIFF_VEC:
5533       print_value (buf, XEXP (x, 0), verbose);
5534       break;
5535     case TRAP_IF:
5536       print_value (t1, TRAP_CONDITION (x), verbose);
5537       sprintf (buf, "trap_if %s", t1);
5538       break;
5539     case UNSPEC:
5540       {
5541         int i;
5542
5543         sprintf (t1, "unspec{");
5544         for (i = 0; i < XVECLEN (x, 0); i++)
5545           {
5546             print_pattern (t2, XVECEXP (x, 0, i), verbose);
5547             sprintf (t3, "%s%s;", t1, t2);
5548             strcpy (t1, t3);
5549           }
5550         sprintf (buf, "%s}", t1);
5551       }
5552       break;
5553     case UNSPEC_VOLATILE:
5554       {
5555         int i;
5556
5557         sprintf (t1, "unspec/v{");
5558         for (i = 0; i < XVECLEN (x, 0); i++)
5559           {
5560             print_pattern (t2, XVECEXP (x, 0, i), verbose);
5561             sprintf (t3, "%s%s;", t1, t2);
5562             strcpy (t1, t3);
5563           }
5564         sprintf (buf, "%s}", t1);
5565       }
5566       break;
5567     default:
5568       print_value (buf, x, verbose);
5569     }
5570 }                               /* print_pattern */
5571
5572 /* This is the main function in rtl visualization mechanism. It
5573    accepts an rtx and tries to recognize it as an insn, then prints it
5574    properly in human readable form, resembling assembler mnemonics.
5575    For every insn it prints its UID and BB the insn belongs too.
5576    (Probably the last "option" should be extended somehow, since it
5577    depends now on sched.c inner variables ...)  */
5578
5579 static void
5580 print_insn (buf, x, verbose)
5581      char *buf;
5582      rtx x;
5583      int verbose;
5584 {
5585   char t[BUF_LEN];
5586   rtx insn = x;
5587
5588   switch (GET_CODE (x))
5589     {
5590     case INSN:
5591       print_pattern (t, PATTERN (x), verbose);
5592       if (verbose)
5593         sprintf (buf, "b%d: i% 4d: %s", INSN_BB (x),
5594                  INSN_UID (x), t);
5595       else
5596         sprintf (buf, "%-4d %s", INSN_UID (x), t);
5597       break;
5598     case JUMP_INSN:
5599       print_pattern (t, PATTERN (x), verbose);
5600       if (verbose)
5601         sprintf (buf, "b%d: i% 4d: jump %s", INSN_BB (x),
5602                  INSN_UID (x), t);
5603       else
5604         sprintf (buf, "%-4d %s", INSN_UID (x), t);
5605       break;
5606     case CALL_INSN:
5607       x = PATTERN (insn);
5608       if (GET_CODE (x) == PARALLEL)
5609         {
5610           x = XVECEXP (x, 0, 0);
5611           print_pattern (t, x, verbose);
5612         }
5613       else
5614         strcpy (t, "call <...>");
5615       if (verbose)
5616         sprintf (buf, "b%d: i% 4d: %s", INSN_BB (insn),
5617                  INSN_UID (insn), t);
5618       else
5619         sprintf (buf, "%-4d %s", INSN_UID (insn), t);
5620       break;
5621     case CODE_LABEL:
5622       sprintf (buf, "L%d:", INSN_UID (x));
5623       break;
5624     case BARRIER:
5625       sprintf (buf, "i% 4d: barrier", INSN_UID (x));
5626       break;
5627     case NOTE:
5628       if (NOTE_LINE_NUMBER (x) > 0)
5629         sprintf (buf, "%4d note \"%s\" %d", INSN_UID (x),
5630                  NOTE_SOURCE_FILE (x), NOTE_LINE_NUMBER (x));
5631       else
5632         sprintf (buf, "%4d %s", INSN_UID (x),
5633                  GET_NOTE_INSN_NAME (NOTE_LINE_NUMBER (x)));
5634       break;
5635     default:
5636       if (verbose)
5637         {
5638           sprintf (buf, "Not an INSN at all\n");
5639           debug_rtx (x);
5640         }
5641       else
5642         sprintf (buf, "i%-4d  <What?>", INSN_UID (x));
5643     }
5644 }                               /* print_insn */
5645
5646 /* Print visualization debugging info.  */
5647
5648 static void
5649 print_block_visualization (b, s)
5650      int b;
5651      const char *s;
5652 {
5653   int unit, i;
5654
5655   /* Print header.  */
5656   fprintf (dump, "\n;;   ==================== scheduling visualization for block %d %s \n", b, s);
5657
5658   /* Print names of units.  */
5659   fprintf (dump, ";;   %-8s", "clock");
5660   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
5661     if (function_units[unit].bitmask & target_units)
5662       for (i = 0; i < function_units[unit].multiplicity; i++)
5663         fprintf (dump, "  %-33s", function_units[unit].name);
5664   fprintf (dump, "  %-8s\n", "no-unit");
5665
5666   fprintf (dump, ";;   %-8s", "=====");
5667   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
5668     if (function_units[unit].bitmask & target_units)
5669       for (i = 0; i < function_units[unit].multiplicity; i++)
5670         fprintf (dump, "  %-33s", "==============================");
5671   fprintf (dump, "  %-8s\n", "=======");
5672
5673   /* Print insns in each cycle.  */
5674   fprintf (dump, "%s\n", visual_tbl);
5675 }
5676
5677 /* Print insns in the 'no_unit' column of visualization.  */
5678
5679 static void
5680 visualize_no_unit (insn)
5681      rtx insn;
5682 {
5683   vis_no_unit[n_vis_no_unit] = insn;
5684   n_vis_no_unit++;
5685 }
5686
5687 /* Print insns scheduled in clock, for visualization.  */
5688
5689 static void
5690 visualize_scheduled_insns (b, clock)
5691      int b, clock;
5692 {
5693   int i, unit;
5694
5695   /* If no more room, split table into two.  */
5696   if (n_visual_lines >= MAX_VISUAL_LINES)
5697     {
5698       print_block_visualization (b, "(incomplete)");
5699       init_block_visualization ();
5700     }
5701
5702   n_visual_lines++;
5703
5704   sprintf (visual_tbl + strlen (visual_tbl), ";;   %-8d", clock);
5705   for (unit = 0; unit < FUNCTION_UNITS_SIZE; unit++)
5706     if (function_units[unit].bitmask & target_units)
5707       for (i = 0; i < function_units[unit].multiplicity; i++)
5708         {
5709           int instance = unit + i * FUNCTION_UNITS_SIZE;
5710           rtx insn = unit_last_insn[instance];
5711
5712           /* Print insns that still keep the unit busy.  */
5713           if (insn &&
5714               actual_hazard_this_instance (unit, instance, insn, clock, 0))
5715             {
5716               char str[BUF_LEN];
5717               print_insn (str, insn, 0);
5718               str[INSN_LEN] = '\0';
5719               sprintf (visual_tbl + strlen (visual_tbl), "  %-33s", str);
5720             }
5721           else
5722             sprintf (visual_tbl + strlen (visual_tbl), "  %-33s", "------------------------------");
5723         }
5724
5725   /* Print insns that are not assigned to any unit.  */
5726   for (i = 0; i < n_vis_no_unit; i++)
5727     sprintf (visual_tbl + strlen (visual_tbl), "  %-8d",
5728              INSN_UID (vis_no_unit[i]));
5729   n_vis_no_unit = 0;
5730
5731   sprintf (visual_tbl + strlen (visual_tbl), "\n");
5732 }
5733
5734 /* Print stalled cycles.  */
5735
5736 static void
5737 visualize_stall_cycles (b, stalls)
5738      int b, stalls;
5739 {
5740   int i;
5741
5742   /* If no more room, split table into two.  */
5743   if (n_visual_lines >= MAX_VISUAL_LINES)
5744     {
5745       print_block_visualization (b, "(incomplete)");
5746       init_block_visualization ();
5747     }
5748
5749   n_visual_lines++;
5750
5751   sprintf (visual_tbl + strlen (visual_tbl), ";;       ");
5752   for (i = 0; i < stalls; i++)
5753     sprintf (visual_tbl + strlen (visual_tbl), ".");
5754   sprintf (visual_tbl + strlen (visual_tbl), "\n");
5755 }
5756
5757 /* move_insn1: Remove INSN from insn chain, and link it after LAST insn.  */
5758
5759 static rtx
5760 move_insn1 (insn, last)
5761      rtx insn, last;
5762 {
5763   NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (insn);
5764   PREV_INSN (NEXT_INSN (insn)) = PREV_INSN (insn);
5765
5766   NEXT_INSN (insn) = NEXT_INSN (last);
5767   PREV_INSN (NEXT_INSN (last)) = insn;
5768
5769   NEXT_INSN (last) = insn;
5770   PREV_INSN (insn) = last;
5771
5772   return insn;
5773 }
5774
5775 /* Search INSN for REG_SAVE_NOTE note pairs for NOTE_INSN_SETJMP,
5776    NOTE_INSN_{LOOP,EHREGION}_{BEG,END}; and convert them back into
5777    NOTEs.  The REG_SAVE_NOTE note following first one is contains the
5778    saved value for NOTE_BLOCK_NUMBER which is useful for
5779    NOTE_INSN_EH_REGION_{BEG,END} NOTEs.  LAST is the last instruction
5780    output by the instruction scheduler.  Return the new value of LAST.  */
5781
5782 static rtx
5783 reemit_notes (insn, last)
5784      rtx insn;
5785      rtx last;
5786 {
5787   rtx note, retval;
5788
5789   retval = last;
5790   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
5791     {
5792       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
5793         {
5794           enum insn_note note_type = INTVAL (XEXP (note, 0));
5795
5796           if (note_type == NOTE_INSN_SETJMP)
5797             {
5798               retval = emit_note_after (NOTE_INSN_SETJMP, insn);
5799               CONST_CALL_P (retval) = CONST_CALL_P (note);
5800               remove_note (insn, note);
5801               note = XEXP (note, 1);
5802             }
5803           else if (note_type == NOTE_INSN_RANGE_BEG
5804                    || note_type == NOTE_INSN_RANGE_END)
5805             {
5806               last = emit_note_before (note_type, last);
5807               remove_note (insn, note);
5808               note = XEXP (note, 1);
5809               NOTE_RANGE_INFO (last) = XEXP (note, 0);
5810             }
5811           else
5812             {
5813               last = emit_note_before (note_type, last);
5814               remove_note (insn, note);
5815               note = XEXP (note, 1);
5816               if (note_type == NOTE_INSN_EH_REGION_BEG
5817                   || note_type == NOTE_INSN_EH_REGION_END)
5818                 NOTE_EH_HANDLER (last) = INTVAL (XEXP (note, 0));
5819             }
5820           remove_note (insn, note);
5821         }
5822     }
5823   return retval;
5824 }
5825
5826 /* Move INSN, and all insns which should be issued before it,
5827    due to SCHED_GROUP_P flag.  Reemit notes if needed.
5828
5829    Return the last insn emitted by the scheduler, which is the
5830    return value from the first call to reemit_notes.  */
5831
5832 static rtx
5833 move_insn (insn, last)
5834      rtx insn, last;
5835 {
5836   rtx retval = NULL;
5837
5838   /* If INSN has SCHED_GROUP_P set, then issue it and any other
5839      insns with SCHED_GROUP_P set first.  */
5840   while (SCHED_GROUP_P (insn))
5841     {
5842       rtx prev = PREV_INSN (insn);
5843
5844       /* Move a SCHED_GROUP_P insn.  */
5845       move_insn1 (insn, last);
5846       /* If this is the first call to reemit_notes, then record
5847          its return value.  */
5848       if (retval == NULL_RTX)
5849         retval = reemit_notes (insn, insn);
5850       else
5851         reemit_notes (insn, insn);
5852       insn = prev;
5853     }
5854
5855   /* Now move the first non SCHED_GROUP_P insn.  */
5856   move_insn1 (insn, last);
5857
5858   /* If this is the first call to reemit_notes, then record
5859      its return value.  */
5860   if (retval == NULL_RTX)
5861     retval = reemit_notes (insn, insn);
5862   else
5863     reemit_notes (insn, insn);
5864
5865   return retval;
5866 }
5867
5868 /* Return an insn which represents a SCHED_GROUP, which is
5869    the last insn in the group.  */
5870
5871 static rtx
5872 group_leader (insn)
5873      rtx insn;
5874 {
5875   rtx prev;
5876
5877   do
5878     {
5879       prev = insn;
5880       insn = next_nonnote_insn (insn);
5881     }
5882   while (insn && SCHED_GROUP_P (insn) && (GET_CODE (insn) != CODE_LABEL));
5883
5884   return prev;
5885 }
5886
5887 /* Use forward list scheduling to rearrange insns of block BB in region RGN,
5888    possibly bringing insns from subsequent blocks in the same region.
5889    Return number of insns scheduled.  */
5890
5891 static int
5892 schedule_block (bb, rgn_n_insns)
5893      int bb;
5894      int rgn_n_insns;
5895 {
5896   /* Local variables.  */
5897   rtx insn, last;
5898   struct ready_list ready;
5899   int can_issue_more;
5900
5901   /* Flow block of this bb.  */
5902   int b = BB_TO_BLOCK (bb);
5903
5904   /* target_n_insns == number of insns in b before scheduling starts.
5905      sched_target_n_insns == how many of b's insns were scheduled.
5906      sched_n_insns == how many insns were scheduled in b.  */
5907   int target_n_insns = 0;
5908   int sched_target_n_insns = 0;
5909   int sched_n_insns = 0;
5910
5911 #define NEED_NOTHING    0
5912 #define NEED_HEAD       1
5913 #define NEED_TAIL       2
5914   int new_needs;
5915
5916   /* Head/tail info for this block.  */
5917   rtx prev_head;
5918   rtx next_tail;
5919   rtx head;
5920   rtx tail;
5921   int bb_src;
5922
5923   /* We used to have code to avoid getting parameters moved from hard
5924      argument registers into pseudos.
5925
5926      However, it was removed when it proved to be of marginal benefit
5927      and caused problems because schedule_block and compute_forward_dependences
5928      had different notions of what the "head" insn was.  */
5929   get_bb_head_tail (bb, &head, &tail);
5930
5931   /* rm_other_notes only removes notes which are _inside_ the
5932      block---that is, it won't remove notes before the first real insn
5933      or after the last real insn of the block.  So if the first insn
5934      has a REG_SAVE_NOTE which would otherwise be emitted before the
5935      insn, it is redundant with the note before the start of the
5936      block, and so we have to take it out.
5937
5938      FIXME: Probably the same thing should be done with REG_SAVE_NOTEs
5939      referencing NOTE_INSN_SETJMP at the end of the block.  */
5940   if (INSN_P (head))
5941     {
5942       rtx note;
5943
5944       for (note = REG_NOTES (head); note; note = XEXP (note, 1))
5945         if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
5946           {
5947             if (INTVAL (XEXP (note, 0)) != NOTE_INSN_SETJMP)
5948               {
5949                 remove_note (head, note);
5950                 note = XEXP (note, 1);
5951                 remove_note (head, note);
5952               }
5953             else
5954               note = XEXP (note, 1);
5955           }
5956     }
5957
5958   next_tail = NEXT_INSN (tail);
5959   prev_head = PREV_INSN (head);
5960
5961   /* If the only insn left is a NOTE or a CODE_LABEL, then there is no need
5962      to schedule this block.  */
5963   if (head == tail && (! INSN_P (head)))
5964     return (sched_n_insns);
5965
5966   /* Debug info.  */
5967   if (sched_verbose)
5968     {
5969       fprintf (dump, ";;   ======================================================\n");
5970       fprintf (dump,
5971                ";;   -- basic block %d from %d to %d -- %s reload\n",
5972                b, INSN_UID (BLOCK_HEAD (b)), INSN_UID (BLOCK_END (b)),
5973                (reload_completed ? "after" : "before"));
5974       fprintf (dump, ";;   ======================================================\n");
5975       fprintf (dump, "\n");
5976
5977       visual_tbl = (char *) alloca (get_visual_tbl_length ());
5978       init_block_visualization ();
5979     }
5980
5981   /* Remove remaining note insns from the block, save them in
5982      note_list.  These notes are restored at the end of
5983      schedule_block ().  */
5984   note_list = 0;
5985   rm_other_notes (head, tail);
5986
5987   target_bb = bb;
5988
5989   /* Prepare current target block info.  */
5990   if (current_nr_blocks > 1)
5991     {
5992       candidate_table = (candidate *) xmalloc (current_nr_blocks
5993                                                * sizeof (candidate));
5994
5995       bblst_last = 0;
5996       /* bblst_table holds split blocks and update blocks for each block after
5997          the current one in the region.  split blocks and update blocks are
5998          the TO blocks of region edges, so there can be at most rgn_nr_edges
5999          of them.  */
6000       bblst_size = (current_nr_blocks - bb) * rgn_nr_edges;
6001       bblst_table = (int *) xmalloc (bblst_size * sizeof (int));
6002
6003       bitlst_table_last = 0;
6004       bitlst_table_size = rgn_nr_edges;
6005       bitlst_table = (int *) xmalloc (rgn_nr_edges * sizeof (int));
6006
6007       compute_trg_info (bb);
6008     }
6009
6010   clear_units ();
6011
6012   /* Allocate the ready list.  */
6013   ready.veclen = rgn_n_insns + 1 + ISSUE_RATE;
6014   ready.first = ready.veclen - 1;
6015   ready.vec = (rtx *) xmalloc (ready.veclen * sizeof (rtx));
6016   ready.n_ready = 0;
6017
6018   /* Print debugging information.  */
6019   if (sched_verbose >= 5)
6020     debug_dependencies ();
6021
6022   /* Initialize ready list with all 'ready' insns in target block.
6023      Count number of insns in the target block being scheduled.  */
6024   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6025     {
6026       rtx next;
6027
6028       if (! INSN_P (insn))
6029         continue;
6030       next = NEXT_INSN (insn);
6031
6032       if (INSN_DEP_COUNT (insn) == 0
6033           && (SCHED_GROUP_P (next) == 0 || ! INSN_P (next)))
6034         ready_add (&ready, insn);
6035       if (!(SCHED_GROUP_P (insn)))
6036         target_n_insns++;
6037     }
6038
6039   /* Add to ready list all 'ready' insns in valid source blocks.
6040      For speculative insns, check-live, exception-free, and
6041      issue-delay.  */
6042   for (bb_src = bb + 1; bb_src < current_nr_blocks; bb_src++)
6043     if (IS_VALID (bb_src))
6044       {
6045         rtx src_head;
6046         rtx src_next_tail;
6047         rtx tail, head;
6048
6049         get_bb_head_tail (bb_src, &head, &tail);
6050         src_next_tail = NEXT_INSN (tail);
6051         src_head = head;
6052
6053         if (head == tail && (! INSN_P (head)))
6054           continue;
6055
6056         for (insn = src_head; insn != src_next_tail; insn = NEXT_INSN (insn))
6057           {
6058             if (! INSN_P (insn))
6059               continue;
6060
6061             if (!CANT_MOVE (insn)
6062                 && (!IS_SPECULATIVE_INSN (insn)
6063                     || (insn_issue_delay (insn) <= 3
6064                         && check_live (insn, bb_src)
6065                         && is_exception_free (insn, bb_src, target_bb))))
6066               {
6067                 rtx next;
6068
6069                 /* Note that we havn't squirrled away the notes for
6070                    blocks other than the current.  So if this is a
6071                    speculative insn, NEXT might otherwise be a note.  */
6072                 next = next_nonnote_insn (insn);
6073                 if (INSN_DEP_COUNT (insn) == 0
6074                     && (! next
6075                         || SCHED_GROUP_P (next) == 0
6076                         || ! INSN_P (next)))
6077                   ready_add (&ready, insn);
6078               }
6079           }
6080       }
6081
6082 #ifdef MD_SCHED_INIT
6083   MD_SCHED_INIT (dump, sched_verbose);
6084 #endif
6085
6086   /* No insns scheduled in this block yet.  */
6087   last_scheduled_insn = 0;
6088
6089   /* Q_SIZE is the total number of insns in the queue.  */
6090   q_ptr = 0;
6091   q_size = 0;
6092   last_clock_var = 0;
6093   memset ((char *) insn_queue, 0, sizeof (insn_queue));
6094
6095   /* Start just before the beginning of time.  */
6096   clock_var = -1;
6097
6098   /* We start inserting insns after PREV_HEAD.  */
6099   last = prev_head;
6100
6101   /* Initialize INSN_QUEUE, LIST and NEW_NEEDS.  */
6102   new_needs = (NEXT_INSN (prev_head) == BLOCK_HEAD (b)
6103                ? NEED_HEAD : NEED_NOTHING);
6104   if (PREV_INSN (next_tail) == BLOCK_END (b))
6105     new_needs |= NEED_TAIL;
6106
6107   /* Loop until all the insns in BB are scheduled.  */
6108   while (sched_target_n_insns < target_n_insns)
6109     {
6110       clock_var++;
6111
6112       /* Add to the ready list all pending insns that can be issued now.
6113          If there are no ready insns, increment clock until one
6114          is ready and add all pending insns at that point to the ready
6115          list.  */
6116       queue_to_ready (&ready);
6117
6118       if (ready.n_ready == 0)
6119         abort ();
6120
6121       if (sched_verbose >= 2)
6122         {
6123           fprintf (dump, ";;\t\tReady list after queue_to_ready:  ");
6124           debug_ready_list (&ready);
6125         }
6126
6127       /* Sort the ready list based on priority.  */
6128       ready_sort (&ready);
6129
6130       /* Allow the target to reorder the list, typically for
6131          better instruction bundling.  */
6132 #ifdef MD_SCHED_REORDER
6133       MD_SCHED_REORDER (dump, sched_verbose, ready_lastpos (&ready),
6134                         ready.n_ready, clock_var, can_issue_more);
6135 #else
6136       can_issue_more = issue_rate;
6137 #endif
6138
6139       if (sched_verbose)
6140         {
6141           fprintf (dump, "\n;;\tReady list (t =%3d):  ", clock_var);
6142           debug_ready_list (&ready);
6143         }
6144
6145       /* Issue insns from ready list.  */
6146       while (ready.n_ready != 0 && can_issue_more)
6147         {
6148           /* Select and remove the insn from the ready list.  */
6149           rtx insn = ready_remove_first (&ready);
6150           int cost = actual_hazard (insn_unit (insn), insn, clock_var, 0);
6151
6152           if (cost >= 1)
6153             {
6154               queue_insn (insn, cost);
6155               continue;
6156             }
6157
6158           /* An interblock motion?  */
6159           if (INSN_BB (insn) != target_bb)
6160             {
6161               rtx temp;
6162               basic_block b1;
6163
6164               if (IS_SPECULATIVE_INSN (insn))
6165                 {
6166                   if (!check_live (insn, INSN_BB (insn)))
6167                     continue;
6168                   update_live (insn, INSN_BB (insn));
6169
6170                   /* For speculative load, mark insns fed by it.  */
6171                   if (IS_LOAD_INSN (insn) || FED_BY_SPEC_LOAD (insn))
6172                     set_spec_fed (insn);
6173
6174                   nr_spec++;
6175                 }
6176               nr_inter++;
6177
6178               /* Find the beginning of the scheduling group.  */
6179               /* ??? Ought to update basic block here, but later bits of
6180                  schedule_block assumes the original insn block is
6181                  still intact.  */
6182
6183               temp = insn;
6184               while (SCHED_GROUP_P (temp))
6185                 temp = PREV_INSN (temp);
6186
6187               /* Update source block boundaries.   */
6188               b1 = BLOCK_FOR_INSN (temp);
6189               if (temp == b1->head && insn == b1->end)
6190                 {
6191                   /* We moved all the insns in the basic block.
6192                      Emit a note after the last insn and update the
6193                      begin/end boundaries to point to the note.  */
6194                   rtx note = emit_note_after (NOTE_INSN_DELETED, insn);
6195                   b1->head = note;
6196                   b1->end = note;
6197                 }
6198               else if (insn == b1->end)
6199                 {
6200                   /* We took insns from the end of the basic block,
6201                      so update the end of block boundary so that it
6202                      points to the first insn we did not move.  */
6203                   b1->end = PREV_INSN (temp);
6204                 }
6205               else if (temp == b1->head)
6206                 {
6207                   /* We took insns from the start of the basic block,
6208                      so update the start of block boundary so that
6209                      it points to the first insn we did not move.  */
6210                   b1->head = NEXT_INSN (insn);
6211                 }
6212             }
6213           else
6214             {
6215               /* In block motion.  */
6216               sched_target_n_insns++;
6217             }
6218
6219           last_scheduled_insn = insn;
6220           last = move_insn (insn, last);
6221           sched_n_insns++;
6222
6223 #ifdef MD_SCHED_VARIABLE_ISSUE
6224           MD_SCHED_VARIABLE_ISSUE (dump, sched_verbose, insn,
6225                                    can_issue_more);
6226 #else
6227           can_issue_more--;
6228 #endif
6229
6230           schedule_insn (insn, &ready, clock_var);
6231
6232           /* Close this block after scheduling its jump.  */
6233           if (GET_CODE (last_scheduled_insn) == JUMP_INSN)
6234             break;
6235         }
6236
6237       /* Debug info.  */
6238       if (sched_verbose)
6239         visualize_scheduled_insns (b, clock_var);
6240     }
6241
6242   /* Debug info.  */
6243   if (sched_verbose)
6244     {
6245       fprintf (dump, ";;\tReady list (final):  ");
6246       debug_ready_list (&ready);
6247       print_block_visualization (b, "");
6248     }
6249
6250   /* Sanity check -- queue must be empty now.  Meaningless if region has
6251      multiple bbs.  */
6252   if (current_nr_blocks > 1)
6253     if (!flag_schedule_interblock && q_size != 0)
6254       abort ();
6255
6256   /* Update head/tail boundaries.  */
6257   head = NEXT_INSN (prev_head);
6258   tail = last;
6259
6260   /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
6261      previously found among the insns.  Insert them at the beginning
6262      of the insns.  */
6263   if (note_list != 0)
6264     {
6265       rtx note_head = note_list;
6266
6267       while (PREV_INSN (note_head))
6268         {
6269           note_head = PREV_INSN (note_head);
6270         }
6271
6272       PREV_INSN (note_head) = PREV_INSN (head);
6273       NEXT_INSN (PREV_INSN (head)) = note_head;
6274       PREV_INSN (head) = note_list;
6275       NEXT_INSN (note_list) = head;
6276       head = note_head;
6277     }
6278
6279   /* Update target block boundaries.  */
6280   if (new_needs & NEED_HEAD)
6281     BLOCK_HEAD (b) = head;
6282
6283   if (new_needs & NEED_TAIL)
6284     BLOCK_END (b) = tail;
6285
6286   /* Debugging.  */
6287   if (sched_verbose)
6288     {
6289       fprintf (dump, ";;   total time = %d\n;;   new basic block head = %d\n",
6290                clock_var, INSN_UID (BLOCK_HEAD (b)));
6291       fprintf (dump, ";;   new basic block end = %d\n\n",
6292                INSN_UID (BLOCK_END (b)));
6293     }
6294
6295   /* Clean up.  */
6296   if (current_nr_blocks > 1)
6297     {
6298       free (candidate_table);
6299       free (bblst_table);
6300       free (bitlst_table);
6301     }
6302   free (ready.vec);
6303
6304   return (sched_n_insns);
6305 }
6306 \f
6307 /* Print the bit-set of registers, S, callable from debugger.  */
6308
6309 extern void
6310 debug_reg_vector (s)
6311      regset s;
6312 {
6313   int regno;
6314
6315   EXECUTE_IF_SET_IN_REG_SET (s, 0, regno,
6316                              {
6317                                fprintf (dump, " %d", regno);
6318                              });
6319
6320   fprintf (dump, "\n");
6321 }
6322
6323 /* Use the backward dependences from LOG_LINKS to build
6324    forward dependences in INSN_DEPEND.  */
6325
6326 static void
6327 compute_block_forward_dependences (bb)
6328      int bb;
6329 {
6330   rtx insn, link;
6331   rtx tail, head;
6332   rtx next_tail;
6333   enum reg_note dep_type;
6334
6335   get_bb_head_tail (bb, &head, &tail);
6336   next_tail = NEXT_INSN (tail);
6337   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6338     {
6339       if (! INSN_P (insn))
6340         continue;
6341
6342       insn = group_leader (insn);
6343
6344       for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
6345         {
6346           rtx x = group_leader (XEXP (link, 0));
6347           rtx new_link;
6348
6349           if (x != XEXP (link, 0))
6350             continue;
6351
6352 #ifdef ENABLE_CHECKING
6353           /* If add_dependence is working properly there should never
6354              be notes, deleted insns or duplicates in the backward
6355              links.  Thus we need not check for them here.
6356
6357              However, if we have enabled checking we might as well go
6358              ahead and verify that add_dependence worked properly.  */
6359           if (GET_CODE (x) == NOTE
6360               || INSN_DELETED_P (x)
6361               || (forward_dependency_cache != NULL
6362                   && TEST_BIT (forward_dependency_cache[INSN_LUID (x)],
6363                                INSN_LUID (insn)))
6364               || (forward_dependency_cache == NULL
6365                   && find_insn_list (insn, INSN_DEPEND (x))))
6366             abort ();
6367           if (forward_dependency_cache != NULL)
6368             SET_BIT (forward_dependency_cache[INSN_LUID (x)],
6369                      INSN_LUID (insn));
6370 #endif
6371
6372           new_link = alloc_INSN_LIST (insn, INSN_DEPEND (x));
6373
6374           dep_type = REG_NOTE_KIND (link);
6375           PUT_REG_NOTE_KIND (new_link, dep_type);
6376
6377           INSN_DEPEND (x) = new_link;
6378           INSN_DEP_COUNT (insn) += 1;
6379         }
6380     }
6381 }
6382
6383 /* Initialize variables for region data dependence analysis.
6384    n_bbs is the number of region blocks.  */
6385
6386 static void
6387 init_deps (deps)
6388      struct deps *deps;
6389 {
6390   int maxreg = max_reg_num ();
6391   deps->reg_last_uses = (rtx *) xcalloc (maxreg, sizeof (rtx));
6392   deps->reg_last_sets = (rtx *) xcalloc (maxreg, sizeof (rtx));
6393   deps->reg_last_clobbers = (rtx *) xcalloc (maxreg, sizeof (rtx));
6394
6395   deps->pending_read_insns = 0;
6396   deps->pending_read_mems = 0;
6397   deps->pending_write_insns = 0;
6398   deps->pending_write_mems = 0;
6399   deps->pending_lists_length = 0;
6400   deps->last_pending_memory_flush = 0;
6401   deps->last_function_call = 0;
6402   deps->in_post_call_group_p = 0;
6403
6404   deps->sched_before_next_call
6405     = gen_rtx_INSN (VOIDmode, 0, NULL_RTX, NULL_RTX,
6406                     NULL_RTX, 0, NULL_RTX, NULL_RTX);
6407   LOG_LINKS (deps->sched_before_next_call) = 0;
6408 }
6409
6410 /* Add dependences so that branches are scheduled to run last in their
6411    block.  */
6412
6413 static void
6414 add_branch_dependences (head, tail)
6415      rtx head, tail;
6416 {
6417   rtx insn, last;
6418
6419   /* For all branches, calls, uses, clobbers, and cc0 setters, force them
6420      to remain in order at the end of the block by adding dependencies and
6421      giving the last a high priority.  There may be notes present, and
6422      prev_head may also be a note.
6423
6424      Branches must obviously remain at the end.  Calls should remain at the
6425      end since moving them results in worse register allocation.  Uses remain
6426      at the end to ensure proper register allocation.  cc0 setters remaim
6427      at the end because they can't be moved away from their cc0 user.  */
6428   insn = tail;
6429   last = 0;
6430   while (GET_CODE (insn) == CALL_INSN
6431          || GET_CODE (insn) == JUMP_INSN
6432          || (GET_CODE (insn) == INSN
6433              && (GET_CODE (PATTERN (insn)) == USE
6434                  || GET_CODE (PATTERN (insn)) == CLOBBER
6435 #ifdef HAVE_cc0
6436                  || sets_cc0_p (PATTERN (insn))
6437 #endif
6438              ))
6439          || GET_CODE (insn) == NOTE)
6440     {
6441       if (GET_CODE (insn) != NOTE)
6442         {
6443           if (last != 0
6444               && !find_insn_list (insn, LOG_LINKS (last)))
6445             {
6446               add_dependence (last, insn, REG_DEP_ANTI);
6447               INSN_REF_COUNT (insn)++;
6448             }
6449
6450           CANT_MOVE (insn) = 1;
6451
6452           last = insn;
6453           /* Skip over insns that are part of a group.
6454              Make each insn explicitly depend on the previous insn.
6455              This ensures that only the group header will ever enter
6456              the ready queue (and, when scheduled, will automatically
6457              schedule the SCHED_GROUP_P block).  */
6458           while (SCHED_GROUP_P (insn))
6459             {
6460               rtx temp = prev_nonnote_insn (insn);
6461               add_dependence (insn, temp, REG_DEP_ANTI);
6462               insn = temp;
6463             }
6464         }
6465
6466       /* Don't overrun the bounds of the basic block.  */
6467       if (insn == head)
6468         break;
6469
6470       insn = PREV_INSN (insn);
6471     }
6472
6473   /* Make sure these insns are scheduled last in their block.  */
6474   insn = last;
6475   if (insn != 0)
6476     while (insn != head)
6477       {
6478         insn = prev_nonnote_insn (insn);
6479
6480         if (INSN_REF_COUNT (insn) != 0)
6481           continue;
6482
6483         add_dependence (last, insn, REG_DEP_ANTI);
6484         INSN_REF_COUNT (insn) = 1;
6485
6486         /* Skip over insns that are part of a group.  */
6487         while (SCHED_GROUP_P (insn))
6488           insn = prev_nonnote_insn (insn);
6489       }
6490 }
6491
6492 /* After computing the dependencies for block BB, propagate the dependencies
6493    found in TMP_DEPS to the successors of the block.  MAX_REG is the number
6494    of registers.  */
6495 static void
6496 propagate_deps (bb, tmp_deps, max_reg)
6497      int bb;
6498      struct deps *tmp_deps;
6499      int max_reg;
6500 {
6501   int b = BB_TO_BLOCK (bb);
6502   int e, first_edge;
6503   int reg;
6504   rtx link_insn, link_mem;
6505   rtx u;
6506
6507   /* These lists should point to the right place, for correct
6508      freeing later.  */
6509   bb_deps[bb].pending_read_insns = tmp_deps->pending_read_insns;
6510   bb_deps[bb].pending_read_mems = tmp_deps->pending_read_mems;
6511   bb_deps[bb].pending_write_insns = tmp_deps->pending_write_insns;
6512   bb_deps[bb].pending_write_mems = tmp_deps->pending_write_mems;
6513
6514   /* bb's structures are inherited by its successors.  */
6515   first_edge = e = OUT_EDGES (b);
6516   if (e <= 0)
6517     return;
6518
6519   do
6520     {
6521       rtx x;
6522       int b_succ = TO_BLOCK (e);
6523       int bb_succ = BLOCK_TO_BB (b_succ);
6524       struct deps *succ_deps = bb_deps + bb_succ;
6525
6526       /* Only bbs "below" bb, in the same region, are interesting.  */
6527       if (CONTAINING_RGN (b) != CONTAINING_RGN (b_succ)
6528           || bb_succ <= bb)
6529         {
6530           e = NEXT_OUT (e);
6531           continue;
6532         }
6533
6534       for (reg = 0; reg < max_reg; reg++)
6535         {
6536           /* reg-last-uses lists are inherited by bb_succ.  */
6537           for (u = tmp_deps->reg_last_uses[reg]; u; u = XEXP (u, 1))
6538             {
6539               if (find_insn_list (XEXP (u, 0),
6540                                   succ_deps->reg_last_uses[reg]))
6541                 continue;
6542
6543               succ_deps->reg_last_uses[reg]
6544                 = alloc_INSN_LIST (XEXP (u, 0),
6545                                    succ_deps->reg_last_uses[reg]);
6546             }
6547
6548           /* reg-last-defs lists are inherited by bb_succ.  */
6549           for (u = tmp_deps->reg_last_sets[reg]; u; u = XEXP (u, 1))
6550             {
6551               if (find_insn_list (XEXP (u, 0),
6552                                   succ_deps->reg_last_sets[reg]))
6553                 continue;
6554
6555               succ_deps->reg_last_sets[reg]
6556                 = alloc_INSN_LIST (XEXP (u, 0),
6557                                    succ_deps->reg_last_sets[reg]);
6558             }
6559
6560           for (u = tmp_deps->reg_last_clobbers[reg]; u; u = XEXP (u, 1))
6561             {
6562               if (find_insn_list (XEXP (u, 0),
6563                                   succ_deps->reg_last_clobbers[reg]))
6564                 continue;
6565
6566               succ_deps->reg_last_clobbers[reg]
6567                 = alloc_INSN_LIST (XEXP (u, 0),
6568                                    succ_deps->reg_last_clobbers[reg]);
6569             }
6570         }
6571
6572       /* Mem read/write lists are inherited by bb_succ.  */
6573       link_insn = tmp_deps->pending_read_insns;
6574       link_mem = tmp_deps->pending_read_mems;
6575       while (link_insn)
6576         {
6577           if (!(find_insn_mem_list (XEXP (link_insn, 0),
6578                                     XEXP (link_mem, 0),
6579                                     succ_deps->pending_read_insns,
6580                                     succ_deps->pending_read_mems)))
6581             add_insn_mem_dependence (succ_deps, &succ_deps->pending_read_insns,
6582                                      &succ_deps->pending_read_mems,
6583                                      XEXP (link_insn, 0), XEXP (link_mem, 0));
6584           link_insn = XEXP (link_insn, 1);
6585           link_mem = XEXP (link_mem, 1);
6586         }
6587
6588       link_insn = tmp_deps->pending_write_insns;
6589       link_mem = tmp_deps->pending_write_mems;
6590       while (link_insn)
6591         {
6592           if (!(find_insn_mem_list (XEXP (link_insn, 0),
6593                                     XEXP (link_mem, 0),
6594                                     succ_deps->pending_write_insns,
6595                                     succ_deps->pending_write_mems)))
6596             add_insn_mem_dependence (succ_deps,
6597                                      &succ_deps->pending_write_insns,
6598                                      &succ_deps->pending_write_mems,
6599                                      XEXP (link_insn, 0), XEXP (link_mem, 0));
6600
6601           link_insn = XEXP (link_insn, 1);
6602           link_mem = XEXP (link_mem, 1);
6603         }
6604
6605       /* last_function_call is inherited by bb_succ.  */
6606       for (u = tmp_deps->last_function_call; u; u = XEXP (u, 1))
6607         {
6608           if (find_insn_list (XEXP (u, 0),
6609                               succ_deps->last_function_call))
6610             continue;
6611
6612           succ_deps->last_function_call
6613             = alloc_INSN_LIST (XEXP (u, 0),
6614                                succ_deps->last_function_call);
6615         }
6616
6617       /* last_pending_memory_flush is inherited by bb_succ.  */
6618       for (u = tmp_deps->last_pending_memory_flush; u; u = XEXP (u, 1))
6619         {
6620           if (find_insn_list (XEXP (u, 0),
6621                               succ_deps->last_pending_memory_flush))
6622             continue;
6623
6624           succ_deps->last_pending_memory_flush
6625             = alloc_INSN_LIST (XEXP (u, 0),
6626                                succ_deps->last_pending_memory_flush);
6627         }
6628
6629       /* sched_before_next_call is inherited by bb_succ.  */
6630       x = LOG_LINKS (tmp_deps->sched_before_next_call);
6631       for (; x; x = XEXP (x, 1))
6632         add_dependence (succ_deps->sched_before_next_call,
6633                         XEXP (x, 0), REG_DEP_ANTI);
6634
6635       e = NEXT_OUT (e);
6636     }
6637   while (e != first_edge);
6638 }
6639
6640 /* Compute backward dependences inside bb.  In a multiple blocks region:
6641    (1) a bb is analyzed after its predecessors, and (2) the lists in
6642    effect at the end of bb (after analyzing for bb) are inherited by
6643    bb's successrs.
6644
6645    Specifically for reg-reg data dependences, the block insns are
6646    scanned by sched_analyze () top-to-bottom.  Two lists are
6647    maintained by sched_analyze (): reg_last_sets[] for register DEFs,
6648    and reg_last_uses[] for register USEs.
6649
6650    When analysis is completed for bb, we update for its successors:
6651    ;  - DEFS[succ] = Union (DEFS [succ], DEFS [bb])
6652    ;  - USES[succ] = Union (USES [succ], DEFS [bb])
6653
6654    The mechanism for computing mem-mem data dependence is very
6655    similar, and the result is interblock dependences in the region.  */
6656
6657 static void
6658 compute_block_backward_dependences (bb)
6659      int bb;
6660 {
6661   int i;
6662   rtx head, tail;
6663   int max_reg = max_reg_num ();
6664   struct deps tmp_deps;
6665
6666   tmp_deps = bb_deps[bb];
6667
6668   /* Do the analysis for this block.  */
6669   get_bb_head_tail (bb, &head, &tail);
6670   sched_analyze (&tmp_deps, head, tail);
6671   add_branch_dependences (head, tail);
6672
6673   if (current_nr_blocks > 1)
6674     propagate_deps (bb, &tmp_deps, max_reg);
6675
6676   /* Free up the INSN_LISTs.
6677
6678      Note this loop is executed max_reg * nr_regions times.  It's first
6679      implementation accounted for over 90% of the calls to free_INSN_LIST_list.
6680      The list was empty for the vast majority of those calls.  On the PA, not
6681      calling free_INSN_LIST_list in those cases improves -O2 compile times by
6682      3-5% on average.  */
6683   for (i = 0; i < max_reg; ++i)
6684     {
6685       if (tmp_deps.reg_last_clobbers[i])
6686         free_INSN_LIST_list (&tmp_deps.reg_last_clobbers[i]);
6687       if (tmp_deps.reg_last_sets[i])
6688         free_INSN_LIST_list (&tmp_deps.reg_last_sets[i]);
6689       if (tmp_deps.reg_last_uses[i])
6690         free_INSN_LIST_list (&tmp_deps.reg_last_uses[i]);
6691     }
6692
6693   /* Assert that we won't need bb_reg_last_* for this block anymore.  */
6694   free (bb_deps[bb].reg_last_uses);
6695   free (bb_deps[bb].reg_last_sets);
6696   free (bb_deps[bb].reg_last_clobbers);
6697   bb_deps[bb].reg_last_uses = 0;
6698   bb_deps[bb].reg_last_sets = 0;
6699   bb_deps[bb].reg_last_clobbers = 0;
6700 }
6701
6702 /* Print dependences for debugging, callable from debugger.  */
6703
6704 void
6705 debug_dependencies ()
6706 {
6707   int bb;
6708
6709   fprintf (dump, ";;   --------------- forward dependences: ------------ \n");
6710   for (bb = 0; bb < current_nr_blocks; bb++)
6711     {
6712       if (1)
6713         {
6714           rtx head, tail;
6715           rtx next_tail;
6716           rtx insn;
6717
6718           get_bb_head_tail (bb, &head, &tail);
6719           next_tail = NEXT_INSN (tail);
6720           fprintf (dump, "\n;;   --- Region Dependences --- b %d bb %d \n",
6721                    BB_TO_BLOCK (bb), bb);
6722
6723           fprintf (dump, ";;   %7s%6s%6s%6s%6s%6s%11s%6s\n",
6724           "insn", "code", "bb", "dep", "prio", "cost", "blockage", "units");
6725           fprintf (dump, ";;   %7s%6s%6s%6s%6s%6s%11s%6s\n",
6726           "----", "----", "--", "---", "----", "----", "--------", "-----");
6727           for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6728             {
6729               rtx link;
6730               int unit, range;
6731
6732               if (! INSN_P (insn))
6733                 {
6734                   int n;
6735                   fprintf (dump, ";;   %6d ", INSN_UID (insn));
6736                   if (GET_CODE (insn) == NOTE)
6737                     {
6738                       n = NOTE_LINE_NUMBER (insn);
6739                       if (n < 0)
6740                         fprintf (dump, "%s\n", GET_NOTE_INSN_NAME (n));
6741                       else
6742                         fprintf (dump, "line %d, file %s\n", n,
6743                                  NOTE_SOURCE_FILE (insn));
6744                     }
6745                   else
6746                     fprintf (dump, " {%s}\n", GET_RTX_NAME (GET_CODE (insn)));
6747                   continue;
6748                 }
6749
6750               unit = insn_unit (insn);
6751               range = (unit < 0
6752                  || function_units[unit].blockage_range_function == 0) ? 0 :
6753                 function_units[unit].blockage_range_function (insn);
6754               fprintf (dump,
6755                        ";;   %s%5d%6d%6d%6d%6d%6d  %3d -%3d   ",
6756                        (SCHED_GROUP_P (insn) ? "+" : " "),
6757                        INSN_UID (insn),
6758                        INSN_CODE (insn),
6759                        INSN_BB (insn),
6760                        INSN_DEP_COUNT (insn),
6761                        INSN_PRIORITY (insn),
6762                        insn_cost (insn, 0, 0),
6763                        (int) MIN_BLOCKAGE_COST (range),
6764                        (int) MAX_BLOCKAGE_COST (range));
6765               insn_print_units (insn);
6766               fprintf (dump, "\t: ");
6767               for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
6768                 fprintf (dump, "%d ", INSN_UID (XEXP (link, 0)));
6769               fprintf (dump, "\n");
6770             }
6771         }
6772     }
6773   fprintf (dump, "\n");
6774 }
6775
6776 /* Set_priorities: compute priority of each insn in the block.  */
6777
6778 static int
6779 set_priorities (bb)
6780      int bb;
6781 {
6782   rtx insn;
6783   int n_insn;
6784
6785   rtx tail;
6786   rtx prev_head;
6787   rtx head;
6788
6789   get_bb_head_tail (bb, &head, &tail);
6790   prev_head = PREV_INSN (head);
6791
6792   if (head == tail && (! INSN_P (head)))
6793     return 0;
6794
6795   n_insn = 0;
6796   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
6797     {
6798
6799       if (GET_CODE (insn) == NOTE)
6800         continue;
6801
6802       if (!(SCHED_GROUP_P (insn)))
6803         n_insn++;
6804       (void) priority (insn);
6805     }
6806
6807   return n_insn;
6808 }
6809
6810 /* Schedule a region.  A region is either an inner loop, a loop-free
6811    subroutine, or a single basic block.  Each bb in the region is
6812    scheduled after its flow predecessors.  */
6813
6814 static void
6815 schedule_region (rgn)
6816      int rgn;
6817 {
6818   int bb;
6819   int rgn_n_insns = 0;
6820   int sched_rgn_n_insns = 0;
6821   regset_head reg_pending_sets_head;
6822   regset_head reg_pending_clobbers_head;
6823
6824   /* Set variables for the current region.  */
6825   current_nr_blocks = RGN_NR_BLOCKS (rgn);
6826   current_blocks = RGN_BLOCKS (rgn);
6827
6828   reg_pending_sets = INITIALIZE_REG_SET (reg_pending_sets_head);
6829   reg_pending_clobbers = INITIALIZE_REG_SET (reg_pending_clobbers_head);
6830   reg_pending_sets_all = 0;
6831
6832   /* Initializations for region data dependence analyisis.  */
6833   bb_deps = (struct deps *) xmalloc (sizeof (struct deps) * current_nr_blocks);
6834   for (bb = 0; bb < current_nr_blocks; bb++)
6835     init_deps (bb_deps + bb);
6836
6837   /* Compute LOG_LINKS.  */
6838   for (bb = 0; bb < current_nr_blocks; bb++)
6839     compute_block_backward_dependences (bb);
6840
6841   /* Compute INSN_DEPEND.  */
6842   for (bb = current_nr_blocks - 1; bb >= 0; bb--)
6843     compute_block_forward_dependences (bb);
6844
6845   /* Delete line notes and set priorities.  */
6846   for (bb = 0; bb < current_nr_blocks; bb++)
6847     {
6848       if (write_symbols != NO_DEBUG)
6849         {
6850           save_line_notes (bb);
6851           rm_line_notes (bb);
6852         }
6853
6854       rgn_n_insns += set_priorities (bb);
6855     }
6856
6857   /* Compute interblock info: probabilities, split-edges, dominators, etc.  */
6858   if (current_nr_blocks > 1)
6859     {
6860       int i;
6861
6862       prob = (float *) xmalloc ((current_nr_blocks) * sizeof (float));
6863
6864       bbset_size = current_nr_blocks / HOST_BITS_PER_WIDE_INT + 1;
6865       dom = (bbset *) xmalloc (current_nr_blocks * sizeof (bbset));
6866       for (i = 0; i < current_nr_blocks; i++)
6867         dom[i] = (bbset) xcalloc (bbset_size, sizeof (HOST_WIDE_INT));
6868
6869       /* Edge to bit.  */
6870       rgn_nr_edges = 0;
6871       edge_to_bit = (int *) xmalloc (nr_edges * sizeof (int));
6872       for (i = 1; i < nr_edges; i++)
6873         if (CONTAINING_RGN (FROM_BLOCK (i)) == rgn)
6874           EDGE_TO_BIT (i) = rgn_nr_edges++;
6875       rgn_edges = (int *) xmalloc (rgn_nr_edges * sizeof (int));
6876
6877       rgn_nr_edges = 0;
6878       for (i = 1; i < nr_edges; i++)
6879         if (CONTAINING_RGN (FROM_BLOCK (i)) == (rgn))
6880           rgn_edges[rgn_nr_edges++] = i;
6881
6882       /* Split edges.  */
6883       edgeset_size = rgn_nr_edges / HOST_BITS_PER_WIDE_INT + 1;
6884       edgeset_bitsize = rgn_nr_edges;
6885       pot_split = (edgeset *) xmalloc (current_nr_blocks * sizeof (edgeset));
6886       ancestor_edges
6887         = (edgeset *) xmalloc (current_nr_blocks * sizeof (edgeset));
6888       for (i = 0; i < current_nr_blocks; i++)
6889         {
6890           pot_split[i] =
6891             (edgeset) xcalloc (edgeset_size, sizeof (HOST_WIDE_INT));
6892           ancestor_edges[i] =
6893             (edgeset) xcalloc (edgeset_size, sizeof (HOST_WIDE_INT));
6894         }
6895
6896       /* Compute probabilities, dominators, split_edges.  */
6897       for (bb = 0; bb < current_nr_blocks; bb++)
6898         compute_dom_prob_ps (bb);
6899     }
6900
6901   /* Now we can schedule all blocks.  */
6902   for (bb = 0; bb < current_nr_blocks; bb++)
6903     sched_rgn_n_insns += schedule_block (bb, rgn_n_insns);
6904
6905   /* Sanity check: verify that all region insns were scheduled.  */
6906   if (sched_rgn_n_insns != rgn_n_insns)
6907     abort ();
6908
6909   /* Restore line notes.  */
6910   if (write_symbols != NO_DEBUG)
6911     {
6912       for (bb = 0; bb < current_nr_blocks; bb++)
6913         restore_line_notes (bb);
6914     }
6915
6916   /* Done with this region.  */
6917   free_pending_lists ();
6918
6919   FREE_REG_SET (reg_pending_sets);
6920   FREE_REG_SET (reg_pending_clobbers);
6921
6922   free (bb_deps);
6923
6924   if (current_nr_blocks > 1)
6925     {
6926       int i;
6927
6928       free (prob);
6929       for (i = 0; i < current_nr_blocks; ++i)
6930         {
6931           free (dom[i]);
6932           free (pot_split[i]);
6933           free (ancestor_edges[i]);
6934         }
6935       free (dom);
6936       free (edge_to_bit);
6937       free (rgn_edges);
6938       free (pot_split);
6939       free (ancestor_edges);
6940     }
6941 }
6942
6943 /* The one entry point in this file.  DUMP_FILE is the dump file for
6944    this pass.  */
6945
6946 void
6947 schedule_insns (dump_file)
6948      FILE *dump_file;
6949 {
6950   int *deaths_in_region;
6951   sbitmap blocks, large_region_blocks;
6952   int max_uid;
6953   int b;
6954   rtx insn;
6955   int rgn;
6956   int luid;
6957   int any_large_regions;
6958
6959   /* Disable speculative loads in their presence if cc0 defined.  */
6960 #ifdef HAVE_cc0
6961   flag_schedule_speculative_load = 0;
6962 #endif
6963
6964   /* Taking care of this degenerate case makes the rest of
6965      this code simpler.  */
6966   if (n_basic_blocks == 0)
6967     return;
6968
6969   /* Set dump and sched_verbose for the desired debugging output.  If no
6970      dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
6971      For -fsched-verbose=N, N>=10, print everything to stderr.  */
6972   sched_verbose = sched_verbose_param;
6973   if (sched_verbose_param == 0 && dump_file)
6974     sched_verbose = 1;
6975   dump = ((sched_verbose_param >= 10 || !dump_file) ? stderr : dump_file);
6976
6977   nr_inter = 0;
6978   nr_spec = 0;
6979
6980   /* Initialize issue_rate.  */
6981   issue_rate = ISSUE_RATE;
6982
6983   split_all_insns (1);
6984
6985   /* We use LUID 0 for the fake insn (UID 0) which holds dependencies for
6986      pseudos which do not cross calls.  */
6987   max_uid = get_max_uid () + 1;
6988
6989   h_i_d = (struct haifa_insn_data *) xcalloc (max_uid, sizeof (*h_i_d));
6990
6991   h_i_d[0].luid = 0;
6992   luid = 1;
6993   for (b = 0; b < n_basic_blocks; b++)
6994     for (insn = BLOCK_HEAD (b);; insn = NEXT_INSN (insn))
6995       {
6996         INSN_LUID (insn) = luid;
6997
6998         /* Increment the next luid, unless this is a note.  We don't
6999            really need separate IDs for notes and we don't want to
7000            schedule differently depending on whether or not there are
7001            line-number notes, i.e., depending on whether or not we're
7002            generating debugging information.  */
7003         if (GET_CODE (insn) != NOTE)
7004           ++luid;
7005
7006         if (insn == BLOCK_END (b))
7007           break;
7008       }
7009
7010   /* ?!? We could save some memory by computing a per-region luid mapping
7011      which could reduce both the number of vectors in the cache and the size
7012      of each vector.  Instead we just avoid the cache entirely unless the
7013      average number of instructions in a basic block is very high.  See
7014      the comment before the declaration of true_dependency_cache for
7015      what we consider "very high".  */
7016   if (luid / n_basic_blocks > 100 * 5)
7017     {
7018       true_dependency_cache = sbitmap_vector_alloc (luid, luid);
7019       sbitmap_vector_zero (true_dependency_cache, luid);
7020       anti_dependency_cache = sbitmap_vector_alloc (luid, luid);
7021       sbitmap_vector_zero (anti_dependency_cache, luid);
7022       output_dependency_cache = sbitmap_vector_alloc (luid, luid);
7023       sbitmap_vector_zero (output_dependency_cache, luid);
7024 #ifdef ENABLE_CHECKING
7025       forward_dependency_cache = sbitmap_vector_alloc (luid, luid);
7026       sbitmap_vector_zero (forward_dependency_cache, luid);
7027 #endif
7028     }
7029
7030   nr_regions = 0;
7031   rgn_table = (region *) xmalloc ((n_basic_blocks) * sizeof (region));
7032   rgn_bb_table = (int *) xmalloc ((n_basic_blocks) * sizeof (int));
7033   block_to_bb = (int *) xmalloc ((n_basic_blocks) * sizeof (int));
7034   containing_rgn = (int *) xmalloc ((n_basic_blocks) * sizeof (int));
7035
7036   blocks = sbitmap_alloc (n_basic_blocks);
7037   large_region_blocks = sbitmap_alloc (n_basic_blocks);
7038
7039   compute_bb_for_insn (max_uid);
7040
7041   /* Compute regions for scheduling.  */
7042   if (reload_completed
7043       || n_basic_blocks == 1
7044       || !flag_schedule_interblock)
7045     {
7046       find_single_block_region ();
7047     }
7048   else
7049     {
7050       /* Verify that a 'good' control flow graph can be built.  */
7051       if (is_cfg_nonregular ())
7052         {
7053           find_single_block_region ();
7054         }
7055       else
7056         {
7057           sbitmap *dom;
7058           struct edge_list *edge_list;
7059
7060           dom = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
7061
7062           /* The scheduler runs after flow; therefore, we can't blindly call
7063              back into find_basic_blocks since doing so could invalidate the
7064              info in global_live_at_start.
7065
7066              Consider a block consisting entirely of dead stores; after life
7067              analysis it would be a block of NOTE_INSN_DELETED notes.  If
7068              we call find_basic_blocks again, then the block would be removed
7069              entirely and invalidate our the register live information.
7070
7071              We could (should?) recompute register live information.  Doing
7072              so may even be beneficial.  */
7073           edge_list = create_edge_list ();
7074
7075           /* Compute the dominators and post dominators.  */
7076           calculate_dominance_info (NULL, dom, CDI_DOMINATORS);
7077
7078           /* build_control_flow will return nonzero if it detects unreachable
7079              blocks or any other irregularity with the cfg which prevents
7080              cross block scheduling.  */
7081           if (build_control_flow (edge_list) != 0)
7082             find_single_block_region ();
7083           else
7084             find_rgns (edge_list, dom);
7085
7086           if (sched_verbose >= 3)
7087             debug_regions ();
7088
7089           /* We are done with flow's edge list.  */
7090           free_edge_list (edge_list);
7091
7092           /* For now.  This will move as more and more of haifa is converted
7093              to using the cfg code in flow.c.  */
7094           free (dom);
7095         }
7096     }
7097
7098   deaths_in_region = (int *) xmalloc (sizeof (int) * nr_regions);
7099
7100   init_alias_analysis ();
7101
7102   if (write_symbols != NO_DEBUG)
7103     {
7104       rtx line;
7105
7106       line_note_head = (rtx *) xcalloc (n_basic_blocks, sizeof (rtx));
7107
7108       /* Save-line-note-head:
7109          Determine the line-number at the start of each basic block.
7110          This must be computed and saved now, because after a basic block's
7111          predecessor has been scheduled, it is impossible to accurately
7112          determine the correct line number for the first insn of the block.  */
7113
7114       for (b = 0; b < n_basic_blocks; b++)
7115         for (line = BLOCK_HEAD (b); line; line = PREV_INSN (line))
7116           if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
7117             {
7118               line_note_head[b] = line;
7119               break;
7120             }
7121     }
7122
7123   /* Find units used in this fuction, for visualization.  */
7124   if (sched_verbose)
7125     init_target_units ();
7126
7127   /* ??? Add a NOTE after the last insn of the last basic block.  It is not
7128      known why this is done.  */
7129
7130   insn = BLOCK_END (n_basic_blocks - 1);
7131   if (NEXT_INSN (insn) == 0
7132       || (GET_CODE (insn) != NOTE
7133           && GET_CODE (insn) != CODE_LABEL
7134           /* Don't emit a NOTE if it would end up between an unconditional
7135              jump and a BARRIER.  */
7136           && !(GET_CODE (insn) == JUMP_INSN
7137                && GET_CODE (NEXT_INSN (insn)) == BARRIER)))
7138     emit_note_after (NOTE_INSN_DELETED, BLOCK_END (n_basic_blocks - 1));
7139
7140   /* Compute INSN_REG_WEIGHT for all blocks.  We must do this before
7141      removing death notes.  */
7142   for (b = n_basic_blocks - 1; b >= 0; b--)
7143     find_insn_reg_weight (b);
7144
7145   /* Remove all death notes from the subroutine.  */
7146   for (rgn = 0; rgn < nr_regions; rgn++)
7147     {
7148       sbitmap_zero (blocks);
7149       for (b = RGN_NR_BLOCKS (rgn) - 1; b >= 0; --b)
7150         SET_BIT (blocks, rgn_bb_table[RGN_BLOCKS (rgn) + b]);
7151
7152       deaths_in_region[rgn] = count_or_remove_death_notes (blocks, 1);
7153     }
7154
7155   /* Schedule every region in the subroutine.  */
7156   for (rgn = 0; rgn < nr_regions; rgn++)
7157     schedule_region (rgn);
7158
7159   /* Update life analysis for the subroutine.  Do single block regions
7160      first so that we can verify that live_at_start didn't change.  Then
7161      do all other blocks.   */
7162   /* ??? There is an outside possibility that update_life_info, or more
7163      to the point propagate_block, could get called with non-zero flags
7164      more than once for one basic block.  This would be kinda bad if it
7165      were to happen, since REG_INFO would be accumulated twice for the
7166      block, and we'd have twice the REG_DEAD notes.
7167
7168      I'm fairly certain that this _shouldn't_ happen, since I don't think
7169      that live_at_start should change at region heads.  Not sure what the
7170      best way to test for this kind of thing...  */
7171
7172   allocate_reg_life_data ();
7173   compute_bb_for_insn (max_uid);
7174
7175   any_large_regions = 0;
7176   sbitmap_ones (large_region_blocks);
7177
7178   for (rgn = 0; rgn < nr_regions; rgn++)
7179     if (RGN_NR_BLOCKS (rgn) > 1)
7180       any_large_regions = 1;
7181     else
7182       {
7183         sbitmap_zero (blocks);
7184         SET_BIT (blocks, rgn_bb_table[RGN_BLOCKS (rgn)]);
7185         RESET_BIT (large_region_blocks, rgn_bb_table[RGN_BLOCKS (rgn)]);
7186
7187         /* Don't update reg info after reload, since that affects
7188            regs_ever_live, which should not change after reload.  */
7189         update_life_info (blocks, UPDATE_LIFE_LOCAL,
7190                           (reload_completed ? PROP_DEATH_NOTES
7191                            : PROP_DEATH_NOTES | PROP_REG_INFO));
7192
7193 #ifndef HAVE_conditional_execution
7194         /* ??? REG_DEAD notes only exist for unconditional deaths.  We need
7195            a count of the conditional plus unconditional deaths for this to
7196            work out.  */
7197         /* In the single block case, the count of registers that died should
7198            not have changed during the schedule.  */
7199         if (count_or_remove_death_notes (blocks, 0) != deaths_in_region[rgn])
7200           abort ();
7201 #endif
7202       }
7203
7204   if (any_large_regions)
7205     {
7206       update_life_info (large_region_blocks, UPDATE_LIFE_GLOBAL,
7207                         PROP_DEATH_NOTES | PROP_REG_INFO);
7208     }
7209
7210   /* Reposition the prologue and epilogue notes in case we moved the
7211      prologue/epilogue insns.  */
7212   if (reload_completed)
7213     reposition_prologue_and_epilogue_notes (get_insns ());
7214
7215   /* Delete redundant line notes.  */
7216   if (write_symbols != NO_DEBUG)
7217     rm_redundant_line_notes ();
7218
7219   if (sched_verbose)
7220     {
7221       if (reload_completed == 0 && flag_schedule_interblock)
7222         {
7223           fprintf (dump,
7224                    "\n;; Procedure interblock/speculative motions == %d/%d \n",
7225                    nr_inter, nr_spec);
7226         }
7227       else
7228         {
7229           if (nr_inter > 0)
7230             abort ();
7231         }
7232       fprintf (dump, "\n\n");
7233     }
7234
7235   /* Clean up.  */
7236   end_alias_analysis ();
7237
7238   if (true_dependency_cache)
7239     {
7240       free (true_dependency_cache);
7241       true_dependency_cache = NULL;
7242       free (anti_dependency_cache);
7243       anti_dependency_cache = NULL;
7244       free (output_dependency_cache);
7245       output_dependency_cache = NULL;
7246 #ifdef ENABLE_CHECKING
7247       free (forward_dependency_cache);
7248       forward_dependency_cache = NULL;
7249 #endif
7250     }
7251   free (rgn_table);
7252   free (rgn_bb_table);
7253   free (block_to_bb);
7254   free (containing_rgn);
7255
7256   free (h_i_d);
7257
7258   if (write_symbols != NO_DEBUG)
7259     free (line_note_head);
7260
7261   if (edge_table)
7262     {
7263       free (edge_table);
7264       edge_table = NULL;
7265     }
7266
7267   if (in_edges)
7268     {
7269       free (in_edges);
7270       in_edges = NULL;
7271     }
7272   if (out_edges)
7273     {
7274       free (out_edges);
7275       out_edges = NULL;
7276     }
7277
7278   sbitmap_free (blocks);
7279   sbitmap_free (large_region_blocks);
7280
7281   free (deaths_in_region);
7282 }
7283
7284 #endif /* INSN_SCHEDULING */