OSDN Git Service

Revert unintended change to copy_loop_body.
[pf3gnuchains/gcc-fork.git] / gcc / unroll.c
1 /* Try to unroll loops, and split induction variables.
2    Copyright (C) 1992, 93, 94, 95, 97, 98, 1999 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, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* Try to unroll a loop, and split induction variables.
23
24    Loops for which the number of iterations can be calculated exactly are
25    handled specially.  If the number of iterations times the insn_count is
26    less than MAX_UNROLLED_INSNS, then the loop is unrolled completely.
27    Otherwise, we try to unroll the loop a number of times modulo the number
28    of iterations, so that only one exit test will be needed.  It is unrolled
29    a number of times approximately equal to MAX_UNROLLED_INSNS divided by
30    the insn count.
31
32    Otherwise, if the number of iterations can be calculated exactly at
33    run time, and the loop is always entered at the top, then we try to
34    precondition the loop.  That is, at run time, calculate how many times
35    the loop will execute, and then execute the loop body a few times so
36    that the remaining iterations will be some multiple of 4 (or 2 if the
37    loop is large).  Then fall through to a loop unrolled 4 (or 2) times,
38    with only one exit test needed at the end of the loop.
39
40    Otherwise, if the number of iterations can not be calculated exactly,
41    not even at run time, then we still unroll the loop a number of times
42    approximately equal to MAX_UNROLLED_INSNS divided by the insn count,
43    but there must be an exit test after each copy of the loop body.
44
45    For each induction variable, which is dead outside the loop (replaceable)
46    or for which we can easily calculate the final value, if we can easily
47    calculate its value at each place where it is set as a function of the
48    current loop unroll count and the variable's value at loop entry, then
49    the induction variable is split into `N' different variables, one for
50    each copy of the loop body.  One variable is live across the backward
51    branch, and the others are all calculated as a function of this variable.
52    This helps eliminate data dependencies, and leads to further opportunities
53    for cse.  */
54
55 /* Possible improvements follow:  */
56
57 /* ??? Add an extra pass somewhere to determine whether unrolling will
58    give any benefit.  E.g. after generating all unrolled insns, compute the
59    cost of all insns and compare against cost of insns in rolled loop.
60
61    - On traditional architectures, unrolling a non-constant bound loop
62      is a win if there is a giv whose only use is in memory addresses, the
63      memory addresses can be split, and hence giv increments can be
64      eliminated.
65    - It is also a win if the loop is executed many times, and preconditioning
66      can be performed for the loop.
67    Add code to check for these and similar cases.  */
68
69 /* ??? Improve control of which loops get unrolled.  Could use profiling
70    info to only unroll the most commonly executed loops.  Perhaps have
71    a user specifyable option to control the amount of code expansion,
72    or the percent of loops to consider for unrolling.  Etc.  */
73
74 /* ??? Look at the register copies inside the loop to see if they form a
75    simple permutation.  If so, iterate the permutation until it gets back to
76    the start state.  This is how many times we should unroll the loop, for
77    best results, because then all register copies can be eliminated.
78    For example, the lisp nreverse function should be unrolled 3 times
79    while (this)
80      {
81        next = this->cdr;
82        this->cdr = prev;
83        prev = this;
84        this = next;
85      }
86
87    ??? The number of times to unroll the loop may also be based on data
88    references in the loop.  For example, if we have a loop that references
89    x[i-1], x[i], and x[i+1], we should unroll it a multiple of 3 times.  */
90
91 /* ??? Add some simple linear equation solving capability so that we can
92    determine the number of loop iterations for more complex loops.
93    For example, consider this loop from gdb
94    #define SWAP_TARGET_AND_HOST(buffer,len)
95      {
96        char tmp;
97        char *p = (char *) buffer;
98        char *q = ((char *) buffer) + len - 1;
99        int iterations = (len + 1) >> 1;
100        int i;
101        for (p; p < q; p++, q--;)
102          {
103            tmp = *q;
104            *q = *p;
105            *p = tmp;
106          }
107      }
108    Note that:
109      start value = p = &buffer + current_iteration
110      end value   = q = &buffer + len - 1 - current_iteration
111    Given the loop exit test of "p < q", then there must be "q - p" iterations,
112    set equal to zero and solve for number of iterations:
113      q - p = len - 1 - 2*current_iteration = 0
114      current_iteration = (len - 1) / 2
115    Hence, there are (len - 1) / 2 (rounded up to the nearest integer)
116    iterations of this loop.  */
117
118 /* ??? Currently, no labels are marked as loop invariant when doing loop
119    unrolling.  This is because an insn inside the loop, that loads the address
120    of a label inside the loop into a register, could be moved outside the loop
121    by the invariant code motion pass if labels were invariant.  If the loop
122    is subsequently unrolled, the code will be wrong because each unrolled
123    body of the loop will use the same address, whereas each actually needs a
124    different address.  A case where this happens is when a loop containing
125    a switch statement is unrolled.
126
127    It would be better to let labels be considered invariant.  When we
128    unroll loops here, check to see if any insns using a label local to the
129    loop were moved before the loop.  If so, then correct the problem, by
130    moving the insn back into the loop, or perhaps replicate the insn before
131    the loop, one copy for each time the loop is unrolled.  */
132
133 /* The prime factors looked for when trying to unroll a loop by some
134    number which is modulo the total number of iterations.  Just checking
135    for these 4 prime factors will find at least one factor for 75% of
136    all numbers theoretically.  Practically speaking, this will succeed
137    almost all of the time since loops are generally a multiple of 2
138    and/or 5.  */
139
140 #define NUM_FACTORS 4
141
142 struct _factor { int factor, count; } factors[NUM_FACTORS]
143   = { {2, 0}, {3, 0}, {5, 0}, {7, 0}};
144
145 /* Describes the different types of loop unrolling performed.  */
146
147 enum unroll_types { UNROLL_COMPLETELY, UNROLL_MODULO, UNROLL_NAIVE };
148
149 #include "config.h"
150 #include "system.h"
151 #include "rtl.h"
152 #include "tm_p.h"
153 #include "insn-config.h"
154 #include "integrate.h"
155 #include "regs.h"
156 #include "recog.h"
157 #include "flags.h"
158 #include "function.h"
159 #include "expr.h"
160 #include "loop.h"
161 #include "toplev.h"
162
163 /* This controls which loops are unrolled, and by how much we unroll
164    them.  */
165
166 #ifndef MAX_UNROLLED_INSNS
167 #define MAX_UNROLLED_INSNS 100
168 #endif
169
170 /* Indexed by register number, if non-zero, then it contains a pointer
171    to a struct induction for a DEST_REG giv which has been combined with
172    one of more address givs.  This is needed because whenever such a DEST_REG
173    giv is modified, we must modify the value of all split address givs
174    that were combined with this DEST_REG giv.  */
175
176 static struct induction **addr_combined_regs;
177
178 /* Indexed by register number, if this is a splittable induction variable,
179    then this will hold the current value of the register, which depends on the
180    iteration number.  */
181
182 static rtx *splittable_regs;
183
184 /* Indexed by register number, if this is a splittable induction variable,
185    this indicates if it was made from a derived giv.  */
186 static char *derived_regs;
187
188 /* Indexed by register number, if this is a splittable induction variable,
189    then this will hold the number of instructions in the loop that modify
190    the induction variable.  Used to ensure that only the last insn modifying
191    a split iv will update the original iv of the dest.  */
192
193 static int *splittable_regs_updates;
194
195 /* Forward declarations.  */
196
197 static void init_reg_map PROTO((struct inline_remap *, int));
198 static rtx calculate_giv_inc PROTO((rtx, rtx, int));
199 static rtx initial_reg_note_copy PROTO((rtx, struct inline_remap *));
200 static void final_reg_note_copy PROTO((rtx, struct inline_remap *));
201 static void copy_loop_body PROTO((rtx, rtx, struct inline_remap *, rtx, int,
202                                   enum unroll_types, rtx, rtx, rtx, rtx));
203 static void iteration_info PROTO((rtx, rtx *, rtx *, rtx, rtx));
204 static int find_splittable_regs PROTO((enum unroll_types, rtx, rtx, rtx, int,
205                                        unsigned HOST_WIDE_INT));
206 static int find_splittable_givs PROTO((struct iv_class *, enum unroll_types,
207                                        rtx, rtx, rtx, int));
208 static int reg_dead_after_loop PROTO((rtx, rtx, rtx));
209 static rtx fold_rtx_mult_add PROTO((rtx, rtx, rtx, enum machine_mode));
210 static int verify_addresses PROTO((struct induction *, rtx, int));
211 static rtx remap_split_bivs PROTO((rtx));
212 static rtx find_common_reg_term PROTO((rtx, rtx));
213 static rtx subtract_reg_term PROTO((rtx, rtx));
214 static rtx loop_find_equiv_value PROTO((rtx, rtx));
215
216 /* Try to unroll one loop and split induction variables in the loop.
217
218    The loop is described by the arguments LOOP_END, INSN_COUNT, and
219    LOOP_START.  END_INSERT_BEFORE indicates where insns should be added
220    which need to be executed when the loop falls through.  STRENGTH_REDUCTION_P
221    indicates whether information generated in the strength reduction pass
222    is available.
223
224    This function is intended to be called from within `strength_reduce'
225    in loop.c.  */
226
227 void
228 unroll_loop (loop_end, insn_count, loop_start, end_insert_before,
229              loop_info, strength_reduce_p)
230      rtx loop_end;
231      int insn_count;
232      rtx loop_start;
233      rtx end_insert_before;
234      struct loop_info *loop_info;
235      int strength_reduce_p;
236 {
237   int i, j, temp;
238   int unroll_number = 1;
239   rtx copy_start, copy_end;
240   rtx insn, sequence, pattern, tem;
241   int max_labelno, max_insnno;
242   rtx insert_before;
243   struct inline_remap *map;
244   char *local_label = NULL;
245   char *local_regno;
246   int max_local_regnum;
247   int maxregnum;
248   rtx exit_label = 0;
249   rtx start_label;
250   struct iv_class *bl;
251   int splitting_not_safe = 0;
252   enum unroll_types unroll_type;
253   int loop_preconditioned = 0;
254   rtx safety_label;
255   /* This points to the last real insn in the loop, which should be either
256      a JUMP_INSN (for conditional jumps) or a BARRIER (for unconditional
257      jumps).  */
258   rtx last_loop_insn;
259
260   /* Don't bother unrolling huge loops.  Since the minimum factor is
261      two, loops greater than one half of MAX_UNROLLED_INSNS will never
262      be unrolled.  */
263   if (insn_count > MAX_UNROLLED_INSNS / 2)
264     {
265       if (loop_dump_stream)
266         fprintf (loop_dump_stream, "Unrolling failure: Loop too big.\n");
267       return;
268     }
269
270   /* When emitting debugger info, we can't unroll loops with unequal numbers
271      of block_beg and block_end notes, because that would unbalance the block
272      structure of the function.  This can happen as a result of the
273      "if (foo) bar; else break;" optimization in jump.c.  */
274   /* ??? Gcc has a general policy that -g is never supposed to change the code
275      that the compiler emits, so we must disable this optimization always,
276      even if debug info is not being output.  This is rare, so this should
277      not be a significant performance problem.  */
278
279   if (1 /* write_symbols != NO_DEBUG */)
280     {
281       int block_begins = 0;
282       int block_ends = 0;
283
284       for (insn = loop_start; insn != loop_end; insn = NEXT_INSN (insn))
285         {
286           if (GET_CODE (insn) == NOTE)
287             {
288               if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_BLOCK_BEG)
289                 block_begins++;
290               else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_BLOCK_END)
291                 block_ends++;
292             }
293         }
294
295       if (block_begins != block_ends)
296         {
297           if (loop_dump_stream)
298             fprintf (loop_dump_stream,
299                      "Unrolling failure: Unbalanced block notes.\n");
300           return;
301         }
302     }
303
304   /* Determine type of unroll to perform.  Depends on the number of iterations
305      and the size of the loop.  */
306
307   /* If there is no strength reduce info, then set
308      loop_info->n_iterations to zero.  This can happen if
309      strength_reduce can't find any bivs in the loop.  A value of zero
310      indicates that the number of iterations could not be calculated.  */
311
312   if (! strength_reduce_p)
313     loop_info->n_iterations = 0;
314
315   if (loop_dump_stream && loop_info->n_iterations > 0)
316     {
317       fputs ("Loop unrolling: ", loop_dump_stream);
318       fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC,
319                loop_info->n_iterations);
320       fputs (" iterations.\n", loop_dump_stream);
321     }
322
323   /* Find and save a pointer to the last nonnote insn in the loop.  */
324
325   last_loop_insn = prev_nonnote_insn (loop_end);
326
327   /* Calculate how many times to unroll the loop.  Indicate whether or
328      not the loop is being completely unrolled.  */
329
330   if (loop_info->n_iterations == 1)
331     {
332       /* If number of iterations is exactly 1, then eliminate the compare and
333          branch at the end of the loop since they will never be taken.
334          Then return, since no other action is needed here.  */
335
336       /* If the last instruction is not a BARRIER or a JUMP_INSN, then
337          don't do anything.  */
338
339       if (GET_CODE (last_loop_insn) == BARRIER)
340         {
341           /* Delete the jump insn.  This will delete the barrier also.  */
342           delete_insn (PREV_INSN (last_loop_insn));
343         }
344       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
345         {
346 #ifdef HAVE_cc0
347           rtx prev = PREV_INSN (last_loop_insn);
348 #endif
349           delete_insn (last_loop_insn);
350 #ifdef HAVE_cc0
351           /* The immediately preceding insn may be a compare which must be
352              deleted.  */
353           if (sets_cc0_p (prev))
354             delete_insn (prev);
355 #endif
356         }
357       return;
358     }
359   else if (loop_info->n_iterations > 0
360            && loop_info->n_iterations * insn_count < MAX_UNROLLED_INSNS)
361     {
362       unroll_number = loop_info->n_iterations;
363       unroll_type = UNROLL_COMPLETELY;
364     }
365   else if (loop_info->n_iterations > 0)
366     {
367       /* Try to factor the number of iterations.  Don't bother with the
368          general case, only using 2, 3, 5, and 7 will get 75% of all
369          numbers theoretically, and almost all in practice.  */
370
371       for (i = 0; i < NUM_FACTORS; i++)
372         factors[i].count = 0;
373
374       temp = loop_info->n_iterations;
375       for (i = NUM_FACTORS - 1; i >= 0; i--)
376         while (temp % factors[i].factor == 0)
377           {
378             factors[i].count++;
379             temp = temp / factors[i].factor;
380           }
381
382       /* Start with the larger factors first so that we generally
383          get lots of unrolling.  */
384
385       unroll_number = 1;
386       temp = insn_count;
387       for (i = 3; i >= 0; i--)
388         while (factors[i].count--)
389           {
390             if (temp * factors[i].factor < MAX_UNROLLED_INSNS)
391               {
392                 unroll_number *= factors[i].factor;
393                 temp *= factors[i].factor;
394               }
395             else
396               break;
397           }
398
399       /* If we couldn't find any factors, then unroll as in the normal
400          case.  */
401       if (unroll_number == 1)
402         {
403           if (loop_dump_stream)
404             fprintf (loop_dump_stream,
405                      "Loop unrolling: No factors found.\n");
406         }
407       else
408         unroll_type = UNROLL_MODULO;
409     }
410
411
412   /* Default case, calculate number of times to unroll loop based on its
413      size.  */
414   if (unroll_number == 1)
415     {
416       if (8 * insn_count < MAX_UNROLLED_INSNS)
417         unroll_number = 8;
418       else if (4 * insn_count < MAX_UNROLLED_INSNS)
419         unroll_number = 4;
420       else
421         unroll_number = 2;
422
423       unroll_type = UNROLL_NAIVE;
424     }
425
426   /* Now we know how many times to unroll the loop.  */
427
428   if (loop_dump_stream)
429     fprintf (loop_dump_stream,
430              "Unrolling loop %d times.\n", unroll_number);
431
432
433   if (unroll_type == UNROLL_COMPLETELY || unroll_type == UNROLL_MODULO)
434     {
435       /* Loops of these types can start with jump down to the exit condition
436          in rare circumstances.
437
438          Consider a pair of nested loops where the inner loop is part
439          of the exit code for the outer loop.
440
441          In this case jump.c will not duplicate the exit test for the outer
442          loop, so it will start with a jump to the exit code.
443
444          Then consider if the inner loop turns out to iterate once and
445          only once.  We will end up deleting the jumps associated with
446          the inner loop.  However, the loop notes are not removed from
447          the instruction stream.
448
449          And finally assume that we can compute the number of iterations
450          for the outer loop.
451
452          In this case unroll may want to unroll the outer loop even though
453          it starts with a jump to the outer loop's exit code.
454
455          We could try to optimize this case, but it hardly seems worth it.
456          Just return without unrolling the loop in such cases.  */
457
458       insn = loop_start;
459       while (GET_CODE (insn) != CODE_LABEL && GET_CODE (insn) != JUMP_INSN)
460         insn = NEXT_INSN (insn);
461       if (GET_CODE (insn) == JUMP_INSN)
462         return;
463     }
464
465   if (unroll_type == UNROLL_COMPLETELY)
466     {
467       /* Completely unrolling the loop:  Delete the compare and branch at
468          the end (the last two instructions).   This delete must done at the
469          very end of loop unrolling, to avoid problems with calls to
470          back_branch_in_range_p, which is called by find_splittable_regs.
471          All increments of splittable bivs/givs are changed to load constant
472          instructions.  */
473
474       copy_start = loop_start;
475
476       /* Set insert_before to the instruction immediately after the JUMP_INSN
477          (or BARRIER), so that any NOTEs between the JUMP_INSN and the end of
478          the loop will be correctly handled by copy_loop_body.  */
479       insert_before = NEXT_INSN (last_loop_insn);
480
481       /* Set copy_end to the insn before the jump at the end of the loop.  */
482       if (GET_CODE (last_loop_insn) == BARRIER)
483         copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
484       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
485         {
486           copy_end = PREV_INSN (last_loop_insn);
487 #ifdef HAVE_cc0
488           /* The instruction immediately before the JUMP_INSN may be a compare
489              instruction which we do not want to copy.  */
490           if (sets_cc0_p (PREV_INSN (copy_end)))
491             copy_end = PREV_INSN (copy_end);
492 #endif
493         }
494       else
495         {
496           /* We currently can't unroll a loop if it doesn't end with a
497              JUMP_INSN.  There would need to be a mechanism that recognizes
498              this case, and then inserts a jump after each loop body, which
499              jumps to after the last loop body.  */
500           if (loop_dump_stream)
501             fprintf (loop_dump_stream,
502                      "Unrolling failure: loop does not end with a JUMP_INSN.\n");
503           return;
504         }
505     }
506   else if (unroll_type == UNROLL_MODULO)
507     {
508       /* Partially unrolling the loop:  The compare and branch at the end
509          (the last two instructions) must remain.  Don't copy the compare
510          and branch instructions at the end of the loop.  Insert the unrolled
511          code immediately before the compare/branch at the end so that the
512          code will fall through to them as before.  */
513
514       copy_start = loop_start;
515
516       /* Set insert_before to the jump insn at the end of the loop.
517          Set copy_end to before the jump insn at the end of the loop.  */
518       if (GET_CODE (last_loop_insn) == BARRIER)
519         {
520           insert_before = PREV_INSN (last_loop_insn);
521           copy_end = PREV_INSN (insert_before);
522         }
523       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
524         {
525           insert_before = last_loop_insn;
526 #ifdef HAVE_cc0
527           /* The instruction immediately before the JUMP_INSN may be a compare
528              instruction which we do not want to copy or delete.  */
529           if (sets_cc0_p (PREV_INSN (insert_before)))
530             insert_before = PREV_INSN (insert_before);
531 #endif
532           copy_end = PREV_INSN (insert_before);
533         }
534       else
535         {
536           /* We currently can't unroll a loop if it doesn't end with a
537              JUMP_INSN.  There would need to be a mechanism that recognizes
538              this case, and then inserts a jump after each loop body, which
539              jumps to after the last loop body.  */
540           if (loop_dump_stream)
541             fprintf (loop_dump_stream,
542                      "Unrolling failure: loop does not end with a JUMP_INSN.\n");
543           return;
544         }
545     }
546   else
547     {
548       /* Normal case: Must copy the compare and branch instructions at the
549          end of the loop.  */
550
551       if (GET_CODE (last_loop_insn) == BARRIER)
552         {
553           /* Loop ends with an unconditional jump and a barrier.
554              Handle this like above, don't copy jump and barrier.
555              This is not strictly necessary, but doing so prevents generating
556              unconditional jumps to an immediately following label.
557
558              This will be corrected below if the target of this jump is
559              not the start_label.  */
560
561           insert_before = PREV_INSN (last_loop_insn);
562           copy_end = PREV_INSN (insert_before);
563         }
564       else if (GET_CODE (last_loop_insn) == JUMP_INSN)
565         {
566           /* Set insert_before to immediately after the JUMP_INSN, so that
567              NOTEs at the end of the loop will be correctly handled by
568              copy_loop_body.  */
569           insert_before = NEXT_INSN (last_loop_insn);
570           copy_end = last_loop_insn;
571         }
572       else
573         {
574           /* We currently can't unroll a loop if it doesn't end with a
575              JUMP_INSN.  There would need to be a mechanism that recognizes
576              this case, and then inserts a jump after each loop body, which
577              jumps to after the last loop body.  */
578           if (loop_dump_stream)
579             fprintf (loop_dump_stream,
580                      "Unrolling failure: loop does not end with a JUMP_INSN.\n");
581           return;
582         }
583
584       /* If copying exit test branches because they can not be eliminated,
585          then must convert the fall through case of the branch to a jump past
586          the end of the loop.  Create a label to emit after the loop and save
587          it for later use.  Do not use the label after the loop, if any, since
588          it might be used by insns outside the loop, or there might be insns
589          added before it later by final_[bg]iv_value which must be after
590          the real exit label.  */
591       exit_label = gen_label_rtx ();
592
593       insn = loop_start;
594       while (GET_CODE (insn) != CODE_LABEL && GET_CODE (insn) != JUMP_INSN)
595         insn = NEXT_INSN (insn);
596
597       if (GET_CODE (insn) == JUMP_INSN)
598         {
599           /* The loop starts with a jump down to the exit condition test.
600              Start copying the loop after the barrier following this
601              jump insn.  */
602           copy_start = NEXT_INSN (insn);
603
604           /* Splitting induction variables doesn't work when the loop is
605              entered via a jump to the bottom, because then we end up doing
606              a comparison against a new register for a split variable, but
607              we did not execute the set insn for the new register because
608              it was skipped over.  */
609           splitting_not_safe = 1;
610           if (loop_dump_stream)
611             fprintf (loop_dump_stream,
612                      "Splitting not safe, because loop not entered at top.\n");
613         }
614       else
615         copy_start = loop_start;
616     }
617
618   /* This should always be the first label in the loop.  */
619   start_label = NEXT_INSN (copy_start);
620   /* There may be a line number note and/or a loop continue note here.  */
621   while (GET_CODE (start_label) == NOTE)
622     start_label = NEXT_INSN (start_label);
623   if (GET_CODE (start_label) != CODE_LABEL)
624     {
625       /* This can happen as a result of jump threading.  If the first insns in
626          the loop test the same condition as the loop's backward jump, or the
627          opposite condition, then the backward jump will be modified to point
628          to elsewhere, and the loop's start label is deleted.
629
630          This case currently can not be handled by the loop unrolling code.  */
631
632       if (loop_dump_stream)
633         fprintf (loop_dump_stream,
634                  "Unrolling failure: unknown insns between BEG note and loop label.\n");
635       return;
636     }
637   if (LABEL_NAME (start_label))
638     {
639       /* The jump optimization pass must have combined the original start label
640          with a named label for a goto.  We can't unroll this case because
641          jumps which go to the named label must be handled differently than
642          jumps to the loop start, and it is impossible to differentiate them
643          in this case.  */
644       if (loop_dump_stream)
645         fprintf (loop_dump_stream,
646                  "Unrolling failure: loop start label is gone\n");
647       return;
648     }
649
650   if (unroll_type == UNROLL_NAIVE
651       && GET_CODE (last_loop_insn) == BARRIER
652       && GET_CODE (PREV_INSN (last_loop_insn)) == JUMP_INSN
653       && start_label != JUMP_LABEL (PREV_INSN (last_loop_insn)))
654     {
655       /* In this case, we must copy the jump and barrier, because they will
656          not be converted to jumps to an immediately following label.  */
657
658       insert_before = NEXT_INSN (last_loop_insn);
659       copy_end = last_loop_insn;
660     }
661
662   if (unroll_type == UNROLL_NAIVE
663       && GET_CODE (last_loop_insn) == JUMP_INSN
664       && start_label != JUMP_LABEL (last_loop_insn))
665     {
666       /* ??? The loop ends with a conditional branch that does not branch back
667          to the loop start label.  In this case, we must emit an unconditional
668          branch to the loop exit after emitting the final branch.
669          copy_loop_body does not have support for this currently, so we
670          give up.  It doesn't seem worthwhile to unroll anyways since
671          unrolling would increase the number of branch instructions
672          executed.  */
673       if (loop_dump_stream)
674         fprintf (loop_dump_stream,
675                  "Unrolling failure: final conditional branch not to loop start\n");
676       return;
677     }
678
679   /* Allocate a translation table for the labels and insn numbers.
680      They will be filled in as we copy the insns in the loop.  */
681
682   max_labelno = max_label_num ();
683   max_insnno = get_max_uid ();
684
685   map = (struct inline_remap *) alloca (sizeof (struct inline_remap));
686
687   map->integrating = 0;
688   map->const_equiv_varray = 0;
689
690   /* Allocate the label map.  */
691
692   if (max_labelno > 0)
693     {
694       map->label_map = (rtx *) alloca (max_labelno * sizeof (rtx));
695
696       local_label = (char *) alloca (max_labelno);
697       bzero (local_label, max_labelno);
698     }
699   else
700     map->label_map = 0;
701
702   /* Search the loop and mark all local labels, i.e. the ones which have to
703      be distinct labels when copied.  For all labels which might be
704      non-local, set their label_map entries to point to themselves.
705      If they happen to be local their label_map entries will be overwritten
706      before the loop body is copied.  The label_map entries for local labels
707      will be set to a different value each time the loop body is copied.  */
708
709   for (insn = copy_start; insn != loop_end; insn = NEXT_INSN (insn))
710     {
711       rtx note;
712
713       if (GET_CODE (insn) == CODE_LABEL)
714         local_label[CODE_LABEL_NUMBER (insn)] = 1;
715       else if (GET_CODE (insn) == JUMP_INSN)
716         {
717           if (JUMP_LABEL (insn))
718             set_label_in_map (map,
719                               CODE_LABEL_NUMBER (JUMP_LABEL (insn)),
720                               JUMP_LABEL (insn));
721           else if (GET_CODE (PATTERN (insn)) == ADDR_VEC
722                    || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
723             {
724               rtx pat = PATTERN (insn);
725               int diff_vec_p = GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC;
726               int len = XVECLEN (pat, diff_vec_p);
727               rtx label;
728
729               for (i = 0; i < len; i++)
730                 {
731                   label = XEXP (XVECEXP (pat, diff_vec_p, i), 0);
732                   set_label_in_map (map,
733                                     CODE_LABEL_NUMBER (label),
734                                     label);
735                 }
736             }
737         }
738       else if ((note = find_reg_note (insn, REG_LABEL, NULL_RTX)))
739         set_label_in_map (map, CODE_LABEL_NUMBER (XEXP (note, 0)),
740                           XEXP (note, 0));
741     }
742
743   /* Allocate space for the insn map.  */
744
745   map->insn_map = (rtx *) alloca (max_insnno * sizeof (rtx));
746
747   /* Set this to zero, to indicate that we are doing loop unrolling,
748      not function inlining.  */
749   map->inline_target = 0;
750
751   /* The register and constant maps depend on the number of registers
752      present, so the final maps can't be created until after
753      find_splittable_regs is called.  However, they are needed for
754      preconditioning, so we create temporary maps when preconditioning
755      is performed.  */
756
757   /* The preconditioning code may allocate two new pseudo registers.  */
758   maxregnum = max_reg_num ();
759
760   /* local_regno is only valid for regnos < max_local_regnum.  */
761   max_local_regnum = maxregnum;
762
763   /* Allocate and zero out the splittable_regs and addr_combined_regs
764      arrays.  These must be zeroed here because they will be used if
765      loop preconditioning is performed, and must be zero for that case.
766
767      It is safe to do this here, since the extra registers created by the
768      preconditioning code and find_splittable_regs will never be used
769      to access the splittable_regs[] and addr_combined_regs[] arrays.  */
770
771   splittable_regs = (rtx *) alloca (maxregnum * sizeof (rtx));
772   bzero ((char *) splittable_regs, maxregnum * sizeof (rtx));
773   derived_regs = (char *) alloca (maxregnum);
774   bzero (derived_regs, maxregnum);
775   splittable_regs_updates = (int *) alloca (maxregnum * sizeof (int));
776   bzero ((char *) splittable_regs_updates, maxregnum * sizeof (int));
777   addr_combined_regs
778     = (struct induction **) alloca (maxregnum * sizeof (struct induction *));
779   bzero ((char *) addr_combined_regs, maxregnum * sizeof (struct induction *));
780   local_regno = (char *) alloca (maxregnum);
781   bzero (local_regno, maxregnum);
782
783   /* Mark all local registers, i.e. the ones which are referenced only
784      inside the loop.  */
785   if (INSN_UID (copy_end) < max_uid_for_loop)
786     {
787       int copy_start_luid = INSN_LUID (copy_start);
788       int copy_end_luid = INSN_LUID (copy_end);
789
790       /* If a register is used in the jump insn, we must not duplicate it
791          since it will also be used outside the loop.  */
792       if (GET_CODE (copy_end) == JUMP_INSN)
793         copy_end_luid--;
794
795       /* If we have a target that uses cc0, then we also must not duplicate
796          the insn that sets cc0 before the jump insn, if one is present.  */
797 #ifdef HAVE_cc0
798       if (GET_CODE (copy_end) == JUMP_INSN && sets_cc0_p (PREV_INSN (copy_end)))
799         copy_end_luid--;
800 #endif
801
802       /* If copy_start points to the NOTE that starts the loop, then we must
803          use the next luid, because invariant pseudo-regs moved out of the loop
804          have their lifetimes modified to start here, but they are not safe
805          to duplicate.  */
806       if (copy_start == loop_start)
807         copy_start_luid++;
808
809       /* If a pseudo's lifetime is entirely contained within this loop, then we
810          can use a different pseudo in each unrolled copy of the loop.  This
811          results in better code.  */
812       /* We must limit the generic test to max_reg_before_loop, because only
813          these pseudo registers have valid regno_first_uid info.  */
814       for (j = FIRST_PSEUDO_REGISTER; j < max_reg_before_loop; ++j)
815         if (REGNO_FIRST_UID (j) > 0 && REGNO_FIRST_UID (j) <= max_uid_for_loop
816             && uid_luid[REGNO_FIRST_UID (j)] >= copy_start_luid
817             && REGNO_LAST_UID (j) > 0 && REGNO_LAST_UID (j) <= max_uid_for_loop
818             && uid_luid[REGNO_LAST_UID (j)] <= copy_end_luid)
819           {
820             /* However, we must also check for loop-carried dependencies.
821                If the value the pseudo has at the end of iteration X is
822                used by iteration X+1, then we can not use a different pseudo
823                for each unrolled copy of the loop.  */
824             /* A pseudo is safe if regno_first_uid is a set, and this
825                set dominates all instructions from regno_first_uid to
826                regno_last_uid.  */
827             /* ??? This check is simplistic.  We would get better code if
828                this check was more sophisticated.  */
829             if (set_dominates_use (j, REGNO_FIRST_UID (j), REGNO_LAST_UID (j),
830                                    copy_start, copy_end))
831               local_regno[j] = 1;
832
833             if (loop_dump_stream)
834               {
835                 if (local_regno[j])
836                   fprintf (loop_dump_stream, "Marked reg %d as local\n", j);
837                 else
838                   fprintf (loop_dump_stream, "Did not mark reg %d as local\n",
839                            j);
840               }
841           }
842       /* Givs that have been created from multiple biv increments always have
843          local registers.  */
844       for (j = first_increment_giv; j <= last_increment_giv; j++)
845         {
846           local_regno[j] = 1;
847           if (loop_dump_stream)
848             fprintf (loop_dump_stream, "Marked reg %d as local\n", j);
849         }
850     }
851
852   /* If this loop requires exit tests when unrolled, check to see if we
853      can precondition the loop so as to make the exit tests unnecessary.
854      Just like variable splitting, this is not safe if the loop is entered
855      via a jump to the bottom.  Also, can not do this if no strength
856      reduce info, because precondition_loop_p uses this info.  */
857
858   /* Must copy the loop body for preconditioning before the following
859      find_splittable_regs call since that will emit insns which need to
860      be after the preconditioned loop copies, but immediately before the
861      unrolled loop copies.  */
862
863   /* Also, it is not safe to split induction variables for the preconditioned
864      copies of the loop body.  If we split induction variables, then the code
865      assumes that each induction variable can be represented as a function
866      of its initial value and the loop iteration number.  This is not true
867      in this case, because the last preconditioned copy of the loop body
868      could be any iteration from the first up to the `unroll_number-1'th,
869      depending on the initial value of the iteration variable.  Therefore
870      we can not split induction variables here, because we can not calculate
871      their value.  Hence, this code must occur before find_splittable_regs
872      is called.  */
873
874   if (unroll_type == UNROLL_NAIVE && ! splitting_not_safe && strength_reduce_p)
875     {
876       rtx initial_value, final_value, increment;
877       enum machine_mode mode;
878
879       if (precondition_loop_p (loop_start, loop_info,
880                                &initial_value, &final_value, &increment,
881                                &mode))
882         {
883           register rtx diff ;
884           rtx *labels;
885           int abs_inc, neg_inc;
886
887           map->reg_map = (rtx *) alloca (maxregnum * sizeof (rtx));
888
889           VARRAY_CONST_EQUIV_INIT (map->const_equiv_varray, maxregnum,
890                                    "unroll_loop");
891           global_const_equiv_varray = map->const_equiv_varray;
892
893           init_reg_map (map, maxregnum);
894
895           /* Limit loop unrolling to 4, since this will make 7 copies of
896              the loop body.  */
897           if (unroll_number > 4)
898             unroll_number = 4;
899
900           /* Save the absolute value of the increment, and also whether or
901              not it is negative.  */
902           neg_inc = 0;
903           abs_inc = INTVAL (increment);
904           if (abs_inc < 0)
905             {
906               abs_inc = - abs_inc;
907               neg_inc = 1;
908             }
909
910           start_sequence ();
911
912           /* Calculate the difference between the final and initial values.
913              Final value may be a (plus (reg x) (const_int 1)) rtx.
914              Let the following cse pass simplify this if initial value is
915              a constant.
916
917              We must copy the final and initial values here to avoid
918              improperly shared rtl.  */
919
920           diff = expand_binop (mode, sub_optab, copy_rtx (final_value),
921                                copy_rtx (initial_value), NULL_RTX, 0,
922                                OPTAB_LIB_WIDEN);
923
924           /* Now calculate (diff % (unroll * abs (increment))) by using an
925              and instruction.  */
926           diff = expand_binop (GET_MODE (diff), and_optab, diff,
927                                GEN_INT (unroll_number * abs_inc - 1),
928                                NULL_RTX, 0, OPTAB_LIB_WIDEN);
929
930           /* Now emit a sequence of branches to jump to the proper precond
931              loop entry point.  */
932
933           labels = (rtx *) alloca (sizeof (rtx) * unroll_number);
934           for (i = 0; i < unroll_number; i++)
935             labels[i] = gen_label_rtx ();
936
937           /* Check for the case where the initial value is greater than or
938              equal to the final value.  In that case, we want to execute
939              exactly one loop iteration.  The code below will fail for this
940              case.  This check does not apply if the loop has a NE
941              comparison at the end.  */
942
943           if (loop_info->comparison_code != NE)
944             {
945               emit_cmp_and_jump_insns (initial_value, final_value,
946                                        neg_inc ? LE : GE,
947                                        NULL_RTX, mode, 0, 0, labels[1]);
948               JUMP_LABEL (get_last_insn ()) = labels[1];
949               LABEL_NUSES (labels[1])++;
950             }
951
952           /* Assuming the unroll_number is 4, and the increment is 2, then
953              for a negative increment:  for a positive increment:
954              diff = 0,1   precond 0     diff = 0,7   precond 0
955              diff = 2,3   precond 3     diff = 1,2   precond 1
956              diff = 4,5   precond 2     diff = 3,4   precond 2
957              diff = 6,7   precond 1     diff = 5,6   precond 3  */
958
959           /* We only need to emit (unroll_number - 1) branches here, the
960              last case just falls through to the following code.  */
961
962           /* ??? This would give better code if we emitted a tree of branches
963              instead of the current linear list of branches.  */
964
965           for (i = 0; i < unroll_number - 1; i++)
966             {
967               int cmp_const;
968               enum rtx_code cmp_code;
969
970               /* For negative increments, must invert the constant compared
971                  against, except when comparing against zero.  */
972               if (i == 0)
973                 {
974                   cmp_const = 0;
975                   cmp_code = EQ;
976                 }
977               else if (neg_inc)
978                 {
979                   cmp_const = unroll_number - i;
980                   cmp_code = GE;
981                 }
982               else
983                 {
984                   cmp_const = i;
985                   cmp_code = LE;
986                 }
987
988               emit_cmp_and_jump_insns (diff, GEN_INT (abs_inc * cmp_const),
989                                        cmp_code, NULL_RTX, mode, 0, 0,
990                                        labels[i]);
991               JUMP_LABEL (get_last_insn ()) = labels[i];
992               LABEL_NUSES (labels[i])++;
993             }
994
995           /* If the increment is greater than one, then we need another branch,
996              to handle other cases equivalent to 0.  */
997
998           /* ??? This should be merged into the code above somehow to help
999              simplify the code here, and reduce the number of branches emitted.
1000              For the negative increment case, the branch here could easily
1001              be merged with the `0' case branch above.  For the positive
1002              increment case, it is not clear how this can be simplified.  */
1003
1004           if (abs_inc != 1)
1005             {
1006               int cmp_const;
1007               enum rtx_code cmp_code;
1008
1009               if (neg_inc)
1010                 {
1011                   cmp_const = abs_inc - 1;
1012                   cmp_code = LE;
1013                 }
1014               else
1015                 {
1016                   cmp_const = abs_inc * (unroll_number - 1) + 1;
1017                   cmp_code = GE;
1018                 }
1019
1020               emit_cmp_and_jump_insns (diff, GEN_INT (cmp_const), cmp_code,
1021                                        NULL_RTX, mode, 0, 0, labels[0]);
1022               JUMP_LABEL (get_last_insn ()) = labels[0];
1023               LABEL_NUSES (labels[0])++;
1024             }
1025
1026           sequence = gen_sequence ();
1027           end_sequence ();
1028           emit_insn_before (sequence, loop_start);
1029
1030           /* Only the last copy of the loop body here needs the exit
1031              test, so set copy_end to exclude the compare/branch here,
1032              and then reset it inside the loop when get to the last
1033              copy.  */
1034
1035           if (GET_CODE (last_loop_insn) == BARRIER)
1036             copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
1037           else if (GET_CODE (last_loop_insn) == JUMP_INSN)
1038             {
1039               copy_end = PREV_INSN (last_loop_insn);
1040 #ifdef HAVE_cc0
1041               /* The immediately preceding insn may be a compare which we do not
1042                  want to copy.  */
1043               if (sets_cc0_p (PREV_INSN (copy_end)))
1044                 copy_end = PREV_INSN (copy_end);
1045 #endif
1046             }
1047           else
1048             abort ();
1049
1050           for (i = 1; i < unroll_number; i++)
1051             {
1052               emit_label_after (labels[unroll_number - i],
1053                                 PREV_INSN (loop_start));
1054
1055               bzero ((char *) map->insn_map, max_insnno * sizeof (rtx));
1056               bzero ((char *) &VARRAY_CONST_EQUIV (map->const_equiv_varray, 0),
1057                      (VARRAY_SIZE (map->const_equiv_varray)
1058                       * sizeof (struct const_equiv_data)));
1059               map->const_age = 0;
1060
1061               for (j = 0; j < max_labelno; j++)
1062                 if (local_label[j])
1063                   set_label_in_map (map, j, gen_label_rtx ());
1064
1065               for (j = FIRST_PSEUDO_REGISTER; j < max_local_regnum; j++)
1066                 if (local_regno[j])
1067                   {
1068                     map->reg_map[j] = gen_reg_rtx (GET_MODE (regno_reg_rtx[j]));
1069                     record_base_value (REGNO (map->reg_map[j]),
1070                                        regno_reg_rtx[j], 0);
1071                   }
1072               /* The last copy needs the compare/branch insns at the end,
1073                  so reset copy_end here if the loop ends with a conditional
1074                  branch.  */
1075
1076               if (i == unroll_number - 1)
1077                 {
1078                   if (GET_CODE (last_loop_insn) == BARRIER)
1079                     copy_end = PREV_INSN (PREV_INSN (last_loop_insn));
1080                   else
1081                     copy_end = last_loop_insn;
1082                 }
1083
1084               /* None of the copies are the `last_iteration', so just
1085                  pass zero for that parameter.  */
1086               copy_loop_body (copy_start, copy_end, map, exit_label, 0,
1087                               unroll_type, start_label, loop_end,
1088                               loop_start, copy_end);
1089             }
1090           emit_label_after (labels[0], PREV_INSN (loop_start));
1091
1092           if (GET_CODE (last_loop_insn) == BARRIER)
1093             {
1094               insert_before = PREV_INSN (last_loop_insn);
1095               copy_end = PREV_INSN (insert_before);
1096             }
1097           else
1098             {
1099               insert_before = last_loop_insn;
1100 #ifdef HAVE_cc0
1101               /* The instruction immediately before the JUMP_INSN may be a compare
1102                  instruction which we do not want to copy or delete.  */
1103               if (sets_cc0_p (PREV_INSN (insert_before)))
1104                 insert_before = PREV_INSN (insert_before);
1105 #endif
1106               copy_end = PREV_INSN (insert_before);
1107             }
1108
1109           /* Set unroll type to MODULO now.  */
1110           unroll_type = UNROLL_MODULO;
1111           loop_preconditioned = 1;
1112         }
1113     }
1114
1115   /* If reach here, and the loop type is UNROLL_NAIVE, then don't unroll
1116      the loop unless all loops are being unrolled.  */
1117   if (unroll_type == UNROLL_NAIVE && ! flag_unroll_all_loops)
1118     {
1119       if (loop_dump_stream)
1120         fprintf (loop_dump_stream, "Unrolling failure: Naive unrolling not being done.\n");
1121       goto egress;
1122     }
1123
1124   /* At this point, we are guaranteed to unroll the loop.  */
1125
1126   /* Keep track of the unroll factor for the loop.  */
1127   loop_info->unroll_number = unroll_number;
1128
1129   /* For each biv and giv, determine whether it can be safely split into
1130      a different variable for each unrolled copy of the loop body.
1131      We precalculate and save this info here, since computing it is
1132      expensive.
1133
1134      Do this before deleting any instructions from the loop, so that
1135      back_branch_in_range_p will work correctly.  */
1136
1137   if (splitting_not_safe)
1138     temp = 0;
1139   else
1140     temp = find_splittable_regs (unroll_type, loop_start, loop_end,
1141                                  end_insert_before, unroll_number,
1142                                  loop_info->n_iterations);
1143
1144   /* find_splittable_regs may have created some new registers, so must
1145      reallocate the reg_map with the new larger size, and must realloc
1146      the constant maps also.  */
1147
1148   maxregnum = max_reg_num ();
1149   map->reg_map = (rtx *) alloca (maxregnum * sizeof (rtx));
1150
1151   init_reg_map (map, maxregnum);
1152
1153   if (map->const_equiv_varray == 0)
1154     VARRAY_CONST_EQUIV_INIT (map->const_equiv_varray,
1155                              maxregnum + temp * unroll_number * 2,
1156                              "unroll_loop");
1157   global_const_equiv_varray = map->const_equiv_varray;
1158
1159   /* Search the list of bivs and givs to find ones which need to be remapped
1160      when split, and set their reg_map entry appropriately.  */
1161
1162   for (bl = loop_iv_list; bl; bl = bl->next)
1163     {
1164       if (REGNO (bl->biv->src_reg) != bl->regno)
1165         map->reg_map[bl->regno] = bl->biv->src_reg;
1166 #if 0
1167       /* Currently, non-reduced/final-value givs are never split.  */
1168       for (v = bl->giv; v; v = v->next_iv)
1169         if (REGNO (v->src_reg) != bl->regno)
1170           map->reg_map[REGNO (v->dest_reg)] = v->src_reg;
1171 #endif
1172     }
1173
1174   /* Use our current register alignment and pointer flags.  */
1175   map->regno_pointer_flag = current_function->emit->regno_pointer_flag;
1176   map->regno_pointer_align = current_function->emit->regno_pointer_align;
1177
1178   /* If the loop is being partially unrolled, and the iteration variables
1179      are being split, and are being renamed for the split, then must fix up
1180      the compare/jump instruction at the end of the loop to refer to the new
1181      registers.  This compare isn't copied, so the registers used in it
1182      will never be replaced if it isn't done here.  */
1183
1184   if (unroll_type == UNROLL_MODULO)
1185     {
1186       insn = NEXT_INSN (copy_end);
1187       if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
1188         PATTERN (insn) = remap_split_bivs (PATTERN (insn));
1189     }
1190
1191   /* For unroll_number times, make a copy of each instruction
1192      between copy_start and copy_end, and insert these new instructions
1193      before the end of the loop.  */
1194
1195   for (i = 0; i < unroll_number; i++)
1196     {
1197       bzero ((char *) map->insn_map, max_insnno * sizeof (rtx));
1198       bzero ((char *) &VARRAY_CONST_EQUIV (map->const_equiv_varray, 0),
1199              VARRAY_SIZE (map->const_equiv_varray) * sizeof (struct const_equiv_data));
1200       map->const_age = 0;
1201
1202       for (j = 0; j < max_labelno; j++)
1203         if (local_label[j])
1204           set_label_in_map (map, j, gen_label_rtx ());
1205
1206       for (j = FIRST_PSEUDO_REGISTER; j < max_local_regnum; j++)
1207         if (local_regno[j])
1208           {
1209             map->reg_map[j] = gen_reg_rtx (GET_MODE (regno_reg_rtx[j]));
1210             record_base_value (REGNO (map->reg_map[j]),
1211                                regno_reg_rtx[j], 0);
1212           }
1213
1214       /* If loop starts with a branch to the test, then fix it so that
1215          it points to the test of the first unrolled copy of the loop.  */
1216       if (i == 0 && loop_start != copy_start)
1217         {
1218           insn = PREV_INSN (copy_start);
1219           pattern = PATTERN (insn);
1220
1221           tem = get_label_from_map (map,
1222                                     CODE_LABEL_NUMBER
1223                                     (XEXP (SET_SRC (pattern), 0)));
1224           SET_SRC (pattern) = gen_rtx_LABEL_REF (VOIDmode, tem);
1225
1226           /* Set the jump label so that it can be used by later loop unrolling
1227              passes.  */
1228           JUMP_LABEL (insn) = tem;
1229           LABEL_NUSES (tem)++;
1230         }
1231
1232       copy_loop_body (copy_start, copy_end, map, exit_label,
1233                       i == unroll_number - 1, unroll_type, start_label,
1234                       loop_end, insert_before, insert_before);
1235     }
1236
1237   /* Before deleting any insns, emit a CODE_LABEL immediately after the last
1238      insn to be deleted.  This prevents any runaway delete_insn call from
1239      more insns that it should, as it always stops at a CODE_LABEL.  */
1240
1241   /* Delete the compare and branch at the end of the loop if completely
1242      unrolling the loop.  Deleting the backward branch at the end also
1243      deletes the code label at the start of the loop.  This is done at
1244      the very end to avoid problems with back_branch_in_range_p.  */
1245
1246   if (unroll_type == UNROLL_COMPLETELY)
1247     safety_label = emit_label_after (gen_label_rtx (), last_loop_insn);
1248   else
1249     safety_label = emit_label_after (gen_label_rtx (), copy_end);
1250
1251   /* Delete all of the original loop instructions.  Don't delete the
1252      LOOP_BEG note, or the first code label in the loop.  */
1253
1254   insn = NEXT_INSN (copy_start);
1255   while (insn != safety_label)
1256     {
1257       /* ??? Don't delete named code labels.  They will be deleted when the
1258          jump that references them is deleted.  Otherwise, we end up deleting
1259          them twice, which causes them to completely disappear instead of turn
1260          into NOTE_INSN_DELETED_LABEL notes.  This in turn causes aborts in
1261          dwarfout.c/dwarf2out.c.  We could perhaps fix the dwarf*out.c files
1262          to handle deleted labels instead.  Or perhaps fix DECL_RTL of the
1263          associated LABEL_DECL to point to one of the new label instances.  */
1264       /* ??? Likewise, we can't delete a NOTE_INSN_DELETED_LABEL note.  */
1265       if (insn != start_label
1266           && ! (GET_CODE (insn) == CODE_LABEL && LABEL_NAME (insn))
1267           && ! (GET_CODE (insn) == NOTE
1268                 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED_LABEL))
1269         insn = delete_insn (insn);
1270       else
1271         insn = NEXT_INSN (insn);
1272     }
1273
1274   /* Can now delete the 'safety' label emitted to protect us from runaway
1275      delete_insn calls.  */
1276   if (INSN_DELETED_P (safety_label))
1277     abort ();
1278   delete_insn (safety_label);
1279
1280   /* If exit_label exists, emit it after the loop.  Doing the emit here
1281      forces it to have a higher INSN_UID than any insn in the unrolled loop.
1282      This is needed so that mostly_true_jump in reorg.c will treat jumps
1283      to this loop end label correctly, i.e. predict that they are usually
1284      not taken.  */
1285   if (exit_label)
1286     emit_label_after (exit_label, loop_end);
1287
1288  egress:
1289   if (map && map->const_equiv_varray)
1290     VARRAY_FREE (map->const_equiv_varray);
1291 }
1292 \f
1293 /* Return true if the loop can be safely, and profitably, preconditioned
1294    so that the unrolled copies of the loop body don't need exit tests.
1295
1296    This only works if final_value, initial_value and increment can be
1297    determined, and if increment is a constant power of 2.
1298    If increment is not a power of 2, then the preconditioning modulo
1299    operation would require a real modulo instead of a boolean AND, and this
1300    is not considered `profitable'.  */
1301
1302 /* ??? If the loop is known to be executed very many times, or the machine
1303    has a very cheap divide instruction, then preconditioning is a win even
1304    when the increment is not a power of 2.  Use RTX_COST to compute
1305    whether divide is cheap.
1306    ??? A divide by constant doesn't actually need a divide, look at
1307    expand_divmod.  The reduced cost of this optimized modulo is not
1308    reflected in RTX_COST.  */
1309
1310 int
1311 precondition_loop_p (loop_start, loop_info,
1312                      initial_value, final_value, increment, mode)
1313      rtx loop_start;
1314      struct loop_info *loop_info;
1315      rtx *initial_value, *final_value, *increment;
1316      enum machine_mode *mode;
1317 {
1318
1319   if (loop_info->n_iterations > 0)
1320     {
1321       *initial_value = const0_rtx;
1322       *increment = const1_rtx;
1323       *final_value = GEN_INT (loop_info->n_iterations);
1324       *mode = word_mode;
1325
1326       if (loop_dump_stream)
1327         {
1328           fputs ("Preconditioning: Success, number of iterations known, ",
1329                  loop_dump_stream);
1330           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC,
1331                    loop_info->n_iterations);
1332           fputs (".\n", loop_dump_stream);
1333         }
1334       return 1;
1335     }
1336
1337   if (loop_info->initial_value == 0)
1338     {
1339       if (loop_dump_stream)
1340         fprintf (loop_dump_stream,
1341                  "Preconditioning: Could not find initial value.\n");
1342       return 0;
1343     }
1344   else if (loop_info->increment == 0)
1345     {
1346       if (loop_dump_stream)
1347         fprintf (loop_dump_stream,
1348                  "Preconditioning: Could not find increment value.\n");
1349       return 0;
1350     }
1351   else if (GET_CODE (loop_info->increment) != CONST_INT)
1352     {
1353       if (loop_dump_stream)
1354         fprintf (loop_dump_stream,
1355                  "Preconditioning: Increment not a constant.\n");
1356       return 0;
1357     }
1358   else if ((exact_log2 (INTVAL (loop_info->increment)) < 0)
1359            && (exact_log2 (- INTVAL (loop_info->increment)) < 0))
1360     {
1361       if (loop_dump_stream)
1362         fprintf (loop_dump_stream,
1363                  "Preconditioning: Increment not a constant power of 2.\n");
1364       return 0;
1365     }
1366
1367   /* Unsigned_compare and compare_dir can be ignored here, since they do
1368      not matter for preconditioning.  */
1369
1370   if (loop_info->final_value == 0)
1371     {
1372       if (loop_dump_stream)
1373         fprintf (loop_dump_stream,
1374                  "Preconditioning: EQ comparison loop.\n");
1375       return 0;
1376     }
1377
1378   /* Must ensure that final_value is invariant, so call invariant_p to
1379      check.  Before doing so, must check regno against max_reg_before_loop
1380      to make sure that the register is in the range covered by invariant_p.
1381      If it isn't, then it is most likely a biv/giv which by definition are
1382      not invariant.  */
1383   if ((GET_CODE (loop_info->final_value) == REG
1384        && REGNO (loop_info->final_value) >= max_reg_before_loop)
1385       || (GET_CODE (loop_info->final_value) == PLUS
1386           && REGNO (XEXP (loop_info->final_value, 0)) >= max_reg_before_loop)
1387       || ! invariant_p (loop_info->final_value))
1388     {
1389       if (loop_dump_stream)
1390         fprintf (loop_dump_stream,
1391                  "Preconditioning: Final value not invariant.\n");
1392       return 0;
1393     }
1394
1395   /* Fail for floating point values, since the caller of this function
1396      does not have code to deal with them.  */
1397   if (GET_MODE_CLASS (GET_MODE (loop_info->final_value)) == MODE_FLOAT
1398       || GET_MODE_CLASS (GET_MODE (loop_info->initial_value)) == MODE_FLOAT)
1399     {
1400       if (loop_dump_stream)
1401         fprintf (loop_dump_stream,
1402                  "Preconditioning: Floating point final or initial value.\n");
1403       return 0;
1404     }
1405
1406   /* Fail if loop_info->iteration_var is not live before loop_start,
1407      since we need to test its value in the preconditioning code.  */
1408
1409   if (uid_luid[REGNO_FIRST_UID (REGNO (loop_info->iteration_var))]
1410       > INSN_LUID (loop_start))
1411     {
1412       if (loop_dump_stream)
1413         fprintf (loop_dump_stream,
1414                  "Preconditioning: Iteration var not live before loop start.\n");
1415       return 0;
1416     }
1417
1418   /* Note that iteration_info biases the initial value for GIV iterators
1419      such as "while (i-- > 0)" so that we can calculate the number of
1420      iterations just like for BIV iterators.
1421
1422      Also note that the absolute values of initial_value and
1423      final_value are unimportant as only their difference is used for
1424      calculating the number of loop iterations.  */
1425   *initial_value = loop_info->initial_value;
1426   *increment = loop_info->increment;
1427   *final_value = loop_info->final_value;
1428
1429   /* Decide what mode to do these calculations in.  Choose the larger
1430      of final_value's mode and initial_value's mode, or a full-word if
1431      both are constants.  */
1432   *mode = GET_MODE (*final_value);
1433   if (*mode == VOIDmode)
1434     {
1435       *mode = GET_MODE (*initial_value);
1436       if (*mode == VOIDmode)
1437         *mode = word_mode;
1438     }
1439   else if (*mode != GET_MODE (*initial_value)
1440            && (GET_MODE_SIZE (*mode)
1441                < GET_MODE_SIZE (GET_MODE (*initial_value))))
1442     *mode = GET_MODE (*initial_value);
1443
1444   /* Success! */
1445   if (loop_dump_stream)
1446     fprintf (loop_dump_stream, "Preconditioning: Successful.\n");
1447   return 1;
1448 }
1449
1450
1451 /* All pseudo-registers must be mapped to themselves.  Two hard registers
1452    must be mapped, VIRTUAL_STACK_VARS_REGNUM and VIRTUAL_INCOMING_ARGS_
1453    REGNUM, to avoid function-inlining specific conversions of these
1454    registers.  All other hard regs can not be mapped because they may be
1455    used with different
1456    modes.  */
1457
1458 static void
1459 init_reg_map (map, maxregnum)
1460      struct inline_remap *map;
1461      int maxregnum;
1462 {
1463   int i;
1464
1465   for (i = maxregnum - 1; i > LAST_VIRTUAL_REGISTER; i--)
1466     map->reg_map[i] = regno_reg_rtx[i];
1467   /* Just clear the rest of the entries.  */
1468   for (i = LAST_VIRTUAL_REGISTER; i >= 0; i--)
1469     map->reg_map[i] = 0;
1470
1471   map->reg_map[VIRTUAL_STACK_VARS_REGNUM]
1472     = regno_reg_rtx[VIRTUAL_STACK_VARS_REGNUM];
1473   map->reg_map[VIRTUAL_INCOMING_ARGS_REGNUM]
1474     = regno_reg_rtx[VIRTUAL_INCOMING_ARGS_REGNUM];
1475 }
1476 \f
1477 /* Strength-reduction will often emit code for optimized biv/givs which
1478    calculates their value in a temporary register, and then copies the result
1479    to the iv.  This procedure reconstructs the pattern computing the iv;
1480    verifying that all operands are of the proper form.
1481
1482    PATTERN must be the result of single_set.
1483    The return value is the amount that the giv is incremented by.  */
1484
1485 static rtx
1486 calculate_giv_inc (pattern, src_insn, regno)
1487      rtx pattern, src_insn;
1488      int regno;
1489 {
1490   rtx increment;
1491   rtx increment_total = 0;
1492   int tries = 0;
1493
1494  retry:
1495   /* Verify that we have an increment insn here.  First check for a plus
1496      as the set source.  */
1497   if (GET_CODE (SET_SRC (pattern)) != PLUS)
1498     {
1499       /* SR sometimes computes the new giv value in a temp, then copies it
1500          to the new_reg.  */
1501       src_insn = PREV_INSN (src_insn);
1502       pattern = PATTERN (src_insn);
1503       if (GET_CODE (SET_SRC (pattern)) != PLUS)
1504         abort ();
1505
1506       /* The last insn emitted is not needed, so delete it to avoid confusing
1507          the second cse pass.  This insn sets the giv unnecessarily.  */
1508       delete_insn (get_last_insn ());
1509     }
1510
1511   /* Verify that we have a constant as the second operand of the plus.  */
1512   increment = XEXP (SET_SRC (pattern), 1);
1513   if (GET_CODE (increment) != CONST_INT)
1514     {
1515       /* SR sometimes puts the constant in a register, especially if it is
1516          too big to be an add immed operand.  */
1517       src_insn = PREV_INSN (src_insn);
1518       increment = SET_SRC (PATTERN (src_insn));
1519
1520       /* SR may have used LO_SUM to compute the constant if it is too large
1521          for a load immed operand.  In this case, the constant is in operand
1522          one of the LO_SUM rtx.  */
1523       if (GET_CODE (increment) == LO_SUM)
1524         increment = XEXP (increment, 1);
1525
1526       /* Some ports store large constants in memory and add a REG_EQUAL
1527          note to the store insn.  */
1528       else if (GET_CODE (increment) == MEM)
1529         {
1530           rtx note = find_reg_note (src_insn, REG_EQUAL, 0);
1531           if (note)
1532             increment = XEXP (note, 0);
1533         }
1534
1535       else if (GET_CODE (increment) == IOR
1536                || GET_CODE (increment) == ASHIFT
1537                || GET_CODE (increment) == PLUS)
1538         {
1539           /* The rs6000 port loads some constants with IOR.
1540              The alpha port loads some constants with ASHIFT and PLUS.  */
1541           rtx second_part = XEXP (increment, 1);
1542           enum rtx_code code = GET_CODE (increment);
1543
1544           src_insn = PREV_INSN (src_insn);
1545           increment = SET_SRC (PATTERN (src_insn));
1546           /* Don't need the last insn anymore.  */
1547           delete_insn (get_last_insn ());
1548
1549           if (GET_CODE (second_part) != CONST_INT
1550               || GET_CODE (increment) != CONST_INT)
1551             abort ();
1552
1553           if (code == IOR)
1554             increment = GEN_INT (INTVAL (increment) | INTVAL (second_part));
1555           else if (code == PLUS)
1556             increment = GEN_INT (INTVAL (increment) + INTVAL (second_part));
1557           else
1558             increment = GEN_INT (INTVAL (increment) << INTVAL (second_part));
1559         }
1560
1561       if (GET_CODE (increment) != CONST_INT)
1562         abort ();
1563
1564       /* The insn loading the constant into a register is no longer needed,
1565          so delete it.  */
1566       delete_insn (get_last_insn ());
1567     }
1568
1569   if (increment_total)
1570     increment_total = GEN_INT (INTVAL (increment_total) + INTVAL (increment));
1571   else
1572     increment_total = increment;
1573
1574   /* Check that the source register is the same as the register we expected
1575      to see as the source.  If not, something is seriously wrong.  */
1576   if (GET_CODE (XEXP (SET_SRC (pattern), 0)) != REG
1577       || REGNO (XEXP (SET_SRC (pattern), 0)) != regno)
1578     {
1579       /* Some machines (e.g. the romp), may emit two add instructions for
1580          certain constants, so lets try looking for another add immediately
1581          before this one if we have only seen one add insn so far.  */
1582
1583       if (tries == 0)
1584         {
1585           tries++;
1586
1587           src_insn = PREV_INSN (src_insn);
1588           pattern = PATTERN (src_insn);
1589
1590           delete_insn (get_last_insn ());
1591
1592           goto retry;
1593         }
1594
1595       abort ();
1596     }
1597
1598   return increment_total;
1599 }
1600
1601 /* Copy REG_NOTES, except for insn references, because not all insn_map
1602    entries are valid yet.  We do need to copy registers now though, because
1603    the reg_map entries can change during copying.  */
1604
1605 static rtx
1606 initial_reg_note_copy (notes, map)
1607      rtx notes;
1608      struct inline_remap *map;
1609 {
1610   rtx copy;
1611
1612   if (notes == 0)
1613     return 0;
1614
1615   copy = rtx_alloc (GET_CODE (notes));
1616   PUT_MODE (copy, GET_MODE (notes));
1617
1618   if (GET_CODE (notes) == EXPR_LIST)
1619     XEXP (copy, 0) = copy_rtx_and_substitute (XEXP (notes, 0), map);
1620   else if (GET_CODE (notes) == INSN_LIST)
1621     /* Don't substitute for these yet.  */
1622     XEXP (copy, 0) = XEXP (notes, 0);
1623   else
1624     abort ();
1625
1626   XEXP (copy, 1) = initial_reg_note_copy (XEXP (notes, 1), map);
1627
1628   return copy;
1629 }
1630
1631 /* Fixup insn references in copied REG_NOTES.  */
1632
1633 static void
1634 final_reg_note_copy (notes, map)
1635      rtx notes;
1636      struct inline_remap *map;
1637 {
1638   rtx note;
1639
1640   for (note = notes; note; note = XEXP (note, 1))
1641     if (GET_CODE (note) == INSN_LIST)
1642       XEXP (note, 0) = map->insn_map[INSN_UID (XEXP (note, 0))];
1643 }
1644
1645 /* Copy each instruction in the loop, substituting from map as appropriate.
1646    This is very similar to a loop in expand_inline_function.  */
1647
1648 static void
1649 copy_loop_body (copy_start, copy_end, map, exit_label, last_iteration,
1650                 unroll_type, start_label, loop_end, insert_before,
1651                 copy_notes_from)
1652      rtx copy_start, copy_end;
1653      struct inline_remap *map;
1654      rtx exit_label;
1655      int last_iteration;
1656      enum unroll_types unroll_type;
1657      rtx start_label, loop_end, insert_before, copy_notes_from;
1658 {
1659   rtx insn, pattern;
1660   rtx set, tem, copy;
1661   int dest_reg_was_split, i;
1662 #ifdef HAVE_cc0
1663   rtx cc0_insn = 0;
1664 #endif
1665   rtx final_label = 0;
1666   rtx giv_inc, giv_dest_reg, giv_src_reg;
1667
1668   /* If this isn't the last iteration, then map any references to the
1669      start_label to final_label.  Final label will then be emitted immediately
1670      after the end of this loop body if it was ever used.
1671
1672      If this is the last iteration, then map references to the start_label
1673      to itself.  */
1674   if (! last_iteration)
1675     {
1676       final_label = gen_label_rtx ();
1677       set_label_in_map (map, CODE_LABEL_NUMBER (start_label),
1678                         final_label);
1679     }
1680   else
1681     set_label_in_map (map, CODE_LABEL_NUMBER (start_label), start_label);
1682
1683   start_sequence ();
1684
1685   /* Emit a NOTE_INSN_DELETED to force at least two insns onto the sequence.
1686      Else gen_sequence could return a raw pattern for a jump which we pass
1687      off to emit_insn_before (instead of emit_jump_insn_before) which causes
1688      a variety of losing behaviors later.  */
1689   emit_note (0, NOTE_INSN_DELETED);
1690
1691   insn = copy_start;
1692   do
1693     {
1694       insn = NEXT_INSN (insn);
1695
1696       map->orig_asm_operands_vector = 0;
1697
1698       switch (GET_CODE (insn))
1699         {
1700         case INSN:
1701           pattern = PATTERN (insn);
1702           copy = 0;
1703           giv_inc = 0;
1704
1705           /* Check to see if this is a giv that has been combined with
1706              some split address givs.  (Combined in the sense that
1707              `combine_givs' in loop.c has put two givs in the same register.)
1708              In this case, we must search all givs based on the same biv to
1709              find the address givs.  Then split the address givs.
1710              Do this before splitting the giv, since that may map the
1711              SET_DEST to a new register.  */
1712
1713           if ((set = single_set (insn))
1714               && GET_CODE (SET_DEST (set)) == REG
1715               && addr_combined_regs[REGNO (SET_DEST (set))])
1716             {
1717               struct iv_class *bl;
1718               struct induction *v, *tv;
1719               int regno = REGNO (SET_DEST (set));
1720
1721               v = addr_combined_regs[REGNO (SET_DEST (set))];
1722               bl = reg_biv_class[REGNO (v->src_reg)];
1723
1724               /* Although the giv_inc amount is not needed here, we must call
1725                  calculate_giv_inc here since it might try to delete the
1726                  last insn emitted.  If we wait until later to call it,
1727                  we might accidentally delete insns generated immediately
1728                  below by emit_unrolled_add.  */
1729
1730               if (! derived_regs[regno])
1731                 giv_inc = calculate_giv_inc (set, insn, regno);
1732
1733               /* Now find all address giv's that were combined with this
1734                  giv 'v'.  */
1735               for (tv = bl->giv; tv; tv = tv->next_iv)
1736                 if (tv->giv_type == DEST_ADDR && tv->same == v)
1737                   {
1738                     int this_giv_inc;
1739
1740                     /* If this DEST_ADDR giv was not split, then ignore it.  */
1741                     if (*tv->location != tv->dest_reg)
1742                       continue;
1743
1744                     /* Scale this_giv_inc if the multiplicative factors of
1745                        the two givs are different.  */
1746                     this_giv_inc = INTVAL (giv_inc);
1747                     if (tv->mult_val != v->mult_val)
1748                       this_giv_inc = (this_giv_inc / INTVAL (v->mult_val)
1749                                       * INTVAL (tv->mult_val));
1750
1751                     tv->dest_reg = plus_constant (tv->dest_reg, this_giv_inc);
1752                     *tv->location = tv->dest_reg;
1753
1754                     if (last_iteration && unroll_type != UNROLL_COMPLETELY)
1755                       {
1756                         /* Must emit an insn to increment the split address
1757                            giv.  Add in the const_adjust field in case there
1758                            was a constant eliminated from the address.  */
1759                         rtx value, dest_reg;
1760
1761                         /* tv->dest_reg will be either a bare register,
1762                            or else a register plus a constant.  */
1763                         if (GET_CODE (tv->dest_reg) == REG)
1764                           dest_reg = tv->dest_reg;
1765                         else
1766                           dest_reg = XEXP (tv->dest_reg, 0);
1767
1768                         /* Check for shared address givs, and avoid
1769                            incrementing the shared pseudo reg more than
1770                            once.  */
1771                         if (! tv->same_insn && ! tv->shared)
1772                           {
1773                             /* tv->dest_reg may actually be a (PLUS (REG)
1774                                (CONST)) here, so we must call plus_constant
1775                                to add the const_adjust amount before calling
1776                                emit_unrolled_add below.  */
1777                             value = plus_constant (tv->dest_reg,
1778                                                    tv->const_adjust);
1779
1780                             /* The constant could be too large for an add
1781                                immediate, so can't directly emit an insn
1782                                here.  */
1783                             emit_unrolled_add (dest_reg, XEXP (value, 0),
1784                                                XEXP (value, 1));
1785                           }
1786
1787                         /* Reset the giv to be just the register again, in case
1788                            it is used after the set we have just emitted.
1789                            We must subtract the const_adjust factor added in
1790                            above.  */
1791                         tv->dest_reg = plus_constant (dest_reg,
1792                                                       - tv->const_adjust);
1793                         *tv->location = tv->dest_reg;
1794                       }
1795                   }
1796             }
1797
1798           /* If this is a setting of a splittable variable, then determine
1799              how to split the variable, create a new set based on this split,
1800              and set up the reg_map so that later uses of the variable will
1801              use the new split variable.  */
1802
1803           dest_reg_was_split = 0;
1804
1805           if ((set = single_set (insn))
1806               && GET_CODE (SET_DEST (set)) == REG
1807               && splittable_regs[REGNO (SET_DEST (set))])
1808             {
1809               int regno = REGNO (SET_DEST (set));
1810               int src_regno;
1811
1812               dest_reg_was_split = 1;
1813
1814               giv_dest_reg = SET_DEST (set);
1815               if (derived_regs[regno])
1816                 {
1817                   /* ??? This relies on SET_SRC (SET) to be of
1818                      the form (plus (reg) (const_int)), and thus
1819                      forces recombine_givs to restrict the kind
1820                      of giv derivations it does before unrolling.  */
1821                   giv_src_reg = XEXP (SET_SRC (set), 0);
1822                   giv_inc = XEXP (SET_SRC (set), 1);
1823                 }
1824               else
1825                 {
1826                   giv_src_reg = giv_dest_reg;
1827                   /* Compute the increment value for the giv, if it wasn't
1828                      already computed above.  */
1829                   if (giv_inc == 0)
1830                     giv_inc = calculate_giv_inc (set, insn, regno);
1831                 }
1832               src_regno = REGNO (giv_src_reg);
1833
1834               if (unroll_type == UNROLL_COMPLETELY)
1835                 {
1836                   /* Completely unrolling the loop.  Set the induction
1837                      variable to a known constant value.  */
1838
1839                   /* The value in splittable_regs may be an invariant
1840                      value, so we must use plus_constant here.  */
1841                   splittable_regs[regno]
1842                     = plus_constant (splittable_regs[src_regno],
1843                                      INTVAL (giv_inc));
1844
1845                   if (GET_CODE (splittable_regs[regno]) == PLUS)
1846                     {
1847                       giv_src_reg = XEXP (splittable_regs[regno], 0);
1848                       giv_inc = XEXP (splittable_regs[regno], 1);
1849                     }
1850                   else
1851                     {
1852                       /* The splittable_regs value must be a REG or a
1853                          CONST_INT, so put the entire value in the giv_src_reg
1854                          variable.  */
1855                       giv_src_reg = splittable_regs[regno];
1856                       giv_inc = const0_rtx;
1857                     }
1858                 }
1859               else
1860                 {
1861                   /* Partially unrolling loop.  Create a new pseudo
1862                      register for the iteration variable, and set it to
1863                      be a constant plus the original register.  Except
1864                      on the last iteration, when the result has to
1865                      go back into the original iteration var register.  */
1866
1867                   /* Handle bivs which must be mapped to a new register
1868                      when split.  This happens for bivs which need their
1869                      final value set before loop entry.  The new register
1870                      for the biv was stored in the biv's first struct
1871                      induction entry by find_splittable_regs.  */
1872
1873                   if (regno < max_reg_before_loop
1874                       && REG_IV_TYPE (regno) == BASIC_INDUCT)
1875                     {
1876                       giv_src_reg = reg_biv_class[regno]->biv->src_reg;
1877                       giv_dest_reg = giv_src_reg;
1878                     }
1879
1880 #if 0
1881                   /* If non-reduced/final-value givs were split, then
1882                      this would have to remap those givs also.  See
1883                      find_splittable_regs.  */
1884 #endif
1885
1886                   splittable_regs[regno]
1887                     = GEN_INT (INTVAL (giv_inc)
1888                                + INTVAL (splittable_regs[src_regno]));
1889                   giv_inc = splittable_regs[regno];
1890
1891                   /* Now split the induction variable by changing the dest
1892                      of this insn to a new register, and setting its
1893                      reg_map entry to point to this new register.
1894
1895                      If this is the last iteration, and this is the last insn
1896                      that will update the iv, then reuse the original dest,
1897                      to ensure that the iv will have the proper value when
1898                      the loop exits or repeats.
1899
1900                      Using splittable_regs_updates here like this is safe,
1901                      because it can only be greater than one if all
1902                      instructions modifying the iv are always executed in
1903                      order.  */
1904
1905                   if (! last_iteration
1906                       || (splittable_regs_updates[regno]-- != 1))
1907                     {
1908                       tem = gen_reg_rtx (GET_MODE (giv_src_reg));
1909                       giv_dest_reg = tem;
1910                       map->reg_map[regno] = tem;
1911                       record_base_value (REGNO (tem),
1912                                          giv_inc == const0_rtx
1913                                          ? giv_src_reg
1914                                          : gen_rtx_PLUS (GET_MODE (giv_src_reg),
1915                                                          giv_src_reg, giv_inc),
1916                                          1);
1917                     }
1918                   else
1919                     map->reg_map[regno] = giv_src_reg;
1920                 }
1921
1922               /* The constant being added could be too large for an add
1923                  immediate, so can't directly emit an insn here.  */
1924               emit_unrolled_add (giv_dest_reg, giv_src_reg, giv_inc);
1925               copy = get_last_insn ();
1926               pattern = PATTERN (copy);
1927             }
1928           else
1929             {
1930               pattern = copy_rtx_and_substitute (pattern, map);
1931               copy = emit_insn (pattern);
1932             }
1933           REG_NOTES (copy) = initial_reg_note_copy (REG_NOTES (insn), map);
1934
1935 #ifdef HAVE_cc0
1936           /* If this insn is setting CC0, it may need to look at
1937              the insn that uses CC0 to see what type of insn it is.
1938              In that case, the call to recog via validate_change will
1939              fail.  So don't substitute constants here.  Instead,
1940              do it when we emit the following insn.
1941
1942              For example, see the pyr.md file.  That machine has signed and
1943              unsigned compares.  The compare patterns must check the
1944              following branch insn to see which what kind of compare to
1945              emit.
1946
1947              If the previous insn set CC0, substitute constants on it as
1948              well.  */
1949           if (sets_cc0_p (PATTERN (copy)) != 0)
1950             cc0_insn = copy;
1951           else
1952             {
1953               if (cc0_insn)
1954                 try_constants (cc0_insn, map);
1955               cc0_insn = 0;
1956               try_constants (copy, map);
1957             }
1958 #else
1959           try_constants (copy, map);
1960 #endif
1961
1962           /* Make split induction variable constants `permanent' since we
1963              know there are no backward branches across iteration variable
1964              settings which would invalidate this.  */
1965           if (dest_reg_was_split)
1966             {
1967               int regno = REGNO (SET_DEST (pattern));
1968
1969               if ((size_t) regno < VARRAY_SIZE (map->const_equiv_varray)
1970                   && (VARRAY_CONST_EQUIV (map->const_equiv_varray, regno).age
1971                       == map->const_age))
1972                 VARRAY_CONST_EQUIV (map->const_equiv_varray, regno).age = -1;
1973             }
1974           break;
1975
1976         case JUMP_INSN:
1977           pattern = copy_rtx_and_substitute (PATTERN (insn), map);
1978           copy = emit_jump_insn (pattern);
1979           REG_NOTES (copy) = initial_reg_note_copy (REG_NOTES (insn), map);
1980
1981           if (JUMP_LABEL (insn) == start_label && insn == copy_end
1982               && ! last_iteration)
1983             {
1984               /* This is a branch to the beginning of the loop; this is the
1985                  last insn being copied; and this is not the last iteration.
1986                  In this case, we want to change the original fall through
1987                  case to be a branch past the end of the loop, and the
1988                  original jump label case to fall_through.  */
1989
1990               if (invert_exp (pattern, copy))
1991                 {
1992                   if (! redirect_exp (&pattern,
1993                                       get_label_from_map (map,
1994                                                           CODE_LABEL_NUMBER
1995                                                           (JUMP_LABEL (insn))),
1996                                       exit_label, copy))
1997                     abort ();
1998                 }
1999               else
2000                 {
2001                   rtx jmp;
2002                   rtx lab = gen_label_rtx ();
2003                   /* Can't do it by reversing the jump (probably because we
2004                      couldn't reverse the conditions), so emit a new
2005                      jump_insn after COPY, and redirect the jump around
2006                      that.  */
2007                   jmp = emit_jump_insn_after (gen_jump (exit_label), copy);
2008                   jmp = emit_barrier_after (jmp);
2009                   emit_label_after (lab, jmp);
2010                   LABEL_NUSES (lab) = 0;
2011                   if (! redirect_exp (&pattern,
2012                                       get_label_from_map (map,
2013                                                           CODE_LABEL_NUMBER
2014                                                           (JUMP_LABEL (insn))),
2015                                       lab, copy))
2016                     abort ();
2017                 }
2018             }
2019
2020 #ifdef HAVE_cc0
2021           if (cc0_insn)
2022             try_constants (cc0_insn, map);
2023           cc0_insn = 0;
2024 #endif
2025           try_constants (copy, map);
2026
2027           /* Set the jump label of COPY correctly to avoid problems with
2028              later passes of unroll_loop, if INSN had jump label set.  */
2029           if (JUMP_LABEL (insn))
2030             {
2031               rtx label = 0;
2032
2033               /* Can't use the label_map for every insn, since this may be
2034                  the backward branch, and hence the label was not mapped.  */
2035               if ((set = single_set (copy)))
2036                 {
2037                   tem = SET_SRC (set);
2038                   if (GET_CODE (tem) == LABEL_REF)
2039                     label = XEXP (tem, 0);
2040                   else if (GET_CODE (tem) == IF_THEN_ELSE)
2041                     {
2042                       if (XEXP (tem, 1) != pc_rtx)
2043                         label = XEXP (XEXP (tem, 1), 0);
2044                       else
2045                         label = XEXP (XEXP (tem, 2), 0);
2046                     }
2047                 }
2048
2049               if (label && GET_CODE (label) == CODE_LABEL)
2050                 JUMP_LABEL (copy) = label;
2051               else
2052                 {
2053                   /* An unrecognizable jump insn, probably the entry jump
2054                      for a switch statement.  This label must have been mapped,
2055                      so just use the label_map to get the new jump label.  */
2056                   JUMP_LABEL (copy)
2057                     = get_label_from_map (map,
2058                                           CODE_LABEL_NUMBER (JUMP_LABEL (insn)));
2059                 }
2060
2061               /* If this is a non-local jump, then must increase the label
2062                  use count so that the label will not be deleted when the
2063                  original jump is deleted.  */
2064               LABEL_NUSES (JUMP_LABEL (copy))++;
2065             }
2066           else if (GET_CODE (PATTERN (copy)) == ADDR_VEC
2067                    || GET_CODE (PATTERN (copy)) == ADDR_DIFF_VEC)
2068             {
2069               rtx pat = PATTERN (copy);
2070               int diff_vec_p = GET_CODE (pat) == ADDR_DIFF_VEC;
2071               int len = XVECLEN (pat, diff_vec_p);
2072               int i;
2073
2074               for (i = 0; i < len; i++)
2075                 LABEL_NUSES (XEXP (XVECEXP (pat, diff_vec_p, i), 0))++;
2076             }
2077
2078           /* If this used to be a conditional jump insn but whose branch
2079              direction is now known, we must do something special.  */
2080           if (condjump_p (insn) && !simplejump_p (insn) && map->last_pc_value)
2081             {
2082 #ifdef HAVE_cc0
2083               /* If the previous insn set cc0 for us, delete it.  */
2084               if (sets_cc0_p (PREV_INSN (copy)))
2085                 delete_insn (PREV_INSN (copy));
2086 #endif
2087
2088               /* If this is now a no-op, delete it.  */
2089               if (map->last_pc_value == pc_rtx)
2090                 {
2091                   /* Don't let delete_insn delete the label referenced here,
2092                      because we might possibly need it later for some other
2093                      instruction in the loop.  */
2094                   if (JUMP_LABEL (copy))
2095                     LABEL_NUSES (JUMP_LABEL (copy))++;
2096                   delete_insn (copy);
2097                   if (JUMP_LABEL (copy))
2098                     LABEL_NUSES (JUMP_LABEL (copy))--;
2099                   copy = 0;
2100                 }
2101               else
2102                 /* Otherwise, this is unconditional jump so we must put a
2103                    BARRIER after it.  We could do some dead code elimination
2104                    here, but jump.c will do it just as well.  */
2105                 emit_barrier ();
2106             }
2107           break;
2108
2109         case CALL_INSN:
2110           pattern = copy_rtx_and_substitute (PATTERN (insn), map);
2111           copy = emit_call_insn (pattern);
2112           REG_NOTES (copy) = initial_reg_note_copy (REG_NOTES (insn), map);
2113
2114           /* Because the USAGE information potentially contains objects other
2115              than hard registers, we need to copy it.  */
2116           CALL_INSN_FUNCTION_USAGE (copy)
2117             = copy_rtx_and_substitute (CALL_INSN_FUNCTION_USAGE (insn), map);
2118
2119 #ifdef HAVE_cc0
2120           if (cc0_insn)
2121             try_constants (cc0_insn, map);
2122           cc0_insn = 0;
2123 #endif
2124           try_constants (copy, map);
2125
2126           /* Be lazy and assume CALL_INSNs clobber all hard registers.  */
2127           for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
2128             VARRAY_CONST_EQUIV (map->const_equiv_varray, i).rtx = 0;
2129           break;
2130
2131         case CODE_LABEL:
2132           /* If this is the loop start label, then we don't need to emit a
2133              copy of this label since no one will use it.  */
2134
2135           if (insn != start_label)
2136             {
2137               copy = emit_label (get_label_from_map (map,
2138                                                      CODE_LABEL_NUMBER (insn)));
2139               map->const_age++;
2140             }
2141           break;
2142
2143         case BARRIER:
2144           copy = emit_barrier ();
2145           break;
2146
2147         case NOTE:
2148           /* VTOP and CONT notes are valid only before the loop exit test.
2149              If placed anywhere else, loop may generate bad code.  */
2150           /* BASIC_BLOCK notes exist to stabilize basic block structures with
2151              the associated rtl.  We do not want to share the structure in 
2152              this new block.  */
2153
2154           if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_DELETED
2155               && NOTE_LINE_NUMBER (insn) != NOTE_INSN_BASIC_BLOCK
2156               && ((NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_VTOP
2157                    && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_CONT)
2158                   || (last_iteration && unroll_type != UNROLL_COMPLETELY)))
2159             copy = emit_note (NOTE_SOURCE_FILE (insn),
2160                               NOTE_LINE_NUMBER (insn));
2161           else
2162             copy = 0;
2163           break;
2164
2165         default:
2166           abort ();
2167         }
2168
2169       map->insn_map[INSN_UID (insn)] = copy;
2170     }
2171   while (insn != copy_end);
2172
2173   /* Now finish coping the REG_NOTES.  */
2174   insn = copy_start;
2175   do
2176     {
2177       insn = NEXT_INSN (insn);
2178       if ((GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN
2179            || GET_CODE (insn) == CALL_INSN)
2180           && map->insn_map[INSN_UID (insn)])
2181         final_reg_note_copy (REG_NOTES (map->insn_map[INSN_UID (insn)]), map);
2182     }
2183   while (insn != copy_end);
2184
2185   /* There may be notes between copy_notes_from and loop_end.  Emit a copy of
2186      each of these notes here, since there may be some important ones, such as
2187      NOTE_INSN_BLOCK_END notes, in this group.  We don't do this on the last
2188      iteration, because the original notes won't be deleted.
2189
2190      We can't use insert_before here, because when from preconditioning,
2191      insert_before points before the loop.  We can't use copy_end, because
2192      there may be insns already inserted after it (which we don't want to
2193      copy) when not from preconditioning code.  */
2194
2195   if (! last_iteration)
2196     {
2197       for (insn = copy_notes_from; insn != loop_end; insn = NEXT_INSN (insn))
2198         {
2199           /* VTOP notes are valid only before the loop exit test.
2200              If placed anywhere else, loop may generate bad code.
2201              There is no need to test for NOTE_INSN_LOOP_CONT notes
2202              here, since COPY_NOTES_FROM will be at most one or two (for cc0)
2203              instructions before the last insn in the loop, and if the
2204              end test is that short, there will be a VTOP note between
2205              the CONT note and the test.  */
2206           if (GET_CODE (insn) == NOTE
2207               && NOTE_LINE_NUMBER (insn) != NOTE_INSN_DELETED
2208               && NOTE_LINE_NUMBER (insn) != NOTE_INSN_BASIC_BLOCK
2209               && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_VTOP)
2210             emit_note (NOTE_SOURCE_FILE (insn), NOTE_LINE_NUMBER (insn));
2211         }
2212     }
2213
2214   if (final_label && LABEL_NUSES (final_label) > 0)
2215     emit_label (final_label);
2216
2217   tem = gen_sequence ();
2218   end_sequence ();
2219   emit_insn_before (tem, insert_before);
2220 }
2221 \f
2222 /* Emit an insn, using the expand_binop to ensure that a valid insn is
2223    emitted.  This will correctly handle the case where the increment value
2224    won't fit in the immediate field of a PLUS insns.  */
2225
2226 void
2227 emit_unrolled_add (dest_reg, src_reg, increment)
2228      rtx dest_reg, src_reg, increment;
2229 {
2230   rtx result;
2231
2232   result = expand_binop (GET_MODE (dest_reg), add_optab, src_reg, increment,
2233                          dest_reg, 0, OPTAB_LIB_WIDEN);
2234
2235   if (dest_reg != result)
2236     emit_move_insn (dest_reg, result);
2237 }
2238 \f
2239 /* Searches the insns between INSN and LOOP_END.  Returns 1 if there
2240    is a backward branch in that range that branches to somewhere between
2241    LOOP_START and INSN.  Returns 0 otherwise.  */
2242
2243 /* ??? This is quadratic algorithm.  Could be rewritten to be linear.
2244    In practice, this is not a problem, because this function is seldom called,
2245    and uses a negligible amount of CPU time on average.  */
2246
2247 int
2248 back_branch_in_range_p (insn, loop_start, loop_end)
2249      rtx insn;
2250      rtx loop_start, loop_end;
2251 {
2252   rtx p, q, target_insn;
2253   rtx orig_loop_end = loop_end;
2254
2255   /* Stop before we get to the backward branch at the end of the loop.  */
2256   loop_end = prev_nonnote_insn (loop_end);
2257   if (GET_CODE (loop_end) == BARRIER)
2258     loop_end = PREV_INSN (loop_end);
2259
2260   /* Check in case insn has been deleted, search forward for first non
2261      deleted insn following it.  */
2262   while (INSN_DELETED_P (insn))
2263     insn = NEXT_INSN (insn);
2264
2265   /* Check for the case where insn is the last insn in the loop.  Deal
2266      with the case where INSN was a deleted loop test insn, in which case
2267      it will now be the NOTE_LOOP_END.  */
2268   if (insn == loop_end || insn == orig_loop_end)
2269     return 0;
2270
2271   for (p = NEXT_INSN (insn); p != loop_end; p = NEXT_INSN (p))
2272     {
2273       if (GET_CODE (p) == JUMP_INSN)
2274         {
2275           target_insn = JUMP_LABEL (p);
2276
2277           /* Search from loop_start to insn, to see if one of them is
2278              the target_insn.  We can't use INSN_LUID comparisons here,
2279              since insn may not have an LUID entry.  */
2280           for (q = loop_start; q != insn; q = NEXT_INSN (q))
2281             if (q == target_insn)
2282               return 1;
2283         }
2284     }
2285
2286   return 0;
2287 }
2288
2289 /* Try to generate the simplest rtx for the expression
2290    (PLUS (MULT mult1 mult2) add1).  This is used to calculate the initial
2291    value of giv's.  */
2292
2293 static rtx
2294 fold_rtx_mult_add (mult1, mult2, add1, mode)
2295      rtx mult1, mult2, add1;
2296      enum machine_mode mode;
2297 {
2298   rtx temp, mult_res;
2299   rtx result;
2300
2301   /* The modes must all be the same.  This should always be true.  For now,
2302      check to make sure.  */
2303   if ((GET_MODE (mult1) != mode && GET_MODE (mult1) != VOIDmode)
2304       || (GET_MODE (mult2) != mode && GET_MODE (mult2) != VOIDmode)
2305       || (GET_MODE (add1) != mode && GET_MODE (add1) != VOIDmode))
2306     abort ();
2307
2308   /* Ensure that if at least one of mult1/mult2 are constant, then mult2
2309      will be a constant.  */
2310   if (GET_CODE (mult1) == CONST_INT)
2311     {
2312       temp = mult2;
2313       mult2 = mult1;
2314       mult1 = temp;
2315     }
2316
2317   mult_res = simplify_binary_operation (MULT, mode, mult1, mult2);
2318   if (! mult_res)
2319     mult_res = gen_rtx_MULT (mode, mult1, mult2);
2320
2321   /* Again, put the constant second.  */
2322   if (GET_CODE (add1) == CONST_INT)
2323     {
2324       temp = add1;
2325       add1 = mult_res;
2326       mult_res = temp;
2327     }
2328
2329   result = simplify_binary_operation (PLUS, mode, add1, mult_res);
2330   if (! result)
2331     result = gen_rtx_PLUS (mode, add1, mult_res);
2332
2333   return result;
2334 }
2335
2336 /* Searches the list of induction struct's for the biv BL, to try to calculate
2337    the total increment value for one iteration of the loop as a constant.
2338
2339    Returns the increment value as an rtx, simplified as much as possible,
2340    if it can be calculated.  Otherwise, returns 0.  */
2341
2342 rtx
2343 biv_total_increment (bl, loop_start, loop_end)
2344      struct iv_class *bl;
2345      rtx loop_start, loop_end;
2346 {
2347   struct induction *v;
2348   rtx result;
2349
2350   /* For increment, must check every instruction that sets it.  Each
2351      instruction must be executed only once each time through the loop.
2352      To verify this, we check that the insn is always executed, and that
2353      there are no backward branches after the insn that branch to before it.
2354      Also, the insn must have a mult_val of one (to make sure it really is
2355      an increment).  */
2356
2357   result = const0_rtx;
2358   for (v = bl->biv; v; v = v->next_iv)
2359     {
2360       if (v->always_computable && v->mult_val == const1_rtx
2361           && ! v->maybe_multiple)
2362         result = fold_rtx_mult_add (result, const1_rtx, v->add_val, v->mode);
2363       else
2364         return 0;
2365     }
2366
2367   return result;
2368 }
2369
2370 /* Determine the initial value of the iteration variable, and the amount
2371    that it is incremented each loop.  Use the tables constructed by
2372    the strength reduction pass to calculate these values.
2373
2374    Initial_value and/or increment are set to zero if their values could not
2375    be calculated.  */
2376
2377 static void
2378 iteration_info (iteration_var, initial_value, increment, loop_start, loop_end)
2379      rtx iteration_var, *initial_value, *increment;
2380      rtx loop_start, loop_end;
2381 {
2382   struct iv_class *bl;
2383 #if 0
2384   struct induction *v;
2385 #endif
2386
2387   /* Clear the result values, in case no answer can be found.  */
2388   *initial_value = 0;
2389   *increment = 0;
2390
2391   /* The iteration variable can be either a giv or a biv.  Check to see
2392      which it is, and compute the variable's initial value, and increment
2393      value if possible.  */
2394
2395   /* If this is a new register, can't handle it since we don't have any
2396      reg_iv_type entry for it.  */
2397   if ((unsigned) REGNO (iteration_var) >= reg_iv_type->num_elements)
2398     {
2399       if (loop_dump_stream)
2400         fprintf (loop_dump_stream,
2401                  "Loop unrolling: No reg_iv_type entry for iteration var.\n");
2402       return;
2403     }
2404
2405   /* Reject iteration variables larger than the host wide int size, since they
2406      could result in a number of iterations greater than the range of our
2407      `unsigned HOST_WIDE_INT' variable loop_info->n_iterations.  */
2408   else if ((GET_MODE_BITSIZE (GET_MODE (iteration_var))
2409             > HOST_BITS_PER_WIDE_INT))
2410     {
2411       if (loop_dump_stream)
2412         fprintf (loop_dump_stream,
2413                  "Loop unrolling: Iteration var rejected because mode too large.\n");
2414       return;
2415     }
2416   else if (GET_MODE_CLASS (GET_MODE (iteration_var)) != MODE_INT)
2417     {
2418       if (loop_dump_stream)
2419         fprintf (loop_dump_stream,
2420                  "Loop unrolling: Iteration var not an integer.\n");
2421       return;
2422     }
2423   else if (REG_IV_TYPE (REGNO (iteration_var)) == BASIC_INDUCT)
2424     {
2425       /* When reg_iv_type / reg_iv_info is resized for biv increments
2426          that are turned into givs, reg_biv_class is not resized.
2427          So check here that we don't make an out-of-bounds access.  */
2428       if (REGNO (iteration_var) >= max_reg_before_loop)
2429         abort ();
2430
2431       /* Grab initial value, only useful if it is a constant.  */
2432       bl = reg_biv_class[REGNO (iteration_var)];
2433       *initial_value = bl->initial_value;
2434
2435       *increment = biv_total_increment (bl, loop_start, loop_end);
2436     }
2437   else if (REG_IV_TYPE (REGNO (iteration_var)) == GENERAL_INDUCT)
2438     {
2439       HOST_WIDE_INT offset = 0;
2440       struct induction *v = REG_IV_INFO (REGNO (iteration_var));
2441
2442       if (REGNO (v->src_reg) >= max_reg_before_loop)
2443         abort ();
2444
2445       bl = reg_biv_class[REGNO (v->src_reg)];
2446
2447       /* Increment value is mult_val times the increment value of the biv.  */
2448
2449       *increment = biv_total_increment (bl, loop_start, loop_end);
2450       if (*increment)
2451         {
2452           struct induction *biv_inc;
2453
2454           *increment
2455             = fold_rtx_mult_add (v->mult_val, *increment, const0_rtx, v->mode);
2456           /* The caller assumes that one full increment has occured at the
2457              first loop test.  But that's not true when the biv is incremented
2458              after the giv is set (which is the usual case), e.g.:
2459              i = 6; do {;} while (i++ < 9) .
2460              Therefore, we bias the initial value by subtracting the amount of
2461              the increment that occurs between the giv set and the giv test.  */
2462           for (biv_inc = bl->biv; biv_inc; biv_inc = biv_inc->next_iv)
2463             {
2464               if (loop_insn_first_p (v->insn, biv_inc->insn))
2465                 offset -= INTVAL (biv_inc->add_val);
2466             }
2467           offset *= INTVAL (v->mult_val);
2468         }
2469       if (loop_dump_stream)
2470         fprintf (loop_dump_stream,
2471                  "Loop unrolling: Giv iterator, initial value bias %ld.\n",
2472                  (long) offset);
2473       /* Initial value is mult_val times the biv's initial value plus
2474          add_val.  Only useful if it is a constant.  */
2475       *initial_value
2476         = fold_rtx_mult_add (v->mult_val,
2477                              plus_constant (bl->initial_value, offset),
2478                              v->add_val, v->mode);
2479     }
2480   else
2481     {
2482       if (loop_dump_stream)
2483         fprintf (loop_dump_stream,
2484                  "Loop unrolling: Not basic or general induction var.\n");
2485       return;
2486     }
2487 }
2488
2489
2490 /* For each biv and giv, determine whether it can be safely split into
2491    a different variable for each unrolled copy of the loop body.  If it
2492    is safe to split, then indicate that by saving some useful info
2493    in the splittable_regs array.
2494
2495    If the loop is being completely unrolled, then splittable_regs will hold
2496    the current value of the induction variable while the loop is unrolled.
2497    It must be set to the initial value of the induction variable here.
2498    Otherwise, splittable_regs will hold the difference between the current
2499    value of the induction variable and the value the induction variable had
2500    at the top of the loop.  It must be set to the value 0 here.
2501
2502    Returns the total number of instructions that set registers that are
2503    splittable.  */
2504
2505 /* ?? If the loop is only unrolled twice, then most of the restrictions to
2506    constant values are unnecessary, since we can easily calculate increment
2507    values in this case even if nothing is constant.  The increment value
2508    should not involve a multiply however.  */
2509
2510 /* ?? Even if the biv/giv increment values aren't constant, it may still
2511    be beneficial to split the variable if the loop is only unrolled a few
2512    times, since multiplies by small integers (1,2,3,4) are very cheap.  */
2513
2514 static int
2515 find_splittable_regs (unroll_type, loop_start, loop_end, end_insert_before,
2516                      unroll_number, n_iterations)
2517      enum unroll_types unroll_type;
2518      rtx loop_start, loop_end;
2519      rtx end_insert_before;
2520      int unroll_number;
2521      unsigned HOST_WIDE_INT n_iterations;
2522 {
2523   struct iv_class *bl;
2524   struct induction *v;
2525   rtx increment, tem;
2526   rtx biv_final_value;
2527   int biv_splittable;
2528   int result = 0;
2529
2530   for (bl = loop_iv_list; bl; bl = bl->next)
2531     {
2532       /* Biv_total_increment must return a constant value,
2533          otherwise we can not calculate the split values.  */
2534
2535       increment = biv_total_increment (bl, loop_start, loop_end);
2536       if (! increment || GET_CODE (increment) != CONST_INT)
2537         continue;
2538
2539       /* The loop must be unrolled completely, or else have a known number
2540          of iterations and only one exit, or else the biv must be dead
2541          outside the loop, or else the final value must be known.  Otherwise,
2542          it is unsafe to split the biv since it may not have the proper
2543          value on loop exit.  */
2544
2545       /* loop_number_exit_count is non-zero if the loop has an exit other than
2546          a fall through at the end.  */
2547
2548       biv_splittable = 1;
2549       biv_final_value = 0;
2550       if (unroll_type != UNROLL_COMPLETELY
2551           && (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]]
2552               || unroll_type == UNROLL_NAIVE)
2553           && (uid_luid[REGNO_LAST_UID (bl->regno)] >= INSN_LUID (loop_end)
2554               || ! bl->init_insn
2555               || INSN_UID (bl->init_insn) >= max_uid_for_loop
2556               || (uid_luid[REGNO_FIRST_UID (bl->regno)]
2557                   < INSN_LUID (bl->init_insn))
2558               || reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
2559           && ! (biv_final_value = final_biv_value (bl, loop_start, loop_end,
2560                                                    n_iterations)))
2561         biv_splittable = 0;
2562
2563       /* If any of the insns setting the BIV don't do so with a simple
2564          PLUS, we don't know how to split it.  */
2565       for (v = bl->biv; biv_splittable && v; v = v->next_iv)
2566         if ((tem = single_set (v->insn)) == 0
2567             || GET_CODE (SET_DEST (tem)) != REG
2568             || REGNO (SET_DEST (tem)) != bl->regno
2569             || GET_CODE (SET_SRC (tem)) != PLUS)
2570           biv_splittable = 0;
2571
2572       /* If final value is non-zero, then must emit an instruction which sets
2573          the value of the biv to the proper value.  This is done after
2574          handling all of the givs, since some of them may need to use the
2575          biv's value in their initialization code.  */
2576
2577       /* This biv is splittable.  If completely unrolling the loop, save
2578          the biv's initial value.  Otherwise, save the constant zero.  */
2579
2580       if (biv_splittable == 1)
2581         {
2582           if (unroll_type == UNROLL_COMPLETELY)
2583             {
2584               /* If the initial value of the biv is itself (i.e. it is too
2585                  complicated for strength_reduce to compute), or is a hard
2586                  register, or it isn't invariant, then we must create a new
2587                  pseudo reg to hold the initial value of the biv.  */
2588
2589               if (GET_CODE (bl->initial_value) == REG
2590                   && (REGNO (bl->initial_value) == bl->regno
2591                       || REGNO (bl->initial_value) < FIRST_PSEUDO_REGISTER
2592                       || ! invariant_p (bl->initial_value)))
2593                 {
2594                   rtx tem = gen_reg_rtx (bl->biv->mode);
2595
2596                   record_base_value (REGNO (tem), bl->biv->add_val, 0);
2597                   emit_insn_before (gen_move_insn (tem, bl->biv->src_reg),
2598                                     loop_start);
2599
2600                   if (loop_dump_stream)
2601                     fprintf (loop_dump_stream, "Biv %d initial value remapped to %d.\n",
2602                              bl->regno, REGNO (tem));
2603
2604                   splittable_regs[bl->regno] = tem;
2605                 }
2606               else
2607                 splittable_regs[bl->regno] = bl->initial_value;
2608             }
2609           else
2610             splittable_regs[bl->regno] = const0_rtx;
2611
2612           /* Save the number of instructions that modify the biv, so that
2613              we can treat the last one specially.  */
2614
2615           splittable_regs_updates[bl->regno] = bl->biv_count;
2616           result += bl->biv_count;
2617
2618           if (loop_dump_stream)
2619             fprintf (loop_dump_stream,
2620                      "Biv %d safe to split.\n", bl->regno);
2621         }
2622
2623       /* Check every giv that depends on this biv to see whether it is
2624          splittable also.  Even if the biv isn't splittable, givs which
2625          depend on it may be splittable if the biv is live outside the
2626          loop, and the givs aren't.  */
2627
2628       result += find_splittable_givs (bl, unroll_type, loop_start, loop_end,
2629                                      increment, unroll_number);
2630
2631       /* If final value is non-zero, then must emit an instruction which sets
2632          the value of the biv to the proper value.  This is done after
2633          handling all of the givs, since some of them may need to use the
2634          biv's value in their initialization code.  */
2635       if (biv_final_value)
2636         {
2637           /* If the loop has multiple exits, emit the insns before the
2638              loop to ensure that it will always be executed no matter
2639              how the loop exits.  Otherwise emit the insn after the loop,
2640              since this is slightly more efficient.  */
2641           if (! loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
2642             emit_insn_before (gen_move_insn (bl->biv->src_reg,
2643                                              biv_final_value),
2644                               end_insert_before);
2645           else
2646             {
2647               /* Create a new register to hold the value of the biv, and then
2648                  set the biv to its final value before the loop start.  The biv
2649                  is set to its final value before loop start to ensure that
2650                  this insn will always be executed, no matter how the loop
2651                  exits.  */
2652               rtx tem = gen_reg_rtx (bl->biv->mode);
2653               record_base_value (REGNO (tem), bl->biv->add_val, 0);
2654
2655               emit_insn_before (gen_move_insn (tem, bl->biv->src_reg),
2656                                 loop_start);
2657               emit_insn_before (gen_move_insn (bl->biv->src_reg,
2658                                                biv_final_value),
2659                                 loop_start);
2660
2661               if (loop_dump_stream)
2662                 fprintf (loop_dump_stream, "Biv %d mapped to %d for split.\n",
2663                          REGNO (bl->biv->src_reg), REGNO (tem));
2664
2665               /* Set up the mapping from the original biv register to the new
2666                  register.  */
2667               bl->biv->src_reg = tem;
2668             }
2669         }
2670     }
2671   return result;
2672 }
2673
2674 /* Return 1 if the first and last unrolled copy of the address giv V is valid
2675    for the instruction that is using it.  Do not make any changes to that
2676    instruction.  */
2677
2678 static int
2679 verify_addresses (v, giv_inc, unroll_number)
2680      struct induction *v;
2681      rtx giv_inc;
2682      int unroll_number;
2683 {
2684   int ret = 1;
2685   rtx orig_addr = *v->location;
2686   rtx last_addr = plus_constant (v->dest_reg,
2687                                  INTVAL (giv_inc) * (unroll_number - 1));
2688
2689   /* First check to see if either address would fail.   Handle the fact
2690      that we have may have a match_dup.  */
2691   if (! validate_replace_rtx (*v->location, v->dest_reg, v->insn)
2692       || ! validate_replace_rtx (*v->location, last_addr, v->insn))
2693     ret = 0;
2694
2695   /* Now put things back the way they were before.  This should always
2696    succeed.  */
2697   if (! validate_replace_rtx (*v->location, orig_addr, v->insn))
2698     abort ();
2699
2700   return ret;
2701 }
2702
2703 /* For every giv based on the biv BL, check to determine whether it is
2704    splittable.  This is a subroutine to find_splittable_regs ().
2705
2706    Return the number of instructions that set splittable registers.  */
2707
2708 static int
2709 find_splittable_givs (bl, unroll_type, loop_start, loop_end, increment,
2710                       unroll_number)
2711      struct iv_class *bl;
2712      enum unroll_types unroll_type;
2713      rtx loop_start, loop_end;
2714      rtx increment;
2715      int unroll_number;
2716 {
2717   struct induction *v, *v2;
2718   rtx final_value;
2719   rtx tem;
2720   int result = 0;
2721
2722   /* Scan the list of givs, and set the same_insn field when there are
2723      multiple identical givs in the same insn.  */
2724   for (v = bl->giv; v; v = v->next_iv)
2725     for (v2 = v->next_iv; v2; v2 = v2->next_iv)
2726       if (v->insn == v2->insn && rtx_equal_p (v->new_reg, v2->new_reg)
2727           && ! v2->same_insn)
2728         v2->same_insn = v;
2729
2730   for (v = bl->giv; v; v = v->next_iv)
2731     {
2732       rtx giv_inc, value;
2733
2734       /* Only split the giv if it has already been reduced, or if the loop is
2735          being completely unrolled.  */
2736       if (unroll_type != UNROLL_COMPLETELY && v->ignore)
2737         continue;
2738
2739       /* The giv can be split if the insn that sets the giv is executed once
2740          and only once on every iteration of the loop.  */
2741       /* An address giv can always be split.  v->insn is just a use not a set,
2742          and hence it does not matter whether it is always executed.  All that
2743          matters is that all the biv increments are always executed, and we
2744          won't reach here if they aren't.  */
2745       if (v->giv_type != DEST_ADDR
2746           && (! v->always_computable
2747               || back_branch_in_range_p (v->insn, loop_start, loop_end)))
2748         continue;
2749
2750       /* The giv increment value must be a constant.  */
2751       giv_inc = fold_rtx_mult_add (v->mult_val, increment, const0_rtx,
2752                                    v->mode);
2753       if (! giv_inc || GET_CODE (giv_inc) != CONST_INT)
2754         continue;
2755
2756       /* The loop must be unrolled completely, or else have a known number of
2757          iterations and only one exit, or else the giv must be dead outside
2758          the loop, or else the final value of the giv must be known.
2759          Otherwise, it is not safe to split the giv since it may not have the
2760          proper value on loop exit.  */
2761
2762       /* The used outside loop test will fail for DEST_ADDR givs.  They are
2763          never used outside the loop anyways, so it is always safe to split a
2764          DEST_ADDR giv.  */
2765
2766       final_value = 0;
2767       if (unroll_type != UNROLL_COMPLETELY
2768           && (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]]
2769               || unroll_type == UNROLL_NAIVE)
2770           && v->giv_type != DEST_ADDR
2771           /* The next part is true if the pseudo is used outside the loop.
2772              We assume that this is true for any pseudo created after loop
2773              starts, because we don't have a reg_n_info entry for them.  */
2774           && (REGNO (v->dest_reg) >= max_reg_before_loop
2775               || (REGNO_FIRST_UID (REGNO (v->dest_reg)) != INSN_UID (v->insn)
2776                   /* Check for the case where the pseudo is set by a shift/add
2777                      sequence, in which case the first insn setting the pseudo
2778                      is the first insn of the shift/add sequence.  */
2779                   && (! (tem = find_reg_note (v->insn, REG_RETVAL, NULL_RTX))
2780                       || (REGNO_FIRST_UID (REGNO (v->dest_reg))
2781                           != INSN_UID (XEXP (tem, 0)))))
2782               /* Line above always fails if INSN was moved by loop opt.  */
2783               || (uid_luid[REGNO_LAST_UID (REGNO (v->dest_reg))]
2784                   >= INSN_LUID (loop_end)))
2785           /* Givs made from biv increments are missed by the above test, so
2786              test explicitly for them.  */
2787           && (REGNO (v->dest_reg) < first_increment_giv
2788               || REGNO (v->dest_reg) > last_increment_giv)
2789           && ! (final_value = v->final_value))
2790         continue;
2791
2792 #if 0
2793       /* Currently, non-reduced/final-value givs are never split.  */
2794       /* Should emit insns after the loop if possible, as the biv final value
2795          code below does.  */
2796
2797       /* If the final value is non-zero, and the giv has not been reduced,
2798          then must emit an instruction to set the final value.  */
2799       if (final_value && !v->new_reg)
2800         {
2801           /* Create a new register to hold the value of the giv, and then set
2802              the giv to its final value before the loop start.  The giv is set
2803              to its final value before loop start to ensure that this insn
2804              will always be executed, no matter how we exit.  */
2805           tem = gen_reg_rtx (v->mode);
2806           emit_insn_before (gen_move_insn (tem, v->dest_reg), loop_start);
2807           emit_insn_before (gen_move_insn (v->dest_reg, final_value),
2808                             loop_start);
2809
2810           if (loop_dump_stream)
2811             fprintf (loop_dump_stream, "Giv %d mapped to %d for split.\n",
2812                      REGNO (v->dest_reg), REGNO (tem));
2813
2814           v->src_reg = tem;
2815         }
2816 #endif
2817
2818       /* This giv is splittable.  If completely unrolling the loop, save the
2819          giv's initial value.  Otherwise, save the constant zero for it.  */
2820
2821       if (unroll_type == UNROLL_COMPLETELY)
2822         {
2823           /* It is not safe to use bl->initial_value here, because it may not
2824              be invariant.  It is safe to use the initial value stored in
2825              the splittable_regs array if it is set.  In rare cases, it won't
2826              be set, so then we do exactly the same thing as
2827              find_splittable_regs does to get a safe value.  */
2828           rtx biv_initial_value;
2829
2830           if (splittable_regs[bl->regno])
2831             biv_initial_value = splittable_regs[bl->regno];
2832           else if (GET_CODE (bl->initial_value) != REG
2833                    || (REGNO (bl->initial_value) != bl->regno
2834                        && REGNO (bl->initial_value) >= FIRST_PSEUDO_REGISTER))
2835             biv_initial_value = bl->initial_value;
2836           else
2837             {
2838               rtx tem = gen_reg_rtx (bl->biv->mode);
2839
2840               record_base_value (REGNO (tem), bl->biv->add_val, 0);
2841               emit_insn_before (gen_move_insn (tem, bl->biv->src_reg),
2842                                 loop_start);
2843               biv_initial_value = tem;
2844             }
2845           value = fold_rtx_mult_add (v->mult_val, biv_initial_value,
2846                                      v->add_val, v->mode);
2847         }
2848       else
2849         value = const0_rtx;
2850
2851       if (v->new_reg)
2852         {
2853           /* If a giv was combined with another giv, then we can only split
2854              this giv if the giv it was combined with was reduced.  This
2855              is because the value of v->new_reg is meaningless in this
2856              case.  */
2857           if (v->same && ! v->same->new_reg)
2858             {
2859               if (loop_dump_stream)
2860                 fprintf (loop_dump_stream,
2861                          "giv combined with unreduced giv not split.\n");
2862               continue;
2863             }
2864           /* If the giv is an address destination, it could be something other
2865              than a simple register, these have to be treated differently.  */
2866           else if (v->giv_type == DEST_REG)
2867             {
2868               /* If value is not a constant, register, or register plus
2869                  constant, then compute its value into a register before
2870                  loop start.  This prevents invalid rtx sharing, and should
2871                  generate better code.  We can use bl->initial_value here
2872                  instead of splittable_regs[bl->regno] because this code
2873                  is going before the loop start.  */
2874               if (unroll_type == UNROLL_COMPLETELY
2875                   && GET_CODE (value) != CONST_INT
2876                   && GET_CODE (value) != REG
2877                   && (GET_CODE (value) != PLUS
2878                       || GET_CODE (XEXP (value, 0)) != REG
2879                       || GET_CODE (XEXP (value, 1)) != CONST_INT))
2880                 {
2881                   rtx tem = gen_reg_rtx (v->mode);
2882                   record_base_value (REGNO (tem), v->add_val, 0);
2883                   emit_iv_add_mult (bl->initial_value, v->mult_val,
2884                                     v->add_val, tem, loop_start);
2885                   value = tem;
2886                 }
2887
2888               splittable_regs[REGNO (v->new_reg)] = value;
2889               derived_regs[REGNO (v->new_reg)] = v->derived_from != 0;
2890             }
2891           else
2892             {
2893               /* Splitting address givs is useful since it will often allow us
2894                  to eliminate some increment insns for the base giv as
2895                  unnecessary.  */
2896
2897               /* If the addr giv is combined with a dest_reg giv, then all
2898                  references to that dest reg will be remapped, which is NOT
2899                  what we want for split addr regs. We always create a new
2900                  register for the split addr giv, just to be safe.  */
2901
2902               /* If we have multiple identical address givs within a
2903                  single instruction, then use a single pseudo reg for
2904                  both.  This is necessary in case one is a match_dup
2905                  of the other.  */
2906
2907               v->const_adjust = 0;
2908
2909               if (v->same_insn)
2910                 {
2911                   v->dest_reg = v->same_insn->dest_reg;
2912                   if (loop_dump_stream)
2913                     fprintf (loop_dump_stream,
2914                              "Sharing address givs in insn %d\n",
2915                              INSN_UID (v->insn));
2916                 }
2917               /* If multiple address GIVs have been combined with the
2918                  same dest_reg GIV, do not create a new register for
2919                  each.  */
2920               else if (unroll_type != UNROLL_COMPLETELY
2921                        && v->giv_type == DEST_ADDR
2922                        && v->same && v->same->giv_type == DEST_ADDR
2923                        && v->same->unrolled
2924                        /* combine_givs_p may return true for some cases
2925                           where the add and mult values are not equal.
2926                           To share a register here, the values must be
2927                           equal.  */
2928                        && rtx_equal_p (v->same->mult_val, v->mult_val)
2929                        && rtx_equal_p (v->same->add_val, v->add_val)
2930                        /* If the memory references have different modes,
2931                           then the address may not be valid and we must
2932                           not share registers.  */
2933                        && verify_addresses (v, giv_inc, unroll_number))
2934                 {
2935                   v->dest_reg = v->same->dest_reg;
2936                   v->shared = 1;
2937                 }
2938               else if (unroll_type != UNROLL_COMPLETELY)
2939                 {
2940                   /* If not completely unrolling the loop, then create a new
2941                      register to hold the split value of the DEST_ADDR giv.
2942                      Emit insn to initialize its value before loop start.  */
2943
2944                   rtx tem = gen_reg_rtx (v->mode);
2945                   struct induction *same = v->same;
2946                   rtx new_reg = v->new_reg;
2947                   record_base_value (REGNO (tem), v->add_val, 0);
2948
2949                   if (same && same->derived_from)
2950                     {
2951                       /* calculate_giv_inc doesn't work for derived givs.
2952                          copy_loop_body works around the problem for the
2953                          DEST_REG givs themselves, but it can't handle
2954                          DEST_ADDR givs that have been combined with
2955                          a derived DEST_REG giv.
2956                          So Handle V as if the giv from which V->SAME has
2957                          been derived has been combined with V.
2958                          recombine_givs only derives givs from givs that
2959                          are reduced the ordinary, so we need not worry
2960                          about same->derived_from being in turn derived.  */
2961
2962                       same = same->derived_from;
2963                       new_reg = express_from (same, v);
2964                       new_reg = replace_rtx (new_reg, same->dest_reg,
2965                                              same->new_reg);
2966                     }
2967
2968                   /* If the address giv has a constant in its new_reg value,
2969                      then this constant can be pulled out and put in value,
2970                      instead of being part of the initialization code.  */
2971
2972                   if (GET_CODE (new_reg) == PLUS
2973                       && GET_CODE (XEXP (new_reg, 1)) == CONST_INT)
2974                     {
2975                       v->dest_reg
2976                         = plus_constant (tem, INTVAL (XEXP (new_reg, 1)));
2977
2978                       /* Only succeed if this will give valid addresses.
2979                          Try to validate both the first and the last
2980                          address resulting from loop unrolling, if
2981                          one fails, then can't do const elim here.  */
2982                       if (verify_addresses (v, giv_inc, unroll_number))
2983                         {
2984                           /* Save the negative of the eliminated const, so
2985                              that we can calculate the dest_reg's increment
2986                              value later.  */
2987                           v->const_adjust = - INTVAL (XEXP (new_reg, 1));
2988
2989                           new_reg = XEXP (new_reg, 0);
2990                           if (loop_dump_stream)
2991                             fprintf (loop_dump_stream,
2992                                      "Eliminating constant from giv %d\n",
2993                                      REGNO (tem));
2994                         }
2995                       else
2996                         v->dest_reg = tem;
2997                     }
2998                   else
2999                     v->dest_reg = tem;
3000
3001                   /* If the address hasn't been checked for validity yet, do so
3002                      now, and fail completely if either the first or the last
3003                      unrolled copy of the address is not a valid address
3004                      for the instruction that uses it.  */
3005                   if (v->dest_reg == tem
3006                       && ! verify_addresses (v, giv_inc, unroll_number))
3007                     {
3008                       for (v2 = v->next_iv; v2; v2 = v2->next_iv)
3009                         if (v2->same_insn == v)
3010                           v2->same_insn = 0;
3011
3012                       if (loop_dump_stream)
3013                         fprintf (loop_dump_stream,
3014                                  "Invalid address for giv at insn %d\n",
3015                                  INSN_UID (v->insn));
3016                       continue;
3017                     }
3018
3019                   v->new_reg = new_reg;
3020                   v->same = same;
3021
3022                   /* We set this after the address check, to guarantee that
3023                      the register will be initialized.  */
3024                   v->unrolled = 1;
3025
3026                   /* To initialize the new register, just move the value of
3027                      new_reg into it.  This is not guaranteed to give a valid
3028                      instruction on machines with complex addressing modes.
3029                      If we can't recognize it, then delete it and emit insns
3030                      to calculate the value from scratch.  */
3031                   emit_insn_before (gen_rtx_SET (VOIDmode, tem,
3032                                                  copy_rtx (v->new_reg)),
3033                                     loop_start);
3034                   if (recog_memoized (PREV_INSN (loop_start)) < 0)
3035                     {
3036                       rtx sequence, ret;
3037
3038                       /* We can't use bl->initial_value to compute the initial
3039                          value, because the loop may have been preconditioned.
3040                          We must calculate it from NEW_REG.  Try using
3041                          force_operand instead of emit_iv_add_mult.  */
3042                       delete_insn (PREV_INSN (loop_start));
3043
3044                       start_sequence ();
3045                       ret = force_operand (v->new_reg, tem);
3046                       if (ret != tem)
3047                         emit_move_insn (tem, ret);
3048                       sequence = gen_sequence ();
3049                       end_sequence ();
3050                       emit_insn_before (sequence, loop_start);
3051
3052                       if (loop_dump_stream)
3053                         fprintf (loop_dump_stream,
3054                                  "Invalid init insn, rewritten.\n");
3055                     }
3056                 }
3057               else
3058                 {
3059                   v->dest_reg = value;
3060
3061                   /* Check the resulting address for validity, and fail
3062                      if the resulting address would be invalid.  */
3063                   if (! verify_addresses (v, giv_inc, unroll_number))
3064                     {
3065                       for (v2 = v->next_iv; v2; v2 = v2->next_iv)
3066                         if (v2->same_insn == v)
3067                           v2->same_insn = 0;
3068
3069                       if (loop_dump_stream)
3070                         fprintf (loop_dump_stream,
3071                                  "Invalid address for giv at insn %d\n",
3072                                  INSN_UID (v->insn));
3073                       continue;
3074                     }
3075                   if (v->same && v->same->derived_from)
3076                     {
3077                       /* Handle V as if the giv from which V->SAME has
3078                          been derived has been combined with V.  */
3079
3080                       v->same = v->same->derived_from;
3081                       v->new_reg = express_from (v->same, v);
3082                       v->new_reg = replace_rtx (v->new_reg, v->same->dest_reg,
3083                                                 v->same->new_reg);
3084                     }
3085
3086                 }
3087
3088               /* Store the value of dest_reg into the insn.  This sharing
3089                  will not be a problem as this insn will always be copied
3090                  later.  */
3091
3092               *v->location = v->dest_reg;
3093
3094               /* If this address giv is combined with a dest reg giv, then
3095                  save the base giv's induction pointer so that we will be
3096                  able to handle this address giv properly.  The base giv
3097                  itself does not have to be splittable.  */
3098
3099               if (v->same && v->same->giv_type == DEST_REG)
3100                 addr_combined_regs[REGNO (v->same->new_reg)] = v->same;
3101
3102               if (GET_CODE (v->new_reg) == REG)
3103                 {
3104                   /* This giv maybe hasn't been combined with any others.
3105                      Make sure that it's giv is marked as splittable here.  */
3106
3107                   splittable_regs[REGNO (v->new_reg)] = value;
3108                   derived_regs[REGNO (v->new_reg)] = v->derived_from != 0;
3109
3110                   /* Make it appear to depend upon itself, so that the
3111                      giv will be properly split in the main loop above.  */
3112                   if (! v->same)
3113                     {
3114                       v->same = v;
3115                       addr_combined_regs[REGNO (v->new_reg)] = v;
3116                     }
3117                 }
3118
3119               if (loop_dump_stream)
3120                 fprintf (loop_dump_stream, "DEST_ADDR giv being split.\n");
3121             }
3122         }
3123       else
3124         {
3125 #if 0
3126           /* Currently, unreduced giv's can't be split.  This is not too much
3127              of a problem since unreduced giv's are not live across loop
3128              iterations anyways.  When unrolling a loop completely though,
3129              it makes sense to reduce&split givs when possible, as this will
3130              result in simpler instructions, and will not require that a reg
3131              be live across loop iterations.  */
3132
3133           splittable_regs[REGNO (v->dest_reg)] = value;
3134           fprintf (stderr, "Giv %d at insn %d not reduced\n",
3135                    REGNO (v->dest_reg), INSN_UID (v->insn));
3136 #else
3137           continue;
3138 #endif
3139         }
3140
3141       /* Unreduced givs are only updated once by definition.  Reduced givs
3142          are updated as many times as their biv is.  Mark it so if this is
3143          a splittable register.  Don't need to do anything for address givs
3144          where this may not be a register.  */
3145
3146       if (GET_CODE (v->new_reg) == REG)
3147         {
3148           int count = 1;
3149           if (! v->ignore)
3150             count = reg_biv_class[REGNO (v->src_reg)]->biv_count;
3151
3152           if (count > 1 && v->derived_from)
3153              /* In this case, there is one set where the giv insn was and one
3154                 set each after each biv increment.  (Most are likely dead.)  */
3155             count++;
3156
3157           splittable_regs_updates[REGNO (v->new_reg)] = count;
3158         }
3159
3160       result++;
3161
3162       if (loop_dump_stream)
3163         {
3164           int regnum;
3165
3166           if (GET_CODE (v->dest_reg) == CONST_INT)
3167             regnum = -1;
3168           else if (GET_CODE (v->dest_reg) != REG)
3169             regnum = REGNO (XEXP (v->dest_reg, 0));
3170           else
3171             regnum = REGNO (v->dest_reg);
3172           fprintf (loop_dump_stream, "Giv %d at insn %d safe to split.\n",
3173                    regnum, INSN_UID (v->insn));
3174         }
3175     }
3176
3177   return result;
3178 }
3179 \f
3180 /* Try to prove that the register is dead after the loop exits.  Trace every
3181    loop exit looking for an insn that will always be executed, which sets
3182    the register to some value, and appears before the first use of the register
3183    is found.  If successful, then return 1, otherwise return 0.  */
3184
3185 /* ?? Could be made more intelligent in the handling of jumps, so that
3186    it can search past if statements and other similar structures.  */
3187
3188 static int
3189 reg_dead_after_loop (reg, loop_start, loop_end)
3190      rtx reg, loop_start, loop_end;
3191 {
3192   rtx insn, label;
3193   enum rtx_code code;
3194   int jump_count = 0;
3195   int label_count = 0;
3196   int this_loop_num = uid_loop_num[INSN_UID (loop_start)];
3197
3198   /* In addition to checking all exits of this loop, we must also check
3199      all exits of inner nested loops that would exit this loop.  We don't
3200      have any way to identify those, so we just give up if there are any
3201      such inner loop exits.  */
3202
3203   for (label = loop_number_exit_labels[this_loop_num]; label;
3204        label = LABEL_NEXTREF (label))
3205     label_count++;
3206
3207   if (label_count != loop_number_exit_count[this_loop_num])
3208     return 0;
3209
3210   /* HACK: Must also search the loop fall through exit, create a label_ref
3211      here which points to the loop_end, and append the loop_number_exit_labels
3212      list to it.  */
3213   label = gen_rtx_LABEL_REF (VOIDmode, loop_end);
3214   LABEL_NEXTREF (label) = loop_number_exit_labels[this_loop_num];
3215
3216   for ( ; label; label = LABEL_NEXTREF (label))
3217     {
3218       /* Succeed if find an insn which sets the biv or if reach end of
3219          function.  Fail if find an insn that uses the biv, or if come to
3220          a conditional jump.  */
3221
3222       insn = NEXT_INSN (XEXP (label, 0));
3223       while (insn)
3224         {
3225           code = GET_CODE (insn);
3226           if (GET_RTX_CLASS (code) == 'i')
3227             {
3228               rtx set;
3229
3230               if (reg_referenced_p (reg, PATTERN (insn)))
3231                 return 0;
3232
3233               set = single_set (insn);
3234               if (set && rtx_equal_p (SET_DEST (set), reg))
3235                 break;
3236             }
3237
3238           if (code == JUMP_INSN)
3239             {
3240               if (GET_CODE (PATTERN (insn)) == RETURN)
3241                 break;
3242               else if (! simplejump_p (insn)
3243                        /* Prevent infinite loop following infinite loops.  */
3244                        || jump_count++ > 20)
3245                 return 0;
3246               else
3247                 insn = JUMP_LABEL (insn);
3248             }
3249
3250           insn = NEXT_INSN (insn);
3251         }
3252     }
3253
3254   /* Success, the register is dead on all loop exits.  */
3255   return 1;
3256 }
3257
3258 /* Try to calculate the final value of the biv, the value it will have at
3259    the end of the loop.  If we can do it, return that value.  */
3260
3261 rtx
3262 final_biv_value (bl, loop_start, loop_end, n_iterations)
3263      struct iv_class *bl;
3264      rtx loop_start, loop_end;
3265      unsigned HOST_WIDE_INT n_iterations;
3266 {
3267   rtx increment, tem;
3268
3269   /* ??? This only works for MODE_INT biv's.  Reject all others for now.  */
3270
3271   if (GET_MODE_CLASS (bl->biv->mode) != MODE_INT)
3272     return 0;
3273
3274   /* The final value for reversed bivs must be calculated differently than
3275       for ordinary bivs.  In this case, there is already an insn after the
3276      loop which sets this biv's final value (if necessary), and there are
3277      no other loop exits, so we can return any value.  */
3278   if (bl->reversed)
3279     {
3280       if (loop_dump_stream)
3281         fprintf (loop_dump_stream,
3282                  "Final biv value for %d, reversed biv.\n", bl->regno);
3283
3284       return const0_rtx;
3285     }
3286
3287   /* Try to calculate the final value as initial value + (number of iterations
3288      * increment).  For this to work, increment must be invariant, the only
3289      exit from the loop must be the fall through at the bottom (otherwise
3290      it may not have its final value when the loop exits), and the initial
3291      value of the biv must be invariant.  */
3292
3293   if (n_iterations != 0
3294       && ! loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]]
3295       && invariant_p (bl->initial_value))
3296     {
3297       increment = biv_total_increment (bl, loop_start, loop_end);
3298
3299       if (increment && invariant_p (increment))
3300         {
3301           /* Can calculate the loop exit value, emit insns after loop
3302              end to calculate this value into a temporary register in
3303              case it is needed later.  */
3304
3305           tem = gen_reg_rtx (bl->biv->mode);
3306           record_base_value (REGNO (tem), bl->biv->add_val, 0);
3307           /* Make sure loop_end is not the last insn.  */
3308           if (NEXT_INSN (loop_end) == 0)
3309             emit_note_after (NOTE_INSN_DELETED, loop_end);
3310           emit_iv_add_mult (increment, GEN_INT (n_iterations),
3311                             bl->initial_value, tem, NEXT_INSN (loop_end));
3312
3313           if (loop_dump_stream)
3314             fprintf (loop_dump_stream,
3315                      "Final biv value for %d, calculated.\n", bl->regno);
3316
3317           return tem;
3318         }
3319     }
3320
3321   /* Check to see if the biv is dead at all loop exits.  */
3322   if (reg_dead_after_loop (bl->biv->src_reg, loop_start, loop_end))
3323     {
3324       if (loop_dump_stream)
3325         fprintf (loop_dump_stream,
3326                  "Final biv value for %d, biv dead after loop exit.\n",
3327                  bl->regno);
3328
3329       return const0_rtx;
3330     }
3331
3332   return 0;
3333 }
3334
3335 /* Try to calculate the final value of the giv, the value it will have at
3336    the end of the loop.  If we can do it, return that value.  */
3337
3338 rtx
3339 final_giv_value (v, loop_start, loop_end, n_iterations)
3340      struct induction *v;
3341      rtx loop_start, loop_end;
3342      unsigned HOST_WIDE_INT n_iterations;
3343 {
3344   struct iv_class *bl;
3345   rtx insn;
3346   rtx increment, tem;
3347   rtx insert_before, seq;
3348
3349   bl = reg_biv_class[REGNO (v->src_reg)];
3350
3351   /* The final value for givs which depend on reversed bivs must be calculated
3352      differently than for ordinary givs.  In this case, there is already an
3353      insn after the loop which sets this giv's final value (if necessary),
3354      and there are no other loop exits, so we can return any value.  */
3355   if (bl->reversed)
3356     {
3357       if (loop_dump_stream)
3358         fprintf (loop_dump_stream,
3359                  "Final giv value for %d, depends on reversed biv\n",
3360                  REGNO (v->dest_reg));
3361       return const0_rtx;
3362     }
3363
3364   /* Try to calculate the final value as a function of the biv it depends
3365      upon.  The only exit from the loop must be the fall through at the bottom
3366      (otherwise it may not have its final value when the loop exits).  */
3367
3368   /* ??? Can calculate the final giv value by subtracting off the
3369      extra biv increments times the giv's mult_val.  The loop must have
3370      only one exit for this to work, but the loop iterations does not need
3371      to be known.  */
3372
3373   if (n_iterations != 0
3374       && ! loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
3375     {
3376       /* ?? It is tempting to use the biv's value here since these insns will
3377          be put after the loop, and hence the biv will have its final value
3378          then.  However, this fails if the biv is subsequently eliminated.
3379          Perhaps determine whether biv's are eliminable before trying to
3380          determine whether giv's are replaceable so that we can use the
3381          biv value here if it is not eliminable.  */
3382
3383       /* We are emitting code after the end of the loop, so we must make
3384          sure that bl->initial_value is still valid then.  It will still
3385          be valid if it is invariant.  */
3386
3387       increment = biv_total_increment (bl, loop_start, loop_end);
3388
3389       if (increment && invariant_p (increment)
3390           && invariant_p (bl->initial_value))
3391         {
3392           /* Can calculate the loop exit value of its biv as
3393              (n_iterations * increment) + initial_value */
3394
3395           /* The loop exit value of the giv is then
3396              (final_biv_value - extra increments) * mult_val + add_val.
3397              The extra increments are any increments to the biv which
3398              occur in the loop after the giv's value is calculated.
3399              We must search from the insn that sets the giv to the end
3400              of the loop to calculate this value.  */
3401
3402           insert_before = NEXT_INSN (loop_end);
3403
3404           /* Put the final biv value in tem.  */
3405           tem = gen_reg_rtx (bl->biv->mode);
3406           record_base_value (REGNO (tem), bl->biv->add_val, 0);
3407           emit_iv_add_mult (increment, GEN_INT (n_iterations),
3408                             bl->initial_value, tem, insert_before);
3409
3410           /* Subtract off extra increments as we find them.  */
3411           for (insn = NEXT_INSN (v->insn); insn != loop_end;
3412                insn = NEXT_INSN (insn))
3413             {
3414               struct induction *biv;
3415
3416               for (biv = bl->biv; biv; biv = biv->next_iv)
3417                 if (biv->insn == insn)
3418                   {
3419                     start_sequence ();
3420                     tem = expand_binop (GET_MODE (tem), sub_optab, tem,
3421                                         biv->add_val, NULL_RTX, 0,
3422                                         OPTAB_LIB_WIDEN);
3423                     seq = gen_sequence ();
3424                     end_sequence ();
3425                     emit_insn_before (seq, insert_before);
3426                   }
3427             }
3428
3429           /* Now calculate the giv's final value.  */
3430           emit_iv_add_mult (tem, v->mult_val, v->add_val, tem,
3431                             insert_before);
3432
3433           if (loop_dump_stream)
3434             fprintf (loop_dump_stream,
3435                      "Final giv value for %d, calc from biv's value.\n",
3436                      REGNO (v->dest_reg));
3437
3438           return tem;
3439         }
3440     }
3441
3442   /* Replaceable giv's should never reach here.  */
3443   if (v->replaceable)
3444     abort ();
3445
3446   /* Check to see if the biv is dead at all loop exits.  */
3447   if (reg_dead_after_loop (v->dest_reg, loop_start, loop_end))
3448     {
3449       if (loop_dump_stream)
3450         fprintf (loop_dump_stream,
3451                  "Final giv value for %d, giv dead after loop exit.\n",
3452                  REGNO (v->dest_reg));
3453
3454       return const0_rtx;
3455     }
3456
3457   return 0;
3458 }
3459
3460
3461 /* Look back before LOOP_START for then insn that sets REG and return
3462    the equivalent constant if there is a REG_EQUAL note otherwise just
3463    the SET_SRC of REG.  */
3464
3465 static rtx
3466 loop_find_equiv_value (loop_start, reg)
3467      rtx loop_start;
3468      rtx reg;
3469 {
3470   rtx insn, set;
3471   rtx ret;
3472
3473   ret = reg;
3474   for (insn = PREV_INSN (loop_start); insn ; insn = PREV_INSN (insn))
3475     {
3476       if (GET_CODE (insn) == CODE_LABEL)
3477         break;
3478
3479       else if (GET_RTX_CLASS (GET_CODE (insn)) == 'i'
3480                && reg_set_p (reg, insn))
3481         {
3482           /* We found the last insn before the loop that sets the register.
3483              If it sets the entire register, and has a REG_EQUAL note,
3484              then use the value of the REG_EQUAL note.  */
3485           if ((set = single_set (insn))
3486                   && (SET_DEST (set) == reg))
3487             {
3488               rtx note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
3489
3490               /* Only use the REG_EQUAL note if it is a constant.
3491                  Other things, divide in particular, will cause
3492                  problems later if we use them.  */
3493               if (note && GET_CODE (XEXP (note, 0)) != EXPR_LIST
3494                   && CONSTANT_P (XEXP (note, 0)))
3495                 ret = XEXP (note, 0);
3496               else
3497                 ret = SET_SRC (set);
3498             }
3499           break;
3500         }
3501     }
3502   return ret;
3503 }
3504
3505 /* Return a simplified rtx for the expression OP - REG.
3506
3507    REG must appear in OP, and OP must be a register or the sum of a register
3508    and a second term.
3509
3510    Thus, the return value must be const0_rtx or the second term.
3511
3512    The caller is responsible for verifying that REG appears in OP and OP has
3513    the proper form.  */
3514
3515 static rtx
3516 subtract_reg_term (op, reg)
3517      rtx op, reg;
3518 {
3519   if (op == reg)
3520     return const0_rtx;
3521   if (GET_CODE (op) == PLUS)
3522     {
3523       if (XEXP (op, 0) == reg)
3524         return XEXP (op, 1);
3525       else if (XEXP (op, 1) == reg)
3526         return XEXP (op, 0);
3527     }
3528   /* OP does not contain REG as a term.  */
3529   abort ();
3530 }
3531
3532
3533 /* Find and return register term common to both expressions OP0 and
3534    OP1 or NULL_RTX if no such term exists.  Each expression must be a
3535    REG or a PLUS of a REG.  */
3536
3537 static rtx
3538 find_common_reg_term (op0, op1)
3539      rtx op0, op1;
3540 {
3541   if ((GET_CODE (op0) == REG || GET_CODE (op0) == PLUS)
3542       && (GET_CODE (op1) == REG || GET_CODE (op1) == PLUS))
3543     {
3544       rtx op00;
3545       rtx op01;
3546       rtx op10;
3547       rtx op11;
3548
3549       if (GET_CODE (op0) == PLUS)
3550         op01 = XEXP (op0, 1), op00 = XEXP (op0, 0);
3551       else
3552         op01 = const0_rtx, op00 = op0;
3553
3554       if (GET_CODE (op1) == PLUS)
3555         op11 = XEXP (op1, 1), op10 = XEXP (op1, 0);
3556       else
3557         op11 = const0_rtx, op10 = op1;
3558
3559       /* Find and return common register term if present.  */
3560       if (REG_P (op00) && (op00 == op10 || op00 == op11))
3561         return op00;
3562       else if (REG_P (op01) && (op01 == op10 || op01 == op11))
3563         return op01;
3564     }
3565
3566   /* No common register term found.  */
3567   return NULL_RTX;
3568 }
3569
3570 /* Calculate the number of loop iterations.  Returns the exact number of loop
3571    iterations if it can be calculated, otherwise returns zero.  */
3572
3573 unsigned HOST_WIDE_INT
3574 loop_iterations (loop_start, loop_end, loop_info)
3575      rtx loop_start, loop_end;
3576      struct loop_info *loop_info;
3577 {
3578   rtx comparison, comparison_value;
3579   rtx iteration_var, initial_value, increment, final_value;
3580   enum rtx_code comparison_code;
3581   HOST_WIDE_INT abs_inc;
3582   unsigned HOST_WIDE_INT abs_diff;
3583   int off_by_one;
3584   int increment_dir;
3585   int unsigned_p, compare_dir, final_larger;
3586   rtx last_loop_insn;
3587   rtx reg_term;
3588
3589   loop_info->n_iterations = 0;
3590   loop_info->initial_value = 0;
3591   loop_info->initial_equiv_value = 0;
3592   loop_info->comparison_value = 0;
3593   loop_info->final_value = 0;
3594   loop_info->final_equiv_value = 0;
3595   loop_info->increment = 0;
3596   loop_info->iteration_var = 0;
3597   loop_info->unroll_number = 1;
3598
3599   /* We used to use prev_nonnote_insn here, but that fails because it might
3600      accidentally get the branch for a contained loop if the branch for this
3601      loop was deleted.  We can only trust branches immediately before the
3602      loop_end.  */
3603   last_loop_insn = PREV_INSN (loop_end);
3604
3605   /* ??? We should probably try harder to find the jump insn
3606      at the end of the loop.  The following code assumes that
3607      the last loop insn is a jump to the top of the loop.  */
3608   if (GET_CODE (last_loop_insn) != JUMP_INSN)
3609     {
3610       if (loop_dump_stream)
3611         fprintf (loop_dump_stream,
3612                  "Loop iterations: No final conditional branch found.\n");
3613       return 0;
3614     }
3615
3616   /* If there is a more than a single jump to the top of the loop
3617      we cannot (easily) determine the iteration count.  */
3618   if (LABEL_NUSES (JUMP_LABEL (last_loop_insn)) > 1)
3619     {
3620       if (loop_dump_stream)
3621         fprintf (loop_dump_stream,
3622                  "Loop iterations: Loop has multiple back edges.\n");
3623       return 0;
3624     }
3625
3626   /* Find the iteration variable.  If the last insn is a conditional
3627      branch, and the insn before tests a register value, make that the
3628      iteration variable.  */
3629
3630   comparison = get_condition_for_loop (last_loop_insn);
3631   if (comparison == 0)
3632     {
3633       if (loop_dump_stream)
3634         fprintf (loop_dump_stream,
3635                  "Loop iterations: No final comparison found.\n");
3636       return 0;
3637     }
3638
3639   /* ??? Get_condition may switch position of induction variable and
3640      invariant register when it canonicalizes the comparison.  */
3641
3642   comparison_code = GET_CODE (comparison);
3643   iteration_var = XEXP (comparison, 0);
3644   comparison_value = XEXP (comparison, 1);
3645
3646   if (GET_CODE (iteration_var) != REG)
3647     {
3648       if (loop_dump_stream)
3649         fprintf (loop_dump_stream,
3650                  "Loop iterations: Comparison not against register.\n");
3651       return 0;
3652     }
3653
3654   /* The only new registers that care created before loop iterations are
3655      givs made from biv increments, so this should never occur.  */
3656
3657   if ((unsigned) REGNO (iteration_var) >= reg_iv_type->num_elements)
3658     abort ();
3659
3660   iteration_info (iteration_var, &initial_value, &increment,
3661                   loop_start, loop_end);
3662   if (initial_value == 0)
3663     /* iteration_info already printed a message.  */
3664     return 0;
3665
3666   unsigned_p = 0;
3667   off_by_one = 0;
3668   switch (comparison_code)
3669     {
3670     case LEU:
3671       unsigned_p = 1;
3672     case LE:
3673       compare_dir = 1;
3674       off_by_one = 1;
3675       break;
3676     case GEU:
3677       unsigned_p = 1;
3678     case GE:
3679       compare_dir = -1;
3680       off_by_one = -1;
3681       break;
3682     case EQ:
3683       /* Cannot determine loop iterations with this case.  */
3684       compare_dir = 0;
3685       break;
3686     case LTU:
3687       unsigned_p = 1;
3688     case LT:
3689       compare_dir = 1;
3690       break;
3691     case GTU:
3692       unsigned_p = 1;
3693     case GT:
3694       compare_dir = -1;
3695     case NE:
3696       compare_dir = 0;
3697       break;
3698     default:
3699       abort ();
3700     }
3701
3702   /* If the comparison value is an invariant register, then try to find
3703      its value from the insns before the start of the loop.  */
3704
3705   final_value = comparison_value;
3706   if (GET_CODE (comparison_value) == REG && invariant_p (comparison_value))
3707     {
3708       final_value = loop_find_equiv_value (loop_start, comparison_value);
3709       /* If we don't get an invariant final value, we are better
3710          off with the original register.  */
3711       if (!invariant_p (final_value))
3712         final_value = comparison_value;
3713     }
3714
3715   /* Calculate the approximate final value of the induction variable
3716      (on the last successful iteration).  The exact final value
3717      depends on the branch operator, and increment sign.  It will be
3718      wrong if the iteration variable is not incremented by one each
3719      time through the loop and (comparison_value + off_by_one -
3720      initial_value) % increment != 0.
3721      ??? Note that the final_value may overflow and thus final_larger
3722      will be bogus.  A potentially infinite loop will be classified
3723      as immediate, e.g. for (i = 0x7ffffff0; i <= 0x7fffffff; i++)  */
3724   if (off_by_one)
3725     final_value = plus_constant (final_value, off_by_one);
3726
3727   /* Save the calculated values describing this loop's bounds, in case
3728      precondition_loop_p will need them later.  These values can not be
3729      recalculated inside precondition_loop_p because strength reduction
3730      optimizations may obscure the loop's structure.
3731
3732      These values are only required by precondition_loop_p and insert_bct
3733      whenever the number of iterations cannot be computed at compile time.
3734      Only the difference between final_value and initial_value is
3735      important.  Note that final_value is only approximate.  */
3736   loop_info->initial_value = initial_value;
3737   loop_info->comparison_value = comparison_value;
3738   loop_info->final_value = plus_constant (comparison_value, off_by_one);
3739   loop_info->increment = increment;
3740   loop_info->iteration_var = iteration_var;
3741   loop_info->comparison_code = comparison_code;
3742
3743   /* Try to determine the iteration count for loops such
3744      as (for i = init; i < init + const; i++).  When running the
3745      loop optimization twice, the first pass often converts simple
3746      loops into this form.  */
3747
3748   if (REG_P (initial_value))
3749     {
3750       rtx reg1;
3751       rtx reg2;
3752       rtx const2;
3753
3754       reg1 = initial_value;
3755       if (GET_CODE (final_value) == PLUS)
3756         reg2 = XEXP (final_value, 0), const2 = XEXP (final_value, 1);
3757       else
3758         reg2 = final_value, const2 = const0_rtx;
3759
3760       /* Check for initial_value = reg1, final_value = reg2 + const2,
3761          where reg1 != reg2.  */
3762       if (REG_P (reg2) && reg2 != reg1)
3763         {
3764           rtx temp;
3765
3766           /* Find what reg1 is equivalent to.  Hopefully it will
3767              either be reg2 or reg2 plus a constant.  */
3768           temp = loop_find_equiv_value (loop_start, reg1);
3769           if (find_common_reg_term (temp, reg2))
3770             initial_value = temp;
3771           else
3772             {
3773               /* Find what reg2 is equivalent to.  Hopefully it will
3774                  either be reg1 or reg1 plus a constant.  Let's ignore
3775                  the latter case for now since it is not so common.  */
3776               temp = loop_find_equiv_value (loop_start, reg2);
3777               if (temp == loop_info->iteration_var)
3778                 temp = initial_value;
3779               if (temp == reg1)
3780                 final_value = (const2 == const0_rtx)
3781                   ? reg1 : gen_rtx_PLUS (GET_MODE (reg1), reg1, const2);
3782             }
3783         }
3784       else if (loop_info->vtop && GET_CODE (reg2) == CONST_INT)
3785         {
3786           rtx temp;
3787
3788           /*  When running the loop optimizer twice, check_dbra_loop
3789               further obfuscates reversible loops of the form:
3790               for (i = init; i < init + const; i++).  We often end up with
3791               final_value = 0, initial_value = temp, temp = temp2 - init,
3792               where temp2 = init + const.  If the loop has a vtop we
3793               can replace initial_value with const.  */
3794
3795           temp = loop_find_equiv_value (loop_start, reg1);
3796           if (GET_CODE (temp) == MINUS && REG_P (XEXP (temp, 0)))
3797             {
3798               rtx temp2 = loop_find_equiv_value (loop_start, XEXP (temp, 0));
3799               if (GET_CODE (temp2) == PLUS
3800                   && XEXP (temp2, 0) == XEXP (temp, 1))
3801                 initial_value = XEXP (temp2, 1);
3802             }
3803         }
3804     }
3805
3806   /* If have initial_value = reg + const1 and final_value = reg +
3807      const2, then replace initial_value with const1 and final_value
3808      with const2.  This should be safe since we are protected by the
3809      initial comparison before entering the loop if we have a vtop.
3810      For example, a + b < a + c is not equivalent to b < c for all a
3811      when using modulo arithmetic.
3812
3813      ??? Without a vtop we could still perform the optimization if we check
3814      the initial and final values carefully.  */
3815   if (loop_info->vtop
3816       && (reg_term = find_common_reg_term (initial_value, final_value)))
3817     {
3818       initial_value = subtract_reg_term (initial_value, reg_term);
3819       final_value = subtract_reg_term (final_value, reg_term);
3820     }
3821
3822   loop_info->initial_equiv_value = initial_value;
3823   loop_info->final_equiv_value = final_value;
3824
3825   /* For EQ comparison loops, we don't have a valid final value.
3826      Check this now so that we won't leave an invalid value if we
3827      return early for any other reason.  */
3828   if (comparison_code == EQ)
3829       loop_info->final_equiv_value = loop_info->final_value = 0;
3830
3831   if (increment == 0)
3832     {
3833       if (loop_dump_stream)
3834         fprintf (loop_dump_stream,
3835                  "Loop iterations: Increment value can't be calculated.\n");
3836       return 0;
3837     }
3838
3839   if (GET_CODE (increment) != CONST_INT)
3840     {
3841       /* If we have a REG, check to see if REG holds a constant value.  */
3842       /* ??? Other RTL, such as (neg (reg)) is possible here, but it isn't
3843          clear if it is worthwhile to try to handle such RTL.  */
3844       if (GET_CODE (increment) == REG || GET_CODE (increment) == SUBREG)
3845         increment = loop_find_equiv_value (loop_start, increment);
3846
3847       if (GET_CODE (increment) != CONST_INT)
3848         {
3849           if (loop_dump_stream)
3850             {
3851               fprintf (loop_dump_stream,
3852                        "Loop iterations: Increment value not constant ");
3853               print_rtl (loop_dump_stream, increment);
3854               fprintf (loop_dump_stream, ".\n");
3855             }
3856           return 0;
3857         }
3858       loop_info->increment = increment;
3859     }
3860
3861   if (GET_CODE (initial_value) != CONST_INT)
3862     {
3863       if (loop_dump_stream)
3864         {
3865           fprintf (loop_dump_stream,
3866                    "Loop iterations: Initial value not constant ");
3867           print_rtl (loop_dump_stream, initial_value);
3868           fprintf (loop_dump_stream, ".\n");
3869         }
3870       return 0;
3871     }
3872   else if (comparison_code == EQ)
3873     {
3874       if (loop_dump_stream)
3875         fprintf (loop_dump_stream,
3876                  "Loop iterations: EQ comparison loop.\n");
3877       return 0;
3878     }
3879   else if (GET_CODE (final_value) != CONST_INT)
3880     {
3881       if (loop_dump_stream)
3882         {
3883           fprintf (loop_dump_stream,
3884                    "Loop iterations: Final value not constant ");
3885           print_rtl (loop_dump_stream, final_value);
3886           fprintf (loop_dump_stream, ".\n");
3887         }
3888       return 0;
3889     }
3890
3891   /* Final_larger is 1 if final larger, 0 if they are equal, otherwise -1.  */
3892   if (unsigned_p)
3893     final_larger
3894       = ((unsigned HOST_WIDE_INT) INTVAL (final_value)
3895          > (unsigned HOST_WIDE_INT) INTVAL (initial_value))
3896         - ((unsigned HOST_WIDE_INT) INTVAL (final_value)
3897            < (unsigned HOST_WIDE_INT) INTVAL (initial_value));
3898   else
3899     final_larger = (INTVAL (final_value) > INTVAL (initial_value))
3900       - (INTVAL (final_value) < INTVAL (initial_value));
3901
3902   if (INTVAL (increment) > 0)
3903     increment_dir = 1;
3904   else if (INTVAL (increment) == 0)
3905     increment_dir = 0;
3906   else
3907     increment_dir = -1;
3908
3909   /* There are 27 different cases: compare_dir = -1, 0, 1;
3910      final_larger = -1, 0, 1; increment_dir = -1, 0, 1.
3911      There are 4 normal cases, 4 reverse cases (where the iteration variable
3912      will overflow before the loop exits), 4 infinite loop cases, and 15
3913      immediate exit (0 or 1 iteration depending on loop type) cases.
3914      Only try to optimize the normal cases.  */
3915
3916   /* (compare_dir/final_larger/increment_dir)
3917      Normal cases: (0/-1/-1), (0/1/1), (-1/-1/-1), (1/1/1)
3918      Reverse cases: (0/-1/1), (0/1/-1), (-1/-1/1), (1/1/-1)
3919      Infinite loops: (0/-1/0), (0/1/0), (-1/-1/0), (1/1/0)
3920      Immediate exit: (0/0/X), (-1/0/X), (-1/1/X), (1/0/X), (1/-1/X) */
3921
3922   /* ?? If the meaning of reverse loops (where the iteration variable
3923      will overflow before the loop exits) is undefined, then could
3924      eliminate all of these special checks, and just always assume
3925      the loops are normal/immediate/infinite.  Note that this means
3926      the sign of increment_dir does not have to be known.  Also,
3927      since it does not really hurt if immediate exit loops or infinite loops
3928      are optimized, then that case could be ignored also, and hence all
3929      loops can be optimized.
3930
3931      According to ANSI Spec, the reverse loop case result is undefined,
3932      because the action on overflow is undefined.
3933
3934      See also the special test for NE loops below.  */
3935
3936   if (final_larger == increment_dir && final_larger != 0
3937       && (final_larger == compare_dir || compare_dir == 0))
3938     /* Normal case.  */
3939     ;
3940   else
3941     {
3942       if (loop_dump_stream)
3943         fprintf (loop_dump_stream,
3944                  "Loop iterations: Not normal loop.\n");
3945       return 0;
3946     }
3947
3948   /* Calculate the number of iterations, final_value is only an approximation,
3949      so correct for that.  Note that abs_diff and n_iterations are
3950      unsigned, because they can be as large as 2^n - 1.  */
3951
3952   abs_inc = INTVAL (increment);
3953   if (abs_inc > 0)
3954     abs_diff = INTVAL (final_value) - INTVAL (initial_value);
3955   else if (abs_inc < 0)
3956     {
3957       abs_diff = INTVAL (initial_value) - INTVAL (final_value);
3958       abs_inc = -abs_inc;
3959     }
3960   else
3961     abort ();
3962
3963   /* For NE tests, make sure that the iteration variable won't miss
3964      the final value.  If abs_diff mod abs_incr is not zero, then the
3965      iteration variable will overflow before the loop exits, and we
3966      can not calculate the number of iterations.  */
3967   if (compare_dir == 0 && (abs_diff % abs_inc) != 0)
3968     return 0;
3969
3970   /* Note that the number of iterations could be calculated using
3971      (abs_diff + abs_inc - 1) / abs_inc, provided care was taken to
3972      handle potential overflow of the summation.  */
3973   loop_info->n_iterations = abs_diff / abs_inc + ((abs_diff % abs_inc) != 0);
3974   return loop_info->n_iterations;
3975 }
3976
3977
3978 /* Replace uses of split bivs with their split pseudo register.  This is
3979    for original instructions which remain after loop unrolling without
3980    copying.  */
3981
3982 static rtx
3983 remap_split_bivs (x)
3984      rtx x;
3985 {
3986   register enum rtx_code code;
3987   register int i;
3988   register const char *fmt;
3989
3990   if (x == 0)
3991     return x;
3992
3993   code = GET_CODE (x);
3994   switch (code)
3995     {
3996     case SCRATCH:
3997     case PC:
3998     case CC0:
3999     case CONST_INT:
4000     case CONST_DOUBLE:
4001     case CONST:
4002     case SYMBOL_REF:
4003     case LABEL_REF:
4004       return x;
4005
4006     case REG:
4007 #if 0
4008       /* If non-reduced/final-value givs were split, then this would also
4009          have to remap those givs also.  */
4010 #endif
4011       if (REGNO (x) < max_reg_before_loop
4012           && REG_IV_TYPE (REGNO (x)) == BASIC_INDUCT)
4013         return reg_biv_class[REGNO (x)]->biv->src_reg;
4014       break;
4015
4016     default:
4017       break;
4018     }
4019
4020   fmt = GET_RTX_FORMAT (code);
4021   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4022     {
4023       if (fmt[i] == 'e')
4024         XEXP (x, i) = remap_split_bivs (XEXP (x, i));
4025       if (fmt[i] == 'E')
4026         {
4027           register int j;
4028           for (j = 0; j < XVECLEN (x, i); j++)
4029             XVECEXP (x, i, j) = remap_split_bivs (XVECEXP (x, i, j));
4030         }
4031     }
4032   return x;
4033 }
4034
4035 /* If FIRST_UID is a set of REGNO, and FIRST_UID dominates LAST_UID (e.g.
4036    FIST_UID is always executed if LAST_UID is), then return 1.  Otherwise
4037    return 0.  COPY_START is where we can start looking for the insns
4038    FIRST_UID and LAST_UID.  COPY_END is where we stop looking for these
4039    insns.
4040
4041    If there is no JUMP_INSN between LOOP_START and FIRST_UID, then FIRST_UID
4042    must dominate LAST_UID.
4043
4044    If there is a CODE_LABEL between FIRST_UID and LAST_UID, then FIRST_UID
4045    may not dominate LAST_UID.
4046
4047    If there is no CODE_LABEL between FIRST_UID and LAST_UID, then FIRST_UID
4048    must dominate LAST_UID.  */
4049
4050 int
4051 set_dominates_use (regno, first_uid, last_uid, copy_start, copy_end)
4052      int regno;
4053      int first_uid;
4054      int last_uid;
4055      rtx copy_start;
4056      rtx copy_end;
4057 {
4058   int passed_jump = 0;
4059   rtx p = NEXT_INSN (copy_start);
4060
4061   while (INSN_UID (p) != first_uid)
4062     {
4063       if (GET_CODE (p) == JUMP_INSN)
4064         passed_jump= 1;
4065       /* Could not find FIRST_UID.  */
4066       if (p == copy_end)
4067         return 0;
4068       p = NEXT_INSN (p);
4069     }
4070
4071   /* Verify that FIRST_UID is an insn that entirely sets REGNO.  */
4072   if (GET_RTX_CLASS (GET_CODE (p)) != 'i'
4073       || ! dead_or_set_regno_p (p, regno))
4074     return 0;
4075
4076   /* FIRST_UID is always executed.  */
4077   if (passed_jump == 0)
4078     return 1;
4079
4080   while (INSN_UID (p) != last_uid)
4081     {
4082       /* If we see a CODE_LABEL between FIRST_UID and LAST_UID, then we
4083          can not be sure that FIRST_UID dominates LAST_UID.  */
4084       if (GET_CODE (p) == CODE_LABEL)
4085         return 0;
4086       /* Could not find LAST_UID, but we reached the end of the loop, so
4087          it must be safe.  */
4088       else if (p == copy_end)
4089         return 1;
4090       p = NEXT_INSN (p);
4091     }
4092
4093   /* FIRST_UID is always executed if LAST_UID is executed.  */
4094   return 1;
4095 }