[AArch64] PR target/65491: Classify V1TF vectors as AAPCS64 short vectors rather...
[official-gcc.git] / gcc / haifa-sched.c
blobbf8ce0bb7c42823086dfc52f3259be04bb93dbac
1 /* Instruction scheduling pass.
2 Copyright (C) 1992-2015 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com) Enhanced by,
4 and currently maintained by, Jim Wilson (wilson@cygnus.com)
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* Instruction scheduling pass. This file, along with sched-deps.c,
23 contains the generic parts. The actual entry point for
24 the normal instruction scheduling pass is found in sched-rgn.c.
26 We compute insn priorities based on data dependencies. Flow
27 analysis only creates a fraction of the data-dependencies we must
28 observe: namely, only those dependencies which the combiner can be
29 expected to use. For this pass, we must therefore create the
30 remaining dependencies we need to observe: register dependencies,
31 memory dependencies, dependencies to keep function calls in order,
32 and the dependence between a conditional branch and the setting of
33 condition codes are all dealt with here.
35 The scheduler first traverses the data flow graph, starting with
36 the last instruction, and proceeding to the first, assigning values
37 to insn_priority as it goes. This sorts the instructions
38 topologically by data dependence.
40 Once priorities have been established, we order the insns using
41 list scheduling. This works as follows: starting with a list of
42 all the ready insns, and sorted according to priority number, we
43 schedule the insn from the end of the list by placing its
44 predecessors in the list according to their priority order. We
45 consider this insn scheduled by setting the pointer to the "end" of
46 the list to point to the previous insn. When an insn has no
47 predecessors, we either queue it until sufficient time has elapsed
48 or add it to the ready list. As the instructions are scheduled or
49 when stalls are introduced, the queue advances and dumps insns into
50 the ready list. When all insns down to the lowest priority have
51 been scheduled, the critical path of the basic block has been made
52 as short as possible. The remaining insns are then scheduled in
53 remaining slots.
55 The following list shows the order in which we want to break ties
56 among insns in the ready list:
58 1. choose insn with the longest path to end of bb, ties
59 broken by
60 2. choose insn with least contribution to register pressure,
61 ties broken by
62 3. prefer in-block upon interblock motion, ties broken by
63 4. prefer useful upon speculative motion, ties broken by
64 5. choose insn with largest control flow probability, ties
65 broken by
66 6. choose insn with the least dependences upon the previously
67 scheduled insn, or finally
68 7 choose the insn which has the most insns dependent on it.
69 8. choose insn with lowest UID.
71 Memory references complicate matters. Only if we can be certain
72 that memory references are not part of the data dependency graph
73 (via true, anti, or output dependence), can we move operations past
74 memory references. To first approximation, reads can be done
75 independently, while writes introduce dependencies. Better
76 approximations will yield fewer dependencies.
78 Before reload, an extended analysis of interblock data dependences
79 is required for interblock scheduling. This is performed in
80 compute_block_dependences ().
82 Dependencies set up by memory references are treated in exactly the
83 same way as other dependencies, by using insn backward dependences
84 INSN_BACK_DEPS. INSN_BACK_DEPS are translated into forward dependences
85 INSN_FORW_DEPS for the purpose of forward list scheduling.
87 Having optimized the critical path, we may have also unduly
88 extended the lifetimes of some registers. If an operation requires
89 that constants be loaded into registers, it is certainly desirable
90 to load those constants as early as necessary, but no earlier.
91 I.e., it will not do to load up a bunch of registers at the
92 beginning of a basic block only to use them at the end, if they
93 could be loaded later, since this may result in excessive register
94 utilization.
96 Note that since branches are never in basic blocks, but only end
97 basic blocks, this pass will not move branches. But that is ok,
98 since we can use GNU's delayed branch scheduling pass to take care
99 of this case.
101 Also note that no further optimizations based on algebraic
102 identities are performed, so this pass would be a good one to
103 perform instruction splitting, such as breaking up a multiply
104 instruction into shifts and adds where that is profitable.
106 Given the memory aliasing analysis that this pass should perform,
107 it should be possible to remove redundant stores to memory, and to
108 load values from registers instead of hitting memory.
110 Before reload, speculative insns are moved only if a 'proof' exists
111 that no exception will be caused by this, and if no live registers
112 exist that inhibit the motion (live registers constraints are not
113 represented by data dependence edges).
115 This pass must update information that subsequent passes expect to
116 be correct. Namely: reg_n_refs, reg_n_sets, reg_n_deaths,
117 reg_n_calls_crossed, and reg_live_length. Also, BB_HEAD, BB_END.
119 The information in the line number notes is carefully retained by
120 this pass. Notes that refer to the starting and ending of
121 exception regions are also carefully retained by this pass. All
122 other NOTE insns are grouped in their same relative order at the
123 beginning of basic blocks and regions that have been scheduled. */
125 #include "config.h"
126 #include "system.h"
127 #include "coretypes.h"
128 #include "tm.h"
129 #include "diagnostic-core.h"
130 #include "hard-reg-set.h"
131 #include "rtl.h"
132 #include "tm_p.h"
133 #include "regs.h"
134 #include "hashtab.h"
135 #include "hash-set.h"
136 #include "vec.h"
137 #include "machmode.h"
138 #include "input.h"
139 #include "function.h"
140 #include "flags.h"
141 #include "insn-config.h"
142 #include "insn-attr.h"
143 #include "except.h"
144 #include "recog.h"
145 #include "dominance.h"
146 #include "cfg.h"
147 #include "cfgrtl.h"
148 #include "cfgbuild.h"
149 #include "predict.h"
150 #include "basic-block.h"
151 #include "sched-int.h"
152 #include "target.h"
153 #include "common/common-target.h"
154 #include "params.h"
155 #include "dbgcnt.h"
156 #include "cfgloop.h"
157 #include "ira.h"
158 #include "emit-rtl.h" /* FIXME: Can go away once crtl is moved to rtl.h. */
159 #include "hash-table.h"
160 #include "dumpfile.h"
162 #ifdef INSN_SCHEDULING
164 /* True if we do register pressure relief through live-range
165 shrinkage. */
166 static bool live_range_shrinkage_p;
168 /* Switch on live range shrinkage. */
169 void
170 initialize_live_range_shrinkage (void)
172 live_range_shrinkage_p = true;
175 /* Switch off live range shrinkage. */
176 void
177 finish_live_range_shrinkage (void)
179 live_range_shrinkage_p = false;
182 /* issue_rate is the number of insns that can be scheduled in the same
183 machine cycle. It can be defined in the config/mach/mach.h file,
184 otherwise we set it to 1. */
186 int issue_rate;
188 /* This can be set to true by a backend if the scheduler should not
189 enable a DCE pass. */
190 bool sched_no_dce;
192 /* The current initiation interval used when modulo scheduling. */
193 static int modulo_ii;
195 /* The maximum number of stages we are prepared to handle. */
196 static int modulo_max_stages;
198 /* The number of insns that exist in each iteration of the loop. We use this
199 to detect when we've scheduled all insns from the first iteration. */
200 static int modulo_n_insns;
202 /* The current count of insns in the first iteration of the loop that have
203 already been scheduled. */
204 static int modulo_insns_scheduled;
206 /* The maximum uid of insns from the first iteration of the loop. */
207 static int modulo_iter0_max_uid;
209 /* The number of times we should attempt to backtrack when modulo scheduling.
210 Decreased each time we have to backtrack. */
211 static int modulo_backtracks_left;
213 /* The stage in which the last insn from the original loop was
214 scheduled. */
215 static int modulo_last_stage;
217 /* sched-verbose controls the amount of debugging output the
218 scheduler prints. It is controlled by -fsched-verbose=N:
219 N>0 and no -DSR : the output is directed to stderr.
220 N>=10 will direct the printouts to stderr (regardless of -dSR).
221 N=1: same as -dSR.
222 N=2: bb's probabilities, detailed ready list info, unit/insn info.
223 N=3: rtl at abort point, control-flow, regions info.
224 N=5: dependences info. */
226 int sched_verbose = 0;
228 /* Debugging file. All printouts are sent to dump, which is always set,
229 either to stderr, or to the dump listing file (-dRS). */
230 FILE *sched_dump = 0;
232 /* This is a placeholder for the scheduler parameters common
233 to all schedulers. */
234 struct common_sched_info_def *common_sched_info;
236 #define INSN_TICK(INSN) (HID (INSN)->tick)
237 #define INSN_EXACT_TICK(INSN) (HID (INSN)->exact_tick)
238 #define INSN_TICK_ESTIMATE(INSN) (HID (INSN)->tick_estimate)
239 #define INTER_TICK(INSN) (HID (INSN)->inter_tick)
240 #define FEEDS_BACKTRACK_INSN(INSN) (HID (INSN)->feeds_backtrack_insn)
241 #define SHADOW_P(INSN) (HID (INSN)->shadow_p)
242 #define MUST_RECOMPUTE_SPEC_P(INSN) (HID (INSN)->must_recompute_spec)
243 /* Cached cost of the instruction. Use insn_cost to get cost of the
244 insn. -1 here means that the field is not initialized. */
245 #define INSN_COST(INSN) (HID (INSN)->cost)
247 /* If INSN_TICK of an instruction is equal to INVALID_TICK,
248 then it should be recalculated from scratch. */
249 #define INVALID_TICK (-(max_insn_queue_index + 1))
250 /* The minimal value of the INSN_TICK of an instruction. */
251 #define MIN_TICK (-max_insn_queue_index)
253 /* Original order of insns in the ready list.
254 Used to keep order of normal insns while separating DEBUG_INSNs. */
255 #define INSN_RFS_DEBUG_ORIG_ORDER(INSN) (HID (INSN)->rfs_debug_orig_order)
257 /* The deciding reason for INSN's place in the ready list. */
258 #define INSN_LAST_RFS_WIN(INSN) (HID (INSN)->last_rfs_win)
260 /* List of important notes we must keep around. This is a pointer to the
261 last element in the list. */
262 rtx_insn *note_list;
264 static struct spec_info_def spec_info_var;
265 /* Description of the speculative part of the scheduling.
266 If NULL - no speculation. */
267 spec_info_t spec_info = NULL;
269 /* True, if recovery block was added during scheduling of current block.
270 Used to determine, if we need to fix INSN_TICKs. */
271 static bool haifa_recovery_bb_recently_added_p;
273 /* True, if recovery block was added during this scheduling pass.
274 Used to determine if we should have empty memory pools of dependencies
275 after finishing current region. */
276 bool haifa_recovery_bb_ever_added_p;
278 /* Counters of different types of speculative instructions. */
279 static int nr_begin_data, nr_be_in_data, nr_begin_control, nr_be_in_control;
281 /* Array used in {unlink, restore}_bb_notes. */
282 static rtx_insn **bb_header = 0;
284 /* Basic block after which recovery blocks will be created. */
285 static basic_block before_recovery;
287 /* Basic block just before the EXIT_BLOCK and after recovery, if we have
288 created it. */
289 basic_block after_recovery;
291 /* FALSE if we add bb to another region, so we don't need to initialize it. */
292 bool adding_bb_to_current_region_p = true;
294 /* Queues, etc. */
296 /* An instruction is ready to be scheduled when all insns preceding it
297 have already been scheduled. It is important to ensure that all
298 insns which use its result will not be executed until its result
299 has been computed. An insn is maintained in one of four structures:
301 (P) the "Pending" set of insns which cannot be scheduled until
302 their dependencies have been satisfied.
303 (Q) the "Queued" set of insns that can be scheduled when sufficient
304 time has passed.
305 (R) the "Ready" list of unscheduled, uncommitted insns.
306 (S) the "Scheduled" list of insns.
308 Initially, all insns are either "Pending" or "Ready" depending on
309 whether their dependencies are satisfied.
311 Insns move from the "Ready" list to the "Scheduled" list as they
312 are committed to the schedule. As this occurs, the insns in the
313 "Pending" list have their dependencies satisfied and move to either
314 the "Ready" list or the "Queued" set depending on whether
315 sufficient time has passed to make them ready. As time passes,
316 insns move from the "Queued" set to the "Ready" list.
318 The "Pending" list (P) are the insns in the INSN_FORW_DEPS of the
319 unscheduled insns, i.e., those that are ready, queued, and pending.
320 The "Queued" set (Q) is implemented by the variable `insn_queue'.
321 The "Ready" list (R) is implemented by the variables `ready' and
322 `n_ready'.
323 The "Scheduled" list (S) is the new insn chain built by this pass.
325 The transition (R->S) is implemented in the scheduling loop in
326 `schedule_block' when the best insn to schedule is chosen.
327 The transitions (P->R and P->Q) are implemented in `schedule_insn' as
328 insns move from the ready list to the scheduled list.
329 The transition (Q->R) is implemented in 'queue_to_insn' as time
330 passes or stalls are introduced. */
332 /* Implement a circular buffer to delay instructions until sufficient
333 time has passed. For the new pipeline description interface,
334 MAX_INSN_QUEUE_INDEX is a power of two minus one which is not less
335 than maximal time of instruction execution computed by genattr.c on
336 the base maximal time of functional unit reservations and getting a
337 result. This is the longest time an insn may be queued. */
339 static rtx_insn_list **insn_queue;
340 static int q_ptr = 0;
341 static int q_size = 0;
342 #define NEXT_Q(X) (((X)+1) & max_insn_queue_index)
343 #define NEXT_Q_AFTER(X, C) (((X)+C) & max_insn_queue_index)
345 #define QUEUE_SCHEDULED (-3)
346 #define QUEUE_NOWHERE (-2)
347 #define QUEUE_READY (-1)
348 /* QUEUE_SCHEDULED - INSN is scheduled.
349 QUEUE_NOWHERE - INSN isn't scheduled yet and is neither in
350 queue or ready list.
351 QUEUE_READY - INSN is in ready list.
352 N >= 0 - INSN queued for X [where NEXT_Q_AFTER (q_ptr, X) == N] cycles. */
354 #define QUEUE_INDEX(INSN) (HID (INSN)->queue_index)
356 /* The following variable value refers for all current and future
357 reservations of the processor units. */
358 state_t curr_state;
360 /* The following variable value is size of memory representing all
361 current and future reservations of the processor units. */
362 size_t dfa_state_size;
364 /* The following array is used to find the best insn from ready when
365 the automaton pipeline interface is used. */
366 signed char *ready_try = NULL;
368 /* The ready list. */
369 struct ready_list ready = {NULL, 0, 0, 0, 0};
371 /* The pointer to the ready list (to be removed). */
372 static struct ready_list *readyp = &ready;
374 /* Scheduling clock. */
375 static int clock_var;
377 /* Clock at which the previous instruction was issued. */
378 static int last_clock_var;
380 /* Set to true if, when queuing a shadow insn, we discover that it would be
381 scheduled too late. */
382 static bool must_backtrack;
384 /* The following variable value is number of essential insns issued on
385 the current cycle. An insn is essential one if it changes the
386 processors state. */
387 int cycle_issued_insns;
389 /* This records the actual schedule. It is built up during the main phase
390 of schedule_block, and afterwards used to reorder the insns in the RTL. */
391 static vec<rtx_insn *> scheduled_insns;
393 static int may_trap_exp (const_rtx, int);
395 /* Nonzero iff the address is comprised from at most 1 register. */
396 #define CONST_BASED_ADDRESS_P(x) \
397 (REG_P (x) \
398 || ((GET_CODE (x) == PLUS || GET_CODE (x) == MINUS \
399 || (GET_CODE (x) == LO_SUM)) \
400 && (CONSTANT_P (XEXP (x, 0)) \
401 || CONSTANT_P (XEXP (x, 1)))))
403 /* Returns a class that insn with GET_DEST(insn)=x may belong to,
404 as found by analyzing insn's expression. */
407 static int haifa_luid_for_non_insn (rtx x);
409 /* Haifa version of sched_info hooks common to all headers. */
410 const struct common_sched_info_def haifa_common_sched_info =
412 NULL, /* fix_recovery_cfg */
413 NULL, /* add_block */
414 NULL, /* estimate_number_of_insns */
415 haifa_luid_for_non_insn, /* luid_for_non_insn */
416 SCHED_PASS_UNKNOWN /* sched_pass_id */
419 /* Mapping from instruction UID to its Logical UID. */
420 vec<int> sched_luids = vNULL;
422 /* Next LUID to assign to an instruction. */
423 int sched_max_luid = 1;
425 /* Haifa Instruction Data. */
426 vec<haifa_insn_data_def> h_i_d = vNULL;
428 void (* sched_init_only_bb) (basic_block, basic_block);
430 /* Split block function. Different schedulers might use different functions
431 to handle their internal data consistent. */
432 basic_block (* sched_split_block) (basic_block, rtx);
434 /* Create empty basic block after the specified block. */
435 basic_block (* sched_create_empty_bb) (basic_block);
437 /* Return the number of cycles until INSN is expected to be ready.
438 Return zero if it already is. */
439 static int
440 insn_delay (rtx_insn *insn)
442 return MAX (INSN_TICK (insn) - clock_var, 0);
445 static int
446 may_trap_exp (const_rtx x, int is_store)
448 enum rtx_code code;
450 if (x == 0)
451 return TRAP_FREE;
452 code = GET_CODE (x);
453 if (is_store)
455 if (code == MEM && may_trap_p (x))
456 return TRAP_RISKY;
457 else
458 return TRAP_FREE;
460 if (code == MEM)
462 /* The insn uses memory: a volatile load. */
463 if (MEM_VOLATILE_P (x))
464 return IRISKY;
465 /* An exception-free load. */
466 if (!may_trap_p (x))
467 return IFREE;
468 /* A load with 1 base register, to be further checked. */
469 if (CONST_BASED_ADDRESS_P (XEXP (x, 0)))
470 return PFREE_CANDIDATE;
471 /* No info on the load, to be further checked. */
472 return PRISKY_CANDIDATE;
474 else
476 const char *fmt;
477 int i, insn_class = TRAP_FREE;
479 /* Neither store nor load, check if it may cause a trap. */
480 if (may_trap_p (x))
481 return TRAP_RISKY;
482 /* Recursive step: walk the insn... */
483 fmt = GET_RTX_FORMAT (code);
484 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
486 if (fmt[i] == 'e')
488 int tmp_class = may_trap_exp (XEXP (x, i), is_store);
489 insn_class = WORST_CLASS (insn_class, tmp_class);
491 else if (fmt[i] == 'E')
493 int j;
494 for (j = 0; j < XVECLEN (x, i); j++)
496 int tmp_class = may_trap_exp (XVECEXP (x, i, j), is_store);
497 insn_class = WORST_CLASS (insn_class, tmp_class);
498 if (insn_class == TRAP_RISKY || insn_class == IRISKY)
499 break;
502 if (insn_class == TRAP_RISKY || insn_class == IRISKY)
503 break;
505 return insn_class;
509 /* Classifies rtx X of an insn for the purpose of verifying that X can be
510 executed speculatively (and consequently the insn can be moved
511 speculatively), by examining X, returning:
512 TRAP_RISKY: store, or risky non-load insn (e.g. division by variable).
513 TRAP_FREE: non-load insn.
514 IFREE: load from a globally safe location.
515 IRISKY: volatile load.
516 PFREE_CANDIDATE, PRISKY_CANDIDATE: load that need to be checked for
517 being either PFREE or PRISKY. */
519 static int
520 haifa_classify_rtx (const_rtx x)
522 int tmp_class = TRAP_FREE;
523 int insn_class = TRAP_FREE;
524 enum rtx_code code;
526 if (GET_CODE (x) == PARALLEL)
528 int i, len = XVECLEN (x, 0);
530 for (i = len - 1; i >= 0; i--)
532 tmp_class = haifa_classify_rtx (XVECEXP (x, 0, i));
533 insn_class = WORST_CLASS (insn_class, tmp_class);
534 if (insn_class == TRAP_RISKY || insn_class == IRISKY)
535 break;
538 else
540 code = GET_CODE (x);
541 switch (code)
543 case CLOBBER:
544 /* Test if it is a 'store'. */
545 tmp_class = may_trap_exp (XEXP (x, 0), 1);
546 break;
547 case SET:
548 /* Test if it is a store. */
549 tmp_class = may_trap_exp (SET_DEST (x), 1);
550 if (tmp_class == TRAP_RISKY)
551 break;
552 /* Test if it is a load. */
553 tmp_class =
554 WORST_CLASS (tmp_class,
555 may_trap_exp (SET_SRC (x), 0));
556 break;
557 case COND_EXEC:
558 tmp_class = haifa_classify_rtx (COND_EXEC_CODE (x));
559 if (tmp_class == TRAP_RISKY)
560 break;
561 tmp_class = WORST_CLASS (tmp_class,
562 may_trap_exp (COND_EXEC_TEST (x), 0));
563 break;
564 case TRAP_IF:
565 tmp_class = TRAP_RISKY;
566 break;
567 default:;
569 insn_class = tmp_class;
572 return insn_class;
576 haifa_classify_insn (const_rtx insn)
578 return haifa_classify_rtx (PATTERN (insn));
581 /* After the scheduler initialization function has been called, this function
582 can be called to enable modulo scheduling. II is the initiation interval
583 we should use, it affects the delays for delay_pairs that were recorded as
584 separated by a given number of stages.
586 MAX_STAGES provides us with a limit
587 after which we give up scheduling; the caller must have unrolled at least
588 as many copies of the loop body and recorded delay_pairs for them.
590 INSNS is the number of real (non-debug) insns in one iteration of
591 the loop. MAX_UID can be used to test whether an insn belongs to
592 the first iteration of the loop; all of them have a uid lower than
593 MAX_UID. */
594 void
595 set_modulo_params (int ii, int max_stages, int insns, int max_uid)
597 modulo_ii = ii;
598 modulo_max_stages = max_stages;
599 modulo_n_insns = insns;
600 modulo_iter0_max_uid = max_uid;
601 modulo_backtracks_left = PARAM_VALUE (PARAM_MAX_MODULO_BACKTRACK_ATTEMPTS);
604 /* A structure to record a pair of insns where the first one is a real
605 insn that has delay slots, and the second is its delayed shadow.
606 I1 is scheduled normally and will emit an assembly instruction,
607 while I2 describes the side effect that takes place at the
608 transition between cycles CYCLES and (CYCLES + 1) after I1. */
609 struct delay_pair
611 struct delay_pair *next_same_i1;
612 rtx_insn *i1, *i2;
613 int cycles;
614 /* When doing modulo scheduling, we a delay_pair can also be used to
615 show that I1 and I2 are the same insn in a different stage. If that
616 is the case, STAGES will be nonzero. */
617 int stages;
620 /* Helpers for delay hashing. */
622 struct delay_i1_hasher : typed_noop_remove <delay_pair>
624 typedef delay_pair *value_type;
625 typedef void *compare_type;
626 static inline hashval_t hash (const delay_pair *);
627 static inline bool equal (const delay_pair *, const void *);
630 /* Returns a hash value for X, based on hashing just I1. */
632 inline hashval_t
633 delay_i1_hasher::hash (const delay_pair *x)
635 return htab_hash_pointer (x->i1);
638 /* Return true if I1 of pair X is the same as that of pair Y. */
640 inline bool
641 delay_i1_hasher::equal (const delay_pair *x, const void *y)
643 return x->i1 == y;
646 struct delay_i2_hasher : typed_free_remove <delay_pair>
648 typedef delay_pair *value_type;
649 typedef void *compare_type;
650 static inline hashval_t hash (const delay_pair *);
651 static inline bool equal (const delay_pair *, const void *);
654 /* Returns a hash value for X, based on hashing just I2. */
656 inline hashval_t
657 delay_i2_hasher::hash (const delay_pair *x)
659 return htab_hash_pointer (x->i2);
662 /* Return true if I2 of pair X is the same as that of pair Y. */
664 inline bool
665 delay_i2_hasher::equal (const delay_pair *x, const void *y)
667 return x->i2 == y;
670 /* Two hash tables to record delay_pairs, one indexed by I1 and the other
671 indexed by I2. */
672 static hash_table<delay_i1_hasher> *delay_htab;
673 static hash_table<delay_i2_hasher> *delay_htab_i2;
675 /* Called through htab_traverse. Walk the hashtable using I2 as
676 index, and delete all elements involving an UID higher than
677 that pointed to by *DATA. */
679 haifa_htab_i2_traverse (delay_pair **slot, int *data)
681 int maxuid = *data;
682 struct delay_pair *p = *slot;
683 if (INSN_UID (p->i2) >= maxuid || INSN_UID (p->i1) >= maxuid)
685 delay_htab_i2->clear_slot (slot);
687 return 1;
690 /* Called through htab_traverse. Walk the hashtable using I2 as
691 index, and delete all elements involving an UID higher than
692 that pointed to by *DATA. */
694 haifa_htab_i1_traverse (delay_pair **pslot, int *data)
696 int maxuid = *data;
697 struct delay_pair *p, *first, **pprev;
699 if (INSN_UID ((*pslot)->i1) >= maxuid)
701 delay_htab->clear_slot (pslot);
702 return 1;
704 pprev = &first;
705 for (p = *pslot; p; p = p->next_same_i1)
707 if (INSN_UID (p->i2) < maxuid)
709 *pprev = p;
710 pprev = &p->next_same_i1;
713 *pprev = NULL;
714 if (first == NULL)
715 delay_htab->clear_slot (pslot);
716 else
717 *pslot = first;
718 return 1;
721 /* Discard all delay pairs which involve an insn with an UID higher
722 than MAX_UID. */
723 void
724 discard_delay_pairs_above (int max_uid)
726 delay_htab->traverse <int *, haifa_htab_i1_traverse> (&max_uid);
727 delay_htab_i2->traverse <int *, haifa_htab_i2_traverse> (&max_uid);
730 /* This function can be called by a port just before it starts the final
731 scheduling pass. It records the fact that an instruction with delay
732 slots has been split into two insns, I1 and I2. The first one will be
733 scheduled normally and initiates the operation. The second one is a
734 shadow which must follow a specific number of cycles after I1; its only
735 purpose is to show the side effect that occurs at that cycle in the RTL.
736 If a JUMP_INSN or a CALL_INSN has been split, I1 should be a normal INSN,
737 while I2 retains the original insn type.
739 There are two ways in which the number of cycles can be specified,
740 involving the CYCLES and STAGES arguments to this function. If STAGES
741 is zero, we just use the value of CYCLES. Otherwise, STAGES is a factor
742 which is multiplied by MODULO_II to give the number of cycles. This is
743 only useful if the caller also calls set_modulo_params to enable modulo
744 scheduling. */
746 void
747 record_delay_slot_pair (rtx_insn *i1, rtx_insn *i2, int cycles, int stages)
749 struct delay_pair *p = XNEW (struct delay_pair);
750 struct delay_pair **slot;
752 p->i1 = i1;
753 p->i2 = i2;
754 p->cycles = cycles;
755 p->stages = stages;
757 if (!delay_htab)
759 delay_htab = new hash_table<delay_i1_hasher> (10);
760 delay_htab_i2 = new hash_table<delay_i2_hasher> (10);
762 slot = delay_htab->find_slot_with_hash (i1, htab_hash_pointer (i1), INSERT);
763 p->next_same_i1 = *slot;
764 *slot = p;
765 slot = delay_htab_i2->find_slot (p, INSERT);
766 *slot = p;
769 /* Examine the delay pair hashtable to see if INSN is a shadow for another,
770 and return the other insn if so. Return NULL otherwise. */
771 rtx_insn *
772 real_insn_for_shadow (rtx_insn *insn)
774 struct delay_pair *pair;
776 if (!delay_htab)
777 return NULL;
779 pair = delay_htab_i2->find_with_hash (insn, htab_hash_pointer (insn));
780 if (!pair || pair->stages > 0)
781 return NULL;
782 return pair->i1;
785 /* For a pair P of insns, return the fixed distance in cycles from the first
786 insn after which the second must be scheduled. */
787 static int
788 pair_delay (struct delay_pair *p)
790 if (p->stages == 0)
791 return p->cycles;
792 else
793 return p->stages * modulo_ii;
796 /* Given an insn INSN, add a dependence on its delayed shadow if it
797 has one. Also try to find situations where shadows depend on each other
798 and add dependencies to the real insns to limit the amount of backtracking
799 needed. */
800 void
801 add_delay_dependencies (rtx_insn *insn)
803 struct delay_pair *pair;
804 sd_iterator_def sd_it;
805 dep_t dep;
807 if (!delay_htab)
808 return;
810 pair = delay_htab_i2->find_with_hash (insn, htab_hash_pointer (insn));
811 if (!pair)
812 return;
813 add_dependence (insn, pair->i1, REG_DEP_ANTI);
814 if (pair->stages)
815 return;
817 FOR_EACH_DEP (pair->i2, SD_LIST_BACK, sd_it, dep)
819 rtx_insn *pro = DEP_PRO (dep);
820 struct delay_pair *other_pair
821 = delay_htab_i2->find_with_hash (pro, htab_hash_pointer (pro));
822 if (!other_pair || other_pair->stages)
823 continue;
824 if (pair_delay (other_pair) >= pair_delay (pair))
826 if (sched_verbose >= 4)
828 fprintf (sched_dump, ";;\tadding dependence %d <- %d\n",
829 INSN_UID (other_pair->i1),
830 INSN_UID (pair->i1));
831 fprintf (sched_dump, ";;\tpair1 %d <- %d, cost %d\n",
832 INSN_UID (pair->i1),
833 INSN_UID (pair->i2),
834 pair_delay (pair));
835 fprintf (sched_dump, ";;\tpair2 %d <- %d, cost %d\n",
836 INSN_UID (other_pair->i1),
837 INSN_UID (other_pair->i2),
838 pair_delay (other_pair));
840 add_dependence (pair->i1, other_pair->i1, REG_DEP_ANTI);
845 /* Forward declarations. */
847 static int priority (rtx_insn *);
848 static int autopref_rank_for_schedule (const rtx_insn *, const rtx_insn *);
849 static int rank_for_schedule (const void *, const void *);
850 static void swap_sort (rtx_insn **, int);
851 static void queue_insn (rtx_insn *, int, const char *);
852 static int schedule_insn (rtx_insn *);
853 static void adjust_priority (rtx_insn *);
854 static void advance_one_cycle (void);
855 static void extend_h_i_d (void);
858 /* Notes handling mechanism:
859 =========================
860 Generally, NOTES are saved before scheduling and restored after scheduling.
861 The scheduler distinguishes between two types of notes:
863 (1) LOOP_BEGIN, LOOP_END, SETJMP, EHREGION_BEG, EHREGION_END notes:
864 Before scheduling a region, a pointer to the note is added to the insn
865 that follows or precedes it. (This happens as part of the data dependence
866 computation). After scheduling an insn, the pointer contained in it is
867 used for regenerating the corresponding note (in reemit_notes).
869 (2) All other notes (e.g. INSN_DELETED): Before scheduling a block,
870 these notes are put in a list (in rm_other_notes() and
871 unlink_other_notes ()). After scheduling the block, these notes are
872 inserted at the beginning of the block (in schedule_block()). */
874 static void ready_add (struct ready_list *, rtx_insn *, bool);
875 static rtx_insn *ready_remove_first (struct ready_list *);
876 static rtx_insn *ready_remove_first_dispatch (struct ready_list *ready);
878 static void queue_to_ready (struct ready_list *);
879 static int early_queue_to_ready (state_t, struct ready_list *);
881 /* The following functions are used to implement multi-pass scheduling
882 on the first cycle. */
883 static rtx_insn *ready_remove (struct ready_list *, int);
884 static void ready_remove_insn (rtx_insn *);
886 static void fix_inter_tick (rtx_insn *, rtx_insn *);
887 static int fix_tick_ready (rtx_insn *);
888 static void change_queue_index (rtx_insn *, int);
890 /* The following functions are used to implement scheduling of data/control
891 speculative instructions. */
893 static void extend_h_i_d (void);
894 static void init_h_i_d (rtx_insn *);
895 static int haifa_speculate_insn (rtx_insn *, ds_t, rtx *);
896 static void generate_recovery_code (rtx_insn *);
897 static void process_insn_forw_deps_be_in_spec (rtx_insn *, rtx_insn *, ds_t);
898 static void begin_speculative_block (rtx_insn *);
899 static void add_to_speculative_block (rtx_insn *);
900 static void init_before_recovery (basic_block *);
901 static void create_check_block_twin (rtx_insn *, bool);
902 static void fix_recovery_deps (basic_block);
903 static bool haifa_change_pattern (rtx_insn *, rtx);
904 static void dump_new_block_header (int, basic_block, rtx_insn *, rtx_insn *);
905 static void restore_bb_notes (basic_block);
906 static void fix_jump_move (rtx_insn *);
907 static void move_block_after_check (rtx_insn *);
908 static void move_succs (vec<edge, va_gc> **, basic_block);
909 static void sched_remove_insn (rtx_insn *);
910 static void clear_priorities (rtx_insn *, rtx_vec_t *);
911 static void calc_priorities (rtx_vec_t);
912 static void add_jump_dependencies (rtx_insn *, rtx_insn *);
914 #endif /* INSN_SCHEDULING */
916 /* Point to state used for the current scheduling pass. */
917 struct haifa_sched_info *current_sched_info;
919 #ifndef INSN_SCHEDULING
920 void
921 schedule_insns (void)
924 #else
926 /* Do register pressure sensitive insn scheduling if the flag is set
927 up. */
928 enum sched_pressure_algorithm sched_pressure;
930 /* Map regno -> its pressure class. The map defined only when
931 SCHED_PRESSURE != SCHED_PRESSURE_NONE. */
932 enum reg_class *sched_regno_pressure_class;
934 /* The current register pressure. Only elements corresponding pressure
935 classes are defined. */
936 static int curr_reg_pressure[N_REG_CLASSES];
938 /* Saved value of the previous array. */
939 static int saved_reg_pressure[N_REG_CLASSES];
941 /* Register living at given scheduling point. */
942 static bitmap curr_reg_live;
944 /* Saved value of the previous array. */
945 static bitmap saved_reg_live;
947 /* Registers mentioned in the current region. */
948 static bitmap region_ref_regs;
950 /* Effective number of available registers of a given class (see comment
951 in sched_pressure_start_bb). */
952 static int sched_class_regs_num[N_REG_CLASSES];
953 /* Number of call_used_regs. This is a helper for calculating of
954 sched_class_regs_num. */
955 static int call_used_regs_num[N_REG_CLASSES];
957 /* Initiate register pressure relative info for scheduling the current
958 region. Currently it is only clearing register mentioned in the
959 current region. */
960 void
961 sched_init_region_reg_pressure_info (void)
963 bitmap_clear (region_ref_regs);
966 /* PRESSURE[CL] describes the pressure on register class CL. Update it
967 for the birth (if BIRTH_P) or death (if !BIRTH_P) of register REGNO.
968 LIVE tracks the set of live registers; if it is null, assume that
969 every birth or death is genuine. */
970 static inline void
971 mark_regno_birth_or_death (bitmap live, int *pressure, int regno, bool birth_p)
973 enum reg_class pressure_class;
975 pressure_class = sched_regno_pressure_class[regno];
976 if (regno >= FIRST_PSEUDO_REGISTER)
978 if (pressure_class != NO_REGS)
980 if (birth_p)
982 if (!live || bitmap_set_bit (live, regno))
983 pressure[pressure_class]
984 += (ira_reg_class_max_nregs
985 [pressure_class][PSEUDO_REGNO_MODE (regno)]);
987 else
989 if (!live || bitmap_clear_bit (live, regno))
990 pressure[pressure_class]
991 -= (ira_reg_class_max_nregs
992 [pressure_class][PSEUDO_REGNO_MODE (regno)]);
996 else if (pressure_class != NO_REGS
997 && ! TEST_HARD_REG_BIT (ira_no_alloc_regs, regno))
999 if (birth_p)
1001 if (!live || bitmap_set_bit (live, regno))
1002 pressure[pressure_class]++;
1004 else
1006 if (!live || bitmap_clear_bit (live, regno))
1007 pressure[pressure_class]--;
1012 /* Initiate current register pressure related info from living
1013 registers given by LIVE. */
1014 static void
1015 initiate_reg_pressure_info (bitmap live)
1017 int i;
1018 unsigned int j;
1019 bitmap_iterator bi;
1021 for (i = 0; i < ira_pressure_classes_num; i++)
1022 curr_reg_pressure[ira_pressure_classes[i]] = 0;
1023 bitmap_clear (curr_reg_live);
1024 EXECUTE_IF_SET_IN_BITMAP (live, 0, j, bi)
1025 if (sched_pressure == SCHED_PRESSURE_MODEL
1026 || current_nr_blocks == 1
1027 || bitmap_bit_p (region_ref_regs, j))
1028 mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure, j, true);
1031 /* Mark registers in X as mentioned in the current region. */
1032 static void
1033 setup_ref_regs (rtx x)
1035 int i, j;
1036 const RTX_CODE code = GET_CODE (x);
1037 const char *fmt;
1039 if (REG_P (x))
1041 bitmap_set_range (region_ref_regs, REGNO (x), REG_NREGS (x));
1042 return;
1044 fmt = GET_RTX_FORMAT (code);
1045 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1046 if (fmt[i] == 'e')
1047 setup_ref_regs (XEXP (x, i));
1048 else if (fmt[i] == 'E')
1050 for (j = 0; j < XVECLEN (x, i); j++)
1051 setup_ref_regs (XVECEXP (x, i, j));
1055 /* Initiate current register pressure related info at the start of
1056 basic block BB. */
1057 static void
1058 initiate_bb_reg_pressure_info (basic_block bb)
1060 unsigned int i ATTRIBUTE_UNUSED;
1061 rtx_insn *insn;
1063 if (current_nr_blocks > 1)
1064 FOR_BB_INSNS (bb, insn)
1065 if (NONDEBUG_INSN_P (insn))
1066 setup_ref_regs (PATTERN (insn));
1067 initiate_reg_pressure_info (df_get_live_in (bb));
1068 if (bb_has_eh_pred (bb))
1069 for (i = 0; ; ++i)
1071 unsigned int regno = EH_RETURN_DATA_REGNO (i);
1073 if (regno == INVALID_REGNUM)
1074 break;
1075 if (! bitmap_bit_p (df_get_live_in (bb), regno))
1076 mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure,
1077 regno, true);
1081 /* Save current register pressure related info. */
1082 static void
1083 save_reg_pressure (void)
1085 int i;
1087 for (i = 0; i < ira_pressure_classes_num; i++)
1088 saved_reg_pressure[ira_pressure_classes[i]]
1089 = curr_reg_pressure[ira_pressure_classes[i]];
1090 bitmap_copy (saved_reg_live, curr_reg_live);
1093 /* Restore saved register pressure related info. */
1094 static void
1095 restore_reg_pressure (void)
1097 int i;
1099 for (i = 0; i < ira_pressure_classes_num; i++)
1100 curr_reg_pressure[ira_pressure_classes[i]]
1101 = saved_reg_pressure[ira_pressure_classes[i]];
1102 bitmap_copy (curr_reg_live, saved_reg_live);
1105 /* Return TRUE if the register is dying after its USE. */
1106 static bool
1107 dying_use_p (struct reg_use_data *use)
1109 struct reg_use_data *next;
1111 for (next = use->next_regno_use; next != use; next = next->next_regno_use)
1112 if (NONDEBUG_INSN_P (next->insn)
1113 && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
1114 return false;
1115 return true;
1118 /* Print info about the current register pressure and its excess for
1119 each pressure class. */
1120 static void
1121 print_curr_reg_pressure (void)
1123 int i;
1124 enum reg_class cl;
1126 fprintf (sched_dump, ";;\t");
1127 for (i = 0; i < ira_pressure_classes_num; i++)
1129 cl = ira_pressure_classes[i];
1130 gcc_assert (curr_reg_pressure[cl] >= 0);
1131 fprintf (sched_dump, " %s:%d(%d)", reg_class_names[cl],
1132 curr_reg_pressure[cl],
1133 curr_reg_pressure[cl] - sched_class_regs_num[cl]);
1135 fprintf (sched_dump, "\n");
1138 /* Determine if INSN has a condition that is clobbered if a register
1139 in SET_REGS is modified. */
1140 static bool
1141 cond_clobbered_p (rtx_insn *insn, HARD_REG_SET set_regs)
1143 rtx pat = PATTERN (insn);
1144 gcc_assert (GET_CODE (pat) == COND_EXEC);
1145 if (TEST_HARD_REG_BIT (set_regs, REGNO (XEXP (COND_EXEC_TEST (pat), 0))))
1147 sd_iterator_def sd_it;
1148 dep_t dep;
1149 haifa_change_pattern (insn, ORIG_PAT (insn));
1150 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
1151 DEP_STATUS (dep) &= ~DEP_CANCELLED;
1152 TODO_SPEC (insn) = HARD_DEP;
1153 if (sched_verbose >= 2)
1154 fprintf (sched_dump,
1155 ";;\t\tdequeue insn %s because of clobbered condition\n",
1156 (*current_sched_info->print_insn) (insn, 0));
1157 return true;
1160 return false;
1163 /* This function should be called after modifying the pattern of INSN,
1164 to update scheduler data structures as needed. */
1165 static void
1166 update_insn_after_change (rtx_insn *insn)
1168 sd_iterator_def sd_it;
1169 dep_t dep;
1171 dfa_clear_single_insn_cache (insn);
1173 sd_it = sd_iterator_start (insn,
1174 SD_LIST_FORW | SD_LIST_BACK | SD_LIST_RES_BACK);
1175 while (sd_iterator_cond (&sd_it, &dep))
1177 DEP_COST (dep) = UNKNOWN_DEP_COST;
1178 sd_iterator_next (&sd_it);
1181 /* Invalidate INSN_COST, so it'll be recalculated. */
1182 INSN_COST (insn) = -1;
1183 /* Invalidate INSN_TICK, so it'll be recalculated. */
1184 INSN_TICK (insn) = INVALID_TICK;
1186 /* Invalidate autoprefetch data entry. */
1187 INSN_AUTOPREF_MULTIPASS_DATA (insn)[0].status
1188 = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
1189 INSN_AUTOPREF_MULTIPASS_DATA (insn)[1].status
1190 = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
1194 /* Two VECs, one to hold dependencies for which pattern replacements
1195 need to be applied or restored at the start of the next cycle, and
1196 another to hold an integer that is either one, to apply the
1197 corresponding replacement, or zero to restore it. */
1198 static vec<dep_t> next_cycle_replace_deps;
1199 static vec<int> next_cycle_apply;
1201 static void apply_replacement (dep_t, bool);
1202 static void restore_pattern (dep_t, bool);
1204 /* Look at the remaining dependencies for insn NEXT, and compute and return
1205 the TODO_SPEC value we should use for it. This is called after one of
1206 NEXT's dependencies has been resolved.
1207 We also perform pattern replacements for predication, and for broken
1208 replacement dependencies. The latter is only done if FOR_BACKTRACK is
1209 false. */
1211 static ds_t
1212 recompute_todo_spec (rtx_insn *next, bool for_backtrack)
1214 ds_t new_ds;
1215 sd_iterator_def sd_it;
1216 dep_t dep, modify_dep = NULL;
1217 int n_spec = 0;
1218 int n_control = 0;
1219 int n_replace = 0;
1220 bool first_p = true;
1222 if (sd_lists_empty_p (next, SD_LIST_BACK))
1223 /* NEXT has all its dependencies resolved. */
1224 return 0;
1226 if (!sd_lists_empty_p (next, SD_LIST_HARD_BACK))
1227 return HARD_DEP;
1229 /* If NEXT is intended to sit adjacent to this instruction, we don't
1230 want to try to break any dependencies. Treat it as a HARD_DEP. */
1231 if (SCHED_GROUP_P (next))
1232 return HARD_DEP;
1234 /* Now we've got NEXT with speculative deps only.
1235 1. Look at the deps to see what we have to do.
1236 2. Check if we can do 'todo'. */
1237 new_ds = 0;
1239 FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
1241 rtx_insn *pro = DEP_PRO (dep);
1242 ds_t ds = DEP_STATUS (dep) & SPECULATIVE;
1244 if (DEBUG_INSN_P (pro) && !DEBUG_INSN_P (next))
1245 continue;
1247 if (ds)
1249 n_spec++;
1250 if (first_p)
1252 first_p = false;
1254 new_ds = ds;
1256 else
1257 new_ds = ds_merge (new_ds, ds);
1259 else if (DEP_TYPE (dep) == REG_DEP_CONTROL)
1261 if (QUEUE_INDEX (pro) != QUEUE_SCHEDULED)
1263 n_control++;
1264 modify_dep = dep;
1266 DEP_STATUS (dep) &= ~DEP_CANCELLED;
1268 else if (DEP_REPLACE (dep) != NULL)
1270 if (QUEUE_INDEX (pro) != QUEUE_SCHEDULED)
1272 n_replace++;
1273 modify_dep = dep;
1275 DEP_STATUS (dep) &= ~DEP_CANCELLED;
1279 if (n_replace > 0 && n_control == 0 && n_spec == 0)
1281 if (!dbg_cnt (sched_breakdep))
1282 return HARD_DEP;
1283 FOR_EACH_DEP (next, SD_LIST_BACK, sd_it, dep)
1285 struct dep_replacement *desc = DEP_REPLACE (dep);
1286 if (desc != NULL)
1288 if (desc->insn == next && !for_backtrack)
1290 gcc_assert (n_replace == 1);
1291 apply_replacement (dep, true);
1293 DEP_STATUS (dep) |= DEP_CANCELLED;
1296 return 0;
1299 else if (n_control == 1 && n_replace == 0 && n_spec == 0)
1301 rtx_insn *pro, *other;
1302 rtx new_pat;
1303 rtx cond = NULL_RTX;
1304 bool success;
1305 rtx_insn *prev = NULL;
1306 int i;
1307 unsigned regno;
1309 if ((current_sched_info->flags & DO_PREDICATION) == 0
1310 || (ORIG_PAT (next) != NULL_RTX
1311 && PREDICATED_PAT (next) == NULL_RTX))
1312 return HARD_DEP;
1314 pro = DEP_PRO (modify_dep);
1315 other = real_insn_for_shadow (pro);
1316 if (other != NULL_RTX)
1317 pro = other;
1319 cond = sched_get_reverse_condition_uncached (pro);
1320 regno = REGNO (XEXP (cond, 0));
1322 /* Find the last scheduled insn that modifies the condition register.
1323 We can stop looking once we find the insn we depend on through the
1324 REG_DEP_CONTROL; if the condition register isn't modified after it,
1325 we know that it still has the right value. */
1326 if (QUEUE_INDEX (pro) == QUEUE_SCHEDULED)
1327 FOR_EACH_VEC_ELT_REVERSE (scheduled_insns, i, prev)
1329 HARD_REG_SET t;
1331 find_all_hard_reg_sets (prev, &t, true);
1332 if (TEST_HARD_REG_BIT (t, regno))
1333 return HARD_DEP;
1334 if (prev == pro)
1335 break;
1337 if (ORIG_PAT (next) == NULL_RTX)
1339 ORIG_PAT (next) = PATTERN (next);
1341 new_pat = gen_rtx_COND_EXEC (VOIDmode, cond, PATTERN (next));
1342 success = haifa_change_pattern (next, new_pat);
1343 if (!success)
1344 return HARD_DEP;
1345 PREDICATED_PAT (next) = new_pat;
1347 else if (PATTERN (next) != PREDICATED_PAT (next))
1349 bool success = haifa_change_pattern (next,
1350 PREDICATED_PAT (next));
1351 gcc_assert (success);
1353 DEP_STATUS (modify_dep) |= DEP_CANCELLED;
1354 return DEP_CONTROL;
1357 if (PREDICATED_PAT (next) != NULL_RTX)
1359 int tick = INSN_TICK (next);
1360 bool success = haifa_change_pattern (next,
1361 ORIG_PAT (next));
1362 INSN_TICK (next) = tick;
1363 gcc_assert (success);
1366 /* We can't handle the case where there are both speculative and control
1367 dependencies, so we return HARD_DEP in such a case. Also fail if
1368 we have speculative dependencies with not enough points, or more than
1369 one control dependency. */
1370 if ((n_spec > 0 && (n_control > 0 || n_replace > 0))
1371 || (n_spec > 0
1372 /* Too few points? */
1373 && ds_weak (new_ds) < spec_info->data_weakness_cutoff)
1374 || n_control > 0
1375 || n_replace > 0)
1376 return HARD_DEP;
1378 return new_ds;
1381 /* Pointer to the last instruction scheduled. */
1382 static rtx_insn *last_scheduled_insn;
1384 /* Pointer to the last nondebug instruction scheduled within the
1385 block, or the prev_head of the scheduling block. Used by
1386 rank_for_schedule, so that insns independent of the last scheduled
1387 insn will be preferred over dependent instructions. */
1388 static rtx_insn *last_nondebug_scheduled_insn;
1390 /* Pointer that iterates through the list of unscheduled insns if we
1391 have a dbg_cnt enabled. It always points at an insn prior to the
1392 first unscheduled one. */
1393 static rtx_insn *nonscheduled_insns_begin;
1395 /* Compute cost of executing INSN.
1396 This is the number of cycles between instruction issue and
1397 instruction results. */
1399 insn_cost (rtx_insn *insn)
1401 int cost;
1403 if (sched_fusion)
1404 return 0;
1406 if (sel_sched_p ())
1408 if (recog_memoized (insn) < 0)
1409 return 0;
1411 cost = insn_default_latency (insn);
1412 if (cost < 0)
1413 cost = 0;
1415 return cost;
1418 cost = INSN_COST (insn);
1420 if (cost < 0)
1422 /* A USE insn, or something else we don't need to
1423 understand. We can't pass these directly to
1424 result_ready_cost or insn_default_latency because it will
1425 trigger a fatal error for unrecognizable insns. */
1426 if (recog_memoized (insn) < 0)
1428 INSN_COST (insn) = 0;
1429 return 0;
1431 else
1433 cost = insn_default_latency (insn);
1434 if (cost < 0)
1435 cost = 0;
1437 INSN_COST (insn) = cost;
1441 return cost;
1444 /* Compute cost of dependence LINK.
1445 This is the number of cycles between instruction issue and
1446 instruction results.
1447 ??? We also use this function to call recog_memoized on all insns. */
1449 dep_cost_1 (dep_t link, dw_t dw)
1451 rtx_insn *insn = DEP_PRO (link);
1452 rtx_insn *used = DEP_CON (link);
1453 int cost;
1455 if (DEP_COST (link) != UNKNOWN_DEP_COST)
1456 return DEP_COST (link);
1458 if (delay_htab)
1460 struct delay_pair *delay_entry;
1461 delay_entry
1462 = delay_htab_i2->find_with_hash (used, htab_hash_pointer (used));
1463 if (delay_entry)
1465 if (delay_entry->i1 == insn)
1467 DEP_COST (link) = pair_delay (delay_entry);
1468 return DEP_COST (link);
1473 /* A USE insn should never require the value used to be computed.
1474 This allows the computation of a function's result and parameter
1475 values to overlap the return and call. We don't care about the
1476 dependence cost when only decreasing register pressure. */
1477 if (recog_memoized (used) < 0)
1479 cost = 0;
1480 recog_memoized (insn);
1482 else
1484 enum reg_note dep_type = DEP_TYPE (link);
1486 cost = insn_cost (insn);
1488 if (INSN_CODE (insn) >= 0)
1490 if (dep_type == REG_DEP_ANTI)
1491 cost = 0;
1492 else if (dep_type == REG_DEP_OUTPUT)
1494 cost = (insn_default_latency (insn)
1495 - insn_default_latency (used));
1496 if (cost <= 0)
1497 cost = 1;
1499 else if (bypass_p (insn))
1500 cost = insn_latency (insn, used);
1504 if (targetm.sched.adjust_cost_2)
1505 cost = targetm.sched.adjust_cost_2 (used, (int) dep_type, insn, cost,
1506 dw);
1507 else if (targetm.sched.adjust_cost != NULL)
1509 /* This variable is used for backward compatibility with the
1510 targets. */
1511 rtx_insn_list *dep_cost_rtx_link =
1512 alloc_INSN_LIST (NULL_RTX, NULL);
1514 /* Make it self-cycled, so that if some tries to walk over this
1515 incomplete list he/she will be caught in an endless loop. */
1516 XEXP (dep_cost_rtx_link, 1) = dep_cost_rtx_link;
1518 /* Targets use only REG_NOTE_KIND of the link. */
1519 PUT_REG_NOTE_KIND (dep_cost_rtx_link, DEP_TYPE (link));
1521 cost = targetm.sched.adjust_cost (used, dep_cost_rtx_link,
1522 insn, cost);
1524 free_INSN_LIST_node (dep_cost_rtx_link);
1527 if (cost < 0)
1528 cost = 0;
1531 DEP_COST (link) = cost;
1532 return cost;
1535 /* Compute cost of dependence LINK.
1536 This is the number of cycles between instruction issue and
1537 instruction results. */
1539 dep_cost (dep_t link)
1541 return dep_cost_1 (link, 0);
1544 /* Use this sel-sched.c friendly function in reorder2 instead of increasing
1545 INSN_PRIORITY explicitly. */
1546 void
1547 increase_insn_priority (rtx_insn *insn, int amount)
1549 if (!sel_sched_p ())
1551 /* We're dealing with haifa-sched.c INSN_PRIORITY. */
1552 if (INSN_PRIORITY_KNOWN (insn))
1553 INSN_PRIORITY (insn) += amount;
1555 else
1557 /* In sel-sched.c INSN_PRIORITY is not kept up to date.
1558 Use EXPR_PRIORITY instead. */
1559 sel_add_to_insn_priority (insn, amount);
1563 /* Return 'true' if DEP should be included in priority calculations. */
1564 static bool
1565 contributes_to_priority_p (dep_t dep)
1567 if (DEBUG_INSN_P (DEP_CON (dep))
1568 || DEBUG_INSN_P (DEP_PRO (dep)))
1569 return false;
1571 /* Critical path is meaningful in block boundaries only. */
1572 if (!current_sched_info->contributes_to_priority (DEP_CON (dep),
1573 DEP_PRO (dep)))
1574 return false;
1576 if (DEP_REPLACE (dep) != NULL)
1577 return false;
1579 /* If flag COUNT_SPEC_IN_CRITICAL_PATH is set,
1580 then speculative instructions will less likely be
1581 scheduled. That is because the priority of
1582 their producers will increase, and, thus, the
1583 producers will more likely be scheduled, thus,
1584 resolving the dependence. */
1585 if (sched_deps_info->generate_spec_deps
1586 && !(spec_info->flags & COUNT_SPEC_IN_CRITICAL_PATH)
1587 && (DEP_STATUS (dep) & SPECULATIVE))
1588 return false;
1590 return true;
1593 /* Compute the number of nondebug deps in list LIST for INSN. */
1595 static int
1596 dep_list_size (rtx_insn *insn, sd_list_types_def list)
1598 sd_iterator_def sd_it;
1599 dep_t dep;
1600 int dbgcount = 0, nodbgcount = 0;
1602 if (!MAY_HAVE_DEBUG_INSNS)
1603 return sd_lists_size (insn, list);
1605 FOR_EACH_DEP (insn, list, sd_it, dep)
1607 if (DEBUG_INSN_P (DEP_CON (dep)))
1608 dbgcount++;
1609 else if (!DEBUG_INSN_P (DEP_PRO (dep)))
1610 nodbgcount++;
1613 gcc_assert (dbgcount + nodbgcount == sd_lists_size (insn, list));
1615 return nodbgcount;
1618 bool sched_fusion;
1620 /* Compute the priority number for INSN. */
1621 static int
1622 priority (rtx_insn *insn)
1624 if (! INSN_P (insn))
1625 return 0;
1627 /* We should not be interested in priority of an already scheduled insn. */
1628 gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
1630 if (!INSN_PRIORITY_KNOWN (insn))
1632 int this_priority = -1;
1634 if (sched_fusion)
1636 int this_fusion_priority;
1638 targetm.sched.fusion_priority (insn, FUSION_MAX_PRIORITY,
1639 &this_fusion_priority, &this_priority);
1640 INSN_FUSION_PRIORITY (insn) = this_fusion_priority;
1642 else if (dep_list_size (insn, SD_LIST_FORW) == 0)
1643 /* ??? We should set INSN_PRIORITY to insn_cost when and insn has
1644 some forward deps but all of them are ignored by
1645 contributes_to_priority hook. At the moment we set priority of
1646 such insn to 0. */
1647 this_priority = insn_cost (insn);
1648 else
1650 rtx_insn *prev_first, *twin;
1651 basic_block rec;
1653 /* For recovery check instructions we calculate priority slightly
1654 different than that of normal instructions. Instead of walking
1655 through INSN_FORW_DEPS (check) list, we walk through
1656 INSN_FORW_DEPS list of each instruction in the corresponding
1657 recovery block. */
1659 /* Selective scheduling does not define RECOVERY_BLOCK macro. */
1660 rec = sel_sched_p () ? NULL : RECOVERY_BLOCK (insn);
1661 if (!rec || rec == EXIT_BLOCK_PTR_FOR_FN (cfun))
1663 prev_first = PREV_INSN (insn);
1664 twin = insn;
1666 else
1668 prev_first = NEXT_INSN (BB_HEAD (rec));
1669 twin = PREV_INSN (BB_END (rec));
1674 sd_iterator_def sd_it;
1675 dep_t dep;
1677 FOR_EACH_DEP (twin, SD_LIST_FORW, sd_it, dep)
1679 rtx_insn *next;
1680 int next_priority;
1682 next = DEP_CON (dep);
1684 if (BLOCK_FOR_INSN (next) != rec)
1686 int cost;
1688 if (!contributes_to_priority_p (dep))
1689 continue;
1691 if (twin == insn)
1692 cost = dep_cost (dep);
1693 else
1695 struct _dep _dep1, *dep1 = &_dep1;
1697 init_dep (dep1, insn, next, REG_DEP_ANTI);
1699 cost = dep_cost (dep1);
1702 next_priority = cost + priority (next);
1704 if (next_priority > this_priority)
1705 this_priority = next_priority;
1709 twin = PREV_INSN (twin);
1711 while (twin != prev_first);
1714 if (this_priority < 0)
1716 gcc_assert (this_priority == -1);
1718 this_priority = insn_cost (insn);
1721 INSN_PRIORITY (insn) = this_priority;
1722 INSN_PRIORITY_STATUS (insn) = 1;
1725 return INSN_PRIORITY (insn);
1728 /* Macros and functions for keeping the priority queue sorted, and
1729 dealing with queuing and dequeuing of instructions. */
1731 /* For each pressure class CL, set DEATH[CL] to the number of registers
1732 in that class that die in INSN. */
1734 static void
1735 calculate_reg_deaths (rtx_insn *insn, int *death)
1737 int i;
1738 struct reg_use_data *use;
1740 for (i = 0; i < ira_pressure_classes_num; i++)
1741 death[ira_pressure_classes[i]] = 0;
1742 for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
1743 if (dying_use_p (use))
1744 mark_regno_birth_or_death (0, death, use->regno, true);
1747 /* Setup info about the current register pressure impact of scheduling
1748 INSN at the current scheduling point. */
1749 static void
1750 setup_insn_reg_pressure_info (rtx_insn *insn)
1752 int i, change, before, after, hard_regno;
1753 int excess_cost_change;
1754 machine_mode mode;
1755 enum reg_class cl;
1756 struct reg_pressure_data *pressure_info;
1757 int *max_reg_pressure;
1758 static int death[N_REG_CLASSES];
1760 gcc_checking_assert (!DEBUG_INSN_P (insn));
1762 excess_cost_change = 0;
1763 calculate_reg_deaths (insn, death);
1764 pressure_info = INSN_REG_PRESSURE (insn);
1765 max_reg_pressure = INSN_MAX_REG_PRESSURE (insn);
1766 gcc_assert (pressure_info != NULL && max_reg_pressure != NULL);
1767 for (i = 0; i < ira_pressure_classes_num; i++)
1769 cl = ira_pressure_classes[i];
1770 gcc_assert (curr_reg_pressure[cl] >= 0);
1771 change = (int) pressure_info[i].set_increase - death[cl];
1772 before = MAX (0, max_reg_pressure[i] - sched_class_regs_num[cl]);
1773 after = MAX (0, max_reg_pressure[i] + change
1774 - sched_class_regs_num[cl]);
1775 hard_regno = ira_class_hard_regs[cl][0];
1776 gcc_assert (hard_regno >= 0);
1777 mode = reg_raw_mode[hard_regno];
1778 excess_cost_change += ((after - before)
1779 * (ira_memory_move_cost[mode][cl][0]
1780 + ira_memory_move_cost[mode][cl][1]));
1782 INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insn) = excess_cost_change;
1785 /* This is the first page of code related to SCHED_PRESSURE_MODEL.
1786 It tries to make the scheduler take register pressure into account
1787 without introducing too many unnecessary stalls. It hooks into the
1788 main scheduling algorithm at several points:
1790 - Before scheduling starts, model_start_schedule constructs a
1791 "model schedule" for the current block. This model schedule is
1792 chosen solely to keep register pressure down. It does not take the
1793 target's pipeline or the original instruction order into account,
1794 except as a tie-breaker. It also doesn't work to a particular
1795 pressure limit.
1797 This model schedule gives us an idea of what pressure can be
1798 achieved for the block and gives us an example of a schedule that
1799 keeps to that pressure. It also makes the final schedule less
1800 dependent on the original instruction order. This is important
1801 because the original order can either be "wide" (many values live
1802 at once, such as in user-scheduled code) or "narrow" (few values
1803 live at once, such as after loop unrolling, where several
1804 iterations are executed sequentially).
1806 We do not apply this model schedule to the rtx stream. We simply
1807 record it in model_schedule. We also compute the maximum pressure,
1808 MP, that was seen during this schedule.
1810 - Instructions are added to the ready queue even if they require
1811 a stall. The length of the stall is instead computed as:
1813 MAX (INSN_TICK (INSN) - clock_var, 0)
1815 (= insn_delay). This allows rank_for_schedule to choose between
1816 introducing a deliberate stall or increasing pressure.
1818 - Before sorting the ready queue, model_set_excess_costs assigns
1819 a pressure-based cost to each ready instruction in the queue.
1820 This is the instruction's INSN_REG_PRESSURE_EXCESS_COST_CHANGE
1821 (ECC for short) and is effectively measured in cycles.
1823 - rank_for_schedule ranks instructions based on:
1825 ECC (insn) + insn_delay (insn)
1827 then as:
1829 insn_delay (insn)
1831 So, for example, an instruction X1 with an ECC of 1 that can issue
1832 now will win over an instruction X0 with an ECC of zero that would
1833 introduce a stall of one cycle. However, an instruction X2 with an
1834 ECC of 2 that can issue now will lose to both X0 and X1.
1836 - When an instruction is scheduled, model_recompute updates the model
1837 schedule with the new pressures (some of which might now exceed the
1838 original maximum pressure MP). model_update_limit_points then searches
1839 for the new point of maximum pressure, if not already known. */
1841 /* Used to separate high-verbosity debug information for SCHED_PRESSURE_MODEL
1842 from surrounding debug information. */
1843 #define MODEL_BAR \
1844 ";;\t\t+------------------------------------------------------\n"
1846 /* Information about the pressure on a particular register class at a
1847 particular point of the model schedule. */
1848 struct model_pressure_data {
1849 /* The pressure at this point of the model schedule, or -1 if the
1850 point is associated with an instruction that has already been
1851 scheduled. */
1852 int ref_pressure;
1854 /* The maximum pressure during or after this point of the model schedule. */
1855 int max_pressure;
1858 /* Per-instruction information that is used while building the model
1859 schedule. Here, "schedule" refers to the model schedule rather
1860 than the main schedule. */
1861 struct model_insn_info {
1862 /* The instruction itself. */
1863 rtx_insn *insn;
1865 /* If this instruction is in model_worklist, these fields link to the
1866 previous (higher-priority) and next (lower-priority) instructions
1867 in the list. */
1868 struct model_insn_info *prev;
1869 struct model_insn_info *next;
1871 /* While constructing the schedule, QUEUE_INDEX describes whether an
1872 instruction has already been added to the schedule (QUEUE_SCHEDULED),
1873 is in model_worklist (QUEUE_READY), or neither (QUEUE_NOWHERE).
1874 old_queue records the value that QUEUE_INDEX had before scheduling
1875 started, so that we can restore it once the schedule is complete. */
1876 int old_queue;
1878 /* The relative importance of an unscheduled instruction. Higher
1879 values indicate greater importance. */
1880 unsigned int model_priority;
1882 /* The length of the longest path of satisfied true dependencies
1883 that leads to this instruction. */
1884 unsigned int depth;
1886 /* The length of the longest path of dependencies of any kind
1887 that leads from this instruction. */
1888 unsigned int alap;
1890 /* The number of predecessor nodes that must still be scheduled. */
1891 int unscheduled_preds;
1894 /* Information about the pressure limit for a particular register class.
1895 This structure is used when applying a model schedule to the main
1896 schedule. */
1897 struct model_pressure_limit {
1898 /* The maximum register pressure seen in the original model schedule. */
1899 int orig_pressure;
1901 /* The maximum register pressure seen in the current model schedule
1902 (which excludes instructions that have already been scheduled). */
1903 int pressure;
1905 /* The point of the current model schedule at which PRESSURE is first
1906 reached. It is set to -1 if the value needs to be recomputed. */
1907 int point;
1910 /* Describes a particular way of measuring register pressure. */
1911 struct model_pressure_group {
1912 /* Index PCI describes the maximum pressure on ira_pressure_classes[PCI]. */
1913 struct model_pressure_limit limits[N_REG_CLASSES];
1915 /* Index (POINT * ira_num_pressure_classes + PCI) describes the pressure
1916 on register class ira_pressure_classes[PCI] at point POINT of the
1917 current model schedule. A POINT of model_num_insns describes the
1918 pressure at the end of the schedule. */
1919 struct model_pressure_data *model;
1922 /* Index POINT gives the instruction at point POINT of the model schedule.
1923 This array doesn't change during main scheduling. */
1924 static vec<rtx_insn *> model_schedule;
1926 /* The list of instructions in the model worklist, sorted in order of
1927 decreasing priority. */
1928 static struct model_insn_info *model_worklist;
1930 /* Index I describes the instruction with INSN_LUID I. */
1931 static struct model_insn_info *model_insns;
1933 /* The number of instructions in the model schedule. */
1934 static int model_num_insns;
1936 /* The index of the first instruction in model_schedule that hasn't yet been
1937 added to the main schedule, or model_num_insns if all of them have. */
1938 static int model_curr_point;
1940 /* Describes the pressure before each instruction in the model schedule. */
1941 static struct model_pressure_group model_before_pressure;
1943 /* The first unused model_priority value (as used in model_insn_info). */
1944 static unsigned int model_next_priority;
1947 /* The model_pressure_data for ira_pressure_classes[PCI] in GROUP
1948 at point POINT of the model schedule. */
1949 #define MODEL_PRESSURE_DATA(GROUP, POINT, PCI) \
1950 (&(GROUP)->model[(POINT) * ira_pressure_classes_num + (PCI)])
1952 /* The maximum pressure on ira_pressure_classes[PCI] in GROUP at or
1953 after point POINT of the model schedule. */
1954 #define MODEL_MAX_PRESSURE(GROUP, POINT, PCI) \
1955 (MODEL_PRESSURE_DATA (GROUP, POINT, PCI)->max_pressure)
1957 /* The pressure on ira_pressure_classes[PCI] in GROUP at point POINT
1958 of the model schedule. */
1959 #define MODEL_REF_PRESSURE(GROUP, POINT, PCI) \
1960 (MODEL_PRESSURE_DATA (GROUP, POINT, PCI)->ref_pressure)
1962 /* Information about INSN that is used when creating the model schedule. */
1963 #define MODEL_INSN_INFO(INSN) \
1964 (&model_insns[INSN_LUID (INSN)])
1966 /* The instruction at point POINT of the model schedule. */
1967 #define MODEL_INSN(POINT) \
1968 (model_schedule[POINT])
1971 /* Return INSN's index in the model schedule, or model_num_insns if it
1972 doesn't belong to that schedule. */
1974 static int
1975 model_index (rtx_insn *insn)
1977 if (INSN_MODEL_INDEX (insn) == 0)
1978 return model_num_insns;
1979 return INSN_MODEL_INDEX (insn) - 1;
1982 /* Make sure that GROUP->limits is up-to-date for the current point
1983 of the model schedule. */
1985 static void
1986 model_update_limit_points_in_group (struct model_pressure_group *group)
1988 int pci, max_pressure, point;
1990 for (pci = 0; pci < ira_pressure_classes_num; pci++)
1992 /* We may have passed the final point at which the pressure in
1993 group->limits[pci].pressure was reached. Update the limit if so. */
1994 max_pressure = MODEL_MAX_PRESSURE (group, model_curr_point, pci);
1995 group->limits[pci].pressure = max_pressure;
1997 /* Find the point at which MAX_PRESSURE is first reached. We need
1998 to search in three cases:
2000 - We've already moved past the previous pressure point.
2001 In this case we search forward from model_curr_point.
2003 - We scheduled the previous point of maximum pressure ahead of
2004 its position in the model schedule, but doing so didn't bring
2005 the pressure point earlier. In this case we search forward
2006 from that previous pressure point.
2008 - Scheduling an instruction early caused the maximum pressure
2009 to decrease. In this case we will have set the pressure
2010 point to -1, and we search forward from model_curr_point. */
2011 point = MAX (group->limits[pci].point, model_curr_point);
2012 while (point < model_num_insns
2013 && MODEL_REF_PRESSURE (group, point, pci) < max_pressure)
2014 point++;
2015 group->limits[pci].point = point;
2017 gcc_assert (MODEL_REF_PRESSURE (group, point, pci) == max_pressure);
2018 gcc_assert (MODEL_MAX_PRESSURE (group, point, pci) == max_pressure);
2022 /* Make sure that all register-pressure limits are up-to-date for the
2023 current position in the model schedule. */
2025 static void
2026 model_update_limit_points (void)
2028 model_update_limit_points_in_group (&model_before_pressure);
2031 /* Return the model_index of the last unscheduled use in chain USE
2032 outside of USE's instruction. Return -1 if there are no other uses,
2033 or model_num_insns if the register is live at the end of the block. */
2035 static int
2036 model_last_use_except (struct reg_use_data *use)
2038 struct reg_use_data *next;
2039 int last, index;
2041 last = -1;
2042 for (next = use->next_regno_use; next != use; next = next->next_regno_use)
2043 if (NONDEBUG_INSN_P (next->insn)
2044 && QUEUE_INDEX (next->insn) != QUEUE_SCHEDULED)
2046 index = model_index (next->insn);
2047 if (index == model_num_insns)
2048 return model_num_insns;
2049 if (last < index)
2050 last = index;
2052 return last;
2055 /* An instruction with model_index POINT has just been scheduled, and it
2056 adds DELTA to the pressure on ira_pressure_classes[PCI] after POINT - 1.
2057 Update MODEL_REF_PRESSURE (GROUP, POINT, PCI) and
2058 MODEL_MAX_PRESSURE (GROUP, POINT, PCI) accordingly. */
2060 static void
2061 model_start_update_pressure (struct model_pressure_group *group,
2062 int point, int pci, int delta)
2064 int next_max_pressure;
2066 if (point == model_num_insns)
2068 /* The instruction wasn't part of the model schedule; it was moved
2069 from a different block. Update the pressure for the end of
2070 the model schedule. */
2071 MODEL_REF_PRESSURE (group, point, pci) += delta;
2072 MODEL_MAX_PRESSURE (group, point, pci) += delta;
2074 else
2076 /* Record that this instruction has been scheduled. Nothing now
2077 changes between POINT and POINT + 1, so get the maximum pressure
2078 from the latter. If the maximum pressure decreases, the new
2079 pressure point may be before POINT. */
2080 MODEL_REF_PRESSURE (group, point, pci) = -1;
2081 next_max_pressure = MODEL_MAX_PRESSURE (group, point + 1, pci);
2082 if (MODEL_MAX_PRESSURE (group, point, pci) > next_max_pressure)
2084 MODEL_MAX_PRESSURE (group, point, pci) = next_max_pressure;
2085 if (group->limits[pci].point == point)
2086 group->limits[pci].point = -1;
2091 /* Record that scheduling a later instruction has changed the pressure
2092 at point POINT of the model schedule by DELTA (which might be 0).
2093 Update GROUP accordingly. Return nonzero if these changes might
2094 trigger changes to previous points as well. */
2096 static int
2097 model_update_pressure (struct model_pressure_group *group,
2098 int point, int pci, int delta)
2100 int ref_pressure, max_pressure, next_max_pressure;
2102 /* If POINT hasn't yet been scheduled, update its pressure. */
2103 ref_pressure = MODEL_REF_PRESSURE (group, point, pci);
2104 if (ref_pressure >= 0 && delta != 0)
2106 ref_pressure += delta;
2107 MODEL_REF_PRESSURE (group, point, pci) = ref_pressure;
2109 /* Check whether the maximum pressure in the overall schedule
2110 has increased. (This means that the MODEL_MAX_PRESSURE of
2111 every point <= POINT will need to increase too; see below.) */
2112 if (group->limits[pci].pressure < ref_pressure)
2113 group->limits[pci].pressure = ref_pressure;
2115 /* If we are at maximum pressure, and the maximum pressure
2116 point was previously unknown or later than POINT,
2117 bring it forward. */
2118 if (group->limits[pci].pressure == ref_pressure
2119 && !IN_RANGE (group->limits[pci].point, 0, point))
2120 group->limits[pci].point = point;
2122 /* If POINT used to be the point of maximum pressure, but isn't
2123 any longer, we need to recalculate it using a forward walk. */
2124 if (group->limits[pci].pressure > ref_pressure
2125 && group->limits[pci].point == point)
2126 group->limits[pci].point = -1;
2129 /* Update the maximum pressure at POINT. Changes here might also
2130 affect the maximum pressure at POINT - 1. */
2131 next_max_pressure = MODEL_MAX_PRESSURE (group, point + 1, pci);
2132 max_pressure = MAX (ref_pressure, next_max_pressure);
2133 if (MODEL_MAX_PRESSURE (group, point, pci) != max_pressure)
2135 MODEL_MAX_PRESSURE (group, point, pci) = max_pressure;
2136 return 1;
2138 return 0;
2141 /* INSN has just been scheduled. Update the model schedule accordingly. */
2143 static void
2144 model_recompute (rtx_insn *insn)
2146 struct {
2147 int last_use;
2148 int regno;
2149 } uses[FIRST_PSEUDO_REGISTER + MAX_RECOG_OPERANDS];
2150 struct reg_use_data *use;
2151 struct reg_pressure_data *reg_pressure;
2152 int delta[N_REG_CLASSES];
2153 int pci, point, mix, new_last, cl, ref_pressure, queue;
2154 unsigned int i, num_uses, num_pending_births;
2155 bool print_p;
2157 /* The destinations of INSN were previously live from POINT onwards, but are
2158 now live from model_curr_point onwards. Set up DELTA accordingly. */
2159 point = model_index (insn);
2160 reg_pressure = INSN_REG_PRESSURE (insn);
2161 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2163 cl = ira_pressure_classes[pci];
2164 delta[cl] = reg_pressure[pci].set_increase;
2167 /* Record which registers previously died at POINT, but which now die
2168 before POINT. Adjust DELTA so that it represents the effect of
2169 this change after POINT - 1. Set NUM_PENDING_BIRTHS to the number of
2170 registers that will be born in the range [model_curr_point, POINT). */
2171 num_uses = 0;
2172 num_pending_births = 0;
2173 for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
2175 new_last = model_last_use_except (use);
2176 if (new_last < point)
2178 gcc_assert (num_uses < ARRAY_SIZE (uses));
2179 uses[num_uses].last_use = new_last;
2180 uses[num_uses].regno = use->regno;
2181 /* This register is no longer live after POINT - 1. */
2182 mark_regno_birth_or_death (NULL, delta, use->regno, false);
2183 num_uses++;
2184 if (new_last >= 0)
2185 num_pending_births++;
2189 /* Update the MODEL_REF_PRESSURE and MODEL_MAX_PRESSURE for POINT.
2190 Also set each group pressure limit for POINT. */
2191 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2193 cl = ira_pressure_classes[pci];
2194 model_start_update_pressure (&model_before_pressure,
2195 point, pci, delta[cl]);
2198 /* Walk the model schedule backwards, starting immediately before POINT. */
2199 print_p = false;
2200 if (point != model_curr_point)
2203 point--;
2204 insn = MODEL_INSN (point);
2205 queue = QUEUE_INDEX (insn);
2207 if (queue != QUEUE_SCHEDULED)
2209 /* DELTA describes the effect of the move on the register pressure
2210 after POINT. Make it describe the effect on the pressure
2211 before POINT. */
2212 i = 0;
2213 while (i < num_uses)
2215 if (uses[i].last_use == point)
2217 /* This register is now live again. */
2218 mark_regno_birth_or_death (NULL, delta,
2219 uses[i].regno, true);
2221 /* Remove this use from the array. */
2222 uses[i] = uses[num_uses - 1];
2223 num_uses--;
2224 num_pending_births--;
2226 else
2227 i++;
2230 if (sched_verbose >= 5)
2232 if (!print_p)
2234 fprintf (sched_dump, MODEL_BAR);
2235 fprintf (sched_dump, ";;\t\t| New pressure for model"
2236 " schedule\n");
2237 fprintf (sched_dump, MODEL_BAR);
2238 print_p = true;
2241 fprintf (sched_dump, ";;\t\t| %3d %4d %-30s ",
2242 point, INSN_UID (insn),
2243 str_pattern_slim (PATTERN (insn)));
2244 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2246 cl = ira_pressure_classes[pci];
2247 ref_pressure = MODEL_REF_PRESSURE (&model_before_pressure,
2248 point, pci);
2249 fprintf (sched_dump, " %s:[%d->%d]",
2250 reg_class_names[ira_pressure_classes[pci]],
2251 ref_pressure, ref_pressure + delta[cl]);
2253 fprintf (sched_dump, "\n");
2257 /* Adjust the pressure at POINT. Set MIX to nonzero if POINT - 1
2258 might have changed as well. */
2259 mix = num_pending_births;
2260 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2262 cl = ira_pressure_classes[pci];
2263 mix |= delta[cl];
2264 mix |= model_update_pressure (&model_before_pressure,
2265 point, pci, delta[cl]);
2268 while (mix && point > model_curr_point);
2270 if (print_p)
2271 fprintf (sched_dump, MODEL_BAR);
2274 /* After DEP, which was cancelled, has been resolved for insn NEXT,
2275 check whether the insn's pattern needs restoring. */
2276 static bool
2277 must_restore_pattern_p (rtx_insn *next, dep_t dep)
2279 if (QUEUE_INDEX (next) == QUEUE_SCHEDULED)
2280 return false;
2282 if (DEP_TYPE (dep) == REG_DEP_CONTROL)
2284 gcc_assert (ORIG_PAT (next) != NULL_RTX);
2285 gcc_assert (next == DEP_CON (dep));
2287 else
2289 struct dep_replacement *desc = DEP_REPLACE (dep);
2290 if (desc->insn != next)
2292 gcc_assert (*desc->loc == desc->orig);
2293 return false;
2296 return true;
2299 /* model_spill_cost (CL, P, P') returns the cost of increasing the
2300 pressure on CL from P to P'. We use this to calculate a "base ECC",
2301 baseECC (CL, X), for each pressure class CL and each instruction X.
2302 Supposing X changes the pressure on CL from P to P', and that the
2303 maximum pressure on CL in the current model schedule is MP', then:
2305 * if X occurs before or at the next point of maximum pressure in
2306 the model schedule and P' > MP', then:
2308 baseECC (CL, X) = model_spill_cost (CL, MP, P')
2310 The idea is that the pressure after scheduling a fixed set of
2311 instructions -- in this case, the set up to and including the
2312 next maximum pressure point -- is going to be the same regardless
2313 of the order; we simply want to keep the intermediate pressure
2314 under control. Thus X has a cost of zero unless scheduling it
2315 now would exceed MP'.
2317 If all increases in the set are by the same amount, no zero-cost
2318 instruction will ever cause the pressure to exceed MP'. However,
2319 if X is instead moved past an instruction X' with pressure in the
2320 range (MP' - (P' - P), MP'), the pressure at X' will increase
2321 beyond MP'. Since baseECC is very much a heuristic anyway,
2322 it doesn't seem worth the overhead of tracking cases like these.
2324 The cost of exceeding MP' is always based on the original maximum
2325 pressure MP. This is so that going 2 registers over the original
2326 limit has the same cost regardless of whether it comes from two
2327 separate +1 deltas or from a single +2 delta.
2329 * if X occurs after the next point of maximum pressure in the model
2330 schedule and P' > P, then:
2332 baseECC (CL, X) = model_spill_cost (CL, MP, MP' + (P' - P))
2334 That is, if we move X forward across a point of maximum pressure,
2335 and if X increases the pressure by P' - P, then we conservatively
2336 assume that scheduling X next would increase the maximum pressure
2337 by P' - P. Again, the cost of doing this is based on the original
2338 maximum pressure MP, for the same reason as above.
2340 * if P' < P, P > MP, and X occurs at or after the next point of
2341 maximum pressure, then:
2343 baseECC (CL, X) = -model_spill_cost (CL, MAX (MP, P'), P)
2345 That is, if we have already exceeded the original maximum pressure MP,
2346 and if X might reduce the maximum pressure again -- or at least push
2347 it further back, and thus allow more scheduling freedom -- it is given
2348 a negative cost to reflect the improvement.
2350 * otherwise,
2352 baseECC (CL, X) = 0
2354 In this case, X is not expected to affect the maximum pressure MP',
2355 so it has zero cost.
2357 We then create a combined value baseECC (X) that is the sum of
2358 baseECC (CL, X) for each pressure class CL.
2360 baseECC (X) could itself be used as the ECC value described above.
2361 However, this is often too conservative, in the sense that it
2362 tends to make high-priority instructions that increase pressure
2363 wait too long in cases where introducing a spill would be better.
2364 For this reason the final ECC is a priority-adjusted form of
2365 baseECC (X). Specifically, we calculate:
2367 P (X) = INSN_PRIORITY (X) - insn_delay (X) - baseECC (X)
2368 baseP = MAX { P (X) | baseECC (X) <= 0 }
2370 Then:
2372 ECC (X) = MAX (MIN (baseP - P (X), baseECC (X)), 0)
2374 Thus an instruction's effect on pressure is ignored if it has a high
2375 enough priority relative to the ones that don't increase pressure.
2376 Negative values of baseECC (X) do not increase the priority of X
2377 itself, but they do make it harder for other instructions to
2378 increase the pressure further.
2380 This pressure cost is deliberately timid. The intention has been
2381 to choose a heuristic that rarely interferes with the normal list
2382 scheduler in cases where that scheduler would produce good code.
2383 We simply want to curb some of its worst excesses. */
2385 /* Return the cost of increasing the pressure in class CL from FROM to TO.
2387 Here we use the very simplistic cost model that every register above
2388 sched_class_regs_num[CL] has a spill cost of 1. We could use other
2389 measures instead, such as one based on MEMORY_MOVE_COST. However:
2391 (1) In order for an instruction to be scheduled, the higher cost
2392 would need to be justified in a single saving of that many stalls.
2393 This is overly pessimistic, because the benefit of spilling is
2394 often to avoid a sequence of several short stalls rather than
2395 a single long one.
2397 (2) The cost is still arbitrary. Because we are not allocating
2398 registers during scheduling, we have no way of knowing for
2399 sure how many memory accesses will be required by each spill,
2400 where the spills will be placed within the block, or even
2401 which block(s) will contain the spills.
2403 So a higher cost than 1 is often too conservative in practice,
2404 forcing blocks to contain unnecessary stalls instead of spill code.
2405 The simple cost below seems to be the best compromise. It reduces
2406 the interference with the normal list scheduler, which helps make
2407 it more suitable for a default-on option. */
2409 static int
2410 model_spill_cost (int cl, int from, int to)
2412 from = MAX (from, sched_class_regs_num[cl]);
2413 return MAX (to, from) - from;
2416 /* Return baseECC (ira_pressure_classes[PCI], POINT), given that
2417 P = curr_reg_pressure[ira_pressure_classes[PCI]] and that
2418 P' = P + DELTA. */
2420 static int
2421 model_excess_group_cost (struct model_pressure_group *group,
2422 int point, int pci, int delta)
2424 int pressure, cl;
2426 cl = ira_pressure_classes[pci];
2427 if (delta < 0 && point >= group->limits[pci].point)
2429 pressure = MAX (group->limits[pci].orig_pressure,
2430 curr_reg_pressure[cl] + delta);
2431 return -model_spill_cost (cl, pressure, curr_reg_pressure[cl]);
2434 if (delta > 0)
2436 if (point > group->limits[pci].point)
2437 pressure = group->limits[pci].pressure + delta;
2438 else
2439 pressure = curr_reg_pressure[cl] + delta;
2441 if (pressure > group->limits[pci].pressure)
2442 return model_spill_cost (cl, group->limits[pci].orig_pressure,
2443 pressure);
2446 return 0;
2449 /* Return baseECC (MODEL_INSN (INSN)). Dump the costs to sched_dump
2450 if PRINT_P. */
2452 static int
2453 model_excess_cost (rtx_insn *insn, bool print_p)
2455 int point, pci, cl, cost, this_cost, delta;
2456 struct reg_pressure_data *insn_reg_pressure;
2457 int insn_death[N_REG_CLASSES];
2459 calculate_reg_deaths (insn, insn_death);
2460 point = model_index (insn);
2461 insn_reg_pressure = INSN_REG_PRESSURE (insn);
2462 cost = 0;
2464 if (print_p)
2465 fprintf (sched_dump, ";;\t\t| %3d %4d | %4d %+3d |", point,
2466 INSN_UID (insn), INSN_PRIORITY (insn), insn_delay (insn));
2468 /* Sum up the individual costs for each register class. */
2469 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2471 cl = ira_pressure_classes[pci];
2472 delta = insn_reg_pressure[pci].set_increase - insn_death[cl];
2473 this_cost = model_excess_group_cost (&model_before_pressure,
2474 point, pci, delta);
2475 cost += this_cost;
2476 if (print_p)
2477 fprintf (sched_dump, " %s:[%d base cost %d]",
2478 reg_class_names[cl], delta, this_cost);
2481 if (print_p)
2482 fprintf (sched_dump, "\n");
2484 return cost;
2487 /* Dump the next points of maximum pressure for GROUP. */
2489 static void
2490 model_dump_pressure_points (struct model_pressure_group *group)
2492 int pci, cl;
2494 fprintf (sched_dump, ";;\t\t| pressure points");
2495 for (pci = 0; pci < ira_pressure_classes_num; pci++)
2497 cl = ira_pressure_classes[pci];
2498 fprintf (sched_dump, " %s:[%d->%d at ", reg_class_names[cl],
2499 curr_reg_pressure[cl], group->limits[pci].pressure);
2500 if (group->limits[pci].point < model_num_insns)
2501 fprintf (sched_dump, "%d:%d]", group->limits[pci].point,
2502 INSN_UID (MODEL_INSN (group->limits[pci].point)));
2503 else
2504 fprintf (sched_dump, "end]");
2506 fprintf (sched_dump, "\n");
2509 /* Set INSN_REG_PRESSURE_EXCESS_COST_CHANGE for INSNS[0...COUNT-1]. */
2511 static void
2512 model_set_excess_costs (rtx_insn **insns, int count)
2514 int i, cost, priority_base, priority;
2515 bool print_p;
2517 /* Record the baseECC value for each instruction in the model schedule,
2518 except that negative costs are converted to zero ones now rather than
2519 later. Do not assign a cost to debug instructions, since they must
2520 not change code-generation decisions. Experiments suggest we also
2521 get better results by not assigning a cost to instructions from
2522 a different block.
2524 Set PRIORITY_BASE to baseP in the block comment above. This is the
2525 maximum priority of the "cheap" instructions, which should always
2526 include the next model instruction. */
2527 priority_base = 0;
2528 print_p = false;
2529 for (i = 0; i < count; i++)
2530 if (INSN_MODEL_INDEX (insns[i]))
2532 if (sched_verbose >= 6 && !print_p)
2534 fprintf (sched_dump, MODEL_BAR);
2535 fprintf (sched_dump, ";;\t\t| Pressure costs for ready queue\n");
2536 model_dump_pressure_points (&model_before_pressure);
2537 fprintf (sched_dump, MODEL_BAR);
2538 print_p = true;
2540 cost = model_excess_cost (insns[i], print_p);
2541 if (cost <= 0)
2543 priority = INSN_PRIORITY (insns[i]) - insn_delay (insns[i]) - cost;
2544 priority_base = MAX (priority_base, priority);
2545 cost = 0;
2547 INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insns[i]) = cost;
2549 if (print_p)
2550 fprintf (sched_dump, MODEL_BAR);
2552 /* Use MAX (baseECC, 0) and baseP to calculcate ECC for each
2553 instruction. */
2554 for (i = 0; i < count; i++)
2556 cost = INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insns[i]);
2557 priority = INSN_PRIORITY (insns[i]) - insn_delay (insns[i]);
2558 if (cost > 0 && priority > priority_base)
2560 cost += priority_base - priority;
2561 INSN_REG_PRESSURE_EXCESS_COST_CHANGE (insns[i]) = MAX (cost, 0);
2567 /* Enum of rank_for_schedule heuristic decisions. */
2568 enum rfs_decision {
2569 RFS_LIVE_RANGE_SHRINK1, RFS_LIVE_RANGE_SHRINK2,
2570 RFS_SCHED_GROUP, RFS_PRESSURE_DELAY, RFS_PRESSURE_TICK,
2571 RFS_FEEDS_BACKTRACK_INSN, RFS_PRIORITY, RFS_SPECULATION,
2572 RFS_SCHED_RANK, RFS_LAST_INSN, RFS_PRESSURE_INDEX,
2573 RFS_DEP_COUNT, RFS_TIE, RFS_FUSION, RFS_N };
2575 /* Corresponding strings for print outs. */
2576 static const char *rfs_str[RFS_N] = {
2577 "RFS_LIVE_RANGE_SHRINK1", "RFS_LIVE_RANGE_SHRINK2",
2578 "RFS_SCHED_GROUP", "RFS_PRESSURE_DELAY", "RFS_PRESSURE_TICK",
2579 "RFS_FEEDS_BACKTRACK_INSN", "RFS_PRIORITY", "RFS_SPECULATION",
2580 "RFS_SCHED_RANK", "RFS_LAST_INSN", "RFS_PRESSURE_INDEX",
2581 "RFS_DEP_COUNT", "RFS_TIE", "RFS_FUSION" };
2583 /* Statistical breakdown of rank_for_schedule decisions. */
2584 typedef struct { unsigned stats[RFS_N]; } rank_for_schedule_stats_t;
2585 static rank_for_schedule_stats_t rank_for_schedule_stats;
2587 /* Return the result of comparing insns TMP and TMP2 and update
2588 Rank_For_Schedule statistics. */
2589 static int
2590 rfs_result (enum rfs_decision decision, int result, rtx tmp, rtx tmp2)
2592 ++rank_for_schedule_stats.stats[decision];
2593 if (result < 0)
2594 INSN_LAST_RFS_WIN (tmp) = decision;
2595 else if (result > 0)
2596 INSN_LAST_RFS_WIN (tmp2) = decision;
2597 else
2598 gcc_unreachable ();
2599 return result;
2602 /* Sorting predicate to move DEBUG_INSNs to the top of ready list, while
2603 keeping normal insns in original order. */
2605 static int
2606 rank_for_schedule_debug (const void *x, const void *y)
2608 rtx_insn *tmp = *(rtx_insn * const *) y;
2609 rtx_insn *tmp2 = *(rtx_insn * const *) x;
2611 /* Schedule debug insns as early as possible. */
2612 if (DEBUG_INSN_P (tmp) && !DEBUG_INSN_P (tmp2))
2613 return -1;
2614 else if (!DEBUG_INSN_P (tmp) && DEBUG_INSN_P (tmp2))
2615 return 1;
2616 else if (DEBUG_INSN_P (tmp) && DEBUG_INSN_P (tmp2))
2617 return INSN_LUID (tmp) - INSN_LUID (tmp2);
2618 else
2619 return INSN_RFS_DEBUG_ORIG_ORDER (tmp2) - INSN_RFS_DEBUG_ORIG_ORDER (tmp);
2622 /* Returns a positive value if x is preferred; returns a negative value if
2623 y is preferred. Should never return 0, since that will make the sort
2624 unstable. */
2626 static int
2627 rank_for_schedule (const void *x, const void *y)
2629 rtx_insn *tmp = *(rtx_insn * const *) y;
2630 rtx_insn *tmp2 = *(rtx_insn * const *) x;
2631 int tmp_class, tmp2_class;
2632 int val, priority_val, info_val, diff;
2634 if (live_range_shrinkage_p)
2636 /* Don't use SCHED_PRESSURE_MODEL -- it results in much worse
2637 code. */
2638 gcc_assert (sched_pressure == SCHED_PRESSURE_WEIGHTED);
2639 if ((INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp) < 0
2640 || INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2) < 0)
2641 && (diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
2642 - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2))) != 0)
2643 return rfs_result (RFS_LIVE_RANGE_SHRINK1, diff, tmp, tmp2);
2644 /* Sort by INSN_LUID (original insn order), so that we make the
2645 sort stable. This minimizes instruction movement, thus
2646 minimizing sched's effect on debugging and cross-jumping. */
2647 return rfs_result (RFS_LIVE_RANGE_SHRINK2,
2648 INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2651 /* The insn in a schedule group should be issued the first. */
2652 if (flag_sched_group_heuristic &&
2653 SCHED_GROUP_P (tmp) != SCHED_GROUP_P (tmp2))
2654 return rfs_result (RFS_SCHED_GROUP, SCHED_GROUP_P (tmp2) ? 1 : -1,
2655 tmp, tmp2);
2657 /* Make sure that priority of TMP and TMP2 are initialized. */
2658 gcc_assert (INSN_PRIORITY_KNOWN (tmp) && INSN_PRIORITY_KNOWN (tmp2));
2660 if (sched_fusion)
2662 /* The instruction that has the same fusion priority as the last
2663 instruction is the instruction we picked next. If that is not
2664 the case, we sort ready list firstly by fusion priority, then
2665 by priority, and at last by INSN_LUID. */
2666 int a = INSN_FUSION_PRIORITY (tmp);
2667 int b = INSN_FUSION_PRIORITY (tmp2);
2668 int last = -1;
2670 if (last_nondebug_scheduled_insn
2671 && !NOTE_P (last_nondebug_scheduled_insn)
2672 && BLOCK_FOR_INSN (tmp)
2673 == BLOCK_FOR_INSN (last_nondebug_scheduled_insn))
2674 last = INSN_FUSION_PRIORITY (last_nondebug_scheduled_insn);
2676 if (a != last && b != last)
2678 if (a == b)
2680 a = INSN_PRIORITY (tmp);
2681 b = INSN_PRIORITY (tmp2);
2683 if (a != b)
2684 return rfs_result (RFS_FUSION, b - a, tmp, tmp2);
2685 else
2686 return rfs_result (RFS_FUSION,
2687 INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2689 else if (a == b)
2691 gcc_assert (last_nondebug_scheduled_insn
2692 && !NOTE_P (last_nondebug_scheduled_insn));
2693 last = INSN_PRIORITY (last_nondebug_scheduled_insn);
2695 a = abs (INSN_PRIORITY (tmp) - last);
2696 b = abs (INSN_PRIORITY (tmp2) - last);
2697 if (a != b)
2698 return rfs_result (RFS_FUSION, a - b, tmp, tmp2);
2699 else
2700 return rfs_result (RFS_FUSION,
2701 INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2703 else if (a == last)
2704 return rfs_result (RFS_FUSION, -1, tmp, tmp2);
2705 else
2706 return rfs_result (RFS_FUSION, 1, tmp, tmp2);
2709 if (sched_pressure != SCHED_PRESSURE_NONE)
2711 /* Prefer insn whose scheduling results in the smallest register
2712 pressure excess. */
2713 if ((diff = (INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp)
2714 + insn_delay (tmp)
2715 - INSN_REG_PRESSURE_EXCESS_COST_CHANGE (tmp2)
2716 - insn_delay (tmp2))))
2717 return rfs_result (RFS_PRESSURE_DELAY, diff, tmp, tmp2);
2720 if (sched_pressure != SCHED_PRESSURE_NONE
2721 && (INSN_TICK (tmp2) > clock_var || INSN_TICK (tmp) > clock_var)
2722 && INSN_TICK (tmp2) != INSN_TICK (tmp))
2724 diff = INSN_TICK (tmp) - INSN_TICK (tmp2);
2725 return rfs_result (RFS_PRESSURE_TICK, diff, tmp, tmp2);
2728 /* If we are doing backtracking in this schedule, prefer insns that
2729 have forward dependencies with negative cost against an insn that
2730 was already scheduled. */
2731 if (current_sched_info->flags & DO_BACKTRACKING)
2733 priority_val = FEEDS_BACKTRACK_INSN (tmp2) - FEEDS_BACKTRACK_INSN (tmp);
2734 if (priority_val)
2735 return rfs_result (RFS_FEEDS_BACKTRACK_INSN, priority_val, tmp, tmp2);
2738 /* Prefer insn with higher priority. */
2739 priority_val = INSN_PRIORITY (tmp2) - INSN_PRIORITY (tmp);
2741 if (flag_sched_critical_path_heuristic && priority_val)
2742 return rfs_result (RFS_PRIORITY, priority_val, tmp, tmp2);
2744 if (PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) >= 0)
2746 int autopref = autopref_rank_for_schedule (tmp, tmp2);
2747 if (autopref != 0)
2748 return autopref;
2751 /* Prefer speculative insn with greater dependencies weakness. */
2752 if (flag_sched_spec_insn_heuristic && spec_info)
2754 ds_t ds1, ds2;
2755 dw_t dw1, dw2;
2756 int dw;
2758 ds1 = TODO_SPEC (tmp) & SPECULATIVE;
2759 if (ds1)
2760 dw1 = ds_weak (ds1);
2761 else
2762 dw1 = NO_DEP_WEAK;
2764 ds2 = TODO_SPEC (tmp2) & SPECULATIVE;
2765 if (ds2)
2766 dw2 = ds_weak (ds2);
2767 else
2768 dw2 = NO_DEP_WEAK;
2770 dw = dw2 - dw1;
2771 if (dw > (NO_DEP_WEAK / 8) || dw < -(NO_DEP_WEAK / 8))
2772 return rfs_result (RFS_SPECULATION, dw, tmp, tmp2);
2775 info_val = (*current_sched_info->rank) (tmp, tmp2);
2776 if (flag_sched_rank_heuristic && info_val)
2777 return rfs_result (RFS_SCHED_RANK, info_val, tmp, tmp2);
2779 /* Compare insns based on their relation to the last scheduled
2780 non-debug insn. */
2781 if (flag_sched_last_insn_heuristic && last_nondebug_scheduled_insn)
2783 dep_t dep1;
2784 dep_t dep2;
2785 rtx_insn *last = last_nondebug_scheduled_insn;
2787 /* Classify the instructions into three classes:
2788 1) Data dependent on last schedule insn.
2789 2) Anti/Output dependent on last scheduled insn.
2790 3) Independent of last scheduled insn, or has latency of one.
2791 Choose the insn from the highest numbered class if different. */
2792 dep1 = sd_find_dep_between (last, tmp, true);
2794 if (dep1 == NULL || dep_cost (dep1) == 1)
2795 tmp_class = 3;
2796 else if (/* Data dependence. */
2797 DEP_TYPE (dep1) == REG_DEP_TRUE)
2798 tmp_class = 1;
2799 else
2800 tmp_class = 2;
2802 dep2 = sd_find_dep_between (last, tmp2, true);
2804 if (dep2 == NULL || dep_cost (dep2) == 1)
2805 tmp2_class = 3;
2806 else if (/* Data dependence. */
2807 DEP_TYPE (dep2) == REG_DEP_TRUE)
2808 tmp2_class = 1;
2809 else
2810 tmp2_class = 2;
2812 if ((val = tmp2_class - tmp_class))
2813 return rfs_result (RFS_LAST_INSN, val, tmp, tmp2);
2816 /* Prefer instructions that occur earlier in the model schedule. */
2817 if (sched_pressure == SCHED_PRESSURE_MODEL
2818 && INSN_BB (tmp) == target_bb && INSN_BB (tmp2) == target_bb)
2820 diff = model_index (tmp) - model_index (tmp2);
2821 gcc_assert (diff != 0);
2822 return rfs_result (RFS_PRESSURE_INDEX, diff, tmp, tmp2);
2825 /* Prefer the insn which has more later insns that depend on it.
2826 This gives the scheduler more freedom when scheduling later
2827 instructions at the expense of added register pressure. */
2829 val = (dep_list_size (tmp2, SD_LIST_FORW)
2830 - dep_list_size (tmp, SD_LIST_FORW));
2832 if (flag_sched_dep_count_heuristic && val != 0)
2833 return rfs_result (RFS_DEP_COUNT, val, tmp, tmp2);
2835 /* If insns are equally good, sort by INSN_LUID (original insn order),
2836 so that we make the sort stable. This minimizes instruction movement,
2837 thus minimizing sched's effect on debugging and cross-jumping. */
2838 return rfs_result (RFS_TIE, INSN_LUID (tmp) - INSN_LUID (tmp2), tmp, tmp2);
2841 /* Resort the array A in which only element at index N may be out of order. */
2843 HAIFA_INLINE static void
2844 swap_sort (rtx_insn **a, int n)
2846 rtx_insn *insn = a[n - 1];
2847 int i = n - 2;
2849 while (i >= 0 && rank_for_schedule (a + i, &insn) >= 0)
2851 a[i + 1] = a[i];
2852 i -= 1;
2854 a[i + 1] = insn;
2857 /* Add INSN to the insn queue so that it can be executed at least
2858 N_CYCLES after the currently executing insn. Preserve insns
2859 chain for debugging purposes. REASON will be printed in debugging
2860 output. */
2862 HAIFA_INLINE static void
2863 queue_insn (rtx_insn *insn, int n_cycles, const char *reason)
2865 int next_q = NEXT_Q_AFTER (q_ptr, n_cycles);
2866 rtx_insn_list *link = alloc_INSN_LIST (insn, insn_queue[next_q]);
2867 int new_tick;
2869 gcc_assert (n_cycles <= max_insn_queue_index);
2870 gcc_assert (!DEBUG_INSN_P (insn));
2872 insn_queue[next_q] = link;
2873 q_size += 1;
2875 if (sched_verbose >= 2)
2877 fprintf (sched_dump, ";;\t\tReady-->Q: insn %s: ",
2878 (*current_sched_info->print_insn) (insn, 0));
2880 fprintf (sched_dump, "queued for %d cycles (%s).\n", n_cycles, reason);
2883 QUEUE_INDEX (insn) = next_q;
2885 if (current_sched_info->flags & DO_BACKTRACKING)
2887 new_tick = clock_var + n_cycles;
2888 if (INSN_TICK (insn) == INVALID_TICK || INSN_TICK (insn) < new_tick)
2889 INSN_TICK (insn) = new_tick;
2891 if (INSN_EXACT_TICK (insn) != INVALID_TICK
2892 && INSN_EXACT_TICK (insn) < clock_var + n_cycles)
2894 must_backtrack = true;
2895 if (sched_verbose >= 2)
2896 fprintf (sched_dump, ";;\t\tcausing a backtrack.\n");
2901 /* Remove INSN from queue. */
2902 static void
2903 queue_remove (rtx_insn *insn)
2905 gcc_assert (QUEUE_INDEX (insn) >= 0);
2906 remove_free_INSN_LIST_elem (insn, &insn_queue[QUEUE_INDEX (insn)]);
2907 q_size--;
2908 QUEUE_INDEX (insn) = QUEUE_NOWHERE;
2911 /* Return a pointer to the bottom of the ready list, i.e. the insn
2912 with the lowest priority. */
2914 rtx_insn **
2915 ready_lastpos (struct ready_list *ready)
2917 gcc_assert (ready->n_ready >= 1);
2918 return ready->vec + ready->first - ready->n_ready + 1;
2921 /* Add an element INSN to the ready list so that it ends up with the
2922 lowest/highest priority depending on FIRST_P. */
2924 HAIFA_INLINE static void
2925 ready_add (struct ready_list *ready, rtx_insn *insn, bool first_p)
2927 if (!first_p)
2929 if (ready->first == ready->n_ready)
2931 memmove (ready->vec + ready->veclen - ready->n_ready,
2932 ready_lastpos (ready),
2933 ready->n_ready * sizeof (rtx));
2934 ready->first = ready->veclen - 1;
2936 ready->vec[ready->first - ready->n_ready] = insn;
2938 else
2940 if (ready->first == ready->veclen - 1)
2942 if (ready->n_ready)
2943 /* ready_lastpos() fails when called with (ready->n_ready == 0). */
2944 memmove (ready->vec + ready->veclen - ready->n_ready - 1,
2945 ready_lastpos (ready),
2946 ready->n_ready * sizeof (rtx));
2947 ready->first = ready->veclen - 2;
2949 ready->vec[++(ready->first)] = insn;
2952 ready->n_ready++;
2953 if (DEBUG_INSN_P (insn))
2954 ready->n_debug++;
2956 gcc_assert (QUEUE_INDEX (insn) != QUEUE_READY);
2957 QUEUE_INDEX (insn) = QUEUE_READY;
2959 if (INSN_EXACT_TICK (insn) != INVALID_TICK
2960 && INSN_EXACT_TICK (insn) < clock_var)
2962 must_backtrack = true;
2966 /* Remove the element with the highest priority from the ready list and
2967 return it. */
2969 HAIFA_INLINE static rtx_insn *
2970 ready_remove_first (struct ready_list *ready)
2972 rtx_insn *t;
2974 gcc_assert (ready->n_ready);
2975 t = ready->vec[ready->first--];
2976 ready->n_ready--;
2977 if (DEBUG_INSN_P (t))
2978 ready->n_debug--;
2979 /* If the queue becomes empty, reset it. */
2980 if (ready->n_ready == 0)
2981 ready->first = ready->veclen - 1;
2983 gcc_assert (QUEUE_INDEX (t) == QUEUE_READY);
2984 QUEUE_INDEX (t) = QUEUE_NOWHERE;
2986 return t;
2989 /* The following code implements multi-pass scheduling for the first
2990 cycle. In other words, we will try to choose ready insn which
2991 permits to start maximum number of insns on the same cycle. */
2993 /* Return a pointer to the element INDEX from the ready. INDEX for
2994 insn with the highest priority is 0, and the lowest priority has
2995 N_READY - 1. */
2997 rtx_insn *
2998 ready_element (struct ready_list *ready, int index)
3000 gcc_assert (ready->n_ready && index < ready->n_ready);
3002 return ready->vec[ready->first - index];
3005 /* Remove the element INDEX from the ready list and return it. INDEX
3006 for insn with the highest priority is 0, and the lowest priority
3007 has N_READY - 1. */
3009 HAIFA_INLINE static rtx_insn *
3010 ready_remove (struct ready_list *ready, int index)
3012 rtx_insn *t;
3013 int i;
3015 if (index == 0)
3016 return ready_remove_first (ready);
3017 gcc_assert (ready->n_ready && index < ready->n_ready);
3018 t = ready->vec[ready->first - index];
3019 ready->n_ready--;
3020 if (DEBUG_INSN_P (t))
3021 ready->n_debug--;
3022 for (i = index; i < ready->n_ready; i++)
3023 ready->vec[ready->first - i] = ready->vec[ready->first - i - 1];
3024 QUEUE_INDEX (t) = QUEUE_NOWHERE;
3025 return t;
3028 /* Remove INSN from the ready list. */
3029 static void
3030 ready_remove_insn (rtx_insn *insn)
3032 int i;
3034 for (i = 0; i < readyp->n_ready; i++)
3035 if (ready_element (readyp, i) == insn)
3037 ready_remove (readyp, i);
3038 return;
3040 gcc_unreachable ();
3043 /* Calculate difference of two statistics set WAS and NOW.
3044 Result returned in WAS. */
3045 static void
3046 rank_for_schedule_stats_diff (rank_for_schedule_stats_t *was,
3047 const rank_for_schedule_stats_t *now)
3049 for (int i = 0; i < RFS_N; ++i)
3050 was->stats[i] = now->stats[i] - was->stats[i];
3053 /* Print rank_for_schedule statistics. */
3054 static void
3055 print_rank_for_schedule_stats (const char *prefix,
3056 const rank_for_schedule_stats_t *stats,
3057 struct ready_list *ready)
3059 for (int i = 0; i < RFS_N; ++i)
3060 if (stats->stats[i])
3062 fprintf (sched_dump, "%s%20s: %u", prefix, rfs_str[i], stats->stats[i]);
3064 if (ready != NULL)
3065 /* Print out insns that won due to RFS_<I>. */
3067 rtx_insn **p = ready_lastpos (ready);
3069 fprintf (sched_dump, ":");
3070 /* Start with 1 since least-priority insn didn't have any wins. */
3071 for (int j = 1; j < ready->n_ready; ++j)
3072 if (INSN_LAST_RFS_WIN (p[j]) == i)
3073 fprintf (sched_dump, " %s",
3074 (*current_sched_info->print_insn) (p[j], 0));
3076 fprintf (sched_dump, "\n");
3080 /* Separate DEBUG_INSNS from normal insns. DEBUG_INSNs go to the end
3081 of array. */
3082 static void
3083 ready_sort_debug (struct ready_list *ready)
3085 int i;
3086 rtx_insn **first = ready_lastpos (ready);
3088 for (i = 0; i < ready->n_ready; ++i)
3089 if (!DEBUG_INSN_P (first[i]))
3090 INSN_RFS_DEBUG_ORIG_ORDER (first[i]) = i;
3092 qsort (first, ready->n_ready, sizeof (rtx), rank_for_schedule_debug);
3095 /* Sort non-debug insns in the ready list READY by ascending priority.
3096 Assumes that all debug insns are separated from the real insns. */
3097 static void
3098 ready_sort_real (struct ready_list *ready)
3100 int i;
3101 rtx_insn **first = ready_lastpos (ready);
3102 int n_ready_real = ready->n_ready - ready->n_debug;
3104 if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
3105 for (i = 0; i < n_ready_real; ++i)
3106 setup_insn_reg_pressure_info (first[i]);
3107 else if (sched_pressure == SCHED_PRESSURE_MODEL
3108 && model_curr_point < model_num_insns)
3109 model_set_excess_costs (first, n_ready_real);
3111 rank_for_schedule_stats_t stats1;
3112 if (sched_verbose >= 4)
3113 stats1 = rank_for_schedule_stats;
3115 if (n_ready_real == 2)
3116 swap_sort (first, n_ready_real);
3117 else if (n_ready_real > 2)
3118 qsort (first, n_ready_real, sizeof (rtx), rank_for_schedule);
3120 if (sched_verbose >= 4)
3122 rank_for_schedule_stats_diff (&stats1, &rank_for_schedule_stats);
3123 print_rank_for_schedule_stats (";;\t\t", &stats1, ready);
3127 /* Sort the ready list READY by ascending priority. */
3128 static void
3129 ready_sort (struct ready_list *ready)
3131 if (ready->n_debug > 0)
3132 ready_sort_debug (ready);
3133 else
3134 ready_sort_real (ready);
3137 /* PREV is an insn that is ready to execute. Adjust its priority if that
3138 will help shorten or lengthen register lifetimes as appropriate. Also
3139 provide a hook for the target to tweak itself. */
3141 HAIFA_INLINE static void
3142 adjust_priority (rtx_insn *prev)
3144 /* ??? There used to be code here to try and estimate how an insn
3145 affected register lifetimes, but it did it by looking at REG_DEAD
3146 notes, which we removed in schedule_region. Nor did it try to
3147 take into account register pressure or anything useful like that.
3149 Revisit when we have a machine model to work with and not before. */
3151 if (targetm.sched.adjust_priority)
3152 INSN_PRIORITY (prev) =
3153 targetm.sched.adjust_priority (prev, INSN_PRIORITY (prev));
3156 /* Advance DFA state STATE on one cycle. */
3157 void
3158 advance_state (state_t state)
3160 if (targetm.sched.dfa_pre_advance_cycle)
3161 targetm.sched.dfa_pre_advance_cycle ();
3163 if (targetm.sched.dfa_pre_cycle_insn)
3164 state_transition (state,
3165 targetm.sched.dfa_pre_cycle_insn ());
3167 state_transition (state, NULL);
3169 if (targetm.sched.dfa_post_cycle_insn)
3170 state_transition (state,
3171 targetm.sched.dfa_post_cycle_insn ());
3173 if (targetm.sched.dfa_post_advance_cycle)
3174 targetm.sched.dfa_post_advance_cycle ();
3177 /* Advance time on one cycle. */
3178 HAIFA_INLINE static void
3179 advance_one_cycle (void)
3181 advance_state (curr_state);
3182 if (sched_verbose >= 4)
3183 fprintf (sched_dump, ";;\tAdvance the current state.\n");
3186 /* Update register pressure after scheduling INSN. */
3187 static void
3188 update_register_pressure (rtx_insn *insn)
3190 struct reg_use_data *use;
3191 struct reg_set_data *set;
3193 gcc_checking_assert (!DEBUG_INSN_P (insn));
3195 for (use = INSN_REG_USE_LIST (insn); use != NULL; use = use->next_insn_use)
3196 if (dying_use_p (use))
3197 mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure,
3198 use->regno, false);
3199 for (set = INSN_REG_SET_LIST (insn); set != NULL; set = set->next_insn_set)
3200 mark_regno_birth_or_death (curr_reg_live, curr_reg_pressure,
3201 set->regno, true);
3204 /* Set up or update (if UPDATE_P) max register pressure (see its
3205 meaning in sched-int.h::_haifa_insn_data) for all current BB insns
3206 after insn AFTER. */
3207 static void
3208 setup_insn_max_reg_pressure (rtx_insn *after, bool update_p)
3210 int i, p;
3211 bool eq_p;
3212 rtx_insn *insn;
3213 static int max_reg_pressure[N_REG_CLASSES];
3215 save_reg_pressure ();
3216 for (i = 0; i < ira_pressure_classes_num; i++)
3217 max_reg_pressure[ira_pressure_classes[i]]
3218 = curr_reg_pressure[ira_pressure_classes[i]];
3219 for (insn = NEXT_INSN (after);
3220 insn != NULL_RTX && ! BARRIER_P (insn)
3221 && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (after);
3222 insn = NEXT_INSN (insn))
3223 if (NONDEBUG_INSN_P (insn))
3225 eq_p = true;
3226 for (i = 0; i < ira_pressure_classes_num; i++)
3228 p = max_reg_pressure[ira_pressure_classes[i]];
3229 if (INSN_MAX_REG_PRESSURE (insn)[i] != p)
3231 eq_p = false;
3232 INSN_MAX_REG_PRESSURE (insn)[i]
3233 = max_reg_pressure[ira_pressure_classes[i]];
3236 if (update_p && eq_p)
3237 break;
3238 update_register_pressure (insn);
3239 for (i = 0; i < ira_pressure_classes_num; i++)
3240 if (max_reg_pressure[ira_pressure_classes[i]]
3241 < curr_reg_pressure[ira_pressure_classes[i]])
3242 max_reg_pressure[ira_pressure_classes[i]]
3243 = curr_reg_pressure[ira_pressure_classes[i]];
3245 restore_reg_pressure ();
3248 /* Update the current register pressure after scheduling INSN. Update
3249 also max register pressure for unscheduled insns of the current
3250 BB. */
3251 static void
3252 update_reg_and_insn_max_reg_pressure (rtx_insn *insn)
3254 int i;
3255 int before[N_REG_CLASSES];
3257 for (i = 0; i < ira_pressure_classes_num; i++)
3258 before[i] = curr_reg_pressure[ira_pressure_classes[i]];
3259 update_register_pressure (insn);
3260 for (i = 0; i < ira_pressure_classes_num; i++)
3261 if (curr_reg_pressure[ira_pressure_classes[i]] != before[i])
3262 break;
3263 if (i < ira_pressure_classes_num)
3264 setup_insn_max_reg_pressure (insn, true);
3267 /* Set up register pressure at the beginning of basic block BB whose
3268 insns starting after insn AFTER. Set up also max register pressure
3269 for all insns of the basic block. */
3270 void
3271 sched_setup_bb_reg_pressure_info (basic_block bb, rtx_insn *after)
3273 gcc_assert (sched_pressure == SCHED_PRESSURE_WEIGHTED);
3274 initiate_bb_reg_pressure_info (bb);
3275 setup_insn_max_reg_pressure (after, false);
3278 /* If doing predication while scheduling, verify whether INSN, which
3279 has just been scheduled, clobbers the conditions of any
3280 instructions that must be predicated in order to break their
3281 dependencies. If so, remove them from the queues so that they will
3282 only be scheduled once their control dependency is resolved. */
3284 static void
3285 check_clobbered_conditions (rtx_insn *insn)
3287 HARD_REG_SET t;
3288 int i;
3290 if ((current_sched_info->flags & DO_PREDICATION) == 0)
3291 return;
3293 find_all_hard_reg_sets (insn, &t, true);
3295 restart:
3296 for (i = 0; i < ready.n_ready; i++)
3298 rtx_insn *x = ready_element (&ready, i);
3299 if (TODO_SPEC (x) == DEP_CONTROL && cond_clobbered_p (x, t))
3301 ready_remove_insn (x);
3302 goto restart;
3305 for (i = 0; i <= max_insn_queue_index; i++)
3307 rtx_insn_list *link;
3308 int q = NEXT_Q_AFTER (q_ptr, i);
3310 restart_queue:
3311 for (link = insn_queue[q]; link; link = link->next ())
3313 rtx_insn *x = link->insn ();
3314 if (TODO_SPEC (x) == DEP_CONTROL && cond_clobbered_p (x, t))
3316 queue_remove (x);
3317 goto restart_queue;
3323 /* Return (in order):
3325 - positive if INSN adversely affects the pressure on one
3326 register class
3328 - negative if INSN reduces the pressure on one register class
3330 - 0 if INSN doesn't affect the pressure on any register class. */
3332 static int
3333 model_classify_pressure (struct model_insn_info *insn)
3335 struct reg_pressure_data *reg_pressure;
3336 int death[N_REG_CLASSES];
3337 int pci, cl, sum;
3339 calculate_reg_deaths (insn->insn, death);
3340 reg_pressure = INSN_REG_PRESSURE (insn->insn);
3341 sum = 0;
3342 for (pci = 0; pci < ira_pressure_classes_num; pci++)
3344 cl = ira_pressure_classes[pci];
3345 if (death[cl] < reg_pressure[pci].set_increase)
3346 return 1;
3347 sum += reg_pressure[pci].set_increase - death[cl];
3349 return sum;
3352 /* Return true if INSN1 should come before INSN2 in the model schedule. */
3354 static int
3355 model_order_p (struct model_insn_info *insn1, struct model_insn_info *insn2)
3357 unsigned int height1, height2;
3358 unsigned int priority1, priority2;
3360 /* Prefer instructions with a higher model priority. */
3361 if (insn1->model_priority != insn2->model_priority)
3362 return insn1->model_priority > insn2->model_priority;
3364 /* Combine the length of the longest path of satisfied true dependencies
3365 that leads to each instruction (depth) with the length of the longest
3366 path of any dependencies that leads from the instruction (alap).
3367 Prefer instructions with the greatest combined length. If the combined
3368 lengths are equal, prefer instructions with the greatest depth.
3370 The idea is that, if we have a set S of "equal" instructions that each
3371 have ALAP value X, and we pick one such instruction I, any true-dependent
3372 successors of I that have ALAP value X - 1 should be preferred over S.
3373 This encourages the schedule to be "narrow" rather than "wide".
3374 However, if I is a low-priority instruction that we decided to
3375 schedule because of its model_classify_pressure, and if there
3376 is a set of higher-priority instructions T, the aforementioned
3377 successors of I should not have the edge over T. */
3378 height1 = insn1->depth + insn1->alap;
3379 height2 = insn2->depth + insn2->alap;
3380 if (height1 != height2)
3381 return height1 > height2;
3382 if (insn1->depth != insn2->depth)
3383 return insn1->depth > insn2->depth;
3385 /* We have no real preference between INSN1 an INSN2 as far as attempts
3386 to reduce pressure go. Prefer instructions with higher priorities. */
3387 priority1 = INSN_PRIORITY (insn1->insn);
3388 priority2 = INSN_PRIORITY (insn2->insn);
3389 if (priority1 != priority2)
3390 return priority1 > priority2;
3392 /* Use the original rtl sequence as a tie-breaker. */
3393 return insn1 < insn2;
3396 /* Add INSN to the model worklist immediately after PREV. Add it to the
3397 beginning of the list if PREV is null. */
3399 static void
3400 model_add_to_worklist_at (struct model_insn_info *insn,
3401 struct model_insn_info *prev)
3403 gcc_assert (QUEUE_INDEX (insn->insn) == QUEUE_NOWHERE);
3404 QUEUE_INDEX (insn->insn) = QUEUE_READY;
3406 insn->prev = prev;
3407 if (prev)
3409 insn->next = prev->next;
3410 prev->next = insn;
3412 else
3414 insn->next = model_worklist;
3415 model_worklist = insn;
3417 if (insn->next)
3418 insn->next->prev = insn;
3421 /* Remove INSN from the model worklist. */
3423 static void
3424 model_remove_from_worklist (struct model_insn_info *insn)
3426 gcc_assert (QUEUE_INDEX (insn->insn) == QUEUE_READY);
3427 QUEUE_INDEX (insn->insn) = QUEUE_NOWHERE;
3429 if (insn->prev)
3430 insn->prev->next = insn->next;
3431 else
3432 model_worklist = insn->next;
3433 if (insn->next)
3434 insn->next->prev = insn->prev;
3437 /* Add INSN to the model worklist. Start looking for a suitable position
3438 between neighbors PREV and NEXT, testing at most MAX_SCHED_READY_INSNS
3439 insns either side. A null PREV indicates the beginning of the list and
3440 a null NEXT indicates the end. */
3442 static void
3443 model_add_to_worklist (struct model_insn_info *insn,
3444 struct model_insn_info *prev,
3445 struct model_insn_info *next)
3447 int count;
3449 count = MAX_SCHED_READY_INSNS;
3450 if (count > 0 && prev && model_order_p (insn, prev))
3453 count--;
3454 prev = prev->prev;
3456 while (count > 0 && prev && model_order_p (insn, prev));
3457 else
3458 while (count > 0 && next && model_order_p (next, insn))
3460 count--;
3461 prev = next;
3462 next = next->next;
3464 model_add_to_worklist_at (insn, prev);
3467 /* INSN may now have a higher priority (in the model_order_p sense)
3468 than before. Move it up the worklist if necessary. */
3470 static void
3471 model_promote_insn (struct model_insn_info *insn)
3473 struct model_insn_info *prev;
3474 int count;
3476 prev = insn->prev;
3477 count = MAX_SCHED_READY_INSNS;
3478 while (count > 0 && prev && model_order_p (insn, prev))
3480 count--;
3481 prev = prev->prev;
3483 if (prev != insn->prev)
3485 model_remove_from_worklist (insn);
3486 model_add_to_worklist_at (insn, prev);
3490 /* Add INSN to the end of the model schedule. */
3492 static void
3493 model_add_to_schedule (rtx_insn *insn)
3495 unsigned int point;
3497 gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
3498 QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
3500 point = model_schedule.length ();
3501 model_schedule.quick_push (insn);
3502 INSN_MODEL_INDEX (insn) = point + 1;
3505 /* Analyze the instructions that are to be scheduled, setting up
3506 MODEL_INSN_INFO (...) and model_num_insns accordingly. Add ready
3507 instructions to model_worklist. */
3509 static void
3510 model_analyze_insns (void)
3512 rtx_insn *start, *end, *iter;
3513 sd_iterator_def sd_it;
3514 dep_t dep;
3515 struct model_insn_info *insn, *con;
3517 model_num_insns = 0;
3518 start = PREV_INSN (current_sched_info->next_tail);
3519 end = current_sched_info->prev_head;
3520 for (iter = start; iter != end; iter = PREV_INSN (iter))
3521 if (NONDEBUG_INSN_P (iter))
3523 insn = MODEL_INSN_INFO (iter);
3524 insn->insn = iter;
3525 FOR_EACH_DEP (iter, SD_LIST_FORW, sd_it, dep)
3527 con = MODEL_INSN_INFO (DEP_CON (dep));
3528 if (con->insn && insn->alap < con->alap + 1)
3529 insn->alap = con->alap + 1;
3532 insn->old_queue = QUEUE_INDEX (iter);
3533 QUEUE_INDEX (iter) = QUEUE_NOWHERE;
3535 insn->unscheduled_preds = dep_list_size (iter, SD_LIST_HARD_BACK);
3536 if (insn->unscheduled_preds == 0)
3537 model_add_to_worklist (insn, NULL, model_worklist);
3539 model_num_insns++;
3543 /* The global state describes the register pressure at the start of the
3544 model schedule. Initialize GROUP accordingly. */
3546 static void
3547 model_init_pressure_group (struct model_pressure_group *group)
3549 int pci, cl;
3551 for (pci = 0; pci < ira_pressure_classes_num; pci++)
3553 cl = ira_pressure_classes[pci];
3554 group->limits[pci].pressure = curr_reg_pressure[cl];
3555 group->limits[pci].point = 0;
3557 /* Use index model_num_insns to record the state after the last
3558 instruction in the model schedule. */
3559 group->model = XNEWVEC (struct model_pressure_data,
3560 (model_num_insns + 1) * ira_pressure_classes_num);
3563 /* Record that MODEL_REF_PRESSURE (GROUP, POINT, PCI) is PRESSURE.
3564 Update the maximum pressure for the whole schedule. */
3566 static void
3567 model_record_pressure (struct model_pressure_group *group,
3568 int point, int pci, int pressure)
3570 MODEL_REF_PRESSURE (group, point, pci) = pressure;
3571 if (group->limits[pci].pressure < pressure)
3573 group->limits[pci].pressure = pressure;
3574 group->limits[pci].point = point;
3578 /* INSN has just been added to the end of the model schedule. Record its
3579 register-pressure information. */
3581 static void
3582 model_record_pressures (struct model_insn_info *insn)
3584 struct reg_pressure_data *reg_pressure;
3585 int point, pci, cl, delta;
3586 int death[N_REG_CLASSES];
3588 point = model_index (insn->insn);
3589 if (sched_verbose >= 2)
3591 if (point == 0)
3593 fprintf (sched_dump, "\n;;\tModel schedule:\n;;\n");
3594 fprintf (sched_dump, ";;\t| idx insn | mpri hght dpth prio |\n");
3596 fprintf (sched_dump, ";;\t| %3d %4d | %4d %4d %4d %4d | %-30s ",
3597 point, INSN_UID (insn->insn), insn->model_priority,
3598 insn->depth + insn->alap, insn->depth,
3599 INSN_PRIORITY (insn->insn),
3600 str_pattern_slim (PATTERN (insn->insn)));
3602 calculate_reg_deaths (insn->insn, death);
3603 reg_pressure = INSN_REG_PRESSURE (insn->insn);
3604 for (pci = 0; pci < ira_pressure_classes_num; pci++)
3606 cl = ira_pressure_classes[pci];
3607 delta = reg_pressure[pci].set_increase - death[cl];
3608 if (sched_verbose >= 2)
3609 fprintf (sched_dump, " %s:[%d,%+d]", reg_class_names[cl],
3610 curr_reg_pressure[cl], delta);
3611 model_record_pressure (&model_before_pressure, point, pci,
3612 curr_reg_pressure[cl]);
3614 if (sched_verbose >= 2)
3615 fprintf (sched_dump, "\n");
3618 /* All instructions have been added to the model schedule. Record the
3619 final register pressure in GROUP and set up all MODEL_MAX_PRESSUREs. */
3621 static void
3622 model_record_final_pressures (struct model_pressure_group *group)
3624 int point, pci, max_pressure, ref_pressure, cl;
3626 for (pci = 0; pci < ira_pressure_classes_num; pci++)
3628 /* Record the final pressure for this class. */
3629 cl = ira_pressure_classes[pci];
3630 point = model_num_insns;
3631 ref_pressure = curr_reg_pressure[cl];
3632 model_record_pressure (group, point, pci, ref_pressure);
3634 /* Record the original maximum pressure. */
3635 group->limits[pci].orig_pressure = group->limits[pci].pressure;
3637 /* Update the MODEL_MAX_PRESSURE for every point of the schedule. */
3638 max_pressure = ref_pressure;
3639 MODEL_MAX_PRESSURE (group, point, pci) = max_pressure;
3640 while (point > 0)
3642 point--;
3643 ref_pressure = MODEL_REF_PRESSURE (group, point, pci);
3644 max_pressure = MAX (max_pressure, ref_pressure);
3645 MODEL_MAX_PRESSURE (group, point, pci) = max_pressure;
3650 /* Update all successors of INSN, given that INSN has just been scheduled. */
3652 static void
3653 model_add_successors_to_worklist (struct model_insn_info *insn)
3655 sd_iterator_def sd_it;
3656 struct model_insn_info *con;
3657 dep_t dep;
3659 FOR_EACH_DEP (insn->insn, SD_LIST_FORW, sd_it, dep)
3661 con = MODEL_INSN_INFO (DEP_CON (dep));
3662 /* Ignore debug instructions, and instructions from other blocks. */
3663 if (con->insn)
3665 con->unscheduled_preds--;
3667 /* Update the depth field of each true-dependent successor.
3668 Increasing the depth gives them a higher priority than
3669 before. */
3670 if (DEP_TYPE (dep) == REG_DEP_TRUE && con->depth < insn->depth + 1)
3672 con->depth = insn->depth + 1;
3673 if (QUEUE_INDEX (con->insn) == QUEUE_READY)
3674 model_promote_insn (con);
3677 /* If this is a true dependency, or if there are no remaining
3678 dependencies for CON (meaning that CON only had non-true
3679 dependencies), make sure that CON is on the worklist.
3680 We don't bother otherwise because it would tend to fill the
3681 worklist with a lot of low-priority instructions that are not
3682 yet ready to issue. */
3683 if ((con->depth > 0 || con->unscheduled_preds == 0)
3684 && QUEUE_INDEX (con->insn) == QUEUE_NOWHERE)
3685 model_add_to_worklist (con, insn, insn->next);
3690 /* Give INSN a higher priority than any current instruction, then give
3691 unscheduled predecessors of INSN a higher priority still. If any of
3692 those predecessors are not on the model worklist, do the same for its
3693 predecessors, and so on. */
3695 static void
3696 model_promote_predecessors (struct model_insn_info *insn)
3698 struct model_insn_info *pro, *first;
3699 sd_iterator_def sd_it;
3700 dep_t dep;
3702 if (sched_verbose >= 7)
3703 fprintf (sched_dump, ";;\t+--- priority of %d = %d, priority of",
3704 INSN_UID (insn->insn), model_next_priority);
3705 insn->model_priority = model_next_priority++;
3706 model_remove_from_worklist (insn);
3707 model_add_to_worklist_at (insn, NULL);
3709 first = NULL;
3710 for (;;)
3712 FOR_EACH_DEP (insn->insn, SD_LIST_HARD_BACK, sd_it, dep)
3714 pro = MODEL_INSN_INFO (DEP_PRO (dep));
3715 /* The first test is to ignore debug instructions, and instructions
3716 from other blocks. */
3717 if (pro->insn
3718 && pro->model_priority != model_next_priority
3719 && QUEUE_INDEX (pro->insn) != QUEUE_SCHEDULED)
3721 pro->model_priority = model_next_priority;
3722 if (sched_verbose >= 7)
3723 fprintf (sched_dump, " %d", INSN_UID (pro->insn));
3724 if (QUEUE_INDEX (pro->insn) == QUEUE_READY)
3726 /* PRO is already in the worklist, but it now has
3727 a higher priority than before. Move it at the
3728 appropriate place. */
3729 model_remove_from_worklist (pro);
3730 model_add_to_worklist (pro, NULL, model_worklist);
3732 else
3734 /* PRO isn't in the worklist. Recursively process
3735 its predecessors until we find one that is. */
3736 pro->next = first;
3737 first = pro;
3741 if (!first)
3742 break;
3743 insn = first;
3744 first = insn->next;
3746 if (sched_verbose >= 7)
3747 fprintf (sched_dump, " = %d\n", model_next_priority);
3748 model_next_priority++;
3751 /* Pick one instruction from model_worklist and process it. */
3753 static void
3754 model_choose_insn (void)
3756 struct model_insn_info *insn, *fallback;
3757 int count;
3759 if (sched_verbose >= 7)
3761 fprintf (sched_dump, ";;\t+--- worklist:\n");
3762 insn = model_worklist;
3763 count = MAX_SCHED_READY_INSNS;
3764 while (count > 0 && insn)
3766 fprintf (sched_dump, ";;\t+--- %d [%d, %d, %d, %d]\n",
3767 INSN_UID (insn->insn), insn->model_priority,
3768 insn->depth + insn->alap, insn->depth,
3769 INSN_PRIORITY (insn->insn));
3770 count--;
3771 insn = insn->next;
3775 /* Look for a ready instruction whose model_classify_priority is zero
3776 or negative, picking the highest-priority one. Adding such an
3777 instruction to the schedule now should do no harm, and may actually
3778 do some good.
3780 Failing that, see whether there is an instruction with the highest
3781 extant model_priority that is not yet ready, but which would reduce
3782 pressure if it became ready. This is designed to catch cases like:
3784 (set (mem (reg R1)) (reg R2))
3786 where the instruction is the last remaining use of R1 and where the
3787 value of R2 is not yet available (or vice versa). The death of R1
3788 means that this instruction already reduces pressure. It is of
3789 course possible that the computation of R2 involves other registers
3790 that are hard to kill, but such cases are rare enough for this
3791 heuristic to be a win in general.
3793 Failing that, just pick the highest-priority instruction in the
3794 worklist. */
3795 count = MAX_SCHED_READY_INSNS;
3796 insn = model_worklist;
3797 fallback = 0;
3798 for (;;)
3800 if (count == 0 || !insn)
3802 insn = fallback ? fallback : model_worklist;
3803 break;
3805 if (insn->unscheduled_preds)
3807 if (model_worklist->model_priority == insn->model_priority
3808 && !fallback
3809 && model_classify_pressure (insn) < 0)
3810 fallback = insn;
3812 else
3814 if (model_classify_pressure (insn) <= 0)
3815 break;
3817 count--;
3818 insn = insn->next;
3821 if (sched_verbose >= 7 && insn != model_worklist)
3823 if (insn->unscheduled_preds)
3824 fprintf (sched_dump, ";;\t+--- promoting insn %d, with dependencies\n",
3825 INSN_UID (insn->insn));
3826 else
3827 fprintf (sched_dump, ";;\t+--- promoting insn %d, which is ready\n",
3828 INSN_UID (insn->insn));
3830 if (insn->unscheduled_preds)
3831 /* INSN isn't yet ready to issue. Give all its predecessors the
3832 highest priority. */
3833 model_promote_predecessors (insn);
3834 else
3836 /* INSN is ready. Add it to the end of model_schedule and
3837 process its successors. */
3838 model_add_successors_to_worklist (insn);
3839 model_remove_from_worklist (insn);
3840 model_add_to_schedule (insn->insn);
3841 model_record_pressures (insn);
3842 update_register_pressure (insn->insn);
3846 /* Restore all QUEUE_INDEXs to the values that they had before
3847 model_start_schedule was called. */
3849 static void
3850 model_reset_queue_indices (void)
3852 unsigned int i;
3853 rtx_insn *insn;
3855 FOR_EACH_VEC_ELT (model_schedule, i, insn)
3856 QUEUE_INDEX (insn) = MODEL_INSN_INFO (insn)->old_queue;
3859 /* We have calculated the model schedule and spill costs. Print a summary
3860 to sched_dump. */
3862 static void
3863 model_dump_pressure_summary (void)
3865 int pci, cl;
3867 fprintf (sched_dump, ";; Pressure summary:");
3868 for (pci = 0; pci < ira_pressure_classes_num; pci++)
3870 cl = ira_pressure_classes[pci];
3871 fprintf (sched_dump, " %s:%d", reg_class_names[cl],
3872 model_before_pressure.limits[pci].pressure);
3874 fprintf (sched_dump, "\n\n");
3877 /* Initialize the SCHED_PRESSURE_MODEL information for the current
3878 scheduling region. */
3880 static void
3881 model_start_schedule (basic_block bb)
3883 model_next_priority = 1;
3884 model_schedule.create (sched_max_luid);
3885 model_insns = XCNEWVEC (struct model_insn_info, sched_max_luid);
3887 gcc_assert (bb == BLOCK_FOR_INSN (NEXT_INSN (current_sched_info->prev_head)));
3888 initiate_reg_pressure_info (df_get_live_in (bb));
3890 model_analyze_insns ();
3891 model_init_pressure_group (&model_before_pressure);
3892 while (model_worklist)
3893 model_choose_insn ();
3894 gcc_assert (model_num_insns == (int) model_schedule.length ());
3895 if (sched_verbose >= 2)
3896 fprintf (sched_dump, "\n");
3898 model_record_final_pressures (&model_before_pressure);
3899 model_reset_queue_indices ();
3901 XDELETEVEC (model_insns);
3903 model_curr_point = 0;
3904 initiate_reg_pressure_info (df_get_live_in (bb));
3905 if (sched_verbose >= 1)
3906 model_dump_pressure_summary ();
3909 /* Free the information associated with GROUP. */
3911 static void
3912 model_finalize_pressure_group (struct model_pressure_group *group)
3914 XDELETEVEC (group->model);
3917 /* Free the information created by model_start_schedule. */
3919 static void
3920 model_end_schedule (void)
3922 model_finalize_pressure_group (&model_before_pressure);
3923 model_schedule.release ();
3926 /* Prepare reg pressure scheduling for basic block BB. */
3927 static void
3928 sched_pressure_start_bb (basic_block bb)
3930 /* Set the number of available registers for each class taking into account
3931 relative probability of current basic block versus function prologue and
3932 epilogue.
3933 * If the basic block executes much more often than the prologue/epilogue
3934 (e.g., inside a hot loop), then cost of spill in the prologue is close to
3935 nil, so the effective number of available registers is
3936 (ira_class_hard_regs_num[cl] - 0).
3937 * If the basic block executes as often as the prologue/epilogue,
3938 then spill in the block is as costly as in the prologue, so the effective
3939 number of available registers is
3940 (ira_class_hard_regs_num[cl] - call_used_regs_num[cl]).
3941 Note that all-else-equal, we prefer to spill in the prologue, since that
3942 allows "extra" registers for other basic blocks of the function.
3943 * If the basic block is on the cold path of the function and executes
3944 rarely, then we should always prefer to spill in the block, rather than
3945 in the prologue/epilogue. The effective number of available register is
3946 (ira_class_hard_regs_num[cl] - call_used_regs_num[cl]). */
3948 int i;
3949 int entry_freq = ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency;
3950 int bb_freq = bb->frequency;
3952 if (bb_freq == 0)
3954 if (entry_freq == 0)
3955 entry_freq = bb_freq = 1;
3957 if (bb_freq < entry_freq)
3958 bb_freq = entry_freq;
3960 for (i = 0; i < ira_pressure_classes_num; ++i)
3962 enum reg_class cl = ira_pressure_classes[i];
3963 sched_class_regs_num[cl] = ira_class_hard_regs_num[cl];
3964 sched_class_regs_num[cl]
3965 -= (call_used_regs_num[cl] * entry_freq) / bb_freq;
3969 if (sched_pressure == SCHED_PRESSURE_MODEL)
3970 model_start_schedule (bb);
3973 /* A structure that holds local state for the loop in schedule_block. */
3974 struct sched_block_state
3976 /* True if no real insns have been scheduled in the current cycle. */
3977 bool first_cycle_insn_p;
3978 /* True if a shadow insn has been scheduled in the current cycle, which
3979 means that no more normal insns can be issued. */
3980 bool shadows_only_p;
3981 /* True if we're winding down a modulo schedule, which means that we only
3982 issue insns with INSN_EXACT_TICK set. */
3983 bool modulo_epilogue;
3984 /* Initialized with the machine's issue rate every cycle, and updated
3985 by calls to the variable_issue hook. */
3986 int can_issue_more;
3989 /* INSN is the "currently executing insn". Launch each insn which was
3990 waiting on INSN. READY is the ready list which contains the insns
3991 that are ready to fire. CLOCK is the current cycle. The function
3992 returns necessary cycle advance after issuing the insn (it is not
3993 zero for insns in a schedule group). */
3995 static int
3996 schedule_insn (rtx_insn *insn)
3998 sd_iterator_def sd_it;
3999 dep_t dep;
4000 int i;
4001 int advance = 0;
4003 if (sched_verbose >= 1)
4005 struct reg_pressure_data *pressure_info;
4006 fprintf (sched_dump, ";;\t%3i--> %s %-40s:",
4007 clock_var, (*current_sched_info->print_insn) (insn, 1),
4008 str_pattern_slim (PATTERN (insn)));
4010 if (recog_memoized (insn) < 0)
4011 fprintf (sched_dump, "nothing");
4012 else
4013 print_reservation (sched_dump, insn);
4014 pressure_info = INSN_REG_PRESSURE (insn);
4015 if (pressure_info != NULL)
4017 fputc (':', sched_dump);
4018 for (i = 0; i < ira_pressure_classes_num; i++)
4019 fprintf (sched_dump, "%s%s%+d(%d)",
4020 scheduled_insns.length () > 1
4021 && INSN_LUID (insn)
4022 < INSN_LUID (scheduled_insns[scheduled_insns.length () - 2]) ? "@" : "",
4023 reg_class_names[ira_pressure_classes[i]],
4024 pressure_info[i].set_increase, pressure_info[i].change);
4026 if (sched_pressure == SCHED_PRESSURE_MODEL
4027 && model_curr_point < model_num_insns
4028 && model_index (insn) == model_curr_point)
4029 fprintf (sched_dump, ":model %d", model_curr_point);
4030 fputc ('\n', sched_dump);
4033 if (sched_pressure == SCHED_PRESSURE_WEIGHTED && !DEBUG_INSN_P (insn))
4034 update_reg_and_insn_max_reg_pressure (insn);
4036 /* Scheduling instruction should have all its dependencies resolved and
4037 should have been removed from the ready list. */
4038 gcc_assert (sd_lists_empty_p (insn, SD_LIST_HARD_BACK));
4040 /* Reset debug insns invalidated by moving this insn. */
4041 if (MAY_HAVE_DEBUG_INSNS && !DEBUG_INSN_P (insn))
4042 for (sd_it = sd_iterator_start (insn, SD_LIST_BACK);
4043 sd_iterator_cond (&sd_it, &dep);)
4045 rtx_insn *dbg = DEP_PRO (dep);
4046 struct reg_use_data *use, *next;
4048 if (DEP_STATUS (dep) & DEP_CANCELLED)
4050 sd_iterator_next (&sd_it);
4051 continue;
4054 gcc_assert (DEBUG_INSN_P (dbg));
4056 if (sched_verbose >= 6)
4057 fprintf (sched_dump, ";;\t\tresetting: debug insn %d\n",
4058 INSN_UID (dbg));
4060 /* ??? Rather than resetting the debug insn, we might be able
4061 to emit a debug temp before the just-scheduled insn, but
4062 this would involve checking that the expression at the
4063 point of the debug insn is equivalent to the expression
4064 before the just-scheduled insn. They might not be: the
4065 expression in the debug insn may depend on other insns not
4066 yet scheduled that set MEMs, REGs or even other debug
4067 insns. It's not clear that attempting to preserve debug
4068 information in these cases is worth the effort, given how
4069 uncommon these resets are and the likelihood that the debug
4070 temps introduced won't survive the schedule change. */
4071 INSN_VAR_LOCATION_LOC (dbg) = gen_rtx_UNKNOWN_VAR_LOC ();
4072 df_insn_rescan (dbg);
4074 /* Unknown location doesn't use any registers. */
4075 for (use = INSN_REG_USE_LIST (dbg); use != NULL; use = next)
4077 struct reg_use_data *prev = use;
4079 /* Remove use from the cyclic next_regno_use chain first. */
4080 while (prev->next_regno_use != use)
4081 prev = prev->next_regno_use;
4082 prev->next_regno_use = use->next_regno_use;
4083 next = use->next_insn_use;
4084 free (use);
4086 INSN_REG_USE_LIST (dbg) = NULL;
4088 /* We delete rather than resolve these deps, otherwise we
4089 crash in sched_free_deps(), because forward deps are
4090 expected to be released before backward deps. */
4091 sd_delete_dep (sd_it);
4094 gcc_assert (QUEUE_INDEX (insn) == QUEUE_NOWHERE);
4095 QUEUE_INDEX (insn) = QUEUE_SCHEDULED;
4097 if (sched_pressure == SCHED_PRESSURE_MODEL
4098 && model_curr_point < model_num_insns
4099 && NONDEBUG_INSN_P (insn))
4101 if (model_index (insn) == model_curr_point)
4103 model_curr_point++;
4104 while (model_curr_point < model_num_insns
4105 && (QUEUE_INDEX (MODEL_INSN (model_curr_point))
4106 == QUEUE_SCHEDULED));
4107 else
4108 model_recompute (insn);
4109 model_update_limit_points ();
4110 update_register_pressure (insn);
4111 if (sched_verbose >= 2)
4112 print_curr_reg_pressure ();
4115 gcc_assert (INSN_TICK (insn) >= MIN_TICK);
4116 if (INSN_TICK (insn) > clock_var)
4117 /* INSN has been prematurely moved from the queue to the ready list.
4118 This is possible only if following flags are set. */
4119 gcc_assert (flag_sched_stalled_insns || sched_fusion);
4121 /* ??? Probably, if INSN is scheduled prematurely, we should leave
4122 INSN_TICK untouched. This is a machine-dependent issue, actually. */
4123 INSN_TICK (insn) = clock_var;
4125 check_clobbered_conditions (insn);
4127 /* Update dependent instructions. First, see if by scheduling this insn
4128 now we broke a dependence in a way that requires us to change another
4129 insn. */
4130 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
4131 sd_iterator_cond (&sd_it, &dep); sd_iterator_next (&sd_it))
4133 struct dep_replacement *desc = DEP_REPLACE (dep);
4134 rtx_insn *pro = DEP_PRO (dep);
4135 if (QUEUE_INDEX (pro) != QUEUE_SCHEDULED
4136 && desc != NULL && desc->insn == pro)
4137 apply_replacement (dep, false);
4140 /* Go through and resolve forward dependencies. */
4141 for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4142 sd_iterator_cond (&sd_it, &dep);)
4144 rtx_insn *next = DEP_CON (dep);
4145 bool cancelled = (DEP_STATUS (dep) & DEP_CANCELLED) != 0;
4147 /* Resolve the dependence between INSN and NEXT.
4148 sd_resolve_dep () moves current dep to another list thus
4149 advancing the iterator. */
4150 sd_resolve_dep (sd_it);
4152 if (cancelled)
4154 if (must_restore_pattern_p (next, dep))
4155 restore_pattern (dep, false);
4156 continue;
4159 /* Don't bother trying to mark next as ready if insn is a debug
4160 insn. If insn is the last hard dependency, it will have
4161 already been discounted. */
4162 if (DEBUG_INSN_P (insn) && !DEBUG_INSN_P (next))
4163 continue;
4165 if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
4167 int effective_cost;
4169 effective_cost = try_ready (next);
4171 if (effective_cost >= 0
4172 && SCHED_GROUP_P (next)
4173 && advance < effective_cost)
4174 advance = effective_cost;
4176 else
4177 /* Check always has only one forward dependence (to the first insn in
4178 the recovery block), therefore, this will be executed only once. */
4180 gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
4181 fix_recovery_deps (RECOVERY_BLOCK (insn));
4185 /* Annotate the instruction with issue information -- TImode
4186 indicates that the instruction is expected not to be able
4187 to issue on the same cycle as the previous insn. A machine
4188 may use this information to decide how the instruction should
4189 be aligned. */
4190 if (issue_rate > 1
4191 && GET_CODE (PATTERN (insn)) != USE
4192 && GET_CODE (PATTERN (insn)) != CLOBBER
4193 && !DEBUG_INSN_P (insn))
4195 if (reload_completed)
4196 PUT_MODE (insn, clock_var > last_clock_var ? TImode : VOIDmode);
4197 last_clock_var = clock_var;
4200 if (nonscheduled_insns_begin != NULL_RTX)
4201 /* Indicate to debug counters that INSN is scheduled. */
4202 nonscheduled_insns_begin = insn;
4204 return advance;
4207 /* Functions for handling of notes. */
4209 /* Add note list that ends on FROM_END to the end of TO_ENDP. */
4210 void
4211 concat_note_lists (rtx_insn *from_end, rtx_insn **to_endp)
4213 rtx_insn *from_start;
4215 /* It's easy when have nothing to concat. */
4216 if (from_end == NULL)
4217 return;
4219 /* It's also easy when destination is empty. */
4220 if (*to_endp == NULL)
4222 *to_endp = from_end;
4223 return;
4226 from_start = from_end;
4227 while (PREV_INSN (from_start) != NULL)
4228 from_start = PREV_INSN (from_start);
4230 SET_PREV_INSN (from_start) = *to_endp;
4231 SET_NEXT_INSN (*to_endp) = from_start;
4232 *to_endp = from_end;
4235 /* Delete notes between HEAD and TAIL and put them in the chain
4236 of notes ended by NOTE_LIST. */
4237 void
4238 remove_notes (rtx_insn *head, rtx_insn *tail)
4240 rtx_insn *next_tail, *insn, *next;
4242 note_list = 0;
4243 if (head == tail && !INSN_P (head))
4244 return;
4246 next_tail = NEXT_INSN (tail);
4247 for (insn = head; insn != next_tail; insn = next)
4249 next = NEXT_INSN (insn);
4250 if (!NOTE_P (insn))
4251 continue;
4253 switch (NOTE_KIND (insn))
4255 case NOTE_INSN_BASIC_BLOCK:
4256 continue;
4258 case NOTE_INSN_EPILOGUE_BEG:
4259 if (insn != tail)
4261 remove_insn (insn);
4262 add_reg_note (next, REG_SAVE_NOTE,
4263 GEN_INT (NOTE_INSN_EPILOGUE_BEG));
4264 break;
4266 /* FALLTHRU */
4268 default:
4269 remove_insn (insn);
4271 /* Add the note to list that ends at NOTE_LIST. */
4272 SET_PREV_INSN (insn) = note_list;
4273 SET_NEXT_INSN (insn) = NULL_RTX;
4274 if (note_list)
4275 SET_NEXT_INSN (note_list) = insn;
4276 note_list = insn;
4277 break;
4280 gcc_assert ((sel_sched_p () || insn != tail) && insn != head);
4284 /* A structure to record enough data to allow us to backtrack the scheduler to
4285 a previous state. */
4286 struct haifa_saved_data
4288 /* Next entry on the list. */
4289 struct haifa_saved_data *next;
4291 /* Backtracking is associated with scheduling insns that have delay slots.
4292 DELAY_PAIR points to the structure that contains the insns involved, and
4293 the number of cycles between them. */
4294 struct delay_pair *delay_pair;
4296 /* Data used by the frontend (e.g. sched-ebb or sched-rgn). */
4297 void *fe_saved_data;
4298 /* Data used by the backend. */
4299 void *be_saved_data;
4301 /* Copies of global state. */
4302 int clock_var, last_clock_var;
4303 struct ready_list ready;
4304 state_t curr_state;
4306 rtx_insn *last_scheduled_insn;
4307 rtx_insn *last_nondebug_scheduled_insn;
4308 rtx_insn *nonscheduled_insns_begin;
4309 int cycle_issued_insns;
4311 /* Copies of state used in the inner loop of schedule_block. */
4312 struct sched_block_state sched_block;
4314 /* We don't need to save q_ptr, as its value is arbitrary and we can set it
4315 to 0 when restoring. */
4316 int q_size;
4317 rtx_insn_list **insn_queue;
4319 /* Describe pattern replacements that occurred since this backtrack point
4320 was queued. */
4321 vec<dep_t> replacement_deps;
4322 vec<int> replace_apply;
4324 /* A copy of the next-cycle replacement vectors at the time of the backtrack
4325 point. */
4326 vec<dep_t> next_cycle_deps;
4327 vec<int> next_cycle_apply;
4330 /* A record, in reverse order, of all scheduled insns which have delay slots
4331 and may require backtracking. */
4332 static struct haifa_saved_data *backtrack_queue;
4334 /* For every dependency of INSN, set the FEEDS_BACKTRACK_INSN bit according
4335 to SET_P. */
4336 static void
4337 mark_backtrack_feeds (rtx_insn *insn, int set_p)
4339 sd_iterator_def sd_it;
4340 dep_t dep;
4341 FOR_EACH_DEP (insn, SD_LIST_HARD_BACK, sd_it, dep)
4343 FEEDS_BACKTRACK_INSN (DEP_PRO (dep)) = set_p;
4347 /* Save the current scheduler state so that we can backtrack to it
4348 later if necessary. PAIR gives the insns that make it necessary to
4349 save this point. SCHED_BLOCK is the local state of schedule_block
4350 that need to be saved. */
4351 static void
4352 save_backtrack_point (struct delay_pair *pair,
4353 struct sched_block_state sched_block)
4355 int i;
4356 struct haifa_saved_data *save = XNEW (struct haifa_saved_data);
4358 save->curr_state = xmalloc (dfa_state_size);
4359 memcpy (save->curr_state, curr_state, dfa_state_size);
4361 save->ready.first = ready.first;
4362 save->ready.n_ready = ready.n_ready;
4363 save->ready.n_debug = ready.n_debug;
4364 save->ready.veclen = ready.veclen;
4365 save->ready.vec = XNEWVEC (rtx_insn *, ready.veclen);
4366 memcpy (save->ready.vec, ready.vec, ready.veclen * sizeof (rtx));
4368 save->insn_queue = XNEWVEC (rtx_insn_list *, max_insn_queue_index + 1);
4369 save->q_size = q_size;
4370 for (i = 0; i <= max_insn_queue_index; i++)
4372 int q = NEXT_Q_AFTER (q_ptr, i);
4373 save->insn_queue[i] = copy_INSN_LIST (insn_queue[q]);
4376 save->clock_var = clock_var;
4377 save->last_clock_var = last_clock_var;
4378 save->cycle_issued_insns = cycle_issued_insns;
4379 save->last_scheduled_insn = last_scheduled_insn;
4380 save->last_nondebug_scheduled_insn = last_nondebug_scheduled_insn;
4381 save->nonscheduled_insns_begin = nonscheduled_insns_begin;
4383 save->sched_block = sched_block;
4385 save->replacement_deps.create (0);
4386 save->replace_apply.create (0);
4387 save->next_cycle_deps = next_cycle_replace_deps.copy ();
4388 save->next_cycle_apply = next_cycle_apply.copy ();
4390 if (current_sched_info->save_state)
4391 save->fe_saved_data = (*current_sched_info->save_state) ();
4393 if (targetm.sched.alloc_sched_context)
4395 save->be_saved_data = targetm.sched.alloc_sched_context ();
4396 targetm.sched.init_sched_context (save->be_saved_data, false);
4398 else
4399 save->be_saved_data = NULL;
4401 save->delay_pair = pair;
4403 save->next = backtrack_queue;
4404 backtrack_queue = save;
4406 while (pair)
4408 mark_backtrack_feeds (pair->i2, 1);
4409 INSN_TICK (pair->i2) = INVALID_TICK;
4410 INSN_EXACT_TICK (pair->i2) = clock_var + pair_delay (pair);
4411 SHADOW_P (pair->i2) = pair->stages == 0;
4412 pair = pair->next_same_i1;
4416 /* Walk the ready list and all queues. If any insns have unresolved backwards
4417 dependencies, these must be cancelled deps, broken by predication. Set or
4418 clear (depending on SET) the DEP_CANCELLED bit in DEP_STATUS. */
4420 static void
4421 toggle_cancelled_flags (bool set)
4423 int i;
4424 sd_iterator_def sd_it;
4425 dep_t dep;
4427 if (ready.n_ready > 0)
4429 rtx_insn **first = ready_lastpos (&ready);
4430 for (i = 0; i < ready.n_ready; i++)
4431 FOR_EACH_DEP (first[i], SD_LIST_BACK, sd_it, dep)
4432 if (!DEBUG_INSN_P (DEP_PRO (dep)))
4434 if (set)
4435 DEP_STATUS (dep) |= DEP_CANCELLED;
4436 else
4437 DEP_STATUS (dep) &= ~DEP_CANCELLED;
4440 for (i = 0; i <= max_insn_queue_index; i++)
4442 int q = NEXT_Q_AFTER (q_ptr, i);
4443 rtx_insn_list *link;
4444 for (link = insn_queue[q]; link; link = link->next ())
4446 rtx_insn *insn = link->insn ();
4447 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4448 if (!DEBUG_INSN_P (DEP_PRO (dep)))
4450 if (set)
4451 DEP_STATUS (dep) |= DEP_CANCELLED;
4452 else
4453 DEP_STATUS (dep) &= ~DEP_CANCELLED;
4459 /* Undo the replacements that have occurred after backtrack point SAVE
4460 was placed. */
4461 static void
4462 undo_replacements_for_backtrack (struct haifa_saved_data *save)
4464 while (!save->replacement_deps.is_empty ())
4466 dep_t dep = save->replacement_deps.pop ();
4467 int apply_p = save->replace_apply.pop ();
4469 if (apply_p)
4470 restore_pattern (dep, true);
4471 else
4472 apply_replacement (dep, true);
4474 save->replacement_deps.release ();
4475 save->replace_apply.release ();
4478 /* Pop entries from the SCHEDULED_INSNS vector up to and including INSN.
4479 Restore their dependencies to an unresolved state, and mark them as
4480 queued nowhere. */
4482 static void
4483 unschedule_insns_until (rtx_insn *insn)
4485 auto_vec<rtx_insn *> recompute_vec;
4487 /* Make two passes over the insns to be unscheduled. First, we clear out
4488 dependencies and other trivial bookkeeping. */
4489 for (;;)
4491 rtx_insn *last;
4492 sd_iterator_def sd_it;
4493 dep_t dep;
4495 last = scheduled_insns.pop ();
4497 /* This will be changed by restore_backtrack_point if the insn is in
4498 any queue. */
4499 QUEUE_INDEX (last) = QUEUE_NOWHERE;
4500 if (last != insn)
4501 INSN_TICK (last) = INVALID_TICK;
4503 if (modulo_ii > 0 && INSN_UID (last) < modulo_iter0_max_uid)
4504 modulo_insns_scheduled--;
4506 for (sd_it = sd_iterator_start (last, SD_LIST_RES_FORW);
4507 sd_iterator_cond (&sd_it, &dep);)
4509 rtx_insn *con = DEP_CON (dep);
4510 sd_unresolve_dep (sd_it);
4511 if (!MUST_RECOMPUTE_SPEC_P (con))
4513 MUST_RECOMPUTE_SPEC_P (con) = 1;
4514 recompute_vec.safe_push (con);
4518 if (last == insn)
4519 break;
4522 /* A second pass, to update ready and speculation status for insns
4523 depending on the unscheduled ones. The first pass must have
4524 popped the scheduled_insns vector up to the point where we
4525 restart scheduling, as recompute_todo_spec requires it to be
4526 up-to-date. */
4527 while (!recompute_vec.is_empty ())
4529 rtx_insn *con;
4531 con = recompute_vec.pop ();
4532 MUST_RECOMPUTE_SPEC_P (con) = 0;
4533 if (!sd_lists_empty_p (con, SD_LIST_HARD_BACK))
4535 TODO_SPEC (con) = HARD_DEP;
4536 INSN_TICK (con) = INVALID_TICK;
4537 if (PREDICATED_PAT (con) != NULL_RTX)
4538 haifa_change_pattern (con, ORIG_PAT (con));
4540 else if (QUEUE_INDEX (con) != QUEUE_SCHEDULED)
4541 TODO_SPEC (con) = recompute_todo_spec (con, true);
4545 /* Restore scheduler state from the topmost entry on the backtracking queue.
4546 PSCHED_BLOCK_P points to the local data of schedule_block that we must
4547 overwrite with the saved data.
4548 The caller must already have called unschedule_insns_until. */
4550 static void
4551 restore_last_backtrack_point (struct sched_block_state *psched_block)
4553 int i;
4554 struct haifa_saved_data *save = backtrack_queue;
4556 backtrack_queue = save->next;
4558 if (current_sched_info->restore_state)
4559 (*current_sched_info->restore_state) (save->fe_saved_data);
4561 if (targetm.sched.alloc_sched_context)
4563 targetm.sched.set_sched_context (save->be_saved_data);
4564 targetm.sched.free_sched_context (save->be_saved_data);
4567 /* Do this first since it clobbers INSN_TICK of the involved
4568 instructions. */
4569 undo_replacements_for_backtrack (save);
4571 /* Clear the QUEUE_INDEX of everything in the ready list or one
4572 of the queues. */
4573 if (ready.n_ready > 0)
4575 rtx_insn **first = ready_lastpos (&ready);
4576 for (i = 0; i < ready.n_ready; i++)
4578 rtx_insn *insn = first[i];
4579 QUEUE_INDEX (insn) = QUEUE_NOWHERE;
4580 INSN_TICK (insn) = INVALID_TICK;
4583 for (i = 0; i <= max_insn_queue_index; i++)
4585 int q = NEXT_Q_AFTER (q_ptr, i);
4587 for (rtx_insn_list *link = insn_queue[q]; link; link = link->next ())
4589 rtx_insn *x = link->insn ();
4590 QUEUE_INDEX (x) = QUEUE_NOWHERE;
4591 INSN_TICK (x) = INVALID_TICK;
4593 free_INSN_LIST_list (&insn_queue[q]);
4596 free (ready.vec);
4597 ready = save->ready;
4599 if (ready.n_ready > 0)
4601 rtx_insn **first = ready_lastpos (&ready);
4602 for (i = 0; i < ready.n_ready; i++)
4604 rtx_insn *insn = first[i];
4605 QUEUE_INDEX (insn) = QUEUE_READY;
4606 TODO_SPEC (insn) = recompute_todo_spec (insn, true);
4607 INSN_TICK (insn) = save->clock_var;
4611 q_ptr = 0;
4612 q_size = save->q_size;
4613 for (i = 0; i <= max_insn_queue_index; i++)
4615 int q = NEXT_Q_AFTER (q_ptr, i);
4617 insn_queue[q] = save->insn_queue[q];
4619 for (rtx_insn_list *link = insn_queue[q]; link; link = link->next ())
4621 rtx_insn *x = link->insn ();
4622 QUEUE_INDEX (x) = i;
4623 TODO_SPEC (x) = recompute_todo_spec (x, true);
4624 INSN_TICK (x) = save->clock_var + i;
4627 free (save->insn_queue);
4629 toggle_cancelled_flags (true);
4631 clock_var = save->clock_var;
4632 last_clock_var = save->last_clock_var;
4633 cycle_issued_insns = save->cycle_issued_insns;
4634 last_scheduled_insn = save->last_scheduled_insn;
4635 last_nondebug_scheduled_insn = save->last_nondebug_scheduled_insn;
4636 nonscheduled_insns_begin = save->nonscheduled_insns_begin;
4638 *psched_block = save->sched_block;
4640 memcpy (curr_state, save->curr_state, dfa_state_size);
4641 free (save->curr_state);
4643 mark_backtrack_feeds (save->delay_pair->i2, 0);
4645 gcc_assert (next_cycle_replace_deps.is_empty ());
4646 next_cycle_replace_deps = save->next_cycle_deps.copy ();
4647 next_cycle_apply = save->next_cycle_apply.copy ();
4649 free (save);
4651 for (save = backtrack_queue; save; save = save->next)
4653 mark_backtrack_feeds (save->delay_pair->i2, 1);
4657 /* Discard all data associated with the topmost entry in the backtrack
4658 queue. If RESET_TICK is false, we just want to free the data. If true,
4659 we are doing this because we discovered a reason to backtrack. In the
4660 latter case, also reset the INSN_TICK for the shadow insn. */
4661 static void
4662 free_topmost_backtrack_point (bool reset_tick)
4664 struct haifa_saved_data *save = backtrack_queue;
4665 int i;
4667 backtrack_queue = save->next;
4669 if (reset_tick)
4671 struct delay_pair *pair = save->delay_pair;
4672 while (pair)
4674 INSN_TICK (pair->i2) = INVALID_TICK;
4675 INSN_EXACT_TICK (pair->i2) = INVALID_TICK;
4676 pair = pair->next_same_i1;
4678 undo_replacements_for_backtrack (save);
4680 else
4682 save->replacement_deps.release ();
4683 save->replace_apply.release ();
4686 if (targetm.sched.free_sched_context)
4687 targetm.sched.free_sched_context (save->be_saved_data);
4688 if (current_sched_info->restore_state)
4689 free (save->fe_saved_data);
4690 for (i = 0; i <= max_insn_queue_index; i++)
4691 free_INSN_LIST_list (&save->insn_queue[i]);
4692 free (save->insn_queue);
4693 free (save->curr_state);
4694 free (save->ready.vec);
4695 free (save);
4698 /* Free the entire backtrack queue. */
4699 static void
4700 free_backtrack_queue (void)
4702 while (backtrack_queue)
4703 free_topmost_backtrack_point (false);
4706 /* Apply a replacement described by DESC. If IMMEDIATELY is false, we
4707 may have to postpone the replacement until the start of the next cycle,
4708 at which point we will be called again with IMMEDIATELY true. This is
4709 only done for machines which have instruction packets with explicit
4710 parallelism however. */
4711 static void
4712 apply_replacement (dep_t dep, bool immediately)
4714 struct dep_replacement *desc = DEP_REPLACE (dep);
4715 if (!immediately && targetm.sched.exposed_pipeline && reload_completed)
4717 next_cycle_replace_deps.safe_push (dep);
4718 next_cycle_apply.safe_push (1);
4720 else
4722 bool success;
4724 if (QUEUE_INDEX (desc->insn) == QUEUE_SCHEDULED)
4725 return;
4727 if (sched_verbose >= 5)
4728 fprintf (sched_dump, "applying replacement for insn %d\n",
4729 INSN_UID (desc->insn));
4731 success = validate_change (desc->insn, desc->loc, desc->newval, 0);
4732 gcc_assert (success);
4734 update_insn_after_change (desc->insn);
4735 if ((TODO_SPEC (desc->insn) & (HARD_DEP | DEP_POSTPONED)) == 0)
4736 fix_tick_ready (desc->insn);
4738 if (backtrack_queue != NULL)
4740 backtrack_queue->replacement_deps.safe_push (dep);
4741 backtrack_queue->replace_apply.safe_push (1);
4746 /* We have determined that a pattern involved in DEP must be restored.
4747 If IMMEDIATELY is false, we may have to postpone the replacement
4748 until the start of the next cycle, at which point we will be called
4749 again with IMMEDIATELY true. */
4750 static void
4751 restore_pattern (dep_t dep, bool immediately)
4753 rtx_insn *next = DEP_CON (dep);
4754 int tick = INSN_TICK (next);
4756 /* If we already scheduled the insn, the modified version is
4757 correct. */
4758 if (QUEUE_INDEX (next) == QUEUE_SCHEDULED)
4759 return;
4761 if (!immediately && targetm.sched.exposed_pipeline && reload_completed)
4763 next_cycle_replace_deps.safe_push (dep);
4764 next_cycle_apply.safe_push (0);
4765 return;
4769 if (DEP_TYPE (dep) == REG_DEP_CONTROL)
4771 if (sched_verbose >= 5)
4772 fprintf (sched_dump, "restoring pattern for insn %d\n",
4773 INSN_UID (next));
4774 haifa_change_pattern (next, ORIG_PAT (next));
4776 else
4778 struct dep_replacement *desc = DEP_REPLACE (dep);
4779 bool success;
4781 if (sched_verbose >= 5)
4782 fprintf (sched_dump, "restoring pattern for insn %d\n",
4783 INSN_UID (desc->insn));
4784 tick = INSN_TICK (desc->insn);
4786 success = validate_change (desc->insn, desc->loc, desc->orig, 0);
4787 gcc_assert (success);
4788 update_insn_after_change (desc->insn);
4789 if (backtrack_queue != NULL)
4791 backtrack_queue->replacement_deps.safe_push (dep);
4792 backtrack_queue->replace_apply.safe_push (0);
4795 INSN_TICK (next) = tick;
4796 if (TODO_SPEC (next) == DEP_POSTPONED)
4797 return;
4799 if (sd_lists_empty_p (next, SD_LIST_BACK))
4800 TODO_SPEC (next) = 0;
4801 else if (!sd_lists_empty_p (next, SD_LIST_HARD_BACK))
4802 TODO_SPEC (next) = HARD_DEP;
4805 /* Perform pattern replacements that were queued up until the next
4806 cycle. */
4807 static void
4808 perform_replacements_new_cycle (void)
4810 int i;
4811 dep_t dep;
4812 FOR_EACH_VEC_ELT (next_cycle_replace_deps, i, dep)
4814 int apply_p = next_cycle_apply[i];
4815 if (apply_p)
4816 apply_replacement (dep, true);
4817 else
4818 restore_pattern (dep, true);
4820 next_cycle_replace_deps.truncate (0);
4821 next_cycle_apply.truncate (0);
4824 /* Compute INSN_TICK_ESTIMATE for INSN. PROCESSED is a bitmap of
4825 instructions we've previously encountered, a set bit prevents
4826 recursion. BUDGET is a limit on how far ahead we look, it is
4827 reduced on recursive calls. Return true if we produced a good
4828 estimate, or false if we exceeded the budget. */
4829 static bool
4830 estimate_insn_tick (bitmap processed, rtx_insn *insn, int budget)
4832 sd_iterator_def sd_it;
4833 dep_t dep;
4834 int earliest = INSN_TICK (insn);
4836 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
4838 rtx_insn *pro = DEP_PRO (dep);
4839 int t;
4841 if (DEP_STATUS (dep) & DEP_CANCELLED)
4842 continue;
4844 if (QUEUE_INDEX (pro) == QUEUE_SCHEDULED)
4845 gcc_assert (INSN_TICK (pro) + dep_cost (dep) <= INSN_TICK (insn));
4846 else
4848 int cost = dep_cost (dep);
4849 if (cost >= budget)
4850 return false;
4851 if (!bitmap_bit_p (processed, INSN_LUID (pro)))
4853 if (!estimate_insn_tick (processed, pro, budget - cost))
4854 return false;
4856 gcc_assert (INSN_TICK_ESTIMATE (pro) != INVALID_TICK);
4857 t = INSN_TICK_ESTIMATE (pro) + cost;
4858 if (earliest == INVALID_TICK || t > earliest)
4859 earliest = t;
4862 bitmap_set_bit (processed, INSN_LUID (insn));
4863 INSN_TICK_ESTIMATE (insn) = earliest;
4864 return true;
4867 /* Examine the pair of insns in P, and estimate (optimistically, assuming
4868 infinite resources) the cycle in which the delayed shadow can be issued.
4869 Return the number of cycles that must pass before the real insn can be
4870 issued in order to meet this constraint. */
4871 static int
4872 estimate_shadow_tick (struct delay_pair *p)
4874 bitmap_head processed;
4875 int t;
4876 bool cutoff;
4877 bitmap_initialize (&processed, 0);
4879 cutoff = !estimate_insn_tick (&processed, p->i2,
4880 max_insn_queue_index + pair_delay (p));
4881 bitmap_clear (&processed);
4882 if (cutoff)
4883 return max_insn_queue_index;
4884 t = INSN_TICK_ESTIMATE (p->i2) - (clock_var + pair_delay (p) + 1);
4885 if (t > 0)
4886 return t;
4887 return 0;
4890 /* If INSN has no unresolved backwards dependencies, add it to the schedule and
4891 recursively resolve all its forward dependencies. */
4892 static void
4893 resolve_dependencies (rtx_insn *insn)
4895 sd_iterator_def sd_it;
4896 dep_t dep;
4898 /* Don't use sd_lists_empty_p; it ignores debug insns. */
4899 if (DEPS_LIST_FIRST (INSN_HARD_BACK_DEPS (insn)) != NULL
4900 || DEPS_LIST_FIRST (INSN_SPEC_BACK_DEPS (insn)) != NULL)
4901 return;
4903 if (sched_verbose >= 4)
4904 fprintf (sched_dump, ";;\tquickly resolving %d\n", INSN_UID (insn));
4906 if (QUEUE_INDEX (insn) >= 0)
4907 queue_remove (insn);
4909 scheduled_insns.safe_push (insn);
4911 /* Update dependent instructions. */
4912 for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
4913 sd_iterator_cond (&sd_it, &dep);)
4915 rtx_insn *next = DEP_CON (dep);
4917 if (sched_verbose >= 4)
4918 fprintf (sched_dump, ";;\t\tdep %d against %d\n", INSN_UID (insn),
4919 INSN_UID (next));
4921 /* Resolve the dependence between INSN and NEXT.
4922 sd_resolve_dep () moves current dep to another list thus
4923 advancing the iterator. */
4924 sd_resolve_dep (sd_it);
4926 if (!IS_SPECULATION_BRANCHY_CHECK_P (insn))
4928 resolve_dependencies (next);
4930 else
4931 /* Check always has only one forward dependence (to the first insn in
4932 the recovery block), therefore, this will be executed only once. */
4934 gcc_assert (sd_lists_empty_p (insn, SD_LIST_FORW));
4940 /* Return the head and tail pointers of ebb starting at BEG and ending
4941 at END. */
4942 void
4943 get_ebb_head_tail (basic_block beg, basic_block end,
4944 rtx_insn **headp, rtx_insn **tailp)
4946 rtx_insn *beg_head = BB_HEAD (beg);
4947 rtx_insn * beg_tail = BB_END (beg);
4948 rtx_insn * end_head = BB_HEAD (end);
4949 rtx_insn * end_tail = BB_END (end);
4951 /* Don't include any notes or labels at the beginning of the BEG
4952 basic block, or notes at the end of the END basic blocks. */
4954 if (LABEL_P (beg_head))
4955 beg_head = NEXT_INSN (beg_head);
4957 while (beg_head != beg_tail)
4958 if (NOTE_P (beg_head))
4959 beg_head = NEXT_INSN (beg_head);
4960 else if (DEBUG_INSN_P (beg_head))
4962 rtx_insn * note, *next;
4964 for (note = NEXT_INSN (beg_head);
4965 note != beg_tail;
4966 note = next)
4968 next = NEXT_INSN (note);
4969 if (NOTE_P (note))
4971 if (sched_verbose >= 9)
4972 fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
4974 reorder_insns_nobb (note, note, PREV_INSN (beg_head));
4976 if (BLOCK_FOR_INSN (note) != beg)
4977 df_insn_change_bb (note, beg);
4979 else if (!DEBUG_INSN_P (note))
4980 break;
4983 break;
4985 else
4986 break;
4988 *headp = beg_head;
4990 if (beg == end)
4991 end_head = beg_head;
4992 else if (LABEL_P (end_head))
4993 end_head = NEXT_INSN (end_head);
4995 while (end_head != end_tail)
4996 if (NOTE_P (end_tail))
4997 end_tail = PREV_INSN (end_tail);
4998 else if (DEBUG_INSN_P (end_tail))
5000 rtx_insn * note, *prev;
5002 for (note = PREV_INSN (end_tail);
5003 note != end_head;
5004 note = prev)
5006 prev = PREV_INSN (note);
5007 if (NOTE_P (note))
5009 if (sched_verbose >= 9)
5010 fprintf (sched_dump, "reorder %i\n", INSN_UID (note));
5012 reorder_insns_nobb (note, note, end_tail);
5014 if (end_tail == BB_END (end))
5015 BB_END (end) = note;
5017 if (BLOCK_FOR_INSN (note) != end)
5018 df_insn_change_bb (note, end);
5020 else if (!DEBUG_INSN_P (note))
5021 break;
5024 break;
5026 else
5027 break;
5029 *tailp = end_tail;
5032 /* Return nonzero if there are no real insns in the range [ HEAD, TAIL ]. */
5035 no_real_insns_p (const rtx_insn *head, const rtx_insn *tail)
5037 while (head != NEXT_INSN (tail))
5039 if (!NOTE_P (head) && !LABEL_P (head))
5040 return 0;
5041 head = NEXT_INSN (head);
5043 return 1;
5046 /* Restore-other-notes: NOTE_LIST is the end of a chain of notes
5047 previously found among the insns. Insert them just before HEAD. */
5048 rtx_insn *
5049 restore_other_notes (rtx_insn *head, basic_block head_bb)
5051 if (note_list != 0)
5053 rtx_insn *note_head = note_list;
5055 if (head)
5056 head_bb = BLOCK_FOR_INSN (head);
5057 else
5058 head = NEXT_INSN (bb_note (head_bb));
5060 while (PREV_INSN (note_head))
5062 set_block_for_insn (note_head, head_bb);
5063 note_head = PREV_INSN (note_head);
5065 /* In the above cycle we've missed this note. */
5066 set_block_for_insn (note_head, head_bb);
5068 SET_PREV_INSN (note_head) = PREV_INSN (head);
5069 SET_NEXT_INSN (PREV_INSN (head)) = note_head;
5070 SET_PREV_INSN (head) = note_list;
5071 SET_NEXT_INSN (note_list) = head;
5073 if (BLOCK_FOR_INSN (head) != head_bb)
5074 BB_END (head_bb) = note_list;
5076 head = note_head;
5079 return head;
5082 /* When we know we are going to discard the schedule due to a failed attempt
5083 at modulo scheduling, undo all replacements. */
5084 static void
5085 undo_all_replacements (void)
5087 rtx_insn *insn;
5088 int i;
5090 FOR_EACH_VEC_ELT (scheduled_insns, i, insn)
5092 sd_iterator_def sd_it;
5093 dep_t dep;
5095 /* See if we must undo a replacement. */
5096 for (sd_it = sd_iterator_start (insn, SD_LIST_RES_FORW);
5097 sd_iterator_cond (&sd_it, &dep); sd_iterator_next (&sd_it))
5099 struct dep_replacement *desc = DEP_REPLACE (dep);
5100 if (desc != NULL)
5101 validate_change (desc->insn, desc->loc, desc->orig, 0);
5106 /* Return first non-scheduled insn in the current scheduling block.
5107 This is mostly used for debug-counter purposes. */
5108 static rtx_insn *
5109 first_nonscheduled_insn (void)
5111 rtx_insn *insn = (nonscheduled_insns_begin != NULL_RTX
5112 ? nonscheduled_insns_begin
5113 : current_sched_info->prev_head);
5117 insn = next_nonnote_nondebug_insn (insn);
5119 while (QUEUE_INDEX (insn) == QUEUE_SCHEDULED);
5121 return insn;
5124 /* Move insns that became ready to fire from queue to ready list. */
5126 static void
5127 queue_to_ready (struct ready_list *ready)
5129 rtx_insn *insn;
5130 rtx_insn_list *link;
5131 rtx_insn *skip_insn;
5133 q_ptr = NEXT_Q (q_ptr);
5135 if (dbg_cnt (sched_insn) == false)
5136 /* If debug counter is activated do not requeue the first
5137 nonscheduled insn. */
5138 skip_insn = first_nonscheduled_insn ();
5139 else
5140 skip_insn = NULL;
5142 /* Add all pending insns that can be scheduled without stalls to the
5143 ready list. */
5144 for (link = insn_queue[q_ptr]; link; link = link->next ())
5146 insn = link->insn ();
5147 q_size -= 1;
5149 if (sched_verbose >= 2)
5150 fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
5151 (*current_sched_info->print_insn) (insn, 0));
5153 /* If the ready list is full, delay the insn for 1 cycle.
5154 See the comment in schedule_block for the rationale. */
5155 if (!reload_completed
5156 && (ready->n_ready - ready->n_debug > MAX_SCHED_READY_INSNS
5157 || (sched_pressure == SCHED_PRESSURE_MODEL
5158 /* Limit pressure recalculations to MAX_SCHED_READY_INSNS
5159 instructions too. */
5160 && model_index (insn) > (model_curr_point
5161 + MAX_SCHED_READY_INSNS)))
5162 && !(sched_pressure == SCHED_PRESSURE_MODEL
5163 && model_curr_point < model_num_insns
5164 /* Always allow the next model instruction to issue. */
5165 && model_index (insn) == model_curr_point)
5166 && !SCHED_GROUP_P (insn)
5167 && insn != skip_insn)
5169 if (sched_verbose >= 2)
5170 fprintf (sched_dump, "keeping in queue, ready full\n");
5171 queue_insn (insn, 1, "ready full");
5173 else
5175 ready_add (ready, insn, false);
5176 if (sched_verbose >= 2)
5177 fprintf (sched_dump, "moving to ready without stalls\n");
5180 free_INSN_LIST_list (&insn_queue[q_ptr]);
5182 /* If there are no ready insns, stall until one is ready and add all
5183 of the pending insns at that point to the ready list. */
5184 if (ready->n_ready == 0)
5186 int stalls;
5188 for (stalls = 1; stalls <= max_insn_queue_index; stalls++)
5190 if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
5192 for (; link; link = link->next ())
5194 insn = link->insn ();
5195 q_size -= 1;
5197 if (sched_verbose >= 2)
5198 fprintf (sched_dump, ";;\t\tQ-->Ready: insn %s: ",
5199 (*current_sched_info->print_insn) (insn, 0));
5201 ready_add (ready, insn, false);
5202 if (sched_verbose >= 2)
5203 fprintf (sched_dump, "moving to ready with %d stalls\n", stalls);
5205 free_INSN_LIST_list (&insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]);
5207 advance_one_cycle ();
5209 break;
5212 advance_one_cycle ();
5215 q_ptr = NEXT_Q_AFTER (q_ptr, stalls);
5216 clock_var += stalls;
5217 if (sched_verbose >= 2)
5218 fprintf (sched_dump, ";;\tAdvancing clock by %d cycle[s] to %d\n",
5219 stalls, clock_var);
5223 /* Used by early_queue_to_ready. Determines whether it is "ok" to
5224 prematurely move INSN from the queue to the ready list. Currently,
5225 if a target defines the hook 'is_costly_dependence', this function
5226 uses the hook to check whether there exist any dependences which are
5227 considered costly by the target, between INSN and other insns that
5228 have already been scheduled. Dependences are checked up to Y cycles
5229 back, with default Y=1; The flag -fsched-stalled-insns-dep=Y allows
5230 controlling this value.
5231 (Other considerations could be taken into account instead (or in
5232 addition) depending on user flags and target hooks. */
5234 static bool
5235 ok_for_early_queue_removal (rtx_insn *insn)
5237 if (targetm.sched.is_costly_dependence)
5239 int n_cycles;
5240 int i = scheduled_insns.length ();
5241 for (n_cycles = flag_sched_stalled_insns_dep; n_cycles; n_cycles--)
5243 while (i-- > 0)
5245 int cost;
5247 rtx_insn *prev_insn = scheduled_insns[i];
5249 if (!NOTE_P (prev_insn))
5251 dep_t dep;
5253 dep = sd_find_dep_between (prev_insn, insn, true);
5255 if (dep != NULL)
5257 cost = dep_cost (dep);
5259 if (targetm.sched.is_costly_dependence (dep, cost,
5260 flag_sched_stalled_insns_dep - n_cycles))
5261 return false;
5265 if (GET_MODE (prev_insn) == TImode) /* end of dispatch group */
5266 break;
5269 if (i == 0)
5270 break;
5274 return true;
5278 /* Remove insns from the queue, before they become "ready" with respect
5279 to FU latency considerations. */
5281 static int
5282 early_queue_to_ready (state_t state, struct ready_list *ready)
5284 rtx_insn *insn;
5285 rtx_insn_list *link;
5286 rtx_insn_list *next_link;
5287 rtx_insn_list *prev_link;
5288 bool move_to_ready;
5289 int cost;
5290 state_t temp_state = alloca (dfa_state_size);
5291 int stalls;
5292 int insns_removed = 0;
5295 Flag '-fsched-stalled-insns=X' determines the aggressiveness of this
5296 function:
5298 X == 0: There is no limit on how many queued insns can be removed
5299 prematurely. (flag_sched_stalled_insns = -1).
5301 X >= 1: Only X queued insns can be removed prematurely in each
5302 invocation. (flag_sched_stalled_insns = X).
5304 Otherwise: Early queue removal is disabled.
5305 (flag_sched_stalled_insns = 0)
5308 if (! flag_sched_stalled_insns)
5309 return 0;
5311 for (stalls = 0; stalls <= max_insn_queue_index; stalls++)
5313 if ((link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)]))
5315 if (sched_verbose > 6)
5316 fprintf (sched_dump, ";; look at index %d + %d\n", q_ptr, stalls);
5318 prev_link = 0;
5319 while (link)
5321 next_link = link->next ();
5322 insn = link->insn ();
5323 if (insn && sched_verbose > 6)
5324 print_rtl_single (sched_dump, insn);
5326 memcpy (temp_state, state, dfa_state_size);
5327 if (recog_memoized (insn) < 0)
5328 /* non-negative to indicate that it's not ready
5329 to avoid infinite Q->R->Q->R... */
5330 cost = 0;
5331 else
5332 cost = state_transition (temp_state, insn);
5334 if (sched_verbose >= 6)
5335 fprintf (sched_dump, "transition cost = %d\n", cost);
5337 move_to_ready = false;
5338 if (cost < 0)
5340 move_to_ready = ok_for_early_queue_removal (insn);
5341 if (move_to_ready == true)
5343 /* move from Q to R */
5344 q_size -= 1;
5345 ready_add (ready, insn, false);
5347 if (prev_link)
5348 XEXP (prev_link, 1) = next_link;
5349 else
5350 insn_queue[NEXT_Q_AFTER (q_ptr, stalls)] = next_link;
5352 free_INSN_LIST_node (link);
5354 if (sched_verbose >= 2)
5355 fprintf (sched_dump, ";;\t\tEarly Q-->Ready: insn %s\n",
5356 (*current_sched_info->print_insn) (insn, 0));
5358 insns_removed++;
5359 if (insns_removed == flag_sched_stalled_insns)
5360 /* Remove no more than flag_sched_stalled_insns insns
5361 from Q at a time. */
5362 return insns_removed;
5366 if (move_to_ready == false)
5367 prev_link = link;
5369 link = next_link;
5370 } /* while link */
5371 } /* if link */
5373 } /* for stalls.. */
5375 return insns_removed;
5379 /* Print the ready list for debugging purposes.
5380 If READY_TRY is non-zero then only print insns that max_issue
5381 will consider. */
5382 static void
5383 debug_ready_list_1 (struct ready_list *ready, signed char *ready_try)
5385 rtx_insn **p;
5386 int i;
5388 if (ready->n_ready == 0)
5390 fprintf (sched_dump, "\n");
5391 return;
5394 p = ready_lastpos (ready);
5395 for (i = 0; i < ready->n_ready; i++)
5397 if (ready_try != NULL && ready_try[ready->n_ready - i - 1])
5398 continue;
5400 fprintf (sched_dump, " %s:%d",
5401 (*current_sched_info->print_insn) (p[i], 0),
5402 INSN_LUID (p[i]));
5403 if (sched_pressure != SCHED_PRESSURE_NONE)
5404 fprintf (sched_dump, "(cost=%d",
5405 INSN_REG_PRESSURE_EXCESS_COST_CHANGE (p[i]));
5406 fprintf (sched_dump, ":prio=%d", INSN_PRIORITY (p[i]));
5407 if (INSN_TICK (p[i]) > clock_var)
5408 fprintf (sched_dump, ":delay=%d", INSN_TICK (p[i]) - clock_var);
5409 if (sched_pressure == SCHED_PRESSURE_MODEL)
5410 fprintf (sched_dump, ":idx=%d",
5411 model_index (p[i]));
5412 if (sched_pressure != SCHED_PRESSURE_NONE)
5413 fprintf (sched_dump, ")");
5415 fprintf (sched_dump, "\n");
5418 /* Print the ready list. Callable from debugger. */
5419 static void
5420 debug_ready_list (struct ready_list *ready)
5422 debug_ready_list_1 (ready, NULL);
5425 /* Search INSN for REG_SAVE_NOTE notes and convert them back into insn
5426 NOTEs. This is used for NOTE_INSN_EPILOGUE_BEG, so that sched-ebb
5427 replaces the epilogue note in the correct basic block. */
5428 void
5429 reemit_notes (rtx_insn *insn)
5431 rtx note;
5432 rtx_insn *last = insn;
5434 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
5436 if (REG_NOTE_KIND (note) == REG_SAVE_NOTE)
5438 enum insn_note note_type = (enum insn_note) INTVAL (XEXP (note, 0));
5440 last = emit_note_before (note_type, last);
5441 remove_note (insn, note);
5446 /* Move INSN. Reemit notes if needed. Update CFG, if needed. */
5447 static void
5448 move_insn (rtx_insn *insn, rtx_insn *last, rtx nt)
5450 if (PREV_INSN (insn) != last)
5452 basic_block bb;
5453 rtx_insn *note;
5454 int jump_p = 0;
5456 bb = BLOCK_FOR_INSN (insn);
5458 /* BB_HEAD is either LABEL or NOTE. */
5459 gcc_assert (BB_HEAD (bb) != insn);
5461 if (BB_END (bb) == insn)
5462 /* If this is last instruction in BB, move end marker one
5463 instruction up. */
5465 /* Jumps are always placed at the end of basic block. */
5466 jump_p = control_flow_insn_p (insn);
5468 gcc_assert (!jump_p
5469 || ((common_sched_info->sched_pass_id == SCHED_RGN_PASS)
5470 && IS_SPECULATION_BRANCHY_CHECK_P (insn))
5471 || (common_sched_info->sched_pass_id
5472 == SCHED_EBB_PASS));
5474 gcc_assert (BLOCK_FOR_INSN (PREV_INSN (insn)) == bb);
5476 BB_END (bb) = PREV_INSN (insn);
5479 gcc_assert (BB_END (bb) != last);
5481 if (jump_p)
5482 /* We move the block note along with jump. */
5484 gcc_assert (nt);
5486 note = NEXT_INSN (insn);
5487 while (NOTE_NOT_BB_P (note) && note != nt)
5488 note = NEXT_INSN (note);
5490 if (note != nt
5491 && (LABEL_P (note)
5492 || BARRIER_P (note)))
5493 note = NEXT_INSN (note);
5495 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
5497 else
5498 note = insn;
5500 SET_NEXT_INSN (PREV_INSN (insn)) = NEXT_INSN (note);
5501 SET_PREV_INSN (NEXT_INSN (note)) = PREV_INSN (insn);
5503 SET_NEXT_INSN (note) = NEXT_INSN (last);
5504 SET_PREV_INSN (NEXT_INSN (last)) = note;
5506 SET_NEXT_INSN (last) = insn;
5507 SET_PREV_INSN (insn) = last;
5509 bb = BLOCK_FOR_INSN (last);
5511 if (jump_p)
5513 fix_jump_move (insn);
5515 if (BLOCK_FOR_INSN (insn) != bb)
5516 move_block_after_check (insn);
5518 gcc_assert (BB_END (bb) == last);
5521 df_insn_change_bb (insn, bb);
5523 /* Update BB_END, if needed. */
5524 if (BB_END (bb) == last)
5525 BB_END (bb) = insn;
5528 SCHED_GROUP_P (insn) = 0;
5531 /* Return true if scheduling INSN will finish current clock cycle. */
5532 static bool
5533 insn_finishes_cycle_p (rtx_insn *insn)
5535 if (SCHED_GROUP_P (insn))
5536 /* After issuing INSN, rest of the sched_group will be forced to issue
5537 in order. Don't make any plans for the rest of cycle. */
5538 return true;
5540 /* Finishing the block will, apparently, finish the cycle. */
5541 if (current_sched_info->insn_finishes_block_p
5542 && current_sched_info->insn_finishes_block_p (insn))
5543 return true;
5545 return false;
5548 /* Functions to model cache auto-prefetcher.
5550 Some of the CPUs have cache auto-prefetcher, which /seems/ to initiate
5551 memory prefetches if it sees instructions with consequitive memory accesses
5552 in the instruction stream. Details of such hardware units are not published,
5553 so we can only guess what exactly is going on there.
5554 In the scheduler, we model abstract auto-prefetcher. If there are memory
5555 insns in the ready list (or the queue) that have same memory base, but
5556 different offsets, then we delay the insns with larger offsets until insns
5557 with smaller offsets get scheduled. If PARAM_SCHED_AUTOPREF_QUEUE_DEPTH
5558 is "1", then we look at the ready list; if it is N>1, then we also look
5559 through N-1 queue entries.
5560 If the param is N>=0, then rank_for_schedule will consider auto-prefetching
5561 among its heuristics.
5562 Param value of "-1" disables modelling of the auto-prefetcher. */
5564 /* Initialize autoprefetcher model data for INSN. */
5565 static void
5566 autopref_multipass_init (const rtx_insn *insn, int write)
5568 autopref_multipass_data_t data = &INSN_AUTOPREF_MULTIPASS_DATA (insn)[write];
5570 gcc_assert (data->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED);
5571 data->base = NULL_RTX;
5572 data->offset = 0;
5573 /* Set insn entry initialized, but not relevant for auto-prefetcher. */
5574 data->status = AUTOPREF_MULTIPASS_DATA_IRRELEVANT;
5576 rtx set = single_set (insn);
5577 if (set == NULL_RTX)
5578 return;
5580 rtx mem = write ? SET_DEST (set) : SET_SRC (set);
5581 if (!MEM_P (mem))
5582 return;
5584 struct address_info info;
5585 decompose_mem_address (&info, mem);
5587 /* TODO: Currently only (base+const) addressing is supported. */
5588 if (info.base == NULL || !REG_P (*info.base)
5589 || (info.disp != NULL && !CONST_INT_P (*info.disp)))
5590 return;
5592 /* This insn is relevant for auto-prefetcher. */
5593 data->base = *info.base;
5594 data->offset = info.disp ? INTVAL (*info.disp) : 0;
5595 data->status = AUTOPREF_MULTIPASS_DATA_NORMAL;
5598 /* Helper function for rank_for_schedule sorting. */
5599 static int
5600 autopref_rank_for_schedule (const rtx_insn *insn1, const rtx_insn *insn2)
5602 for (int write = 0; write < 2; ++write)
5604 autopref_multipass_data_t data1
5605 = &INSN_AUTOPREF_MULTIPASS_DATA (insn1)[write];
5606 autopref_multipass_data_t data2
5607 = &INSN_AUTOPREF_MULTIPASS_DATA (insn2)[write];
5609 if (data1->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5610 autopref_multipass_init (insn1, write);
5611 if (data1->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5612 continue;
5614 if (data2->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5615 autopref_multipass_init (insn2, write);
5616 if (data2->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5617 continue;
5619 if (!rtx_equal_p (data1->base, data2->base))
5620 continue;
5622 return data1->offset - data2->offset;
5625 return 0;
5628 /* True if header of debug dump was printed. */
5629 static bool autopref_multipass_dfa_lookahead_guard_started_dump_p;
5631 /* Helper for autopref_multipass_dfa_lookahead_guard.
5632 Return "1" if INSN1 should be delayed in favor of INSN2. */
5633 static int
5634 autopref_multipass_dfa_lookahead_guard_1 (const rtx_insn *insn1,
5635 const rtx_insn *insn2, int write)
5637 autopref_multipass_data_t data1
5638 = &INSN_AUTOPREF_MULTIPASS_DATA (insn1)[write];
5639 autopref_multipass_data_t data2
5640 = &INSN_AUTOPREF_MULTIPASS_DATA (insn2)[write];
5642 if (data2->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5643 autopref_multipass_init (insn2, write);
5644 if (data2->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5645 return 0;
5647 if (rtx_equal_p (data1->base, data2->base)
5648 && data1->offset > data2->offset)
5650 if (sched_verbose >= 2)
5652 if (!autopref_multipass_dfa_lookahead_guard_started_dump_p)
5654 fprintf (sched_dump,
5655 ";;\t\tnot trying in max_issue due to autoprefetch "
5656 "model: ");
5657 autopref_multipass_dfa_lookahead_guard_started_dump_p = true;
5660 fprintf (sched_dump, " %d(%d)", INSN_UID (insn1), INSN_UID (insn2));
5663 return 1;
5666 return 0;
5669 /* General note:
5671 We could have also hooked autoprefetcher model into
5672 first_cycle_multipass_backtrack / first_cycle_multipass_issue hooks
5673 to enable intelligent selection of "[r1+0]=r2; [r1+4]=r3" on the same cycle
5674 (e.g., once "[r1+0]=r2" is issued in max_issue(), "[r1+4]=r3" gets
5675 unblocked). We don't bother about this yet because target of interest
5676 (ARM Cortex-A15) can issue only 1 memory operation per cycle. */
5678 /* Implementation of first_cycle_multipass_dfa_lookahead_guard hook.
5679 Return "1" if INSN1 should not be considered in max_issue due to
5680 auto-prefetcher considerations. */
5682 autopref_multipass_dfa_lookahead_guard (rtx_insn *insn1, int ready_index)
5684 int r = 0;
5686 if (PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) <= 0)
5687 return 0;
5689 if (sched_verbose >= 2 && ready_index == 0)
5690 autopref_multipass_dfa_lookahead_guard_started_dump_p = false;
5692 for (int write = 0; write < 2; ++write)
5694 autopref_multipass_data_t data1
5695 = &INSN_AUTOPREF_MULTIPASS_DATA (insn1)[write];
5697 if (data1->status == AUTOPREF_MULTIPASS_DATA_UNINITIALIZED)
5698 autopref_multipass_init (insn1, write);
5699 if (data1->status == AUTOPREF_MULTIPASS_DATA_IRRELEVANT)
5700 continue;
5702 if (ready_index == 0
5703 && data1->status == AUTOPREF_MULTIPASS_DATA_DONT_DELAY)
5704 /* We allow only a single delay on priviledged instructions.
5705 Doing otherwise would cause infinite loop. */
5707 if (sched_verbose >= 2)
5709 if (!autopref_multipass_dfa_lookahead_guard_started_dump_p)
5711 fprintf (sched_dump,
5712 ";;\t\tnot trying in max_issue due to autoprefetch "
5713 "model: ");
5714 autopref_multipass_dfa_lookahead_guard_started_dump_p = true;
5717 fprintf (sched_dump, " *%d*", INSN_UID (insn1));
5719 continue;
5722 for (int i2 = 0; i2 < ready.n_ready; ++i2)
5724 rtx_insn *insn2 = get_ready_element (i2);
5725 if (insn1 == insn2)
5726 continue;
5727 r = autopref_multipass_dfa_lookahead_guard_1 (insn1, insn2, write);
5728 if (r)
5730 if (ready_index == 0)
5732 r = -1;
5733 data1->status = AUTOPREF_MULTIPASS_DATA_DONT_DELAY;
5735 goto finish;
5739 if (PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) == 1)
5740 continue;
5742 /* Everything from the current queue slot should have been moved to
5743 the ready list. */
5744 gcc_assert (insn_queue[NEXT_Q_AFTER (q_ptr, 0)] == NULL_RTX);
5746 int n_stalls = PARAM_VALUE (PARAM_SCHED_AUTOPREF_QUEUE_DEPTH) - 1;
5747 if (n_stalls > max_insn_queue_index)
5748 n_stalls = max_insn_queue_index;
5750 for (int stalls = 1; stalls <= n_stalls; ++stalls)
5752 for (rtx_insn_list *link = insn_queue[NEXT_Q_AFTER (q_ptr, stalls)];
5753 link != NULL_RTX;
5754 link = link->next ())
5756 rtx_insn *insn2 = link->insn ();
5757 r = autopref_multipass_dfa_lookahead_guard_1 (insn1, insn2,
5758 write);
5759 if (r)
5761 /* Queue INSN1 until INSN2 can issue. */
5762 r = -stalls;
5763 if (ready_index == 0)
5764 data1->status = AUTOPREF_MULTIPASS_DATA_DONT_DELAY;
5765 goto finish;
5771 finish:
5772 if (sched_verbose >= 2
5773 && autopref_multipass_dfa_lookahead_guard_started_dump_p
5774 && (ready_index == ready.n_ready - 1 || r < 0))
5775 /* This does not /always/ trigger. We don't output EOL if the last
5776 insn is not recognized (INSN_CODE < 0) and lookahead_guard is not
5777 called. We can live with this. */
5778 fprintf (sched_dump, "\n");
5780 return r;
5783 /* Define type for target data used in multipass scheduling. */
5784 #ifndef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T
5785 # define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T int
5786 #endif
5787 typedef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DATA_T first_cycle_multipass_data_t;
5789 /* The following structure describe an entry of the stack of choices. */
5790 struct choice_entry
5792 /* Ordinal number of the issued insn in the ready queue. */
5793 int index;
5794 /* The number of the rest insns whose issues we should try. */
5795 int rest;
5796 /* The number of issued essential insns. */
5797 int n;
5798 /* State after issuing the insn. */
5799 state_t state;
5800 /* Target-specific data. */
5801 first_cycle_multipass_data_t target_data;
5804 /* The following array is used to implement a stack of choices used in
5805 function max_issue. */
5806 static struct choice_entry *choice_stack;
5808 /* This holds the value of the target dfa_lookahead hook. */
5809 int dfa_lookahead;
5811 /* The following variable value is maximal number of tries of issuing
5812 insns for the first cycle multipass insn scheduling. We define
5813 this value as constant*(DFA_LOOKAHEAD**ISSUE_RATE). We would not
5814 need this constraint if all real insns (with non-negative codes)
5815 had reservations because in this case the algorithm complexity is
5816 O(DFA_LOOKAHEAD**ISSUE_RATE). Unfortunately, the dfa descriptions
5817 might be incomplete and such insn might occur. For such
5818 descriptions, the complexity of algorithm (without the constraint)
5819 could achieve DFA_LOOKAHEAD ** N , where N is the queue length. */
5820 static int max_lookahead_tries;
5822 /* The following function returns maximal (or close to maximal) number
5823 of insns which can be issued on the same cycle and one of which
5824 insns is insns with the best rank (the first insn in READY). To
5825 make this function tries different samples of ready insns. READY
5826 is current queue `ready'. Global array READY_TRY reflects what
5827 insns are already issued in this try. The function stops immediately,
5828 if it reached the such a solution, that all instruction can be issued.
5829 INDEX will contain index of the best insn in READY. The following
5830 function is used only for first cycle multipass scheduling.
5832 PRIVILEGED_N >= 0
5834 This function expects recognized insns only. All USEs,
5835 CLOBBERs, etc must be filtered elsewhere. */
5837 max_issue (struct ready_list *ready, int privileged_n, state_t state,
5838 bool first_cycle_insn_p, int *index)
5840 int n, i, all, n_ready, best, delay, tries_num;
5841 int more_issue;
5842 struct choice_entry *top;
5843 rtx_insn *insn;
5845 if (sched_fusion)
5846 return 0;
5848 n_ready = ready->n_ready;
5849 gcc_assert (dfa_lookahead >= 1 && privileged_n >= 0
5850 && privileged_n <= n_ready);
5852 /* Init MAX_LOOKAHEAD_TRIES. */
5853 if (max_lookahead_tries == 0)
5855 max_lookahead_tries = 100;
5856 for (i = 0; i < issue_rate; i++)
5857 max_lookahead_tries *= dfa_lookahead;
5860 /* Init max_points. */
5861 more_issue = issue_rate - cycle_issued_insns;
5862 gcc_assert (more_issue >= 0);
5864 /* The number of the issued insns in the best solution. */
5865 best = 0;
5867 top = choice_stack;
5869 /* Set initial state of the search. */
5870 memcpy (top->state, state, dfa_state_size);
5871 top->rest = dfa_lookahead;
5872 top->n = 0;
5873 if (targetm.sched.first_cycle_multipass_begin)
5874 targetm.sched.first_cycle_multipass_begin (&top->target_data,
5875 ready_try, n_ready,
5876 first_cycle_insn_p);
5878 /* Count the number of the insns to search among. */
5879 for (all = i = 0; i < n_ready; i++)
5880 if (!ready_try [i])
5881 all++;
5883 if (sched_verbose >= 2)
5885 fprintf (sched_dump, ";;\t\tmax_issue among %d insns:", all);
5886 debug_ready_list_1 (ready, ready_try);
5889 /* I is the index of the insn to try next. */
5890 i = 0;
5891 tries_num = 0;
5892 for (;;)
5894 if (/* If we've reached a dead end or searched enough of what we have
5895 been asked... */
5896 top->rest == 0
5897 /* or have nothing else to try... */
5898 || i >= n_ready
5899 /* or should not issue more. */
5900 || top->n >= more_issue)
5902 /* ??? (... || i == n_ready). */
5903 gcc_assert (i <= n_ready);
5905 /* We should not issue more than issue_rate instructions. */
5906 gcc_assert (top->n <= more_issue);
5908 if (top == choice_stack)
5909 break;
5911 if (best < top - choice_stack)
5913 if (privileged_n)
5915 n = privileged_n;
5916 /* Try to find issued privileged insn. */
5917 while (n && !ready_try[--n])
5921 if (/* If all insns are equally good... */
5922 privileged_n == 0
5923 /* Or a privileged insn will be issued. */
5924 || ready_try[n])
5925 /* Then we have a solution. */
5927 best = top - choice_stack;
5928 /* This is the index of the insn issued first in this
5929 solution. */
5930 *index = choice_stack [1].index;
5931 if (top->n == more_issue || best == all)
5932 break;
5936 /* Set ready-list index to point to the last insn
5937 ('i++' below will advance it to the next insn). */
5938 i = top->index;
5940 /* Backtrack. */
5941 ready_try [i] = 0;
5943 if (targetm.sched.first_cycle_multipass_backtrack)
5944 targetm.sched.first_cycle_multipass_backtrack (&top->target_data,
5945 ready_try, n_ready);
5947 top--;
5948 memcpy (state, top->state, dfa_state_size);
5950 else if (!ready_try [i])
5952 tries_num++;
5953 if (tries_num > max_lookahead_tries)
5954 break;
5955 insn = ready_element (ready, i);
5956 delay = state_transition (state, insn);
5957 if (delay < 0)
5959 if (state_dead_lock_p (state)
5960 || insn_finishes_cycle_p (insn))
5961 /* We won't issue any more instructions in the next
5962 choice_state. */
5963 top->rest = 0;
5964 else
5965 top->rest--;
5967 n = top->n;
5968 if (memcmp (top->state, state, dfa_state_size) != 0)
5969 n++;
5971 /* Advance to the next choice_entry. */
5972 top++;
5973 /* Initialize it. */
5974 top->rest = dfa_lookahead;
5975 top->index = i;
5976 top->n = n;
5977 memcpy (top->state, state, dfa_state_size);
5978 ready_try [i] = 1;
5980 if (targetm.sched.first_cycle_multipass_issue)
5981 targetm.sched.first_cycle_multipass_issue (&top->target_data,
5982 ready_try, n_ready,
5983 insn,
5984 &((top - 1)
5985 ->target_data));
5987 i = -1;
5991 /* Increase ready-list index. */
5992 i++;
5995 if (targetm.sched.first_cycle_multipass_end)
5996 targetm.sched.first_cycle_multipass_end (best != 0
5997 ? &choice_stack[1].target_data
5998 : NULL);
6000 /* Restore the original state of the DFA. */
6001 memcpy (state, choice_stack->state, dfa_state_size);
6003 return best;
6006 /* The following function chooses insn from READY and modifies
6007 READY. The following function is used only for first
6008 cycle multipass scheduling.
6009 Return:
6010 -1 if cycle should be advanced,
6011 0 if INSN_PTR is set to point to the desirable insn,
6012 1 if choose_ready () should be restarted without advancing the cycle. */
6013 static int
6014 choose_ready (struct ready_list *ready, bool first_cycle_insn_p,
6015 rtx_insn **insn_ptr)
6017 if (dbg_cnt (sched_insn) == false)
6019 if (nonscheduled_insns_begin == NULL_RTX)
6020 nonscheduled_insns_begin = current_sched_info->prev_head;
6022 rtx_insn *insn = first_nonscheduled_insn ();
6024 if (QUEUE_INDEX (insn) == QUEUE_READY)
6025 /* INSN is in the ready_list. */
6027 ready_remove_insn (insn);
6028 *insn_ptr = insn;
6029 return 0;
6032 /* INSN is in the queue. Advance cycle to move it to the ready list. */
6033 gcc_assert (QUEUE_INDEX (insn) >= 0);
6034 return -1;
6037 if (dfa_lookahead <= 0 || SCHED_GROUP_P (ready_element (ready, 0))
6038 || DEBUG_INSN_P (ready_element (ready, 0)))
6040 if (targetm.sched.dispatch (NULL, IS_DISPATCH_ON))
6041 *insn_ptr = ready_remove_first_dispatch (ready);
6042 else
6043 *insn_ptr = ready_remove_first (ready);
6045 return 0;
6047 else
6049 /* Try to choose the best insn. */
6050 int index = 0, i;
6051 rtx_insn *insn;
6053 insn = ready_element (ready, 0);
6054 if (INSN_CODE (insn) < 0)
6056 *insn_ptr = ready_remove_first (ready);
6057 return 0;
6060 /* Filter the search space. */
6061 for (i = 0; i < ready->n_ready; i++)
6063 ready_try[i] = 0;
6065 insn = ready_element (ready, i);
6067 /* If this insn is recognizable we should have already
6068 recognized it earlier.
6069 ??? Not very clear where this is supposed to be done.
6070 See dep_cost_1. */
6071 gcc_checking_assert (INSN_CODE (insn) >= 0
6072 || recog_memoized (insn) < 0);
6073 if (INSN_CODE (insn) < 0)
6075 /* Non-recognized insns at position 0 are handled above. */
6076 gcc_assert (i > 0);
6077 ready_try[i] = 1;
6078 continue;
6081 if (targetm.sched.first_cycle_multipass_dfa_lookahead_guard)
6083 ready_try[i]
6084 = (targetm.sched.first_cycle_multipass_dfa_lookahead_guard
6085 (insn, i));
6087 if (ready_try[i] < 0)
6088 /* Queue instruction for several cycles.
6089 We need to restart choose_ready as we have changed
6090 the ready list. */
6092 change_queue_index (insn, -ready_try[i]);
6093 return 1;
6096 /* Make sure that we didn't end up with 0'th insn filtered out.
6097 Don't be tempted to make life easier for backends and just
6098 requeue 0'th insn if (ready_try[0] == 0) and restart
6099 choose_ready. Backends should be very considerate about
6100 requeueing instructions -- especially the highest priority
6101 one at position 0. */
6102 gcc_assert (ready_try[i] == 0 || i > 0);
6103 if (ready_try[i])
6104 continue;
6107 gcc_assert (ready_try[i] == 0);
6108 /* INSN made it through the scrutiny of filters! */
6111 if (max_issue (ready, 1, curr_state, first_cycle_insn_p, &index) == 0)
6113 *insn_ptr = ready_remove_first (ready);
6114 if (sched_verbose >= 4)
6115 fprintf (sched_dump, ";;\t\tChosen insn (but can't issue) : %s \n",
6116 (*current_sched_info->print_insn) (*insn_ptr, 0));
6117 return 0;
6119 else
6121 if (sched_verbose >= 4)
6122 fprintf (sched_dump, ";;\t\tChosen insn : %s\n",
6123 (*current_sched_info->print_insn)
6124 (ready_element (ready, index), 0));
6126 *insn_ptr = ready_remove (ready, index);
6127 return 0;
6132 /* This function is called when we have successfully scheduled a
6133 block. It uses the schedule stored in the scheduled_insns vector
6134 to rearrange the RTL. PREV_HEAD is used as the anchor to which we
6135 append the scheduled insns; TAIL is the insn after the scheduled
6136 block. TARGET_BB is the argument passed to schedule_block. */
6138 static void
6139 commit_schedule (rtx_insn *prev_head, rtx_insn *tail, basic_block *target_bb)
6141 unsigned int i;
6142 rtx_insn *insn;
6144 last_scheduled_insn = prev_head;
6145 for (i = 0;
6146 scheduled_insns.iterate (i, &insn);
6147 i++)
6149 if (control_flow_insn_p (last_scheduled_insn)
6150 || current_sched_info->advance_target_bb (*target_bb, insn))
6152 *target_bb = current_sched_info->advance_target_bb (*target_bb, 0);
6154 if (sched_verbose)
6156 rtx_insn *x;
6158 x = next_real_insn (last_scheduled_insn);
6159 gcc_assert (x);
6160 dump_new_block_header (1, *target_bb, x, tail);
6163 last_scheduled_insn = bb_note (*target_bb);
6166 if (current_sched_info->begin_move_insn)
6167 (*current_sched_info->begin_move_insn) (insn, last_scheduled_insn);
6168 move_insn (insn, last_scheduled_insn,
6169 current_sched_info->next_tail);
6170 if (!DEBUG_INSN_P (insn))
6171 reemit_notes (insn);
6172 last_scheduled_insn = insn;
6175 scheduled_insns.truncate (0);
6178 /* Examine all insns on the ready list and queue those which can't be
6179 issued in this cycle. TEMP_STATE is temporary scheduler state we
6180 can use as scratch space. If FIRST_CYCLE_INSN_P is true, no insns
6181 have been issued for the current cycle, which means it is valid to
6182 issue an asm statement.
6184 If SHADOWS_ONLY_P is true, we eliminate all real insns and only
6185 leave those for which SHADOW_P is true. If MODULO_EPILOGUE is true,
6186 we only leave insns which have an INSN_EXACT_TICK. */
6188 static void
6189 prune_ready_list (state_t temp_state, bool first_cycle_insn_p,
6190 bool shadows_only_p, bool modulo_epilogue_p)
6192 int i, pass;
6193 bool sched_group_found = false;
6194 int min_cost_group = 1;
6196 if (sched_fusion)
6197 return;
6199 for (i = 0; i < ready.n_ready; i++)
6201 rtx_insn *insn = ready_element (&ready, i);
6202 if (SCHED_GROUP_P (insn))
6204 sched_group_found = true;
6205 break;
6209 /* Make two passes if there's a SCHED_GROUP_P insn; make sure to handle
6210 such an insn first and note its cost, then schedule all other insns
6211 for one cycle later. */
6212 for (pass = sched_group_found ? 0 : 1; pass < 2; )
6214 int n = ready.n_ready;
6215 for (i = 0; i < n; i++)
6217 rtx_insn *insn = ready_element (&ready, i);
6218 int cost = 0;
6219 const char *reason = "resource conflict";
6221 if (DEBUG_INSN_P (insn))
6222 continue;
6224 if (sched_group_found && !SCHED_GROUP_P (insn))
6226 if (pass == 0)
6227 continue;
6228 cost = min_cost_group;
6229 reason = "not in sched group";
6231 else if (modulo_epilogue_p
6232 && INSN_EXACT_TICK (insn) == INVALID_TICK)
6234 cost = max_insn_queue_index;
6235 reason = "not an epilogue insn";
6237 else if (shadows_only_p && !SHADOW_P (insn))
6239 cost = 1;
6240 reason = "not a shadow";
6242 else if (recog_memoized (insn) < 0)
6244 if (!first_cycle_insn_p
6245 && (GET_CODE (PATTERN (insn)) == ASM_INPUT
6246 || asm_noperands (PATTERN (insn)) >= 0))
6247 cost = 1;
6248 reason = "asm";
6250 else if (sched_pressure != SCHED_PRESSURE_NONE)
6252 if (sched_pressure == SCHED_PRESSURE_MODEL
6253 && INSN_TICK (insn) <= clock_var)
6255 memcpy (temp_state, curr_state, dfa_state_size);
6256 if (state_transition (temp_state, insn) >= 0)
6257 INSN_TICK (insn) = clock_var + 1;
6259 cost = 0;
6261 else
6263 int delay_cost = 0;
6265 if (delay_htab)
6267 struct delay_pair *delay_entry;
6268 delay_entry
6269 = delay_htab->find_with_hash (insn,
6270 htab_hash_pointer (insn));
6271 while (delay_entry && delay_cost == 0)
6273 delay_cost = estimate_shadow_tick (delay_entry);
6274 if (delay_cost > max_insn_queue_index)
6275 delay_cost = max_insn_queue_index;
6276 delay_entry = delay_entry->next_same_i1;
6280 memcpy (temp_state, curr_state, dfa_state_size);
6281 cost = state_transition (temp_state, insn);
6282 if (cost < 0)
6283 cost = 0;
6284 else if (cost == 0)
6285 cost = 1;
6286 if (cost < delay_cost)
6288 cost = delay_cost;
6289 reason = "shadow tick";
6292 if (cost >= 1)
6294 if (SCHED_GROUP_P (insn) && cost > min_cost_group)
6295 min_cost_group = cost;
6296 ready_remove (&ready, i);
6297 /* Normally we'd want to queue INSN for COST cycles. However,
6298 if SCHED_GROUP_P is set, then we must ensure that nothing
6299 else comes between INSN and its predecessor. If there is
6300 some other insn ready to fire on the next cycle, then that
6301 invariant would be broken.
6303 So when SCHED_GROUP_P is set, just queue this insn for a
6304 single cycle. */
6305 queue_insn (insn, SCHED_GROUP_P (insn) ? 1 : cost, reason);
6306 if (i + 1 < n)
6307 break;
6310 if (i == n)
6311 pass++;
6315 /* Called when we detect that the schedule is impossible. We examine the
6316 backtrack queue to find the earliest insn that caused this condition. */
6318 static struct haifa_saved_data *
6319 verify_shadows (void)
6321 struct haifa_saved_data *save, *earliest_fail = NULL;
6322 for (save = backtrack_queue; save; save = save->next)
6324 int t;
6325 struct delay_pair *pair = save->delay_pair;
6326 rtx_insn *i1 = pair->i1;
6328 for (; pair; pair = pair->next_same_i1)
6330 rtx_insn *i2 = pair->i2;
6332 if (QUEUE_INDEX (i2) == QUEUE_SCHEDULED)
6333 continue;
6335 t = INSN_TICK (i1) + pair_delay (pair);
6336 if (t < clock_var)
6338 if (sched_verbose >= 2)
6339 fprintf (sched_dump,
6340 ";;\t\tfailed delay requirements for %d/%d (%d->%d)"
6341 ", not ready\n",
6342 INSN_UID (pair->i1), INSN_UID (pair->i2),
6343 INSN_TICK (pair->i1), INSN_EXACT_TICK (pair->i2));
6344 earliest_fail = save;
6345 break;
6347 if (QUEUE_INDEX (i2) >= 0)
6349 int queued_for = INSN_TICK (i2);
6351 if (t < queued_for)
6353 if (sched_verbose >= 2)
6354 fprintf (sched_dump,
6355 ";;\t\tfailed delay requirements for %d/%d"
6356 " (%d->%d), queued too late\n",
6357 INSN_UID (pair->i1), INSN_UID (pair->i2),
6358 INSN_TICK (pair->i1), INSN_EXACT_TICK (pair->i2));
6359 earliest_fail = save;
6360 break;
6366 return earliest_fail;
6369 /* Print instructions together with useful scheduling information between
6370 HEAD and TAIL (inclusive). */
6371 static void
6372 dump_insn_stream (rtx_insn *head, rtx_insn *tail)
6374 fprintf (sched_dump, ";;\t| insn | prio |\n");
6376 rtx_insn *next_tail = NEXT_INSN (tail);
6377 for (rtx_insn *insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6379 int priority = NOTE_P (insn) ? 0 : INSN_PRIORITY (insn);
6380 const char *pattern = (NOTE_P (insn)
6381 ? "note"
6382 : str_pattern_slim (PATTERN (insn)));
6384 fprintf (sched_dump, ";;\t| %4d | %4d | %-30s ",
6385 INSN_UID (insn), priority, pattern);
6387 if (sched_verbose >= 4)
6389 if (NOTE_P (insn) || recog_memoized (insn) < 0)
6390 fprintf (sched_dump, "nothing");
6391 else
6392 print_reservation (sched_dump, insn);
6394 fprintf (sched_dump, "\n");
6398 /* Use forward list scheduling to rearrange insns of block pointed to by
6399 TARGET_BB, possibly bringing insns from subsequent blocks in the same
6400 region. */
6402 bool
6403 schedule_block (basic_block *target_bb, state_t init_state)
6405 int i;
6406 bool success = modulo_ii == 0;
6407 struct sched_block_state ls;
6408 state_t temp_state = NULL; /* It is used for multipass scheduling. */
6409 int sort_p, advance, start_clock_var;
6411 /* Head/tail info for this block. */
6412 rtx_insn *prev_head = current_sched_info->prev_head;
6413 rtx_insn *next_tail = current_sched_info->next_tail;
6414 rtx_insn *head = NEXT_INSN (prev_head);
6415 rtx_insn *tail = PREV_INSN (next_tail);
6417 if ((current_sched_info->flags & DONT_BREAK_DEPENDENCIES) == 0
6418 && sched_pressure != SCHED_PRESSURE_MODEL && !sched_fusion)
6419 find_modifiable_mems (head, tail);
6421 /* We used to have code to avoid getting parameters moved from hard
6422 argument registers into pseudos.
6424 However, it was removed when it proved to be of marginal benefit
6425 and caused problems because schedule_block and compute_forward_dependences
6426 had different notions of what the "head" insn was. */
6428 gcc_assert (head != tail || INSN_P (head));
6430 haifa_recovery_bb_recently_added_p = false;
6432 backtrack_queue = NULL;
6434 /* Debug info. */
6435 if (sched_verbose)
6437 dump_new_block_header (0, *target_bb, head, tail);
6439 if (sched_verbose >= 2)
6441 dump_insn_stream (head, tail);
6442 memset (&rank_for_schedule_stats, 0,
6443 sizeof (rank_for_schedule_stats));
6447 if (init_state == NULL)
6448 state_reset (curr_state);
6449 else
6450 memcpy (curr_state, init_state, dfa_state_size);
6452 /* Clear the ready list. */
6453 ready.first = ready.veclen - 1;
6454 ready.n_ready = 0;
6455 ready.n_debug = 0;
6457 /* It is used for first cycle multipass scheduling. */
6458 temp_state = alloca (dfa_state_size);
6460 if (targetm.sched.init)
6461 targetm.sched.init (sched_dump, sched_verbose, ready.veclen);
6463 /* We start inserting insns after PREV_HEAD. */
6464 last_scheduled_insn = prev_head;
6465 last_nondebug_scheduled_insn = NULL;
6466 nonscheduled_insns_begin = NULL;
6468 gcc_assert ((NOTE_P (last_scheduled_insn)
6469 || DEBUG_INSN_P (last_scheduled_insn))
6470 && BLOCK_FOR_INSN (last_scheduled_insn) == *target_bb);
6472 /* Initialize INSN_QUEUE. Q_SIZE is the total number of insns in the
6473 queue. */
6474 q_ptr = 0;
6475 q_size = 0;
6477 insn_queue = XALLOCAVEC (rtx_insn_list *, max_insn_queue_index + 1);
6478 memset (insn_queue, 0, (max_insn_queue_index + 1) * sizeof (rtx));
6480 /* Start just before the beginning of time. */
6481 clock_var = -1;
6483 /* We need queue and ready lists and clock_var be initialized
6484 in try_ready () (which is called through init_ready_list ()). */
6485 (*current_sched_info->init_ready_list) ();
6487 if (sched_pressure)
6488 sched_pressure_start_bb (*target_bb);
6490 /* The algorithm is O(n^2) in the number of ready insns at any given
6491 time in the worst case. Before reload we are more likely to have
6492 big lists so truncate them to a reasonable size. */
6493 if (!reload_completed
6494 && ready.n_ready - ready.n_debug > MAX_SCHED_READY_INSNS)
6496 ready_sort_debug (&ready);
6497 ready_sort_real (&ready);
6499 /* Find first free-standing insn past MAX_SCHED_READY_INSNS.
6500 If there are debug insns, we know they're first. */
6501 for (i = MAX_SCHED_READY_INSNS + ready.n_debug; i < ready.n_ready; i++)
6502 if (!SCHED_GROUP_P (ready_element (&ready, i)))
6503 break;
6505 if (sched_verbose >= 2)
6507 fprintf (sched_dump,
6508 ";;\t\tReady list on entry: %d insns: ", ready.n_ready);
6509 debug_ready_list (&ready);
6510 fprintf (sched_dump,
6511 ";;\t\t before reload => truncated to %d insns\n", i);
6514 /* Delay all insns past it for 1 cycle. If debug counter is
6515 activated make an exception for the insn right after
6516 nonscheduled_insns_begin. */
6518 rtx_insn *skip_insn;
6520 if (dbg_cnt (sched_insn) == false)
6521 skip_insn = first_nonscheduled_insn ();
6522 else
6523 skip_insn = NULL;
6525 while (i < ready.n_ready)
6527 rtx_insn *insn;
6529 insn = ready_remove (&ready, i);
6531 if (insn != skip_insn)
6532 queue_insn (insn, 1, "list truncated");
6534 if (skip_insn)
6535 ready_add (&ready, skip_insn, true);
6539 /* Now we can restore basic block notes and maintain precise cfg. */
6540 restore_bb_notes (*target_bb);
6542 last_clock_var = -1;
6544 advance = 0;
6546 gcc_assert (scheduled_insns.length () == 0);
6547 sort_p = TRUE;
6548 must_backtrack = false;
6549 modulo_insns_scheduled = 0;
6551 ls.modulo_epilogue = false;
6552 ls.first_cycle_insn_p = true;
6554 /* Loop until all the insns in BB are scheduled. */
6555 while ((*current_sched_info->schedule_more_p) ())
6557 perform_replacements_new_cycle ();
6560 start_clock_var = clock_var;
6562 clock_var++;
6564 advance_one_cycle ();
6566 /* Add to the ready list all pending insns that can be issued now.
6567 If there are no ready insns, increment clock until one
6568 is ready and add all pending insns at that point to the ready
6569 list. */
6570 queue_to_ready (&ready);
6572 gcc_assert (ready.n_ready);
6574 if (sched_verbose >= 2)
6576 fprintf (sched_dump, ";;\t\tReady list after queue_to_ready:");
6577 debug_ready_list (&ready);
6579 advance -= clock_var - start_clock_var;
6581 while (advance > 0);
6583 if (ls.modulo_epilogue)
6585 int stage = clock_var / modulo_ii;
6586 if (stage > modulo_last_stage * 2 + 2)
6588 if (sched_verbose >= 2)
6589 fprintf (sched_dump,
6590 ";;\t\tmodulo scheduled succeeded at II %d\n",
6591 modulo_ii);
6592 success = true;
6593 goto end_schedule;
6596 else if (modulo_ii > 0)
6598 int stage = clock_var / modulo_ii;
6599 if (stage > modulo_max_stages)
6601 if (sched_verbose >= 2)
6602 fprintf (sched_dump,
6603 ";;\t\tfailing schedule due to excessive stages\n");
6604 goto end_schedule;
6606 if (modulo_n_insns == modulo_insns_scheduled
6607 && stage > modulo_last_stage)
6609 if (sched_verbose >= 2)
6610 fprintf (sched_dump,
6611 ";;\t\tfound kernel after %d stages, II %d\n",
6612 stage, modulo_ii);
6613 ls.modulo_epilogue = true;
6617 prune_ready_list (temp_state, true, false, ls.modulo_epilogue);
6618 if (ready.n_ready == 0)
6619 continue;
6620 if (must_backtrack)
6621 goto do_backtrack;
6623 ls.shadows_only_p = false;
6624 cycle_issued_insns = 0;
6625 ls.can_issue_more = issue_rate;
6626 for (;;)
6628 rtx_insn *insn;
6629 int cost;
6630 bool asm_p;
6632 if (sort_p && ready.n_ready > 0)
6634 /* Sort the ready list based on priority. This must be
6635 done every iteration through the loop, as schedule_insn
6636 may have readied additional insns that will not be
6637 sorted correctly. */
6638 ready_sort (&ready);
6640 if (sched_verbose >= 2)
6642 fprintf (sched_dump,
6643 ";;\t\tReady list after ready_sort: ");
6644 debug_ready_list (&ready);
6648 /* We don't want md sched reorder to even see debug isns, so put
6649 them out right away. */
6650 if (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0))
6651 && (*current_sched_info->schedule_more_p) ())
6653 while (ready.n_ready && DEBUG_INSN_P (ready_element (&ready, 0)))
6655 rtx_insn *insn = ready_remove_first (&ready);
6656 gcc_assert (DEBUG_INSN_P (insn));
6657 (*current_sched_info->begin_schedule_ready) (insn);
6658 scheduled_insns.safe_push (insn);
6659 last_scheduled_insn = insn;
6660 advance = schedule_insn (insn);
6661 gcc_assert (advance == 0);
6662 if (ready.n_ready > 0)
6663 ready_sort (&ready);
6667 if (ls.first_cycle_insn_p && !ready.n_ready)
6668 break;
6670 resume_after_backtrack:
6671 /* Allow the target to reorder the list, typically for
6672 better instruction bundling. */
6673 if (sort_p
6674 && (ready.n_ready == 0
6675 || !SCHED_GROUP_P (ready_element (&ready, 0))))
6677 if (ls.first_cycle_insn_p && targetm.sched.reorder)
6678 ls.can_issue_more
6679 = targetm.sched.reorder (sched_dump, sched_verbose,
6680 ready_lastpos (&ready),
6681 &ready.n_ready, clock_var);
6682 else if (!ls.first_cycle_insn_p && targetm.sched.reorder2)
6683 ls.can_issue_more
6684 = targetm.sched.reorder2 (sched_dump, sched_verbose,
6685 ready.n_ready
6686 ? ready_lastpos (&ready) : NULL,
6687 &ready.n_ready, clock_var);
6690 restart_choose_ready:
6691 if (sched_verbose >= 2)
6693 fprintf (sched_dump, ";;\tReady list (t = %3d): ",
6694 clock_var);
6695 debug_ready_list (&ready);
6696 if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
6697 print_curr_reg_pressure ();
6700 if (ready.n_ready == 0
6701 && ls.can_issue_more
6702 && reload_completed)
6704 /* Allow scheduling insns directly from the queue in case
6705 there's nothing better to do (ready list is empty) but
6706 there are still vacant dispatch slots in the current cycle. */
6707 if (sched_verbose >= 6)
6708 fprintf (sched_dump,";;\t\tSecond chance\n");
6709 memcpy (temp_state, curr_state, dfa_state_size);
6710 if (early_queue_to_ready (temp_state, &ready))
6711 ready_sort (&ready);
6714 if (ready.n_ready == 0
6715 || !ls.can_issue_more
6716 || state_dead_lock_p (curr_state)
6717 || !(*current_sched_info->schedule_more_p) ())
6718 break;
6720 /* Select and remove the insn from the ready list. */
6721 if (sort_p)
6723 int res;
6725 insn = NULL;
6726 res = choose_ready (&ready, ls.first_cycle_insn_p, &insn);
6728 if (res < 0)
6729 /* Finish cycle. */
6730 break;
6731 if (res > 0)
6732 goto restart_choose_ready;
6734 gcc_assert (insn != NULL_RTX);
6736 else
6737 insn = ready_remove_first (&ready);
6739 if (sched_pressure != SCHED_PRESSURE_NONE
6740 && INSN_TICK (insn) > clock_var)
6742 ready_add (&ready, insn, true);
6743 advance = 1;
6744 break;
6747 if (targetm.sched.dfa_new_cycle
6748 && targetm.sched.dfa_new_cycle (sched_dump, sched_verbose,
6749 insn, last_clock_var,
6750 clock_var, &sort_p))
6751 /* SORT_P is used by the target to override sorting
6752 of the ready list. This is needed when the target
6753 has modified its internal structures expecting that
6754 the insn will be issued next. As we need the insn
6755 to have the highest priority (so it will be returned by
6756 the ready_remove_first call above), we invoke
6757 ready_add (&ready, insn, true).
6758 But, still, there is one issue: INSN can be later
6759 discarded by scheduler's front end through
6760 current_sched_info->can_schedule_ready_p, hence, won't
6761 be issued next. */
6763 ready_add (&ready, insn, true);
6764 break;
6767 sort_p = TRUE;
6769 if (current_sched_info->can_schedule_ready_p
6770 && ! (*current_sched_info->can_schedule_ready_p) (insn))
6771 /* We normally get here only if we don't want to move
6772 insn from the split block. */
6774 TODO_SPEC (insn) = DEP_POSTPONED;
6775 goto restart_choose_ready;
6778 if (delay_htab)
6780 /* If this insn is the first part of a delay-slot pair, record a
6781 backtrack point. */
6782 struct delay_pair *delay_entry;
6783 delay_entry
6784 = delay_htab->find_with_hash (insn, htab_hash_pointer (insn));
6785 if (delay_entry)
6787 save_backtrack_point (delay_entry, ls);
6788 if (sched_verbose >= 2)
6789 fprintf (sched_dump, ";;\t\tsaving backtrack point\n");
6793 /* DECISION is made. */
6795 if (modulo_ii > 0 && INSN_UID (insn) < modulo_iter0_max_uid)
6797 modulo_insns_scheduled++;
6798 modulo_last_stage = clock_var / modulo_ii;
6800 if (TODO_SPEC (insn) & SPECULATIVE)
6801 generate_recovery_code (insn);
6803 if (targetm.sched.dispatch (NULL, IS_DISPATCH_ON))
6804 targetm.sched.dispatch_do (insn, ADD_TO_DISPATCH_WINDOW);
6806 /* Update counters, etc in the scheduler's front end. */
6807 (*current_sched_info->begin_schedule_ready) (insn);
6808 scheduled_insns.safe_push (insn);
6809 gcc_assert (NONDEBUG_INSN_P (insn));
6810 last_nondebug_scheduled_insn = last_scheduled_insn = insn;
6812 if (recog_memoized (insn) >= 0)
6814 memcpy (temp_state, curr_state, dfa_state_size);
6815 cost = state_transition (curr_state, insn);
6816 if (sched_pressure != SCHED_PRESSURE_WEIGHTED && !sched_fusion)
6817 gcc_assert (cost < 0);
6818 if (memcmp (temp_state, curr_state, dfa_state_size) != 0)
6819 cycle_issued_insns++;
6820 asm_p = false;
6822 else
6823 asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
6824 || asm_noperands (PATTERN (insn)) >= 0);
6826 if (targetm.sched.variable_issue)
6827 ls.can_issue_more =
6828 targetm.sched.variable_issue (sched_dump, sched_verbose,
6829 insn, ls.can_issue_more);
6830 /* A naked CLOBBER or USE generates no instruction, so do
6831 not count them against the issue rate. */
6832 else if (GET_CODE (PATTERN (insn)) != USE
6833 && GET_CODE (PATTERN (insn)) != CLOBBER)
6834 ls.can_issue_more--;
6835 advance = schedule_insn (insn);
6837 if (SHADOW_P (insn))
6838 ls.shadows_only_p = true;
6840 /* After issuing an asm insn we should start a new cycle. */
6841 if (advance == 0 && asm_p)
6842 advance = 1;
6844 if (must_backtrack)
6845 break;
6847 if (advance != 0)
6848 break;
6850 ls.first_cycle_insn_p = false;
6851 if (ready.n_ready > 0)
6852 prune_ready_list (temp_state, false, ls.shadows_only_p,
6853 ls.modulo_epilogue);
6856 do_backtrack:
6857 if (!must_backtrack)
6858 for (i = 0; i < ready.n_ready; i++)
6860 rtx_insn *insn = ready_element (&ready, i);
6861 if (INSN_EXACT_TICK (insn) == clock_var)
6863 must_backtrack = true;
6864 clock_var++;
6865 break;
6868 if (must_backtrack && modulo_ii > 0)
6870 if (modulo_backtracks_left == 0)
6871 goto end_schedule;
6872 modulo_backtracks_left--;
6874 while (must_backtrack)
6876 struct haifa_saved_data *failed;
6877 rtx_insn *failed_insn;
6879 must_backtrack = false;
6880 failed = verify_shadows ();
6881 gcc_assert (failed);
6883 failed_insn = failed->delay_pair->i1;
6884 /* Clear these queues. */
6885 perform_replacements_new_cycle ();
6886 toggle_cancelled_flags (false);
6887 unschedule_insns_until (failed_insn);
6888 while (failed != backtrack_queue)
6889 free_topmost_backtrack_point (true);
6890 restore_last_backtrack_point (&ls);
6891 if (sched_verbose >= 2)
6892 fprintf (sched_dump, ";;\t\trewind to cycle %d\n", clock_var);
6893 /* Delay by at least a cycle. This could cause additional
6894 backtracking. */
6895 queue_insn (failed_insn, 1, "backtracked");
6896 advance = 0;
6897 if (must_backtrack)
6898 continue;
6899 if (ready.n_ready > 0)
6900 goto resume_after_backtrack;
6901 else
6903 if (clock_var == 0 && ls.first_cycle_insn_p)
6904 goto end_schedule;
6905 advance = 1;
6906 break;
6909 ls.first_cycle_insn_p = true;
6911 if (ls.modulo_epilogue)
6912 success = true;
6913 end_schedule:
6914 if (!ls.first_cycle_insn_p || advance)
6915 advance_one_cycle ();
6916 perform_replacements_new_cycle ();
6917 if (modulo_ii > 0)
6919 /* Once again, debug insn suckiness: they can be on the ready list
6920 even if they have unresolved dependencies. To make our view
6921 of the world consistent, remove such "ready" insns. */
6922 restart_debug_insn_loop:
6923 for (i = ready.n_ready - 1; i >= 0; i--)
6925 rtx_insn *x;
6927 x = ready_element (&ready, i);
6928 if (DEPS_LIST_FIRST (INSN_HARD_BACK_DEPS (x)) != NULL
6929 || DEPS_LIST_FIRST (INSN_SPEC_BACK_DEPS (x)) != NULL)
6931 ready_remove (&ready, i);
6932 goto restart_debug_insn_loop;
6935 for (i = ready.n_ready - 1; i >= 0; i--)
6937 rtx_insn *x;
6939 x = ready_element (&ready, i);
6940 resolve_dependencies (x);
6942 for (i = 0; i <= max_insn_queue_index; i++)
6944 rtx_insn_list *link;
6945 while ((link = insn_queue[i]) != NULL)
6947 rtx_insn *x = link->insn ();
6948 insn_queue[i] = link->next ();
6949 QUEUE_INDEX (x) = QUEUE_NOWHERE;
6950 free_INSN_LIST_node (link);
6951 resolve_dependencies (x);
6956 if (!success)
6957 undo_all_replacements ();
6959 /* Debug info. */
6960 if (sched_verbose)
6962 fprintf (sched_dump, ";;\tReady list (final): ");
6963 debug_ready_list (&ready);
6966 if (modulo_ii == 0 && current_sched_info->queue_must_finish_empty)
6967 /* Sanity check -- queue must be empty now. Meaningless if region has
6968 multiple bbs. */
6969 gcc_assert (!q_size && !ready.n_ready && !ready.n_debug);
6970 else if (modulo_ii == 0)
6972 /* We must maintain QUEUE_INDEX between blocks in region. */
6973 for (i = ready.n_ready - 1; i >= 0; i--)
6975 rtx_insn *x;
6977 x = ready_element (&ready, i);
6978 QUEUE_INDEX (x) = QUEUE_NOWHERE;
6979 TODO_SPEC (x) = HARD_DEP;
6982 if (q_size)
6983 for (i = 0; i <= max_insn_queue_index; i++)
6985 rtx_insn_list *link;
6986 for (link = insn_queue[i]; link; link = link->next ())
6988 rtx_insn *x;
6990 x = link->insn ();
6991 QUEUE_INDEX (x) = QUEUE_NOWHERE;
6992 TODO_SPEC (x) = HARD_DEP;
6994 free_INSN_LIST_list (&insn_queue[i]);
6998 if (sched_pressure == SCHED_PRESSURE_MODEL)
6999 model_end_schedule ();
7001 if (success)
7003 commit_schedule (prev_head, tail, target_bb);
7004 if (sched_verbose)
7005 fprintf (sched_dump, ";; total time = %d\n", clock_var);
7007 else
7008 last_scheduled_insn = tail;
7010 scheduled_insns.truncate (0);
7012 if (!current_sched_info->queue_must_finish_empty
7013 || haifa_recovery_bb_recently_added_p)
7015 /* INSN_TICK (minimum clock tick at which the insn becomes
7016 ready) may be not correct for the insn in the subsequent
7017 blocks of the region. We should use a correct value of
7018 `clock_var' or modify INSN_TICK. It is better to keep
7019 clock_var value equal to 0 at the start of a basic block.
7020 Therefore we modify INSN_TICK here. */
7021 fix_inter_tick (NEXT_INSN (prev_head), last_scheduled_insn);
7024 if (targetm.sched.finish)
7026 targetm.sched.finish (sched_dump, sched_verbose);
7027 /* Target might have added some instructions to the scheduled block
7028 in its md_finish () hook. These new insns don't have any data
7029 initialized and to identify them we extend h_i_d so that they'll
7030 get zero luids. */
7031 sched_extend_luids ();
7034 /* Update head/tail boundaries. */
7035 head = NEXT_INSN (prev_head);
7036 tail = last_scheduled_insn;
7038 if (sched_verbose)
7040 fprintf (sched_dump, ";; new head = %d\n;; new tail = %d\n",
7041 INSN_UID (head), INSN_UID (tail));
7043 if (sched_verbose >= 2)
7045 dump_insn_stream (head, tail);
7046 print_rank_for_schedule_stats (";; TOTAL ", &rank_for_schedule_stats,
7047 NULL);
7050 fprintf (sched_dump, "\n");
7053 head = restore_other_notes (head, NULL);
7055 current_sched_info->head = head;
7056 current_sched_info->tail = tail;
7058 free_backtrack_queue ();
7060 return success;
7063 /* Set_priorities: compute priority of each insn in the block. */
7066 set_priorities (rtx_insn *head, rtx_insn *tail)
7068 rtx_insn *insn;
7069 int n_insn;
7070 int sched_max_insns_priority =
7071 current_sched_info->sched_max_insns_priority;
7072 rtx_insn *prev_head;
7074 if (head == tail && ! INSN_P (head))
7075 gcc_unreachable ();
7077 n_insn = 0;
7079 prev_head = PREV_INSN (head);
7080 for (insn = tail; insn != prev_head; insn = PREV_INSN (insn))
7082 if (!INSN_P (insn))
7083 continue;
7085 n_insn++;
7086 (void) priority (insn);
7088 gcc_assert (INSN_PRIORITY_KNOWN (insn));
7090 sched_max_insns_priority = MAX (sched_max_insns_priority,
7091 INSN_PRIORITY (insn));
7094 current_sched_info->sched_max_insns_priority = sched_max_insns_priority;
7096 return n_insn;
7099 /* Set dump and sched_verbose for the desired debugging output. If no
7100 dump-file was specified, but -fsched-verbose=N (any N), print to stderr.
7101 For -fsched-verbose=N, N>=10, print everything to stderr. */
7102 void
7103 setup_sched_dump (void)
7105 sched_verbose = sched_verbose_param;
7106 if (sched_verbose_param == 0 && dump_file)
7107 sched_verbose = 1;
7108 sched_dump = ((sched_verbose_param >= 10 || !dump_file)
7109 ? stderr : dump_file);
7112 /* Allocate data for register pressure sensitive scheduling. */
7113 static void
7114 alloc_global_sched_pressure_data (void)
7116 if (sched_pressure != SCHED_PRESSURE_NONE)
7118 int i, max_regno = max_reg_num ();
7120 if (sched_dump != NULL)
7121 /* We need info about pseudos for rtl dumps about pseudo
7122 classes and costs. */
7123 regstat_init_n_sets_and_refs ();
7124 ira_set_pseudo_classes (true, sched_verbose ? sched_dump : NULL);
7125 sched_regno_pressure_class
7126 = (enum reg_class *) xmalloc (max_regno * sizeof (enum reg_class));
7127 for (i = 0; i < max_regno; i++)
7128 sched_regno_pressure_class[i]
7129 = (i < FIRST_PSEUDO_REGISTER
7130 ? ira_pressure_class_translate[REGNO_REG_CLASS (i)]
7131 : ira_pressure_class_translate[reg_allocno_class (i)]);
7132 curr_reg_live = BITMAP_ALLOC (NULL);
7133 if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
7135 saved_reg_live = BITMAP_ALLOC (NULL);
7136 region_ref_regs = BITMAP_ALLOC (NULL);
7139 /* Calculate number of CALL_USED_REGS in register classes that
7140 we calculate register pressure for. */
7141 for (int c = 0; c < ira_pressure_classes_num; ++c)
7143 enum reg_class cl = ira_pressure_classes[c];
7145 call_used_regs_num[cl] = 0;
7147 for (int i = 0; i < ira_class_hard_regs_num[cl]; ++i)
7148 if (call_used_regs[ira_class_hard_regs[cl][i]])
7149 ++call_used_regs_num[cl];
7154 /* Free data for register pressure sensitive scheduling. Also called
7155 from schedule_region when stopping sched-pressure early. */
7156 void
7157 free_global_sched_pressure_data (void)
7159 if (sched_pressure != SCHED_PRESSURE_NONE)
7161 if (regstat_n_sets_and_refs != NULL)
7162 regstat_free_n_sets_and_refs ();
7163 if (sched_pressure == SCHED_PRESSURE_WEIGHTED)
7165 BITMAP_FREE (region_ref_regs);
7166 BITMAP_FREE (saved_reg_live);
7168 BITMAP_FREE (curr_reg_live);
7169 free (sched_regno_pressure_class);
7173 /* Initialize some global state for the scheduler. This function works
7174 with the common data shared between all the schedulers. It is called
7175 from the scheduler specific initialization routine. */
7177 void
7178 sched_init (void)
7180 /* Disable speculative loads in their presence if cc0 defined. */
7181 if (HAVE_cc0)
7182 flag_schedule_speculative_load = 0;
7184 if (targetm.sched.dispatch (NULL, IS_DISPATCH_ON))
7185 targetm.sched.dispatch_do (NULL, DISPATCH_INIT);
7187 if (live_range_shrinkage_p)
7188 sched_pressure = SCHED_PRESSURE_WEIGHTED;
7189 else if (flag_sched_pressure
7190 && !reload_completed
7191 && common_sched_info->sched_pass_id == SCHED_RGN_PASS)
7192 sched_pressure = ((enum sched_pressure_algorithm)
7193 PARAM_VALUE (PARAM_SCHED_PRESSURE_ALGORITHM));
7194 else
7195 sched_pressure = SCHED_PRESSURE_NONE;
7197 if (sched_pressure != SCHED_PRESSURE_NONE)
7198 ira_setup_eliminable_regset ();
7200 /* Initialize SPEC_INFO. */
7201 if (targetm.sched.set_sched_flags)
7203 spec_info = &spec_info_var;
7204 targetm.sched.set_sched_flags (spec_info);
7206 if (spec_info->mask != 0)
7208 spec_info->data_weakness_cutoff =
7209 (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF) * MAX_DEP_WEAK) / 100;
7210 spec_info->control_weakness_cutoff =
7211 (PARAM_VALUE (PARAM_SCHED_SPEC_PROB_CUTOFF)
7212 * REG_BR_PROB_BASE) / 100;
7214 else
7215 /* So we won't read anything accidentally. */
7216 spec_info = NULL;
7219 else
7220 /* So we won't read anything accidentally. */
7221 spec_info = 0;
7223 /* Initialize issue_rate. */
7224 if (targetm.sched.issue_rate)
7225 issue_rate = targetm.sched.issue_rate ();
7226 else
7227 issue_rate = 1;
7229 if (targetm.sched.first_cycle_multipass_dfa_lookahead
7230 /* Don't use max_issue with reg_pressure scheduling. Multipass
7231 scheduling and reg_pressure scheduling undo each other's decisions. */
7232 && sched_pressure == SCHED_PRESSURE_NONE)
7233 dfa_lookahead = targetm.sched.first_cycle_multipass_dfa_lookahead ();
7234 else
7235 dfa_lookahead = 0;
7237 /* Set to "0" so that we recalculate. */
7238 max_lookahead_tries = 0;
7240 if (targetm.sched.init_dfa_pre_cycle_insn)
7241 targetm.sched.init_dfa_pre_cycle_insn ();
7243 if (targetm.sched.init_dfa_post_cycle_insn)
7244 targetm.sched.init_dfa_post_cycle_insn ();
7246 dfa_start ();
7247 dfa_state_size = state_size ();
7249 init_alias_analysis ();
7251 if (!sched_no_dce)
7252 df_set_flags (DF_LR_RUN_DCE);
7253 df_note_add_problem ();
7255 /* More problems needed for interloop dep calculation in SMS. */
7256 if (common_sched_info->sched_pass_id == SCHED_SMS_PASS)
7258 df_rd_add_problem ();
7259 df_chain_add_problem (DF_DU_CHAIN + DF_UD_CHAIN);
7262 df_analyze ();
7264 /* Do not run DCE after reload, as this can kill nops inserted
7265 by bundling. */
7266 if (reload_completed)
7267 df_clear_flags (DF_LR_RUN_DCE);
7269 regstat_compute_calls_crossed ();
7271 if (targetm.sched.init_global)
7272 targetm.sched.init_global (sched_dump, sched_verbose, get_max_uid () + 1);
7274 alloc_global_sched_pressure_data ();
7276 curr_state = xmalloc (dfa_state_size);
7279 static void haifa_init_only_bb (basic_block, basic_block);
7281 /* Initialize data structures specific to the Haifa scheduler. */
7282 void
7283 haifa_sched_init (void)
7285 setup_sched_dump ();
7286 sched_init ();
7288 scheduled_insns.create (0);
7290 if (spec_info != NULL)
7292 sched_deps_info->use_deps_list = 1;
7293 sched_deps_info->generate_spec_deps = 1;
7296 /* Initialize luids, dependency caches, target and h_i_d for the
7297 whole function. */
7299 bb_vec_t bbs;
7300 bbs.create (n_basic_blocks_for_fn (cfun));
7301 basic_block bb;
7303 sched_init_bbs ();
7305 FOR_EACH_BB_FN (bb, cfun)
7306 bbs.quick_push (bb);
7307 sched_init_luids (bbs);
7308 sched_deps_init (true);
7309 sched_extend_target ();
7310 haifa_init_h_i_d (bbs);
7312 bbs.release ();
7315 sched_init_only_bb = haifa_init_only_bb;
7316 sched_split_block = sched_split_block_1;
7317 sched_create_empty_bb = sched_create_empty_bb_1;
7318 haifa_recovery_bb_ever_added_p = false;
7320 nr_begin_data = nr_begin_control = nr_be_in_data = nr_be_in_control = 0;
7321 before_recovery = 0;
7322 after_recovery = 0;
7324 modulo_ii = 0;
7327 /* Finish work with the data specific to the Haifa scheduler. */
7328 void
7329 haifa_sched_finish (void)
7331 sched_create_empty_bb = NULL;
7332 sched_split_block = NULL;
7333 sched_init_only_bb = NULL;
7335 if (spec_info && spec_info->dump)
7337 char c = reload_completed ? 'a' : 'b';
7339 fprintf (spec_info->dump,
7340 ";; %s:\n", current_function_name ());
7342 fprintf (spec_info->dump,
7343 ";; Procedure %cr-begin-data-spec motions == %d\n",
7344 c, nr_begin_data);
7345 fprintf (spec_info->dump,
7346 ";; Procedure %cr-be-in-data-spec motions == %d\n",
7347 c, nr_be_in_data);
7348 fprintf (spec_info->dump,
7349 ";; Procedure %cr-begin-control-spec motions == %d\n",
7350 c, nr_begin_control);
7351 fprintf (spec_info->dump,
7352 ";; Procedure %cr-be-in-control-spec motions == %d\n",
7353 c, nr_be_in_control);
7356 scheduled_insns.release ();
7358 /* Finalize h_i_d, dependency caches, and luids for the whole
7359 function. Target will be finalized in md_global_finish (). */
7360 sched_deps_finish ();
7361 sched_finish_luids ();
7362 current_sched_info = NULL;
7363 sched_finish ();
7366 /* Free global data used during insn scheduling. This function works with
7367 the common data shared between the schedulers. */
7369 void
7370 sched_finish (void)
7372 haifa_finish_h_i_d ();
7373 free_global_sched_pressure_data ();
7374 free (curr_state);
7376 if (targetm.sched.finish_global)
7377 targetm.sched.finish_global (sched_dump, sched_verbose);
7379 end_alias_analysis ();
7381 regstat_free_calls_crossed ();
7383 dfa_finish ();
7386 /* Free all delay_pair structures that were recorded. */
7387 void
7388 free_delay_pairs (void)
7390 if (delay_htab)
7392 delay_htab->empty ();
7393 delay_htab_i2->empty ();
7397 /* Fix INSN_TICKs of the instructions in the current block as well as
7398 INSN_TICKs of their dependents.
7399 HEAD and TAIL are the begin and the end of the current scheduled block. */
7400 static void
7401 fix_inter_tick (rtx_insn *head, rtx_insn *tail)
7403 /* Set of instructions with corrected INSN_TICK. */
7404 bitmap_head processed;
7405 /* ??? It is doubtful if we should assume that cycle advance happens on
7406 basic block boundaries. Basically insns that are unconditionally ready
7407 on the start of the block are more preferable then those which have
7408 a one cycle dependency over insn from the previous block. */
7409 int next_clock = clock_var + 1;
7411 bitmap_initialize (&processed, 0);
7413 /* Iterates over scheduled instructions and fix their INSN_TICKs and
7414 INSN_TICKs of dependent instructions, so that INSN_TICKs are consistent
7415 across different blocks. */
7416 for (tail = NEXT_INSN (tail); head != tail; head = NEXT_INSN (head))
7418 if (INSN_P (head))
7420 int tick;
7421 sd_iterator_def sd_it;
7422 dep_t dep;
7424 tick = INSN_TICK (head);
7425 gcc_assert (tick >= MIN_TICK);
7427 /* Fix INSN_TICK of instruction from just scheduled block. */
7428 if (bitmap_set_bit (&processed, INSN_LUID (head)))
7430 tick -= next_clock;
7432 if (tick < MIN_TICK)
7433 tick = MIN_TICK;
7435 INSN_TICK (head) = tick;
7438 if (DEBUG_INSN_P (head))
7439 continue;
7441 FOR_EACH_DEP (head, SD_LIST_RES_FORW, sd_it, dep)
7443 rtx_insn *next;
7445 next = DEP_CON (dep);
7446 tick = INSN_TICK (next);
7448 if (tick != INVALID_TICK
7449 /* If NEXT has its INSN_TICK calculated, fix it.
7450 If not - it will be properly calculated from
7451 scratch later in fix_tick_ready. */
7452 && bitmap_set_bit (&processed, INSN_LUID (next)))
7454 tick -= next_clock;
7456 if (tick < MIN_TICK)
7457 tick = MIN_TICK;
7459 if (tick > INTER_TICK (next))
7460 INTER_TICK (next) = tick;
7461 else
7462 tick = INTER_TICK (next);
7464 INSN_TICK (next) = tick;
7469 bitmap_clear (&processed);
7472 /* Check if NEXT is ready to be added to the ready or queue list.
7473 If "yes", add it to the proper list.
7474 Returns:
7475 -1 - is not ready yet,
7476 0 - added to the ready list,
7477 0 < N - queued for N cycles. */
7479 try_ready (rtx_insn *next)
7481 ds_t old_ts, new_ts;
7483 old_ts = TODO_SPEC (next);
7485 gcc_assert (!(old_ts & ~(SPECULATIVE | HARD_DEP | DEP_CONTROL | DEP_POSTPONED))
7486 && (old_ts == HARD_DEP
7487 || old_ts == DEP_POSTPONED
7488 || (old_ts & SPECULATIVE)
7489 || old_ts == DEP_CONTROL));
7491 new_ts = recompute_todo_spec (next, false);
7493 if (new_ts & (HARD_DEP | DEP_POSTPONED))
7494 gcc_assert (new_ts == old_ts
7495 && QUEUE_INDEX (next) == QUEUE_NOWHERE);
7496 else if (current_sched_info->new_ready)
7497 new_ts = current_sched_info->new_ready (next, new_ts);
7499 /* * if !(old_ts & SPECULATIVE) (e.g. HARD_DEP or 0), then insn might
7500 have its original pattern or changed (speculative) one. This is due
7501 to changing ebb in region scheduling.
7502 * But if (old_ts & SPECULATIVE), then we are pretty sure that insn
7503 has speculative pattern.
7505 We can't assert (!(new_ts & HARD_DEP) || new_ts == old_ts) here because
7506 control-speculative NEXT could have been discarded by sched-rgn.c
7507 (the same case as when discarded by can_schedule_ready_p ()). */
7509 if ((new_ts & SPECULATIVE)
7510 /* If (old_ts == new_ts), then (old_ts & SPECULATIVE) and we don't
7511 need to change anything. */
7512 && new_ts != old_ts)
7514 int res;
7515 rtx new_pat;
7517 gcc_assert ((new_ts & SPECULATIVE) && !(new_ts & ~SPECULATIVE));
7519 res = haifa_speculate_insn (next, new_ts, &new_pat);
7521 switch (res)
7523 case -1:
7524 /* It would be nice to change DEP_STATUS of all dependences,
7525 which have ((DEP_STATUS & SPECULATIVE) == new_ts) to HARD_DEP,
7526 so we won't reanalyze anything. */
7527 new_ts = HARD_DEP;
7528 break;
7530 case 0:
7531 /* We follow the rule, that every speculative insn
7532 has non-null ORIG_PAT. */
7533 if (!ORIG_PAT (next))
7534 ORIG_PAT (next) = PATTERN (next);
7535 break;
7537 case 1:
7538 if (!ORIG_PAT (next))
7539 /* If we gonna to overwrite the original pattern of insn,
7540 save it. */
7541 ORIG_PAT (next) = PATTERN (next);
7543 res = haifa_change_pattern (next, new_pat);
7544 gcc_assert (res);
7545 break;
7547 default:
7548 gcc_unreachable ();
7552 /* We need to restore pattern only if (new_ts == 0), because otherwise it is
7553 either correct (new_ts & SPECULATIVE),
7554 or we simply don't care (new_ts & HARD_DEP). */
7556 gcc_assert (!ORIG_PAT (next)
7557 || !IS_SPECULATION_BRANCHY_CHECK_P (next));
7559 TODO_SPEC (next) = new_ts;
7561 if (new_ts & (HARD_DEP | DEP_POSTPONED))
7563 /* We can't assert (QUEUE_INDEX (next) == QUEUE_NOWHERE) here because
7564 control-speculative NEXT could have been discarded by sched-rgn.c
7565 (the same case as when discarded by can_schedule_ready_p ()). */
7566 /*gcc_assert (QUEUE_INDEX (next) == QUEUE_NOWHERE);*/
7568 change_queue_index (next, QUEUE_NOWHERE);
7570 return -1;
7572 else if (!(new_ts & BEGIN_SPEC)
7573 && ORIG_PAT (next) && PREDICATED_PAT (next) == NULL_RTX
7574 && !IS_SPECULATION_CHECK_P (next))
7575 /* We should change pattern of every previously speculative
7576 instruction - and we determine if NEXT was speculative by using
7577 ORIG_PAT field. Except one case - speculation checks have ORIG_PAT
7578 pat too, so skip them. */
7580 bool success = haifa_change_pattern (next, ORIG_PAT (next));
7581 gcc_assert (success);
7582 ORIG_PAT (next) = 0;
7585 if (sched_verbose >= 2)
7587 fprintf (sched_dump, ";;\t\tdependencies resolved: insn %s",
7588 (*current_sched_info->print_insn) (next, 0));
7590 if (spec_info && spec_info->dump)
7592 if (new_ts & BEGIN_DATA)
7593 fprintf (spec_info->dump, "; data-spec;");
7594 if (new_ts & BEGIN_CONTROL)
7595 fprintf (spec_info->dump, "; control-spec;");
7596 if (new_ts & BE_IN_CONTROL)
7597 fprintf (spec_info->dump, "; in-control-spec;");
7599 if (TODO_SPEC (next) & DEP_CONTROL)
7600 fprintf (sched_dump, " predicated");
7601 fprintf (sched_dump, "\n");
7604 adjust_priority (next);
7606 return fix_tick_ready (next);
7609 /* Calculate INSN_TICK of NEXT and add it to either ready or queue list. */
7610 static int
7611 fix_tick_ready (rtx_insn *next)
7613 int tick, delay;
7615 if (!DEBUG_INSN_P (next) && !sd_lists_empty_p (next, SD_LIST_RES_BACK))
7617 int full_p;
7618 sd_iterator_def sd_it;
7619 dep_t dep;
7621 tick = INSN_TICK (next);
7622 /* if tick is not equal to INVALID_TICK, then update
7623 INSN_TICK of NEXT with the most recent resolved dependence
7624 cost. Otherwise, recalculate from scratch. */
7625 full_p = (tick == INVALID_TICK);
7627 FOR_EACH_DEP (next, SD_LIST_RES_BACK, sd_it, dep)
7629 rtx_insn *pro = DEP_PRO (dep);
7630 int tick1;
7632 gcc_assert (INSN_TICK (pro) >= MIN_TICK);
7634 tick1 = INSN_TICK (pro) + dep_cost (dep);
7635 if (tick1 > tick)
7636 tick = tick1;
7638 if (!full_p)
7639 break;
7642 else
7643 tick = -1;
7645 INSN_TICK (next) = tick;
7647 delay = tick - clock_var;
7648 if (delay <= 0 || sched_pressure != SCHED_PRESSURE_NONE || sched_fusion)
7649 delay = QUEUE_READY;
7651 change_queue_index (next, delay);
7653 return delay;
7656 /* Move NEXT to the proper queue list with (DELAY >= 1),
7657 or add it to the ready list (DELAY == QUEUE_READY),
7658 or remove it from ready and queue lists at all (DELAY == QUEUE_NOWHERE). */
7659 static void
7660 change_queue_index (rtx_insn *next, int delay)
7662 int i = QUEUE_INDEX (next);
7664 gcc_assert (QUEUE_NOWHERE <= delay && delay <= max_insn_queue_index
7665 && delay != 0);
7666 gcc_assert (i != QUEUE_SCHEDULED);
7668 if ((delay > 0 && NEXT_Q_AFTER (q_ptr, delay) == i)
7669 || (delay < 0 && delay == i))
7670 /* We have nothing to do. */
7671 return;
7673 /* Remove NEXT from wherever it is now. */
7674 if (i == QUEUE_READY)
7675 ready_remove_insn (next);
7676 else if (i >= 0)
7677 queue_remove (next);
7679 /* Add it to the proper place. */
7680 if (delay == QUEUE_READY)
7681 ready_add (readyp, next, false);
7682 else if (delay >= 1)
7683 queue_insn (next, delay, "change queue index");
7685 if (sched_verbose >= 2)
7687 fprintf (sched_dump, ";;\t\ttick updated: insn %s",
7688 (*current_sched_info->print_insn) (next, 0));
7690 if (delay == QUEUE_READY)
7691 fprintf (sched_dump, " into ready\n");
7692 else if (delay >= 1)
7693 fprintf (sched_dump, " into queue with cost=%d\n", delay);
7694 else
7695 fprintf (sched_dump, " removed from ready or queue lists\n");
7699 static int sched_ready_n_insns = -1;
7701 /* Initialize per region data structures. */
7702 void
7703 sched_extend_ready_list (int new_sched_ready_n_insns)
7705 int i;
7707 if (sched_ready_n_insns == -1)
7708 /* At the first call we need to initialize one more choice_stack
7709 entry. */
7711 i = 0;
7712 sched_ready_n_insns = 0;
7713 scheduled_insns.reserve (new_sched_ready_n_insns);
7715 else
7716 i = sched_ready_n_insns + 1;
7718 ready.veclen = new_sched_ready_n_insns + issue_rate;
7719 ready.vec = XRESIZEVEC (rtx_insn *, ready.vec, ready.veclen);
7721 gcc_assert (new_sched_ready_n_insns >= sched_ready_n_insns);
7723 ready_try = (signed char *) xrecalloc (ready_try, new_sched_ready_n_insns,
7724 sched_ready_n_insns,
7725 sizeof (*ready_try));
7727 /* We allocate +1 element to save initial state in the choice_stack[0]
7728 entry. */
7729 choice_stack = XRESIZEVEC (struct choice_entry, choice_stack,
7730 new_sched_ready_n_insns + 1);
7732 for (; i <= new_sched_ready_n_insns; i++)
7734 choice_stack[i].state = xmalloc (dfa_state_size);
7736 if (targetm.sched.first_cycle_multipass_init)
7737 targetm.sched.first_cycle_multipass_init (&(choice_stack[i]
7738 .target_data));
7741 sched_ready_n_insns = new_sched_ready_n_insns;
7744 /* Free per region data structures. */
7745 void
7746 sched_finish_ready_list (void)
7748 int i;
7750 free (ready.vec);
7751 ready.vec = NULL;
7752 ready.veclen = 0;
7754 free (ready_try);
7755 ready_try = NULL;
7757 for (i = 0; i <= sched_ready_n_insns; i++)
7759 if (targetm.sched.first_cycle_multipass_fini)
7760 targetm.sched.first_cycle_multipass_fini (&(choice_stack[i]
7761 .target_data));
7763 free (choice_stack [i].state);
7765 free (choice_stack);
7766 choice_stack = NULL;
7768 sched_ready_n_insns = -1;
7771 static int
7772 haifa_luid_for_non_insn (rtx x)
7774 gcc_assert (NOTE_P (x) || LABEL_P (x));
7776 return 0;
7779 /* Generates recovery code for INSN. */
7780 static void
7781 generate_recovery_code (rtx_insn *insn)
7783 if (TODO_SPEC (insn) & BEGIN_SPEC)
7784 begin_speculative_block (insn);
7786 /* Here we have insn with no dependencies to
7787 instructions other then CHECK_SPEC ones. */
7789 if (TODO_SPEC (insn) & BE_IN_SPEC)
7790 add_to_speculative_block (insn);
7793 /* Helper function.
7794 Tries to add speculative dependencies of type FS between instructions
7795 in deps_list L and TWIN. */
7796 static void
7797 process_insn_forw_deps_be_in_spec (rtx_insn *insn, rtx_insn *twin, ds_t fs)
7799 sd_iterator_def sd_it;
7800 dep_t dep;
7802 FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
7804 ds_t ds;
7805 rtx_insn *consumer;
7807 consumer = DEP_CON (dep);
7809 ds = DEP_STATUS (dep);
7811 if (/* If we want to create speculative dep. */
7813 /* And we can do that because this is a true dep. */
7814 && (ds & DEP_TYPES) == DEP_TRUE)
7816 gcc_assert (!(ds & BE_IN_SPEC));
7818 if (/* If this dep can be overcome with 'begin speculation'. */
7819 ds & BEGIN_SPEC)
7820 /* Then we have a choice: keep the dep 'begin speculative'
7821 or transform it into 'be in speculative'. */
7823 if (/* In try_ready we assert that if insn once became ready
7824 it can be removed from the ready (or queue) list only
7825 due to backend decision. Hence we can't let the
7826 probability of the speculative dep to decrease. */
7827 ds_weak (ds) <= ds_weak (fs))
7829 ds_t new_ds;
7831 new_ds = (ds & ~BEGIN_SPEC) | fs;
7833 if (/* consumer can 'be in speculative'. */
7834 sched_insn_is_legitimate_for_speculation_p (consumer,
7835 new_ds))
7836 /* Transform it to be in speculative. */
7837 ds = new_ds;
7840 else
7841 /* Mark the dep as 'be in speculative'. */
7842 ds |= fs;
7846 dep_def _new_dep, *new_dep = &_new_dep;
7848 init_dep_1 (new_dep, twin, consumer, DEP_TYPE (dep), ds);
7849 sd_add_dep (new_dep, false);
7854 /* Generates recovery code for BEGIN speculative INSN. */
7855 static void
7856 begin_speculative_block (rtx_insn *insn)
7858 if (TODO_SPEC (insn) & BEGIN_DATA)
7859 nr_begin_data++;
7860 if (TODO_SPEC (insn) & BEGIN_CONTROL)
7861 nr_begin_control++;
7863 create_check_block_twin (insn, false);
7865 TODO_SPEC (insn) &= ~BEGIN_SPEC;
7868 static void haifa_init_insn (rtx_insn *);
7870 /* Generates recovery code for BE_IN speculative INSN. */
7871 static void
7872 add_to_speculative_block (rtx_insn *insn)
7874 ds_t ts;
7875 sd_iterator_def sd_it;
7876 dep_t dep;
7877 rtx_insn_list *twins = NULL;
7878 rtx_vec_t priorities_roots;
7880 ts = TODO_SPEC (insn);
7881 gcc_assert (!(ts & ~BE_IN_SPEC));
7883 if (ts & BE_IN_DATA)
7884 nr_be_in_data++;
7885 if (ts & BE_IN_CONTROL)
7886 nr_be_in_control++;
7888 TODO_SPEC (insn) &= ~BE_IN_SPEC;
7889 gcc_assert (!TODO_SPEC (insn));
7891 DONE_SPEC (insn) |= ts;
7893 /* First we convert all simple checks to branchy. */
7894 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7895 sd_iterator_cond (&sd_it, &dep);)
7897 rtx_insn *check = DEP_PRO (dep);
7899 if (IS_SPECULATION_SIMPLE_CHECK_P (check))
7901 create_check_block_twin (check, true);
7903 /* Restart search. */
7904 sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7906 else
7907 /* Continue search. */
7908 sd_iterator_next (&sd_it);
7911 priorities_roots.create (0);
7912 clear_priorities (insn, &priorities_roots);
7914 while (1)
7916 rtx_insn *check, *twin;
7917 basic_block rec;
7919 /* Get the first backward dependency of INSN. */
7920 sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7921 if (!sd_iterator_cond (&sd_it, &dep))
7922 /* INSN has no backward dependencies left. */
7923 break;
7925 gcc_assert ((DEP_STATUS (dep) & BEGIN_SPEC) == 0
7926 && (DEP_STATUS (dep) & BE_IN_SPEC) != 0
7927 && (DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
7929 check = DEP_PRO (dep);
7931 gcc_assert (!IS_SPECULATION_CHECK_P (check) && !ORIG_PAT (check)
7932 && QUEUE_INDEX (check) == QUEUE_NOWHERE);
7934 rec = BLOCK_FOR_INSN (check);
7936 twin = emit_insn_before (copy_insn (PATTERN (insn)), BB_END (rec));
7937 haifa_init_insn (twin);
7939 sd_copy_back_deps (twin, insn, true);
7941 if (sched_verbose && spec_info->dump)
7942 /* INSN_BB (insn) isn't determined for twin insns yet.
7943 So we can't use current_sched_info->print_insn. */
7944 fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
7945 INSN_UID (twin), rec->index);
7947 twins = alloc_INSN_LIST (twin, twins);
7949 /* Add dependences between TWIN and all appropriate
7950 instructions from REC. */
7951 FOR_EACH_DEP (insn, SD_LIST_SPEC_BACK, sd_it, dep)
7953 rtx_insn *pro = DEP_PRO (dep);
7955 gcc_assert (DEP_TYPE (dep) == REG_DEP_TRUE);
7957 /* INSN might have dependencies from the instructions from
7958 several recovery blocks. At this iteration we process those
7959 producers that reside in REC. */
7960 if (BLOCK_FOR_INSN (pro) == rec)
7962 dep_def _new_dep, *new_dep = &_new_dep;
7964 init_dep (new_dep, pro, twin, REG_DEP_TRUE);
7965 sd_add_dep (new_dep, false);
7969 process_insn_forw_deps_be_in_spec (insn, twin, ts);
7971 /* Remove all dependencies between INSN and insns in REC. */
7972 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
7973 sd_iterator_cond (&sd_it, &dep);)
7975 rtx_insn *pro = DEP_PRO (dep);
7977 if (BLOCK_FOR_INSN (pro) == rec)
7978 sd_delete_dep (sd_it);
7979 else
7980 sd_iterator_next (&sd_it);
7984 /* We couldn't have added the dependencies between INSN and TWINS earlier
7985 because that would make TWINS appear in the INSN_BACK_DEPS (INSN). */
7986 while (twins)
7988 rtx_insn *twin;
7989 rtx_insn_list *next_node;
7991 twin = twins->insn ();
7994 dep_def _new_dep, *new_dep = &_new_dep;
7996 init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
7997 sd_add_dep (new_dep, false);
8000 next_node = twins->next ();
8001 free_INSN_LIST_node (twins);
8002 twins = next_node;
8005 calc_priorities (priorities_roots);
8006 priorities_roots.release ();
8009 /* Extends and fills with zeros (only the new part) array pointed to by P. */
8010 void *
8011 xrecalloc (void *p, size_t new_nmemb, size_t old_nmemb, size_t size)
8013 gcc_assert (new_nmemb >= old_nmemb);
8014 p = XRESIZEVAR (void, p, new_nmemb * size);
8015 memset (((char *) p) + old_nmemb * size, 0, (new_nmemb - old_nmemb) * size);
8016 return p;
8019 /* Helper function.
8020 Find fallthru edge from PRED. */
8021 edge
8022 find_fallthru_edge_from (basic_block pred)
8024 edge e;
8025 basic_block succ;
8027 succ = pred->next_bb;
8028 gcc_assert (succ->prev_bb == pred);
8030 if (EDGE_COUNT (pred->succs) <= EDGE_COUNT (succ->preds))
8032 e = find_fallthru_edge (pred->succs);
8034 if (e)
8036 gcc_assert (e->dest == succ);
8037 return e;
8040 else
8042 e = find_fallthru_edge (succ->preds);
8044 if (e)
8046 gcc_assert (e->src == pred);
8047 return e;
8051 return NULL;
8054 /* Extend per basic block data structures. */
8055 static void
8056 sched_extend_bb (void)
8058 /* The following is done to keep current_sched_info->next_tail non null. */
8059 rtx_insn *end = BB_END (EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb);
8060 rtx_insn *insn = DEBUG_INSN_P (end) ? prev_nondebug_insn (end) : end;
8061 if (NEXT_INSN (end) == 0
8062 || (!NOTE_P (insn)
8063 && !LABEL_P (insn)
8064 /* Don't emit a NOTE if it would end up before a BARRIER. */
8065 && !BARRIER_P (NEXT_INSN (end))))
8067 rtx_note *note = emit_note_after (NOTE_INSN_DELETED, end);
8068 /* Make note appear outside BB. */
8069 set_block_for_insn (note, NULL);
8070 BB_END (EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb) = end;
8074 /* Init per basic block data structures. */
8075 void
8076 sched_init_bbs (void)
8078 sched_extend_bb ();
8081 /* Initialize BEFORE_RECOVERY variable. */
8082 static void
8083 init_before_recovery (basic_block *before_recovery_ptr)
8085 basic_block last;
8086 edge e;
8088 last = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
8089 e = find_fallthru_edge_from (last);
8091 if (e)
8093 /* We create two basic blocks:
8094 1. Single instruction block is inserted right after E->SRC
8095 and has jump to
8096 2. Empty block right before EXIT_BLOCK.
8097 Between these two blocks recovery blocks will be emitted. */
8099 basic_block single, empty;
8100 rtx_insn *x;
8101 rtx label;
8103 /* If the fallthrough edge to exit we've found is from the block we've
8104 created before, don't do anything more. */
8105 if (last == after_recovery)
8106 return;
8108 adding_bb_to_current_region_p = false;
8110 single = sched_create_empty_bb (last);
8111 empty = sched_create_empty_bb (single);
8113 /* Add new blocks to the root loop. */
8114 if (current_loops != NULL)
8116 add_bb_to_loop (single, (*current_loops->larray)[0]);
8117 add_bb_to_loop (empty, (*current_loops->larray)[0]);
8120 single->count = last->count;
8121 empty->count = last->count;
8122 single->frequency = last->frequency;
8123 empty->frequency = last->frequency;
8124 BB_COPY_PARTITION (single, last);
8125 BB_COPY_PARTITION (empty, last);
8127 redirect_edge_succ (e, single);
8128 make_single_succ_edge (single, empty, 0);
8129 make_single_succ_edge (empty, EXIT_BLOCK_PTR_FOR_FN (cfun),
8130 EDGE_FALLTHRU);
8132 label = block_label (empty);
8133 x = emit_jump_insn_after (gen_jump (label), BB_END (single));
8134 JUMP_LABEL (x) = label;
8135 LABEL_NUSES (label)++;
8136 haifa_init_insn (x);
8138 emit_barrier_after (x);
8140 sched_init_only_bb (empty, NULL);
8141 sched_init_only_bb (single, NULL);
8142 sched_extend_bb ();
8144 adding_bb_to_current_region_p = true;
8145 before_recovery = single;
8146 after_recovery = empty;
8148 if (before_recovery_ptr)
8149 *before_recovery_ptr = before_recovery;
8151 if (sched_verbose >= 2 && spec_info->dump)
8152 fprintf (spec_info->dump,
8153 ";;\t\tFixed fallthru to EXIT : %d->>%d->%d->>EXIT\n",
8154 last->index, single->index, empty->index);
8156 else
8157 before_recovery = last;
8160 /* Returns new recovery block. */
8161 basic_block
8162 sched_create_recovery_block (basic_block *before_recovery_ptr)
8164 rtx label;
8165 rtx_insn *barrier;
8166 basic_block rec;
8168 haifa_recovery_bb_recently_added_p = true;
8169 haifa_recovery_bb_ever_added_p = true;
8171 init_before_recovery (before_recovery_ptr);
8173 barrier = get_last_bb_insn (before_recovery);
8174 gcc_assert (BARRIER_P (barrier));
8176 label = emit_label_after (gen_label_rtx (), barrier);
8178 rec = create_basic_block (label, label, before_recovery);
8180 /* A recovery block always ends with an unconditional jump. */
8181 emit_barrier_after (BB_END (rec));
8183 if (BB_PARTITION (before_recovery) != BB_UNPARTITIONED)
8184 BB_SET_PARTITION (rec, BB_COLD_PARTITION);
8186 if (sched_verbose && spec_info->dump)
8187 fprintf (spec_info->dump, ";;\t\tGenerated recovery block rec%d\n",
8188 rec->index);
8190 return rec;
8193 /* Create edges: FIRST_BB -> REC; FIRST_BB -> SECOND_BB; REC -> SECOND_BB
8194 and emit necessary jumps. */
8195 void
8196 sched_create_recovery_edges (basic_block first_bb, basic_block rec,
8197 basic_block second_bb)
8199 rtx label;
8200 rtx jump;
8201 int edge_flags;
8203 /* This is fixing of incoming edge. */
8204 /* ??? Which other flags should be specified? */
8205 if (BB_PARTITION (first_bb) != BB_PARTITION (rec))
8206 /* Partition type is the same, if it is "unpartitioned". */
8207 edge_flags = EDGE_CROSSING;
8208 else
8209 edge_flags = 0;
8211 make_edge (first_bb, rec, edge_flags);
8212 label = block_label (second_bb);
8213 jump = emit_jump_insn_after (gen_jump (label), BB_END (rec));
8214 JUMP_LABEL (jump) = label;
8215 LABEL_NUSES (label)++;
8217 if (BB_PARTITION (second_bb) != BB_PARTITION (rec))
8218 /* Partition type is the same, if it is "unpartitioned". */
8220 /* Rewritten from cfgrtl.c. */
8221 if (flag_reorder_blocks_and_partition
8222 && targetm_common.have_named_sections)
8224 /* We don't need the same note for the check because
8225 any_condjump_p (check) == true. */
8226 CROSSING_JUMP_P (jump) = 1;
8228 edge_flags = EDGE_CROSSING;
8230 else
8231 edge_flags = 0;
8233 make_single_succ_edge (rec, second_bb, edge_flags);
8234 if (dom_info_available_p (CDI_DOMINATORS))
8235 set_immediate_dominator (CDI_DOMINATORS, rec, first_bb);
8238 /* This function creates recovery code for INSN. If MUTATE_P is nonzero,
8239 INSN is a simple check, that should be converted to branchy one. */
8240 static void
8241 create_check_block_twin (rtx_insn *insn, bool mutate_p)
8243 basic_block rec;
8244 rtx_insn *label, *check, *twin;
8245 rtx check_pat;
8246 ds_t fs;
8247 sd_iterator_def sd_it;
8248 dep_t dep;
8249 dep_def _new_dep, *new_dep = &_new_dep;
8250 ds_t todo_spec;
8252 gcc_assert (ORIG_PAT (insn) != NULL_RTX);
8254 if (!mutate_p)
8255 todo_spec = TODO_SPEC (insn);
8256 else
8258 gcc_assert (IS_SPECULATION_SIMPLE_CHECK_P (insn)
8259 && (TODO_SPEC (insn) & SPECULATIVE) == 0);
8261 todo_spec = CHECK_SPEC (insn);
8264 todo_spec &= SPECULATIVE;
8266 /* Create recovery block. */
8267 if (mutate_p || targetm.sched.needs_block_p (todo_spec))
8269 rec = sched_create_recovery_block (NULL);
8270 label = BB_HEAD (rec);
8272 else
8274 rec = EXIT_BLOCK_PTR_FOR_FN (cfun);
8275 label = NULL;
8278 /* Emit CHECK. */
8279 check_pat = targetm.sched.gen_spec_check (insn, label, todo_spec);
8281 if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8283 /* To have mem_reg alive at the beginning of second_bb,
8284 we emit check BEFORE insn, so insn after splitting
8285 insn will be at the beginning of second_bb, which will
8286 provide us with the correct life information. */
8287 check = emit_jump_insn_before (check_pat, insn);
8288 JUMP_LABEL (check) = label;
8289 LABEL_NUSES (label)++;
8291 else
8292 check = emit_insn_before (check_pat, insn);
8294 /* Extend data structures. */
8295 haifa_init_insn (check);
8297 /* CHECK is being added to current region. Extend ready list. */
8298 gcc_assert (sched_ready_n_insns != -1);
8299 sched_extend_ready_list (sched_ready_n_insns + 1);
8301 if (current_sched_info->add_remove_insn)
8302 current_sched_info->add_remove_insn (insn, 0);
8304 RECOVERY_BLOCK (check) = rec;
8306 if (sched_verbose && spec_info->dump)
8307 fprintf (spec_info->dump, ";;\t\tGenerated check insn : %s\n",
8308 (*current_sched_info->print_insn) (check, 0));
8310 gcc_assert (ORIG_PAT (insn));
8312 /* Initialize TWIN (twin is a duplicate of original instruction
8313 in the recovery block). */
8314 if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8316 sd_iterator_def sd_it;
8317 dep_t dep;
8319 FOR_EACH_DEP (insn, SD_LIST_RES_BACK, sd_it, dep)
8320 if ((DEP_STATUS (dep) & DEP_OUTPUT) != 0)
8322 struct _dep _dep2, *dep2 = &_dep2;
8324 init_dep (dep2, DEP_PRO (dep), check, REG_DEP_TRUE);
8326 sd_add_dep (dep2, true);
8329 twin = emit_insn_after (ORIG_PAT (insn), BB_END (rec));
8330 haifa_init_insn (twin);
8332 if (sched_verbose && spec_info->dump)
8333 /* INSN_BB (insn) isn't determined for twin insns yet.
8334 So we can't use current_sched_info->print_insn. */
8335 fprintf (spec_info->dump, ";;\t\tGenerated twin insn : %d/rec%d\n",
8336 INSN_UID (twin), rec->index);
8338 else
8340 ORIG_PAT (check) = ORIG_PAT (insn);
8341 HAS_INTERNAL_DEP (check) = 1;
8342 twin = check;
8343 /* ??? We probably should change all OUTPUT dependencies to
8344 (TRUE | OUTPUT). */
8347 /* Copy all resolved back dependencies of INSN to TWIN. This will
8348 provide correct value for INSN_TICK (TWIN). */
8349 sd_copy_back_deps (twin, insn, true);
8351 if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8352 /* In case of branchy check, fix CFG. */
8354 basic_block first_bb, second_bb;
8355 rtx_insn *jump;
8357 first_bb = BLOCK_FOR_INSN (check);
8358 second_bb = sched_split_block (first_bb, check);
8360 sched_create_recovery_edges (first_bb, rec, second_bb);
8362 sched_init_only_bb (second_bb, first_bb);
8363 sched_init_only_bb (rec, EXIT_BLOCK_PTR_FOR_FN (cfun));
8365 jump = BB_END (rec);
8366 haifa_init_insn (jump);
8369 /* Move backward dependences from INSN to CHECK and
8370 move forward dependences from INSN to TWIN. */
8372 /* First, create dependencies between INSN's producers and CHECK & TWIN. */
8373 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
8375 rtx_insn *pro = DEP_PRO (dep);
8376 ds_t ds;
8378 /* If BEGIN_DATA: [insn ~~TRUE~~> producer]:
8379 check --TRUE--> producer ??? or ANTI ???
8380 twin --TRUE--> producer
8381 twin --ANTI--> check
8383 If BEGIN_CONTROL: [insn ~~ANTI~~> producer]:
8384 check --ANTI--> producer
8385 twin --ANTI--> producer
8386 twin --ANTI--> check
8388 If BE_IN_SPEC: [insn ~~TRUE~~> producer]:
8389 check ~~TRUE~~> producer
8390 twin ~~TRUE~~> producer
8391 twin --ANTI--> check */
8393 ds = DEP_STATUS (dep);
8395 if (ds & BEGIN_SPEC)
8397 gcc_assert (!mutate_p);
8398 ds &= ~BEGIN_SPEC;
8401 init_dep_1 (new_dep, pro, check, DEP_TYPE (dep), ds);
8402 sd_add_dep (new_dep, false);
8404 if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8406 DEP_CON (new_dep) = twin;
8407 sd_add_dep (new_dep, false);
8411 /* Second, remove backward dependencies of INSN. */
8412 for (sd_it = sd_iterator_start (insn, SD_LIST_SPEC_BACK);
8413 sd_iterator_cond (&sd_it, &dep);)
8415 if ((DEP_STATUS (dep) & BEGIN_SPEC)
8416 || mutate_p)
8417 /* We can delete this dep because we overcome it with
8418 BEGIN_SPECULATION. */
8419 sd_delete_dep (sd_it);
8420 else
8421 sd_iterator_next (&sd_it);
8424 /* Future Speculations. Determine what BE_IN speculations will be like. */
8425 fs = 0;
8427 /* Fields (DONE_SPEC (x) & BEGIN_SPEC) and CHECK_SPEC (x) are set only
8428 here. */
8430 gcc_assert (!DONE_SPEC (insn));
8432 if (!mutate_p)
8434 ds_t ts = TODO_SPEC (insn);
8436 DONE_SPEC (insn) = ts & BEGIN_SPEC;
8437 CHECK_SPEC (check) = ts & BEGIN_SPEC;
8439 /* Luckiness of future speculations solely depends upon initial
8440 BEGIN speculation. */
8441 if (ts & BEGIN_DATA)
8442 fs = set_dep_weak (fs, BE_IN_DATA, get_dep_weak (ts, BEGIN_DATA));
8443 if (ts & BEGIN_CONTROL)
8444 fs = set_dep_weak (fs, BE_IN_CONTROL,
8445 get_dep_weak (ts, BEGIN_CONTROL));
8447 else
8448 CHECK_SPEC (check) = CHECK_SPEC (insn);
8450 /* Future speculations: call the helper. */
8451 process_insn_forw_deps_be_in_spec (insn, twin, fs);
8453 if (rec != EXIT_BLOCK_PTR_FOR_FN (cfun))
8455 /* Which types of dependencies should we use here is,
8456 generally, machine-dependent question... But, for now,
8457 it is not. */
8459 if (!mutate_p)
8461 init_dep (new_dep, insn, check, REG_DEP_TRUE);
8462 sd_add_dep (new_dep, false);
8464 init_dep (new_dep, insn, twin, REG_DEP_OUTPUT);
8465 sd_add_dep (new_dep, false);
8467 else
8469 if (spec_info->dump)
8470 fprintf (spec_info->dump, ";;\t\tRemoved simple check : %s\n",
8471 (*current_sched_info->print_insn) (insn, 0));
8473 /* Remove all dependencies of the INSN. */
8475 sd_it = sd_iterator_start (insn, (SD_LIST_FORW
8476 | SD_LIST_BACK
8477 | SD_LIST_RES_BACK));
8478 while (sd_iterator_cond (&sd_it, &dep))
8479 sd_delete_dep (sd_it);
8482 /* If former check (INSN) already was moved to the ready (or queue)
8483 list, add new check (CHECK) there too. */
8484 if (QUEUE_INDEX (insn) != QUEUE_NOWHERE)
8485 try_ready (check);
8487 /* Remove old check from instruction stream and free its
8488 data. */
8489 sched_remove_insn (insn);
8492 init_dep (new_dep, check, twin, REG_DEP_ANTI);
8493 sd_add_dep (new_dep, false);
8495 else
8497 init_dep_1 (new_dep, insn, check, REG_DEP_TRUE, DEP_TRUE | DEP_OUTPUT);
8498 sd_add_dep (new_dep, false);
8501 if (!mutate_p)
8502 /* Fix priorities. If MUTATE_P is nonzero, this is not necessary,
8503 because it'll be done later in add_to_speculative_block. */
8505 rtx_vec_t priorities_roots = rtx_vec_t ();
8507 clear_priorities (twin, &priorities_roots);
8508 calc_priorities (priorities_roots);
8509 priorities_roots.release ();
8513 /* Removes dependency between instructions in the recovery block REC
8514 and usual region instructions. It keeps inner dependences so it
8515 won't be necessary to recompute them. */
8516 static void
8517 fix_recovery_deps (basic_block rec)
8519 rtx_insn *note, *insn, *jump;
8520 rtx_insn_list *ready_list = 0;
8521 bitmap_head in_ready;
8522 rtx_insn_list *link;
8524 bitmap_initialize (&in_ready, 0);
8526 /* NOTE - a basic block note. */
8527 note = NEXT_INSN (BB_HEAD (rec));
8528 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
8529 insn = BB_END (rec);
8530 gcc_assert (JUMP_P (insn));
8531 insn = PREV_INSN (insn);
8535 sd_iterator_def sd_it;
8536 dep_t dep;
8538 for (sd_it = sd_iterator_start (insn, SD_LIST_FORW);
8539 sd_iterator_cond (&sd_it, &dep);)
8541 rtx_insn *consumer = DEP_CON (dep);
8543 if (BLOCK_FOR_INSN (consumer) != rec)
8545 sd_delete_dep (sd_it);
8547 if (bitmap_set_bit (&in_ready, INSN_LUID (consumer)))
8548 ready_list = alloc_INSN_LIST (consumer, ready_list);
8550 else
8552 gcc_assert ((DEP_STATUS (dep) & DEP_TYPES) == DEP_TRUE);
8554 sd_iterator_next (&sd_it);
8558 insn = PREV_INSN (insn);
8560 while (insn != note);
8562 bitmap_clear (&in_ready);
8564 /* Try to add instructions to the ready or queue list. */
8565 for (link = ready_list; link; link = link->next ())
8566 try_ready (link->insn ());
8567 free_INSN_LIST_list (&ready_list);
8569 /* Fixing jump's dependences. */
8570 insn = BB_HEAD (rec);
8571 jump = BB_END (rec);
8573 gcc_assert (LABEL_P (insn));
8574 insn = NEXT_INSN (insn);
8576 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (insn));
8577 add_jump_dependencies (insn, jump);
8580 /* Change pattern of INSN to NEW_PAT. Invalidate cached haifa
8581 instruction data. */
8582 static bool
8583 haifa_change_pattern (rtx_insn *insn, rtx new_pat)
8585 int t;
8587 t = validate_change (insn, &PATTERN (insn), new_pat, 0);
8588 if (!t)
8589 return false;
8591 update_insn_after_change (insn);
8592 return true;
8595 /* -1 - can't speculate,
8596 0 - for speculation with REQUEST mode it is OK to use
8597 current instruction pattern,
8598 1 - need to change pattern for *NEW_PAT to be speculative. */
8600 sched_speculate_insn (rtx_insn *insn, ds_t request, rtx *new_pat)
8602 gcc_assert (current_sched_info->flags & DO_SPECULATION
8603 && (request & SPECULATIVE)
8604 && sched_insn_is_legitimate_for_speculation_p (insn, request));
8606 if ((request & spec_info->mask) != request)
8607 return -1;
8609 if (request & BE_IN_SPEC
8610 && !(request & BEGIN_SPEC))
8611 return 0;
8613 return targetm.sched.speculate_insn (insn, request, new_pat);
8616 static int
8617 haifa_speculate_insn (rtx_insn *insn, ds_t request, rtx *new_pat)
8619 gcc_assert (sched_deps_info->generate_spec_deps
8620 && !IS_SPECULATION_CHECK_P (insn));
8622 if (HAS_INTERNAL_DEP (insn)
8623 || SCHED_GROUP_P (insn))
8624 return -1;
8626 return sched_speculate_insn (insn, request, new_pat);
8629 /* Print some information about block BB, which starts with HEAD and
8630 ends with TAIL, before scheduling it.
8631 I is zero, if scheduler is about to start with the fresh ebb. */
8632 static void
8633 dump_new_block_header (int i, basic_block bb, rtx_insn *head, rtx_insn *tail)
8635 if (!i)
8636 fprintf (sched_dump,
8637 ";; ======================================================\n");
8638 else
8639 fprintf (sched_dump,
8640 ";; =====================ADVANCING TO=====================\n");
8641 fprintf (sched_dump,
8642 ";; -- basic block %d from %d to %d -- %s reload\n",
8643 bb->index, INSN_UID (head), INSN_UID (tail),
8644 (reload_completed ? "after" : "before"));
8645 fprintf (sched_dump,
8646 ";; ======================================================\n");
8647 fprintf (sched_dump, "\n");
8650 /* Unlink basic block notes and labels and saves them, so they
8651 can be easily restored. We unlink basic block notes in EBB to
8652 provide back-compatibility with the previous code, as target backends
8653 assume, that there'll be only instructions between
8654 current_sched_info->{head and tail}. We restore these notes as soon
8655 as we can.
8656 FIRST (LAST) is the first (last) basic block in the ebb.
8657 NB: In usual case (FIRST == LAST) nothing is really done. */
8658 void
8659 unlink_bb_notes (basic_block first, basic_block last)
8661 /* We DON'T unlink basic block notes of the first block in the ebb. */
8662 if (first == last)
8663 return;
8665 bb_header = XNEWVEC (rtx_insn *, last_basic_block_for_fn (cfun));
8667 /* Make a sentinel. */
8668 if (last->next_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
8669 bb_header[last->next_bb->index] = 0;
8671 first = first->next_bb;
8674 rtx_insn *prev, *label, *note, *next;
8676 label = BB_HEAD (last);
8677 if (LABEL_P (label))
8678 note = NEXT_INSN (label);
8679 else
8680 note = label;
8681 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
8683 prev = PREV_INSN (label);
8684 next = NEXT_INSN (note);
8685 gcc_assert (prev && next);
8687 SET_NEXT_INSN (prev) = next;
8688 SET_PREV_INSN (next) = prev;
8690 bb_header[last->index] = label;
8692 if (last == first)
8693 break;
8695 last = last->prev_bb;
8697 while (1);
8700 /* Restore basic block notes.
8701 FIRST is the first basic block in the ebb. */
8702 static void
8703 restore_bb_notes (basic_block first)
8705 if (!bb_header)
8706 return;
8708 /* We DON'T unlink basic block notes of the first block in the ebb. */
8709 first = first->next_bb;
8710 /* Remember: FIRST is actually a second basic block in the ebb. */
8712 while (first != EXIT_BLOCK_PTR_FOR_FN (cfun)
8713 && bb_header[first->index])
8715 rtx_insn *prev, *label, *note, *next;
8717 label = bb_header[first->index];
8718 prev = PREV_INSN (label);
8719 next = NEXT_INSN (prev);
8721 if (LABEL_P (label))
8722 note = NEXT_INSN (label);
8723 else
8724 note = label;
8725 gcc_assert (NOTE_INSN_BASIC_BLOCK_P (note));
8727 bb_header[first->index] = 0;
8729 SET_NEXT_INSN (prev) = label;
8730 SET_NEXT_INSN (note) = next;
8731 SET_PREV_INSN (next) = note;
8733 first = first->next_bb;
8736 free (bb_header);
8737 bb_header = 0;
8740 /* Helper function.
8741 Fix CFG after both in- and inter-block movement of
8742 control_flow_insn_p JUMP. */
8743 static void
8744 fix_jump_move (rtx_insn *jump)
8746 basic_block bb, jump_bb, jump_bb_next;
8748 bb = BLOCK_FOR_INSN (PREV_INSN (jump));
8749 jump_bb = BLOCK_FOR_INSN (jump);
8750 jump_bb_next = jump_bb->next_bb;
8752 gcc_assert (common_sched_info->sched_pass_id == SCHED_EBB_PASS
8753 || IS_SPECULATION_BRANCHY_CHECK_P (jump));
8755 if (!NOTE_INSN_BASIC_BLOCK_P (BB_END (jump_bb_next)))
8756 /* if jump_bb_next is not empty. */
8757 BB_END (jump_bb) = BB_END (jump_bb_next);
8759 if (BB_END (bb) != PREV_INSN (jump))
8760 /* Then there are instruction after jump that should be placed
8761 to jump_bb_next. */
8762 BB_END (jump_bb_next) = BB_END (bb);
8763 else
8764 /* Otherwise jump_bb_next is empty. */
8765 BB_END (jump_bb_next) = NEXT_INSN (BB_HEAD (jump_bb_next));
8767 /* To make assertion in move_insn happy. */
8768 BB_END (bb) = PREV_INSN (jump);
8770 update_bb_for_insn (jump_bb_next);
8773 /* Fix CFG after interblock movement of control_flow_insn_p JUMP. */
8774 static void
8775 move_block_after_check (rtx_insn *jump)
8777 basic_block bb, jump_bb, jump_bb_next;
8778 vec<edge, va_gc> *t;
8780 bb = BLOCK_FOR_INSN (PREV_INSN (jump));
8781 jump_bb = BLOCK_FOR_INSN (jump);
8782 jump_bb_next = jump_bb->next_bb;
8784 update_bb_for_insn (jump_bb);
8786 gcc_assert (IS_SPECULATION_CHECK_P (jump)
8787 || IS_SPECULATION_CHECK_P (BB_END (jump_bb_next)));
8789 unlink_block (jump_bb_next);
8790 link_block (jump_bb_next, bb);
8792 t = bb->succs;
8793 bb->succs = 0;
8794 move_succs (&(jump_bb->succs), bb);
8795 move_succs (&(jump_bb_next->succs), jump_bb);
8796 move_succs (&t, jump_bb_next);
8798 df_mark_solutions_dirty ();
8800 common_sched_info->fix_recovery_cfg
8801 (bb->index, jump_bb->index, jump_bb_next->index);
8804 /* Helper function for move_block_after_check.
8805 This functions attaches edge vector pointed to by SUCCSP to
8806 block TO. */
8807 static void
8808 move_succs (vec<edge, va_gc> **succsp, basic_block to)
8810 edge e;
8811 edge_iterator ei;
8813 gcc_assert (to->succs == 0);
8815 to->succs = *succsp;
8817 FOR_EACH_EDGE (e, ei, to->succs)
8818 e->src = to;
8820 *succsp = 0;
8823 /* Remove INSN from the instruction stream.
8824 INSN should have any dependencies. */
8825 static void
8826 sched_remove_insn (rtx_insn *insn)
8828 sd_finish_insn (insn);
8830 change_queue_index (insn, QUEUE_NOWHERE);
8831 current_sched_info->add_remove_insn (insn, 1);
8832 delete_insn (insn);
8835 /* Clear priorities of all instructions, that are forward dependent on INSN.
8836 Store in vector pointed to by ROOTS_PTR insns on which priority () should
8837 be invoked to initialize all cleared priorities. */
8838 static void
8839 clear_priorities (rtx_insn *insn, rtx_vec_t *roots_ptr)
8841 sd_iterator_def sd_it;
8842 dep_t dep;
8843 bool insn_is_root_p = true;
8845 gcc_assert (QUEUE_INDEX (insn) != QUEUE_SCHEDULED);
8847 FOR_EACH_DEP (insn, SD_LIST_BACK, sd_it, dep)
8849 rtx_insn *pro = DEP_PRO (dep);
8851 if (INSN_PRIORITY_STATUS (pro) >= 0
8852 && QUEUE_INDEX (insn) != QUEUE_SCHEDULED)
8854 /* If DEP doesn't contribute to priority then INSN itself should
8855 be added to priority roots. */
8856 if (contributes_to_priority_p (dep))
8857 insn_is_root_p = false;
8859 INSN_PRIORITY_STATUS (pro) = -1;
8860 clear_priorities (pro, roots_ptr);
8864 if (insn_is_root_p)
8865 roots_ptr->safe_push (insn);
8868 /* Recompute priorities of instructions, whose priorities might have been
8869 changed. ROOTS is a vector of instructions whose priority computation will
8870 trigger initialization of all cleared priorities. */
8871 static void
8872 calc_priorities (rtx_vec_t roots)
8874 int i;
8875 rtx_insn *insn;
8877 FOR_EACH_VEC_ELT (roots, i, insn)
8878 priority (insn);
8882 /* Add dependences between JUMP and other instructions in the recovery
8883 block. INSN is the first insn the recovery block. */
8884 static void
8885 add_jump_dependencies (rtx_insn *insn, rtx_insn *jump)
8889 insn = NEXT_INSN (insn);
8890 if (insn == jump)
8891 break;
8893 if (dep_list_size (insn, SD_LIST_FORW) == 0)
8895 dep_def _new_dep, *new_dep = &_new_dep;
8897 init_dep (new_dep, insn, jump, REG_DEP_ANTI);
8898 sd_add_dep (new_dep, false);
8901 while (1);
8903 gcc_assert (!sd_lists_empty_p (jump, SD_LIST_BACK));
8906 /* Extend data structures for logical insn UID. */
8907 void
8908 sched_extend_luids (void)
8910 int new_luids_max_uid = get_max_uid () + 1;
8912 sched_luids.safe_grow_cleared (new_luids_max_uid);
8915 /* Initialize LUID for INSN. */
8916 void
8917 sched_init_insn_luid (rtx_insn *insn)
8919 int i = INSN_P (insn) ? 1 : common_sched_info->luid_for_non_insn (insn);
8920 int luid;
8922 if (i >= 0)
8924 luid = sched_max_luid;
8925 sched_max_luid += i;
8927 else
8928 luid = -1;
8930 SET_INSN_LUID (insn, luid);
8933 /* Initialize luids for BBS.
8934 The hook common_sched_info->luid_for_non_insn () is used to determine
8935 if notes, labels, etc. need luids. */
8936 void
8937 sched_init_luids (bb_vec_t bbs)
8939 int i;
8940 basic_block bb;
8942 sched_extend_luids ();
8943 FOR_EACH_VEC_ELT (bbs, i, bb)
8945 rtx_insn *insn;
8947 FOR_BB_INSNS (bb, insn)
8948 sched_init_insn_luid (insn);
8952 /* Free LUIDs. */
8953 void
8954 sched_finish_luids (void)
8956 sched_luids.release ();
8957 sched_max_luid = 1;
8960 /* Return logical uid of INSN. Helpful while debugging. */
8962 insn_luid (rtx_insn *insn)
8964 return INSN_LUID (insn);
8967 /* Extend per insn data in the target. */
8968 void
8969 sched_extend_target (void)
8971 if (targetm.sched.h_i_d_extended)
8972 targetm.sched.h_i_d_extended ();
8975 /* Extend global scheduler structures (those, that live across calls to
8976 schedule_block) to include information about just emitted INSN. */
8977 static void
8978 extend_h_i_d (void)
8980 int reserve = (get_max_uid () + 1 - h_i_d.length ());
8981 if (reserve > 0
8982 && ! h_i_d.space (reserve))
8984 h_i_d.safe_grow_cleared (3 * get_max_uid () / 2);
8985 sched_extend_target ();
8989 /* Initialize h_i_d entry of the INSN with default values.
8990 Values, that are not explicitly initialized here, hold zero. */
8991 static void
8992 init_h_i_d (rtx_insn *insn)
8994 if (INSN_LUID (insn) > 0)
8996 INSN_COST (insn) = -1;
8997 QUEUE_INDEX (insn) = QUEUE_NOWHERE;
8998 INSN_TICK (insn) = INVALID_TICK;
8999 INSN_EXACT_TICK (insn) = INVALID_TICK;
9000 INTER_TICK (insn) = INVALID_TICK;
9001 TODO_SPEC (insn) = HARD_DEP;
9002 INSN_AUTOPREF_MULTIPASS_DATA (insn)[0].status
9003 = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
9004 INSN_AUTOPREF_MULTIPASS_DATA (insn)[1].status
9005 = AUTOPREF_MULTIPASS_DATA_UNINITIALIZED;
9009 /* Initialize haifa_insn_data for BBS. */
9010 void
9011 haifa_init_h_i_d (bb_vec_t bbs)
9013 int i;
9014 basic_block bb;
9016 extend_h_i_d ();
9017 FOR_EACH_VEC_ELT (bbs, i, bb)
9019 rtx_insn *insn;
9021 FOR_BB_INSNS (bb, insn)
9022 init_h_i_d (insn);
9026 /* Finalize haifa_insn_data. */
9027 void
9028 haifa_finish_h_i_d (void)
9030 int i;
9031 haifa_insn_data_t data;
9032 struct reg_use_data *use, *next;
9034 FOR_EACH_VEC_ELT (h_i_d, i, data)
9036 free (data->max_reg_pressure);
9037 free (data->reg_pressure);
9038 for (use = data->reg_use_list; use != NULL; use = next)
9040 next = use->next_insn_use;
9041 free (use);
9044 h_i_d.release ();
9047 /* Init data for the new insn INSN. */
9048 static void
9049 haifa_init_insn (rtx_insn *insn)
9051 gcc_assert (insn != NULL);
9053 sched_extend_luids ();
9054 sched_init_insn_luid (insn);
9055 sched_extend_target ();
9056 sched_deps_init (false);
9057 extend_h_i_d ();
9058 init_h_i_d (insn);
9060 if (adding_bb_to_current_region_p)
9062 sd_init_insn (insn);
9064 /* Extend dependency caches by one element. */
9065 extend_dependency_caches (1, false);
9067 if (sched_pressure != SCHED_PRESSURE_NONE)
9068 init_insn_reg_pressure_info (insn);
9071 /* Init data for the new basic block BB which comes after AFTER. */
9072 static void
9073 haifa_init_only_bb (basic_block bb, basic_block after)
9075 gcc_assert (bb != NULL);
9077 sched_init_bbs ();
9079 if (common_sched_info->add_block)
9080 /* This changes only data structures of the front-end. */
9081 common_sched_info->add_block (bb, after);
9084 /* A generic version of sched_split_block (). */
9085 basic_block
9086 sched_split_block_1 (basic_block first_bb, rtx after)
9088 edge e;
9090 e = split_block (first_bb, after);
9091 gcc_assert (e->src == first_bb);
9093 /* sched_split_block emits note if *check == BB_END. Probably it
9094 is better to rip that note off. */
9096 return e->dest;
9099 /* A generic version of sched_create_empty_bb (). */
9100 basic_block
9101 sched_create_empty_bb_1 (basic_block after)
9103 return create_empty_bb (after);
9106 /* Insert PAT as an INSN into the schedule and update the necessary data
9107 structures to account for it. */
9108 rtx_insn *
9109 sched_emit_insn (rtx pat)
9111 rtx_insn *insn = emit_insn_before (pat, first_nonscheduled_insn ());
9112 haifa_init_insn (insn);
9114 if (current_sched_info->add_remove_insn)
9115 current_sched_info->add_remove_insn (insn, 0);
9117 (*current_sched_info->begin_schedule_ready) (insn);
9118 scheduled_insns.safe_push (insn);
9120 last_scheduled_insn = insn;
9121 return insn;
9124 /* This function returns a candidate satisfying dispatch constraints from
9125 the ready list. */
9127 static rtx_insn *
9128 ready_remove_first_dispatch (struct ready_list *ready)
9130 int i;
9131 rtx_insn *insn = ready_element (ready, 0);
9133 if (ready->n_ready == 1
9134 || !INSN_P (insn)
9135 || INSN_CODE (insn) < 0
9136 || !active_insn_p (insn)
9137 || targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
9138 return ready_remove_first (ready);
9140 for (i = 1; i < ready->n_ready; i++)
9142 insn = ready_element (ready, i);
9144 if (!INSN_P (insn)
9145 || INSN_CODE (insn) < 0
9146 || !active_insn_p (insn))
9147 continue;
9149 if (targetm.sched.dispatch (insn, FITS_DISPATCH_WINDOW))
9151 /* Return ith element of ready. */
9152 insn = ready_remove (ready, i);
9153 return insn;
9157 if (targetm.sched.dispatch (NULL, DISPATCH_VIOLATION))
9158 return ready_remove_first (ready);
9160 for (i = 1; i < ready->n_ready; i++)
9162 insn = ready_element (ready, i);
9164 if (!INSN_P (insn)
9165 || INSN_CODE (insn) < 0
9166 || !active_insn_p (insn))
9167 continue;
9169 /* Return i-th element of ready. */
9170 if (targetm.sched.dispatch (insn, IS_CMP))
9171 return ready_remove (ready, i);
9174 return ready_remove_first (ready);
9177 /* Get number of ready insn in the ready list. */
9180 number_in_ready (void)
9182 return ready.n_ready;
9185 /* Get number of ready's in the ready list. */
9187 rtx_insn *
9188 get_ready_element (int i)
9190 return ready_element (&ready, i);
9193 #endif /* INSN_SCHEDULING */