OSDN Git Service

* config/xtensa/xtensa.c (xtensa_init_machine_status): Fix
[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, 2001, 2002 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 GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 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 GCC; see the file COPYING.  If not, write to the Free
21 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 02111-1307, USA.  */
23
24 /* Instruction scheduling pass.  This file, along with sched-deps.c,
25    contains the generic parts.  The actual entry point is found for
26    the normal instruction scheduling pass is found in sched-rgn.c.
27
28    We compute insn priorities based on data dependencies.  Flow
29    analysis only creates a fraction of the data-dependencies we must
30    observe: namely, only those dependencies which the combiner can be
31    expected to use.  For this pass, we must therefore create the
32    remaining dependencies we need to observe: register dependencies,
33    memory dependencies, dependencies to keep function calls in order,
34    and the dependence between a conditional branch and the setting of
35    condition codes are all dealt with here.
36
37    The scheduler first traverses the data flow graph, starting with
38    the last instruction, and proceeding to the first, assigning values
39    to insn_priority as it goes.  This sorts the instructions
40    topologically by data dependence.
41
42    Once priorities have been established, we order the insns using
43    list scheduling.  This works as follows: starting with a list of
44    all the ready insns, and sorted according to priority number, we
45    schedule the insn from the end of the list by placing its
46    predecessors in the list according to their priority order.  We
47    consider this insn scheduled by setting the pointer to the "end" of
48    the list to point to the previous insn.  When an insn has no
49    predecessors, we either queue it until sufficient time has elapsed
50    or add it to the ready list.  As the instructions are scheduled or
51    when stalls are introduced, the queue advances and dumps insns into
52    the ready list.  When all insns down to the lowest priority have
53    been scheduled, the critical path of the basic block has been made
54    as short as possible.  The remaining insns are then scheduled in
55    remaining slots.
56
57    Function unit conflicts are resolved during forward list scheduling
58    by tracking the time when each insn is committed to the schedule
59    and from that, the time the function units it uses must be free.
60    As insns on the ready list are considered for scheduling, those
61    that would result in a blockage of the already committed insns are
62    queued until no blockage will result.
63
64    The following list shows the order in which we want to break ties
65    among insns in the ready list:
66
67    1.  choose insn with the longest path to end of bb, ties
68    broken by
69    2.  choose insn with least contribution to register pressure,
70    ties broken by
71    3.  prefer in-block upon interblock motion, ties broken by
72    4.  prefer useful upon speculative motion, ties broken by
73    5.  choose insn with largest control flow probability, ties
74    broken by
75    6.  choose insn with the least dependences upon the previously
76    scheduled insn, or finally
77    7   choose the insn which has the most insns dependent on it.
78    8.  choose insn with lowest UID.
79
80    Memory references complicate matters.  Only if we can be certain
81    that memory references are not part of the data dependency graph
82    (via true, anti, or output dependence), can we move operations past
83    memory references.  To first approximation, reads can be done
84    independently, while writes introduce dependencies.  Better
85    approximations will yield fewer dependencies.
86
87    Before reload, an extended analysis of interblock data dependences
88    is required for interblock scheduling.  This is performed in
89    compute_block_backward_dependences ().
90
91    Dependencies set up by memory references are treated in exactly the
92    same way as other dependencies, by using LOG_LINKS backward
93    dependences.  LOG_LINKS are translated into INSN_DEPEND forward
94    dependences for the purpose of forward list scheduling.
95
96    Having optimized the critical path, we may have also unduly
97    extended the lifetimes of some registers.  If an operation requires
98    that constants be loaded into registers, it is certainly desirable
99    to load those constants as early as necessary, but no earlier.
100    I.e., it will not do to load up a bunch of registers at the
101    beginning of a basic block only to use them at the end, if they
102    could be loaded later, since this may result in excessive register
103    utilization.
104
105    Note that since branches are never in basic blocks, but only end
106    basic blocks, this pass will not move branches.  But that is ok,
107    since we can use GNU's delayed branch scheduling pass to take care
108    of this case.
109
110    Also note that no further optimizations based on algebraic
111    identities are performed, so this pass would be a good one to
112    perform instruction splitting, such as breaking up a multiply
113    instruction into shifts and adds where that is profitable.
114
115    Given the memory aliasing analysis that this pass should perform,
116    it should be possible to remove redundant stores to memory, and to
117    load values from registers instead of hitting memory.
118
119    Before reload, speculative insns are moved only if a 'proof' exists
120    that no exception will be caused by this, and if no live registers
121    exist that inhibit the motion (live registers constraints are not
122    represented by data dependence edges).
123
124    This pass must update information that subsequent passes expect to
125    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
126    reg_n_calls_crossed, and reg_live_length.  Also, BLOCK_HEAD,
127    BLOCK_END.
128
129    The information in the line number notes is carefully retained by
130    this pass.  Notes that refer to the starting and ending of
131    exception regions are also carefully retained by this pass.  All
132    other NOTE insns are grouped in their same relative order at the
133    beginning of basic blocks and regions that have been scheduled.  */
134 \f
135 #include "config.h"
136 #include "system.h"
137 #include "toplev.h"
138 #include "rtl.h"
139 #include "tm_p.h"
140 #include "hard-reg-set.h"
141 #include "basic-block.h"
142 #include "regs.h"
143 #include "function.h"
144 #include "flags.h"
145 #include "insn-config.h"
146 #include "insn-attr.h"
147 #include "except.h"
148 #include "toplev.h"
149 #include "recog.h"
150 #include "sched-int.h"
151 #include "target.h"
152
153 #ifdef INSN_SCHEDULING
154
155 /* issue_rate is the number of insns that can be scheduled in the same
156    machine cycle.  It can be defined in the config/mach/mach.h file,
157    otherwise we set it to 1.  */
158
159 static int issue_rate;
160
161 /* If the following variable value is non zero, the scheduler inserts
162    bubbles (nop insns).  The value of variable affects on scheduler
163    behavior only if automaton pipeline interface with multipass
164    scheduling is used and hook dfa_bubble is defined.  */
165 int insert_schedule_bubbles_p = 0;
166
167 /* sched-verbose controls the amount of debugging output the
168    scheduler prints.  It is controlled by -fsched-verbose=N:
169    N>0 and no -DSR : the output is directed to stderr.
170    N>=10 will direct the printouts to stderr (regardless of -dSR).
171    N=1: same as -dSR.
172    N=2: bb's probabilities, detailed ready list info, unit/insn info.
173    N=3: rtl at abort point, control-flow, regions info.
174    N=5: dependences info.  */
175
176 static int sched_verbose_param = 0;
177 int sched_verbose = 0;
178
179 /* Debugging file.  All printouts are sent to dump, which is always set,
180    either to stderr, or to the dump listing file (-dRS).  */
181 FILE *sched_dump = 0;
182
183 /* Highest uid before scheduling.  */
184 static int old_max_uid;
185
186 /* fix_sched_param() is called from toplev.c upon detection
187    of the -fsched-verbose=N option.  */
188
189 void
190 fix_sched_param (param, val)
191      const char *param, *val;
192 {
193   if (!strcmp (param, "verbose"))
194     sched_verbose_param = atoi (val);
195   else
196     warning ("fix_sched_param: unknown param: %s", param);
197 }
198
199 struct haifa_insn_data *h_i_d;
200
201 #define DONE_PRIORITY   -1
202 #define MAX_PRIORITY    0x7fffffff
203 #define TAIL_PRIORITY   0x7ffffffe
204 #define LAUNCH_PRIORITY 0x7f000001
205 #define DONE_PRIORITY_P(INSN) (INSN_PRIORITY (INSN) < 0)
206 #define LOW_PRIORITY_P(INSN) ((INSN_PRIORITY (INSN) & 0x7f000000) == 0)
207
208 #define LINE_NOTE(INSN)         (h_i_d[INSN_UID (INSN)].line_note)
209 #define INSN_TICK(INSN)         (h_i_d[INSN_UID (INSN)].tick)
210
211 /* Vector indexed by basic block number giving the starting line-number
212    for each basic block.  */
213 static rtx *line_note_head;
214
215 /* List of important notes we must keep around.  This is a pointer to the
216    last element in the list.  */
217 static rtx note_list;
218
219 /* Queues, etc.  */
220
221 /* An instruction is ready to be scheduled when all insns preceding it
222    have already been scheduled.  It is important to ensure that all
223    insns which use its result will not be executed until its result
224    has been computed.  An insn is maintained in one of four structures:
225
226    (P) the "Pending" set of insns which cannot be scheduled until
227    their dependencies have been satisfied.
228    (Q) the "Queued" set of insns that can be scheduled when sufficient
229    time has passed.
230    (R) the "Ready" list of unscheduled, uncommitted insns.
231    (S) the "Scheduled" list of insns.
232
233    Initially, all insns are either "Pending" or "Ready" depending on
234    whether their dependencies are satisfied.
235
236    Insns move from the "Ready" list to the "Scheduled" list as they
237    are committed to the schedule.  As this occurs, the insns in the
238    "Pending" list have their dependencies satisfied and move to either
239    the "Ready" list or the "Queued" set depending on whether
240    sufficient time has passed to make them ready.  As time passes,
241    insns move from the "Queued" set to the "Ready" list.  Insns may
242    move from the "Ready" list to the "Queued" set if they are blocked
243    due to a function unit conflict.
244
245    The "Pending" list (P) are the insns in the INSN_DEPEND of the unscheduled
246    insns, i.e., those that are ready, queued, and pending.
247    The "Queued" set (Q) is implemented by the variable `insn_queue'.
248    The "Ready" list (R) is implemented by the variables `ready' and
249    `n_ready'.
250    The "Scheduled" list (S) is the new insn chain built by this pass.
251
252    The transition (R->S) is implemented in the scheduling loop in
253    `schedule_block' when the best insn to schedule is chosen.
254    The transition (R->Q) is implemented in `queue_insn' when an
255    insn is found to have a function unit conflict with the already
256    committed insns.
257    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
258    insns move from the ready list to the scheduled list.
259    The transition (Q->R) is implemented in 'queue_to_insn' as time
260    passes or stalls are introduced.  */
261
262 /* Implement a circular buffer to delay instructions until sufficient
263    time has passed.  For the old pipeline description interface,
264    INSN_QUEUE_SIZE is a power of two larger than MAX_BLOCKAGE and
265    MAX_READY_COST computed by genattr.c.  For the new pipeline
266    description interface, MAX_INSN_QUEUE_INDEX is a power of two minus
267    one which is larger than maximal time of instruction execution
268    computed by genattr.c on the base maximal time of functional unit
269    reservations and geting a result.  This is the longest time an
270    insn may be queued.  */
271
272 #define MAX_INSN_QUEUE_INDEX max_insn_queue_index_macro_value
273
274 static rtx *insn_queue;
275 static int q_ptr = 0;
276 static int q_size = 0;
277 #define NEXT_Q(X) (((X)+1) & MAX_INSN_QUEUE_INDEX)
278 #define NEXT_Q_AFTER(X, C) (((X)+C) & MAX_INSN_QUEUE_INDEX)
279
280 /* The following variable defines value for macro
281    MAX_INSN_QUEUE_INDEX.  */
282 static int max_insn_queue_index_macro_value;
283
284 /* The following variable value refers for all current and future
285    reservations of the processor units.  */
286 state_t curr_state;
287
288 /* The following variable value is size of memory representing all
289    current and future reservations of the processor units.  It is used
290    only by DFA based scheduler.  */
291 static size_t dfa_state_size;
292
293 /* The following array is used to find the best insn from ready when
294    the automaton pipeline interface is used.  */
295 static char *ready_try;
296
297 /* Describe the ready list of the scheduler.
298    VEC holds space enough for all insns in the current region.  VECLEN
299    says how many exactly.
300    FIRST is the index of the element with the highest priority; i.e. the
301    last one in the ready list, since elements are ordered by ascending
302    priority.
303    N_READY determines how many insns are on the ready list.  */
304
305 struct ready_list
306 {
307   rtx *vec;
308   int veclen;
309   int first;
310   int n_ready;
311 };
312
313 /* Forward declarations.  */
314
315 /* The scheduler using only DFA description should never use the
316    following five functions:  */
317 static unsigned int blockage_range PARAMS ((int, rtx));
318 static void clear_units PARAMS ((void));
319 static void schedule_unit PARAMS ((int, rtx, int));
320 static int actual_hazard PARAMS ((int, rtx, int, int));
321 static int potential_hazard PARAMS ((int, rtx, int));
322
323 static int priority PARAMS ((rtx));
324 static int rank_for_schedule PARAMS ((const PTR, const PTR));
325 static void swap_sort PARAMS ((rtx *, int));
326 static void queue_insn PARAMS ((rtx, int));
327 static void schedule_insn PARAMS ((rtx, struct ready_list *, int));
328 static void find_insn_reg_weight PARAMS ((int));
329 static void adjust_priority PARAMS ((rtx));
330 static void advance_one_cycle PARAMS ((void));
331
332 /* Notes handling mechanism:
333    =========================
334    Generally, NOTES are saved before scheduling and restored after scheduling.
335    The scheduler distinguishes between three types of notes:
336
337    (1) LINE_NUMBER notes, generated and used for debugging.  Here,
338    before scheduling a region, a pointer to the LINE_NUMBER note is
339    added to the insn following it (in save_line_notes()), and the note
340    is removed (in rm_line_notes() and unlink_line_notes()).  After
341    scheduling the region, this pointer is used for regeneration of
342    the LINE_NUMBER note (in restore_line_notes()).
343
344    (2) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
345    Before scheduling a region, a pointer to the note is added to the insn
346    that follows or precedes it.  (This happens as part of the data dependence
347    computation).  After scheduling an insn, the pointer contained in it is
348    used for regenerating the corresponding note (in reemit_notes).
349
350    (3) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
351    these notes are put in a list (in rm_other_notes() and
352    unlink_other_notes ()).  After scheduling the block, these notes are
353    inserted at the beginning of the block (in schedule_block()).  */
354
355 static rtx unlink_other_notes PARAMS ((rtx, rtx));
356 static rtx unlink_line_notes PARAMS ((rtx, rtx));
357 static rtx reemit_notes PARAMS ((rtx, rtx));
358
359 static rtx *ready_lastpos PARAMS ((struct ready_list *));
360 static void ready_sort PARAMS ((struct ready_list *));
361 static rtx ready_remove_first PARAMS ((struct ready_list *));
362
363 static void queue_to_ready PARAMS ((struct ready_list *));
364
365 static void debug_ready_list PARAMS ((struct ready_list *));
366
367 static rtx move_insn1 PARAMS ((rtx, rtx));
368 static rtx move_insn PARAMS ((rtx, rtx));
369
370 /* The following functions are used to implement multi-pass scheduling
371    on the first cycle.  It is used only for DFA based scheduler.  */
372 static rtx ready_element PARAMS ((struct ready_list *, int));
373 static rtx ready_remove PARAMS ((struct ready_list *, int));
374 static int max_issue PARAMS ((struct ready_list *, state_t, int *));
375
376 static rtx choose_ready PARAMS ((struct ready_list *));
377
378 #endif /* INSN_SCHEDULING */
379 \f
380 /* Point to state used for the current scheduling pass.  */
381 struct sched_info *current_sched_info;
382 \f
383 #ifndef INSN_SCHEDULING
384 void
385 schedule_insns (dump_file)
386      FILE *dump_file ATTRIBUTE_UNUSED;
387 {
388 }
389 #else
390
391 /* Pointer to the last instruction scheduled.  Used by rank_for_schedule,
392    so that insns independent of the last scheduled insn will be preferred
393    over dependent instructions.  */
394
395 static rtx last_scheduled_insn;
396
397 /* Compute the function units used by INSN.  This caches the value
398    returned by function_units_used.  A function unit is encoded as the
399    unit number if the value is non-negative and the compliment of a
400    mask if the value is negative.  A function unit index is the
401    non-negative encoding.  The scheduler using only DFA description
402    should never use the following function.  */
403
404 HAIFA_INLINE int
405 insn_unit (insn)
406      rtx insn;
407 {
408   int unit = INSN_UNIT (insn);
409
410   if (unit == 0)
411     {
412       recog_memoized (insn);
413
414       /* A USE insn, or something else we don't need to understand.
415          We can't pass these directly to function_units_used because it will
416          trigger a fatal error for unrecognizable insns.  */
417       if (INSN_CODE (insn) < 0)
418         unit = -1;
419       else
420         {
421           unit = function_units_used (insn);
422           /* Increment non-negative values so we can cache zero.  */
423           if (unit >= 0)
424             unit++;
425         }
426       /* We only cache 16 bits of the result, so if the value is out of
427          range, don't cache it.  */
428       if (FUNCTION_UNITS_SIZE < HOST_BITS_PER_SHORT
429           || unit >= 0
430           || (unit & ~((1 << (HOST_BITS_PER_SHORT - 1)) - 1)) == 0)
431         INSN_UNIT (insn) = unit;
432     }
433   return (unit > 0 ? unit - 1 : unit);
434 }
435
436 /* Compute the blockage range for executing INSN on UNIT.  This caches
437    the value returned by the blockage_range_function for the unit.
438    These values are encoded in an int where the upper half gives the
439    minimum value and the lower half gives the maximum value.  The
440    scheduler using only DFA description should never use the following
441    function.  */
442
443 HAIFA_INLINE static unsigned int
444 blockage_range (unit, insn)
445      int unit;
446      rtx insn;
447 {
448   unsigned int blockage = INSN_BLOCKAGE (insn);
449   unsigned int range;
450
451   if ((int) UNIT_BLOCKED (blockage) != unit + 1)
452     {
453       range = function_units[unit].blockage_range_function (insn);
454       /* We only cache the blockage range for one unit and then only if
455          the values fit.  */
456       if (HOST_BITS_PER_INT >= UNIT_BITS + 2 * BLOCKAGE_BITS)
457         INSN_BLOCKAGE (insn) = ENCODE_BLOCKAGE (unit + 1, range);
458     }
459   else
460     range = BLOCKAGE_RANGE (blockage);
461
462   return range;
463 }
464
465 /* A vector indexed by function unit instance giving the last insn to
466    use the unit.  The value of the function unit instance index for
467    unit U instance I is (U + I * FUNCTION_UNITS_SIZE).  The scheduler
468    using only DFA description should never use the following variable.  */
469 #if FUNCTION_UNITS_SIZE
470 static rtx unit_last_insn[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
471 #else
472 static rtx unit_last_insn[1];
473 #endif
474
475 /* A vector indexed by function unit instance giving the minimum time
476    when the unit will unblock based on the maximum blockage cost.  The
477    scheduler using only DFA description should never use the following
478    variable.  */
479 #if FUNCTION_UNITS_SIZE
480 static int unit_tick[FUNCTION_UNITS_SIZE * MAX_MULTIPLICITY];
481 #else
482 static int unit_tick[1];
483 #endif
484
485 /* A vector indexed by function unit number giving the number of insns
486    that remain to use the unit.  The scheduler using only DFA
487    description should never use the following variable.  */
488 #if FUNCTION_UNITS_SIZE
489 static int unit_n_insns[FUNCTION_UNITS_SIZE];
490 #else
491 static int unit_n_insns[1];
492 #endif
493
494 /* Access the unit_last_insn array.  Used by the visualization code.
495    The scheduler using only DFA description should never use the
496    following function.  */
497
498 rtx
499 get_unit_last_insn (instance)
500      int instance;
501 {
502   return unit_last_insn[instance];
503 }
504
505 /* Reset the function unit state to the null state.  */
506
507 static void
508 clear_units ()
509 {
510   memset ((char *) unit_last_insn, 0, sizeof (unit_last_insn));
511   memset ((char *) unit_tick, 0, sizeof (unit_tick));
512   memset ((char *) unit_n_insns, 0, sizeof (unit_n_insns));
513 }
514
515 /* Return the issue-delay of an insn.  The scheduler using only DFA
516    description should never use the following function.  */
517
518 HAIFA_INLINE int
519 insn_issue_delay (insn)
520      rtx insn;
521 {
522   int i, delay = 0;
523   int unit = insn_unit (insn);
524
525   /* Efficiency note: in fact, we are working 'hard' to compute a
526      value that was available in md file, and is not available in
527      function_units[] structure.  It would be nice to have this
528      value there, too.  */
529   if (unit >= 0)
530     {
531       if (function_units[unit].blockage_range_function &&
532           function_units[unit].blockage_function)
533         delay = function_units[unit].blockage_function (insn, insn);
534     }
535   else
536     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
537       if ((unit & 1) != 0 && function_units[i].blockage_range_function
538           && function_units[i].blockage_function)
539         delay = MAX (delay, function_units[i].blockage_function (insn, insn));
540
541   return delay;
542 }
543
544 /* Return the actual hazard cost of executing INSN on the unit UNIT,
545    instance INSTANCE at time CLOCK if the previous actual hazard cost
546    was COST.  The scheduler using only DFA description should never
547    use the following function.  */
548
549 HAIFA_INLINE int
550 actual_hazard_this_instance (unit, instance, insn, clock, cost)
551      int unit, instance, clock, cost;
552      rtx insn;
553 {
554   int tick = unit_tick[instance]; /* Issue time of the last issued insn.  */
555
556   if (tick - clock > cost)
557     {
558       /* The scheduler is operating forward, so unit's last insn is the
559          executing insn and INSN is the candidate insn.  We want a
560          more exact measure of the blockage if we execute INSN at CLOCK
561          given when we committed the execution of the unit's last insn.
562
563          The blockage value is given by either the unit's max blockage
564          constant, blockage range function, or blockage function.  Use
565          the most exact form for the given unit.  */
566
567       if (function_units[unit].blockage_range_function)
568         {
569           if (function_units[unit].blockage_function)
570             tick += (function_units[unit].blockage_function
571                      (unit_last_insn[instance], insn)
572                      - function_units[unit].max_blockage);
573           else
574             tick += ((int) MAX_BLOCKAGE_COST (blockage_range (unit, insn))
575                      - function_units[unit].max_blockage);
576         }
577       if (tick - clock > cost)
578         cost = tick - clock;
579     }
580   return cost;
581 }
582
583 /* Record INSN as having begun execution on the units encoded by UNIT
584    at time CLOCK.  The scheduler using only DFA description should
585    never use the following function.  */
586
587 HAIFA_INLINE static void
588 schedule_unit (unit, insn, clock)
589      int unit, clock;
590      rtx insn;
591 {
592   int i;
593
594   if (unit >= 0)
595     {
596       int instance = unit;
597 #if MAX_MULTIPLICITY > 1
598       /* Find the first free instance of the function unit and use that
599          one.  We assume that one is free.  */
600       for (i = function_units[unit].multiplicity - 1; i > 0; i--)
601         {
602           if (!actual_hazard_this_instance (unit, instance, insn, clock, 0))
603             break;
604           instance += FUNCTION_UNITS_SIZE;
605         }
606 #endif
607       unit_last_insn[instance] = insn;
608       unit_tick[instance] = (clock + function_units[unit].max_blockage);
609     }
610   else
611     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
612       if ((unit & 1) != 0)
613         schedule_unit (i, insn, clock);
614 }
615
616 /* Return the actual hazard cost of executing INSN on the units
617    encoded by UNIT at time CLOCK if the previous actual hazard cost
618    was COST.  The scheduler using only DFA description should never
619    use the following function.  */
620
621 HAIFA_INLINE static int
622 actual_hazard (unit, insn, clock, cost)
623      int unit, clock, cost;
624      rtx insn;
625 {
626   int i;
627
628   if (unit >= 0)
629     {
630       /* Find the instance of the function unit with the minimum hazard.  */
631       int instance = unit;
632       int best_cost = actual_hazard_this_instance (unit, instance, insn,
633                                                    clock, cost);
634 #if MAX_MULTIPLICITY > 1
635       int this_cost;
636
637       if (best_cost > cost)
638         {
639           for (i = function_units[unit].multiplicity - 1; i > 0; i--)
640             {
641               instance += FUNCTION_UNITS_SIZE;
642               this_cost = actual_hazard_this_instance (unit, instance, insn,
643                                                        clock, cost);
644               if (this_cost < best_cost)
645                 {
646                   best_cost = this_cost;
647                   if (this_cost <= cost)
648                     break;
649                 }
650             }
651         }
652 #endif
653       cost = MAX (cost, best_cost);
654     }
655   else
656     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
657       if ((unit & 1) != 0)
658         cost = actual_hazard (i, insn, clock, cost);
659
660   return cost;
661 }
662
663 /* Return the potential hazard cost of executing an instruction on the
664    units encoded by UNIT if the previous potential hazard cost was
665    COST.  An insn with a large blockage time is chosen in preference
666    to one with a smaller time; an insn that uses a unit that is more
667    likely to be used is chosen in preference to one with a unit that
668    is less used.  We are trying to minimize a subsequent actual
669    hazard.  The scheduler using only DFA description should never use
670    the following function.  */
671
672 HAIFA_INLINE static int
673 potential_hazard (unit, insn, cost)
674      int unit, cost;
675      rtx insn;
676 {
677   int i, ncost;
678   unsigned int minb, maxb;
679
680   if (unit >= 0)
681     {
682       minb = maxb = function_units[unit].max_blockage;
683       if (maxb > 1)
684         {
685           if (function_units[unit].blockage_range_function)
686             {
687               maxb = minb = blockage_range (unit, insn);
688               maxb = MAX_BLOCKAGE_COST (maxb);
689               minb = MIN_BLOCKAGE_COST (minb);
690             }
691
692           if (maxb > 1)
693             {
694               /* Make the number of instructions left dominate.  Make the
695                  minimum delay dominate the maximum delay.  If all these
696                  are the same, use the unit number to add an arbitrary
697                  ordering.  Other terms can be added.  */
698               ncost = minb * 0x40 + maxb;
699               ncost *= (unit_n_insns[unit] - 1) * 0x1000 + unit;
700               if (ncost > cost)
701                 cost = ncost;
702             }
703         }
704     }
705   else
706     for (i = 0, unit = ~unit; unit; i++, unit >>= 1)
707       if ((unit & 1) != 0)
708         cost = potential_hazard (i, insn, cost);
709
710   return cost;
711 }
712
713 /* Compute cost of executing INSN given the dependence LINK on the insn USED.
714    This is the number of cycles between instruction issue and
715    instruction results.  */
716
717 HAIFA_INLINE int
718 insn_cost (insn, link, used)
719      rtx insn, link, used;
720 {
721   int cost = INSN_COST (insn);
722
723   if (cost < 0)
724     {
725       /* A USE insn, or something else we don't need to
726          understand.  We can't pass these directly to
727          result_ready_cost or insn_default_latency because it will
728          trigger a fatal error for unrecognizable insns.  */
729       if (recog_memoized (insn) < 0)
730         {
731           INSN_COST (insn) = 0;
732           return 0;
733         }
734       else
735         {
736           if (targetm.sched.use_dfa_pipeline_interface
737               && (*targetm.sched.use_dfa_pipeline_interface) ())
738             cost = insn_default_latency (insn);
739           else
740             cost = result_ready_cost (insn);
741           
742           if (cost < 0)
743             cost = 0;
744           
745           INSN_COST (insn) = cost;
746         }
747     }
748
749   /* In this case estimate cost without caring how insn is used.  */
750   if (link == 0 || used == 0)
751     return cost;
752
753   /* A USE insn should never require the value used to be computed.
754      This allows the computation of a function's result and parameter
755      values to overlap the return and call.  */
756   if (recog_memoized (used) < 0)
757     cost = 0;
758   else
759     {
760       if (targetm.sched.use_dfa_pipeline_interface
761           && (*targetm.sched.use_dfa_pipeline_interface) ())
762         {
763           if (INSN_CODE (insn) >= 0)
764             {
765               if (REG_NOTE_KIND (link) == REG_DEP_ANTI)
766                 cost = 0;
767               else if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
768                 {
769                   cost = (insn_default_latency (insn)
770                           - insn_default_latency (used));
771                   if (cost <= 0)
772                     cost = 1;
773                 }
774               else if (bypass_p (insn))
775                 cost = insn_latency (insn, used);
776             }
777         }
778
779       if (targetm.sched.adjust_cost)
780         cost = (*targetm.sched.adjust_cost) (used, link, insn, cost);
781
782       if (cost < 0)
783         cost = 0;
784     }
785   
786   return cost;
787 }
788
789 /* Compute the priority number for INSN.  */
790
791 static int
792 priority (insn)
793      rtx insn;
794 {
795   rtx link;
796
797   if (! INSN_P (insn))
798     return 0;
799
800   if (! INSN_PRIORITY_KNOWN (insn))
801     {
802       int this_priority = 0;
803
804       if (INSN_DEPEND (insn) == 0)
805         this_priority = insn_cost (insn, 0, 0);
806       else
807         {
808           for (link = INSN_DEPEND (insn); link; link = XEXP (link, 1))
809             {
810               rtx next;
811               int next_priority;
812
813               if (RTX_INTEGRATED_P (link))
814                 continue;
815
816               next = XEXP (link, 0);
817
818               /* Critical path is meaningful in block boundaries only.  */
819               if (! (*current_sched_info->contributes_to_priority) (next, insn))
820                 continue;
821
822               next_priority = insn_cost (insn, link, next) + priority (next);
823               if (next_priority > this_priority)
824                 this_priority = next_priority;
825             }
826         }
827       INSN_PRIORITY (insn) = this_priority;
828       INSN_PRIORITY_KNOWN (insn) = 1;
829     }
830
831   return INSN_PRIORITY (insn);
832 }
833 \f
834 /* Macros and functions for keeping the priority queue sorted, and
835    dealing with queueing and dequeueing of instructions.  */
836
837 #define SCHED_SORT(READY, N_READY)                                   \
838 do { if ((N_READY) == 2)                                             \
839        swap_sort (READY, N_READY);                                   \
840      else if ((N_READY) > 2)                                         \
841          qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); }  \
842 while (0)
843
844 /* Returns a positive value if x is preferred; returns a negative value if
845    y is preferred.  Should never return 0, since that will make the sort
846    unstable.  */
847
848 static int
849 rank_for_schedule (x, y)
850      const PTR x;
851      const PTR y;
852 {
853   rtx tmp = *(const rtx *) y;
854   rtx tmp2 = *(const rtx *) x;
855   rtx link;
856   int tmp_class, tmp2_class, depend_count1, depend_count2;
857   int val, priority_val, weight_val, info_val;
858
859   /* Prefer insn with higher priority.  */
860   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
861   if (priority_val)
862     return priority_val;
863
864   /* Prefer an insn with smaller contribution to registers-pressure.  */
865   if (!reload_completed &&
866       (weight_val = INSN_REG_WEIGHT (tmp) - INSN_REG_WEIGHT (tmp2)))
867     return (weight_val);
868
869   info_val = (*current_sched_info->rank) (tmp, tmp2);
870   if (info_val)
871     return info_val;
872
873   /* Compare insns based on their relation to the last-scheduled-insn.  */
874   if (last_scheduled_insn)
875     {
876       /* Classify the instructions into three classes:
877          1) Data dependent on last schedule insn.
878          2) Anti/Output dependent on last scheduled insn.
879          3) Independent of last scheduled insn, or has latency of one.
880          Choose the insn from the highest numbered class if different.  */
881       link = find_insn_list (tmp, INSN_DEPEND (last_scheduled_insn));
882       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp) == 1)
883         tmp_class = 3;
884       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
885         tmp_class = 1;
886       else
887         tmp_class = 2;
888
889       link = find_insn_list (tmp2, INSN_DEPEND (last_scheduled_insn));
890       if (link == 0 || insn_cost (last_scheduled_insn, link, tmp2) == 1)
891         tmp2_class = 3;
892       else if (REG_NOTE_KIND (link) == 0)       /* Data dependence.  */
893         tmp2_class = 1;
894       else
895         tmp2_class = 2;
896
897       if ((val = tmp2_class - tmp_class))
898         return val;
899     }
900
901   /* Prefer the insn which has more later insns that depend on it.
902      This gives the scheduler more freedom when scheduling later
903      instructions at the expense of added register pressure.  */
904   depend_count1 = 0;
905   for (link = INSN_DEPEND (tmp); link; link = XEXP (link, 1))
906     depend_count1++;
907
908   depend_count2 = 0;
909   for (link = INSN_DEPEND (tmp2); link; link = XEXP (link, 1))
910     depend_count2++;
911
912   val = depend_count2 - depend_count1;
913   if (val)
914     return val;
915
916   /* If insns are equally good, sort by INSN_LUID (original insn order),
917      so that we make the sort stable.  This minimizes instruction movement,
918      thus minimizing sched's effect on debugging and cross-jumping.  */
919   return INSN_LUID (tmp) - INSN_LUID (tmp2);
920 }
921
922 /* Resort the array A in which only element at index N may be out of order.  */
923
924 HAIFA_INLINE static void
925 swap_sort (a, n)
926      rtx *a;
927      int n;
928 {
929   rtx insn = a[n - 1];
930   int i = n - 2;
931
932   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
933     {
934       a[i + 1] = a[i];
935       i -= 1;
936     }
937   a[i + 1] = insn;
938 }
939
940 /* Add INSN to the insn queue so that it can be executed at least
941    N_CYCLES after the currently executing insn.  Preserve insns
942    chain for debugging purposes.  */
943
944 HAIFA_INLINE static void
945 queue_insn (insn, n_cycles)
946      rtx insn;
947      int n_cycles;
948 {
949   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
950   rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
951   insn_queue[next_q] = link;
952   q_size += 1;
953
954   if (sched_verbose >= 2)
955     {
956       fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
957                (*current_sched_info->print_insn) (insn, 0));
958
959       fprintf (sched_dump, "queued for %d cycles.\n", n_cycles);
960     }
961 }
962
963 /* Return a pointer to the bottom of the ready list, i.e. the insn
964    with the lowest priority.  */
965
966 HAIFA_INLINE static rtx *
967 ready_lastpos (ready)
968      struct ready_list *ready;
969 {
970   if (ready->n_ready == 0)
971     abort ();
972   return ready->vec + ready->first - ready->n_ready + 1;
973 }
974
975 /* Add an element INSN to the ready list so that it ends up with the lowest
976    priority.  */
977
978 HAIFA_INLINE void
979 ready_add (ready, insn)
980      struct ready_list *ready;
981      rtx insn;
982 {
983   if (ready->first == ready->n_ready)
984     {
985       memmove (ready->vec + ready->veclen - ready->n_ready,
986                ready_lastpos (ready),
987                ready->n_ready * sizeof (rtx));
988       ready->first = ready->veclen - 1;
989     }
990   ready->vec[ready->first - ready->n_ready] = insn;
991   ready->n_ready++;
992 }
993
994 /* Remove the element with the highest priority from the ready list and
995    return it.  */
996
997 HAIFA_INLINE static rtx
998 ready_remove_first (ready)
999      struct ready_list *ready;
1000 {
1001   rtx t;
1002   if (ready->n_ready == 0)
1003     abort ();
1004   t = ready->vec[ready->first--];
1005   ready->n_ready--;
1006   /* If the queue becomes empty, reset it.  */
1007   if (ready->n_ready == 0)
1008     ready->first = ready->veclen - 1;
1009   return t;
1010 }
1011
1012 /* The following code implements multi-pass scheduling for the first
1013    cycle.  In other words, we will try to choose ready insn which
1014    permits to start maximum number of insns on the same cycle.  */
1015
1016 /* Return a pointer to the element INDEX from the ready.  INDEX for
1017    insn with the highest priority is 0, and the lowest priority has
1018    N_READY - 1.  */
1019
1020 HAIFA_INLINE static rtx
1021 ready_element (ready, index)
1022      struct ready_list *ready;
1023      int index;
1024 {
1025   if (ready->n_ready == 0 || index >= ready->n_ready)
1026     abort ();
1027   return ready->vec[ready->first - index];
1028 }
1029
1030 /* Remove the element INDEX from the ready list and return it.  INDEX
1031    for insn with the highest priority is 0, and the lowest priority
1032    has N_READY - 1.  */
1033
1034 HAIFA_INLINE static rtx
1035 ready_remove (ready, index)
1036      struct ready_list *ready;
1037      int index;
1038 {
1039   rtx t;
1040   int i;
1041
1042   if (index == 0)
1043     return ready_remove_first (ready);
1044   if (ready->n_ready == 0 || index >= ready->n_ready)
1045     abort ();
1046   t = ready->vec[ready->first - index];
1047   ready->n_ready--;
1048   for (i = index; i < ready->n_ready; i++)
1049     ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
1050   return t;
1051 }
1052
1053
1054 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
1055    macro.  */
1056
1057 HAIFA_INLINE static void
1058 ready_sort (ready)
1059      struct ready_list *ready;
1060 {
1061   rtx *first = ready_lastpos (ready);
1062   SCHED_SORT (first, ready->n_ready);
1063 }
1064
1065 /* PREV is an insn that is ready to execute.  Adjust its priority if that
1066    will help shorten or lengthen register lifetimes as appropriate.  Also
1067    provide a hook for the target to tweek itself.  */
1068
1069 HAIFA_INLINE static void
1070 adjust_priority (prev)
1071      rtx prev;
1072 {
1073   /* ??? There used to be code here to try and estimate how an insn
1074      affected register lifetimes, but it did it by looking at REG_DEAD
1075      notes, which we removed in schedule_region.  Nor did it try to
1076      take into account register pressure or anything useful like that.
1077
1078      Revisit when we have a machine model to work with and not before.  */
1079
1080   if (targetm.sched.adjust_priority)
1081     INSN_PRIORITY (prev) =
1082       (*targetm.sched.adjust_priority) (prev, INSN_PRIORITY (prev));
1083 }
1084
1085 /* Advance time on one cycle.  */
1086 HAIFA_INLINE static void
1087 advance_one_cycle ()
1088 {
1089   if (targetm.sched.use_dfa_pipeline_interface
1090       && (*targetm.sched.use_dfa_pipeline_interface) ())
1091     {
1092       if (targetm.sched.dfa_pre_cycle_insn)
1093         state_transition (curr_state,
1094                           (*targetm.sched.dfa_pre_cycle_insn) ());
1095
1096       state_transition (curr_state, NULL);
1097
1098       if (targetm.sched.dfa_post_cycle_insn)
1099         state_transition (curr_state,
1100                           (*targetm.sched.dfa_post_cycle_insn) ());
1101     }
1102 }
1103
1104 /* Clock at which the previous instruction was issued.  */
1105 static int last_clock_var;
1106
1107 /* INSN is the "currently executing insn".  Launch each insn which was
1108    waiting on INSN.  READY is the ready list which contains the insns
1109    that are ready to fire.  CLOCK is the current cycle.
1110    */
1111
1112 static void
1113 schedule_insn (insn, ready, clock)
1114      rtx insn;
1115      struct ready_list *ready;
1116      int clock;
1117 {
1118   rtx link;
1119   int unit = 0;
1120
1121   if (!targetm.sched.use_dfa_pipeline_interface
1122       || !(*targetm.sched.use_dfa_pipeline_interface) ())
1123     unit = insn_unit (insn);
1124
1125   if (targetm.sched.use_dfa_pipeline_interface
1126       && (*targetm.sched.use_dfa_pipeline_interface) ()
1127       && sched_verbose >= 1)
1128     {
1129       char buf[2048];
1130
1131       print_insn (buf, insn, 0);
1132       buf[40]=0;
1133       fprintf (sched_dump, ";;\t%3i--> %-40s:", clock, buf);
1134
1135       if (recog_memoized (insn) < 0)
1136         fprintf (sched_dump, "nothing");
1137       else
1138         print_reservation (sched_dump, insn);
1139       fputc ('\n', sched_dump);
1140     }
1141   else if (sched_verbose >= 2)
1142     {
1143       fprintf (sched_dump, ";;\t\t--> scheduling insn <<<%d>>> on unit ",
1144                INSN_UID (insn));
1145       insn_print_units (insn);
1146       fputc ('\n', sched_dump);
1147     }
1148
1149   if (!targetm.sched.use_dfa_pipeline_interface
1150       || !(*targetm.sched.use_dfa_pipeline_interface) ())
1151     {
1152       if (sched_verbose && unit == -1)
1153         visualize_no_unit (insn);
1154
1155
1156       if (MAX_BLOCKAGE > 1 || issue_rate > 1 || sched_verbose)
1157         schedule_unit (unit, insn, clock);
1158       
1159       if (INSN_DEPEND (insn) == 0)
1160         return;
1161     }
1162
1163   for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
1164     {
1165       rtx next = XEXP (link, 0);
1166       int cost = insn_cost (insn, link, next);
1167
1168       INSN_TICK (next) = MAX (INSN_TICK (next), clock + cost);
1169
1170       if ((INSN_DEP_COUNT (next) -= 1) == 0)
1171         {
1172           int effective_cost = INSN_TICK (next) - clock;
1173
1174           if (! (*current_sched_info->new_ready) (next))
1175             continue;
1176
1177           if (sched_verbose >= 2)
1178             {
1179               fprintf (sched_dump, ";;\t\tdependences resolved: insn %s ",
1180                        (*current_sched_info->print_insn) (next, 0));
1181
1182               if (effective_cost < 1)
1183                 fprintf (sched_dump, "into ready\n");
1184               else
1185                 fprintf (sched_dump, "into queue with cost=%d\n", effective_cost);
1186             }
1187
1188           /* Adjust the priority of NEXT and either put it on the ready
1189              list or queue it.  */
1190           adjust_priority (next);
1191           if (effective_cost < 1)
1192             ready_add (ready, next);
1193           else
1194             queue_insn (next, effective_cost);
1195         }
1196     }
1197
1198   /* Annotate the instruction with issue information -- TImode
1199      indicates that the instruction is expected not to be able
1200      to issue on the same cycle as the previous insn.  A machine
1201      may use this information to decide how the instruction should
1202      be aligned.  */
1203   if (reload_completed && issue_rate > 1
1204       && GET_CODE (PATTERN (insn)) != USE
1205       && GET_CODE (PATTERN (insn)) != CLOBBER)
1206     {
1207       PUT_MODE (insn, clock > last_clock_var ? TImode : VOIDmode);
1208       last_clock_var = clock;
1209     }
1210 }
1211
1212 /* Functions for handling of notes.  */
1213
1214 /* Delete notes beginning with INSN and put them in the chain
1215    of notes ended by NOTE_LIST.
1216    Returns the insn following the notes.  */
1217
1218 static rtx
1219 unlink_other_notes (insn, tail)
1220      rtx insn, tail;
1221 {
1222   rtx prev = PREV_INSN (insn);
1223
1224   while (insn != tail && GET_CODE (insn) == NOTE)
1225     {
1226       rtx next = NEXT_INSN (insn);
1227       /* Delete the note from its current position.  */
1228       if (prev)
1229         NEXT_INSN (prev) = next;
1230       if (next)
1231         PREV_INSN (next) = prev;
1232
1233       /* See sched_analyze to see how these are handled.  */
1234       if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG
1235           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_END
1236           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_BEG
1237           && NOTE_LINE_NUMBER (insn) != NOTE_INSN_EH_REGION_END)
1238         {
1239           /* Insert the note at the end of the notes list.  */
1240           PREV_INSN (insn) = note_list;
1241           if (note_list)
1242             NEXT_INSN (note_list) = insn;
1243           note_list = insn;
1244         }
1245
1246       insn = next;
1247     }
1248   return insn;
1249 }
1250
1251 /* Delete line notes beginning with INSN. Record line-number notes so
1252    they can be reused.  Returns the insn following the notes.  */
1253
1254 static rtx
1255 unlink_line_notes (insn, tail)
1256      rtx insn, tail;
1257 {
1258   rtx prev = PREV_INSN (insn);
1259
1260   while (insn != tail && GET_CODE (insn) == NOTE)
1261     {
1262       rtx next = NEXT_INSN (insn);
1263
1264       if (write_symbols != NO_DEBUG && NOTE_LINE_NUMBER (insn) > 0)
1265         {
1266           /* Delete the note from its current position.  */
1267           if (prev)
1268             NEXT_INSN (prev) = next;
1269           if (next)
1270             PREV_INSN (next) = prev;
1271
1272           /* Record line-number notes so they can be reused.  */
1273           LINE_NOTE (insn) = insn;
1274         }
1275       else
1276         prev = insn;
1277
1278       insn = next;
1279     }
1280   return insn;
1281 }
1282
1283 /* Return the head and tail pointers of BB.  */
1284
1285 void
1286 get_block_head_tail (b, headp, tailp)
1287      int b;
1288      rtx *headp;
1289      rtx *tailp;
1290 {
1291   /* HEAD and TAIL delimit the basic block being scheduled.  */
1292   rtx head = BLOCK_HEAD (b);
1293   rtx tail = BLOCK_END (b);
1294
1295   /* Don't include any notes or labels at the beginning of the
1296      basic block, or notes at the ends of basic blocks.  */
1297   while (head != tail)
1298     {
1299       if (GET_CODE (head) == NOTE)
1300         head = NEXT_INSN (head);
1301       else if (GET_CODE (tail) == NOTE)
1302         tail = PREV_INSN (tail);
1303       else if (GET_CODE (head) == CODE_LABEL)
1304         head = NEXT_INSN (head);
1305       else
1306         break;
1307     }
1308
1309   *headp = head;
1310   *tailp = tail;
1311 }
1312
1313 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ].  */
1314
1315 int
1316 no_real_insns_p (head, tail)
1317      rtx head, tail;
1318 {
1319   while (head != NEXT_INSN (tail))
1320     {
1321       if (GET_CODE (head) != NOTE && GET_CODE (head) != CODE_LABEL)
1322         return 0;
1323       head = NEXT_INSN (head);
1324     }
1325   return 1;
1326 }
1327
1328 /* Delete line notes from one block. Save them so they can be later restored
1329    (in restore_line_notes).  HEAD and TAIL are the boundaries of the
1330    block in which notes should be processed.  */
1331
1332 void
1333 rm_line_notes (head, tail)
1334      rtx head, tail;
1335 {
1336   rtx next_tail;
1337   rtx insn;
1338
1339   next_tail = NEXT_INSN (tail);
1340   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1341     {
1342       rtx prev;
1343
1344       /* Farm out notes, and maybe save them in NOTE_LIST.
1345          This is needed to keep the debugger from
1346          getting completely deranged.  */
1347       if (GET_CODE (insn) == NOTE)
1348         {
1349           prev = insn;
1350           insn = unlink_line_notes (insn, next_tail);
1351
1352           if (prev == tail)
1353             abort ();
1354           if (prev == head)
1355             abort ();
1356           if (insn == next_tail)
1357             abort ();
1358         }
1359     }
1360 }
1361
1362 /* Save line number notes for each insn in block B.  HEAD and TAIL are
1363    the boundaries of the block in which notes should be processed.  */
1364
1365 void
1366 save_line_notes (b, head, tail)
1367      int b;
1368      rtx head, tail;
1369 {
1370   rtx next_tail;
1371
1372   /* We must use the true line number for the first insn in the block
1373      that was computed and saved at the start of this pass.  We can't
1374      use the current line number, because scheduling of the previous
1375      block may have changed the current line number.  */
1376
1377   rtx line = line_note_head[b];
1378   rtx insn;
1379
1380   next_tail = NEXT_INSN (tail);
1381
1382   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1383     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
1384       line = insn;
1385     else
1386       LINE_NOTE (insn) = line;
1387 }
1388
1389 /* After a block was scheduled, insert line notes into the insns list.
1390    HEAD and TAIL are the boundaries of the block in which notes should
1391    be processed.  */
1392
1393 void
1394 restore_line_notes (head, tail)
1395      rtx head, tail;
1396 {
1397   rtx line, note, prev, new;
1398   int added_notes = 0;
1399   rtx next_tail, insn;
1400
1401   head = head;
1402   next_tail = NEXT_INSN (tail);
1403
1404   /* Determine the current line-number.  We want to know the current
1405      line number of the first insn of the block here, in case it is
1406      different from the true line number that was saved earlier.  If
1407      different, then we need a line number note before the first insn
1408      of this block.  If it happens to be the same, then we don't want to
1409      emit another line number note here.  */
1410   for (line = head; line; line = PREV_INSN (line))
1411     if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
1412       break;
1413
1414   /* Walk the insns keeping track of the current line-number and inserting
1415      the line-number notes as needed.  */
1416   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1417     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
1418       line = insn;
1419   /* This used to emit line number notes before every non-deleted note.
1420      However, this confuses a debugger, because line notes not separated
1421      by real instructions all end up at the same address.  I can find no
1422      use for line number notes before other notes, so none are emitted.  */
1423     else if (GET_CODE (insn) != NOTE
1424              && INSN_UID (insn) < old_max_uid
1425              && (note = LINE_NOTE (insn)) != 0
1426              && note != line
1427              && (line == 0
1428                  || NOTE_LINE_NUMBER (note) != NOTE_LINE_NUMBER (line)
1429                  || NOTE_SOURCE_FILE (note) != NOTE_SOURCE_FILE (line)))
1430       {
1431         line = note;
1432         prev = PREV_INSN (insn);
1433         if (LINE_NOTE (note))
1434           {
1435             /* Re-use the original line-number note.  */
1436             LINE_NOTE (note) = 0;
1437             PREV_INSN (note) = prev;
1438             NEXT_INSN (prev) = note;
1439             PREV_INSN (insn) = note;
1440             NEXT_INSN (note) = insn;
1441           }
1442         else
1443           {
1444             added_notes++;
1445             new = emit_note_after (NOTE_LINE_NUMBER (note), prev);
1446             NOTE_SOURCE_FILE (new) = NOTE_SOURCE_FILE (note);
1447             RTX_INTEGRATED_P (new) = RTX_INTEGRATED_P (note);
1448           }
1449       }
1450   if (sched_verbose && added_notes)
1451     fprintf (sched_dump, ";; added %d line-number notes\n", added_notes);
1452 }
1453
1454 /* After scheduling the function, delete redundant line notes from the
1455    insns list.  */
1456
1457 void
1458 rm_redundant_line_notes ()
1459 {
1460   rtx line = 0;
1461   rtx insn = get_insns ();
1462   int active_insn = 0;
1463   int notes = 0;
1464
1465   /* Walk the insns deleting redundant line-number notes.  Many of these
1466      are already present.  The remainder tend to occur at basic
1467      block boundaries.  */
1468   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1469     if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) > 0)
1470       {
1471         /* If there are no active insns following, INSN is redundant.  */
1472         if (active_insn == 0)
1473           {
1474             notes++;
1475             NOTE_SOURCE_FILE (insn) = 0;
1476             NOTE_LINE_NUMBER (insn) = NOTE_INSN_DELETED;
1477           }
1478         /* If the line number is unchanged, LINE is redundant.  */
1479         else if (line
1480                  && NOTE_LINE_NUMBER (line) == NOTE_LINE_NUMBER (insn)
1481                  && NOTE_SOURCE_FILE (line) == NOTE_SOURCE_FILE (insn))
1482           {
1483             notes++;
1484             NOTE_SOURCE_FILE (line) = 0;
1485             NOTE_LINE_NUMBER (line) = NOTE_INSN_DELETED;
1486             line = insn;
1487           }
1488         else
1489           line = insn;
1490         active_insn = 0;
1491       }
1492     else if (!((GET_CODE (insn) == NOTE
1493                 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED)
1494                || (GET_CODE (insn) == INSN
1495                    && (GET_CODE (PATTERN (insn)) == USE
1496                        || GET_CODE (PATTERN (insn)) == CLOBBER))))
1497       active_insn++;
1498
1499   if (sched_verbose && notes)
1500     fprintf (sched_dump, ";; deleted %d line-number notes\n", notes);
1501 }
1502
1503 /* Delete notes between HEAD and TAIL and put them in the chain
1504    of notes ended by NOTE_LIST.  */
1505
1506 void
1507 rm_other_notes (head, tail)
1508      rtx head;
1509      rtx tail;
1510 {
1511   rtx next_tail;
1512   rtx insn;
1513
1514   note_list = 0;
1515   if (head == tail && (! INSN_P (head)))
1516     return;
1517
1518   next_tail = NEXT_INSN (tail);
1519   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1520     {
1521       rtx prev;
1522
1523       /* Farm out notes, and maybe save them in NOTE_LIST.
1524          This is needed to keep the debugger from
1525          getting completely deranged.  */
1526       if (GET_CODE (insn) == NOTE)
1527         {
1528           prev = insn;
1529
1530           insn = unlink_other_notes (insn, next_tail);
1531
1532           if (prev == tail)
1533             abort ();
1534           if (prev == head)
1535             abort ();
1536           if (insn == next_tail)
1537             abort ();
1538         }
1539     }
1540 }
1541
1542 /* Functions for computation of registers live/usage info.  */
1543
1544 /* Calculate INSN_REG_WEIGHT for all insns of a block.  */
1545
1546 static void
1547 find_insn_reg_weight (b)
1548      int b;
1549 {
1550   rtx insn, next_tail, head, tail;
1551
1552   get_block_head_tail (b, &head, &tail);
1553   next_tail = NEXT_INSN (tail);
1554
1555   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
1556     {
1557       int reg_weight = 0;
1558       rtx x;
1559
1560       /* Handle register life information.  */
1561       if (! INSN_P (insn))
1562         continue;
1563
1564       /* Increment weight for each register born here.  */
1565       x = PATTERN (insn);
1566       if ((GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
1567           && register_operand (SET_DEST (x), VOIDmode))
1568         reg_weight++;
1569       else if (GET_CODE (x) == PARALLEL)
1570         {
1571           int j;
1572           for (j = XVECLEN (x, 0) - 1; j >= 0; j--)
1573             {
1574               x = XVECEXP (PATTERN (insn), 0, j);
1575               if ((GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
1576                   && register_operand (SET_DEST (x), VOIDmode))
1577                 reg_weight++;
1578             }
1579         }
1580
1581       /* Decrement weight for each register that dies here.  */
1582       for (x = REG_NOTES (insn); x; x = XEXP (x, 1))
1583         {
1584           if (REG_NOTE_KIND (x) == REG_DEAD
1585               || REG_NOTE_KIND (x) == REG_UNUSED)
1586             reg_weight--;
1587         }
1588
1589       INSN_REG_WEIGHT (insn) = reg_weight;
1590     }
1591 }
1592
1593 /* Scheduling clock, modified in schedule_block() and queue_to_ready ().  */
1594 static int clock_var;
1595
1596 /* Move insns that became ready to fire from queue to ready list.  */
1597
1598 static void
1599 queue_to_ready (ready)
1600      struct ready_list *ready;
1601 {
1602   rtx insn;
1603   rtx link;
1604
1605   q_ptr = NEXT_Q (q_ptr);
1606
1607   /* Add all pending insns that can be scheduled without stalls to the
1608      ready list.  */
1609   for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
1610     {
1611       insn = XEXP (link, 0);
1612       q_size -= 1;
1613
1614       if (sched_verbose >= 2)
1615         fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
1616                  (*current_sched_info->print_insn) (insn, 0));
1617
1618       ready_add (ready, insn);
1619       if (sched_verbose >= 2)
1620         fprintf (sched_dump, "moving to ready without stalls\n");
1621     }
1622   insn_queue[q_ptr] = 0;
1623
1624   /* If there are no ready insns, stall until one is ready and add all
1625      of the pending insns at that point to the ready list.  */
1626   if (ready->n_ready == 0)
1627     {
1628       int stalls;
1629
1630       for (stalls = 1; stalls <= MAX_INSN_QUEUE_INDEX; stalls++)
1631         {
1632           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
1633             {
1634               for (; link; link = XEXP (link, 1))
1635                 {
1636                   insn = XEXP (link, 0);
1637                   q_size -= 1;
1638
1639                   if (sched_verbose >= 2)
1640                     fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
1641                              (*current_sched_info->print_insn) (insn, 0));
1642
1643                   ready_add (ready, insn);
1644                   if (sched_verbose >= 2)
1645                     fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
1646                 }
1647               insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = 0;
1648
1649               advance_one_cycle ();
1650
1651               break;
1652             }
1653
1654           advance_one_cycle ();
1655         }
1656
1657       if ((!targetm.sched.use_dfa_pipeline_interface
1658            || !(*targetm.sched.use_dfa_pipeline_interface) ())
1659           && sched_verbose && stalls)
1660         visualize_stall_cycles (stalls);
1661
1662       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
1663       clock_var += stalls;
1664     }
1665 }
1666
1667 /* Print the ready list for debugging purposes.  Callable from debugger.  */
1668
1669 static void
1670 debug_ready_list (ready)
1671      struct ready_list *ready;
1672 {
1673   rtx *p;
1674   int i;
1675
1676   if (ready->n_ready == 0)
1677     {
1678       fprintf (sched_dump, "\n");
1679       return;
1680     }
1681
1682   p = ready_lastpos (ready);
1683   for (i = 0; i < ready->n_ready; i++)
1684     fprintf (sched_dump, "  %s", (*current_sched_info->print_insn) (p[i], 0));
1685   fprintf (sched_dump, "\n");
1686 }
1687
1688 /* move_insn1: Remove INSN from insn chain, and link it after LAST insn.  */
1689
1690 static rtx
1691 move_insn1 (insn, last)
1692      rtx insn, last;
1693 {
1694   NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (insn);
1695   PREV_INSN (NEXT_INSN (insn)) = PREV_INSN (insn);
1696
1697   NEXT_INSN (insn) = NEXT_INSN (last);
1698   PREV_INSN (NEXT_INSN (last)) = insn;
1699
1700   NEXT_INSN (last) = insn;
1701   PREV_INSN (insn) = last;
1702
1703   return insn;
1704 }
1705
1706 /* Search INSN for REG_SAVE_NOTE note pairs for
1707    NOTE_INSN_{LOOP,EHREGION}_{BEG,END}; and convert them back into
1708    NOTEs.  The REG_SAVE_NOTE note following first one is contains the
1709    saved value for NOTE_BLOCK_NUMBER which is useful for
1710    NOTE_INSN_EH_REGION_{BEG,END} NOTEs.  LAST is the last instruction
1711    output by the instruction scheduler.  Return the new value of LAST.  */
1712
1713 static rtx
1714 reemit_notes (insn, last)
1715      rtx insn;
1716      rtx last;
1717 {
1718   rtx note, retval;
1719
1720   retval = last;
1721   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
1722     {
1723       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
1724         {
1725           enum insn_note note_type = INTVAL (XEXP (note, 0));
1726
1727           last = emit_note_before (note_type, last);
1728           remove_note (insn, note);
1729           note = XEXP (note, 1);
1730           if (note_type == NOTE_INSN_EH_REGION_BEG
1731               || note_type == NOTE_INSN_EH_REGION_END)
1732             NOTE_EH_HANDLER (last) = INTVAL (XEXP (note, 0));
1733           remove_note (insn, note);
1734         }
1735     }
1736   return retval;
1737 }
1738
1739 /* Move INSN, and all insns which should be issued before it,
1740    due to SCHED_GROUP_P flag.  Reemit notes if needed.
1741
1742    Return the last insn emitted by the scheduler, which is the
1743    return value from the first call to reemit_notes.  */
1744
1745 static rtx
1746 move_insn (insn, last)
1747      rtx insn, last;
1748 {
1749   rtx retval = NULL;
1750
1751   /* If INSN has SCHED_GROUP_P set, then issue it and any other
1752      insns with SCHED_GROUP_P set first.  */
1753   while (SCHED_GROUP_P (insn))
1754     {
1755       rtx prev = PREV_INSN (insn);
1756
1757       /* Move a SCHED_GROUP_P insn.  */
1758       move_insn1 (insn, last);
1759       /* If this is the first call to reemit_notes, then record
1760          its return value.  */
1761       if (retval == NULL_RTX)
1762         retval = reemit_notes (insn, insn);
1763       else
1764         reemit_notes (insn, insn);
1765       /* Consume SCHED_GROUP_P flag.  */
1766       SCHED_GROUP_P (insn) = 0;
1767       insn = prev;
1768     }
1769
1770   /* Now move the first non SCHED_GROUP_P insn.  */
1771   move_insn1 (insn, last);
1772
1773   /* If this is the first call to reemit_notes, then record
1774      its return value.  */
1775   if (retval == NULL_RTX)
1776     retval = reemit_notes (insn, insn);
1777   else
1778     reemit_notes (insn, insn);
1779
1780   return retval;
1781 }
1782
1783 /* The following function returns maximal (or close to maximal) number
1784    of insns which can be issued on the same cycle and one of which
1785    insns is insns with the best rank (the last insn in READY).  To
1786    make this function tries different samples of ready insns.  READY
1787    is current queue `ready'.  Global array READY_TRY reflects what
1788    insns are already issued in this try.  STATE is current processor
1789    state.  If the function returns nonzero, INDEX will contain index
1790    of the best insn in READY.  The following function is used only for
1791    first cycle multipass scheduling.  */
1792
1793 static int
1794 max_issue (ready, state, index)
1795      struct ready_list *ready;
1796      state_t state;
1797      int *index;
1798 {
1799   int i, best, n, temp_index, delay;
1800   state_t temp_state;
1801   rtx insn;
1802   int max_lookahead = (*targetm.sched.first_cycle_multipass_dfa_lookahead) ();
1803
1804   if (state_dead_lock_p (state))
1805     return 0;
1806
1807   temp_state = alloca (dfa_state_size);
1808   best = 0;
1809   
1810   for (i = 0; i < ready->n_ready; i++)
1811     if (!ready_try [i])
1812       {
1813         insn = ready_element (ready, i);
1814         
1815         if (INSN_CODE (insn) < 0)
1816           continue;
1817         
1818         memcpy (temp_state, state, dfa_state_size);
1819         
1820         delay = state_transition (temp_state, insn);
1821         
1822         if (delay == 0)
1823           {
1824             if (!targetm.sched.dfa_bubble)
1825               continue;
1826             else
1827               {
1828                 int j;
1829                 rtx bubble;
1830                 
1831                 for (j = 0;
1832                      (bubble = (*targetm.sched.dfa_bubble) (j)) != NULL_RTX;
1833                      j++)
1834                   if (state_transition (temp_state, bubble) < 0
1835                       && state_transition (temp_state, insn) < 0)
1836                     break;
1837                 
1838                 if (bubble == NULL_RTX)
1839                   continue;
1840               }
1841           }
1842         else if (delay > 0)
1843           continue;
1844         
1845         --max_lookahead;
1846         
1847         if (max_lookahead < 0)
1848           break;
1849         
1850         ready_try [i] = 1;
1851
1852         n = max_issue (ready, temp_state, &temp_index);
1853         if (n > 0 || ready_try[0])
1854           n += 1;
1855
1856         if (best < n)
1857           {
1858             best = n;
1859             *index = i;
1860           }
1861         ready_try [i] = 0;
1862       }
1863   
1864   return best;
1865 }
1866
1867 /* The following function chooses insn from READY and modifies
1868    *N_READY and READY.  The following function is used only for first
1869    cycle multipass scheduling.  */
1870
1871 static rtx
1872 choose_ready (ready)
1873      struct ready_list *ready;
1874 {
1875   if (!targetm.sched.first_cycle_multipass_dfa_lookahead
1876       || (*targetm.sched.first_cycle_multipass_dfa_lookahead) () <= 0)
1877     return ready_remove_first (ready);
1878   else
1879     {
1880       /* Try to choose the better insn.  */
1881       int index;
1882
1883       if (max_issue (ready, curr_state, &index) == 0)
1884         return ready_remove_first (ready);
1885       else
1886         return ready_remove (ready, index);
1887     }
1888 }
1889
1890 /* Called from backends from targetm.sched.reorder to emit stuff into
1891    the instruction stream.  */
1892
1893 rtx
1894 sched_emit_insn (pat)
1895      rtx pat;
1896 {
1897   rtx insn = emit_insn_after (pat, last_scheduled_insn);
1898   last_scheduled_insn = insn;
1899   return insn;
1900 }
1901
1902 /* Use forward list scheduling to rearrange insns of block B in region RGN,
1903    possibly bringing insns from subsequent blocks in the same region.  */
1904
1905 void
1906 schedule_block (b, rgn_n_insns)
1907      int b;
1908      int rgn_n_insns;
1909 {
1910   struct ready_list ready;
1911   int first_cycle_insn_p;
1912   int can_issue_more;
1913   state_t temp_state = NULL;  /* It is used for multipass scheduling.  */
1914
1915   /* Head/tail info for this block.  */
1916   rtx prev_head = current_sched_info->prev_head;
1917   rtx next_tail = current_sched_info->next_tail;
1918   rtx head = NEXT_INSN (prev_head);
1919   rtx tail = PREV_INSN (next_tail);
1920
1921   /* We used to have code to avoid getting parameters moved from hard
1922      argument registers into pseudos.
1923
1924      However, it was removed when it proved to be of marginal benefit
1925      and caused problems because schedule_block and compute_forward_dependences
1926      had different notions of what the "head" insn was.  */
1927
1928   if (head == tail && (! INSN_P (head)))
1929     abort ();
1930
1931   /* Debug info.  */
1932   if (sched_verbose)
1933     {
1934       fprintf (sched_dump, ";;   ======================================================\n");
1935       fprintf (sched_dump,
1936                ";;   -- basic block %d from %d to %d -- %s reload\n",
1937                b, INSN_UID (head), INSN_UID (tail),
1938                (reload_completed ? "after" : "before"));
1939       fprintf (sched_dump, ";;   ======================================================\n");
1940       fprintf (sched_dump, "\n");
1941
1942       visualize_alloc ();
1943       init_block_visualization ();
1944     }
1945
1946   if (targetm.sched.use_dfa_pipeline_interface
1947       && (*targetm.sched.use_dfa_pipeline_interface) ())
1948     state_reset (curr_state);
1949   else
1950     clear_units ();
1951
1952   /* Allocate the ready list.  */
1953   ready.veclen = rgn_n_insns + 1 + issue_rate;
1954   ready.first = ready.veclen - 1;
1955   ready.vec = (rtx *) xmalloc (ready.veclen * sizeof (rtx));
1956   ready.n_ready = 0;
1957
1958   if (targetm.sched.use_dfa_pipeline_interface
1959       && (*targetm.sched.use_dfa_pipeline_interface) ())
1960     {
1961       /* It is used for first cycle multipass scheduling.  */
1962       temp_state = alloca (dfa_state_size);
1963       ready_try = (char *) xmalloc ((rgn_n_insns + 1) * sizeof (char));
1964       memset (ready_try, 0, (rgn_n_insns + 1) * sizeof (char));
1965     }
1966
1967   (*current_sched_info->init_ready_list) (&ready);
1968
1969   if (targetm.sched.md_init)
1970     (*targetm.sched.md_init) (sched_dump, sched_verbose, ready.veclen);
1971
1972   /* We start inserting insns after PREV_HEAD.  */
1973   last_scheduled_insn = prev_head;
1974
1975   /* Initialize INSN_QUEUE.  Q_SIZE is the total number of insns in the
1976      queue.  */
1977   q_ptr = 0;
1978   q_size = 0;
1979
1980   if (!targetm.sched.use_dfa_pipeline_interface
1981       || !(*targetm.sched.use_dfa_pipeline_interface) ())
1982     max_insn_queue_index_macro_value = INSN_QUEUE_SIZE - 1;
1983   else
1984     max_insn_queue_index_macro_value = max_insn_queue_index;
1985
1986   insn_queue = (rtx *) alloca ((MAX_INSN_QUEUE_INDEX + 1) * sizeof (rtx));
1987   memset ((char *) insn_queue, 0, (MAX_INSN_QUEUE_INDEX + 1) * sizeof (rtx));
1988   last_clock_var = -1;
1989
1990   /* Start just before the beginning of time.  */
1991   clock_var = -1;
1992
1993   /* Loop until all the insns in BB are scheduled.  */
1994   while ((*current_sched_info->schedule_more_p) ())
1995     {
1996       clock_var++;
1997
1998       advance_one_cycle ();
1999
2000       /* Add to the ready list all pending insns that can be issued now.
2001          If there are no ready insns, increment clock until one
2002          is ready and add all pending insns at that point to the ready
2003          list.  */
2004       queue_to_ready (&ready);
2005
2006       if (ready.n_ready == 0)
2007         abort ();
2008
2009       if (sched_verbose >= 2)
2010         {
2011           fprintf (sched_dump, ";;\t\tReady list after queue_to_ready:  ");
2012           debug_ready_list (&ready);
2013         }
2014
2015       /* Sort the ready list based on priority.  */
2016       ready_sort (&ready);
2017
2018       /* Allow the target to reorder the list, typically for
2019          better instruction bundling.  */
2020       if (targetm.sched.reorder)
2021         can_issue_more =
2022           (*targetm.sched.reorder) (sched_dump, sched_verbose,
2023                                     ready_lastpos (&ready),
2024                                     &ready.n_ready, clock_var);
2025       else
2026         can_issue_more = issue_rate;
2027
2028       first_cycle_insn_p = 1;
2029       for (;;)
2030         {
2031           rtx insn;
2032           int cost;
2033
2034           if (sched_verbose >= 2)
2035             {
2036               fprintf (sched_dump, ";;\tReady list (t =%3d):  ",
2037                        clock_var);
2038               debug_ready_list (&ready);
2039             }
2040
2041           if (!targetm.sched.use_dfa_pipeline_interface
2042               || !(*targetm.sched.use_dfa_pipeline_interface) ())
2043             {
2044               if (ready.n_ready == 0 || !can_issue_more
2045                   || !(*current_sched_info->schedule_more_p) ())
2046                 break;
2047               insn = choose_ready (&ready);
2048               cost = actual_hazard (insn_unit (insn), insn, clock_var, 0);
2049             }
2050           else
2051             {
2052               if (ready.n_ready == 0 || !can_issue_more
2053                   || state_dead_lock_p (curr_state)
2054                   || !(*current_sched_info->schedule_more_p) ())
2055                 break;
2056               
2057               /* Select and remove the insn from the ready list.  */
2058               insn = choose_ready (&ready);
2059               
2060               memcpy (temp_state, curr_state, dfa_state_size);
2061               if (recog_memoized (insn) < 0)
2062                 {
2063                   if (!first_cycle_insn_p
2064                       && (GET_CODE (PATTERN (insn)) == ASM_INPUT
2065                           || asm_noperands (PATTERN (insn)) >= 0))
2066                     /* This is asm insn which is tryed to be issued on the
2067                        cycle not first.  Issue it on the next cycle.  */
2068                     cost = 1;
2069                   else
2070                     /* A USE insn, or something else we don't need to
2071                        understand.  We can't pass these directly to
2072                        state_transition because it will trigger a
2073                        fatal error for unrecognizable insns.  */
2074                     cost = 0;
2075                 }
2076               else
2077                 {
2078                   cost = state_transition (temp_state, insn);
2079
2080                   if (targetm.sched.first_cycle_multipass_dfa_lookahead
2081                       && targetm.sched.dfa_bubble)
2082                     {
2083                       if (cost == 0)
2084                         {
2085                           int j;
2086                           rtx bubble;
2087                           
2088                           for (j = 0;
2089                                (bubble = (*targetm.sched.dfa_bubble) (j))
2090                                  != NULL_RTX;
2091                                j++)
2092                             {
2093                               memcpy (temp_state, curr_state, dfa_state_size);
2094                               
2095                               if (state_transition (temp_state, bubble) < 0
2096                                   && state_transition (temp_state, insn) < 0)
2097                                 break;
2098                             }
2099                           
2100                           if (bubble != NULL_RTX)
2101                             {
2102                               if (insert_schedule_bubbles_p)
2103                                 {
2104                                   rtx copy;
2105                                   
2106                                   copy = copy_rtx (PATTERN (bubble));
2107                                   emit_insn_after (copy, last_scheduled_insn);
2108                                   last_scheduled_insn
2109                                     = NEXT_INSN (last_scheduled_insn);
2110                                   INSN_CODE (last_scheduled_insn)
2111                                     = INSN_CODE (bubble);
2112                                   
2113                                   /* Annotate the same for the first insns
2114                                      scheduling by using mode.  */
2115                                   PUT_MODE (last_scheduled_insn,
2116                                             (clock_var > last_clock_var
2117                                              ? clock_var - last_clock_var
2118                                              : VOIDmode));
2119                                   last_clock_var = clock_var;
2120                                   
2121                                   if (sched_verbose >= 2)
2122                                     {
2123                                       fprintf (sched_dump,
2124                                                ";;\t\t--> scheduling bubble insn <<<%d>>>:reservation ",
2125                                                INSN_UID (last_scheduled_insn));
2126                                       
2127                                       if (recog_memoized (last_scheduled_insn)
2128                                           < 0)
2129                                         fprintf (sched_dump, "nothing");
2130                                       else
2131                                         print_reservation
2132                                           (sched_dump, last_scheduled_insn);
2133                                       
2134                                       fprintf (sched_dump, "\n");
2135                                     }
2136                                 }
2137                               cost = -1;
2138                             }
2139                         }
2140                     }
2141
2142                   if (cost < 0)
2143                     cost = 0;
2144                   else if (cost == 0)
2145                     cost = 1;
2146                 }
2147             }
2148
2149
2150           if (cost >= 1)
2151             {
2152               queue_insn (insn, cost);
2153               continue;
2154             }
2155
2156           if (! (*current_sched_info->can_schedule_ready_p) (insn))
2157             goto next;
2158
2159           last_scheduled_insn = move_insn (insn, last_scheduled_insn);
2160
2161           if (targetm.sched.use_dfa_pipeline_interface
2162               && (*targetm.sched.use_dfa_pipeline_interface) ())
2163             memcpy (curr_state, temp_state, dfa_state_size);
2164             
2165           if (targetm.sched.variable_issue)
2166             can_issue_more =
2167               (*targetm.sched.variable_issue) (sched_dump, sched_verbose,
2168                                                insn, can_issue_more);
2169           /* A naked CLOBBER or USE generates no instruction, so do
2170              not count them against the issue rate.  */
2171           else if (GET_CODE (PATTERN (insn)) != USE
2172                    && GET_CODE (PATTERN (insn)) != CLOBBER)
2173             can_issue_more--;
2174
2175           schedule_insn (insn, &ready, clock_var);
2176
2177         next:
2178           first_cycle_insn_p = 0;
2179
2180           if (targetm.sched.reorder2)
2181             {
2182               /* Sort the ready list based on priority.  */
2183               if (ready.n_ready > 0)
2184                 ready_sort (&ready);
2185               can_issue_more =
2186                 (*targetm.sched.reorder2) (sched_dump,sched_verbose,
2187                                            ready.n_ready
2188                                            ? ready_lastpos (&ready) : NULL,
2189                                            &ready.n_ready, clock_var);
2190             }
2191         }
2192
2193       if ((!targetm.sched.use_dfa_pipeline_interface
2194            || !(*targetm.sched.use_dfa_pipeline_interface) ())
2195           && sched_verbose)
2196         /* Debug info.  */
2197         visualize_scheduled_insns (clock_var);
2198     }
2199
2200   if (targetm.sched.md_finish)
2201     (*targetm.sched.md_finish) (sched_dump, sched_verbose);
2202
2203   /* Debug info.  */
2204   if (sched_verbose)
2205     {
2206       fprintf (sched_dump, ";;\tReady list (final):  ");
2207       debug_ready_list (&ready);
2208       if (!targetm.sched.use_dfa_pipeline_interface
2209           || !(*targetm.sched.use_dfa_pipeline_interface) ())
2210         print_block_visualization ("");
2211     }
2212
2213   /* Sanity check -- queue must be empty now.  Meaningless if region has
2214      multiple bbs.  */
2215   if (current_sched_info->queue_must_finish_empty && q_size != 0)
2216       abort ();
2217
2218   /* Update head/tail boundaries.  */
2219   head = NEXT_INSN (prev_head);
2220   tail = last_scheduled_insn;
2221
2222   /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
2223      previously found among the insns.  Insert them at the beginning
2224      of the insns.  */
2225   if (note_list != 0)
2226     {
2227       rtx note_head = note_list;
2228
2229       while (PREV_INSN (note_head))
2230         {
2231           note_head = PREV_INSN (note_head);
2232         }
2233
2234       PREV_INSN (note_head) = PREV_INSN (head);
2235       NEXT_INSN (PREV_INSN (head)) = note_head;
2236       PREV_INSN (head) = note_list;
2237       NEXT_INSN (note_list) = head;
2238       head = note_head;
2239     }
2240
2241   /* Debugging.  */
2242   if (sched_verbose)
2243     {
2244       fprintf (sched_dump, ";;   total time = %d\n;;   new head = %d\n",
2245                clock_var, INSN_UID (head));
2246       fprintf (sched_dump, ";;   new tail = %d\n\n",
2247                INSN_UID (tail));
2248       visualize_free ();
2249     }
2250
2251   current_sched_info->head = head;
2252   current_sched_info->tail = tail;
2253
2254   free (ready.vec);
2255
2256   if (targetm.sched.use_dfa_pipeline_interface
2257       && (*targetm.sched.use_dfa_pipeline_interface) ())
2258     free (ready_try);
2259 }
2260 \f
2261 /* Set_priorities: compute priority of each insn in the block.  */
2262
2263 int
2264 set_priorities (head, tail)
2265      rtx head, tail;
2266 {
2267   rtx insn;
2268   int n_insn;
2269
2270   rtx prev_head;
2271
2272   prev_head = PREV_INSN (head);
2273
2274   if (head == tail && (! INSN_P (head)))
2275     return 0;
2276
2277   n_insn = 0;
2278   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
2279     {
2280       if (GET_CODE (insn) == NOTE)
2281         continue;
2282
2283       if (!(SCHED_GROUP_P (insn)))
2284         n_insn++;
2285       (void) priority (insn);
2286     }
2287
2288   return n_insn;
2289 }
2290
2291 /* Initialize some global state for the scheduler.  DUMP_FILE is to be used
2292    for debugging output.  */
2293
2294 void
2295 sched_init (dump_file)
2296      FILE *dump_file;
2297 {
2298   int luid;
2299   basic_block b;
2300   rtx insn;
2301   int i;
2302
2303   /* Disable speculative loads in their presence if cc0 defined.  */
2304 #ifdef HAVE_cc0
2305   flag_schedule_speculative_load = 0;
2306 #endif
2307
2308   /* Set dump and sched_verbose for the desired debugging output.  If no
2309      dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
2310      For -fsched-verbose=N, N>=10, print everything to stderr.  */
2311   sched_verbose = sched_verbose_param;
2312   if (sched_verbose_param == 0 && dump_file)
2313     sched_verbose = 1;
2314   sched_dump = ((sched_verbose_param >= 10 || !dump_file)
2315                 ? stderr : dump_file);
2316
2317   /* Initialize issue_rate.  */
2318   if (targetm.sched.issue_rate)
2319     issue_rate = (*targetm.sched.issue_rate) ();
2320   else
2321     issue_rate = 1;
2322
2323   /* We use LUID 0 for the fake insn (UID 0) which holds dependencies for
2324      pseudos which do not cross calls.  */
2325   old_max_uid = get_max_uid () + 1;
2326
2327   h_i_d = (struct haifa_insn_data *) xcalloc (old_max_uid, sizeof (*h_i_d));
2328
2329   for (i = 0; i < old_max_uid; i++)
2330     h_i_d [i].cost = -1;
2331
2332   if (targetm.sched.use_dfa_pipeline_interface
2333       && (*targetm.sched.use_dfa_pipeline_interface) ())
2334     {
2335       if (targetm.sched.init_dfa_pre_cycle_insn)
2336         (*targetm.sched.init_dfa_pre_cycle_insn) ();
2337       
2338       if (targetm.sched.init_dfa_post_cycle_insn)
2339         (*targetm.sched.init_dfa_post_cycle_insn) ();
2340       
2341       if (targetm.sched.first_cycle_multipass_dfa_lookahead
2342           && targetm.sched.init_dfa_bubbles)
2343         (*targetm.sched.init_dfa_bubbles) ();
2344       
2345       dfa_start ();
2346       dfa_state_size = state_size ();
2347       curr_state = xmalloc (dfa_state_size);
2348     }
2349
2350   h_i_d[0].luid = 0;
2351   luid = 1;
2352   FOR_EACH_BB (b)
2353     for (insn = b->head;; insn = NEXT_INSN (insn))
2354       {
2355         INSN_LUID (insn) = luid;
2356
2357         /* Increment the next luid, unless this is a note.  We don't
2358            really need separate IDs for notes and we don't want to
2359            schedule differently depending on whether or not there are
2360            line-number notes, i.e., depending on whether or not we're
2361            generating debugging information.  */
2362         if (GET_CODE (insn) != NOTE)
2363           ++luid;
2364
2365         if (insn == b->end)
2366           break;
2367       }
2368
2369   init_dependency_caches (luid);
2370
2371   compute_bb_for_insn (old_max_uid);
2372
2373   init_alias_analysis ();
2374
2375   if (write_symbols != NO_DEBUG)
2376     {
2377       rtx line;
2378
2379       line_note_head = (rtx *) xcalloc (last_basic_block, sizeof (rtx));
2380
2381       /* Save-line-note-head:
2382          Determine the line-number at the start of each basic block.
2383          This must be computed and saved now, because after a basic block's
2384          predecessor has been scheduled, it is impossible to accurately
2385          determine the correct line number for the first insn of the block.  */
2386
2387       FOR_EACH_BB (b)
2388         {
2389           for (line = b->head; line; line = PREV_INSN (line))
2390             if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
2391               {
2392                 line_note_head[b->index] = line;
2393                 break;
2394               }
2395           /* Do a forward search as well, since we won't get to see the first
2396              notes in a basic block.  */
2397           for (line = b->head; line; line = NEXT_INSN (line))
2398             {
2399               if (INSN_P (line))
2400                 break;
2401               if (GET_CODE (line) == NOTE && NOTE_LINE_NUMBER (line) > 0)
2402                 line_note_head[b->index] = line;
2403             }
2404         }
2405     }
2406
2407   if ((!targetm.sched.use_dfa_pipeline_interface
2408        || !(*targetm.sched.use_dfa_pipeline_interface) ())
2409       && sched_verbose)
2410     /* Find units used in this function, for visualization.  */
2411     init_target_units ();
2412
2413   /* ??? Add a NOTE after the last insn of the last basic block.  It is not
2414      known why this is done.  */
2415
2416   insn = EXIT_BLOCK_PTR->prev_bb->end;
2417   if (NEXT_INSN (insn) == 0
2418       || (GET_CODE (insn) != NOTE
2419           && GET_CODE (insn) != CODE_LABEL
2420           /* Don't emit a NOTE if it would end up before a BARRIER.  */
2421           && GET_CODE (NEXT_INSN (insn)) != BARRIER))
2422     {
2423       emit_note_after (NOTE_INSN_DELETED, EXIT_BLOCK_PTR->prev_bb->end);
2424       /* Make insn to appear outside BB.  */
2425       EXIT_BLOCK_PTR->prev_bb->end = PREV_INSN (EXIT_BLOCK_PTR->prev_bb->end);
2426     }
2427
2428   /* Compute INSN_REG_WEIGHT for all blocks.  We must do this before
2429      removing death notes.  */
2430   FOR_EACH_BB_REVERSE (b)
2431     find_insn_reg_weight (b->index);
2432 }
2433
2434 /* Free global data used during insn scheduling.  */
2435
2436 void
2437 sched_finish ()
2438 {
2439   free (h_i_d);
2440
2441   if (targetm.sched.use_dfa_pipeline_interface
2442       && (*targetm.sched.use_dfa_pipeline_interface) ())
2443     {
2444       free (curr_state);
2445       dfa_finish ();
2446     }
2447   free_dependency_caches ();
2448   end_alias_analysis ();
2449   if (write_symbols != NO_DEBUG)
2450     free (line_note_head);
2451 }
2452 #endif /* INSN_SCHEDULING */