OSDN Git Service

SMS: Support instructions with REG_INC_NOTE
[pf3gnuchains/gcc-fork.git] / gcc / modulo-sched.c
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>
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 3, 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 COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22
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"
51
52 #ifdef INSN_SCHEDULING
53
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).
62
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).
86
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.  */
101 \f
102 /* This page defines partial-schedule structures and functions for
103    modulo scheduling.  */
104
105 typedef struct partial_schedule *partial_schedule_ptr;
106 typedef struct ps_insn *ps_insn_ptr;
107
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)
110
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)
113
114 /* Perform signed modulo, always returning a non-negative value.  */
115 #define SMODULO(x,y) ((x) % (y) < 0 ? ((x) % (y) + (y)) : (x) % (y))
116
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)
123
124 /* A single instruction in the partial schedule.  */
125 struct ps_insn
126 {
127   /* The corresponding DDG_NODE.  */
128   ddg_node_ptr node;
129
130   /* The (absolute) cycle in which the PS instruction is scheduled.
131      Same as SCHED_TIME (node).  */
132   int cycle;
133
134   /* The next/prev PS_INSN in the same row.  */
135   ps_insn_ptr next_in_row,
136               prev_in_row;
137
138 };
139
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
144 {
145   int ii;       /* Number of rows in the partial schedule.  */
146   int history;  /* Threshold for conflict checking using DFA.  */
147
148   /* rows[i] points to linked list of insns scheduled in row i (0<=i<ii).  */
149   ps_insn_ptr *rows;
150
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;
156   
157   /* The earliest absolute cycle of an insn in the partial schedule.  */
158   int min_cycle;
159
160   /* The latest absolute cycle of an insn in the partial schedule.  */
161   int max_cycle;
162
163   ddg_ptr g;    /* The DDG of the insns in the partial schedule.  */
164
165   int stage_count;  /* The stage count of the partial schedule.  */
166 };
167
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
171 {
172   rtx insn;
173   rtx orig_reg;
174   rtx new_reg;
175   struct undo_replace_buff_elem *next;
176 };
177
178
179
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);
193
194 \f
195 /* This page defines constants and structures for the modulo scheduling
196    driver.  */
197
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);
215
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)
225
226 /* The scheduling parameters held for each node.  */
227 typedef struct node_sched_params
228 {
229   int asap;     /* A lower-bound on the absolute scheduling cycle.  */
230   int time;     /* The absolute scheduling cycle (time >= asap).  */
231
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;
237
238   /* The number of register-move instructions added, immediately preceding
239      first_reg_move.  */
240   int nreg_moves;
241
242   int row;    /* Holds time % ii.  */
243   int stage;  /* Holds time / ii.  */
244
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;
249
250 \f
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)
256 {
257   static char tmp[80];
258
259   sprintf (tmp, "i%4d", INSN_UID (insn));
260   return tmp;
261 }
262
263 static void
264 compute_jump_reg_dependencies (rtx insn ATTRIBUTE_UNUSED,
265                                regset used ATTRIBUTE_UNUSED)
266 {
267 }
268
269 static struct common_sched_info_def sms_common_sched_info;
270
271 static struct sched_deps_info_def sms_sched_deps_info =
272   {
273     compute_jump_reg_dependencies,
274     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
275     NULL,
276     0, 0, 0
277   };
278
279 static struct haifa_sched_info sms_sched_info =
280 {
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,
292
293   NULL, NULL, NULL, NULL,
294   NULL, NULL,
295   0
296 };
297
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)
304 {
305 #ifdef HAVE_doloop_end
306   rtx reg, condition, insn, first_insn_not_to_check;
307
308   if (!JUMP_P (tail))
309     return NULL_RTX;
310
311   /* TODO: Free SMS's dependence on doloop_condition_get.  */
312   condition = doloop_condition_get (tail);
313   if (! condition)
314     return NULL_RTX;
315
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 ();
323
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));
330
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))
333       {
334         if (dump_file)
335         {
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);
340         }
341
342         return NULL_RTX;
343       }
344
345   return reg;
346 #else
347   return NULL_RTX;
348 #endif
349 }
350
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)
358 {
359   rtx insn;
360   rtx head, tail;
361
362   if (! pre_header)
363     return NULL_RTX;
364
365   get_ebb_head_tail (pre_header, pre_header, &head, &tail);
366
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))))
370       {
371         rtx pat = single_set (insn);
372
373         if (CONST_INT_P (SET_SRC (pat)))
374           {
375             *count = INTVAL (SET_SRC (pat));
376             return insn;
377           }
378
379         return NULL_RTX;
380       }
381
382   return NULL_RTX;
383 }
384
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)
390 {
391   if (targetm.sched.sms_res_mii)
392     return targetm.sched.sms_res_mii (g);
393
394   return ((g->num_nodes - g->num_debug) / issue_rate);
395 }
396
397
398 /* Points to the array that contains the sched data for each node.  */
399 static node_sched_params_ptr node_sched_params;
400
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)
406 {
407   int i;
408
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));
414
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++)
418     {
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];
422     }
423 }
424
425 static void
426 print_node_sched_params (FILE *file, int num_nodes, ddg_ptr g)
427 {
428   int i;
429
430   if (! file)
431     return;
432   for (i = 0; i < num_nodes; i++)
433     {
434       node_sched_params_ptr nsp = &node_sched_params[i];
435       rtx reg_move = nsp->first_reg_move;
436       int j;
437
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++)
444         {
445           fprintf (file, " reg_move = ");
446           print_rtl_single (file, reg_move);
447           reg_move = PREV_INSN (reg_move);
448         }
449     }
450 }
451
452 /*
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.
462 */
463 static struct undo_replace_buff_elem *
464 generate_reg_moves (partial_schedule_ptr ps, bool rescan)
465 {
466   ddg_ptr g = ps->g;
467   int ii = ps->ii;
468   int i;
469   struct undo_replace_buff_elem *reg_move_replaces = NULL;
470
471   for (i = 0; i < g->num_nodes; i++)
472     {
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;
479       rtx set = single_set (u->insn);
480       
481       /* Skip instructions that do not set a register.  */
482       if ((set && !REG_P (SET_DEST (set))))
483         continue;
484  
485       /* Compute the number of reg_moves needed for u, by looking at life
486          ranges started at u (excluding self-loops).  */
487       for (e = u->out; e; e = e->next_out)
488         if (e->type == TRUE_DEP && e->dest != e->src)
489           {
490             int nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
491
492             if (e->distance == 1)
493               nreg_moves4e = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
494
495             /* If dest precedes src in the schedule of the kernel, then dest
496                will read before src writes and we can save one reg_copy.  */
497             if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
498                 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
499               nreg_moves4e--;
500
501             if (nreg_moves4e >= 1)
502               {
503                 /* !single_set instructions are not supported yet and
504                    thus we do not except to encounter them in the loop
505                    except from the doloop part.  For the latter case
506                    we assume no regmoves are generated as the doloop
507                    instructions are tied to the branch with an edge.  */
508                 gcc_assert (set);
509                 /* If the instruction contains auto-inc register then
510                    validate that the regmov is being generated for the
511                    target regsiter rather then the inc'ed register.     */
512                 gcc_assert (!autoinc_var_is_used_p (u->insn, e->dest->insn));
513               }
514             
515             nreg_moves = MAX (nreg_moves, nreg_moves4e);
516           }
517
518       if (nreg_moves == 0)
519         continue;
520
521       /* Every use of the register defined by node may require a different
522          copy of this register, depending on the time the use is scheduled.
523          Set a bitmap vector, telling which nodes use each copy of this
524          register.  */
525       uses_of_defs = sbitmap_vector_alloc (nreg_moves, g->num_nodes);
526       sbitmap_vector_zero (uses_of_defs, nreg_moves);
527       for (e = u->out; e; e = e->next_out)
528         if (e->type == TRUE_DEP && e->dest != e->src)
529           {
530             int dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src)) / ii;
531
532             if (e->distance == 1)
533               dest_copy = (SCHED_TIME (e->dest) - SCHED_TIME (e->src) + ii) / ii;
534
535             if (SCHED_ROW (e->dest) == SCHED_ROW (e->src)
536                 && SCHED_COLUMN (e->dest) < SCHED_COLUMN (e->src))
537               dest_copy--;
538
539             if (dest_copy)
540               SET_BIT (uses_of_defs[dest_copy - 1], e->dest->cuid);
541           }
542
543       /* Now generate the reg_moves, attaching relevant uses to them.  */
544       SCHED_NREG_MOVES (u) = nreg_moves;
545       old_reg = prev_reg = copy_rtx (SET_DEST (single_set (u->insn)));
546       /* Insert the reg-moves right before the notes which precede
547          the insn they relates to.  */
548       last_reg_move = u->first_note;
549
550       for (i_reg_move = 0; i_reg_move < nreg_moves; i_reg_move++)
551         {
552           unsigned int i_use = 0;
553           rtx new_reg = gen_reg_rtx (GET_MODE (prev_reg));
554           rtx reg_move = gen_move_insn (new_reg, prev_reg);
555           sbitmap_iterator sbi;
556
557           add_insn_before (reg_move, last_reg_move, NULL);
558           last_reg_move = reg_move;
559
560           if (!SCHED_FIRST_REG_MOVE (u))
561             SCHED_FIRST_REG_MOVE (u) = reg_move;
562
563           EXECUTE_IF_SET_IN_SBITMAP (uses_of_defs[i_reg_move], 0, i_use, sbi)
564             {
565               struct undo_replace_buff_elem *rep;
566
567               rep = (struct undo_replace_buff_elem *)
568                     xcalloc (1, sizeof (struct undo_replace_buff_elem));
569               rep->insn = g->nodes[i_use].insn;
570               rep->orig_reg = old_reg;
571               rep->new_reg = new_reg;
572
573               if (! reg_move_replaces)
574                 reg_move_replaces = rep;
575               else
576                 {
577                   rep->next = reg_move_replaces;
578                   reg_move_replaces = rep;
579                 }
580
581               replace_rtx (g->nodes[i_use].insn, old_reg, new_reg);
582               if (rescan)
583                 df_insn_rescan (g->nodes[i_use].insn);
584             }
585
586           prev_reg = new_reg;
587         }
588       sbitmap_vector_free (uses_of_defs);
589     }
590   return reg_move_replaces;
591 }
592
593 /* Free memory allocated for the undo buffer.  */
594 static void
595 free_undo_replace_buff (struct undo_replace_buff_elem *reg_move_replaces)
596 {
597
598   while (reg_move_replaces)
599     {
600       struct undo_replace_buff_elem *rep = reg_move_replaces;
601
602       reg_move_replaces = reg_move_replaces->next;
603       free (rep);
604     }
605 }
606
607 /* Update the sched_params (time, row and stage) for node U using the II,
608    the CYCLE of U and MIN_CYCLE.  
609    We're not simply taking the following
610    SCHED_STAGE (u) = CALC_STAGE_COUNT (SCHED_TIME (u), min_cycle, ii);
611    because the stages may not be aligned on cycle 0.  */
612 static void
613 update_node_sched_params (ddg_node_ptr u, int ii, int cycle, int min_cycle)
614 {
615   int sc_until_cycle_zero;
616   int stage;
617
618   SCHED_TIME (u) = cycle;
619   SCHED_ROW (u) = SMODULO (cycle, ii);
620
621   /* The calculation of stage count is done adding the number
622      of stages before cycle zero and after cycle zero.  */
623   sc_until_cycle_zero = CALC_STAGE_COUNT (-1, min_cycle, ii);
624
625   if (SCHED_TIME (u) < 0)
626     {
627       stage = CALC_STAGE_COUNT (-1, SCHED_TIME (u), ii);
628       SCHED_STAGE (u) = sc_until_cycle_zero - stage;
629     }
630   else
631     {
632       stage = CALC_STAGE_COUNT (SCHED_TIME (u), 0, ii);
633       SCHED_STAGE (u) = sc_until_cycle_zero + stage - 1;
634     }
635 }
636
637 /* Bump the SCHED_TIMEs of all nodes by AMOUNT.  Set the values of
638    SCHED_ROW and SCHED_STAGE.  Instruction scheduled on cycle AMOUNT
639    will move to cycle zero.  */
640 static void
641 reset_sched_times (partial_schedule_ptr ps, int amount)
642 {
643   int row;
644   int ii = ps->ii;
645   ps_insn_ptr crr_insn;
646
647   for (row = 0; row < ii; row++)
648     for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
649       {
650         ddg_node_ptr u = crr_insn->node;
651         int normalized_time = SCHED_TIME (u) - amount;
652         int new_min_cycle = PS_MIN_CYCLE (ps) - amount;
653
654         if (dump_file)
655           {
656             /* Print the scheduling times after the rotation.  */
657             fprintf (dump_file, "crr_insn->node=%d (insn id %d), "
658                      "crr_insn->cycle=%d, min_cycle=%d", crr_insn->node->cuid,
659                      INSN_UID (crr_insn->node->insn), normalized_time,
660                      new_min_cycle);
661             if (JUMP_P (crr_insn->node->insn))
662               fprintf (dump_file, " (branch)");
663             fprintf (dump_file, "\n");
664           }
665         
666         gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
667         gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
668
669         crr_insn->cycle = normalized_time;
670         update_node_sched_params (u, ii, normalized_time, new_min_cycle);
671       }
672 }
673  
674 /* Set SCHED_COLUMN of each node according to its position in PS.  */
675 static void
676 set_columns_for_ps (partial_schedule_ptr ps)
677 {
678   int row;
679
680   for (row = 0; row < ps->ii; row++)
681     {
682       ps_insn_ptr cur_insn = ps->rows[row];
683       int column = 0;
684
685       for (; cur_insn; cur_insn = cur_insn->next_in_row)
686         SCHED_COLUMN (cur_insn->node) = column++;
687     }
688 }
689
690 /* Permute the insns according to their order in PS, from row 0 to
691    row ii-1, and position them right before LAST.  This schedules
692    the insns of the loop kernel.  */
693 static void
694 permute_partial_schedule (partial_schedule_ptr ps, rtx last)
695 {
696   int ii = ps->ii;
697   int row;
698   ps_insn_ptr ps_ij;
699
700   for (row = 0; row < ii ; row++)
701     for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
702       if (PREV_INSN (last) != ps_ij->node->insn)
703         reorder_insns_nobb (ps_ij->node->first_note, ps_ij->node->insn,
704                             PREV_INSN (last));
705 }
706
707 /* Set bitmaps TMP_FOLLOW and TMP_PRECEDE to MUST_FOLLOW and MUST_PRECEDE
708    respectively only if cycle C falls on the border of the scheduling
709    window boundaries marked by START and END cycles.  STEP is the
710    direction of the window.  */
711 static inline void
712 set_must_precede_follow (sbitmap *tmp_follow, sbitmap must_follow,
713                          sbitmap *tmp_precede, sbitmap must_precede, int c,
714                          int start, int end, int step)
715 {
716   *tmp_precede = NULL;
717   *tmp_follow = NULL;
718
719   if (c == start)
720     {
721       if (step == 1)
722         *tmp_precede = must_precede;
723       else                      /* step == -1.  */
724         *tmp_follow = must_follow;
725     }
726   if (c == end - step)
727     {
728       if (step == 1)
729         *tmp_follow = must_follow;
730       else                      /* step == -1.  */
731         *tmp_precede = must_precede;
732     }
733
734 }
735
736 /* Return True if the branch can be moved to row ii-1 while
737    normalizing the partial schedule PS to start from cycle zero and thus
738    optimize the SC.  Otherwise return False.  */
739 static bool
740 optimize_sc (partial_schedule_ptr ps, ddg_ptr g)
741 {
742   int amount = PS_MIN_CYCLE (ps);
743   sbitmap sched_nodes = sbitmap_alloc (g->num_nodes);
744   int start, end, step;
745   int ii = ps->ii;
746   bool ok = false;
747   int stage_count, stage_count_curr;
748
749   /* Compare the SC after normalization and SC after bringing the branch
750      to row ii-1.  If they are equal just bail out.  */
751   stage_count = calculate_stage_count (ps, amount);
752   stage_count_curr =
753     calculate_stage_count (ps, SCHED_TIME (g->closing_branch) - (ii - 1));
754
755   if (stage_count == stage_count_curr)
756     {
757       if (dump_file)
758         fprintf (dump_file, "SMS SC already optimized.\n");
759
760       ok = false;
761       goto clear;
762     }
763
764   if (dump_file)
765     {
766       fprintf (dump_file, "SMS Trying to optimize branch location\n");
767       fprintf (dump_file, "SMS partial schedule before trial:\n");
768       print_partial_schedule (ps, dump_file);
769     }
770
771   /* First, normalize the partial scheduling.  */
772   reset_sched_times (ps, amount);
773   rotate_partial_schedule (ps, amount);
774   if (dump_file)
775     {
776       fprintf (dump_file,
777                "SMS partial schedule after normalization (ii, %d, SC %d):\n",
778                ii, stage_count);
779       print_partial_schedule (ps, dump_file);
780     }
781
782   if (SMODULO (SCHED_TIME (g->closing_branch), ii) == ii - 1)
783     {
784       ok = true;
785       goto clear;
786     }
787
788   sbitmap_ones (sched_nodes);
789
790   /* Calculate the new placement of the branch.  It should be in row
791      ii-1 and fall into it's scheduling window.  */
792   if (get_sched_window (ps, g->closing_branch, sched_nodes, ii, &start,
793                         &step, &end) == 0)
794     {
795       bool success;
796       ps_insn_ptr next_ps_i;
797       int branch_cycle = SCHED_TIME (g->closing_branch);
798       int row = SMODULO (branch_cycle, ps->ii);
799       int num_splits = 0;
800       sbitmap must_precede, must_follow, tmp_precede, tmp_follow;
801       int c;
802
803       if (dump_file)
804         fprintf (dump_file, "\nTrying to schedule node %d "
805                  "INSN = %d  in (%d .. %d) step %d\n",
806                  g->closing_branch->cuid,
807                  (INSN_UID (g->closing_branch->insn)), start, end, step);
808
809       gcc_assert ((step > 0 && start < end) || (step < 0 && start > end));
810       if (step == 1)
811         {
812           c = start + ii - SMODULO (start, ii) - 1;
813           gcc_assert (c >= start);
814           if (c >= end)
815             {
816               ok = false;
817               if (dump_file)
818                 fprintf (dump_file,
819                          "SMS failed to schedule branch at cycle: %d\n", c);
820               goto clear;
821             }
822         }
823       else
824         {
825           c = start - SMODULO (start, ii) - 1;
826           gcc_assert (c <= start);
827
828           if (c <= end)
829             {
830               if (dump_file)
831                 fprintf (dump_file,
832                          "SMS failed to schedule branch at cycle: %d\n", c);
833               ok = false;
834               goto clear;
835             }
836         }
837
838       must_precede = sbitmap_alloc (g->num_nodes);
839       must_follow = sbitmap_alloc (g->num_nodes);
840
841       /* Try to schedule the branch is it's new cycle.  */
842       calculate_must_precede_follow (g->closing_branch, start, end,
843                                      step, ii, sched_nodes,
844                                      must_precede, must_follow);
845
846       set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
847                                must_precede, c, start, end, step);
848
849       /* Find the element in the partial schedule related to the closing
850          branch so we can remove it from it's current cycle.  */
851       for (next_ps_i = ps->rows[row];
852            next_ps_i; next_ps_i = next_ps_i->next_in_row)
853         if (next_ps_i->node->cuid == g->closing_branch->cuid)
854           break;
855
856       remove_node_from_ps (ps, next_ps_i);
857       success =
858         try_scheduling_node_in_cycle (ps, g->closing_branch,
859                                       g->closing_branch->cuid, c,
860                                       sched_nodes, &num_splits,
861                                       tmp_precede, tmp_follow);
862       gcc_assert (num_splits == 0);
863       if (!success)
864         {
865           if (dump_file)
866             fprintf (dump_file,
867                      "SMS failed to schedule branch at cycle: %d, "
868                      "bringing it back to cycle %d\n", c, branch_cycle);
869
870           /* The branch was failed to be placed in row ii - 1.
871              Put it back in it's original place in the partial
872              schedualing.  */
873           set_must_precede_follow (&tmp_follow, must_follow, &tmp_precede,
874                                    must_precede, branch_cycle, start, end,
875                                    step);
876           success =
877             try_scheduling_node_in_cycle (ps, g->closing_branch,
878                                           g->closing_branch->cuid,
879                                           branch_cycle, sched_nodes,
880                                           &num_splits, tmp_precede,
881                                           tmp_follow);
882           gcc_assert (success && (num_splits == 0));
883           ok = false;
884         }
885       else
886         {
887           /* The branch is placed in row ii - 1.  */
888           if (dump_file)
889             fprintf (dump_file,
890                      "SMS success in moving branch to cycle %d\n", c);
891
892           update_node_sched_params (g->closing_branch, ii, c,
893                                     PS_MIN_CYCLE (ps));
894           ok = true;
895         }
896
897       free (must_precede);
898       free (must_follow);
899     }
900
901 clear:
902   free (sched_nodes);
903   return ok;
904 }
905
906 static void
907 duplicate_insns_of_cycles (partial_schedule_ptr ps, int from_stage,
908                            int to_stage, int for_prolog, rtx count_reg)
909 {
910   int row;
911   ps_insn_ptr ps_ij;
912
913   for (row = 0; row < ps->ii; row++)
914     for (ps_ij = ps->rows[row]; ps_ij; ps_ij = ps_ij->next_in_row)
915       {
916         ddg_node_ptr u_node = ps_ij->node;
917         int j, i_reg_moves;
918         rtx reg_move = NULL_RTX;
919
920         /* Do not duplicate any insn which refers to count_reg as it
921            belongs to the control part.
922            The closing branch is scheduled as well and thus should
923            be ignored.
924            TODO: This should be done by analyzing the control part of
925            the loop.  */
926         if (reg_mentioned_p (count_reg, u_node->insn)
927             || JUMP_P (ps_ij->node->insn))
928           continue;
929
930         if (for_prolog)
931           {
932             /* SCHED_STAGE (u_node) >= from_stage == 0.  Generate increasing
933                number of reg_moves starting with the second occurrence of
934                u_node, which is generated if its SCHED_STAGE <= to_stage.  */
935             i_reg_moves = to_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));
938
939             /* The reg_moves start from the *first* reg_move backwards.  */
940             if (i_reg_moves)
941               {
942                 reg_move = SCHED_FIRST_REG_MOVE (u_node);
943                 for (j = 1; j < i_reg_moves; j++)
944                   reg_move = PREV_INSN (reg_move);
945               }
946           }
947         else /* It's for the epilog.  */
948           {
949             /* SCHED_STAGE (u_node) <= to_stage.  Generate all reg_moves,
950                starting to decrease one stage after u_node no longer occurs;
951                that is, generate all reg_moves until
952                SCHED_STAGE (u_node) == from_stage - 1.  */
953             i_reg_moves = SCHED_NREG_MOVES (u_node)
954                        - (from_stage - SCHED_STAGE (u_node) - 1);
955             i_reg_moves = MAX (i_reg_moves, 0);
956             i_reg_moves = MIN (i_reg_moves, SCHED_NREG_MOVES (u_node));
957
958             /* The reg_moves start from the *last* reg_move forwards.  */
959             if (i_reg_moves)
960               {
961                 reg_move = SCHED_FIRST_REG_MOVE (u_node);
962                 for (j = 1; j < SCHED_NREG_MOVES (u_node); j++)
963                   reg_move = PREV_INSN (reg_move);
964               }
965           }
966
967         for (j = 0; j < i_reg_moves; j++, reg_move = NEXT_INSN (reg_move))
968           emit_insn (copy_rtx (PATTERN (reg_move)));
969         if (SCHED_STAGE (u_node) >= from_stage
970             && SCHED_STAGE (u_node) <= to_stage)
971           duplicate_insn_chain (u_node->first_note, u_node->insn);
972       }
973 }
974
975
976 /* Generate the instructions (including reg_moves) for prolog & epilog.  */
977 static void
978 generate_prolog_epilog (partial_schedule_ptr ps, struct loop *loop,
979                         rtx count_reg, rtx count_init)
980 {
981   int i;
982   int last_stage = PS_STAGE_COUNT (ps) - 1;
983   edge e;
984
985   /* Generate the prolog, inserting its insns on the loop-entry edge.  */
986   start_sequence ();
987
988   if (!count_init)
989     {
990       /* Generate instructions at the beginning of the prolog to
991          adjust the loop count by STAGE_COUNT.  If loop count is constant
992          (count_init), this constant is adjusted by STAGE_COUNT in
993          generate_prolog_epilog function.  */
994       rtx sub_reg = NULL_RTX;
995
996       sub_reg = expand_simple_binop (GET_MODE (count_reg), MINUS,
997                                      count_reg, GEN_INT (last_stage),
998                                      count_reg, 1, OPTAB_DIRECT);
999       gcc_assert (REG_P (sub_reg));
1000       if (REGNO (sub_reg) != REGNO (count_reg))
1001         emit_move_insn (count_reg, sub_reg);
1002     }
1003
1004   for (i = 0; i < last_stage; i++)
1005     duplicate_insns_of_cycles (ps, 0, i, 1, count_reg);
1006
1007   /* Put the prolog on the entry edge.  */
1008   e = loop_preheader_edge (loop);
1009   split_edge_and_insert (e, get_insns ());
1010
1011   end_sequence ();
1012
1013   /* Generate the epilog, inserting its insns on the loop-exit edge.  */
1014   start_sequence ();
1015
1016   for (i = 0; i < last_stage; i++)
1017     duplicate_insns_of_cycles (ps, i + 1, last_stage, 0, count_reg);
1018
1019   /* Put the epilogue on the exit edge.  */
1020   gcc_assert (single_exit (loop));
1021   e = single_exit (loop);
1022   split_edge_and_insert (e, get_insns ());
1023   end_sequence ();
1024 }
1025
1026 /* Return true if all the BBs of the loop are empty except the
1027    loop header.  */
1028 static bool
1029 loop_single_full_bb_p (struct loop *loop)
1030 {
1031   unsigned i;
1032   basic_block *bbs = get_loop_body (loop);
1033
1034   for (i = 0; i < loop->num_nodes ; i++)
1035     {
1036       rtx head, tail;
1037       bool empty_bb = true;
1038
1039       if (bbs[i] == loop->header)
1040         continue;
1041
1042       /* Make sure that basic blocks other than the header
1043          have only notes labels or jumps.  */
1044       get_ebb_head_tail (bbs[i], bbs[i], &head, &tail);
1045       for (; head != NEXT_INSN (tail); head = NEXT_INSN (head))
1046         {
1047           if (NOTE_P (head) || LABEL_P (head)
1048               || (INSN_P (head) && (DEBUG_INSN_P (head) || JUMP_P (head))))
1049             continue;
1050           empty_bb = false;
1051           break;
1052         }
1053
1054       if (! empty_bb)
1055         {
1056           free (bbs);
1057           return false;
1058         }
1059     }
1060   free (bbs);
1061   return true;
1062 }
1063
1064 /* A simple loop from SMS point of view; it is a loop that is composed of
1065    either a single basic block or two BBs - a header and a latch.  */
1066 #define SIMPLE_SMS_LOOP_P(loop) ((loop->num_nodes < 3 )                     \
1067                                   && (EDGE_COUNT (loop->latch->preds) == 1) \
1068                                   && (EDGE_COUNT (loop->latch->succs) == 1))
1069
1070 /* Return true if the loop is in its canonical form and false if not.
1071    i.e. SIMPLE_SMS_LOOP_P and have one preheader block, and single exit.  */
1072 static bool
1073 loop_canon_p (struct loop *loop)
1074 {
1075
1076   if (loop->inner || !loop_outer (loop))
1077   {
1078     if (dump_file)
1079       fprintf (dump_file, "SMS loop inner or !loop_outer\n");
1080     return false;
1081   }
1082
1083   if (!single_exit (loop))
1084     {
1085       if (dump_file)
1086         {
1087           rtx insn = BB_END (loop->header);
1088
1089           fprintf (dump_file, "SMS loop many exits ");
1090                   fprintf (dump_file, " %s %d (file, line)\n",
1091                            insn_file (insn), insn_line (insn));
1092         }
1093       return false;
1094     }
1095
1096   if (! SIMPLE_SMS_LOOP_P (loop) && ! loop_single_full_bb_p (loop))
1097     {
1098       if (dump_file)
1099         {
1100           rtx insn = BB_END (loop->header);
1101
1102           fprintf (dump_file, "SMS loop many BBs. ");
1103           fprintf (dump_file, " %s %d (file, line)\n",
1104                    insn_file (insn), insn_line (insn));
1105         }
1106       return false;
1107     }
1108
1109     return true;
1110 }
1111
1112 /* If there are more than one entry for the loop,
1113    make it one by splitting the first entry edge and
1114    redirecting the others to the new BB.  */
1115 static void
1116 canon_loop (struct loop *loop)
1117 {
1118   edge e;
1119   edge_iterator i;
1120
1121   /* Avoid annoying special cases of edges going to exit
1122      block.  */
1123   FOR_EACH_EDGE (e, i, EXIT_BLOCK_PTR->preds)
1124     if ((e->flags & EDGE_FALLTHRU) && (EDGE_COUNT (e->src->succs) > 1))
1125       split_edge (e);
1126
1127   if (loop->latch == loop->header
1128       || EDGE_COUNT (loop->latch->succs) > 1)
1129     {
1130       FOR_EACH_EDGE (e, i, loop->header->preds)
1131         if (e->src == loop->latch)
1132           break;
1133       split_edge (e);
1134     }
1135 }
1136
1137 /* Setup infos.  */
1138 static void
1139 setup_sched_infos (void)
1140 {
1141   memcpy (&sms_common_sched_info, &haifa_common_sched_info,
1142           sizeof (sms_common_sched_info));
1143   sms_common_sched_info.sched_pass_id = SCHED_SMS_PASS;
1144   common_sched_info = &sms_common_sched_info;
1145
1146   sched_deps_info = &sms_sched_deps_info;
1147   current_sched_info = &sms_sched_info;
1148 }
1149
1150 /* Probability in % that the sms-ed loop rolls enough so that optimized
1151    version may be entered.  Just a guess.  */
1152 #define PROB_SMS_ENOUGH_ITERATIONS 80
1153
1154 /* Used to calculate the upper bound of ii.  */
1155 #define MAXII_FACTOR 2
1156
1157 /* Main entry point, perform SMS scheduling on the loops of the function
1158    that consist of single basic blocks.  */
1159 static void
1160 sms_schedule (void)
1161 {
1162   rtx insn;
1163   ddg_ptr *g_arr, g;
1164   int * node_order;
1165   int maxii, max_asap;
1166   loop_iterator li;
1167   partial_schedule_ptr ps;
1168   basic_block bb = NULL;
1169   struct loop *loop;
1170   basic_block condition_bb = NULL;
1171   edge latch_edge;
1172   gcov_type trip_count = 0;
1173
1174   loop_optimizer_init (LOOPS_HAVE_PREHEADERS
1175                        | LOOPS_HAVE_RECORDED_EXITS);
1176   if (number_of_loops () <= 1)
1177     {
1178       loop_optimizer_finalize ();
1179       return;  /* There are no loops to schedule.  */
1180     }
1181
1182   /* Initialize issue_rate.  */
1183   if (targetm.sched.issue_rate)
1184     {
1185       int temp = reload_completed;
1186
1187       reload_completed = 1;
1188       issue_rate = targetm.sched.issue_rate ();
1189       reload_completed = temp;
1190     }
1191   else
1192     issue_rate = 1;
1193
1194   /* Initialize the scheduler.  */
1195   setup_sched_infos ();
1196   haifa_sched_init ();
1197
1198   /* Allocate memory to hold the DDG array one entry for each loop.
1199      We use loop->num as index into this array.  */
1200   g_arr = XCNEWVEC (ddg_ptr, number_of_loops ());
1201
1202   if (dump_file)
1203   {
1204     fprintf (dump_file, "\n\nSMS analysis phase\n");
1205     fprintf (dump_file, "===================\n\n");
1206   }
1207
1208   /* Build DDGs for all the relevant loops and hold them in G_ARR
1209      indexed by the loop index.  */
1210   FOR_EACH_LOOP (li, loop, 0)
1211     {
1212       rtx head, tail;
1213       rtx count_reg;
1214
1215       /* For debugging.  */
1216       if (dbg_cnt (sms_sched_loop) == false)
1217         {
1218           if (dump_file)
1219             fprintf (dump_file, "SMS reached max limit... \n");
1220
1221           break;
1222         }
1223
1224       if (dump_file)
1225       {
1226          rtx insn = BB_END (loop->header);
1227
1228          fprintf (dump_file, "SMS loop num: %d, file: %s, line: %d\n",
1229                   loop->num, insn_file (insn), insn_line (insn));
1230
1231       }
1232
1233       if (! loop_canon_p (loop))
1234         continue;
1235
1236       if (! loop_single_full_bb_p (loop))
1237       {
1238         if (dump_file)
1239           fprintf (dump_file, "SMS not loop_single_full_bb_p\n");
1240         continue;
1241       }
1242
1243       bb = loop->header;
1244
1245       get_ebb_head_tail (bb, bb, &head, &tail);
1246       latch_edge = loop_latch_edge (loop);
1247       gcc_assert (single_exit (loop));
1248       if (single_exit (loop)->count)
1249         trip_count = latch_edge->count / single_exit (loop)->count;
1250
1251       /* Perform SMS only on loops that their average count is above threshold.  */
1252
1253       if ( latch_edge->count
1254           && (latch_edge->count < single_exit (loop)->count * SMS_LOOP_AVERAGE_COUNT_THRESHOLD))
1255         {
1256           if (dump_file)
1257             {
1258               fprintf (dump_file, " %s %d (file, line)\n",
1259                        insn_file (tail), insn_line (tail));
1260               fprintf (dump_file, "SMS single-bb-loop\n");
1261               if (profile_info && flag_branch_probabilities)
1262                 {
1263                   fprintf (dump_file, "SMS loop-count ");
1264                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1265                            (HOST_WIDEST_INT) bb->count);
1266                   fprintf (dump_file, "\n");
1267                   fprintf (dump_file, "SMS trip-count ");
1268                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1269                            (HOST_WIDEST_INT) trip_count);
1270                   fprintf (dump_file, "\n");
1271                   fprintf (dump_file, "SMS profile-sum-max ");
1272                   fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1273                            (HOST_WIDEST_INT) profile_info->sum_max);
1274                   fprintf (dump_file, "\n");
1275                 }
1276             }
1277           continue;
1278         }
1279
1280       /* Make sure this is a doloop.  */
1281       if ( !(count_reg = doloop_register_get (head, tail)))
1282       {
1283         if (dump_file)
1284           fprintf (dump_file, "SMS doloop_register_get failed\n");
1285         continue;
1286       }
1287
1288       /* Don't handle BBs with calls or barriers
1289          or !single_set with the exception of instructions that include
1290          count_reg---these instructions are part of the control part
1291          that do-loop recognizes.
1292          ??? Should handle insns defining subregs.  */
1293      for (insn = head; insn != NEXT_INSN (tail); insn = NEXT_INSN (insn))
1294       {
1295          rtx set;
1296
1297         if (CALL_P (insn)
1298             || BARRIER_P (insn)
1299             || (NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1300                 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE
1301                 && !reg_mentioned_p (count_reg, insn))
1302             || (INSN_P (insn) && (set = single_set (insn))
1303                 && GET_CODE (SET_DEST (set)) == SUBREG))
1304         break;
1305       }
1306
1307       if (insn != NEXT_INSN (tail))
1308         {
1309           if (dump_file)
1310             {
1311               if (CALL_P (insn))
1312                 fprintf (dump_file, "SMS loop-with-call\n");
1313               else if (BARRIER_P (insn))
1314                 fprintf (dump_file, "SMS loop-with-barrier\n");
1315               else if ((NONDEBUG_INSN_P (insn) && !JUMP_P (insn)
1316                 && !single_set (insn) && GET_CODE (PATTERN (insn)) != USE))
1317                 fprintf (dump_file, "SMS loop-with-not-single-set\n");
1318               else
1319                fprintf (dump_file, "SMS loop with subreg in lhs\n");
1320               print_rtl_single (dump_file, insn);
1321             }
1322
1323           continue;
1324         }
1325
1326       /* Always schedule the closing branch with the rest of the
1327          instructions. The branch is rotated to be in row ii-1 at the
1328          end of the scheduling procedure to make sure it's the last
1329          instruction in the iteration.  */
1330       if (! (g = create_ddg (bb, 1)))
1331         {
1332           if (dump_file)
1333             fprintf (dump_file, "SMS create_ddg failed\n");
1334           continue;
1335         }
1336
1337       g_arr[loop->num] = g;
1338       if (dump_file)
1339         fprintf (dump_file, "...OK\n");
1340
1341     }
1342   if (dump_file)
1343   {
1344     fprintf (dump_file, "\nSMS transformation phase\n");
1345     fprintf (dump_file, "=========================\n\n");
1346   }
1347
1348   /* We don't want to perform SMS on new loops - created by versioning.  */
1349   FOR_EACH_LOOP (li, loop, 0)
1350     {
1351       rtx head, tail;
1352       rtx count_reg, count_init;
1353       int mii, rec_mii;
1354       unsigned stage_count = 0;
1355       HOST_WIDEST_INT loop_count = 0;
1356       bool opt_sc_p = false;
1357
1358       if (! (g = g_arr[loop->num]))
1359         continue;
1360
1361       if (dump_file)
1362       {
1363          rtx insn = BB_END (loop->header);
1364
1365          fprintf (dump_file, "SMS loop num: %d, file: %s, line: %d\n",
1366                   loop->num, insn_file (insn), insn_line (insn));
1367
1368          print_ddg (dump_file, g);
1369       }
1370
1371       get_ebb_head_tail (loop->header, loop->header, &head, &tail);
1372
1373       latch_edge = loop_latch_edge (loop);
1374       gcc_assert (single_exit (loop));
1375       if (single_exit (loop)->count)
1376         trip_count = latch_edge->count / single_exit (loop)->count;
1377
1378       if (dump_file)
1379         {
1380           fprintf (dump_file, " %s %d (file, line)\n",
1381                    insn_file (tail), insn_line (tail));
1382           fprintf (dump_file, "SMS single-bb-loop\n");
1383           if (profile_info && flag_branch_probabilities)
1384             {
1385               fprintf (dump_file, "SMS loop-count ");
1386               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1387                        (HOST_WIDEST_INT) bb->count);
1388               fprintf (dump_file, "\n");
1389               fprintf (dump_file, "SMS profile-sum-max ");
1390               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1391                        (HOST_WIDEST_INT) profile_info->sum_max);
1392               fprintf (dump_file, "\n");
1393             }
1394           fprintf (dump_file, "SMS doloop\n");
1395           fprintf (dump_file, "SMS built-ddg %d\n", g->num_nodes);
1396           fprintf (dump_file, "SMS num-loads %d\n", g->num_loads);
1397           fprintf (dump_file, "SMS num-stores %d\n", g->num_stores);
1398         }
1399
1400
1401       /* In case of th loop have doloop register it gets special
1402          handling.  */
1403       count_init = NULL_RTX;
1404       if ((count_reg = doloop_register_get (head, tail)))
1405         {
1406           basic_block pre_header;
1407
1408           pre_header = loop_preheader_edge (loop)->src;
1409           count_init = const_iteration_count (count_reg, pre_header,
1410                                               &loop_count);
1411         }
1412       gcc_assert (count_reg);
1413
1414       if (dump_file && count_init)
1415         {
1416           fprintf (dump_file, "SMS const-doloop ");
1417           fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1418                      loop_count);
1419           fprintf (dump_file, "\n");
1420         }
1421
1422       node_order = XNEWVEC (int, g->num_nodes);
1423
1424       mii = 1; /* Need to pass some estimate of mii.  */
1425       rec_mii = sms_order_nodes (g, mii, node_order, &max_asap);
1426       mii = MAX (res_MII (g), rec_mii);
1427       maxii = MAX (max_asap, MAXII_FACTOR * mii);
1428
1429       if (dump_file)
1430         fprintf (dump_file, "SMS iis %d %d %d (rec_mii, mii, maxii)\n",
1431                  rec_mii, mii, maxii);
1432
1433       /* After sms_order_nodes and before sms_schedule_by_order, to copy over
1434          ASAP.  */
1435       set_node_sched_params (g);
1436
1437       ps = sms_schedule_by_order (g, mii, maxii, node_order);
1438       
1439       if (ps)
1440         {
1441           /* Try to achieve optimized SC by normalizing the partial
1442              schedule (having the cycles start from cycle zero).
1443              The branch location must be placed in row ii-1 in the
1444              final scheduling.  If failed, shift all instructions to
1445              position the branch in row ii-1.  */
1446           opt_sc_p = optimize_sc (ps, g);
1447           if (opt_sc_p)
1448             stage_count = calculate_stage_count (ps, 0);
1449           else
1450             {
1451               /* Bring the branch to cycle ii-1.  */
1452               int amount = SCHED_TIME (g->closing_branch) - (ps->ii - 1);
1453               
1454               if (dump_file)
1455                 fprintf (dump_file, "SMS schedule branch at cycle ii-1\n");
1456               
1457               stage_count = calculate_stage_count (ps, amount);
1458             }
1459           
1460           gcc_assert (stage_count >= 1);
1461           PS_STAGE_COUNT (ps) = stage_count;
1462         }
1463       
1464       /* The default value of PARAM_SMS_MIN_SC is 2 as stage count of
1465          1 means that there is no interleaving between iterations thus
1466          we let the scheduling passes do the job in this case.  */
1467       if (stage_count < (unsigned) PARAM_VALUE (PARAM_SMS_MIN_SC)
1468           || (count_init && (loop_count <= stage_count))
1469           || (flag_branch_probabilities && (trip_count <= stage_count)))
1470         {
1471           if (dump_file)
1472             {
1473               fprintf (dump_file, "SMS failed... \n");
1474               fprintf (dump_file, "SMS sched-failed (stage-count=%d, loop-count=", stage_count);
1475               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, loop_count);
1476               fprintf (dump_file, ", trip-count=");
1477               fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, trip_count);
1478               fprintf (dump_file, ")\n");
1479             }
1480         }
1481       else
1482         {
1483           struct undo_replace_buff_elem *reg_move_replaces;
1484
1485           if (!opt_sc_p)
1486             {
1487               /* Rotate the partial schedule to have the branch in row ii-1.  */
1488               int amount = SCHED_TIME (g->closing_branch) - (ps->ii - 1);
1489               
1490               reset_sched_times (ps, amount);
1491               rotate_partial_schedule (ps, amount);
1492             }
1493           
1494           set_columns_for_ps (ps);
1495
1496           canon_loop (loop);
1497
1498           if (dump_file)
1499             {
1500               fprintf (dump_file,
1501                        "%s:%d SMS succeeded %d %d (with ii, sc)\n",
1502                        insn_file (tail), insn_line (tail), ps->ii, stage_count);
1503               print_partial_schedule (ps, dump_file);
1504             }
1505  
1506           /* case the BCT count is not known , Do loop-versioning */
1507           if (count_reg && ! count_init)
1508             {
1509               rtx comp_rtx = gen_rtx_fmt_ee (GT, VOIDmode, count_reg,
1510                                              GEN_INT(stage_count));
1511               unsigned prob = (PROB_SMS_ENOUGH_ITERATIONS
1512                                * REG_BR_PROB_BASE) / 100;
1513
1514               loop_version (loop, comp_rtx, &condition_bb,
1515                             prob, prob, REG_BR_PROB_BASE - prob,
1516                             true);
1517              }
1518
1519           /* Set new iteration count of loop kernel.  */
1520           if (count_reg && count_init)
1521             SET_SRC (single_set (count_init)) = GEN_INT (loop_count
1522                                                      - stage_count + 1);
1523
1524           /* Now apply the scheduled kernel to the RTL of the loop.  */
1525           permute_partial_schedule (ps, g->closing_branch->first_note);
1526
1527           /* Mark this loop as software pipelined so the later
1528              scheduling passes doesn't touch it.  */
1529           if (! flag_resched_modulo_sched)
1530             g->bb->flags |= BB_DISABLE_SCHEDULE;
1531           /* The life-info is not valid any more.  */
1532           df_set_bb_dirty (g->bb);
1533
1534           reg_move_replaces = generate_reg_moves (ps, true);
1535           if (dump_file)
1536             print_node_sched_params (dump_file, g->num_nodes, g);
1537           /* Generate prolog and epilog.  */
1538           generate_prolog_epilog (ps, loop, count_reg, count_init);
1539
1540           free_undo_replace_buff (reg_move_replaces);
1541         }
1542
1543       free_partial_schedule (ps);
1544       free (node_sched_params);
1545       free (node_order);
1546       free_ddg (g);
1547     }
1548
1549   free (g_arr);
1550
1551   /* Release scheduler data, needed until now because of DFA.  */
1552   haifa_sched_finish ();
1553   loop_optimizer_finalize ();
1554 }
1555
1556 /* The SMS scheduling algorithm itself
1557    -----------------------------------
1558    Input: 'O' an ordered list of insns of a loop.
1559    Output: A scheduling of the loop - kernel, prolog, and epilogue.
1560
1561    'Q' is the empty Set
1562    'PS' is the partial schedule; it holds the currently scheduled nodes with
1563         their cycle/slot.
1564    'PSP' previously scheduled predecessors.
1565    'PSS' previously scheduled successors.
1566    't(u)' the cycle where u is scheduled.
1567    'l(u)' is the latency of u.
1568    'd(v,u)' is the dependence distance from v to u.
1569    'ASAP(u)' the earliest time at which u could be scheduled as computed in
1570              the node ordering phase.
1571    'check_hardware_resources_conflicts(u, PS, c)'
1572                              run a trace around cycle/slot through DFA model
1573                              to check resource conflicts involving instruction u
1574                              at cycle c given the partial schedule PS.
1575    'add_to_partial_schedule_at_time(u, PS, c)'
1576                              Add the node/instruction u to the partial schedule
1577                              PS at time c.
1578    'calculate_register_pressure(PS)'
1579                              Given a schedule of instructions, calculate the register
1580                              pressure it implies.  One implementation could be the
1581                              maximum number of overlapping live ranges.
1582    'maxRP' The maximum allowed register pressure, it is usually derived from the number
1583            registers available in the hardware.
1584
1585    1. II = MII.
1586    2. PS = empty list
1587    3. for each node u in O in pre-computed order
1588    4.   if (PSP(u) != Q && PSS(u) == Q) then
1589    5.     Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1590    6.     start = Early_start; end = Early_start + II - 1; step = 1
1591    11.  else if (PSP(u) == Q && PSS(u) != Q) then
1592    12.      Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1593    13.     start = Late_start; end = Late_start - II + 1; step = -1
1594    14.  else if (PSP(u) != Q && PSS(u) != Q) then
1595    15.     Early_start(u) = max ( t(v) + l(v) - d(v,u)*II ) over all every v in PSP(u).
1596    16.     Late_start(u) = min ( t(v) - l(v) + d(v,u)*II ) over all every v in PSS(u).
1597    17.     start = Early_start;
1598    18.     end = min(Early_start + II - 1 , Late_start);
1599    19.     step = 1
1600    20.     else "if (PSP(u) == Q && PSS(u) == Q)"
1601    21.    start = ASAP(u); end = start + II - 1; step = 1
1602    22.  endif
1603
1604    23.  success = false
1605    24.  for (c = start ; c != end ; c += step)
1606    25.     if check_hardware_resources_conflicts(u, PS, c) then
1607    26.       add_to_partial_schedule_at_time(u, PS, c)
1608    27.       success = true
1609    28.       break
1610    29.     endif
1611    30.  endfor
1612    31.  if (success == false) then
1613    32.    II = II + 1
1614    33.    if (II > maxII) then
1615    34.       finish - failed to schedule
1616    35.   endif
1617    36.    goto 2.
1618    37.  endif
1619    38. endfor
1620    39. if (calculate_register_pressure(PS) > maxRP) then
1621    40.    goto 32.
1622    41. endif
1623    42. compute epilogue & prologue
1624    43. finish - succeeded to schedule
1625 */
1626
1627 /* A limit on the number of cycles that resource conflicts can span.  ??? Should
1628    be provided by DFA, and be dependent on the type of insn scheduled.  Currently
1629    set to 0 to save compile time.  */
1630 #define DFA_HISTORY SMS_DFA_HISTORY
1631
1632 /* A threshold for the number of repeated unsuccessful attempts to insert
1633    an empty row, before we flush the partial schedule and start over.  */
1634 #define MAX_SPLIT_NUM 10
1635 /* Given the partial schedule PS, this function calculates and returns the
1636    cycles in which we can schedule the node with the given index I.
1637    NOTE: Here we do the backtracking in SMS, in some special cases. We have
1638    noticed that there are several cases in which we fail    to SMS the loop
1639    because the sched window of a node is empty    due to tight data-deps. In
1640    such cases we want to unschedule    some of the predecessors/successors
1641    until we get non-empty    scheduling window.  It returns -1 if the
1642    scheduling window is empty and zero otherwise.  */
1643
1644 static int
1645 get_sched_window (partial_schedule_ptr ps, ddg_node_ptr u_node,
1646                   sbitmap sched_nodes, int ii, int *start_p, int *step_p,
1647                   int *end_p)
1648 {
1649   int start, step, end;
1650   int early_start, late_start;
1651   ddg_edge_ptr e;
1652   sbitmap psp = sbitmap_alloc (ps->g->num_nodes);
1653   sbitmap pss = sbitmap_alloc (ps->g->num_nodes);
1654   sbitmap u_node_preds = NODE_PREDECESSORS (u_node);
1655   sbitmap u_node_succs = NODE_SUCCESSORS (u_node);
1656   int psp_not_empty;
1657   int pss_not_empty;
1658   int count_preds;
1659   int count_succs;
1660
1661   /* 1. compute sched window for u (start, end, step).  */
1662   sbitmap_zero (psp);
1663   sbitmap_zero (pss);
1664   psp_not_empty = sbitmap_a_and_b_cg (psp, u_node_preds, sched_nodes);
1665   pss_not_empty = sbitmap_a_and_b_cg (pss, u_node_succs, sched_nodes);
1666
1667   /* We first compute a forward range (start <= end), then decide whether
1668      to reverse it.  */
1669   early_start = INT_MIN;
1670   late_start = INT_MAX;
1671   start = INT_MIN;
1672   end = INT_MAX;
1673   step = 1;
1674
1675   count_preds = 0;
1676   count_succs = 0;
1677
1678   if (dump_file && (psp_not_empty || pss_not_empty))
1679     {
1680       fprintf (dump_file, "\nAnalyzing dependencies for node %d (INSN %d)"
1681                "; ii = %d\n\n", u_node->cuid, INSN_UID (u_node->insn), ii);
1682       fprintf (dump_file, "%11s %11s %11s %11s %5s\n",
1683                "start", "early start", "late start", "end", "time");
1684       fprintf (dump_file, "=========== =========== =========== ==========="
1685                " =====\n");
1686     }
1687   /* Calculate early_start and limit end.  Both bounds are inclusive.  */
1688   if (psp_not_empty)
1689     for (e = u_node->in; e != 0; e = e->next_in)
1690       {
1691         ddg_node_ptr v_node = e->src;
1692
1693         if (TEST_BIT (sched_nodes, v_node->cuid))
1694           {
1695             int p_st = SCHED_TIME (v_node);
1696             int earliest = p_st + e->latency - (e->distance * ii);
1697             int latest = (e->data_type == MEM_DEP ? p_st + ii - 1 : INT_MAX);
1698
1699             if (dump_file)
1700               {
1701                 fprintf (dump_file, "%11s %11d %11s %11d %5d",
1702                          "", earliest, "", latest, p_st);
1703                 print_ddg_edge (dump_file, e);
1704                 fprintf (dump_file, "\n");
1705               }
1706
1707             early_start = MAX (early_start, earliest);
1708             end = MIN (end, latest);
1709
1710             if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1711               count_preds++;
1712           }
1713       }
1714
1715   /* Calculate late_start and limit start.  Both bounds are inclusive.  */
1716   if (pss_not_empty)
1717     for (e = u_node->out; e != 0; e = e->next_out)
1718       {
1719         ddg_node_ptr v_node = e->dest;
1720
1721         if (TEST_BIT (sched_nodes, v_node->cuid))
1722           {
1723             int s_st = SCHED_TIME (v_node);
1724             int earliest = (e->data_type == MEM_DEP ? s_st - ii + 1 : INT_MIN);
1725             int latest = s_st - e->latency + (e->distance * ii);
1726
1727             if (dump_file)
1728               {
1729                 fprintf (dump_file, "%11d %11s %11d %11s %5d",
1730                          earliest, "", latest, "", s_st);
1731                 print_ddg_edge (dump_file, e);
1732                 fprintf (dump_file, "\n");
1733               }
1734
1735             start = MAX (start, earliest);
1736             late_start = MIN (late_start, latest);
1737
1738             if (e->type == TRUE_DEP && e->data_type == REG_DEP)
1739               count_succs++;
1740           }
1741       }
1742
1743   if (dump_file && (psp_not_empty || pss_not_empty))
1744     {
1745       fprintf (dump_file, "----------- ----------- ----------- -----------"
1746                " -----\n");
1747       fprintf (dump_file, "%11d %11d %11d %11d %5s %s\n",
1748                start, early_start, late_start, end, "",
1749                "(max, max, min, min)");
1750     }
1751
1752   /* Get a target scheduling window no bigger than ii.  */
1753   if (early_start == INT_MIN && late_start == INT_MAX)
1754     early_start = SCHED_ASAP (u_node);
1755   else if (early_start == INT_MIN)
1756     early_start = late_start - (ii - 1);
1757   late_start = MIN (late_start, early_start + (ii - 1));
1758
1759   /* Apply memory dependence limits.  */
1760   start = MAX (start, early_start);
1761   end = MIN (end, late_start);
1762
1763   if (dump_file && (psp_not_empty || pss_not_empty))
1764     fprintf (dump_file, "%11s %11d %11d %11s %5s final window\n",
1765              "", start, end, "", "");
1766
1767   /* If there are at least as many successors as predecessors, schedule the
1768      node close to its successors.  */
1769   if (pss_not_empty && count_succs >= count_preds)
1770     {
1771       int tmp = end;
1772       end = start;
1773       start = tmp;
1774       step = -1;
1775     }
1776
1777   /* Now that we've finalized the window, make END an exclusive rather
1778      than an inclusive bound.  */
1779   end += step;
1780
1781   *start_p = start;
1782   *step_p = step;
1783   *end_p = end;
1784   sbitmap_free (psp);
1785   sbitmap_free (pss);
1786
1787   if ((start >= end && step == 1) || (start <= end && step == -1))
1788     {
1789       if (dump_file)
1790         fprintf (dump_file, "\nEmpty window: start=%d, end=%d, step=%d\n",
1791                  start, end, step);
1792       return -1;
1793     }
1794
1795   return 0;
1796 }
1797
1798 /* Calculate MUST_PRECEDE/MUST_FOLLOW bitmaps of U_NODE; which is the
1799    node currently been scheduled.  At the end of the calculation
1800    MUST_PRECEDE/MUST_FOLLOW contains all predecessors/successors of
1801    U_NODE which are (1) already scheduled in the first/last row of
1802    U_NODE's scheduling window, (2) whose dependence inequality with U
1803    becomes an equality when U is scheduled in this same row, and (3)
1804    whose dependence latency is zero.
1805
1806    The first and last rows are calculated using the following parameters:
1807    START/END rows - The cycles that begins/ends the traversal on the window;
1808    searching for an empty cycle to schedule U_NODE.
1809    STEP - The direction in which we traverse the window.
1810    II - The initiation interval.  */
1811
1812 static void
1813 calculate_must_precede_follow (ddg_node_ptr u_node, int start, int end,
1814                                int step, int ii, sbitmap sched_nodes,
1815                                sbitmap must_precede, sbitmap must_follow)
1816 {
1817   ddg_edge_ptr e;
1818   int first_cycle_in_window, last_cycle_in_window;
1819
1820   gcc_assert (must_precede && must_follow);
1821
1822   /* Consider the following scheduling window:
1823      {first_cycle_in_window, first_cycle_in_window+1, ...,
1824      last_cycle_in_window}.  If step is 1 then the following will be
1825      the order we traverse the window: {start=first_cycle_in_window,
1826      first_cycle_in_window+1, ..., end=last_cycle_in_window+1},
1827      or {start=last_cycle_in_window, last_cycle_in_window-1, ...,
1828      end=first_cycle_in_window-1} if step is -1.  */
1829   first_cycle_in_window = (step == 1) ? start : end - step;
1830   last_cycle_in_window = (step == 1) ? end - step : start;
1831
1832   sbitmap_zero (must_precede);
1833   sbitmap_zero (must_follow);
1834
1835   if (dump_file)
1836     fprintf (dump_file, "\nmust_precede: ");
1837
1838   /* Instead of checking if:
1839       (SMODULO (SCHED_TIME (e->src), ii) == first_row_in_window)
1840       && ((SCHED_TIME (e->src) + e->latency - (e->distance * ii)) ==
1841              first_cycle_in_window)
1842       && e->latency == 0
1843      we use the fact that latency is non-negative:
1844       SCHED_TIME (e->src) - (e->distance * ii) <=
1845       SCHED_TIME (e->src) + e->latency - (e->distance * ii)) <=
1846       first_cycle_in_window
1847      and check only if
1848       SCHED_TIME (e->src) - (e->distance * ii) == first_cycle_in_window  */
1849   for (e = u_node->in; e != 0; e = e->next_in)
1850     if (TEST_BIT (sched_nodes, e->src->cuid)
1851         && ((SCHED_TIME (e->src) - (e->distance * ii)) ==
1852              first_cycle_in_window))
1853       {
1854         if (dump_file)
1855           fprintf (dump_file, "%d ", e->src->cuid);
1856
1857         SET_BIT (must_precede, e->src->cuid);
1858       }
1859
1860   if (dump_file)
1861     fprintf (dump_file, "\nmust_follow: ");
1862
1863   /* Instead of checking if:
1864       (SMODULO (SCHED_TIME (e->dest), ii) == last_row_in_window)
1865       && ((SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) ==
1866              last_cycle_in_window)
1867       && e->latency == 0
1868      we use the fact that latency is non-negative:
1869       SCHED_TIME (e->dest) + (e->distance * ii) >=
1870       SCHED_TIME (e->dest) - e->latency + (e->distance * ii)) >=
1871       last_cycle_in_window
1872      and check only if
1873       SCHED_TIME (e->dest) + (e->distance * ii) == last_cycle_in_window  */
1874   for (e = u_node->out; e != 0; e = e->next_out)
1875     if (TEST_BIT (sched_nodes, e->dest->cuid)
1876         && ((SCHED_TIME (e->dest) + (e->distance * ii)) ==
1877              last_cycle_in_window))
1878       {
1879         if (dump_file)
1880           fprintf (dump_file, "%d ", e->dest->cuid);
1881
1882         SET_BIT (must_follow, e->dest->cuid);
1883       }
1884
1885   if (dump_file)
1886     fprintf (dump_file, "\n");
1887 }
1888
1889 /* Return 1 if U_NODE can be scheduled in CYCLE.  Use the following
1890    parameters to decide if that's possible:
1891    PS - The partial schedule.
1892    U - The serial number of U_NODE.
1893    NUM_SPLITS - The number of row splits made so far.
1894    MUST_PRECEDE - The nodes that must precede U_NODE. (only valid at
1895    the first row of the scheduling window)
1896    MUST_FOLLOW - The nodes that must follow U_NODE. (only valid at the
1897    last row of the scheduling window)  */
1898
1899 static bool
1900 try_scheduling_node_in_cycle (partial_schedule_ptr ps, ddg_node_ptr u_node,
1901                               int u, int cycle, sbitmap sched_nodes,
1902                               int *num_splits, sbitmap must_precede,
1903                               sbitmap must_follow)
1904 {
1905   ps_insn_ptr psi;
1906   bool success = 0;
1907
1908   verify_partial_schedule (ps, sched_nodes);
1909   psi = ps_add_node_check_conflicts (ps, u_node, cycle,
1910                                      must_precede, must_follow);
1911   if (psi)
1912     {
1913       SCHED_TIME (u_node) = cycle;
1914       SET_BIT (sched_nodes, u);
1915       success = 1;
1916       *num_splits = 0;
1917       if (dump_file)
1918         fprintf (dump_file, "Scheduled w/o split in %d\n", cycle);
1919
1920     }
1921
1922   return success;
1923 }
1924
1925 /* This function implements the scheduling algorithm for SMS according to the
1926    above algorithm.  */
1927 static partial_schedule_ptr
1928 sms_schedule_by_order (ddg_ptr g, int mii, int maxii, int *nodes_order)
1929 {
1930   int ii = mii;
1931   int i, c, success, num_splits = 0;
1932   int flush_and_start_over = true;
1933   int num_nodes = g->num_nodes;
1934   int start, end, step; /* Place together into one struct?  */
1935   sbitmap sched_nodes = sbitmap_alloc (num_nodes);
1936   sbitmap must_precede = sbitmap_alloc (num_nodes);
1937   sbitmap must_follow = sbitmap_alloc (num_nodes);
1938   sbitmap tobe_scheduled = sbitmap_alloc (num_nodes);
1939
1940   partial_schedule_ptr ps = create_partial_schedule (ii, g, DFA_HISTORY);
1941
1942   sbitmap_ones (tobe_scheduled);
1943   sbitmap_zero (sched_nodes);
1944
1945   while (flush_and_start_over && (ii < maxii))
1946     {
1947
1948       if (dump_file)
1949         fprintf (dump_file, "Starting with ii=%d\n", ii);
1950       flush_and_start_over = false;
1951       sbitmap_zero (sched_nodes);
1952
1953       for (i = 0; i < num_nodes; i++)
1954         {
1955           int u = nodes_order[i];
1956           ddg_node_ptr u_node = &ps->g->nodes[u];
1957           rtx insn = u_node->insn;
1958
1959           if (!NONDEBUG_INSN_P (insn))
1960             {
1961               RESET_BIT (tobe_scheduled, u);
1962               continue;
1963             }
1964
1965           if (TEST_BIT (sched_nodes, u))
1966             continue;
1967
1968           /* Try to get non-empty scheduling window.  */
1969          success = 0;
1970          if (get_sched_window (ps, u_node, sched_nodes, ii, &start,
1971                                 &step, &end) == 0)
1972             {
1973               if (dump_file)
1974                 fprintf (dump_file, "\nTrying to schedule node %d "
1975                          "INSN = %d  in (%d .. %d) step %d\n", u, (INSN_UID
1976                         (g->nodes[u].insn)), start, end, step);
1977
1978               gcc_assert ((step > 0 && start < end)
1979                           || (step < 0 && start > end));
1980
1981               calculate_must_precede_follow (u_node, start, end, step, ii,
1982                                              sched_nodes, must_precede,
1983                                              must_follow);
1984
1985               for (c = start; c != end; c += step)
1986                 {
1987                   sbitmap tmp_precede, tmp_follow;
1988
1989                   set_must_precede_follow (&tmp_follow, must_follow, 
1990                                            &tmp_precede, must_precede, 
1991                                            c, start, end, step);
1992                   success =
1993                     try_scheduling_node_in_cycle (ps, u_node, u, c,
1994                                                   sched_nodes,
1995                                                   &num_splits, tmp_precede,
1996                                                   tmp_follow);
1997                   if (success)
1998                     break;
1999                 }
2000
2001               verify_partial_schedule (ps, sched_nodes);
2002             }
2003             if (!success)
2004             {
2005               int split_row;
2006
2007               if (ii++ == maxii)
2008                 break;
2009
2010               if (num_splits >= MAX_SPLIT_NUM)
2011                 {
2012                   num_splits = 0;
2013                   flush_and_start_over = true;
2014                   verify_partial_schedule (ps, sched_nodes);
2015                   reset_partial_schedule (ps, ii);
2016                   verify_partial_schedule (ps, sched_nodes);
2017                   break;
2018                 }
2019
2020               num_splits++;
2021               /* The scheduling window is exclusive of 'end'
2022                  whereas compute_split_window() expects an inclusive,
2023                  ordered range.  */
2024               if (step == 1)
2025                 split_row = compute_split_row (sched_nodes, start, end - 1,
2026                                                ps->ii, u_node);
2027               else
2028                 split_row = compute_split_row (sched_nodes, end + 1, start,
2029                                                ps->ii, u_node);
2030
2031               ps_insert_empty_row (ps, split_row, sched_nodes);
2032               i--;              /* Go back and retry node i.  */
2033
2034               if (dump_file)
2035                 fprintf (dump_file, "num_splits=%d\n", num_splits);
2036             }
2037
2038           /* ??? If (success), check register pressure estimates.  */
2039         }                       /* Continue with next node.  */
2040     }                           /* While flush_and_start_over.  */
2041   if (ii >= maxii)
2042     {
2043       free_partial_schedule (ps);
2044       ps = NULL;
2045     }
2046   else
2047     gcc_assert (sbitmap_equal (tobe_scheduled, sched_nodes));
2048
2049   sbitmap_free (sched_nodes);
2050   sbitmap_free (must_precede);
2051   sbitmap_free (must_follow);
2052   sbitmap_free (tobe_scheduled);
2053
2054   return ps;
2055 }
2056
2057 /* This function inserts a new empty row into PS at the position
2058    according to SPLITROW, keeping all already scheduled instructions
2059    intact and updating their SCHED_TIME and cycle accordingly.  */
2060 static void
2061 ps_insert_empty_row (partial_schedule_ptr ps, int split_row,
2062                      sbitmap sched_nodes)
2063 {
2064   ps_insn_ptr crr_insn;
2065   ps_insn_ptr *rows_new;
2066   int ii = ps->ii;
2067   int new_ii = ii + 1;
2068   int row;
2069   int *rows_length_new;
2070
2071   verify_partial_schedule (ps, sched_nodes);
2072
2073   /* We normalize sched_time and rotate ps to have only non-negative sched
2074      times, for simplicity of updating cycles after inserting new row.  */
2075   split_row -= ps->min_cycle;
2076   split_row = SMODULO (split_row, ii);
2077   if (dump_file)
2078     fprintf (dump_file, "split_row=%d\n", split_row);
2079
2080   reset_sched_times (ps, PS_MIN_CYCLE (ps));
2081   rotate_partial_schedule (ps, PS_MIN_CYCLE (ps));
2082
2083   rows_new = (ps_insn_ptr *) xcalloc (new_ii, sizeof (ps_insn_ptr));
2084   rows_length_new = (int *) xcalloc (new_ii, sizeof (int));
2085   for (row = 0; row < split_row; row++)
2086     {
2087       rows_new[row] = ps->rows[row];
2088       rows_length_new[row] = ps->rows_length[row];
2089       ps->rows[row] = NULL;
2090       for (crr_insn = rows_new[row];
2091            crr_insn; crr_insn = crr_insn->next_in_row)
2092         {
2093           ddg_node_ptr u = crr_insn->node;
2094           int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii);
2095
2096           SCHED_TIME (u) = new_time;
2097           crr_insn->cycle = new_time;
2098           SCHED_ROW (u) = new_time % new_ii;
2099           SCHED_STAGE (u) = new_time / new_ii;
2100         }
2101
2102     }
2103
2104   rows_new[split_row] = NULL;
2105
2106   for (row = split_row; row < ii; row++)
2107     {
2108       rows_new[row + 1] = ps->rows[row];
2109       rows_length_new[row + 1] = ps->rows_length[row];
2110       ps->rows[row] = NULL;
2111       for (crr_insn = rows_new[row + 1];
2112            crr_insn; crr_insn = crr_insn->next_in_row)
2113         {
2114           ddg_node_ptr u = crr_insn->node;
2115           int new_time = SCHED_TIME (u) + (SCHED_TIME (u) / ii) + 1;
2116
2117           SCHED_TIME (u) = new_time;
2118           crr_insn->cycle = new_time;
2119           SCHED_ROW (u) = new_time % new_ii;
2120           SCHED_STAGE (u) = new_time / new_ii;
2121         }
2122     }
2123
2124   /* Updating ps.  */
2125   ps->min_cycle = ps->min_cycle + ps->min_cycle / ii
2126     + (SMODULO (ps->min_cycle, ii) >= split_row ? 1 : 0);
2127   ps->max_cycle = ps->max_cycle + ps->max_cycle / ii
2128     + (SMODULO (ps->max_cycle, ii) >= split_row ? 1 : 0);
2129   free (ps->rows);
2130   ps->rows = rows_new;
2131   free (ps->rows_length);
2132   ps->rows_length = rows_length_new;
2133   ps->ii = new_ii;
2134   gcc_assert (ps->min_cycle >= 0);
2135
2136   verify_partial_schedule (ps, sched_nodes);
2137
2138   if (dump_file)
2139     fprintf (dump_file, "min_cycle=%d, max_cycle=%d\n", ps->min_cycle,
2140              ps->max_cycle);
2141 }
2142
2143 /* Given U_NODE which is the node that failed to be scheduled; LOW and
2144    UP which are the boundaries of it's scheduling window; compute using
2145    SCHED_NODES and II a row in the partial schedule that can be split
2146    which will separate a critical predecessor from a critical successor
2147    thereby expanding the window, and return it.  */
2148 static int
2149 compute_split_row (sbitmap sched_nodes, int low, int up, int ii,
2150                    ddg_node_ptr u_node)
2151 {
2152   ddg_edge_ptr e;
2153   int lower = INT_MIN, upper = INT_MAX;
2154   ddg_node_ptr crit_pred = NULL;
2155   ddg_node_ptr crit_succ = NULL;
2156   int crit_cycle;
2157
2158   for (e = u_node->in; e != 0; e = e->next_in)
2159     {
2160       ddg_node_ptr v_node = e->src;
2161
2162       if (TEST_BIT (sched_nodes, v_node->cuid)
2163           && (low == SCHED_TIME (v_node) + e->latency - (e->distance * ii)))
2164         if (SCHED_TIME (v_node) > lower)
2165           {
2166             crit_pred = v_node;
2167             lower = SCHED_TIME (v_node);
2168           }
2169     }
2170
2171   if (crit_pred != NULL)
2172     {
2173       crit_cycle = SCHED_TIME (crit_pred) + 1;
2174       return SMODULO (crit_cycle, ii);
2175     }
2176
2177   for (e = u_node->out; e != 0; e = e->next_out)
2178     {
2179       ddg_node_ptr v_node = e->dest;
2180       if (TEST_BIT (sched_nodes, v_node->cuid)
2181           && (up == SCHED_TIME (v_node) - e->latency + (e->distance * ii)))
2182         if (SCHED_TIME (v_node) < upper)
2183           {
2184             crit_succ = v_node;
2185             upper = SCHED_TIME (v_node);
2186           }
2187     }
2188
2189   if (crit_succ != NULL)
2190     {
2191       crit_cycle = SCHED_TIME (crit_succ);
2192       return SMODULO (crit_cycle, ii);
2193     }
2194
2195   if (dump_file)
2196     fprintf (dump_file, "Both crit_pred and crit_succ are NULL\n");
2197
2198   return SMODULO ((low + up + 1) / 2, ii);
2199 }
2200
2201 static void
2202 verify_partial_schedule (partial_schedule_ptr ps, sbitmap sched_nodes)
2203 {
2204   int row;
2205   ps_insn_ptr crr_insn;
2206
2207   for (row = 0; row < ps->ii; row++)
2208     {
2209       int length = 0;
2210       
2211       for (crr_insn = ps->rows[row]; crr_insn; crr_insn = crr_insn->next_in_row)
2212         {
2213           ddg_node_ptr u = crr_insn->node;
2214           
2215           length++;
2216           gcc_assert (TEST_BIT (sched_nodes, u->cuid));
2217           /* ??? Test also that all nodes of sched_nodes are in ps, perhaps by
2218              popcount (sched_nodes) == number of insns in ps.  */
2219           gcc_assert (SCHED_TIME (u) >= ps->min_cycle);
2220           gcc_assert (SCHED_TIME (u) <= ps->max_cycle);
2221         }
2222       
2223       gcc_assert (ps->rows_length[row] == length);
2224     }
2225 }
2226
2227 \f
2228 /* This page implements the algorithm for ordering the nodes of a DDG
2229    for modulo scheduling, activated through the
2230    "int sms_order_nodes (ddg_ptr, int mii, int * result)" API.  */
2231
2232 #define ORDER_PARAMS(x) ((struct node_order_params *) (x)->aux.info)
2233 #define ASAP(x) (ORDER_PARAMS ((x))->asap)
2234 #define ALAP(x) (ORDER_PARAMS ((x))->alap)
2235 #define HEIGHT(x) (ORDER_PARAMS ((x))->height)
2236 #define MOB(x) (ALAP ((x)) - ASAP ((x)))
2237 #define DEPTH(x) (ASAP ((x)))
2238
2239 typedef struct node_order_params * nopa;
2240
2241 static void order_nodes_of_sccs (ddg_all_sccs_ptr, int * result);
2242 static int order_nodes_in_scc (ddg_ptr, sbitmap, sbitmap, int*, int);
2243 static nopa  calculate_order_params (ddg_ptr, int, int *);
2244 static int find_max_asap (ddg_ptr, sbitmap);
2245 static int find_max_hv_min_mob (ddg_ptr, sbitmap);
2246 static int find_max_dv_min_mob (ddg_ptr, sbitmap);
2247
2248 enum sms_direction {BOTTOMUP, TOPDOWN};
2249
2250 struct node_order_params
2251 {
2252   int asap;
2253   int alap;
2254   int height;
2255 };
2256
2257 /* Check if NODE_ORDER contains a permutation of 0 .. NUM_NODES-1.  */
2258 static void
2259 check_nodes_order (int *node_order, int num_nodes)
2260 {
2261   int i;
2262   sbitmap tmp = sbitmap_alloc (num_nodes);
2263
2264   sbitmap_zero (tmp);
2265
2266   if (dump_file)
2267     fprintf (dump_file, "SMS final nodes order: \n");
2268
2269   for (i = 0; i < num_nodes; i++)
2270     {
2271       int u = node_order[i];
2272
2273       if (dump_file)
2274         fprintf (dump_file, "%d ", u);
2275       gcc_assert (u < num_nodes && u >= 0 && !TEST_BIT (tmp, u));
2276
2277       SET_BIT (tmp, u);
2278     }
2279
2280   if (dump_file)
2281     fprintf (dump_file, "\n");
2282
2283   sbitmap_free (tmp);
2284 }
2285
2286 /* Order the nodes of G for scheduling and pass the result in
2287    NODE_ORDER.  Also set aux.count of each node to ASAP.
2288    Put maximal ASAP to PMAX_ASAP.  Return the recMII for the given DDG.  */
2289 static int
2290 sms_order_nodes (ddg_ptr g, int mii, int * node_order, int *pmax_asap)
2291 {
2292   int i;
2293   int rec_mii = 0;
2294   ddg_all_sccs_ptr sccs = create_ddg_all_sccs (g);
2295
2296   nopa nops = calculate_order_params (g, mii, pmax_asap);
2297
2298   if (dump_file)
2299     print_sccs (dump_file, sccs, g);
2300
2301   order_nodes_of_sccs (sccs, node_order);
2302
2303   if (sccs->num_sccs > 0)
2304     /* First SCC has the largest recurrence_length.  */
2305     rec_mii = sccs->sccs[0]->recurrence_length;
2306
2307   /* Save ASAP before destroying node_order_params.  */
2308   for (i = 0; i < g->num_nodes; i++)
2309     {
2310       ddg_node_ptr v = &g->nodes[i];
2311       v->aux.count = ASAP (v);
2312     }
2313
2314   free (nops);
2315   free_ddg_all_sccs (sccs);
2316   check_nodes_order (node_order, g->num_nodes);
2317
2318   return rec_mii;
2319 }
2320
2321 static void
2322 order_nodes_of_sccs (ddg_all_sccs_ptr all_sccs, int * node_order)
2323 {
2324   int i, pos = 0;
2325   ddg_ptr g = all_sccs->ddg;
2326   int num_nodes = g->num_nodes;
2327   sbitmap prev_sccs = sbitmap_alloc (num_nodes);
2328   sbitmap on_path = sbitmap_alloc (num_nodes);
2329   sbitmap tmp = sbitmap_alloc (num_nodes);
2330   sbitmap ones = sbitmap_alloc (num_nodes);
2331
2332   sbitmap_zero (prev_sccs);
2333   sbitmap_ones (ones);
2334
2335   /* Perform the node ordering starting from the SCC with the highest recMII.
2336      For each SCC order the nodes according to their ASAP/ALAP/HEIGHT etc.  */
2337   for (i = 0; i < all_sccs->num_sccs; i++)
2338     {
2339       ddg_scc_ptr scc = all_sccs->sccs[i];
2340
2341       /* Add nodes on paths from previous SCCs to the current SCC.  */
2342       find_nodes_on_paths (on_path, g, prev_sccs, scc->nodes);
2343       sbitmap_a_or_b (tmp, scc->nodes, on_path);
2344
2345       /* Add nodes on paths from the current SCC to previous SCCs.  */
2346       find_nodes_on_paths (on_path, g, scc->nodes, prev_sccs);
2347       sbitmap_a_or_b (tmp, tmp, on_path);
2348
2349       /* Remove nodes of previous SCCs from current extended SCC.  */
2350       sbitmap_difference (tmp, tmp, prev_sccs);
2351
2352       pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2353       /* Above call to order_nodes_in_scc updated prev_sccs |= tmp.  */
2354     }
2355
2356   /* Handle the remaining nodes that do not belong to any scc.  Each call
2357      to order_nodes_in_scc handles a single connected component.  */
2358   while (pos < g->num_nodes)
2359     {
2360       sbitmap_difference (tmp, ones, prev_sccs);
2361       pos = order_nodes_in_scc (g, prev_sccs, tmp, node_order, pos);
2362     }
2363   sbitmap_free (prev_sccs);
2364   sbitmap_free (on_path);
2365   sbitmap_free (tmp);
2366   sbitmap_free (ones);
2367 }
2368
2369 /* MII is needed if we consider backarcs (that do not close recursive cycles).  */
2370 static struct node_order_params *
2371 calculate_order_params (ddg_ptr g, int mii ATTRIBUTE_UNUSED, int *pmax_asap)
2372 {
2373   int u;
2374   int max_asap;
2375   int num_nodes = g->num_nodes;
2376   ddg_edge_ptr e;
2377   /* Allocate a place to hold ordering params for each node in the DDG.  */
2378   nopa node_order_params_arr;
2379
2380   /* Initialize of ASAP/ALAP/HEIGHT to zero.  */
2381   node_order_params_arr = (nopa) xcalloc (num_nodes,
2382                                           sizeof (struct node_order_params));
2383
2384   /* Set the aux pointer of each node to point to its order_params structure.  */
2385   for (u = 0; u < num_nodes; u++)
2386     g->nodes[u].aux.info = &node_order_params_arr[u];
2387
2388   /* Disregarding a backarc from each recursive cycle to obtain a DAG,
2389      calculate ASAP, ALAP, mobility, distance, and height for each node
2390      in the dependence (direct acyclic) graph.  */
2391
2392   /* We assume that the nodes in the array are in topological order.  */
2393
2394   max_asap = 0;
2395   for (u = 0; u < num_nodes; u++)
2396     {
2397       ddg_node_ptr u_node = &g->nodes[u];
2398
2399       ASAP (u_node) = 0;
2400       for (e = u_node->in; e; e = e->next_in)
2401         if (e->distance == 0)
2402           ASAP (u_node) = MAX (ASAP (u_node),
2403                                ASAP (e->src) + e->latency);
2404       max_asap = MAX (max_asap, ASAP (u_node));
2405     }
2406
2407   for (u = num_nodes - 1; u > -1; u--)
2408     {
2409       ddg_node_ptr u_node = &g->nodes[u];
2410
2411       ALAP (u_node) = max_asap;
2412       HEIGHT (u_node) = 0;
2413       for (e = u_node->out; e; e = e->next_out)
2414         if (e->distance == 0)
2415           {
2416             ALAP (u_node) = MIN (ALAP (u_node),
2417                                  ALAP (e->dest) - e->latency);
2418             HEIGHT (u_node) = MAX (HEIGHT (u_node),
2419                                    HEIGHT (e->dest) + e->latency);
2420           }
2421     }
2422   if (dump_file)
2423   {
2424     fprintf (dump_file, "\nOrder params\n");
2425     for (u = 0; u < num_nodes; u++)
2426       {
2427         ddg_node_ptr u_node = &g->nodes[u];
2428
2429         fprintf (dump_file, "node %d, ASAP: %d, ALAP: %d, HEIGHT: %d\n", u,
2430                  ASAP (u_node), ALAP (u_node), HEIGHT (u_node));
2431       }
2432   }
2433
2434   *pmax_asap = max_asap;
2435   return node_order_params_arr;
2436 }
2437
2438 static int
2439 find_max_asap (ddg_ptr g, sbitmap nodes)
2440 {
2441   unsigned int u = 0;
2442   int max_asap = -1;
2443   int result = -1;
2444   sbitmap_iterator sbi;
2445
2446   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2447     {
2448       ddg_node_ptr u_node = &g->nodes[u];
2449
2450       if (max_asap < ASAP (u_node))
2451         {
2452           max_asap = ASAP (u_node);
2453           result = u;
2454         }
2455     }
2456   return result;
2457 }
2458
2459 static int
2460 find_max_hv_min_mob (ddg_ptr g, sbitmap nodes)
2461 {
2462   unsigned int u = 0;
2463   int max_hv = -1;
2464   int min_mob = INT_MAX;
2465   int result = -1;
2466   sbitmap_iterator sbi;
2467
2468   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2469     {
2470       ddg_node_ptr u_node = &g->nodes[u];
2471
2472       if (max_hv < HEIGHT (u_node))
2473         {
2474           max_hv = HEIGHT (u_node);
2475           min_mob = MOB (u_node);
2476           result = u;
2477         }
2478       else if ((max_hv == HEIGHT (u_node))
2479                && (min_mob > MOB (u_node)))
2480         {
2481           min_mob = MOB (u_node);
2482           result = u;
2483         }
2484     }
2485   return result;
2486 }
2487
2488 static int
2489 find_max_dv_min_mob (ddg_ptr g, sbitmap nodes)
2490 {
2491   unsigned int u = 0;
2492   int max_dv = -1;
2493   int min_mob = INT_MAX;
2494   int result = -1;
2495   sbitmap_iterator sbi;
2496
2497   EXECUTE_IF_SET_IN_SBITMAP (nodes, 0, u, sbi)
2498     {
2499       ddg_node_ptr u_node = &g->nodes[u];
2500
2501       if (max_dv < DEPTH (u_node))
2502         {
2503           max_dv = DEPTH (u_node);
2504           min_mob = MOB (u_node);
2505           result = u;
2506         }
2507       else if ((max_dv == DEPTH (u_node))
2508                && (min_mob > MOB (u_node)))
2509         {
2510           min_mob = MOB (u_node);
2511           result = u;
2512         }
2513     }
2514   return result;
2515 }
2516
2517 /* Places the nodes of SCC into the NODE_ORDER array starting
2518    at position POS, according to the SMS ordering algorithm.
2519    NODES_ORDERED (in&out parameter) holds the bitset of all nodes in
2520    the NODE_ORDER array, starting from position zero.  */
2521 static int
2522 order_nodes_in_scc (ddg_ptr g, sbitmap nodes_ordered, sbitmap scc,
2523                     int * node_order, int pos)
2524 {
2525   enum sms_direction dir;
2526   int num_nodes = g->num_nodes;
2527   sbitmap workset = sbitmap_alloc (num_nodes);
2528   sbitmap tmp = sbitmap_alloc (num_nodes);
2529   sbitmap zero_bitmap = sbitmap_alloc (num_nodes);
2530   sbitmap predecessors = sbitmap_alloc (num_nodes);
2531   sbitmap successors = sbitmap_alloc (num_nodes);
2532
2533   sbitmap_zero (predecessors);
2534   find_predecessors (predecessors, g, nodes_ordered);
2535
2536   sbitmap_zero (successors);
2537   find_successors (successors, g, nodes_ordered);
2538
2539   sbitmap_zero (tmp);
2540   if (sbitmap_a_and_b_cg (tmp, predecessors, scc))
2541     {
2542       sbitmap_copy (workset, tmp);
2543       dir = BOTTOMUP;
2544     }
2545   else if (sbitmap_a_and_b_cg (tmp, successors, scc))
2546     {
2547       sbitmap_copy (workset, tmp);
2548       dir = TOPDOWN;
2549     }
2550   else
2551     {
2552       int u;
2553
2554       sbitmap_zero (workset);
2555       if ((u = find_max_asap (g, scc)) >= 0)
2556         SET_BIT (workset, u);
2557       dir = BOTTOMUP;
2558     }
2559
2560   sbitmap_zero (zero_bitmap);
2561   while (!sbitmap_equal (workset, zero_bitmap))
2562     {
2563       int v;
2564       ddg_node_ptr v_node;
2565       sbitmap v_node_preds;
2566       sbitmap v_node_succs;
2567
2568       if (dir == TOPDOWN)
2569         {
2570           while (!sbitmap_equal (workset, zero_bitmap))
2571             {
2572               v = find_max_hv_min_mob (g, workset);
2573               v_node = &g->nodes[v];
2574               node_order[pos++] = v;
2575               v_node_succs = NODE_SUCCESSORS (v_node);
2576               sbitmap_a_and_b (tmp, v_node_succs, scc);
2577
2578               /* Don't consider the already ordered successors again.  */
2579               sbitmap_difference (tmp, tmp, nodes_ordered);
2580               sbitmap_a_or_b (workset, workset, tmp);
2581               RESET_BIT (workset, v);
2582               SET_BIT (nodes_ordered, v);
2583             }
2584           dir = BOTTOMUP;
2585           sbitmap_zero (predecessors);
2586           find_predecessors (predecessors, g, nodes_ordered);
2587           sbitmap_a_and_b (workset, predecessors, scc);
2588         }
2589       else
2590         {
2591           while (!sbitmap_equal (workset, zero_bitmap))
2592             {
2593               v = find_max_dv_min_mob (g, workset);
2594               v_node = &g->nodes[v];
2595               node_order[pos++] = v;
2596               v_node_preds = NODE_PREDECESSORS (v_node);
2597               sbitmap_a_and_b (tmp, v_node_preds, scc);
2598
2599               /* Don't consider the already ordered predecessors again.  */
2600               sbitmap_difference (tmp, tmp, nodes_ordered);
2601               sbitmap_a_or_b (workset, workset, tmp);
2602               RESET_BIT (workset, v);
2603               SET_BIT (nodes_ordered, v);
2604             }
2605           dir = TOPDOWN;
2606           sbitmap_zero (successors);
2607           find_successors (successors, g, nodes_ordered);
2608           sbitmap_a_and_b (workset, successors, scc);
2609         }
2610     }
2611   sbitmap_free (tmp);
2612   sbitmap_free (workset);
2613   sbitmap_free (zero_bitmap);
2614   sbitmap_free (predecessors);
2615   sbitmap_free (successors);
2616   return pos;
2617 }
2618
2619 \f
2620 /* This page contains functions for manipulating partial-schedules during
2621    modulo scheduling.  */
2622
2623 /* Create a partial schedule and allocate a memory to hold II rows.  */
2624
2625 static partial_schedule_ptr
2626 create_partial_schedule (int ii, ddg_ptr g, int history)
2627 {
2628   partial_schedule_ptr ps = XNEW (struct partial_schedule);
2629   ps->rows = (ps_insn_ptr *) xcalloc (ii, sizeof (ps_insn_ptr));
2630   ps->rows_length = (int *) xcalloc (ii, sizeof (int));
2631   ps->ii = ii;
2632   ps->history = history;
2633   ps->min_cycle = INT_MAX;
2634   ps->max_cycle = INT_MIN;
2635   ps->g = g;
2636
2637   return ps;
2638 }
2639
2640 /* Free the PS_INSNs in rows array of the given partial schedule.
2641    ??? Consider caching the PS_INSN's.  */
2642 static void
2643 free_ps_insns (partial_schedule_ptr ps)
2644 {
2645   int i;
2646
2647   for (i = 0; i < ps->ii; i++)
2648     {
2649       while (ps->rows[i])
2650         {
2651           ps_insn_ptr ps_insn = ps->rows[i]->next_in_row;
2652
2653           free (ps->rows[i]);
2654           ps->rows[i] = ps_insn;
2655         }
2656       ps->rows[i] = NULL;
2657     }
2658 }
2659
2660 /* Free all the memory allocated to the partial schedule.  */
2661
2662 static void
2663 free_partial_schedule (partial_schedule_ptr ps)
2664 {
2665   if (!ps)
2666     return;
2667   free_ps_insns (ps);
2668   free (ps->rows);
2669   free (ps->rows_length);
2670   free (ps);
2671 }
2672
2673 /* Clear the rows array with its PS_INSNs, and create a new one with
2674    NEW_II rows.  */
2675
2676 static void
2677 reset_partial_schedule (partial_schedule_ptr ps, int new_ii)
2678 {
2679   if (!ps)
2680     return;
2681   free_ps_insns (ps);
2682   if (new_ii == ps->ii)
2683     return;
2684   ps->rows = (ps_insn_ptr *) xrealloc (ps->rows, new_ii
2685                                                  * sizeof (ps_insn_ptr));
2686   memset (ps->rows, 0, new_ii * sizeof (ps_insn_ptr));
2687   ps->rows_length = (int *) xrealloc (ps->rows_length, new_ii * sizeof (int));
2688   memset (ps->rows_length, 0, new_ii * sizeof (int));
2689   ps->ii = new_ii;
2690   ps->min_cycle = INT_MAX;
2691   ps->max_cycle = INT_MIN;
2692 }
2693
2694 /* Prints the partial schedule as an ii rows array, for each rows
2695    print the ids of the insns in it.  */
2696 void
2697 print_partial_schedule (partial_schedule_ptr ps, FILE *dump)
2698 {
2699   int i;
2700
2701   for (i = 0; i < ps->ii; i++)
2702     {
2703       ps_insn_ptr ps_i = ps->rows[i];
2704
2705       fprintf (dump, "\n[ROW %d ]: ", i);
2706       while (ps_i)
2707         {
2708           if (JUMP_P (ps_i->node->insn))
2709             fprintf (dump, "%d (branch), ",
2710                      INSN_UID (ps_i->node->insn));
2711           else
2712             fprintf (dump, "%d, ",
2713                      INSN_UID (ps_i->node->insn));
2714         
2715           ps_i = ps_i->next_in_row;
2716         }
2717     }
2718 }
2719
2720 /* Creates an object of PS_INSN and initializes it to the given parameters.  */
2721 static ps_insn_ptr
2722 create_ps_insn (ddg_node_ptr node, int cycle)
2723 {
2724   ps_insn_ptr ps_i = XNEW (struct ps_insn);
2725
2726   ps_i->node = node;
2727   ps_i->next_in_row = NULL;
2728   ps_i->prev_in_row = NULL;
2729   ps_i->cycle = cycle;
2730
2731   return ps_i;
2732 }
2733
2734
2735 /* Removes the given PS_INSN from the partial schedule.  */  
2736 static void 
2737 remove_node_from_ps (partial_schedule_ptr ps, ps_insn_ptr ps_i)
2738 {
2739   int row;
2740
2741   gcc_assert (ps && ps_i);
2742   
2743   row = SMODULO (ps_i->cycle, ps->ii);
2744   if (! ps_i->prev_in_row)
2745     {
2746       gcc_assert (ps_i == ps->rows[row]);
2747       ps->rows[row] = ps_i->next_in_row;
2748       if (ps->rows[row])
2749         ps->rows[row]->prev_in_row = NULL;
2750     }
2751   else
2752     {
2753       ps_i->prev_in_row->next_in_row = ps_i->next_in_row;
2754       if (ps_i->next_in_row)
2755         ps_i->next_in_row->prev_in_row = ps_i->prev_in_row;
2756     }
2757    
2758   ps->rows_length[row] -= 1; 
2759   free (ps_i);
2760   return;
2761 }
2762
2763 /* Unlike what literature describes for modulo scheduling (which focuses
2764    on VLIW machines) the order of the instructions inside a cycle is
2765    important.  Given the bitmaps MUST_FOLLOW and MUST_PRECEDE we know
2766    where the current instruction should go relative to the already
2767    scheduled instructions in the given cycle.  Go over these
2768    instructions and find the first possible column to put it in.  */
2769 static bool
2770 ps_insn_find_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2771                      sbitmap must_precede, sbitmap must_follow)
2772 {
2773   ps_insn_ptr next_ps_i;
2774   ps_insn_ptr first_must_follow = NULL;
2775   ps_insn_ptr last_must_precede = NULL;
2776   ps_insn_ptr last_in_row = NULL;
2777   int row;
2778
2779   if (! ps_i)
2780     return false;
2781
2782   row = SMODULO (ps_i->cycle, ps->ii);
2783
2784   /* Find the first must follow and the last must precede
2785      and insert the node immediately after the must precede
2786      but make sure that it there is no must follow after it.  */
2787   for (next_ps_i = ps->rows[row];
2788        next_ps_i;
2789        next_ps_i = next_ps_i->next_in_row)
2790     {
2791       if (must_follow && TEST_BIT (must_follow, next_ps_i->node->cuid)
2792           && ! first_must_follow)
2793         first_must_follow = next_ps_i;
2794       if (must_precede && TEST_BIT (must_precede, next_ps_i->node->cuid))
2795         {
2796           /* If we have already met a node that must follow, then
2797              there is no possible column.  */
2798           if (first_must_follow)
2799             return false;
2800           else
2801             last_must_precede = next_ps_i;
2802         }
2803       /* The closing branch must be the last in the row.  */
2804       if (must_precede 
2805           && TEST_BIT (must_precede, next_ps_i->node->cuid) 
2806           && JUMP_P (next_ps_i->node->insn))     
2807         return false;
2808              
2809        last_in_row = next_ps_i;
2810     }
2811
2812   /* The closing branch is scheduled as well.  Make sure there is no
2813      dependent instruction after it as the branch should be the last
2814      instruction in the row.  */
2815   if (JUMP_P (ps_i->node->insn)) 
2816     {
2817       if (first_must_follow)
2818         return false;
2819       if (last_in_row)
2820         {
2821           /* Make the branch the last in the row.  New instructions
2822              will be inserted at the beginning of the row or after the
2823              last must_precede instruction thus the branch is guaranteed
2824              to remain the last instruction in the row.  */
2825           last_in_row->next_in_row = ps_i;
2826           ps_i->prev_in_row = last_in_row;
2827           ps_i->next_in_row = NULL;
2828         }
2829       else
2830         ps->rows[row] = ps_i;
2831       return true;
2832     }
2833   
2834   /* Now insert the node after INSERT_AFTER_PSI.  */
2835
2836   if (! last_must_precede)
2837     {
2838       ps_i->next_in_row = ps->rows[row];
2839       ps_i->prev_in_row = NULL;
2840       if (ps_i->next_in_row)
2841         ps_i->next_in_row->prev_in_row = ps_i;
2842       ps->rows[row] = ps_i;
2843     }
2844   else
2845     {
2846       ps_i->next_in_row = last_must_precede->next_in_row;
2847       last_must_precede->next_in_row = ps_i;
2848       ps_i->prev_in_row = last_must_precede;
2849       if (ps_i->next_in_row)
2850         ps_i->next_in_row->prev_in_row = ps_i;
2851     }
2852
2853   return true;
2854 }
2855
2856 /* Advances the PS_INSN one column in its current row; returns false
2857    in failure and true in success.  Bit N is set in MUST_FOLLOW if
2858    the node with cuid N must be come after the node pointed to by
2859    PS_I when scheduled in the same cycle.  */
2860 static int
2861 ps_insn_advance_column (partial_schedule_ptr ps, ps_insn_ptr ps_i,
2862                         sbitmap must_follow)
2863 {
2864   ps_insn_ptr prev, next;
2865   int row;
2866   ddg_node_ptr next_node;
2867
2868   if (!ps || !ps_i)
2869     return false;
2870
2871   row = SMODULO (ps_i->cycle, ps->ii);
2872
2873   if (! ps_i->next_in_row)
2874     return false;
2875
2876   next_node = ps_i->next_in_row->node;
2877
2878   /* Check if next_in_row is dependent on ps_i, both having same sched
2879      times (typically ANTI_DEP).  If so, ps_i cannot skip over it.  */
2880   if (must_follow && TEST_BIT (must_follow, next_node->cuid))
2881     return false;
2882
2883   /* Advance PS_I over its next_in_row in the doubly linked list.  */
2884   prev = ps_i->prev_in_row;
2885   next = ps_i->next_in_row;
2886
2887   if (ps_i == ps->rows[row])
2888     ps->rows[row] = next;
2889
2890   ps_i->next_in_row = next->next_in_row;
2891
2892   if (next->next_in_row)
2893     next->next_in_row->prev_in_row = ps_i;
2894
2895   next->next_in_row = ps_i;
2896   ps_i->prev_in_row = next;
2897
2898   next->prev_in_row = prev;
2899   if (prev)
2900     prev->next_in_row = next;
2901
2902   return true;
2903 }
2904
2905 /* Inserts a DDG_NODE to the given partial schedule at the given cycle.
2906    Returns 0 if this is not possible and a PS_INSN otherwise.  Bit N is
2907    set in MUST_PRECEDE/MUST_FOLLOW if the node with cuid N must be come
2908    before/after (respectively) the node pointed to by PS_I when scheduled
2909    in the same cycle.  */
2910 static ps_insn_ptr
2911 add_node_to_ps (partial_schedule_ptr ps, ddg_node_ptr node, int cycle,
2912                 sbitmap must_precede, sbitmap must_follow)
2913 {
2914   ps_insn_ptr ps_i;
2915   int row = SMODULO (cycle, ps->ii);
2916
2917   if (ps->rows_length[row] >= issue_rate)
2918     return NULL;
2919
2920   ps_i = create_ps_insn (node, cycle);
2921
2922   /* Finds and inserts PS_I according to MUST_FOLLOW and
2923      MUST_PRECEDE.  */
2924   if (! ps_insn_find_column (ps, ps_i, must_precede, must_follow))
2925     {
2926       free (ps_i);
2927       return NULL;
2928     }
2929
2930   ps->rows_length[row] += 1;
2931   return ps_i;
2932 }
2933
2934 /* Advance time one cycle.  Assumes DFA is being used.  */
2935 static void
2936 advance_one_cycle (void)
2937 {
2938   if (targetm.sched.dfa_pre_cycle_insn)
2939     state_transition (curr_state,
2940                       targetm.sched.dfa_pre_cycle_insn ());
2941
2942   state_transition (curr_state, NULL);
2943
2944   if (targetm.sched.dfa_post_cycle_insn)
2945     state_transition (curr_state,
2946                       targetm.sched.dfa_post_cycle_insn ());
2947 }
2948
2949
2950
2951 /* Checks if PS has resource conflicts according to DFA, starting from
2952    FROM cycle to TO cycle; returns true if there are conflicts and false
2953    if there are no conflicts.  Assumes DFA is being used.  */
2954 static int
2955 ps_has_conflicts (partial_schedule_ptr ps, int from, int to)
2956 {
2957   int cycle;
2958
2959   state_reset (curr_state);
2960
2961   for (cycle = from; cycle <= to; cycle++)
2962     {
2963       ps_insn_ptr crr_insn;
2964       /* Holds the remaining issue slots in the current row.  */
2965       int can_issue_more = issue_rate;
2966
2967       /* Walk through the DFA for the current row.  */
2968       for (crr_insn = ps->rows[SMODULO (cycle, ps->ii)];
2969            crr_insn;
2970            crr_insn = crr_insn->next_in_row)
2971         {
2972           rtx insn = crr_insn->node->insn;
2973
2974           if (!NONDEBUG_INSN_P (insn))
2975             continue;
2976
2977           /* Check if there is room for the current insn.  */
2978           if (!can_issue_more || state_dead_lock_p (curr_state))
2979             return true;
2980
2981           /* Update the DFA state and return with failure if the DFA found
2982              resource conflicts.  */
2983           if (state_transition (curr_state, insn) >= 0)
2984             return true;
2985
2986           if (targetm.sched.variable_issue)
2987             can_issue_more =
2988               targetm.sched.variable_issue (sched_dump, sched_verbose,
2989                                             insn, can_issue_more);
2990           /* A naked CLOBBER or USE generates no instruction, so don't
2991              let them consume issue slots.  */
2992           else if (GET_CODE (PATTERN (insn)) != USE
2993                    && GET_CODE (PATTERN (insn)) != CLOBBER)
2994             can_issue_more--;
2995         }
2996
2997       /* Advance the DFA to the next cycle.  */
2998       advance_one_cycle ();
2999     }
3000   return false;
3001 }
3002
3003 /* Checks if the given node causes resource conflicts when added to PS at
3004    cycle C.  If not the node is added to PS and returned; otherwise zero
3005    is returned.  Bit N is set in MUST_PRECEDE/MUST_FOLLOW if the node with
3006    cuid N must be come before/after (respectively) the node pointed to by
3007    PS_I when scheduled in the same cycle.  */
3008 ps_insn_ptr
3009 ps_add_node_check_conflicts (partial_schedule_ptr ps, ddg_node_ptr n,
3010                              int c, sbitmap must_precede,
3011                              sbitmap must_follow)
3012 {
3013   int has_conflicts = 0;
3014   ps_insn_ptr ps_i;
3015
3016   /* First add the node to the PS, if this succeeds check for
3017      conflicts, trying different issue slots in the same row.  */
3018   if (! (ps_i = add_node_to_ps (ps, n, c, must_precede, must_follow)))
3019     return NULL; /* Failed to insert the node at the given cycle.  */
3020
3021   has_conflicts = ps_has_conflicts (ps, c, c)
3022                   || (ps->history > 0
3023                       && ps_has_conflicts (ps,
3024                                            c - ps->history,
3025                                            c + ps->history));
3026
3027   /* Try different issue slots to find one that the given node can be
3028      scheduled in without conflicts.  */
3029   while (has_conflicts)
3030     {
3031       if (! ps_insn_advance_column (ps, ps_i, must_follow))
3032         break;
3033       has_conflicts = ps_has_conflicts (ps, c, c)
3034                       || (ps->history > 0
3035                           && ps_has_conflicts (ps,
3036                                                c - ps->history,
3037                                                c + ps->history));
3038     }
3039
3040   if (has_conflicts)
3041     {
3042       remove_node_from_ps (ps, ps_i);
3043       return NULL;
3044     }
3045
3046   ps->min_cycle = MIN (ps->min_cycle, c);
3047   ps->max_cycle = MAX (ps->max_cycle, c);
3048   return ps_i;
3049 }
3050
3051 /* Calculate the stage count of the partial schedule PS.  The calculation
3052    takes into account the rotation amount passed in ROTATION_AMOUNT.  */
3053 int
3054 calculate_stage_count (partial_schedule_ptr ps, int rotation_amount)
3055 {
3056   int new_min_cycle = PS_MIN_CYCLE (ps) - rotation_amount;
3057   int new_max_cycle = PS_MAX_CYCLE (ps) - rotation_amount;
3058   int stage_count = CALC_STAGE_COUNT (-1, new_min_cycle, ps->ii);
3059
3060   /* The calculation of stage count is done adding the number of stages
3061      before cycle zero and after cycle zero.  */ 
3062   stage_count += CALC_STAGE_COUNT (new_max_cycle, 0, ps->ii);
3063
3064   return stage_count;
3065 }
3066
3067 /* Rotate the rows of PS such that insns scheduled at time
3068    START_CYCLE will appear in row 0.  Updates max/min_cycles.  */
3069 void
3070 rotate_partial_schedule (partial_schedule_ptr ps, int start_cycle)
3071 {
3072   int i, row, backward_rotates;
3073   int last_row = ps->ii - 1;
3074
3075   if (start_cycle == 0)
3076     return;
3077
3078   backward_rotates = SMODULO (start_cycle, ps->ii);
3079
3080   /* Revisit later and optimize this into a single loop.  */
3081   for (i = 0; i < backward_rotates; i++)
3082     {
3083       ps_insn_ptr first_row = ps->rows[0];
3084       int first_row_length = ps->rows_length[0];
3085
3086       for (row = 0; row < last_row; row++)
3087         {
3088           ps->rows[row] = ps->rows[row + 1];
3089           ps->rows_length[row] = ps->rows_length[row + 1]; 
3090         }
3091
3092       ps->rows[last_row] = first_row;
3093       ps->rows_length[last_row] = first_row_length;
3094     }
3095
3096   ps->max_cycle -= start_cycle;
3097   ps->min_cycle -= start_cycle;
3098 }
3099
3100 #endif /* INSN_SCHEDULING */
3101 \f
3102 static bool
3103 gate_handle_sms (void)
3104 {
3105   return (optimize > 0 && flag_modulo_sched);
3106 }
3107
3108
3109 /* Run instruction scheduler.  */
3110 /* Perform SMS module scheduling.  */
3111 static unsigned int
3112 rest_of_handle_sms (void)
3113 {
3114 #ifdef INSN_SCHEDULING
3115   basic_block bb;
3116
3117   /* Collect loop information to be used in SMS.  */
3118   cfg_layout_initialize (0);
3119   sms_schedule ();
3120
3121   /* Update the life information, because we add pseudos.  */
3122   max_regno = max_reg_num ();
3123
3124   /* Finalize layout changes.  */
3125   FOR_EACH_BB (bb)
3126     if (bb->next_bb != EXIT_BLOCK_PTR)
3127       bb->aux = bb->next_bb;
3128   free_dominance_info (CDI_DOMINATORS);
3129   cfg_layout_finalize ();
3130 #endif /* INSN_SCHEDULING */
3131   return 0;
3132 }
3133
3134 struct rtl_opt_pass pass_sms =
3135 {
3136  {
3137   RTL_PASS,
3138   "sms",                                /* name */
3139   gate_handle_sms,                      /* gate */
3140   rest_of_handle_sms,                   /* execute */
3141   NULL,                                 /* sub */
3142   NULL,                                 /* next */
3143   0,                                    /* static_pass_number */
3144   TV_SMS,                               /* tv_id */
3145   0,                                    /* properties_required */
3146   0,                                    /* properties_provided */
3147   0,                                    /* properties_destroyed */
3148   0,                                    /* todo_flags_start */
3149   TODO_df_finish
3150     | TODO_verify_flow
3151     | TODO_verify_rtl_sharing
3152     | TODO_ggc_collect                  /* todo_flags_finish */
3153  }
3154 };