OSDN Git Service

(basic_induction_var): Inside PLUS, when looking for promoted
[pf3gnuchains/gcc-fork.git] / gcc / loop.c
1 /* Move constant computations out of loops.
2    Copyright (C) 1987, 1988, 1989, 1991, 1992 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20
21 /* This is the loop optimization pass of the compiler.
22    It finds invariant computations within loops and moves them
23    to the beginning of the loop.  Then it identifies basic and 
24    general induction variables.  Strength reduction is applied to the general
25    induction variables, and induction variable elimination is applied to
26    the basic induction variables.
27
28    It also finds cases where
29    a register is set within the loop by zero-extending a narrower value
30    and changes these to zero the entire register once before the loop
31    and merely copy the low part within the loop.
32
33    Most of the complexity is in heuristics to decide when it is worth
34    while to do these things.  */
35
36 #include <stdio.h>
37 #include "config.h"
38 #include "rtl.h"
39 #include "obstack.h"
40 #include "expr.h"
41 #include "insn-config.h"
42 #include "insn-flags.h"
43 #include "regs.h"
44 #include "hard-reg-set.h"
45 #include "recog.h"
46 #include "flags.h"
47 #include "real.h"
48 #include "loop.h"
49
50 /* Vector mapping INSN_UIDs to luids.
51    The luids are like uids but increase monotonically always.
52    We use them to see whether a jump comes from outside a given loop.  */
53
54 int *uid_luid;
55
56 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
57    number the insn is contained in.  */
58
59 int *uid_loop_num;
60
61 /* 1 + largest uid of any insn.  */
62
63 int max_uid_for_loop;
64
65 /* 1 + luid of last insn.  */
66
67 static int max_luid;
68
69 /* Number of loops detected in current function.  Used as index to the
70    next few tables.  */
71
72 static int max_loop_num;
73
74 /* Indexed by loop number, contains the first and last insn of each loop.  */
75
76 static rtx *loop_number_loop_starts, *loop_number_loop_ends;
77
78 /* For each loop, gives the containing loop number, -1 if none.  */
79
80 int *loop_outer_loop;
81
82 /* Indexed by loop number, contains a nonzero value if the "loop" isn't
83    really a loop (an insn outside the loop branches into it).  */
84
85 static char *loop_invalid;
86
87 /* Indexed by loop number, links together all LABEL_REFs which refer to
88    code labels outside the loop.  Used by routines that need to know all
89    loop exits, such as final_biv_value and final_giv_value.
90
91    This does not include loop exits due to return instructions.  This is
92    because all bivs and givs are pseudos, and hence must be dead after a
93    return, so the presense of a return does not affect any of the
94    optimizations that use this info.  It is simpler to just not include return
95    instructions on this list.  */
96
97 rtx *loop_number_exit_labels;
98
99 /* Holds the number of loop iterations.  It is zero if the number could not be
100    calculated.  Must be unsigned since the number of iterations can
101    be as high as 2^wordsize-1.  For loops with a wider iterator, this number
102    will will be zero if the number of loop iterations is too large for an
103    unsigned integer to hold.  */
104
105 unsigned HOST_WIDE_INT loop_n_iterations;
106
107 /* Nonzero if there is a subroutine call in the current loop.
108    (unknown_address_altered is also nonzero in this case.)  */
109
110 static int loop_has_call;
111
112 /* Nonzero if there is a volatile memory reference in the current
113    loop.  */
114
115 static int loop_has_volatile;
116
117 /* Added loop_continue which is the NOTE_INSN_LOOP_CONT of the
118    current loop.  A continue statement will generate a branch to
119    NEXT_INSN (loop_continue).  */
120
121 static rtx loop_continue;
122
123 /* Indexed by register number, contains the number of times the reg
124    is set during the loop being scanned.
125    During code motion, a negative value indicates a reg that has been
126    made a candidate; in particular -2 means that it is an candidate that
127    we know is equal to a constant and -1 means that it is an candidate
128    not known equal to a constant.
129    After code motion, regs moved have 0 (which is accurate now)
130    while the failed candidates have the original number of times set.
131
132    Therefore, at all times, == 0 indicates an invariant register;
133    < 0 a conditionally invariant one.  */
134
135 static short *n_times_set;
136
137 /* Original value of n_times_set; same except that this value
138    is not set negative for a reg whose sets have been made candidates
139    and not set to 0 for a reg that is moved.  */
140
141 static short *n_times_used;
142
143 /* Index by register number, 1 indicates that the register
144    cannot be moved or strength reduced.  */
145
146 static char *may_not_optimize;
147
148 /* Nonzero means reg N has already been moved out of one loop.
149    This reduces the desire to move it out of another.  */
150
151 static char *moved_once;
152
153 /* Array of MEMs that are stored in this loop. If there are too many to fit
154    here, we just turn on unknown_address_altered.  */
155
156 #define NUM_STORES 20
157 static rtx loop_store_mems[NUM_STORES];
158
159 /* Index of first available slot in above array.  */
160 static int loop_store_mems_idx;
161
162 /* Nonzero if we don't know what MEMs were changed in the current loop.
163    This happens if the loop contains a call (in which case `loop_has_call'
164    will also be set) or if we store into more than NUM_STORES MEMs.  */
165
166 static int unknown_address_altered;
167
168 /* Count of movable (i.e. invariant) instructions discovered in the loop.  */
169 static int num_movables;
170
171 /* Count of memory write instructions discovered in the loop.  */
172 static int num_mem_sets;
173
174 /* Number of loops contained within the current one, including itself.  */
175 static int loops_enclosed;
176
177 /* Bound on pseudo register number before loop optimization.
178    A pseudo has valid regscan info if its number is < max_reg_before_loop.  */
179 int max_reg_before_loop;
180
181 /* This obstack is used in product_cheap_p to allocate its rtl.  It
182    may call gen_reg_rtx which, in turn, may reallocate regno_reg_rtx.
183    If we used the same obstack that it did, we would be deallocating
184    that array.  */
185
186 static struct obstack temp_obstack;
187
188 /* This is where the pointer to the obstack being used for RTL is stored.  */
189
190 extern struct obstack *rtl_obstack;
191
192 #define obstack_chunk_alloc xmalloc
193 #define obstack_chunk_free free
194
195 extern char *oballoc ();
196 \f
197 /* During the analysis of a loop, a chain of `struct movable's
198    is made to record all the movable insns found.
199    Then the entire chain can be scanned to decide which to move.  */
200
201 struct movable
202 {
203   rtx insn;                     /* A movable insn */
204   rtx set_src;                  /* The expression this reg is set from. */
205   rtx set_dest;                 /* The destination of this SET. */
206   rtx dependencies;             /* When INSN is libcall, this is an EXPR_LIST
207                                    of any registers used within the LIBCALL. */
208   int consec;                   /* Number of consecutive following insns 
209                                    that must be moved with this one.  */
210   int regno;                    /* The register it sets */
211   short lifetime;               /* lifetime of that register;
212                                    may be adjusted when matching movables
213                                    that load the same value are found.  */
214   short savings;                /* Number of insns we can move for this reg,
215                                    including other movables that force this
216                                    or match this one.  */
217   unsigned int cond : 1;        /* 1 if only conditionally movable */
218   unsigned int force : 1;       /* 1 means MUST move this insn */
219   unsigned int global : 1;      /* 1 means reg is live outside this loop */
220                 /* If PARTIAL is 1, GLOBAL means something different:
221                    that the reg is live outside the range from where it is set
222                    to the following label.  */
223   unsigned int done : 1;        /* 1 inhibits further processing of this */
224   
225   unsigned int partial : 1;     /* 1 means this reg is used for zero-extending.
226                                    In particular, moving it does not make it
227                                    invariant.  */
228   unsigned int move_insn : 1;   /* 1 means that we call emit_move_insn to
229                                    load SRC, rather than copying INSN.  */
230   unsigned int is_equiv : 1;    /* 1 means a REG_EQUIV is present on INSN. */
231   enum machine_mode savemode;   /* Nonzero means it is a mode for a low part
232                                    that we should avoid changing when clearing
233                                    the rest of the reg.  */
234   struct movable *match;        /* First entry for same value */
235   struct movable *forces;       /* An insn that must be moved if this is */
236   struct movable *next;
237 };
238
239 FILE *loop_dump_stream;
240
241 /* Forward declarations.  */
242
243 static void find_and_verify_loops ();
244 static void mark_loop_jump ();
245 static void prescan_loop ();
246 static int reg_in_basic_block_p ();
247 static int consec_sets_invariant_p ();
248 static rtx libcall_other_reg ();
249 static int labels_in_range_p ();
250 static void count_loop_regs_set ();
251 static void note_addr_stored ();
252 static int loop_reg_used_before_p ();
253 static void scan_loop ();
254 static void replace_call_address ();
255 static rtx skip_consec_insns ();
256 static int libcall_benefit ();
257 static void ignore_some_movables ();
258 static void force_movables ();
259 static void combine_movables ();
260 static int rtx_equal_for_loop_p ();
261 static void move_movables ();
262 static void strength_reduce ();
263 static int valid_initial_value_p ();
264 static void find_mem_givs ();
265 static void record_biv ();
266 static void check_final_value ();
267 static void record_giv ();
268 static void update_giv_derive ();
269 static void delete_insn_forces ();
270 static int basic_induction_var ();
271 static rtx simplify_giv_expr ();
272 static int general_induction_var ();
273 static int consec_sets_giv ();
274 static int check_dbra_loop ();
275 static rtx express_from ();
276 static int combine_givs_p ();
277 static void combine_givs ();
278 static int product_cheap_p ();
279 static int maybe_eliminate_biv ();
280 static int maybe_eliminate_biv_1 ();
281 static int last_use_this_basic_block ();
282 static void record_initial ();
283 static void update_reg_last_use ();
284 \f
285 /* Relative gain of eliminating various kinds of operations.  */
286 int add_cost;
287 #if 0
288 int shift_cost;
289 int mult_cost;
290 #endif
291
292 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
293    copy the value of the strength reduced giv to its original register.  */
294 int copy_cost;
295
296 void
297 init_loop ()
298 {
299   char *free_point = (char *) oballoc (1);
300   rtx reg = gen_rtx (REG, word_mode, 0);
301   rtx pow2 = GEN_INT (32);
302   rtx lea;
303   int i;
304
305   add_cost = rtx_cost (gen_rtx (PLUS, word_mode, reg, reg), SET);
306
307   /* We multiply by 2 to reconcile the difference in scale between
308      these two ways of computing costs.  Otherwise the cost of a copy
309      will be far less than the cost of an add.  */
310
311   copy_cost = 2 * 2;
312
313   /* Free the objects we just allocated.  */
314   obfree (free_point);
315
316   /* Initialize the obstack used for rtl in product_cheap_p.  */
317   gcc_obstack_init (&temp_obstack);
318 }
319 \f
320 /* Entry point of this file.  Perform loop optimization
321    on the current function.  F is the first insn of the function
322    and DUMPFILE is a stream for output of a trace of actions taken
323    (or 0 if none should be output).  */
324
325 void
326 loop_optimize (f, dumpfile)
327      /* f is the first instruction of a chain of insns for one function */
328      rtx f;
329      FILE *dumpfile;
330 {
331   register rtx insn;
332   register int i;
333   rtx end;
334   rtx last_insn;
335
336   loop_dump_stream = dumpfile;
337
338   init_recog_no_volatile ();
339   init_alias_analysis ();
340
341   max_reg_before_loop = max_reg_num ();
342
343   moved_once = (char *) alloca (max_reg_before_loop);
344   bzero (moved_once, max_reg_before_loop);
345
346   regs_may_share = 0;
347
348   /* Count the number of loops. */
349
350   max_loop_num = 0;
351   for (insn = f; insn; insn = NEXT_INSN (insn))
352     {
353       if (GET_CODE (insn) == NOTE
354           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
355         max_loop_num++;
356     }
357
358   /* Don't waste time if no loops.  */
359   if (max_loop_num == 0)
360     return;
361
362   /* Get size to use for tables indexed by uids.
363      Leave some space for labels allocated by find_and_verify_loops.  */
364   max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 4;
365
366   uid_luid = (int *) alloca (max_uid_for_loop * sizeof (int));
367   uid_loop_num = (int *) alloca (max_uid_for_loop * sizeof (int));
368
369   bzero (uid_luid, max_uid_for_loop * sizeof (int));
370   bzero (uid_loop_num, max_uid_for_loop * sizeof (int));
371
372   /* Allocate tables for recording each loop.  We set each entry, so they need
373      not be zeroed.  */
374   loop_number_loop_starts = (rtx *) alloca (max_loop_num * sizeof (rtx));
375   loop_number_loop_ends = (rtx *) alloca (max_loop_num * sizeof (rtx));
376   loop_outer_loop = (int *) alloca (max_loop_num * sizeof (int));
377   loop_invalid = (char *) alloca (max_loop_num * sizeof (char));
378   loop_number_exit_labels = (rtx *) alloca (max_loop_num * sizeof (rtx));
379
380   /* Find and process each loop.
381      First, find them, and record them in order of their beginnings.  */
382   find_and_verify_loops (f);
383
384   /* Now find all register lifetimes.  This must be done after
385      find_and_verify_loops, because it might reorder the insns in the
386      function.  */
387   reg_scan (f, max_reg_num (), 1);
388
389   /* Compute the mapping from uids to luids.
390      LUIDs are numbers assigned to insns, like uids,
391      except that luids increase monotonically through the code.
392      Don't assign luids to line-number NOTEs, so that the distance in luids
393      between two insns is not affected by -g.  */
394
395   for (insn = f, i = 0; insn; insn = NEXT_INSN (insn))
396     {
397       last_insn = insn;
398       if (GET_CODE (insn) != NOTE
399           || NOTE_LINE_NUMBER (insn) <= 0)
400         uid_luid[INSN_UID (insn)] = ++i;
401       else
402         /* Give a line number note the same luid as preceding insn.  */
403         uid_luid[INSN_UID (insn)] = i;
404     }
405
406   max_luid = i + 1;
407
408   /* Don't leave gaps in uid_luid for insns that have been
409      deleted.  It is possible that the first or last insn
410      using some register has been deleted by cross-jumping.
411      Make sure that uid_luid for that former insn's uid
412      points to the general area where that insn used to be.  */
413   for (i = 0; i < max_uid_for_loop; i++)
414     {
415       uid_luid[0] = uid_luid[i];
416       if (uid_luid[0] != 0)
417         break;
418     }
419   for (i = 0; i < max_uid_for_loop; i++)
420     if (uid_luid[i] == 0)
421       uid_luid[i] = uid_luid[i - 1];
422
423   /* Create a mapping from loops to BLOCK tree nodes.  */
424   if (flag_unroll_loops && write_symbols != NO_DEBUG)
425     find_loop_tree_blocks ();
426
427   /* Now scan the loops, last ones first, since this means inner ones are done
428      before outer ones.  */
429   for (i = max_loop_num-1; i >= 0; i--)
430     if (! loop_invalid[i] && loop_number_loop_ends[i])
431       scan_loop (loop_number_loop_starts[i], loop_number_loop_ends[i],
432                  max_reg_num ());
433
434   /* If debugging and unrolling loops, we must replicate the tree nodes
435      corresponding to the blocks inside the loop, so that the original one
436      to one mapping will remain.  */
437   if (flag_unroll_loops && write_symbols != NO_DEBUG)
438     unroll_block_trees ();
439 }
440 \f
441 /* Optimize one loop whose start is LOOP_START and end is END.
442    LOOP_START is the NOTE_INSN_LOOP_BEG and END is the matching
443    NOTE_INSN_LOOP_END.  */
444
445 /* ??? Could also move memory writes out of loops if the destination address
446    is invariant, the source is invariant, the memory write is not volatile,
447    and if we can prove that no read inside the loop can read this address
448    before the write occurs.  If there is a read of this address after the
449    write, then we can also mark the memory read as invariant.  */
450
451 static void
452 scan_loop (loop_start, end, nregs)
453      rtx loop_start, end;
454      int nregs;
455 {
456   register int i;
457   register rtx p;
458   /* 1 if we are scanning insns that could be executed zero times.  */
459   int maybe_never = 0;
460   /* 1 if we are scanning insns that might never be executed
461      due to a subroutine call which might exit before they are reached.  */
462   int call_passed = 0;
463   /* For a rotated loop that is entered near the bottom,
464      this is the label at the top.  Otherwise it is zero.  */
465   rtx loop_top = 0;
466   /* Jump insn that enters the loop, or 0 if control drops in.  */
467   rtx loop_entry_jump = 0;
468   /* Place in the loop where control enters.  */
469   rtx scan_start;
470   /* Number of insns in the loop.  */
471   int insn_count;
472   int in_libcall = 0;
473   int tem;
474   rtx temp;
475   /* The SET from an insn, if it is the only SET in the insn.  */
476   rtx set, set1;
477   /* Chain describing insns movable in current loop.  */
478   struct movable *movables = 0;
479   /* Last element in `movables' -- so we can add elements at the end.  */
480   struct movable *last_movable = 0;
481   /* Ratio of extra register life span we can justify
482      for saving an instruction.  More if loop doesn't call subroutines
483      since in that case saving an insn makes more difference
484      and more registers are available.  */
485   int threshold;
486   /* If we have calls, contains the insn in which a register was used
487      if it was used exactly once; contains const0_rtx if it was used more
488      than once.  */
489   rtx *reg_single_usage = 0;
490
491   n_times_set = (short *) alloca (nregs * sizeof (short));
492   n_times_used = (short *) alloca (nregs * sizeof (short));
493   may_not_optimize = (char *) alloca (nregs);
494
495   /* Determine whether this loop starts with a jump down to a test at
496      the end.  This will occur for a small number of loops with a test
497      that is too complex to duplicate in front of the loop.
498
499      We search for the first insn or label in the loop, skipping NOTEs.
500      However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
501      (because we might have a loop executed only once that contains a
502      loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
503      (in case we have a degenerate loop).
504
505      Note that if we mistakenly think that a loop is entered at the top
506      when, in fact, it is entered at the exit test, the only effect will be
507      slightly poorer optimization.  Making the opposite error can generate
508      incorrect code.  Since very few loops now start with a jump to the 
509      exit test, the code here to detect that case is very conservative.  */
510
511   for (p = NEXT_INSN (loop_start);
512        p != end
513          && GET_CODE (p) != CODE_LABEL && GET_RTX_CLASS (GET_CODE (p)) != 'i'
514          && (GET_CODE (p) != NOTE
515              || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
516                  && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
517        p = NEXT_INSN (p))
518     ;
519
520   scan_start = p;
521
522   /* Set up variables describing this loop.  */
523   prescan_loop (loop_start, end);
524   threshold = (loop_has_call ? 1 : 2) * (1 + n_non_fixed_regs);
525
526   /* If loop has a jump before the first label,
527      the true entry is the target of that jump.
528      Start scan from there.
529      But record in LOOP_TOP the place where the end-test jumps
530      back to so we can scan that after the end of the loop.  */
531   if (GET_CODE (p) == JUMP_INSN)
532     {
533       loop_entry_jump = p;
534
535       /* Loop entry must be unconditional jump (and not a RETURN)  */
536       if (simplejump_p (p)
537           && JUMP_LABEL (p) != 0
538           /* Check to see whether the jump actually
539              jumps out of the loop (meaning it's no loop).
540              This case can happen for things like
541              do {..} while (0).  If this label was generated previously
542              by loop, we can't tell anything about it and have to reject
543              the loop.  */
544           && INSN_UID (JUMP_LABEL (p)) < max_uid_for_loop
545           && INSN_LUID (JUMP_LABEL (p)) >= INSN_LUID (loop_start)
546           && INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (end))
547         {
548           loop_top = next_label (scan_start);
549           scan_start = JUMP_LABEL (p);
550         }
551     }
552
553   /* If SCAN_START was an insn created by loop, we don't know its luid
554      as required by loop_reg_used_before_p.  So skip such loops.  (This
555      test may never be true, but it's best to play it safe.) 
556
557      Also, skip loops where we do not start scanning at a label.  This
558      test also rejects loops starting with a JUMP_INSN that failed the
559      test above.  */
560
561   if (INSN_UID (scan_start) >= max_uid_for_loop
562       || GET_CODE (scan_start) != CODE_LABEL)
563     {
564       if (loop_dump_stream)
565         fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
566                  INSN_UID (loop_start), INSN_UID (end));
567       return;
568     }
569
570   /* Count number of times each reg is set during this loop.
571      Set may_not_optimize[I] if it is not safe to move out
572      the setting of register I.  If this loop has calls, set
573      reg_single_usage[I].  */
574
575   bzero (n_times_set, nregs * sizeof (short));
576   bzero (may_not_optimize, nregs);
577
578   if (loop_has_call)
579     {
580       reg_single_usage = (rtx *) alloca (nregs * sizeof (rtx));
581       bzero (reg_single_usage, nregs * sizeof (rtx));
582     }
583
584   count_loop_regs_set (loop_top ? loop_top : loop_start, end,
585                        may_not_optimize, reg_single_usage, &insn_count, nregs);
586
587   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
588     may_not_optimize[i] = 1, n_times_set[i] = 1;
589   bcopy (n_times_set, n_times_used, nregs * sizeof (short));
590
591   if (loop_dump_stream)
592     {
593       fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
594                INSN_UID (loop_start), INSN_UID (end), insn_count);
595       if (loop_continue)
596         fprintf (loop_dump_stream, "Continue at insn %d.\n",
597                  INSN_UID (loop_continue));
598     }
599
600   /* Scan through the loop finding insns that are safe to move.
601      Set n_times_set negative for the reg being set, so that
602      this reg will be considered invariant for subsequent insns.
603      We consider whether subsequent insns use the reg
604      in deciding whether it is worth actually moving.
605
606      MAYBE_NEVER is nonzero if we have passed a conditional jump insn
607      and therefore it is possible that the insns we are scanning
608      would never be executed.  At such times, we must make sure
609      that it is safe to execute the insn once instead of zero times.
610      When MAYBE_NEVER is 0, all insns will be executed at least once
611      so that is not a problem.  */
612
613   p = scan_start;
614   while (1)
615     {
616       p = NEXT_INSN (p);
617       /* At end of a straight-in loop, we are done.
618          At end of a loop entered at the bottom, scan the top.  */
619       if (p == scan_start)
620         break;
621       if (p == end)
622         {
623           if (loop_top != 0)
624             p = NEXT_INSN (loop_top);
625           else
626             break;
627           if (p == scan_start)
628             break;
629         }
630
631       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
632           && find_reg_note (p, REG_LIBCALL, NULL_RTX))
633         in_libcall = 1;
634       else if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
635                && find_reg_note (p, REG_RETVAL, NULL_RTX))
636         in_libcall = 0;
637
638       if (GET_CODE (p) == INSN
639           && (set = single_set (p))
640           && GET_CODE (SET_DEST (set)) == REG
641           && ! may_not_optimize[REGNO (SET_DEST (set))])
642         {
643           int tem1 = 0;
644           int tem2 = 0;
645           int move_insn = 0;
646           rtx src = SET_SRC (set);
647           rtx dependencies = 0;
648
649           /* Figure out what to use as a source of this insn.  If a REG_EQUIV
650              note is given or if a REG_EQUAL note with a constant operand is
651              specified, use it as the source and mark that we should move
652              this insn by calling emit_move_insn rather that duplicating the
653              insn.
654
655              Otherwise, only use the REG_EQUAL contents if a REG_RETVAL note
656              is present.  */
657           temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
658           if (temp)
659             src = XEXP (temp, 0), move_insn = 1;
660           else 
661             {
662               temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
663               if (temp && CONSTANT_P (XEXP (temp, 0)))
664                 src = XEXP (temp, 0), move_insn = 1;
665               if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
666                 {
667                   src = XEXP (temp, 0);
668                   /* A libcall block can use regs that don't appear in
669                      the equivalent expression.  To move the libcall,
670                      we must move those regs too.  */
671                   dependencies = libcall_other_reg (p, src);
672                 }
673             }
674
675           /* Don't try to optimize a register that was made
676              by loop-optimization for an inner loop.
677              We don't know its life-span, so we can't compute the benefit.  */
678           if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
679             ;
680           /* In order to move a register, we need to have one of three cases:
681              (1) it is used only in the same basic block as the set
682              (2) it is not a user variable.
683              (3) the set is guaranteed to be executed once the loop starts,
684                  and the reg is not used until after that.  */
685           else if (! ((! maybe_never
686                        && ! loop_reg_used_before_p (set, p, loop_start,
687                                                     scan_start, end))
688                       || ! REG_USERVAR_P (SET_DEST (PATTERN (p)))
689                       || reg_in_basic_block_p (p, SET_DEST (PATTERN (p)))))
690             ;
691           else if ((tem = invariant_p (src))
692                    && (dependencies == 0
693                        || (tem2 = invariant_p (dependencies)) != 0)
694                    && (n_times_set[REGNO (SET_DEST (set))] == 1
695                        || (tem1
696                            = consec_sets_invariant_p (SET_DEST (set),
697                                                       n_times_set[REGNO (SET_DEST (set))],
698                                                       p)))
699                    /* If the insn can cause a trap (such as divide by zero),
700                       can't move it unless it's guaranteed to be executed
701                       once loop is entered.  Even a function call might
702                       prevent the trap insn from being reached
703                       (since it might exit!)  */
704                    && ! ((maybe_never || call_passed)
705                          && may_trap_p (src)))
706             {
707               register struct movable *m;
708               register int regno = REGNO (SET_DEST (set));
709
710               /* A potential lossage is where we have a case where two insns
711                  can be combined as long as they are both in the loop, but
712                  we move one of them outside the loop.  For large loops,
713                  this can lose.  The most common case of this is the address
714                  of a function being called.  
715
716                  Therefore, if this register is marked as being used exactly
717                  once if we are in a loop with calls (a "large loop"), see if
718                  we can replace the usage of this register with the source
719                  of this SET.  If we can, delete this insn. 
720
721                  Don't do this if P has a REG_RETVAL note or if we have
722                  SMALL_REGISTER_CLASSES and SET_SRC is a hard register.  */
723
724               if (reg_single_usage && reg_single_usage[regno] != 0
725                   && reg_single_usage[regno] != const0_rtx
726                   && regno_first_uid[regno] == INSN_UID (p)
727                   && (regno_last_uid[regno]
728                       == INSN_UID (reg_single_usage[regno]))
729                   && n_times_set[REGNO (SET_DEST (set))] == 1
730                   && ! side_effects_p (SET_SRC (set))
731                   && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
732 #ifdef SMALL_REGISTER_CLASSES
733                   && ! (GET_CODE (SET_SRC (set)) == REG
734                         && REGNO (SET_SRC (set)) < FIRST_PSEUDO_REGISTER)
735 #endif
736                   /* This test is not redundant; SET_SRC (set) might be
737                      a call-clobbered register and the life of REGNO
738                      might span a call.  */
739                   && ! modified_between_p (SET_SRC (set), p,
740                                           reg_single_usage[regno])
741                   && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
742                                            reg_single_usage[regno]))
743                 {
744                   /* Replace any usage in a REG_EQUAL note.  */
745                   REG_NOTES (reg_single_usage[regno])
746                     = replace_rtx (REG_NOTES (reg_single_usage[regno]),
747                                    SET_DEST (set), SET_SRC (set));
748                                    
749                   PUT_CODE (p, NOTE);
750                   NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED;
751                   NOTE_SOURCE_FILE (p) = 0;
752                   n_times_set[regno] = 0;
753                   continue;
754                 }
755
756               m = (struct movable *) alloca (sizeof (struct movable));
757               m->next = 0;
758               m->insn = p;
759               m->set_src = src;
760               m->dependencies = dependencies;
761               m->set_dest = SET_DEST (set);
762               m->force = 0;
763               m->consec = n_times_set[REGNO (SET_DEST (set))] - 1;
764               m->done = 0;
765               m->forces = 0;
766               m->partial = 0;
767               m->move_insn = move_insn;
768               m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
769               m->savemode = VOIDmode;
770               m->regno = regno;
771               /* Set M->cond if either invariant_p or consec_sets_invariant_p
772                  returned 2 (only conditionally invariant).  */
773               m->cond = ((tem | tem1 | tem2) > 1);
774               m->global = (uid_luid[regno_last_uid[regno]] > INSN_LUID (end)
775                            || uid_luid[regno_first_uid[regno]] < INSN_LUID (loop_start));
776               m->match = 0;
777               m->lifetime = (uid_luid[regno_last_uid[regno]]
778                              - uid_luid[regno_first_uid[regno]]);
779               m->savings = n_times_used[regno];
780               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
781                 m->savings += libcall_benefit (p);
782               n_times_set[regno] = move_insn ? -2 : -1;
783               /* Add M to the end of the chain MOVABLES.  */
784               if (movables == 0)
785                 movables = m;
786               else
787                 last_movable->next = m;
788               last_movable = m;
789
790               if (m->consec > 0)
791                 {
792                   /* Skip this insn, not checking REG_LIBCALL notes.  */
793                   p = NEXT_INSN (p);
794                   /* Skip the consecutive insns, if there are any.  */
795                   p = skip_consec_insns (p, m->consec);
796                   /* Back up to the last insn of the consecutive group.  */
797                   p = prev_nonnote_insn (p);
798
799                   /* We must now reset m->move_insn, m->is_equiv, and possibly
800                      m->set_src to correspond to the effects of all the
801                      insns.  */
802                   temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
803                   if (temp)
804                     m->set_src = XEXP (temp, 0), m->move_insn = 1;
805                   else
806                     {
807                       temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
808                       if (temp && CONSTANT_P (XEXP (temp, 0)))
809                         m->set_src = XEXP (temp, 0), m->move_insn = 1;
810                       else
811                         m->move_insn = 0;
812
813                     }
814                   m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
815                 }
816             }
817           /* If this register is always set within a STRICT_LOW_PART
818              or set to zero, then its high bytes are constant.
819              So clear them outside the loop and within the loop
820              just load the low bytes.
821              We must check that the machine has an instruction to do so.
822              Also, if the value loaded into the register
823              depends on the same register, this cannot be done.  */
824           else if (SET_SRC (set) == const0_rtx
825                    && GET_CODE (NEXT_INSN (p)) == INSN
826                    && (set1 = single_set (NEXT_INSN (p)))
827                    && GET_CODE (set1) == SET
828                    && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
829                    && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
830                    && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
831                        == SET_DEST (set))
832                    && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
833             {
834               register int regno = REGNO (SET_DEST (set));
835               if (n_times_set[regno] == 2)
836                 {
837                   register struct movable *m;
838                   m = (struct movable *) alloca (sizeof (struct movable));
839                   m->next = 0;
840                   m->insn = p;
841                   m->set_dest = SET_DEST (set);
842                   m->dependencies = 0;
843                   m->force = 0;
844                   m->consec = 0;
845                   m->done = 0;
846                   m->forces = 0;
847                   m->move_insn = 0;
848                   m->partial = 1;
849                   /* If the insn may not be executed on some cycles,
850                      we can't clear the whole reg; clear just high part.
851                      Not even if the reg is used only within this loop.
852                      Consider this:
853                      while (1)
854                        while (s != t) {
855                          if (foo ()) x = *s;
856                          use (x);
857                        }
858                      Clearing x before the inner loop could clobber a value
859                      being saved from the last time around the outer loop.
860                      However, if the reg is not used outside this loop
861                      and all uses of the register are in the same
862                      basic block as the store, there is no problem.
863
864                      If this insn was made by loop, we don't know its
865                      INSN_LUID and hence must make a conservative
866                      assumption. */
867                   m->global = (INSN_UID (p) >= max_uid_for_loop
868                                || (uid_luid[regno_last_uid[regno]]
869                                    > INSN_LUID (end))
870                                || (uid_luid[regno_first_uid[regno]]
871                                    < INSN_LUID (p))
872                                || (labels_in_range_p
873                                    (p, uid_luid[regno_first_uid[regno]])));
874                   if (maybe_never && m->global)
875                     m->savemode = GET_MODE (SET_SRC (set1));
876                   else
877                     m->savemode = VOIDmode;
878                   m->regno = regno;
879                   m->cond = 0;
880                   m->match = 0;
881                   m->lifetime = (uid_luid[regno_last_uid[regno]]
882                                  - uid_luid[regno_first_uid[regno]]);
883                   m->savings = 1;
884                   n_times_set[regno] = -1;
885                   /* Add M to the end of the chain MOVABLES.  */
886                   if (movables == 0)
887                     movables = m;
888                   else
889                     last_movable->next = m;
890                   last_movable = m;
891                 }
892             }
893         }
894       /* Past a call insn, we get to insns which might not be executed
895          because the call might exit.  This matters for insns that trap.
896          Call insns inside a REG_LIBCALL/REG_RETVAL block always return,
897          so they don't count.  */
898       else if (GET_CODE (p) == CALL_INSN && ! in_libcall)
899         call_passed = 1;
900       /* Past a label or a jump, we get to insns for which we
901          can't count on whether or how many times they will be
902          executed during each iteration.  Therefore, we can
903          only move out sets of trivial variables
904          (those not used after the loop).  */
905       /* This code appears in three places, once in scan_loop, and twice
906          in strength_reduce.  */
907       else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
908                /* If we enter the loop in the middle, and scan around to the
909                   beginning, don't set maybe_never for that.  This must be an
910                   unconditional jump, otherwise the code at the top of the
911                   loop might never be executed.  Unconditional jumps are
912                   followed a by barrier then loop end.  */
913                && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop_top
914                      && NEXT_INSN (NEXT_INSN (p)) == end
915                      && simplejump_p (p)))
916         maybe_never = 1;
917       /* At the virtual top of a converted loop, insns are again known to
918          be executed: logically, the loop begins here even though the exit
919          code has been duplicated.  */
920       else if (GET_CODE (p) == NOTE
921                && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP)
922         maybe_never = call_passed = 0;
923     }
924
925   /* If one movable subsumes another, ignore that other.  */
926
927   ignore_some_movables (movables);
928
929   /* For each movable insn, see if the reg that it loads
930      leads when it dies right into another conditionally movable insn.
931      If so, record that the second insn "forces" the first one,
932      since the second can be moved only if the first is.  */
933
934   force_movables (movables);
935
936   /* See if there are multiple movable insns that load the same value.
937      If there are, make all but the first point at the first one
938      through the `match' field, and add the priorities of them
939      all together as the priority of the first.  */
940
941   combine_movables (movables, nregs);
942         
943   /* Now consider each movable insn to decide whether it is worth moving.
944      Store 0 in n_times_set for each reg that is moved.  */
945
946   move_movables (movables, threshold,
947                  insn_count, loop_start, end, nregs);
948
949   /* Now candidates that still are negative are those not moved.
950      Change n_times_set to indicate that those are not actually invariant.  */
951   for (i = 0; i < nregs; i++)
952     if (n_times_set[i] < 0)
953       n_times_set[i] = n_times_used[i];
954
955   if (flag_strength_reduce)
956     strength_reduce (scan_start, end, loop_top,
957                      insn_count, loop_start, end);
958 }
959 \f
960 /* Add elements to *OUTPUT to record all the pseudo-regs
961    mentioned in IN_THIS but not mentioned in NOT_IN_THIS.  */
962
963 void
964 record_excess_regs (in_this, not_in_this, output)
965      rtx in_this, not_in_this;
966      rtx *output;
967 {
968   enum rtx_code code;
969   char *fmt;
970   int i;
971
972   code = GET_CODE (in_this);
973
974   switch (code)
975     {
976     case PC:
977     case CC0:
978     case CONST_INT:
979     case CONST_DOUBLE:
980     case CONST:
981     case SYMBOL_REF:
982     case LABEL_REF:
983       return;
984
985     case REG:
986       if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
987           && ! reg_mentioned_p (in_this, not_in_this))
988         *output = gen_rtx (EXPR_LIST, VOIDmode, in_this, *output);
989       return;
990     }
991
992   fmt = GET_RTX_FORMAT (code);
993   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
994     {
995       int j;
996
997       switch (fmt[i])
998         {
999         case 'E':
1000           for (j = 0; j < XVECLEN (in_this, i); j++)
1001             record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1002           break;
1003
1004         case 'e':
1005           record_excess_regs (XEXP (in_this, i), not_in_this, output);
1006           break;
1007         }
1008     }
1009 }
1010 \f
1011 /* Check what regs are referred to in the libcall block ending with INSN,
1012    aside from those mentioned in the equivalent value.
1013    If there are none, return 0.
1014    If there are one or more, return an EXPR_LIST containing all of them.  */
1015
1016 static rtx
1017 libcall_other_reg (insn, equiv)
1018      rtx insn, equiv;
1019 {
1020   rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1021   rtx p = XEXP (note, 0);
1022   rtx output = 0;
1023
1024   /* First, find all the regs used in the libcall block
1025      that are not mentioned as inputs to the result.  */
1026
1027   while (p != insn)
1028     {
1029       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1030           || GET_CODE (p) == CALL_INSN)
1031         record_excess_regs (PATTERN (p), equiv, &output);
1032       p = NEXT_INSN (p);
1033     }
1034
1035   return output;
1036 }
1037 \f
1038 /* Return 1 if all uses of REG
1039    are between INSN and the end of the basic block.  */
1040
1041 static int 
1042 reg_in_basic_block_p (insn, reg)
1043      rtx insn, reg;
1044 {
1045   int regno = REGNO (reg);
1046   rtx p;
1047
1048   if (regno_first_uid[regno] != INSN_UID (insn))
1049     return 0;
1050
1051   /* Search this basic block for the already recorded last use of the reg.  */
1052   for (p = insn; p; p = NEXT_INSN (p))
1053     {
1054       switch (GET_CODE (p))
1055         {
1056         case NOTE:
1057           break;
1058
1059         case INSN:
1060         case CALL_INSN:
1061           /* Ordinary insn: if this is the last use, we win.  */
1062           if (regno_last_uid[regno] == INSN_UID (p))
1063             return 1;
1064           break;
1065
1066         case JUMP_INSN:
1067           /* Jump insn: if this is the last use, we win.  */
1068           if (regno_last_uid[regno] == INSN_UID (p))
1069             return 1;
1070           /* Otherwise, it's the end of the basic block, so we lose.  */
1071           return 0;
1072
1073         case CODE_LABEL:
1074         case BARRIER:
1075           /* It's the end of the basic block, so we lose.  */
1076           return 0;
1077         }
1078     }
1079
1080   /* The "last use" doesn't follow the "first use"??  */
1081   abort ();
1082 }
1083 \f
1084 /* Compute the benefit of eliminating the insns in the block whose
1085    last insn is LAST.  This may be a group of insns used to compute a
1086    value directly or can contain a library call.  */
1087
1088 static int
1089 libcall_benefit (last)
1090      rtx last;
1091 {
1092   rtx insn;
1093   int benefit = 0;
1094
1095   for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1096        insn != last; insn = NEXT_INSN (insn))
1097     {
1098       if (GET_CODE (insn) == CALL_INSN)
1099         benefit += 10;          /* Assume at least this many insns in a library
1100                                    routine. */
1101       else if (GET_CODE (insn) == INSN
1102                && GET_CODE (PATTERN (insn)) != USE
1103                && GET_CODE (PATTERN (insn)) != CLOBBER)
1104         benefit++;
1105     }
1106
1107   return benefit;
1108 }
1109 \f
1110 /* Skip COUNT insns from INSN, counting library calls as 1 insn.  */
1111
1112 static rtx
1113 skip_consec_insns (insn, count)
1114      rtx insn;
1115      int count;
1116 {
1117   for (; count > 0; count--)
1118     {
1119       rtx temp;
1120
1121       /* If first insn of libcall sequence, skip to end.  */
1122       /* Do this at start of loop, since INSN is guaranteed to 
1123          be an insn here.  */
1124       if (GET_CODE (insn) != NOTE
1125           && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1126         insn = XEXP (temp, 0);
1127
1128       do insn = NEXT_INSN (insn);
1129       while (GET_CODE (insn) == NOTE);
1130     }
1131
1132   return insn;
1133 }
1134
1135 /* Ignore any movable whose insn falls within a libcall
1136    which is part of another movable.
1137    We make use of the fact that the movable for the libcall value
1138    was made later and so appears later on the chain.  */
1139
1140 static void
1141 ignore_some_movables (movables)
1142      struct movable *movables;
1143 {
1144   register struct movable *m, *m1;
1145
1146   for (m = movables; m; m = m->next)
1147     {
1148       /* Is this a movable for the value of a libcall?  */
1149       rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1150       if (note)
1151         {
1152           rtx insn;
1153           /* Check for earlier movables inside that range,
1154              and mark them invalid.  We cannot use LUIDs here because
1155              insns created by loop.c for prior loops don't have LUIDs.
1156              Rather than reject all such insns from movables, we just
1157              explicitly check each insn in the libcall (since invariant
1158              libcalls aren't that common).  */
1159           for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1160             for (m1 = movables; m1 != m; m1 = m1->next)
1161               if (m1->insn == insn)
1162                 m1->done = 1;
1163         }
1164     }
1165 }         
1166
1167 /* For each movable insn, see if the reg that it loads
1168    leads when it dies right into another conditionally movable insn.
1169    If so, record that the second insn "forces" the first one,
1170    since the second can be moved only if the first is.  */
1171
1172 static void
1173 force_movables (movables)
1174      struct movable *movables;
1175 {
1176   register struct movable *m, *m1;
1177   for (m1 = movables; m1; m1 = m1->next)
1178     /* Omit this if moving just the (SET (REG) 0) of a zero-extend.  */
1179     if (!m1->partial && !m1->done)
1180       {
1181         int regno = m1->regno;
1182         for (m = m1->next; m; m = m->next)
1183           /* ??? Could this be a bug?  What if CSE caused the
1184              register of M1 to be used after this insn?
1185              Since CSE does not update regno_last_uid,
1186              this insn M->insn might not be where it dies.
1187              But very likely this doesn't matter; what matters is
1188              that M's reg is computed from M1's reg.  */
1189           if (INSN_UID (m->insn) == regno_last_uid[regno]
1190               && !m->done)
1191             break;
1192         if (m != 0 && m->set_src == m1->set_dest
1193             /* If m->consec, m->set_src isn't valid.  */
1194             && m->consec == 0)
1195           m = 0;
1196
1197         /* Increase the priority of the moving the first insn
1198            since it permits the second to be moved as well.  */
1199         if (m != 0)
1200           {
1201             m->forces = m1;
1202             m1->lifetime += m->lifetime;
1203             m1->savings += m1->savings;
1204           }
1205       }
1206 }
1207 \f
1208 /* Find invariant expressions that are equal and can be combined into
1209    one register.  */
1210
1211 static void
1212 combine_movables (movables, nregs)
1213      struct movable *movables;
1214      int nregs;
1215 {
1216   register struct movable *m;
1217   char *matched_regs = (char *) alloca (nregs);
1218   enum machine_mode mode;
1219
1220   /* Regs that are set more than once are not allowed to match
1221      or be matched.  I'm no longer sure why not.  */
1222   /* Perhaps testing m->consec_sets would be more appropriate here?  */
1223
1224   for (m = movables; m; m = m->next)
1225     if (m->match == 0 && n_times_used[m->regno] == 1 && !m->partial)
1226       {
1227         register struct movable *m1;
1228         int regno = m->regno;
1229         rtx reg_note, reg_note1;
1230
1231         bzero (matched_regs, nregs);
1232         matched_regs[regno] = 1;
1233
1234         for (m1 = movables; m1; m1 = m1->next)
1235           if (m != m1 && m1->match == 0 && n_times_used[m1->regno] == 1
1236               /* A reg used outside the loop mustn't be eliminated.  */
1237               && !m1->global
1238               /* A reg used for zero-extending mustn't be eliminated.  */
1239               && !m1->partial
1240               && (matched_regs[m1->regno]
1241                   ||
1242                   (
1243                    /* Can combine regs with different modes loaded from the
1244                       same constant only if the modes are the same or
1245                       if both are integer modes with M wider or the same
1246                       width as M1.  The check for integer is redundant, but
1247                       safe, since the only case of differing destination
1248                       modes with equal sources is when both sources are
1249                       VOIDmode, i.e., CONST_INT.  */
1250                    (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1251                     || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1252                         && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1253                         && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1254                             >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1255                    /* See if the source of M1 says it matches M.  */
1256                    && ((GET_CODE (m1->set_src) == REG
1257                         && matched_regs[REGNO (m1->set_src)])
1258                        || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1259                                                 movables))))
1260               && ((m->dependencies == m1->dependencies)
1261                   || rtx_equal_p (m->dependencies, m1->dependencies)))
1262             {
1263               m->lifetime += m1->lifetime;
1264               m->savings += m1->savings;
1265               m1->done = 1;
1266               m1->match = m;
1267               matched_regs[m1->regno] = 1;
1268             }
1269       }
1270
1271   /* Now combine the regs used for zero-extension.
1272      This can be done for those not marked `global'
1273      provided their lives don't overlap.  */
1274
1275   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1276        mode = GET_MODE_WIDER_MODE (mode))
1277     {
1278       register struct movable *m0 = 0;
1279
1280       /* Combine all the registers for extension from mode MODE.
1281          Don't combine any that are used outside this loop.  */
1282       for (m = movables; m; m = m->next)
1283         if (m->partial && ! m->global
1284             && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1285           {
1286             register struct movable *m1;
1287             int first = uid_luid[regno_first_uid[m->regno]];
1288             int last = uid_luid[regno_last_uid[m->regno]];
1289
1290             if (m0 == 0)
1291               {
1292                 /* First one: don't check for overlap, just record it.  */
1293                 m0 = m;
1294                   continue;
1295               }
1296
1297             /* Make sure they extend to the same mode.
1298                (Almost always true.)  */
1299             if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1300                 continue;
1301
1302             /* We already have one: check for overlap with those
1303                already combined together.  */
1304             for (m1 = movables; m1 != m; m1 = m1->next)
1305               if (m1 == m0 || (m1->partial && m1->match == m0))
1306                 if (! (uid_luid[regno_first_uid[m1->regno]] > last
1307                        || uid_luid[regno_last_uid[m1->regno]] < first))
1308                   goto overlap;
1309
1310             /* No overlap: we can combine this with the others.  */
1311             m0->lifetime += m->lifetime;
1312             m0->savings += m->savings;
1313             m->done = 1;
1314             m->match = m0;
1315
1316           overlap: ;
1317           }
1318     }
1319 }
1320 \f
1321 /* Return 1 if regs X and Y will become the same if moved.  */
1322
1323 static int
1324 regs_match_p (x, y, movables)
1325      rtx x, y;
1326      struct movable *movables;
1327 {
1328   int xn = REGNO (x);
1329   int yn = REGNO (y);
1330   struct movable *mx, *my;
1331
1332   for (mx = movables; mx; mx = mx->next)
1333     if (mx->regno == xn)
1334       break;
1335
1336   for (my = movables; my; my = my->next)
1337     if (my->regno == yn)
1338       break;
1339
1340   return (mx && my
1341           && ((mx->match == my->match && mx->match != 0)
1342               || mx->match == my
1343               || mx == my->match));
1344 }
1345
1346 /* Return 1 if X and Y are identical-looking rtx's.
1347    This is the Lisp function EQUAL for rtx arguments.
1348
1349    If two registers are matching movables or a movable register and an
1350    equivalent constant, consider them equal.  */
1351
1352 static int
1353 rtx_equal_for_loop_p (x, y, movables)
1354      rtx x, y;
1355      struct movable *movables;
1356 {
1357   register int i;
1358   register int j;
1359   register struct movable *m;
1360   register enum rtx_code code;
1361   register char *fmt;
1362
1363   if (x == y)
1364     return 1;
1365   if (x == 0 || y == 0)
1366     return 0;
1367
1368   code = GET_CODE (x);
1369
1370   /* If we have a register and a constant, they may sometimes be
1371      equal.  */
1372   if (GET_CODE (x) == REG && n_times_set[REGNO (x)] == -2
1373       && CONSTANT_P (y))
1374     for (m = movables; m; m = m->next)
1375       if (m->move_insn && m->regno == REGNO (x)
1376           && rtx_equal_p (m->set_src, y))
1377         return 1;
1378
1379   else if (GET_CODE (y) == REG && n_times_set[REGNO (y)] == -2
1380            && CONSTANT_P (x))
1381     for (m = movables; m; m = m->next)
1382       if (m->move_insn && m->regno == REGNO (y)
1383           && rtx_equal_p (m->set_src, x))
1384         return 1;
1385
1386   /* Otherwise, rtx's of different codes cannot be equal.  */
1387   if (code != GET_CODE (y))
1388     return 0;
1389
1390   /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1391      (REG:SI x) and (REG:HI x) are NOT equivalent.  */
1392
1393   if (GET_MODE (x) != GET_MODE (y))
1394     return 0;
1395
1396   /* These three types of rtx's can be compared nonrecursively.  */
1397   if (code == REG)
1398     return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1399
1400   if (code == LABEL_REF)
1401     return XEXP (x, 0) == XEXP (y, 0);
1402   if (code == SYMBOL_REF)
1403     return XSTR (x, 0) == XSTR (y, 0);
1404
1405   /* Compare the elements.  If any pair of corresponding elements
1406      fail to match, return 0 for the whole things.  */
1407
1408   fmt = GET_RTX_FORMAT (code);
1409   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1410     {
1411       switch (fmt[i])
1412         {
1413         case 'w':
1414           if (XWINT (x, i) != XWINT (y, i))
1415             return 0;
1416           break;
1417
1418         case 'i':
1419           if (XINT (x, i) != XINT (y, i))
1420             return 0;
1421           break;
1422
1423         case 'E':
1424           /* Two vectors must have the same length.  */
1425           if (XVECLEN (x, i) != XVECLEN (y, i))
1426             return 0;
1427
1428           /* And the corresponding elements must match.  */
1429           for (j = 0; j < XVECLEN (x, i); j++)
1430             if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j), movables) == 0)
1431               return 0;
1432           break;
1433
1434         case 'e':
1435           if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables) == 0)
1436             return 0;
1437           break;
1438
1439         case 's':
1440           if (strcmp (XSTR (x, i), XSTR (y, i)))
1441             return 0;
1442           break;
1443
1444         case 'u':
1445           /* These are just backpointers, so they don't matter.  */
1446           break;
1447
1448         case '0':
1449           break;
1450
1451           /* It is believed that rtx's at this level will never
1452              contain anything but integers and other rtx's,
1453              except for within LABEL_REFs and SYMBOL_REFs.  */
1454         default:
1455           abort ();
1456         }
1457     }
1458   return 1;
1459 }
1460 \f
1461 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1462   insns in INSNS which use thet reference.  */
1463
1464 static void
1465 add_label_notes (x, insns)
1466      rtx x;
1467      rtx insns;
1468 {
1469   enum rtx_code code = GET_CODE (x);
1470   int i, j;
1471   char *fmt;
1472   rtx insn;
1473
1474   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1475     {
1476       for (insn = insns; insn; insn = NEXT_INSN (insn))
1477         if (reg_mentioned_p (XEXP (x, 0), insn))
1478           REG_NOTES (insn) = gen_rtx (EXPR_LIST, REG_LABEL, XEXP (x, 0),
1479                                       REG_NOTES (insn));
1480       return;
1481     }
1482
1483   fmt = GET_RTX_FORMAT (code);
1484   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1485     {
1486       if (fmt[i] == 'e')
1487         add_label_notes (XEXP (x, i), insns);
1488       else if (fmt[i] == 'E')
1489         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1490           add_label_notes (XVECEXP (x, i, j), insns);
1491     }
1492 }
1493 \f
1494 /* Scan MOVABLES, and move the insns that deserve to be moved.
1495    If two matching movables are combined, replace one reg with the
1496    other throughout.  */
1497
1498 static void
1499 move_movables (movables, threshold, insn_count, loop_start, end, nregs)
1500      struct movable *movables;
1501      int threshold;
1502      int insn_count;
1503      rtx loop_start;
1504      rtx end;
1505      int nregs;
1506 {
1507   rtx new_start = 0;
1508   register struct movable *m;
1509   register rtx p;
1510   /* Map of pseudo-register replacements to handle combining
1511      when we move several insns that load the same value
1512      into different pseudo-registers.  */
1513   rtx *reg_map = (rtx *) alloca (nregs * sizeof (rtx));
1514   char *already_moved = (char *) alloca (nregs);
1515
1516   bzero (already_moved, nregs);
1517   bzero (reg_map, nregs * sizeof (rtx));
1518
1519   num_movables = 0;
1520
1521   for (m = movables; m; m = m->next)
1522     {
1523       /* Describe this movable insn.  */
1524
1525       if (loop_dump_stream)
1526         {
1527           fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1528                    INSN_UID (m->insn), m->regno, m->lifetime);
1529           if (m->consec > 0)
1530             fprintf (loop_dump_stream, "consec %d, ", m->consec);
1531           if (m->cond)
1532             fprintf (loop_dump_stream, "cond ");
1533           if (m->force)
1534             fprintf (loop_dump_stream, "force ");
1535           if (m->global)
1536             fprintf (loop_dump_stream, "global ");
1537           if (m->done)
1538             fprintf (loop_dump_stream, "done ");
1539           if (m->move_insn)
1540             fprintf (loop_dump_stream, "move-insn ");
1541           if (m->match)
1542             fprintf (loop_dump_stream, "matches %d ",
1543                      INSN_UID (m->match->insn));
1544           if (m->forces)
1545             fprintf (loop_dump_stream, "forces %d ",
1546                      INSN_UID (m->forces->insn));
1547         }
1548
1549       /* Count movables.  Value used in heuristics in strength_reduce.  */
1550       num_movables++;
1551
1552       /* Ignore the insn if it's already done (it matched something else).
1553          Otherwise, see if it is now safe to move.  */
1554
1555       if (!m->done
1556           && (! m->cond
1557               || (1 == invariant_p (m->set_src)
1558                   && (m->dependencies == 0
1559                       || 1 == invariant_p (m->dependencies))
1560                   && (m->consec == 0
1561                       || 1 == consec_sets_invariant_p (m->set_dest,
1562                                                        m->consec + 1,
1563                                                        m->insn))))
1564           && (! m->forces || m->forces->done))
1565         {
1566           register int regno;
1567           register rtx p;
1568           int savings = m->savings;
1569
1570           /* We have an insn that is safe to move.
1571              Compute its desirability.  */
1572
1573           p = m->insn;
1574           regno = m->regno;
1575
1576           if (loop_dump_stream)
1577             fprintf (loop_dump_stream, "savings %d ", savings);
1578
1579           if (moved_once[regno])
1580             {
1581               insn_count *= 2;
1582
1583               if (loop_dump_stream)
1584                 fprintf (loop_dump_stream, "halved since already moved ");
1585             }
1586
1587           /* An insn MUST be moved if we already moved something else
1588              which is safe only if this one is moved too: that is,
1589              if already_moved[REGNO] is nonzero.  */
1590
1591           /* An insn is desirable to move if the new lifetime of the
1592              register is no more than THRESHOLD times the old lifetime.
1593              If it's not desirable, it means the loop is so big
1594              that moving won't speed things up much,
1595              and it is liable to make register usage worse.  */
1596
1597           /* It is also desirable to move if it can be moved at no
1598              extra cost because something else was already moved.  */
1599
1600           if (already_moved[regno]
1601               || (threshold * savings * m->lifetime) >= insn_count
1602               || (m->forces && m->forces->done
1603                   && n_times_used[m->forces->regno] == 1))
1604             {
1605               int count;
1606               register struct movable *m1;
1607               rtx first;
1608
1609               /* Now move the insns that set the reg.  */
1610
1611               if (m->partial && m->match)
1612                 {
1613                   rtx newpat, i1;
1614                   rtx r1, r2;
1615                   /* Find the end of this chain of matching regs.
1616                      Thus, we load each reg in the chain from that one reg.
1617                      And that reg is loaded with 0 directly,
1618                      since it has ->match == 0.  */
1619                   for (m1 = m; m1->match; m1 = m1->match);
1620                   newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1621                                           SET_DEST (PATTERN (m1->insn)));
1622                   i1 = emit_insn_before (newpat, loop_start);
1623
1624                   /* Mark the moved, invariant reg as being allowed to
1625                      share a hard reg with the other matching invariant.  */
1626                   REG_NOTES (i1) = REG_NOTES (m->insn);
1627                   r1 = SET_DEST (PATTERN (m->insn));
1628                   r2 = SET_DEST (PATTERN (m1->insn));
1629                   regs_may_share = gen_rtx (EXPR_LIST, VOIDmode, r1,
1630                                             gen_rtx (EXPR_LIST, VOIDmode, r2,
1631                                                      regs_may_share));
1632                   delete_insn (m->insn);
1633
1634                   if (new_start == 0)
1635                     new_start = i1;
1636
1637                   if (loop_dump_stream)
1638                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1639                 }
1640               /* If we are to re-generate the item being moved with a
1641                  new move insn, first delete what we have and then emit
1642                  the move insn before the loop.  */
1643               else if (m->move_insn)
1644                 {
1645                   rtx i1, temp;
1646
1647                   for (count = m->consec; count >= 0; count--)
1648                     {
1649                       /* If this is the first insn of a library call sequence,
1650                          skip to the end.  */
1651                       if (GET_CODE (p) != NOTE
1652                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1653                         p = XEXP (temp, 0);
1654
1655                       /* If this is the last insn of a libcall sequence, then
1656                          delete every insn in the sequence except the last.
1657                          The last insn is handled in the normal manner.  */
1658                       if (GET_CODE (p) != NOTE
1659                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1660                         {
1661                           temp = XEXP (temp, 0);
1662                           while (temp != p)
1663                             temp = delete_insn (temp);
1664                         }
1665
1666                       p = delete_insn (p);
1667                     }
1668
1669                   start_sequence ();
1670                   emit_move_insn (m->set_dest, m->set_src);
1671                   temp = get_insns ();
1672                   end_sequence ();
1673
1674                   add_label_notes (m->set_src, temp);
1675
1676                   i1 = emit_insns_before (temp, loop_start);
1677                   if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
1678                     REG_NOTES (i1)
1679                       = gen_rtx (EXPR_LIST,
1680                                  m->is_equiv ? REG_EQUIV : REG_EQUAL,
1681                                  m->set_src, REG_NOTES (i1));
1682
1683                   if (loop_dump_stream)
1684                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1685
1686                   /* The more regs we move, the less we like moving them.  */
1687                   threshold -= 3;
1688                 }
1689               else
1690                 {
1691                   for (count = m->consec; count >= 0; count--)
1692                     {
1693                       rtx i1, temp;
1694
1695                       /* If first insn of libcall sequence, skip to end. */
1696                       /* Do this at start of loop, since p is guaranteed to 
1697                          be an insn here.  */
1698                       if (GET_CODE (p) != NOTE
1699                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1700                         p = XEXP (temp, 0);
1701
1702                       /* If last insn of libcall sequence, move all
1703                          insns except the last before the loop.  The last
1704                          insn is handled in the normal manner.  */
1705                       if (GET_CODE (p) != NOTE
1706                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1707                         {
1708                           rtx fn_address = 0;
1709                           rtx fn_reg = 0;
1710                           rtx fn_address_insn = 0;
1711
1712                           first = 0;
1713                           for (temp = XEXP (temp, 0); temp != p;
1714                                temp = NEXT_INSN (temp))
1715                             {
1716                               rtx body;
1717                               rtx n;
1718                               rtx next;
1719
1720                               if (GET_CODE (temp) == NOTE)
1721                                 continue;
1722
1723                               body = PATTERN (temp);
1724
1725                               /* Find the next insn after TEMP,
1726                                  not counting USE or NOTE insns.  */
1727                               for (next = NEXT_INSN (temp); next != p;
1728                                    next = NEXT_INSN (next))
1729                                 if (! (GET_CODE (next) == INSN
1730                                        && GET_CODE (PATTERN (next)) == USE)
1731                                     && GET_CODE (next) != NOTE)
1732                                   break;
1733                               
1734                               /* If that is the call, this may be the insn
1735                                  that loads the function address.
1736
1737                                  Extract the function address from the insn
1738                                  that loads it into a register.
1739                                  If this insn was cse'd, we get incorrect code.
1740
1741                                  So emit a new move insn that copies the
1742                                  function address into the register that the
1743                                  call insn will use.  flow.c will delete any
1744                                  redundant stores that we have created.  */
1745                               if (GET_CODE (next) == CALL_INSN
1746                                   && GET_CODE (body) == SET
1747                                   && GET_CODE (SET_DEST (body)) == REG
1748                                   && (n = find_reg_note (temp, REG_EQUAL,
1749                                                          NULL_RTX)))
1750                                 {
1751                                   fn_reg = SET_SRC (body);
1752                                   if (GET_CODE (fn_reg) != REG)
1753                                     fn_reg = SET_DEST (body);
1754                                   fn_address = XEXP (n, 0);
1755                                   fn_address_insn = temp;
1756                                 }
1757                               /* We have the call insn.
1758                                  If it uses the register we suspect it might,
1759                                  load it with the correct address directly.  */
1760                               if (GET_CODE (temp) == CALL_INSN
1761                                   && fn_address != 0
1762                                   && reg_referenced_p (fn_reg, body))
1763                                 emit_insn_after (gen_move_insn (fn_reg,
1764                                                                 fn_address),
1765                                                  fn_address_insn);
1766
1767                               if (GET_CODE (temp) == CALL_INSN)
1768                                 i1 = emit_call_insn_before (body, loop_start);
1769                               else
1770                                 i1 = emit_insn_before (body, loop_start);
1771                               if (first == 0)
1772                                 first = i1;
1773                               if (temp == fn_address_insn)
1774                                 fn_address_insn = i1;
1775                               REG_NOTES (i1) = REG_NOTES (temp);
1776                               delete_insn (temp);
1777                             }
1778                         }
1779                       if (m->savemode != VOIDmode)
1780                         {
1781                           /* P sets REG to zero; but we should clear only
1782                              the bits that are not covered by the mode
1783                              m->savemode.  */
1784                           rtx reg = m->set_dest;
1785                           rtx sequence;
1786                           rtx tem;
1787                       
1788                           start_sequence ();
1789                           tem = expand_binop
1790                             (GET_MODE (reg), and_optab, reg,
1791                              GEN_INT ((((HOST_WIDE_INT) 1
1792                                         << GET_MODE_BITSIZE (m->savemode)))
1793                                       - 1),
1794                              reg, 1, OPTAB_LIB_WIDEN);
1795                           if (tem == 0)
1796                             abort ();
1797                           if (tem != reg)
1798                             emit_move_insn (reg, tem);
1799                           sequence = gen_sequence ();
1800                           end_sequence ();
1801                           i1 = emit_insn_before (sequence, loop_start);
1802                         }
1803                       else if (GET_CODE (p) == CALL_INSN)
1804                         i1 = emit_call_insn_before (PATTERN (p), loop_start);
1805                       else
1806                         i1 = emit_insn_before (PATTERN (p), loop_start);
1807
1808                       REG_NOTES (i1) = REG_NOTES (p);
1809
1810                       if (new_start == 0)
1811                         new_start = i1;
1812
1813                       if (loop_dump_stream)
1814                         fprintf (loop_dump_stream, " moved to %d",
1815                                  INSN_UID (i1));
1816
1817 #if 0
1818                       /* This isn't needed because REG_NOTES is copied
1819                          below and is wrong since P might be a PARALLEL.  */
1820                       if (REG_NOTES (i1) == 0
1821                           && ! m->partial /* But not if it's a zero-extend clr. */
1822                           && ! m->global /* and not if used outside the loop
1823                                             (since it might get set outside).  */
1824                           && CONSTANT_P (SET_SRC (PATTERN (p))))
1825                         REG_NOTES (i1)
1826                           = gen_rtx (EXPR_LIST, REG_EQUAL,
1827                                      SET_SRC (PATTERN (p)), REG_NOTES (i1));
1828 #endif
1829
1830                       /* If library call, now fix the REG_NOTES that contain
1831                          insn pointers, namely REG_LIBCALL on FIRST
1832                          and REG_RETVAL on I1.  */
1833                       if (temp = find_reg_note (i1, REG_RETVAL, NULL_RTX))
1834                         {
1835                           XEXP (temp, 0) = first;
1836                           temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
1837                           XEXP (temp, 0) = i1;
1838                         }
1839
1840                       delete_insn (p);
1841                       do p = NEXT_INSN (p);
1842                       while (p && GET_CODE (p) == NOTE);
1843                     }
1844
1845                   /* The more regs we move, the less we like moving them.  */
1846                   threshold -= 3;
1847                 }
1848
1849               /* Any other movable that loads the same register
1850                  MUST be moved.  */
1851               already_moved[regno] = 1;
1852
1853               /* This reg has been moved out of one loop.  */
1854               moved_once[regno] = 1;
1855
1856               /* The reg set here is now invariant.  */
1857               if (! m->partial)
1858                 n_times_set[regno] = 0;
1859
1860               m->done = 1;
1861
1862               /* Change the length-of-life info for the register
1863                  to say it lives at least the full length of this loop.
1864                  This will help guide optimizations in outer loops.  */
1865
1866               if (uid_luid[regno_first_uid[regno]] > INSN_LUID (loop_start))
1867                 /* This is the old insn before all the moved insns.
1868                    We can't use the moved insn because it is out of range
1869                    in uid_luid.  Only the old insns have luids.  */
1870                 regno_first_uid[regno] = INSN_UID (loop_start);
1871               if (uid_luid[regno_last_uid[regno]] < INSN_LUID (end))
1872                 regno_last_uid[regno] = INSN_UID (end);
1873
1874               /* Combine with this moved insn any other matching movables.  */
1875
1876               if (! m->partial)
1877                 for (m1 = movables; m1; m1 = m1->next)
1878                   if (m1->match == m)
1879                     {
1880                       rtx temp;
1881
1882                       /* Schedule the reg loaded by M1
1883                          for replacement so that shares the reg of M.
1884                          If the modes differ (only possible in restricted
1885                          circumstances, make a SUBREG.  */
1886                       if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
1887                         reg_map[m1->regno] = m->set_dest;
1888                       else
1889                         reg_map[m1->regno]
1890                           = gen_lowpart_common (GET_MODE (m1->set_dest),
1891                                                 m->set_dest);
1892                     
1893                       /* Get rid of the matching insn
1894                          and prevent further processing of it.  */
1895                       m1->done = 1;
1896
1897                       /* if library call, delete all insn except last, which
1898                          is deleted below */
1899                       if (temp = find_reg_note (m1->insn, REG_RETVAL,
1900                                                 NULL_RTX))
1901                         {
1902                           for (temp = XEXP (temp, 0); temp != m1->insn;
1903                                temp = NEXT_INSN (temp))
1904                             delete_insn (temp);
1905                         }
1906                       delete_insn (m1->insn);
1907
1908                       /* Any other movable that loads the same register
1909                          MUST be moved.  */
1910                       already_moved[m1->regno] = 1;
1911
1912                       /* The reg merged here is now invariant,
1913                          if the reg it matches is invariant.  */
1914                       if (! m->partial)
1915                         n_times_set[m1->regno] = 0;
1916                     }
1917             }
1918           else if (loop_dump_stream)
1919             fprintf (loop_dump_stream, "not desirable");
1920         }
1921       else if (loop_dump_stream && !m->match)
1922         fprintf (loop_dump_stream, "not safe");
1923
1924       if (loop_dump_stream)
1925         fprintf (loop_dump_stream, "\n");
1926     }
1927
1928   if (new_start == 0)
1929     new_start = loop_start;
1930
1931   /* Go through all the instructions in the loop, making
1932      all the register substitutions scheduled in REG_MAP.  */
1933   for (p = new_start; p != end; p = NEXT_INSN (p))
1934     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1935         || GET_CODE (p) == CALL_INSN)
1936       {
1937         replace_regs (PATTERN (p), reg_map, nregs, 0);
1938         replace_regs (REG_NOTES (p), reg_map, nregs, 0);
1939       }
1940 }
1941 \f
1942 #if 0
1943 /* Scan X and replace the address of any MEM in it with ADDR.
1944    REG is the address that MEM should have before the replacement.  */
1945
1946 static void
1947 replace_call_address (x, reg, addr)
1948      rtx x, reg, addr;
1949 {
1950   register enum rtx_code code;
1951   register int i;
1952   register char *fmt;
1953
1954   if (x == 0)
1955     return;
1956   code = GET_CODE (x);
1957   switch (code)
1958     {
1959     case PC:
1960     case CC0:
1961     case CONST_INT:
1962     case CONST_DOUBLE:
1963     case CONST:
1964     case SYMBOL_REF:
1965     case LABEL_REF:
1966     case REG:
1967       return;
1968
1969     case SET:
1970       /* Short cut for very common case.  */
1971       replace_call_address (XEXP (x, 1), reg, addr);
1972       return;
1973
1974     case CALL:
1975       /* Short cut for very common case.  */
1976       replace_call_address (XEXP (x, 0), reg, addr);
1977       return;
1978
1979     case MEM:
1980       /* If this MEM uses a reg other than the one we expected,
1981          something is wrong.  */
1982       if (XEXP (x, 0) != reg)
1983         abort ();
1984       XEXP (x, 0) = addr;
1985       return;
1986     }
1987
1988   fmt = GET_RTX_FORMAT (code);
1989   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1990     {
1991       if (fmt[i] == 'e')
1992         replace_call_address (XEXP (x, i), reg, addr);
1993       if (fmt[i] == 'E')
1994         {
1995           register int j;
1996           for (j = 0; j < XVECLEN (x, i); j++)
1997             replace_call_address (XVECEXP (x, i, j), reg, addr);
1998         }
1999     }
2000 }
2001 #endif
2002 \f
2003 /* Return the number of memory refs to addresses that vary
2004    in the rtx X.  */
2005
2006 static int
2007 count_nonfixed_reads (x)
2008      rtx x;
2009 {
2010   register enum rtx_code code;
2011   register int i;
2012   register char *fmt;
2013   int value;
2014
2015   if (x == 0)
2016     return 0;
2017
2018   code = GET_CODE (x);
2019   switch (code)
2020     {
2021     case PC:
2022     case CC0:
2023     case CONST_INT:
2024     case CONST_DOUBLE:
2025     case CONST:
2026     case SYMBOL_REF:
2027     case LABEL_REF:
2028     case REG:
2029       return 0;
2030
2031     case MEM:
2032       return ((invariant_p (XEXP (x, 0)) != 1)
2033               + count_nonfixed_reads (XEXP (x, 0)));
2034     }
2035
2036   value = 0;
2037   fmt = GET_RTX_FORMAT (code);
2038   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2039     {
2040       if (fmt[i] == 'e')
2041         value += count_nonfixed_reads (XEXP (x, i));
2042       if (fmt[i] == 'E')
2043         {
2044           register int j;
2045           for (j = 0; j < XVECLEN (x, i); j++)
2046             value += count_nonfixed_reads (XVECEXP (x, i, j));
2047         }
2048     }
2049   return value;
2050 }
2051
2052 \f
2053 #if 0
2054 /* P is an instruction that sets a register to the result of a ZERO_EXTEND.
2055    Replace it with an instruction to load just the low bytes
2056    if the machine supports such an instruction,
2057    and insert above LOOP_START an instruction to clear the register.  */
2058
2059 static void
2060 constant_high_bytes (p, loop_start)
2061      rtx p, loop_start;
2062 {
2063   register rtx new;
2064   register int insn_code_number;
2065
2066   /* Try to change (SET (REG ...) (ZERO_EXTEND (..:B ...)))
2067      to (SET (STRICT_LOW_PART (SUBREG:B (REG...))) ...).  */
2068
2069   new = gen_rtx (SET, VOIDmode,
2070                  gen_rtx (STRICT_LOW_PART, VOIDmode,
2071                           gen_rtx (SUBREG, GET_MODE (XEXP (SET_SRC (PATTERN (p)), 0)),
2072                                    SET_DEST (PATTERN (p)),
2073                                    0)),
2074                  XEXP (SET_SRC (PATTERN (p)), 0));
2075   insn_code_number = recog (new, p);
2076
2077   if (insn_code_number)
2078     {
2079       register int i;
2080
2081       /* Clear destination register before the loop.  */
2082       emit_insn_before (gen_rtx (SET, VOIDmode,
2083                                  SET_DEST (PATTERN (p)),
2084                                  const0_rtx),
2085                         loop_start);
2086
2087       /* Inside the loop, just load the low part.  */
2088       PATTERN (p) = new;
2089     }
2090 }
2091 #endif
2092 \f
2093 /* Scan a loop setting the variables `unknown_address_altered',
2094    `num_mem_sets', `loop_continue', loops_enclosed', `loop_has_call',
2095    and `loop_has_volatile'.
2096    Also, fill in the array `loop_store_mems'.  */
2097
2098 static void
2099 prescan_loop (start, end)
2100      rtx start, end;
2101 {
2102   register int level = 1;
2103   register rtx insn;
2104
2105   unknown_address_altered = 0;
2106   loop_has_call = 0;
2107   loop_has_volatile = 0;
2108   loop_store_mems_idx = 0;
2109
2110   num_mem_sets = 0;
2111   loops_enclosed = 1;
2112   loop_continue = 0;
2113
2114   for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2115        insn = NEXT_INSN (insn))
2116     {
2117       if (GET_CODE (insn) == NOTE)
2118         {
2119           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2120             {
2121               ++level;
2122               /* Count number of loops contained in this one.  */
2123               loops_enclosed++;
2124             }
2125           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2126             {
2127               --level;
2128               if (level == 0)
2129                 {
2130                   end = insn;
2131                   break;
2132                 }
2133             }
2134           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_CONT)
2135             {
2136               if (level == 1)
2137                 loop_continue = insn;
2138             }
2139         }
2140       else if (GET_CODE (insn) == CALL_INSN)
2141         {
2142           unknown_address_altered = 1;
2143           loop_has_call = 1;
2144         }
2145       else
2146         {
2147           if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
2148             {
2149               if (volatile_refs_p (PATTERN (insn)))
2150                 loop_has_volatile = 1;
2151
2152               note_stores (PATTERN (insn), note_addr_stored);
2153             }
2154         }
2155     }
2156 }
2157 \f
2158 /* Scan the function looking for loops.  Record the start and end of each loop.
2159    Also mark as invalid loops any loops that contain a setjmp or are branched
2160    to from outside the loop.  */
2161
2162 static void
2163 find_and_verify_loops (f)
2164      rtx f;
2165 {
2166   rtx insn;
2167   int current_loop = -1;
2168   int next_loop = -1;
2169   int loop;
2170
2171   /* If there are jumps to undefined labels,
2172      treat them as jumps out of any/all loops.
2173      This also avoids writing past end of tables when there are no loops.  */
2174   uid_loop_num[0] = -1;
2175
2176   /* Find boundaries of loops, mark which loops are contained within
2177      loops, and invalidate loops that have setjmp.  */
2178
2179   for (insn = f; insn; insn = NEXT_INSN (insn))
2180     {
2181       if (GET_CODE (insn) == NOTE)
2182         switch (NOTE_LINE_NUMBER (insn))
2183           {
2184           case NOTE_INSN_LOOP_BEG:
2185             loop_number_loop_starts[++next_loop] =  insn;
2186             loop_number_loop_ends[next_loop] = 0;
2187             loop_outer_loop[next_loop] = current_loop;
2188             loop_invalid[next_loop] = 0;
2189             loop_number_exit_labels[next_loop] = 0;
2190             current_loop = next_loop;
2191             break;
2192
2193           case NOTE_INSN_SETJMP:
2194             /* In this case, we must invalidate our current loop and any
2195                enclosing loop.  */
2196             for (loop = current_loop; loop != -1; loop = loop_outer_loop[loop])
2197               {
2198                 loop_invalid[loop] = 1;
2199                 if (loop_dump_stream)
2200                   fprintf (loop_dump_stream,
2201                            "\nLoop at %d ignored due to setjmp.\n",
2202                            INSN_UID (loop_number_loop_starts[loop]));
2203               }
2204             break;
2205
2206           case NOTE_INSN_LOOP_END:
2207             if (current_loop == -1)
2208               abort ();
2209
2210             loop_number_loop_ends[current_loop] = insn;
2211             current_loop = loop_outer_loop[current_loop];
2212             break;
2213
2214           }
2215
2216       /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2217          enclosing loop, but this doesn't matter.  */
2218       uid_loop_num[INSN_UID (insn)] = current_loop;
2219     }
2220
2221   /* Now scan all JUMP_INSN's in the function.  If any branches into a loop
2222      that it is not contained within, that loop is marked invalid.
2223
2224      Also look for blocks of code ending in an unconditional branch that
2225      exits the loop.  If such a block is surrounded by a conditional 
2226      branch around the block, move the block elsewhere (see below) and
2227      invert the jump to point to the code block.  This may eliminate a
2228      label in our loop and will simplify processing by both us and a
2229      possible second cse pass.  */
2230
2231   for (insn = f; insn; insn = NEXT_INSN (insn))
2232     if (GET_CODE (insn) == JUMP_INSN)
2233       {
2234         int this_loop_num = uid_loop_num[INSN_UID (insn)];
2235
2236         mark_loop_jump (PATTERN (insn), this_loop_num);
2237
2238         /* See if this is an unconditional branch outside the loop.  */
2239         if (this_loop_num != -1
2240             && (GET_CODE (PATTERN (insn)) == RETURN
2241                 || (simplejump_p (insn)
2242                     && (uid_loop_num[INSN_UID (JUMP_LABEL (insn))]
2243                         != this_loop_num))))
2244           {
2245             rtx p;
2246             rtx our_next = next_real_insn (insn);
2247
2248             /* Go backwards until we reach the start of the loop, a label,
2249                or a JUMP_INSN.  */
2250             for (p = PREV_INSN (insn);
2251                  GET_CODE (p) != CODE_LABEL
2252                  && ! (GET_CODE (p) == NOTE
2253                        && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2254                  && GET_CODE (p) != JUMP_INSN;
2255                  p = PREV_INSN (p))
2256               ;
2257
2258             /* If we stopped on a JUMP_INSN to the next insn after INSN,
2259                we have a block of code to try to move.
2260
2261                We look backward and then forward from the target of INSN
2262                to find a BARRIER at the same loop depth as the target.
2263                If we find such a BARRIER, we make a new label for the start
2264                of the block, invert the jump in P and point it to that label,
2265                and move the block of code to the spot we found.  */
2266
2267             if (GET_CODE (p) == JUMP_INSN
2268                 && JUMP_LABEL (p) != 0
2269                 /* Just ignore jumps to labels that were never emitted.
2270                    These always indicate compilation errors.  */
2271                 && INSN_UID (JUMP_LABEL (p)) != 0
2272                 && condjump_p (p)
2273                 && ! simplejump_p (p)
2274                 && next_real_insn (JUMP_LABEL (p)) == our_next)
2275               {
2276                 rtx target
2277                   = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2278                 int target_loop_num = uid_loop_num[INSN_UID (target)];
2279                 rtx loc;
2280
2281                 for (loc = target; loc; loc = PREV_INSN (loc))
2282                   if (GET_CODE (loc) == BARRIER
2283                       && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2284                     break;
2285
2286                 if (loc == 0)
2287                   for (loc = target; loc; loc = NEXT_INSN (loc))
2288                     if (GET_CODE (loc) == BARRIER
2289                         && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2290                       break;
2291
2292                 if (loc)
2293                   {
2294                     rtx cond_label = JUMP_LABEL (p);
2295                     rtx new_label = get_label_after (p);
2296
2297                     /* Ensure our label doesn't go away.  */
2298                     LABEL_NUSES (cond_label)++;
2299
2300                     /* Verify that uid_loop_num is large enough and that
2301                        we can invert P. */
2302                    if (INSN_UID (new_label) < max_uid_for_loop
2303                        && invert_jump (p, new_label))
2304                      {
2305                        rtx q, r;
2306
2307                        /* Include the BARRIER after INSN and copy the
2308                           block after LOC.  */
2309                        new_label = squeeze_notes (new_label, NEXT_INSN (insn));
2310                        reorder_insns (new_label, NEXT_INSN (insn), loc);
2311
2312                        /* All those insns are now in TARGET_LOOP_NUM.  */
2313                        for (q = new_label; q != NEXT_INSN (NEXT_INSN (insn));
2314                             q = NEXT_INSN (q))
2315                          uid_loop_num[INSN_UID (q)] = target_loop_num;
2316
2317                        /* The label jumped to by INSN is no longer a loop exit.
2318                           Unless INSN does not have a label (e.g., it is a
2319                           RETURN insn), search loop_number_exit_labels to find
2320                           its label_ref, and remove it.  Also turn off
2321                           LABEL_OUTSIDE_LOOP_P bit.  */
2322                        if (JUMP_LABEL (insn))
2323                          {
2324                            for (q = 0,
2325                                 r = loop_number_exit_labels[this_loop_num];
2326                                 r; q = r, r = LABEL_NEXTREF (r))
2327                              if (XEXP (r, 0) == JUMP_LABEL (insn))
2328                                {
2329                                  LABEL_OUTSIDE_LOOP_P (r) = 0;
2330                                  if (q)
2331                                    LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2332                                  else
2333                                    loop_number_exit_labels[this_loop_num]
2334                                      = LABEL_NEXTREF (r);
2335                                  break;
2336                                }
2337
2338                            /* If we didn't find it, then something is wrong. */
2339                            if (! r)
2340                              abort ();
2341                          }
2342
2343                        /* P is now a jump outside the loop, so it must be put
2344                           in loop_number_exit_labels, and marked as such.
2345                           The easiest way to do this is to just call
2346                           mark_loop_jump again for P.  */
2347                        mark_loop_jump (PATTERN (p), this_loop_num);
2348
2349                        /* If INSN now jumps to the insn after it,
2350                           delete INSN.  */
2351                        if (JUMP_LABEL (insn) != 0
2352                            && (next_real_insn (JUMP_LABEL (insn))
2353                                == next_real_insn (insn)))
2354                          delete_insn (insn);
2355                      }
2356
2357                     /* Continue the loop after where the conditional
2358                        branch used to jump, since the only branch insn
2359                        in the block (if it still remains) is an inter-loop
2360                        branch and hence needs no processing.  */
2361                     insn = NEXT_INSN (cond_label);
2362
2363                     if (--LABEL_NUSES (cond_label) == 0)
2364                       delete_insn (cond_label);
2365                   }
2366               }
2367           }
2368       }
2369 }
2370
2371 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
2372    loops it is contained in, mark the target loop invalid.
2373
2374    For speed, we assume that X is part of a pattern of a JUMP_INSN.  */
2375
2376 static void
2377 mark_loop_jump (x, loop_num)
2378      rtx x;
2379      int loop_num;
2380 {
2381   int dest_loop;
2382   int outer_loop;
2383   int i;
2384
2385   switch (GET_CODE (x))
2386     {
2387     case PC:
2388     case USE:
2389     case CLOBBER:
2390     case REG:
2391     case MEM:
2392     case CONST_INT:
2393     case CONST_DOUBLE:
2394     case RETURN:
2395       return;
2396
2397     case CONST:
2398       /* There could be a label reference in here.  */
2399       mark_loop_jump (XEXP (x, 0), loop_num);
2400       return;
2401
2402     case PLUS:
2403     case MINUS:
2404     case MULT:
2405     case LSHIFT:
2406       mark_loop_jump (XEXP (x, 0), loop_num);
2407       mark_loop_jump (XEXP (x, 1), loop_num);
2408       return;
2409
2410     case SIGN_EXTEND:
2411     case ZERO_EXTEND:
2412       mark_loop_jump (XEXP (x, 0), loop_num);
2413       return;
2414
2415     case LABEL_REF:
2416       dest_loop = uid_loop_num[INSN_UID (XEXP (x, 0))];
2417
2418       /* Link together all labels that branch outside the loop.  This
2419          is used by final_[bg]iv_value and the loop unrolling code.  Also
2420          mark this LABEL_REF so we know that this branch should predict
2421          false.  */
2422
2423       if (dest_loop != loop_num && loop_num != -1)
2424         {
2425           LABEL_OUTSIDE_LOOP_P (x) = 1;
2426           LABEL_NEXTREF (x) = loop_number_exit_labels[loop_num];
2427           loop_number_exit_labels[loop_num] = x;
2428         }
2429
2430       /* If this is inside a loop, but not in the current loop or one enclosed
2431          by it, it invalidates at least one loop.  */
2432
2433       if (dest_loop == -1)
2434         return;
2435
2436       /* We must invalidate every nested loop containing the target of this
2437          label, except those that also contain the jump insn.  */
2438
2439       for (; dest_loop != -1; dest_loop = loop_outer_loop[dest_loop])
2440         {
2441           /* Stop when we reach a loop that also contains the jump insn.  */
2442           for (outer_loop = loop_num; outer_loop != -1;
2443                outer_loop = loop_outer_loop[outer_loop])
2444             if (dest_loop == outer_loop)
2445               return;
2446
2447           /* If we get here, we know we need to invalidate a loop.  */
2448           if (loop_dump_stream && ! loop_invalid[dest_loop])
2449             fprintf (loop_dump_stream,
2450                      "\nLoop at %d ignored due to multiple entry points.\n",
2451                      INSN_UID (loop_number_loop_starts[dest_loop]));
2452           
2453           loop_invalid[dest_loop] = 1;
2454         }
2455       return;
2456
2457     case SET:
2458       /* If this is not setting pc, ignore.  */
2459       if (SET_DEST (x) == pc_rtx)
2460         mark_loop_jump (SET_SRC (x), loop_num);
2461       return;
2462
2463     case IF_THEN_ELSE:
2464       mark_loop_jump (XEXP (x, 1), loop_num);
2465       mark_loop_jump (XEXP (x, 2), loop_num);
2466       return;
2467
2468     case PARALLEL:
2469     case ADDR_VEC:
2470       for (i = 0; i < XVECLEN (x, 0); i++)
2471         mark_loop_jump (XVECEXP (x, 0, i), loop_num);
2472       return;
2473
2474     case ADDR_DIFF_VEC:
2475       for (i = 0; i < XVECLEN (x, 1); i++)
2476         mark_loop_jump (XVECEXP (x, 1, i), loop_num);
2477       return;
2478
2479     default:
2480       /* Nothing else should occur in a JUMP_INSN.  */
2481       abort ();
2482     }
2483 }
2484 \f
2485 /* Return nonzero if there is a label in the range from
2486    insn INSN to and including the insn whose luid is END
2487    INSN must have an assigned luid (i.e., it must not have
2488    been previously created by loop.c).  */
2489
2490 static int
2491 labels_in_range_p (insn, end)
2492      rtx insn;
2493      int end;
2494 {
2495   while (insn && INSN_LUID (insn) <= end)
2496     {
2497       if (GET_CODE (insn) == CODE_LABEL)
2498         return 1;
2499       insn = NEXT_INSN (insn);
2500     }
2501
2502   return 0;
2503 }
2504
2505 /* Record that a memory reference X is being set.  */
2506
2507 static void
2508 note_addr_stored (x)
2509      rtx x;
2510 {
2511   register int i;
2512
2513   if (x == 0 || GET_CODE (x) != MEM)
2514     return;
2515
2516   /* Count number of memory writes.
2517      This affects heuristics in strength_reduce.  */
2518   num_mem_sets++;
2519
2520   if (unknown_address_altered)
2521     return;
2522
2523   for (i = 0; i < loop_store_mems_idx; i++)
2524     if (rtx_equal_p (XEXP (loop_store_mems[i], 0), XEXP (x, 0))
2525         && MEM_IN_STRUCT_P (x) == MEM_IN_STRUCT_P (loop_store_mems[i]))
2526       {
2527         /* We are storing at the same address as previously noted.  Save the
2528            wider reference, treating BLKmode as wider.  */
2529         if (GET_MODE (x) == BLKmode
2530             || (GET_MODE_SIZE (GET_MODE (x))
2531                 > GET_MODE_SIZE (GET_MODE (loop_store_mems[i]))))
2532           loop_store_mems[i] = x;
2533         break;
2534       }
2535
2536   if (i == NUM_STORES)
2537     unknown_address_altered = 1;
2538
2539   else if (i == loop_store_mems_idx)
2540     loop_store_mems[loop_store_mems_idx++] = x;
2541 }
2542 \f
2543 /* Return nonzero if the rtx X is invariant over the current loop.
2544
2545    The value is 2 if we refer to something only conditionally invariant.
2546
2547    If `unknown_address_altered' is nonzero, no memory ref is invariant.
2548    Otherwise, a memory ref is invariant if it does not conflict with
2549    anything stored in `loop_store_mems'.  */
2550
2551 int
2552 invariant_p (x)
2553      register rtx x;
2554 {
2555   register int i;
2556   register enum rtx_code code;
2557   register char *fmt;
2558   int conditional = 0;
2559
2560   if (x == 0)
2561     return 1;
2562   code = GET_CODE (x);
2563   switch (code)
2564     {
2565     case CONST_INT:
2566     case CONST_DOUBLE:
2567     case SYMBOL_REF:
2568     case CONST:
2569       return 1;
2570
2571     case LABEL_REF:
2572       /* A LABEL_REF is normally invariant, however, if we are unrolling
2573          loops, and this label is inside the loop, then it isn't invariant.
2574          This is because each unrolled copy of the loop body will have
2575          a copy of this label.  If this was invariant, then an insn loading
2576          the address of this label into a register might get moved outside
2577          the loop, and then each loop body would end up using the same label.
2578
2579          We don't know the loop bounds here though, so just fail for all
2580          labels.  */
2581       if (flag_unroll_loops)
2582         return 0;
2583       else
2584         return 1;
2585
2586     case PC:
2587     case CC0:
2588     case UNSPEC_VOLATILE:
2589       return 0;
2590
2591     case REG:
2592       /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
2593          since the reg might be set by initialization within the loop.  */
2594       if (x == frame_pointer_rtx || x == arg_pointer_rtx)
2595         return 1;
2596       if (loop_has_call
2597           && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
2598         return 0;
2599       if (n_times_set[REGNO (x)] < 0)
2600         return 2;
2601       return n_times_set[REGNO (x)] == 0;
2602
2603     case MEM:
2604       /* Read-only items (such as constants in a constant pool) are
2605          invariant if their address is.  */
2606       if (RTX_UNCHANGING_P (x))
2607         break;
2608
2609       /* If we filled the table (or had a subroutine call), any location
2610          in memory could have been clobbered.  */
2611       if (unknown_address_altered
2612           /* Don't mess with volatile memory references.  */
2613           || MEM_VOLATILE_P (x))
2614         return 0;
2615
2616       /* See if there is any dependence between a store and this load.  */
2617       for (i = loop_store_mems_idx - 1; i >= 0; i--)
2618         if (true_dependence (loop_store_mems[i], x))
2619           return 0;
2620
2621       /* It's not invalidated by a store in memory
2622          but we must still verify the address is invariant.  */
2623       break;
2624
2625     case ASM_OPERANDS:
2626       /* Don't mess with insns declared volatile.  */
2627       if (MEM_VOLATILE_P (x))
2628         return 0;
2629     }
2630
2631   fmt = GET_RTX_FORMAT (code);
2632   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2633     {
2634       if (fmt[i] == 'e')
2635         {
2636           int tem = invariant_p (XEXP (x, i));
2637           if (tem == 0)
2638             return 0;
2639           if (tem == 2)
2640             conditional = 1;
2641         }
2642       else if (fmt[i] == 'E')
2643         {
2644           register int j;
2645           for (j = 0; j < XVECLEN (x, i); j++)
2646             {
2647               int tem = invariant_p (XVECEXP (x, i, j));
2648               if (tem == 0)
2649                 return 0;
2650               if (tem == 2)
2651                 conditional = 1;
2652             }
2653
2654         }
2655     }
2656
2657   return 1 + conditional;
2658 }
2659
2660 /* Return 1 if OTHER (a mem ref) overlaps the area of memory
2661    which is SIZE bytes starting at BASE.  */
2662
2663 int
2664 addr_overlap_p (other, base, size)
2665      rtx other;
2666      rtx base;
2667      HOST_WIDE_INT size;
2668 {
2669   HOST_WIDE_INT start = 0, end;
2670
2671   if (GET_CODE (base) == CONST)
2672     base = XEXP (base, 0);
2673   if (GET_CODE (base) == PLUS
2674       && GET_CODE (XEXP (base, 1)) == CONST_INT)
2675     {
2676       start = INTVAL (XEXP (base, 1));
2677       base = XEXP (base, 0);
2678     }
2679
2680   end = start + size;
2681   return refers_to_mem_p (other, base, start, end);
2682 }
2683 \f
2684 /* Return nonzero if all the insns in the loop that set REG
2685    are INSN and the immediately following insns,
2686    and if each of those insns sets REG in an invariant way
2687    (not counting uses of REG in them).
2688
2689    The value is 2 if some of these insns are only conditionally invariant.
2690
2691    We assume that INSN itself is the first set of REG
2692    and that its source is invariant.  */
2693
2694 static int
2695 consec_sets_invariant_p (reg, n_sets, insn)
2696      int n_sets;
2697      rtx reg, insn;
2698 {
2699   register rtx p = insn;
2700   register int regno = REGNO (reg);
2701   rtx temp;
2702   /* Number of sets we have to insist on finding after INSN.  */
2703   int count = n_sets - 1;
2704   int old = n_times_set[regno];
2705   int value = 0;
2706   int this;
2707
2708   /* If N_SETS hit the limit, we can't rely on its value.  */
2709   if (n_sets == 127)
2710     return 0;
2711
2712   n_times_set[regno] = 0;
2713
2714   while (count > 0)
2715     {
2716       register enum rtx_code code;
2717       rtx set;
2718
2719       p = NEXT_INSN (p);
2720       code = GET_CODE (p);
2721
2722       /* If library call, skip to end of of it.  */
2723       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
2724         p = XEXP (temp, 0);
2725
2726       this = 0;
2727       if (code == INSN
2728           && (set = single_set (p))
2729           && GET_CODE (SET_DEST (set)) == REG
2730           && REGNO (SET_DEST (set)) == regno)
2731         {
2732           this = invariant_p (SET_SRC (set));
2733           if (this != 0)
2734             value |= this;
2735           else if (temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
2736             {
2737               this = invariant_p (XEXP (temp, 0));
2738               if (this != 0)
2739                 value |= this;
2740             }
2741         }
2742       if (this != 0)
2743         count--;
2744       else if (code != NOTE)
2745         {
2746           n_times_set[regno] = old;
2747           return 0;
2748         }
2749     }
2750
2751   n_times_set[regno] = old;
2752   /* If invariant_p ever returned 2, we return 2.  */
2753   return 1 + (value & 2);
2754 }
2755
2756 #if 0
2757 /* I don't think this condition is sufficient to allow INSN
2758    to be moved, so we no longer test it.  */
2759
2760 /* Return 1 if all insns in the basic block of INSN and following INSN
2761    that set REG are invariant according to TABLE.  */
2762
2763 static int
2764 all_sets_invariant_p (reg, insn, table)
2765      rtx reg, insn;
2766      short *table;
2767 {
2768   register rtx p = insn;
2769   register int regno = REGNO (reg);
2770
2771   while (1)
2772     {
2773       register enum rtx_code code;
2774       p = NEXT_INSN (p);
2775       code = GET_CODE (p);
2776       if (code == CODE_LABEL || code == JUMP_INSN)
2777         return 1;
2778       if (code == INSN && GET_CODE (PATTERN (p)) == SET
2779           && GET_CODE (SET_DEST (PATTERN (p))) == REG
2780           && REGNO (SET_DEST (PATTERN (p))) == regno)
2781         {
2782           if (!invariant_p (SET_SRC (PATTERN (p)), table))
2783             return 0;
2784         }
2785     }
2786 }
2787 #endif /* 0 */
2788 \f
2789 /* Look at all uses (not sets) of registers in X.  For each, if it is
2790    the single use, set USAGE[REGNO] to INSN; if there was a previous use in
2791    a different insn, set USAGE[REGNO] to const0_rtx.  */
2792
2793 static void
2794 find_single_use_in_loop (insn, x, usage)
2795      rtx insn;
2796      rtx x;
2797      rtx *usage;
2798 {
2799   enum rtx_code code = GET_CODE (x);
2800   char *fmt = GET_RTX_FORMAT (code);
2801   int i, j;
2802
2803   if (code == REG)
2804     usage[REGNO (x)]
2805       = (usage[REGNO (x)] != 0 && usage[REGNO (x)] != insn)
2806         ? const0_rtx : insn;
2807
2808   else if (code == SET)
2809     {
2810       /* Don't count SET_DEST if it is a REG; otherwise count things
2811          in SET_DEST because if a register is partially modified, it won't
2812          show up as a potential movable so we don't care how USAGE is set 
2813          for it.  */
2814       if (GET_CODE (SET_DEST (x)) != REG)
2815         find_single_use_in_loop (insn, SET_DEST (x), usage);
2816       find_single_use_in_loop (insn, SET_SRC (x), usage);
2817     }
2818   else
2819     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2820       {
2821         if (fmt[i] == 'e' && XEXP (x, i) != 0)
2822           find_single_use_in_loop (insn, XEXP (x, i), usage);
2823         else if (fmt[i] == 'E')
2824           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
2825             find_single_use_in_loop (insn, XVECEXP (x, i, j), usage);
2826       }
2827 }
2828 \f
2829 /* Increment N_TIMES_SET at the index of each register
2830    that is modified by an insn between FROM and TO.
2831    If the value of an element of N_TIMES_SET becomes 127 or more,
2832    stop incrementing it, to avoid overflow.
2833
2834    Store in SINGLE_USAGE[I] the single insn in which register I is
2835    used, if it is only used once.  Otherwise, it is set to 0 (for no
2836    uses) or const0_rtx for more than one use.  This parameter may be zero,
2837    in which case this processing is not done.
2838
2839    Store in *COUNT_PTR the number of actual instruction
2840    in the loop.  We use this to decide what is worth moving out.  */
2841
2842 /* last_set[n] is nonzero iff reg n has been set in the current basic block.
2843    In that case, it is the insn that last set reg n.  */
2844
2845 static void
2846 count_loop_regs_set (from, to, may_not_move, single_usage, count_ptr, nregs)
2847      register rtx from, to;
2848      char *may_not_move;
2849      rtx *single_usage;
2850      int *count_ptr;
2851      int nregs;
2852 {
2853   register rtx *last_set = (rtx *) alloca (nregs * sizeof (rtx));
2854   register rtx insn;
2855   register int count = 0;
2856   register rtx dest;
2857
2858   bzero (last_set, nregs * sizeof (rtx));
2859   for (insn = from; insn != to; insn = NEXT_INSN (insn))
2860     {
2861       if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
2862         {
2863           ++count;
2864
2865           /* If requested, record registers that have exactly one use.  */
2866           if (single_usage)
2867             {
2868               find_single_use_in_loop (insn, PATTERN (insn), single_usage);
2869
2870               /* Include uses in REG_EQUAL notes.  */
2871               if (REG_NOTES (insn))
2872                 find_single_use_in_loop (insn, REG_NOTES (insn), single_usage);
2873             }
2874
2875           if (GET_CODE (PATTERN (insn)) == CLOBBER
2876               && GET_CODE (XEXP (PATTERN (insn), 0)) == REG)
2877             /* Don't move a reg that has an explicit clobber.
2878                We might do so sometimes, but it's not worth the pain.  */
2879             may_not_move[REGNO (XEXP (PATTERN (insn), 0))] = 1;
2880
2881           if (GET_CODE (PATTERN (insn)) == SET
2882               || GET_CODE (PATTERN (insn)) == CLOBBER)
2883             {
2884               dest = SET_DEST (PATTERN (insn));
2885               while (GET_CODE (dest) == SUBREG
2886                      || GET_CODE (dest) == ZERO_EXTRACT
2887                      || GET_CODE (dest) == SIGN_EXTRACT
2888                      || GET_CODE (dest) == STRICT_LOW_PART)
2889                 dest = XEXP (dest, 0);
2890               if (GET_CODE (dest) == REG)
2891                 {
2892                   register int regno = REGNO (dest);
2893                   /* If this is the first setting of this reg
2894                      in current basic block, and it was set before,
2895                      it must be set in two basic blocks, so it cannot
2896                      be moved out of the loop.  */
2897                   if (n_times_set[regno] > 0 && last_set[regno] == 0)
2898                     may_not_move[regno] = 1;
2899                   /* If this is not first setting in current basic block,
2900                      see if reg was used in between previous one and this.
2901                      If so, neither one can be moved.  */
2902                   if (last_set[regno] != 0
2903                       && reg_used_between_p (dest, last_set[regno], insn))
2904                     may_not_move[regno] = 1;
2905                   if (n_times_set[regno] < 127)
2906                     ++n_times_set[regno];
2907                   last_set[regno] = insn;
2908                 }
2909             }
2910           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
2911             {
2912               register int i;
2913               for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
2914                 {
2915                   register rtx x = XVECEXP (PATTERN (insn), 0, i);
2916                   if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
2917                     /* Don't move a reg that has an explicit clobber.
2918                        It's not worth the pain to try to do it correctly.  */
2919                     may_not_move[REGNO (XEXP (x, 0))] = 1;
2920
2921                   if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
2922                     {
2923                       dest = SET_DEST (x);
2924                       while (GET_CODE (dest) == SUBREG
2925                              || GET_CODE (dest) == ZERO_EXTRACT
2926                              || GET_CODE (dest) == SIGN_EXTRACT
2927                              || GET_CODE (dest) == STRICT_LOW_PART)
2928                         dest = XEXP (dest, 0);
2929                       if (GET_CODE (dest) == REG)
2930                         {
2931                           register int regno = REGNO (dest);
2932                           if (n_times_set[regno] > 0 && last_set[regno] == 0)
2933                             may_not_move[regno] = 1;
2934                           if (last_set[regno] != 0
2935                               && reg_used_between_p (dest, last_set[regno], insn))
2936                             may_not_move[regno] = 1;
2937                           if (n_times_set[regno] < 127)
2938                             ++n_times_set[regno];
2939                           last_set[regno] = insn;
2940                         }
2941                     }
2942                 }
2943             }
2944         }
2945       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
2946         bzero (last_set, nregs * sizeof (rtx));
2947     }
2948   *count_ptr = count;
2949 }
2950 \f
2951 /* Given a loop that is bounded by LOOP_START and LOOP_END
2952    and that is entered at SCAN_START,
2953    return 1 if the register set in SET contained in insn INSN is used by
2954    any insn that precedes INSN in cyclic order starting
2955    from the loop entry point.
2956
2957    We don't want to use INSN_LUID here because if we restrict INSN to those
2958    that have a valid INSN_LUID, it means we cannot move an invariant out
2959    from an inner loop past two loops.  */
2960
2961 static int
2962 loop_reg_used_before_p (set, insn, loop_start, scan_start, loop_end)
2963      rtx set, insn, loop_start, scan_start, loop_end;
2964 {
2965   rtx reg = SET_DEST (set);
2966   rtx p;
2967
2968   /* Scan forward checking for register usage.  If we hit INSN, we
2969      are done.  Otherwise, if we hit LOOP_END, wrap around to LOOP_START.  */
2970   for (p = scan_start; p != insn; p = NEXT_INSN (p))
2971     {
2972       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
2973           && reg_overlap_mentioned_p (reg, PATTERN (p)))
2974         return 1;
2975
2976       if (p == loop_end)
2977         p = loop_start;
2978     }
2979
2980   return 0;
2981 }
2982 \f
2983 /* A "basic induction variable" or biv is a pseudo reg that is set
2984    (within this loop) only by incrementing or decrementing it.  */
2985 /* A "general induction variable" or giv is a pseudo reg whose
2986    value is a linear function of a biv.  */
2987
2988 /* Bivs are recognized by `basic_induction_var';
2989    Givs by `general_induct_var'.  */
2990
2991 /* Indexed by register number, indicates whether or not register is an
2992    induction variable, and if so what type.  */
2993
2994 enum iv_mode *reg_iv_type;
2995
2996 /* Indexed by register number, contains pointer to `struct induction'
2997    if register is an induction variable.  This holds general info for
2998    all induction variables.  */
2999
3000 struct induction **reg_iv_info;
3001
3002 /* Indexed by register number, contains pointer to `struct iv_class'
3003    if register is a basic induction variable.  This holds info describing
3004    the class (a related group) of induction variables that the biv belongs
3005    to.  */
3006
3007 struct iv_class **reg_biv_class;
3008
3009 /* The head of a list which links together (via the next field)
3010    every iv class for the current loop.  */
3011
3012 struct iv_class *loop_iv_list;
3013
3014 /* Communication with routines called via `note_stores'.  */
3015
3016 static rtx note_insn;
3017
3018 /* Dummy register to have non-zero DEST_REG for DEST_ADDR type givs.  */
3019
3020 static rtx addr_placeholder;
3021
3022 /* ??? Unfinished optimizations, and possible future optimizations,
3023    for the strength reduction code.  */
3024
3025 /* ??? There is one more optimization you might be interested in doing: to
3026    allocate pseudo registers for frequently-accessed memory locations.
3027    If the same memory location is referenced each time around, it might
3028    be possible to copy it into a register before and out after.
3029    This is especially useful when the memory location is a variable which
3030    is in a stack slot because somewhere its address is taken.  If the
3031    loop doesn't contain a function call and the variable isn't volatile,
3032    it is safe to keep the value in a register for the duration of the
3033    loop. One tricky thing is that the copying of the value back from the
3034    register has to be done on all exits from the loop.  You need to check that
3035    all the exits from the loop go to the same place. */
3036
3037 /* ??? The interaction of biv elimination, and recognition of 'constant'
3038    bivs, may cause problems. */
3039
3040 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
3041    performance problems.
3042
3043    Perhaps don't eliminate things that can be combined with an addressing
3044    mode.  Find all givs that have the same biv, mult_val, and add_val;
3045    then for each giv, check to see if its only use dies in a following
3046    memory address.  If so, generate a new memory address and check to see
3047    if it is valid.   If it is valid, then store the modified memory address,
3048    otherwise, mark the giv as not done so that it will get its own iv.  */
3049
3050 /* ??? Could try to optimize branches when it is known that a biv is always
3051    positive.  */
3052
3053 /* ??? When replace a biv in a compare insn, we should replace with closest
3054    giv so that an optimized branch can still be recognized by the combiner,
3055    e.g. the VAX acb insn.  */
3056
3057 /* ??? Many of the checks involving uid_luid could be simplified if regscan
3058    was rerun in loop_optimize whenever a register was added or moved.
3059    Also, some of the optimizations could be a little less conservative.  */
3060 \f
3061 /* Perform strength reduction and induction variable elimination.  */
3062
3063 /* Pseudo registers created during this function will be beyond the last
3064    valid index in several tables including n_times_set and regno_last_uid.
3065    This does not cause a problem here, because the added registers cannot be
3066    givs outside of their loop, and hence will never be reconsidered.
3067    But scan_loop must check regnos to make sure they are in bounds.  */
3068
3069 static void
3070 strength_reduce (scan_start, end, loop_top, insn_count,
3071                  loop_start, loop_end)
3072      rtx scan_start;
3073      rtx end;
3074      rtx loop_top;
3075      int insn_count;
3076      rtx loop_start;
3077      rtx loop_end;
3078 {
3079   rtx p;
3080   rtx set;
3081   rtx inc_val;
3082   rtx mult_val;
3083   rtx dest_reg;
3084   /* This is 1 if current insn is not executed at least once for every loop
3085      iteration.  */
3086   int not_every_iteration = 0;
3087   /* This is 1 if current insn may be executed more than once for every
3088      loop iteration.  */
3089   int maybe_multiple = 0;
3090   /* Temporary list pointers for traversing loop_iv_list.  */
3091   struct iv_class *bl, **backbl;
3092   /* Ratio of extra register life span we can justify
3093      for saving an instruction.  More if loop doesn't call subroutines
3094      since in that case saving an insn makes more difference
3095      and more registers are available.  */
3096   /* ??? could set this to last value of threshold in move_movables */
3097   int threshold = (loop_has_call ? 1 : 2) * (3 + n_non_fixed_regs);
3098   /* Map of pseudo-register replacements.  */
3099   rtx *reg_map;
3100   int call_seen;
3101   rtx test;
3102   rtx end_insert_before;
3103
3104   reg_iv_type = (enum iv_mode *) alloca (max_reg_before_loop
3105                                          * sizeof (enum iv_mode *));
3106   bzero ((char *) reg_iv_type, max_reg_before_loop * sizeof (enum iv_mode *));
3107   reg_iv_info = (struct induction **)
3108     alloca (max_reg_before_loop * sizeof (struct induction *));
3109   bzero ((char *) reg_iv_info, (max_reg_before_loop
3110                                 * sizeof (struct induction *)));
3111   reg_biv_class = (struct iv_class **)
3112     alloca (max_reg_before_loop * sizeof (struct iv_class *));
3113   bzero ((char *) reg_biv_class, (max_reg_before_loop
3114                                   * sizeof (struct iv_class *)));
3115
3116   loop_iv_list = 0;
3117   addr_placeholder = gen_reg_rtx (Pmode);
3118
3119   /* Save insn immediately after the loop_end.  Insns inserted after loop_end
3120      must be put before this insn, so that they will appear in the right
3121      order (i.e. loop order).  */
3122
3123   end_insert_before = NEXT_INSN (loop_end);
3124
3125   /* Scan through loop to find all possible bivs.  */
3126
3127   p = scan_start;
3128   while (1)
3129     {
3130       p = NEXT_INSN (p);
3131       /* At end of a straight-in loop, we are done.
3132          At end of a loop entered at the bottom, scan the top.  */
3133       if (p == scan_start)
3134         break;
3135       if (p == end)
3136         {
3137           if (loop_top != 0)
3138             p = NEXT_INSN (loop_top);
3139           else
3140             break;
3141           if (p == scan_start)
3142             break;
3143         }
3144
3145       if (GET_CODE (p) == INSN
3146           && (set = single_set (p))
3147           && GET_CODE (SET_DEST (set)) == REG)
3148         {
3149           dest_reg = SET_DEST (set);
3150           if (REGNO (dest_reg) < max_reg_before_loop
3151               && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
3152               && reg_iv_type[REGNO (dest_reg)] != NOT_BASIC_INDUCT)
3153             {
3154               if (basic_induction_var (SET_SRC (set), dest_reg, p,
3155                                       &inc_val, &mult_val))
3156                 {
3157                   /* It is a possible basic induction variable.
3158                      Create and initialize an induction structure for it.  */
3159
3160                   struct induction *v
3161                     = (struct induction *) alloca (sizeof (struct induction));
3162
3163                   record_biv (v, p, dest_reg, inc_val, mult_val,
3164                               not_every_iteration, maybe_multiple);
3165                   reg_iv_type[REGNO (dest_reg)] = BASIC_INDUCT;
3166                 }
3167               else if (REGNO (dest_reg) < max_reg_before_loop)
3168                 reg_iv_type[REGNO (dest_reg)] = NOT_BASIC_INDUCT;
3169             }
3170         }
3171
3172       /* Past CODE_LABEL, we get to insns that may be executed multiple
3173          times.  The only way we can be sure that they can't is if every
3174          every jump insn between here and the end of the loop either
3175          returns, exits the loop, or is a forward jump.  */
3176
3177       if (GET_CODE (p) == CODE_LABEL)
3178         {
3179           rtx insn = p;
3180
3181           maybe_multiple = 0;
3182
3183           while (1)
3184             {
3185               insn = NEXT_INSN (insn);
3186               if (insn == scan_start)
3187                 break;
3188               if (insn == end)
3189                 {
3190                   if (loop_top != 0)
3191                     insn = NEXT_INSN (loop_top);
3192                   else
3193                     break;
3194                   if (insn == scan_start)
3195                     break;
3196                 }
3197
3198               if (GET_CODE (insn) == JUMP_INSN
3199                   && GET_CODE (PATTERN (insn)) != RETURN
3200                   && (! condjump_p (insn)
3201                       || (JUMP_LABEL (insn) != 0
3202                           && (INSN_UID (JUMP_LABEL (insn)) >= max_uid_for_loop
3203                               || INSN_UID (insn) >= max_uid_for_loop
3204                               || (INSN_LUID (JUMP_LABEL (insn))
3205                                   < INSN_LUID (insn))))))
3206               {
3207                 maybe_multiple = 1;
3208                 break;
3209               }
3210             }
3211         }
3212
3213       /* Past a label or a jump, we get to insns for which we can't count
3214          on whether or how many times they will be executed during each
3215          iteration.  */
3216       /* This code appears in three places, once in scan_loop, and twice
3217          in strength_reduce.  */
3218       if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
3219           /* If we enter the loop in the middle, and scan around to the
3220              beginning, don't set not_every_iteration for that.
3221              This can be any kind of jump, since we want to know if insns
3222              will be executed if the loop is executed.  */
3223           && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop_top
3224                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3225                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3226         not_every_iteration = 1;
3227
3228       /* At the virtual top of a converted loop, insns are again known to
3229          be executed each iteration: logically, the loop begins here
3230          even though the exit code has been duplicated.  */
3231
3232       else if (GET_CODE (p) == NOTE
3233                && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP)
3234         not_every_iteration = 0;
3235
3236       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3237          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3238          or not an insn is known to be executed each iteration of the
3239          loop, whether or not any iterations are known to occur.
3240
3241          Therefore, if we have just passed a label and have no more labels
3242          between here and the test insn of the loop, we know these insns
3243          will be executed each iteration.  This can also happen if we
3244          have just passed a jump, for example, when there are nested loops.  */
3245
3246       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
3247           && no_labels_between_p (p, loop_end))
3248         not_every_iteration = 0;
3249     }
3250
3251   /* Scan loop_iv_list to remove all regs that proved not to be bivs.
3252      Make a sanity check against n_times_set.  */
3253   for (backbl = &loop_iv_list, bl = *backbl; bl; bl = bl->next)
3254     {
3255       if (reg_iv_type[bl->regno] != BASIC_INDUCT
3256           /* Above happens if register modified by subreg, etc.  */
3257           /* Make sure it is not recognized as a basic induction var: */
3258           || n_times_set[bl->regno] != bl->biv_count
3259           /* If never incremented, it is invariant that we decided not to
3260              move.  So leave it alone.  */
3261           || ! bl->incremented)
3262         {
3263           if (loop_dump_stream)
3264             fprintf (loop_dump_stream, "Reg %d: biv discarded, %s\n",
3265                      bl->regno,
3266                      (reg_iv_type[bl->regno] != BASIC_INDUCT
3267                       ? "not induction variable"
3268                       : (! bl->incremented ? "never incremented"
3269                          : "count error")));
3270           
3271           reg_iv_type[bl->regno] = NOT_BASIC_INDUCT;
3272           *backbl = bl->next;
3273         }
3274       else
3275         {
3276           backbl = &bl->next;
3277
3278           if (loop_dump_stream)
3279             fprintf (loop_dump_stream, "Reg %d: biv verified\n", bl->regno);
3280         }
3281     }
3282
3283   /* Exit if there are no bivs.  */
3284   if (! loop_iv_list)
3285     {
3286       /* Can still unroll the loop anyways, but indicate that there is no
3287          strength reduction info available.  */
3288       if (flag_unroll_loops)
3289         unroll_loop (loop_end, insn_count, loop_start, end_insert_before, 0);
3290
3291       return;
3292     }
3293
3294   /* Find initial value for each biv by searching backwards from loop_start,
3295      halting at first label.  Also record any test condition.  */
3296
3297   call_seen = 0;
3298   for (p = loop_start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
3299     {
3300       note_insn = p;
3301
3302       if (GET_CODE (p) == CALL_INSN)
3303         call_seen = 1;
3304
3305       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3306           || GET_CODE (p) == CALL_INSN)
3307         note_stores (PATTERN (p), record_initial);
3308
3309       /* Record any test of a biv that branches around the loop if no store
3310          between it and the start of loop.  We only care about tests with
3311          constants and registers and only certain of those.  */
3312       if (GET_CODE (p) == JUMP_INSN
3313           && JUMP_LABEL (p) != 0
3314           && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop_end)
3315           && (test = get_condition_for_loop (p)) != 0
3316           && GET_CODE (XEXP (test, 0)) == REG
3317           && REGNO (XEXP (test, 0)) < max_reg_before_loop
3318           && (bl = reg_biv_class[REGNO (XEXP (test, 0))]) != 0
3319           && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop_start)
3320           && bl->init_insn == 0)
3321         {
3322           /* If an NE test, we have an initial value!  */
3323           if (GET_CODE (test) == NE)
3324             {
3325               bl->init_insn = p;
3326               bl->init_set = gen_rtx (SET, VOIDmode,
3327                                       XEXP (test, 0), XEXP (test, 1));
3328             }
3329           else
3330             bl->initial_test = test;
3331         }
3332     }
3333
3334   /* Look at the each biv and see if we can say anything better about its
3335      initial value from any initializing insns set up above.  (This is done
3336      in two passes to avoid missing SETs in a PARALLEL.)  */
3337   for (bl = loop_iv_list; bl; bl = bl->next)
3338     {
3339       rtx src;
3340
3341       if (! bl->init_insn)
3342         continue;
3343
3344       src = SET_SRC (bl->init_set);
3345
3346       if (loop_dump_stream)
3347         fprintf (loop_dump_stream,
3348                  "Biv %d initialized at insn %d: initial value ",
3349                  bl->regno, INSN_UID (bl->init_insn));
3350
3351       if (valid_initial_value_p (src, bl->init_insn, call_seen, loop_start))
3352         {
3353           bl->initial_value = src;
3354
3355           if (loop_dump_stream)
3356             {
3357               if (GET_CODE (src) == CONST_INT)
3358                 fprintf (loop_dump_stream, "%d\n", INTVAL (src));
3359               else
3360                 {
3361                   print_rtl (loop_dump_stream, src);
3362                   fprintf (loop_dump_stream, "\n");
3363                 }
3364             }
3365         }
3366       else
3367         {
3368           /* Biv initial value is not simple move,
3369              so let it keep initial value of "itself".  */
3370
3371           if (loop_dump_stream)
3372             fprintf (loop_dump_stream, "is complex\n");
3373         }
3374     }
3375
3376   /* Search the loop for general induction variables.  */
3377
3378   /* A register is a giv if: it is only set once, it is a function of a
3379      biv and a constant (or invariant), and it is not a biv.  */
3380
3381   not_every_iteration = 0;
3382   p = scan_start;
3383   while (1)
3384     {
3385       p = NEXT_INSN (p);
3386       /* At end of a straight-in loop, we are done.
3387          At end of a loop entered at the bottom, scan the top.  */
3388       if (p == scan_start)
3389         break;
3390       if (p == end)
3391         {
3392           if (loop_top != 0)
3393             p = NEXT_INSN (loop_top);
3394           else
3395             break;
3396           if (p == scan_start)
3397             break;
3398         }
3399
3400       /* Look for a general induction variable in a register.  */
3401       if (GET_CODE (p) == INSN
3402           && (set = single_set (p))
3403           && GET_CODE (SET_DEST (set)) == REG
3404           && ! may_not_optimize[REGNO (SET_DEST (set))])
3405         {
3406           rtx src_reg;
3407           rtx add_val;
3408           rtx mult_val;
3409           int benefit;
3410           rtx regnote = 0;
3411
3412           dest_reg = SET_DEST (set);
3413           if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
3414             continue;
3415
3416           if (/* SET_SRC is a giv.  */
3417               ((benefit = general_induction_var (SET_SRC (set),
3418                                                  &src_reg, &add_val,
3419                                                  &mult_val))
3420                /* Equivalent expression is a giv. */
3421                || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
3422                    && (benefit = general_induction_var (XEXP (regnote, 0),
3423                                                         &src_reg,
3424                                                         &add_val, &mult_val))))
3425               /* Don't try to handle any regs made by loop optimization.
3426                  We have nothing on them in regno_first_uid, etc.  */
3427               && REGNO (dest_reg) < max_reg_before_loop
3428               /* Don't recognize a BASIC_INDUCT_VAR here.  */
3429               && dest_reg != src_reg
3430               /* This must be the only place where the register is set.  */
3431               && (n_times_set[REGNO (dest_reg)] == 1
3432                   /* or all sets must be consecutive and make a giv. */
3433                   || (benefit = consec_sets_giv (benefit, p,
3434                                                  src_reg, dest_reg,
3435                                                  &add_val, &mult_val))))
3436             {
3437               int count;
3438               struct induction *v
3439                 = (struct induction *) alloca (sizeof (struct induction));
3440               rtx temp;
3441
3442               /* If this is a library call, increase benefit.  */
3443               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
3444                 benefit += libcall_benefit (p);
3445
3446               /* Skip the consecutive insns, if there are any.  */
3447               for (count = n_times_set[REGNO (dest_reg)] - 1;
3448                    count > 0; count--)
3449                 {
3450                   /* If first insn of libcall sequence, skip to end.
3451                      Do this at start of loop, since INSN is guaranteed to
3452                      be an insn here.  */
3453                   if (GET_CODE (p) != NOTE
3454                       && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3455                     p = XEXP (temp, 0);
3456
3457                   do p = NEXT_INSN (p);
3458                   while (GET_CODE (p) == NOTE);
3459                 }
3460
3461               record_giv (v, p, src_reg, dest_reg, mult_val, add_val, benefit,
3462                           DEST_REG, not_every_iteration, NULL_PTR, loop_start,
3463                           loop_end);
3464
3465             }
3466         }
3467
3468 #ifndef DONT_REDUCE_ADDR
3469       /* Look for givs which are memory addresses.  */
3470       /* This resulted in worse code on a VAX 8600.  I wonder if it
3471          still does.  */
3472       if (GET_CODE (p) == INSN)
3473         find_mem_givs (PATTERN (p), p, not_every_iteration, loop_start,
3474                        loop_end);
3475 #endif
3476
3477       /* Update the status of whether giv can derive other givs.  This can
3478          change when we pass a label or an insn that updates a biv.  */
3479       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3480         || GET_CODE (p) == CODE_LABEL)
3481         update_giv_derive (p);
3482
3483       /* Past a label or a jump, we get to insns for which we can't count
3484          on whether or how many times they will be executed during each
3485          iteration.  */
3486       /* This code appears in three places, once in scan_loop, and twice
3487          in strength_reduce.  */
3488       if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
3489           /* If we enter the loop in the middle, and scan around
3490              to the beginning, don't set not_every_iteration for that.
3491              This can be any kind of jump, since we want to know if insns
3492              will be executed if the loop is executed.  */
3493           && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop_top
3494                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3495                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3496         not_every_iteration = 1;
3497
3498       /* At the virtual top of a converted loop, insns are again known to
3499          be executed each iteration: logically, the loop begins here
3500          even though the exit code has been duplicated.  */
3501
3502       else if (GET_CODE (p) == NOTE
3503                && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP)
3504         not_every_iteration = 0;
3505
3506       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3507          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3508          or not an insn is known to be executed each iteration of the
3509          loop, whether or not any iterations are known to occur.
3510
3511          Therefore, if we have just passed a label and have no more labels
3512          between here and the test insn of the loop, we know these insns
3513          will be executed each iteration.  */
3514
3515       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
3516           && no_labels_between_p (p, loop_end))
3517         not_every_iteration = 0;
3518     }
3519
3520   /* Try to calculate and save the number of loop iterations.  This is
3521      set to zero if the actual number can not be calculated.  This must
3522      be called after all giv's have been identified, since otherwise it may
3523      fail if the iteration variable is a giv.  */
3524
3525   loop_n_iterations = loop_iterations (loop_start, loop_end);
3526
3527   /* Now for each giv for which we still don't know whether or not it is
3528      replaceable, check to see if it is replaceable because its final value
3529      can be calculated.  This must be done after loop_iterations is called,
3530      so that final_giv_value will work correctly.  */
3531
3532   for (bl = loop_iv_list; bl; bl = bl->next)
3533     {
3534       struct induction *v;
3535
3536       for (v = bl->giv; v; v = v->next_iv)
3537         if (! v->replaceable && ! v->not_replaceable)
3538           check_final_value (v, loop_start, loop_end);
3539     }
3540
3541   /* Try to prove that the loop counter variable (if any) is always
3542      nonnegative; if so, record that fact with a REG_NONNEG note
3543      so that "decrement and branch until zero" insn can be used.  */
3544   check_dbra_loop (loop_end, insn_count, loop_start);
3545
3546   /* Create reg_map to hold substitutions for replaceable giv regs.  */
3547   reg_map = (rtx *) alloca (max_reg_before_loop * sizeof (rtx));
3548   bzero ((char *) reg_map, max_reg_before_loop * sizeof (rtx));
3549
3550   /* Examine each iv class for feasibility of strength reduction/induction
3551      variable elimination.  */
3552
3553   for (bl = loop_iv_list; bl; bl = bl->next)
3554     {
3555       struct induction *v;
3556       int benefit;
3557       int all_reduced;
3558       rtx final_value = 0;
3559
3560       /* Test whether it will be possible to eliminate this biv
3561          provided all givs are reduced.  This is possible if either
3562          the reg is not used outside the loop, or we can compute
3563          what its final value will be.
3564
3565          For architectures with a decrement_and_branch_until_zero insn,
3566          don't do this if we put a REG_NONNEG note on the endtest for
3567          this biv.  */
3568
3569       /* Compare against bl->init_insn rather than loop_start.
3570          We aren't concerned with any uses of the biv between
3571          init_insn and loop_start since these won't be affected
3572          by the value of the biv elsewhere in the function, so
3573          long as init_insn doesn't use the biv itself.
3574          March 14, 1989 -- self@bayes.arc.nasa.gov */
3575
3576       if ((uid_luid[regno_last_uid[bl->regno]] < INSN_LUID (loop_end)
3577            && bl->init_insn
3578            && INSN_UID (bl->init_insn) < max_uid_for_loop
3579            && uid_luid[regno_first_uid[bl->regno]] >= INSN_LUID (bl->init_insn)
3580 #ifdef HAVE_decrement_and_branch_until_zero
3581            && ! bl->nonneg
3582 #endif
3583            && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
3584           || ((final_value = final_biv_value (bl, loop_start, loop_end))
3585 #ifdef HAVE_decrement_and_branch_until_zero
3586               && ! bl->nonneg
3587 #endif
3588               ))
3589         bl->eliminable = maybe_eliminate_biv (bl, loop_start, end, 0,
3590                                               threshold, insn_count);
3591       else
3592         {
3593           if (loop_dump_stream)
3594             {
3595               fprintf (loop_dump_stream,
3596                        "Cannot eliminate biv %d.\n",
3597                        bl->regno);
3598               fprintf (loop_dump_stream,
3599                        "First use: insn %d, last use: insn %d.\n",
3600                        regno_first_uid[bl->regno],
3601                        regno_last_uid[bl->regno]);
3602             }
3603         }
3604
3605       /* Combine all giv's for this iv_class.  */
3606       combine_givs (bl);
3607
3608       /* This will be true at the end, if all givs which depend on this
3609          biv have been strength reduced.
3610          We can't (currently) eliminate the biv unless this is so.  */
3611       all_reduced = 1;
3612
3613       /* Check each giv in this class to see if we will benefit by reducing
3614          it.  Skip giv's combined with others.  */
3615       for (v = bl->giv; v; v = v->next_iv)
3616         {
3617           struct induction *tv;
3618
3619           if (v->ignore || v->same)
3620             continue;
3621
3622           benefit = v->benefit;
3623
3624           /* Reduce benefit if not replaceable, since we will insert
3625              a move-insn to replace the insn that calculates this giv.
3626              Don't do this unless the giv is a user variable, since it
3627              will often be marked non-replaceable because of the duplication
3628              of the exit code outside the loop.  In such a case, the copies
3629              we insert are dead and will be deleted.  So they don't have
3630              a cost.  Similar situations exist.  */
3631           /* ??? The new final_[bg]iv_value code does a much better job
3632              of finding replaceable giv's, and hence this code may no longer
3633              be necessary.  */
3634           if (! v->replaceable && ! bl->eliminable
3635               && REG_USERVAR_P (v->dest_reg))
3636             benefit -= copy_cost;
3637
3638           /* Decrease the benefit to count the add-insns that we will
3639              insert to increment the reduced reg for the giv.  */
3640           benefit -= add_cost * bl->biv_count;
3641
3642           /* Decide whether to strength-reduce this giv or to leave the code
3643              unchanged (recompute it from the biv each time it is used).
3644              This decision can be made independently for each giv.  */
3645
3646           /* ??? Perhaps attempt to guess whether autoincrement will handle
3647              some of the new add insns; if so, can increase BENEFIT
3648              (undo the subtraction of add_cost that was done above).  */
3649
3650           /* If an insn is not to be strength reduced, then set its ignore
3651              flag, and clear all_reduced.  */
3652
3653           if (v->lifetime * threshold * benefit < insn_count)
3654             {
3655               if (loop_dump_stream)
3656                 fprintf (loop_dump_stream,
3657                          "giv of insn %d not worth while, %d vs %d.\n",
3658                          INSN_UID (v->insn),
3659                          v->lifetime * threshold * benefit, insn_count);
3660               v->ignore = 1;
3661               all_reduced = 0;
3662             }
3663           else
3664             {
3665               /* Check that we can increment the reduced giv without a
3666                  multiply insn.  If not, reject it.  */
3667
3668               for (tv = bl->biv; tv; tv = tv->next_iv)
3669                 if (tv->mult_val == const1_rtx
3670                     && ! product_cheap_p (tv->add_val, v->mult_val))
3671                   {
3672                     if (loop_dump_stream)
3673                       fprintf (loop_dump_stream,
3674                                "giv of insn %d: would need a multiply.\n",
3675                                INSN_UID (v->insn));
3676                     v->ignore = 1;
3677                     all_reduced = 0;
3678                     break;
3679                   }
3680             }
3681         }
3682
3683       /* Reduce each giv that we decided to reduce.  */
3684
3685       for (v = bl->giv; v; v = v->next_iv)
3686         {
3687           struct induction *tv;
3688           if (! v->ignore && v->same == 0)
3689             {
3690               v->new_reg = gen_reg_rtx (v->mode);
3691
3692               /* For each place where the biv is incremented,
3693                  add an insn to increment the new, reduced reg for the giv.  */
3694               for (tv = bl->biv; tv; tv = tv->next_iv)
3695                 {
3696                   if (tv->mult_val == const1_rtx)
3697                     emit_iv_add_mult (tv->add_val, v->mult_val,
3698                                       v->new_reg, v->new_reg, tv->insn);
3699                   else /* tv->mult_val == const0_rtx */
3700                     /* A multiply is acceptable here
3701                        since this is presumed to be seldom executed.  */
3702                     emit_iv_add_mult (tv->add_val, v->mult_val,
3703                                       v->add_val, v->new_reg, tv->insn);
3704                 }
3705
3706               /* Add code at loop start to initialize giv's reduced reg.  */
3707
3708               emit_iv_add_mult (bl->initial_value, v->mult_val,
3709                                 v->add_val, v->new_reg, loop_start);
3710             }
3711         }
3712
3713       /* Rescan all givs.  If a giv is the same as a giv not reduced, mark it
3714          as not reduced.
3715          
3716          For each giv register that can be reduced now: if replaceable,
3717          substitute reduced reg wherever the old giv occurs;
3718          else add new move insn "giv_reg = reduced_reg".
3719
3720          Also check for givs whose first use is their definition and whose
3721          last use is the definition of another giv.  If so, it is likely
3722          dead and should not be used to eliminate a biv.  */
3723       for (v = bl->giv; v; v = v->next_iv)
3724         {
3725           if (v->same && v->same->ignore)
3726             v->ignore = 1;
3727
3728           if (v->ignore)
3729             continue;
3730
3731           if (v->giv_type == DEST_REG
3732               && regno_first_uid[REGNO (v->dest_reg)] == INSN_UID (v->insn))
3733             {
3734               struct induction *v1;
3735
3736               for (v1 = bl->giv; v1; v1 = v1->next_iv)
3737                 if (regno_last_uid[REGNO (v->dest_reg)] == INSN_UID (v1->insn))
3738                   v->maybe_dead = 1;
3739             }
3740
3741           /* Update expression if this was combined, in case other giv was
3742              replaced.  */
3743           if (v->same)
3744             v->new_reg = replace_rtx (v->new_reg,
3745                                       v->same->dest_reg, v->same->new_reg);
3746
3747           if (v->giv_type == DEST_ADDR)
3748             /* Store reduced reg as the address in the memref where we found
3749                this giv.  */
3750             *v->location = v->new_reg;
3751           else if (v->replaceable)
3752             {
3753               reg_map[REGNO (v->dest_reg)] = v->new_reg;
3754
3755 #if 0
3756               /* I can no longer duplicate the original problem.  Perhaps
3757                  this is unnecessary now?  */
3758
3759               /* Replaceable; it isn't strictly necessary to delete the old
3760                  insn and emit a new one, because v->dest_reg is now dead.
3761
3762                  However, especially when unrolling loops, the special
3763                  handling for (set REG0 REG1) in the second cse pass may
3764                  make v->dest_reg live again.  To avoid this problem, emit
3765                  an insn to set the original giv reg from the reduced giv.
3766                  We can not delete the original insn, since it may be part
3767                  of a LIBCALL, and the code in flow that eliminates dead
3768                  libcalls will fail if it is deleted.  */
3769               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
3770                                v->insn);
3771 #endif
3772             }
3773           else
3774             {
3775               /* Not replaceable; emit an insn to set the original giv reg from
3776                  the reduced giv, same as above.  */
3777               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
3778                                v->insn);
3779             }
3780
3781           /* When a loop is reversed, givs which depend on the reversed
3782              biv, and which are live outside the loop, must be set to their
3783              correct final value.  This insn is only needed if the giv is
3784              not replaceable.  The correct final value is the same as the
3785              value that the giv starts the reversed loop with.  */
3786           if (bl->reversed && ! v->replaceable)
3787             emit_iv_add_mult (bl->initial_value, v->mult_val,
3788                               v->add_val, v->dest_reg, end_insert_before);
3789           else if (v->final_value)
3790             {
3791               rtx insert_before;
3792
3793               /* If the loop has multiple exits, emit the insn before the
3794                  loop to ensure that it will always be executed no matter
3795                  how the loop exits.  Otherwise, emit the insn after the loop,
3796                  since this is slightly more efficient.  */
3797               if (loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]])
3798                 insert_before = loop_start;
3799               else
3800                 insert_before = end_insert_before;
3801               emit_insn_before (gen_move_insn (v->dest_reg, v->final_value),
3802                                 insert_before);
3803
3804 #if 0
3805               /* If the insn to set the final value of the giv was emitted
3806                  before the loop, then we must delete the insn inside the loop
3807                  that sets it.  If this is a LIBCALL, then we must delete
3808                  every insn in the libcall.  Note, however, that
3809                  final_giv_value will only succeed when there are multiple
3810                  exits if the giv is dead at each exit, hence it does not
3811                  matter that the original insn remains because it is dead
3812                  anyways.  */
3813               /* Delete the insn inside the loop that sets the giv since
3814                  the giv is now set before (or after) the loop.  */
3815               delete_insn (v->insn);
3816 #endif
3817             }
3818
3819           if (loop_dump_stream)
3820             {
3821               fprintf (loop_dump_stream, "giv at %d reduced to ",
3822                        INSN_UID (v->insn));
3823               print_rtl (loop_dump_stream, v->new_reg);
3824               fprintf (loop_dump_stream, "\n");
3825             }
3826         }
3827
3828       /* All the givs based on the biv bl have been reduced if they
3829          merit it.  */
3830
3831       /* For each giv not marked as maybe dead that has been combined with a
3832          second giv, clear any "maybe dead" mark on that second giv.
3833          v->new_reg will either be or refer to the register of the giv it
3834          combined with.
3835
3836          Doing this clearing avoids problems in biv elimination where a
3837          giv's new_reg is a complex value that can't be put in the insn but
3838          the giv combined with (with a reg as new_reg) is marked maybe_dead.
3839          Since the register will be used in either case, we'd prefer it be
3840          used from the simpler giv.  */
3841
3842       for (v = bl->giv; v; v = v->next_iv)
3843         if (! v->maybe_dead && v->same)
3844           v->same->maybe_dead = 0;
3845
3846       /* Try to eliminate the biv, if it is a candidate.
3847          This won't work if ! all_reduced,
3848          since the givs we planned to use might not have been reduced.
3849
3850          We have to be careful that we didn't initially think we could eliminate
3851          this biv because of a giv that we now think may be dead and shouldn't
3852          be used as a biv replacement.  
3853
3854          Also, there is the possibility that we may have a giv that looks
3855          like it can be used to eliminate a biv, but the resulting insn
3856          isn't valid.  This can happen, for example, on the 88k, where a 
3857          JUMP_INSN can compare a register only with zero.  Attempts to
3858          replace it with a compare with a constant will fail.
3859
3860          Note that in cases where this call fails, we may have replaced some
3861          of the occurrences of the biv with a giv, but no harm was done in
3862          doing so in the rare cases where it can occur.  */
3863
3864       if (all_reduced == 1 && bl->eliminable
3865           && maybe_eliminate_biv (bl, loop_start, end, 1,
3866                                   threshold, insn_count))
3867
3868         {
3869           /* ?? If we created a new test to bypass the loop entirely,
3870              or otherwise drop straight in, based on this test, then
3871              we might want to rewrite it also.  This way some later
3872              pass has more hope of removing the initialization of this
3873              biv entirely. */
3874
3875           /* If final_value != 0, then the biv may be used after loop end
3876              and we must emit an insn to set it just in case.
3877
3878              Reversed bivs already have an insn after the loop setting their
3879              value, so we don't need another one.  We can't calculate the
3880              proper final value for such a biv here anyways. */
3881           if (final_value != 0 && ! bl->reversed)
3882             {
3883               rtx insert_before;
3884
3885               /* If the loop has multiple exits, emit the insn before the
3886                  loop to ensure that it will always be executed no matter
3887                  how the loop exits.  Otherwise, emit the insn after the
3888                  loop, since this is slightly more efficient.  */
3889               if (loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]])
3890                 insert_before = loop_start;
3891               else
3892                 insert_before = end_insert_before;
3893
3894               emit_insn_before (gen_move_insn (bl->biv->dest_reg, final_value),
3895                                 end_insert_before);
3896             }
3897
3898 #if 0
3899           /* Delete all of the instructions inside the loop which set
3900              the biv, as they are all dead.  If is safe to delete them,
3901              because an insn setting a biv will never be part of a libcall.  */
3902           /* However, deleting them will invalidate the regno_last_uid info,
3903              so keeping them around is more convenient.  Final_biv_value
3904              will only succeed when there are multiple exits if the biv
3905              is dead at each exit, hence it does not matter that the original
3906              insn remains, because it is dead anyways.  */
3907           for (v = bl->biv; v; v = v->next_iv)
3908             delete_insn (v->insn);
3909 #endif
3910
3911           if (loop_dump_stream)
3912             fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
3913                      bl->regno);
3914         }
3915     }
3916
3917   /* Go through all the instructions in the loop, making all the
3918      register substitutions scheduled in REG_MAP.  */
3919
3920   for (p = loop_start; p != end; p = NEXT_INSN (p))
3921     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3922         || GET_CODE (p) == CALL_INSN)
3923       {
3924         replace_regs (PATTERN (p), reg_map, max_reg_before_loop, 0);
3925         replace_regs (REG_NOTES (p), reg_map, max_reg_before_loop, 0);
3926       }
3927
3928   /* Unroll loops from within strength reduction so that we can use the
3929      induction variable information that strength_reduce has already
3930      collected.  */
3931   
3932   if (flag_unroll_loops)
3933     unroll_loop (loop_end, insn_count, loop_start, end_insert_before, 1);
3934
3935   if (loop_dump_stream)
3936     fprintf (loop_dump_stream, "\n");
3937 }
3938 \f
3939 /* Return 1 if X is a valid source for an initial value (or as value being
3940    compared against in an initial test).
3941
3942    X must be either a register or constant and must not be clobbered between
3943    the current insn and the start of the loop.
3944
3945    INSN is the insn containing X.  */
3946
3947 static int
3948 valid_initial_value_p (x, insn, call_seen, loop_start)
3949      rtx x;
3950      rtx insn;
3951      int call_seen;
3952      rtx loop_start;
3953 {
3954   if (CONSTANT_P (x))
3955     return 1;
3956
3957   /* Only consider pseudos we know about initialized in insns whose luids
3958      we know.  */
3959   if (GET_CODE (x) != REG
3960       || REGNO (x) >= max_reg_before_loop)
3961     return 0;
3962
3963   /* Don't use call-clobbered registers across a call which clobbers it.  On
3964      some machines, don't use any hard registers at all.  */
3965   if (REGNO (x) < FIRST_PSEUDO_REGISTER
3966 #ifndef SMALL_REGISTER_CLASSES
3967       && call_used_regs[REGNO (x)] && call_seen
3968 #endif
3969       )
3970     return 0;
3971
3972   /* Don't use registers that have been clobbered before the start of the
3973      loop.  */
3974   if (reg_set_between_p (x, insn, loop_start))
3975     return 0;
3976
3977   return 1;
3978 }
3979 \f
3980 /* Scan X for memory refs and check each memory address
3981    as a possible giv.  INSN is the insn whose pattern X comes from.
3982    NOT_EVERY_ITERATION is 1 if the insn might not be executed during
3983    every loop iteration.  */
3984
3985 static void
3986 find_mem_givs (x, insn, not_every_iteration, loop_start, loop_end)
3987      rtx x;
3988      rtx insn;
3989      int not_every_iteration;
3990      rtx loop_start, loop_end;
3991 {
3992   register int i, j;
3993   register enum rtx_code code;
3994   register char *fmt;
3995
3996   if (x == 0)
3997     return;
3998
3999   code = GET_CODE (x);
4000   switch (code)
4001     {
4002     case REG:
4003     case CONST_INT:
4004     case CONST:
4005     case CONST_DOUBLE:
4006     case SYMBOL_REF:
4007     case LABEL_REF:
4008     case PC:
4009     case CC0:
4010     case ADDR_VEC:
4011     case ADDR_DIFF_VEC:
4012     case USE:
4013     case CLOBBER:
4014       return;
4015
4016     case MEM:
4017       {
4018         rtx src_reg;
4019         rtx add_val;
4020         rtx mult_val;
4021         int benefit;
4022
4023         benefit = general_induction_var (XEXP (x, 0),
4024                                          &src_reg, &add_val, &mult_val);
4025
4026         /* Don't make a DEST_ADDR giv with mult_val == 1 && add_val == 0.
4027            Such a giv isn't useful.  */
4028         if (benefit > 0 && (mult_val != const1_rtx || add_val != const0_rtx))
4029           {
4030             /* Found one; record it.  */
4031             struct induction *v
4032               = (struct induction *) oballoc (sizeof (struct induction));
4033
4034             record_giv (v, insn, src_reg, addr_placeholder, mult_val,
4035                         add_val, benefit, DEST_ADDR, not_every_iteration,
4036                         &XEXP (x, 0), loop_start, loop_end);
4037
4038             v->mem_mode = GET_MODE (x);
4039           }
4040         return;
4041       }
4042     }
4043
4044   /* Recursively scan the subexpressions for other mem refs.  */
4045
4046   fmt = GET_RTX_FORMAT (code);
4047   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4048     if (fmt[i] == 'e')
4049       find_mem_givs (XEXP (x, i), insn, not_every_iteration, loop_start,
4050                      loop_end);
4051     else if (fmt[i] == 'E')
4052       for (j = 0; j < XVECLEN (x, i); j++)
4053         find_mem_givs (XVECEXP (x, i, j), insn, not_every_iteration,
4054                        loop_start, loop_end);
4055 }
4056 \f
4057 /* Fill in the data about one biv update.
4058    V is the `struct induction' in which we record the biv.  (It is
4059    allocated by the caller, with alloca.)
4060    INSN is the insn that sets it.
4061    DEST_REG is the biv's reg.
4062
4063    MULT_VAL is const1_rtx if the biv is being incremented here, in which case
4064    INC_VAL is the increment.  Otherwise, MULT_VAL is const0_rtx and the biv is
4065    being set to INC_VAL.
4066
4067    NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
4068    executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
4069    can be executed more than once per iteration.  If MAYBE_MULTIPLE
4070    and NOT_EVERY_ITERATION are both zero, we know that the biv update is
4071    executed exactly once per iteration.  */
4072
4073 static void
4074 record_biv (v, insn, dest_reg, inc_val, mult_val,
4075             not_every_iteration, maybe_multiple)
4076      struct induction *v;
4077      rtx insn;
4078      rtx dest_reg;
4079      rtx inc_val;
4080      rtx mult_val;
4081      int not_every_iteration;
4082      int maybe_multiple;
4083 {
4084   struct iv_class *bl;
4085
4086   v->insn = insn;
4087   v->src_reg = dest_reg;
4088   v->dest_reg = dest_reg;
4089   v->mult_val = mult_val;
4090   v->add_val = inc_val;
4091   v->mode = GET_MODE (dest_reg);
4092   v->always_computable = ! not_every_iteration;
4093   v->maybe_multiple = maybe_multiple;
4094
4095   /* Add this to the reg's iv_class, creating a class
4096      if this is the first incrementation of the reg.  */
4097
4098   bl = reg_biv_class[REGNO (dest_reg)];
4099   if (bl == 0)
4100     {
4101       /* Create and initialize new iv_class.  */
4102
4103       bl = (struct iv_class *) oballoc (sizeof (struct iv_class));
4104
4105       bl->regno = REGNO (dest_reg);
4106       bl->biv = 0;
4107       bl->giv = 0;
4108       bl->biv_count = 0;
4109       bl->giv_count = 0;
4110
4111       /* Set initial value to the reg itself.  */
4112       bl->initial_value = dest_reg;
4113       /* We haven't seen the initializing insn yet */
4114       bl->init_insn = 0;
4115       bl->init_set = 0;
4116       bl->initial_test = 0;
4117       bl->incremented = 0;
4118       bl->eliminable = 0;
4119       bl->nonneg = 0;
4120       bl->reversed = 0;
4121
4122       /* Add this class to loop_iv_list.  */
4123       bl->next = loop_iv_list;
4124       loop_iv_list = bl;
4125
4126       /* Put it in the array of biv register classes.  */
4127       reg_biv_class[REGNO (dest_reg)] = bl;
4128     }
4129
4130   /* Update IV_CLASS entry for this biv.  */
4131   v->next_iv = bl->biv;
4132   bl->biv = v;
4133   bl->biv_count++;
4134   if (mult_val == const1_rtx)
4135     bl->incremented = 1;
4136
4137   if (loop_dump_stream)
4138     {
4139       fprintf (loop_dump_stream,
4140                "Insn %d: possible biv, reg %d,",
4141                INSN_UID (insn), REGNO (dest_reg));
4142       if (GET_CODE (inc_val) == CONST_INT)
4143         fprintf (loop_dump_stream, " const = %d\n",
4144                  INTVAL (inc_val));
4145       else
4146         {
4147           fprintf (loop_dump_stream, " const = ");
4148           print_rtl (loop_dump_stream, inc_val);
4149           fprintf (loop_dump_stream, "\n");
4150         }
4151     }
4152 }
4153 \f
4154 /* Fill in the data about one giv.
4155    V is the `struct induction' in which we record the giv.  (It is
4156    allocated by the caller, with alloca.)
4157    INSN is the insn that sets it.
4158    BENEFIT estimates the savings from deleting this insn.
4159    TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
4160    into a register or is used as a memory address.
4161
4162    SRC_REG is the biv reg which the giv is computed from.
4163    DEST_REG is the giv's reg (if the giv is stored in a reg).
4164    MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
4165    LOCATION points to the place where this giv's value appears in INSN.  */
4166
4167 static void
4168 record_giv (v, insn, src_reg, dest_reg, mult_val, add_val, benefit,
4169             type, not_every_iteration, location, loop_start, loop_end)
4170      struct induction *v;
4171      rtx insn;
4172      rtx src_reg;
4173      rtx dest_reg;
4174      rtx mult_val, add_val;
4175      int benefit;
4176      enum g_types type;
4177      int not_every_iteration;
4178      rtx *location;
4179      rtx loop_start, loop_end;
4180 {
4181   struct induction *b;
4182   struct iv_class *bl;
4183   rtx set = single_set (insn);
4184   rtx p;
4185
4186   v->insn = insn;
4187   v->src_reg = src_reg;
4188   v->giv_type = type;
4189   v->dest_reg = dest_reg;
4190   v->mult_val = mult_val;
4191   v->add_val = add_val;
4192   v->benefit = benefit;
4193   v->location = location;
4194   v->cant_derive = 0;
4195   v->combined_with = 0;
4196   v->maybe_multiple = 0;
4197   v->maybe_dead = 0;
4198   v->derive_adjustment = 0;
4199   v->same = 0;
4200   v->ignore = 0;
4201   v->new_reg = 0;
4202   v->final_value = 0;
4203
4204   /* The v->always_computable field is used in update_giv_derive, to
4205      determine whether a giv can be used to derive another giv.  For a
4206      DEST_REG giv, INSN computes a new value for the giv, so its value
4207      isn't computable if INSN insn't executed every iteration.
4208      However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
4209      it does not compute a new value.  Hence the value is always computable
4210      regardless of whether INSN is executed each iteration.  */
4211
4212   if (type == DEST_ADDR)
4213     v->always_computable = 1;
4214   else
4215     v->always_computable = ! not_every_iteration;
4216
4217   if (type == DEST_ADDR)
4218     {
4219       v->mode = GET_MODE (*location);
4220       v->lifetime = 1;
4221       v->times_used = 1;
4222     }
4223   else /* type == DEST_REG */
4224     {
4225       v->mode = GET_MODE (SET_DEST (set));
4226
4227       v->lifetime = (uid_luid[regno_last_uid[REGNO (dest_reg)]]
4228                      - uid_luid[regno_first_uid[REGNO (dest_reg)]]);
4229
4230       v->times_used = n_times_used[REGNO (dest_reg)];
4231
4232       /* If the lifetime is zero, it means that this register is
4233          really a dead store.  So mark this as a giv that can be
4234          ignored.  This will not prevent the biv from being eliminated. */
4235       if (v->lifetime == 0)
4236         v->ignore = 1;
4237
4238       reg_iv_type[REGNO (dest_reg)] = GENERAL_INDUCT;
4239       reg_iv_info[REGNO (dest_reg)] = v;
4240     }
4241
4242   /* Add the giv to the class of givs computed from one biv.  */
4243
4244   bl = reg_biv_class[REGNO (src_reg)];
4245   if (bl)
4246     {
4247       v->next_iv = bl->giv;
4248       bl->giv = v;
4249       /* Don't count DEST_ADDR.  This is supposed to count the number of
4250          insns that calculate givs.  */
4251       if (type == DEST_REG)
4252         bl->giv_count++;
4253       bl->total_benefit += benefit;
4254     }
4255   else
4256     /* Fatal error, biv missing for this giv?  */
4257     abort ();
4258
4259   if (type == DEST_ADDR)
4260     v->replaceable = 1;
4261   else
4262     {
4263       /* The giv can be replaced outright by the reduced register only if all
4264          of the following conditions are true:
4265          - the insn that sets the giv is always executed on any iteration
4266            on which the giv is used at all
4267            (there are two ways to deduce this:
4268             either the insn is executed on every iteration,
4269             or all uses follow that insn in the same basic block),
4270          - the giv is not used outside the loop
4271          - no assignments to the biv occur during the giv's lifetime.  */
4272
4273       if (regno_first_uid[REGNO (dest_reg)] == INSN_UID (insn)
4274           /* Previous line always fails if INSN was moved by loop opt.  */
4275           && uid_luid[regno_last_uid[REGNO (dest_reg)]] < INSN_LUID (loop_end)
4276           && (! not_every_iteration
4277               || last_use_this_basic_block (dest_reg, insn)))
4278         {
4279           /* Now check that there are no assignments to the biv within the
4280              giv's lifetime.  This requires two separate checks.  */
4281
4282           /* Check each biv update, and fail if any are between the first
4283              and last use of the giv.
4284              
4285              If this loop contains an inner loop that was unrolled, then
4286              the insn modifying the biv may have been emitted by the loop
4287              unrolling code, and hence does not have a valid luid.  Just
4288              mark the biv as not replaceable in this case.  It is not very
4289              useful as a biv, because it is used in two different loops.
4290              It is very unlikely that we would be able to optimize the giv
4291              using this biv anyways.  */
4292
4293           v->replaceable = 1;
4294           for (b = bl->biv; b; b = b->next_iv)
4295             {
4296               if (INSN_UID (b->insn) >= max_uid_for_loop
4297                   || ((uid_luid[INSN_UID (b->insn)]
4298                        >= uid_luid[regno_first_uid[REGNO (dest_reg)]])
4299                       && (uid_luid[INSN_UID (b->insn)]
4300                           <= uid_luid[regno_last_uid[REGNO (dest_reg)]])))
4301                 {
4302                   v->replaceable = 0;
4303                   v->not_replaceable = 1;
4304                   break;
4305                 }
4306             }
4307
4308           /* Check each insn between the first and last use of the giv,
4309              and fail if any of them are branches that jump to a named label
4310              outside this range, but still inside the loop.  This catches
4311              cases of spaghetti code where the execution order of insns
4312              is not linear, and hence the above test fails.  For example,
4313              in the following code, j is not replaceable:
4314              for (i = 0; i < 100; )      {
4315              L0:        j = 4*i; goto L1;
4316              L2:        k = j;   goto L3;
4317              L1:        i++;     goto L2;
4318              L3:        ;        }
4319              printf ("k = %d\n", k); }
4320              This test is conservative, but this test succeeds rarely enough
4321              that it isn't a problem.  See also check_final_value below.  */
4322
4323           if (v->replaceable)
4324             for (p = insn;
4325                  INSN_UID (p) >= max_uid_for_loop
4326                  || INSN_LUID (p) < uid_luid[regno_last_uid[REGNO (dest_reg)]];
4327                  p = NEXT_INSN (p))
4328               {
4329                 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
4330                     && LABEL_NAME (JUMP_LABEL (p))
4331                     && ((INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop_start)
4332                          && (INSN_LUID (JUMP_LABEL (p))
4333                              < uid_luid[regno_first_uid[REGNO (dest_reg)]]))
4334                         || (INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop_end)
4335                             && (INSN_LUID (JUMP_LABEL (p))
4336                                 > uid_luid[regno_last_uid[REGNO (dest_reg)]]))))
4337                   {
4338                     v->replaceable = 0;
4339                     v->not_replaceable = 1;
4340
4341                     if (loop_dump_stream)
4342                       fprintf (loop_dump_stream,
4343                                "Found branch outside giv lifetime.\n");
4344
4345                     break;
4346                   }
4347               }
4348         }
4349       else
4350         {
4351           /* May still be replaceable, we don't have enough info here to
4352              decide.  */
4353           v->replaceable = 0;
4354           v->not_replaceable = 0;
4355         }
4356     }
4357
4358   if (loop_dump_stream)
4359     {
4360       if (type == DEST_REG)
4361         fprintf (loop_dump_stream, "Insn %d: giv reg %d",
4362                  INSN_UID (insn), REGNO (dest_reg));
4363       else
4364         fprintf (loop_dump_stream, "Insn %d: dest address",
4365                  INSN_UID (insn));
4366
4367       fprintf (loop_dump_stream, " src reg %d benefit %d",
4368                REGNO (src_reg), v->benefit);
4369       fprintf (loop_dump_stream, " used %d lifetime %d",
4370                v->times_used, v->lifetime);
4371
4372       if (v->replaceable)
4373         fprintf (loop_dump_stream, " replaceable");
4374
4375       if (GET_CODE (mult_val) == CONST_INT)
4376         fprintf (loop_dump_stream, " mult %d",
4377                  INTVAL (mult_val));
4378       else
4379         {
4380           fprintf (loop_dump_stream, " mult ");
4381           print_rtl (loop_dump_stream, mult_val);
4382         }
4383
4384       if (GET_CODE (add_val) == CONST_INT)
4385         fprintf (loop_dump_stream, " add %d",
4386                  INTVAL (add_val));
4387       else
4388         {
4389           fprintf (loop_dump_stream, " add ");
4390           print_rtl (loop_dump_stream, add_val);
4391         }
4392     }
4393
4394   if (loop_dump_stream)
4395     fprintf (loop_dump_stream, "\n");
4396
4397 }
4398
4399
4400 /* All this does is determine whether a giv can be made replaceable because
4401    its final value can be calculated.  This code can not be part of record_giv
4402    above, because final_giv_value requires that the number of loop iterations
4403    be known, and that can not be accurately calculated until after all givs
4404    have been identified.  */
4405
4406 static void
4407 check_final_value (v, loop_start, loop_end)
4408      struct induction *v;
4409      rtx loop_start, loop_end;
4410 {
4411   struct iv_class *bl;
4412   rtx final_value = 0;
4413   rtx tem;
4414
4415   bl = reg_biv_class[REGNO (v->src_reg)];
4416
4417   /* DEST_ADDR givs will never reach here, because they are always marked
4418      replaceable above in record_giv.  */
4419
4420   /* The giv can be replaced outright by the reduced register only if all
4421      of the following conditions are true:
4422      - the insn that sets the giv is always executed on any iteration
4423        on which the giv is used at all
4424        (there are two ways to deduce this:
4425         either the insn is executed on every iteration,
4426         or all uses follow that insn in the same basic block),
4427      - its final value can be calculated (this condition is different
4428        than the one above in record_giv)
4429      - no assignments to the biv occur during the giv's lifetime.  */
4430
4431 #if 0
4432   /* This is only called now when replaceable is known to be false.  */
4433   /* Clear replaceable, so that it won't confuse final_giv_value.  */
4434   v->replaceable = 0;
4435 #endif
4436
4437   if ((final_value = final_giv_value (v, loop_start, loop_end))
4438       && (v->always_computable || last_use_this_basic_block (v->dest_reg, v->insn)))
4439     {
4440       int biv_increment_seen = 0;
4441       rtx p = v->insn;
4442       rtx last_giv_use;
4443
4444       v->replaceable = 1;
4445
4446       /* When trying to determine whether or not a biv increment occurs
4447          during the lifetime of the giv, we can ignore uses of the variable
4448          outside the loop because final_value is true.  Hence we can not
4449          use regno_last_uid and regno_first_uid as above in record_giv.  */
4450
4451       /* Search the loop to determine whether any assignments to the
4452          biv occur during the giv's lifetime.  Start with the insn
4453          that sets the giv, and search around the loop until we come
4454          back to that insn again.
4455
4456          Also fail if there is a jump within the giv's lifetime that jumps
4457          to somewhere outside the lifetime but still within the loop.  This
4458          catches spaghetti code where the execution order is not linear, and
4459          hence the above test fails.  Here we assume that the giv lifetime
4460          does not extend from one iteration of the loop to the next, so as
4461          to make the test easier.  Since the lifetime isn't known yet,
4462          this requires two loops.  See also record_giv above.  */
4463
4464       last_giv_use = v->insn;
4465
4466       while (1)
4467         {
4468           p = NEXT_INSN (p);
4469           if (p == loop_end)
4470             p = NEXT_INSN (loop_start);
4471           if (p == v->insn)
4472             break;
4473
4474           if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4475               || GET_CODE (p) == CALL_INSN)
4476             {
4477               if (biv_increment_seen)
4478                 {
4479                   if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
4480                     {
4481                       v->replaceable = 0;
4482                       v->not_replaceable = 1;
4483                       break;
4484                     }
4485                 }
4486               else if (GET_CODE (PATTERN (p)) == SET
4487                        && SET_DEST (PATTERN (p)) == v->src_reg)
4488                 biv_increment_seen = 1;
4489               else if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
4490                 last_giv_use = p;
4491             }
4492         }
4493       
4494       /* Now that the lifetime of the giv is known, check for branches
4495          from within the lifetime to outside the lifetime if it is still
4496          replaceable.  */
4497
4498       if (v->replaceable)
4499         {
4500           p = v->insn;
4501           while (1)
4502             {
4503               p = NEXT_INSN (p);
4504               if (p == loop_end)
4505                 p = NEXT_INSN (loop_start);
4506               if (p == last_giv_use)
4507                 break;
4508
4509               if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
4510                   && LABEL_NAME (JUMP_LABEL (p))
4511                   && ((INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (v->insn)
4512                        && INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop_start))
4513                       || (INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (last_giv_use)
4514                           && INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop_end))))
4515                 {
4516                   v->replaceable = 0;
4517                   v->not_replaceable = 1;
4518
4519                   if (loop_dump_stream)
4520                     fprintf (loop_dump_stream,
4521                              "Found branch outside giv lifetime.\n");
4522
4523                   break;
4524                 }
4525             }
4526         }
4527
4528       /* If it is replaceable, then save the final value.  */
4529       if (v->replaceable)
4530         v->final_value = final_value;
4531     }
4532
4533   if (loop_dump_stream && v->replaceable)
4534     fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
4535              INSN_UID (v->insn), REGNO (v->dest_reg));
4536 }
4537 \f
4538 /* Update the status of whether a giv can derive other givs.
4539
4540    We need to do something special if there is or may be an update to the biv
4541    between the time the giv is defined and the time it is used to derive
4542    another giv.
4543
4544    In addition, a giv that is only conditionally set is not allowed to
4545    derive another giv once a label has been passed.
4546
4547    The cases we look at are when a label or an update to a biv is passed.  */
4548
4549 static void
4550 update_giv_derive (p)
4551      rtx p;
4552 {
4553   struct iv_class *bl;
4554   struct induction *biv, *giv;
4555   rtx tem;
4556   int dummy;
4557
4558   /* Search all IV classes, then all bivs, and finally all givs.
4559
4560      There are three cases we are concerned with.  First we have the situation
4561      of a giv that is only updated conditionally.  In that case, it may not
4562      derive any givs after a label is passed.
4563
4564      The second case is when a biv update occurs, or may occur, after the
4565      definition of a giv.  For certain biv updates (see below) that are
4566      known to occur between the giv definition and use, we can adjust the
4567      giv definition.  For others, or when the biv update is conditional,
4568      we must prevent the giv from deriving any other givs.  There are two
4569      sub-cases within this case.
4570
4571      If this is a label, we are concerned with any biv update that is done
4572      conditionally, since it may be done after the giv is defined followed by
4573      a branch here (actually, we need to pass both a jump and a label, but
4574      this extra tracking doesn't seem worth it).
4575
4576      If this is a jump, we are concerned about any biv update that may be
4577      executed multiple times.  We are actually only concerned about
4578      backward jumps, but it is probably not worth performing the test
4579      on the jump again here.
4580
4581      If this is a biv update, we must adjust the giv status to show that a
4582      subsequent biv update was performed.  If this adjustment cannot be done,
4583      the giv cannot derive further givs.  */
4584
4585   for (bl = loop_iv_list; bl; bl = bl->next)
4586     for (biv = bl->biv; biv; biv = biv->next_iv)
4587       if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
4588           || biv->insn == p)
4589         {
4590           for (giv = bl->giv; giv; giv = giv->next_iv)
4591             {
4592               /* If cant_derive is already true, there is no point in
4593                  checking all of these conditions again.  */
4594               if (giv->cant_derive)
4595                 continue;
4596
4597               /* If this giv is conditionally set and we have passed a label,
4598                  it cannot derive anything.  */
4599               if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
4600                 giv->cant_derive = 1;
4601
4602               /* Skip givs that have mult_val == 0, since
4603                  they are really invariants.  Also skip those that are
4604                  replaceable, since we know their lifetime doesn't contain
4605                  any biv update.  */
4606               else if (giv->mult_val == const0_rtx || giv->replaceable)
4607                 continue;
4608
4609               /* The only way we can allow this giv to derive another
4610                  is if this is a biv increment and we can form the product
4611                  of biv->add_val and giv->mult_val.  In this case, we will
4612                  be able to compute a compensation.  */
4613               else if (biv->insn == p)
4614                 {
4615                   tem = 0;
4616
4617                   if (biv->mult_val == const1_rtx)
4618                     tem = simplify_giv_expr (gen_rtx (MULT, giv->mode,
4619                                                       biv->add_val,
4620                                                       giv->mult_val),
4621                                              &dummy);
4622
4623                   if (tem && giv->derive_adjustment)
4624                     tem = simplify_giv_expr (gen_rtx (PLUS, giv->mode, tem,
4625                                                       giv->derive_adjustment),
4626                                              &dummy);
4627                   if (tem)
4628                     giv->derive_adjustment = tem;
4629                   else
4630                     giv->cant_derive = 1;
4631                 }
4632               else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
4633                        || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
4634                 giv->cant_derive = 1;
4635             }
4636         }
4637 }
4638 \f
4639 /* Check whether an insn is an increment legitimate for a basic induction var.
4640    X is the source of insn P.
4641    DEST_REG is the putative biv, also the destination of the insn.
4642    We accept patterns of these forms:
4643      REG = REG + INVARIANT (includes REG = REG - CONSTANT)
4644      REG = INVARIANT + REG
4645
4646    If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
4647    and store the additive term into *INC_VAL.
4648
4649    If X is an assignment of an invariant into DEST_REG, we set
4650    *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
4651
4652    We also want to detect a BIV when it corresponds to a variable
4653    whose mode was promoted via PROMOTED_MODE.  In that case, an increment
4654    of the variable may be a PLUS that adds a SUBREG of that variable to
4655    an invariant and then sign- or zero-extends the result of the PLUS
4656    into the variable.
4657
4658    Most GIVs in such cases will be in the promoted mode, since that is the
4659    probably the natural computation mode (and almost certainly the mode
4660    used for addresses) on the machine.  So we view the pseudo-reg containing
4661    the variable as the BIV, as if it were simply incremented.
4662
4663    Note that treating the entire pseudo as a BIV will result in making
4664    simple increments to any GIVs based on it.  However, if the variable
4665    overflows in its declared mode but not its promoted mode, the result will
4666    be incorrect.  This is acceptable if the variable is signed, since 
4667    overflows in such cases are undefined, but not if it is unsigned, since
4668    those overflows are defined.  So we only check for SIGN_EXTEND and
4669    not ZERO_EXTEND.
4670
4671    If we cannot find a biv, we return 0.  */
4672
4673 static int
4674 basic_induction_var (x, dest_reg, p, inc_val, mult_val)
4675      register rtx x;
4676      rtx p;
4677      rtx dest_reg;
4678      rtx *inc_val;
4679      rtx *mult_val;
4680 {
4681   register enum rtx_code code;
4682   rtx arg;
4683   rtx insn, set = 0;
4684
4685   code = GET_CODE (x);
4686   switch (code)
4687     {
4688     case PLUS:
4689       if (XEXP (x, 0) == dest_reg
4690           || (GET_CODE (XEXP (x, 0)) == SUBREG
4691               && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
4692               && SUBREG_REG (XEXP (x, 0)) == dest_reg))
4693         arg = XEXP (x, 1);
4694       else if (XEXP (x, 1) == dest_reg
4695                || (GET_CODE (XEXP (x, 1)) == SUBREG
4696                    && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
4697                    && SUBREG_REG (XEXP (x, 1)) == dest_reg))
4698         arg = XEXP (x, 0);
4699       else
4700         return 0;
4701
4702       if (invariant_p (arg) != 1)
4703         return 0;
4704
4705       *inc_val = convert_to_mode (GET_MODE (dest_reg), arg, 0);;
4706       *mult_val = const1_rtx;
4707       return 1;
4708
4709     case SUBREG:
4710       /* If this is a SUBREG for a promoted variable, check the inner
4711          value.  */
4712       if (SUBREG_PROMOTED_VAR_P (x))
4713           return basic_induction_var (SUBREG_REG (x), dest_reg, p,
4714                                     inc_val, mult_val);
4715
4716     case REG:
4717       /* If this register is assigned in the previous insn, look at its
4718          source, but don't go outside the loop or past a label.  */
4719
4720       for (insn = PREV_INSN (p);
4721            (insn && GET_CODE (insn) == NOTE
4722             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
4723            insn = PREV_INSN (insn))
4724         ;
4725
4726       if (insn)
4727         set = single_set (insn);
4728
4729       if (set != 0 && SET_DEST (set) == x)
4730         return basic_induction_var (SET_SRC (set), dest_reg, insn,
4731                                     inc_val, mult_val);
4732       /* ... fall through ... */
4733
4734       /* Can accept constant setting of biv only when inside inner most loop.
4735          Otherwise, a biv of an inner loop may be incorrectly recognized
4736          as a biv of the outer loop,
4737          causing code to be moved INTO the inner loop.  */
4738     case MEM:
4739       if (invariant_p (x) != 1)
4740         return 0;
4741     case CONST_INT:
4742     case SYMBOL_REF:
4743     case CONST:
4744       if (loops_enclosed == 1)
4745         {
4746           *inc_val = convert_to_mode (GET_MODE (dest_reg), x, 0);;
4747           *mult_val = const0_rtx;
4748           return 1;
4749         }
4750       else
4751         return 0;
4752
4753     case SIGN_EXTEND:
4754       return basic_induction_var (XEXP (x, 0), dest_reg, p,
4755                                   inc_val, mult_val);
4756     case ASHIFTRT:
4757       /* Similar, since this can be a sign extension.  */
4758       for (insn = PREV_INSN (p);
4759            (insn && GET_CODE (insn) == NOTE
4760             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
4761            insn = PREV_INSN (insn))
4762         ;
4763
4764       if (insn)
4765         set = single_set (insn);
4766
4767       if (set && SET_DEST (set) == XEXP (x, 0)
4768           && GET_CODE (XEXP (x, 1)) == CONST_INT
4769           && INTVAL (XEXP (x, 1)) >= 0
4770           && GET_CODE (SET_SRC (set)) == ASHIFT
4771           && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
4772         return basic_induction_var (XEXP (SET_SRC (set), 0), dest_reg, insn,
4773                                     inc_val, mult_val);
4774       return 0;
4775
4776     default:
4777       return 0;
4778     }
4779 }
4780 \f
4781 /* A general induction variable (giv) is any quantity that is a linear
4782    function   of a basic induction variable,
4783    i.e. giv = biv * mult_val + add_val.
4784    The coefficients can be any loop invariant quantity.
4785    A giv need not be computed directly from the biv;
4786    it can be computed by way of other givs.  */
4787
4788 /* Determine whether X computes a giv.
4789    If it does, return a nonzero value
4790      which is the benefit from eliminating the computation of X;
4791    set *SRC_REG to the register of the biv that it is computed from;
4792    set *ADD_VAL and *MULT_VAL to the coefficients,
4793      such that the value of X is biv * mult + add;  */
4794
4795 static int
4796 general_induction_var (x, src_reg, add_val, mult_val)
4797      rtx x;
4798      rtx *src_reg;
4799      rtx *add_val;
4800      rtx *mult_val;
4801 {
4802   rtx orig_x = x;
4803   int benefit = 0;
4804   char *storage;
4805
4806   /* If this is an invariant, forget it, it isn't a giv.  */
4807   if (invariant_p (x) == 1)
4808     return 0;
4809
4810   /* See if the expression could be a giv and get its form.
4811      Mark our place on the obstack in case we don't find a giv.  */
4812   storage = (char *) oballoc (0);
4813   x = simplify_giv_expr (x, &benefit);
4814   if (x == 0)
4815     {
4816       obfree (storage);
4817       return 0;
4818     }
4819
4820   switch (GET_CODE (x))
4821     {
4822     case USE:
4823     case CONST_INT:
4824       /* Since this is now an invariant and wasn't before, it must be a giv
4825          with MULT_VAL == 0.  It doesn't matter which BIV we associate this
4826          with.  */
4827       *src_reg = loop_iv_list->biv->dest_reg;
4828       *mult_val = const0_rtx;
4829       *add_val = x;
4830       break;
4831
4832     case REG:
4833       /* This is equivalent to a BIV.  */
4834       *src_reg = x;
4835       *mult_val = const1_rtx;
4836       *add_val = const0_rtx;
4837       break;
4838
4839     case PLUS:
4840       /* Either (plus (biv) (invar)) or
4841          (plus (mult (biv) (invar_1)) (invar_2)).  */
4842       if (GET_CODE (XEXP (x, 0)) == MULT)
4843         {
4844           *src_reg = XEXP (XEXP (x, 0), 0);
4845           *mult_val = XEXP (XEXP (x, 0), 1);
4846         }
4847       else
4848         {
4849           *src_reg = XEXP (x, 0);
4850           *mult_val = const1_rtx;
4851         }
4852       *add_val = XEXP (x, 1);
4853       break;
4854
4855     case MULT:
4856       /* ADD_VAL is zero.  */
4857       *src_reg = XEXP (x, 0);
4858       *mult_val = XEXP (x, 1);
4859       *add_val = const0_rtx;
4860       break;
4861
4862     default:
4863       abort ();
4864     }
4865
4866   /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
4867      unless they are CONST_INT).  */
4868   if (GET_CODE (*add_val) == USE)
4869     *add_val = XEXP (*add_val, 0);
4870   if (GET_CODE (*mult_val) == USE)
4871     *mult_val = XEXP (*mult_val, 0);
4872
4873   benefit += rtx_cost (orig_x, SET);
4874
4875   /* Always return some benefit if this is a giv so it will be detected
4876      as such.  This allows elimination of bivs that might otherwise
4877      not be eliminated.  */
4878   return benefit == 0 ? 1 : benefit;
4879 }
4880 \f
4881 /* Given an expression, X, try to form it as a linear function of a biv.
4882    We will canonicalize it to be of the form
4883         (plus (mult (BIV) (invar_1))
4884               (invar_2))
4885    with possible degeneracies.
4886
4887    The invariant expressions must each be of a form that can be used as a
4888    machine operand.  We surround then with a USE rtx (a hack, but localized
4889    and certainly unambiguous!) if not a CONST_INT for simplicity in this
4890    routine; it is the caller's responsibility to strip them.
4891
4892    If no such canonicalization is possible (i.e., two biv's are used or an
4893    expression that is neither invariant nor a biv or giv), this routine
4894    returns 0.
4895
4896    For a non-zero return, the result will have a code of CONST_INT, USE,
4897    REG (for a BIV), PLUS, or MULT.  No other codes will occur.  
4898
4899    *BENEFIT will be incremented by the benefit of any sub-giv encountered.  */
4900
4901 static rtx
4902 simplify_giv_expr (x, benefit)
4903      rtx x;
4904      int *benefit;
4905 {
4906   enum machine_mode mode = GET_MODE (x);
4907   rtx arg0, arg1;
4908   rtx tem;
4909
4910   /* If this is not an integer mode, or if we cannot do arithmetic in this
4911      mode, this can't be a giv.  */
4912   if (mode != VOIDmode
4913       && (GET_MODE_CLASS (mode) != MODE_INT
4914           || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
4915     return 0;
4916
4917   switch (GET_CODE (x))
4918     {
4919     case PLUS:
4920       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
4921       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
4922       if (arg0 == 0 || arg1 == 0)
4923         return 0;
4924
4925       /* Put constant last, CONST_INT last if both constant.  */
4926       if ((GET_CODE (arg0) == USE
4927            || GET_CODE (arg0) == CONST_INT)
4928           && GET_CODE (arg1) != CONST_INT)
4929         tem = arg0, arg0 = arg1, arg1 = tem;
4930
4931       /* Handle addition of zero, then addition of an invariant.  */
4932       if (arg1 == const0_rtx)
4933         return arg0;
4934       else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
4935         switch (GET_CODE (arg0))
4936           {
4937           case CONST_INT:
4938           case USE:
4939             /* Both invariant.  Only valid if sum is machine operand.
4940                First strip off possible USE on first operand.  */
4941             if (GET_CODE (arg0) == USE)
4942               arg0 = XEXP (arg0, 0);
4943
4944             tem = 0;
4945             if (CONSTANT_P (arg0) && GET_CODE (arg1) == CONST_INT)
4946               {
4947                 tem = plus_constant (arg0, INTVAL (arg1));
4948                 if (GET_CODE (tem) != CONST_INT)
4949                   tem = gen_rtx (USE, mode, tem);
4950               }
4951
4952             return tem;
4953
4954           case REG:
4955           case MULT:
4956             /* biv + invar or mult + invar.  Return sum.  */
4957             return gen_rtx (PLUS, mode, arg0, arg1);
4958
4959           case PLUS:
4960             /* (a + invar_1) + invar_2.  Associate.  */
4961             return simplify_giv_expr (gen_rtx (PLUS, mode,
4962                                                XEXP (arg0, 0),
4963                                                gen_rtx (PLUS, mode,
4964                                                         XEXP (arg0, 1), arg1)),
4965                                       benefit);
4966
4967           default:
4968             abort ();
4969           }
4970
4971       /* Each argument must be either REG, PLUS, or MULT.  Convert REG to
4972          MULT to reduce cases.  */
4973       if (GET_CODE (arg0) == REG)
4974         arg0 = gen_rtx (MULT, mode, arg0, const1_rtx);
4975       if (GET_CODE (arg1) == REG)
4976         arg1 = gen_rtx (MULT, mode, arg1, const1_rtx);
4977
4978       /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
4979          Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
4980          Recurse to associate the second PLUS.  */
4981       if (GET_CODE (arg1) == MULT)
4982         tem = arg0, arg0 = arg1, arg1 = tem;
4983
4984       if (GET_CODE (arg1) == PLUS)
4985           return simplify_giv_expr (gen_rtx (PLUS, mode,
4986                                              gen_rtx (PLUS, mode,
4987                                                       arg0, XEXP (arg1, 0)),
4988                                              XEXP (arg1, 1)),
4989                                     benefit);
4990
4991       /* Now must have MULT + MULT.  Distribute if same biv, else not giv.  */
4992       if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
4993         abort ();
4994
4995       if (XEXP (arg0, 0) != XEXP (arg1, 0))
4996         return 0;
4997
4998       return simplify_giv_expr (gen_rtx (MULT, mode,
4999                                          XEXP (arg0, 0),
5000                                          gen_rtx (PLUS, mode,
5001                                                   XEXP (arg0, 1),
5002                                                   XEXP (arg1, 1))),
5003                                 benefit);
5004
5005     case MINUS:
5006       /* Handle "a - b" as "a + b * (-1)". */
5007       return simplify_giv_expr (gen_rtx (PLUS, mode,
5008                                          XEXP (x, 0),
5009                                          gen_rtx (MULT, mode,
5010                                                   XEXP (x, 1), constm1_rtx)),
5011                                 benefit);
5012
5013     case MULT:
5014       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
5015       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
5016       if (arg0 == 0 || arg1 == 0)
5017         return 0;
5018
5019       /* Put constant last, CONST_INT last if both constant.  */
5020       if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
5021           && GET_CODE (arg1) != CONST_INT)
5022         tem = arg0, arg0 = arg1, arg1 = tem;
5023
5024       /* If second argument is not now constant, not giv.  */
5025       if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
5026         return 0;
5027
5028       /* Handle multiply by 0 or 1.  */
5029       if (arg1 == const0_rtx)
5030         return const0_rtx;
5031
5032       else if (arg1 == const1_rtx)
5033         return arg0;
5034
5035       switch (GET_CODE (arg0))
5036         {
5037         case REG:
5038           /* biv * invar.  Done.  */
5039           return gen_rtx (MULT, mode, arg0, arg1);
5040
5041         case CONST_INT:
5042           /* Product of two constants.  */
5043           return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
5044
5045         case USE:
5046           /* invar * invar.  Not giv. */
5047           return 0;
5048
5049         case MULT:
5050           /* (a * invar_1) * invar_2.  Associate.  */
5051           return simplify_giv_expr (gen_rtx (MULT, mode,
5052                                              XEXP (arg0, 0),
5053                                              gen_rtx (MULT, mode,
5054                                                       XEXP (arg0, 1), arg1)),
5055                                     benefit);
5056
5057         case PLUS:
5058           /* (a + invar_1) * invar_2.  Distribute.  */
5059           return simplify_giv_expr (gen_rtx (PLUS, mode,
5060                                              gen_rtx (MULT, mode,
5061                                                       XEXP (arg0, 0), arg1),
5062                                              gen_rtx (MULT, mode,
5063                                                       XEXP (arg0, 1), arg1)),
5064                                     benefit);
5065
5066         default:
5067           abort ();
5068         }
5069
5070     case ASHIFT:
5071     case LSHIFT:
5072       /* Shift by constant is multiply by power of two.  */
5073       if (GET_CODE (XEXP (x, 1)) != CONST_INT)
5074         return 0;
5075
5076       return simplify_giv_expr (gen_rtx (MULT, mode,
5077                                          XEXP (x, 0),
5078                                          GEN_INT ((HOST_WIDE_INT) 1
5079                                                   << INTVAL (XEXP (x, 1)))),
5080                                 benefit);
5081
5082     case NEG:
5083       /* "-a" is "a * (-1)" */
5084       return simplify_giv_expr (gen_rtx (MULT, mode, XEXP (x, 0), constm1_rtx),
5085                                 benefit);
5086
5087     case NOT:
5088       /* "~a" is "-a - 1". Silly, but easy.  */
5089       return simplify_giv_expr (gen_rtx (MINUS, mode,
5090                                          gen_rtx (NEG, mode, XEXP (x, 0)),
5091                                          const1_rtx),
5092                                 benefit);
5093
5094     case USE:
5095       /* Already in proper form for invariant.  */
5096       return x;
5097
5098     case REG:
5099       /* If this is a new register, we can't deal with it.  */
5100       if (REGNO (x) >= max_reg_before_loop)
5101         return 0;
5102
5103       /* Check for biv or giv.  */
5104       switch (reg_iv_type[REGNO (x)])
5105         {
5106         case BASIC_INDUCT:
5107           return x;
5108         case GENERAL_INDUCT:
5109           {
5110             struct induction *v = reg_iv_info[REGNO (x)];
5111
5112             /* Form expression from giv and add benefit.  Ensure this giv
5113                can derive another and subtract any needed adjustment if so.  */
5114             *benefit += v->benefit;
5115             if (v->cant_derive)
5116               return 0;
5117
5118             tem = gen_rtx (PLUS, mode, gen_rtx (MULT, mode,
5119                                                 v->src_reg, v->mult_val),
5120                            v->add_val);
5121             if (v->derive_adjustment)
5122               tem = gen_rtx (MINUS, mode, tem, v->derive_adjustment);
5123             return simplify_giv_expr (tem, benefit);
5124           }
5125         }
5126
5127       /* Fall through to general case.  */
5128     default:
5129       /* If invariant, return as USE (unless CONST_INT).
5130          Otherwise, not giv.  */
5131       if (GET_CODE (x) == USE)
5132         x = XEXP (x, 0);
5133
5134       if (invariant_p (x) == 1)
5135         {
5136           if (GET_CODE (x) == CONST_INT)
5137             return x;
5138           else
5139             return gen_rtx (USE, mode, x);
5140         }
5141       else
5142         return 0;
5143     }
5144 }
5145 \f
5146 /* Help detect a giv that is calculated by several consecutive insns;
5147    for example,
5148       giv = biv * M
5149       giv = giv + A
5150    The caller has already identified the first insn P as having a giv as dest;
5151    we check that all other insns that set the same register follow
5152    immediately after P, that they alter nothing else,
5153    and that the result of the last is still a giv.
5154
5155    The value is 0 if the reg set in P is not really a giv.
5156    Otherwise, the value is the amount gained by eliminating
5157    all the consecutive insns that compute the value.
5158
5159    FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
5160    SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
5161
5162    The coefficients of the ultimate giv value are stored in
5163    *MULT_VAL and *ADD_VAL.  */
5164
5165 static int
5166 consec_sets_giv (first_benefit, p, src_reg, dest_reg,
5167                  add_val, mult_val)
5168      int first_benefit;
5169      rtx p;
5170      rtx src_reg;
5171      rtx dest_reg;
5172      rtx *add_val;
5173      rtx *mult_val;
5174 {
5175   int count;
5176   enum rtx_code code;
5177   int benefit;
5178   rtx temp;
5179   rtx set;
5180
5181   /* Indicate that this is a giv so that we can update the value produced in
5182      each insn of the multi-insn sequence. 
5183
5184      This induction structure will be used only by the call to
5185      general_induction_var below, so we can allocate it on our stack.
5186      If this is a giv, our caller will replace the induct var entry with
5187      a new induction structure.  */
5188   struct induction *v
5189     = (struct induction *) alloca (sizeof (struct induction));
5190   v->src_reg = src_reg;
5191   v->mult_val = *mult_val;
5192   v->add_val = *add_val;
5193   v->benefit = first_benefit;
5194   v->cant_derive = 0;
5195   v->derive_adjustment = 0;
5196
5197   reg_iv_type[REGNO (dest_reg)] = GENERAL_INDUCT;
5198   reg_iv_info[REGNO (dest_reg)] = v;
5199
5200   count = n_times_set[REGNO (dest_reg)] - 1;
5201
5202   while (count > 0)
5203     {
5204       p = NEXT_INSN (p);
5205       code = GET_CODE (p);
5206
5207       /* If libcall, skip to end of call sequence.  */
5208       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
5209         p = XEXP (temp, 0);
5210
5211       if (code == INSN
5212           && (set = single_set (p))
5213           && GET_CODE (SET_DEST (set)) == REG
5214           && SET_DEST (set) == dest_reg
5215           && ((benefit = general_induction_var (SET_SRC (set), &src_reg,
5216                                                 add_val, mult_val))
5217               /* Giv created by equivalent expression.  */
5218               || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
5219                   && (benefit = general_induction_var (XEXP (temp, 0), &src_reg,
5220                                                        add_val, mult_val))))
5221           && src_reg == v->src_reg)
5222         {
5223           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
5224             benefit += libcall_benefit (p);
5225
5226           count--;
5227           v->mult_val = *mult_val;
5228           v->add_val = *add_val;
5229           v->benefit = benefit;
5230         }
5231       else if (code != NOTE)
5232         {
5233           /* Allow insns that set something other than this giv to a
5234              constant.  Such insns are needed on machines which cannot
5235              include long constants and should not disqualify a giv.  */
5236           if (code == INSN
5237               && (set = single_set (p))
5238               && SET_DEST (set) != dest_reg
5239               && CONSTANT_P (SET_SRC (set)))
5240             continue;
5241
5242           reg_iv_type[REGNO (dest_reg)] = UNKNOWN_INDUCT;
5243           return 0;
5244         }
5245     }
5246
5247   return v->benefit;
5248 }
5249 \f
5250 /* Return an rtx, if any, that expresses giv G2 as a function of the register
5251    represented by G1.  If no such expression can be found, or it is clear that
5252    it cannot possibly be a valid address, 0 is returned. 
5253
5254    To perform the computation, we note that
5255         G1 = a * v + b          and
5256         G2 = c * v + d
5257    where `v' is the biv.
5258
5259    So G2 = (c/a) * G1 + (d - b*c/a)  */
5260
5261 #ifdef ADDRESS_COST
5262 static rtx
5263 express_from (g1, g2)
5264      struct induction *g1, *g2;
5265 {
5266   rtx mult, add;
5267
5268   /* The value that G1 will be multiplied by must be a constant integer.  Also,
5269      the only chance we have of getting a valid address is if b*c/a (see above
5270      for notation) is also an integer.  */
5271   if (GET_CODE (g1->mult_val) != CONST_INT
5272       || GET_CODE (g2->mult_val) != CONST_INT
5273       || GET_CODE (g1->add_val) != CONST_INT
5274       || g1->mult_val == const0_rtx
5275       || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
5276     return 0;
5277
5278   mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
5279   add = plus_constant (g2->add_val, - INTVAL (g1->add_val) * INTVAL (mult));
5280
5281   /* Form simplified final result.  */
5282   if (mult == const0_rtx)
5283     return add;
5284   else if (mult == const1_rtx)
5285     mult = g1->dest_reg;
5286   else
5287     mult = gen_rtx (MULT, g2->mode, g1->dest_reg, mult);
5288
5289   if (add == const0_rtx)
5290     return mult;
5291   else
5292     return gen_rtx (PLUS, g2->mode, mult, add);
5293 }
5294 #endif
5295 \f
5296 /* Return 1 if giv G2 can be combined with G1.  This means that G2 can use
5297    (either directly or via an address expression) a register used to represent
5298    G1.  Set g2->new_reg to a represtation of G1 (normally just
5299    g1->dest_reg).  */
5300
5301 static int
5302 combine_givs_p (g1, g2)
5303      struct induction *g1, *g2;
5304 {
5305   rtx tem;
5306
5307   /* If these givs are identical, they can be combined.  */
5308   if (rtx_equal_p (g1->mult_val, g2->mult_val)
5309       && rtx_equal_p (g1->add_val, g2->add_val))
5310     {
5311       g2->new_reg = g1->dest_reg;
5312       return 1;
5313     }
5314
5315 #ifdef ADDRESS_COST
5316   /* If G2 can be expressed as a function of G1 and that function is valid
5317      as an address and no more expensive than using a register for G2,
5318      the expression of G2 in terms of G1 can be used.  */
5319   if (g2->giv_type == DEST_ADDR
5320       && (tem = express_from (g1, g2)) != 0
5321       && memory_address_p (g2->mem_mode, tem)
5322       && ADDRESS_COST (tem) <= ADDRESS_COST (*g2->location))
5323     {
5324       g2->new_reg = tem;
5325       return 1;
5326     }
5327 #endif
5328
5329   return 0;
5330 }
5331 \f
5332 /* Check all pairs of givs for iv_class BL and see if any can be combined with
5333    any other.  If so, point SAME to the giv combined with and set NEW_REG to
5334    be an expression (in terms of the other giv's DEST_REG) equivalent to the
5335    giv.  Also, update BENEFIT and related fields for cost/benefit analysis.  */
5336
5337 static void
5338 combine_givs (bl)
5339      struct iv_class *bl;
5340 {
5341   struct induction *g1, *g2;
5342   int pass;
5343
5344   for (g1 = bl->giv; g1; g1 = g1->next_iv)
5345     for (pass = 0; pass <= 1; pass++)
5346       for (g2 = bl->giv; g2; g2 = g2->next_iv)
5347         if (g1 != g2
5348             /* First try to combine with replaceable givs, then all givs. */
5349             && (g1->replaceable || pass == 1)
5350             /* If either has already been combined or is to be ignored, can't
5351                combine.  */
5352             && ! g1->ignore && ! g2->ignore && ! g1->same && ! g2->same
5353             /* If something has been based on G2, G2 cannot itself be based
5354                on something else.  */
5355             && ! g2->combined_with
5356             && combine_givs_p (g1, g2))
5357           {
5358             /* g2->new_reg set by `combine_givs_p'  */
5359             g2->same = g1;
5360             g1->combined_with = 1;
5361             g1->benefit += g2->benefit;
5362             /* ??? The new final_[bg]iv_value code does a much better job
5363                of finding replaceable giv's, and hence this code may no
5364                longer be necessary.  */
5365             if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
5366               g1->benefit -= copy_cost;
5367             g1->lifetime += g2->lifetime;
5368             g1->times_used += g2->times_used;
5369
5370             if (loop_dump_stream)
5371               fprintf (loop_dump_stream, "giv at %d combined with giv at %d\n",
5372                        INSN_UID (g2->insn), INSN_UID (g1->insn));
5373           }
5374 }
5375 \f
5376 /* EMIT code before INSERT_BEFORE to set REG = B * M + A.  */
5377
5378 void
5379 emit_iv_add_mult (b, m, a, reg, insert_before)
5380      rtx b;          /* initial value of basic induction variable */
5381      rtx m;          /* multiplicative constant */
5382      rtx a;          /* additive constant */
5383      rtx reg;        /* destination register */
5384      rtx insert_before;
5385 {
5386   rtx seq;
5387   rtx result;
5388
5389   /* Prevent unexpected sharing of these rtx.  */
5390   a = copy_rtx (a);
5391   b = copy_rtx (b);
5392
5393   /* Increase the lifetime of any invariants moved further in code. */
5394   update_reg_last_use (a, insert_before);
5395   update_reg_last_use (b, insert_before);
5396   update_reg_last_use (m, insert_before);
5397
5398   start_sequence ();
5399   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 0);
5400   if (reg != result)
5401     emit_move_insn (reg, result);
5402   seq = gen_sequence ();
5403   end_sequence ();
5404
5405   emit_insn_before (seq, insert_before);
5406 }
5407 \f
5408 /* Test whether A * B can be computed without
5409    an actual multiply insn.  Value is 1 if so.  */
5410
5411 static int
5412 product_cheap_p (a, b)
5413      rtx a;
5414      rtx b;
5415 {
5416   int i;
5417   rtx tmp;
5418   struct obstack *old_rtl_obstack = rtl_obstack;
5419   char *storage = (char *) obstack_alloc (&temp_obstack, 0);
5420   int win = 1;
5421
5422   /* If only one is constant, make it B. */
5423   if (GET_CODE (a) == CONST_INT)
5424     tmp = a, a = b, b = tmp;
5425
5426   /* If first constant, both constant, so don't need multiply.  */
5427   if (GET_CODE (a) == CONST_INT)
5428     return 1;
5429
5430   /* If second not constant, neither is constant, so would need multiply.  */
5431   if (GET_CODE (b) != CONST_INT)
5432     return 0;
5433
5434   /* One operand is constant, so might not need multiply insn.  Generate the
5435      code for the multiply and see if a call or multiply, or long sequence
5436      of insns is generated.  */
5437
5438   rtl_obstack = &temp_obstack;
5439   start_sequence ();
5440   expand_mult (GET_MODE (a), a, b, NULL_RTX, 0);
5441   tmp = gen_sequence ();
5442   end_sequence ();
5443
5444   if (GET_CODE (tmp) == SEQUENCE)
5445     {
5446       if (XVEC (tmp, 0) == 0)
5447         win = 1;
5448       else if (XVECLEN (tmp, 0) > 3)
5449         win = 0;
5450       else
5451         for (i = 0; i < XVECLEN (tmp, 0); i++)
5452           {
5453             rtx insn = XVECEXP (tmp, 0, i);
5454
5455             if (GET_CODE (insn) != INSN
5456                 || (GET_CODE (PATTERN (insn)) == SET
5457                     && GET_CODE (SET_SRC (PATTERN (insn))) == MULT)
5458                 || (GET_CODE (PATTERN (insn)) == PARALLEL
5459                     && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == SET
5460                     && GET_CODE (SET_SRC (XVECEXP (PATTERN (insn), 0, 0))) == MULT))
5461               {
5462                 win = 0;
5463                 break;
5464               }
5465           }
5466     }
5467   else if (GET_CODE (tmp) == SET
5468            && GET_CODE (SET_SRC (tmp)) == MULT)
5469     win = 0;
5470   else if (GET_CODE (tmp) == PARALLEL
5471            && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
5472            && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
5473     win = 0;
5474
5475   /* Free any storage we obtained in generating this multiply and restore rtl
5476      allocation to its normal obstack.  */
5477   obstack_free (&temp_obstack, storage);
5478   rtl_obstack = old_rtl_obstack;
5479
5480   return win;
5481 }
5482 \f
5483 /* Check to see if loop can be terminated by a "decrement and branch until
5484    zero" instruction.  If so, add a REG_NONNEG note to the branch insn if so.
5485    Also try reversing an increment loop to a decrement loop
5486    to see if the optimization can be performed.
5487    Value is nonzero if optimization was performed.  */
5488
5489 /* This is useful even if the architecture doesn't have such an insn,
5490    because it might change a loops which increments from 0 to n to a loop
5491    which decrements from n to 0.  A loop that decrements to zero is usually
5492    faster than one that increments from zero.  */
5493
5494 /* ??? This could be rewritten to use some of the loop unrolling procedures,
5495    such as approx_final_value, biv_total_increment, loop_iterations, and
5496    final_[bg]iv_value.  */
5497
5498 static int
5499 check_dbra_loop (loop_end, insn_count, loop_start)
5500      rtx loop_end;
5501      int insn_count;
5502      rtx loop_start;
5503 {
5504   struct iv_class *bl;
5505   rtx reg;
5506   rtx jump_label;
5507   rtx final_value;
5508   rtx start_value;
5509   enum rtx_code branch_code;
5510   rtx new_add_val;
5511   rtx comparison;
5512   rtx before_comparison;
5513   rtx p;
5514
5515   /* If last insn is a conditional branch, and the insn before tests a
5516      register value, try to optimize it.  Otherwise, we can't do anything.  */
5517
5518   comparison = get_condition_for_loop (PREV_INSN (loop_end));
5519   if (comparison == 0)
5520     return 0;
5521
5522   /* Check all of the bivs to see if the compare uses one of them.
5523      Skip biv's set more than once because we can't guarantee that
5524      it will be zero on the last iteration.  Also skip if the biv is
5525      used between its update and the test insn.  */
5526
5527   for (bl = loop_iv_list; bl; bl = bl->next)
5528     {
5529       if (bl->biv_count == 1
5530           && bl->biv->dest_reg == XEXP (comparison, 0)
5531           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
5532                                    PREV_INSN (PREV_INSN (loop_end))))
5533         break;
5534     }
5535
5536   if (! bl)
5537     return 0;
5538
5539   /* Look for the case where the basic induction variable is always
5540      nonnegative, and equals zero on the last iteration.
5541      In this case, add a reg_note REG_NONNEG, which allows the
5542      m68k DBRA instruction to be used.  */
5543
5544   if (((GET_CODE (comparison) == GT
5545         && GET_CODE (XEXP (comparison, 1)) == CONST_INT
5546         && INTVAL (XEXP (comparison, 1)) == -1)
5547        || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
5548       && GET_CODE (bl->biv->add_val) == CONST_INT
5549       && INTVAL (bl->biv->add_val) < 0)
5550     {
5551       /* Initial value must be greater than 0,
5552          init_val % -dec_value == 0 to ensure that it equals zero on
5553          the last iteration */
5554
5555       if (GET_CODE (bl->initial_value) == CONST_INT
5556           && INTVAL (bl->initial_value) > 0
5557           && (INTVAL (bl->initial_value) %
5558               (-INTVAL (bl->biv->add_val))) == 0)
5559         {
5560           /* register always nonnegative, add REG_NOTE to branch */
5561           REG_NOTES (PREV_INSN (loop_end))
5562             = gen_rtx (EXPR_LIST, REG_NONNEG, NULL_RTX,
5563                        REG_NOTES (PREV_INSN (loop_end)));
5564           bl->nonneg = 1;
5565
5566           return 1;
5567         }
5568
5569       /* If the decrement is 1 and the value was tested as >= 0 before
5570          the loop, then we can safely optimize.  */
5571       for (p = loop_start; p; p = PREV_INSN (p))
5572         {
5573           if (GET_CODE (p) == CODE_LABEL)
5574             break;
5575           if (GET_CODE (p) != JUMP_INSN)
5576             continue;
5577
5578           before_comparison = get_condition_for_loop (p);
5579           if (before_comparison
5580               && XEXP (before_comparison, 0) == bl->biv->dest_reg
5581               && GET_CODE (before_comparison) == LT
5582               && XEXP (before_comparison, 1) == const0_rtx
5583               && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
5584               && INTVAL (bl->biv->add_val) == -1)
5585             {
5586               REG_NOTES (PREV_INSN (loop_end))
5587                 = gen_rtx (EXPR_LIST, REG_NONNEG, NULL_RTX,
5588                            REG_NOTES (PREV_INSN (loop_end)));
5589               bl->nonneg = 1;
5590
5591               return 1;
5592             }
5593         }
5594     }
5595   else if (num_mem_sets <= 1)
5596     {
5597       /* Try to change inc to dec, so can apply above optimization.  */
5598       /* Can do this if:
5599          all registers modified are induction variables or invariant,
5600          all memory references have non-overlapping addresses
5601          (obviously true if only one write)
5602          allow 2 insns for the compare/jump at the end of the loop.  */
5603       int num_nonfixed_reads = 0;
5604       /* 1 if the iteration var is used only to count iterations.  */
5605       int no_use_except_counting = 0;
5606
5607       for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
5608         if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
5609           num_nonfixed_reads += count_nonfixed_reads (PATTERN (p));
5610
5611       if (bl->giv_count == 0
5612           && ! loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]])
5613         {
5614           rtx bivreg = regno_reg_rtx[bl->regno];
5615
5616           /* If there are no givs for this biv, and the only exit is the
5617              fall through at the end of the the loop, then
5618              see if perhaps there are no uses except to count.  */
5619           no_use_except_counting = 1;
5620           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
5621             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
5622               {
5623                 rtx set = single_set (p);
5624
5625                 if (set && GET_CODE (SET_DEST (set)) == REG
5626                     && REGNO (SET_DEST (set)) == bl->regno)
5627                   /* An insn that sets the biv is okay.  */
5628                   ;
5629                 else if (p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
5630                          || p == prev_nonnote_insn (loop_end))
5631                   /* Don't bother about the end test.  */
5632                   ;
5633                 else if (reg_mentioned_p (bivreg, PATTERN (p)))
5634                   /* Any other use of the biv is no good.  */
5635                   {
5636                     no_use_except_counting = 0;
5637                     break;
5638                   }
5639               }
5640         }
5641
5642       /* This code only acts for innermost loops.  Also it simplifies
5643          the memory address check by only reversing loops with
5644          zero or one memory access.
5645          Two memory accesses could involve parts of the same array,
5646          and that can't be reversed.  */
5647
5648       if (num_nonfixed_reads <= 1
5649           && !loop_has_call
5650           && !loop_has_volatile
5651           && (no_use_except_counting
5652               || (bl->giv_count + bl->biv_count + num_mem_sets
5653                   + num_movables + 2 == insn_count)))
5654         {
5655           rtx condition = get_condition_for_loop (PREV_INSN (loop_end));
5656           int win;
5657           rtx tem;
5658
5659           /* Loop can be reversed.  */
5660           if (loop_dump_stream)
5661             fprintf (loop_dump_stream, "Can reverse loop\n");
5662
5663           /* Now check other conditions:
5664              initial_value must be zero,
5665              final_value % add_val == 0, so that when reversed, the
5666              biv will be zero on the last iteration.
5667
5668              This test can probably be improved since +/- 1 in the constant
5669              can be obtained by changing LT to LE and vice versa; this is
5670              confusing.  */
5671
5672           if (comparison && bl->initial_value == const0_rtx
5673               && GET_CODE (XEXP (comparison, 1)) == CONST_INT
5674               /* LE gets turned into LT */
5675               && GET_CODE (comparison) == LT
5676               && (INTVAL (XEXP (comparison, 1))
5677                   % INTVAL (bl->biv->add_val)) == 0)
5678             {
5679               /* Register will always be nonnegative, with value
5680                  0 on last iteration if loop reversed */
5681
5682               /* Save some info needed to produce the new insns.  */
5683               reg = bl->biv->dest_reg;
5684               jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 1);
5685               new_add_val = GEN_INT (- INTVAL (bl->biv->add_val));
5686
5687               final_value = XEXP (comparison, 1);
5688               start_value = GEN_INT (INTVAL (XEXP (comparison, 1))
5689                                      - INTVAL (bl->biv->add_val));
5690
5691               /* Initialize biv to start_value before loop start.
5692                  The old initializing insn will be deleted as a
5693                  dead store by flow.c.  */
5694               emit_insn_before (gen_move_insn (reg, start_value), loop_start);
5695
5696               /* Add insn to decrement register, and delete insn
5697                  that incremented the register.  */
5698               p = emit_insn_before (gen_add2_insn (reg, new_add_val),
5699                                     bl->biv->insn);
5700               delete_insn (bl->biv->insn);
5701                       
5702               /* Update biv info to reflect its new status.  */
5703               bl->biv->insn = p;
5704               bl->initial_value = start_value;
5705               bl->biv->add_val = new_add_val;
5706
5707               /* Inc LABEL_NUSES so that delete_insn will
5708                  not delete the label.  */
5709               LABEL_NUSES (XEXP (jump_label, 0)) ++;
5710
5711               /* Emit an insn after the end of the loop to set the biv's
5712                  proper exit value if it is used anywhere outside the loop.  */
5713               if ((regno_last_uid[bl->regno]
5714                    != INSN_UID (PREV_INSN (PREV_INSN (loop_end))))
5715                   || ! bl->init_insn
5716                   || regno_first_uid[bl->regno] != INSN_UID (bl->init_insn))
5717                 emit_insn_after (gen_move_insn (reg, final_value),
5718                                  loop_end);
5719
5720               /* Delete compare/branch at end of loop.  */
5721               delete_insn (PREV_INSN (loop_end));
5722               delete_insn (PREV_INSN (loop_end));
5723
5724               /* Add new compare/branch insn at end of loop.  */
5725               start_sequence ();
5726               emit_cmp_insn (reg, const0_rtx, GE, NULL_RTX,
5727                              GET_MODE (reg), 0, 0);
5728               emit_jump_insn (gen_bge (XEXP (jump_label, 0)));
5729               tem = gen_sequence ();
5730               end_sequence ();
5731               emit_jump_insn_before (tem, loop_end);
5732
5733               for (tem = PREV_INSN (loop_end);
5734                    tem && GET_CODE (tem) != JUMP_INSN; tem = PREV_INSN (tem))
5735                 ;
5736               if (tem)
5737                 {
5738                   JUMP_LABEL (tem) = XEXP (jump_label, 0);
5739
5740                   /* Increment of LABEL_NUSES done above. */
5741                   /* Register is now always nonnegative,
5742                      so add REG_NONNEG note to the branch.  */
5743                   REG_NOTES (tem) = gen_rtx (EXPR_LIST, REG_NONNEG, NULL_RTX,
5744                                              REG_NOTES (tem));
5745                 }
5746
5747               bl->nonneg = 1;
5748
5749               /* Mark that this biv has been reversed.  Each giv which depends
5750                  on this biv, and which is also live past the end of the loop
5751                  will have to be fixed up.  */
5752
5753               bl->reversed = 1;
5754
5755               if (loop_dump_stream)
5756                 fprintf (loop_dump_stream,
5757                          "Reversed loop and added reg_nonneg\n");
5758
5759               return 1;
5760             }
5761         }
5762     }
5763
5764   return 0;
5765 }
5766 \f
5767 /* Verify whether the biv BL appears to be eliminable,
5768    based on the insns in the loop that refer to it.
5769    LOOP_START is the first insn of the loop, and END is the end insn.
5770
5771    If ELIMINATE_P is non-zero, actually do the elimination.
5772
5773    THRESHOLD and INSN_COUNT are from loop_optimize and are used to
5774    determine whether invariant insns should be placed inside or at the
5775    start of the loop.  */
5776
5777 static int
5778 maybe_eliminate_biv (bl, loop_start, end, eliminate_p, threshold, insn_count)
5779      struct iv_class *bl;
5780      rtx loop_start;
5781      rtx end;
5782      int eliminate_p;
5783      int threshold, insn_count;
5784 {
5785   rtx reg = bl->biv->dest_reg;
5786   rtx p, set;
5787   struct induction *v;
5788
5789   /* Scan all insns in the loop, stopping if we find one that uses the
5790      biv in a way that we cannot eliminate.  */
5791
5792   for (p = loop_start; p != end; p = NEXT_INSN (p))
5793     {
5794       enum rtx_code code = GET_CODE (p);
5795       rtx where = threshold >= insn_count ? loop_start : p;
5796
5797       if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
5798           && reg_mentioned_p (reg, PATTERN (p))
5799           && ! maybe_eliminate_biv_1 (PATTERN (p), p, bl, eliminate_p, where))
5800         {
5801           if (loop_dump_stream)
5802             fprintf (loop_dump_stream,
5803                      "Cannot eliminate biv %d: biv used in insn %d.\n",
5804                      bl->regno, INSN_UID (p));
5805           break;
5806         }
5807     }
5808
5809   if (p == end)
5810     {
5811       if (loop_dump_stream)
5812         fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
5813                  bl->regno, eliminate_p ? "was" : "can be");
5814       return 1;
5815     }
5816
5817   return 0;
5818 }
5819 \f
5820 /* If BL appears in X (part of the pattern of INSN), see if we can
5821    eliminate its use.  If so, return 1.  If not, return 0.
5822
5823    If BIV does not appear in X, return 1.
5824
5825    If ELIMINATE_P is non-zero, actually do the elimination.  WHERE indicates
5826    where extra insns should be added.  Depending on how many items have been
5827    moved out of the loop, it will either be before INSN or at the start of
5828    the loop.  */
5829
5830 static int
5831 maybe_eliminate_biv_1 (x, insn, bl, eliminate_p, where)
5832      rtx x, insn;
5833      struct iv_class *bl;
5834      int eliminate_p;
5835      rtx where;
5836 {
5837   enum rtx_code code = GET_CODE (x);
5838   rtx reg = bl->biv->dest_reg;
5839   enum machine_mode mode = GET_MODE (reg);
5840   struct induction *v;
5841   rtx arg, new, tem;
5842   int arg_operand;
5843   char *fmt;
5844   int i, j;
5845
5846   switch (code)
5847     {
5848     case REG:
5849       /* If we haven't already been able to do something with this BIV,
5850          we can't eliminate it.  */
5851       if (x == reg)
5852         return 0;
5853       return 1;
5854
5855     case SET:
5856       /* If this sets the BIV, it is not a problem.  */
5857       if (SET_DEST (x) == reg)
5858         return 1;
5859
5860       /* If this is an insn that defines a giv, it is also ok because
5861          it will go away when the giv is reduced.  */
5862       for (v = bl->giv; v; v = v->next_iv)
5863         if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
5864           return 1;
5865
5866 #ifdef HAVE_cc0
5867       if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
5868         {
5869           /* Can replace with any giv that was reduced and
5870              that has (MULT_VAL != 0) and (ADD_VAL == 0).
5871              Require a constant for MULT_VAL, so we know it's nonzero.  */
5872
5873           for (v = bl->giv; v; v = v->next_iv)
5874             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
5875                 && v->add_val == const0_rtx
5876                 && ! v->ignore && ! v->maybe_dead
5877                 && v->mode == mode)
5878               {
5879                 if (! eliminate_p)
5880                   return 1;
5881
5882                 /* If the giv has the opposite direction of change,
5883                    then reverse the comparison.  */
5884                 if (INTVAL (v->mult_val) < 0)
5885                   new = gen_rtx (COMPARE, GET_MODE (v->new_reg),
5886                                  const0_rtx, v->new_reg);
5887                 else
5888                   new = v->new_reg;
5889
5890                 /* We can probably test that giv's reduced reg.  */
5891                 if (validate_change (insn, &SET_SRC (x), new, 0))
5892                   return 1;
5893               }
5894
5895           /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
5896              replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
5897              Require a constant for MULT_VAL, so we know it's nonzero.  */
5898
5899           for (v = bl->giv; v; v = v->next_iv)
5900             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
5901                 && ! v->ignore && ! v->maybe_dead
5902                 && v->mode == mode)
5903               {
5904                 if (! eliminate_p)
5905                   return 1;
5906
5907                 /* If the giv has the opposite direction of change,
5908                    then reverse the comparison.  */
5909                 if (INTVAL (v->mult_val) < 0)
5910                   new = gen_rtx (COMPARE, VOIDmode, copy_rtx (v->add_val),
5911                                  v->new_reg);
5912                 else
5913                   new = gen_rtx (COMPARE, VOIDmode, v->new_reg,
5914                                  copy_rtx (v->add_val));
5915
5916                 /* Replace biv with the giv's reduced register.  */
5917                 update_reg_last_use (v->add_val, insn);
5918                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
5919                   return 1;
5920
5921                 /* Insn doesn't support that constant or invariant.  Copy it
5922                    into a register (it will be a loop invariant.)  */
5923                 tem = gen_reg_rtx (GET_MODE (v->new_reg));
5924
5925                 emit_insn_before (gen_move_insn (tem, copy_rtx (v->add_val)),
5926                                   where);
5927
5928                 if (validate_change (insn, &SET_SRC (PATTERN (insn)),
5929                                      gen_rtx (COMPARE, VOIDmode,
5930                                               v->new_reg, tem), 0))
5931                   return 1;
5932               }
5933         }
5934 #endif
5935       break;
5936
5937     case COMPARE:
5938     case EQ:  case NE:
5939     case GT:  case GE:  case GTU:  case GEU:
5940     case LT:  case LE:  case LTU:  case LEU:
5941       /* See if either argument is the biv.  */
5942       if (XEXP (x, 0) == reg)
5943         arg = XEXP (x, 1), arg_operand = 1;
5944       else if (XEXP (x, 1) == reg)
5945         arg = XEXP (x, 0), arg_operand = 0;
5946       else
5947         break;
5948
5949       if (CONSTANT_P (arg))
5950         {
5951           /* First try to replace with any giv that has constant positive
5952              mult_val and constant add_val.  We might be able to support
5953              negative mult_val, but it seems complex to do it in general.  */
5954
5955           for (v = bl->giv; v; v = v->next_iv)
5956             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
5957                 && CONSTANT_P (v->add_val)
5958                 && ! v->ignore && ! v->maybe_dead
5959                 && v->mode == mode)
5960               {
5961                 if (! eliminate_p)
5962                   return 1;
5963
5964                 /* Replace biv with the giv's reduced reg.  */
5965                 XEXP (x, 1-arg_operand) = v->new_reg;
5966
5967                 /* If all constants are actually constant integers and
5968                    the derived constant can be directly placed in the COMPARE,
5969                    do so.  */
5970                 if (GET_CODE (arg) == CONST_INT
5971                     && GET_CODE (v->mult_val) == CONST_INT
5972                     && GET_CODE (v->add_val) == CONST_INT
5973                     && validate_change (insn, &XEXP (x, arg_operand),
5974                                         GEN_INT (INTVAL (arg)
5975                                                  * INTVAL (v->mult_val)
5976                                                  + INTVAL (v->add_val)), 0))
5977                   return 1;
5978
5979                 /* Otherwise, load it into a register.  */
5980                 tem = gen_reg_rtx (mode);
5981                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
5982                 if (validate_change (insn, &XEXP (x, arg_operand), tem, 0))
5983                   return 1;
5984
5985                 /* If that failed, put back the change we made above.  */
5986                 XEXP (x, 1-arg_operand) = reg;
5987               }
5988           
5989           /* Look for giv with positive constant mult_val and nonconst add_val.
5990              Insert insns to calculate new compare value.  */
5991
5992           for (v = bl->giv; v; v = v->next_iv)
5993             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
5994                 && ! v->ignore && ! v->maybe_dead
5995                 && v->mode == mode)
5996               {
5997                 rtx tem;
5998
5999                 if (! eliminate_p)
6000                   return 1;
6001
6002                 tem = gen_reg_rtx (mode);
6003
6004                 /* Replace biv with giv's reduced register.  */
6005                 validate_change (insn, &XEXP (x, 1 - arg_operand),
6006                                  v->new_reg, 1);
6007
6008                 /* Compute value to compare against.  */
6009                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
6010                 /* Use it in this insn.  */
6011                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
6012                 if (apply_change_group ())
6013                   return 1;
6014               }
6015         }
6016       else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
6017         {
6018           if (invariant_p (arg) == 1)
6019             {
6020               /* Look for giv with constant positive mult_val and nonconst
6021                  add_val. Insert insns to compute new compare value.  */
6022
6023               for (v = bl->giv; v; v = v->next_iv)
6024                 if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
6025                     && ! v->ignore && ! v->maybe_dead
6026                     && v->mode == mode)
6027                   {
6028                     rtx tem;
6029
6030                     if (! eliminate_p)
6031                       return 1;
6032
6033                     tem = gen_reg_rtx (mode);
6034
6035                     /* Replace biv with giv's reduced register.  */
6036                     validate_change (insn, &XEXP (x, 1 - arg_operand),
6037                                      v->new_reg, 1);
6038
6039                     /* Compute value to compare against.  */
6040                     emit_iv_add_mult (arg, v->mult_val, v->add_val,
6041                                       tem, where);
6042                     validate_change (insn, &XEXP (x, arg_operand), tem, 1);
6043                     if (apply_change_group ())
6044                       return 1;
6045                   }
6046             }
6047
6048           /* This code has problems.  Basically, you can't know when
6049              seeing if we will eliminate BL, whether a particular giv
6050              of ARG will be reduced.  If it isn't going to be reduced,
6051              we can't eliminate BL.  We can try forcing it to be reduced,
6052              but that can generate poor code.
6053
6054              The problem is that the benefit of reducing TV, below should
6055              be increased if BL can actually be eliminated, but this means
6056              we might have to do a topological sort of the order in which
6057              we try to process biv.  It doesn't seem worthwhile to do
6058              this sort of thing now.  */
6059
6060 #if 0
6061           /* Otherwise the reg compared with had better be a biv.  */
6062           if (GET_CODE (arg) != REG
6063               || reg_iv_type[REGNO (arg)] != BASIC_INDUCT)
6064             return 0;
6065
6066           /* Look for a pair of givs, one for each biv,
6067              with identical coefficients.  */
6068           for (v = bl->giv; v; v = v->next_iv)
6069             {
6070               struct induction *tv;
6071
6072               if (v->ignore || v->maybe_dead || v->mode != mode)
6073                 continue;
6074
6075               for (tv = reg_biv_class[REGNO (arg)]->giv; tv; tv = tv->next_iv)
6076                 if (! tv->ignore && ! tv->maybe_dead
6077                     && rtx_equal_p (tv->mult_val, v->mult_val)
6078                     && rtx_equal_p (tv->add_val, v->add_val)
6079                     && tv->mode == mode)
6080                   {
6081                     if (! eliminate_p)
6082                       return 1;
6083
6084                     /* Replace biv with its giv's reduced reg.  */
6085                     XEXP (x, 1-arg_operand) = v->new_reg;
6086                     /* Replace other operand with the other giv's
6087                        reduced reg.  */
6088                     XEXP (x, arg_operand) = tv->new_reg;
6089                     return 1;
6090                   }
6091             }
6092 #endif
6093         }
6094
6095       /* If we get here, the biv can't be eliminated.  */
6096       return 0;
6097
6098     case MEM:
6099       /* If this address is a DEST_ADDR giv, it doesn't matter if the
6100          biv is used in it, since it will be replaced.  */
6101       for (v = bl->giv; v; v = v->next_iv)
6102         if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
6103           return 1;
6104       break;
6105     }
6106
6107   /* See if any subexpression fails elimination.  */
6108   fmt = GET_RTX_FORMAT (code);
6109   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
6110     {
6111       switch (fmt[i])
6112         {
6113         case 'e':
6114           if (! maybe_eliminate_biv_1 (XEXP (x, i), insn, bl, 
6115                                        eliminate_p, where))
6116             return 0;
6117           break;
6118
6119         case 'E':
6120           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
6121             if (! maybe_eliminate_biv_1 (XVECEXP (x, i, j), insn, bl,
6122                                          eliminate_p, where))
6123               return 0;
6124           break;
6125         }
6126     }
6127
6128   return 1;
6129 }  
6130 \f
6131 /* Return nonzero if the last use of REG
6132    is in an insn following INSN in the same basic block.  */
6133
6134 static int
6135 last_use_this_basic_block (reg, insn)
6136      rtx reg;
6137      rtx insn;
6138 {
6139   rtx n;
6140   for (n = insn;
6141        n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
6142        n = NEXT_INSN (n))
6143     {
6144       if (regno_last_uid[REGNO (reg)] == INSN_UID (n))
6145         return 1;
6146     }
6147   return 0;
6148 }
6149 \f
6150 /* Called via `note_stores' to record the initial value of a biv.  Here we
6151    just record the location of the set and process it later.  */
6152
6153 static void
6154 record_initial (dest, set)
6155      rtx dest;
6156      rtx set;
6157 {
6158   struct iv_class *bl;
6159
6160   if (GET_CODE (dest) != REG
6161       || REGNO (dest) >= max_reg_before_loop
6162       || reg_iv_type[REGNO (dest)] != BASIC_INDUCT)
6163     return;
6164
6165   bl = reg_biv_class[REGNO (dest)];
6166
6167   /* If this is the first set found, record it.  */
6168   if (bl->init_insn == 0)
6169     {
6170       bl->init_insn = note_insn;
6171       bl->init_set = set;
6172     }
6173 }
6174 \f
6175 /* If any of the registers in X are "old" and currently have a last use earlier
6176    than INSN, update them to have a last use of INSN.  Their actual last use
6177    will be the previous insn but it will not have a valid uid_luid so we can't
6178    use it.  */
6179
6180 static void
6181 update_reg_last_use (x, insn)
6182      rtx x;
6183      rtx insn;
6184 {
6185   /* Check for the case where INSN does not have a valid luid.  In this case,
6186      there is no need to modify the regno_last_uid, as this can only happen
6187      when code is inserted after the loop_end to set a pseudo's final value,
6188      and hence this insn will never be the last use of x.  */
6189   if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
6190       && INSN_UID (insn) < max_uid_for_loop
6191       && uid_luid[regno_last_uid[REGNO (x)]] < uid_luid[INSN_UID (insn)])
6192     regno_last_uid[REGNO (x)] = INSN_UID (insn);
6193   else
6194     {
6195       register int i, j;
6196       register char *fmt = GET_RTX_FORMAT (GET_CODE (x));
6197       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
6198         {
6199           if (fmt[i] == 'e')
6200             update_reg_last_use (XEXP (x, i), insn);
6201           else if (fmt[i] == 'E')
6202             for (j = XVECLEN (x, i) - 1; j >= 0; j--)
6203               update_reg_last_use (XVECEXP (x, i, j), insn);
6204         }
6205     }
6206 }
6207 \f
6208 /* Given a jump insn JUMP, return the condition that will cause it to branch
6209    to its JUMP_LABEL.  If the condition cannot be understood, or is an
6210    inequality floating-point comparison which needs to be reversed, 0 will
6211    be returned.
6212
6213    If EARLIEST is non-zero, it is a pointer to a place where the earliest
6214    insn used in locating the condition was found.  If a replacement test
6215    of the condition is desired, it should be placed in front of that
6216    insn and we will be sure that the inputs are still valid.
6217
6218    The condition will be returned in a canonical form to simplify testing by
6219    callers.  Specifically:
6220
6221    (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
6222    (2) Both operands will be machine operands; (cc0) will have been replaced.
6223    (3) If an operand is a constant, it will be the second operand.
6224    (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
6225        for GE, GEU, and LEU.  */
6226
6227 rtx
6228 get_condition (jump, earliest)
6229      rtx jump;
6230      rtx *earliest;
6231 {
6232   enum rtx_code code;
6233   rtx prev = jump;
6234   rtx set;
6235   rtx tem;
6236   rtx op0, op1;
6237   int reverse_code = 0;
6238   int did_reverse_condition = 0;
6239
6240   /* If this is not a standard conditional jump, we can't parse it.  */
6241   if (GET_CODE (jump) != JUMP_INSN
6242       || ! condjump_p (jump) || simplejump_p (jump))
6243     return 0;
6244
6245   code = GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 0));
6246   op0 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 0);
6247   op1 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 1);
6248
6249   if (earliest)
6250     *earliest = jump;
6251
6252   /* If this branches to JUMP_LABEL when the condition is false, reverse
6253      the condition.  */
6254   if (XEXP (XEXP (SET_SRC (PATTERN (jump)), 2), 0) == JUMP_LABEL (jump))
6255     code = reverse_condition (code), did_reverse_condition ^= 1;
6256
6257   /* If we are comparing a register with zero, see if the register is set
6258      in the previous insn to a COMPARE or a comparison operation.  Perform
6259      the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
6260      in cse.c  */
6261
6262   while (GET_RTX_CLASS (code) == '<' && op1 == const0_rtx)
6263     {
6264       /* Set non-zero when we find something of interest.  */
6265       rtx x = 0;
6266
6267 #ifdef HAVE_cc0
6268       /* If comparison with cc0, import actual comparison from compare
6269          insn.  */
6270       if (op0 == cc0_rtx)
6271         {
6272           if ((prev = prev_nonnote_insn (prev)) == 0
6273               || GET_CODE (prev) != INSN
6274               || (set = single_set (prev)) == 0
6275               || SET_DEST (set) != cc0_rtx)
6276             return 0;
6277
6278           op0 = SET_SRC (set);
6279           op1 = CONST0_RTX (GET_MODE (op0));
6280           if (earliest)
6281             *earliest = prev;
6282         }
6283 #endif
6284
6285       /* If this is a COMPARE, pick up the two things being compared.  */
6286       if (GET_CODE (op0) == COMPARE)
6287         {
6288           op1 = XEXP (op0, 1);
6289           op0 = XEXP (op0, 0);
6290           continue;
6291         }
6292       else if (GET_CODE (op0) != REG)
6293         break;
6294
6295       /* Go back to the previous insn.  Stop if it is not an INSN.  We also
6296          stop if it isn't a single set or if it has a REG_INC note because
6297          we don't want to bother dealing with it.  */
6298
6299       if ((prev = prev_nonnote_insn (prev)) == 0
6300           || GET_CODE (prev) != INSN
6301           || FIND_REG_INC_NOTE (prev, 0)
6302           || (set = single_set (prev)) == 0)
6303         break;
6304
6305       /* If this is setting OP0, get what it sets it to if it looks
6306          relevant.  */
6307       if (SET_DEST (set) == op0)
6308         {
6309           enum machine_mode inner_mode = GET_MODE (SET_SRC (set));
6310
6311           if ((GET_CODE (SET_SRC (set)) == COMPARE
6312                || (((code == NE
6313                      || (code == LT
6314                          && GET_MODE_CLASS (inner_mode) == MODE_INT
6315                          && (GET_MODE_BITSIZE (inner_mode)
6316                              <= HOST_BITS_PER_WIDE_INT)
6317                          && (STORE_FLAG_VALUE
6318                              & ((HOST_WIDE_INT) 1
6319                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
6320 #ifdef FLOAT_STORE_FLAG_VALUE
6321                      || (code == LT
6322                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
6323                          && FLOAT_STORE_FLAG_VALUE < 0)
6324 #endif
6325                      ))
6326                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<')))
6327             x = SET_SRC (set);
6328           else if (((code == EQ
6329                      || (code == GE
6330                          && (GET_MODE_BITSIZE (inner_mode)
6331                              <= HOST_BITS_PER_WIDE_INT)
6332                          && GET_MODE_CLASS (inner_mode) == MODE_INT
6333                          && (STORE_FLAG_VALUE
6334                              & ((HOST_WIDE_INT) 1
6335                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
6336 #ifdef FLOAT_STORE_FLAG_VALUE
6337                      || (code == GE
6338                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
6339                          && FLOAT_STORE_FLAG_VALUE < 0)
6340 #endif
6341                      ))
6342                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<')
6343             {
6344               /* We might have reversed a LT to get a GE here.  But this wasn't
6345                  actually the comparison of data, so we don't flag that we
6346                  have had to reverse the condition.  */
6347               did_reverse_condition ^= 1;
6348               reverse_code = 1;
6349               x = SET_SRC (set);
6350             }
6351         }
6352
6353       else if (reg_set_p (op0, prev))
6354         /* If this sets OP0, but not directly, we have to give up.  */
6355         break;
6356
6357       if (x)
6358         {
6359           if (GET_RTX_CLASS (GET_CODE (x)) == '<')
6360             code = GET_CODE (x);
6361           if (reverse_code)
6362             {
6363               code = reverse_condition (code);
6364               did_reverse_condition ^= 1;
6365               reverse_code = 0;
6366             }
6367
6368           op0 = XEXP (x, 0), op1 = XEXP (x, 1);
6369           if (earliest)
6370             *earliest = prev;
6371         }
6372     }
6373
6374   /* If constant is first, put it last.  */
6375   if (CONSTANT_P (op0))
6376     code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
6377
6378   /* If OP0 is the result of a comparison, we weren't able to find what
6379      was really being compared, so fail.  */
6380   if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
6381     return 0;
6382
6383   /* Canonicalize any ordered comparison with integers involving equality.  */
6384   if (GET_CODE (op1) == CONST_INT)
6385     {
6386       HOST_WIDE_INT const_val = INTVAL (op1);
6387       unsigned HOST_WIDE_INT uconst_val = const_val;
6388
6389       switch (code)
6390       {
6391       case LE:
6392         code = LT;
6393         op1 = GEN_INT (const_val + 1);
6394         break;
6395
6396       case GE:
6397         code = GT;
6398         op1 = GEN_INT (const_val - 1);
6399         break;
6400
6401       case LEU:
6402         code = LTU;
6403         op1 = GEN_INT (uconst_val + 1);
6404         break;
6405
6406       case GEU:
6407         code = GTU;
6408         op1 = GEN_INT (uconst_val - 1);
6409         break;
6410       }
6411     }
6412
6413   /* If this was floating-point and we reversed anything other than an
6414      EQ or NE, return zero.  */
6415   if (TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
6416       && did_reverse_condition && code != NE && code != EQ
6417       && GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
6418     return 0;
6419
6420 #ifdef HAVE_cc0
6421   /* Never return CC0; return zero instead.  */
6422   if (op0 == cc0_rtx)
6423     return 0;
6424 #endif
6425
6426   return gen_rtx (code, VOIDmode, op0, op1);
6427 }
6428
6429 /* Similar to above routine, except that we also put an invariant last
6430    unless both operands are invariants.  */
6431
6432 rtx
6433 get_condition_for_loop (x)
6434      rtx x;
6435 {
6436   rtx comparison = get_condition (x, NULL_PTR);
6437
6438   if (comparison == 0
6439       || ! invariant_p (XEXP (comparison, 0))
6440       || invariant_p (XEXP (comparison, 1)))
6441     return comparison;
6442
6443   return gen_rtx (swap_condition (GET_CODE (comparison)), VOIDmode,
6444                   XEXP (comparison, 1), XEXP (comparison, 0));
6445 }