OSDN Git Service

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