name-lookup.c (lookup_arg_dependent): Use conditional timevars.
[official-gcc.git] / gcc / modulo-sched.c
blob28be9425b449a00888081c2f9bda4d524d5bc890
1 /* Swing Modulo Scheduling implementation.
2 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
3 Free Software Foundation, Inc.
4 Contributed by Ayal Zaks and Mustafa Hagog <zaks,mustafa@il.ibm.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/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "diagnostic-core.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "hard-reg-set.h"
31 #include "regs.h"
32 #include "function.h"
33 #include "flags.h"
34 #include "insn-config.h"
35 #include "insn-attr.h"
36 #include "except.h"
37 #include "recog.h"
38 #include "sched-int.h"
39 #include "target.h"
40 #include "cfglayout.h"
41 #include "cfgloop.h"
42 #include "cfghooks.h"
43 #include "expr.h"
44 #include "params.h"
45 #include "gcov-io.h"
46 #include "ddg.h"
47 #include "timevar.h"
48 #include "tree-pass.h"
49 #include "dbgcnt.h"
50 #include "df.h"
52 #ifdef INSN_SCHEDULING
54 /* This file contains the implementation of the Swing Modulo Scheduler,
55 described in the following references:
56 [1] J. Llosa, A. Gonzalez, E. Ayguade, M. Valero., and J. Eckhardt.
57 Lifetime--sensitive modulo scheduling in a production environment.
58 IEEE Trans. on Comps., 50(3), March 2001
59 [2] J. Llosa, A. Gonzalez, E. Ayguade, and M. Valero.
60 Swing Modulo Scheduling: A Lifetime Sensitive Approach.
61 PACT '96 , pages 80-87, October 1996 (Boston - Massachusetts - USA).
63 The basic structure is:
64 1. Build a data-dependence graph (DDG) for each loop.
65 2. Use the DDG to order the insns of a loop (not in topological order
66 necessarily, but rather) trying to place each insn after all its
67 predecessors _or_ after all its successors.
68 3. Compute MII: a lower bound on the number of cycles to schedule the loop.
69 4. Use the ordering to perform list-scheduling of the loop:
70 1. Set II = MII. We will try to schedule the loop within II cycles.
71 2. Try to schedule the insns one by one according to the ordering.
72 For each insn compute an interval of cycles by considering already-
73 scheduled preds and succs (and associated latencies); try to place
74 the insn in the cycles of this window checking for potential
75 resource conflicts (using the DFA interface).
76 Note: this is different from the cycle-scheduling of schedule_insns;
77 here the insns are not scheduled monotonically top-down (nor bottom-
78 up).
79 3. If failed in scheduling all insns - bump II++ and try again, unless
80 II reaches an upper bound MaxII, in which case report failure.
81 5. If we succeeded in scheduling the loop within II cycles, we now
82 generate prolog and epilog, decrease the counter of the loop, and
83 perform modulo variable expansion for live ranges that span more than
84 II cycles (i.e. use register copies to prevent a def from overwriting
85 itself before reaching the use).
87 SMS works with countable loops (1) whose control part can be easily
88 decoupled from the rest of the loop and (2) whose loop count can
89 be easily adjusted. This is because we peel a constant number of
90 iterations into a prologue and epilogue for which we want to avoid
91 emitting the control part, and a kernel which is to iterate that
92 constant number of iterations less than the original loop. So the
93 control part should be a set of insns clearly identified and having
94 its own iv, not otherwise used in the loop (at-least for now), which
95 initializes a register before the loop to the number of iterations.
96 Currently SMS relies on the do-loop pattern to recognize such loops,
97 where (1) the control part comprises of all insns defining and/or
98 using a certain 'count' register and (2) the loop count can be
99 adjusted by modifying this register prior to the loop.
100 TODO: Rely on cfgloop analysis instead. */
102 /* This page defines partial-schedule structures and functions for
103 modulo scheduling. */
105 typedef struct partial_schedule *partial_schedule_ptr;
106 typedef struct ps_insn *ps_insn_ptr;
108 /* The minimum (absolute) cycle that a node of ps was scheduled in. */
109 #define PS_MIN_CYCLE(ps) (((partial_schedule_ptr)(ps))->min_cycle)
111 /* The maximum (absolute) cycle that a node of ps was scheduled in. */
112 #define PS_MAX_CYCLE(ps) (((partial_schedule_ptr)(ps))->max_cycle)
114 /* Perform signed modulo, always returning a non-negative value. */
115 #define SMODULO(x,y) ((x) % (y) < 0 ? ((x) % (y) + (y)) : (x) % (y))
117 /* The number of different iterations the nodes in ps span, assuming
118 the stage boundaries are placed efficiently. */
119 #define CALC_STAGE_COUNT(max_cycle,min_cycle,ii) ((max_cycle - min_cycle \
120 + 1 + ii - 1) / ii)
121 /* The stage count of ps. */
122 #define PS_STAGE_COUNT(ps) (((partial_schedule_ptr)(ps))->stage_count)
124 /* A single instruction in the partial schedule. */
125 struct ps_insn
127 /* The corresponding DDG_NODE. */
128 ddg_node_ptr node;
130 /* The (absolute) cycle in which the PS instruction is scheduled.
131 Same as SCHED_TIME (node). */
132 int cycle;
134 /* The next/prev PS_INSN in the same row. */
135 ps_insn_ptr next_in_row,
136 prev_in_row;
140 /* Holds the partial schedule as an array of II rows. Each entry of the
141 array points to a linked list of PS_INSNs, which represents the
142 instructions that are scheduled for that row. */
143 struct partial_schedule
145 int ii; /* Number of rows in the partial schedule. */
146 int history; /* Threshold for conflict checking using DFA. */
148 /* rows[i] points to linked list of insns scheduled in row i (0<=i<ii). */
149 ps_insn_ptr *rows;
151 /* rows_length[i] holds the number of instructions in the row.
152 It is used only (as an optimization) to back off quickly from
153 trying to schedule a node in a full row; that is, to avoid running
154 through futile DFA state transitions. */
155 int *rows_length;
157 /* The earliest absolute cycle of an insn in the partial schedule. */
158 int min_cycle;
160 /* The latest absolute cycle of an insn in the partial schedule. */
161 int max_cycle;
163 ddg_ptr g; /* The DDG of the insns in the partial schedule. */
165 int stage_count; /* The stage count of the partial schedule. */
168 /* We use this to record all the register replacements we do in
169 the kernel so we can undo SMS if it is not profitable. */
170 struct undo_replace_buff_elem
172 rtx insn;
173 rtx orig_reg;
174 rtx new_reg;
175 struct undo_replace_buff_elem *next;
180 static partial_schedule_ptr create_partial_schedule (int ii, ddg_ptr, int history);
181 static void free_partial_schedule (partial_schedule_ptr);
182 static void reset_partial_schedule (partial_schedule_ptr, int new_ii);
183 void print_partial_schedule (partial_schedule_ptr, FILE *);
184 static void verify_partial_schedule (partial_schedule_ptr, sbitmap);
185 static ps_insn_ptr ps_add_node_check_conflicts (partial_schedule_ptr,
186 ddg_node_ptr node, int cycle,
187 sbitmap must_precede,
188 sbitmap must_follow);
189 static void rotate_partial_schedule (partial_schedule_ptr, int);
190 void set_row_column_for_ps (partial_schedule_ptr);
191 static void ps_insert_empty_row (partial_schedule_ptr, int, sbitmap);
192 static int compute_split_row (sbitmap, int, int, int, ddg_node_ptr);
195 /* This page defines constants and structures for the modulo scheduling
196 driver. */
198 static int sms_order_nodes (ddg_ptr, int, int *, int *);
199 static void set_node_sched_params (ddg_ptr);
200 static partial_schedule_ptr sms_schedule_by_order (ddg_ptr, int, int, int *);
201 static void permute_partial_schedule (partial_schedule_ptr, rtx);
202 static void generate_prolog_epilog (partial_schedule_ptr, struct loop *,
203 rtx, rtx);
204 static void duplicate_insns_of_cycles (partial_schedule_ptr,
205 int, int, int, rtx);
206 static int calculate_stage_count (partial_schedule_ptr, int);
207 static void calculate_must_precede_follow (ddg_node_ptr, int, int,
208 int, int, sbitmap, sbitmap, sbitmap);
209 static int get_sched_window (partial_schedule_ptr, ddg_node_ptr,
210 sbitmap, int, int *, int *, int *);
211 static bool try_scheduling_node_in_cycle (partial_schedule_ptr, ddg_node_ptr,
212 int, int, sbitmap, int *, sbitmap,
213 sbitmap);
214 static void remove_node_from_ps (partial_schedule_ptr, ps_insn_ptr);
216 #define SCHED_ASAP(x) (((node_sched_params_ptr)(x)->aux.info)->asap)
217 #define SCHED_TIME(x) (((node_sched_params_ptr)(x)->aux.info)->time)
218 #define SCHED_FIRST_REG_MOVE(x) \
219 (((node_sched_params_ptr)(x)->aux.info)->first_reg_move)
220 #define SCHED_NREG_MOVES(x) \
221 (((node_sched_params_ptr)(x)->aux.info)->nreg_moves)
222 #define SCHED_ROW(x) (((node_sched_params_ptr)(x)->aux.info)->row)
223 #define SCHED_STAGE(x) (((node_sched_params_ptr)(x)->aux.info)->stage)
224 #define SCHED_COLUMN(x) (((node_sched_params_ptr)(x)->aux.info)->column)
226 /* The scheduling parameters held for each node. */
227 typedef struct node_sched_params
229 int asap; /* A lower-bound on the absolute scheduling cycle. */
230 int time; /* The absolute scheduling cycle (time >= asap). */
232 /* The following field (first_reg_move) is a pointer to the first
233 register-move instruction added to handle the modulo-variable-expansion
234 of the register defined by this node. This register-move copies the
235 original register defined by the node. */
236 rtx first_reg_move;
238 /* The number of register-move instructions added, immediately preceding
239 first_reg_move. */
240 int nreg_moves;
242 int row; /* Holds time % ii. */
243 int stage; /* Holds time / ii. */
245 /* The column of a node inside the ps. If nodes u, v are on the same row,
246 u will precede v if column (u) < column (v). */
247 int column;
248 } *node_sched_params_ptr;
251 /* The following three functions are copied from the current scheduler
252 code in order to use sched_analyze() for computing the dependencies.
253 They are used when initializing the sched_info structure. */
254 static const char *
255 sms_print_insn (const_rtx insn, int aligned ATTRIBUTE_UNUSED)
257 static char tmp[80];
259 sprintf (tmp, "i%4d", INSN_UID (insn));
260 return tmp;
263 static void
264 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
265 regset used ATTRIBUTE_UNUSED)
269 static struct common_sched_info_def sms_common_sched_info;
271 static struct sched_deps_info_def sms_sched_deps_info =
273 compute_jump_reg_dependencies,
274 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
275 NULL,
276 0, 0, 0
279 static struct haifa_sched_info sms_sched_info =
281 NULL,
282 NULL,
283 NULL,
284 NULL,
285 NULL,
286 sms_print_insn,
287 NULL,
288 NULL, /* insn_finishes_block_p */
289 NULL, NULL,
290 NULL, NULL,
291 0, 0,
293 NULL, NULL, NULL, NULL,
294 NULL, NULL,
298 /* Given HEAD and TAIL which are the first and last insns in a loop;
299 return the register which controls the loop. Return zero if it has
300 more than one occurrence in the loop besides the control part or the
301 do-loop pattern is not of the form we expect. */
302 static rtx
303 doloop_register_get (rtx head ATTRIBUTE_UNUSED, rtx tail ATTRIBUTE_UNUSED)
305 #ifdef HAVE_doloop_end
306 rtx reg, condition, insn, first_insn_not_to_check;
308 if (!JUMP_P (tail))
309 return NULL_RTX;
311 /* TODO: Free SMS's dependence on doloop_condition_get. */
312 condition = doloop_condition_get (tail);
313 if (! condition)
314 return NULL_RTX;
316 if (REG_P (XEXP (condition, 0)))
317 reg = XEXP (condition, 0);
318 else if (GET_CODE (XEXP (condition, 0)) == PLUS
319 && REG_P (XEXP (XEXP (condition, 0), 0)))
320 reg = XEXP (XEXP (condition, 0), 0);
321 else
322 gcc_unreachable ();
324 /* Check that the COUNT_REG has no other occurrences in the loop
325 until the decrement. We assume the control part consists of
326 either a single (parallel) branch-on-count or a (non-parallel)
327 branch immediately preceded by a single (decrement) insn. */
328 first_insn_not_to_check = (GET_CODE (PATTERN (tail)) == PARALLEL ? tail
329 : prev_nondebug_insn (tail));
331 for (insn = head; insn != first_insn_not_to_check; insn = NEXT_INSN (insn))
332 if (!DEBUG_INSN_P (insn) && reg_mentioned_p (reg, insn))
334 if (dump_file)
336 fprintf (dump_file, "SMS count_reg found ");
337 print_rtl_single (dump_file, reg);
338 fprintf (dump_file, " outside control in insn:\n");
339 print_rtl_single (dump_file, insn);
342 return NULL_RTX;
345 return reg;
346 #else
347 return NULL_RTX;
348 #endif
351 /* Check if COUNT_REG is set to a constant in the PRE_HEADER block, so
352 that the number of iterations is a compile-time constant. If so,
353 return the rtx that sets COUNT_REG to a constant, and set COUNT to
354 this constant. Otherwise return 0. */
355 static rtx
356 const_iteration_count (rtx count_reg, basic_block pre_header,
357 HOST_WIDEST_INT * count)
359 rtx insn;
360 rtx head, tail;
362 if (! pre_header)
363 return NULL_RTX;
365 get_ebb_head_tail (pre_header, pre_header, &head, &tail);
367 for (insn = tail; insn != PREV_INSN (head); insn = PREV_INSN (insn))
368 if (NONDEBUG_INSN_P (insn) && single_set (insn) &&
369 rtx_equal_p (count_reg, SET_DEST (single_set (insn))))
371 rtx pat = single_set (insn);
373 if (CONST_INT_P (SET_SRC (pat)))
375 *count = INTVAL (SET_SRC (pat));
376 return insn;
379 return NULL_RTX;
382 return NULL_RTX;
385 /* A very simple resource-based lower bound on the initiation interval.
386 ??? Improve the accuracy of this bound by considering the
387 utilization of various units. */
388 static int
389 res_MII (ddg_ptr g)
391 if (targetm.sched.sms_res_mii)
392 return targetm.sched.sms_res_mii (g);
394 return ((g->num_nodes - g->num_debug) / issue_rate);
398 /* Points to the array that contains the sched data for each node. */
399 static node_sched_params_ptr node_sched_params;
401 /* Allocate sched_params for each node and initialize it. Assumes that
402 the aux field of each node contain the asap bound (computed earlier),
403 and copies it into the sched_params field. */
404 static void
405 set_node_sched_params (ddg_ptr g)
407 int i;
409 /* Allocate for each node in the DDG a place to hold the "sched_data". */
410 /* Initialize ASAP/ALAP/HIGHT to zero. */
411 node_sched_params = (node_sched_params_ptr)
412 xcalloc (g->num_nodes,
413 sizeof (struct node_sched_params));
415 /* Set the pointer of the general data of the node to point to the
416 appropriate sched_params structure. */
417 for (i = 0; i < g->num_nodes; i++)
419 /* Watch out for aliasing problems? */
420 node_sched_params[i].asap = g->nodes[i].aux.count;
421 g->nodes[i].aux.info = &node_sched_params[i];
425 static void
426 print_node_sched_params (FILE *file, int num_nodes, ddg_ptr g)
428 int i;
430 if (! file)
431 return;
432 for (i = 0; i < num_nodes; i++)
434 node_sched_params_ptr nsp = &node_sched_params[i];
435 rtx reg_move = nsp->first_reg_move;
436 int j;
438 fprintf (file, "Node = %d; INSN = %d\n", i,
439 (INSN_UID (g->nodes[i].insn)));
440 fprintf (file, " asap = %d:\n", nsp->asap);
441 fprintf (file, " time = %d:\n", nsp->time);
442 fprintf (file, " nreg_moves = %d:\n", nsp->nreg_moves);
443 for (j = 0; j < nsp->nreg_moves; j++)
445 fprintf (file, " reg_move = ");
446 print_rtl_single (file, reg_move);
447 reg_move = PREV_INSN (reg_move);
453 Breaking intra-loop register anti-dependences:
454 Each intra-loop register anti-dependence implies a cross-iteration true
455 dependence of distance 1. Therefore, we can remove such false dependencies
456 and figure out if the partial schedule broke them by checking if (for a
457 true-dependence of distance 1): SCHED_TIME (def) < SCHED_TIME (use) and
458 if so generate a register move. The number of such moves is equal to:
459 SCHED_TIME (use) - SCHED_TIME (def) { 0 broken
460 nreg_moves = ----------------------------------- + 1 - { dependence.
461 ii { 1 if not.
463 static struct undo_replace_buff_elem *
464 generate_reg_moves (partial_schedule_ptr ps, bool rescan)
466 ddg_ptr g = ps->g;
467 int ii = ps->ii;
468 int i;
469 struct undo_replace_buff_elem *reg_move_replaces = NULL;
471 for (i = 0; i < g->num_nodes; i++)
473 ddg_node_ptr u = &g->nodes[i];
474 ddg_edge_ptr e;
475 int nreg_moves = 0, i_reg_move;
476 sbitmap *uses_of_defs;
477 rtx last_reg_move;
478 rtx prev_reg, old_reg;
480 /* Compute the number of reg_moves needed for u, by looking at life
481 ranges started at u (excluding self-loops). */
482 for (e = u->out; e; e = e->next_out)
483 if (e->type == TRUE_DEP && e->dest != e->src)
485 int nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
487 if (e->distance == 1)
488 nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
490 /* If dest precedes src in the schedule of the kernel, then dest
491 will read before src writes and we can save one reg_copy. */
492 if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
493 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
494 nreg_moves4e--;
496 nreg_moves = MAX (nreg_moves, nreg_moves4e);
499 if (nreg_moves == 0)
500 continue;
502 /* Every use of the register defined by node may require a different
503 copy of this register, depending on the time the use is scheduled.
504 Set a bitmap vector, telling which nodes use each copy of this
505 register. */
506 uses_of_defs = sbitmap_vector_alloc (nreg_moves, g->num_nodes);
507 sbitmap_vector_zero (uses_of_defs, nreg_moves);
508 for (e = u->out; e; e = e->next_out)
509 if (e->type == TRUE_DEP && e->dest != e->src)
511 int dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
513 if (e->distance == 1)
514 dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
516 if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
517 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
518 dest_copy--;
520 if (dest_copy)
521 SET_BIT (uses_of_defs[dest_copy - 1], e->dest->cuid);
524 /* Now generate the reg_moves, attaching relevant uses to them. */
525 SCHED_NREG_MOVES (u) = nreg_moves;
526 old_reg = prev_reg = copy_rtx (SET_DEST (single_set (u->insn)));
527 /* Insert the reg-moves right before the notes which precede
528 the insn they relates to. */
529 last_reg_move = u->first_note;
531 for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
533 unsigned int i_use = 0;
534 rtx new_reg = gen_reg_rtx (GET_MODE (prev_reg));
535 rtx reg_move = gen_move_insn (new_reg, prev_reg);
536 sbitmap_iterator sbi;
538 add_insn_before (reg_move, last_reg_move, NULL);
539 last_reg_move = reg_move;
541 if (!SCHED_FIRST_REG_MOVE (u))
542 SCHED_FIRST_REG_MOVE (u) = reg_move;
544 EXECUTE_IF_SET_IN_SBITMAP (uses_of_defs[i_reg_move], 0, i_use, sbi)
546 struct undo_replace_buff_elem *rep;
548 rep = (struct undo_replace_buff_elem *)
549 xcalloc (1, sizeof (struct undo_replace_buff_elem));
550 rep->insn = g->nodes[i_use].insn;
551 rep->orig_reg = old_reg;
552 rep->new_reg = new_reg;
554 if (! reg_move_replaces)
555 reg_move_replaces = rep;
556 else
558 rep->next = reg_move_replaces;
559 reg_move_replaces = rep;
562 replace_rtx (g->nodes[i_use].insn, old_reg, new_reg);
563 if (rescan)
564 df_insn_rescan (g->nodes[i_use].insn);
567 prev_reg = new_reg;
569 sbitmap_vector_free (uses_of_defs);
571 return reg_move_replaces;
574 /* Free memory allocated for the undo buffer. */
575 static void
576 free_undo_replace_buff (struct undo_replace_buff_elem *reg_move_replaces)
579 while (reg_move_replaces)
581 struct undo_replace_buff_elem *rep = reg_move_replaces;
583 reg_move_replaces = reg_move_replaces->next;
584 free (rep);
588 /* Update the sched_params (time, row and stage) for node U using the II,
589 the CYCLE of U and MIN_CYCLE.
590 We're not simply taking the following
591 SCHED_STAGE (u) = CALC_STAGE_COUNT (SCHED_TIME (u), min_cycle, ii);
592 because the stages may not be aligned on cycle 0. */
593 static void
594 update_node_sched_params (ddg_node_ptr u, int ii, int cycle, int min_cycle)
596 int sc_until_cycle_zero;
597 int stage;
599 SCHED_TIME (u) = cycle;
600 SCHED_ROW (u) = SMODULO (cycle, ii);
602 /* The calculation of stage count is done adding the number
603 of stages before cycle zero and after cycle zero. */
604 sc_until_cycle_zero = CALC_STAGE_COUNT (-1, min_cycle, ii);
606 if (SCHED_TIME (u) < 0)
608 stage = CALC_STAGE_COUNT (-1, SCHED_TIME (u), ii);
609 SCHED_STAGE (u) = sc_until_cycle_zero - stage;
611 else
613 stage = CALC_STAGE_COUNT (SCHED_TIME (u), 0, ii);
614 SCHED_STAGE (u) = sc_until_cycle_zero + stage - 1;
618 /* Bump the SCHED_TIMEs of all nodes by AMOUNT. Set the values of
619 SCHED_ROW and SCHED_STAGE. Instruction scheduled on cycle AMOUNT
620 will move to cycle zero. */
621 static void
622 reset_sched_times (partial_schedule_ptr ps, int amount)
624 int row;
625 int ii = ps->ii;
626 ps_insn_ptr crr_insn;
628 for (row = 0; row < ii; row++)
629 for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
631 ddg_node_ptr u = crr_insn->node;
632 int normalized_time = SCHED_TIME (u) - amount;
633 int new_min_cycle = PS_MIN_CYCLE (ps) - amount;
635 if (dump_file)
637 /* Print the scheduling times after the rotation. */
638 fprintf (dump_file, "crr_insn->node=%d (insn id %d), "
639 "crr_insn->cycle=%d, min_cycle=%d", crr_insn->node->cuid,
640 INSN_UID (crr_insn->node->insn), normalized_time,
641 new_min_cycle);
642 if (JUMP_P (crr_insn->node->insn))
643 fprintf (dump_file, " (branch)");
644 fprintf (dump_file, "\n");
647 gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
648 gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
650 crr_insn->cycle = normalized_time;
651 update_node_sched_params (u, ii, normalized_time, new_min_cycle);
655 /* Set SCHED_COLUMN of each node according to its position in PS. */
656 static void
657 set_columns_for_ps (partial_schedule_ptr ps)
659 int row;
661 for (row = 0; row < ps->ii; row++)
663 ps_insn_ptr cur_insn = ps->rows[row];
664 int column = 0;
666 for (; cur_insn; cur_insn = cur_insn->next_in_row)
667 SCHED_COLUMN (cur_insn->node) = column++;
671 /* Permute the insns according to their order in PS, from row 0 to
672 row ii-1, and position them right before LAST. This schedules
673 the insns of the loop kernel. */
674 static void
675 permute_partial_schedule (partial_schedule_ptr ps, rtx last)
677 int ii = ps->ii;
678 int row;
679 ps_insn_ptr ps_ij;
681 for (row = 0; row < ii ; row++)
682 for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
683 if (PREV_INSN (last) != ps_ij->node->insn)
684 reorder_insns_nobb (ps_ij->node->first_note, ps_ij->node->insn,
685 PREV_INSN (last));
688 /* Set bitmaps TMP_FOLLOW and TMP_PRECEDE to MUST_FOLLOW and MUST_PRECEDE
689 respectively only if cycle C falls on the border of the scheduling
690 window boundaries marked by START and END cycles. STEP is the
691 direction of the window. */
692 static inline void
693 set_must_precede_follow (sbitmap *tmp_follow, sbitmap must_follow,
694 sbitmap *tmp_precede, sbitmap must_precede, int c,
695 int start, int end, int step)
697 *tmp_precede = NULL;
698 *tmp_follow = NULL;
700 if (c == start)
702 if (step == 1)
703 *tmp_precede = must_precede;
704 else /* step == -1. */
705 *tmp_follow = must_follow;
707 if (c == end - step)
709 if (step == 1)
710 *tmp_follow = must_follow;
711 else /* step == -1. */
712 *tmp_precede = must_precede;
717 /* Return True if the branch can be moved to row ii-1 while
718 normalizing the partial schedule PS to start from cycle zero and thus
719 optimize the SC. Otherwise return False. */
720 static bool
721 optimize_sc (partial_schedule_ptr ps, ddg_ptr g)
723 int amount = PS_MIN_CYCLE (ps);
724 sbitmap sched_nodes = sbitmap_alloc (g->num_nodes);
725 int start, end, step;
726 int ii = ps->ii;
727 bool ok = false;
728 int stage_count, stage_count_curr;
730 /* Compare the SC after normalization and SC after bringing the branch
731 to row ii-1. If they are equal just bail out. */
732 stage_count = calculate_stage_count (ps, amount);
733 stage_count_curr =
734 calculate_stage_count (ps, SCHED_TIME (g->closing_branch) - (ii - 1));
736 if (stage_count == stage_count_curr)
738 if (dump_file)
739 fprintf (dump_file, "SMS SC already optimized.\n");
741 ok = false;
742 goto clear;
745 if (dump_file)
747 fprintf (dump_file, "SMS Trying to optimize branch location\n");
748 fprintf (dump_file, "SMS partial schedule before trial:\n");
749 print_partial_schedule (ps, dump_file);
752 /* First, normalize the partial scheduling. */
753 reset_sched_times (ps, amount);
754 rotate_partial_schedule (ps, amount);
755 if (dump_file)
757 fprintf (dump_file,
758 "SMS partial schedule after normalization (ii, %d, SC %d):\n",
759 ii, stage_count);
760 print_partial_schedule (ps, dump_file);
763 if (SMODULO (SCHED_TIME (g->closing_branch), ii) == ii - 1)
765 ok = true;
766 goto clear;
769 sbitmap_ones (sched_nodes);
771 /* Calculate the new placement of the branch. It should be in row
772 ii-1 and fall into it's scheduling window. */
773 if (get_sched_window (ps, g->closing_branch, sched_nodes, ii, &start,
774 &step, &end) == 0)
776 bool success;
777 ps_insn_ptr next_ps_i;
778 int branch_cycle = SCHED_TIME (g->closing_branch);
779 int row = SMODULO (branch_cycle, ps->ii);
780 int num_splits = 0;
781 sbitmap must_precede, must_follow, tmp_precede, tmp_follow;
782 int c;
784 if (dump_file)
785 fprintf (dump_file, "\nTrying to schedule node %d "
786 "INSN = %d in (%d .. %d) step %d\n",
787 g->closing_branch->cuid,
788 (INSN_UID (g->closing_branch->insn)), start, end, step);
790 gcc_assert ((step > 0 && start < end) || (step < 0 && start > end));
791 if (step == 1)
793 c = start + ii - SMODULO (start, ii) - 1;
794 gcc_assert (c >= start);
795 if (c >= end)
797 ok = false;
798 if (dump_file)
799 fprintf (dump_file,
800 "SMS failed to schedule branch at cycle: %d\n", c);
801 goto clear;
804 else
806 c = start - SMODULO (start, ii) - 1;
807 gcc_assert (c <= start);
809 if (c <= end)
811 if (dump_file)
812 fprintf (dump_file,
813 "SMS failed to schedule branch at cycle: %d\n", c);
814 ok = false;
815 goto clear;
819 must_precede = sbitmap_alloc (g->num_nodes);
820 must_follow = sbitmap_alloc (g->num_nodes);
822 /* Try to schedule the branch is it's new cycle. */
823 calculate_must_precede_follow (g->closing_branch, start, end,
824 step, ii, sched_nodes,
825 must_precede, must_follow);
827 set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
828 must_precede, c, start, end, step);
830 /* Find the element in the partial schedule related to the closing
831 branch so we can remove it from it's current cycle. */
832 for (next_ps_i = ps->rows[row];
833 next_ps_i; next_ps_i = next_ps_i->next_in_row)
834 if (next_ps_i->node->cuid == g->closing_branch->cuid)
835 break;
837 remove_node_from_ps (ps, next_ps_i);
838 success =
839 try_scheduling_node_in_cycle (ps, g->closing_branch,
840 g->closing_branch->cuid, c,
841 sched_nodes, &num_splits,
842 tmp_precede, tmp_follow);
843 gcc_assert (num_splits == 0);
844 if (!success)
846 if (dump_file)
847 fprintf (dump_file,
848 "SMS failed to schedule branch at cycle: %d, "
849 "bringing it back to cycle %d\n", c, branch_cycle);
851 /* The branch was failed to be placed in row ii - 1.
852 Put it back in it's original place in the partial
853 schedualing. */
854 set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
855 must_precede, branch_cycle, start, end,
856 step);
857 success =
858 try_scheduling_node_in_cycle (ps, g->closing_branch,
859 g->closing_branch->cuid,
860 branch_cycle, sched_nodes,
861 &num_splits, tmp_precede,
862 tmp_follow);
863 gcc_assert (success && (num_splits == 0));
864 ok = false;
866 else
868 /* The branch is placed in row ii - 1. */
869 if (dump_file)
870 fprintf (dump_file,
871 "SMS success in moving branch to cycle %d\n", c);
873 update_node_sched_params (g->closing_branch, ii, c,
874 PS_MIN_CYCLE (ps));
875 ok = true;
878 free (must_precede);
879 free (must_follow);
882 clear:
883 free (sched_nodes);
884 return ok;
887 static void
888 duplicate_insns_of_cycles (partial_schedule_ptr ps, int from_stage,
889 int to_stage, int for_prolog, rtx count_reg)
891 int row;
892 ps_insn_ptr ps_ij;
894 for (row = 0; row < ps->ii; row++)
895 for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
897 ddg_node_ptr u_node = ps_ij->node;
898 int j, i_reg_moves;
899 rtx reg_move = NULL_RTX;
901 /* Do not duplicate any insn which refers to count_reg as it
902 belongs to the control part.
903 The closing branch is scheduled as well and thus should
904 be ignored.
905 TODO: This should be done by analyzing the control part of
906 the loop. */
907 if (reg_mentioned_p (count_reg, u_node->insn)
908 || JUMP_P (ps_ij->node->insn))
909 continue;
911 if (for_prolog)
913 /* SCHED_STAGE (u_node) >= from_stage == 0. Generate increasing
914 number of reg_moves starting with the second occurrence of
915 u_node, which is generated if its SCHED_STAGE <= to_stage. */
916 i_reg_moves = to_stage - SCHED_STAGE (u_node) + 1;
917 i_reg_moves = MAX (i_reg_moves, 0);
918 i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
920 /* The reg_moves start from the *first* reg_move backwards. */
921 if (i_reg_moves)
923 reg_move = SCHED_FIRST_REG_MOVE (u_node);
924 for (j = 1; j < i_reg_moves; j++)
925 reg_move = PREV_INSN (reg_move);
928 else /* It's for the epilog. */
930 /* SCHED_STAGE (u_node) <= to_stage. Generate all reg_moves,
931 starting to decrease one stage after u_node no longer occurs;
932 that is, generate all reg_moves until
933 SCHED_STAGE (u_node) == from_stage - 1. */
934 i_reg_moves = SCHED_NREG_MOVES (u_node)
935 - (from_stage - SCHED_STAGE (u_node) - 1);
936 i_reg_moves = MAX (i_reg_moves, 0);
937 i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
939 /* The reg_moves start from the *last* reg_move forwards. */
940 if (i_reg_moves)
942 reg_move = SCHED_FIRST_REG_MOVE (u_node);
943 for (j = 1; j < SCHED_NREG_MOVES (u_node); j++)
944 reg_move = PREV_INSN (reg_move);
948 for (j = 0; j < i_reg_moves; j++, reg_move = NEXT_INSN (reg_move))
949 emit_insn (copy_rtx (PATTERN (reg_move)));
950 if (SCHED_STAGE (u_node) >= from_stage
951 && SCHED_STAGE (u_node) <= to_stage)
952 duplicate_insn_chain (u_node->first_note, u_node->insn);
957 /* Generate the instructions (including reg_moves) for prolog & epilog. */
958 static void
959 generate_prolog_epilog (partial_schedule_ptr ps, struct loop *loop,
960 rtx count_reg, rtx count_init)
962 int i;
963 int last_stage = PS_STAGE_COUNT (ps) - 1;
964 edge e;
966 /* Generate the prolog, inserting its insns on the loop-entry edge. */
967 start_sequence ();
969 if (!count_init)
971 /* Generate instructions at the beginning of the prolog to
972 adjust the loop count by STAGE_COUNT. If loop count is constant
973 (count_init), this constant is adjusted by STAGE_COUNT in
974 generate_prolog_epilog function. */
975 rtx sub_reg = NULL_RTX;
977 sub_reg = expand_simple_binop (GET_MODE (count_reg), MINUS,
978 count_reg, GEN_INT (last_stage),
979 count_reg, 1, OPTAB_DIRECT);
980 gcc_assert (REG_P (sub_reg));
981 if (REGNO (sub_reg) != REGNO (count_reg))
982 emit_move_insn (count_reg, sub_reg);
985 for (i = 0; i < last_stage; i++)
986 duplicate_insns_of_cycles (ps, 0, i, 1, count_reg);
988 /* Put the prolog on the entry edge. */
989 e = loop_preheader_edge (loop);
990 split_edge_and_insert (e, get_insns ());
992 end_sequence ();
994 /* Generate the epilog, inserting its insns on the loop-exit edge. */
995 start_sequence ();
997 for (i = 0; i < last_stage; i++)
998 duplicate_insns_of_cycles (ps, i + 1, last_stage, 0, count_reg);
1000 /* Put the epilogue on the exit edge. */
1001 gcc_assert (single_exit (loop));
1002 e = single_exit (loop);
1003 split_edge_and_insert (e, get_insns ());
1004 end_sequence ();
1007 /* Return true if all the BBs of the loop are empty except the
1008 loop header. */
1009 static bool
1010 loop_single_full_bb_p (struct loop *loop)
1012 unsigned i;
1013 basic_block *bbs = get_loop_body (loop);
1015 for (i = 0; i < loop->num_nodes ; i++)
1017 rtx head, tail;
1018 bool empty_bb = true;
1020 if (bbs[i] == loop->header)
1021 continue;
1023 /* Make sure that basic blocks other than the header
1024 have only notes labels or jumps. */
1025 get_ebb_head_tail (bbs[i], bbs[i], &head, &tail);
1026 for (; head != NEXT_INSN (tail); head = NEXT_INSN (head))
1028 if (NOTE_P (head) || LABEL_P (head)
1029 || (INSN_P (head) && (DEBUG_INSN_P (head) || JUMP_P (head))))
1030 continue;
1031 empty_bb = false;
1032 break;
1035 if (! empty_bb)
1037 free (bbs);
1038 return false;
1041 free (bbs);
1042 return true;
1045 /* A simple loop from SMS point of view; it is a loop that is composed of
1046 either a single basic block or two BBs - a header and a latch. */
1047 #define SIMPLE_SMS_LOOP_P(loop) ((loop->num_nodes < 3 ) \
1048 && (EDGE_COUNT (loop->latch->preds) == 1) \
1049 && (EDGE_COUNT (loop->latch->succs) == 1))
1051 /* Return true if the loop is in its canonical form and false if not.
1052 i.e. SIMPLE_SMS_LOOP_P and have one preheader block, and single exit. */
1053 static bool
1054 loop_canon_p (struct loop *loop)
1057 if (loop->inner || !loop_outer (loop))
1059 if (dump_file)
1060 fprintf (dump_file, "SMS loop inner or !loop_outer\n");
1061 return false;
1064 if (!single_exit (loop))
1066 if (dump_file)
1068 rtx insn = BB_END (loop->header);
1070 fprintf (dump_file, "SMS loop many exits ");
1071 fprintf (dump_file, " %s %d (file, line)\n",
1072 insn_file (insn), insn_line (insn));
1074 return false;
1077 if (! SIMPLE_SMS_LOOP_P (loop) && ! loop_single_full_bb_p (loop))
1079 if (dump_file)
1081 rtx insn = BB_END (loop->header);
1083 fprintf (dump_file, "SMS loop many BBs. ");
1084 fprintf (dump_file, " %s %d (file, line)\n",
1085 insn_file (insn), insn_line (insn));
1087 return false;
1090 return true;
1093 /* If there are more than one entry for the loop,
1094 make it one by splitting the first entry edge and
1095 redirecting the others to the new BB. */
1096 static void
1097 canon_loop (struct loop *loop)
1099 edge e;
1100 edge_iterator i;
1102 /* Avoid annoying special cases of edges going to exit
1103 block. */
1104 FOR_EACH_EDGE (e, i, EXIT_BLOCK_PTR->preds)
1105 if ((e->flags & EDGE_FALLTHRU) && (EDGE_COUNT (e->src->succs) > 1))
1106 split_edge (e);
1108 if (loop->latch == loop->header
1109 || EDGE_COUNT (loop->latch->succs) > 1)
1111 FOR_EACH_EDGE (e, i, loop->header->preds)
1112 if (e->src == loop->latch)
1113 break;
1114 split_edge (e);
1118 /* Setup infos. */
1119 static void
1120 setup_sched_infos (void)
1122 memcpy (&sms_common_sched_info, &haifa_common_sched_info,
1123 sizeof (sms_common_sched_info));
1124 sms_common_sched_info.sched_pass_id = SCHED_SMS_PASS;
1125 common_sched_info = &sms_common_sched_info;
1127 sched_deps_info = &sms_sched_deps_info;
1128 current_sched_info = &sms_sched_info;
1131 /* Probability in % that the sms-ed loop rolls enough so that optimized
1132 version may be entered. Just a guess. */
1133 #define PROB_SMS_ENOUGH_ITERATIONS 80
1135 /* Used to calculate the upper bound of ii. */
1136 #define MAXII_FACTOR 2
1138 /* Main entry point, perform SMS scheduling on the loops of the function
1139 that consist of single basic blocks. */
1140 static void
1141 sms_schedule (void)
1143 rtx insn;
1144 ddg_ptr *g_arr, g;
1145 int * node_order;
1146 int maxii, max_asap;
1147 loop_iterator li;
1148 partial_schedule_ptr ps;
1149 basic_block bb = NULL;
1150 struct loop *loop;
1151 basic_block condition_bb = NULL;
1152 edge latch_edge;
1153 gcov_type trip_count = 0;
1155 loop_optimizer_init (LOOPS_HAVE_PREHEADERS
1156 | LOOPS_HAVE_RECORDED_EXITS);
1157 if (number_of_loops () <= 1)
1159 loop_optimizer_finalize ();
1160 return; /* There are no loops to schedule. */
1163 /* Initialize issue_rate. */
1164 if (targetm.sched.issue_rate)
1166 int temp = reload_completed;
1168 reload_completed = 1;
1169 issue_rate = targetm.sched.issue_rate ();
1170 reload_completed = temp;
1172 else
1173 issue_rate = 1;
1175 /* Initialize the scheduler. */
1176 setup_sched_infos ();
1177 haifa_sched_init ();
1179 /* Allocate memory to hold the DDG array one entry for each loop.
1180 We use loop->num as index into this array. */
1181 g_arr = XCNEWVEC (ddg_ptr, number_of_loops ());
1183 if (dump_file)
1185 fprintf (dump_file, "\n\nSMS analysis phase\n");
1186 fprintf (dump_file, "===================\n\n");
1189 /* Build DDGs for all the relevant loops and hold them in G_ARR
1190 indexed by the loop index. */
1191 FOR_EACH_LOOP (li, loop, 0)
1193 rtx head, tail;
1194 rtx count_reg;
1196 /* For debugging. */
1197 if (dbg_cnt (sms_sched_loop) == false)
1199 if (dump_file)
1200 fprintf (dump_file, "SMS reached max limit... \n");
1202 break;
1205 if (dump_file)
1207 rtx insn = BB_END (loop->header);
1209 fprintf (dump_file, "SMS loop num: %d, file: %s, line: %d\n",
1210 loop->num, insn_file (insn), insn_line (insn));
1214 if (! loop_canon_p (loop))
1215 continue;
1217 if (! loop_single_full_bb_p (loop))
1219 if (dump_file)
1220 fprintf (dump_file, "SMS not loop_single_full_bb_p\n");
1221 continue;
1224 bb = loop->header;
1226 get_ebb_head_tail (bb, bb, &head, &tail);
1227 latch_edge = loop_latch_edge (loop);
1228 gcc_assert (single_exit (loop));
1229 if (single_exit (loop)->count)
1230 trip_count = latch_edge->count / single_exit (loop)->count;
1232 /* Perform SMS only on loops that their average count is above threshold. */
1234 if ( latch_edge->count
1235 && (latch_edge->count < single_exit (loop)->count * SMS_LOOP_AVERAGE_COUNT_THRESHOLD))
1237 if (dump_file)
1239 fprintf (dump_file, " %s %d (file, line)\n",
1240 insn_file (tail), insn_line (tail));
1241 fprintf (dump_file, "SMS single-bb-loop\n");
1242 if (profile_info && flag_branch_probabilities)
1244 fprintf (dump_file, "SMS loop-count ");
1245 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1246 (HOST_WIDEST_INT) bb->count);
1247 fprintf (dump_file, "\n");
1248 fprintf (dump_file, "SMS trip-count ");
1249 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1250 (HOST_WIDEST_INT) trip_count);
1251 fprintf (dump_file, "\n");
1252 fprintf (dump_file, "SMS profile-sum-max ");
1253 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1254 (HOST_WIDEST_INT) profile_info->sum_max);
1255 fprintf (dump_file, "\n");
1258 continue;
1261 /* Make sure this is a doloop. */
1262 if ( !(count_reg = doloop_register_get (head, tail)))
1264 if (dump_file)
1265 fprintf (dump_file, "SMS doloop_register_get failed\n");
1266 continue;
1269 /* Don't handle BBs with calls or barriers or auto-increment insns
1270 (to avoid creating invalid reg-moves for the auto-increment insns),
1271 or !single_set with the exception of instructions that include
1272 count_reg---these instructions are part of the control part
1273 that do-loop recognizes.
1274 ??? Should handle auto-increment insns.
1275 ??? Should handle insns defining subregs. */
1276 for (insn = head; insn != NEXT_INSN (tail); insn = NEXT_INSN (insn))
1278 rtx set;
1280 if (CALL_P (insn)
1281 || BARRIER_P (insn)
1282 || (NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1283 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE
1284 && !reg_mentioned_p (count_reg, insn))
1285 || (FIND_REG_INC_NOTE (insn, NULL_RTX) != 0)
1286 || (INSN_P (insn) && (set = single_set (insn))
1287 && GET_CODE (SET_DEST (set)) == SUBREG))
1288 break;
1291 if (insn != NEXT_INSN (tail))
1293 if (dump_file)
1295 if (CALL_P (insn))
1296 fprintf (dump_file, "SMS loop-with-call\n");
1297 else if (BARRIER_P (insn))
1298 fprintf (dump_file, "SMS loop-with-barrier\n");
1299 else if (FIND_REG_INC_NOTE (insn, NULL_RTX) != 0)
1300 fprintf (dump_file, "SMS reg inc\n");
1301 else if ((NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1302 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE))
1303 fprintf (dump_file, "SMS loop-with-not-single-set\n");
1304 else
1305 fprintf (dump_file, "SMS loop with subreg in lhs\n");
1306 print_rtl_single (dump_file, insn);
1309 continue;
1312 /* Always schedule the closing branch with the rest of the
1313 instructions. The branch is rotated to be in row ii-1 at the
1314 end of the scheduling procedure to make sure it's the last
1315 instruction in the iteration. */
1316 if (! (g = create_ddg (bb, 1)))
1318 if (dump_file)
1319 fprintf (dump_file, "SMS create_ddg failed\n");
1320 continue;
1323 g_arr[loop->num] = g;
1324 if (dump_file)
1325 fprintf (dump_file, "...OK\n");
1328 if (dump_file)
1330 fprintf (dump_file, "\nSMS transformation phase\n");
1331 fprintf (dump_file, "=========================\n\n");
1334 /* We don't want to perform SMS on new loops - created by versioning. */
1335 FOR_EACH_LOOP (li, loop, 0)
1337 rtx head, tail;
1338 rtx count_reg, count_init;
1339 int mii, rec_mii;
1340 unsigned stage_count = 0;
1341 HOST_WIDEST_INT loop_count = 0;
1342 bool opt_sc_p = false;
1344 if (! (g = g_arr[loop->num]))
1345 continue;
1347 if (dump_file)
1349 rtx insn = BB_END (loop->header);
1351 fprintf (dump_file, "SMS loop num: %d, file: %s, line: %d\n",
1352 loop->num, insn_file (insn), insn_line (insn));
1354 print_ddg (dump_file, g);
1357 get_ebb_head_tail (loop->header, loop->header, &head, &tail);
1359 latch_edge = loop_latch_edge (loop);
1360 gcc_assert (single_exit (loop));
1361 if (single_exit (loop)->count)
1362 trip_count = latch_edge->count / single_exit (loop)->count;
1364 if (dump_file)
1366 fprintf (dump_file, " %s %d (file, line)\n",
1367 insn_file (tail), insn_line (tail));
1368 fprintf (dump_file, "SMS single-bb-loop\n");
1369 if (profile_info && flag_branch_probabilities)
1371 fprintf (dump_file, "SMS loop-count ");
1372 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1373 (HOST_WIDEST_INT) bb->count);
1374 fprintf (dump_file, "\n");
1375 fprintf (dump_file, "SMS profile-sum-max ");
1376 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1377 (HOST_WIDEST_INT) profile_info->sum_max);
1378 fprintf (dump_file, "\n");
1380 fprintf (dump_file, "SMS doloop\n");
1381 fprintf (dump_file, "SMS built-ddg %d\n", g->num_nodes);
1382 fprintf (dump_file, "SMS num-loads %d\n", g->num_loads);
1383 fprintf (dump_file, "SMS num-stores %d\n", g->num_stores);
1387 /* In case of th loop have doloop register it gets special
1388 handling. */
1389 count_init = NULL_RTX;
1390 if ((count_reg = doloop_register_get (head, tail)))
1392 basic_block pre_header;
1394 pre_header = loop_preheader_edge (loop)->src;
1395 count_init = const_iteration_count (count_reg, pre_header,
1396 &loop_count);
1398 gcc_assert (count_reg);
1400 if (dump_file && count_init)
1402 fprintf (dump_file, "SMS const-doloop ");
1403 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1404 loop_count);
1405 fprintf (dump_file, "\n");
1408 node_order = XNEWVEC (int, g->num_nodes);
1410 mii = 1; /* Need to pass some estimate of mii. */
1411 rec_mii = sms_order_nodes (g, mii, node_order, &max_asap);
1412 mii = MAX (res_MII (g), rec_mii);
1413 maxii = MAX (max_asap, MAXII_FACTOR * mii);
1415 if (dump_file)
1416 fprintf (dump_file, "SMS iis %d %d %d (rec_mii, mii, maxii)\n",
1417 rec_mii, mii, maxii);
1419 /* After sms_order_nodes and before sms_schedule_by_order, to copy over
1420 ASAP. */
1421 set_node_sched_params (g);
1423 ps = sms_schedule_by_order (g, mii, maxii, node_order);
1425 if (ps)
1427 /* Try to achieve optimized SC by normalizing the partial
1428 schedule (having the cycles start from cycle zero).
1429 The branch location must be placed in row ii-1 in the
1430 final scheduling. If failed, shift all instructions to
1431 position the branch in row ii-1. */
1432 opt_sc_p = optimize_sc (ps, g);
1433 if (opt_sc_p)
1434 stage_count = calculate_stage_count (ps, 0);
1435 else
1437 /* Bring the branch to cycle ii-1. */
1438 int amount = SCHED_TIME (g->closing_branch) - (ps->ii - 1);
1440 if (dump_file)
1441 fprintf (dump_file, "SMS schedule branch at cycle ii-1\n");
1443 stage_count = calculate_stage_count (ps, amount);
1446 gcc_assert (stage_count >= 1);
1447 PS_STAGE_COUNT (ps) = stage_count;
1450 /* The default value of PARAM_SMS_MIN_SC is 2 as stage count of
1451 1 means that there is no interleaving between iterations thus
1452 we let the scheduling passes do the job in this case. */
1453 if (stage_count < (unsigned) PARAM_VALUE (PARAM_SMS_MIN_SC)
1454 || (count_init && (loop_count <= stage_count))
1455 || (flag_branch_probabilities && (trip_count <= stage_count)))
1457 if (dump_file)
1459 fprintf (dump_file, "SMS failed... \n");
1460 fprintf (dump_file, "SMS sched-failed (stage-count=%d, loop-count=", stage_count);
1461 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, loop_count);
1462 fprintf (dump_file, ", trip-count=");
1463 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, trip_count);
1464 fprintf (dump_file, ")\n");
1467 else
1469 struct undo_replace_buff_elem *reg_move_replaces;
1471 if (!opt_sc_p)
1473 /* Rotate the partial schedule to have the branch in row ii-1. */
1474 int amount = SCHED_TIME (g->closing_branch) - (ps->ii - 1);
1476 reset_sched_times (ps, amount);
1477 rotate_partial_schedule (ps, amount);
1480 set_columns_for_ps (ps);
1482 canon_loop (loop);
1484 if (dump_file)
1486 fprintf (dump_file,
1487 "%s:%d SMS succeeded %d %d (with ii, sc)\n",
1488 insn_file (tail), insn_line (tail), ps->ii, stage_count);
1489 print_partial_schedule (ps, dump_file);
1492 /* case the BCT count is not known , Do loop-versioning */
1493 if (count_reg && ! count_init)
1495 rtx comp_rtx = gen_rtx_fmt_ee (GT, VOIDmode, count_reg,
1496 GEN_INT(stage_count));
1497 unsigned prob = (PROB_SMS_ENOUGH_ITERATIONS
1498 * REG_BR_PROB_BASE) / 100;
1500 loop_version (loop, comp_rtx, &condition_bb,
1501 prob, prob, REG_BR_PROB_BASE - prob,
1502 true);
1505 /* Set new iteration count of loop kernel. */
1506 if (count_reg && count_init)
1507 SET_SRC (single_set (count_init)) = GEN_INT (loop_count
1508 - stage_count + 1);
1510 /* Now apply the scheduled kernel to the RTL of the loop. */
1511 permute_partial_schedule (ps, g->closing_branch->first_note);
1513 /* Mark this loop as software pipelined so the later
1514 scheduling passes doesn't touch it. */
1515 if (! flag_resched_modulo_sched)
1516 g->bb->flags |= BB_DISABLE_SCHEDULE;
1517 /* The life-info is not valid any more. */
1518 df_set_bb_dirty (g->bb);
1520 reg_move_replaces = generate_reg_moves (ps, true);
1521 if (dump_file)
1522 print_node_sched_params (dump_file, g->num_nodes, g);
1523 /* Generate prolog and epilog. */
1524 generate_prolog_epilog (ps, loop, count_reg, count_init);
1526 free_undo_replace_buff (reg_move_replaces);
1529 free_partial_schedule (ps);
1530 free (node_sched_params);
1531 free (node_order);
1532 free_ddg (g);
1535 free (g_arr);
1537 /* Release scheduler data, needed until now because of DFA. */
1538 haifa_sched_finish ();
1539 loop_optimizer_finalize ();
1542 /* The SMS scheduling algorithm itself
1543 -----------------------------------
1544 Input: 'O' an ordered list of insns of a loop.
1545 Output: A scheduling of the loop - kernel, prolog, and epilogue.
1547 'Q' is the empty Set
1548 'PS' is the partial schedule; it holds the currently scheduled nodes with
1549 their cycle/slot.
1550 'PSP' previously scheduled predecessors.
1551 'PSS' previously scheduled successors.
1552 't(u)' the cycle where u is scheduled.
1553 'l(u)' is the latency of u.
1554 'd(v,u)' is the dependence distance from v to u.
1555 'ASAP(u)' the earliest time at which u could be scheduled as computed in
1556 the node ordering phase.
1557 'check_hardware_resources_conflicts(u, PS, c)'
1558 run a trace around cycle/slot through DFA model
1559 to check resource conflicts involving instruction u
1560 at cycle c given the partial schedule PS.
1561 'add_to_partial_schedule_at_time(u, PS, c)'
1562 Add the node/instruction u to the partial schedule
1563 PS at time c.
1564 'calculate_register_pressure(PS)'
1565 Given a schedule of instructions, calculate the register
1566 pressure it implies. One implementation could be the
1567 maximum number of overlapping live ranges.
1568 'maxRP' The maximum allowed register pressure, it is usually derived from the number
1569 registers available in the hardware.
1571 1. II = MII.
1572 2. PS = empty list
1573 3. for each node u in O in pre-computed order
1574 4. if (PSP(u) != Q && PSS(u) == Q) then
1575 5. Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1576 6. start = Early_start; end = Early_start + II - 1; step = 1
1577 11. else if (PSP(u) == Q && PSS(u) != Q) then
1578 12. Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1579 13. start = Late_start; end = Late_start - II + 1; step = -1
1580 14. else if (PSP(u) != Q && PSS(u) != Q) then
1581 15. Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1582 16. Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1583 17. start = Early_start;
1584 18. end = min(Early_start + II - 1 , Late_start);
1585 19. step = 1
1586 20. else "if (PSP(u) == Q && PSS(u) == Q)"
1587 21. start = ASAP(u); end = start + II - 1; step = 1
1588 22. endif
1590 23. success = false
1591 24. for (c = start ; c != end ; c += step)
1592 25. if check_hardware_resources_conflicts(u, PS, c) then
1593 26. add_to_partial_schedule_at_time(u, PS, c)
1594 27. success = true
1595 28. break
1596 29. endif
1597 30. endfor
1598 31. if (success == false) then
1599 32. II = II + 1
1600 33. if (II > maxII) then
1601 34. finish - failed to schedule
1602 35. endif
1603 36. goto 2.
1604 37. endif
1605 38. endfor
1606 39. if (calculate_register_pressure(PS) > maxRP) then
1607 40. goto 32.
1608 41. endif
1609 42. compute epilogue & prologue
1610 43. finish - succeeded to schedule
1613 /* A limit on the number of cycles that resource conflicts can span. ??? Should
1614 be provided by DFA, and be dependent on the type of insn scheduled. Currently
1615 set to 0 to save compile time. */
1616 #define DFA_HISTORY SMS_DFA_HISTORY
1618 /* A threshold for the number of repeated unsuccessful attempts to insert
1619 an empty row, before we flush the partial schedule and start over. */
1620 #define MAX_SPLIT_NUM 10
1621 /* Given the partial schedule PS, this function calculates and returns the
1622 cycles in which we can schedule the node with the given index I.
1623 NOTE: Here we do the backtracking in SMS, in some special cases. We have
1624 noticed that there are several cases in which we fail to SMS the loop
1625 because the sched window of a node is empty due to tight data-deps. In
1626 such cases we want to unschedule some of the predecessors/successors
1627 until we get non-empty scheduling window. It returns -1 if the
1628 scheduling window is empty and zero otherwise. */
1630 static int
1631 get_sched_window (partial_schedule_ptr ps, ddg_node_ptr u_node,
1632 sbitmap sched_nodes, int ii, int *start_p, int *step_p,
1633 int *end_p)
1635 int start, step, end;
1636 int early_start, late_start;
1637 ddg_edge_ptr e;
1638 sbitmap psp = sbitmap_alloc (ps->g->num_nodes);
1639 sbitmap pss = sbitmap_alloc (ps->g->num_nodes);
1640 sbitmap u_node_preds = NODE_PREDECESSORS (u_node);
1641 sbitmap u_node_succs = NODE_SUCCESSORS (u_node);
1642 int psp_not_empty;
1643 int pss_not_empty;
1644 int count_preds;
1645 int count_succs;
1647 /* 1. compute sched window for u (start, end, step). */
1648 sbitmap_zero (psp);
1649 sbitmap_zero (pss);
1650 psp_not_empty = sbitmap_a_and_b_cg (psp, u_node_preds, sched_nodes);
1651 pss_not_empty = sbitmap_a_and_b_cg (pss, u_node_succs, sched_nodes);
1653 /* We first compute a forward range (start <= end), then decide whether
1654 to reverse it. */
1655 early_start = INT_MIN;
1656 late_start = INT_MAX;
1657 start = INT_MIN;
1658 end = INT_MAX;
1659 step = 1;
1661 count_preds = 0;
1662 count_succs = 0;
1664 if (dump_file && (psp_not_empty || pss_not_empty))
1666 fprintf (dump_file, "\nAnalyzing dependencies for node %d (INSN %d)"
1667 "; ii = %d\n\n", u_node->cuid, INSN_UID (u_node->insn), ii);
1668 fprintf (dump_file, "%11s %11s %11s %11s %5s\n",
1669 "start", "early start", "late start", "end", "time");
1670 fprintf (dump_file, "=========== =========== =========== ==========="
1671 " =====\n");
1673 /* Calculate early_start and limit end. Both bounds are inclusive. */
1674 if (psp_not_empty)
1675 for (e = u_node->in; e != 0; e = e->next_in)
1677 ddg_node_ptr v_node = e->src;
1679 if (TEST_BIT (sched_nodes, v_node->cuid))
1681 int p_st = SCHED_TIME (v_node);
1682 int earliest = p_st + e->latency - (e->distance * ii);
1683 int latest = (e->data_type == MEM_DEP ? p_st + ii - 1 : INT_MAX);
1685 if (dump_file)
1687 fprintf (dump_file, "%11s %11d %11s %11d %5d",
1688 "", earliest, "", latest, p_st);
1689 print_ddg_edge (dump_file, e);
1690 fprintf (dump_file, "\n");
1693 early_start = MAX (early_start, earliest);
1694 end = MIN (end, latest);
1696 if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1697 count_preds++;
1701 /* Calculate late_start and limit start. Both bounds are inclusive. */
1702 if (pss_not_empty)
1703 for (e = u_node->out; e != 0; e = e->next_out)
1705 ddg_node_ptr v_node = e->dest;
1707 if (TEST_BIT (sched_nodes, v_node->cuid))
1709 int s_st = SCHED_TIME (v_node);
1710 int earliest = (e->data_type == MEM_DEP ? s_st - ii + 1 : INT_MIN);
1711 int latest = s_st - e->latency + (e->distance * ii);
1713 if (dump_file)
1715 fprintf (dump_file, "%11d %11s %11d %11s %5d",
1716 earliest, "", latest, "", s_st);
1717 print_ddg_edge (dump_file, e);
1718 fprintf (dump_file, "\n");
1721 start = MAX (start, earliest);
1722 late_start = MIN (late_start, latest);
1724 if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1725 count_succs++;
1729 if (dump_file && (psp_not_empty || pss_not_empty))
1731 fprintf (dump_file, "----------- ----------- ----------- -----------"
1732 " -----\n");
1733 fprintf (dump_file, "%11d %11d %11d %11d %5s %s\n",
1734 start, early_start, late_start, end, "",
1735 "(max, max, min, min)");
1738 /* Get a target scheduling window no bigger than ii. */
1739 if (early_start == INT_MIN && late_start == INT_MAX)
1740 early_start = SCHED_ASAP (u_node);
1741 else if (early_start == INT_MIN)
1742 early_start = late_start - (ii - 1);
1743 late_start = MIN (late_start, early_start + (ii - 1));
1745 /* Apply memory dependence limits. */
1746 start = MAX (start, early_start);
1747 end = MIN (end, late_start);
1749 if (dump_file && (psp_not_empty || pss_not_empty))
1750 fprintf (dump_file, "%11s %11d %11d %11s %5s final window\n",
1751 "", start, end, "", "");
1753 /* If there are at least as many successors as predecessors, schedule the
1754 node close to its successors. */
1755 if (pss_not_empty && count_succs >= count_preds)
1757 int tmp = end;
1758 end = start;
1759 start = tmp;
1760 step = -1;
1763 /* Now that we've finalized the window, make END an exclusive rather
1764 than an inclusive bound. */
1765 end += step;
1767 *start_p = start;
1768 *step_p = step;
1769 *end_p = end;
1770 sbitmap_free (psp);
1771 sbitmap_free (pss);
1773 if ((start >= end && step == 1) || (start <= end && step == -1))
1775 if (dump_file)
1776 fprintf (dump_file, "\nEmpty window: start=%d, end=%d, step=%d\n",
1777 start, end, step);
1778 return -1;
1781 return 0;
1784 /* Calculate MUST_PRECEDE/MUST_FOLLOW bitmaps of U_NODE; which is the
1785 node currently been scheduled. At the end of the calculation
1786 MUST_PRECEDE/MUST_FOLLOW contains all predecessors/successors of
1787 U_NODE which are (1) already scheduled in the first/last row of
1788 U_NODE's scheduling window, (2) whose dependence inequality with U
1789 becomes an equality when U is scheduled in this same row, and (3)
1790 whose dependence latency is zero.
1792 The first and last rows are calculated using the following parameters:
1793 START/END rows - The cycles that begins/ends the traversal on the window;
1794 searching for an empty cycle to schedule U_NODE.
1795 STEP - The direction in which we traverse the window.
1796 II - The initiation interval. */
1798 static void
1799 calculate_must_precede_follow (ddg_node_ptr u_node, int start, int end,
1800 int step, int ii, sbitmap sched_nodes,
1801 sbitmap must_precede, sbitmap must_follow)
1803 ddg_edge_ptr e;
1804 int first_cycle_in_window, last_cycle_in_window;
1806 gcc_assert (must_precede && must_follow);
1808 /* Consider the following scheduling window:
1809 {first_cycle_in_window, first_cycle_in_window+1, ...,
1810 last_cycle_in_window}. If step is 1 then the following will be
1811 the order we traverse the window: {start=first_cycle_in_window,
1812 first_cycle_in_window+1, ..., end=last_cycle_in_window+1},
1813 or {start=last_cycle_in_window, last_cycle_in_window-1, ...,
1814 end=first_cycle_in_window-1} if step is -1. */
1815 first_cycle_in_window = (step == 1) ? start : end - step;
1816 last_cycle_in_window = (step == 1) ? end - step : start;
1818 sbitmap_zero (must_precede);
1819 sbitmap_zero (must_follow);
1821 if (dump_file)
1822 fprintf (dump_file, "\nmust_precede: ");
1824 /* Instead of checking if:
1825 (SMODULO (SCHED_TIME (e->src), ii) == first_row_in_window)
1826 && ((SCHED_TIME (e->src) + e->latency - (e->distance * ii)) ==
1827 first_cycle_in_window)
1828 && e->latency == 0
1829 we use the fact that latency is non-negative:
1830 SCHED_TIME (e->src) - (e->distance * ii) <=
1831 SCHED_TIME (e->src) + e->latency - (e->distance * ii)) <=
1832 first_cycle_in_window
1833 and check only if
1834 SCHED_TIME (e->src) - (e->distance * ii) == first_cycle_in_window */
1835 for (e = u_node->in; e != 0; e = e->next_in)
1836 if (TEST_BIT (sched_nodes, e->src->cuid)
1837 && ((SCHED_TIME (e->src) - (e->distance * ii)) ==
1838 first_cycle_in_window))
1840 if (dump_file)
1841 fprintf (dump_file, "%d ", e->src->cuid);
1843 SET_BIT (must_precede, e->src->cuid);
1846 if (dump_file)
1847 fprintf (dump_file, "\nmust_follow: ");
1849 /* Instead of checking if:
1850 (SMODULO (SCHED_TIME (e->dest), ii) == last_row_in_window)
1851 && ((SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) ==
1852 last_cycle_in_window)
1853 && e->latency == 0
1854 we use the fact that latency is non-negative:
1855 SCHED_TIME (e->dest) + (e->distance * ii) >=
1856 SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) >=
1857 last_cycle_in_window
1858 and check only if
1859 SCHED_TIME (e->dest) + (e->distance * ii) == last_cycle_in_window */
1860 for (e = u_node->out; e != 0; e = e->next_out)
1861 if (TEST_BIT (sched_nodes, e->dest->cuid)
1862 && ((SCHED_TIME (e->dest) + (e->distance * ii)) ==
1863 last_cycle_in_window))
1865 if (dump_file)
1866 fprintf (dump_file, "%d ", e->dest->cuid);
1868 SET_BIT (must_follow, e->dest->cuid);
1871 if (dump_file)
1872 fprintf (dump_file, "\n");
1875 /* Return 1 if U_NODE can be scheduled in CYCLE. Use the following
1876 parameters to decide if that's possible:
1877 PS - The partial schedule.
1878 U - The serial number of U_NODE.
1879 NUM_SPLITS - The number of row splits made so far.
1880 MUST_PRECEDE - The nodes that must precede U_NODE. (only valid at
1881 the first row of the scheduling window)
1882 MUST_FOLLOW - The nodes that must follow U_NODE. (only valid at the
1883 last row of the scheduling window) */
1885 static bool
1886 try_scheduling_node_in_cycle (partial_schedule_ptr ps, ddg_node_ptr u_node,
1887 int u, int cycle, sbitmap sched_nodes,
1888 int *num_splits, sbitmap must_precede,
1889 sbitmap must_follow)
1891 ps_insn_ptr psi;
1892 bool success = 0;
1894 verify_partial_schedule (ps, sched_nodes);
1895 psi = ps_add_node_check_conflicts (ps, u_node, cycle,
1896 must_precede, must_follow);
1897 if (psi)
1899 SCHED_TIME (u_node) = cycle;
1900 SET_BIT (sched_nodes, u);
1901 success = 1;
1902 *num_splits = 0;
1903 if (dump_file)
1904 fprintf (dump_file, "Scheduled w/o split in %d\n", cycle);
1908 return success;
1911 /* This function implements the scheduling algorithm for SMS according to the
1912 above algorithm. */
1913 static partial_schedule_ptr
1914 sms_schedule_by_order (ddg_ptr g, int mii, int maxii, int *nodes_order)
1916 int ii = mii;
1917 int i, c, success, num_splits = 0;
1918 int flush_and_start_over = true;
1919 int num_nodes = g->num_nodes;
1920 int start, end, step; /* Place together into one struct? */
1921 sbitmap sched_nodes = sbitmap_alloc (num_nodes);
1922 sbitmap must_precede = sbitmap_alloc (num_nodes);
1923 sbitmap must_follow = sbitmap_alloc (num_nodes);
1924 sbitmap tobe_scheduled = sbitmap_alloc (num_nodes);
1926 partial_schedule_ptr ps = create_partial_schedule (ii, g, DFA_HISTORY);
1928 sbitmap_ones (tobe_scheduled);
1929 sbitmap_zero (sched_nodes);
1931 while (flush_and_start_over && (ii < maxii))
1934 if (dump_file)
1935 fprintf (dump_file, "Starting with ii=%d\n", ii);
1936 flush_and_start_over = false;
1937 sbitmap_zero (sched_nodes);
1939 for (i = 0; i < num_nodes; i++)
1941 int u = nodes_order[i];
1942 ddg_node_ptr u_node = &ps->g->nodes[u];
1943 rtx insn = u_node->insn;
1945 if (!NONDEBUG_INSN_P (insn))
1947 RESET_BIT (tobe_scheduled, u);
1948 continue;
1951 if (TEST_BIT (sched_nodes, u))
1952 continue;
1954 /* Try to get non-empty scheduling window. */
1955 success = 0;
1956 if (get_sched_window (ps, u_node, sched_nodes, ii, &start,
1957 &step, &end) == 0)
1959 if (dump_file)
1960 fprintf (dump_file, "\nTrying to schedule node %d "
1961 "INSN = %d in (%d .. %d) step %d\n", u, (INSN_UID
1962 (g->nodes[u].insn)), start, end, step);
1964 gcc_assert ((step > 0 && start < end)
1965 || (step < 0 && start > end));
1967 calculate_must_precede_follow (u_node, start, end, step, ii,
1968 sched_nodes, must_precede,
1969 must_follow);
1971 for (c = start; c != end; c += step)
1973 sbitmap tmp_precede, tmp_follow;
1975 set_must_precede_follow (&tmp_follow, must_follow,
1976 &tmp_precede, must_precede,
1977 c, start, end, step);
1978 success =
1979 try_scheduling_node_in_cycle (ps, u_node, u, c,
1980 sched_nodes,
1981 &num_splits, tmp_precede,
1982 tmp_follow);
1983 if (success)
1984 break;
1987 verify_partial_schedule (ps, sched_nodes);
1989 if (!success)
1991 int split_row;
1993 if (ii++ == maxii)
1994 break;
1996 if (num_splits >= MAX_SPLIT_NUM)
1998 num_splits = 0;
1999 flush_and_start_over = true;
2000 verify_partial_schedule (ps, sched_nodes);
2001 reset_partial_schedule (ps, ii);
2002 verify_partial_schedule (ps, sched_nodes);
2003 break;
2006 num_splits++;
2007 /* The scheduling window is exclusive of 'end'
2008 whereas compute_split_window() expects an inclusive,
2009 ordered range. */
2010 if (step == 1)
2011 split_row = compute_split_row (sched_nodes, start, end - 1,
2012 ps->ii, u_node);
2013 else
2014 split_row = compute_split_row (sched_nodes, end + 1, start,
2015 ps->ii, u_node);
2017 ps_insert_empty_row (ps, split_row, sched_nodes);
2018 i--; /* Go back and retry node i. */
2020 if (dump_file)
2021 fprintf (dump_file, "num_splits=%d\n", num_splits);
2024 /* ??? If (success), check register pressure estimates. */
2025 } /* Continue with next node. */
2026 } /* While flush_and_start_over. */
2027 if (ii >= maxii)
2029 free_partial_schedule (ps);
2030 ps = NULL;
2032 else
2033 gcc_assert (sbitmap_equal (tobe_scheduled, sched_nodes));
2035 sbitmap_free (sched_nodes);
2036 sbitmap_free (must_precede);
2037 sbitmap_free (must_follow);
2038 sbitmap_free (tobe_scheduled);
2040 return ps;
2043 /* This function inserts a new empty row into PS at the position
2044 according to SPLITROW, keeping all already scheduled instructions
2045 intact and updating their SCHED_TIME and cycle accordingly. */
2046 static void
2047 ps_insert_empty_row (partial_schedule_ptr ps, int split_row,
2048 sbitmap sched_nodes)
2050 ps_insn_ptr crr_insn;
2051 ps_insn_ptr *rows_new;
2052 int ii = ps->ii;
2053 int new_ii = ii + 1;
2054 int row;
2055 int *rows_length_new;
2057 verify_partial_schedule (ps, sched_nodes);
2059 /* We normalize sched_time and rotate ps to have only non-negative sched
2060 times, for simplicity of updating cycles after inserting new row. */
2061 split_row -= ps->min_cycle;
2062 split_row = SMODULO (split_row, ii);
2063 if (dump_file)
2064 fprintf (dump_file, "split_row=%d\n", split_row);
2066 reset_sched_times (ps, PS_MIN_CYCLE (ps));
2067 rotate_partial_schedule (ps, PS_MIN_CYCLE (ps));
2069 rows_new = (ps_insn_ptr *) xcalloc (new_ii, sizeof (ps_insn_ptr));
2070 rows_length_new = (int *) xcalloc (new_ii, sizeof (int));
2071 for (row = 0; row < split_row; row++)
2073 rows_new[row] = ps->rows[row];
2074 rows_length_new[row] = ps->rows_length[row];
2075 ps->rows[row] = NULL;
2076 for (crr_insn = rows_new[row];
2077 crr_insn; crr_insn = crr_insn->next_in_row)
2079 ddg_node_ptr u = crr_insn->node;
2080 int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii);
2082 SCHED_TIME (u) = new_time;
2083 crr_insn->cycle = new_time;
2084 SCHED_ROW (u) = new_time % new_ii;
2085 SCHED_STAGE (u) = new_time / new_ii;
2090 rows_new[split_row] = NULL;
2092 for (row = split_row; row < ii; row++)
2094 rows_new[row + 1] = ps->rows[row];
2095 rows_length_new[row + 1] = ps->rows_length[row];
2096 ps->rows[row] = NULL;
2097 for (crr_insn = rows_new[row + 1];
2098 crr_insn; crr_insn = crr_insn->next_in_row)
2100 ddg_node_ptr u = crr_insn->node;
2101 int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii) + 1;
2103 SCHED_TIME (u) = new_time;
2104 crr_insn->cycle = new_time;
2105 SCHED_ROW (u) = new_time % new_ii;
2106 SCHED_STAGE (u) = new_time / new_ii;
2110 /* Updating ps. */
2111 ps->min_cycle = ps->min_cycle + ps->min_cycle / ii
2112 + (SMODULO (ps->min_cycle, ii) >= split_row ? 1 : 0);
2113 ps->max_cycle = ps->max_cycle + ps->max_cycle / ii
2114 + (SMODULO (ps->max_cycle, ii) >= split_row ? 1 : 0);
2115 free (ps->rows);
2116 ps->rows = rows_new;
2117 free (ps->rows_length);
2118 ps->rows_length = rows_length_new;
2119 ps->ii = new_ii;
2120 gcc_assert (ps->min_cycle >= 0);
2122 verify_partial_schedule (ps, sched_nodes);
2124 if (dump_file)
2125 fprintf (dump_file, "min_cycle=%d, max_cycle=%d\n", ps->min_cycle,
2126 ps->max_cycle);
2129 /* Given U_NODE which is the node that failed to be scheduled; LOW and
2130 UP which are the boundaries of it's scheduling window; compute using
2131 SCHED_NODES and II a row in the partial schedule that can be split
2132 which will separate a critical predecessor from a critical successor
2133 thereby expanding the window, and return it. */
2134 static int
2135 compute_split_row (sbitmap sched_nodes, int low, int up, int ii,
2136 ddg_node_ptr u_node)
2138 ddg_edge_ptr e;
2139 int lower = INT_MIN, upper = INT_MAX;
2140 ddg_node_ptr crit_pred = NULL;
2141 ddg_node_ptr crit_succ = NULL;
2142 int crit_cycle;
2144 for (e = u_node->in; e != 0; e = e->next_in)
2146 ddg_node_ptr v_node = e->src;
2148 if (TEST_BIT (sched_nodes, v_node->cuid)
2149 && (low == SCHED_TIME (v_node) + e->latency - (e->distance * ii)))
2150 if (SCHED_TIME (v_node) > lower)
2152 crit_pred = v_node;
2153 lower = SCHED_TIME (v_node);
2157 if (crit_pred != NULL)
2159 crit_cycle = SCHED_TIME (crit_pred) + 1;
2160 return SMODULO (crit_cycle, ii);
2163 for (e = u_node->out; e != 0; e = e->next_out)
2165 ddg_node_ptr v_node = e->dest;
2166 if (TEST_BIT (sched_nodes, v_node->cuid)
2167 && (up == SCHED_TIME (v_node) - e->latency + (e->distance * ii)))
2168 if (SCHED_TIME (v_node) < upper)
2170 crit_succ = v_node;
2171 upper = SCHED_TIME (v_node);
2175 if (crit_succ != NULL)
2177 crit_cycle = SCHED_TIME (crit_succ);
2178 return SMODULO (crit_cycle, ii);
2181 if (dump_file)
2182 fprintf (dump_file, "Both crit_pred and crit_succ are NULL\n");
2184 return SMODULO ((low + up + 1) / 2, ii);
2187 static void
2188 verify_partial_schedule (partial_schedule_ptr ps, sbitmap sched_nodes)
2190 int row;
2191 ps_insn_ptr crr_insn;
2193 for (row = 0; row < ps->ii; row++)
2195 int length = 0;
2197 for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
2199 ddg_node_ptr u = crr_insn->node;
2201 length++;
2202 gcc_assert (TEST_BIT (sched_nodes, u->cuid));
2203 /* ??? Test also that all nodes of sched_nodes are in ps, perhaps by
2204 popcount (sched_nodes) == number of insns in ps. */
2205 gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
2206 gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
2209 gcc_assert (ps->rows_length[row] == length);
2214 /* This page implements the algorithm for ordering the nodes of a DDG
2215 for modulo scheduling, activated through the
2216 "int sms_order_nodes (ddg_ptr, int mii, int * result)" API. */
2218 #define ORDER_PARAMS(x) ((struct node_order_params *) (x)->aux.info)
2219 #define ASAP(x) (ORDER_PARAMS ((x))->asap)
2220 #define ALAP(x) (ORDER_PARAMS ((x))->alap)
2221 #define HEIGHT(x) (ORDER_PARAMS ((x))->height)
2222 #define MOB(x) (ALAP ((x)) - ASAP ((x)))
2223 #define DEPTH(x) (ASAP ((x)))
2225 typedef struct node_order_params * nopa;
2227 static void order_nodes_of_sccs (ddg_all_sccs_ptr, int * result);
2228 static int order_nodes_in_scc (ddg_ptr, sbitmap, sbitmap, int*, int);
2229 static nopa calculate_order_params (ddg_ptr, int, int *);
2230 static int find_max_asap (ddg_ptr, sbitmap);
2231 static int find_max_hv_min_mob (ddg_ptr, sbitmap);
2232 static int find_max_dv_min_mob (ddg_ptr, sbitmap);
2234 enum sms_direction {BOTTOMUP, TOPDOWN};
2236 struct node_order_params
2238 int asap;
2239 int alap;
2240 int height;
2243 /* Check if NODE_ORDER contains a permutation of 0 .. NUM_NODES-1. */
2244 static void
2245 check_nodes_order (int *node_order, int num_nodes)
2247 int i;
2248 sbitmap tmp = sbitmap_alloc (num_nodes);
2250 sbitmap_zero (tmp);
2252 if (dump_file)
2253 fprintf (dump_file, "SMS final nodes order: \n");
2255 for (i = 0; i < num_nodes; i++)
2257 int u = node_order[i];
2259 if (dump_file)
2260 fprintf (dump_file, "%d ", u);
2261 gcc_assert (u < num_nodes && u >= 0 && !TEST_BIT (tmp, u));
2263 SET_BIT (tmp, u);
2266 if (dump_file)
2267 fprintf (dump_file, "\n");
2269 sbitmap_free (tmp);
2272 /* Order the nodes of G for scheduling and pass the result in
2273 NODE_ORDER. Also set aux.count of each node to ASAP.
2274 Put maximal ASAP to PMAX_ASAP. Return the recMII for the given DDG. */
2275 static int
2276 sms_order_nodes (ddg_ptr g, int mii, int * node_order, int *pmax_asap)
2278 int i;
2279 int rec_mii = 0;
2280 ddg_all_sccs_ptr sccs = create_ddg_all_sccs (g);
2282 nopa nops = calculate_order_params (g, mii, pmax_asap);
2284 if (dump_file)
2285 print_sccs (dump_file, sccs, g);
2287 order_nodes_of_sccs (sccs, node_order);
2289 if (sccs->num_sccs > 0)
2290 /* First SCC has the largest recurrence_length. */
2291 rec_mii = sccs->sccs[0]->recurrence_length;
2293 /* Save ASAP before destroying node_order_params. */
2294 for (i = 0; i < g->num_nodes; i++)
2296 ddg_node_ptr v = &g->nodes[i];
2297 v->aux.count = ASAP (v);
2300 free (nops);
2301 free_ddg_all_sccs (sccs);
2302 check_nodes_order (node_order, g->num_nodes);
2304 return rec_mii;
2307 static void
2308 order_nodes_of_sccs (ddg_all_sccs_ptr all_sccs, int * node_order)
2310 int i, pos = 0;
2311 ddg_ptr g = all_sccs->ddg;
2312 int num_nodes = g->num_nodes;
2313 sbitmap prev_sccs = sbitmap_alloc (num_nodes);
2314 sbitmap on_path = sbitmap_alloc (num_nodes);
2315 sbitmap tmp = sbitmap_alloc (num_nodes);
2316 sbitmap ones = sbitmap_alloc (num_nodes);
2318 sbitmap_zero (prev_sccs);
2319 sbitmap_ones (ones);
2321 /* Perform the node ordering starting from the SCC with the highest recMII.
2322 For each SCC order the nodes according to their ASAP/ALAP/HEIGHT etc. */
2323 for (i = 0; i < all_sccs->num_sccs; i++)
2325 ddg_scc_ptr scc = all_sccs->sccs[i];
2327 /* Add nodes on paths from previous SCCs to the current SCC. */
2328 find_nodes_on_paths (on_path, g, prev_sccs, scc->nodes);
2329 sbitmap_a_or_b (tmp, scc->nodes, on_path);
2331 /* Add nodes on paths from the current SCC to previous SCCs. */
2332 find_nodes_on_paths (on_path, g, scc->nodes, prev_sccs);
2333 sbitmap_a_or_b (tmp, tmp, on_path);
2335 /* Remove nodes of previous SCCs from current extended SCC. */
2336 sbitmap_difference (tmp, tmp, prev_sccs);
2338 pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2339 /* Above call to order_nodes_in_scc updated prev_sccs |= tmp. */
2342 /* Handle the remaining nodes that do not belong to any scc. Each call
2343 to order_nodes_in_scc handles a single connected component. */
2344 while (pos < g->num_nodes)
2346 sbitmap_difference (tmp, ones, prev_sccs);
2347 pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2349 sbitmap_free (prev_sccs);
2350 sbitmap_free (on_path);
2351 sbitmap_free (tmp);
2352 sbitmap_free (ones);
2355 /* MII is needed if we consider backarcs (that do not close recursive cycles). */
2356 static struct node_order_params *
2357 calculate_order_params (ddg_ptr g, int mii ATTRIBUTE_UNUSED, int *pmax_asap)
2359 int u;
2360 int max_asap;
2361 int num_nodes = g->num_nodes;
2362 ddg_edge_ptr e;
2363 /* Allocate a place to hold ordering params for each node in the DDG. */
2364 nopa node_order_params_arr;
2366 /* Initialize of ASAP/ALAP/HEIGHT to zero. */
2367 node_order_params_arr = (nopa) xcalloc (num_nodes,
2368 sizeof (struct node_order_params));
2370 /* Set the aux pointer of each node to point to its order_params structure. */
2371 for (u = 0; u < num_nodes; u++)
2372 g->nodes[u].aux.info = &node_order_params_arr[u];
2374 /* Disregarding a backarc from each recursive cycle to obtain a DAG,
2375 calculate ASAP, ALAP, mobility, distance, and height for each node
2376 in the dependence (direct acyclic) graph. */
2378 /* We assume that the nodes in the array are in topological order. */
2380 max_asap = 0;
2381 for (u = 0; u < num_nodes; u++)
2383 ddg_node_ptr u_node = &g->nodes[u];
2385 ASAP (u_node) = 0;
2386 for (e = u_node->in; e; e = e->next_in)
2387 if (e->distance == 0)
2388 ASAP (u_node) = MAX (ASAP (u_node),
2389 ASAP (e->src) + e->latency);
2390 max_asap = MAX (max_asap, ASAP (u_node));
2393 for (u = num_nodes - 1; u > -1; u--)
2395 ddg_node_ptr u_node = &g->nodes[u];
2397 ALAP (u_node) = max_asap;
2398 HEIGHT (u_node) = 0;
2399 for (e = u_node->out; e; e = e->next_out)
2400 if (e->distance == 0)
2402 ALAP (u_node) = MIN (ALAP (u_node),
2403 ALAP (e->dest) - e->latency);
2404 HEIGHT (u_node) = MAX (HEIGHT (u_node),
2405 HEIGHT (e->dest) + e->latency);
2408 if (dump_file)
2410 fprintf (dump_file, "\nOrder params\n");
2411 for (u = 0; u < num_nodes; u++)
2413 ddg_node_ptr u_node = &g->nodes[u];
2415 fprintf (dump_file, "node %d, ASAP: %d, ALAP: %d, HEIGHT: %d\n", u,
2416 ASAP (u_node), ALAP (u_node), HEIGHT (u_node));
2420 *pmax_asap = max_asap;
2421 return node_order_params_arr;
2424 static int
2425 find_max_asap (ddg_ptr g, sbitmap nodes)
2427 unsigned int u = 0;
2428 int max_asap = -1;
2429 int result = -1;
2430 sbitmap_iterator sbi;
2432 EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2434 ddg_node_ptr u_node = &g->nodes[u];
2436 if (max_asap < ASAP (u_node))
2438 max_asap = ASAP (u_node);
2439 result = u;
2442 return result;
2445 static int
2446 find_max_hv_min_mob (ddg_ptr g, sbitmap nodes)
2448 unsigned int u = 0;
2449 int max_hv = -1;
2450 int min_mob = INT_MAX;
2451 int result = -1;
2452 sbitmap_iterator sbi;
2454 EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2456 ddg_node_ptr u_node = &g->nodes[u];
2458 if (max_hv < HEIGHT (u_node))
2460 max_hv = HEIGHT (u_node);
2461 min_mob = MOB (u_node);
2462 result = u;
2464 else if ((max_hv == HEIGHT (u_node))
2465 && (min_mob > MOB (u_node)))
2467 min_mob = MOB (u_node);
2468 result = u;
2471 return result;
2474 static int
2475 find_max_dv_min_mob (ddg_ptr g, sbitmap nodes)
2477 unsigned int u = 0;
2478 int max_dv = -1;
2479 int min_mob = INT_MAX;
2480 int result = -1;
2481 sbitmap_iterator sbi;
2483 EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2485 ddg_node_ptr u_node = &g->nodes[u];
2487 if (max_dv < DEPTH (u_node))
2489 max_dv = DEPTH (u_node);
2490 min_mob = MOB (u_node);
2491 result = u;
2493 else if ((max_dv == DEPTH (u_node))
2494 && (min_mob > MOB (u_node)))
2496 min_mob = MOB (u_node);
2497 result = u;
2500 return result;
2503 /* Places the nodes of SCC into the NODE_ORDER array starting
2504 at position POS, according to the SMS ordering algorithm.
2505 NODES_ORDERED (in&out parameter) holds the bitset of all nodes in
2506 the NODE_ORDER array, starting from position zero. */
2507 static int
2508 order_nodes_in_scc (ddg_ptr g, sbitmap nodes_ordered, sbitmap scc,
2509 int * node_order, int pos)
2511 enum sms_direction dir;
2512 int num_nodes = g->num_nodes;
2513 sbitmap workset = sbitmap_alloc (num_nodes);
2514 sbitmap tmp = sbitmap_alloc (num_nodes);
2515 sbitmap zero_bitmap = sbitmap_alloc (num_nodes);
2516 sbitmap predecessors = sbitmap_alloc (num_nodes);
2517 sbitmap successors = sbitmap_alloc (num_nodes);
2519 sbitmap_zero (predecessors);
2520 find_predecessors (predecessors, g, nodes_ordered);
2522 sbitmap_zero (successors);
2523 find_successors (successors, g, nodes_ordered);
2525 sbitmap_zero (tmp);
2526 if (sbitmap_a_and_b_cg (tmp, predecessors, scc))
2528 sbitmap_copy (workset, tmp);
2529 dir = BOTTOMUP;
2531 else if (sbitmap_a_and_b_cg (tmp, successors, scc))
2533 sbitmap_copy (workset, tmp);
2534 dir = TOPDOWN;
2536 else
2538 int u;
2540 sbitmap_zero (workset);
2541 if ((u = find_max_asap (g, scc)) >= 0)
2542 SET_BIT (workset, u);
2543 dir = BOTTOMUP;
2546 sbitmap_zero (zero_bitmap);
2547 while (!sbitmap_equal (workset, zero_bitmap))
2549 int v;
2550 ddg_node_ptr v_node;
2551 sbitmap v_node_preds;
2552 sbitmap v_node_succs;
2554 if (dir == TOPDOWN)
2556 while (!sbitmap_equal (workset, zero_bitmap))
2558 v = find_max_hv_min_mob (g, workset);
2559 v_node = &g->nodes[v];
2560 node_order[pos++] = v;
2561 v_node_succs = NODE_SUCCESSORS (v_node);
2562 sbitmap_a_and_b (tmp, v_node_succs, scc);
2564 /* Don't consider the already ordered successors again. */
2565 sbitmap_difference (tmp, tmp, nodes_ordered);
2566 sbitmap_a_or_b (workset, workset, tmp);
2567 RESET_BIT (workset, v);
2568 SET_BIT (nodes_ordered, v);
2570 dir = BOTTOMUP;
2571 sbitmap_zero (predecessors);
2572 find_predecessors (predecessors, g, nodes_ordered);
2573 sbitmap_a_and_b (workset, predecessors, scc);
2575 else
2577 while (!sbitmap_equal (workset, zero_bitmap))
2579 v = find_max_dv_min_mob (g, workset);
2580 v_node = &g->nodes[v];
2581 node_order[pos++] = v;
2582 v_node_preds = NODE_PREDECESSORS (v_node);
2583 sbitmap_a_and_b (tmp, v_node_preds, scc);
2585 /* Don't consider the already ordered predecessors again. */
2586 sbitmap_difference (tmp, tmp, nodes_ordered);
2587 sbitmap_a_or_b (workset, workset, tmp);
2588 RESET_BIT (workset, v);
2589 SET_BIT (nodes_ordered, v);
2591 dir = TOPDOWN;
2592 sbitmap_zero (successors);
2593 find_successors (successors, g, nodes_ordered);
2594 sbitmap_a_and_b (workset, successors, scc);
2597 sbitmap_free (tmp);
2598 sbitmap_free (workset);
2599 sbitmap_free (zero_bitmap);
2600 sbitmap_free (predecessors);
2601 sbitmap_free (successors);
2602 return pos;
2606 /* This page contains functions for manipulating partial-schedules during
2607 modulo scheduling. */
2609 /* Create a partial schedule and allocate a memory to hold II rows. */
2611 static partial_schedule_ptr
2612 create_partial_schedule (int ii, ddg_ptr g, int history)
2614 partial_schedule_ptr ps = XNEW (struct partial_schedule);
2615 ps->rows = (ps_insn_ptr *) xcalloc (ii, sizeof (ps_insn_ptr));
2616 ps->rows_length = (int *) xcalloc (ii, sizeof (int));
2617 ps->ii = ii;
2618 ps->history = history;
2619 ps->min_cycle = INT_MAX;
2620 ps->max_cycle = INT_MIN;
2621 ps->g = g;
2623 return ps;
2626 /* Free the PS_INSNs in rows array of the given partial schedule.
2627 ??? Consider caching the PS_INSN's. */
2628 static void
2629 free_ps_insns (partial_schedule_ptr ps)
2631 int i;
2633 for (i = 0; i < ps->ii; i++)
2635 while (ps->rows[i])
2637 ps_insn_ptr ps_insn = ps->rows[i]->next_in_row;
2639 free (ps->rows[i]);
2640 ps->rows[i] = ps_insn;
2642 ps->rows[i] = NULL;
2646 /* Free all the memory allocated to the partial schedule. */
2648 static void
2649 free_partial_schedule (partial_schedule_ptr ps)
2651 if (!ps)
2652 return;
2653 free_ps_insns (ps);
2654 free (ps->rows);
2655 free (ps->rows_length);
2656 free (ps);
2659 /* Clear the rows array with its PS_INSNs, and create a new one with
2660 NEW_II rows. */
2662 static void
2663 reset_partial_schedule (partial_schedule_ptr ps, int new_ii)
2665 if (!ps)
2666 return;
2667 free_ps_insns (ps);
2668 if (new_ii == ps->ii)
2669 return;
2670 ps->rows = (ps_insn_ptr *) xrealloc (ps->rows, new_ii
2671 * sizeof (ps_insn_ptr));
2672 memset (ps->rows, 0, new_ii * sizeof (ps_insn_ptr));
2673 ps->rows_length = (int *) xrealloc (ps->rows_length, new_ii * sizeof (int));
2674 memset (ps->rows_length, 0, new_ii * sizeof (int));
2675 ps->ii = new_ii;
2676 ps->min_cycle = INT_MAX;
2677 ps->max_cycle = INT_MIN;
2680 /* Prints the partial schedule as an ii rows array, for each rows
2681 print the ids of the insns in it. */
2682 void
2683 print_partial_schedule (partial_schedule_ptr ps, FILE *dump)
2685 int i;
2687 for (i = 0; i < ps->ii; i++)
2689 ps_insn_ptr ps_i = ps->rows[i];
2691 fprintf (dump, "\n[ROW %d ]: ", i);
2692 while (ps_i)
2694 if (JUMP_P (ps_i->node->insn))
2695 fprintf (dump, "%d (branch), ",
2696 INSN_UID (ps_i->node->insn));
2697 else
2698 fprintf (dump, "%d, ",
2699 INSN_UID (ps_i->node->insn));
2701 ps_i = ps_i->next_in_row;
2706 /* Creates an object of PS_INSN and initializes it to the given parameters. */
2707 static ps_insn_ptr
2708 create_ps_insn (ddg_node_ptr node, int cycle)
2710 ps_insn_ptr ps_i = XNEW (struct ps_insn);
2712 ps_i->node = node;
2713 ps_i->next_in_row = NULL;
2714 ps_i->prev_in_row = NULL;
2715 ps_i->cycle = cycle;
2717 return ps_i;
2721 /* Removes the given PS_INSN from the partial schedule. */
2722 static void
2723 remove_node_from_ps (partial_schedule_ptr ps, ps_insn_ptr ps_i)
2725 int row;
2727 gcc_assert (ps && ps_i);
2729 row = SMODULO (ps_i->cycle, ps->ii);
2730 if (! ps_i->prev_in_row)
2732 gcc_assert (ps_i == ps->rows[row]);
2733 ps->rows[row] = ps_i->next_in_row;
2734 if (ps->rows[row])
2735 ps->rows[row]->prev_in_row = NULL;
2737 else
2739 ps_i->prev_in_row->next_in_row = ps_i->next_in_row;
2740 if (ps_i->next_in_row)
2741 ps_i->next_in_row->prev_in_row = ps_i->prev_in_row;
2744 ps->rows_length[row] -= 1;
2745 free (ps_i);
2746 return;
2749 /* Unlike what literature describes for modulo scheduling (which focuses
2750 on VLIW machines) the order of the instructions inside a cycle is
2751 important. Given the bitmaps MUST_FOLLOW and MUST_PRECEDE we know
2752 where the current instruction should go relative to the already
2753 scheduled instructions in the given cycle. Go over these
2754 instructions and find the first possible column to put it in. */
2755 static bool
2756 ps_insn_find_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2757 sbitmap must_precede, sbitmap must_follow)
2759 ps_insn_ptr next_ps_i;
2760 ps_insn_ptr first_must_follow = NULL;
2761 ps_insn_ptr last_must_precede = NULL;
2762 ps_insn_ptr last_in_row = NULL;
2763 int row;
2765 if (! ps_i)
2766 return false;
2768 row = SMODULO (ps_i->cycle, ps->ii);
2770 /* Find the first must follow and the last must precede
2771 and insert the node immediately after the must precede
2772 but make sure that it there is no must follow after it. */
2773 for (next_ps_i = ps->rows[row];
2774 next_ps_i;
2775 next_ps_i = next_ps_i->next_in_row)
2777 if (must_follow && TEST_BIT (must_follow, next_ps_i->node->cuid)
2778 && ! first_must_follow)
2779 first_must_follow = next_ps_i;
2780 if (must_precede && TEST_BIT (must_precede, next_ps_i->node->cuid))
2782 /* If we have already met a node that must follow, then
2783 there is no possible column. */
2784 if (first_must_follow)
2785 return false;
2786 else
2787 last_must_precede = next_ps_i;
2789 /* The closing branch must be the last in the row. */
2790 if (must_precede
2791 && TEST_BIT (must_precede, next_ps_i->node->cuid)
2792 && JUMP_P (next_ps_i->node->insn))
2793 return false;
2795 last_in_row = next_ps_i;
2798 /* The closing branch is scheduled as well. Make sure there is no
2799 dependent instruction after it as the branch should be the last
2800 instruction in the row. */
2801 if (JUMP_P (ps_i->node->insn))
2803 if (first_must_follow)
2804 return false;
2805 if (last_in_row)
2807 /* Make the branch the last in the row. New instructions
2808 will be inserted at the beginning of the row or after the
2809 last must_precede instruction thus the branch is guaranteed
2810 to remain the last instruction in the row. */
2811 last_in_row->next_in_row = ps_i;
2812 ps_i->prev_in_row = last_in_row;
2813 ps_i->next_in_row = NULL;
2815 else
2816 ps->rows[row] = ps_i;
2817 return true;
2820 /* Now insert the node after INSERT_AFTER_PSI. */
2822 if (! last_must_precede)
2824 ps_i->next_in_row = ps->rows[row];
2825 ps_i->prev_in_row = NULL;
2826 if (ps_i->next_in_row)
2827 ps_i->next_in_row->prev_in_row = ps_i;
2828 ps->rows[row] = ps_i;
2830 else
2832 ps_i->next_in_row = last_must_precede->next_in_row;
2833 last_must_precede->next_in_row = ps_i;
2834 ps_i->prev_in_row = last_must_precede;
2835 if (ps_i->next_in_row)
2836 ps_i->next_in_row->prev_in_row = ps_i;
2839 return true;
2842 /* Advances the PS_INSN one column in its current row; returns false
2843 in failure and true in success. Bit N is set in MUST_FOLLOW if
2844 the node with cuid N must be come after the node pointed to by
2845 PS_I when scheduled in the same cycle. */
2846 static int
2847 ps_insn_advance_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2848 sbitmap must_follow)
2850 ps_insn_ptr prev, next;
2851 int row;
2852 ddg_node_ptr next_node;
2854 if (!ps || !ps_i)
2855 return false;
2857 row = SMODULO (ps_i->cycle, ps->ii);
2859 if (! ps_i->next_in_row)
2860 return false;
2862 next_node = ps_i->next_in_row->node;
2864 /* Check if next_in_row is dependent on ps_i, both having same sched
2865 times (typically ANTI_DEP). If so, ps_i cannot skip over it. */
2866 if (must_follow && TEST_BIT (must_follow, next_node->cuid))
2867 return false;
2869 /* Advance PS_I over its next_in_row in the doubly linked list. */
2870 prev = ps_i->prev_in_row;
2871 next = ps_i->next_in_row;
2873 if (ps_i == ps->rows[row])
2874 ps->rows[row] = next;
2876 ps_i->next_in_row = next->next_in_row;
2878 if (next->next_in_row)
2879 next->next_in_row->prev_in_row = ps_i;
2881 next->next_in_row = ps_i;
2882 ps_i->prev_in_row = next;
2884 next->prev_in_row = prev;
2885 if (prev)
2886 prev->next_in_row = next;
2888 return true;
2891 /* Inserts a DDG_NODE to the given partial schedule at the given cycle.
2892 Returns 0 if this is not possible and a PS_INSN otherwise. Bit N is
2893 set in MUST_PRECEDE/MUST_FOLLOW if the node with cuid N must be come
2894 before/after (respectively) the node pointed to by PS_I when scheduled
2895 in the same cycle. */
2896 static ps_insn_ptr
2897 add_node_to_ps (partial_schedule_ptr ps, ddg_node_ptr node, int cycle,
2898 sbitmap must_precede, sbitmap must_follow)
2900 ps_insn_ptr ps_i;
2901 int row = SMODULO (cycle, ps->ii);
2903 if (ps->rows_length[row] >= issue_rate)
2904 return NULL;
2906 ps_i = create_ps_insn (node, cycle);
2908 /* Finds and inserts PS_I according to MUST_FOLLOW and
2909 MUST_PRECEDE. */
2910 if (! ps_insn_find_column (ps, ps_i, must_precede, must_follow))
2912 free (ps_i);
2913 return NULL;
2916 ps->rows_length[row] += 1;
2917 return ps_i;
2920 /* Advance time one cycle. Assumes DFA is being used. */
2921 static void
2922 advance_one_cycle (void)
2924 if (targetm.sched.dfa_pre_cycle_insn)
2925 state_transition (curr_state,
2926 targetm.sched.dfa_pre_cycle_insn ());
2928 state_transition (curr_state, NULL);
2930 if (targetm.sched.dfa_post_cycle_insn)
2931 state_transition (curr_state,
2932 targetm.sched.dfa_post_cycle_insn ());
2937 /* Checks if PS has resource conflicts according to DFA, starting from
2938 FROM cycle to TO cycle; returns true if there are conflicts and false
2939 if there are no conflicts. Assumes DFA is being used. */
2940 static int
2941 ps_has_conflicts (partial_schedule_ptr ps, int from, int to)
2943 int cycle;
2945 state_reset (curr_state);
2947 for (cycle = from; cycle <= to; cycle++)
2949 ps_insn_ptr crr_insn;
2950 /* Holds the remaining issue slots in the current row. */
2951 int can_issue_more = issue_rate;
2953 /* Walk through the DFA for the current row. */
2954 for (crr_insn = ps->rows[SMODULO (cycle, ps->ii)];
2955 crr_insn;
2956 crr_insn = crr_insn->next_in_row)
2958 rtx insn = crr_insn->node->insn;
2960 if (!NONDEBUG_INSN_P (insn))
2961 continue;
2963 /* Check if there is room for the current insn. */
2964 if (!can_issue_more || state_dead_lock_p (curr_state))
2965 return true;
2967 /* Update the DFA state and return with failure if the DFA found
2968 resource conflicts. */
2969 if (state_transition (curr_state, insn) >= 0)
2970 return true;
2972 if (targetm.sched.variable_issue)
2973 can_issue_more =
2974 targetm.sched.variable_issue (sched_dump, sched_verbose,
2975 insn, can_issue_more);
2976 /* A naked CLOBBER or USE generates no instruction, so don't
2977 let them consume issue slots. */
2978 else if (GET_CODE (PATTERN (insn)) != USE
2979 && GET_CODE (PATTERN (insn)) != CLOBBER)
2980 can_issue_more--;
2983 /* Advance the DFA to the next cycle. */
2984 advance_one_cycle ();
2986 return false;
2989 /* Checks if the given node causes resource conflicts when added to PS at
2990 cycle C. If not the node is added to PS and returned; otherwise zero
2991 is returned. Bit N is set in MUST_PRECEDE/MUST_FOLLOW if the node with
2992 cuid N must be come before/after (respectively) the node pointed to by
2993 PS_I when scheduled in the same cycle. */
2994 ps_insn_ptr
2995 ps_add_node_check_conflicts (partial_schedule_ptr ps, ddg_node_ptr n,
2996 int c, sbitmap must_precede,
2997 sbitmap must_follow)
2999 int has_conflicts = 0;
3000 ps_insn_ptr ps_i;
3002 /* First add the node to the PS, if this succeeds check for
3003 conflicts, trying different issue slots in the same row. */
3004 if (! (ps_i = add_node_to_ps (ps, n, c, must_precede, must_follow)))
3005 return NULL; /* Failed to insert the node at the given cycle. */
3007 has_conflicts = ps_has_conflicts (ps, c, c)
3008 || (ps->history > 0
3009 && ps_has_conflicts (ps,
3010 c - ps->history,
3011 c + ps->history));
3013 /* Try different issue slots to find one that the given node can be
3014 scheduled in without conflicts. */
3015 while (has_conflicts)
3017 if (! ps_insn_advance_column (ps, ps_i, must_follow))
3018 break;
3019 has_conflicts = ps_has_conflicts (ps, c, c)
3020 || (ps->history > 0
3021 && ps_has_conflicts (ps,
3022 c - ps->history,
3023 c + ps->history));
3026 if (has_conflicts)
3028 remove_node_from_ps (ps, ps_i);
3029 return NULL;
3032 ps->min_cycle = MIN (ps->min_cycle, c);
3033 ps->max_cycle = MAX (ps->max_cycle, c);
3034 return ps_i;
3037 /* Calculate the stage count of the partial schedule PS. The calculation
3038 takes into account the rotation amount passed in ROTATION_AMOUNT. */
3040 calculate_stage_count (partial_schedule_ptr ps, int rotation_amount)
3042 int new_min_cycle = PS_MIN_CYCLE (ps) - rotation_amount;
3043 int new_max_cycle = PS_MAX_CYCLE (ps) - rotation_amount;
3044 int stage_count = CALC_STAGE_COUNT (-1, new_min_cycle, ps->ii);
3046 /* The calculation of stage count is done adding the number of stages
3047 before cycle zero and after cycle zero. */
3048 stage_count += CALC_STAGE_COUNT (new_max_cycle, 0, ps->ii);
3050 return stage_count;
3053 /* Rotate the rows of PS such that insns scheduled at time
3054 START_CYCLE will appear in row 0. Updates max/min_cycles. */
3055 void
3056 rotate_partial_schedule (partial_schedule_ptr ps, int start_cycle)
3058 int i, row, backward_rotates;
3059 int last_row = ps->ii - 1;
3061 if (start_cycle == 0)
3062 return;
3064 backward_rotates = SMODULO (start_cycle, ps->ii);
3066 /* Revisit later and optimize this into a single loop. */
3067 for (i = 0; i < backward_rotates; i++)
3069 ps_insn_ptr first_row = ps->rows[0];
3070 int first_row_length = ps->rows_length[0];
3072 for (row = 0; row < last_row; row++)
3074 ps->rows[row] = ps->rows[row + 1];
3075 ps->rows_length[row] = ps->rows_length[row + 1];
3078 ps->rows[last_row] = first_row;
3079 ps->rows_length[last_row] = first_row_length;
3082 ps->max_cycle -= start_cycle;
3083 ps->min_cycle -= start_cycle;
3086 #endif /* INSN_SCHEDULING */
3088 static bool
3089 gate_handle_sms (void)
3091 return (optimize > 0 && flag_modulo_sched);
3095 /* Run instruction scheduler. */
3096 /* Perform SMS module scheduling. */
3097 static unsigned int
3098 rest_of_handle_sms (void)
3100 #ifdef INSN_SCHEDULING
3101 basic_block bb;
3103 /* Collect loop information to be used in SMS. */
3104 cfg_layout_initialize (0);
3105 sms_schedule ();
3107 /* Update the life information, because we add pseudos. */
3108 max_regno = max_reg_num ();
3110 /* Finalize layout changes. */
3111 FOR_EACH_BB (bb)
3112 if (bb->next_bb != EXIT_BLOCK_PTR)
3113 bb->aux = bb->next_bb;
3114 free_dominance_info (CDI_DOMINATORS);
3115 cfg_layout_finalize ();
3116 #endif /* INSN_SCHEDULING */
3117 return 0;
3120 struct rtl_opt_pass pass_sms =
3123 RTL_PASS,
3124 "sms", /* name */
3125 gate_handle_sms, /* gate */
3126 rest_of_handle_sms, /* execute */
3127 NULL, /* sub */
3128 NULL, /* next */
3129 0, /* static_pass_number */
3130 TV_SMS, /* tv_id */
3131 0, /* properties_required */
3132 0, /* properties_provided */
3133 0, /* properties_destroyed */
3134 0, /* todo_flags_start */
3135 TODO_df_finish
3136 | TODO_verify_flow
3137 | TODO_verify_rtl_sharing
3138 | TODO_ggc_collect /* todo_flags_finish */