OSDN Git Service

(find_splittable_givs): recog_memoized failure return is -1 not 0.
[pf3gnuchains/gcc-fork.git] / gcc / unroll.c
1 /* Try to unroll loops, and split induction variables.
2    Copyright (C) 1992 Free Software Foundation, Inc.
3    Contributed by James E. Wilson, Cygnus Support/UC Berkeley.
4
5 This file is part of GNU CC.
6
7 GNU CC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU CC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU CC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 /* Try to unroll a loop, and split induction variables.
22
23    Loops for which the number of iterations can be calculated exactly are
24    handled specially.  If the number of iterations times the insn_count is
25    less than MAX_UNROLLED_INSNS, then the loop is unrolled completely.
26    Otherwise, we try to unroll the loop a number of times modulo the number
27    of iterations, so that only one exit test will be needed.  It is unrolled
28    a number of times approximately equal to MAX_UNROLLED_INSNS divided by
29    the insn count.
30
31    Otherwise, if the number of iterations can be calculated exactly at
32    run time, and the loop is always entered at the top, then we try to
33    precondition the loop.  That is, at run time, calculate how many times
34    the loop will execute, and then execute the loop body a few times so
35    that the remaining iterations will be some multiple of 4 (or 2 if the
36    loop is large).  Then fall through to a loop unrolled 4 (or 2) times,
37    with only one exit test needed at the end of the loop.
38
39    Otherwise, if the number of iterations can not be calculated exactly,
40    not even at run time, then we still unroll the loop a number of times
41    approximately equal to MAX_UNROLLED_INSNS divided by the insn count,
42    but there must be an exit test after each copy of the loop body.
43
44    For each induction variable, which is dead outside the loop (replaceable)
45    or for which we can easily calculate the final value, if we can easily
46    calculate its value at each place where it is set as a function of the
47    current loop unroll count and the variable's value at loop entry, then
48    the induction variable is split into `N' different variables, one for
49    each copy of the loop body.  One variable is live across the backward
50    branch, and the others are all calculated as a function of this variable.
51    This helps eliminate data dependencies, and leads to further opportunities
52    for cse.  */
53
54 /* Possible improvements follow:  */
55
56 /* ??? Add an extra pass somewhere to determine whether unrolling will
57    give any benefit.  E.g. after generating all unrolled insns, compute the
58    cost of all insns and compare against cost of insns in rolled loop.
59
60    - On traditional architectures, unrolling a non-constant bound loop
61      is a win if there is a giv whose only use is in memory addresses, the
62      memory addresses can be split, and hence giv increments can be
63      eliminated.
64    - It is also a win if the loop is executed many times, and preconditioning
65      can be performed for the loop.
66    Add code to check for these and similar cases.  */
67
68 /* ??? Improve control of which loops get unrolled.  Could use profiling
69    info to only unroll the most commonly executed loops.  Perhaps have
70    a user specifyable option to control the amount of code expansion,
71    or the percent of loops to consider for unrolling.  Etc.  */
72
73 /* ??? Look at the register copies inside the loop to see if they form a
74    simple permutation.  If so, iterate the permutation until it gets back to
75    the start state.  This is how many times we should unroll the loop, for
76    best results, because then all register copies can be eliminated.
77    For example, the lisp nreverse function should be unrolled 3 times
78    while (this)
79      {
80        next = this->cdr;
81        this->cdr = prev;
82        prev = this;
83        this = next;
84      }
85
86    ??? The number of times to unroll the loop may also be based on data
87    references in the loop.  For example, if we have a loop that references
88    x[i-1], x[i], and x[i+1], we should unroll it a multiple of 3 times.  */
89
90 /* ??? Add some simple linear equation solving capability so that we can
91    determine the number of loop iterations for more complex loops.
92    For example, consider this loop from gdb
93    #define SWAP_TARGET_AND_HOST(buffer,len)
94      {
95        char tmp;
96        char *p = (char *) buffer;
97        char *q = ((char *) buffer) + len - 1;
98        int iterations = (len + 1) >> 1;
99        int i;
100        for (p; p < q; p++, q--;)
101          {
102            tmp = *q;
103            *q = *p;
104            *p = tmp;
105          }
106      }
107    Note that:
108      start value = p = &buffer + current_iteration
109      end value   = q = &buffer + len - 1 - current_iteration
110    Given the loop exit test of "p < q", then there must be "q - p" iterations,
111    set equal to zero and solve for number of iterations:
112      q - p = len - 1 - 2*current_iteration = 0
113      current_iteration = (len - 1) / 2
114    Hence, there are (len - 1) / 2 (rounded up to the nearest integer)
115    iterations of this loop.  */
116
117 /* ??? Currently, no labels are marked as loop invariant when doing loop
118    unrolling.  This is because an insn inside the loop, that loads the address
119    of a label inside the loop into a register, could be moved outside the loop
120    by the invariant code motion pass if labels were invariant.  If the loop
121    is subsequently unrolled, the code will be wrong because each unrolled
122    body of the loop will use the same address, whereas each actually needs a
123    different address.  A case where this happens is when a loop containing
124    a switch statement is unrolled.
125
126    It would be better to let labels be considered invariant.  When we
127    unroll loops here, check to see if any insns using a label local to the
128    loop were moved before the loop.  If so, then correct the problem, by
129    moving the insn back into the loop, or perhaps replicate the insn before
130    the loop, one copy for each time the loop is unrolled.  */
131
132 /* The prime factors looked for when trying to unroll a loop by some
133    number which is modulo the total number of iterations.  Just checking
134    for these 4 prime factors will find at least one factor for 75% of
135    all numbers theoretically.  Practically speaking, this will succeed
136    almost all of the time since loops are generally a multiple of 2
137    and/or 5.  */
138
139 #define NUM_FACTORS 4
140
141 struct _factor { int factor, count; } factors[NUM_FACTORS]
142   = { {2, 0}, {3, 0}, {5, 0}, {7, 0}};
143       
144 /* Describes the different types of loop unrolling performed.  */
145
146 enum unroll_types { UNROLL_COMPLETELY, UNROLL_MODULO, UNROLL_NAIVE };
147
148 #include "config.h"
149 #include "rtl.h"
150 #include "insn-config.h"
151 #include "integrate.h"
152 #include "regs.h"
153 #include "flags.h"
154 #include "expr.h"
155 #include <stdio.h>
156 #include "loop.h"
157
158 /* This controls which loops are unrolled, and by how much we unroll
159    them.  */
160
161 #ifndef MAX_UNROLLED_INSNS
162 #define MAX_UNROLLED_INSNS 100
163 #endif
164
165 /* Indexed by register number, if non-zero, then it contains a pointer
166    to a struct induction for a DEST_REG giv which has been combined with
167    one of more address givs.  This is needed because whenever such a DEST_REG
168    giv is modified, we must modify the value of all split address givs
169    that were combined with this DEST_REG giv.  */
170
171 static struct induction **addr_combined_regs;
172
173 /* Indexed by register number, if this is a splittable induction variable,
174    then this will hold the current value of the register, which depends on the
175    iteration number.  */
176
177 static rtx *splittable_regs;
178
179 /* Indexed by register number, if this is a splittable induction variable,
180    then this will hold the number of instructions in the loop that modify
181    the induction variable.  Used to ensure that only the last insn modifying
182    a split iv will update the original iv of the dest.  */
183
184 static int *splittable_regs_updates;
185
186 /* Values describing the current loop's iteration variable.  These are set up
187    by loop_iterations, and used by precondition_loop_p.  */
188
189 static rtx loop_iteration_var;
190 static rtx loop_initial_value;
191 static rtx loop_increment;
192 static rtx loop_final_value;
193
194 /* Forward declarations.  */
195
196 static void init_reg_map ();
197 static int precondition_loop_p ();
198 static void copy_loop_body ();
199 static void iteration_info ();
200 static rtx approx_final_value ();
201 static int find_splittable_regs ();
202 static int find_splittable_givs ();
203 static rtx fold_rtx_mult_add ();
204
205 /* Try to unroll one loop and split induction variables in the loop.
206
207    The loop is described by the arguments LOOP_END, INSN_COUNT, and
208    LOOP_START.  END_INSERT_BEFORE indicates where insns should be added
209    which need to be executed when the loop falls through.  STRENGTH_REDUCTION_P
210    indicates whether information generated in the strength reduction pass
211    is available.
212
213    This function is intended to be called from within `strength_reduce'
214    in loop.c.  */
215
216 void
217 unroll_loop (loop_end, insn_count, loop_start, end_insert_before,
218              strength_reduce_p)
219      rtx loop_end;
220      int insn_count;
221      rtx loop_start;
222      rtx end_insert_before;
223      int strength_reduce_p;
224 {
225   int i, j, temp;
226   int unroll_number = 1;
227   rtx copy_start, copy_end;
228   rtx insn, copy, sequence, pattern, tem;
229   int max_labelno, max_insnno;
230   rtx insert_before;
231   struct inline_remap *map;
232   char *local_label;
233   int maxregnum;
234   int new_maxregnum;
235   rtx exit_label = 0;
236   rtx start_label;
237   struct iv_class *bl;
238   struct induction *v;
239   int splitting_not_safe = 0;
240   enum unroll_types unroll_type;
241   int loop_preconditioned = 0;
242   rtx safety_label;
243   /* This points to the last real insn in the loop, which should be either
244      a JUMP_INSN (for conditional jumps) or a BARRIER (for unconditional
245      jumps).  */
246   rtx last_loop_insn;
247
248   /* Don't bother unrolling huge loops.  Since the minimum factor is
249      two, loops greater than one half of MAX_UNROLLED_INSNS will never
250      be unrolled.  */
251   if (insn_count > MAX_UNROLLED_INSNS / 2)
252     {
253       if (loop_dump_stream)
254         fprintf (loop_dump_stream, "Unrolling failure: Loop too big.\n");
255       return;
256     }
257
258   /* When emitting debugger info, we can't unroll loops with unequal numbers
259      of block_beg and block_end notes, because that would unbalance the block
260      structure of the function.  This can happen as a result of the
261      "if (foo) bar; else break;" optimization in jump.c.  */
262
263   if (write_symbols != NO_DEBUG)
264     {
265       int block_begins = 0;
266       int block_ends = 0;
267
268       for (insn = loop_start; insn != loop_end; insn = NEXT_INSN (insn))
269         {
270           if (GET_CODE (insn) == NOTE)
271             {
272               if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_BLOCK_BEG)
273                 block_begins++;
274               else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_BLOCK_END)
275                 block_ends++;
276             }
277         }
278
279       if (block_begins != block_ends)
280         {
281           if (loop_dump_stream)
282             fprintf (loop_dump_stream,
283                      "Unrolling failure: Unbalanced block notes.\n");
284           return;
285         }
286     }
287
288   /* Determine type of unroll to perform.  Depends on the number of iterations
289      and the size of the loop.  */
290
291   /* If there is no strength reduce info, then set loop_n_iterations to zero.
292      This can happen if strength_reduce can't find any bivs in the loop.
293      A value of zero indicates that the number of iterations could not be
294      calculated.  */
295
296   if (! strength_reduce_p)
297     loop_n_iterations = 0;
298
299   if (loop_dump_stream && loop_n_iterations > 0)
300     fprintf (loop_dump_stream,
301              "Loop unrolling: %d iterations.\n", loop_n_iterations);
302
303   /* Find and save a pointer to the last nonnote insn in the loop.  */
304
305   last_loop_insn = prev_nonnote_insn (loop_end);
306
307   /* Calculate how many times to unroll the loop.  Indicate whether or
308      not the loop is being completely unrolled.  */
309
310   if (loop_n_iterations == 1)
311     {
312       /* If number of iterations is exactly 1, then eliminate the compare and
313          branch at the end of the loop since they will never be taken.
314          Then return, since no other action is needed here.  */
315
316       /* If the last instruction is not a BARRIER or a JUMP_INSN, then
317          don't do anything.  */
318
319       if (GET_CODE (last_loop_insn) == BARRIER)
320         {
321           /* Delete the jump insn.  This will delete the barrier also.  */
322           delete_insn (PREV_INSN (last_loop_insn));
323         }
324       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
325         {
326 #ifdef HAVE_cc0
327           /* The immediately preceding insn is a compare which must be
328              deleted.  */
329           delete_insn (last_loop_insn);
330           delete_insn (PREV_INSN (last_loop_insn));
331 #else
332           /* The immediately preceding insn may not be the compare, so don't
333              delete it.  */
334           delete_insn (last_loop_insn);
335 #endif
336         }
337       return;
338     }
339   else if (loop_n_iterations > 0
340       && loop_n_iterations * insn_count < MAX_UNROLLED_INSNS)
341     {
342       unroll_number = loop_n_iterations;
343       unroll_type = UNROLL_COMPLETELY;
344     }
345   else if (loop_n_iterations > 0)
346     {
347       /* Try to factor the number of iterations.  Don't bother with the
348          general case, only using 2, 3, 5, and 7 will get 75% of all
349          numbers theoretically, and almost all in practice.  */
350
351       for (i = 0; i < NUM_FACTORS; i++)
352         factors[i].count = 0;
353
354       temp = loop_n_iterations;
355       for (i = NUM_FACTORS - 1; i >= 0; i--)
356         while (temp % factors[i].factor == 0)
357           {
358             factors[i].count++;
359             temp = temp / factors[i].factor;
360           }
361
362       /* Start with the larger factors first so that we generally
363          get lots of unrolling.  */
364
365       unroll_number = 1;
366       temp = insn_count;
367       for (i = 3; i >= 0; i--)
368         while (factors[i].count--)
369           {
370             if (temp * factors[i].factor < MAX_UNROLLED_INSNS)
371               {
372                 unroll_number *= factors[i].factor;
373                 temp *= factors[i].factor;
374               }
375             else
376               break;
377           }
378
379       /* If we couldn't find any factors, then unroll as in the normal
380          case.  */
381       if (unroll_number == 1)
382         {
383           if (loop_dump_stream)
384             fprintf (loop_dump_stream,
385                      "Loop unrolling: No factors found.\n");
386         }
387       else
388         unroll_type = UNROLL_MODULO;
389     }
390
391
392   /* Default case, calculate number of times to unroll loop based on its
393      size.  */
394   if (unroll_number == 1)
395     {
396       if (8 * insn_count < MAX_UNROLLED_INSNS)
397         unroll_number = 8;
398       else if (4 * insn_count < MAX_UNROLLED_INSNS)
399         unroll_number = 4;
400       else
401         unroll_number = 2;
402
403       unroll_type = UNROLL_NAIVE;
404     }
405
406   /* Now we know how many times to unroll the loop.  */
407
408   if (loop_dump_stream)
409     fprintf (loop_dump_stream,
410              "Unrolling loop %d times.\n", unroll_number);
411
412
413   if (unroll_type == UNROLL_COMPLETELY || unroll_type == UNROLL_MODULO)
414     {
415       /* Loops of these types should never start with a jump down to
416          the exit condition test.  For now, check for this case just to
417          be sure.  UNROLL_NAIVE loops can be of this form, this case is
418          handled below.  */
419       insn = loop_start;
420       while (GET_CODE (insn) != CODE_LABEL && GET_CODE (insn) != JUMP_INSN)
421         insn = NEXT_INSN (insn);
422       if (GET_CODE (insn) == JUMP_INSN)
423         abort ();
424     }
425
426   if (unroll_type == UNROLL_COMPLETELY)
427     {
428       /* Completely unrolling the loop:  Delete the compare and branch at
429          the end (the last two instructions).   This delete must done at the
430          very end of loop unrolling, to avoid problems with calls to
431          back_branch_in_range_p, which is called by find_splittable_regs.
432          All increments of splittable bivs/givs are changed to load constant
433          instructions.  */
434
435       copy_start = loop_start;
436
437       /* Set insert_before to the instruction immediately after the JUMP_INSN
438          (or BARRIER), so that any NOTEs between the JUMP_INSN and the end of
439          the loop will be correctly handled by copy_loop_body.  */
440       insert_before = NEXT_INSN (last_loop_insn);
441
442       /* Set copy_end to the insn before the jump at the end of the loop.  */
443       if (GET_CODE (last_loop_insn) == BARRIER)
444         copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
445       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
446         {
447 #ifdef HAVE_cc0
448           /* The instruction immediately before the JUMP_INSN is a compare
449              instruction which we do not want to copy.  */
450           copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
451 #else
452           /* The instruction immediately before the JUMP_INSN may not be the
453              compare, so we must copy it.  */
454           copy_end = PREV_INSN (last_loop_insn);
455 #endif
456         }
457       else
458         {
459           /* We currently can't unroll a loop if it doesn't end with a
460              JUMP_INSN.  There would need to be a mechanism that recognizes
461              this case, and then inserts a jump after each loop body, which
462              jumps to after the last loop body.  */
463           if (loop_dump_stream)
464             fprintf (loop_dump_stream,
465                      "Unrolling failure: loop does not end with a JUMP_INSN.\n");
466           return;
467         }
468     }
469   else if (unroll_type == UNROLL_MODULO)
470     {
471       /* Partially unrolling the loop:  The compare and branch at the end
472          (the last two instructions) must remain.  Don't copy the compare
473          and branch instructions at the end of the loop.  Insert the unrolled
474          code immediately before the compare/branch at the end so that the
475          code will fall through to them as before.  */
476
477       copy_start = loop_start;
478
479       /* Set insert_before to the jump insn at the end of the loop.
480          Set copy_end to before the jump insn at the end of the loop.  */
481       if (GET_CODE (last_loop_insn) == BARRIER)
482         {
483           insert_before = PREV_INSN (last_loop_insn);
484           copy_end = PREV_INSN (insert_before);
485         }
486       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
487         {
488 #ifdef HAVE_cc0
489           /* The instruction immediately before the JUMP_INSN is a compare
490              instruction which we do not want to copy or delete.  */
491           insert_before = PREV_INSN (last_loop_insn);
492           copy_end = PREV_INSN (insert_before);
493 #else
494           /* The instruction immediately before the JUMP_INSN may not be the
495              compare, so we must copy it.  */
496           insert_before = last_loop_insn;
497           copy_end = PREV_INSN (last_loop_insn);
498 #endif
499         }
500       else
501         {
502           /* We currently can't unroll a loop if it doesn't end with a
503              JUMP_INSN.  There would need to be a mechanism that recognizes
504              this case, and then inserts a jump after each loop body, which
505              jumps to after the last loop body.  */
506           if (loop_dump_stream)
507             fprintf (loop_dump_stream,
508                      "Unrolling failure: loop does not end with a JUMP_INSN.\n");
509           return;
510         }
511     }
512   else
513     {
514       /* Normal case: Must copy the compare and branch instructions at the
515          end of the loop.  */
516
517       if (GET_CODE (last_loop_insn) == BARRIER)
518         {
519           /* Loop ends with an unconditional jump and a barrier.
520              Handle this like above, don't copy jump and barrier.
521              This is not strictly necessary, but doing so prevents generating
522              unconditional jumps to an immediately following label.
523
524              This will be corrected below if the target of this jump is
525              not the start_label.  */
526
527           insert_before = PREV_INSN (last_loop_insn);
528           copy_end = PREV_INSN (insert_before);
529         }
530       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
531         {
532           /* Set insert_before to immediately after the JUMP_INSN, so that
533              NOTEs at the end of the loop will be correctly handled by
534              copy_loop_body.  */
535           insert_before = NEXT_INSN (last_loop_insn);
536           copy_end = last_loop_insn;
537         }
538       else
539         {
540           /* We currently can't unroll a loop if it doesn't end with a
541              JUMP_INSN.  There would need to be a mechanism that recognizes
542              this case, and then inserts a jump after each loop body, which
543              jumps to after the last loop body.  */
544           if (loop_dump_stream)
545             fprintf (loop_dump_stream,
546                      "Unrolling failure: loop does not end with a JUMP_INSN.\n");
547           return;
548         }
549
550       /* If copying exit test branches because they can not be eliminated,
551          then must convert the fall through case of the branch to a jump past
552          the end of the loop.  Create a label to emit after the loop and save
553          it for later use.  Do not use the label after the loop, if any, since
554          it might be used by insns outside the loop, or there might be insns
555          added before it later by final_[bg]iv_value which must be after
556          the real exit label.  */
557       exit_label = gen_label_rtx ();
558
559       insn = loop_start;
560       while (GET_CODE (insn) != CODE_LABEL && GET_CODE (insn) != JUMP_INSN)
561         insn = NEXT_INSN (insn);
562
563       if (GET_CODE (insn) == JUMP_INSN)
564         {
565           /* The loop starts with a jump down to the exit condition test.
566              Start copying the loop after the barrier following this
567              jump insn.  */
568           copy_start = NEXT_INSN (insn);
569
570           /* Splitting induction variables doesn't work when the loop is
571              entered via a jump to the bottom, because then we end up doing
572              a comparison against a new register for a split variable, but
573              we did not execute the set insn for the new register because
574              it was skipped over.  */
575           splitting_not_safe = 1;
576           if (loop_dump_stream)
577             fprintf (loop_dump_stream,
578                      "Splitting not safe, because loop not entered at top.\n");
579         }
580       else
581         copy_start = loop_start;
582     }
583
584   /* This should always be the first label in the loop.  */
585   start_label = NEXT_INSN (copy_start);
586   /* There may be a line number note and/or a loop continue note here.  */
587   while (GET_CODE (start_label) == NOTE)
588     start_label = NEXT_INSN (start_label);
589   if (GET_CODE (start_label) != CODE_LABEL)
590     {
591       /* This can happen as a result of jump threading.  If the first insns in
592          the loop test the same condition as the loop's backward jump, or the
593          opposite condition, then the backward jump will be modified to point
594          to elsewhere, and the loop's start label is deleted.
595
596          This case currently can not be handled by the loop unrolling code.  */
597
598       if (loop_dump_stream)
599         fprintf (loop_dump_stream,
600                  "Unrolling failure: unknown insns between BEG note and loop label.\n");
601       return;
602     }
603
604   if (unroll_type == UNROLL_NAIVE
605       && GET_CODE (last_loop_insn) == BARRIER
606       && start_label != JUMP_LABEL (PREV_INSN (last_loop_insn)))
607     {
608       /* In this case, we must copy the jump and barrier, because they will
609          not be converted to jumps to an immediately following label.  */
610
611       insert_before = NEXT_INSN (last_loop_insn);
612       copy_end = last_loop_insn;
613     }
614
615   /* Allocate a translation table for the labels and insn numbers.
616      They will be filled in as we copy the insns in the loop.  */
617
618   max_labelno = max_label_num ();
619   max_insnno = get_max_uid ();
620
621   map = (struct inline_remap *) alloca (sizeof (struct inline_remap));
622
623   /* Allocate the label map.  */
624
625   if (max_labelno > 0)
626     {
627       map->label_map = (rtx *) alloca (max_labelno * sizeof (rtx));
628
629       local_label = (char *) alloca (max_labelno);
630       bzero (local_label, max_labelno);
631     }
632   else
633     map->label_map = 0;
634
635   /* Search the loop and mark all local labels, i.e. the ones which have to
636      be distinct labels when copied.  For all labels which might be
637      non-local, set their label_map entries to point to themselves.
638      If they happen to be local their label_map entries will be overwritten
639      before the loop body is copied.  The label_map entries for local labels
640      will be set to a different value each time the loop body is copied.  */
641
642   for (insn = copy_start; insn != loop_end; insn = NEXT_INSN (insn))
643     {
644       if (GET_CODE (insn) == CODE_LABEL)
645         local_label[CODE_LABEL_NUMBER (insn)] = 1;
646       else if (GET_CODE (insn) == JUMP_INSN)
647         {
648           if (JUMP_LABEL (insn))
649             map->label_map[CODE_LABEL_NUMBER (JUMP_LABEL (insn))]
650               = JUMP_LABEL (insn);
651           else if (GET_CODE (PATTERN (insn)) == ADDR_VEC
652                    || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
653             {
654               rtx pat = PATTERN (insn);
655               int diff_vec_p = GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC;
656               int len = XVECLEN (pat, diff_vec_p);
657               rtx label;
658
659               for (i = 0; i < len; i++)
660                 {
661                   label = XEXP (XVECEXP (pat, diff_vec_p, i), 0);
662                   map->label_map[CODE_LABEL_NUMBER (label)] = label;
663                 }
664             }
665         }
666     }
667
668   /* Allocate space for the insn map.  */
669
670   map->insn_map = (rtx *) alloca (max_insnno * sizeof (rtx));
671
672   /* Set this to zero, to indicate that we are doing loop unrolling,
673      not function inlining.  */
674   map->inline_target = 0;
675
676   /* The register and constant maps depend on the number of registers
677      present, so the final maps can't be created until after
678      find_splittable_regs is called.  However, they are needed for
679      preconditioning, so we create temporary maps when preconditioning
680      is performed.  */
681
682   /* The preconditioning code may allocate two new pseudo registers.  */
683   maxregnum = max_reg_num ();
684
685   /* Allocate and zero out the splittable_regs and addr_combined_regs
686      arrays.  These must be zeroed here because they will be used if
687      loop preconditioning is performed, and must be zero for that case.
688
689      It is safe to do this here, since the extra registers created by the
690      preconditioning code and find_splittable_regs will never be used
691      to access the splittable_regs[] and addr_combined_regs[] arrays.  */
692
693   splittable_regs = (rtx *) alloca (maxregnum * sizeof (rtx));
694   bzero (splittable_regs, maxregnum * sizeof (rtx));
695   splittable_regs_updates = (int *) alloca (maxregnum * sizeof (int));
696   bzero (splittable_regs_updates, maxregnum * sizeof (int));
697   addr_combined_regs
698     = (struct induction **) alloca (maxregnum * sizeof (struct induction *));
699   bzero (addr_combined_regs, maxregnum * sizeof (struct induction *));
700
701   /* If this loop requires exit tests when unrolled, check to see if we
702      can precondition the loop so as to make the exit tests unnecessary.
703      Just like variable splitting, this is not safe if the loop is entered
704      via a jump to the bottom.  Also, can not do this if no strength
705      reduce info, because precondition_loop_p uses this info.  */
706
707   /* Must copy the loop body for preconditioning before the following
708      find_splittable_regs call since that will emit insns which need to
709      be after the preconditioned loop copies, but immediately before the
710      unrolled loop copies.  */
711
712   /* Also, it is not safe to split induction variables for the preconditioned
713      copies of the loop body.  If we split induction variables, then the code
714      assumes that each induction variable can be represented as a function
715      of its initial value and the loop iteration number.  This is not true
716      in this case, because the last preconditioned copy of the loop body
717      could be any iteration from the first up to the `unroll_number-1'th,
718      depending on the initial value of the iteration variable.  Therefore
719      we can not split induction variables here, because we can not calculate
720      their value.  Hence, this code must occur before find_splittable_regs
721      is called.  */
722
723   if (unroll_type == UNROLL_NAIVE && ! splitting_not_safe && strength_reduce_p)
724     {
725       rtx initial_value, final_value, increment;
726
727       if (precondition_loop_p (&initial_value, &final_value, &increment,
728                                loop_start, loop_end))
729         {
730           register rtx diff, temp;
731           enum machine_mode mode;
732           rtx *labels;
733           int abs_inc, neg_inc;
734
735           map->reg_map = (rtx *) alloca (maxregnum * sizeof (rtx));
736
737           map->const_equiv_map = (rtx *) alloca (maxregnum * sizeof (rtx));
738           map->const_age_map = (unsigned *) alloca (maxregnum
739                                                     * sizeof (unsigned));
740           map->const_equiv_map_size = maxregnum;
741           global_const_equiv_map = map->const_equiv_map;
742
743           init_reg_map (map, maxregnum);
744
745           /* Limit loop unrolling to 4, since this will make 7 copies of
746              the loop body.  */
747           if (unroll_number > 4)
748             unroll_number = 4;
749
750           /* Save the absolute value of the increment, and also whether or
751              not it is negative.  */
752           neg_inc = 0;
753           abs_inc = INTVAL (increment);
754           if (abs_inc < 0)
755             {
756               abs_inc = - abs_inc;
757               neg_inc = 1;
758             }
759
760           start_sequence ();
761
762           /* Decide what mode to do these calculations in.  Choose the larger
763              of final_value's mode and initial_value's mode, or a full-word if
764              both are constants.  */
765           mode = GET_MODE (final_value);
766           if (mode == VOIDmode)
767             {
768               mode = GET_MODE (initial_value);
769               if (mode == VOIDmode)
770                 mode = word_mode;
771             }
772           else if (mode != GET_MODE (initial_value)
773                    && (GET_MODE_SIZE (mode)
774                        < GET_MODE_SIZE (GET_MODE (initial_value))))
775             mode = GET_MODE (initial_value);
776
777           /* Calculate the difference between the final and initial values.
778              Final value may be a (plus (reg x) (const_int 1)) rtx.
779              Let the following cse pass simplify this if initial value is
780              a constant. 
781
782              We must copy the final and initial values here to avoid
783              improperly shared rtl.  */
784
785           diff = expand_binop (mode, sub_optab, copy_rtx (final_value),
786                                copy_rtx (initial_value), NULL_RTX, 0,
787                                OPTAB_LIB_WIDEN);
788
789           /* Now calculate (diff % (unroll * abs (increment))) by using an
790              and instruction.  */
791           diff = expand_binop (GET_MODE (diff), and_optab, diff,
792                                GEN_INT (unroll_number * abs_inc - 1),
793                                NULL_RTX, 0, OPTAB_LIB_WIDEN);
794
795           /* Now emit a sequence of branches to jump to the proper precond
796              loop entry point.  */
797
798           labels = (rtx *) alloca (sizeof (rtx) * unroll_number);
799           for (i = 0; i < unroll_number; i++)
800             labels[i] = gen_label_rtx ();
801
802           /* Assuming the unroll_number is 4, and the increment is 2, then
803              for a negative increment:  for a positive increment:
804              diff = 0,1   precond 0     diff = 0,7   precond 0
805              diff = 2,3   precond 3     diff = 1,2   precond 1
806              diff = 4,5   precond 2     diff = 3,4   precond 2
807              diff = 6,7   precond 1     diff = 5,6   precond 3  */
808
809           /* We only need to emit (unroll_number - 1) branches here, the
810              last case just falls through to the following code.  */
811
812           /* ??? This would give better code if we emitted a tree of branches
813              instead of the current linear list of branches.  */
814
815           for (i = 0; i < unroll_number - 1; i++)
816             {
817               int cmp_const;
818
819               /* For negative increments, must invert the constant compared
820                  against, except when comparing against zero.  */
821               if (i == 0)
822                 cmp_const = 0;
823               else if (neg_inc)
824                 cmp_const = unroll_number - i;
825               else
826                 cmp_const = i;
827
828               emit_cmp_insn (diff, GEN_INT (abs_inc * cmp_const),
829                              EQ, NULL_RTX, mode, 0, 0);
830
831               if (i == 0)
832                 emit_jump_insn (gen_beq (labels[i]));
833               else if (neg_inc)
834                 emit_jump_insn (gen_bge (labels[i]));
835               else
836                 emit_jump_insn (gen_ble (labels[i]));
837               JUMP_LABEL (get_last_insn ()) = labels[i];
838               LABEL_NUSES (labels[i])++;
839             }
840
841           /* If the increment is greater than one, then we need another branch,
842              to handle other cases equivalent to 0.  */
843
844           /* ??? This should be merged into the code above somehow to help
845              simplify the code here, and reduce the number of branches emitted.
846              For the negative increment case, the branch here could easily
847              be merged with the `0' case branch above.  For the positive
848              increment case, it is not clear how this can be simplified.  */
849              
850           if (abs_inc != 1)
851             {
852               int cmp_const;
853
854               if (neg_inc)
855                 cmp_const = abs_inc - 1;
856               else
857                 cmp_const = abs_inc * (unroll_number - 1) + 1;
858
859               emit_cmp_insn (diff, GEN_INT (cmp_const), EQ, NULL_RTX,
860                              mode, 0, 0);
861
862               if (neg_inc)
863                 emit_jump_insn (gen_ble (labels[0]));
864               else
865                 emit_jump_insn (gen_bge (labels[0]));
866               JUMP_LABEL (get_last_insn ()) = labels[0];
867               LABEL_NUSES (labels[0])++;
868             }
869
870           sequence = gen_sequence ();
871           end_sequence ();
872           emit_insn_before (sequence, loop_start);
873           
874           /* Only the last copy of the loop body here needs the exit
875              test, so set copy_end to exclude the compare/branch here,
876              and then reset it inside the loop when get to the last
877              copy.  */
878
879           if (GET_CODE (last_loop_insn) == BARRIER)
880             copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
881           else if (GET_CODE (last_loop_insn) == JUMP_INSN)
882             {
883 #ifdef HAVE_cc0
884               /* The immediately preceding insn is a compare which we do not
885                  want to copy.  */
886               copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
887 #else
888               /* The immediately preceding insn may not be a compare, so we
889                  must copy it.  */
890               copy_end = PREV_INSN (last_loop_insn);
891 #endif
892             }
893           else
894             abort ();
895
896           for (i = 1; i < unroll_number; i++)
897             {
898               emit_label_after (labels[unroll_number - i],
899                                 PREV_INSN (loop_start));
900
901               bzero (map->insn_map, max_insnno * sizeof (rtx));
902               bzero (map->const_equiv_map, maxregnum * sizeof (rtx));
903               bzero (map->const_age_map, maxregnum * sizeof (unsigned));
904               map->const_age = 0;
905
906               for (j = 0; j < max_labelno; j++)
907                 if (local_label[j])
908                   map->label_map[j] = gen_label_rtx ();
909
910               /* The last copy needs the compare/branch insns at the end,
911                  so reset copy_end here if the loop ends with a conditional
912                  branch.  */
913
914               if (i == unroll_number - 1)
915                 {
916                   if (GET_CODE (last_loop_insn) == BARRIER)
917                     copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
918                   else
919                     copy_end = last_loop_insn;
920                 }
921
922               /* None of the copies are the `last_iteration', so just
923                  pass zero for that parameter.  */
924               copy_loop_body (copy_start, copy_end, map, exit_label, 0,
925                               unroll_type, start_label, loop_end,
926                               loop_start, copy_end);
927             }
928           emit_label_after (labels[0], PREV_INSN (loop_start));
929
930           if (GET_CODE (last_loop_insn) == BARRIER)
931             {
932               insert_before = PREV_INSN (last_loop_insn);
933               copy_end = PREV_INSN (insert_before);
934             }
935           else
936             {
937 #ifdef HAVE_cc0
938               /* The immediately preceding insn is a compare which we do not
939                  want to copy.  */
940               insert_before = PREV_INSN (last_loop_insn);
941               copy_end = PREV_INSN (insert_before);
942 #else
943               /* The immediately preceding insn may not be a compare, so we
944                  must copy it.  */
945               insert_before = last_loop_insn;
946               copy_end = PREV_INSN (last_loop_insn);
947 #endif
948             }
949
950           /* Set unroll type to MODULO now.  */
951           unroll_type = UNROLL_MODULO;
952           loop_preconditioned = 1;
953         }
954     }
955
956   /* If reach here, and the loop type is UNROLL_NAIVE, then don't unroll
957      the loop unless all loops are being unrolled.  */
958   if (unroll_type == UNROLL_NAIVE && ! flag_unroll_all_loops)
959     {
960       if (loop_dump_stream)
961         fprintf (loop_dump_stream, "Unrolling failure: Naive unrolling not being done.\n");
962       return;
963     }
964
965   /* At this point, we are guaranteed to unroll the loop.  */
966
967   /* For each biv and giv, determine whether it can be safely split into
968      a different variable for each unrolled copy of the loop body.
969      We precalculate and save this info here, since computing it is
970      expensive.
971
972      Do this before deleting any instructions from the loop, so that
973      back_branch_in_range_p will work correctly.  */
974
975   if (splitting_not_safe)
976     temp = 0;
977   else
978     temp = find_splittable_regs (unroll_type, loop_start, loop_end,
979                                 end_insert_before, unroll_number);
980
981   /* find_splittable_regs may have created some new registers, so must
982      reallocate the reg_map with the new larger size, and must realloc
983      the constant maps also.  */
984
985   maxregnum = max_reg_num ();
986   map->reg_map = (rtx *) alloca (maxregnum * sizeof (rtx));
987
988   init_reg_map (map, maxregnum);
989
990   /* Space is needed in some of the map for new registers, so new_maxregnum
991      is an (over)estimate of how many registers will exist at the end.  */
992   new_maxregnum = maxregnum + (temp * unroll_number * 2);
993
994   /* Must realloc space for the constant maps, because the number of registers
995      may have changed.  */
996
997   map->const_equiv_map = (rtx *) alloca (new_maxregnum * sizeof (rtx));
998   map->const_age_map = (unsigned *) alloca (new_maxregnum * sizeof (unsigned));
999
1000   global_const_equiv_map = map->const_equiv_map;
1001
1002   /* Search the list of bivs and givs to find ones which need to be remapped
1003      when split, and set their reg_map entry appropriately.  */
1004
1005   for (bl = loop_iv_list; bl; bl = bl->next)
1006     {
1007       if (REGNO (bl->biv->src_reg) != bl->regno)
1008         map->reg_map[bl->regno] = bl->biv->src_reg;
1009 #if 0
1010       /* Currently, non-reduced/final-value givs are never split.  */
1011       for (v = bl->giv; v; v = v->next_iv)
1012         if (REGNO (v->src_reg) != bl->regno)
1013           map->reg_map[REGNO (v->dest_reg)] = v->src_reg;
1014 #endif
1015     }
1016
1017   /* If the loop is being partially unrolled, and the iteration variables
1018      are being split, and are being renamed for the split, then must fix up
1019      the compare instruction at the end of the loop to refer to the new
1020      registers.  This compare isn't copied, so the registers used in it
1021      will never be replaced if it isn't done here.  */
1022
1023   if (unroll_type == UNROLL_MODULO)
1024     {
1025       insn = NEXT_INSN (copy_end);
1026       if (GET_CODE (insn) == INSN && GET_CODE (PATTERN (insn)) == SET)
1027         {
1028 #if 0
1029           /* If non-reduced/final-value givs were split, then this would also
1030              have to remap those givs.  */
1031 #endif
1032
1033           tem = SET_SRC (PATTERN (insn));
1034           /* The set source is a register.  */
1035           if (GET_CODE (tem) == REG)
1036             {
1037               if (REGNO (tem) < max_reg_before_loop
1038                   && reg_iv_type[REGNO (tem)] == BASIC_INDUCT)
1039                 SET_SRC (PATTERN (insn))
1040                   = reg_biv_class[REGNO (tem)]->biv->src_reg;
1041             }
1042           else
1043             {
1044               /* The set source is a compare of some sort.  */
1045               tem = XEXP (SET_SRC (PATTERN (insn)), 0);
1046               if (GET_CODE (tem) == REG
1047                   && REGNO (tem) < max_reg_before_loop
1048                   && reg_iv_type[REGNO (tem)] == BASIC_INDUCT)
1049                 XEXP (SET_SRC (PATTERN (insn)), 0)
1050                   = reg_biv_class[REGNO (tem)]->biv->src_reg;
1051               
1052               tem = XEXP (SET_SRC (PATTERN (insn)), 1);
1053               if (GET_CODE (tem) == REG
1054                   && REGNO (tem) < max_reg_before_loop
1055                   && reg_iv_type[REGNO (tem)] == BASIC_INDUCT)
1056                 XEXP (SET_SRC (PATTERN (insn)), 1)
1057                   = reg_biv_class[REGNO (tem)]->biv->src_reg;
1058             }
1059         }
1060     }
1061
1062   /* For unroll_number - 1 times, make a copy of each instruction
1063      between copy_start and copy_end, and insert these new instructions
1064      before the end of the loop.  */
1065
1066   for (i = 0; i < unroll_number; i++)
1067     {
1068       bzero (map->insn_map, max_insnno * sizeof (rtx));
1069       bzero (map->const_equiv_map, new_maxregnum * sizeof (rtx));
1070       bzero (map->const_age_map, new_maxregnum * sizeof (unsigned));
1071       map->const_age = 0;
1072
1073       for (j = 0; j < max_labelno; j++)
1074         if (local_label[j])
1075           map->label_map[j] = gen_label_rtx ();
1076
1077       /* If loop starts with a branch to the test, then fix it so that
1078          it points to the test of the first unrolled copy of the loop.  */
1079       if (i == 0 && loop_start != copy_start)
1080         {
1081           insn = PREV_INSN (copy_start);
1082           pattern = PATTERN (insn);
1083           
1084           tem = map->label_map[CODE_LABEL_NUMBER
1085                                (XEXP (SET_SRC (pattern), 0))];
1086           SET_SRC (pattern) = gen_rtx (LABEL_REF, VOIDmode, tem);
1087
1088           /* Set the jump label so that it can be used by later loop unrolling
1089              passes.  */
1090           JUMP_LABEL (insn) = tem;
1091           LABEL_NUSES (tem)++;
1092         }
1093
1094       copy_loop_body (copy_start, copy_end, map, exit_label,
1095                       i == unroll_number - 1, unroll_type, start_label,
1096                       loop_end, insert_before, insert_before);
1097     }
1098
1099   /* Before deleting any insns, emit a CODE_LABEL immediately after the last
1100      insn to be deleted.  This prevents any runaway delete_insn call from
1101      more insns that it should, as it always stops at a CODE_LABEL.  */
1102
1103   /* Delete the compare and branch at the end of the loop if completely
1104      unrolling the loop.  Deleting the backward branch at the end also
1105      deletes the code label at the start of the loop.  This is done at
1106      the very end to avoid problems with back_branch_in_range_p.  */
1107
1108   if (unroll_type == UNROLL_COMPLETELY)
1109     safety_label = emit_label_after (gen_label_rtx (), last_loop_insn);
1110   else
1111     safety_label = emit_label_after (gen_label_rtx (), copy_end);
1112
1113   /* Delete all of the original loop instructions.  Don't delete the 
1114      LOOP_BEG note, or the first code label in the loop.  */
1115
1116   insn = NEXT_INSN (copy_start);
1117   while (insn != safety_label)
1118     {
1119       if (insn != start_label)
1120         insn = delete_insn (insn);
1121       else
1122         insn = NEXT_INSN (insn);
1123     }
1124
1125   /* Can now delete the 'safety' label emitted to protect us from runaway
1126      delete_insn calls.  */
1127   if (INSN_DELETED_P (safety_label))
1128     abort ();
1129   delete_insn (safety_label);
1130
1131   /* If exit_label exists, emit it after the loop.  Doing the emit here
1132      forces it to have a higher INSN_UID than any insn in the unrolled loop.
1133      This is needed so that mostly_true_jump in reorg.c will treat jumps
1134      to this loop end label correctly, i.e. predict that they are usually
1135      not taken.  */
1136   if (exit_label)
1137     emit_label_after (exit_label, loop_end);
1138 }
1139 \f
1140 /* Return true if the loop can be safely, and profitably, preconditioned
1141    so that the unrolled copies of the loop body don't need exit tests.
1142
1143    This only works if final_value, initial_value and increment can be
1144    determined, and if increment is a constant power of 2.
1145    If increment is not a power of 2, then the preconditioning modulo
1146    operation would require a real modulo instead of a boolean AND, and this
1147    is not considered `profitable'.  */
1148
1149 /* ??? If the loop is known to be executed very many times, or the machine
1150    has a very cheap divide instruction, then preconditioning is a win even
1151    when the increment is not a power of 2.  Use RTX_COST to compute
1152    whether divide is cheap.  */
1153
1154 static int
1155 precondition_loop_p (initial_value, final_value, increment, loop_start,
1156                      loop_end)
1157      rtx *initial_value, *final_value, *increment;
1158      rtx loop_start, loop_end;
1159 {
1160   int unsigned_compare, compare_dir;
1161
1162   if (loop_n_iterations > 0)
1163     {
1164       *initial_value = const0_rtx;
1165       *increment = const1_rtx;
1166       *final_value = GEN_INT (loop_n_iterations);
1167
1168       if (loop_dump_stream)
1169         fprintf (loop_dump_stream,
1170                  "Preconditioning: Success, number of iterations known, %d.\n",
1171                  loop_n_iterations);
1172       return 1;
1173     }
1174
1175   if (loop_initial_value == 0)
1176     {
1177       if (loop_dump_stream)
1178         fprintf (loop_dump_stream,
1179                  "Preconditioning: Could not find initial value.\n");
1180       return 0;
1181     }
1182   else if (loop_increment == 0)
1183     {
1184       if (loop_dump_stream)
1185         fprintf (loop_dump_stream,
1186                  "Preconditioning: Could not find increment value.\n");
1187       return 0;
1188     }
1189   else if (GET_CODE (loop_increment) != CONST_INT)
1190     {
1191       if (loop_dump_stream)
1192         fprintf (loop_dump_stream,
1193                  "Preconditioning: Increment not a constant.\n");
1194       return 0;
1195     }
1196   else if ((exact_log2 (INTVAL (loop_increment)) < 0)
1197            && (exact_log2 (- INTVAL (loop_increment)) < 0))
1198     {
1199       if (loop_dump_stream)
1200         fprintf (loop_dump_stream,
1201                  "Preconditioning: Increment not a constant power of 2.\n");
1202       return 0;
1203     }
1204
1205   /* Unsigned_compare and compare_dir can be ignored here, since they do
1206      not matter for preconditioning.  */
1207
1208   if (loop_final_value == 0)
1209     {
1210       if (loop_dump_stream)
1211         fprintf (loop_dump_stream,
1212                  "Preconditioning: EQ comparison loop.\n");
1213       return 0;
1214     }
1215
1216   /* Must ensure that final_value is invariant, so call invariant_p to
1217      check.  Before doing so, must check regno against max_reg_before_loop
1218      to make sure that the register is in the range covered by invariant_p.
1219      If it isn't, then it is most likely a biv/giv which by definition are
1220      not invariant.  */
1221   if ((GET_CODE (loop_final_value) == REG
1222        && REGNO (loop_final_value) >= max_reg_before_loop)
1223       || (GET_CODE (loop_final_value) == PLUS
1224           && REGNO (XEXP (loop_final_value, 0)) >= max_reg_before_loop)
1225       || ! invariant_p (loop_final_value))
1226     {
1227       if (loop_dump_stream)
1228         fprintf (loop_dump_stream,
1229                  "Preconditioning: Final value not invariant.\n");
1230       return 0;
1231     }
1232
1233   /* Fail for floating point values, since the caller of this function
1234      does not have code to deal with them.  */
1235   if (GET_MODE_CLASS (GET_MODE (loop_final_value)) == MODE_FLOAT
1236       || GET_MODE_CLASS (GET_MODE (loop_initial_value)) == MODE_FLOAT)
1237     {
1238       if (loop_dump_stream)
1239         fprintf (loop_dump_stream,
1240                  "Preconditioning: Floating point final or initial value.\n");
1241       return 0;
1242     }
1243
1244   /* Now set initial_value to be the iteration_var, since that may be a
1245      simpler expression, and is guaranteed to be correct if all of the
1246      above tests succeed.
1247
1248      We can not use the initial_value as calculated, because it will be
1249      one too small for loops of the form "while (i-- > 0)".  We can not
1250      emit code before the loop_skip_over insns to fix this problem as this
1251      will then give a number one too large for loops of the form
1252      "while (--i > 0)".
1253
1254      Note that all loops that reach here are entered at the top, because
1255      this function is not called if the loop starts with a jump.  */
1256
1257   /* Fail if loop_iteration_var is not live before loop_start, since we need
1258      to test its value in the preconditioning code.  */
1259
1260   if (uid_luid[regno_first_uid[REGNO (loop_iteration_var)]]
1261       > INSN_LUID (loop_start))
1262     {
1263       if (loop_dump_stream)
1264         fprintf (loop_dump_stream,
1265                  "Preconditioning: Iteration var not live before loop start.\n");
1266       return 0;
1267     }
1268
1269   *initial_value = loop_iteration_var;
1270   *increment = loop_increment;
1271   *final_value = loop_final_value;
1272
1273   /* Success! */
1274   if (loop_dump_stream)
1275     fprintf (loop_dump_stream, "Preconditioning: Successful.\n");
1276   return 1;
1277 }
1278
1279
1280 /* All pseudo-registers must be mapped to themselves.  Two hard registers
1281    must be mapped, VIRTUAL_STACK_VARS_REGNUM and VIRTUAL_INCOMING_ARGS_
1282    REGNUM, to avoid function-inlining specific conversions of these
1283    registers.  All other hard regs can not be mapped because they may be
1284    used with different
1285    modes.  */
1286
1287 static void
1288 init_reg_map (map, maxregnum)
1289      struct inline_remap *map;
1290      int maxregnum;
1291 {
1292   int i;
1293
1294   for (i = maxregnum - 1; i > LAST_VIRTUAL_REGISTER; i--)
1295     map->reg_map[i] = regno_reg_rtx[i];
1296   /* Just clear the rest of the entries.  */
1297   for (i = LAST_VIRTUAL_REGISTER; i >= 0; i--)
1298     map->reg_map[i] = 0;
1299
1300   map->reg_map[VIRTUAL_STACK_VARS_REGNUM]
1301     = regno_reg_rtx[VIRTUAL_STACK_VARS_REGNUM];
1302   map->reg_map[VIRTUAL_INCOMING_ARGS_REGNUM]
1303     = regno_reg_rtx[VIRTUAL_INCOMING_ARGS_REGNUM];
1304 }
1305 \f
1306 /* Strength-reduction will often emit code for optimized biv/givs which
1307    calculates their value in a temporary register, and then copies the result
1308    to the iv.  This procedure reconstructs the pattern computing the iv;
1309    verifying that all operands are of the proper form.
1310
1311    The return value is the amount that the giv is incremented by.  */
1312
1313 static rtx
1314 calculate_giv_inc (pattern, src_insn, regno)
1315      rtx pattern, src_insn;
1316      int regno;
1317 {
1318   rtx increment;
1319
1320   /* Verify that we have an increment insn here.  First check for a plus
1321      as the set source.  */
1322   if (GET_CODE (SET_SRC (pattern)) != PLUS)
1323     {
1324       /* SR sometimes computes the new giv value in a temp, then copies it
1325          to the new_reg.  */
1326       src_insn = PREV_INSN (src_insn);
1327       pattern = PATTERN (src_insn);
1328       if (GET_CODE (SET_SRC (pattern)) != PLUS)
1329         abort ();
1330                   
1331       /* The last insn emitted is not needed, so delete it to avoid confusing
1332          the second cse pass.  This insn sets the giv unnecessarily.  */
1333       delete_insn (get_last_insn ());
1334     }
1335
1336   /* Verify that we have a constant as the second operand of the plus.  */
1337   increment = XEXP (SET_SRC (pattern), 1);
1338   if (GET_CODE (increment) != CONST_INT)
1339     {
1340       /* SR sometimes puts the constant in a register, especially if it is
1341          too big to be an add immed operand.  */
1342       increment = SET_SRC (PATTERN (PREV_INSN (src_insn)));
1343
1344       /* SR may have used LO_SUM to compute the constant if it is too large
1345          for a load immed operand.  In this case, the constant is in operand
1346          one of the LO_SUM rtx.  */
1347       if (GET_CODE (increment) == LO_SUM)
1348         increment = XEXP (increment, 1);
1349
1350       if (GET_CODE (increment) != CONST_INT)
1351         abort ();
1352                   
1353       /* The insn loading the constant into a register is not longer needed,
1354          so delete it.  */
1355       delete_insn (get_last_insn ());
1356     }
1357
1358   /* Check that the source register is the same as the dest register.  */
1359   if (GET_CODE (XEXP (SET_SRC (pattern), 0)) != REG
1360       || REGNO (XEXP (SET_SRC (pattern), 0)) != regno)
1361     abort ();
1362
1363   return increment;
1364 }
1365
1366
1367 /* Copy each instruction in the loop, substituting from map as appropriate.
1368    This is very similar to a loop in expand_inline_function.  */
1369   
1370 static void
1371 copy_loop_body (copy_start, copy_end, map, exit_label, last_iteration,
1372                 unroll_type, start_label, loop_end, insert_before,
1373                 copy_notes_from)
1374      rtx copy_start, copy_end;
1375      struct inline_remap *map;
1376      rtx exit_label;
1377      int last_iteration;
1378      enum unroll_types unroll_type;
1379      rtx start_label, loop_end, insert_before, copy_notes_from;
1380 {
1381   rtx insn, pattern;
1382   rtx tem, copy;
1383   int dest_reg_was_split, i;
1384   rtx cc0_insn = 0;
1385   rtx final_label = 0;
1386   rtx giv_inc, giv_dest_reg, giv_src_reg;
1387
1388   /* If this isn't the last iteration, then map any references to the
1389      start_label to final_label.  Final label will then be emitted immediately
1390      after the end of this loop body if it was ever used.
1391
1392      If this is the last iteration, then map references to the start_label
1393      to itself.  */
1394   if (! last_iteration)
1395     {
1396       final_label = gen_label_rtx ();
1397       map->label_map[CODE_LABEL_NUMBER (start_label)] = final_label;
1398     }
1399   else
1400     map->label_map[CODE_LABEL_NUMBER (start_label)] = start_label;
1401
1402   start_sequence ();
1403   
1404   insn = copy_start;
1405   do
1406     {
1407       insn = NEXT_INSN (insn);
1408       
1409       map->orig_asm_operands_vector = 0;
1410       
1411       switch (GET_CODE (insn))
1412         {
1413         case INSN:
1414           pattern = PATTERN (insn);
1415           copy = 0;
1416           giv_inc = 0;
1417           
1418           /* Check to see if this is a giv that has been combined with
1419              some split address givs.  (Combined in the sense that 
1420              `combine_givs' in loop.c has put two givs in the same register.)
1421              In this case, we must search all givs based on the same biv to
1422              find the address givs.  Then split the address givs.
1423              Do this before splitting the giv, since that may map the
1424              SET_DEST to a new register.  */
1425           
1426           if (GET_CODE (pattern) == SET
1427               && GET_CODE (SET_DEST (pattern)) == REG
1428               && addr_combined_regs[REGNO (SET_DEST (pattern))])
1429             {
1430               struct iv_class *bl;
1431               struct induction *v, *tv;
1432               int regno = REGNO (SET_DEST (pattern));
1433               
1434               v = addr_combined_regs[REGNO (SET_DEST (pattern))];
1435               bl = reg_biv_class[REGNO (v->src_reg)];
1436               
1437               /* Although the giv_inc amount is not needed here, we must call
1438                  calculate_giv_inc here since it might try to delete the
1439                  last insn emitted.  If we wait until later to call it,
1440                  we might accidentally delete insns generated immediately
1441                  below by emit_unrolled_add.  */
1442
1443               giv_inc = calculate_giv_inc (pattern, insn, regno);
1444
1445               /* Now find all address giv's that were combined with this
1446                  giv 'v'.  */
1447               for (tv = bl->giv; tv; tv = tv->next_iv)
1448                 if (tv->giv_type == DEST_ADDR && tv->same == v)
1449                   {
1450                     int this_giv_inc = INTVAL (giv_inc);
1451
1452                     /* Scale this_giv_inc if the multiplicative factors of
1453                        the two givs are different.  */
1454                     if (tv->mult_val != v->mult_val)
1455                       this_giv_inc = (this_giv_inc / INTVAL (v->mult_val)
1456                                       * INTVAL (tv->mult_val));
1457                        
1458                     tv->dest_reg = plus_constant (tv->dest_reg, this_giv_inc);
1459                     *tv->location = tv->dest_reg;
1460                     
1461                     if (last_iteration && unroll_type != UNROLL_COMPLETELY)
1462                       {
1463                         /* Must emit an insn to increment the split address
1464                            giv.  Add in the const_adjust field in case there
1465                            was a constant eliminated from the address.  */
1466                         rtx value, dest_reg;
1467                         
1468                         /* tv->dest_reg will be either a bare register,
1469                            or else a register plus a constant.  */
1470                         if (GET_CODE (tv->dest_reg) == REG)
1471                           dest_reg = tv->dest_reg;
1472                         else
1473                           dest_reg = XEXP (tv->dest_reg, 0);
1474                         
1475                         /* tv->dest_reg may actually be a (PLUS (REG) (CONST))
1476                            here, so we must call plus_constant to add
1477                            the const_adjust amount before calling
1478                            emit_unrolled_add below.  */
1479                         value = plus_constant (tv->dest_reg, tv->const_adjust);
1480
1481                         /* The constant could be too large for an add
1482                            immediate, so can't directly emit an insn here.  */
1483                         emit_unrolled_add (dest_reg, XEXP (value, 0),
1484                                            XEXP (value, 1));
1485                         
1486                         /* Reset the giv to be just the register again, in case
1487                            it is used after the set we have just emitted.
1488                            We must subtract the const_adjust factor added in
1489                            above.  */
1490                         tv->dest_reg = plus_constant (dest_reg,
1491                                                       - tv->const_adjust);
1492                         *tv->location = tv->dest_reg;
1493                       }
1494                   }
1495             }
1496           
1497           /* If this is a setting of a splittable variable, then determine
1498              how to split the variable, create a new set based on this split,
1499              and set up the reg_map so that later uses of the variable will
1500              use the new split variable.  */
1501           
1502           dest_reg_was_split = 0;
1503           
1504           if (GET_CODE (pattern) == SET
1505               && GET_CODE (SET_DEST (pattern)) == REG
1506               && splittable_regs[REGNO (SET_DEST (pattern))])
1507             {
1508               int regno = REGNO (SET_DEST (pattern));
1509               
1510               dest_reg_was_split = 1;
1511               
1512               /* Compute the increment value for the giv, if it wasn't
1513                  already computed above.  */
1514
1515               if (giv_inc == 0)
1516                 giv_inc = calculate_giv_inc (pattern, insn, regno);
1517               giv_dest_reg = SET_DEST (pattern);
1518               giv_src_reg = SET_DEST (pattern);
1519
1520               if (unroll_type == UNROLL_COMPLETELY)
1521                 {
1522                   /* Completely unrolling the loop.  Set the induction
1523                      variable to a known constant value.  */
1524                   
1525                   /* The value in splittable_regs may be an invariant
1526                      value, so we must use plus_constant here.  */
1527                   splittable_regs[regno]
1528                     = plus_constant (splittable_regs[regno], INTVAL (giv_inc));
1529
1530                   if (GET_CODE (splittable_regs[regno]) == PLUS)
1531                     {
1532                       giv_src_reg = XEXP (splittable_regs[regno], 0);
1533                       giv_inc = XEXP (splittable_regs[regno], 1);
1534                     }
1535                   else
1536                     {
1537                       /* The splittable_regs value must be a REG or a
1538                          CONST_INT, so put the entire value in the giv_src_reg
1539                          variable.  */
1540                       giv_src_reg = splittable_regs[regno];
1541                       giv_inc = const0_rtx;
1542                     }
1543                 }
1544               else
1545                 {
1546                   /* Partially unrolling loop.  Create a new pseudo
1547                      register for the iteration variable, and set it to
1548                      be a constant plus the original register.  Except
1549                      on the last iteration, when the result has to
1550                      go back into the original iteration var register.  */
1551                   
1552                   /* Handle bivs which must be mapped to a new register
1553                      when split.  This happens for bivs which need their
1554                      final value set before loop entry.  The new register
1555                      for the biv was stored in the biv's first struct
1556                      induction entry by find_splittable_regs.  */
1557
1558                   if (regno < max_reg_before_loop
1559                       && reg_iv_type[regno] == BASIC_INDUCT)
1560                     {
1561                       giv_src_reg = reg_biv_class[regno]->biv->src_reg;
1562                       giv_dest_reg = giv_src_reg;
1563                     }
1564                   
1565 #if 0
1566                   /* If non-reduced/final-value givs were split, then
1567                      this would have to remap those givs also.  See
1568                      find_splittable_regs.  */
1569 #endif
1570                   
1571                   splittable_regs[regno]
1572                     = GEN_INT (INTVAL (giv_inc)
1573                                + INTVAL (splittable_regs[regno]));
1574                   giv_inc = splittable_regs[regno];
1575                   
1576                   /* Now split the induction variable by changing the dest
1577                      of this insn to a new register, and setting its
1578                      reg_map entry to point to this new register.
1579
1580                      If this is the last iteration, and this is the last insn
1581                      that will update the iv, then reuse the original dest,
1582                      to ensure that the iv will have the proper value when
1583                      the loop exits or repeats.
1584
1585                      Using splittable_regs_updates here like this is safe,
1586                      because it can only be greater than one if all
1587                      instructions modifying the iv are always executed in
1588                      order.  */
1589
1590                   if (! last_iteration
1591                       || (splittable_regs_updates[regno]-- != 1))
1592                     {
1593                       tem = gen_reg_rtx (GET_MODE (giv_src_reg));
1594                       giv_dest_reg = tem;
1595                       map->reg_map[regno] = tem;
1596                     }
1597                   else
1598                     map->reg_map[regno] = giv_src_reg;
1599                 }
1600
1601               /* The constant being added could be too large for an add
1602                  immediate, so can't directly emit an insn here.  */
1603               emit_unrolled_add (giv_dest_reg, giv_src_reg, giv_inc);
1604               copy = get_last_insn ();
1605               pattern = PATTERN (copy);
1606             }
1607           else
1608             {
1609               pattern = copy_rtx_and_substitute (pattern, map);
1610               copy = emit_insn (pattern);
1611             }
1612           /* REG_NOTES will be copied later.  */
1613           
1614 #ifdef HAVE_cc0
1615           /* If this insn is setting CC0, it may need to look at
1616              the insn that uses CC0 to see what type of insn it is.
1617              In that case, the call to recog via validate_change will
1618              fail.  So don't substitute constants here.  Instead,
1619              do it when we emit the following insn.
1620
1621              For example, see the pyr.md file.  That machine has signed and
1622              unsigned compares.  The compare patterns must check the
1623              following branch insn to see which what kind of compare to
1624              emit.
1625
1626              If the previous insn set CC0, substitute constants on it as
1627              well.  */
1628           if (sets_cc0_p (copy) != 0)
1629             cc0_insn = copy;
1630           else
1631             {
1632               if (cc0_insn)
1633                 try_constants (cc0_insn, map);
1634               cc0_insn = 0;
1635               try_constants (copy, map);
1636             }
1637 #else
1638           try_constants (copy, map);
1639 #endif
1640
1641           /* Make split induction variable constants `permanent' since we
1642              know there are no backward branches across iteration variable
1643              settings which would invalidate this.  */
1644           if (dest_reg_was_split)
1645             {
1646               int regno = REGNO (SET_DEST (pattern));
1647
1648               if (map->const_age_map[regno] == map->const_age)
1649                 map->const_age_map[regno] = -1;
1650             }
1651           break;
1652           
1653         case JUMP_INSN:
1654           if (JUMP_LABEL (insn) == start_label && insn == copy_end
1655               && ! last_iteration)
1656             {
1657               /* This is a branch to the beginning of the loop; this is the
1658                  last insn being copied; and this is not the last iteration.
1659                  In this case, we want to change the original fall through
1660                  case to be a branch past the end of the loop, and the
1661                  original jump label case to fall_through.  */
1662               /* Never map the label in this case.  */
1663
1664               pattern = copy_rtx (PATTERN (insn));
1665               copy = emit_jump_insn (pattern);
1666
1667               if (! invert_exp (pattern, copy)
1668                   || ! redirect_exp (&pattern, JUMP_LABEL (insn),
1669                                      exit_label, copy))
1670                 abort ();
1671             }
1672           else
1673             {
1674               pattern = copy_rtx_and_substitute (PATTERN (insn), map);
1675               copy = emit_jump_insn (pattern);
1676             }
1677           
1678 #ifdef HAVE_cc0
1679           if (cc0_insn)
1680             try_constants (cc0_insn, map);
1681           cc0_insn = 0;
1682 #endif
1683           try_constants (copy, map);
1684
1685           /* Set the jump label of COPY correctly to avoid problems with
1686              later passes of unroll_loop, if INSN had jump label set.  */
1687           if (JUMP_LABEL (insn))
1688             {
1689               rtx label = 0;
1690
1691               /* Can't use the label_map for every insn, since this may be
1692                  the backward branch, and hence the label was not mapped.  */
1693               if (GET_CODE (pattern) == SET)
1694                 {
1695                   tem = SET_SRC (pattern);
1696                   if (GET_CODE (tem) == LABEL_REF)
1697                     label = XEXP (tem, 0);
1698                   else if (GET_CODE (tem) == IF_THEN_ELSE)
1699                     {
1700                       if (XEXP (tem, 1) != pc_rtx)
1701                         label = XEXP (XEXP (tem, 1), 0);
1702                       else
1703                         label = XEXP (XEXP (tem, 2), 0);
1704                     }
1705                   else
1706                     abort ();
1707                 }
1708
1709               if (label && GET_CODE (label) == CODE_LABEL)
1710                 JUMP_LABEL (copy) = label;
1711               else
1712                 {
1713                   /* An unrecognizable jump insn, probably the entry jump
1714                      for a switch statement.  This label must have been mapped,
1715                      so just use the label_map to get the new jump label.  */
1716                   JUMP_LABEL (copy) = map->label_map[CODE_LABEL_NUMBER
1717                                                      (JUMP_LABEL (insn))];
1718                 }
1719           
1720               /* If this is a non-local jump, then must increase the label
1721                  use count so that the label will not be deleted when the
1722                  original jump is deleted.  */
1723               LABEL_NUSES (JUMP_LABEL (copy))++;
1724             }
1725           else if (GET_CODE (PATTERN (copy)) == ADDR_VEC
1726                    || GET_CODE (PATTERN (copy)) == ADDR_DIFF_VEC)
1727             {
1728               rtx pat = PATTERN (copy);
1729               int diff_vec_p = GET_CODE (pat) == ADDR_DIFF_VEC;
1730               int len = XVECLEN (pat, diff_vec_p);
1731               int i;
1732
1733               for (i = 0; i < len; i++)
1734                 LABEL_NUSES (XEXP (XVECEXP (pat, diff_vec_p, i), 0))++;
1735             }
1736
1737           /* If this used to be a conditional jump insn but whose branch
1738              direction is now known, we must do something special.  */
1739           if (condjump_p (insn) && !simplejump_p (insn) && map->last_pc_value)
1740             {
1741 #ifdef HAVE_cc0
1742               /* The previous insn set cc0 for us.  So delete it.  */
1743               delete_insn (PREV_INSN (copy));
1744 #endif
1745
1746               /* If this is now a no-op, delete it.  */
1747               if (map->last_pc_value == pc_rtx)
1748                 {
1749                   delete_insn (copy);
1750                   copy = 0;
1751                 }
1752               else
1753                 /* Otherwise, this is unconditional jump so we must put a
1754                    BARRIER after it.  We could do some dead code elimination
1755                    here, but jump.c will do it just as well.  */
1756                 emit_barrier ();
1757             }
1758           break;
1759           
1760         case CALL_INSN:
1761           pattern = copy_rtx_and_substitute (PATTERN (insn), map);
1762           copy = emit_call_insn (pattern);
1763
1764 #ifdef HAVE_cc0
1765           if (cc0_insn)
1766             try_constants (cc0_insn, map);
1767           cc0_insn = 0;
1768 #endif
1769           try_constants (copy, map);
1770
1771           /* Be lazy and assume CALL_INSNs clobber all hard registers.  */
1772           for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
1773             map->const_equiv_map[i] = 0;
1774           break;
1775           
1776         case CODE_LABEL:
1777           /* If this is the loop start label, then we don't need to emit a
1778              copy of this label since no one will use it.  */
1779
1780           if (insn != start_label)
1781             {
1782               copy = emit_label (map->label_map[CODE_LABEL_NUMBER (insn)]);
1783               map->const_age++;
1784             }
1785           break;
1786           
1787         case BARRIER:
1788           copy = emit_barrier ();
1789           break;
1790           
1791         case NOTE:
1792           /* VTOP notes are valid only before the loop exit test.  If placed
1793              anywhere else, loop may generate bad code.  */
1794              
1795           if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_DELETED
1796               && (NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_VTOP
1797                   || (last_iteration && unroll_type != UNROLL_COMPLETELY)))
1798             copy = emit_note (NOTE_SOURCE_FILE (insn),
1799                               NOTE_LINE_NUMBER (insn));
1800           else
1801             copy = 0;
1802           break;
1803           
1804         default:
1805           abort ();
1806           break;
1807         }
1808       
1809       map->insn_map[INSN_UID (insn)] = copy;
1810     }
1811   while (insn != copy_end);
1812   
1813   /* Now copy the REG_NOTES.  */
1814   insn = copy_start;
1815   do
1816     {
1817       insn = NEXT_INSN (insn);
1818       if ((GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN
1819            || GET_CODE (insn) == CALL_INSN)
1820           && map->insn_map[INSN_UID (insn)])
1821         REG_NOTES (map->insn_map[INSN_UID (insn)])
1822           = copy_rtx_and_substitute (REG_NOTES (insn), map);
1823     }
1824   while (insn != copy_end);
1825
1826   /* There may be notes between copy_notes_from and loop_end.  Emit a copy of
1827      each of these notes here, since there may be some important ones, such as
1828      NOTE_INSN_BLOCK_END notes, in this group.  We don't do this on the last
1829      iteration, because the original notes won't be deleted.
1830
1831      We can't use insert_before here, because when from preconditioning,
1832      insert_before points before the loop.  We can't use copy_end, because
1833      there may be insns already inserted after it (which we don't want to
1834      copy) when not from preconditioning code.  */
1835
1836   if (! last_iteration)
1837     {
1838       for (insn = copy_notes_from; insn != loop_end; insn = NEXT_INSN (insn))
1839         {
1840           if (GET_CODE (insn) == NOTE
1841               && NOTE_LINE_NUMBER (insn) != NOTE_INSN_DELETED)
1842             emit_note (NOTE_SOURCE_FILE (insn), NOTE_LINE_NUMBER (insn));
1843         }
1844     }
1845
1846   if (final_label && LABEL_NUSES (final_label) > 0)
1847     emit_label (final_label);
1848
1849   tem = gen_sequence ();
1850   end_sequence ();
1851   emit_insn_before (tem, insert_before);
1852 }
1853 \f
1854 /* Emit an insn, using the expand_binop to ensure that a valid insn is
1855    emitted.  This will correctly handle the case where the increment value
1856    won't fit in the immediate field of a PLUS insns.  */
1857
1858 void
1859 emit_unrolled_add (dest_reg, src_reg, increment)
1860      rtx dest_reg, src_reg, increment;
1861 {
1862   rtx result;
1863
1864   result = expand_binop (GET_MODE (dest_reg), add_optab, src_reg, increment,
1865                          dest_reg, 0, OPTAB_LIB_WIDEN);
1866
1867   if (dest_reg != result)
1868     emit_move_insn (dest_reg, result);
1869 }
1870 \f
1871 /* Searches the insns between INSN and LOOP_END.  Returns 1 if there
1872    is a backward branch in that range that branches to somewhere between
1873    LOOP_START and INSN.  Returns 0 otherwise.  */
1874
1875 /* ??? This is quadratic algorithm.  Could be rewritten to be linear.
1876    In practice, this is not a problem, because this function is seldom called,
1877    and uses a negligible amount of CPU time on average.  */
1878
1879 static int
1880 back_branch_in_range_p (insn, loop_start, loop_end)
1881      rtx insn;
1882      rtx loop_start, loop_end;
1883 {
1884   rtx p, q, target_insn;
1885
1886   /* Stop before we get to the backward branch at the end of the loop.  */
1887   loop_end = prev_nonnote_insn (loop_end);
1888   if (GET_CODE (loop_end) == BARRIER)
1889     loop_end = PREV_INSN (loop_end);
1890
1891   /* Check in case insn has been deleted, search forward for first non
1892      deleted insn following it.  */
1893   while (INSN_DELETED_P (insn))
1894     insn = NEXT_INSN (insn);
1895
1896   /* Check for the case where insn is the last insn in the loop.  */
1897   if (insn == loop_end)
1898     return 0;
1899
1900   for (p = NEXT_INSN (insn); p != loop_end; p = NEXT_INSN (p))
1901     {
1902       if (GET_CODE (p) == JUMP_INSN)
1903         {
1904           target_insn = JUMP_LABEL (p);
1905           
1906           /* Search from loop_start to insn, to see if one of them is
1907              the target_insn.  We can't use INSN_LUID comparisons here,
1908              since insn may not have an LUID entry.  */
1909           for (q = loop_start; q != insn; q = NEXT_INSN (q))
1910             if (q == target_insn)
1911               return 1;
1912         }
1913     }
1914
1915   return 0;
1916 }
1917
1918 /* Try to generate the simplest rtx for the expression
1919    (PLUS (MULT mult1 mult2) add1).  This is used to calculate the initial
1920    value of giv's.  */
1921
1922 static rtx
1923 fold_rtx_mult_add (mult1, mult2, add1, mode)
1924      rtx mult1, mult2, add1;
1925      enum machine_mode mode;
1926 {
1927   rtx temp, mult_res;
1928   rtx result;
1929
1930   /* The modes must all be the same.  This should always be true.  For now,
1931      check to make sure.  */
1932   if ((GET_MODE (mult1) != mode && GET_MODE (mult1) != VOIDmode)
1933       || (GET_MODE (mult2) != mode && GET_MODE (mult2) != VOIDmode)
1934       || (GET_MODE (add1) != mode && GET_MODE (add1) != VOIDmode))
1935     abort ();
1936
1937   /* Ensure that if at least one of mult1/mult2 are constant, then mult2
1938      will be a constant.  */
1939   if (GET_CODE (mult1) == CONST_INT)
1940     {
1941       temp = mult2;
1942       mult2 = mult1;
1943       mult1 = temp;
1944     }
1945
1946   mult_res = simplify_binary_operation (MULT, mode, mult1, mult2);
1947   if (! mult_res)
1948     mult_res = gen_rtx (MULT, mode, mult1, mult2);
1949
1950   /* Again, put the constant second.  */
1951   if (GET_CODE (add1) == CONST_INT)
1952     {
1953       temp = add1;
1954       add1 = mult_res;
1955       mult_res = temp;
1956     }
1957
1958   result = simplify_binary_operation (PLUS, mode, add1, mult_res);
1959   if (! result)
1960     result = gen_rtx (PLUS, mode, add1, mult_res);
1961
1962   return result;
1963 }
1964
1965 /* Searches the list of induction struct's for the biv BL, to try to calculate
1966    the total increment value for one iteration of the loop as a constant.
1967
1968    Returns the increment value as an rtx, simplified as much as possible,
1969    if it can be calculated.  Otherwise, returns 0.  */
1970
1971 rtx 
1972 biv_total_increment (bl, loop_start, loop_end)
1973      struct iv_class *bl;
1974      rtx loop_start, loop_end;
1975 {
1976   struct induction *v;
1977   rtx result;
1978
1979   /* For increment, must check every instruction that sets it.  Each
1980      instruction must be executed only once each time through the loop.
1981      To verify this, we check that the the insn is always executed, and that
1982      there are no backward branches after the insn that branch to before it.
1983      Also, the insn must have a mult_val of one (to make sure it really is
1984      an increment).  */
1985
1986   result = const0_rtx;
1987   for (v = bl->biv; v; v = v->next_iv)
1988     {
1989       if (v->always_computable && v->mult_val == const1_rtx
1990           && ! back_branch_in_range_p (v->insn, loop_start, loop_end))
1991         result = fold_rtx_mult_add (result, const1_rtx, v->add_val, v->mode);
1992       else
1993         return 0;
1994     }
1995
1996   return result;
1997 }
1998
1999 /* Determine the initial value of the iteration variable, and the amount
2000    that it is incremented each loop.  Use the tables constructed by
2001    the strength reduction pass to calculate these values.
2002
2003    Initial_value and/or increment are set to zero if their values could not
2004    be calculated.  */
2005
2006 static void
2007 iteration_info (iteration_var, initial_value, increment, loop_start, loop_end)
2008      rtx iteration_var, *initial_value, *increment;
2009      rtx loop_start, loop_end;
2010 {
2011   struct iv_class *bl;
2012   struct induction *v, *b;
2013
2014   /* Clear the result values, in case no answer can be found.  */
2015   *initial_value = 0;
2016   *increment = 0;
2017
2018   /* The iteration variable can be either a giv or a biv.  Check to see
2019      which it is, and compute the variable's initial value, and increment
2020      value if possible.  */
2021
2022   /* If this is a new register, can't handle it since we don't have any
2023      reg_iv_type entry for it.  */
2024   if (REGNO (iteration_var) >= max_reg_before_loop)
2025     {
2026       if (loop_dump_stream)
2027         fprintf (loop_dump_stream,
2028                  "Loop unrolling: No reg_iv_type entry for iteration var.\n");
2029       return;
2030     }
2031   /* Reject iteration variables larger than the host long size, since they
2032      could result in a number of iterations greater than the range of our
2033      `unsigned long' variable loop_n_iterations.  */
2034   else if (GET_MODE_BITSIZE (GET_MODE (iteration_var)) > HOST_BITS_PER_LONG)
2035     {
2036       if (loop_dump_stream)
2037         fprintf (loop_dump_stream,
2038                  "Loop unrolling: Iteration var rejected because mode larger than host long.\n");
2039       return;
2040     }
2041   else if (GET_MODE_CLASS (GET_MODE (iteration_var)) != MODE_INT)
2042     {
2043       if (loop_dump_stream)
2044         fprintf (loop_dump_stream,
2045                  "Loop unrolling: Iteration var not an integer.\n");
2046       return;
2047     }
2048   else if (reg_iv_type[REGNO (iteration_var)] == BASIC_INDUCT)
2049     {
2050       /* Grab initial value, only useful if it is a constant.  */
2051       bl = reg_biv_class[REGNO (iteration_var)];
2052       *initial_value = bl->initial_value;
2053
2054       *increment = biv_total_increment (bl, loop_start, loop_end);
2055     }
2056   else if (reg_iv_type[REGNO (iteration_var)] == GENERAL_INDUCT)
2057     {
2058 #if 1
2059       /* ??? The code below does not work because the incorrect number of
2060          iterations is calculated when the biv is incremented after the giv
2061          is set (which is the usual case).  This can probably be accounted
2062          for by biasing the initial_value by subtracting the amount of the
2063          increment that occurs between the giv set and the giv test.  However,
2064          a giv as an iterator is very rare, so it does not seem worthwhile
2065          to handle this.  */
2066       /* ??? An example failure is: i = 6; do {;} while (i++ < 9).  */
2067       if (loop_dump_stream)
2068         fprintf (loop_dump_stream,
2069                  "Loop unrolling: Giv iterators are not handled.\n");
2070       return;
2071 #else
2072       /* Initial value is mult_val times the biv's initial value plus
2073          add_val.  Only useful if it is a constant.  */
2074       v = reg_iv_info[REGNO (iteration_var)];
2075       bl = reg_biv_class[REGNO (v->src_reg)];
2076       *initial_value = fold_rtx_mult_add (v->mult_val, bl->initial_value,
2077                                           v->add_val, v->mode);
2078       
2079       /* Increment value is mult_val times the increment value of the biv.  */
2080
2081       *increment = biv_total_increment (bl, loop_start, loop_end);
2082       if (*increment)
2083         *increment = fold_rtx_mult_add (v->mult_val, *increment, const0_rtx,
2084                                         v->mode);
2085 #endif
2086     }
2087   else
2088     {
2089       if (loop_dump_stream)
2090         fprintf (loop_dump_stream,
2091                  "Loop unrolling: Not basic or general induction var.\n");
2092       return;
2093     }
2094 }
2095
2096 /* Calculate the approximate final value of the iteration variable
2097    which has an loop exit test with code COMPARISON_CODE and comparison value
2098    of COMPARISON_VALUE.  Also returns an indication of whether the comparison
2099    was signed or unsigned, and the direction of the comparison.  This info is
2100    needed to calculate the number of loop iterations.  */
2101
2102 static rtx
2103 approx_final_value (comparison_code, comparison_value, unsigned_p, compare_dir)
2104      enum rtx_code comparison_code;
2105      rtx comparison_value;
2106      int *unsigned_p;
2107      int *compare_dir;
2108 {
2109   /* Calculate the final value of the induction variable.
2110      The exact final value depends on the branch operator, and increment sign.
2111      This is only an approximate value.  It will be wrong if the iteration
2112      variable is not incremented by one each time through the loop, and
2113      approx final value - start value % increment != 0.  */
2114
2115   *unsigned_p = 0;
2116   switch (comparison_code)
2117     {
2118     case LEU:
2119       *unsigned_p = 1;
2120     case LE:
2121       *compare_dir = 1;
2122       return plus_constant (comparison_value, 1);
2123     case GEU:
2124       *unsigned_p = 1;
2125     case GE:
2126       *compare_dir = -1;
2127       return plus_constant (comparison_value, -1);
2128     case EQ:
2129       /* Can not calculate a final value for this case.  */
2130       *compare_dir = 0;
2131       return 0;
2132     case LTU:
2133       *unsigned_p = 1;
2134     case LT:
2135       *compare_dir = 1;
2136       return comparison_value;
2137       break;
2138     case GTU:
2139       *unsigned_p = 1;
2140     case GT:
2141       *compare_dir = -1;
2142       return comparison_value;
2143     case NE:
2144       *compare_dir = 0;
2145       return comparison_value;
2146     default:
2147       abort ();
2148     }
2149 }
2150
2151 /* For each biv and giv, determine whether it can be safely split into
2152    a different variable for each unrolled copy of the loop body.  If it
2153    is safe to split, then indicate that by saving some useful info
2154    in the splittable_regs array.
2155
2156    If the loop is being completely unrolled, then splittable_regs will hold
2157    the current value of the induction variable while the loop is unrolled.
2158    It must be set to the initial value of the induction variable here.
2159    Otherwise, splittable_regs will hold the difference between the current
2160    value of the induction variable and the value the induction variable had
2161    at the top of the loop.  It must be set to the value 0 here.  */
2162
2163 /* ?? If the loop is only unrolled twice, then most of the restrictions to
2164    constant values are unnecessary, since we can easily calculate increment
2165    values in this case even if nothing is constant.  The increment value
2166    should not involve a multiply however.  */
2167
2168 /* ?? Even if the biv/giv increment values aren't constant, it may still
2169    be beneficial to split the variable if the loop is only unrolled a few
2170    times, since multiplies by small integers (1,2,3,4) are very cheap.  */
2171
2172 static int
2173 find_splittable_regs (unroll_type, loop_start, loop_end, end_insert_before,
2174                      unroll_number)
2175      enum unroll_types unroll_type;
2176      rtx loop_start, loop_end;
2177      rtx end_insert_before;
2178      int unroll_number;
2179 {
2180   struct iv_class *bl;
2181   struct induction *v;
2182   rtx increment, tem;
2183   rtx biv_final_value;
2184   int biv_splittable;
2185   int result = 0;
2186
2187   for (bl = loop_iv_list; bl; bl = bl->next)
2188     {
2189       /* Biv_total_increment must return a constant value,
2190          otherwise we can not calculate the split values.  */
2191
2192       increment = biv_total_increment (bl, loop_start, loop_end);
2193       if (! increment || GET_CODE (increment) != CONST_INT)
2194         continue;
2195
2196       /* The loop must be unrolled completely, or else have a known number
2197          of iterations and only one exit, or else the biv must be dead
2198          outside the loop, or else the final value must be known.  Otherwise,
2199          it is unsafe to split the biv since it may not have the proper
2200          value on loop exit.  */
2201
2202       /* loop_number_exit_labels is non-zero if the loop has an exit other than
2203          a fall through at the end.  */
2204
2205       biv_splittable = 1;
2206       biv_final_value = 0;
2207       if (unroll_type != UNROLL_COMPLETELY
2208           && (loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]]
2209               || unroll_type == UNROLL_NAIVE)
2210           && (uid_luid[regno_last_uid[bl->regno]] >= INSN_LUID (loop_end)
2211               || ! bl->init_insn
2212               || INSN_UID (bl->init_insn) >= max_uid_for_loop
2213               || (uid_luid[regno_first_uid[bl->regno]]
2214                   < INSN_LUID (bl->init_insn))
2215               || reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
2216           && ! (biv_final_value = final_biv_value (bl, loop_start, loop_end)))
2217         biv_splittable = 0;
2218
2219       /* If any of the insns setting the BIV don't do so with a simple
2220          PLUS, we don't know how to split it.  */
2221       for (v = bl->biv; biv_splittable && v; v = v->next_iv)
2222         if ((tem = single_set (v->insn)) == 0
2223             || GET_CODE (SET_DEST (tem)) != REG
2224             || REGNO (SET_DEST (tem)) != bl->regno
2225             || GET_CODE (SET_SRC (tem)) != PLUS)
2226           biv_splittable = 0;
2227
2228       /* If final value is non-zero, then must emit an instruction which sets
2229          the value of the biv to the proper value.  This is done after
2230          handling all of the givs, since some of them may need to use the
2231          biv's value in their initialization code.  */
2232
2233       /* This biv is splittable.  If completely unrolling the loop, save
2234          the biv's initial value.  Otherwise, save the constant zero.  */
2235
2236       if (biv_splittable == 1)
2237         {
2238           if (unroll_type == UNROLL_COMPLETELY)
2239             {
2240               /* If the initial value of the biv is itself (i.e. it is too
2241                  complicated for strength_reduce to compute), or is a hard
2242                  register, then we must create a new pseudo reg to hold the
2243                  initial value of the biv.  */
2244
2245               if (GET_CODE (bl->initial_value) == REG
2246                   && (REGNO (bl->initial_value) == bl->regno
2247                       || REGNO (bl->initial_value) < FIRST_PSEUDO_REGISTER))
2248                 {
2249                   rtx tem = gen_reg_rtx (bl->biv->mode);
2250                   
2251                   emit_insn_before (gen_move_insn (tem, bl->biv->src_reg),
2252                                     loop_start);
2253
2254                   if (loop_dump_stream)
2255                     fprintf (loop_dump_stream, "Biv %d initial value remapped to %d.\n",
2256                              bl->regno, REGNO (tem));
2257
2258                   splittable_regs[bl->regno] = tem;
2259                 }
2260               else
2261                 splittable_regs[bl->regno] = bl->initial_value;
2262             }
2263           else
2264             splittable_regs[bl->regno] = const0_rtx;
2265
2266           /* Save the number of instructions that modify the biv, so that
2267              we can treat the last one specially.  */
2268
2269           splittable_regs_updates[bl->regno] = bl->biv_count;
2270
2271           result++;
2272
2273           if (loop_dump_stream)
2274             fprintf (loop_dump_stream,
2275                      "Biv %d safe to split.\n", bl->regno);
2276         }
2277
2278       /* Check every giv that depends on this biv to see whether it is
2279          splittable also.  Even if the biv isn't splittable, givs which
2280          depend on it may be splittable if the biv is live outside the
2281          loop, and the givs aren't.  */
2282
2283       result = find_splittable_givs (bl, unroll_type, loop_start, loop_end,
2284                                      increment, unroll_number, result);
2285
2286       /* If final value is non-zero, then must emit an instruction which sets
2287          the value of the biv to the proper value.  This is done after
2288          handling all of the givs, since some of them may need to use the
2289          biv's value in their initialization code.  */
2290       if (biv_final_value)
2291         {
2292           /* If the loop has multiple exits, emit the insns before the
2293              loop to ensure that it will always be executed no matter
2294              how the loop exits.  Otherwise emit the insn after the loop,
2295              since this is slightly more efficient.  */
2296           if (! loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]])
2297             emit_insn_before (gen_move_insn (bl->biv->src_reg,
2298                                              biv_final_value),
2299                               end_insert_before);
2300           else
2301             {
2302               /* Create a new register to hold the value of the biv, and then
2303                  set the biv to its final value before the loop start.  The biv
2304                  is set to its final value before loop start to ensure that
2305                  this insn will always be executed, no matter how the loop
2306                  exits.  */
2307               rtx tem = gen_reg_rtx (bl->biv->mode);
2308               emit_insn_before (gen_move_insn (tem, bl->biv->src_reg),
2309                                 loop_start);
2310               emit_insn_before (gen_move_insn (bl->biv->src_reg,
2311                                                biv_final_value),
2312                                 loop_start);
2313
2314               if (loop_dump_stream)
2315                 fprintf (loop_dump_stream, "Biv %d mapped to %d for split.\n",
2316                          REGNO (bl->biv->src_reg), REGNO (tem));
2317
2318               /* Set up the mapping from the original biv register to the new
2319                  register.  */
2320               bl->biv->src_reg = tem;
2321             }
2322         }
2323     }
2324   return result;
2325 }
2326
2327 /* For every giv based on the biv BL, check to determine whether it is
2328    splittable.  This is a subroutine to find_splittable_regs ().  */
2329
2330 static int
2331 find_splittable_givs (bl, unroll_type, loop_start, loop_end, increment,
2332                       unroll_number, result)
2333      struct iv_class *bl;
2334      enum unroll_types unroll_type;
2335      rtx loop_start, loop_end;
2336      rtx increment;
2337      int unroll_number, result;
2338 {
2339   struct induction *v;
2340   rtx final_value;
2341   rtx tem;
2342
2343   for (v = bl->giv; v; v = v->next_iv)
2344     {
2345       rtx giv_inc, value;
2346
2347       /* Only split the giv if it has already been reduced, or if the loop is
2348          being completely unrolled.  */
2349       if (unroll_type != UNROLL_COMPLETELY && v->ignore)
2350         continue;
2351
2352       /* The giv can be split if the insn that sets the giv is executed once
2353          and only once on every iteration of the loop.  */
2354       /* An address giv can always be split.  v->insn is just a use not a set,
2355          and hence it does not matter whether it is always executed.  All that
2356          matters is that all the biv increments are always executed, and we
2357          won't reach here if they aren't.  */
2358       if (v->giv_type != DEST_ADDR
2359           && (! v->always_computable
2360               || back_branch_in_range_p (v->insn, loop_start, loop_end)))
2361         continue;
2362       
2363       /* The giv increment value must be a constant.  */
2364       giv_inc = fold_rtx_mult_add (v->mult_val, increment, const0_rtx,
2365                                    v->mode);
2366       if (! giv_inc || GET_CODE (giv_inc) != CONST_INT)
2367         continue;
2368
2369       /* The loop must be unrolled completely, or else have a known number of
2370          iterations and only one exit, or else the giv must be dead outside
2371          the loop, or else the final value of the giv must be known.
2372          Otherwise, it is not safe to split the giv since it may not have the
2373          proper value on loop exit.  */
2374           
2375       /* The used outside loop test will fail for DEST_ADDR givs.  They are
2376          never used outside the loop anyways, so it is always safe to split a
2377          DEST_ADDR giv.  */
2378
2379       final_value = 0;
2380       if (unroll_type != UNROLL_COMPLETELY
2381           && (loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]]
2382               || unroll_type == UNROLL_NAIVE)
2383           && v->giv_type != DEST_ADDR
2384           && ((regno_first_uid[REGNO (v->dest_reg)] != INSN_UID (v->insn)
2385                /* Check for the case where the pseudo is set by a shift/add
2386                   sequence, in which case the first insn setting the pseudo
2387                   is the first insn of the shift/add sequence.  */
2388                && (! (tem = find_reg_note (v->insn, REG_RETVAL, NULL_RTX))
2389                    || (regno_first_uid[REGNO (v->dest_reg)]
2390                        != INSN_UID (XEXP (tem, 0)))))
2391               /* Line above always fails if INSN was moved by loop opt.  */
2392               || (uid_luid[regno_last_uid[REGNO (v->dest_reg)]]
2393                   >= INSN_LUID (loop_end)))
2394           && ! (final_value = v->final_value))
2395         continue;
2396
2397 #if 0
2398       /* Currently, non-reduced/final-value givs are never split.  */
2399       /* Should emit insns after the loop if possible, as the biv final value
2400          code below does.  */
2401
2402       /* If the final value is non-zero, and the giv has not been reduced,
2403          then must emit an instruction to set the final value.  */
2404       if (final_value && !v->new_reg)
2405         {
2406           /* Create a new register to hold the value of the giv, and then set
2407              the giv to its final value before the loop start.  The giv is set
2408              to its final value before loop start to ensure that this insn
2409              will always be executed, no matter how we exit.  */
2410           tem = gen_reg_rtx (v->mode);
2411           emit_insn_before (gen_move_insn (tem, v->dest_reg), loop_start);
2412           emit_insn_before (gen_move_insn (v->dest_reg, final_value),
2413                             loop_start);
2414           
2415           if (loop_dump_stream)
2416             fprintf (loop_dump_stream, "Giv %d mapped to %d for split.\n",
2417                      REGNO (v->dest_reg), REGNO (tem));
2418           
2419           v->src_reg = tem;
2420         }
2421 #endif
2422
2423       /* This giv is splittable.  If completely unrolling the loop, save the
2424          giv's initial value.  Otherwise, save the constant zero for it.  */
2425
2426       if (unroll_type == UNROLL_COMPLETELY)
2427         {
2428           /* It is not safe to use bl->initial_value here, because it may not
2429              be invariant.  It is safe to use the initial value stored in
2430              the splittable_regs array if it is set.  In rare cases, it won't
2431              be set, so then we do exactly the same thing as
2432              find_splittable_regs does to get a safe value.  */
2433           rtx biv_initial_value;
2434
2435           if (splittable_regs[bl->regno])
2436             biv_initial_value = splittable_regs[bl->regno];
2437           else if (GET_CODE (bl->initial_value) != REG
2438                    || (REGNO (bl->initial_value) != bl->regno
2439                        && REGNO (bl->initial_value) >= FIRST_PSEUDO_REGISTER))
2440             biv_initial_value = bl->initial_value;
2441           else
2442             {
2443               rtx tem = gen_reg_rtx (bl->biv->mode);
2444
2445               emit_insn_before (gen_move_insn (tem, bl->biv->src_reg),
2446                                 loop_start);
2447               biv_initial_value = tem;
2448             }
2449           value = fold_rtx_mult_add (v->mult_val, biv_initial_value,
2450                                      v->add_val, v->mode);
2451         }
2452       else
2453         value = const0_rtx;
2454
2455       if (v->new_reg)
2456         {
2457           /* If a giv was combined with another giv, then we can only split
2458              this giv if the giv it was combined with was reduced.  This
2459              is because the value of v->new_reg is meaningless in this
2460              case.  */
2461           if (v->same && ! v->same->new_reg)
2462             {
2463               if (loop_dump_stream)
2464                 fprintf (loop_dump_stream,
2465                          "giv combined with unreduced giv not split.\n");
2466               continue;
2467             }
2468           /* If the giv is an address destination, it could be something other
2469              than a simple register, these have to be treated differently.  */
2470           else if (v->giv_type == DEST_REG)
2471             {
2472               /* If value is not a constant, register, or register plus
2473                  constant, then compute its value into a register before
2474                  loop start.  This prevents illegal rtx sharing, and should
2475                  generate better code.  We can use bl->initial_value here
2476                  instead of splittable_regs[bl->regno] because this code
2477                  is going before the loop start.  */
2478               if (unroll_type == UNROLL_COMPLETELY
2479                   && GET_CODE (value) != CONST_INT
2480                   && GET_CODE (value) != REG
2481                   && (GET_CODE (value) != PLUS
2482                       || GET_CODE (XEXP (value, 0)) != REG
2483                       || GET_CODE (XEXP (value, 1)) != CONST_INT))
2484                 {
2485                   rtx tem = gen_reg_rtx (v->mode);
2486                   emit_iv_add_mult (bl->initial_value, v->mult_val,
2487                                     v->add_val, tem, loop_start);
2488                   value = tem;
2489                 }
2490                 
2491               splittable_regs[REGNO (v->new_reg)] = value;
2492             }
2493           else
2494             {
2495               /* Splitting address givs is useful since it will often allow us
2496                  to eliminate some increment insns for the base giv as
2497                  unnecessary.  */
2498
2499               /* If the addr giv is combined with a dest_reg giv, then all
2500                  references to that dest reg will be remapped, which is NOT
2501                  what we want for split addr regs. We always create a new
2502                  register for the split addr giv, just to be safe.  */
2503
2504               /* ??? If there are multiple address givs which have been
2505                  combined with the same dest_reg giv, then we may only need
2506                  one new register for them.  Pulling out constants below will
2507                  catch some of the common cases of this.  Currently, I leave
2508                  the work of simplifying multiple address givs to the
2509                  following cse pass.  */
2510               
2511               v->const_adjust = 0;
2512               if (unroll_type != UNROLL_COMPLETELY)
2513                 {
2514                   /* If not completely unrolling the loop, then create a new
2515                      register to hold the split value of the DEST_ADDR giv.
2516                      Emit insn to initialize its value before loop start.  */
2517                   tem = gen_reg_rtx (v->mode);
2518
2519                   /* If the address giv has a constant in its new_reg value,
2520                      then this constant can be pulled out and put in value,
2521                      instead of being part of the initialization code.  */
2522                   
2523                   if (GET_CODE (v->new_reg) == PLUS
2524                       && GET_CODE (XEXP (v->new_reg, 1)) == CONST_INT)
2525                     {
2526                       v->dest_reg
2527                         = plus_constant (tem, INTVAL (XEXP (v->new_reg,1)));
2528                       
2529                       /* Only succeed if this will give valid addresses.
2530                          Try to validate both the first and the last
2531                          address resulting from loop unrolling, if
2532                          one fails, then can't do const elim here.  */
2533                       if (memory_address_p (v->mem_mode, v->dest_reg)
2534                           && memory_address_p (v->mem_mode,
2535                                        plus_constant (v->dest_reg,
2536                                                       INTVAL (giv_inc)
2537                                                       * (unroll_number - 1))))
2538                         {
2539                           /* Save the negative of the eliminated const, so
2540                              that we can calculate the dest_reg's increment
2541                              value later.  */
2542                           v->const_adjust = - INTVAL (XEXP (v->new_reg, 1));
2543
2544                           v->new_reg = XEXP (v->new_reg, 0);
2545                           if (loop_dump_stream)
2546                             fprintf (loop_dump_stream,
2547                                      "Eliminating constant from giv %d\n",
2548                                      REGNO (tem));
2549                         }
2550                       else
2551                         v->dest_reg = tem;
2552                     }
2553                   else
2554                     v->dest_reg = tem;
2555                   
2556                   /* If the address hasn't been checked for validity yet, do so
2557                      now, and fail completely if either the first or the last
2558                      unrolled copy of the address is not a valid address.  */
2559                   if (v->dest_reg == tem
2560                       && (! memory_address_p (v->mem_mode, v->dest_reg)
2561                           || ! memory_address_p (v->mem_mode,
2562                                  plus_constant (v->dest_reg,
2563                                                 INTVAL (giv_inc)
2564                                                 * (unroll_number -1)))))
2565                     {
2566                       if (loop_dump_stream)
2567                         fprintf (loop_dump_stream,
2568                                  "Illegal address for giv at insn %d\n",
2569                                  INSN_UID (v->insn));
2570                       continue;
2571                     }
2572                   
2573                   /* To initialize the new register, just move the value of
2574                      new_reg into it.  This is not guaranteed to give a valid
2575                      instruction on machines with complex addressing modes.
2576                      If we can't recognize it, then delete it and emit insns
2577                      to calculate the value from scratch.  */
2578                   emit_insn_before (gen_rtx (SET, VOIDmode, tem,
2579                                              copy_rtx (v->new_reg)),
2580                                     loop_start);
2581                   if (recog_memoized (PREV_INSN (loop_start)) < 0)
2582                     {
2583                       delete_insn (PREV_INSN (loop_start));
2584                       emit_iv_add_mult (bl->initial_value, v->mult_val,
2585                                         v->add_val, tem, loop_start);
2586                       if (loop_dump_stream)
2587                         fprintf (loop_dump_stream,
2588                                  "Illegal init insn, rewritten.\n");
2589                     }
2590                 }
2591               else
2592                 {
2593                   v->dest_reg = value;
2594                   
2595                   /* Check the resulting address for validity, and fail
2596                      if the resulting address would be illegal.  */
2597                   if (! memory_address_p (v->mem_mode, v->dest_reg)
2598                       || ! memory_address_p (v->mem_mode,
2599                                      plus_constant (v->dest_reg,
2600                                                     INTVAL (giv_inc) *
2601                                                     (unroll_number -1))))
2602                     {
2603                       if (loop_dump_stream)
2604                         fprintf (loop_dump_stream,
2605                                  "Illegal address for giv at insn %d\n",
2606                                  INSN_UID (v->insn));
2607                       continue;
2608                     }
2609                 }
2610               
2611               /* Store the value of dest_reg into the insn.  This sharing
2612                  will not be a problem as this insn will always be copied
2613                  later.  */
2614               
2615               *v->location = v->dest_reg;
2616               
2617               /* If this address giv is combined with a dest reg giv, then
2618                  save the base giv's induction pointer so that we will be
2619                  able to handle this address giv properly.  The base giv
2620                  itself does not have to be splittable.  */
2621               
2622               if (v->same && v->same->giv_type == DEST_REG)
2623                 addr_combined_regs[REGNO (v->same->new_reg)] = v->same;
2624               
2625               if (GET_CODE (v->new_reg) == REG)
2626                 {
2627                   /* This giv maybe hasn't been combined with any others.
2628                      Make sure that it's giv is marked as splittable here.  */
2629                   
2630                   splittable_regs[REGNO (v->new_reg)] = value;
2631                   
2632                   /* Make it appear to depend upon itself, so that the
2633                      giv will be properly split in the main loop above.  */
2634                   if (! v->same)
2635                     {
2636                       v->same = v;
2637                       addr_combined_regs[REGNO (v->new_reg)] = v;
2638                     }
2639                 }
2640
2641               if (loop_dump_stream)
2642                 fprintf (loop_dump_stream, "DEST_ADDR giv being split.\n");
2643             }
2644         }
2645       else
2646         {
2647 #if 0
2648           /* Currently, unreduced giv's can't be split.  This is not too much
2649              of a problem since unreduced giv's are not live across loop
2650              iterations anyways.  When unrolling a loop completely though,
2651              it makes sense to reduce&split givs when possible, as this will
2652              result in simpler instructions, and will not require that a reg
2653              be live across loop iterations.  */
2654           
2655           splittable_regs[REGNO (v->dest_reg)] = value;
2656           fprintf (stderr, "Giv %d at insn %d not reduced\n",
2657                    REGNO (v->dest_reg), INSN_UID (v->insn));
2658 #else
2659           continue;
2660 #endif
2661         }
2662       
2663       /* Givs are only updated once by definition.  Mark it so if this is
2664          a splittable register.  Don't need to do anything for address givs
2665          where this may not be a register.  */
2666
2667       if (GET_CODE (v->new_reg) == REG)
2668         splittable_regs_updates[REGNO (v->new_reg)] = 1;
2669
2670       result++;
2671       
2672       if (loop_dump_stream)
2673         {
2674           int regnum;
2675           
2676           if (GET_CODE (v->dest_reg) == CONST_INT)
2677             regnum = -1;
2678           else if (GET_CODE (v->dest_reg) != REG)
2679             regnum = REGNO (XEXP (v->dest_reg, 0));
2680           else
2681             regnum = REGNO (v->dest_reg);
2682           fprintf (loop_dump_stream, "Giv %d at insn %d safe to split.\n",
2683                    regnum, INSN_UID (v->insn));
2684         }
2685     }
2686
2687   return result;
2688 }
2689 \f
2690 /* Try to prove that the register is dead after the loop exits.  Trace every
2691    loop exit looking for an insn that will always be executed, which sets
2692    the register to some value, and appears before the first use of the register
2693    is found.  If successful, then return 1, otherwise return 0.  */
2694
2695 /* ?? Could be made more intelligent in the handling of jumps, so that
2696    it can search past if statements and other similar structures.  */
2697
2698 static int
2699 reg_dead_after_loop (reg, loop_start, loop_end)
2700      rtx reg, loop_start, loop_end;
2701 {
2702   rtx insn, label;
2703   enum rtx_code code;
2704   int jump_count = 0;
2705
2706   /* HACK: Must also search the loop fall through exit, create a label_ref
2707      here which points to the loop_end, and append the loop_number_exit_labels
2708      list to it.  */
2709   label = gen_rtx (LABEL_REF, VOIDmode, loop_end);
2710   LABEL_NEXTREF (label)
2711     = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
2712
2713   for ( ; label; label = LABEL_NEXTREF (label))
2714     {
2715       /* Succeed if find an insn which sets the biv or if reach end of
2716          function.  Fail if find an insn that uses the biv, or if come to
2717          a conditional jump.  */
2718
2719       insn = NEXT_INSN (XEXP (label, 0));
2720       while (insn)
2721         {
2722           code = GET_CODE (insn);
2723           if (GET_RTX_CLASS (code) == 'i')
2724             {
2725               rtx set;
2726
2727               if (reg_referenced_p (reg, PATTERN (insn)))
2728                 return 0;
2729
2730               set = single_set (insn);
2731               if (set && rtx_equal_p (SET_DEST (set), reg))
2732                 break;
2733             }
2734
2735           if (code == JUMP_INSN)
2736             {
2737               if (GET_CODE (PATTERN (insn)) == RETURN)
2738                 break;
2739               else if (! simplejump_p (insn)
2740                        /* Prevent infinite loop following infinite loops. */
2741                        || jump_count++ > 20)
2742                 return 0;
2743               else
2744                 insn = JUMP_LABEL (insn);
2745             }
2746
2747           insn = NEXT_INSN (insn);
2748         }
2749     }
2750
2751   /* Success, the register is dead on all loop exits.  */
2752   return 1;
2753 }
2754
2755 /* Try to calculate the final value of the biv, the value it will have at
2756    the end of the loop.  If we can do it, return that value.  */
2757   
2758 rtx
2759 final_biv_value (bl, loop_start, loop_end)
2760      struct iv_class *bl;
2761      rtx loop_start, loop_end;
2762 {
2763   rtx increment, tem;
2764
2765   /* ??? This only works for MODE_INT biv's.  Reject all others for now.  */
2766
2767   if (GET_MODE_CLASS (bl->biv->mode) != MODE_INT)
2768     return 0;
2769
2770   /* The final value for reversed bivs must be calculated differently than
2771       for ordinary bivs.  In this case, there is already an insn after the
2772      loop which sets this biv's final value (if necessary), and there are
2773      no other loop exits, so we can return any value.  */
2774   if (bl->reversed)
2775     {
2776       if (loop_dump_stream)
2777         fprintf (loop_dump_stream,
2778                  "Final biv value for %d, reversed biv.\n", bl->regno);
2779                  
2780       return const0_rtx;
2781     }
2782
2783   /* Try to calculate the final value as initial value + (number of iterations
2784      * increment).  For this to work, increment must be invariant, the only
2785      exit from the loop must be the fall through at the bottom (otherwise
2786      it may not have its final value when the loop exits), and the initial
2787      value of the biv must be invariant.  */
2788
2789   if (loop_n_iterations != 0
2790       && ! loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]]
2791       && invariant_p (bl->initial_value))
2792     {
2793       increment = biv_total_increment (bl, loop_start, loop_end);
2794       
2795       if (increment && invariant_p (increment))
2796         {
2797           /* Can calculate the loop exit value, emit insns after loop
2798              end to calculate this value into a temporary register in
2799              case it is needed later.  */
2800
2801           tem = gen_reg_rtx (bl->biv->mode);
2802           emit_iv_add_mult (increment, GEN_INT (loop_n_iterations),
2803                             bl->initial_value, tem, NEXT_INSN (loop_end));
2804
2805           if (loop_dump_stream)
2806             fprintf (loop_dump_stream,
2807                      "Final biv value for %d, calculated.\n", bl->regno);
2808           
2809           return tem;
2810         }
2811     }
2812
2813   /* Check to see if the biv is dead at all loop exits.  */
2814   if (reg_dead_after_loop (bl->biv->src_reg, loop_start, loop_end))
2815     {
2816       if (loop_dump_stream)
2817         fprintf (loop_dump_stream,
2818                  "Final biv value for %d, biv dead after loop exit.\n",
2819                  bl->regno);
2820
2821       return const0_rtx;
2822     }
2823
2824   return 0;
2825 }
2826
2827 /* Try to calculate the final value of the giv, the value it will have at
2828    the end of the loop.  If we can do it, return that value.  */
2829
2830 rtx
2831 final_giv_value (v, loop_start, loop_end)
2832      struct induction *v;
2833      rtx loop_start, loop_end;
2834 {
2835   struct iv_class *bl;
2836   rtx insn;
2837   rtx increment, tem;
2838   enum rtx_code code;
2839   rtx insert_before, seq;
2840
2841   bl = reg_biv_class[REGNO (v->src_reg)];
2842
2843   /* The final value for givs which depend on reversed bivs must be calculated
2844      differently than for ordinary givs.  In this case, there is already an
2845      insn after the loop which sets this giv's final value (if necessary),
2846      and there are no other loop exits, so we can return any value.  */
2847   if (bl->reversed)
2848     {
2849       if (loop_dump_stream)
2850         fprintf (loop_dump_stream,
2851                  "Final giv value for %d, depends on reversed biv\n",
2852                  REGNO (v->dest_reg));
2853       return const0_rtx;
2854     }
2855
2856   /* Try to calculate the final value as a function of the biv it depends
2857      upon.  The only exit from the loop must be the fall through at the bottom
2858      (otherwise it may not have its final value when the loop exits).  */
2859       
2860   /* ??? Can calculate the final giv value by subtracting off the
2861      extra biv increments times the giv's mult_val.  The loop must have
2862      only one exit for this to work, but the loop iterations does not need
2863      to be known.  */
2864
2865   if (loop_n_iterations != 0
2866       && ! loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]])
2867     {
2868       /* ?? It is tempting to use the biv's value here since these insns will
2869          be put after the loop, and hence the biv will have its final value
2870          then.  However, this fails if the biv is subsequently eliminated.
2871          Perhaps determine whether biv's are eliminable before trying to
2872          determine whether giv's are replaceable so that we can use the
2873          biv value here if it is not eliminable.  */
2874
2875       increment = biv_total_increment (bl, loop_start, loop_end);
2876
2877       if (increment && invariant_p (increment))
2878         {
2879           /* Can calculate the loop exit value of its biv as
2880              (loop_n_iterations * increment) + initial_value */
2881               
2882           /* The loop exit value of the giv is then
2883              (final_biv_value - extra increments) * mult_val + add_val.
2884              The extra increments are any increments to the biv which
2885              occur in the loop after the giv's value is calculated.
2886              We must search from the insn that sets the giv to the end
2887              of the loop to calculate this value.  */
2888
2889           insert_before = NEXT_INSN (loop_end);
2890
2891           /* Put the final biv value in tem.  */
2892           tem = gen_reg_rtx (bl->biv->mode);
2893           emit_iv_add_mult (increment, GEN_INT (loop_n_iterations),
2894                             bl->initial_value, tem, insert_before);
2895
2896           /* Subtract off extra increments as we find them.  */
2897           for (insn = NEXT_INSN (v->insn); insn != loop_end;
2898                insn = NEXT_INSN (insn))
2899             {
2900               struct induction *biv;
2901
2902               for (biv = bl->biv; biv; biv = biv->next_iv)
2903                 if (biv->insn == insn)
2904                   {
2905                     start_sequence ();
2906                     tem = expand_binop (GET_MODE (tem), sub_optab, tem,
2907                                         biv->add_val, NULL_RTX, 0,
2908                                         OPTAB_LIB_WIDEN);
2909                     seq = gen_sequence ();
2910                     end_sequence ();
2911                     emit_insn_before (seq, insert_before);
2912                   }
2913             }
2914           
2915           /* Now calculate the giv's final value.  */
2916           emit_iv_add_mult (tem, v->mult_val, v->add_val, tem,
2917                             insert_before);
2918           
2919           if (loop_dump_stream)
2920             fprintf (loop_dump_stream,
2921                      "Final giv value for %d, calc from biv's value.\n",
2922                      REGNO (v->dest_reg));
2923
2924           return tem;
2925         }
2926     }
2927
2928   /* Replaceable giv's should never reach here.  */
2929   if (v->replaceable)
2930     abort ();
2931
2932   /* Check to see if the biv is dead at all loop exits.  */
2933   if (reg_dead_after_loop (v->dest_reg, loop_start, loop_end))
2934     {
2935       if (loop_dump_stream)
2936         fprintf (loop_dump_stream,
2937                  "Final giv value for %d, giv dead after loop exit.\n",
2938                  REGNO (v->dest_reg));
2939
2940       return const0_rtx;
2941     }
2942
2943   return 0;
2944 }
2945
2946
2947 /* Calculate the number of loop iterations.  Returns the exact number of loop
2948    iterations if it can be calculated, otherwise returns zero.  */
2949
2950 unsigned HOST_WIDE_INT
2951 loop_iterations (loop_start, loop_end)
2952      rtx loop_start, loop_end;
2953 {
2954   rtx comparison, comparison_value;
2955   rtx iteration_var, initial_value, increment, final_value;
2956   enum rtx_code comparison_code;
2957   HOST_WIDE_INT i;
2958   int increment_dir;
2959   int unsigned_compare, compare_dir, final_larger;
2960   unsigned long tempu;
2961   rtx last_loop_insn;
2962
2963   /* First find the iteration variable.  If the last insn is a conditional
2964      branch, and the insn before tests a register value, make that the
2965      iteration variable.  */
2966   
2967   loop_initial_value = 0;
2968   loop_increment = 0;
2969   loop_final_value = 0;
2970   loop_iteration_var = 0;
2971
2972   last_loop_insn = prev_nonnote_insn (loop_end);
2973
2974   comparison = get_condition_for_loop (last_loop_insn);
2975   if (comparison == 0)
2976     {
2977       if (loop_dump_stream)
2978         fprintf (loop_dump_stream,
2979                  "Loop unrolling: No final conditional branch found.\n");
2980       return 0;
2981     }
2982
2983   /* ??? Get_condition may switch position of induction variable and
2984      invariant register when it canonicalizes the comparison.  */
2985
2986   comparison_code = GET_CODE (comparison);
2987   iteration_var = XEXP (comparison, 0);
2988   comparison_value = XEXP (comparison, 1);
2989
2990   if (GET_CODE (iteration_var) != REG)
2991     {
2992       if (loop_dump_stream)
2993         fprintf (loop_dump_stream,
2994                  "Loop unrolling: Comparison not against register.\n");
2995       return 0;
2996     }
2997
2998   /* Loop iterations is always called before any new registers are created
2999      now, so this should never occur.  */
3000
3001   if (REGNO (iteration_var) >= max_reg_before_loop)
3002     abort ();
3003
3004   iteration_info (iteration_var, &initial_value, &increment,
3005                   loop_start, loop_end);
3006   if (initial_value == 0)
3007     /* iteration_info already printed a message.  */
3008     return 0;
3009
3010   if (increment == 0)
3011     {
3012       if (loop_dump_stream)
3013         fprintf (loop_dump_stream,
3014                  "Loop unrolling: Increment value can't be calculated.\n");
3015       return 0;
3016     }
3017   if (GET_CODE (increment) != CONST_INT)
3018     {
3019       if (loop_dump_stream)
3020         fprintf (loop_dump_stream,
3021                  "Loop unrolling: Increment value not constant.\n");
3022       return 0;
3023     }
3024   if (GET_CODE (initial_value) != CONST_INT)
3025     {
3026       if (loop_dump_stream)
3027         fprintf (loop_dump_stream,
3028                  "Loop unrolling: Initial value not constant.\n");
3029       return 0;
3030     }
3031
3032   /* If the comparison value is an invariant register, then try to find
3033      its value from the insns before the start of the loop.  */
3034
3035   if (GET_CODE (comparison_value) == REG && invariant_p (comparison_value))
3036     {
3037       rtx insn, set;
3038     
3039       for (insn = PREV_INSN (loop_start); insn ; insn = PREV_INSN (insn))
3040         {
3041           if (GET_CODE (insn) == CODE_LABEL)
3042             break;
3043
3044           else if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
3045                    && (set = single_set (insn))
3046                    && (SET_DEST (set) == comparison_value))
3047             {
3048               rtx note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
3049
3050               if (note && GET_CODE (XEXP (note, 0)) != EXPR_LIST)
3051                 comparison_value = XEXP (note, 0);
3052
3053               break;
3054             }
3055         }
3056     }
3057
3058   final_value = approx_final_value (comparison_code, comparison_value,
3059                                     &unsigned_compare, &compare_dir);
3060
3061   /* Save the calculated values describing this loop's bounds, in case
3062      precondition_loop_p will need them later.  These values can not be
3063      recalculated inside precondition_loop_p because strength reduction
3064      optimizations may obscure the loop's structure.  */
3065
3066   loop_iteration_var = iteration_var;
3067   loop_initial_value = initial_value;
3068   loop_increment = increment;
3069   loop_final_value = final_value;
3070
3071   if (final_value == 0)
3072     {
3073       if (loop_dump_stream)
3074         fprintf (loop_dump_stream,
3075                  "Loop unrolling: EQ comparison loop.\n");
3076       return 0;
3077     }
3078   else if (GET_CODE (final_value) != CONST_INT)
3079     {
3080       if (loop_dump_stream)
3081         fprintf (loop_dump_stream,
3082                  "Loop unrolling: Final value not constant.\n");
3083       return 0;
3084     }
3085
3086   /* ?? Final value and initial value do not have to be constants.
3087      Only their difference has to be constant.  When the iteration variable
3088      is an array address, the final value and initial value might both
3089      be addresses with the same base but different constant offsets.
3090      Final value must be invariant for this to work.
3091
3092      To do this, need some way to find the values of registers which are
3093      invariant.  */
3094
3095   /* Final_larger is 1 if final larger, 0 if they are equal, otherwise -1.  */
3096   if (unsigned_compare)
3097     final_larger
3098       = ((unsigned HOST_WIDE_INT) INTVAL (final_value)
3099          > (unsigned HOST_WIDE_INT) INTVAL (initial_value))
3100         - ((unsigned HOST_WIDE_INT) INTVAL (final_value)
3101            < (unsigned HOST_WIDE_INT) INTVAL (initial_value));
3102   else
3103     final_larger = (INTVAL (final_value) > INTVAL (initial_value))
3104       - (INTVAL (final_value) < INTVAL (initial_value));
3105
3106   if (INTVAL (increment) > 0)
3107     increment_dir = 1;
3108   else if (INTVAL (increment) == 0)
3109     increment_dir = 0;
3110   else
3111     increment_dir = -1;
3112
3113   /* There are 27 different cases: compare_dir = -1, 0, 1;
3114      final_larger = -1, 0, 1; increment_dir = -1, 0, 1.
3115      There are 4 normal cases, 4 reverse cases (where the iteration variable
3116      will overflow before the loop exits), 4 infinite loop cases, and 15
3117      immediate exit (0 or 1 iteration depending on loop type) cases.
3118      Only try to optimize the normal cases.  */
3119      
3120   /* (compare_dir/final_larger/increment_dir)
3121      Normal cases: (0/-1/-1), (0/1/1), (-1/-1/-1), (1/1/1)
3122      Reverse cases: (0/-1/1), (0/1/-1), (-1/-1/1), (1/1/-1)
3123      Infinite loops: (0/-1/0), (0/1/0), (-1/-1/0), (1/1/0)
3124      Immediate exit: (0/0/X), (-1/0/X), (-1/1/X), (1/0/X), (1/-1/X) */
3125
3126   /* ?? If the meaning of reverse loops (where the iteration variable
3127      will overflow before the loop exits) is undefined, then could
3128      eliminate all of these special checks, and just always assume
3129      the loops are normal/immediate/infinite.  Note that this means
3130      the sign of increment_dir does not have to be known.  Also,
3131      since it does not really hurt if immediate exit loops or infinite loops
3132      are optimized, then that case could be ignored also, and hence all
3133      loops can be optimized.
3134
3135      According to ANSI Spec, the reverse loop case result is undefined,
3136      because the action on overflow is undefined.
3137
3138      See also the special test for NE loops below.  */
3139
3140   if (final_larger == increment_dir && final_larger != 0
3141       && (final_larger == compare_dir || compare_dir == 0))
3142     /* Normal case.  */
3143     ;
3144   else
3145     {
3146       if (loop_dump_stream)
3147         fprintf (loop_dump_stream,
3148                  "Loop unrolling: Not normal loop.\n");
3149       return 0;
3150     }
3151
3152   /* Calculate the number of iterations, final_value is only an approximation,
3153      so correct for that.  Note that tempu and loop_n_iterations are
3154      unsigned, because they can be as large as 2^n - 1.  */
3155
3156   i = INTVAL (increment);
3157   if (i > 0)
3158     tempu = INTVAL (final_value) - INTVAL (initial_value);
3159   else if (i < 0)
3160     {
3161       tempu = INTVAL (initial_value) - INTVAL (final_value);
3162       i = -i;
3163     }
3164   else
3165     abort ();
3166
3167   /* For NE tests, make sure that the iteration variable won't miss the
3168      final value.  If tempu mod i is not zero, then the iteration variable
3169      will overflow before the loop exits, and we can not calculate the
3170      number of iterations.  */
3171   if (compare_dir == 0 && (tempu % i) != 0)
3172     return 0;
3173
3174   return tempu / i + ((tempu % i) != 0);
3175 }