OSDN Git Service

2011-05-27 Alexander Monakov <amonakov@ispras.ru>
[pf3gnuchains/gcc-fork.git] / gcc / haifa-sched.c
1 /* Instruction scheduling pass.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
6    and currently maintained by, Jim Wilson (wilson@cygnus.com)
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* 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    The following list shows the order in which we want to break ties
58    among insns in the ready list:
59
60    1.  choose insn with the longest path to end of bb, ties
61    broken by
62    2.  choose insn with least contribution to register pressure,
63    ties broken by
64    3.  prefer in-block upon interblock motion, ties broken by
65    4.  prefer useful upon speculative motion, ties broken by
66    5.  choose insn with largest control flow probability, ties
67    broken by
68    6.  choose insn with the least dependences upon the previously
69    scheduled insn, or finally
70    7   choose the insn which has the most insns dependent on it.
71    8.  choose insn with lowest UID.
72
73    Memory references complicate matters.  Only if we can be certain
74    that memory references are not part of the data dependency graph
75    (via true, anti, or output dependence), can we move operations past
76    memory references.  To first approximation, reads can be done
77    independently, while writes introduce dependencies.  Better
78    approximations will yield fewer dependencies.
79
80    Before reload, an extended analysis of interblock data dependences
81    is required for interblock scheduling.  This is performed in
82    compute_block_backward_dependences ().
83
84    Dependencies set up by memory references are treated in exactly the
85    same way as other dependencies, by using insn backward dependences
86    INSN_BACK_DEPS.  INSN_BACK_DEPS are translated into forward dependences
87    INSN_FORW_DEPS the purpose of forward list scheduling.
88
89    Having optimized the critical path, we may have also unduly
90    extended the lifetimes of some registers.  If an operation requires
91    that constants be loaded into registers, it is certainly desirable
92    to load those constants as early as necessary, but no earlier.
93    I.e., it will not do to load up a bunch of registers at the
94    beginning of a basic block only to use them at the end, if they
95    could be loaded later, since this may result in excessive register
96    utilization.
97
98    Note that since branches are never in basic blocks, but only end
99    basic blocks, this pass will not move branches.  But that is ok,
100    since we can use GNU's delayed branch scheduling pass to take care
101    of this case.
102
103    Also note that no further optimizations based on algebraic
104    identities are performed, so this pass would be a good one to
105    perform instruction splitting, such as breaking up a multiply
106    instruction into shifts and adds where that is profitable.
107
108    Given the memory aliasing analysis that this pass should perform,
109    it should be possible to remove redundant stores to memory, and to
110    load values from registers instead of hitting memory.
111
112    Before reload, speculative insns are moved only if a 'proof' exists
113    that no exception will be caused by this, and if no live registers
114    exist that inhibit the motion (live registers constraints are not
115    represented by data dependence edges).
116
117    This pass must update information that subsequent passes expect to
118    be correct.  Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
119    reg_n_calls_crossed, and reg_live_length.  Also, BB_HEAD, BB_END.
120
121    The information in the line number notes is carefully retained by
122    this pass.  Notes that refer to the starting and ending of
123    exception regions are also carefully retained by this pass.  All
124    other NOTE insns are grouped in their same relative order at the
125    beginning of basic blocks and regions that have been scheduled.  */
126 \f
127 #include "config.h"
128 #include "system.h"
129 #include "coretypes.h"
130 #include "tm.h"
131 #include "diagnostic-core.h"
132 #include "rtl.h"
133 #include "tm_p.h"
134 #include "hard-reg-set.h"
135 #include "regs.h"
136 #include "function.h"
137 #include "flags.h"
138 #include "insn-config.h"
139 #include "insn-attr.h"
140 #include "except.h"
141 #include "recog.h"
142 #include "sched-int.h"
143 #include "target.h"
144 #include "output.h"
145 #include "params.h"
146 #include "vecprim.h"
147 #include "dbgcnt.h"
148 #include "cfgloop.h"
149 #include "ira.h"
150 #include "emit-rtl.h"  /* FIXME: Can go away once crtl is moved to rtl.h.  */
151
152 #ifdef INSN_SCHEDULING
153
154 /* issue_rate is the number of insns that can be scheduled in the same
155    machine cycle.  It can be defined in the config/mach/mach.h file,
156    otherwise we set it to 1.  */
157
158 int issue_rate;
159
160 /* sched-verbose controls the amount of debugging output the
161    scheduler prints.  It is controlled by -fsched-verbose=N:
162    N>0 and no -DSR : the output is directed to stderr.
163    N>=10 will direct the printouts to stderr (regardless of -dSR).
164    N=1: same as -dSR.
165    N=2: bb's probabilities, detailed ready list info, unit/insn info.
166    N=3: rtl at abort point, control-flow, regions info.
167    N=5: dependences info.  */
168
169 int sched_verbose = 0;
170
171 /* Debugging file.  All printouts are sent to dump, which is always set,
172    either to stderr, or to the dump listing file (-dRS).  */
173 FILE *sched_dump = 0;
174
175 /* This is a placeholder for the scheduler parameters common
176    to all schedulers.  */
177 struct common_sched_info_def *common_sched_info;
178
179 #define INSN_TICK(INSN) (HID (INSN)->tick)
180 #define INTER_TICK(INSN) (HID (INSN)->inter_tick)
181
182 /* If INSN_TICK of an instruction is equal to INVALID_TICK,
183    then it should be recalculated from scratch.  */
184 #define INVALID_TICK (-(max_insn_queue_index + 1))
185 /* The minimal value of the INSN_TICK of an instruction.  */
186 #define MIN_TICK (-max_insn_queue_index)
187
188 /* List of important notes we must keep around.  This is a pointer to the
189    last element in the list.  */
190 rtx note_list;
191
192 static struct spec_info_def spec_info_var;
193 /* Description of the speculative part of the scheduling.
194    If NULL - no speculation.  */
195 spec_info_t spec_info = NULL;
196
197 /* True, if recovery block was added during scheduling of current block.
198    Used to determine, if we need to fix INSN_TICKs.  */
199 static bool haifa_recovery_bb_recently_added_p;
200
201 /* True, if recovery block was added during this scheduling pass.
202    Used to determine if we should have empty memory pools of dependencies
203    after finishing current region.  */
204 bool haifa_recovery_bb_ever_added_p;
205
206 /* Counters of different types of speculative instructions.  */
207 static int nr_begin_data, nr_be_in_data, nr_begin_control, nr_be_in_control;
208
209 /* Array used in {unlink, restore}_bb_notes.  */
210 static rtx *bb_header = 0;
211
212 /* Basic block after which recovery blocks will be created.  */
213 static basic_block before_recovery;
214
215 /* Basic block just before the EXIT_BLOCK and after recovery, if we have
216    created it.  */
217 basic_block after_recovery;
218
219 /* FALSE if we add bb to another region, so we don't need to initialize it.  */
220 bool adding_bb_to_current_region_p = true;
221
222 /* Queues, etc.  */
223
224 /* An instruction is ready to be scheduled when all insns preceding it
225    have already been scheduled.  It is important to ensure that all
226    insns which use its result will not be executed until its result
227    has been computed.  An insn is maintained in one of four structures:
228
229    (P) the "Pending" set of insns which cannot be scheduled until
230    their dependencies have been satisfied.
231    (Q) the "Queued" set of insns that can be scheduled when sufficient
232    time has passed.
233    (R) the "Ready" list of unscheduled, uncommitted insns.
234    (S) the "Scheduled" list of insns.
235
236    Initially, all insns are either "Pending" or "Ready" depending on
237    whether their dependencies are satisfied.
238
239    Insns move from the "Ready" list to the "Scheduled" list as they
240    are committed to the schedule.  As this occurs, the insns in the
241    "Pending" list have their dependencies satisfied and move to either
242    the "Ready" list or the "Queued" set depending on whether
243    sufficient time has passed to make them ready.  As time passes,
244    insns move from the "Queued" set to the "Ready" list.
245
246    The "Pending" list (P) are the insns in the INSN_FORW_DEPS of the
247    unscheduled insns, i.e., those that are ready, queued, and pending.
248    The "Queued" set (Q) is implemented by the variable `insn_queue'.
249    The "Ready" list (R) is implemented by the variables `ready' and
250    `n_ready'.
251    The "Scheduled" list (S) is the new insn chain built by this pass.
252
253    The transition (R->S) is implemented in the scheduling loop in
254    `schedule_block' when the best insn to schedule is chosen.
255    The transitions (P->R and P->Q) are implemented in `schedule_insn' as
256    insns move from the ready list to the scheduled list.
257    The transition (Q->R) is implemented in 'queue_to_insn' as time
258    passes or stalls are introduced.  */
259
260 /* Implement a circular buffer to delay instructions until sufficient
261    time has passed.  For the new pipeline description interface,
262    MAX_INSN_QUEUE_INDEX is a power of two minus one which is not less
263    than maximal time of instruction execution computed by genattr.c on
264    the base maximal time of functional unit reservations and getting a
265    result.  This is the longest time an insn may be queued.  */
266
267 static rtx *insn_queue;
268 static int q_ptr = 0;
269 static int q_size = 0;
270 #define NEXT_Q(X) (((X)+1) & max_insn_queue_index)
271 #define NEXT_Q_AFTER(X, C) (((X)+C) & max_insn_queue_index)
272
273 #define QUEUE_SCHEDULED (-3)
274 #define QUEUE_NOWHERE   (-2)
275 #define QUEUE_READY     (-1)
276 /* QUEUE_SCHEDULED - INSN is scheduled.
277    QUEUE_NOWHERE   - INSN isn't scheduled yet and is neither in
278    queue or ready list.
279    QUEUE_READY     - INSN is in ready list.
280    N >= 0 - INSN queued for X [where NEXT_Q_AFTER (q_ptr, X) == N] cycles.  */
281
282 #define QUEUE_INDEX(INSN) (HID (INSN)->queue_index)
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.  */
290 size_t dfa_state_size;
291
292 /* The following array is used to find the best insn from ready when
293    the automaton pipeline interface is used.  */
294 char *ready_try = NULL;
295
296 /* The ready list.  */
297 struct ready_list ready = {NULL, 0, 0, 0, 0};
298
299 /* The pointer to the ready list (to be removed).  */
300 static struct ready_list *readyp = &ready;
301
302 /* Scheduling clock.  */
303 static int clock_var;
304
305 /* This records the actual schedule.  It is built up during the main phase
306    of schedule_block, and afterwards used to reorder the insns in the RTL.  */
307 static VEC(rtx, heap) *scheduled_insns;
308
309 static int may_trap_exp (const_rtx, int);
310
311 /* Nonzero iff the address is comprised from at most 1 register.  */
312 #define CONST_BASED_ADDRESS_P(x)                        \
313   (REG_P (x)                                    \
314    || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS   \
315         || (GET_CODE (x) == LO_SUM))                    \
316        && (CONSTANT_P (XEXP (x, 0))                     \
317            || CONSTANT_P (XEXP (x, 1)))))
318
319 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
320    as found by analyzing insn's expression.  */
321
322 \f
323 static int haifa_luid_for_non_insn (rtx x);
324
325 /* Haifa version of sched_info hooks common to all headers.  */
326 const struct common_sched_info_def haifa_common_sched_info =
327   {
328     NULL, /* fix_recovery_cfg */
329     NULL, /* add_block */
330     NULL, /* estimate_number_of_insns */
331     haifa_luid_for_non_insn, /* luid_for_non_insn */
332     SCHED_PASS_UNKNOWN /* sched_pass_id */
333   };
334
335 /* Mapping from instruction UID to its Logical UID.  */
336 VEC (int, heap) *sched_luids = NULL;
337
338 /* Next LUID to assign to an instruction.  */
339 int sched_max_luid = 1;
340
341 /* Haifa Instruction Data.  */
342 VEC (haifa_insn_data_def, heap) *h_i_d = NULL;
343
344 void (* sched_init_only_bb) (basic_block, basic_block);
345
346 /* Split block function.  Different schedulers might use different functions
347    to handle their internal data consistent.  */
348 basic_block (* sched_split_block) (basic_block, rtx);
349
350 /* Create empty basic block after the specified block.  */
351 basic_block (* sched_create_empty_bb) (basic_block);
352
353 static int
354 may_trap_exp (const_rtx x, int is_store)
355 {
356   enum rtx_code code;
357
358   if (x == 0)
359     return TRAP_FREE;
360   code = GET_CODE (x);
361   if (is_store)
362     {
363       if (code == MEM && may_trap_p (x))
364         return TRAP_RISKY;
365       else
366         return TRAP_FREE;
367     }
368   if (code == MEM)
369     {
370       /* The insn uses memory:  a volatile load.  */
371       if (MEM_VOLATILE_P (x))
372         return IRISKY;
373       /* An exception-free load.  */
374       if (!may_trap_p (x))
375         return IFREE;
376       /* A load with 1 base register, to be further checked.  */
377       if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
378         return PFREE_CANDIDATE;
379       /* No info on the load, to be further checked.  */
380       return PRISKY_CANDIDATE;
381     }
382   else
383     {
384       const char *fmt;
385       int i, insn_class = TRAP_FREE;
386
387       /* Neither store nor load, check if it may cause a trap.  */
388       if (may_trap_p (x))
389         return TRAP_RISKY;
390       /* Recursive step: walk the insn...  */
391       fmt = GET_RTX_FORMAT (code);
392       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
393         {
394           if (fmt[i] == 'e')
395             {
396               int tmp_class = may_trap_exp (XEXP (x, i), is_store);
397               insn_class = WORST_CLASS (insn_class, tmp_class);
398             }
399           else if (fmt[i] == 'E')
400             {
401               int j;
402               for (j = 0; j < XVECLEN (x, i); j++)
403                 {
404                   int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
405                   insn_class = WORST_CLASS (insn_class, tmp_class);
406                   if (insn_class == TRAP_RISKY || insn_class == IRISKY)
407                     break;
408                 }
409             }
410           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
411             break;
412         }
413       return insn_class;
414     }
415 }
416
417 /* Classifies rtx X of an insn for the purpose of verifying that X can be
418    executed speculatively (and consequently the insn can be moved
419    speculatively), by examining X, returning:
420    TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
421    TRAP_FREE: non-load insn.
422    IFREE: load from a globally safe location.
423    IRISKY: volatile load.
424    PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
425    being either PFREE or PRISKY.  */
426
427 static int
428 haifa_classify_rtx (const_rtx x)
429 {
430   int tmp_class = TRAP_FREE;
431   int insn_class = TRAP_FREE;
432   enum rtx_code code;
433
434   if (GET_CODE (x) == PARALLEL)
435     {
436       int i, len = XVECLEN (x, 0);
437
438       for (i = len - 1; i >= 0; i--)
439         {
440           tmp_class = haifa_classify_rtx (XVECEXP (x, 0, i));
441           insn_class = WORST_CLASS (insn_class, tmp_class);
442           if (insn_class == TRAP_RISKY || insn_class == IRISKY)
443             break;
444         }
445     }
446   else
447     {
448       code = GET_CODE (x);
449       switch (code)
450         {
451         case CLOBBER:
452           /* Test if it is a 'store'.  */
453           tmp_class = may_trap_exp (XEXP (x, 0), 1);
454           break;
455         case SET:
456           /* Test if it is a store.  */
457           tmp_class = may_trap_exp (SET_DEST (x), 1);
458           if (tmp_class == TRAP_RISKY)
459             break;
460           /* Test if it is a load.  */
461           tmp_class =
462             WORST_CLASS (tmp_class,
463                          may_trap_exp (SET_SRC (x), 0));
464           break;
465         case COND_EXEC:
466           tmp_class = haifa_classify_rtx (COND_EXEC_CODE (x));
467           if (tmp_class == TRAP_RISKY)
468             break;
469           tmp_class = WORST_CLASS (tmp_class,
470                                    may_trap_exp (COND_EXEC_TEST (x), 0));
471           break;
472         case TRAP_IF:
473           tmp_class = TRAP_RISKY;
474           break;
475         default:;
476         }
477       insn_class = tmp_class;
478     }
479
480   return insn_class;
481 }
482
483 int
484 haifa_classify_insn (const_rtx insn)
485 {
486   return haifa_classify_rtx (PATTERN (insn));
487 }
488
489 /* Forward declarations.  */
490
491 static int priority (rtx);
492 static int rank_for_schedule (const void *, const void *);
493 static void swap_sort (rtx *, int);
494 static void queue_insn (rtx, int, const char *);
495 static int schedule_insn (rtx);
496 static void adjust_priority (rtx);
497 static void advance_one_cycle (void);
498 static void extend_h_i_d (void);
499
500
501 /* Notes handling mechanism:
502    =========================
503    Generally, NOTES are saved before scheduling and restored after scheduling.
504    The scheduler distinguishes between two types of notes:
505
506    (1) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
507    Before scheduling a region, a pointer to the note is added to the insn
508    that follows or precedes it.  (This happens as part of the data dependence
509    computation).  After scheduling an insn, the pointer contained in it is
510    used for regenerating the corresponding note (in reemit_notes).
511
512    (2) All other notes (e.g. INSN_DELETED):  Before scheduling a block,
513    these notes are put in a list (in rm_other_notes() and
514    unlink_other_notes ()).  After scheduling the block, these notes are
515    inserted at the beginning of the block (in schedule_block()).  */
516
517 static void ready_add (struct ready_list *, rtx, bool);
518 static rtx ready_remove_first (struct ready_list *);
519 static rtx ready_remove_first_dispatch (struct ready_list *ready);
520
521 static void queue_to_ready (struct ready_list *);
522 static int early_queue_to_ready (state_t, struct ready_list *);
523
524 static void debug_ready_list (struct ready_list *);
525
526 /* The following functions are used to implement multi-pass scheduling
527    on the first cycle.  */
528 static rtx ready_remove (struct ready_list *, int);
529 static void ready_remove_insn (rtx);
530
531 static void fix_inter_tick (rtx, rtx);
532 static int fix_tick_ready (rtx);
533 static void change_queue_index (rtx, int);
534
535 /* The following functions are used to implement scheduling of data/control
536    speculative instructions.  */
537
538 static void extend_h_i_d (void);
539 static void init_h_i_d (rtx);
540 static void generate_recovery_code (rtx);
541 static void process_insn_forw_deps_be_in_spec (rtx, rtx, ds_t);
542 static void begin_speculative_block (rtx);
543 static void add_to_speculative_block (rtx);
544 static void init_before_recovery (basic_block *);
545 static void create_check_block_twin (rtx, bool);
546 static void fix_recovery_deps (basic_block);
547 static void haifa_change_pattern (rtx, rtx);
548 static void dump_new_block_header (int, basic_block, rtx, rtx);
549 static void restore_bb_notes (basic_block);
550 static void fix_jump_move (rtx);
551 static void move_block_after_check (rtx);
552 static void move_succs (VEC(edge,gc) **, basic_block);
553 static void sched_remove_insn (rtx);
554 static void clear_priorities (rtx, rtx_vec_t *);
555 static void calc_priorities (rtx_vec_t);
556 static void add_jump_dependencies (rtx, rtx);
557 #ifdef ENABLE_CHECKING
558 static int has_edge_p (VEC(edge,gc) *, int);
559 static void check_cfg (rtx, rtx);
560 #endif
561
562 #endif /* INSN_SCHEDULING */
563 \f
564 /* Point to state used for the current scheduling pass.  */
565 struct haifa_sched_info *current_sched_info;
566 \f
567 #ifndef INSN_SCHEDULING
568 void
569 schedule_insns (void)
570 {
571 }
572 #else
573
574 /* Do register pressure sensitive insn scheduling if the flag is set
575    up.  */
576 bool sched_pressure_p;
577
578 /* Map regno -> its pressure class.  The map defined only when
579    SCHED_PRESSURE_P is true.  */
580 enum reg_class *sched_regno_pressure_class;
581
582 /* The current register pressure.  Only elements corresponding pressure
583    classes are defined.  */
584 static int curr_reg_pressure[N_REG_CLASSES];
585
586 /* Saved value of the previous array.  */
587 static int saved_reg_pressure[N_REG_CLASSES];
588
589 /* Register living at given scheduling point.  */
590 static bitmap curr_reg_live;
591
592 /* Saved value of the previous array.  */
593 static bitmap saved_reg_live;
594
595 /* Registers mentioned in the current region.  */
596 static bitmap region_ref_regs;
597
598 /* Initiate register pressure relative info for scheduling the current
599    region.  Currently it is only clearing register mentioned in the
600    current region.  */
601 void
602 sched_init_region_reg_pressure_info (void)
603 {
604   bitmap_clear (region_ref_regs);
605 }
606
607 /* Update current register pressure related info after birth (if
608    BIRTH_P) or death of register REGNO.  */
609 static void
610 mark_regno_birth_or_death (int regno, bool birth_p)
611 {
612   enum reg_class pressure_class;
613
614   pressure_class = sched_regno_pressure_class[regno];
615   if (regno >= FIRST_PSEUDO_REGISTER)
616     {
617       if (pressure_class != NO_REGS)
618         {
619           if (birth_p)
620             {
621               bitmap_set_bit (curr_reg_live, regno);
622               curr_reg_pressure[pressure_class]
623                 += (ira_reg_class_max_nregs
624                     [pressure_class][PSEUDO_REGNO_MODE (regno)]);
625             }
626           else
627             {
628               bitmap_clear_bit (curr_reg_live, regno);
629               curr_reg_pressure[pressure_class]
630                 -= (ira_reg_class_max_nregs
631                     [pressure_class][PSEUDO_REGNO_MODE (regno)]);
632             }
633         }
634     }
635   else if (pressure_class != NO_REGS
636            && ! TEST_HARD_REG_BIT (ira_no_alloc_regs, regno))
637     {
638       if (birth_p)
639         {
640           bitmap_set_bit (curr_reg_live, regno);
641           curr_reg_pressure[pressure_class]++;
642         }
643       else
644         {
645           bitmap_clear_bit (curr_reg_live, regno);
646           curr_reg_pressure[pressure_class]--;
647         }
648     }
649 }
650
651 /* Initiate current register pressure related info from living
652    registers given by LIVE.  */
653 static void
654 initiate_reg_pressure_info (bitmap live)
655 {
656   int i;
657   unsigned int j;
658   bitmap_iterator bi;
659
660   for (i = 0; i < ira_pressure_classes_num; i++)
661     curr_reg_pressure[ira_pressure_classes[i]] = 0;
662   bitmap_clear (curr_reg_live);
663   EXECUTE_IF_SET_IN_BITMAP (live, 0, j, bi)
664     if (current_nr_blocks == 1 || bitmap_bit_p (region_ref_regs, j))
665       mark_regno_birth_or_death (j, true);
666 }
667
668 /* Mark registers in X as mentioned in the current region.  */
669 static void
670 setup_ref_regs (rtx x)
671 {
672   int i, j, regno;
673   const RTX_CODE code = GET_CODE (x);
674   const char *fmt;
675
676   if (REG_P (x))
677     {
678       regno = REGNO (x);
679       if (HARD_REGISTER_NUM_P (regno))
680         bitmap_set_range (region_ref_regs, regno,
681                           hard_regno_nregs[regno][GET_MODE (x)]);
682       else
683         bitmap_set_bit (region_ref_regs, REGNO (x));
684       return;
685     }
686   fmt = GET_RTX_FORMAT (code);
687   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
688     if (fmt[i] == 'e')
689       setup_ref_regs (XEXP (x, i));
690     else if (fmt[i] == 'E')
691       {
692         for (j = 0; j < XVECLEN (x, i); j++)
693           setup_ref_regs (XVECEXP (x, i, j));
694       }
695 }
696
697 /* Initiate current register pressure related info at the start of
698    basic block BB.  */
699 static void
700 initiate_bb_reg_pressure_info (basic_block bb)
701 {
702   unsigned int i ATTRIBUTE_UNUSED;
703   rtx insn;
704
705   if (current_nr_blocks > 1)
706     FOR_BB_INSNS (bb, insn)
707       if (NONDEBUG_INSN_P (insn))
708         setup_ref_regs (PATTERN (insn));
709   initiate_reg_pressure_info (df_get_live_in (bb));
710 #ifdef EH_RETURN_DATA_REGNO
711   if (bb_has_eh_pred (bb))
712     for (i = 0; ; ++i)
713       {
714         unsigned int regno = EH_RETURN_DATA_REGNO (i);
715
716         if (regno == INVALID_REGNUM)
717           break;
718         if (! bitmap_bit_p (df_get_live_in (bb), regno))
719           mark_regno_birth_or_death (regno, true);
720       }
721 #endif
722 }
723
724 /* Save current register pressure related info.  */
725 static void
726 save_reg_pressure (void)
727 {
728   int i;
729
730   for (i = 0; i < ira_pressure_classes_num; i++)
731     saved_reg_pressure[ira_pressure_classes[i]]
732       = curr_reg_pressure[ira_pressure_classes[i]];
733   bitmap_copy (saved_reg_live, curr_reg_live);
734 }
735
736 /* Restore saved register pressure related info.  */
737 static void
738 restore_reg_pressure (void)
739 {
740   int i;
741
742   for (i = 0; i < ira_pressure_classes_num; i++)
743     curr_reg_pressure[ira_pressure_classes[i]]
744       = saved_reg_pressure[ira_pressure_classes[i]];
745   bitmap_copy (curr_reg_live, saved_reg_live);
746 }
747
748 /* Return TRUE if the register is dying after its USE.  */
749 static bool
750 dying_use_p (struct reg_use_data *use)
751 {
752   struct reg_use_data *next;
753
754   for (next = use->next_regno_use; next != use; next = next->next_regno_use)
755     if (NONDEBUG_INSN_P (next->insn)
756         && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
757       return false;
758   return true;
759 }
760
761 /* Print info about the current register pressure and its excess for
762    each pressure class.  */
763 static void
764 print_curr_reg_pressure (void)
765 {
766   int i;
767   enum reg_class cl;
768
769   fprintf (sched_dump, ";;\t");
770   for (i = 0; i < ira_pressure_classes_num; i++)
771     {
772       cl = ira_pressure_classes[i];
773       gcc_assert (curr_reg_pressure[cl] >= 0);
774       fprintf (sched_dump, "  %s:%d(%d)", reg_class_names[cl],
775                curr_reg_pressure[cl],
776                curr_reg_pressure[cl] - ira_available_class_regs[cl]);
777     }
778   fprintf (sched_dump, "\n");
779 }
780
781 /* Pointer to the last instruction scheduled.  */
782 static rtx last_scheduled_insn;
783
784 /* Pointer to the last nondebug instruction scheduled within the
785    block, or the prev_head of the scheduling block.  Used by
786    rank_for_schedule, so that insns independent of the last scheduled
787    insn will be preferred over dependent instructions.  */
788 static rtx last_nondebug_scheduled_insn;
789
790 /* Pointer that iterates through the list of unscheduled insns if we
791    have a dbg_cnt enabled.  It always points at an insn prior to the
792    first unscheduled one.  */
793 static rtx nonscheduled_insns_begin;
794
795 /* Cached cost of the instruction.  Use below function to get cost of the
796    insn.  -1 here means that the field is not initialized.  */
797 #define INSN_COST(INSN) (HID (INSN)->cost)
798
799 /* Compute cost of executing INSN.
800    This is the number of cycles between instruction issue and
801    instruction results.  */
802 int
803 insn_cost (rtx insn)
804 {
805   int cost;
806
807   if (sel_sched_p ())
808     {
809       if (recog_memoized (insn) < 0)
810         return 0;
811
812       cost = insn_default_latency (insn);
813       if (cost < 0)
814         cost = 0;
815
816       return cost;
817     }
818
819   cost = INSN_COST (insn);
820
821   if (cost < 0)
822     {
823       /* A USE insn, or something else we don't need to
824          understand.  We can't pass these directly to
825          result_ready_cost or insn_default_latency because it will
826          trigger a fatal error for unrecognizable insns.  */
827       if (recog_memoized (insn) < 0)
828         {
829           INSN_COST (insn) = 0;
830           return 0;
831         }
832       else
833         {
834           cost = insn_default_latency (insn);
835           if (cost < 0)
836             cost = 0;
837
838           INSN_COST (insn) = cost;
839         }
840     }
841
842   return cost;
843 }
844
845 /* Compute cost of dependence LINK.
846    This is the number of cycles between instruction issue and
847    instruction results.
848    ??? We also use this function to call recog_memoized on all insns.  */
849 int
850 dep_cost_1 (dep_t link, dw_t dw)
851 {
852   rtx insn = DEP_PRO (link);
853   rtx used = DEP_CON (link);
854   int cost;
855
856   /* A USE insn should never require the value used to be computed.
857      This allows the computation of a function's result and parameter
858      values to overlap the return and call.  We don't care about the
859      dependence cost when only decreasing register pressure.  */
860   if (recog_memoized (used) < 0)
861     {
862       cost = 0;
863       recog_memoized (insn);
864     }
865   else
866     {
867       enum reg_note dep_type = DEP_TYPE (link);
868
869       cost = insn_cost (insn);
870
871       if (INSN_CODE (insn) >= 0)
872         {
873           if (dep_type == REG_DEP_ANTI)
874             cost = 0;
875           else if (dep_type == REG_DEP_OUTPUT)
876             {
877               cost = (insn_default_latency (insn)
878                       - insn_default_latency (used));
879               if (cost <= 0)
880                 cost = 1;
881             }
882           else if (bypass_p (insn))
883             cost = insn_latency (insn, used);
884         }
885
886
887       if (targetm.sched.adjust_cost_2)
888         cost = targetm.sched.adjust_cost_2 (used, (int) dep_type, insn, cost,
889                                             dw);
890       else if (targetm.sched.adjust_cost != NULL)
891         {
892           /* This variable is used for backward compatibility with the
893              targets.  */
894           rtx dep_cost_rtx_link = alloc_INSN_LIST (NULL_RTX, NULL_RTX);
895
896           /* Make it self-cycled, so that if some tries to walk over this
897              incomplete list he/she will be caught in an endless loop.  */
898           XEXP (dep_cost_rtx_link, 1) = dep_cost_rtx_link;
899
900           /* Targets use only REG_NOTE_KIND of the link.  */
901           PUT_REG_NOTE_KIND (dep_cost_rtx_link, DEP_TYPE (link));
902
903           cost = targetm.sched.adjust_cost (used, dep_cost_rtx_link,
904                                             insn, cost);
905
906           free_INSN_LIST_node (dep_cost_rtx_link);
907         }
908
909       if (cost < 0)
910         cost = 0;
911     }
912
913   return cost;
914 }
915
916 /* Compute cost of dependence LINK.
917    This is the number of cycles between instruction issue and
918    instruction results.  */
919 int
920 dep_cost (dep_t link)
921 {
922   return dep_cost_1 (link, 0);
923 }
924
925 /* Use this sel-sched.c friendly function in reorder2 instead of increasing
926    INSN_PRIORITY explicitly.  */
927 void
928 increase_insn_priority (rtx insn, int amount)
929 {
930   if (!sel_sched_p ())
931     {
932       /* We're dealing with haifa-sched.c INSN_PRIORITY.  */
933       if (INSN_PRIORITY_KNOWN (insn))
934           INSN_PRIORITY (insn) += amount;
935     }
936   else
937     {
938       /* In sel-sched.c INSN_PRIORITY is not kept up to date.
939          Use EXPR_PRIORITY instead. */
940       sel_add_to_insn_priority (insn, amount);
941     }
942 }
943
944 /* Return 'true' if DEP should be included in priority calculations.  */
945 static bool
946 contributes_to_priority_p (dep_t dep)
947 {
948   if (DEBUG_INSN_P (DEP_CON (dep))
949       || DEBUG_INSN_P (DEP_PRO (dep)))
950     return false;
951
952   /* Critical path is meaningful in block boundaries only.  */
953   if (!current_sched_info->contributes_to_priority (DEP_CON (dep),
954                                                     DEP_PRO (dep)))
955     return false;
956
957   /* If flag COUNT_SPEC_IN_CRITICAL_PATH is set,
958      then speculative instructions will less likely be
959      scheduled.  That is because the priority of
960      their producers will increase, and, thus, the
961      producers will more likely be scheduled, thus,
962      resolving the dependence.  */
963   if (sched_deps_info->generate_spec_deps
964       && !(spec_info->flags & COUNT_SPEC_IN_CRITICAL_PATH)
965       && (DEP_STATUS (dep) & SPECULATIVE))
966     return false;
967
968   return true;
969 }
970
971 /* Compute the number of nondebug forward deps of an insn.  */
972
973 static int
974 dep_list_size (rtx insn)
975 {
976   sd_iterator_def sd_it;
977   dep_t dep;
978   int dbgcount = 0, nodbgcount = 0;
979
980   if (!MAY_HAVE_DEBUG_INSNS)
981     return sd_lists_size (insn, SD_LIST_FORW);
982
983   FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
984     {
985       if (DEBUG_INSN_P (DEP_CON (dep)))
986         dbgcount++;
987       else if (!DEBUG_INSN_P (DEP_PRO (dep)))
988         nodbgcount++;
989     }
990
991   gcc_assert (dbgcount + nodbgcount == sd_lists_size (insn, SD_LIST_FORW));
992
993   return nodbgcount;
994 }
995
996 /* Compute the priority number for INSN.  */
997 static int
998 priority (rtx insn)
999 {
1000   if (! INSN_P (insn))
1001     return 0;
1002
1003   /* We should not be interested in priority of an already scheduled insn.  */
1004   gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
1005
1006   if (!INSN_PRIORITY_KNOWN (insn))
1007     {
1008       int this_priority = -1;
1009
1010       if (dep_list_size (insn) == 0)
1011         /* ??? We should set INSN_PRIORITY to insn_cost when and insn has
1012            some forward deps but all of them are ignored by
1013            contributes_to_priority hook.  At the moment we set priority of
1014            such insn to 0.  */
1015         this_priority = insn_cost (insn);
1016       else
1017         {
1018           rtx prev_first, twin;
1019           basic_block rec;
1020
1021           /* For recovery check instructions we calculate priority slightly
1022              different than that of normal instructions.  Instead of walking
1023              through INSN_FORW_DEPS (check) list, we walk through
1024              INSN_FORW_DEPS list of each instruction in the corresponding
1025              recovery block.  */
1026
1027           /* Selective scheduling does not define RECOVERY_BLOCK macro.  */
1028           rec = sel_sched_p () ? NULL : RECOVERY_BLOCK (insn);
1029           if (!rec || rec == EXIT_BLOCK_PTR)
1030             {
1031               prev_first = PREV_INSN (insn);
1032               twin = insn;
1033             }
1034           else
1035             {
1036               prev_first = NEXT_INSN (BB_HEAD (rec));
1037               twin = PREV_INSN (BB_END (rec));
1038             }
1039
1040           do
1041             {
1042               sd_iterator_def sd_it;
1043               dep_t dep;
1044
1045               FOR_EACH_DEP (twin, SD_LIST_FORW, sd_it, dep)
1046                 {
1047                   rtx next;
1048                   int next_priority;
1049
1050                   next = DEP_CON (dep);
1051
1052                   if (BLOCK_FOR_INSN (next) != rec)
1053                     {
1054                       int cost;
1055
1056                       if (!contributes_to_priority_p (dep))
1057                         continue;
1058
1059                       if (twin == insn)
1060                         cost = dep_cost (dep);
1061                       else
1062                         {
1063                           struct _dep _dep1, *dep1 = &_dep1;
1064
1065                           init_dep (dep1, insn, next, REG_DEP_ANTI);
1066
1067                           cost = dep_cost (dep1);
1068                         }
1069
1070                       next_priority = cost + priority (next);
1071
1072                       if (next_priority > this_priority)
1073                         this_priority = next_priority;
1074                     }
1075                 }
1076
1077               twin = PREV_INSN (twin);
1078             }
1079           while (twin != prev_first);
1080         }
1081
1082       if (this_priority < 0)
1083         {
1084           gcc_assert (this_priority == -1);
1085
1086           this_priority = insn_cost (insn);
1087         }
1088
1089       INSN_PRIORITY (insn) = this_priority;
1090       INSN_PRIORITY_STATUS (insn) = 1;
1091     }
1092
1093   return INSN_PRIORITY (insn);
1094 }
1095 \f
1096 /* Macros and functions for keeping the priority queue sorted, and
1097    dealing with queuing and dequeuing of instructions.  */
1098
1099 #define SCHED_SORT(READY, N_READY)                                   \
1100 do { if ((N_READY) == 2)                                             \
1101        swap_sort (READY, N_READY);                                   \
1102      else if ((N_READY) > 2)                                         \
1103          qsort (READY, N_READY, sizeof (rtx), rank_for_schedule); }  \
1104 while (0)
1105
1106 /* Setup info about the current register pressure impact of scheduling
1107    INSN at the current scheduling point.  */
1108 static void
1109 setup_insn_reg_pressure_info (rtx insn)
1110 {
1111   int i, change, before, after, hard_regno;
1112   int excess_cost_change;
1113   enum machine_mode mode;
1114   enum reg_class cl;
1115   struct reg_pressure_data *pressure_info;
1116   int *max_reg_pressure;
1117   struct reg_use_data *use;
1118   static int death[N_REG_CLASSES];
1119
1120   gcc_checking_assert (!DEBUG_INSN_P (insn));
1121
1122   excess_cost_change = 0;
1123   for (i = 0; i < ira_pressure_classes_num; i++)
1124     death[ira_pressure_classes[i]] = 0;
1125   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1126     if (dying_use_p (use))
1127       {
1128         cl = sched_regno_pressure_class[use->regno];
1129         if (use->regno < FIRST_PSEUDO_REGISTER)
1130           death[cl]++;
1131         else
1132           death[cl]
1133             += ira_reg_class_max_nregs[cl][PSEUDO_REGNO_MODE (use->regno)];
1134       }
1135   pressure_info = INSN_REG_PRESSURE (insn);
1136   max_reg_pressure = INSN_MAX_REG_PRESSURE (insn);
1137   gcc_assert (pressure_info != NULL && max_reg_pressure != NULL);
1138   for (i = 0; i < ira_pressure_classes_num; i++)
1139     {
1140       cl = ira_pressure_classes[i];
1141       gcc_assert (curr_reg_pressure[cl] >= 0);
1142       change = (int) pressure_info[i].set_increase - death[cl];
1143       before = MAX (0, max_reg_pressure[i] - ira_available_class_regs[cl]);
1144       after = MAX (0, max_reg_pressure[i] + change
1145                    - ira_available_class_regs[cl]);
1146       hard_regno = ira_class_hard_regs[cl][0];
1147       gcc_assert (hard_regno >= 0);
1148       mode = reg_raw_mode[hard_regno];
1149       excess_cost_change += ((after - before)
1150                              * (ira_memory_move_cost[mode][cl][0]
1151                                 + ira_memory_move_cost[mode][cl][1]));
1152     }
1153   INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insn) = excess_cost_change;
1154 }
1155
1156 /* Returns a positive value if x is preferred; returns a negative value if
1157    y is preferred.  Should never return 0, since that will make the sort
1158    unstable.  */
1159
1160 static int
1161 rank_for_schedule (const void *x, const void *y)
1162 {
1163   rtx tmp = *(const rtx *) y;
1164   rtx tmp2 = *(const rtx *) x;
1165   int tmp_class, tmp2_class;
1166   int val, priority_val, info_val;
1167
1168   if (MAY_HAVE_DEBUG_INSNS)
1169     {
1170       /* Schedule debug insns as early as possible.  */
1171       if (DEBUG_INSN_P (tmp) && !DEBUG_INSN_P (tmp2))
1172         return -1;
1173       else if (DEBUG_INSN_P (tmp2))
1174         return 1;
1175     }
1176
1177   /* The insn in a schedule group should be issued the first.  */
1178   if (flag_sched_group_heuristic &&
1179       SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
1180     return SCHED_GROUP_P (tmp2) ? 1 : -1;
1181
1182   /* Make sure that priority of TMP and TMP2 are initialized.  */
1183   gcc_assert (INSN_PRIORITY_KNOWN (tmp) && INSN_PRIORITY_KNOWN (tmp2));
1184
1185   if (sched_pressure_p)
1186     {
1187       int diff;
1188
1189       /* Prefer insn whose scheduling results in the smallest register
1190          pressure excess.  */
1191       if ((diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
1192                    + (INSN_TICK (tmp) > clock_var
1193                       ? INSN_TICK (tmp) - clock_var : 0)
1194                    - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2)
1195                    - (INSN_TICK (tmp2) > clock_var
1196                       ? INSN_TICK (tmp2) - clock_var : 0))) != 0)
1197         return diff;
1198     }
1199
1200
1201   if (sched_pressure_p
1202       && (INSN_TICK (tmp2) > clock_var || INSN_TICK (tmp) > clock_var))
1203     {
1204       if (INSN_TICK (tmp) <= clock_var)
1205         return -1;
1206       else if (INSN_TICK (tmp2) <= clock_var)
1207         return 1;
1208       else
1209         return INSN_TICK (tmp) - INSN_TICK (tmp2);
1210     }
1211   /* Prefer insn with higher priority.  */
1212   priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
1213
1214   if (flag_sched_critical_path_heuristic && priority_val)
1215     return priority_val;
1216
1217   /* Prefer speculative insn with greater dependencies weakness.  */
1218   if (flag_sched_spec_insn_heuristic && spec_info)
1219     {
1220       ds_t ds1, ds2;
1221       dw_t dw1, dw2;
1222       int dw;
1223
1224       ds1 = TODO_SPEC (tmp) & SPECULATIVE;
1225       if (ds1)
1226         dw1 = ds_weak (ds1);
1227       else
1228         dw1 = NO_DEP_WEAK;
1229
1230       ds2 = TODO_SPEC (tmp2) & SPECULATIVE;
1231       if (ds2)
1232         dw2 = ds_weak (ds2);
1233       else
1234         dw2 = NO_DEP_WEAK;
1235
1236       dw = dw2 - dw1;
1237       if (dw > (NO_DEP_WEAK / 8) || dw < -(NO_DEP_WEAK / 8))
1238         return dw;
1239     }
1240
1241   info_val = (*current_sched_info->rank) (tmp, tmp2);
1242   if(flag_sched_rank_heuristic && info_val)
1243     return info_val;
1244
1245   /* Compare insns based on their relation to the last scheduled
1246      non-debug insn.  */
1247   if (flag_sched_last_insn_heuristic && last_nondebug_scheduled_insn)
1248     {
1249       dep_t dep1;
1250       dep_t dep2;
1251       rtx last = last_nondebug_scheduled_insn;
1252
1253       /* Classify the instructions into three classes:
1254          1) Data dependent on last schedule insn.
1255          2) Anti/Output dependent on last scheduled insn.
1256          3) Independent of last scheduled insn, or has latency of one.
1257          Choose the insn from the highest numbered class if different.  */
1258       dep1 = sd_find_dep_between (last, tmp, true);
1259
1260       if (dep1 == NULL || dep_cost (dep1) == 1)
1261         tmp_class = 3;
1262       else if (/* Data dependence.  */
1263                DEP_TYPE (dep1) == REG_DEP_TRUE)
1264         tmp_class = 1;
1265       else
1266         tmp_class = 2;
1267
1268       dep2 = sd_find_dep_between (last, tmp2, true);
1269
1270       if (dep2 == NULL || dep_cost (dep2)  == 1)
1271         tmp2_class = 3;
1272       else if (/* Data dependence.  */
1273                DEP_TYPE (dep2) == REG_DEP_TRUE)
1274         tmp2_class = 1;
1275       else
1276         tmp2_class = 2;
1277
1278       if ((val = tmp2_class - tmp_class))
1279         return val;
1280     }
1281
1282   /* Prefer the insn which has more later insns that depend on it.
1283      This gives the scheduler more freedom when scheduling later
1284      instructions at the expense of added register pressure.  */
1285
1286   val = (dep_list_size (tmp2) - dep_list_size (tmp));
1287
1288   if (flag_sched_dep_count_heuristic && val != 0)
1289     return val;
1290
1291   /* If insns are equally good, sort by INSN_LUID (original insn order),
1292      so that we make the sort stable.  This minimizes instruction movement,
1293      thus minimizing sched's effect on debugging and cross-jumping.  */
1294   return INSN_LUID (tmp) - INSN_LUID (tmp2);
1295 }
1296
1297 /* Resort the array A in which only element at index N may be out of order.  */
1298
1299 HAIFA_INLINE static void
1300 swap_sort (rtx *a, int n)
1301 {
1302   rtx insn = a[n - 1];
1303   int i = n - 2;
1304
1305   while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
1306     {
1307       a[i + 1] = a[i];
1308       i -= 1;
1309     }
1310   a[i + 1] = insn;
1311 }
1312
1313 /* Add INSN to the insn queue so that it can be executed at least
1314    N_CYCLES after the currently executing insn.  Preserve insns
1315    chain for debugging purposes.  REASON will be printed in debugging
1316    output.  */
1317
1318 HAIFA_INLINE static void
1319 queue_insn (rtx insn, int n_cycles, const char *reason)
1320 {
1321   int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
1322   rtx link = alloc_INSN_LIST (insn, insn_queue[next_q]);
1323
1324   gcc_assert (n_cycles <= max_insn_queue_index);
1325   gcc_assert (!DEBUG_INSN_P (insn));
1326
1327   insn_queue[next_q] = link;
1328   q_size += 1;
1329
1330   if (sched_verbose >= 2)
1331     {
1332       fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
1333                (*current_sched_info->print_insn) (insn, 0));
1334
1335       fprintf (sched_dump, "queued for %d cycles (%s).\n", n_cycles, reason);
1336     }
1337
1338   QUEUE_INDEX (insn) = next_q;
1339 }
1340
1341 /* Remove INSN from queue.  */
1342 static void
1343 queue_remove (rtx insn)
1344 {
1345   gcc_assert (QUEUE_INDEX (insn) >= 0);
1346   remove_free_INSN_LIST_elem (insn, &insn_queue[QUEUE_INDEX (insn)]);
1347   q_size--;
1348   QUEUE_INDEX (insn) = QUEUE_NOWHERE;
1349 }
1350
1351 /* Return a pointer to the bottom of the ready list, i.e. the insn
1352    with the lowest priority.  */
1353
1354 rtx *
1355 ready_lastpos (struct ready_list *ready)
1356 {
1357   gcc_assert (ready->n_ready >= 1);
1358   return ready->vec + ready->first - ready->n_ready + 1;
1359 }
1360
1361 /* Add an element INSN to the ready list so that it ends up with the
1362    lowest/highest priority depending on FIRST_P.  */
1363
1364 HAIFA_INLINE static void
1365 ready_add (struct ready_list *ready, rtx insn, bool first_p)
1366 {
1367   if (!first_p)
1368     {
1369       if (ready->first == ready->n_ready)
1370         {
1371           memmove (ready->vec + ready->veclen - ready->n_ready,
1372                    ready_lastpos (ready),
1373                    ready->n_ready * sizeof (rtx));
1374           ready->first = ready->veclen - 1;
1375         }
1376       ready->vec[ready->first - ready->n_ready] = insn;
1377     }
1378   else
1379     {
1380       if (ready->first == ready->veclen - 1)
1381         {
1382           if (ready->n_ready)
1383             /* ready_lastpos() fails when called with (ready->n_ready == 0).  */
1384             memmove (ready->vec + ready->veclen - ready->n_ready - 1,
1385                      ready_lastpos (ready),
1386                      ready->n_ready * sizeof (rtx));
1387           ready->first = ready->veclen - 2;
1388         }
1389       ready->vec[++(ready->first)] = insn;
1390     }
1391
1392   ready->n_ready++;
1393   if (DEBUG_INSN_P (insn))
1394     ready->n_debug++;
1395
1396   gcc_assert (QUEUE_INDEX (insn) != QUEUE_READY);
1397   QUEUE_INDEX (insn) = QUEUE_READY;
1398 }
1399
1400 /* Remove the element with the highest priority from the ready list and
1401    return it.  */
1402
1403 HAIFA_INLINE static rtx
1404 ready_remove_first (struct ready_list *ready)
1405 {
1406   rtx t;
1407
1408   gcc_assert (ready->n_ready);
1409   t = ready->vec[ready->first--];
1410   ready->n_ready--;
1411   if (DEBUG_INSN_P (t))
1412     ready->n_debug--;
1413   /* If the queue becomes empty, reset it.  */
1414   if (ready->n_ready == 0)
1415     ready->first = ready->veclen - 1;
1416
1417   gcc_assert (QUEUE_INDEX (t) == QUEUE_READY);
1418   QUEUE_INDEX (t) = QUEUE_NOWHERE;
1419
1420   return t;
1421 }
1422
1423 /* The following code implements multi-pass scheduling for the first
1424    cycle.  In other words, we will try to choose ready insn which
1425    permits to start maximum number of insns on the same cycle.  */
1426
1427 /* Return a pointer to the element INDEX from the ready.  INDEX for
1428    insn with the highest priority is 0, and the lowest priority has
1429    N_READY - 1.  */
1430
1431 rtx
1432 ready_element (struct ready_list *ready, int index)
1433 {
1434   gcc_assert (ready->n_ready && index < ready->n_ready);
1435
1436   return ready->vec[ready->first - index];
1437 }
1438
1439 /* Remove the element INDEX from the ready list and return it.  INDEX
1440    for insn with the highest priority is 0, and the lowest priority
1441    has N_READY - 1.  */
1442
1443 HAIFA_INLINE static rtx
1444 ready_remove (struct ready_list *ready, int index)
1445 {
1446   rtx t;
1447   int i;
1448
1449   if (index == 0)
1450     return ready_remove_first (ready);
1451   gcc_assert (ready->n_ready && index < ready->n_ready);
1452   t = ready->vec[ready->first - index];
1453   ready->n_ready--;
1454   if (DEBUG_INSN_P (t))
1455     ready->n_debug--;
1456   for (i = index; i < ready->n_ready; i++)
1457     ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
1458   QUEUE_INDEX (t) = QUEUE_NOWHERE;
1459   return t;
1460 }
1461
1462 /* Remove INSN from the ready list.  */
1463 static void
1464 ready_remove_insn (rtx insn)
1465 {
1466   int i;
1467
1468   for (i = 0; i < readyp->n_ready; i++)
1469     if (ready_element (readyp, i) == insn)
1470       {
1471         ready_remove (readyp, i);
1472         return;
1473       }
1474   gcc_unreachable ();
1475 }
1476
1477 /* Sort the ready list READY by ascending priority, using the SCHED_SORT
1478    macro.  */
1479
1480 void
1481 ready_sort (struct ready_list *ready)
1482 {
1483   int i;
1484   rtx *first = ready_lastpos (ready);
1485
1486   if (sched_pressure_p)
1487     {
1488       for (i = 0; i < ready->n_ready; i++)
1489         if (!DEBUG_INSN_P (first[i]))
1490           setup_insn_reg_pressure_info (first[i]);
1491     }
1492   SCHED_SORT (first, ready->n_ready);
1493 }
1494
1495 /* PREV is an insn that is ready to execute.  Adjust its priority if that
1496    will help shorten or lengthen register lifetimes as appropriate.  Also
1497    provide a hook for the target to tweak itself.  */
1498
1499 HAIFA_INLINE static void
1500 adjust_priority (rtx prev)
1501 {
1502   /* ??? There used to be code here to try and estimate how an insn
1503      affected register lifetimes, but it did it by looking at REG_DEAD
1504      notes, which we removed in schedule_region.  Nor did it try to
1505      take into account register pressure or anything useful like that.
1506
1507      Revisit when we have a machine model to work with and not before.  */
1508
1509   if (targetm.sched.adjust_priority)
1510     INSN_PRIORITY (prev) =
1511       targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
1512 }
1513
1514 /* Advance DFA state STATE on one cycle.  */
1515 void
1516 advance_state (state_t state)
1517 {
1518   if (targetm.sched.dfa_pre_advance_cycle)
1519     targetm.sched.dfa_pre_advance_cycle ();
1520
1521   if (targetm.sched.dfa_pre_cycle_insn)
1522     state_transition (state,
1523                       targetm.sched.dfa_pre_cycle_insn ());
1524
1525   state_transition (state, NULL);
1526
1527   if (targetm.sched.dfa_post_cycle_insn)
1528     state_transition (state,
1529                       targetm.sched.dfa_post_cycle_insn ());
1530
1531   if (targetm.sched.dfa_post_advance_cycle)
1532     targetm.sched.dfa_post_advance_cycle ();
1533 }
1534
1535 /* Advance time on one cycle.  */
1536 HAIFA_INLINE static void
1537 advance_one_cycle (void)
1538 {
1539   advance_state (curr_state);
1540   if (sched_verbose >= 6)
1541     fprintf (sched_dump, ";;\tAdvanced a state.\n");
1542 }
1543
1544 /* Clock at which the previous instruction was issued.  */
1545 static int last_clock_var;
1546
1547 /* Update register pressure after scheduling INSN.  */
1548 static void
1549 update_register_pressure (rtx insn)
1550 {
1551   struct reg_use_data *use;
1552   struct reg_set_data *set;
1553
1554   gcc_checking_assert (!DEBUG_INSN_P (insn));
1555
1556   for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1557     if (dying_use_p (use) && bitmap_bit_p (curr_reg_live, use->regno))
1558       mark_regno_birth_or_death (use->regno, false);
1559   for (set = INSN_REG_SET_LIST (insn); set != NULL; set = set->next_insn_set)
1560     mark_regno_birth_or_death (set->regno, true);
1561 }
1562
1563 /* Set up or update (if UPDATE_P) max register pressure (see its
1564    meaning in sched-int.h::_haifa_insn_data) for all current BB insns
1565    after insn AFTER.  */
1566 static void
1567 setup_insn_max_reg_pressure (rtx after, bool update_p)
1568 {
1569   int i, p;
1570   bool eq_p;
1571   rtx insn;
1572   static int max_reg_pressure[N_REG_CLASSES];
1573
1574   save_reg_pressure ();
1575   for (i = 0; i < ira_pressure_classes_num; i++)
1576     max_reg_pressure[ira_pressure_classes[i]]
1577       = curr_reg_pressure[ira_pressure_classes[i]];
1578   for (insn = NEXT_INSN (after);
1579        insn != NULL_RTX && ! BARRIER_P (insn)
1580          && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (after);
1581        insn = NEXT_INSN (insn))
1582     if (NONDEBUG_INSN_P (insn))
1583       {
1584         eq_p = true;
1585         for (i = 0; i < ira_pressure_classes_num; i++)
1586           {
1587             p = max_reg_pressure[ira_pressure_classes[i]];
1588             if (INSN_MAX_REG_PRESSURE (insn)[i] != p)
1589               {
1590                 eq_p = false;
1591                 INSN_MAX_REG_PRESSURE (insn)[i]
1592                   = max_reg_pressure[ira_pressure_classes[i]];
1593               }
1594           }
1595         if (update_p && eq_p)
1596           break;
1597         update_register_pressure (insn);
1598         for (i = 0; i < ira_pressure_classes_num; i++)
1599           if (max_reg_pressure[ira_pressure_classes[i]]
1600               < curr_reg_pressure[ira_pressure_classes[i]])
1601             max_reg_pressure[ira_pressure_classes[i]]
1602               = curr_reg_pressure[ira_pressure_classes[i]];
1603       }
1604   restore_reg_pressure ();
1605 }
1606
1607 /* Update the current register pressure after scheduling INSN.  Update
1608    also max register pressure for unscheduled insns of the current
1609    BB.  */
1610 static void
1611 update_reg_and_insn_max_reg_pressure (rtx insn)
1612 {
1613   int i;
1614   int before[N_REG_CLASSES];
1615
1616   for (i = 0; i < ira_pressure_classes_num; i++)
1617     before[i] = curr_reg_pressure[ira_pressure_classes[i]];
1618   update_register_pressure (insn);
1619   for (i = 0; i < ira_pressure_classes_num; i++)
1620     if (curr_reg_pressure[ira_pressure_classes[i]] != before[i])
1621       break;
1622   if (i < ira_pressure_classes_num)
1623     setup_insn_max_reg_pressure (insn, true);
1624 }
1625
1626 /* Set up register pressure at the beginning of basic block BB whose
1627    insns starting after insn AFTER.  Set up also max register pressure
1628    for all insns of the basic block.  */
1629 void
1630 sched_setup_bb_reg_pressure_info (basic_block bb, rtx after)
1631 {
1632   gcc_assert (sched_pressure_p);
1633   initiate_bb_reg_pressure_info (bb);
1634   setup_insn_max_reg_pressure (after, false);
1635 }
1636
1637 /* INSN is the "currently executing insn".  Launch each insn which was
1638    waiting on INSN.  READY is the ready list which contains the insns
1639    that are ready to fire.  CLOCK is the current cycle.  The function
1640    returns necessary cycle advance after issuing the insn (it is not
1641    zero for insns in a schedule group).  */
1642
1643 static int
1644 schedule_insn (rtx insn)
1645 {
1646   sd_iterator_def sd_it;
1647   dep_t dep;
1648   int i;
1649   int advance = 0;
1650
1651   if (sched_verbose >= 1)
1652     {
1653       struct reg_pressure_data *pressure_info;
1654       char buf[2048];
1655
1656       print_insn (buf, insn, 0);
1657       buf[40] = 0;
1658       fprintf (sched_dump, ";;\t%3i--> %-40s:", clock_var, buf);
1659
1660       if (recog_memoized (insn) < 0)
1661         fprintf (sched_dump, "nothing");
1662       else
1663         print_reservation (sched_dump, insn);
1664       pressure_info = INSN_REG_PRESSURE (insn);
1665       if (pressure_info != NULL)
1666         {
1667           fputc (':', sched_dump);
1668           for (i = 0; i < ira_pressure_classes_num; i++)
1669             fprintf (sched_dump, "%s%+d(%d)",
1670                      reg_class_names[ira_pressure_classes[i]],
1671                      pressure_info[i].set_increase, pressure_info[i].change);
1672         }
1673       fputc ('\n', sched_dump);
1674     }
1675
1676   if (sched_pressure_p && !DEBUG_INSN_P (insn))
1677     update_reg_and_insn_max_reg_pressure (insn);
1678
1679   /* Scheduling instruction should have all its dependencies resolved and
1680      should have been removed from the ready list.  */
1681   gcc_assert (sd_lists_empty_p (insn, SD_LIST_BACK));
1682
1683   /* Reset debug insns invalidated by moving this insn.  */
1684   if (MAY_HAVE_DEBUG_INSNS && !DEBUG_INSN_P (insn))
1685     for (sd_it = sd_iterator_start (insn, SD_LIST_BACK);
1686          sd_iterator_cond (&sd_it, &dep);)
1687       {
1688         rtx dbg = DEP_PRO (dep);
1689         struct reg_use_data *use, *next;
1690
1691         gcc_assert (DEBUG_INSN_P (dbg));
1692
1693         if (sched_verbose >= 6)
1694           fprintf (sched_dump, ";;\t\tresetting: debug insn %d\n",
1695                    INSN_UID (dbg));
1696
1697         /* ??? Rather than resetting the debug insn, we might be able
1698            to emit a debug temp before the just-scheduled insn, but
1699            this would involve checking that the expression at the
1700            point of the debug insn is equivalent to the expression
1701            before the just-scheduled insn.  They might not be: the
1702            expression in the debug insn may depend on other insns not
1703            yet scheduled that set MEMs, REGs or even other debug
1704            insns.  It's not clear that attempting to preserve debug
1705            information in these cases is worth the effort, given how
1706            uncommon these resets are and the likelihood that the debug
1707            temps introduced won't survive the schedule change.  */
1708         INSN_VAR_LOCATION_LOC (dbg) = gen_rtx_UNKNOWN_VAR_LOC ();
1709         df_insn_rescan (dbg);
1710
1711         /* Unknown location doesn't use any registers.  */
1712         for (use = INSN_REG_USE_LIST (dbg); use != NULL; use = next)
1713           {
1714             struct reg_use_data *prev = use;
1715
1716             /* Remove use from the cyclic next_regno_use chain first.  */
1717             while (prev->next_regno_use != use)
1718               prev = prev->next_regno_use;
1719             prev->next_regno_use = use->next_regno_use;
1720             next = use->next_insn_use;
1721             free (use);
1722           }
1723         INSN_REG_USE_LIST (dbg) = NULL;
1724
1725         /* We delete rather than resolve these deps, otherwise we
1726            crash in sched_free_deps(), because forward deps are
1727            expected to be released before backward deps.  */
1728         sd_delete_dep (sd_it);
1729       }
1730
1731   gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
1732   QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
1733
1734   gcc_assert (INSN_TICK (insn) >= MIN_TICK);
1735   if (INSN_TICK (insn) > clock_var)
1736     /* INSN has been prematurely moved from the queue to the ready list.
1737        This is possible only if following flag is set.  */
1738     gcc_assert (flag_sched_stalled_insns);
1739
1740   /* ??? Probably, if INSN is scheduled prematurely, we should leave
1741      INSN_TICK untouched.  This is a machine-dependent issue, actually.  */
1742   INSN_TICK (insn) = clock_var;
1743
1744   /* Update dependent instructions.  */
1745   for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
1746        sd_iterator_cond (&sd_it, &dep);)
1747     {
1748       rtx next = DEP_CON (dep);
1749
1750       /* Resolve the dependence between INSN and NEXT.
1751          sd_resolve_dep () moves current dep to another list thus
1752          advancing the iterator.  */
1753       sd_resolve_dep (sd_it);
1754
1755       /* Don't bother trying to mark next as ready if insn is a debug
1756          insn.  If insn is the last hard dependency, it will have
1757          already been discounted.  */
1758       if (DEBUG_INSN_P (insn) && !DEBUG_INSN_P (next))
1759         continue;
1760
1761       if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
1762         {
1763           int effective_cost;
1764
1765           effective_cost = try_ready (next);
1766
1767           if (effective_cost >= 0
1768               && SCHED_GROUP_P (next)
1769               && advance < effective_cost)
1770             advance = effective_cost;
1771         }
1772       else
1773         /* Check always has only one forward dependence (to the first insn in
1774            the recovery block), therefore, this will be executed only once.  */
1775         {
1776           gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
1777           fix_recovery_deps (RECOVERY_BLOCK (insn));
1778         }
1779     }
1780
1781   /* This is the place where scheduler doesn't *basically* need backward and
1782      forward dependencies for INSN anymore.  Nevertheless they are used in
1783      heuristics in rank_for_schedule (), early_queue_to_ready () and in
1784      some targets (e.g. rs6000).  Thus the earliest place where we *can*
1785      remove dependencies is after targetm.sched.finish () call in
1786      schedule_block ().  But, on the other side, the safest place to remove
1787      dependencies is when we are finishing scheduling entire region.  As we
1788      don't generate [many] dependencies during scheduling itself, we won't
1789      need memory until beginning of next region.
1790      Bottom line: Dependencies are removed for all insns in the end of
1791      scheduling the region.  */
1792
1793   /* Annotate the instruction with issue information -- TImode
1794      indicates that the instruction is expected not to be able
1795      to issue on the same cycle as the previous insn.  A machine
1796      may use this information to decide how the instruction should
1797      be aligned.  */
1798   if (issue_rate > 1
1799       && GET_CODE (PATTERN (insn)) != USE
1800       && GET_CODE (PATTERN (insn)) != CLOBBER
1801       && !DEBUG_INSN_P (insn))
1802     {
1803       if (reload_completed)
1804         PUT_MODE (insn, clock_var > last_clock_var ? TImode : VOIDmode);
1805       last_clock_var = clock_var;
1806     }
1807
1808   return advance;
1809 }
1810
1811 /* Functions for handling of notes.  */
1812
1813 /* Add note list that ends on FROM_END to the end of TO_ENDP.  */
1814 void
1815 concat_note_lists (rtx from_end, rtx *to_endp)
1816 {
1817   rtx from_start;
1818
1819   /* It's easy when have nothing to concat.  */
1820   if (from_end == NULL)
1821     return;
1822
1823   /* It's also easy when destination is empty.  */
1824   if (*to_endp == NULL)
1825     {
1826       *to_endp = from_end;
1827       return;
1828     }
1829
1830   from_start = from_end;
1831   while (PREV_INSN (from_start) != NULL)
1832     from_start = PREV_INSN (from_start);
1833
1834   PREV_INSN (from_start) = *to_endp;
1835   NEXT_INSN (*to_endp) = from_start;
1836   *to_endp = from_end;
1837 }
1838
1839 /* Delete notes between HEAD and TAIL and put them in the chain
1840    of notes ended by NOTE_LIST.  */
1841 void
1842 remove_notes (rtx head, rtx tail)
1843 {
1844   rtx next_tail, insn, next;
1845
1846   note_list = 0;
1847   if (head == tail && !INSN_P (head))
1848     return;
1849
1850   next_tail = NEXT_INSN (tail);
1851   for (insn = head; insn != next_tail; insn = next)
1852     {
1853       next = NEXT_INSN (insn);
1854       if (!NOTE_P (insn))
1855         continue;
1856
1857       switch (NOTE_KIND (insn))
1858         {
1859         case NOTE_INSN_BASIC_BLOCK:
1860           continue;
1861
1862         case NOTE_INSN_EPILOGUE_BEG:
1863           if (insn != tail)
1864             {
1865               remove_insn (insn);
1866               add_reg_note (next, REG_SAVE_NOTE,
1867                             GEN_INT (NOTE_INSN_EPILOGUE_BEG));
1868               break;
1869             }
1870           /* FALLTHRU */
1871
1872         default:
1873           remove_insn (insn);
1874
1875           /* Add the note to list that ends at NOTE_LIST.  */
1876           PREV_INSN (insn) = note_list;
1877           NEXT_INSN (insn) = NULL_RTX;
1878           if (note_list)
1879             NEXT_INSN (note_list) = insn;
1880           note_list = insn;
1881           break;
1882         }
1883
1884       gcc_assert ((sel_sched_p () || insn != tail) && insn != head);
1885     }
1886 }
1887
1888
1889 /* Return the head and tail pointers of ebb starting at BEG and ending
1890    at END.  */
1891 void
1892 get_ebb_head_tail (basic_block beg, basic_block end, rtx *headp, rtx *tailp)
1893 {
1894   rtx beg_head = BB_HEAD (beg);
1895   rtx beg_tail = BB_END (beg);
1896   rtx end_head = BB_HEAD (end);
1897   rtx end_tail = BB_END (end);
1898
1899   /* Don't include any notes or labels at the beginning of the BEG
1900      basic block, or notes at the end of the END basic blocks.  */
1901
1902   if (LABEL_P (beg_head))
1903     beg_head = NEXT_INSN (beg_head);
1904
1905   while (beg_head != beg_tail)
1906     if (NOTE_P (beg_head))
1907       beg_head = NEXT_INSN (beg_head);
1908     else if (DEBUG_INSN_P (beg_head))
1909       {
1910         rtx note, next;
1911
1912         for (note = NEXT_INSN (beg_head);
1913              note != beg_tail;
1914              note = next)
1915           {
1916             next = NEXT_INSN (note);
1917             if (NOTE_P (note))
1918               {
1919                 if (sched_verbose >= 9)
1920                   fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
1921
1922                 reorder_insns_nobb (note, note, PREV_INSN (beg_head));
1923
1924                 if (BLOCK_FOR_INSN (note) != beg)
1925                   df_insn_change_bb (note, beg);
1926               }
1927             else if (!DEBUG_INSN_P (note))
1928               break;
1929           }
1930
1931         break;
1932       }
1933     else
1934       break;
1935
1936   *headp = beg_head;
1937
1938   if (beg == end)
1939     end_head = beg_head;
1940   else if (LABEL_P (end_head))
1941     end_head = NEXT_INSN (end_head);
1942
1943   while (end_head != end_tail)
1944     if (NOTE_P (end_tail))
1945       end_tail = PREV_INSN (end_tail);
1946     else if (DEBUG_INSN_P (end_tail))
1947       {
1948         rtx note, prev;
1949
1950         for (note = PREV_INSN (end_tail);
1951              note != end_head;
1952              note = prev)
1953           {
1954             prev = PREV_INSN (note);
1955             if (NOTE_P (note))
1956               {
1957                 if (sched_verbose >= 9)
1958                   fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
1959
1960                 reorder_insns_nobb (note, note, end_tail);
1961
1962                 if (end_tail == BB_END (end))
1963                   BB_END (end) = note;
1964
1965                 if (BLOCK_FOR_INSN (note) != end)
1966                   df_insn_change_bb (note, end);
1967               }
1968             else if (!DEBUG_INSN_P (note))
1969               break;
1970           }
1971
1972         break;
1973       }
1974     else
1975       break;
1976
1977   *tailp = end_tail;
1978 }
1979
1980 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ].  */
1981
1982 int
1983 no_real_insns_p (const_rtx head, const_rtx tail)
1984 {
1985   while (head != NEXT_INSN (tail))
1986     {
1987       if (!NOTE_P (head) && !LABEL_P (head))
1988         return 0;
1989       head = NEXT_INSN (head);
1990     }
1991   return 1;
1992 }
1993
1994 /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
1995    previously found among the insns.  Insert them just before HEAD.  */
1996 rtx
1997 restore_other_notes (rtx head, basic_block head_bb)
1998 {
1999   if (note_list != 0)
2000     {
2001       rtx note_head = note_list;
2002
2003       if (head)
2004         head_bb = BLOCK_FOR_INSN (head);
2005       else
2006         head = NEXT_INSN (bb_note (head_bb));
2007
2008       while (PREV_INSN (note_head))
2009         {
2010           set_block_for_insn (note_head, head_bb);
2011           note_head = PREV_INSN (note_head);
2012         }
2013       /* In the above cycle we've missed this note.  */
2014       set_block_for_insn (note_head, head_bb);
2015
2016       PREV_INSN (note_head) = PREV_INSN (head);
2017       NEXT_INSN (PREV_INSN (head)) = note_head;
2018       PREV_INSN (head) = note_list;
2019       NEXT_INSN (note_list) = head;
2020
2021       if (BLOCK_FOR_INSN (head) != head_bb)
2022         BB_END (head_bb) = note_list;
2023
2024       head = note_head;
2025     }
2026
2027   return head;
2028 }
2029
2030 /* Move insns that became ready to fire from queue to ready list.  */
2031
2032 static void
2033 queue_to_ready (struct ready_list *ready)
2034 {
2035   rtx insn;
2036   rtx link;
2037   rtx skip_insn;
2038
2039   q_ptr = NEXT_Q (q_ptr);
2040
2041   if (dbg_cnt (sched_insn) == false)
2042     {
2043       /* If debug counter is activated do not requeue the first
2044          nonscheduled insn.  */
2045       skip_insn = nonscheduled_insns_begin;
2046       do
2047         {
2048           skip_insn = next_nonnote_nondebug_insn (skip_insn);
2049         }
2050       while (QUEUE_INDEX (skip_insn) == QUEUE_SCHEDULED);
2051     }
2052   else
2053     skip_insn = NULL_RTX;
2054
2055   /* Add all pending insns that can be scheduled without stalls to the
2056      ready list.  */
2057   for (link = insn_queue[q_ptr]; link; link = XEXP (link, 1))
2058     {
2059       insn = XEXP (link, 0);
2060       q_size -= 1;
2061
2062       if (sched_verbose >= 2)
2063         fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
2064                  (*current_sched_info->print_insn) (insn, 0));
2065
2066       /* If the ready list is full, delay the insn for 1 cycle.
2067          See the comment in schedule_block for the rationale.  */
2068       if (!reload_completed
2069           && ready->n_ready - ready->n_debug > MAX_SCHED_READY_INSNS
2070           && !SCHED_GROUP_P (insn)
2071           && insn != skip_insn)
2072         queue_insn (insn, 1, "ready full");
2073       else
2074         {
2075           ready_add (ready, insn, false);
2076           if (sched_verbose >= 2)
2077             fprintf (sched_dump, "moving to ready without stalls\n");
2078         }
2079     }
2080   free_INSN_LIST_list (&insn_queue[q_ptr]);
2081
2082   /* If there are no ready insns, stall until one is ready and add all
2083      of the pending insns at that point to the ready list.  */
2084   if (ready->n_ready == 0)
2085     {
2086       int stalls;
2087
2088       for (stalls = 1; stalls <= max_insn_queue_index; stalls++)
2089         {
2090           if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
2091             {
2092               for (; link; link = XEXP (link, 1))
2093                 {
2094                   insn = XEXP (link, 0);
2095                   q_size -= 1;
2096
2097                   if (sched_verbose >= 2)
2098                     fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
2099                              (*current_sched_info->print_insn) (insn, 0));
2100
2101                   ready_add (ready, insn, false);
2102                   if (sched_verbose >= 2)
2103                     fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
2104                 }
2105               free_INSN_LIST_list (&insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]);
2106
2107               advance_one_cycle ();
2108
2109               break;
2110             }
2111
2112           advance_one_cycle ();
2113         }
2114
2115       q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
2116       clock_var += stalls;
2117     }
2118 }
2119
2120 /* Used by early_queue_to_ready.  Determines whether it is "ok" to
2121    prematurely move INSN from the queue to the ready list.  Currently,
2122    if a target defines the hook 'is_costly_dependence', this function
2123    uses the hook to check whether there exist any dependences which are
2124    considered costly by the target, between INSN and other insns that
2125    have already been scheduled.  Dependences are checked up to Y cycles
2126    back, with default Y=1; The flag -fsched-stalled-insns-dep=Y allows
2127    controlling this value.
2128    (Other considerations could be taken into account instead (or in
2129    addition) depending on user flags and target hooks.  */
2130
2131 static bool
2132 ok_for_early_queue_removal (rtx insn)
2133 {
2134   if (targetm.sched.is_costly_dependence)
2135     {
2136       rtx prev_insn;
2137       int n_cycles;
2138       int i = VEC_length (rtx, scheduled_insns);
2139       for (n_cycles = flag_sched_stalled_insns_dep; n_cycles; n_cycles--)
2140         {
2141           while (i-- > 0)
2142             {
2143               int cost;
2144
2145               prev_insn = VEC_index (rtx, scheduled_insns, i);
2146
2147               if (!NOTE_P (prev_insn))
2148                 {
2149                   dep_t dep;
2150
2151                   dep = sd_find_dep_between (prev_insn, insn, true);
2152
2153                   if (dep != NULL)
2154                     {
2155                       cost = dep_cost (dep);
2156
2157                       if (targetm.sched.is_costly_dependence (dep, cost,
2158                                 flag_sched_stalled_insns_dep - n_cycles))
2159                         return false;
2160                     }
2161                 }
2162
2163               if (GET_MODE (prev_insn) == TImode) /* end of dispatch group */
2164                 break;
2165             }
2166
2167           if (i == 0)
2168             break;
2169         }
2170     }
2171
2172   return true;
2173 }
2174
2175
2176 /* Remove insns from the queue, before they become "ready" with respect
2177    to FU latency considerations.  */
2178
2179 static int
2180 early_queue_to_ready (state_t state, struct ready_list *ready)
2181 {
2182   rtx insn;
2183   rtx link;
2184   rtx next_link;
2185   rtx prev_link;
2186   bool move_to_ready;
2187   int cost;
2188   state_t temp_state = alloca (dfa_state_size);
2189   int stalls;
2190   int insns_removed = 0;
2191
2192   /*
2193      Flag '-fsched-stalled-insns=X' determines the aggressiveness of this
2194      function:
2195
2196      X == 0: There is no limit on how many queued insns can be removed
2197              prematurely.  (flag_sched_stalled_insns = -1).
2198
2199      X >= 1: Only X queued insns can be removed prematurely in each
2200              invocation.  (flag_sched_stalled_insns = X).
2201
2202      Otherwise: Early queue removal is disabled.
2203          (flag_sched_stalled_insns = 0)
2204   */
2205
2206   if (! flag_sched_stalled_insns)
2207     return 0;
2208
2209   for (stalls = 0; stalls <= max_insn_queue_index; stalls++)
2210     {
2211       if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
2212         {
2213           if (sched_verbose > 6)
2214             fprintf (sched_dump, ";; look at index %d + %d\n", q_ptr, stalls);
2215
2216           prev_link = 0;
2217           while (link)
2218             {
2219               next_link = XEXP (link, 1);
2220               insn = XEXP (link, 0);
2221               if (insn && sched_verbose > 6)
2222                 print_rtl_single (sched_dump, insn);
2223
2224               memcpy (temp_state, state, dfa_state_size);
2225               if (recog_memoized (insn) < 0)
2226                 /* non-negative to indicate that it's not ready
2227                    to avoid infinite Q->R->Q->R... */
2228                 cost = 0;
2229               else
2230                 cost = state_transition (temp_state, insn);
2231
2232               if (sched_verbose >= 6)
2233                 fprintf (sched_dump, "transition cost = %d\n", cost);
2234
2235               move_to_ready = false;
2236               if (cost < 0)
2237                 {
2238                   move_to_ready = ok_for_early_queue_removal (insn);
2239                   if (move_to_ready == true)
2240                     {
2241                       /* move from Q to R */
2242                       q_size -= 1;
2243                       ready_add (ready, insn, false);
2244
2245                       if (prev_link)
2246                         XEXP (prev_link, 1) = next_link;
2247                       else
2248                         insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = next_link;
2249
2250                       free_INSN_LIST_node (link);
2251
2252                       if (sched_verbose >= 2)
2253                         fprintf (sched_dump, ";;\t\tEarly Q-->Ready: insn %s\n",
2254                                  (*current_sched_info->print_insn) (insn, 0));
2255
2256                       insns_removed++;
2257                       if (insns_removed == flag_sched_stalled_insns)
2258                         /* Remove no more than flag_sched_stalled_insns insns
2259                            from Q at a time.  */
2260                         return insns_removed;
2261                     }
2262                 }
2263
2264               if (move_to_ready == false)
2265                 prev_link = link;
2266
2267               link = next_link;
2268             } /* while link */
2269         } /* if link */
2270
2271     } /* for stalls.. */
2272
2273   return insns_removed;
2274 }
2275
2276
2277 /* Print the ready list for debugging purposes.  Callable from debugger.  */
2278
2279 static void
2280 debug_ready_list (struct ready_list *ready)
2281 {
2282   rtx *p;
2283   int i;
2284
2285   if (ready->n_ready == 0)
2286     {
2287       fprintf (sched_dump, "\n");
2288       return;
2289     }
2290
2291   p = ready_lastpos (ready);
2292   for (i = 0; i < ready->n_ready; i++)
2293     {
2294       fprintf (sched_dump, "  %s:%d",
2295                (*current_sched_info->print_insn) (p[i], 0),
2296                INSN_LUID (p[i]));
2297       if (sched_pressure_p)
2298         fprintf (sched_dump, "(cost=%d",
2299                  INSN_REG_PRESSURE_EXCESS_COST_CHANGE (p[i]));
2300       if (INSN_TICK (p[i]) > clock_var)
2301         fprintf (sched_dump, ":delay=%d", INSN_TICK (p[i]) - clock_var);
2302       if (sched_pressure_p)
2303         fprintf (sched_dump, ")");
2304     }
2305   fprintf (sched_dump, "\n");
2306 }
2307
2308 /* Search INSN for REG_SAVE_NOTE notes and convert them back into insn
2309    NOTEs.  This is used for NOTE_INSN_EPILOGUE_BEG, so that sched-ebb
2310    replaces the epilogue note in the correct basic block.  */
2311 void
2312 reemit_notes (rtx insn)
2313 {
2314   rtx note, last = insn;
2315
2316   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
2317     {
2318       if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
2319         {
2320           enum insn_note note_type = (enum insn_note) INTVAL (XEXP (note, 0));
2321
2322           last = emit_note_before (note_type, last);
2323           remove_note (insn, note);
2324         }
2325     }
2326 }
2327
2328 /* Move INSN.  Reemit notes if needed.  Update CFG, if needed.  */
2329 static void
2330 move_insn (rtx insn, rtx last, rtx nt)
2331 {
2332   if (PREV_INSN (insn) != last)
2333     {
2334       basic_block bb;
2335       rtx note;
2336       int jump_p = 0;
2337
2338       bb = BLOCK_FOR_INSN (insn);
2339
2340       /* BB_HEAD is either LABEL or NOTE.  */
2341       gcc_assert (BB_HEAD (bb) != insn);
2342
2343       if (BB_END (bb) == insn)
2344         /* If this is last instruction in BB, move end marker one
2345            instruction up.  */
2346         {
2347           /* Jumps are always placed at the end of basic block.  */
2348           jump_p = control_flow_insn_p (insn);
2349
2350           gcc_assert (!jump_p
2351                       || ((common_sched_info->sched_pass_id == SCHED_RGN_PASS)
2352                           && IS_SPECULATION_BRANCHY_CHECK_P (insn))
2353                       || (common_sched_info->sched_pass_id
2354                           == SCHED_EBB_PASS));
2355
2356           gcc_assert (BLOCK_FOR_INSN (PREV_INSN (insn)) == bb);
2357
2358           BB_END (bb) = PREV_INSN (insn);
2359         }
2360
2361       gcc_assert (BB_END (bb) != last);
2362
2363       if (jump_p)
2364         /* We move the block note along with jump.  */
2365         {
2366           gcc_assert (nt);
2367
2368           note = NEXT_INSN (insn);
2369           while (NOTE_NOT_BB_P (note) && note != nt)
2370             note = NEXT_INSN (note);
2371
2372           if (note != nt
2373               && (LABEL_P (note)
2374                   || BARRIER_P (note)))
2375             note = NEXT_INSN (note);
2376
2377           gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
2378         }
2379       else
2380         note = insn;
2381
2382       NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (note);
2383       PREV_INSN (NEXT_INSN (note)) = PREV_INSN (insn);
2384
2385       NEXT_INSN (note) = NEXT_INSN (last);
2386       PREV_INSN (NEXT_INSN (last)) = note;
2387
2388       NEXT_INSN (last) = insn;
2389       PREV_INSN (insn) = last;
2390
2391       bb = BLOCK_FOR_INSN (last);
2392
2393       if (jump_p)
2394         {
2395           fix_jump_move (insn);
2396
2397           if (BLOCK_FOR_INSN (insn) != bb)
2398             move_block_after_check (insn);
2399
2400           gcc_assert (BB_END (bb) == last);
2401         }
2402
2403       df_insn_change_bb (insn, bb);
2404
2405       /* Update BB_END, if needed.  */
2406       if (BB_END (bb) == last)
2407         BB_END (bb) = insn;
2408     }
2409
2410   SCHED_GROUP_P (insn) = 0;
2411 }
2412
2413 /* Return true if scheduling INSN will finish current clock cycle.  */
2414 static bool
2415 insn_finishes_cycle_p (rtx insn)
2416 {
2417   if (SCHED_GROUP_P (insn))
2418     /* After issuing INSN, rest of the sched_group will be forced to issue
2419        in order.  Don't make any plans for the rest of cycle.  */
2420     return true;
2421
2422   /* Finishing the block will, apparently, finish the cycle.  */
2423   if (current_sched_info->insn_finishes_block_p
2424       && current_sched_info->insn_finishes_block_p (insn))
2425     return true;
2426
2427   return false;
2428 }
2429
2430 /* Define type for target data used in multipass scheduling.  */
2431 #ifndef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T
2432 # define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T int
2433 #endif
2434 typedef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T first_cycle_multipass_data_t;
2435
2436 /* The following structure describe an entry of the stack of choices.  */
2437 struct choice_entry
2438 {
2439   /* Ordinal number of the issued insn in the ready queue.  */
2440   int index;
2441   /* The number of the rest insns whose issues we should try.  */
2442   int rest;
2443   /* The number of issued essential insns.  */
2444   int n;
2445   /* State after issuing the insn.  */
2446   state_t state;
2447   /* Target-specific data.  */
2448   first_cycle_multipass_data_t target_data;
2449 };
2450
2451 /* The following array is used to implement a stack of choices used in
2452    function max_issue.  */
2453 static struct choice_entry *choice_stack;
2454
2455 /* The following variable value is number of essential insns issued on
2456    the current cycle.  An insn is essential one if it changes the
2457    processors state.  */
2458 int cycle_issued_insns;
2459
2460 /* This holds the value of the target dfa_lookahead hook.  */
2461 int dfa_lookahead;
2462
2463 /* The following variable value is maximal number of tries of issuing
2464    insns for the first cycle multipass insn scheduling.  We define
2465    this value as constant*(DFA_LOOKAHEAD**ISSUE_RATE).  We would not
2466    need this constraint if all real insns (with non-negative codes)
2467    had reservations because in this case the algorithm complexity is
2468    O(DFA_LOOKAHEAD**ISSUE_RATE).  Unfortunately, the dfa descriptions
2469    might be incomplete and such insn might occur.  For such
2470    descriptions, the complexity of algorithm (without the constraint)
2471    could achieve DFA_LOOKAHEAD ** N , where N is the queue length.  */
2472 static int max_lookahead_tries;
2473
2474 /* The following value is value of hook
2475    `first_cycle_multipass_dfa_lookahead' at the last call of
2476    `max_issue'.  */
2477 static int cached_first_cycle_multipass_dfa_lookahead = 0;
2478
2479 /* The following value is value of `issue_rate' at the last call of
2480    `sched_init'.  */
2481 static int cached_issue_rate = 0;
2482
2483 /* The following function returns maximal (or close to maximal) number
2484    of insns which can be issued on the same cycle and one of which
2485    insns is insns with the best rank (the first insn in READY).  To
2486    make this function tries different samples of ready insns.  READY
2487    is current queue `ready'.  Global array READY_TRY reflects what
2488    insns are already issued in this try.  The function stops immediately,
2489    if it reached the such a solution, that all instruction can be issued.
2490    INDEX will contain index of the best insn in READY.  The following
2491    function is used only for first cycle multipass scheduling.
2492
2493    PRIVILEGED_N >= 0
2494
2495    This function expects recognized insns only.  All USEs,
2496    CLOBBERs, etc must be filtered elsewhere.  */
2497 int
2498 max_issue (struct ready_list *ready, int privileged_n, state_t state,
2499            bool first_cycle_insn_p, int *index)
2500 {
2501   int n, i, all, n_ready, best, delay, tries_num;
2502   int more_issue;
2503   struct choice_entry *top;
2504   rtx insn;
2505
2506   n_ready = ready->n_ready;
2507   gcc_assert (dfa_lookahead >= 1 && privileged_n >= 0
2508               && privileged_n <= n_ready);
2509
2510   /* Init MAX_LOOKAHEAD_TRIES.  */
2511   if (cached_first_cycle_multipass_dfa_lookahead != dfa_lookahead)
2512     {
2513       cached_first_cycle_multipass_dfa_lookahead = dfa_lookahead;
2514       max_lookahead_tries = 100;
2515       for (i = 0; i < issue_rate; i++)
2516         max_lookahead_tries *= dfa_lookahead;
2517     }
2518
2519   /* Init max_points.  */
2520   more_issue = issue_rate - cycle_issued_insns;
2521   gcc_assert (more_issue >= 0);
2522
2523   /* The number of the issued insns in the best solution.  */
2524   best = 0;
2525
2526   top = choice_stack;
2527
2528   /* Set initial state of the search.  */
2529   memcpy (top->state, state, dfa_state_size);
2530   top->rest = dfa_lookahead;
2531   top->n = 0;
2532   if (targetm.sched.first_cycle_multipass_begin)
2533     targetm.sched.first_cycle_multipass_begin (&top->target_data,
2534                                                ready_try, n_ready,
2535                                                first_cycle_insn_p);
2536
2537   /* Count the number of the insns to search among.  */
2538   for (all = i = 0; i < n_ready; i++)
2539     if (!ready_try [i])
2540       all++;
2541
2542   /* I is the index of the insn to try next.  */
2543   i = 0;
2544   tries_num = 0;
2545   for (;;)
2546     {
2547       if (/* If we've reached a dead end or searched enough of what we have
2548              been asked...  */
2549           top->rest == 0
2550           /* or have nothing else to try...  */
2551           || i >= n_ready
2552           /* or should not issue more.  */
2553           || top->n >= more_issue)
2554         {
2555           /* ??? (... || i == n_ready).  */
2556           gcc_assert (i <= n_ready);
2557
2558           /* We should not issue more than issue_rate instructions.  */
2559           gcc_assert (top->n <= more_issue);
2560
2561           if (top == choice_stack)
2562             break;
2563
2564           if (best < top - choice_stack)
2565             {
2566               if (privileged_n)
2567                 {
2568                   n = privileged_n;
2569                   /* Try to find issued privileged insn.  */
2570                   while (n && !ready_try[--n]);
2571                 }
2572
2573               if (/* If all insns are equally good...  */
2574                   privileged_n == 0
2575                   /* Or a privileged insn will be issued.  */
2576                   || ready_try[n])
2577                 /* Then we have a solution.  */
2578                 {
2579                   best = top - choice_stack;
2580                   /* This is the index of the insn issued first in this
2581                      solution.  */
2582                   *index = choice_stack [1].index;
2583                   if (top->n == more_issue || best == all)
2584                     break;
2585                 }
2586             }
2587
2588           /* Set ready-list index to point to the last insn
2589              ('i++' below will advance it to the next insn).  */
2590           i = top->index;
2591
2592           /* Backtrack.  */
2593           ready_try [i] = 0;
2594
2595           if (targetm.sched.first_cycle_multipass_backtrack)
2596             targetm.sched.first_cycle_multipass_backtrack (&top->target_data,
2597                                                            ready_try, n_ready);
2598
2599           top--;
2600           memcpy (state, top->state, dfa_state_size);
2601         }
2602       else if (!ready_try [i])
2603         {
2604           tries_num++;
2605           if (tries_num > max_lookahead_tries)
2606             break;
2607           insn = ready_element (ready, i);
2608           delay = state_transition (state, insn);
2609           if (delay < 0)
2610             {
2611               if (state_dead_lock_p (state)
2612                   || insn_finishes_cycle_p (insn))
2613                 /* We won't issue any more instructions in the next
2614                    choice_state.  */
2615                 top->rest = 0;
2616               else
2617                 top->rest--;
2618
2619               n = top->n;
2620               if (memcmp (top->state, state, dfa_state_size) != 0)
2621                 n++;
2622
2623               /* Advance to the next choice_entry.  */
2624               top++;
2625               /* Initialize it.  */
2626               top->rest = dfa_lookahead;
2627               top->index = i;
2628               top->n = n;
2629               memcpy (top->state, state, dfa_state_size);
2630               ready_try [i] = 1;
2631
2632               if (targetm.sched.first_cycle_multipass_issue)
2633                 targetm.sched.first_cycle_multipass_issue (&top->target_data,
2634                                                            ready_try, n_ready,
2635                                                            insn,
2636                                                            &((top - 1)
2637                                                              ->target_data));
2638
2639               i = -1;
2640             }
2641         }
2642
2643       /* Increase ready-list index.  */
2644       i++;
2645     }
2646
2647   if (targetm.sched.first_cycle_multipass_end)
2648     targetm.sched.first_cycle_multipass_end (best != 0
2649                                              ? &choice_stack[1].target_data
2650                                              : NULL);
2651
2652   /* Restore the original state of the DFA.  */
2653   memcpy (state, choice_stack->state, dfa_state_size);
2654
2655   return best;
2656 }
2657
2658 /* The following function chooses insn from READY and modifies
2659    READY.  The following function is used only for first
2660    cycle multipass scheduling.
2661    Return:
2662    -1 if cycle should be advanced,
2663    0 if INSN_PTR is set to point to the desirable insn,
2664    1 if choose_ready () should be restarted without advancing the cycle.  */
2665 static int
2666 choose_ready (struct ready_list *ready, bool first_cycle_insn_p,
2667               rtx *insn_ptr)
2668 {
2669   int lookahead;
2670
2671   if (dbg_cnt (sched_insn) == false)
2672     {
2673       rtx insn = nonscheduled_insns_begin;
2674       do
2675         {
2676           insn = next_nonnote_insn (insn);
2677         }
2678       while (QUEUE_INDEX (insn) == QUEUE_SCHEDULED);
2679
2680       if (QUEUE_INDEX (insn) == QUEUE_READY)
2681         /* INSN is in the ready_list.  */
2682         {
2683           nonscheduled_insns_begin = insn;
2684           ready_remove_insn (insn);
2685           *insn_ptr = insn;
2686           return 0;
2687         }
2688
2689       /* INSN is in the queue.  Advance cycle to move it to the ready list.  */
2690       return -1;
2691     }
2692
2693   lookahead = 0;
2694
2695   if (targetm.sched.first_cycle_multipass_dfa_lookahead)
2696     lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
2697   if (lookahead <= 0 || SCHED_GROUP_P (ready_element (ready, 0))
2698       || DEBUG_INSN_P (ready_element (ready, 0)))
2699     {
2700       if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
2701         *insn_ptr = ready_remove_first_dispatch (ready);
2702       else
2703         *insn_ptr = ready_remove_first (ready);
2704
2705       return 0;
2706     }
2707   else
2708     {
2709       /* Try to choose the better insn.  */
2710       int index = 0, i, n;
2711       rtx insn;
2712       int try_data = 1, try_control = 1;
2713       ds_t ts;
2714
2715       insn = ready_element (ready, 0);
2716       if (INSN_CODE (insn) < 0)
2717         {
2718           *insn_ptr = ready_remove_first (ready);
2719           return 0;
2720         }
2721
2722       if (spec_info
2723           && spec_info->flags & (PREFER_NON_DATA_SPEC
2724                                  | PREFER_NON_CONTROL_SPEC))
2725         {
2726           for (i = 0, n = ready->n_ready; i < n; i++)
2727             {
2728               rtx x;
2729               ds_t s;
2730
2731               x = ready_element (ready, i);
2732               s = TODO_SPEC (x);
2733
2734               if (spec_info->flags & PREFER_NON_DATA_SPEC
2735                   && !(s & DATA_SPEC))
2736                 {
2737                   try_data = 0;
2738                   if (!(spec_info->flags & PREFER_NON_CONTROL_SPEC)
2739                       || !try_control)
2740                     break;
2741                 }
2742
2743               if (spec_info->flags & PREFER_NON_CONTROL_SPEC
2744                   && !(s & CONTROL_SPEC))
2745                 {
2746                   try_control = 0;
2747                   if (!(spec_info->flags & PREFER_NON_DATA_SPEC) || !try_data)
2748                     break;
2749                 }
2750             }
2751         }
2752
2753       ts = TODO_SPEC (insn);
2754       if ((ts & SPECULATIVE)
2755           && (((!try_data && (ts & DATA_SPEC))
2756                || (!try_control && (ts & CONTROL_SPEC)))
2757               || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard_spec
2758                   && !targetm.sched
2759                   .first_cycle_multipass_dfa_lookahead_guard_spec (insn))))
2760         /* Discard speculative instruction that stands first in the ready
2761            list.  */
2762         {
2763           change_queue_index (insn, 1);
2764           return 1;
2765         }
2766
2767       ready_try[0] = 0;
2768
2769       for (i = 1; i < ready->n_ready; i++)
2770         {
2771           insn = ready_element (ready, i);
2772
2773           ready_try [i]
2774             = ((!try_data && (TODO_SPEC (insn) & DATA_SPEC))
2775                || (!try_control && (TODO_SPEC (insn) & CONTROL_SPEC)));
2776         }
2777
2778       /* Let the target filter the search space.  */
2779       for (i = 1; i < ready->n_ready; i++)
2780         if (!ready_try[i])
2781           {
2782             insn = ready_element (ready, i);
2783
2784             /* If this insn is recognizable we should have already
2785                recognized it earlier.
2786                ??? Not very clear where this is supposed to be done.
2787                See dep_cost_1.  */
2788             gcc_checking_assert (INSN_CODE (insn) >= 0
2789                                  || recog_memoized (insn) < 0);
2790
2791             ready_try [i]
2792               = (/* INSN_CODE check can be omitted here as it is also done later
2793                     in max_issue ().  */
2794                  INSN_CODE (insn) < 0
2795                  || (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2796                      && !targetm.sched.first_cycle_multipass_dfa_lookahead_guard
2797                      (insn)));
2798           }
2799
2800       if (max_issue (ready, 1, curr_state, first_cycle_insn_p, &index) == 0)
2801         {
2802           *insn_ptr = ready_remove_first (ready);
2803           if (sched_verbose >= 4)
2804             fprintf (sched_dump, ";;\t\tChosen insn (but can't issue) : %s \n",
2805                      (*current_sched_info->print_insn) (*insn_ptr, 0));
2806           return 0;
2807         }
2808       else
2809         {
2810           if (sched_verbose >= 4)
2811             fprintf (sched_dump, ";;\t\tChosen insn : %s\n",
2812                      (*current_sched_info->print_insn)
2813                      (ready_element (ready, index), 0));
2814
2815           *insn_ptr = ready_remove (ready, index);
2816           return 0;
2817         }
2818     }
2819 }
2820
2821 /* This function is called when we have successfully scheduled a
2822    block.  It uses the schedule stored in the scheduled_insns vector
2823    to rearrange the RTL.  PREV_HEAD is used as the anchor to which we
2824    append the scheduled insns; TAIL is the insn after the scheduled
2825    block.  TARGET_BB is the argument passed to schedule_block.  */
2826
2827 static void
2828 commit_schedule (rtx prev_head, rtx tail, basic_block *target_bb)
2829 {
2830   unsigned int i;
2831   rtx insn;
2832
2833   last_scheduled_insn = prev_head;
2834   for (i = 0;
2835        VEC_iterate (rtx, scheduled_insns, i, insn);
2836        i++)
2837     {
2838       if (control_flow_insn_p (last_scheduled_insn)
2839           || current_sched_info->advance_target_bb (*target_bb, insn))
2840         {
2841           *target_bb = current_sched_info->advance_target_bb (*target_bb, 0);
2842
2843           if (sched_verbose)
2844             {
2845               rtx x;
2846
2847               x = next_real_insn (last_scheduled_insn);
2848               gcc_assert (x);
2849               dump_new_block_header (1, *target_bb, x, tail);
2850             }
2851
2852           last_scheduled_insn = bb_note (*target_bb);
2853         }
2854
2855       if (current_sched_info->begin_move_insn)
2856         (*current_sched_info->begin_move_insn) (insn, last_scheduled_insn);
2857       move_insn (insn, last_scheduled_insn,
2858                  current_sched_info->next_tail);
2859       if (!DEBUG_INSN_P (insn))
2860         reemit_notes (insn);
2861       last_scheduled_insn = insn;
2862     }
2863
2864   VEC_truncate (rtx, scheduled_insns, 0);
2865 }
2866
2867 /* Examine all insns on the ready list and queue those which can't be
2868    issued in this cycle.  TEMP_STATE is temporary scheduler state we
2869    can use as scratch space.  If FIRST_CYCLE_INSN_P is true, no insns
2870    have been issued for the current cycle, which means it is valid to
2871    issue an asm statement.  */
2872
2873 static void
2874 prune_ready_list (state_t temp_state, bool first_cycle_insn_p)
2875 {
2876   int i;
2877
2878  restart:
2879   for (i = 0; i < ready.n_ready; i++)
2880     {
2881       rtx insn = ready_element (&ready, i);
2882       int cost = 0;
2883       const char *reason = "resource conflict";
2884
2885       if (recog_memoized (insn) < 0)
2886         {
2887           if (!first_cycle_insn_p
2888               && (GET_CODE (PATTERN (insn)) == ASM_INPUT
2889                   || asm_noperands (PATTERN (insn)) >= 0))
2890             cost = 1;
2891           reason = "asm";
2892         }
2893       else if (sched_pressure_p)
2894         cost = 0;
2895       else
2896         {
2897           memcpy (temp_state, curr_state, dfa_state_size);
2898           cost = state_transition (temp_state, insn);
2899           if (cost < 0)
2900             cost = 0;
2901           else if (cost == 0)
2902             cost = 1;
2903         }
2904       if (cost >= 1)
2905         {
2906           ready_remove (&ready, i);
2907           queue_insn (insn, cost, reason);
2908           goto restart;
2909         }
2910     }
2911 }
2912
2913 /* Use forward list scheduling to rearrange insns of block pointed to by
2914    TARGET_BB, possibly bringing insns from subsequent blocks in the same
2915    region.  */
2916
2917 void
2918 schedule_block (basic_block *target_bb)
2919 {
2920   int i;
2921   bool first_cycle_insn_p;
2922   int can_issue_more;
2923   state_t temp_state = NULL;  /* It is used for multipass scheduling.  */
2924   int sort_p, advance, start_clock_var;
2925
2926   /* Head/tail info for this block.  */
2927   rtx prev_head = current_sched_info->prev_head;
2928   rtx next_tail = current_sched_info->next_tail;
2929   rtx head = NEXT_INSN (prev_head);
2930   rtx tail = PREV_INSN (next_tail);
2931
2932   /* We used to have code to avoid getting parameters moved from hard
2933      argument registers into pseudos.
2934
2935      However, it was removed when it proved to be of marginal benefit
2936      and caused problems because schedule_block and compute_forward_dependences
2937      had different notions of what the "head" insn was.  */
2938
2939   gcc_assert (head != tail || INSN_P (head));
2940
2941   haifa_recovery_bb_recently_added_p = false;
2942
2943   /* Debug info.  */
2944   if (sched_verbose)
2945     dump_new_block_header (0, *target_bb, head, tail);
2946
2947   state_reset (curr_state);
2948
2949   /* Clear the ready list.  */
2950   ready.first = ready.veclen - 1;
2951   ready.n_ready = 0;
2952   ready.n_debug = 0;
2953
2954   /* It is used for first cycle multipass scheduling.  */
2955   temp_state = alloca (dfa_state_size);
2956
2957   if (targetm.sched.init)
2958     targetm.sched.init (sched_dump, sched_verbose, ready.veclen);
2959
2960   /* We start inserting insns after PREV_HEAD.  */
2961   last_scheduled_insn = nonscheduled_insns_begin = prev_head;
2962   last_nondebug_scheduled_insn = NULL_RTX;
2963
2964   gcc_assert ((NOTE_P (last_scheduled_insn)
2965                || DEBUG_INSN_P (last_scheduled_insn))
2966               && BLOCK_FOR_INSN (last_scheduled_insn) == *target_bb);
2967
2968   /* Initialize INSN_QUEUE.  Q_SIZE is the total number of insns in the
2969      queue.  */
2970   q_ptr = 0;
2971   q_size = 0;
2972
2973   insn_queue = XALLOCAVEC (rtx, max_insn_queue_index + 1);
2974   memset (insn_queue, 0, (max_insn_queue_index + 1) * sizeof (rtx));
2975
2976   /* Start just before the beginning of time.  */
2977   clock_var = -1;
2978
2979   /* We need queue and ready lists and clock_var be initialized
2980      in try_ready () (which is called through init_ready_list ()).  */
2981   (*current_sched_info->init_ready_list) ();
2982
2983   /* The algorithm is O(n^2) in the number of ready insns at any given
2984      time in the worst case.  Before reload we are more likely to have
2985      big lists so truncate them to a reasonable size.  */
2986   if (!reload_completed
2987       && ready.n_ready - ready.n_debug > MAX_SCHED_READY_INSNS)
2988     {
2989       ready_sort (&ready);
2990
2991       /* Find first free-standing insn past MAX_SCHED_READY_INSNS.
2992          If there are debug insns, we know they're first.  */
2993       for (i = MAX_SCHED_READY_INSNS + ready.n_debug; i < ready.n_ready; i++)
2994         if (!SCHED_GROUP_P (ready_element (&ready, i)))
2995           break;
2996
2997       if (sched_verbose >= 2)
2998         {
2999           fprintf (sched_dump,
3000                    ";;\t\tReady list on entry: %d insns\n", ready.n_ready);
3001           fprintf (sched_dump,
3002                    ";;\t\t before reload => truncated to %d insns\n", i);
3003         }
3004
3005       /* Delay all insns past it for 1 cycle.  If debug counter is
3006          activated make an exception for the insn right after
3007          nonscheduled_insns_begin.  */
3008       {
3009         rtx skip_insn;
3010
3011         if (dbg_cnt (sched_insn) == false)
3012           skip_insn = next_nonnote_insn (nonscheduled_insns_begin);
3013         else
3014           skip_insn = NULL_RTX;
3015
3016         while (i < ready.n_ready)
3017           {
3018             rtx insn;
3019
3020             insn = ready_remove (&ready, i);
3021
3022             if (insn != skip_insn)
3023               queue_insn (insn, 1, "list truncated");
3024           }
3025         if (skip_insn)
3026           ready_add (&ready, skip_insn, true);
3027       }
3028     }
3029
3030   /* Now we can restore basic block notes and maintain precise cfg.  */
3031   restore_bb_notes (*target_bb);
3032
3033   last_clock_var = -1;
3034
3035   advance = 0;
3036
3037   gcc_assert (VEC_length (rtx, scheduled_insns) == 0);
3038   sort_p = TRUE;
3039   /* Loop until all the insns in BB are scheduled.  */
3040   while ((*current_sched_info->schedule_more_p) ())
3041     {
3042       do
3043         {
3044           start_clock_var = clock_var;
3045
3046           clock_var++;
3047
3048           advance_one_cycle ();
3049
3050           /* Add to the ready list all pending insns that can be issued now.
3051              If there are no ready insns, increment clock until one
3052              is ready and add all pending insns at that point to the ready
3053              list.  */
3054           queue_to_ready (&ready);
3055
3056           gcc_assert (ready.n_ready);
3057
3058           if (sched_verbose >= 2)
3059             {
3060               fprintf (sched_dump, ";;\t\tReady list after queue_to_ready:  ");
3061               debug_ready_list (&ready);
3062             }
3063           advance -= clock_var - start_clock_var;
3064         }
3065       while (advance > 0);
3066
3067       if (ready.n_ready > 0)
3068         prune_ready_list (temp_state, true);
3069       if (ready.n_ready == 0)
3070         continue;
3071
3072       first_cycle_insn_p = true;
3073       cycle_issued_insns = 0;
3074       can_issue_more = issue_rate;
3075       for (;;)
3076         {
3077           rtx insn;
3078           int cost;
3079           bool asm_p = false;
3080
3081           if (sort_p && ready.n_ready > 0)
3082             {
3083               /* Sort the ready list based on priority.  This must be
3084                  done every iteration through the loop, as schedule_insn
3085                  may have readied additional insns that will not be
3086                  sorted correctly.  */
3087               ready_sort (&ready);
3088
3089               if (sched_verbose >= 2)
3090                 {
3091                   fprintf (sched_dump, ";;\t\tReady list after ready_sort:  ");
3092                   debug_ready_list (&ready);
3093                 }
3094             }
3095
3096           /* We don't want md sched reorder to even see debug isns, so put
3097              them out right away.  */
3098           if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0))
3099               && (*current_sched_info->schedule_more_p) ())
3100             {
3101               while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
3102                 {
3103                   rtx insn = ready_remove_first (&ready);
3104                   gcc_assert (DEBUG_INSN_P (insn));
3105                   (*current_sched_info->begin_schedule_ready) (insn);
3106                   VEC_safe_push (rtx, heap, scheduled_insns, insn);
3107                   last_scheduled_insn = insn;
3108                   advance = schedule_insn (insn);
3109                   gcc_assert (advance == 0);
3110                   if (ready.n_ready > 0)
3111                     ready_sort (&ready);
3112                 }
3113             }
3114
3115           if (first_cycle_insn_p && !ready.n_ready)
3116             break;
3117
3118           /* Allow the target to reorder the list, typically for
3119              better instruction bundling.  */
3120           if (sort_p
3121               && (ready.n_ready == 0
3122                   || !SCHED_GROUP_P (ready_element (&ready, 0))))
3123             {
3124               if (first_cycle_insn_p && targetm.sched.reorder)
3125                 can_issue_more
3126                   = targetm.sched.reorder (sched_dump, sched_verbose,
3127                                            ready_lastpos (&ready),
3128                                            &ready.n_ready, clock_var);
3129               else if (!first_cycle_insn_p && targetm.sched.reorder2)
3130                 can_issue_more
3131                   = targetm.sched.reorder2 (sched_dump, sched_verbose,
3132                                             ready.n_ready
3133                                             ? ready_lastpos (&ready) : NULL,
3134                                             &ready.n_ready, clock_var);
3135             }
3136
3137         restart_choose_ready:
3138           if (sched_verbose >= 2)
3139             {
3140               fprintf (sched_dump, ";;\tReady list (t = %3d):  ",
3141                        clock_var);
3142               debug_ready_list (&ready);
3143               if (sched_pressure_p)
3144                 print_curr_reg_pressure ();
3145             }
3146
3147           if (ready.n_ready == 0
3148               && can_issue_more
3149               && reload_completed)
3150             {
3151               /* Allow scheduling insns directly from the queue in case
3152                  there's nothing better to do (ready list is empty) but
3153                  there are still vacant dispatch slots in the current cycle.  */
3154               if (sched_verbose >= 6)
3155                 fprintf (sched_dump,";;\t\tSecond chance\n");
3156               memcpy (temp_state, curr_state, dfa_state_size);
3157               if (early_queue_to_ready (temp_state, &ready))
3158                 ready_sort (&ready);
3159             }
3160
3161           if (ready.n_ready == 0
3162               || !can_issue_more
3163               || state_dead_lock_p (curr_state)
3164               || !(*current_sched_info->schedule_more_p) ())
3165             break;
3166
3167           /* Select and remove the insn from the ready list.  */
3168           if (sort_p)
3169             {
3170               int res;
3171
3172               insn = NULL_RTX;
3173               res = choose_ready (&ready, first_cycle_insn_p, &insn);
3174
3175               if (res < 0)
3176                 /* Finish cycle.  */
3177                 break;
3178               if (res > 0)
3179                 goto restart_choose_ready;
3180
3181               gcc_assert (insn != NULL_RTX);
3182             }
3183           else
3184             insn = ready_remove_first (&ready);
3185
3186           if (sched_pressure_p && INSN_TICK (insn) > clock_var)
3187             {
3188               ready_add (&ready, insn, true);
3189               advance = 1;
3190               break;
3191             }
3192
3193           if (targetm.sched.dfa_new_cycle
3194               && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
3195                                               insn, last_clock_var,
3196                                               clock_var, &sort_p))
3197             /* SORT_P is used by the target to override sorting
3198                of the ready list.  This is needed when the target
3199                has modified its internal structures expecting that
3200                the insn will be issued next.  As we need the insn
3201                to have the highest priority (so it will be returned by
3202                the ready_remove_first call above), we invoke
3203                ready_add (&ready, insn, true).
3204                But, still, there is one issue: INSN can be later
3205                discarded by scheduler's front end through
3206                current_sched_info->can_schedule_ready_p, hence, won't
3207                be issued next.  */
3208             {
3209               ready_add (&ready, insn, true);
3210               break;
3211             }
3212
3213           sort_p = TRUE;
3214
3215           if (current_sched_info->can_schedule_ready_p
3216               && ! (*current_sched_info->can_schedule_ready_p) (insn))
3217             /* We normally get here only if we don't want to move
3218                insn from the split block.  */
3219             {
3220               TODO_SPEC (insn) = (TODO_SPEC (insn) & ~SPECULATIVE) | HARD_DEP;
3221               goto restart_choose_ready;
3222             }
3223
3224           /* DECISION is made.  */
3225
3226           if (TODO_SPEC (insn) & SPECULATIVE)
3227             generate_recovery_code (insn);
3228
3229           if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
3230             targetm.sched.dispatch_do (insn, ADD_TO_DISPATCH_WINDOW);
3231
3232           /* Update counters, etc in the scheduler's front end.  */
3233           (*current_sched_info->begin_schedule_ready) (insn);
3234           VEC_safe_push (rtx, heap, scheduled_insns, insn);
3235           gcc_assert (NONDEBUG_INSN_P (insn));
3236           last_nondebug_scheduled_insn = last_scheduled_insn = insn;
3237
3238           if (recog_memoized (insn) >= 0)
3239             {
3240               memcpy (temp_state, curr_state, dfa_state_size);
3241               cost = state_transition (curr_state, insn);
3242               if (!sched_pressure_p)
3243                 gcc_assert (cost < 0);
3244               if (memcmp (temp_state, curr_state, dfa_state_size) != 0)
3245                 cycle_issued_insns++;
3246               asm_p = false;
3247             }
3248           else
3249             asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
3250                      || asm_noperands (PATTERN (insn)) >= 0);
3251
3252           if (targetm.sched.variable_issue)
3253             can_issue_more =
3254               targetm.sched.variable_issue (sched_dump, sched_verbose,
3255                                             insn, can_issue_more);
3256           /* A naked CLOBBER or USE generates no instruction, so do
3257              not count them against the issue rate.  */
3258           else if (GET_CODE (PATTERN (insn)) != USE
3259                    && GET_CODE (PATTERN (insn)) != CLOBBER)
3260             can_issue_more--;
3261           advance = schedule_insn (insn);
3262
3263           /* After issuing an asm insn we should start a new cycle.  */
3264           if (advance == 0 && asm_p)
3265             advance = 1;
3266           if (advance != 0)
3267             break;
3268
3269           first_cycle_insn_p = false;
3270           if (ready.n_ready > 0)
3271             prune_ready_list (temp_state, false);
3272         }
3273     }
3274
3275   /* Debug info.  */
3276   if (sched_verbose)
3277     {
3278       fprintf (sched_dump, ";;\tReady list (final):  ");
3279       debug_ready_list (&ready);
3280     }
3281
3282   if (current_sched_info->queue_must_finish_empty)
3283     /* Sanity check -- queue must be empty now.  Meaningless if region has
3284        multiple bbs.  */
3285     gcc_assert (!q_size && !ready.n_ready && !ready.n_debug);
3286   else
3287     {
3288       /* We must maintain QUEUE_INDEX between blocks in region.  */
3289       for (i = ready.n_ready - 1; i >= 0; i--)
3290         {
3291           rtx x;
3292
3293           x = ready_element (&ready, i);
3294           QUEUE_INDEX (x) = QUEUE_NOWHERE;
3295           TODO_SPEC (x) = (TODO_SPEC (x) & ~SPECULATIVE) | HARD_DEP;
3296         }
3297
3298       if (q_size)
3299         for (i = 0; i <= max_insn_queue_index; i++)
3300           {
3301             rtx link;
3302             for (link = insn_queue[i]; link; link = XEXP (link, 1))
3303               {
3304                 rtx x;
3305
3306                 x = XEXP (link, 0);
3307                 QUEUE_INDEX (x) = QUEUE_NOWHERE;
3308                 TODO_SPEC (x) = (TODO_SPEC (x) & ~SPECULATIVE) | HARD_DEP;
3309               }
3310             free_INSN_LIST_list (&insn_queue[i]);
3311           }
3312     }
3313
3314   commit_schedule (prev_head, tail, target_bb);
3315   if (sched_verbose)
3316     fprintf (sched_dump, ";;   total time = %d\n", clock_var);
3317
3318   if (!current_sched_info->queue_must_finish_empty
3319       || haifa_recovery_bb_recently_added_p)
3320     {
3321       /* INSN_TICK (minimum clock tick at which the insn becomes
3322          ready) may be not correct for the insn in the subsequent
3323          blocks of the region.  We should use a correct value of
3324          `clock_var' or modify INSN_TICK.  It is better to keep
3325          clock_var value equal to 0 at the start of a basic block.
3326          Therefore we modify INSN_TICK here.  */
3327       fix_inter_tick (NEXT_INSN (prev_head), last_scheduled_insn);
3328     }
3329
3330   if (targetm.sched.finish)
3331     {
3332       targetm.sched.finish (sched_dump, sched_verbose);
3333       /* Target might have added some instructions to the scheduled block
3334          in its md_finish () hook.  These new insns don't have any data
3335          initialized and to identify them we extend h_i_d so that they'll
3336          get zero luids.  */
3337       sched_extend_luids ();
3338     }
3339
3340   if (sched_verbose)
3341     fprintf (sched_dump, ";;   new head = %d\n;;   new tail = %d\n\n",
3342              INSN_UID (head), INSN_UID (tail));
3343
3344   /* Update head/tail boundaries.  */
3345   head = NEXT_INSN (prev_head);
3346   tail = last_scheduled_insn;
3347
3348   head = restore_other_notes (head, NULL);
3349
3350   current_sched_info->head = head;
3351   current_sched_info->tail = tail;
3352 }
3353 \f
3354 /* Set_priorities: compute priority of each insn in the block.  */
3355
3356 int
3357 set_priorities (rtx head, rtx tail)
3358 {
3359   rtx insn;
3360   int n_insn;
3361   int sched_max_insns_priority =
3362         current_sched_info->sched_max_insns_priority;
3363   rtx prev_head;
3364
3365   if (head == tail && ! INSN_P (head))
3366     gcc_unreachable ();
3367
3368   n_insn = 0;
3369
3370   prev_head = PREV_INSN (head);
3371   for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
3372     {
3373       if (!INSN_P (insn))
3374         continue;
3375
3376       n_insn++;
3377       (void) priority (insn);
3378
3379       gcc_assert (INSN_PRIORITY_KNOWN (insn));
3380
3381       sched_max_insns_priority = MAX (sched_max_insns_priority,
3382                                       INSN_PRIORITY (insn));
3383     }
3384
3385   current_sched_info->sched_max_insns_priority = sched_max_insns_priority;
3386
3387   return n_insn;
3388 }
3389
3390 /* Set dump and sched_verbose for the desired debugging output.  If no
3391    dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
3392    For -fsched-verbose=N, N>=10, print everything to stderr.  */
3393 void
3394 setup_sched_dump (void)
3395 {
3396   sched_verbose = sched_verbose_param;
3397   if (sched_verbose_param == 0 && dump_file)
3398     sched_verbose = 1;
3399   sched_dump = ((sched_verbose_param >= 10 || !dump_file)
3400                 ? stderr : dump_file);
3401 }
3402
3403 /* Initialize some global state for the scheduler.  This function works
3404    with the common data shared between all the schedulers.  It is called
3405    from the scheduler specific initialization routine.  */
3406
3407 void
3408 sched_init (void)
3409 {
3410   /* Disable speculative loads in their presence if cc0 defined.  */
3411 #ifdef HAVE_cc0
3412   flag_schedule_speculative_load = 0;
3413 #endif
3414
3415   if (targetm.sched.dispatch (NULL_RTX, IS_DISPATCH_ON))
3416     targetm.sched.dispatch_do (NULL_RTX, DISPATCH_INIT);
3417
3418   sched_pressure_p = (flag_sched_pressure && ! reload_completed
3419                       && common_sched_info->sched_pass_id == SCHED_RGN_PASS);
3420
3421   if (sched_pressure_p)
3422     ira_setup_eliminable_regset ();
3423
3424   /* Initialize SPEC_INFO.  */
3425   if (targetm.sched.set_sched_flags)
3426     {
3427       spec_info = &spec_info_var;
3428       targetm.sched.set_sched_flags (spec_info);
3429
3430       if (spec_info->mask != 0)
3431         {
3432           spec_info->data_weakness_cutoff =
3433             (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
3434           spec_info->control_weakness_cutoff =
3435             (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF)
3436              * REG_BR_PROB_BASE) / 100;
3437         }
3438       else
3439         /* So we won't read anything accidentally.  */
3440         spec_info = NULL;
3441
3442     }
3443   else
3444     /* So we won't read anything accidentally.  */
3445     spec_info = 0;
3446
3447   /* Initialize issue_rate.  */
3448   if (targetm.sched.issue_rate)
3449     issue_rate = targetm.sched.issue_rate ();
3450   else
3451     issue_rate = 1;
3452
3453   if (cached_issue_rate != issue_rate)
3454     {
3455       cached_issue_rate = issue_rate;
3456       /* To invalidate max_lookahead_tries:  */
3457       cached_first_cycle_multipass_dfa_lookahead = 0;
3458     }
3459
3460   if (targetm.sched.first_cycle_multipass_dfa_lookahead)
3461     dfa_lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
3462   else
3463     dfa_lookahead = 0;
3464
3465   if (targetm.sched.init_dfa_pre_cycle_insn)
3466     targetm.sched.init_dfa_pre_cycle_insn ();
3467
3468   if (targetm.sched.init_dfa_post_cycle_insn)
3469     targetm.sched.init_dfa_post_cycle_insn ();
3470
3471   dfa_start ();
3472   dfa_state_size = state_size ();
3473
3474   init_alias_analysis ();
3475
3476   df_set_flags (DF_LR_RUN_DCE);
3477   df_note_add_problem ();
3478
3479   /* More problems needed for interloop dep calculation in SMS.  */
3480   if (common_sched_info->sched_pass_id == SCHED_SMS_PASS)
3481     {
3482       df_rd_add_problem ();
3483       df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
3484     }
3485
3486   df_analyze ();
3487
3488   /* Do not run DCE after reload, as this can kill nops inserted
3489      by bundling.  */
3490   if (reload_completed)
3491     df_clear_flags (DF_LR_RUN_DCE);
3492
3493   regstat_compute_calls_crossed ();
3494
3495   if (targetm.sched.init_global)
3496     targetm.sched.init_global (sched_dump, sched_verbose, get_max_uid () + 1);
3497
3498   if (sched_pressure_p)
3499     {
3500       int i, max_regno = max_reg_num ();
3501
3502       ira_set_pseudo_classes (sched_verbose ? sched_dump : NULL);
3503       sched_regno_pressure_class
3504         = (enum reg_class *) xmalloc (max_regno * sizeof (enum reg_class));
3505       for (i = 0; i < max_regno; i++)
3506         sched_regno_pressure_class[i]
3507           = (i < FIRST_PSEUDO_REGISTER
3508              ? ira_pressure_class_translate[REGNO_REG_CLASS (i)]
3509              : ira_pressure_class_translate[reg_allocno_class (i)]);
3510       curr_reg_live = BITMAP_ALLOC (NULL);
3511       saved_reg_live = BITMAP_ALLOC (NULL);
3512       region_ref_regs = BITMAP_ALLOC (NULL);
3513     }
3514
3515   curr_state = xmalloc (dfa_state_size);
3516 }
3517
3518 static void haifa_init_only_bb (basic_block, basic_block);
3519
3520 /* Initialize data structures specific to the Haifa scheduler.  */
3521 void
3522 haifa_sched_init (void)
3523 {
3524   setup_sched_dump ();
3525   sched_init ();
3526
3527   scheduled_insns = VEC_alloc (rtx, heap, 0);
3528
3529   if (spec_info != NULL)
3530     {
3531       sched_deps_info->use_deps_list = 1;
3532       sched_deps_info->generate_spec_deps = 1;
3533     }
3534
3535   /* Initialize luids, dependency caches, target and h_i_d for the
3536      whole function.  */
3537   {
3538     bb_vec_t bbs = VEC_alloc (basic_block, heap, n_basic_blocks);
3539     basic_block bb;
3540
3541     sched_init_bbs ();
3542
3543     FOR_EACH_BB (bb)
3544       VEC_quick_push (basic_block, bbs, bb);
3545     sched_init_luids (bbs);
3546     sched_deps_init (true);
3547     sched_extend_target ();
3548     haifa_init_h_i_d (bbs);
3549
3550     VEC_free (basic_block, heap, bbs);
3551   }
3552
3553   sched_init_only_bb = haifa_init_only_bb;
3554   sched_split_block = sched_split_block_1;
3555   sched_create_empty_bb = sched_create_empty_bb_1;
3556   haifa_recovery_bb_ever_added_p = false;
3557
3558 #ifdef ENABLE_CHECKING
3559   /* This is used preferably for finding bugs in check_cfg () itself.
3560      We must call sched_bbs_init () before check_cfg () because check_cfg ()
3561      assumes that the last insn in the last bb has a non-null successor.  */
3562   check_cfg (0, 0);
3563 #endif
3564
3565   nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
3566   before_recovery = 0;
3567   after_recovery = 0;
3568 }
3569
3570 /* Finish work with the data specific to the Haifa scheduler.  */
3571 void
3572 haifa_sched_finish (void)
3573 {
3574   sched_create_empty_bb = NULL;
3575   sched_split_block = NULL;
3576   sched_init_only_bb = NULL;
3577
3578   if (spec_info && spec_info->dump)
3579     {
3580       char c = reload_completed ? 'a' : 'b';
3581
3582       fprintf (spec_info->dump,
3583                ";; %s:\n", current_function_name ());
3584
3585       fprintf (spec_info->dump,
3586                ";; Procedure %cr-begin-data-spec motions == %d\n",
3587                c, nr_begin_data);
3588       fprintf (spec_info->dump,
3589                ";; Procedure %cr-be-in-data-spec motions == %d\n",
3590                c, nr_be_in_data);
3591       fprintf (spec_info->dump,
3592                ";; Procedure %cr-begin-control-spec motions == %d\n",
3593                c, nr_begin_control);
3594       fprintf (spec_info->dump,
3595                ";; Procedure %cr-be-in-control-spec motions == %d\n",
3596                c, nr_be_in_control);
3597     }
3598
3599   VEC_free (rtx, heap, scheduled_insns);
3600
3601   /* Finalize h_i_d, dependency caches, and luids for the whole
3602      function.  Target will be finalized in md_global_finish ().  */
3603   sched_deps_finish ();
3604   sched_finish_luids ();
3605   current_sched_info = NULL;
3606   sched_finish ();
3607 }
3608
3609 /* Free global data used during insn scheduling.  This function works with
3610    the common data shared between the schedulers.  */
3611
3612 void
3613 sched_finish (void)
3614 {
3615   haifa_finish_h_i_d ();
3616   if (sched_pressure_p)
3617     {
3618       free (sched_regno_pressure_class);
3619       BITMAP_FREE (region_ref_regs);
3620       BITMAP_FREE (saved_reg_live);
3621       BITMAP_FREE (curr_reg_live);
3622     }
3623   free (curr_state);
3624
3625   if (targetm.sched.finish_global)
3626     targetm.sched.finish_global (sched_dump, sched_verbose);
3627
3628   end_alias_analysis ();
3629
3630   regstat_free_calls_crossed ();
3631
3632   dfa_finish ();
3633
3634 #ifdef ENABLE_CHECKING
3635   /* After reload ia64 backend clobbers CFG, so can't check anything.  */
3636   if (!reload_completed)
3637     check_cfg (0, 0);
3638 #endif
3639 }
3640
3641 /* Fix INSN_TICKs of the instructions in the current block as well as
3642    INSN_TICKs of their dependents.
3643    HEAD and TAIL are the begin and the end of the current scheduled block.  */
3644 static void
3645 fix_inter_tick (rtx head, rtx tail)
3646 {
3647   /* Set of instructions with corrected INSN_TICK.  */
3648   bitmap_head processed;
3649   /* ??? It is doubtful if we should assume that cycle advance happens on
3650      basic block boundaries.  Basically insns that are unconditionally ready
3651      on the start of the block are more preferable then those which have
3652      a one cycle dependency over insn from the previous block.  */
3653   int next_clock = clock_var + 1;
3654
3655   bitmap_initialize (&processed, 0);
3656
3657   /* Iterates over scheduled instructions and fix their INSN_TICKs and
3658      INSN_TICKs of dependent instructions, so that INSN_TICKs are consistent
3659      across different blocks.  */
3660   for (tail = NEXT_INSN (tail); head != tail; head = NEXT_INSN (head))
3661     {
3662       if (INSN_P (head))
3663         {
3664           int tick;
3665           sd_iterator_def sd_it;
3666           dep_t dep;
3667
3668           tick = INSN_TICK (head);
3669           gcc_assert (tick >= MIN_TICK);
3670
3671           /* Fix INSN_TICK of instruction from just scheduled block.  */
3672           if (bitmap_set_bit (&processed, INSN_LUID (head)))
3673             {
3674               tick -= next_clock;
3675
3676               if (tick < MIN_TICK)
3677                 tick = MIN_TICK;
3678
3679               INSN_TICK (head) = tick;
3680             }
3681
3682           FOR_EACH_DEP (head, SD_LIST_RES_FORW, sd_it, dep)
3683             {
3684               rtx next;
3685
3686               next = DEP_CON (dep);
3687               tick = INSN_TICK (next);
3688
3689               if (tick != INVALID_TICK
3690                   /* If NEXT has its INSN_TICK calculated, fix it.
3691                      If not - it will be properly calculated from
3692                      scratch later in fix_tick_ready.  */
3693                   && bitmap_set_bit (&processed, INSN_LUID (next)))
3694                 {
3695                   tick -= next_clock;
3696
3697                   if (tick < MIN_TICK)
3698                     tick = MIN_TICK;
3699
3700                   if (tick > INTER_TICK (next))
3701                     INTER_TICK (next) = tick;
3702                   else
3703                     tick = INTER_TICK (next);
3704
3705                   INSN_TICK (next) = tick;
3706                 }
3707             }
3708         }
3709     }
3710   bitmap_clear (&processed);
3711 }
3712
3713 static int haifa_speculate_insn (rtx, ds_t, rtx *);
3714
3715 /* Check if NEXT is ready to be added to the ready or queue list.
3716    If "yes", add it to the proper list.
3717    Returns:
3718       -1 - is not ready yet,
3719        0 - added to the ready list,
3720    0 < N - queued for N cycles.  */
3721 int
3722 try_ready (rtx next)
3723 {
3724   ds_t old_ts, *ts;
3725
3726   ts = &TODO_SPEC (next);
3727   old_ts = *ts;
3728
3729   gcc_assert (!(old_ts & ~(SPECULATIVE | HARD_DEP))
3730               && ((old_ts & HARD_DEP)
3731                   || (old_ts & SPECULATIVE)));
3732
3733   if (sd_lists_empty_p (next, SD_LIST_BACK))
3734     /* NEXT has all its dependencies resolved.  */
3735     {
3736       /* Remove HARD_DEP bit from NEXT's status.  */
3737       *ts &= ~HARD_DEP;
3738
3739       if (current_sched_info->flags & DO_SPECULATION)
3740         /* Remove all speculative bits from NEXT's status.  */
3741         *ts &= ~SPECULATIVE;
3742     }
3743   else
3744     {
3745       /* One of the NEXT's dependencies has been resolved.
3746          Recalculate NEXT's status.  */
3747
3748       *ts &= ~SPECULATIVE & ~HARD_DEP;
3749
3750       if (sd_lists_empty_p (next, SD_LIST_HARD_BACK))
3751         /* Now we've got NEXT with speculative deps only.
3752            1. Look at the deps to see what we have to do.
3753            2. Check if we can do 'todo'.  */
3754         {
3755           sd_iterator_def sd_it;
3756           dep_t dep;
3757           bool first_p = true;
3758
3759           FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
3760             {
3761               ds_t ds = DEP_STATUS (dep) & SPECULATIVE;
3762
3763               if (DEBUG_INSN_P (DEP_PRO (dep))
3764                   && !DEBUG_INSN_P (next))
3765                 continue;
3766
3767               if (first_p)
3768                 {
3769                   first_p = false;
3770
3771                   *ts = ds;
3772                 }
3773               else
3774                 *ts = ds_merge (*ts, ds);
3775             }
3776
3777           if (ds_weak (*ts) < spec_info->data_weakness_cutoff)
3778             /* Too few points.  */
3779             *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
3780         }
3781       else
3782         *ts |= HARD_DEP;
3783     }
3784
3785   if (*ts & HARD_DEP)
3786     gcc_assert (*ts == old_ts
3787                 && QUEUE_INDEX (next) == QUEUE_NOWHERE);
3788   else if (current_sched_info->new_ready)
3789     *ts = current_sched_info->new_ready (next, *ts);
3790
3791   /* * if !(old_ts & SPECULATIVE) (e.g. HARD_DEP or 0), then insn might
3792      have its original pattern or changed (speculative) one.  This is due
3793      to changing ebb in region scheduling.
3794      * But if (old_ts & SPECULATIVE), then we are pretty sure that insn
3795      has speculative pattern.
3796
3797      We can't assert (!(*ts & HARD_DEP) || *ts == old_ts) here because
3798      control-speculative NEXT could have been discarded by sched-rgn.c
3799      (the same case as when discarded by can_schedule_ready_p ()).  */
3800
3801   if ((*ts & SPECULATIVE)
3802       /* If (old_ts == *ts), then (old_ts & SPECULATIVE) and we don't
3803          need to change anything.  */
3804       && *ts != old_ts)
3805     {
3806       int res;
3807       rtx new_pat;
3808
3809       gcc_assert ((*ts & SPECULATIVE) && !(*ts & ~SPECULATIVE));
3810
3811       res = haifa_speculate_insn (next, *ts, &new_pat);
3812
3813       switch (res)
3814         {
3815         case -1:
3816           /* It would be nice to change DEP_STATUS of all dependences,
3817              which have ((DEP_STATUS & SPECULATIVE) == *ts) to HARD_DEP,
3818              so we won't reanalyze anything.  */
3819           *ts = (*ts & ~SPECULATIVE) | HARD_DEP;
3820           break;
3821
3822         case 0:
3823           /* We follow the rule, that every speculative insn
3824              has non-null ORIG_PAT.  */
3825           if (!ORIG_PAT (next))
3826             ORIG_PAT (next) = PATTERN (next);
3827           break;
3828
3829         case 1:
3830           if (!ORIG_PAT (next))
3831             /* If we gonna to overwrite the original pattern of insn,
3832                save it.  */
3833             ORIG_PAT (next) = PATTERN (next);
3834
3835           haifa_change_pattern (next, new_pat);
3836           break;
3837
3838         default:
3839           gcc_unreachable ();
3840         }
3841     }
3842
3843   /* We need to restore pattern only if (*ts == 0), because otherwise it is
3844      either correct (*ts & SPECULATIVE),
3845      or we simply don't care (*ts & HARD_DEP).  */
3846
3847   gcc_assert (!ORIG_PAT (next)
3848               || !IS_SPECULATION_BRANCHY_CHECK_P (next));
3849
3850   if (*ts & HARD_DEP)
3851     {
3852       /* We can't assert (QUEUE_INDEX (next) == QUEUE_NOWHERE) here because
3853          control-speculative NEXT could have been discarded by sched-rgn.c
3854          (the same case as when discarded by can_schedule_ready_p ()).  */
3855       /*gcc_assert (QUEUE_INDEX (next) == QUEUE_NOWHERE);*/
3856
3857       change_queue_index (next, QUEUE_NOWHERE);
3858       return -1;
3859     }
3860   else if (!(*ts & BEGIN_SPEC) && ORIG_PAT (next) && !IS_SPECULATION_CHECK_P (next))
3861     /* We should change pattern of every previously speculative
3862        instruction - and we determine if NEXT was speculative by using
3863        ORIG_PAT field.  Except one case - speculation checks have ORIG_PAT
3864        pat too, so skip them.  */
3865     {
3866       haifa_change_pattern (next, ORIG_PAT (next));
3867       ORIG_PAT (next) = 0;
3868     }
3869
3870   if (sched_verbose >= 2)
3871     {
3872       int s = TODO_SPEC (next);
3873
3874       fprintf (sched_dump, ";;\t\tdependencies resolved: insn %s",
3875                (*current_sched_info->print_insn) (next, 0));
3876
3877       if (spec_info && spec_info->dump)
3878         {
3879           if (s & BEGIN_DATA)
3880             fprintf (spec_info->dump, "; data-spec;");
3881           if (s & BEGIN_CONTROL)
3882             fprintf (spec_info->dump, "; control-spec;");
3883           if (s & BE_IN_CONTROL)
3884             fprintf (spec_info->dump, "; in-control-spec;");
3885         }
3886
3887       fprintf (sched_dump, "\n");
3888     }
3889
3890   adjust_priority (next);
3891
3892   return fix_tick_ready (next);
3893 }
3894
3895 /* Calculate INSN_TICK of NEXT and add it to either ready or queue list.  */
3896 static int
3897 fix_tick_ready (rtx next)
3898 {
3899   int tick, delay;
3900
3901   if (!DEBUG_INSN_P (next) && !sd_lists_empty_p (next, SD_LIST_RES_BACK))
3902     {
3903       int full_p;
3904       sd_iterator_def sd_it;
3905       dep_t dep;
3906
3907       tick = INSN_TICK (next);
3908       /* if tick is not equal to INVALID_TICK, then update
3909          INSN_TICK of NEXT with the most recent resolved dependence
3910          cost.  Otherwise, recalculate from scratch.  */
3911       full_p = (tick == INVALID_TICK);
3912
3913       FOR_EACH_DEP (next, SD_LIST_RES_BACK, sd_it, dep)
3914         {
3915           rtx pro = DEP_PRO (dep);
3916           int tick1;
3917
3918           gcc_assert (INSN_TICK (pro) >= MIN_TICK);
3919
3920           tick1 = INSN_TICK (pro) + dep_cost (dep);
3921           if (tick1 > tick)
3922             tick = tick1;
3923
3924           if (!full_p)
3925             break;
3926         }
3927     }
3928   else
3929     tick = -1;
3930
3931   INSN_TICK (next) = tick;
3932
3933   delay = tick - clock_var;
3934   if (delay <= 0 || sched_pressure_p)
3935     delay = QUEUE_READY;
3936
3937   change_queue_index (next, delay);
3938
3939   return delay;
3940 }
3941
3942 /* Move NEXT to the proper queue list with (DELAY >= 1),
3943    or add it to the ready list (DELAY == QUEUE_READY),
3944    or remove it from ready and queue lists at all (DELAY == QUEUE_NOWHERE).  */
3945 static void
3946 change_queue_index (rtx next, int delay)
3947 {
3948   int i = QUEUE_INDEX (next);
3949
3950   gcc_assert (QUEUE_NOWHERE <= delay && delay <= max_insn_queue_index
3951               && delay != 0);
3952   gcc_assert (i != QUEUE_SCHEDULED);
3953
3954   if ((delay > 0 && NEXT_Q_AFTER (q_ptr, delay) == i)
3955       || (delay < 0 && delay == i))
3956     /* We have nothing to do.  */
3957     return;
3958
3959   /* Remove NEXT from wherever it is now.  */
3960   if (i == QUEUE_READY)
3961     ready_remove_insn (next);
3962   else if (i >= 0)
3963     queue_remove (next);
3964
3965   /* Add it to the proper place.  */
3966   if (delay == QUEUE_READY)
3967     ready_add (readyp, next, false);
3968   else if (delay >= 1)
3969     queue_insn (next, delay, "change queue index");
3970
3971   if (sched_verbose >= 2)
3972     {
3973       fprintf (sched_dump, ";;\t\ttick updated: insn %s",
3974                (*current_sched_info->print_insn) (next, 0));
3975
3976       if (delay == QUEUE_READY)
3977         fprintf (sched_dump, " into ready\n");
3978       else if (delay >= 1)
3979         fprintf (sched_dump, " into queue with cost=%d\n", delay);
3980       else
3981         fprintf (sched_dump, " removed from ready or queue lists\n");
3982     }
3983 }
3984
3985 static int sched_ready_n_insns = -1;
3986
3987 /* Initialize per region data structures.  */
3988 void
3989 sched_extend_ready_list (int new_sched_ready_n_insns)
3990 {
3991   int i;
3992
3993   if (sched_ready_n_insns == -1)
3994     /* At the first call we need to initialize one more choice_stack
3995        entry.  */
3996     {
3997       i = 0;
3998       sched_ready_n_insns = 0;
3999       VEC_reserve (rtx, heap, scheduled_insns, new_sched_ready_n_insns);
4000     }
4001   else
4002     i = sched_ready_n_insns + 1;
4003
4004   ready.veclen = new_sched_ready_n_insns + issue_rate;
4005   ready.vec = XRESIZEVEC (rtx, ready.vec, ready.veclen);
4006
4007   gcc_assert (new_sched_ready_n_insns >= sched_ready_n_insns);
4008
4009   ready_try = (char *) xrecalloc (ready_try, new_sched_ready_n_insns,
4010                                   sched_ready_n_insns, sizeof (*ready_try));
4011
4012   /* We allocate +1 element to save initial state in the choice_stack[0]
4013      entry.  */
4014   choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
4015                              new_sched_ready_n_insns + 1);
4016
4017   for (; i <= new_sched_ready_n_insns; i++)
4018     {
4019       choice_stack[i].state = xmalloc (dfa_state_size);
4020
4021       if (targetm.sched.first_cycle_multipass_init)
4022         targetm.sched.first_cycle_multipass_init (&(choice_stack[i]
4023                                                     .target_data));
4024     }
4025
4026   sched_ready_n_insns = new_sched_ready_n_insns;
4027 }
4028
4029 /* Free per region data structures.  */
4030 void
4031 sched_finish_ready_list (void)
4032 {
4033   int i;
4034
4035   free (ready.vec);
4036   ready.vec = NULL;
4037   ready.veclen = 0;
4038
4039   free (ready_try);
4040   ready_try = NULL;
4041
4042   for (i = 0; i <= sched_ready_n_insns; i++)
4043     {
4044       if (targetm.sched.first_cycle_multipass_fini)
4045         targetm.sched.first_cycle_multipass_fini (&(choice_stack[i]
4046                                                     .target_data));
4047
4048       free (choice_stack [i].state);
4049     }
4050   free (choice_stack);
4051   choice_stack = NULL;
4052
4053   sched_ready_n_insns = -1;
4054 }
4055
4056 static int
4057 haifa_luid_for_non_insn (rtx x)
4058 {
4059   gcc_assert (NOTE_P (x) || LABEL_P (x));
4060
4061   return 0;
4062 }
4063
4064 /* Generates recovery code for INSN.  */
4065 static void
4066 generate_recovery_code (rtx insn)
4067 {
4068   if (TODO_SPEC (insn) & BEGIN_SPEC)
4069     begin_speculative_block (insn);
4070
4071   /* Here we have insn with no dependencies to
4072      instructions other then CHECK_SPEC ones.  */
4073
4074   if (TODO_SPEC (insn) & BE_IN_SPEC)
4075     add_to_speculative_block (insn);
4076 }
4077
4078 /* Helper function.
4079    Tries to add speculative dependencies of type FS between instructions
4080    in deps_list L and TWIN.  */
4081 static void
4082 process_insn_forw_deps_be_in_spec (rtx insn, rtx twin, ds_t fs)
4083 {
4084   sd_iterator_def sd_it;
4085   dep_t dep;
4086
4087   FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
4088     {
4089       ds_t ds;
4090       rtx consumer;
4091
4092       consumer = DEP_CON (dep);
4093
4094       ds = DEP_STATUS (dep);
4095
4096       if (/* If we want to create speculative dep.  */
4097           fs
4098           /* And we can do that because this is a true dep.  */
4099           && (ds & DEP_TYPES) == DEP_TRUE)
4100         {
4101           gcc_assert (!(ds & BE_IN_SPEC));
4102
4103           if (/* If this dep can be overcome with 'begin speculation'.  */
4104               ds & BEGIN_SPEC)
4105             /* Then we have a choice: keep the dep 'begin speculative'
4106                or transform it into 'be in speculative'.  */
4107             {
4108               if (/* In try_ready we assert that if insn once became ready
4109                      it can be removed from the ready (or queue) list only
4110                      due to backend decision.  Hence we can't let the
4111                      probability of the speculative dep to decrease.  */
4112                   ds_weak (ds) <= ds_weak (fs))
4113                 {
4114                   ds_t new_ds;
4115
4116                   new_ds = (ds & ~BEGIN_SPEC) | fs;
4117
4118                   if (/* consumer can 'be in speculative'.  */
4119                       sched_insn_is_legitimate_for_speculation_p (consumer,
4120                                                                   new_ds))
4121                     /* Transform it to be in speculative.  */
4122                     ds = new_ds;
4123                 }
4124             }
4125           else
4126             /* Mark the dep as 'be in speculative'.  */
4127             ds |= fs;
4128         }
4129
4130       {
4131         dep_def _new_dep, *new_dep = &_new_dep;
4132
4133         init_dep_1 (new_dep, twin, consumer, DEP_TYPE (dep), ds);
4134         sd_add_dep (new_dep, false);
4135       }
4136     }
4137 }
4138
4139 /* Generates recovery code for BEGIN speculative INSN.  */
4140 static void
4141 begin_speculative_block (rtx insn)
4142 {
4143   if (TODO_SPEC (insn) & BEGIN_DATA)
4144     nr_begin_data++;
4145   if (TODO_SPEC (insn) & BEGIN_CONTROL)
4146     nr_begin_control++;
4147
4148   create_check_block_twin (insn, false);
4149
4150   TODO_SPEC (insn) &= ~BEGIN_SPEC;
4151 }
4152
4153 static void haifa_init_insn (rtx);
4154
4155 /* Generates recovery code for BE_IN speculative INSN.  */
4156 static void
4157 add_to_speculative_block (rtx insn)
4158 {
4159   ds_t ts;
4160   sd_iterator_def sd_it;
4161   dep_t dep;
4162   rtx twins = NULL;
4163   rtx_vec_t priorities_roots;
4164
4165   ts = TODO_SPEC (insn);
4166   gcc_assert (!(ts & ~BE_IN_SPEC));
4167
4168   if (ts & BE_IN_DATA)
4169     nr_be_in_data++;
4170   if (ts & BE_IN_CONTROL)
4171     nr_be_in_control++;
4172
4173   TODO_SPEC (insn) &= ~BE_IN_SPEC;
4174   gcc_assert (!TODO_SPEC (insn));
4175
4176   DONE_SPEC (insn) |= ts;
4177
4178   /* First we convert all simple checks to branchy.  */
4179   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4180        sd_iterator_cond (&sd_it, &dep);)
4181     {
4182       rtx check = DEP_PRO (dep);
4183
4184       if (IS_SPECULATION_SIMPLE_CHECK_P (check))
4185         {
4186           create_check_block_twin (check, true);
4187
4188           /* Restart search.  */
4189           sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4190         }
4191       else
4192         /* Continue search.  */
4193         sd_iterator_next (&sd_it);
4194     }
4195
4196   priorities_roots = NULL;
4197   clear_priorities (insn, &priorities_roots);
4198
4199   while (1)
4200     {
4201       rtx check, twin;
4202       basic_block rec;
4203
4204       /* Get the first backward dependency of INSN.  */
4205       sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4206       if (!sd_iterator_cond (&sd_it, &dep))
4207         /* INSN has no backward dependencies left.  */
4208         break;
4209
4210       gcc_assert ((DEP_STATUS (dep) & BEGIN_SPEC) == 0
4211                   && (DEP_STATUS (dep) & BE_IN_SPEC) != 0
4212                   && (DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
4213
4214       check = DEP_PRO (dep);
4215
4216       gcc_assert (!IS_SPECULATION_CHECK_P (check) && !ORIG_PAT (check)
4217                   && QUEUE_INDEX (check) == QUEUE_NOWHERE);
4218
4219       rec = BLOCK_FOR_INSN (check);
4220
4221       twin = emit_insn_before (copy_insn (PATTERN (insn)), BB_END (rec));
4222       haifa_init_insn (twin);
4223
4224       sd_copy_back_deps (twin, insn, true);
4225
4226       if (sched_verbose && spec_info->dump)
4227         /* INSN_BB (insn) isn't determined for twin insns yet.
4228            So we can't use current_sched_info->print_insn.  */
4229         fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
4230                  INSN_UID (twin), rec->index);
4231
4232       twins = alloc_INSN_LIST (twin, twins);
4233
4234       /* Add dependences between TWIN and all appropriate
4235          instructions from REC.  */
4236       FOR_EACH_DEP (insn, SD_LIST_SPEC_BACK, sd_it, dep)
4237         {
4238           rtx pro = DEP_PRO (dep);
4239
4240           gcc_assert (DEP_TYPE (dep) == REG_DEP_TRUE);
4241
4242           /* INSN might have dependencies from the instructions from
4243              several recovery blocks.  At this iteration we process those
4244              producers that reside in REC.  */
4245           if (BLOCK_FOR_INSN (pro) == rec)
4246             {
4247               dep_def _new_dep, *new_dep = &_new_dep;
4248
4249               init_dep (new_dep, pro, twin, REG_DEP_TRUE);
4250               sd_add_dep (new_dep, false);
4251             }
4252         }
4253
4254       process_insn_forw_deps_be_in_spec (insn, twin, ts);
4255
4256       /* Remove all dependencies between INSN and insns in REC.  */
4257       for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4258            sd_iterator_cond (&sd_it, &dep);)
4259         {
4260           rtx pro = DEP_PRO (dep);
4261
4262           if (BLOCK_FOR_INSN (pro) == rec)
4263             sd_delete_dep (sd_it);
4264           else
4265             sd_iterator_next (&sd_it);
4266         }
4267     }
4268
4269   /* We couldn't have added the dependencies between INSN and TWINS earlier
4270      because that would make TWINS appear in the INSN_BACK_DEPS (INSN).  */
4271   while (twins)
4272     {
4273       rtx twin;
4274
4275       twin = XEXP (twins, 0);
4276
4277       {
4278         dep_def _new_dep, *new_dep = &_new_dep;
4279
4280         init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
4281         sd_add_dep (new_dep, false);
4282       }
4283
4284       twin = XEXP (twins, 1);
4285       free_INSN_LIST_node (twins);
4286       twins = twin;
4287     }
4288
4289   calc_priorities (priorities_roots);
4290   VEC_free (rtx, heap, priorities_roots);
4291 }
4292
4293 /* Extends and fills with zeros (only the new part) array pointed to by P.  */
4294 void *
4295 xrecalloc (void *p, size_t new_nmemb, size_t old_nmemb, size_t size)
4296 {
4297   gcc_assert (new_nmemb >= old_nmemb);
4298   p = XRESIZEVAR (void, p, new_nmemb * size);
4299   memset (((char *) p) + old_nmemb * size, 0, (new_nmemb - old_nmemb) * size);
4300   return p;
4301 }
4302
4303 /* Helper function.
4304    Find fallthru edge from PRED.  */
4305 edge
4306 find_fallthru_edge_from (basic_block pred)
4307 {
4308   edge e;
4309   basic_block succ;
4310
4311   succ = pred->next_bb;
4312   gcc_assert (succ->prev_bb == pred);
4313
4314   if (EDGE_COUNT (pred->succs) <= EDGE_COUNT (succ->preds))
4315     {
4316       e = find_fallthru_edge (pred->succs);
4317
4318       if (e)
4319         {
4320           gcc_assert (e->dest == succ);
4321           return e;
4322         }
4323     }
4324   else
4325     {
4326       e = find_fallthru_edge (succ->preds);
4327
4328       if (e)
4329         {
4330           gcc_assert (e->src == pred);
4331           return e;
4332         }
4333     }
4334
4335   return NULL;
4336 }
4337
4338 /* Extend per basic block data structures.  */
4339 static void
4340 sched_extend_bb (void)
4341 {
4342   rtx insn;
4343
4344   /* The following is done to keep current_sched_info->next_tail non null.  */
4345   insn = BB_END (EXIT_BLOCK_PTR->prev_bb);
4346   if (NEXT_INSN (insn) == 0
4347       || (!NOTE_P (insn)
4348           && !LABEL_P (insn)
4349           /* Don't emit a NOTE if it would end up before a BARRIER.  */
4350           && !BARRIER_P (NEXT_INSN (insn))))
4351     {
4352       rtx note = emit_note_after (NOTE_INSN_DELETED, insn);
4353       /* Make insn appear outside BB.  */
4354       set_block_for_insn (note, NULL);
4355       BB_END (EXIT_BLOCK_PTR->prev_bb) = insn;
4356     }
4357 }
4358
4359 /* Init per basic block data structures.  */
4360 void
4361 sched_init_bbs (void)
4362 {
4363   sched_extend_bb ();
4364 }
4365
4366 /* Initialize BEFORE_RECOVERY variable.  */
4367 static void
4368 init_before_recovery (basic_block *before_recovery_ptr)
4369 {
4370   basic_block last;
4371   edge e;
4372
4373   last = EXIT_BLOCK_PTR->prev_bb;
4374   e = find_fallthru_edge_from (last);
4375
4376   if (e)
4377     {
4378       /* We create two basic blocks:
4379          1. Single instruction block is inserted right after E->SRC
4380          and has jump to
4381          2. Empty block right before EXIT_BLOCK.
4382          Between these two blocks recovery blocks will be emitted.  */
4383
4384       basic_block single, empty;
4385       rtx x, label;
4386
4387       /* If the fallthrough edge to exit we've found is from the block we've
4388          created before, don't do anything more.  */
4389       if (last == after_recovery)
4390         return;
4391
4392       adding_bb_to_current_region_p = false;
4393
4394       single = sched_create_empty_bb (last);
4395       empty = sched_create_empty_bb (single);
4396
4397       /* Add new blocks to the root loop.  */
4398       if (current_loops != NULL)
4399         {
4400           add_bb_to_loop (single, VEC_index (loop_p, current_loops->larray, 0));
4401           add_bb_to_loop (empty, VEC_index (loop_p, current_loops->larray, 0));
4402         }
4403
4404       single->count = last->count;
4405       empty->count = last->count;
4406       single->frequency = last->frequency;
4407       empty->frequency = last->frequency;
4408       BB_COPY_PARTITION (single, last);
4409       BB_COPY_PARTITION (empty, last);
4410
4411       redirect_edge_succ (e, single);
4412       make_single_succ_edge (single, empty, 0);
4413       make_single_succ_edge (empty, EXIT_BLOCK_PTR,
4414                              EDGE_FALLTHRU | EDGE_CAN_FALLTHRU);
4415
4416       label = block_label (empty);
4417       x = emit_jump_insn_after (gen_jump (label), BB_END (single));
4418       JUMP_LABEL (x) = label;
4419       LABEL_NUSES (label)++;
4420       haifa_init_insn (x);
4421
4422       emit_barrier_after (x);
4423
4424       sched_init_only_bb (empty, NULL);
4425       sched_init_only_bb (single, NULL);
4426       sched_extend_bb ();
4427
4428       adding_bb_to_current_region_p = true;
4429       before_recovery = single;
4430       after_recovery = empty;
4431
4432       if (before_recovery_ptr)
4433         *before_recovery_ptr = before_recovery;
4434
4435       if (sched_verbose >= 2 && spec_info->dump)
4436         fprintf (spec_info->dump,
4437                  ";;\t\tFixed fallthru to EXIT : %d->>%d->%d->>EXIT\n",
4438                  last->index, single->index, empty->index);
4439     }
4440   else
4441     before_recovery = last;
4442 }
4443
4444 /* Returns new recovery block.  */
4445 basic_block
4446 sched_create_recovery_block (basic_block *before_recovery_ptr)
4447 {
4448   rtx label;
4449   rtx barrier;
4450   basic_block rec;
4451
4452   haifa_recovery_bb_recently_added_p = true;
4453   haifa_recovery_bb_ever_added_p = true;
4454
4455   init_before_recovery (before_recovery_ptr);
4456
4457   barrier = get_last_bb_insn (before_recovery);
4458   gcc_assert (BARRIER_P (barrier));
4459
4460   label = emit_label_after (gen_label_rtx (), barrier);
4461
4462   rec = create_basic_block (label, label, before_recovery);
4463
4464   /* A recovery block always ends with an unconditional jump.  */
4465   emit_barrier_after (BB_END (rec));
4466
4467   if (BB_PARTITION (before_recovery) != BB_UNPARTITIONED)
4468     BB_SET_PARTITION (rec, BB_COLD_PARTITION);
4469
4470   if (sched_verbose && spec_info->dump)
4471     fprintf (spec_info->dump, ";;\t\tGenerated recovery block rec%d\n",
4472              rec->index);
4473
4474   return rec;
4475 }
4476
4477 /* Create edges: FIRST_BB -> REC; FIRST_BB -> SECOND_BB; REC -> SECOND_BB
4478    and emit necessary jumps.  */
4479 void
4480 sched_create_recovery_edges (basic_block first_bb, basic_block rec,
4481                              basic_block second_bb)
4482 {
4483   rtx label;
4484   rtx jump;
4485   int edge_flags;
4486
4487   /* This is fixing of incoming edge.  */
4488   /* ??? Which other flags should be specified?  */
4489   if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
4490     /* Partition type is the same, if it is "unpartitioned".  */
4491     edge_flags = EDGE_CROSSING;
4492   else
4493     edge_flags = 0;
4494
4495   make_edge (first_bb, rec, edge_flags);
4496   label = block_label (second_bb);
4497   jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
4498   JUMP_LABEL (jump) = label;
4499   LABEL_NUSES (label)++;
4500
4501   if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
4502     /* Partition type is the same, if it is "unpartitioned".  */
4503     {
4504       /* Rewritten from cfgrtl.c.  */
4505       if (flag_reorder_blocks_and_partition
4506           && targetm.have_named_sections)
4507         {
4508           /* We don't need the same note for the check because
4509              any_condjump_p (check) == true.  */
4510           add_reg_note (jump, REG_CROSSING_JUMP, NULL_RTX);
4511         }
4512       edge_flags = EDGE_CROSSING;
4513     }
4514   else
4515     edge_flags = 0;
4516
4517   make_single_succ_edge (rec, second_bb, edge_flags);
4518   if (dom_info_available_p (CDI_DOMINATORS))
4519     set_immediate_dominator (CDI_DOMINATORS, rec, first_bb);
4520 }
4521
4522 /* This function creates recovery code for INSN.  If MUTATE_P is nonzero,
4523    INSN is a simple check, that should be converted to branchy one.  */
4524 static void
4525 create_check_block_twin (rtx insn, bool mutate_p)
4526 {
4527   basic_block rec;
4528   rtx label, check, twin;
4529   ds_t fs;
4530   sd_iterator_def sd_it;
4531   dep_t dep;
4532   dep_def _new_dep, *new_dep = &_new_dep;
4533   ds_t todo_spec;
4534
4535   gcc_assert (ORIG_PAT (insn) != NULL_RTX);
4536
4537   if (!mutate_p)
4538     todo_spec = TODO_SPEC (insn);
4539   else
4540     {
4541       gcc_assert (IS_SPECULATION_SIMPLE_CHECK_P (insn)
4542                   && (TODO_SPEC (insn) & SPECULATIVE) == 0);
4543
4544       todo_spec = CHECK_SPEC (insn);
4545     }
4546
4547   todo_spec &= SPECULATIVE;
4548
4549   /* Create recovery block.  */
4550   if (mutate_p || targetm.sched.needs_block_p (todo_spec))
4551     {
4552       rec = sched_create_recovery_block (NULL);
4553       label = BB_HEAD (rec);
4554     }
4555   else
4556     {
4557       rec = EXIT_BLOCK_PTR;
4558       label = NULL_RTX;
4559     }
4560
4561   /* Emit CHECK.  */
4562   check = targetm.sched.gen_spec_check (insn, label, todo_spec);
4563
4564   if (rec != EXIT_BLOCK_PTR)
4565     {
4566       /* To have mem_reg alive at the beginning of second_bb,
4567          we emit check BEFORE insn, so insn after splitting
4568          insn will be at the beginning of second_bb, which will
4569          provide us with the correct life information.  */
4570       check = emit_jump_insn_before (check, insn);
4571       JUMP_LABEL (check) = label;
4572       LABEL_NUSES (label)++;
4573     }
4574   else
4575     check = emit_insn_before (check, insn);
4576
4577   /* Extend data structures.  */
4578   haifa_init_insn (check);
4579
4580   /* CHECK is being added to current region.  Extend ready list.  */
4581   gcc_assert (sched_ready_n_insns != -1);
4582   sched_extend_ready_list (sched_ready_n_insns + 1);
4583
4584   if (current_sched_info->add_remove_insn)
4585     current_sched_info->add_remove_insn (insn, 0);
4586
4587   RECOVERY_BLOCK (check) = rec;
4588
4589   if (sched_verbose && spec_info->dump)
4590     fprintf (spec_info->dump, ";;\t\tGenerated check insn : %s\n",
4591              (*current_sched_info->print_insn) (check, 0));
4592
4593   gcc_assert (ORIG_PAT (insn));
4594
4595   /* Initialize TWIN (twin is a duplicate of original instruction
4596      in the recovery block).  */
4597   if (rec != EXIT_BLOCK_PTR)
4598     {
4599       sd_iterator_def sd_it;
4600       dep_t dep;
4601
4602       FOR_EACH_DEP (insn, SD_LIST_RES_BACK, sd_it, dep)
4603         if ((DEP_STATUS (dep) & DEP_OUTPUT) != 0)
4604           {
4605             struct _dep _dep2, *dep2 = &_dep2;
4606
4607             init_dep (dep2, DEP_PRO (dep), check, REG_DEP_TRUE);
4608
4609             sd_add_dep (dep2, true);
4610           }
4611
4612       twin = emit_insn_after (ORIG_PAT (insn), BB_END (rec));
4613       haifa_init_insn (twin);
4614
4615       if (sched_verbose && spec_info->dump)
4616         /* INSN_BB (insn) isn't determined for twin insns yet.
4617            So we can't use current_sched_info->print_insn.  */
4618         fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
4619                  INSN_UID (twin), rec->index);
4620     }
4621   else
4622     {
4623       ORIG_PAT (check) = ORIG_PAT (insn);
4624       HAS_INTERNAL_DEP (check) = 1;
4625       twin = check;
4626       /* ??? We probably should change all OUTPUT dependencies to
4627          (TRUE | OUTPUT).  */
4628     }
4629
4630   /* Copy all resolved back dependencies of INSN to TWIN.  This will
4631      provide correct value for INSN_TICK (TWIN).  */
4632   sd_copy_back_deps (twin, insn, true);
4633
4634   if (rec != EXIT_BLOCK_PTR)
4635     /* In case of branchy check, fix CFG.  */
4636     {
4637       basic_block first_bb, second_bb;
4638       rtx jump;
4639
4640       first_bb = BLOCK_FOR_INSN (check);
4641       second_bb = sched_split_block (first_bb, check);
4642
4643       sched_create_recovery_edges (first_bb, rec, second_bb);
4644
4645       sched_init_only_bb (second_bb, first_bb);
4646       sched_init_only_bb (rec, EXIT_BLOCK_PTR);
4647
4648       jump = BB_END (rec);
4649       haifa_init_insn (jump);
4650     }
4651
4652   /* Move backward dependences from INSN to CHECK and
4653      move forward dependences from INSN to TWIN.  */
4654
4655   /* First, create dependencies between INSN's producers and CHECK & TWIN.  */
4656   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4657     {
4658       rtx pro = DEP_PRO (dep);
4659       ds_t ds;
4660
4661       /* If BEGIN_DATA: [insn ~~TRUE~~> producer]:
4662          check --TRUE--> producer  ??? or ANTI ???
4663          twin  --TRUE--> producer
4664          twin  --ANTI--> check
4665
4666          If BEGIN_CONTROL: [insn ~~ANTI~~> producer]:
4667          check --ANTI--> producer
4668          twin  --ANTI--> producer
4669          twin  --ANTI--> check
4670
4671          If BE_IN_SPEC: [insn ~~TRUE~~> producer]:
4672          check ~~TRUE~~> producer
4673          twin  ~~TRUE~~> producer
4674          twin  --ANTI--> check  */
4675
4676       ds = DEP_STATUS (dep);
4677
4678       if (ds & BEGIN_SPEC)
4679         {
4680           gcc_assert (!mutate_p);
4681           ds &= ~BEGIN_SPEC;
4682         }
4683
4684       init_dep_1 (new_dep, pro, check, DEP_TYPE (dep), ds);
4685       sd_add_dep (new_dep, false);
4686
4687       if (rec != EXIT_BLOCK_PTR)
4688         {
4689           DEP_CON (new_dep) = twin;
4690           sd_add_dep (new_dep, false);
4691         }
4692     }
4693
4694   /* Second, remove backward dependencies of INSN.  */
4695   for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4696        sd_iterator_cond (&sd_it, &dep);)
4697     {
4698       if ((DEP_STATUS (dep) & BEGIN_SPEC)
4699           || mutate_p)
4700         /* We can delete this dep because we overcome it with
4701            BEGIN_SPECULATION.  */
4702         sd_delete_dep (sd_it);
4703       else
4704         sd_iterator_next (&sd_it);
4705     }
4706
4707   /* Future Speculations.  Determine what BE_IN speculations will be like.  */
4708   fs = 0;
4709
4710   /* Fields (DONE_SPEC (x) & BEGIN_SPEC) and CHECK_SPEC (x) are set only
4711      here.  */
4712
4713   gcc_assert (!DONE_SPEC (insn));
4714
4715   if (!mutate_p)
4716     {
4717       ds_t ts = TODO_SPEC (insn);
4718
4719       DONE_SPEC (insn) = ts & BEGIN_SPEC;
4720       CHECK_SPEC (check) = ts & BEGIN_SPEC;
4721
4722       /* Luckiness of future speculations solely depends upon initial
4723          BEGIN speculation.  */
4724       if (ts & BEGIN_DATA)
4725         fs = set_dep_weak (fs, BE_IN_DATA, get_dep_weak (ts, BEGIN_DATA));
4726       if (ts & BEGIN_CONTROL)
4727         fs = set_dep_weak (fs, BE_IN_CONTROL,
4728                            get_dep_weak (ts, BEGIN_CONTROL));
4729     }
4730   else
4731     CHECK_SPEC (check) = CHECK_SPEC (insn);
4732
4733   /* Future speculations: call the helper.  */
4734   process_insn_forw_deps_be_in_spec (insn, twin, fs);
4735
4736   if (rec != EXIT_BLOCK_PTR)
4737     {
4738       /* Which types of dependencies should we use here is,
4739          generally, machine-dependent question...  But, for now,
4740          it is not.  */
4741
4742       if (!mutate_p)
4743         {
4744           init_dep (new_dep, insn, check, REG_DEP_TRUE);
4745           sd_add_dep (new_dep, false);
4746
4747           init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
4748           sd_add_dep (new_dep, false);
4749         }
4750       else
4751         {
4752           if (spec_info->dump)
4753             fprintf (spec_info->dump, ";;\t\tRemoved simple check : %s\n",
4754                      (*current_sched_info->print_insn) (insn, 0));
4755
4756           /* Remove all dependencies of the INSN.  */
4757           {
4758             sd_it = sd_iterator_start (insn, (SD_LIST_FORW
4759                                               | SD_LIST_BACK
4760                                               | SD_LIST_RES_BACK));
4761             while (sd_iterator_cond (&sd_it, &dep))
4762               sd_delete_dep (sd_it);
4763           }
4764
4765           /* If former check (INSN) already was moved to the ready (or queue)
4766              list, add new check (CHECK) there too.  */
4767           if (QUEUE_INDEX (insn) != QUEUE_NOWHERE)
4768             try_ready (check);
4769
4770           /* Remove old check from instruction stream and free its
4771              data.  */
4772           sched_remove_insn (insn);
4773         }
4774
4775       init_dep (new_dep, check, twin, REG_DEP_ANTI);
4776       sd_add_dep (new_dep, false);
4777     }
4778   else
4779     {
4780       init_dep_1 (new_dep, insn, check, REG_DEP_TRUE, DEP_TRUE | DEP_OUTPUT);
4781       sd_add_dep (new_dep, false);
4782     }
4783
4784   if (!mutate_p)
4785     /* Fix priorities.  If MUTATE_P is nonzero, this is not necessary,
4786        because it'll be done later in add_to_speculative_block.  */
4787     {
4788       rtx_vec_t priorities_roots = NULL;
4789
4790       clear_priorities (twin, &priorities_roots);
4791       calc_priorities (priorities_roots);
4792       VEC_free (rtx, heap, priorities_roots);
4793     }
4794 }
4795
4796 /* Removes dependency between instructions in the recovery block REC
4797    and usual region instructions.  It keeps inner dependences so it
4798    won't be necessary to recompute them.  */
4799 static void
4800 fix_recovery_deps (basic_block rec)
4801 {
4802   rtx note, insn, jump, ready_list = 0;
4803   bitmap_head in_ready;
4804   rtx link;
4805
4806   bitmap_initialize (&in_ready, 0);
4807
4808   /* NOTE - a basic block note.  */
4809   note = NEXT_INSN (BB_HEAD (rec));
4810   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
4811   insn = BB_END (rec);
4812   gcc_assert (JUMP_P (insn));
4813   insn = PREV_INSN (insn);
4814
4815   do
4816     {
4817       sd_iterator_def sd_it;
4818       dep_t dep;
4819
4820       for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4821            sd_iterator_cond (&sd_it, &dep);)
4822         {
4823           rtx consumer = DEP_CON (dep);
4824
4825           if (BLOCK_FOR_INSN (consumer) != rec)
4826             {
4827               sd_delete_dep (sd_it);
4828
4829               if (bitmap_set_bit (&in_ready, INSN_LUID (consumer)))
4830                 ready_list = alloc_INSN_LIST (consumer, ready_list);
4831             }
4832           else
4833             {
4834               gcc_assert ((DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
4835
4836               sd_iterator_next (&sd_it);
4837             }
4838         }
4839
4840       insn = PREV_INSN (insn);
4841     }
4842   while (insn != note);
4843
4844   bitmap_clear (&in_ready);
4845
4846   /* Try to add instructions to the ready or queue list.  */
4847   for (link = ready_list; link; link = XEXP (link, 1))
4848     try_ready (XEXP (link, 0));
4849   free_INSN_LIST_list (&ready_list);
4850
4851   /* Fixing jump's dependences.  */
4852   insn = BB_HEAD (rec);
4853   jump = BB_END (rec);
4854
4855   gcc_assert (LABEL_P (insn));
4856   insn = NEXT_INSN (insn);
4857
4858   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (insn));
4859   add_jump_dependencies (insn, jump);
4860 }
4861
4862 /* Change pattern of INSN to NEW_PAT.  */
4863 void
4864 sched_change_pattern (rtx insn, rtx new_pat)
4865 {
4866   int t;
4867
4868   t = validate_change (insn, &PATTERN (insn), new_pat, 0);
4869   gcc_assert (t);
4870   dfa_clear_single_insn_cache (insn);
4871 }
4872
4873 /* Change pattern of INSN to NEW_PAT.  Invalidate cached haifa
4874    instruction data.  */
4875 static void
4876 haifa_change_pattern (rtx insn, rtx new_pat)
4877 {
4878   sched_change_pattern (insn, new_pat);
4879
4880   /* Invalidate INSN_COST, so it'll be recalculated.  */
4881   INSN_COST (insn) = -1;
4882   /* Invalidate INSN_TICK, so it'll be recalculated.  */
4883   INSN_TICK (insn) = INVALID_TICK;
4884 }
4885
4886 /* -1 - can't speculate,
4887    0 - for speculation with REQUEST mode it is OK to use
4888    current instruction pattern,
4889    1 - need to change pattern for *NEW_PAT to be speculative.  */
4890 int
4891 sched_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
4892 {
4893   gcc_assert (current_sched_info->flags & DO_SPECULATION
4894               && (request & SPECULATIVE)
4895               && sched_insn_is_legitimate_for_speculation_p (insn, request));
4896
4897   if ((request & spec_info->mask) != request)
4898     return -1;
4899
4900   if (request & BE_IN_SPEC
4901       && !(request & BEGIN_SPEC))
4902     return 0;
4903
4904   return targetm.sched.speculate_insn (insn, request, new_pat);
4905 }
4906
4907 static int
4908 haifa_speculate_insn (rtx insn, ds_t request, rtx *new_pat)
4909 {
4910   gcc_assert (sched_deps_info->generate_spec_deps
4911               && !IS_SPECULATION_CHECK_P (insn));
4912
4913   if (HAS_INTERNAL_DEP (insn)
4914       || SCHED_GROUP_P (insn))
4915     return -1;
4916
4917   return sched_speculate_insn (insn, request, new_pat);
4918 }
4919
4920 /* Print some information about block BB, which starts with HEAD and
4921    ends with TAIL, before scheduling it.
4922    I is zero, if scheduler is about to start with the fresh ebb.  */
4923 static void
4924 dump_new_block_header (int i, basic_block bb, rtx head, rtx tail)
4925 {
4926   if (!i)
4927     fprintf (sched_dump,
4928              ";;   ======================================================\n");
4929   else
4930     fprintf (sched_dump,
4931              ";;   =====================ADVANCING TO=====================\n");
4932   fprintf (sched_dump,
4933            ";;   -- basic block %d from %d to %d -- %s reload\n",
4934            bb->index, INSN_UID (head), INSN_UID (tail),
4935            (reload_completed ? "after" : "before"));
4936   fprintf (sched_dump,
4937            ";;   ======================================================\n");
4938   fprintf (sched_dump, "\n");
4939 }
4940
4941 /* Unlink basic block notes and labels and saves them, so they
4942    can be easily restored.  We unlink basic block notes in EBB to
4943    provide back-compatibility with the previous code, as target backends
4944    assume, that there'll be only instructions between
4945    current_sched_info->{head and tail}.  We restore these notes as soon
4946    as we can.
4947    FIRST (LAST) is the first (last) basic block in the ebb.
4948    NB: In usual case (FIRST == LAST) nothing is really done.  */
4949 void
4950 unlink_bb_notes (basic_block first, basic_block last)
4951 {
4952   /* We DON'T unlink basic block notes of the first block in the ebb.  */
4953   if (first == last)
4954     return;
4955
4956   bb_header = XNEWVEC (rtx, last_basic_block);
4957
4958   /* Make a sentinel.  */
4959   if (last->next_bb != EXIT_BLOCK_PTR)
4960     bb_header[last->next_bb->index] = 0;
4961
4962   first = first->next_bb;
4963   do
4964     {
4965       rtx prev, label, note, next;
4966
4967       label = BB_HEAD (last);
4968       if (LABEL_P (label))
4969         note = NEXT_INSN (label);
4970       else
4971         note = label;
4972       gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
4973
4974       prev = PREV_INSN (label);
4975       next = NEXT_INSN (note);
4976       gcc_assert (prev && next);
4977
4978       NEXT_INSN (prev) = next;
4979       PREV_INSN (next) = prev;
4980
4981       bb_header[last->index] = label;
4982
4983       if (last == first)
4984         break;
4985
4986       last = last->prev_bb;
4987     }
4988   while (1);
4989 }
4990
4991 /* Restore basic block notes.
4992    FIRST is the first basic block in the ebb.  */
4993 static void
4994 restore_bb_notes (basic_block first)
4995 {
4996   if (!bb_header)
4997     return;
4998
4999   /* We DON'T unlink basic block notes of the first block in the ebb.  */
5000   first = first->next_bb;
5001   /* Remember: FIRST is actually a second basic block in the ebb.  */
5002
5003   while (first != EXIT_BLOCK_PTR
5004          && bb_header[first->index])
5005     {
5006       rtx prev, label, note, next;
5007
5008       label = bb_header[first->index];
5009       prev = PREV_INSN (label);
5010       next = NEXT_INSN (prev);
5011
5012       if (LABEL_P (label))
5013         note = NEXT_INSN (label);
5014       else
5015         note = label;
5016       gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5017
5018       bb_header[first->index] = 0;
5019
5020       NEXT_INSN (prev) = label;
5021       NEXT_INSN (note) = next;
5022       PREV_INSN (next) = note;
5023
5024       first = first->next_bb;
5025     }
5026
5027   free (bb_header);
5028   bb_header = 0;
5029 }
5030
5031 /* Helper function.
5032    Fix CFG after both in- and inter-block movement of
5033    control_flow_insn_p JUMP.  */
5034 static void
5035 fix_jump_move (rtx jump)
5036 {
5037   basic_block bb, jump_bb, jump_bb_next;
5038
5039   bb = BLOCK_FOR_INSN (PREV_INSN (jump));
5040   jump_bb = BLOCK_FOR_INSN (jump);
5041   jump_bb_next = jump_bb->next_bb;
5042
5043   gcc_assert (common_sched_info->sched_pass_id == SCHED_EBB_PASS
5044               || IS_SPECULATION_BRANCHY_CHECK_P (jump));
5045
5046   if (!NOTE_INSN_BASIC_BLOCK_P (BB_END (jump_bb_next)))
5047     /* if jump_bb_next is not empty.  */
5048     BB_END (jump_bb) = BB_END (jump_bb_next);
5049
5050   if (BB_END (bb) != PREV_INSN (jump))
5051     /* Then there are instruction after jump that should be placed
5052        to jump_bb_next.  */
5053     BB_END (jump_bb_next) = BB_END (bb);
5054   else
5055     /* Otherwise jump_bb_next is empty.  */
5056     BB_END (jump_bb_next) = NEXT_INSN (BB_HEAD (jump_bb_next));
5057
5058   /* To make assertion in move_insn happy.  */
5059   BB_END (bb) = PREV_INSN (jump);
5060
5061   update_bb_for_insn (jump_bb_next);
5062 }
5063
5064 /* Fix CFG after interblock movement of control_flow_insn_p JUMP.  */
5065 static void
5066 move_block_after_check (rtx jump)
5067 {
5068   basic_block bb, jump_bb, jump_bb_next;
5069   VEC(edge,gc) *t;
5070
5071   bb = BLOCK_FOR_INSN (PREV_INSN (jump));
5072   jump_bb = BLOCK_FOR_INSN (jump);
5073   jump_bb_next = jump_bb->next_bb;
5074
5075   update_bb_for_insn (jump_bb);
5076
5077   gcc_assert (IS_SPECULATION_CHECK_P (jump)
5078               || IS_SPECULATION_CHECK_P (BB_END (jump_bb_next)));
5079
5080   unlink_block (jump_bb_next);
5081   link_block (jump_bb_next, bb);
5082
5083   t = bb->succs;
5084   bb->succs = 0;
5085   move_succs (&(jump_bb->succs), bb);
5086   move_succs (&(jump_bb_next->succs), jump_bb);
5087   move_succs (&t, jump_bb_next);
5088
5089   df_mark_solutions_dirty ();
5090
5091   common_sched_info->fix_recovery_cfg
5092     (bb->index, jump_bb->index, jump_bb_next->index);
5093 }
5094
5095 /* Helper function for move_block_after_check.
5096    This functions attaches edge vector pointed to by SUCCSP to
5097    block TO.  */
5098 static void
5099 move_succs (VEC(edge,gc) **succsp, basic_block to)
5100 {
5101   edge e;
5102   edge_iterator ei;
5103
5104   gcc_assert (to->succs == 0);
5105
5106   to->succs = *succsp;
5107
5108   FOR_EACH_EDGE (e, ei, to->succs)
5109     e->src = to;
5110
5111   *succsp = 0;
5112 }
5113
5114 /* Remove INSN from the instruction stream.
5115    INSN should have any dependencies.  */
5116 static void
5117 sched_remove_insn (rtx insn)
5118 {
5119   sd_finish_insn (insn);
5120
5121   change_queue_index (insn, QUEUE_NOWHERE);
5122   current_sched_info->add_remove_insn (insn, 1);
5123   remove_insn (insn);
5124 }
5125
5126 /* Clear priorities of all instructions, that are forward dependent on INSN.
5127    Store in vector pointed to by ROOTS_PTR insns on which priority () should
5128    be invoked to initialize all cleared priorities.  */
5129 static void
5130 clear_priorities (rtx insn, rtx_vec_t *roots_ptr)
5131 {
5132   sd_iterator_def sd_it;
5133   dep_t dep;
5134   bool insn_is_root_p = true;
5135
5136   gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
5137
5138   FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
5139     {
5140       rtx pro = DEP_PRO (dep);
5141
5142       if (INSN_PRIORITY_STATUS (pro) >= 0
5143           && QUEUE_INDEX (insn) != QUEUE_SCHEDULED)
5144         {
5145           /* If DEP doesn't contribute to priority then INSN itself should
5146              be added to priority roots.  */
5147           if (contributes_to_priority_p (dep))
5148             insn_is_root_p = false;
5149
5150           INSN_PRIORITY_STATUS (pro) = -1;
5151           clear_priorities (pro, roots_ptr);
5152         }
5153     }
5154
5155   if (insn_is_root_p)
5156     VEC_safe_push (rtx, heap, *roots_ptr, insn);
5157 }
5158
5159 /* Recompute priorities of instructions, whose priorities might have been
5160    changed.  ROOTS is a vector of instructions whose priority computation will
5161    trigger initialization of all cleared priorities.  */
5162 static void
5163 calc_priorities (rtx_vec_t roots)
5164 {
5165   int i;
5166   rtx insn;
5167
5168   FOR_EACH_VEC_ELT (rtx, roots, i, insn)
5169     priority (insn);
5170 }
5171
5172
5173 /* Add dependences between JUMP and other instructions in the recovery
5174    block.  INSN is the first insn the recovery block.  */
5175 static void
5176 add_jump_dependencies (rtx insn, rtx jump)
5177 {
5178   do
5179     {
5180       insn = NEXT_INSN (insn);
5181       if (insn == jump)
5182         break;
5183
5184       if (dep_list_size (insn) == 0)
5185         {
5186           dep_def _new_dep, *new_dep = &_new_dep;
5187
5188           init_dep (new_dep, insn, jump, REG_DEP_ANTI);
5189           sd_add_dep (new_dep, false);
5190         }
5191     }
5192   while (1);
5193
5194   gcc_assert (!sd_lists_empty_p (jump, SD_LIST_BACK));
5195 }
5196
5197 /* Return the NOTE_INSN_BASIC_BLOCK of BB.  */
5198 rtx
5199 bb_note (basic_block bb)
5200 {
5201   rtx note;
5202
5203   note = BB_HEAD (bb);
5204   if (LABEL_P (note))
5205     note = NEXT_INSN (note);
5206
5207   gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5208   return note;
5209 }
5210
5211 #ifdef ENABLE_CHECKING
5212 /* Helper function for check_cfg.
5213    Return nonzero, if edge vector pointed to by EL has edge with TYPE in
5214    its flags.  */
5215 static int
5216 has_edge_p (VEC(edge,gc) *el, int type)
5217 {
5218   edge e;
5219   edge_iterator ei;
5220
5221   FOR_EACH_EDGE (e, ei, el)
5222     if (e->flags & type)
5223       return 1;
5224   return 0;
5225 }
5226
5227 /* Search back, starting at INSN, for an insn that is not a
5228    NOTE_INSN_VAR_LOCATION.  Don't search beyond HEAD, and return it if
5229    no such insn can be found.  */
5230 static inline rtx
5231 prev_non_location_insn (rtx insn, rtx head)
5232 {
5233   while (insn != head && NOTE_P (insn)
5234          && NOTE_KIND (insn) == NOTE_INSN_VAR_LOCATION)
5235     insn = PREV_INSN (insn);
5236
5237   return insn;
5238 }
5239
5240 /* Check few properties of CFG between HEAD and TAIL.
5241    If HEAD (TAIL) is NULL check from the beginning (till the end) of the
5242    instruction stream.  */
5243 static void
5244 check_cfg (rtx head, rtx tail)
5245 {
5246   rtx next_tail;
5247   basic_block bb = 0;
5248   int not_first = 0, not_last;
5249
5250   if (head == NULL)
5251     head = get_insns ();
5252   if (tail == NULL)
5253     tail = get_last_insn ();
5254   next_tail = NEXT_INSN (tail);
5255
5256   do
5257     {
5258       not_last = head != tail;
5259
5260       if (not_first)
5261         gcc_assert (NEXT_INSN (PREV_INSN (head)) == head);
5262       if (not_last)
5263         gcc_assert (PREV_INSN (NEXT_INSN (head)) == head);
5264
5265       if (LABEL_P (head)
5266           || (NOTE_INSN_BASIC_BLOCK_P (head)
5267               && (!not_first
5268                   || (not_first && !LABEL_P (PREV_INSN (head))))))
5269         {
5270           gcc_assert (bb == 0);
5271           bb = BLOCK_FOR_INSN (head);
5272           if (bb != 0)
5273             gcc_assert (BB_HEAD (bb) == head);
5274           else
5275             /* This is the case of jump table.  See inside_basic_block_p ().  */
5276             gcc_assert (LABEL_P (head) && !inside_basic_block_p (head));
5277         }
5278
5279       if (bb == 0)
5280         {
5281           gcc_assert (!inside_basic_block_p (head));
5282           head = NEXT_INSN (head);
5283         }
5284       else
5285         {
5286           gcc_assert (inside_basic_block_p (head)
5287                       || NOTE_P (head));
5288           gcc_assert (BLOCK_FOR_INSN (head) == bb);
5289
5290           if (LABEL_P (head))
5291             {
5292               head = NEXT_INSN (head);
5293               gcc_assert (NOTE_INSN_BASIC_BLOCK_P (head));
5294             }
5295           else
5296             {
5297               if (control_flow_insn_p (head))
5298                 {
5299                   gcc_assert (prev_non_location_insn (BB_END (bb), head)
5300                               == head);
5301
5302                   if (any_uncondjump_p (head))
5303                     gcc_assert (EDGE_COUNT (bb->succs) == 1
5304                                 && BARRIER_P (NEXT_INSN (head)));
5305                   else if (any_condjump_p (head))
5306                     gcc_assert (/* Usual case.  */
5307                                 (EDGE_COUNT (bb->succs) > 1
5308                                  && !BARRIER_P (NEXT_INSN (head)))
5309                                 /* Or jump to the next instruction.  */
5310                                 || (EDGE_COUNT (bb->succs) == 1
5311                                     && (BB_HEAD (EDGE_I (bb->succs, 0)->dest)
5312                                         == JUMP_LABEL (head))));
5313                 }
5314               if (BB_END (bb) == head)
5315                 {
5316                   if (EDGE_COUNT (bb->succs) > 1)
5317                     gcc_assert (control_flow_insn_p (prev_non_location_insn
5318                                                      (head, BB_HEAD (bb)))
5319                                 || has_edge_p (bb->succs, EDGE_COMPLEX));
5320                   bb = 0;
5321                 }
5322
5323               head = NEXT_INSN (head);
5324             }
5325         }
5326
5327       not_first = 1;
5328     }
5329   while (head != next_tail);
5330
5331   gcc_assert (bb == 0);
5332 }
5333
5334 #endif /* ENABLE_CHECKING */
5335
5336 /* Extend data structures for logical insn UID.  */
5337 void
5338 sched_extend_luids (void)
5339 {
5340   int new_luids_max_uid = get_max_uid () + 1;
5341
5342   VEC_safe_grow_cleared (int, heap, sched_luids, new_luids_max_uid);
5343 }
5344
5345 /* Initialize LUID for INSN.  */
5346 void
5347 sched_init_insn_luid (rtx insn)
5348 {
5349   int i = INSN_P (insn) ? 1 : common_sched_info->luid_for_non_insn (insn);
5350   int luid;
5351
5352   if (i >= 0)
5353     {
5354       luid = sched_max_luid;
5355       sched_max_luid += i;
5356     }
5357   else
5358     luid = -1;
5359
5360   SET_INSN_LUID (insn, luid);
5361 }
5362
5363 /* Initialize luids for BBS.
5364    The hook common_sched_info->luid_for_non_insn () is used to determine
5365    if notes, labels, etc. need luids.  */
5366 void
5367 sched_init_luids (bb_vec_t bbs)
5368 {
5369   int i;
5370   basic_block bb;
5371
5372   sched_extend_luids ();
5373   FOR_EACH_VEC_ELT (basic_block, bbs, i, bb)
5374     {
5375       rtx insn;
5376
5377       FOR_BB_INSNS (bb, insn)
5378         sched_init_insn_luid (insn);
5379     }
5380 }
5381
5382 /* Free LUIDs.  */
5383 void
5384 sched_finish_luids (void)
5385 {
5386   VEC_free (int, heap, sched_luids);
5387   sched_max_luid = 1;
5388 }
5389
5390 /* Return logical uid of INSN.  Helpful while debugging.  */
5391 int
5392 insn_luid (rtx insn)
5393 {
5394   return INSN_LUID (insn);
5395 }
5396
5397 /* Extend per insn data in the target.  */
5398 void
5399 sched_extend_target (void)
5400 {
5401   if (targetm.sched.h_i_d_extended)
5402     targetm.sched.h_i_d_extended ();
5403 }
5404
5405 /* Extend global scheduler structures (those, that live across calls to
5406    schedule_block) to include information about just emitted INSN.  */
5407 static void
5408 extend_h_i_d (void)
5409 {
5410   int reserve = (get_max_uid () + 1
5411                  - VEC_length (haifa_insn_data_def, h_i_d));
5412   if (reserve > 0
5413       && ! VEC_space (haifa_insn_data_def, h_i_d, reserve))
5414     {
5415       VEC_safe_grow_cleared (haifa_insn_data_def, heap, h_i_d,
5416                              3 * get_max_uid () / 2);
5417       sched_extend_target ();
5418     }
5419 }
5420
5421 /* Initialize h_i_d entry of the INSN with default values.
5422    Values, that are not explicitly initialized here, hold zero.  */
5423 static void
5424 init_h_i_d (rtx insn)
5425 {
5426   if (INSN_LUID (insn) > 0)
5427     {
5428       INSN_COST (insn) = -1;
5429       QUEUE_INDEX (insn) = QUEUE_NOWHERE;
5430       INSN_TICK (insn) = INVALID_TICK;
5431       INTER_TICK (insn) = INVALID_TICK;
5432       TODO_SPEC (insn) = HARD_DEP;
5433     }
5434 }
5435
5436 /* Initialize haifa_insn_data for BBS.  */
5437 void
5438 haifa_init_h_i_d (bb_vec_t bbs)
5439 {
5440   int i;
5441   basic_block bb;
5442
5443   extend_h_i_d ();
5444   FOR_EACH_VEC_ELT (basic_block, bbs, i, bb)
5445     {
5446       rtx insn;
5447
5448       FOR_BB_INSNS (bb, insn)
5449         init_h_i_d (insn);
5450     }
5451 }
5452
5453 /* Finalize haifa_insn_data.  */
5454 void
5455 haifa_finish_h_i_d (void)
5456 {
5457   int i;
5458   haifa_insn_data_t data;
5459   struct reg_use_data *use, *next;
5460
5461   FOR_EACH_VEC_ELT (haifa_insn_data_def, h_i_d, i, data)
5462     {
5463       free (data->reg_pressure);
5464       for (use = data->reg_use_list; use != NULL; use = next)
5465         {
5466           next = use->next_insn_use;
5467           free (use);
5468         }
5469     }
5470   VEC_free (haifa_insn_data_def, heap, h_i_d);
5471 }
5472
5473 /* Init data for the new insn INSN.  */
5474 static void
5475 haifa_init_insn (rtx insn)
5476 {
5477   gcc_assert (insn != NULL);
5478
5479   sched_extend_luids ();
5480   sched_init_insn_luid (insn);
5481   sched_extend_target ();
5482   sched_deps_init (false);
5483   extend_h_i_d ();
5484   init_h_i_d (insn);
5485
5486   if (adding_bb_to_current_region_p)
5487     {
5488       sd_init_insn (insn);
5489
5490       /* Extend dependency caches by one element.  */
5491       extend_dependency_caches (1, false);
5492     }
5493   if (sched_pressure_p)
5494     init_insn_reg_pressure_info (insn);
5495 }
5496
5497 /* Init data for the new basic block BB which comes after AFTER.  */
5498 static void
5499 haifa_init_only_bb (basic_block bb, basic_block after)
5500 {
5501   gcc_assert (bb != NULL);
5502
5503   sched_init_bbs ();
5504
5505   if (common_sched_info->add_block)
5506     /* This changes only data structures of the front-end.  */
5507     common_sched_info->add_block (bb, after);
5508 }
5509
5510 /* A generic version of sched_split_block ().  */
5511 basic_block
5512 sched_split_block_1 (basic_block first_bb, rtx after)
5513 {
5514   edge e;
5515
5516   e = split_block (first_bb, after);
5517   gcc_assert (e->src == first_bb);
5518
5519   /* sched_split_block emits note if *check == BB_END.  Probably it
5520      is better to rip that note off.  */
5521
5522   return e->dest;
5523 }
5524
5525 /* A generic version of sched_create_empty_bb ().  */
5526 basic_block
5527 sched_create_empty_bb_1 (basic_block after)
5528 {
5529   return create_empty_bb (after);
5530 }
5531
5532 /* Insert PAT as an INSN into the schedule and update the necessary data
5533    structures to account for it. */
5534 rtx
5535 sched_emit_insn (rtx pat)
5536 {
5537   rtx insn = emit_insn_before (pat, nonscheduled_insns_begin);
5538   haifa_init_insn (insn);
5539
5540   if (current_sched_info->add_remove_insn)
5541     current_sched_info->add_remove_insn (insn, 0);
5542
5543   (*current_sched_info->begin_schedule_ready) (insn);
5544   VEC_safe_push (rtx, heap, scheduled_insns, insn);
5545
5546   last_scheduled_insn = insn;
5547   return insn;
5548 }
5549
5550 /* This function returns a candidate satisfying dispatch constraints from
5551    the ready list.  */
5552
5553 static rtx
5554 ready_remove_first_dispatch (struct ready_list *ready)
5555 {
5556   int i;
5557   rtx insn = ready_element (ready, 0);
5558
5559   if (ready->n_ready == 1
5560       || INSN_CODE (insn) < 0
5561       || !INSN_P (insn)
5562       || !active_insn_p (insn)
5563       || targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
5564     return ready_remove_first (ready);
5565
5566   for (i = 1; i < ready->n_ready; i++)
5567     {
5568       insn = ready_element (ready, i);
5569
5570       if (INSN_CODE (insn) < 0
5571           || !INSN_P (insn)
5572           || !active_insn_p (insn))
5573         continue;
5574
5575       if (targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
5576         {
5577           /* Return ith element of ready.  */
5578           insn = ready_remove (ready, i);
5579           return insn;
5580         }
5581     }
5582
5583   if (targetm.sched.dispatch (NULL_RTX, DISPATCH_VIOLATION))
5584     return ready_remove_first (ready);
5585
5586   for (i = 1; i < ready->n_ready; i++)
5587     {
5588       insn = ready_element (ready, i);
5589
5590       if (INSN_CODE (insn) < 0
5591           || !INSN_P (insn)
5592           || !active_insn_p (insn))
5593         continue;
5594
5595       /* Return i-th element of ready.  */
5596       if (targetm.sched.dispatch (insn, IS_CMP))
5597         return ready_remove (ready, i);
5598     }
5599
5600   return ready_remove_first (ready);
5601 }
5602
5603 /* Get number of ready insn in the ready list.  */
5604
5605 int
5606 number_in_ready (void)
5607 {
5608   return ready.n_ready;
5609 }
5610
5611 /* Get number of ready's in the ready list.  */
5612
5613 rtx
5614 get_ready_element (int i)
5615 {
5616   return ready_element (&ready, i);
5617 }
5618
5619 #endif /* INSN_SCHEDULING */