OSDN Git Service

PR/30079
[pf3gnuchains/gcc-fork.git] / gcc / modulo-sched.c
1 /* Swing Modulo Scheduling implementation.
2    Copyright (C) 2004, 2005, 2006
3    Free Software Foundation, Inc.
4    Contributed by Ayal Zaks and Mustafa Hagog <zaks,mustafa@il.ibm.com>
5
6 This file is part of GCC.
7
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 2, or (at your option) any later
11 version.
12
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.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
21 02110-1301, USA.  */
22
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "toplev.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "hard-reg-set.h"
32 #include "regs.h"
33 #include "function.h"
34 #include "flags.h"
35 #include "insn-config.h"
36 #include "insn-attr.h"
37 #include "except.h"
38 #include "toplev.h"
39 #include "recog.h"
40 #include "sched-int.h"
41 #include "target.h"
42 #include "cfglayout.h"
43 #include "cfgloop.h"
44 #include "cfghooks.h"
45 #include "expr.h"
46 #include "params.h"
47 #include "gcov-io.h"
48 #include "df.h"
49 #include "ddg.h"
50 #include "timevar.h"
51 #include "tree-pass.h"
52
53 #ifdef INSN_SCHEDULING
54
55 /* This file contains the implementation of the Swing Modulo Scheduler,
56    described in the following references:
57    [1] J. Llosa, A. Gonzalez, E. Ayguade, M. Valero., and J. Eckhardt.
58        Lifetime--sensitive modulo scheduling in a production environment.
59        IEEE Trans. on Comps., 50(3), March 2001
60    [2] J. Llosa, A. Gonzalez, E. Ayguade, and M. Valero.
61        Swing Modulo Scheduling: A Lifetime Sensitive Approach.
62        PACT '96 , pages 80-87, October 1996 (Boston - Massachusetts - USA).
63
64    The basic structure is:
65    1. Build a data-dependence graph (DDG) for each loop.
66    2. Use the DDG to order the insns of a loop (not in topological order
67       necessarily, but rather) trying to place each insn after all its
68       predecessors _or_ after all its successors.
69    3. Compute MII: a lower bound on the number of cycles to schedule the loop.
70    4. Use the ordering to perform list-scheduling of the loop:
71       1. Set II = MII.  We will try to schedule the loop within II cycles.
72       2. Try to schedule the insns one by one according to the ordering.
73          For each insn compute an interval of cycles by considering already-
74          scheduled preds and succs (and associated latencies); try to place
75          the insn in the cycles of this window checking for potential
76          resource conflicts (using the DFA interface).
77          Note: this is different from the cycle-scheduling of schedule_insns;
78          here the insns are not scheduled monotonically top-down (nor bottom-
79          up).
80       3. If failed in scheduling all insns - bump II++ and try again, unless
81          II reaches an upper bound MaxII, in which case report failure.
82    5. If we succeeded in scheduling the loop within II cycles, we now
83       generate prolog and epilog, decrease the counter of the loop, and
84       perform modulo variable expansion for live ranges that span more than
85       II cycles (i.e. use register copies to prevent a def from overwriting
86       itself before reaching the use).
87 */
88
89 \f
90 /* This page defines partial-schedule structures and functions for
91    modulo scheduling.  */
92
93 typedef struct partial_schedule *partial_schedule_ptr;
94 typedef struct ps_insn *ps_insn_ptr;
95
96 /* The minimum (absolute) cycle that a node of ps was scheduled in.  */
97 #define PS_MIN_CYCLE(ps) (((partial_schedule_ptr)(ps))->min_cycle)
98
99 /* The maximum (absolute) cycle that a node of ps was scheduled in.  */
100 #define PS_MAX_CYCLE(ps) (((partial_schedule_ptr)(ps))->max_cycle)
101
102 /* Perform signed modulo, always returning a non-negative value.  */
103 #define SMODULO(x,y) ((x) % (y) < 0 ? ((x) % (y) + (y)) : (x) % (y))
104
105 /* The number of different iterations the nodes in ps span, assuming
106    the stage boundaries are placed efficiently.  */
107 #define PS_STAGE_COUNT(ps) ((PS_MAX_CYCLE (ps) - PS_MIN_CYCLE (ps) \
108                              + 1 + (ps)->ii - 1) / (ps)->ii)
109
110 /* A single instruction in the partial schedule.  */
111 struct ps_insn
112 {
113   /* The corresponding DDG_NODE.  */
114   ddg_node_ptr node;
115
116   /* The (absolute) cycle in which the PS instruction is scheduled.
117      Same as SCHED_TIME (node).  */
118   int cycle;
119
120   /* The next/prev PS_INSN in the same row.  */
121   ps_insn_ptr next_in_row,
122               prev_in_row;
123
124   /* The number of nodes in the same row that come after this node.  */
125   int row_rest_count;
126 };
127
128 /* Holds the partial schedule as an array of II rows.  Each entry of the
129    array points to a linked list of PS_INSNs, which represents the
130    instructions that are scheduled for that row.  */
131 struct partial_schedule
132 {
133   int ii;       /* Number of rows in the partial schedule.  */
134   int history;  /* Threshold for conflict checking using DFA.  */
135
136   /* rows[i] points to linked list of insns scheduled in row i (0<=i<ii).  */
137   ps_insn_ptr *rows;
138
139   /* The earliest absolute cycle of an insn in the partial schedule.  */
140   int min_cycle;
141
142   /* The latest absolute cycle of an insn in the partial schedule.  */
143   int max_cycle;
144
145   ddg_ptr g;    /* The DDG of the insns in the partial schedule.  */
146 };
147
148 /* We use this to record all the register replacements we do in
149    the kernel so we can undo SMS if it is not profitable.  */
150 struct undo_replace_buff_elem
151 {
152   rtx insn;
153   rtx orig_reg;
154   rtx new_reg;
155   struct undo_replace_buff_elem *next;
156 };
157
158
159   
160 static partial_schedule_ptr create_partial_schedule (int ii, ddg_ptr, int history);
161 static void free_partial_schedule (partial_schedule_ptr);
162 static void reset_partial_schedule (partial_schedule_ptr, int new_ii);
163 void print_partial_schedule (partial_schedule_ptr, FILE *);
164 static int kernel_number_of_cycles (rtx first_insn, rtx last_insn);
165 static ps_insn_ptr ps_add_node_check_conflicts (partial_schedule_ptr,
166                                                 ddg_node_ptr node, int cycle,
167                                                 sbitmap must_precede,
168                                                 sbitmap must_follow);
169 static void rotate_partial_schedule (partial_schedule_ptr, int);
170 void set_row_column_for_ps (partial_schedule_ptr);
171 static bool ps_unschedule_node (partial_schedule_ptr, ddg_node_ptr );
172
173 \f
174 /* This page defines constants and structures for the modulo scheduling
175    driver.  */
176
177 /* As in haifa-sched.c:  */
178 /* issue_rate is the number of insns that can be scheduled in the same
179    machine cycle.  It can be defined in the config/mach/mach.h file,
180    otherwise we set it to 1.  */
181
182 static int issue_rate;
183
184 static int sms_order_nodes (ddg_ptr, int, int * result);
185 static void set_node_sched_params (ddg_ptr);
186 static partial_schedule_ptr sms_schedule_by_order (ddg_ptr, int, int, int *);
187 static void permute_partial_schedule (partial_schedule_ptr ps, rtx last);
188 static void generate_prolog_epilog (partial_schedule_ptr ,struct loop * loop, rtx);
189 static void duplicate_insns_of_cycles (partial_schedule_ptr ps,
190                                        int from_stage, int to_stage,
191                                        int is_prolog);
192
193 #define SCHED_ASAP(x) (((node_sched_params_ptr)(x)->aux.info)->asap)
194 #define SCHED_TIME(x) (((node_sched_params_ptr)(x)->aux.info)->time)
195 #define SCHED_FIRST_REG_MOVE(x) \
196         (((node_sched_params_ptr)(x)->aux.info)->first_reg_move)
197 #define SCHED_NREG_MOVES(x) \
198         (((node_sched_params_ptr)(x)->aux.info)->nreg_moves)
199 #define SCHED_ROW(x) (((node_sched_params_ptr)(x)->aux.info)->row)
200 #define SCHED_STAGE(x) (((node_sched_params_ptr)(x)->aux.info)->stage)
201 #define SCHED_COLUMN(x) (((node_sched_params_ptr)(x)->aux.info)->column)
202
203 /* The scheduling parameters held for each node.  */
204 typedef struct node_sched_params
205 {
206   int asap;     /* A lower-bound on the absolute scheduling cycle.  */
207   int time;     /* The absolute scheduling cycle (time >= asap).  */
208
209   /* The following field (first_reg_move) is a pointer to the first
210      register-move instruction added to handle the modulo-variable-expansion
211      of the register defined by this node.  This register-move copies the
212      original register defined by the node.  */
213   rtx first_reg_move;
214
215   /* The number of register-move instructions added, immediately preceding
216      first_reg_move.  */
217   int nreg_moves;
218
219   int row;    /* Holds time % ii.  */
220   int stage;  /* Holds time / ii.  */
221
222   /* The column of a node inside the ps.  If nodes u, v are on the same row,
223      u will precede v if column (u) < column (v).  */
224   int column;
225 } *node_sched_params_ptr;
226
227 \f
228 /* The following three functions are copied from the current scheduler
229    code in order to use sched_analyze() for computing the dependencies.
230    They are used when initializing the sched_info structure.  */
231 static const char *
232 sms_print_insn (rtx insn, int aligned ATTRIBUTE_UNUSED)
233 {
234   static char tmp[80];
235
236   sprintf (tmp, "i%4d", INSN_UID (insn));
237   return tmp;
238 }
239
240 static void
241 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
242                                regset cond_exec ATTRIBUTE_UNUSED,
243                                regset used ATTRIBUTE_UNUSED,
244                                regset set ATTRIBUTE_UNUSED)
245 {
246 }
247
248 static struct sched_info sms_sched_info =
249 {
250   NULL,
251   NULL,
252   NULL,
253   NULL,
254   NULL,
255   sms_print_insn,
256   NULL,
257   compute_jump_reg_dependencies,
258   NULL, NULL,
259   NULL, NULL,
260   0, 0, 0,
261
262   NULL, NULL, NULL, NULL, NULL,
263 #ifdef ENABLE_CHECKING
264   NULL,
265 #endif
266   0
267 };
268
269
270 /* Return the register decremented and tested in INSN,
271    or zero if it is not a decrement-and-branch insn.  */
272
273 static rtx
274 doloop_register_get (rtx insn ATTRIBUTE_UNUSED)
275 {
276 #ifdef HAVE_doloop_end
277   rtx pattern, reg, condition;
278
279   if (! JUMP_P (insn))
280     return NULL_RTX;
281
282   pattern = PATTERN (insn);
283   condition = doloop_condition_get (pattern);
284   if (! condition)
285     return NULL_RTX;
286
287   if (REG_P (XEXP (condition, 0)))
288     reg = XEXP (condition, 0);
289   else if (GET_CODE (XEXP (condition, 0)) == PLUS
290            && REG_P (XEXP (XEXP (condition, 0), 0)))
291     reg = XEXP (XEXP (condition, 0), 0);
292   else
293     gcc_unreachable ();
294
295   return reg;
296 #else
297   return NULL_RTX;
298 #endif
299 }
300
301 /* Check if COUNT_REG is set to a constant in the PRE_HEADER block, so
302    that the number of iterations is a compile-time constant.  If so,
303    return the rtx that sets COUNT_REG to a constant, and set COUNT to
304    this constant.  Otherwise return 0.  */
305 static rtx
306 const_iteration_count (rtx count_reg, basic_block pre_header,
307                        HOST_WIDEST_INT * count)
308 {
309   rtx insn;
310   rtx head, tail;
311
312   if (! pre_header)
313     return NULL_RTX;
314
315   get_ebb_head_tail (pre_header, pre_header, &head, &tail);
316
317   for (insn = tail; insn != PREV_INSN (head); insn = PREV_INSN (insn))
318     if (INSN_P (insn) && single_set (insn) &&
319         rtx_equal_p (count_reg, SET_DEST (single_set (insn))))
320       {
321         rtx pat = single_set (insn);
322
323         if (GET_CODE (SET_SRC (pat)) == CONST_INT)
324           {
325             *count = INTVAL (SET_SRC (pat));
326             return insn;
327           }
328
329         return NULL_RTX;
330       }
331
332   return NULL_RTX;
333 }
334
335 /* A very simple resource-based lower bound on the initiation interval.
336    ??? Improve the accuracy of this bound by considering the
337    utilization of various units.  */
338 static int
339 res_MII (ddg_ptr g)
340 {
341   return (g->num_nodes / issue_rate);
342 }
343
344
345 /* Points to the array that contains the sched data for each node.  */
346 static node_sched_params_ptr node_sched_params;
347
348 /* Allocate sched_params for each node and initialize it.  Assumes that
349    the aux field of each node contain the asap bound (computed earlier),
350    and copies it into the sched_params field.  */
351 static void
352 set_node_sched_params (ddg_ptr g)
353 {
354   int i;
355
356   /* Allocate for each node in the DDG a place to hold the "sched_data".  */
357   /* Initialize ASAP/ALAP/HIGHT to zero.  */
358   node_sched_params = (node_sched_params_ptr)
359                        xcalloc (g->num_nodes,
360                                 sizeof (struct node_sched_params));
361
362   /* Set the pointer of the general data of the node to point to the
363      appropriate sched_params structure.  */
364   for (i = 0; i < g->num_nodes; i++)
365     {
366       /* Watch out for aliasing problems?  */
367       node_sched_params[i].asap = g->nodes[i].aux.count;
368       g->nodes[i].aux.info = &node_sched_params[i];
369     }
370 }
371
372 static void
373 print_node_sched_params (FILE * file, int num_nodes)
374 {
375   int i;
376
377   if (! file)
378     return;
379   for (i = 0; i < num_nodes; i++)
380     {
381       node_sched_params_ptr nsp = &node_sched_params[i];
382       rtx reg_move = nsp->first_reg_move;
383       int j;
384
385       fprintf (file, "Node %d:\n", i);
386       fprintf (file, " asap = %d:\n", nsp->asap);
387       fprintf (file, " time = %d:\n", nsp->time);
388       fprintf (file, " nreg_moves = %d:\n", nsp->nreg_moves);
389       for (j = 0; j < nsp->nreg_moves; j++)
390         {
391           fprintf (file, " reg_move = ");
392           print_rtl_single (file, reg_move);
393           reg_move = PREV_INSN (reg_move);
394         }
395     }
396 }
397
398 /* Calculate an upper bound for II.  SMS should not schedule the loop if it
399    requires more cycles than this bound.  Currently set to the sum of the
400    longest latency edge for each node.  Reset based on experiments.  */
401 static int
402 calculate_maxii (ddg_ptr g)
403 {
404   int i;
405   int maxii = 0;
406
407   for (i = 0; i < g->num_nodes; i++)
408     {
409       ddg_node_ptr u = &g->nodes[i];
410       ddg_edge_ptr e;
411       int max_edge_latency = 0;
412
413       for (e = u->out; e; e = e->next_out)
414         max_edge_latency = MAX (max_edge_latency, e->latency);
415
416       maxii += max_edge_latency;
417     }
418   return maxii;
419 }
420
421 /*
422    Breaking intra-loop register anti-dependences:
423    Each intra-loop register anti-dependence implies a cross-iteration true
424    dependence of distance 1. Therefore, we can remove such false dependencies
425    and figure out if the partial schedule broke them by checking if (for a
426    true-dependence of distance 1): SCHED_TIME (def) < SCHED_TIME (use) and
427    if so generate a register move.   The number of such moves is equal to:
428               SCHED_TIME (use) - SCHED_TIME (def)       { 0 broken
429    nreg_moves = ----------------------------------- + 1 - {   dependence.
430                             ii                          { 1 if not.
431 */
432 static struct undo_replace_buff_elem *
433 generate_reg_moves (partial_schedule_ptr ps)
434 {
435   ddg_ptr g = ps->g;
436   int ii = ps->ii;
437   int i;
438   struct undo_replace_buff_elem *reg_move_replaces = NULL;
439
440   for (i = 0; i < g->num_nodes; i++)
441     {
442       ddg_node_ptr u = &g->nodes[i];
443       ddg_edge_ptr e;
444       int nreg_moves = 0, i_reg_move;
445       sbitmap *uses_of_defs;
446       rtx last_reg_move;
447       rtx prev_reg, old_reg;
448
449       /* Compute the number of reg_moves needed for u, by looking at life
450          ranges started at u (excluding self-loops).  */
451       for (e = u->out; e; e = e->next_out)
452         if (e->type == TRUE_DEP && e->dest != e->src)
453           {
454             int nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
455
456             if (e->distance == 1)
457               nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
458
459             /* If dest precedes src in the schedule of the kernel, then dest
460                will read before src writes and we can save one reg_copy.  */
461             if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
462                 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
463               nreg_moves4e--;
464
465             nreg_moves = MAX (nreg_moves, nreg_moves4e);
466           }
467
468       if (nreg_moves == 0)
469         continue;
470
471       /* Every use of the register defined by node may require a different
472          copy of this register, depending on the time the use is scheduled.
473          Set a bitmap vector, telling which nodes use each copy of this
474          register.  */
475       uses_of_defs = sbitmap_vector_alloc (nreg_moves, g->num_nodes);
476       sbitmap_vector_zero (uses_of_defs, nreg_moves);
477       for (e = u->out; e; e = e->next_out)
478         if (e->type == TRUE_DEP && e->dest != e->src)
479           {
480             int dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
481
482             if (e->distance == 1)
483               dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
484
485             if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
486                 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
487               dest_copy--;
488
489             if (dest_copy)
490               SET_BIT (uses_of_defs[dest_copy - 1], e->dest->cuid);
491           }
492
493       /* Now generate the reg_moves, attaching relevant uses to them.  */
494       SCHED_NREG_MOVES (u) = nreg_moves;
495       old_reg = prev_reg = copy_rtx (SET_DEST (single_set (u->insn)));
496       last_reg_move = u->insn;
497
498       for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
499         {
500           unsigned int i_use = 0;
501           rtx new_reg = gen_reg_rtx (GET_MODE (prev_reg));
502           rtx reg_move = gen_move_insn (new_reg, prev_reg);
503           sbitmap_iterator sbi;
504
505           add_insn_before (reg_move, last_reg_move);
506           last_reg_move = reg_move;
507
508           if (!SCHED_FIRST_REG_MOVE (u))
509             SCHED_FIRST_REG_MOVE (u) = reg_move;
510
511           EXECUTE_IF_SET_IN_SBITMAP (uses_of_defs[i_reg_move], 0, i_use, sbi)
512             {
513               struct undo_replace_buff_elem *rep;
514
515               rep = (struct undo_replace_buff_elem *)
516                     xcalloc (1, sizeof (struct undo_replace_buff_elem));
517               rep->insn = g->nodes[i_use].insn;
518               rep->orig_reg = old_reg;
519               rep->new_reg = new_reg;
520
521               if (! reg_move_replaces)
522                 reg_move_replaces = rep;
523               else
524                 {
525                   rep->next = reg_move_replaces;
526                   reg_move_replaces = rep;
527                 }
528
529               replace_rtx (g->nodes[i_use].insn, old_reg, new_reg);
530             }
531
532           prev_reg = new_reg;
533         }
534       sbitmap_vector_free (uses_of_defs);
535     }
536   return reg_move_replaces;
537 }
538
539 /* We call this when we want to undo the SMS schedule for a given loop.
540    One of the things that we do is to delete the register moves generated
541    for the sake of SMS; this function deletes the register move instructions
542    recorded in the undo buffer.  */
543 static void
544 undo_generate_reg_moves (partial_schedule_ptr ps,
545                          struct undo_replace_buff_elem *reg_move_replaces)
546 {
547   int i,j;
548
549   for (i = 0; i < ps->g->num_nodes; i++)
550     {
551       ddg_node_ptr u = &ps->g->nodes[i];
552       rtx prev;
553       rtx crr = SCHED_FIRST_REG_MOVE (u);
554
555       for (j = 0; j < SCHED_NREG_MOVES (u); j++)
556         {
557           prev = PREV_INSN (crr);
558           delete_insn (crr);
559           crr = prev;
560         }
561       SCHED_FIRST_REG_MOVE (u) = NULL_RTX;
562     }
563
564   while (reg_move_replaces)
565     {
566       struct undo_replace_buff_elem *rep = reg_move_replaces;
567
568       reg_move_replaces = reg_move_replaces->next;
569       replace_rtx (rep->insn, rep->new_reg, rep->orig_reg);
570     }
571 }
572
573 /* Free memory allocated for the undo buffer.  */
574 static void
575 free_undo_replace_buff (struct undo_replace_buff_elem *reg_move_replaces)
576 {
577
578   while (reg_move_replaces)
579     {
580       struct undo_replace_buff_elem *rep = reg_move_replaces;
581
582       reg_move_replaces = reg_move_replaces->next;
583       free (rep);
584     }
585 }
586
587 /* Bump the SCHED_TIMEs of all nodes to start from zero.  Set the values
588    of SCHED_ROW and SCHED_STAGE.  */
589 static void
590 normalize_sched_times (partial_schedule_ptr ps)
591 {
592   int i;
593   ddg_ptr g = ps->g;
594   int amount = PS_MIN_CYCLE (ps);
595   int ii = ps->ii;
596
597   /* Don't include the closing branch assuming that it is the last node.  */
598   for (i = 0; i < g->num_nodes - 1; i++)
599     {
600       ddg_node_ptr u = &g->nodes[i];
601       int normalized_time = SCHED_TIME (u) - amount;
602
603       gcc_assert (normalized_time >= 0);
604
605       SCHED_TIME (u) = normalized_time;
606       SCHED_ROW (u) = normalized_time % ii;
607       SCHED_STAGE (u) = normalized_time / ii;
608     }
609 }
610
611 /* Set SCHED_COLUMN of each node according to its position in PS.  */
612 static void
613 set_columns_for_ps (partial_schedule_ptr ps)
614 {
615   int row;
616
617   for (row = 0; row < ps->ii; row++)
618     {
619       ps_insn_ptr cur_insn = ps->rows[row];
620       int column = 0;
621
622       for (; cur_insn; cur_insn = cur_insn->next_in_row)
623         SCHED_COLUMN (cur_insn->node) = column++;
624     }
625 }
626
627 /* Permute the insns according to their order in PS, from row 0 to
628    row ii-1, and position them right before LAST.  This schedules
629    the insns of the loop kernel.  */
630 static void
631 permute_partial_schedule (partial_schedule_ptr ps, rtx last)
632 {
633   int ii = ps->ii;
634   int row;
635   ps_insn_ptr ps_ij;
636
637   for (row = 0; row < ii ; row++)
638     for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
639       if (PREV_INSN (last) != ps_ij->node->insn)
640         reorder_insns_nobb (ps_ij->node->first_note, ps_ij->node->insn,
641                             PREV_INSN (last));
642 }
643
644 /* As part of undoing SMS we return to the original ordering of the
645    instructions inside the loop kernel.  Given the partial schedule PS, this
646    function returns the ordering of the instruction according to their CUID
647    in the DDG (PS->G), which is the original order of the instruction before
648    performing SMS.  */
649 static void
650 undo_permute_partial_schedule (partial_schedule_ptr ps, rtx last)
651 {
652   int i;
653
654   for (i = 0 ; i < ps->g->num_nodes; i++)
655     if (last == ps->g->nodes[i].insn
656         || last == ps->g->nodes[i].first_note)
657       break;
658     else if (PREV_INSN (last) != ps->g->nodes[i].insn)
659       reorder_insns_nobb (ps->g->nodes[i].first_note, ps->g->nodes[i].insn,
660                           PREV_INSN (last));
661 }
662
663 /* Used to generate the prologue & epilogue.  Duplicate the subset of
664    nodes whose stages are between FROM_STAGE and TO_STAGE (inclusive
665    of both), together with a prefix/suffix of their reg_moves.  */
666 static void
667 duplicate_insns_of_cycles (partial_schedule_ptr ps, int from_stage,
668                            int to_stage, int for_prolog)
669 {
670   int row;
671   ps_insn_ptr ps_ij;
672
673   for (row = 0; row < ps->ii; row++)
674     for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
675       {
676         ddg_node_ptr u_node = ps_ij->node;
677         int j, i_reg_moves;
678         rtx reg_move = NULL_RTX;
679
680         if (for_prolog)
681           {
682             /* SCHED_STAGE (u_node) >= from_stage == 0.  Generate increasing
683                number of reg_moves starting with the second occurrence of
684                u_node, which is generated if its SCHED_STAGE <= to_stage.  */
685             i_reg_moves = to_stage - SCHED_STAGE (u_node) + 1;
686             i_reg_moves = MAX (i_reg_moves, 0);
687             i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
688
689             /* The reg_moves start from the *first* reg_move backwards.  */
690             if (i_reg_moves)
691               {
692                 reg_move = SCHED_FIRST_REG_MOVE (u_node);
693                 for (j = 1; j < i_reg_moves; j++)
694                   reg_move = PREV_INSN (reg_move);
695               }
696           }
697         else /* It's for the epilog.  */
698           {
699             /* SCHED_STAGE (u_node) <= to_stage.  Generate all reg_moves,
700                starting to decrease one stage after u_node no longer occurs;
701                that is, generate all reg_moves until
702                SCHED_STAGE (u_node) == from_stage - 1.  */
703             i_reg_moves = SCHED_NREG_MOVES (u_node)
704                        - (from_stage - SCHED_STAGE (u_node) - 1);
705             i_reg_moves = MAX (i_reg_moves, 0);
706             i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
707
708             /* The reg_moves start from the *last* reg_move forwards.  */
709             if (i_reg_moves)
710               {
711                 reg_move = SCHED_FIRST_REG_MOVE (u_node);
712                 for (j = 1; j < SCHED_NREG_MOVES (u_node); j++)
713                   reg_move = PREV_INSN (reg_move);
714               }
715           }
716
717         for (j = 0; j < i_reg_moves; j++, reg_move = NEXT_INSN (reg_move))
718           emit_insn (copy_rtx (PATTERN (reg_move)));
719         if (SCHED_STAGE (u_node) >= from_stage
720             && SCHED_STAGE (u_node) <= to_stage)
721           duplicate_insn_chain (u_node->first_note, u_node->insn);
722       }
723 }
724
725
726 /* Generate the instructions (including reg_moves) for prolog & epilog.  */
727 static void
728 generate_prolog_epilog (partial_schedule_ptr ps, struct loop * loop, rtx count_reg)
729 {
730   int i;
731   int last_stage = PS_STAGE_COUNT (ps) - 1;
732   edge e;
733
734   /* Generate the prolog, inserting its insns on the loop-entry edge.  */
735   start_sequence ();
736
737   if (count_reg)
738    /* Generate a subtract instruction at the beginning of the prolog to
739       adjust the loop count by STAGE_COUNT.  */
740    emit_insn (gen_sub2_insn (count_reg, GEN_INT (last_stage)));
741
742   for (i = 0; i < last_stage; i++)
743     duplicate_insns_of_cycles (ps, 0, i, 1);
744
745   /* Put the prolog on the entry edge.  */
746   e = loop_preheader_edge (loop);
747   split_edge_and_insert (e, get_insns());
748
749   end_sequence ();
750
751   /* Generate the epilog, inserting its insns on the loop-exit edge.  */
752   start_sequence ();
753
754   for (i = 0; i < last_stage; i++)
755     duplicate_insns_of_cycles (ps, i + 1, last_stage, 0);
756
757   /* Put the epilogue on the exit edge.  */
758   gcc_assert (single_exit (loop));
759   e = single_exit (loop);
760   split_edge_and_insert (e, get_insns());
761   end_sequence ();
762 }
763
764 /* Return true if all the BBs of the loop are empty except the
765    loop header.  */
766 static bool
767 loop_single_full_bb_p (struct loop *loop)
768 {
769   unsigned i;
770   basic_block *bbs = get_loop_body (loop);
771
772   for (i = 0; i < loop->num_nodes ; i++)
773     {
774       rtx head, tail;
775       bool empty_bb = true;
776
777       if (bbs[i] == loop->header)
778         continue;
779
780       /* Make sure that basic blocks other than the header
781          have only notes labels or jumps.  */
782       get_ebb_head_tail (bbs[i], bbs[i], &head, &tail);
783       for (; head != NEXT_INSN (tail); head = NEXT_INSN (head))
784         {
785           if (NOTE_P (head) || LABEL_P (head)
786               || (INSN_P (head) && JUMP_P (head)))
787             continue;
788           empty_bb = false;
789           break;
790         }
791
792       if (! empty_bb)
793         {
794           free (bbs);
795           return false;
796         }
797     }
798   free (bbs);
799   return true;
800 }
801
802 /* A simple loop from SMS point of view; it is a loop that is composed of
803    either a single basic block or two BBs - a header and a latch.  */
804 #define SIMPLE_SMS_LOOP_P(loop) ((loop->num_nodes < 3 )                     \
805                                   && (EDGE_COUNT (loop->latch->preds) == 1) \
806                                   && (EDGE_COUNT (loop->latch->succs) == 1))
807
808 /* Return true if the loop is in its canonical form and false if not.
809    i.e. SIMPLE_SMS_LOOP_P and have one preheader block, and single exit.  */
810 static bool
811 loop_canon_p (struct loop *loop)
812 {
813
814   if (loop->inner || ! loop->outer)
815     return false;
816
817   if (!single_exit (loop))
818     {
819       if (dump_file)
820         {
821           rtx insn = BB_END (loop->header);
822  
823           fprintf (dump_file, "SMS loop many exits ");
824                   fprintf (dump_file, " %s %d (file, line)\n",
825                            insn_file (insn), insn_line (insn));
826         }
827       return false;
828     }
829
830   if (! SIMPLE_SMS_LOOP_P (loop) && ! loop_single_full_bb_p (loop))
831     {
832       if (dump_file)
833         {
834           rtx insn = BB_END (loop->header);
835  
836           fprintf (dump_file, "SMS loop many BBs. ");
837           fprintf (dump_file, " %s %d (file, line)\n",
838                    insn_file (insn), insn_line (insn));
839         }
840       return false;
841     }
842
843     return true;
844 }
845
846 /* If there are more than one entry for the loop,
847    make it one by splitting the first entry edge and
848    redirecting the others to the new BB.  */
849 static void
850 canon_loop (struct loop *loop)
851 {
852   edge e;
853   edge_iterator i;
854
855   /* Avoid annoying special cases of edges going to exit
856      block.  */
857   FOR_EACH_EDGE (e, i, EXIT_BLOCK_PTR->preds)
858     if ((e->flags & EDGE_FALLTHRU) && (EDGE_COUNT (e->src->succs) > 1))
859       split_edge (e);
860
861   if (loop->latch == loop->header
862       || EDGE_COUNT (loop->latch->succs) > 1)
863     {
864       FOR_EACH_EDGE (e, i, loop->header->preds)
865         if (e->src == loop->latch)
866           break;
867       split_edge (e);
868     }
869 }
870
871 /* Main entry point, perform SMS scheduling on the loops of the function
872    that consist of single basic blocks.  */
873 static void
874 sms_schedule (void)
875 {
876   static int passes = 0;
877   rtx insn;
878   ddg_ptr *g_arr, g;
879   int * node_order;
880   int maxii;
881   unsigned i,num_loops;
882   partial_schedule_ptr ps;
883   struct df *df;
884   basic_block bb = NULL;
885   /* vars to the versioning only if needed*/
886   struct loop * nloop;
887   basic_block condition_bb = NULL;
888   edge latch_edge;
889   gcov_type trip_count = 0;
890
891   loop_optimizer_init (LOOPS_HAVE_PREHEADERS
892                        | LOOPS_HAVE_MARKED_SINGLE_EXITS);
893   if (!current_loops)
894     return;  /* There are no loops to schedule.  */
895
896   /* Initialize issue_rate.  */
897   if (targetm.sched.issue_rate)
898     {
899       int temp = reload_completed;
900
901       reload_completed = 1;
902       issue_rate = targetm.sched.issue_rate ();
903       reload_completed = temp;
904     }
905   else
906     issue_rate = 1;
907
908   /* Initialize the scheduler.  */
909   current_sched_info = &sms_sched_info;
910   sched_init ();
911
912   /* Init Data Flow analysis, to be used in interloop dep calculation.  */
913   df = df_init (DF_HARD_REGS | DF_EQUIV_NOTES | DF_SUBREGS);
914   df_rd_add_problem (df, 0);
915   df_ru_add_problem (df, 0);
916   df_chain_add_problem (df, DF_DU_CHAIN | DF_UD_CHAIN);
917   df_analyze (df);
918
919   if (dump_file)
920     df_dump (df, dump_file);
921
922   /* Allocate memory to hold the DDG array one entry for each loop.
923      We use loop->num as index into this array.  */
924   g_arr = XCNEWVEC (ddg_ptr, current_loops->num);
925
926
927   /* Build DDGs for all the relevant loops and hold them in G_ARR
928      indexed by the loop index.  */
929   for (i = 0; i < current_loops->num; i++)
930     {
931       rtx head, tail;
932       rtx count_reg;
933       struct loop *loop = current_loops->parray[i];
934
935       /* For debugging.  */
936       if ((passes++ > MAX_SMS_LOOP_NUMBER) && (MAX_SMS_LOOP_NUMBER != -1))
937         {
938           if (dump_file)
939             fprintf (dump_file, "SMS reached MAX_PASSES... \n");
940
941           break;
942         }
943
944       if (! loop_canon_p (loop))
945         continue;
946
947       if (! loop_single_full_bb_p (loop))
948         continue;
949
950       bb = loop->header;
951
952       get_ebb_head_tail (bb, bb, &head, &tail);
953       latch_edge = loop_latch_edge (loop);
954       gcc_assert (single_exit (loop));
955       if (single_exit (loop)->count)
956         trip_count = latch_edge->count / single_exit (loop)->count;
957
958       /* Perfrom SMS only on loops that their average count is above threshold.  */
959
960       if ( latch_edge->count
961           && (latch_edge->count < single_exit (loop)->count * SMS_LOOP_AVERAGE_COUNT_THRESHOLD))
962         {
963           if (dump_file)
964             {
965               fprintf (dump_file, " %s %d (file, line)\n",
966                        insn_file (tail), insn_line (tail));
967               fprintf (dump_file, "SMS single-bb-loop\n");
968               if (profile_info && flag_branch_probabilities)
969                 {
970                   fprintf (dump_file, "SMS loop-count ");
971                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
972                            (HOST_WIDEST_INT) bb->count);
973                   fprintf (dump_file, "\n");
974                   fprintf (dump_file, "SMS trip-count ");
975                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
976                            (HOST_WIDEST_INT) trip_count);
977                   fprintf (dump_file, "\n");
978                   fprintf (dump_file, "SMS profile-sum-max ");
979                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
980                            (HOST_WIDEST_INT) profile_info->sum_max);
981                   fprintf (dump_file, "\n");
982                 }
983             }
984           continue;
985         }
986
987       /* Make sure this is a doloop.  */
988       if ( !(count_reg = doloop_register_get (tail)))
989         continue;
990
991       /* Don't handle BBs with calls or barriers, or !single_set insns.  */
992       for (insn = head; insn != NEXT_INSN (tail); insn = NEXT_INSN (insn))
993         if (CALL_P (insn)
994             || BARRIER_P (insn)
995             || (INSN_P (insn) && !JUMP_P (insn)
996                 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE))
997           break;
998
999       if (insn != NEXT_INSN (tail))
1000         {
1001           if (dump_file)
1002             {
1003               if (CALL_P (insn))
1004                 fprintf (dump_file, "SMS loop-with-call\n");
1005               else if (BARRIER_P (insn))
1006                 fprintf (dump_file, "SMS loop-with-barrier\n");
1007               else
1008                 fprintf (dump_file, "SMS loop-with-not-single-set\n");
1009               print_rtl_single (dump_file, insn);
1010             }
1011
1012           continue;
1013         }
1014
1015       if (! (g = create_ddg (bb, df, 0)))
1016         {
1017           if (dump_file)
1018             fprintf (dump_file, "SMS doloop\n");
1019           continue;
1020         }
1021
1022       g_arr[i] = g;
1023     }
1024
1025   /* Release Data Flow analysis data structures.  */
1026   df_finish (df);
1027   df = NULL;
1028
1029   /* We don't want to perform SMS on new loops - created by versioning.  */
1030   num_loops = current_loops->num;
1031   /* Go over the built DDGs and perfrom SMS for each one of them.  */
1032   for (i = 0; i < num_loops; i++)
1033     {
1034       rtx head, tail;
1035       rtx count_reg, count_init;
1036       int mii, rec_mii;
1037       unsigned stage_count = 0;
1038       HOST_WIDEST_INT loop_count = 0;
1039       struct loop *loop = current_loops->parray[i];
1040
1041       if (! (g = g_arr[i]))
1042         continue;
1043
1044       if (dump_file)
1045         print_ddg (dump_file, g);
1046
1047       get_ebb_head_tail (loop->header, loop->header, &head, &tail);
1048
1049       latch_edge = loop_latch_edge (loop);
1050       gcc_assert (single_exit (loop));
1051       if (single_exit (loop)->count)
1052         trip_count = latch_edge->count / single_exit (loop)->count;
1053
1054       if (dump_file)
1055         {
1056           fprintf (dump_file, " %s %d (file, line)\n",
1057                    insn_file (tail), insn_line (tail));
1058           fprintf (dump_file, "SMS single-bb-loop\n");
1059           if (profile_info && flag_branch_probabilities)
1060             {
1061               fprintf (dump_file, "SMS loop-count ");
1062               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1063                        (HOST_WIDEST_INT) bb->count);
1064               fprintf (dump_file, "\n");
1065               fprintf (dump_file, "SMS profile-sum-max ");
1066               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1067                        (HOST_WIDEST_INT) profile_info->sum_max);
1068               fprintf (dump_file, "\n");
1069             }
1070           fprintf (dump_file, "SMS doloop\n");
1071           fprintf (dump_file, "SMS built-ddg %d\n", g->num_nodes);
1072           fprintf (dump_file, "SMS num-loads %d\n", g->num_loads);
1073           fprintf (dump_file, "SMS num-stores %d\n", g->num_stores);
1074         }
1075
1076
1077       /* In case of th loop have doloop register it gets special
1078          handling.  */
1079       count_init = NULL_RTX;
1080       if ((count_reg = doloop_register_get (tail)))
1081         {
1082           basic_block pre_header;
1083
1084           pre_header = loop_preheader_edge (loop)->src;
1085           count_init = const_iteration_count (count_reg, pre_header,
1086                                               &loop_count);
1087         }
1088       gcc_assert (count_reg);
1089
1090       if (dump_file && count_init)
1091         {
1092           fprintf (dump_file, "SMS const-doloop ");
1093           fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1094                      loop_count);
1095           fprintf (dump_file, "\n");
1096         }
1097
1098       node_order = XNEWVEC (int, g->num_nodes);
1099
1100       mii = 1; /* Need to pass some estimate of mii.  */
1101       rec_mii = sms_order_nodes (g, mii, node_order);
1102       mii = MAX (res_MII (g), rec_mii);
1103       maxii = (calculate_maxii (g) * SMS_MAX_II_FACTOR) / 100;
1104
1105       if (dump_file)
1106         fprintf (dump_file, "SMS iis %d %d %d (rec_mii, mii, maxii)\n",
1107                  rec_mii, mii, maxii);
1108
1109       /* After sms_order_nodes and before sms_schedule_by_order, to copy over
1110          ASAP.  */
1111       set_node_sched_params (g);
1112
1113       ps = sms_schedule_by_order (g, mii, maxii, node_order);
1114
1115       if (ps)
1116         stage_count = PS_STAGE_COUNT (ps);
1117
1118       /* Stage count of 1 means that there is no interleaving between
1119          iterations, let the scheduling passes do the job.  */
1120       if (stage_count < 1
1121           || (count_init && (loop_count <= stage_count))
1122           || (flag_branch_probabilities && (trip_count <= stage_count)))
1123         {
1124           if (dump_file)
1125             {
1126               fprintf (dump_file, "SMS failed... \n");
1127               fprintf (dump_file, "SMS sched-failed (stage-count=%d, loop-count=", stage_count);
1128               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, loop_count);
1129               fprintf (dump_file, ", trip-count=");
1130               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, trip_count);
1131               fprintf (dump_file, ")\n");
1132             }
1133           continue;
1134         }
1135       else
1136         {
1137           int orig_cycles = kernel_number_of_cycles (BB_HEAD (g->bb), BB_END (g->bb));
1138           int new_cycles;
1139           struct undo_replace_buff_elem *reg_move_replaces;
1140
1141           if (dump_file)
1142             {
1143               fprintf (dump_file,
1144                        "SMS succeeded %d %d (with ii, sc)\n", ps->ii,
1145                        stage_count);
1146               print_partial_schedule (ps, dump_file);
1147               fprintf (dump_file,
1148                        "SMS Branch (%d) will later be scheduled at cycle %d.\n",
1149                        g->closing_branch->cuid, PS_MIN_CYCLE (ps) - 1);
1150             }
1151
1152           /* Set the stage boundaries.  If the DDG is built with closing_branch_deps,
1153              the closing_branch was scheduled and should appear in the last (ii-1)
1154              row.  Otherwise, we are free to schedule the branch, and we let nodes
1155              that were scheduled at the first PS_MIN_CYCLE cycle appear in the first
1156              row; this should reduce stage_count to minimum.  */
1157           normalize_sched_times (ps);
1158           rotate_partial_schedule (ps, PS_MIN_CYCLE (ps));
1159           set_columns_for_ps (ps);
1160
1161           /* Generate the kernel just to be able to measure its cycles.  */
1162           permute_partial_schedule (ps, g->closing_branch->first_note);
1163           reg_move_replaces = generate_reg_moves (ps);
1164
1165           /* Get the number of cycles the new kernel expect to execute in.  */
1166           new_cycles = kernel_number_of_cycles (BB_HEAD (g->bb), BB_END (g->bb));
1167
1168           /* Get back to the original loop so we can do loop versioning.  */
1169           undo_permute_partial_schedule (ps, g->closing_branch->first_note);
1170           if (reg_move_replaces)
1171             undo_generate_reg_moves (ps, reg_move_replaces);
1172
1173           if ( new_cycles >= orig_cycles)
1174             {
1175               /* SMS is not profitable so undo the permutation and reg move generation
1176                  and return the kernel to its original state.  */
1177               if (dump_file)
1178                 fprintf (dump_file, "Undoing SMS because it is not profitable.\n");
1179
1180             }
1181           else
1182             {
1183               canon_loop (loop);
1184
1185               /* case the BCT count is not known , Do loop-versioning */
1186               if (count_reg && ! count_init)
1187                 {
1188                   rtx comp_rtx = gen_rtx_fmt_ee (GT, VOIDmode, count_reg,
1189                                                  GEN_INT(stage_count));
1190
1191                   nloop = loop_version (loop, comp_rtx, &condition_bb, true);
1192                 }
1193
1194               /* Set new iteration count of loop kernel.  */
1195               if (count_reg && count_init)
1196                 SET_SRC (single_set (count_init)) = GEN_INT (loop_count
1197                                                              - stage_count + 1);
1198
1199               /* Now apply the scheduled kernel to the RTL of the loop.  */
1200               permute_partial_schedule (ps, g->closing_branch->first_note);
1201
1202               /* Mark this loop as software pipelined so the later
1203               scheduling passes doesn't touch it.  */
1204               if (! flag_resched_modulo_sched)
1205                 g->bb->flags |= BB_DISABLE_SCHEDULE;
1206               /* The life-info is not valid any more.  */
1207               g->bb->flags |= BB_DIRTY;
1208
1209               reg_move_replaces = generate_reg_moves (ps);
1210               if (dump_file)
1211                 print_node_sched_params (dump_file, g->num_nodes);
1212               /* Generate prolog and epilog.  */
1213               if (count_reg && !count_init)
1214                 generate_prolog_epilog (ps, loop, count_reg);
1215               else
1216                 generate_prolog_epilog (ps, loop, NULL_RTX);
1217             }
1218           free_undo_replace_buff (reg_move_replaces);
1219         }
1220
1221       free_partial_schedule (ps);
1222       free (node_sched_params);
1223       free (node_order);
1224       free_ddg (g);
1225     }
1226
1227   free (g_arr);
1228
1229   /* Release scheduler data, needed until now because of DFA.  */
1230   sched_finish ();
1231   loop_optimizer_finalize ();
1232 }
1233
1234 /* The SMS scheduling algorithm itself
1235    -----------------------------------
1236    Input: 'O' an ordered list of insns of a loop.
1237    Output: A scheduling of the loop - kernel, prolog, and epilogue.
1238
1239    'Q' is the empty Set
1240    'PS' is the partial schedule; it holds the currently scheduled nodes with
1241         their cycle/slot.
1242    'PSP' previously scheduled predecessors.
1243    'PSS' previously scheduled successors.
1244    't(u)' the cycle where u is scheduled.
1245    'l(u)' is the latency of u.
1246    'd(v,u)' is the dependence distance from v to u.
1247    'ASAP(u)' the earliest time at which u could be scheduled as computed in
1248              the node ordering phase.
1249    'check_hardware_resources_conflicts(u, PS, c)'
1250                              run a trace around cycle/slot through DFA model
1251                              to check resource conflicts involving instruction u
1252                              at cycle c given the partial schedule PS.
1253    'add_to_partial_schedule_at_time(u, PS, c)'
1254                              Add the node/instruction u to the partial schedule
1255                              PS at time c.
1256    'calculate_register_pressure(PS)'
1257                              Given a schedule of instructions, calculate the register
1258                              pressure it implies.  One implementation could be the
1259                              maximum number of overlapping live ranges.
1260    'maxRP' The maximum allowed register pressure, it is usually derived from the number
1261            registers available in the hardware.
1262
1263    1. II = MII.
1264    2. PS = empty list
1265    3. for each node u in O in pre-computed order
1266    4.   if (PSP(u) != Q && PSS(u) == Q) then
1267    5.     Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1268    6.     start = Early_start; end = Early_start + II - 1; step = 1
1269    11.  else if (PSP(u) == Q && PSS(u) != Q) then
1270    12.      Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1271    13.     start = Late_start; end = Late_start - II + 1; step = -1
1272    14.  else if (PSP(u) != Q && PSS(u) != Q) then
1273    15.     Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1274    16.     Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1275    17.     start = Early_start;
1276    18.     end = min(Early_start + II - 1 , Late_start);
1277    19.     step = 1
1278    20.     else "if (PSP(u) == Q && PSS(u) == Q)"
1279    21.    start = ASAP(u); end = start + II - 1; step = 1
1280    22.  endif
1281
1282    23.  success = false
1283    24.  for (c = start ; c != end ; c += step)
1284    25.     if check_hardware_resources_conflicts(u, PS, c) then
1285    26.       add_to_partial_schedule_at_time(u, PS, c)
1286    27.       success = true
1287    28.       break
1288    29.     endif
1289    30.  endfor
1290    31.  if (success == false) then
1291    32.    II = II + 1
1292    33.    if (II > maxII) then
1293    34.       finish - failed to schedule
1294    35.   endif
1295    36.    goto 2.
1296    37.  endif
1297    38. endfor
1298    39. if (calculate_register_pressure(PS) > maxRP) then
1299    40.    goto 32.
1300    41. endif
1301    42. compute epilogue & prologue
1302    43. finish - succeeded to schedule
1303 */
1304
1305 /* A limit on the number of cycles that resource conflicts can span.  ??? Should
1306    be provided by DFA, and be dependent on the type of insn scheduled.  Currently
1307    set to 0 to save compile time.  */
1308 #define DFA_HISTORY SMS_DFA_HISTORY
1309
1310 /* Given the partial schedule PS, this function calculates and returns the
1311    cycles in which we can schedule the node with the given index I.
1312    NOTE: Here we do the backtracking in SMS, in some special cases. We have
1313    noticed that there are several cases in which we fail    to SMS the loop
1314    because the sched window of a node is empty    due to tight data-deps. In
1315    such cases we want to unschedule    some of the predecessors/successors
1316    until we get non-empty    scheduling window.  It returns -1 if the
1317    scheduling window is empty and zero otherwise.  */
1318
1319 static int
1320 get_sched_window (partial_schedule_ptr ps, int *nodes_order, int i,
1321                   sbitmap sched_nodes, int ii, int *start_p, int *step_p, int *end_p)
1322 {
1323   int start, step, end;
1324   ddg_edge_ptr e;
1325   int u = nodes_order [i];
1326   ddg_node_ptr u_node = &ps->g->nodes[u];
1327   sbitmap psp = sbitmap_alloc (ps->g->num_nodes);
1328   sbitmap pss = sbitmap_alloc (ps->g->num_nodes);
1329   sbitmap u_node_preds = NODE_PREDECESSORS (u_node);
1330   sbitmap u_node_succs = NODE_SUCCESSORS (u_node);
1331   int psp_not_empty;
1332   int pss_not_empty;
1333
1334   /* 1. compute sched window for u (start, end, step).  */
1335   sbitmap_zero (psp);
1336   sbitmap_zero (pss);
1337   psp_not_empty = sbitmap_a_and_b_cg (psp, u_node_preds, sched_nodes);
1338   pss_not_empty = sbitmap_a_and_b_cg (pss, u_node_succs, sched_nodes);
1339
1340   if (psp_not_empty && !pss_not_empty)
1341     {
1342       int early_start = INT_MIN;
1343
1344       end = INT_MAX;
1345       for (e = u_node->in; e != 0; e = e->next_in)
1346         {
1347           ddg_node_ptr v_node = e->src;
1348           if (TEST_BIT (sched_nodes, v_node->cuid))
1349             {
1350               int node_st = SCHED_TIME (v_node)
1351                             + e->latency - (e->distance * ii);
1352
1353               early_start = MAX (early_start, node_st);
1354
1355               if (e->data_type == MEM_DEP)
1356                 end = MIN (end, SCHED_TIME (v_node) + ii - 1);
1357             }
1358         }
1359       start = early_start;
1360       end = MIN (end, early_start + ii);
1361       step = 1;
1362     }
1363
1364   else if (!psp_not_empty && pss_not_empty)
1365     {
1366       int late_start = INT_MAX;
1367
1368       end = INT_MIN;
1369       for (e = u_node->out; e != 0; e = e->next_out)
1370         {
1371           ddg_node_ptr v_node = e->dest;
1372           if (TEST_BIT (sched_nodes, v_node->cuid))
1373             {
1374               late_start = MIN (late_start,
1375                                 SCHED_TIME (v_node) - e->latency
1376                                 + (e->distance * ii));
1377               if (e->data_type == MEM_DEP)
1378                 end = MAX (end, SCHED_TIME (v_node) - ii + 1);
1379             }
1380         }
1381       start = late_start;
1382       end = MAX (end, late_start - ii);
1383       step = -1;
1384     }
1385
1386   else if (psp_not_empty && pss_not_empty)
1387     {
1388       int early_start = INT_MIN;
1389       int late_start = INT_MAX;
1390
1391       start = INT_MIN;
1392       end = INT_MAX;
1393       for (e = u_node->in; e != 0; e = e->next_in)
1394         {
1395           ddg_node_ptr v_node = e->src;
1396
1397           if (TEST_BIT (sched_nodes, v_node->cuid))
1398             {
1399               early_start = MAX (early_start,
1400                                  SCHED_TIME (v_node) + e->latency
1401                                  - (e->distance * ii));
1402               if (e->data_type == MEM_DEP)
1403                 end = MIN (end, SCHED_TIME (v_node) + ii - 1);
1404             }
1405         }
1406       for (e = u_node->out; e != 0; e = e->next_out)
1407         {
1408           ddg_node_ptr v_node = e->dest;
1409
1410           if (TEST_BIT (sched_nodes, v_node->cuid))
1411             {
1412               late_start = MIN (late_start,
1413                                 SCHED_TIME (v_node) - e->latency
1414                                 + (e->distance * ii));
1415               if (e->data_type == MEM_DEP)
1416                 start = MAX (start, SCHED_TIME (v_node) - ii + 1);
1417             }
1418         }
1419       start = MAX (start, early_start);
1420       end = MIN (end, MIN (early_start + ii, late_start + 1));
1421       step = 1;
1422     }
1423   else /* psp is empty && pss is empty.  */
1424     {
1425       start = SCHED_ASAP (u_node);
1426       end = start + ii;
1427       step = 1;
1428     }
1429
1430   *start_p = start;
1431   *step_p = step;
1432   *end_p = end;
1433   sbitmap_free (psp);
1434   sbitmap_free (pss);
1435
1436   if ((start >= end && step == 1) || (start <= end && step == -1))
1437     return -1;
1438   else
1439     return 0;
1440 }
1441
1442 /* This function implements the scheduling algorithm for SMS according to the
1443    above algorithm.  */
1444 static partial_schedule_ptr
1445 sms_schedule_by_order (ddg_ptr g, int mii, int maxii, int *nodes_order)
1446 {
1447   int ii = mii;
1448   int i, c, success;
1449   int try_again_with_larger_ii = true;
1450   int num_nodes = g->num_nodes;
1451   ddg_edge_ptr e;
1452   int start, end, step; /* Place together into one struct?  */
1453   sbitmap sched_nodes = sbitmap_alloc (num_nodes);
1454   sbitmap must_precede = sbitmap_alloc (num_nodes);
1455   sbitmap must_follow = sbitmap_alloc (num_nodes);
1456   sbitmap tobe_scheduled = sbitmap_alloc (num_nodes);
1457
1458   partial_schedule_ptr ps = create_partial_schedule (ii, g, DFA_HISTORY);
1459
1460   sbitmap_ones (tobe_scheduled);
1461   sbitmap_zero (sched_nodes);
1462
1463   while ((! sbitmap_equal (tobe_scheduled, sched_nodes)
1464          || try_again_with_larger_ii ) && ii < maxii)
1465     {
1466       int j;
1467       bool unscheduled_nodes = false;
1468
1469       if (dump_file)
1470         fprintf(dump_file, "Starting with ii=%d\n", ii);
1471       if (try_again_with_larger_ii)
1472         {
1473           try_again_with_larger_ii = false;
1474           sbitmap_zero (sched_nodes);
1475         }
1476
1477       for (i = 0; i < num_nodes; i++)
1478         {
1479           int u = nodes_order[i];
1480           ddg_node_ptr u_node = &ps->g->nodes[u];
1481           rtx insn = u_node->insn;
1482
1483           if (!INSN_P (insn))
1484             {
1485               RESET_BIT (tobe_scheduled, u);
1486               continue;
1487             }
1488
1489           if (JUMP_P (insn)) /* Closing branch handled later.  */
1490             {
1491               RESET_BIT (tobe_scheduled, u);
1492               continue;
1493             }
1494
1495           if (TEST_BIT (sched_nodes, u))
1496             continue;
1497
1498           /* Try to get non-empty scheduling window.  */
1499           j = i;
1500           while (get_sched_window (ps, nodes_order, i, sched_nodes, ii, &start, &step, &end) < 0
1501                  && j > 0)
1502             {
1503               unscheduled_nodes = true;
1504               if (TEST_BIT (NODE_PREDECESSORS (u_node), nodes_order[j - 1])
1505                   || TEST_BIT (NODE_SUCCESSORS (u_node), nodes_order[j - 1]))
1506                 {
1507                   ps_unschedule_node (ps, &ps->g->nodes[nodes_order[j - 1]]);
1508                   RESET_BIT (sched_nodes, nodes_order [j - 1]);
1509                 }
1510               j--;
1511             }
1512           if (j < 0)
1513             {
1514               /* ??? Try backtracking instead of immediately ii++?  */
1515               ii++;
1516               try_again_with_larger_ii = true;
1517               reset_partial_schedule (ps, ii);
1518               break;
1519             }
1520           /* 2. Try scheduling u in window.  */
1521           if (dump_file)
1522             fprintf(dump_file, "Trying to schedule node %d in (%d .. %d) step %d\n",
1523                     u, start, end, step);
1524
1525           /* use must_follow & must_precede bitmaps to determine order
1526              of nodes within the cycle.  */
1527           sbitmap_zero (must_precede);
1528           sbitmap_zero (must_follow);
1529           for (e = u_node->in; e != 0; e = e->next_in)
1530             if (TEST_BIT (sched_nodes, e->src->cuid)
1531                 && e->latency == (ii * e->distance)
1532                 && start == SCHED_TIME (e->src))
1533              SET_BIT (must_precede, e->src->cuid);
1534
1535           for (e = u_node->out; e != 0; e = e->next_out)
1536             if (TEST_BIT (sched_nodes, e->dest->cuid)
1537                 && e->latency == (ii * e->distance)
1538                 && end == SCHED_TIME (e->dest))
1539              SET_BIT (must_follow, e->dest->cuid);
1540
1541           success = 0;
1542           if ((step > 0 && start < end) ||  (step < 0 && start > end))
1543             for (c = start; c != end; c += step)
1544               {
1545                 ps_insn_ptr psi;
1546
1547                 psi = ps_add_node_check_conflicts (ps, u_node, c,
1548                                                    must_precede,
1549                                                    must_follow);
1550
1551                 if (psi)
1552                   {
1553                     SCHED_TIME (u_node) = c;
1554                     SET_BIT (sched_nodes, u);
1555                     success = 1;
1556                     if (dump_file)
1557                       fprintf(dump_file, "Schedule in %d\n", c);
1558                     break;
1559                   }
1560               }
1561           if (!success)
1562             {
1563               /* ??? Try backtracking instead of immediately ii++?  */
1564               ii++;
1565               try_again_with_larger_ii = true;
1566               reset_partial_schedule (ps, ii);
1567               break;
1568             }
1569           if (unscheduled_nodes)
1570             break;
1571
1572           /* ??? If (success), check register pressure estimates.  */
1573         } /* Continue with next node.  */
1574     } /* While try_again_with_larger_ii.  */
1575
1576   sbitmap_free (sched_nodes);
1577   sbitmap_free (must_precede);
1578   sbitmap_free (must_follow);
1579   sbitmap_free (tobe_scheduled);
1580
1581   if (ii >= maxii)
1582     {
1583       free_partial_schedule (ps);
1584       ps = NULL;
1585     }
1586   return ps;
1587 }
1588
1589 \f
1590 /* This page implements the algorithm for ordering the nodes of a DDG
1591    for modulo scheduling, activated through the
1592    "int sms_order_nodes (ddg_ptr, int mii, int * result)" API.  */
1593
1594 #define ORDER_PARAMS(x) ((struct node_order_params *) (x)->aux.info)
1595 #define ASAP(x) (ORDER_PARAMS ((x))->asap)
1596 #define ALAP(x) (ORDER_PARAMS ((x))->alap)
1597 #define HEIGHT(x) (ORDER_PARAMS ((x))->height)
1598 #define MOB(x) (ALAP ((x)) - ASAP ((x)))
1599 #define DEPTH(x) (ASAP ((x)))
1600
1601 typedef struct node_order_params * nopa;
1602
1603 static void order_nodes_of_sccs (ddg_all_sccs_ptr, int * result);
1604 static int order_nodes_in_scc (ddg_ptr, sbitmap, sbitmap, int*, int);
1605 static nopa  calculate_order_params (ddg_ptr, int mii);
1606 static int find_max_asap (ddg_ptr, sbitmap);
1607 static int find_max_hv_min_mob (ddg_ptr, sbitmap);
1608 static int find_max_dv_min_mob (ddg_ptr, sbitmap);
1609
1610 enum sms_direction {BOTTOMUP, TOPDOWN};
1611
1612 struct node_order_params
1613 {
1614   int asap;
1615   int alap;
1616   int height;
1617 };
1618
1619 /* Check if NODE_ORDER contains a permutation of 0 .. NUM_NODES-1.  */
1620 static void
1621 check_nodes_order (int *node_order, int num_nodes)
1622 {
1623   int i;
1624   sbitmap tmp = sbitmap_alloc (num_nodes);
1625
1626   sbitmap_zero (tmp);
1627
1628   for (i = 0; i < num_nodes; i++)
1629     {
1630       int u = node_order[i];
1631
1632       gcc_assert (u < num_nodes && u >= 0 && !TEST_BIT (tmp, u));
1633
1634       SET_BIT (tmp, u);
1635     }
1636
1637   sbitmap_free (tmp);
1638 }
1639
1640 /* Order the nodes of G for scheduling and pass the result in
1641    NODE_ORDER.  Also set aux.count of each node to ASAP.
1642    Return the recMII for the given DDG.  */
1643 static int
1644 sms_order_nodes (ddg_ptr g, int mii, int * node_order)
1645 {
1646   int i;
1647   int rec_mii = 0;
1648   ddg_all_sccs_ptr sccs = create_ddg_all_sccs (g);
1649
1650   nopa nops = calculate_order_params (g, mii);
1651
1652   order_nodes_of_sccs (sccs, node_order);
1653
1654   if (sccs->num_sccs > 0)
1655     /* First SCC has the largest recurrence_length.  */
1656     rec_mii = sccs->sccs[0]->recurrence_length;
1657
1658   /* Save ASAP before destroying node_order_params.  */
1659   for (i = 0; i < g->num_nodes; i++)
1660     {
1661       ddg_node_ptr v = &g->nodes[i];
1662       v->aux.count = ASAP (v);
1663     }
1664
1665   free (nops);
1666   free_ddg_all_sccs (sccs);
1667   check_nodes_order (node_order, g->num_nodes);
1668
1669   return rec_mii;
1670 }
1671
1672 static void
1673 order_nodes_of_sccs (ddg_all_sccs_ptr all_sccs, int * node_order)
1674 {
1675   int i, pos = 0;
1676   ddg_ptr g = all_sccs->ddg;
1677   int num_nodes = g->num_nodes;
1678   sbitmap prev_sccs = sbitmap_alloc (num_nodes);
1679   sbitmap on_path = sbitmap_alloc (num_nodes);
1680   sbitmap tmp = sbitmap_alloc (num_nodes);
1681   sbitmap ones = sbitmap_alloc (num_nodes);
1682
1683   sbitmap_zero (prev_sccs);
1684   sbitmap_ones (ones);
1685
1686   /* Perfrom the node ordering starting from the SCC with the highest recMII.
1687      For each SCC order the nodes according to their ASAP/ALAP/HEIGHT etc.  */
1688   for (i = 0; i < all_sccs->num_sccs; i++)
1689     {
1690       ddg_scc_ptr scc = all_sccs->sccs[i];
1691
1692       /* Add nodes on paths from previous SCCs to the current SCC.  */
1693       find_nodes_on_paths (on_path, g, prev_sccs, scc->nodes);
1694       sbitmap_a_or_b (tmp, scc->nodes, on_path);
1695
1696       /* Add nodes on paths from the current SCC to previous SCCs.  */
1697       find_nodes_on_paths (on_path, g, scc->nodes, prev_sccs);
1698       sbitmap_a_or_b (tmp, tmp, on_path);
1699
1700       /* Remove nodes of previous SCCs from current extended SCC.  */
1701       sbitmap_difference (tmp, tmp, prev_sccs);
1702
1703       pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
1704       /* Above call to order_nodes_in_scc updated prev_sccs |= tmp.  */
1705     }
1706
1707   /* Handle the remaining nodes that do not belong to any scc.  Each call
1708      to order_nodes_in_scc handles a single connected component.  */
1709   while (pos < g->num_nodes)
1710     {
1711       sbitmap_difference (tmp, ones, prev_sccs);
1712       pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
1713     }
1714   sbitmap_free (prev_sccs);
1715   sbitmap_free (on_path);
1716   sbitmap_free (tmp);
1717   sbitmap_free (ones);
1718 }
1719
1720 /* MII is needed if we consider backarcs (that do not close recursive cycles).  */
1721 static struct node_order_params *
1722 calculate_order_params (ddg_ptr g, int mii ATTRIBUTE_UNUSED)
1723 {
1724   int u;
1725   int max_asap;
1726   int num_nodes = g->num_nodes;
1727   ddg_edge_ptr e;
1728   /* Allocate a place to hold ordering params for each node in the DDG.  */
1729   nopa node_order_params_arr;
1730
1731   /* Initialize of ASAP/ALAP/HEIGHT to zero.  */
1732   node_order_params_arr = (nopa) xcalloc (num_nodes,
1733                                           sizeof (struct node_order_params));
1734
1735   /* Set the aux pointer of each node to point to its order_params structure.  */
1736   for (u = 0; u < num_nodes; u++)
1737     g->nodes[u].aux.info = &node_order_params_arr[u];
1738
1739   /* Disregarding a backarc from each recursive cycle to obtain a DAG,
1740      calculate ASAP, ALAP, mobility, distance, and height for each node
1741      in the dependence (direct acyclic) graph.  */
1742
1743   /* We assume that the nodes in the array are in topological order.  */
1744
1745   max_asap = 0;
1746   for (u = 0; u < num_nodes; u++)
1747     {
1748       ddg_node_ptr u_node = &g->nodes[u];
1749
1750       ASAP (u_node) = 0;
1751       for (e = u_node->in; e; e = e->next_in)
1752         if (e->distance == 0)
1753           ASAP (u_node) = MAX (ASAP (u_node),
1754                                ASAP (e->src) + e->latency);
1755       max_asap = MAX (max_asap, ASAP (u_node));
1756     }
1757
1758   for (u = num_nodes - 1; u > -1; u--)
1759     {
1760       ddg_node_ptr u_node = &g->nodes[u];
1761
1762       ALAP (u_node) = max_asap;
1763       HEIGHT (u_node) = 0;
1764       for (e = u_node->out; e; e = e->next_out)
1765         if (e->distance == 0)
1766           {
1767             ALAP (u_node) = MIN (ALAP (u_node),
1768                                  ALAP (e->dest) - e->latency);
1769             HEIGHT (u_node) = MAX (HEIGHT (u_node),
1770                                    HEIGHT (e->dest) + e->latency);
1771           }
1772     }
1773
1774   return node_order_params_arr;
1775 }
1776
1777 static int
1778 find_max_asap (ddg_ptr g, sbitmap nodes)
1779 {
1780   unsigned int u = 0;
1781   int max_asap = -1;
1782   int result = -1;
1783   sbitmap_iterator sbi;
1784
1785   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
1786     {
1787       ddg_node_ptr u_node = &g->nodes[u];
1788
1789       if (max_asap < ASAP (u_node))
1790         {
1791           max_asap = ASAP (u_node);
1792           result = u;
1793         }
1794     }
1795   return result;
1796 }
1797
1798 static int
1799 find_max_hv_min_mob (ddg_ptr g, sbitmap nodes)
1800 {
1801   unsigned int u = 0;
1802   int max_hv = -1;
1803   int min_mob = INT_MAX;
1804   int result = -1;
1805   sbitmap_iterator sbi;
1806
1807   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
1808     {
1809       ddg_node_ptr u_node = &g->nodes[u];
1810
1811       if (max_hv < HEIGHT (u_node))
1812         {
1813           max_hv = HEIGHT (u_node);
1814           min_mob = MOB (u_node);
1815           result = u;
1816         }
1817       else if ((max_hv == HEIGHT (u_node))
1818                && (min_mob > MOB (u_node)))
1819         {
1820           min_mob = MOB (u_node);
1821           result = u;
1822         }
1823     }
1824   return result;
1825 }
1826
1827 static int
1828 find_max_dv_min_mob (ddg_ptr g, sbitmap nodes)
1829 {
1830   unsigned int u = 0;
1831   int max_dv = -1;
1832   int min_mob = INT_MAX;
1833   int result = -1;
1834   sbitmap_iterator sbi;
1835
1836   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
1837     {
1838       ddg_node_ptr u_node = &g->nodes[u];
1839
1840       if (max_dv < DEPTH (u_node))
1841         {
1842           max_dv = DEPTH (u_node);
1843           min_mob = MOB (u_node);
1844           result = u;
1845         }
1846       else if ((max_dv == DEPTH (u_node))
1847                && (min_mob > MOB (u_node)))
1848         {
1849           min_mob = MOB (u_node);
1850           result = u;
1851         }
1852     }
1853   return result;
1854 }
1855
1856 /* Places the nodes of SCC into the NODE_ORDER array starting
1857    at position POS, according to the SMS ordering algorithm.
1858    NODES_ORDERED (in&out parameter) holds the bitset of all nodes in
1859    the NODE_ORDER array, starting from position zero.  */
1860 static int
1861 order_nodes_in_scc (ddg_ptr g, sbitmap nodes_ordered, sbitmap scc,
1862                     int * node_order, int pos)
1863 {
1864   enum sms_direction dir;
1865   int num_nodes = g->num_nodes;
1866   sbitmap workset = sbitmap_alloc (num_nodes);
1867   sbitmap tmp = sbitmap_alloc (num_nodes);
1868   sbitmap zero_bitmap = sbitmap_alloc (num_nodes);
1869   sbitmap predecessors = sbitmap_alloc (num_nodes);
1870   sbitmap successors = sbitmap_alloc (num_nodes);
1871
1872   sbitmap_zero (predecessors);
1873   find_predecessors (predecessors, g, nodes_ordered);
1874
1875   sbitmap_zero (successors);
1876   find_successors (successors, g, nodes_ordered);
1877
1878   sbitmap_zero (tmp);
1879   if (sbitmap_a_and_b_cg (tmp, predecessors, scc))
1880     {
1881       sbitmap_copy (workset, tmp);
1882       dir = BOTTOMUP;
1883     }
1884   else if (sbitmap_a_and_b_cg (tmp, successors, scc))
1885     {
1886       sbitmap_copy (workset, tmp);
1887       dir = TOPDOWN;
1888     }
1889   else
1890     {
1891       int u;
1892
1893       sbitmap_zero (workset);
1894       if ((u = find_max_asap (g, scc)) >= 0)
1895         SET_BIT (workset, u);
1896       dir = BOTTOMUP;
1897     }
1898
1899   sbitmap_zero (zero_bitmap);
1900   while (!sbitmap_equal (workset, zero_bitmap))
1901     {
1902       int v;
1903       ddg_node_ptr v_node;
1904       sbitmap v_node_preds;
1905       sbitmap v_node_succs;
1906
1907       if (dir == TOPDOWN)
1908         {
1909           while (!sbitmap_equal (workset, zero_bitmap))
1910             {
1911               v = find_max_hv_min_mob (g, workset);
1912               v_node = &g->nodes[v];
1913               node_order[pos++] = v;
1914               v_node_succs = NODE_SUCCESSORS (v_node);
1915               sbitmap_a_and_b (tmp, v_node_succs, scc);
1916
1917               /* Don't consider the already ordered successors again.  */
1918               sbitmap_difference (tmp, tmp, nodes_ordered);
1919               sbitmap_a_or_b (workset, workset, tmp);
1920               RESET_BIT (workset, v);
1921               SET_BIT (nodes_ordered, v);
1922             }
1923           dir = BOTTOMUP;
1924           sbitmap_zero (predecessors);
1925           find_predecessors (predecessors, g, nodes_ordered);
1926           sbitmap_a_and_b (workset, predecessors, scc);
1927         }
1928       else
1929         {
1930           while (!sbitmap_equal (workset, zero_bitmap))
1931             {
1932               v = find_max_dv_min_mob (g, workset);
1933               v_node = &g->nodes[v];
1934               node_order[pos++] = v;
1935               v_node_preds = NODE_PREDECESSORS (v_node);
1936               sbitmap_a_and_b (tmp, v_node_preds, scc);
1937
1938               /* Don't consider the already ordered predecessors again.  */
1939               sbitmap_difference (tmp, tmp, nodes_ordered);
1940               sbitmap_a_or_b (workset, workset, tmp);
1941               RESET_BIT (workset, v);
1942               SET_BIT (nodes_ordered, v);
1943             }
1944           dir = TOPDOWN;
1945           sbitmap_zero (successors);
1946           find_successors (successors, g, nodes_ordered);
1947           sbitmap_a_and_b (workset, successors, scc);
1948         }
1949     }
1950   sbitmap_free (tmp);
1951   sbitmap_free (workset);
1952   sbitmap_free (zero_bitmap);
1953   sbitmap_free (predecessors);
1954   sbitmap_free (successors);
1955   return pos;
1956 }
1957
1958 \f
1959 /* This page contains functions for manipulating partial-schedules during
1960    modulo scheduling.  */
1961
1962 /* Create a partial schedule and allocate a memory to hold II rows.  */
1963
1964 static partial_schedule_ptr
1965 create_partial_schedule (int ii, ddg_ptr g, int history)
1966 {
1967   partial_schedule_ptr ps = XNEW (struct partial_schedule);
1968   ps->rows = (ps_insn_ptr *) xcalloc (ii, sizeof (ps_insn_ptr));
1969   ps->ii = ii;
1970   ps->history = history;
1971   ps->min_cycle = INT_MAX;
1972   ps->max_cycle = INT_MIN;
1973   ps->g = g;
1974
1975   return ps;
1976 }
1977
1978 /* Free the PS_INSNs in rows array of the given partial schedule.
1979    ??? Consider caching the PS_INSN's.  */
1980 static void
1981 free_ps_insns (partial_schedule_ptr ps)
1982 {
1983   int i;
1984
1985   for (i = 0; i < ps->ii; i++)
1986     {
1987       while (ps->rows[i])
1988         {
1989           ps_insn_ptr ps_insn = ps->rows[i]->next_in_row;
1990
1991           free (ps->rows[i]);
1992           ps->rows[i] = ps_insn;
1993         }
1994       ps->rows[i] = NULL;
1995     }
1996 }
1997
1998 /* Free all the memory allocated to the partial schedule.  */
1999
2000 static void
2001 free_partial_schedule (partial_schedule_ptr ps)
2002 {
2003   if (!ps)
2004     return;
2005   free_ps_insns (ps);
2006   free (ps->rows);
2007   free (ps);
2008 }
2009
2010 /* Clear the rows array with its PS_INSNs, and create a new one with
2011    NEW_II rows.  */
2012
2013 static void
2014 reset_partial_schedule (partial_schedule_ptr ps, int new_ii)
2015 {
2016   if (!ps)
2017     return;
2018   free_ps_insns (ps);
2019   if (new_ii == ps->ii)
2020     return;
2021   ps->rows = (ps_insn_ptr *) xrealloc (ps->rows, new_ii
2022                                                  * sizeof (ps_insn_ptr));
2023   memset (ps->rows, 0, new_ii * sizeof (ps_insn_ptr));
2024   ps->ii = new_ii;
2025   ps->min_cycle = INT_MAX;
2026   ps->max_cycle = INT_MIN;
2027 }
2028
2029 /* Prints the partial schedule as an ii rows array, for each rows
2030    print the ids of the insns in it.  */
2031 void
2032 print_partial_schedule (partial_schedule_ptr ps, FILE *dump)
2033 {
2034   int i;
2035
2036   for (i = 0; i < ps->ii; i++)
2037     {
2038       ps_insn_ptr ps_i = ps->rows[i];
2039
2040       fprintf (dump, "\n[CYCLE %d ]: ", i);
2041       while (ps_i)
2042         {
2043           fprintf (dump, "%d, ",
2044                    INSN_UID (ps_i->node->insn));
2045           ps_i = ps_i->next_in_row;
2046         }
2047     }
2048 }
2049
2050 /* Creates an object of PS_INSN and initializes it to the given parameters.  */
2051 static ps_insn_ptr
2052 create_ps_insn (ddg_node_ptr node, int rest_count, int cycle)
2053 {
2054   ps_insn_ptr ps_i = XNEW (struct ps_insn);
2055
2056   ps_i->node = node;
2057   ps_i->next_in_row = NULL;
2058   ps_i->prev_in_row = NULL;
2059   ps_i->row_rest_count = rest_count;
2060   ps_i->cycle = cycle;
2061
2062   return ps_i;
2063 }
2064
2065
2066 /* Removes the given PS_INSN from the partial schedule.  Returns false if the
2067    node is not found in the partial schedule, else returns true.  */
2068 static bool
2069 remove_node_from_ps (partial_schedule_ptr ps, ps_insn_ptr ps_i)
2070 {
2071   int row;
2072
2073   if (!ps || !ps_i)
2074     return false;
2075
2076   row = SMODULO (ps_i->cycle, ps->ii);
2077   if (! ps_i->prev_in_row)
2078     {
2079       if (ps_i != ps->rows[row])
2080         return false;
2081
2082       ps->rows[row] = ps_i->next_in_row;
2083       if (ps->rows[row])
2084         ps->rows[row]->prev_in_row = NULL;
2085     }
2086   else
2087     {
2088       ps_i->prev_in_row->next_in_row = ps_i->next_in_row;
2089       if (ps_i->next_in_row)
2090         ps_i->next_in_row->prev_in_row = ps_i->prev_in_row;
2091     }
2092   free (ps_i);
2093   return true;
2094 }
2095
2096 /* Unlike what literature describes for modulo scheduling (which focuses
2097    on VLIW machines) the order of the instructions inside a cycle is
2098    important.  Given the bitmaps MUST_FOLLOW and MUST_PRECEDE we know
2099    where the current instruction should go relative to the already
2100    scheduled instructions in the given cycle.  Go over these
2101    instructions and find the first possible column to put it in.  */
2102 static bool
2103 ps_insn_find_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2104                      sbitmap must_precede, sbitmap must_follow)
2105 {
2106   ps_insn_ptr next_ps_i;
2107   ps_insn_ptr first_must_follow = NULL;
2108   ps_insn_ptr last_must_precede = NULL;
2109   int row;
2110
2111   if (! ps_i)
2112     return false;
2113
2114   row = SMODULO (ps_i->cycle, ps->ii);
2115
2116   /* Find the first must follow and the last must precede
2117      and insert the node immediately after the must precede
2118      but make sure that it there is no must follow after it.  */
2119   for (next_ps_i = ps->rows[row];
2120        next_ps_i;
2121        next_ps_i = next_ps_i->next_in_row)
2122     {
2123       if (TEST_BIT (must_follow, next_ps_i->node->cuid)
2124           && ! first_must_follow)
2125         first_must_follow = next_ps_i;
2126       if (TEST_BIT (must_precede, next_ps_i->node->cuid))
2127         {
2128           /* If we have already met a node that must follow, then
2129              there is no possible column.  */
2130           if (first_must_follow)
2131             return false;
2132           else
2133             last_must_precede = next_ps_i;
2134         }
2135     }
2136
2137   /* Now insert the node after INSERT_AFTER_PSI.  */
2138
2139   if (! last_must_precede)
2140     {
2141       ps_i->next_in_row = ps->rows[row];
2142       ps_i->prev_in_row = NULL;
2143       if (ps_i->next_in_row)
2144         ps_i->next_in_row->prev_in_row = ps_i;
2145       ps->rows[row] = ps_i;
2146     }
2147   else
2148     {
2149       ps_i->next_in_row = last_must_precede->next_in_row;
2150       last_must_precede->next_in_row = ps_i;
2151       ps_i->prev_in_row = last_must_precede;
2152       if (ps_i->next_in_row)
2153         ps_i->next_in_row->prev_in_row = ps_i;
2154     }
2155
2156   return true;
2157 }
2158
2159 /* Advances the PS_INSN one column in its current row; returns false
2160    in failure and true in success.  Bit N is set in MUST_FOLLOW if 
2161    the node with cuid N must be come after the node pointed to by 
2162    PS_I when scheduled in the same cycle.  */
2163 static int
2164 ps_insn_advance_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2165                         sbitmap must_follow)
2166 {
2167   ps_insn_ptr prev, next;
2168   int row;
2169   ddg_node_ptr next_node;
2170
2171   if (!ps || !ps_i)
2172     return false;
2173
2174   row = SMODULO (ps_i->cycle, ps->ii);
2175
2176   if (! ps_i->next_in_row)
2177     return false;
2178
2179   next_node = ps_i->next_in_row->node;
2180
2181   /* Check if next_in_row is dependent on ps_i, both having same sched
2182      times (typically ANTI_DEP).  If so, ps_i cannot skip over it.  */
2183   if (TEST_BIT (must_follow, next_node->cuid))
2184     return false;
2185
2186   /* Advance PS_I over its next_in_row in the doubly linked list.  */
2187   prev = ps_i->prev_in_row;
2188   next = ps_i->next_in_row;
2189
2190   if (ps_i == ps->rows[row])
2191     ps->rows[row] = next;
2192
2193   ps_i->next_in_row = next->next_in_row;
2194
2195   if (next->next_in_row)
2196     next->next_in_row->prev_in_row = ps_i;
2197
2198   next->next_in_row = ps_i;
2199   ps_i->prev_in_row = next;
2200
2201   next->prev_in_row = prev;
2202   if (prev)
2203     prev->next_in_row = next;
2204
2205   return true;
2206 }
2207
2208 /* Inserts a DDG_NODE to the given partial schedule at the given cycle.
2209    Returns 0 if this is not possible and a PS_INSN otherwise.  Bit N is 
2210    set in MUST_PRECEDE/MUST_FOLLOW if the node with cuid N must be come 
2211    before/after (respectively) the node pointed to by PS_I when scheduled 
2212    in the same cycle.  */
2213 static ps_insn_ptr
2214 add_node_to_ps (partial_schedule_ptr ps, ddg_node_ptr node, int cycle,
2215                 sbitmap must_precede, sbitmap must_follow)
2216 {
2217   ps_insn_ptr ps_i;
2218   int rest_count = 1;
2219   int row = SMODULO (cycle, ps->ii);
2220
2221   if (ps->rows[row]
2222       && ps->rows[row]->row_rest_count >= issue_rate)
2223     return NULL;
2224
2225   if (ps->rows[row])
2226     rest_count += ps->rows[row]->row_rest_count;
2227
2228   ps_i = create_ps_insn (node, rest_count, cycle);
2229
2230   /* Finds and inserts PS_I according to MUST_FOLLOW and
2231      MUST_PRECEDE.  */
2232   if (! ps_insn_find_column (ps, ps_i, must_precede, must_follow))
2233     {
2234       free (ps_i);
2235       return NULL;
2236     }
2237
2238   return ps_i;
2239 }
2240
2241 /* Advance time one cycle.  Assumes DFA is being used.  */
2242 static void
2243 advance_one_cycle (void)
2244 {
2245   if (targetm.sched.dfa_pre_cycle_insn)
2246     state_transition (curr_state,
2247                       targetm.sched.dfa_pre_cycle_insn ());
2248
2249   state_transition (curr_state, NULL);
2250
2251   if (targetm.sched.dfa_post_cycle_insn)
2252     state_transition (curr_state,
2253                       targetm.sched.dfa_post_cycle_insn ());
2254 }
2255
2256 /* Given the kernel of a loop (from FIRST_INSN to LAST_INSN), finds
2257    the number of cycles according to DFA that the kernel fits in,
2258    we use this to check if we done well with SMS after we add
2259    register moves.  In some cases register moves overhead makes
2260    it even worse than the original loop.  We want SMS to be performed
2261    when it gives less cycles after register moves are added.  */
2262 static int
2263 kernel_number_of_cycles (rtx first_insn, rtx last_insn)
2264 {
2265   int cycles = 0;
2266   rtx insn;
2267   int can_issue_more = issue_rate;
2268
2269   state_reset (curr_state);
2270
2271   for (insn = first_insn;
2272        insn != NULL_RTX && insn != last_insn;
2273        insn = NEXT_INSN (insn))
2274     {
2275       if (! INSN_P (insn) || GET_CODE (PATTERN (insn)) == USE)
2276         continue;
2277
2278       /* Check if there is room for the current insn.  */
2279       if (!can_issue_more || state_dead_lock_p (curr_state))
2280         {
2281           cycles ++;
2282           advance_one_cycle ();
2283           can_issue_more = issue_rate;
2284         }
2285
2286         /* Update the DFA state and return with failure if the DFA found
2287            recource conflicts.  */
2288       if (state_transition (curr_state, insn) >= 0)
2289         {
2290           cycles ++;
2291           advance_one_cycle ();
2292           can_issue_more = issue_rate;
2293         }
2294
2295       if (targetm.sched.variable_issue)
2296         can_issue_more =
2297           targetm.sched.variable_issue (sched_dump, sched_verbose,
2298                                         insn, can_issue_more);
2299       /* A naked CLOBBER or USE generates no instruction, so don't
2300          let them consume issue slots.  */
2301       else if (GET_CODE (PATTERN (insn)) != USE
2302                && GET_CODE (PATTERN (insn)) != CLOBBER)
2303         can_issue_more--;
2304     }
2305   return cycles;
2306 }
2307
2308 /* Checks if PS has resource conflicts according to DFA, starting from
2309    FROM cycle to TO cycle; returns true if there are conflicts and false
2310    if there are no conflicts.  Assumes DFA is being used.  */
2311 static int
2312 ps_has_conflicts (partial_schedule_ptr ps, int from, int to)
2313 {
2314   int cycle;
2315
2316   state_reset (curr_state);
2317
2318   for (cycle = from; cycle <= to; cycle++)
2319     {
2320       ps_insn_ptr crr_insn;
2321       /* Holds the remaining issue slots in the current row.  */
2322       int can_issue_more = issue_rate;
2323
2324       /* Walk through the DFA for the current row.  */
2325       for (crr_insn = ps->rows[SMODULO (cycle, ps->ii)];
2326            crr_insn;
2327            crr_insn = crr_insn->next_in_row)
2328         {
2329           rtx insn = crr_insn->node->insn;
2330
2331           if (!INSN_P (insn))
2332             continue;
2333
2334           /* Check if there is room for the current insn.  */
2335           if (!can_issue_more || state_dead_lock_p (curr_state))
2336             return true;
2337
2338           /* Update the DFA state and return with failure if the DFA found
2339              recource conflicts.  */
2340           if (state_transition (curr_state, insn) >= 0)
2341             return true;
2342
2343           if (targetm.sched.variable_issue)
2344             can_issue_more =
2345               targetm.sched.variable_issue (sched_dump, sched_verbose,
2346                                             insn, can_issue_more);
2347           /* A naked CLOBBER or USE generates no instruction, so don't
2348              let them consume issue slots.  */
2349           else if (GET_CODE (PATTERN (insn)) != USE
2350                    && GET_CODE (PATTERN (insn)) != CLOBBER)
2351             can_issue_more--;
2352         }
2353
2354       /* Advance the DFA to the next cycle.  */
2355       advance_one_cycle ();
2356     }
2357   return false;
2358 }
2359
2360 /* Checks if the given node causes resource conflicts when added to PS at
2361    cycle C.  If not the node is added to PS and returned; otherwise zero
2362    is returned.  Bit N is set in MUST_PRECEDE/MUST_FOLLOW if the node with 
2363    cuid N must be come before/after (respectively) the node pointed to by 
2364    PS_I when scheduled in the same cycle.  */
2365 ps_insn_ptr
2366 ps_add_node_check_conflicts (partial_schedule_ptr ps, ddg_node_ptr n,
2367                              int c, sbitmap must_precede,
2368                              sbitmap must_follow)
2369 {
2370   int has_conflicts = 0;
2371   ps_insn_ptr ps_i;
2372
2373   /* First add the node to the PS, if this succeeds check for
2374      conflicts, trying different issue slots in the same row.  */
2375   if (! (ps_i = add_node_to_ps (ps, n, c, must_precede, must_follow)))
2376     return NULL; /* Failed to insert the node at the given cycle.  */
2377
2378   has_conflicts = ps_has_conflicts (ps, c, c)
2379                   || (ps->history > 0
2380                       && ps_has_conflicts (ps,
2381                                            c - ps->history,
2382                                            c + ps->history));
2383
2384   /* Try different issue slots to find one that the given node can be
2385      scheduled in without conflicts.  */
2386   while (has_conflicts)
2387     {
2388       if (! ps_insn_advance_column (ps, ps_i, must_follow))
2389         break;
2390       has_conflicts = ps_has_conflicts (ps, c, c)
2391                       || (ps->history > 0
2392                           && ps_has_conflicts (ps,
2393                                                c - ps->history,
2394                                                c + ps->history));
2395     }
2396
2397   if (has_conflicts)
2398     {
2399       remove_node_from_ps (ps, ps_i);
2400       return NULL;
2401     }
2402
2403   ps->min_cycle = MIN (ps->min_cycle, c);
2404   ps->max_cycle = MAX (ps->max_cycle, c);
2405   return ps_i;
2406 }
2407
2408 /* Rotate the rows of PS such that insns scheduled at time
2409    START_CYCLE will appear in row 0.  Updates max/min_cycles.  */
2410 void
2411 rotate_partial_schedule (partial_schedule_ptr ps, int start_cycle)
2412 {
2413   int i, row, backward_rotates;
2414   int last_row = ps->ii - 1;
2415
2416   if (start_cycle == 0)
2417     return;
2418
2419   backward_rotates = SMODULO (start_cycle, ps->ii);
2420
2421   /* Revisit later and optimize this into a single loop.  */
2422   for (i = 0; i < backward_rotates; i++)
2423     {
2424       ps_insn_ptr first_row = ps->rows[0];
2425
2426       for (row = 0; row < last_row; row++)
2427         ps->rows[row] = ps->rows[row+1];
2428
2429       ps->rows[last_row] = first_row;
2430     }
2431
2432   ps->max_cycle -= start_cycle;
2433   ps->min_cycle -= start_cycle;
2434 }
2435
2436 /* Remove the node N from the partial schedule PS; because we restart the DFA
2437    each time we want to check for resource conflicts; this is equivalent to
2438    unscheduling the node N.  */
2439 static bool
2440 ps_unschedule_node (partial_schedule_ptr ps, ddg_node_ptr n)
2441 {
2442   ps_insn_ptr ps_i;
2443   int row = SMODULO (SCHED_TIME (n), ps->ii);
2444
2445   if (row < 0 || row > ps->ii)
2446     return false;
2447
2448   for (ps_i = ps->rows[row];
2449        ps_i &&  ps_i->node != n;
2450        ps_i = ps_i->next_in_row);
2451   if (!ps_i)
2452     return false;
2453
2454   return remove_node_from_ps (ps, ps_i);
2455 }
2456 #endif /* INSN_SCHEDULING */
2457 \f
2458 static bool
2459 gate_handle_sms (void)
2460 {
2461   return (optimize > 0 && flag_modulo_sched);
2462 }
2463
2464
2465 /* Run instruction scheduler.  */
2466 /* Perform SMS module scheduling.  */
2467 static unsigned int
2468 rest_of_handle_sms (void)
2469 {
2470 #ifdef INSN_SCHEDULING
2471   basic_block bb;
2472
2473   /* We want to be able to create new pseudos.  */
2474   no_new_pseudos = 0;
2475   /* Collect loop information to be used in SMS.  */
2476   cfg_layout_initialize (CLEANUP_UPDATE_LIFE);
2477   sms_schedule ();
2478
2479   /* Update the life information, because we add pseudos.  */
2480   max_regno = max_reg_num ();
2481   allocate_reg_info (max_regno, FALSE, FALSE);
2482   update_life_info (NULL, UPDATE_LIFE_GLOBAL_RM_NOTES,
2483                     (PROP_DEATH_NOTES
2484                      | PROP_REG_INFO
2485                      | PROP_KILL_DEAD_CODE
2486                      | PROP_SCAN_DEAD_CODE));
2487
2488   no_new_pseudos = 1;
2489
2490   /* Finalize layout changes.  */
2491   FOR_EACH_BB (bb)
2492     if (bb->next_bb != EXIT_BLOCK_PTR)
2493       bb->aux = bb->next_bb;
2494   cfg_layout_finalize ();
2495   free_dominance_info (CDI_DOMINATORS);
2496 #endif /* INSN_SCHEDULING */
2497   return 0;
2498 }
2499
2500 struct tree_opt_pass pass_sms =
2501 {
2502   "sms",                                /* name */
2503   gate_handle_sms,                      /* gate */
2504   rest_of_handle_sms,                   /* execute */
2505   NULL,                                 /* sub */
2506   NULL,                                 /* next */
2507   0,                                    /* static_pass_number */
2508   TV_SMS,                               /* tv_id */
2509   0,                                    /* properties_required */
2510   0,                                    /* properties_provided */
2511   0,                                    /* properties_destroyed */
2512   TODO_dump_func,                       /* todo_flags_start */
2513   TODO_dump_func |
2514   TODO_ggc_collect,                     /* todo_flags_finish */
2515   'm'                                   /* letter */
2516 };
2517