OSDN Git Service

Fix for SH gcc.c-torture/compile/991229-3.c failure:
[pf3gnuchains/gcc-fork.git] / gcc / loop.c
1 /* Perform various loop optimizations, including strength reduction.
2    Copyright (C) 1987, 1988, 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3    1998, 1999, 2000 Free Software Foundation, Inc.
4
5 This file is part of GNU CC.
6
7 GNU CC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU CC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU CC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22
23 /* This is the loop optimization pass of the compiler.
24    It finds invariant computations within loops and moves them
25    to the beginning of the loop.  Then it identifies basic and 
26    general induction variables.  Strength reduction is applied to the general
27    induction variables, and induction variable elimination is applied to
28    the basic induction variables.
29
30    It also finds cases where
31    a register is set within the loop by zero-extending a narrower value
32    and changes these to zero the entire register once before the loop
33    and merely copy the low part within the loop.
34
35    Most of the complexity is in heuristics to decide when it is worth
36    while to do these things.  */
37
38 #include "config.h"
39 #include "system.h"
40 #include "rtl.h"
41 #include "tm_p.h"
42 #include "obstack.h"
43 #include "function.h"
44 #include "expr.h"
45 #include "basic-block.h"
46 #include "insn-config.h"
47 #include "insn-flags.h"
48 #include "regs.h"
49 #include "hard-reg-set.h"
50 #include "recog.h"
51 #include "flags.h"
52 #include "real.h"
53 #include "loop.h"
54 #include "except.h"
55 #include "toplev.h"
56
57 /* Vector mapping INSN_UIDs to luids.
58    The luids are like uids but increase monotonically always.
59    We use them to see whether a jump comes from outside a given loop.  */
60
61 int *uid_luid;
62
63 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
64    number the insn is contained in.  */
65
66 struct loop **uid_loop;
67
68 /* 1 + largest uid of any insn.  */
69
70 int max_uid_for_loop;
71
72 /* 1 + luid of last insn.  */
73
74 static int max_luid;
75
76 /* Number of loops detected in current function.  Used as index to the
77    next few tables.  */
78
79 static int max_loop_num;
80
81 /* Indexed by register number, contains the number of times the reg
82    is set during the loop being scanned.
83    During code motion, a negative value indicates a reg that has been
84    made a candidate; in particular -2 means that it is an candidate that
85    we know is equal to a constant and -1 means that it is an candidate
86    not known equal to a constant.
87    After code motion, regs moved have 0 (which is accurate now)
88    while the failed candidates have the original number of times set.
89
90    Therefore, at all times, == 0 indicates an invariant register;
91    < 0 a conditionally invariant one.  */
92
93 static varray_type set_in_loop;
94
95 /* Original value of set_in_loop; same except that this value
96    is not set negative for a reg whose sets have been made candidates
97    and not set to 0 for a reg that is moved.  */
98
99 static varray_type n_times_set;
100
101 /* Index by register number, 1 indicates that the register
102    cannot be moved or strength reduced.  */
103
104 static varray_type may_not_optimize;
105
106 /* Contains the insn in which a register was used if it was used
107    exactly once; contains const0_rtx if it was used more than once.  */
108
109 static varray_type reg_single_usage;
110
111 /* Nonzero means reg N has already been moved out of one loop.
112    This reduces the desire to move it out of another.  */
113
114 static char *moved_once;
115
116 /* List of MEMs that are stored in this loop.  */
117
118 static rtx loop_store_mems;
119
120 /* The insn where the first of these was found.  */
121 static rtx first_loop_store_insn;
122
123 typedef struct loop_mem_info {
124   rtx mem;      /* The MEM itself.  */
125   rtx reg;      /* Corresponding pseudo, if any.  */
126   int optimize; /* Nonzero if we can optimize access to this MEM.  */
127 } loop_mem_info;
128
129 /* Array of MEMs that are used (read or written) in this loop, but
130    cannot be aliased by anything in this loop, except perhaps
131    themselves.  In other words, if loop_mems[i] is altered during the
132    loop, it is altered by an expression that is rtx_equal_p to it.  */
133
134 static loop_mem_info *loop_mems;
135
136 /* The index of the next available slot in LOOP_MEMS.  */
137
138 static int loop_mems_idx;
139
140 /* The number of elements allocated in LOOP_MEMs.  */
141
142 static int loop_mems_allocated;
143
144 /* Nonzero if we don't know what MEMs were changed in the current
145    loop.  This happens if the loop contains a call (in which case
146    `loop_info->has_call' will also be set) or if we store into more
147    than NUM_STORES MEMs.  */
148
149 static int unknown_address_altered;
150
151 /* The above doesn't count any readonly memory locations that are stored.
152    This does.  */
153
154 static int unknown_constant_address_altered;
155
156 /* Count of movable (i.e. invariant) instructions discovered in the loop.  */
157 static int num_movables;
158
159 /* Count of memory write instructions discovered in the loop.  */
160 static int num_mem_sets;
161
162 /* Bound on pseudo register number before loop optimization.
163    A pseudo has valid regscan info if its number is < max_reg_before_loop.  */
164 int max_reg_before_loop;
165
166 /* The value to pass to the next call of reg_scan_update.  */
167 static int loop_max_reg;
168
169 /* This obstack is used in product_cheap_p to allocate its rtl.  It
170    may call gen_reg_rtx which, in turn, may reallocate regno_reg_rtx.
171    If we used the same obstack that it did, we would be deallocating
172    that array.  */
173
174 static struct obstack temp_obstack;
175
176 /* This is where the pointer to the obstack being used for RTL is stored.  */
177
178 extern struct obstack *rtl_obstack;
179
180 #define obstack_chunk_alloc xmalloc
181 #define obstack_chunk_free free
182 \f
183 /* During the analysis of a loop, a chain of `struct movable's
184    is made to record all the movable insns found.
185    Then the entire chain can be scanned to decide which to move.  */
186
187 struct movable
188 {
189   rtx insn;                     /* A movable insn */
190   rtx set_src;                  /* The expression this reg is set from.  */
191   rtx set_dest;                 /* The destination of this SET.  */
192   rtx dependencies;             /* When INSN is libcall, this is an EXPR_LIST
193                                    of any registers used within the LIBCALL.  */
194   int consec;                   /* Number of consecutive following insns 
195                                    that must be moved with this one.  */
196   int regno;                    /* The register it sets */
197   short lifetime;               /* lifetime of that register;
198                                    may be adjusted when matching movables
199                                    that load the same value are found.  */
200   short savings;                /* Number of insns we can move for this reg,
201                                    including other movables that force this
202                                    or match this one.  */
203   unsigned int cond : 1;        /* 1 if only conditionally movable */
204   unsigned int force : 1;       /* 1 means MUST move this insn */
205   unsigned int global : 1;      /* 1 means reg is live outside this loop */
206                 /* If PARTIAL is 1, GLOBAL means something different:
207                    that the reg is live outside the range from where it is set
208                    to the following label.  */
209   unsigned int done : 1;        /* 1 inhibits further processing of this */
210   
211   unsigned int partial : 1;     /* 1 means this reg is used for zero-extending.
212                                    In particular, moving it does not make it
213                                    invariant.  */
214   unsigned int move_insn : 1;   /* 1 means that we call emit_move_insn to
215                                    load SRC, rather than copying INSN.  */
216   unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
217                                     first insn of a consecutive sets group.  */
218   unsigned int is_equiv : 1;    /* 1 means a REG_EQUIV is present on INSN.  */
219   enum machine_mode savemode;   /* Nonzero means it is a mode for a low part
220                                    that we should avoid changing when clearing
221                                    the rest of the reg.  */
222   struct movable *match;        /* First entry for same value */
223   struct movable *forces;       /* An insn that must be moved if this is */
224   struct movable *next;
225 };
226
227 static struct movable *the_movables;
228
229 FILE *loop_dump_stream;
230
231 /* Forward declarations.  */
232
233 static void verify_dominator PARAMS ((struct loop *));
234 static void find_and_verify_loops PARAMS ((rtx, struct loops *));
235 static void mark_loop_jump PARAMS ((rtx, struct loop *));
236 static void prescan_loop PARAMS ((struct loop *));
237 static int reg_in_basic_block_p PARAMS ((rtx, rtx));
238 static int consec_sets_invariant_p PARAMS ((const struct loop *,
239                                             rtx, int, rtx));
240 static int labels_in_range_p PARAMS ((rtx, int));
241 static void count_one_set PARAMS ((rtx, rtx, varray_type, rtx *));
242
243 static void count_loop_regs_set PARAMS ((rtx, rtx, varray_type, varray_type,
244                                          int *, int)); 
245 static void note_addr_stored PARAMS ((rtx, rtx, void *));
246 static void note_set_pseudo_multiple_uses PARAMS ((rtx, rtx, void *));
247 static int loop_reg_used_before_p PARAMS ((const struct loop *, rtx, rtx));
248 static void scan_loop PARAMS ((struct loop*, int, int));
249 #if 0
250 static void replace_call_address PARAMS ((rtx, rtx, rtx));
251 #endif
252 static rtx skip_consec_insns PARAMS ((rtx, int));
253 static int libcall_benefit PARAMS ((rtx));
254 static void ignore_some_movables PARAMS ((struct movable *));
255 static void force_movables PARAMS ((struct movable *));
256 static void combine_movables PARAMS ((struct movable *, int));
257 static int regs_match_p PARAMS ((rtx, rtx, struct movable *));
258 static int rtx_equal_for_loop_p PARAMS ((rtx, rtx, struct movable *));
259 static void add_label_notes PARAMS ((rtx, rtx));
260 static void move_movables PARAMS ((struct loop *loop, struct movable *, 
261                                    int, int, int));
262 static int count_nonfixed_reads PARAMS ((const struct loop *, rtx));
263 static void strength_reduce PARAMS ((struct loop *, int, int, int));
264 static void find_single_use_in_loop PARAMS ((rtx, rtx, varray_type));
265 static int valid_initial_value_p PARAMS ((rtx, rtx, int, rtx));
266 static void find_mem_givs PARAMS ((const struct loop *, rtx, rtx, int, int));
267 static void record_biv PARAMS ((struct induction *, rtx, rtx, rtx, rtx, rtx *, 
268                                 int, int, int));
269 static void check_final_value PARAMS ((const struct loop *,
270                                        struct induction *));
271 static void record_giv PARAMS ((const struct loop *, struct induction *, 
272                                 rtx, rtx, rtx, rtx, rtx, int, enum g_types, 
273                                 int, int, rtx *));
274 static void update_giv_derive PARAMS ((const struct loop *, rtx));
275 static int basic_induction_var PARAMS ((const struct loop *, rtx, 
276                                         enum machine_mode, rtx, rtx,
277                                         rtx *, rtx *, rtx **, int *));
278 static rtx simplify_giv_expr PARAMS ((const struct loop *, rtx, int *));
279 static int general_induction_var PARAMS ((const struct loop *loop, rtx, rtx *,
280                                           rtx *, rtx *, int, int *));
281 static int consec_sets_giv PARAMS ((const struct loop *, int, rtx,
282                                     rtx, rtx, rtx *, rtx *, rtx *));
283 static int check_dbra_loop PARAMS ((struct loop *, int));
284 static rtx express_from_1 PARAMS ((rtx, rtx, rtx));
285 static rtx combine_givs_p PARAMS ((struct induction *, struct induction *));
286 static void combine_givs PARAMS ((struct iv_class *));
287 struct recombine_givs_stats;
288 static int find_life_end PARAMS ((rtx, struct recombine_givs_stats *,
289                                   rtx, rtx));
290 static void recombine_givs PARAMS ((const struct loop *, struct iv_class *,
291                                     int));
292 static int product_cheap_p PARAMS ((rtx, rtx));
293 static int maybe_eliminate_biv PARAMS ((const struct loop *, struct iv_class *,
294                                         int, int, int));
295 static int maybe_eliminate_biv_1 PARAMS ((const struct loop *, rtx, rtx, 
296                                           struct iv_class *, int, rtx));
297 static int last_use_this_basic_block PARAMS ((rtx, rtx));
298 static void record_initial PARAMS ((rtx, rtx, void *));
299 static void update_reg_last_use PARAMS ((rtx, rtx));
300 static rtx next_insn_in_loop PARAMS ((const struct loop *, rtx));
301 static void load_mems_and_recount_loop_regs_set PARAMS ((const struct loop*,
302                                                          int *));
303 static void load_mems PARAMS ((const struct loop *));
304 static int insert_loop_mem PARAMS ((rtx *, void *));
305 static int replace_loop_mem PARAMS ((rtx *, void *));
306 static int replace_loop_reg PARAMS ((rtx *, void *));
307 static void note_reg_stored PARAMS ((rtx, rtx, void *));
308 static void try_copy_prop PARAMS ((const struct loop *, rtx, int));
309 static int replace_label PARAMS ((rtx *, void *));
310
311 typedef struct rtx_and_int {
312   rtx r;
313   int i;
314 } rtx_and_int;
315
316 typedef struct rtx_pair {
317   rtx r1;
318   rtx r2;
319 } rtx_pair;
320
321 /* Nonzero iff INSN is between START and END, inclusive.  */
322 #define INSN_IN_RANGE_P(INSN, START, END)       \
323   (INSN_UID (INSN) < max_uid_for_loop           \
324    && INSN_LUID (INSN) >= INSN_LUID (START)     \
325    && INSN_LUID (INSN) <= INSN_LUID (END))
326
327 #ifdef HAVE_decrement_and_branch_on_count
328 /* Test whether BCT applicable and safe.  */
329 static void insert_bct PARAMS ((struct loop *));
330
331 /* Auxiliary function that inserts the BCT pattern into the loop.  */
332 static void instrument_loop_bct PARAMS ((rtx, rtx, rtx));
333 #endif /* HAVE_decrement_and_branch_on_count */
334
335 /* Indirect_jump_in_function is computed once per function.  */
336 int indirect_jump_in_function = 0;
337 static int indirect_jump_in_function_p PARAMS ((rtx));
338
339 static int compute_luids PARAMS ((rtx, rtx, int));
340
341 static int biv_elimination_giv_has_0_offset PARAMS ((struct induction *,
342                                                    struct induction *, rtx));
343 \f
344 /* Relative gain of eliminating various kinds of operations.  */
345 static int add_cost;
346 #if 0
347 static int shift_cost;
348 static int mult_cost;
349 #endif
350
351 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
352    copy the value of the strength reduced giv to its original register.  */
353 static int copy_cost;
354
355 /* Cost of using a register, to normalize the benefits of a giv.  */
356 static int reg_address_cost;
357
358
359 void
360 init_loop ()
361 {
362   char *free_point = (char *) oballoc (1);
363   rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
364
365   add_cost = rtx_cost (gen_rtx_PLUS (word_mode, reg, reg), SET);
366
367 #ifdef ADDRESS_COST
368   reg_address_cost = ADDRESS_COST (reg);
369 #else
370   reg_address_cost = rtx_cost (reg, MEM);
371 #endif
372
373   /* We multiply by 2 to reconcile the difference in scale between
374      these two ways of computing costs.  Otherwise the cost of a copy
375      will be far less than the cost of an add.  */
376
377   copy_cost = 2 * 2;
378
379   /* Free the objects we just allocated.  */
380   obfree (free_point);
381
382   /* Initialize the obstack used for rtl in product_cheap_p.  */
383   gcc_obstack_init (&temp_obstack);
384 }
385 \f
386 /* Compute the mapping from uids to luids.
387    LUIDs are numbers assigned to insns, like uids,
388    except that luids increase monotonically through the code.
389    Start at insn START and stop just before END.  Assign LUIDs
390    starting with PREV_LUID + 1.  Return the last assigned LUID + 1.  */
391 static int
392 compute_luids (start, end, prev_luid)
393      rtx start, end;
394      int prev_luid;
395 {
396   int i;
397   rtx insn;
398
399   for (insn = start, i = prev_luid; insn != end; insn = NEXT_INSN (insn))
400     {
401       if (INSN_UID (insn) >= max_uid_for_loop)
402         continue;
403       /* Don't assign luids to line-number NOTEs, so that the distance in
404          luids between two insns is not affected by -g.  */
405       if (GET_CODE (insn) != NOTE
406           || NOTE_LINE_NUMBER (insn) <= 0)
407         uid_luid[INSN_UID (insn)] = ++i;
408       else
409         /* Give a line number note the same luid as preceding insn.  */
410         uid_luid[INSN_UID (insn)] = i;
411     }
412   return i + 1;
413 }
414 \f
415 /* Entry point of this file.  Perform loop optimization
416    on the current function.  F is the first insn of the function
417    and DUMPFILE is a stream for output of a trace of actions taken
418    (or 0 if none should be output).  */
419
420 void
421 loop_optimize (f, dumpfile, unroll_p, bct_p)
422      /* f is the first instruction of a chain of insns for one function */
423      rtx f;
424      FILE *dumpfile;
425      int unroll_p, bct_p;
426 {
427   register rtx insn;
428   register int i;
429   struct loops loops_data;
430   struct loops *loops = &loops_data;
431   struct loop_info *loops_info;
432
433   loop_dump_stream = dumpfile;
434
435   init_recog_no_volatile ();
436
437   max_reg_before_loop = max_reg_num ();
438   loop_max_reg = max_reg_before_loop;
439
440   regs_may_share = 0;
441
442   /* Count the number of loops.  */
443
444   max_loop_num = 0;
445   for (insn = f; insn; insn = NEXT_INSN (insn))
446     {
447       if (GET_CODE (insn) == NOTE
448           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
449         max_loop_num++;
450     }
451
452   /* Don't waste time if no loops.  */
453   if (max_loop_num == 0)
454     return;
455
456   loops->num = max_loop_num;
457
458   moved_once = (char *) xcalloc (max_reg_before_loop, sizeof (char));
459
460   /* Get size to use for tables indexed by uids.
461      Leave some space for labels allocated by find_and_verify_loops.  */
462   max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
463
464   uid_luid = (int *) xcalloc (max_uid_for_loop, sizeof (int));
465   uid_loop = (struct loop **) xcalloc (max_uid_for_loop, 
466                                        sizeof (struct loop *));
467
468   /* Allocate storage for array of loops.  */
469   loops->array = (struct loop *)
470     xcalloc (loops->num, sizeof (struct loop));
471
472   /* Find and process each loop.
473      First, find them, and record them in order of their beginnings.  */
474   find_and_verify_loops (f, loops);
475
476   /* Allocate and initialize auxiliary loop information.  */
477   loops_info = xcalloc (loops->num, sizeof (struct loop_info));
478   for (i = 0; i < loops->num; i++)
479     loops->array[i].aux = loops_info + i;
480
481   /* Now find all register lifetimes.  This must be done after
482      find_and_verify_loops, because it might reorder the insns in the
483      function.  */
484   reg_scan (f, max_reg_before_loop, 1);
485
486   /* This must occur after reg_scan so that registers created by gcse
487      will have entries in the register tables.
488
489      We could have added a call to reg_scan after gcse_main in toplev.c,
490      but moving this call to init_alias_analysis is more efficient.  */
491   init_alias_analysis ();
492
493   /* See if we went too far.  Note that get_max_uid already returns
494      one more that the maximum uid of all insn.  */
495   if (get_max_uid () > max_uid_for_loop)
496     abort ();
497   /* Now reset it to the actual size we need.  See above.  */
498   max_uid_for_loop = get_max_uid ();
499
500   /* find_and_verify_loops has already called compute_luids, but it
501      might have rearranged code afterwards, so we need to recompute
502      the luids now.  */
503   max_luid = compute_luids (f, NULL_RTX, 0);
504
505   /* Don't leave gaps in uid_luid for insns that have been
506      deleted.  It is possible that the first or last insn
507      using some register has been deleted by cross-jumping.
508      Make sure that uid_luid for that former insn's uid
509      points to the general area where that insn used to be.  */
510   for (i = 0; i < max_uid_for_loop; i++)
511     {
512       uid_luid[0] = uid_luid[i];
513       if (uid_luid[0] != 0)
514         break;
515     }
516   for (i = 0; i < max_uid_for_loop; i++)
517     if (uid_luid[i] == 0)
518       uid_luid[i] = uid_luid[i - 1];
519
520   /* If debugging and unrolling loops, we must replicate the tree
521      nodes corresponding to the BLOCKs inside the loop, so that the
522      original one to one mapping will remain.  We sometimes unroll
523      loops even when unroll_p is false, so we must always do this when
524      debugging.  */
525   if (write_symbols != NO_DEBUG)
526     find_loop_tree_blocks ();
527
528   /* Determine if the function has indirect jump.  On some systems
529      this prevents low overhead loop instructions from being used.  */
530   indirect_jump_in_function = indirect_jump_in_function_p (f);
531
532   /* Now scan the loops, last ones first, since this means inner ones are done
533      before outer ones.  */
534   for (i = max_loop_num - 1; i >= 0; i--)
535     {
536       struct loop *loop = &loops->array[i];
537
538       if (! loop->invalid && loop->end)
539         scan_loop (loop, unroll_p, bct_p);
540     }
541
542   /* Replicate the BLOCKs.  */
543   if (write_symbols != NO_DEBUG)
544     unroll_block_trees ();
545
546   end_alias_analysis ();
547
548   /* Clean up.  */
549   free (moved_once);
550   free (uid_luid);
551   free (uid_loop);
552   free (loops_info);
553   free (loops->array);
554 }
555 \f
556 /* Returns the next insn, in execution order, after INSN.  START and
557    END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
558    respectively.  LOOP->TOP, if non-NULL, is the top of the loop in the
559    insn-stream; it is used with loops that are entered near the
560    bottom.  */
561
562 static rtx
563 next_insn_in_loop (loop, insn)
564      const struct loop *loop;
565      rtx insn;
566 {
567   insn = NEXT_INSN (insn);
568
569   if (insn == loop->end)
570     {
571       if (loop->top)
572         /* Go to the top of the loop, and continue there.  */
573         insn = loop->top;
574       else
575         /* We're done.  */
576         insn = NULL_RTX;
577     }
578
579   if (insn == loop->scan_start)
580     /* We're done.  */
581     insn = NULL_RTX;
582
583   return insn;
584 }
585
586 /* Optimize one loop described by LOOP.  */
587
588 /* ??? Could also move memory writes out of loops if the destination address
589    is invariant, the source is invariant, the memory write is not volatile,
590    and if we can prove that no read inside the loop can read this address
591    before the write occurs.  If there is a read of this address after the
592    write, then we can also mark the memory read as invariant.  */
593
594 static void
595 scan_loop (loop, unroll_p, bct_p)
596      struct loop *loop;
597      int unroll_p, bct_p;
598 {
599   register int i;
600   rtx loop_start = loop->start;
601   rtx loop_end = loop->end;
602   /* Additional information about the current loop being processed
603      that is used to compute the number of loop iterations for loop
604      unrolling and doloop optimization.  */
605   struct loop_info *loop_info = LOOP_INFO (loop);
606   rtx p;
607   /* 1 if we are scanning insns that could be executed zero times.  */
608   int maybe_never = 0;
609   /* 1 if we are scanning insns that might never be executed
610      due to a subroutine call which might exit before they are reached.  */
611   int call_passed = 0;
612   /* Jump insn that enters the loop, or 0 if control drops in.  */
613   rtx loop_entry_jump = 0;
614   /* Number of insns in the loop.  */
615   int insn_count;
616   int in_libcall = 0;
617   int tem;
618   rtx temp, update_start, update_end;
619   /* The SET from an insn, if it is the only SET in the insn.  */
620   rtx set, set1;
621   /* Chain describing insns movable in current loop.  */
622   struct movable *movables = 0;
623   /* Last element in `movables' -- so we can add elements at the end.  */
624   struct movable *last_movable = 0;
625   /* Ratio of extra register life span we can justify
626      for saving an instruction.  More if loop doesn't call subroutines
627      since in that case saving an insn makes more difference
628      and more registers are available.  */
629   int threshold;
630   /* Nonzero if we are scanning instructions in a sub-loop.  */
631   int loop_depth = 0;
632   int nregs;
633
634   loop->top = 0;
635
636   /* Determine whether this loop starts with a jump down to a test at
637      the end.  This will occur for a small number of loops with a test
638      that is too complex to duplicate in front of the loop.
639
640      We search for the first insn or label in the loop, skipping NOTEs.
641      However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
642      (because we might have a loop executed only once that contains a
643      loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
644      (in case we have a degenerate loop).
645
646      Note that if we mistakenly think that a loop is entered at the top
647      when, in fact, it is entered at the exit test, the only effect will be
648      slightly poorer optimization.  Making the opposite error can generate
649      incorrect code.  Since very few loops now start with a jump to the 
650      exit test, the code here to detect that case is very conservative.  */
651
652   for (p = NEXT_INSN (loop_start);
653        p != loop_end
654          && GET_CODE (p) != CODE_LABEL && GET_RTX_CLASS (GET_CODE (p)) != 'i'
655          && (GET_CODE (p) != NOTE
656              || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
657                  && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
658        p = NEXT_INSN (p))
659     ;
660
661   loop->scan_start = p;
662
663   /* Set up variables describing this loop.  */
664   prescan_loop (loop);
665   threshold = (loop_info->has_call ? 1 : 2) * (1 + n_non_fixed_regs);
666
667   /* If loop has a jump before the first label,
668      the true entry is the target of that jump.
669      Start scan from there.
670      But record in LOOP->TOP the place where the end-test jumps
671      back to so we can scan that after the end of the loop.  */
672   if (GET_CODE (p) == JUMP_INSN)
673     {
674       loop_entry_jump = p;
675
676       /* Loop entry must be unconditional jump (and not a RETURN)  */
677       if (simplejump_p (p)
678           && JUMP_LABEL (p) != 0
679           /* Check to see whether the jump actually
680              jumps out of the loop (meaning it's no loop).
681              This case can happen for things like
682              do {..} while (0).  If this label was generated previously
683              by loop, we can't tell anything about it and have to reject
684              the loop.  */
685           && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, loop_end))
686         {
687           loop->top = next_label (loop->scan_start);
688           loop->scan_start = JUMP_LABEL (p);
689         }
690     }
691
692   /* If LOOP->SCAN_START was an insn created by loop, we don't know its luid
693      as required by loop_reg_used_before_p.  So skip such loops.  (This
694      test may never be true, but it's best to play it safe.) 
695
696      Also, skip loops where we do not start scanning at a label.  This
697      test also rejects loops starting with a JUMP_INSN that failed the
698      test above.  */
699
700   if (INSN_UID (loop->scan_start) >= max_uid_for_loop
701       || GET_CODE (loop->scan_start) != CODE_LABEL)
702     {
703       if (loop_dump_stream)
704         fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
705                  INSN_UID (loop_start), INSN_UID (loop_end));
706       return;
707     }
708
709   /* Count number of times each reg is set during this loop.
710      Set VARRAY_CHAR (may_not_optimize, I) if it is not safe to move out
711      the setting of register I.  Set VARRAY_RTX (reg_single_usage, I).  */
712   
713   /* Allocate extra space for REGS that might be created by
714      load_mems.  We allocate a little extra slop as well, in the hopes
715      that even after the moving of movables creates some new registers
716      we won't have to reallocate these arrays.  However, we do grow
717      the arrays, if necessary, in load_mems_recount_loop_regs_set.  */
718   nregs = max_reg_num () + loop_mems_idx + 16;
719   VARRAY_INT_INIT (set_in_loop, nregs, "set_in_loop");
720   VARRAY_INT_INIT (n_times_set, nregs, "n_times_set");
721   VARRAY_CHAR_INIT (may_not_optimize, nregs, "may_not_optimize");
722   VARRAY_RTX_INIT (reg_single_usage, nregs, "reg_single_usage");
723
724   count_loop_regs_set (loop->top ? loop->top : loop->start, loop->end,
725                        may_not_optimize, reg_single_usage, &insn_count, nregs);
726
727   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
728     {
729       VARRAY_CHAR (may_not_optimize, i) = 1;
730       VARRAY_INT (set_in_loop, i) = 1;
731     }
732
733 #ifdef AVOID_CCMODE_COPIES
734   /* Don't try to move insns which set CC registers if we should not
735      create CCmode register copies.  */
736   for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
737     if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
738       VARRAY_CHAR (may_not_optimize, i) = 1;
739 #endif
740
741   bcopy ((char *) &set_in_loop->data, 
742          (char *) &n_times_set->data, nregs * sizeof (int));
743
744   if (loop_dump_stream)
745     {
746       fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
747                INSN_UID (loop_start), INSN_UID (loop_end), insn_count);
748       if (loop->cont)
749         fprintf (loop_dump_stream, "Continue at insn %d.\n",
750                  INSN_UID (loop->cont));
751     }
752
753   /* Scan through the loop finding insns that are safe to move.
754      Set set_in_loop negative for the reg being set, so that
755      this reg will be considered invariant for subsequent insns.
756      We consider whether subsequent insns use the reg
757      in deciding whether it is worth actually moving.
758
759      MAYBE_NEVER is nonzero if we have passed a conditional jump insn
760      and therefore it is possible that the insns we are scanning
761      would never be executed.  At such times, we must make sure
762      that it is safe to execute the insn once instead of zero times.
763      When MAYBE_NEVER is 0, all insns will be executed at least once
764      so that is not a problem.  */
765
766   for (p = next_insn_in_loop (loop, loop->scan_start); 
767        p != NULL_RTX;
768        p = next_insn_in_loop (loop, p))
769     {
770       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
771           && find_reg_note (p, REG_LIBCALL, NULL_RTX))
772         in_libcall = 1;
773       else if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
774                && find_reg_note (p, REG_RETVAL, NULL_RTX))
775         in_libcall = 0;
776
777       if (GET_CODE (p) == INSN
778           && (set = single_set (p))
779           && GET_CODE (SET_DEST (set)) == REG
780           && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
781         {
782           int tem1 = 0;
783           int tem2 = 0;
784           int move_insn = 0;
785           rtx src = SET_SRC (set);
786           rtx dependencies = 0;
787
788           /* Figure out what to use as a source of this insn.  If a REG_EQUIV
789              note is given or if a REG_EQUAL note with a constant operand is
790              specified, use it as the source and mark that we should move
791              this insn by calling emit_move_insn rather that duplicating the
792              insn.
793
794              Otherwise, only use the REG_EQUAL contents if a REG_RETVAL note
795              is present.  */
796           temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
797           if (temp)
798             src = XEXP (temp, 0), move_insn = 1;
799           else 
800             {
801               temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
802               if (temp && CONSTANT_P (XEXP (temp, 0)))
803                 src = XEXP (temp, 0), move_insn = 1;
804               if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
805                 {
806                   src = XEXP (temp, 0);
807                   /* A libcall block can use regs that don't appear in
808                      the equivalent expression.  To move the libcall,
809                      we must move those regs too.  */
810                   dependencies = libcall_other_reg (p, src);
811                 }
812             }
813
814           /* Don't try to optimize a register that was made
815              by loop-optimization for an inner loop.
816              We don't know its life-span, so we can't compute the benefit.  */
817           if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
818             ;
819           else if (/* The register is used in basic blocks other
820                       than the one where it is set (meaning that
821                       something after this point in the loop might
822                       depend on its value before the set).  */
823                    ! reg_in_basic_block_p (p, SET_DEST (set))
824                    /* And the set is not guaranteed to be executed one
825                       the loop starts, or the value before the set is
826                       needed before the set occurs... 
827
828                       ??? Note we have quadratic behaviour here, mitigated
829                       by the fact that the previous test will often fail for
830                       large loops.  Rather than re-scanning the entire loop
831                       each time for register usage, we should build tables
832                       of the register usage and use them here instead.  */
833                    && (maybe_never
834                        || loop_reg_used_before_p (loop, set, p)))
835             /* It is unsafe to move the set.  
836
837                This code used to consider it OK to move a set of a variable
838                which was not created by the user and not used in an exit test.
839                That behavior is incorrect and was removed.  */
840             ;
841           else if ((tem = loop_invariant_p (loop, src))
842                    && (dependencies == 0
843                        || (tem2 = loop_invariant_p (loop, dependencies)) != 0)
844                    && (VARRAY_INT (set_in_loop, 
845                                    REGNO (SET_DEST (set))) == 1
846                        || (tem1
847                            = consec_sets_invariant_p 
848                            (loop, SET_DEST (set),
849                             VARRAY_INT (set_in_loop, REGNO (SET_DEST (set))),
850                             p)))
851                    /* If the insn can cause a trap (such as divide by zero),
852                       can't move it unless it's guaranteed to be executed
853                       once loop is entered.  Even a function call might
854                       prevent the trap insn from being reached
855                       (since it might exit!)  */
856                    && ! ((maybe_never || call_passed)
857                          && may_trap_p (src)))
858             {
859               register struct movable *m;
860               register int regno = REGNO (SET_DEST (set));
861
862               /* A potential lossage is where we have a case where two insns
863                  can be combined as long as they are both in the loop, but
864                  we move one of them outside the loop.  For large loops,
865                  this can lose.  The most common case of this is the address
866                  of a function being called.  
867
868                  Therefore, if this register is marked as being used exactly
869                  once if we are in a loop with calls (a "large loop"), see if
870                  we can replace the usage of this register with the source
871                  of this SET.  If we can, delete this insn. 
872
873                  Don't do this if P has a REG_RETVAL note or if we have
874                  SMALL_REGISTER_CLASSES and SET_SRC is a hard register.  */
875
876               if (loop_info->has_call
877                   && VARRAY_RTX (reg_single_usage, regno) != 0
878                   && VARRAY_RTX (reg_single_usage, regno) != const0_rtx
879                   && REGNO_FIRST_UID (regno) == INSN_UID (p)
880                   && (REGNO_LAST_UID (regno)
881                       == INSN_UID (VARRAY_RTX (reg_single_usage, regno)))
882                   && VARRAY_INT (set_in_loop, regno) == 1
883                   && ! side_effects_p (SET_SRC (set))
884                   && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
885                   && (! SMALL_REGISTER_CLASSES
886                       || (! (GET_CODE (SET_SRC (set)) == REG
887                              && REGNO (SET_SRC (set)) < FIRST_PSEUDO_REGISTER)))
888                   /* This test is not redundant; SET_SRC (set) might be
889                      a call-clobbered register and the life of REGNO
890                      might span a call.  */
891                   && ! modified_between_p (SET_SRC (set), p,
892                                            VARRAY_RTX
893                                            (reg_single_usage, regno)) 
894                   && no_labels_between_p (p, VARRAY_RTX (reg_single_usage, regno))
895                   && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
896                                            VARRAY_RTX
897                                            (reg_single_usage, regno))) 
898                 {
899                   /* Replace any usage in a REG_EQUAL note.  Must copy the
900                      new source, so that we don't get rtx sharing between the
901                      SET_SOURCE and REG_NOTES of insn p.  */
902                   REG_NOTES (VARRAY_RTX (reg_single_usage, regno))
903                     = replace_rtx (REG_NOTES (VARRAY_RTX
904                                               (reg_single_usage, regno)), 
905                                    SET_DEST (set), copy_rtx (SET_SRC (set)));
906                                    
907                   PUT_CODE (p, NOTE);
908                   NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED;
909                   NOTE_SOURCE_FILE (p) = 0;
910                   VARRAY_INT (set_in_loop, regno) = 0;
911                   continue;
912                 }
913
914               m = (struct movable *) alloca (sizeof (struct movable));
915               m->next = 0;
916               m->insn = p;
917               m->set_src = src;
918               m->dependencies = dependencies;
919               m->set_dest = SET_DEST (set);
920               m->force = 0;
921               m->consec = VARRAY_INT (set_in_loop, 
922                                       REGNO (SET_DEST (set))) - 1;
923               m->done = 0;
924               m->forces = 0;
925               m->partial = 0;
926               m->move_insn = move_insn;
927               m->move_insn_first = 0;
928               m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
929               m->savemode = VOIDmode;
930               m->regno = regno;
931               /* Set M->cond if either loop_invariant_p
932                  or consec_sets_invariant_p returned 2
933                  (only conditionally invariant).  */
934               m->cond = ((tem | tem1 | tem2) > 1);
935               m->global = (uid_luid[REGNO_LAST_UID (regno)] 
936                            > INSN_LUID (loop_end)
937                            || uid_luid[REGNO_FIRST_UID (regno)] < INSN_LUID (loop_start));
938               m->match = 0;
939               m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
940                              - uid_luid[REGNO_FIRST_UID (regno)]);
941               m->savings = VARRAY_INT (n_times_set, regno);
942               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
943                 m->savings += libcall_benefit (p);
944               VARRAY_INT (set_in_loop, regno) = move_insn ? -2 : -1;
945               /* Add M to the end of the chain MOVABLES.  */
946               if (movables == 0)
947                 movables = m;
948               else
949                 last_movable->next = m;
950               last_movable = m;
951
952               if (m->consec > 0)
953                 {
954                   /* It is possible for the first instruction to have a
955                      REG_EQUAL note but a non-invariant SET_SRC, so we must
956                      remember the status of the first instruction in case
957                      the last instruction doesn't have a REG_EQUAL note.  */
958                   m->move_insn_first = m->move_insn;
959
960                   /* Skip this insn, not checking REG_LIBCALL notes.  */
961                   p = next_nonnote_insn (p);
962                   /* Skip the consecutive insns, if there are any.  */
963                   p = skip_consec_insns (p, m->consec);
964                   /* Back up to the last insn of the consecutive group.  */
965                   p = prev_nonnote_insn (p);
966
967                   /* We must now reset m->move_insn, m->is_equiv, and possibly
968                      m->set_src to correspond to the effects of all the
969                      insns.  */
970                   temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
971                   if (temp)
972                     m->set_src = XEXP (temp, 0), m->move_insn = 1;
973                   else
974                     {
975                       temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
976                       if (temp && CONSTANT_P (XEXP (temp, 0)))
977                         m->set_src = XEXP (temp, 0), m->move_insn = 1;
978                       else
979                         m->move_insn = 0;
980
981                     }
982                   m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
983                 }
984             }
985           /* If this register is always set within a STRICT_LOW_PART
986              or set to zero, then its high bytes are constant.
987              So clear them outside the loop and within the loop
988              just load the low bytes.
989              We must check that the machine has an instruction to do so.
990              Also, if the value loaded into the register
991              depends on the same register, this cannot be done.  */
992           else if (SET_SRC (set) == const0_rtx
993                    && GET_CODE (NEXT_INSN (p)) == INSN
994                    && (set1 = single_set (NEXT_INSN (p)))
995                    && GET_CODE (set1) == SET
996                    && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
997                    && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
998                    && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
999                        == SET_DEST (set))
1000                    && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1001             {
1002               register int regno = REGNO (SET_DEST (set));
1003               if (VARRAY_INT (set_in_loop, regno) == 2)
1004                 {
1005                   register struct movable *m;
1006                   m = (struct movable *) alloca (sizeof (struct movable));
1007                   m->next = 0;
1008                   m->insn = p;
1009                   m->set_dest = SET_DEST (set);
1010                   m->dependencies = 0;
1011                   m->force = 0;
1012                   m->consec = 0;
1013                   m->done = 0;
1014                   m->forces = 0;
1015                   m->move_insn = 0;
1016                   m->move_insn_first = 0;
1017                   m->partial = 1;
1018                   /* If the insn may not be executed on some cycles,
1019                      we can't clear the whole reg; clear just high part.
1020                      Not even if the reg is used only within this loop.
1021                      Consider this:
1022                      while (1)
1023                        while (s != t) {
1024                          if (foo ()) x = *s;
1025                          use (x);
1026                        }
1027                      Clearing x before the inner loop could clobber a value
1028                      being saved from the last time around the outer loop.
1029                      However, if the reg is not used outside this loop
1030                      and all uses of the register are in the same
1031                      basic block as the store, there is no problem.
1032
1033                      If this insn was made by loop, we don't know its
1034                      INSN_LUID and hence must make a conservative
1035                      assumption.  */
1036                   m->global = (INSN_UID (p) >= max_uid_for_loop
1037                                || (uid_luid[REGNO_LAST_UID (regno)]
1038                                    > INSN_LUID (loop_end))
1039                                || (uid_luid[REGNO_FIRST_UID (regno)]
1040                                    < INSN_LUID (p))
1041                                || (labels_in_range_p
1042                                    (p, uid_luid[REGNO_FIRST_UID (regno)])));
1043                   if (maybe_never && m->global)
1044                     m->savemode = GET_MODE (SET_SRC (set1));
1045                   else
1046                     m->savemode = VOIDmode;
1047                   m->regno = regno;
1048                   m->cond = 0;
1049                   m->match = 0;
1050                   m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
1051                                  - uid_luid[REGNO_FIRST_UID (regno)]);
1052                   m->savings = 1;
1053                   VARRAY_INT (set_in_loop, regno) = -1;
1054                   /* Add M to the end of the chain MOVABLES.  */
1055                   if (movables == 0)
1056                     movables = m;
1057                   else
1058                     last_movable->next = m;
1059                   last_movable = m;
1060                 }
1061             }
1062         }
1063       /* Past a call insn, we get to insns which might not be executed
1064          because the call might exit.  This matters for insns that trap.
1065          Call insns inside a REG_LIBCALL/REG_RETVAL block always return,
1066          so they don't count.  */
1067       else if (GET_CODE (p) == CALL_INSN && ! in_libcall)
1068         call_passed = 1;
1069       /* Past a label or a jump, we get to insns for which we
1070          can't count on whether or how many times they will be
1071          executed during each iteration.  Therefore, we can
1072          only move out sets of trivial variables
1073          (those not used after the loop).  */
1074       /* Similar code appears twice in strength_reduce.  */
1075       else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
1076                /* If we enter the loop in the middle, and scan around to the
1077                   beginning, don't set maybe_never for that.  This must be an
1078                   unconditional jump, otherwise the code at the top of the
1079                   loop might never be executed.  Unconditional jumps are
1080                   followed a by barrier then loop end.  */
1081                && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop->top
1082                      && NEXT_INSN (NEXT_INSN (p)) == loop_end
1083                      && simplejump_p (p)))
1084         maybe_never = 1;
1085       else if (GET_CODE (p) == NOTE)
1086         {
1087           /* At the virtual top of a converted loop, insns are again known to
1088              be executed: logically, the loop begins here even though the exit
1089              code has been duplicated.  */
1090           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1091             maybe_never = call_passed = 0;
1092           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1093             loop_depth++;
1094           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1095             loop_depth--;
1096         }
1097     }
1098
1099   /* If one movable subsumes another, ignore that other.  */
1100
1101   ignore_some_movables (movables);
1102
1103   /* For each movable insn, see if the reg that it loads
1104      leads when it dies right into another conditionally movable insn.
1105      If so, record that the second insn "forces" the first one,
1106      since the second can be moved only if the first is.  */
1107
1108   force_movables (movables);
1109
1110   /* See if there are multiple movable insns that load the same value.
1111      If there are, make all but the first point at the first one
1112      through the `match' field, and add the priorities of them
1113      all together as the priority of the first.  */
1114
1115   combine_movables (movables, nregs);
1116         
1117   /* Now consider each movable insn to decide whether it is worth moving.
1118      Store 0 in set_in_loop for each reg that is moved.
1119
1120      Generally this increases code size, so do not move moveables when
1121      optimizing for code size.  */
1122
1123   if (! optimize_size)
1124     move_movables (loop, movables, threshold, insn_count, nregs);
1125
1126   /* Now candidates that still are negative are those not moved.
1127      Change set_in_loop to indicate that those are not actually invariant.  */
1128   for (i = 0; i < nregs; i++)
1129     if (VARRAY_INT (set_in_loop, i) < 0)
1130       VARRAY_INT (set_in_loop, i) = VARRAY_INT (n_times_set, i);
1131
1132   /* Now that we've moved some things out of the loop, we might be able to
1133      hoist even more memory references.  */
1134   load_mems_and_recount_loop_regs_set (loop, &insn_count);
1135
1136   for (update_start = loop_start;
1137        PREV_INSN (update_start)
1138          && GET_CODE (PREV_INSN (update_start)) != CODE_LABEL;
1139        update_start = PREV_INSN (update_start))
1140     ;
1141   update_end = NEXT_INSN (loop_end);
1142
1143   reg_scan_update (update_start, update_end, loop_max_reg);
1144   loop_max_reg = max_reg_num ();
1145
1146   if (flag_strength_reduce)
1147     {
1148       the_movables = movables;
1149       strength_reduce (loop, insn_count, unroll_p, bct_p);
1150
1151       reg_scan_update (update_start, update_end, loop_max_reg);
1152       loop_max_reg = max_reg_num ();
1153     }
1154
1155   VARRAY_FREE (reg_single_usage);
1156   VARRAY_FREE (set_in_loop);
1157   VARRAY_FREE (n_times_set);
1158   VARRAY_FREE (may_not_optimize);
1159 }
1160 \f
1161 /* Add elements to *OUTPUT to record all the pseudo-regs
1162    mentioned in IN_THIS but not mentioned in NOT_IN_THIS.  */
1163
1164 void
1165 record_excess_regs (in_this, not_in_this, output)
1166      rtx in_this, not_in_this;
1167      rtx *output;
1168 {
1169   enum rtx_code code;
1170   const char *fmt;
1171   int i;
1172
1173   code = GET_CODE (in_this);
1174
1175   switch (code)
1176     {
1177     case PC:
1178     case CC0:
1179     case CONST_INT:
1180     case CONST_DOUBLE:
1181     case CONST:
1182     case SYMBOL_REF:
1183     case LABEL_REF:
1184       return;
1185
1186     case REG:
1187       if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1188           && ! reg_mentioned_p (in_this, not_in_this))
1189         *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1190       return;
1191       
1192     default:
1193       break;
1194     }
1195
1196   fmt = GET_RTX_FORMAT (code);
1197   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1198     {
1199       int j;
1200
1201       switch (fmt[i])
1202         {
1203         case 'E':
1204           for (j = 0; j < XVECLEN (in_this, i); j++)
1205             record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1206           break;
1207
1208         case 'e':
1209           record_excess_regs (XEXP (in_this, i), not_in_this, output);
1210           break;
1211         }
1212     }
1213 }
1214 \f
1215 /* Check what regs are referred to in the libcall block ending with INSN,
1216    aside from those mentioned in the equivalent value.
1217    If there are none, return 0.
1218    If there are one or more, return an EXPR_LIST containing all of them.  */
1219
1220 rtx
1221 libcall_other_reg (insn, equiv)
1222      rtx insn, equiv;
1223 {
1224   rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1225   rtx p = XEXP (note, 0);
1226   rtx output = 0;
1227
1228   /* First, find all the regs used in the libcall block
1229      that are not mentioned as inputs to the result.  */
1230
1231   while (p != insn)
1232     {
1233       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1234           || GET_CODE (p) == CALL_INSN)
1235         record_excess_regs (PATTERN (p), equiv, &output);
1236       p = NEXT_INSN (p);
1237     }
1238
1239   return output;
1240 }
1241 \f
1242 /* Return 1 if all uses of REG
1243    are between INSN and the end of the basic block.  */
1244
1245 static int 
1246 reg_in_basic_block_p (insn, reg)
1247      rtx insn, reg;
1248 {
1249   int regno = REGNO (reg);
1250   rtx p;
1251
1252   if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1253     return 0;
1254
1255   /* Search this basic block for the already recorded last use of the reg.  */
1256   for (p = insn; p; p = NEXT_INSN (p))
1257     {
1258       switch (GET_CODE (p))
1259         {
1260         case NOTE:
1261           break;
1262
1263         case INSN:
1264         case CALL_INSN:
1265           /* Ordinary insn: if this is the last use, we win.  */
1266           if (REGNO_LAST_UID (regno) == INSN_UID (p))
1267             return 1;
1268           break;
1269
1270         case JUMP_INSN:
1271           /* Jump insn: if this is the last use, we win.  */
1272           if (REGNO_LAST_UID (regno) == INSN_UID (p))
1273             return 1;
1274           /* Otherwise, it's the end of the basic block, so we lose.  */
1275           return 0;
1276
1277         case CODE_LABEL:
1278         case BARRIER:
1279           /* It's the end of the basic block, so we lose.  */
1280           return 0;
1281           
1282         default:
1283           break;
1284         }
1285     }
1286
1287   /* The "last use" that was recorded can't be found after the first
1288      use.  This can happen when the last use was deleted while
1289      processing an inner loop, this inner loop was then completely
1290      unrolled, and the outer loop is always exited after the inner loop,
1291      so that everything after the first use becomes a single basic block.  */
1292   return 1;
1293 }
1294 \f
1295 /* Compute the benefit of eliminating the insns in the block whose
1296    last insn is LAST.  This may be a group of insns used to compute a
1297    value directly or can contain a library call.  */
1298
1299 static int
1300 libcall_benefit (last)
1301      rtx last;
1302 {
1303   rtx insn;
1304   int benefit = 0;
1305
1306   for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1307        insn != last; insn = NEXT_INSN (insn))
1308     {
1309       if (GET_CODE (insn) == CALL_INSN)
1310         benefit += 10;          /* Assume at least this many insns in a library
1311                                    routine.  */
1312       else if (GET_CODE (insn) == INSN
1313                && GET_CODE (PATTERN (insn)) != USE
1314                && GET_CODE (PATTERN (insn)) != CLOBBER)
1315         benefit++;
1316     }
1317
1318   return benefit;
1319 }
1320 \f
1321 /* Skip COUNT insns from INSN, counting library calls as 1 insn.  */
1322
1323 static rtx
1324 skip_consec_insns (insn, count)
1325      rtx insn;
1326      int count;
1327 {
1328   for (; count > 0; count--)
1329     {
1330       rtx temp;
1331
1332       /* If first insn of libcall sequence, skip to end.  */
1333       /* Do this at start of loop, since INSN is guaranteed to 
1334          be an insn here.  */
1335       if (GET_CODE (insn) != NOTE
1336           && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1337         insn = XEXP (temp, 0);
1338
1339       do insn = NEXT_INSN (insn);
1340       while (GET_CODE (insn) == NOTE);
1341     }
1342
1343   return insn;
1344 }
1345
1346 /* Ignore any movable whose insn falls within a libcall
1347    which is part of another movable.
1348    We make use of the fact that the movable for the libcall value
1349    was made later and so appears later on the chain.  */
1350
1351 static void
1352 ignore_some_movables (movables)
1353      struct movable *movables;
1354 {
1355   register struct movable *m, *m1;
1356
1357   for (m = movables; m; m = m->next)
1358     {
1359       /* Is this a movable for the value of a libcall?  */
1360       rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1361       if (note)
1362         {
1363           rtx insn;
1364           /* Check for earlier movables inside that range,
1365              and mark them invalid.  We cannot use LUIDs here because
1366              insns created by loop.c for prior loops don't have LUIDs.
1367              Rather than reject all such insns from movables, we just
1368              explicitly check each insn in the libcall (since invariant
1369              libcalls aren't that common).  */
1370           for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1371             for (m1 = movables; m1 != m; m1 = m1->next)
1372               if (m1->insn == insn)
1373                 m1->done = 1;
1374         }
1375     }
1376 }         
1377
1378 /* For each movable insn, see if the reg that it loads
1379    leads when it dies right into another conditionally movable insn.
1380    If so, record that the second insn "forces" the first one,
1381    since the second can be moved only if the first is.  */
1382
1383 static void
1384 force_movables (movables)
1385      struct movable *movables;
1386 {
1387   register struct movable *m, *m1;
1388   for (m1 = movables; m1; m1 = m1->next)
1389     /* Omit this if moving just the (SET (REG) 0) of a zero-extend.  */
1390     if (!m1->partial && !m1->done)
1391       {
1392         int regno = m1->regno;
1393         for (m = m1->next; m; m = m->next)
1394           /* ??? Could this be a bug?  What if CSE caused the
1395              register of M1 to be used after this insn?
1396              Since CSE does not update regno_last_uid,
1397              this insn M->insn might not be where it dies.
1398              But very likely this doesn't matter; what matters is
1399              that M's reg is computed from M1's reg.  */
1400           if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1401               && !m->done)
1402             break;
1403         if (m != 0 && m->set_src == m1->set_dest
1404             /* If m->consec, m->set_src isn't valid.  */
1405             && m->consec == 0)
1406           m = 0;
1407
1408         /* Increase the priority of the moving the first insn
1409            since it permits the second to be moved as well.  */
1410         if (m != 0)
1411           {
1412             m->forces = m1;
1413             m1->lifetime += m->lifetime;
1414             m1->savings += m->savings;
1415           }
1416       }
1417 }
1418 \f
1419 /* Find invariant expressions that are equal and can be combined into
1420    one register.  */
1421
1422 static void
1423 combine_movables (movables, nregs)
1424      struct movable *movables;
1425      int nregs;
1426 {
1427   register struct movable *m;
1428   char *matched_regs = (char *) xmalloc (nregs);
1429   enum machine_mode mode;
1430
1431   /* Regs that are set more than once are not allowed to match
1432      or be matched.  I'm no longer sure why not.  */
1433   /* Perhaps testing m->consec_sets would be more appropriate here?  */
1434
1435   for (m = movables; m; m = m->next)
1436     if (m->match == 0 && VARRAY_INT (n_times_set, m->regno) == 1 && !m->partial)
1437       {
1438         register struct movable *m1;
1439         int regno = m->regno;
1440
1441         bzero (matched_regs, nregs);
1442         matched_regs[regno] = 1;
1443
1444         /* We want later insns to match the first one.  Don't make the first
1445            one match any later ones.  So start this loop at m->next.  */
1446         for (m1 = m->next; m1; m1 = m1->next)
1447           if (m != m1 && m1->match == 0 && VARRAY_INT (n_times_set, m1->regno) == 1
1448               /* A reg used outside the loop mustn't be eliminated.  */
1449               && !m1->global
1450               /* A reg used for zero-extending mustn't be eliminated.  */
1451               && !m1->partial
1452               && (matched_regs[m1->regno]
1453                   ||
1454                   (
1455                    /* Can combine regs with different modes loaded from the
1456                       same constant only if the modes are the same or
1457                       if both are integer modes with M wider or the same
1458                       width as M1.  The check for integer is redundant, but
1459                       safe, since the only case of differing destination
1460                       modes with equal sources is when both sources are
1461                       VOIDmode, i.e., CONST_INT.  */
1462                    (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1463                     || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1464                         && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1465                         && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1466                             >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1467                    /* See if the source of M1 says it matches M.  */
1468                    && ((GET_CODE (m1->set_src) == REG
1469                         && matched_regs[REGNO (m1->set_src)])
1470                        || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1471                                                 movables))))
1472               && ((m->dependencies == m1->dependencies)
1473                   || rtx_equal_p (m->dependencies, m1->dependencies)))
1474             {
1475               m->lifetime += m1->lifetime;
1476               m->savings += m1->savings;
1477               m1->done = 1;
1478               m1->match = m;
1479               matched_regs[m1->regno] = 1;
1480             }
1481       }
1482
1483   /* Now combine the regs used for zero-extension.
1484      This can be done for those not marked `global'
1485      provided their lives don't overlap.  */
1486
1487   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1488        mode = GET_MODE_WIDER_MODE (mode))
1489     {
1490       register struct movable *m0 = 0;
1491
1492       /* Combine all the registers for extension from mode MODE.
1493          Don't combine any that are used outside this loop.  */
1494       for (m = movables; m; m = m->next)
1495         if (m->partial && ! m->global
1496             && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1497           {
1498             register struct movable *m1;
1499             int first = uid_luid[REGNO_FIRST_UID (m->regno)];
1500             int last = uid_luid[REGNO_LAST_UID (m->regno)];
1501
1502             if (m0 == 0)
1503               {
1504                 /* First one: don't check for overlap, just record it.  */
1505                 m0 = m;
1506                   continue;
1507               }
1508
1509             /* Make sure they extend to the same mode.
1510                (Almost always true.)  */
1511             if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1512                 continue;
1513
1514             /* We already have one: check for overlap with those
1515                already combined together.  */
1516             for (m1 = movables; m1 != m; m1 = m1->next)
1517               if (m1 == m0 || (m1->partial && m1->match == m0))
1518                 if (! (uid_luid[REGNO_FIRST_UID (m1->regno)] > last
1519                        || uid_luid[REGNO_LAST_UID (m1->regno)] < first))
1520                   goto overlap;
1521
1522             /* No overlap: we can combine this with the others.  */
1523             m0->lifetime += m->lifetime;
1524             m0->savings += m->savings;
1525             m->done = 1;
1526             m->match = m0;
1527
1528           overlap: ;
1529           }
1530     }
1531
1532   /* Clean up.  */
1533   free (matched_regs);
1534 }
1535 \f
1536 /* Return 1 if regs X and Y will become the same if moved.  */
1537
1538 static int
1539 regs_match_p (x, y, movables)
1540      rtx x, y;
1541      struct movable *movables;
1542 {
1543   int xn = REGNO (x);
1544   int yn = REGNO (y);
1545   struct movable *mx, *my;
1546
1547   for (mx = movables; mx; mx = mx->next)
1548     if (mx->regno == xn)
1549       break;
1550
1551   for (my = movables; my; my = my->next)
1552     if (my->regno == yn)
1553       break;
1554
1555   return (mx && my
1556           && ((mx->match == my->match && mx->match != 0)
1557               || mx->match == my
1558               || mx == my->match));
1559 }
1560
1561 /* Return 1 if X and Y are identical-looking rtx's.
1562    This is the Lisp function EQUAL for rtx arguments.
1563
1564    If two registers are matching movables or a movable register and an
1565    equivalent constant, consider them equal.  */
1566
1567 static int
1568 rtx_equal_for_loop_p (x, y, movables)
1569      rtx x, y;
1570      struct movable *movables;
1571 {
1572   register int i;
1573   register int j;
1574   register struct movable *m;
1575   register enum rtx_code code;
1576   register const char *fmt;
1577
1578   if (x == y)
1579     return 1;
1580   if (x == 0 || y == 0)
1581     return 0;
1582
1583   code = GET_CODE (x);
1584
1585   /* If we have a register and a constant, they may sometimes be
1586      equal.  */
1587   if (GET_CODE (x) == REG && VARRAY_INT (set_in_loop, REGNO (x)) == -2
1588       && CONSTANT_P (y))
1589     {
1590       for (m = movables; m; m = m->next)
1591         if (m->move_insn && m->regno == REGNO (x)
1592             && rtx_equal_p (m->set_src, y))
1593           return 1;
1594     }
1595   else if (GET_CODE (y) == REG && VARRAY_INT (set_in_loop, REGNO (y)) == -2
1596            && CONSTANT_P (x))
1597     {
1598       for (m = movables; m; m = m->next)
1599         if (m->move_insn && m->regno == REGNO (y)
1600             && rtx_equal_p (m->set_src, x))
1601           return 1;
1602     }
1603
1604   /* Otherwise, rtx's of different codes cannot be equal.  */
1605   if (code != GET_CODE (y))
1606     return 0;
1607
1608   /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1609      (REG:SI x) and (REG:HI x) are NOT equivalent.  */
1610
1611   if (GET_MODE (x) != GET_MODE (y))
1612     return 0;
1613
1614   /* These three types of rtx's can be compared nonrecursively.  */
1615   if (code == REG)
1616     return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1617
1618   if (code == LABEL_REF)
1619     return XEXP (x, 0) == XEXP (y, 0);
1620   if (code == SYMBOL_REF)
1621     return XSTR (x, 0) == XSTR (y, 0);
1622
1623   /* Compare the elements.  If any pair of corresponding elements
1624      fail to match, return 0 for the whole things.  */
1625
1626   fmt = GET_RTX_FORMAT (code);
1627   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1628     {
1629       switch (fmt[i])
1630         {
1631         case 'w':
1632           if (XWINT (x, i) != XWINT (y, i))
1633             return 0;
1634           break;
1635
1636         case 'i':
1637           if (XINT (x, i) != XINT (y, i))
1638             return 0;
1639           break;
1640
1641         case 'E':
1642           /* Two vectors must have the same length.  */
1643           if (XVECLEN (x, i) != XVECLEN (y, i))
1644             return 0;
1645
1646           /* And the corresponding elements must match.  */
1647           for (j = 0; j < XVECLEN (x, i); j++)
1648             if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j), movables) == 0)
1649               return 0;
1650           break;
1651
1652         case 'e':
1653           if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables) == 0)
1654             return 0;
1655           break;
1656
1657         case 's':
1658           if (strcmp (XSTR (x, i), XSTR (y, i)))
1659             return 0;
1660           break;
1661
1662         case 'u':
1663           /* These are just backpointers, so they don't matter.  */
1664           break;
1665
1666         case '0':
1667           break;
1668
1669           /* It is believed that rtx's at this level will never
1670              contain anything but integers and other rtx's,
1671              except for within LABEL_REFs and SYMBOL_REFs.  */
1672         default:
1673           abort ();
1674         }
1675     }
1676   return 1;
1677 }
1678 \f
1679 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1680   insns in INSNS which use the reference.  */
1681
1682 static void
1683 add_label_notes (x, insns)
1684      rtx x;
1685      rtx insns;
1686 {
1687   enum rtx_code code = GET_CODE (x);
1688   int i, j;
1689   const char *fmt;
1690   rtx insn;
1691
1692   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1693     {
1694       /* This code used to ignore labels that referred to dispatch tables to
1695          avoid flow generating (slighly) worse code.
1696
1697          We no longer ignore such label references (see LABEL_REF handling in
1698          mark_jump_label for additional information).  */
1699       for (insn = insns; insn; insn = NEXT_INSN (insn))
1700         if (reg_mentioned_p (XEXP (x, 0), insn))
1701           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_LABEL, XEXP (x, 0),
1702                                                 REG_NOTES (insn));
1703     }
1704
1705   fmt = GET_RTX_FORMAT (code);
1706   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1707     {
1708       if (fmt[i] == 'e')
1709         add_label_notes (XEXP (x, i), insns);
1710       else if (fmt[i] == 'E')
1711         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1712           add_label_notes (XVECEXP (x, i, j), insns);
1713     }
1714 }
1715 \f
1716 /* Scan MOVABLES, and move the insns that deserve to be moved.
1717    If two matching movables are combined, replace one reg with the
1718    other throughout.  */
1719
1720 static void
1721 move_movables (loop, movables, threshold, insn_count, nregs)
1722      struct loop *loop;
1723      struct movable *movables;
1724      int threshold;
1725      int insn_count;
1726      int nregs;
1727 {
1728   rtx new_start = 0;
1729   register struct movable *m;
1730   register rtx p;
1731   rtx loop_start = loop->start;
1732   rtx loop_end = loop->end;
1733   /* Map of pseudo-register replacements to handle combining
1734      when we move several insns that load the same value
1735      into different pseudo-registers.  */
1736   rtx *reg_map = (rtx *) xcalloc (nregs, sizeof (rtx));
1737   char *already_moved = (char *) xcalloc (nregs, sizeof (char));
1738
1739   num_movables = 0;
1740
1741   for (m = movables; m; m = m->next)
1742     {
1743       /* Describe this movable insn.  */
1744
1745       if (loop_dump_stream)
1746         {
1747           fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1748                    INSN_UID (m->insn), m->regno, m->lifetime);
1749           if (m->consec > 0)
1750             fprintf (loop_dump_stream, "consec %d, ", m->consec);
1751           if (m->cond)
1752             fprintf (loop_dump_stream, "cond ");
1753           if (m->force)
1754             fprintf (loop_dump_stream, "force ");
1755           if (m->global)
1756             fprintf (loop_dump_stream, "global ");
1757           if (m->done)
1758             fprintf (loop_dump_stream, "done ");
1759           if (m->move_insn)
1760             fprintf (loop_dump_stream, "move-insn ");
1761           if (m->match)
1762             fprintf (loop_dump_stream, "matches %d ",
1763                      INSN_UID (m->match->insn));
1764           if (m->forces)
1765             fprintf (loop_dump_stream, "forces %d ",
1766                      INSN_UID (m->forces->insn));
1767         }
1768
1769       /* Count movables.  Value used in heuristics in strength_reduce.  */
1770       num_movables++;
1771
1772       /* Ignore the insn if it's already done (it matched something else).
1773          Otherwise, see if it is now safe to move.  */
1774
1775       if (!m->done
1776           && (! m->cond
1777               || (1 == loop_invariant_p (loop, m->set_src)
1778                   && (m->dependencies == 0
1779                       || 1 == loop_invariant_p (loop, m->dependencies))
1780                   && (m->consec == 0
1781                       || 1 == consec_sets_invariant_p (loop, m->set_dest,
1782                                                        m->consec + 1,
1783                                                        m->insn))))
1784           && (! m->forces || m->forces->done))
1785         {
1786           register int regno;
1787           register rtx p;
1788           int savings = m->savings;
1789
1790           /* We have an insn that is safe to move.
1791              Compute its desirability.  */
1792
1793           p = m->insn;
1794           regno = m->regno;
1795
1796           if (loop_dump_stream)
1797             fprintf (loop_dump_stream, "savings %d ", savings);
1798
1799           if (moved_once[regno] && loop_dump_stream)
1800             fprintf (loop_dump_stream, "halved since already moved ");
1801
1802           /* An insn MUST be moved if we already moved something else
1803              which is safe only if this one is moved too: that is,
1804              if already_moved[REGNO] is nonzero.  */
1805
1806           /* An insn is desirable to move if the new lifetime of the
1807              register is no more than THRESHOLD times the old lifetime.
1808              If it's not desirable, it means the loop is so big
1809              that moving won't speed things up much,
1810              and it is liable to make register usage worse.  */
1811
1812           /* It is also desirable to move if it can be moved at no
1813              extra cost because something else was already moved.  */
1814
1815           if (already_moved[regno]
1816               || flag_move_all_movables
1817               || (threshold * savings * m->lifetime) >=
1818                  (moved_once[regno] ? insn_count * 2 : insn_count)
1819               || (m->forces && m->forces->done
1820                   && VARRAY_INT (n_times_set, m->forces->regno) == 1))
1821             {
1822               int count;
1823               register struct movable *m1;
1824               rtx first = NULL_RTX;
1825
1826               /* Now move the insns that set the reg.  */
1827
1828               if (m->partial && m->match)
1829                 {
1830                   rtx newpat, i1;
1831                   rtx r1, r2;
1832                   /* Find the end of this chain of matching regs.
1833                      Thus, we load each reg in the chain from that one reg.
1834                      And that reg is loaded with 0 directly,
1835                      since it has ->match == 0.  */
1836                   for (m1 = m; m1->match; m1 = m1->match);
1837                   newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1838                                           SET_DEST (PATTERN (m1->insn)));
1839                   i1 = emit_insn_before (newpat, loop_start);
1840
1841                   /* Mark the moved, invariant reg as being allowed to
1842                      share a hard reg with the other matching invariant.  */
1843                   REG_NOTES (i1) = REG_NOTES (m->insn);
1844                   r1 = SET_DEST (PATTERN (m->insn));
1845                   r2 = SET_DEST (PATTERN (m1->insn));
1846                   regs_may_share
1847                     = gen_rtx_EXPR_LIST (VOIDmode, r1,
1848                                          gen_rtx_EXPR_LIST (VOIDmode, r2,
1849                                                             regs_may_share));
1850                   delete_insn (m->insn);
1851
1852                   if (new_start == 0)
1853                     new_start = i1;
1854
1855                   if (loop_dump_stream)
1856                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1857                 }
1858               /* If we are to re-generate the item being moved with a
1859                  new move insn, first delete what we have and then emit
1860                  the move insn before the loop.  */
1861               else if (m->move_insn)
1862                 {
1863                   rtx i1, temp;
1864
1865                   for (count = m->consec; count >= 0; count--)
1866                     {
1867                       /* If this is the first insn of a library call sequence,
1868                          skip to the end.  */
1869                       if (GET_CODE (p) != NOTE
1870                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1871                         p = XEXP (temp, 0);
1872
1873                       /* If this is the last insn of a libcall sequence, then
1874                          delete every insn in the sequence except the last.
1875                          The last insn is handled in the normal manner.  */
1876                       if (GET_CODE (p) != NOTE
1877                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1878                         {
1879                           temp = XEXP (temp, 0);
1880                           while (temp != p)
1881                             temp = delete_insn (temp);
1882                         }
1883
1884                       temp = p;
1885                       p = delete_insn (p);
1886
1887                       /* simplify_giv_expr expects that it can walk the insns
1888                          at m->insn forwards and see this old sequence we are
1889                          tossing here.  delete_insn does preserve the next
1890                          pointers, but when we skip over a NOTE we must fix
1891                          it up.  Otherwise that code walks into the non-deleted
1892                          insn stream.  */
1893                       while (p && GET_CODE (p) == NOTE)
1894                         p = NEXT_INSN (temp) = NEXT_INSN (p);
1895                     }
1896
1897                   start_sequence ();
1898                   emit_move_insn (m->set_dest, m->set_src);
1899                   temp = get_insns ();
1900                   end_sequence ();
1901
1902                   add_label_notes (m->set_src, temp);
1903
1904                   i1 = emit_insns_before (temp, loop_start);
1905                   if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
1906                     REG_NOTES (i1)
1907                       = gen_rtx_EXPR_LIST (m->is_equiv ? REG_EQUIV : REG_EQUAL,
1908                                            m->set_src, REG_NOTES (i1));
1909
1910                   if (loop_dump_stream)
1911                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1912
1913                   /* The more regs we move, the less we like moving them.  */
1914                   threshold -= 3;
1915                 }
1916               else
1917                 {
1918                   for (count = m->consec; count >= 0; count--)
1919                     {
1920                       rtx i1, temp;
1921
1922                       /* If first insn of libcall sequence, skip to end.  */
1923                       /* Do this at start of loop, since p is guaranteed to 
1924                          be an insn here.  */
1925                       if (GET_CODE (p) != NOTE
1926                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1927                         p = XEXP (temp, 0);
1928
1929                       /* If last insn of libcall sequence, move all
1930                          insns except the last before the loop.  The last
1931                          insn is handled in the normal manner.  */
1932                       if (GET_CODE (p) != NOTE
1933                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1934                         {
1935                           rtx fn_address = 0;
1936                           rtx fn_reg = 0;
1937                           rtx fn_address_insn = 0;
1938
1939                           first = 0;
1940                           for (temp = XEXP (temp, 0); temp != p;
1941                                temp = NEXT_INSN (temp))
1942                             {
1943                               rtx body;
1944                               rtx n;
1945                               rtx next;
1946
1947                               if (GET_CODE (temp) == NOTE)
1948                                 continue;
1949
1950                               body = PATTERN (temp);
1951
1952                               /* Find the next insn after TEMP,
1953                                  not counting USE or NOTE insns.  */
1954                               for (next = NEXT_INSN (temp); next != p;
1955                                    next = NEXT_INSN (next))
1956                                 if (! (GET_CODE (next) == INSN
1957                                        && GET_CODE (PATTERN (next)) == USE)
1958                                     && GET_CODE (next) != NOTE)
1959                                   break;
1960                               
1961                               /* If that is the call, this may be the insn
1962                                  that loads the function address.
1963
1964                                  Extract the function address from the insn
1965                                  that loads it into a register.
1966                                  If this insn was cse'd, we get incorrect code.
1967
1968                                  So emit a new move insn that copies the
1969                                  function address into the register that the
1970                                  call insn will use.  flow.c will delete any
1971                                  redundant stores that we have created.  */
1972                               if (GET_CODE (next) == CALL_INSN
1973                                   && GET_CODE (body) == SET
1974                                   && GET_CODE (SET_DEST (body)) == REG
1975                                   && (n = find_reg_note (temp, REG_EQUAL,
1976                                                          NULL_RTX)))
1977                                 {
1978                                   fn_reg = SET_SRC (body);
1979                                   if (GET_CODE (fn_reg) != REG)
1980                                     fn_reg = SET_DEST (body);
1981                                   fn_address = XEXP (n, 0);
1982                                   fn_address_insn = temp;
1983                                 }
1984                               /* We have the call insn.
1985                                  If it uses the register we suspect it might,
1986                                  load it with the correct address directly.  */
1987                               if (GET_CODE (temp) == CALL_INSN
1988                                   && fn_address != 0
1989                                   && reg_referenced_p (fn_reg, body))
1990                                 emit_insn_after (gen_move_insn (fn_reg,
1991                                                                 fn_address),
1992                                                  fn_address_insn);
1993
1994                               if (GET_CODE (temp) == CALL_INSN)
1995                                 {
1996                                   i1 = emit_call_insn_before (body, loop_start);
1997                                   /* Because the USAGE information potentially
1998                                      contains objects other than hard registers
1999                                      we need to copy it.  */
2000                                   if (CALL_INSN_FUNCTION_USAGE (temp))
2001                                     CALL_INSN_FUNCTION_USAGE (i1)
2002                                       = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
2003                                 }
2004                               else
2005                                 i1 = emit_insn_before (body, loop_start);
2006                               if (first == 0)
2007                                 first = i1;
2008                               if (temp == fn_address_insn)
2009                                 fn_address_insn = i1;
2010                               REG_NOTES (i1) = REG_NOTES (temp);
2011                               delete_insn (temp);
2012                             }
2013                           if (new_start == 0)
2014                             new_start = first;
2015                         }
2016                       if (m->savemode != VOIDmode)
2017                         {
2018                           /* P sets REG to zero; but we should clear only
2019                              the bits that are not covered by the mode
2020                              m->savemode.  */
2021                           rtx reg = m->set_dest;
2022                           rtx sequence;
2023                           rtx tem;
2024                       
2025                           start_sequence ();
2026                           tem = expand_binop
2027                             (GET_MODE (reg), and_optab, reg,
2028                              GEN_INT ((((HOST_WIDE_INT) 1
2029                                         << GET_MODE_BITSIZE (m->savemode)))
2030                                       - 1),
2031                              reg, 1, OPTAB_LIB_WIDEN);
2032                           if (tem == 0)
2033                             abort ();
2034                           if (tem != reg)
2035                             emit_move_insn (reg, tem);
2036                           sequence = gen_sequence ();
2037                           end_sequence ();
2038                           i1 = emit_insn_before (sequence, loop_start);
2039                         }
2040                       else if (GET_CODE (p) == CALL_INSN)
2041                         {
2042                           i1 = emit_call_insn_before (PATTERN (p), loop_start);
2043                           /* Because the USAGE information potentially
2044                              contains objects other than hard registers
2045                              we need to copy it.  */
2046                           if (CALL_INSN_FUNCTION_USAGE (p))
2047                             CALL_INSN_FUNCTION_USAGE (i1)
2048                               = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2049                         }
2050                       else if (count == m->consec && m->move_insn_first)
2051                         {
2052                           /* The SET_SRC might not be invariant, so we must
2053                              use the REG_EQUAL note.  */
2054                           start_sequence ();
2055                           emit_move_insn (m->set_dest, m->set_src);
2056                           temp = get_insns ();
2057                           end_sequence ();
2058
2059                           add_label_notes (m->set_src, temp);
2060
2061                           i1 = emit_insns_before (temp, loop_start);
2062                           if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2063                             REG_NOTES (i1)
2064                               = gen_rtx_EXPR_LIST ((m->is_equiv ? REG_EQUIV
2065                                                     : REG_EQUAL),
2066                                                    m->set_src, REG_NOTES (i1));
2067                         }
2068                       else
2069                         i1 = emit_insn_before (PATTERN (p), loop_start);
2070
2071                       if (REG_NOTES (i1) == 0)
2072                         {
2073                           REG_NOTES (i1) = REG_NOTES (p);
2074
2075                           /* If there is a REG_EQUAL note present whose value
2076                              is not loop invariant, then delete it, since it
2077                              may cause problems with later optimization passes.
2078                              It is possible for cse to create such notes
2079                              like this as a result of record_jump_cond.  */
2080                       
2081                           if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2082                               && ! loop_invariant_p (loop, XEXP (temp, 0)))
2083                             remove_note (i1, temp);
2084                         }
2085
2086                       if (new_start == 0)
2087                         new_start = i1;
2088
2089                       if (loop_dump_stream)
2090                         fprintf (loop_dump_stream, " moved to %d",
2091                                  INSN_UID (i1));
2092
2093                       /* If library call, now fix the REG_NOTES that contain
2094                          insn pointers, namely REG_LIBCALL on FIRST
2095                          and REG_RETVAL on I1.  */
2096                       if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2097                         {
2098                           XEXP (temp, 0) = first;
2099                           temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2100                           XEXP (temp, 0) = i1;
2101                         }
2102
2103                       temp = p;
2104                       delete_insn (p);
2105                       p = NEXT_INSN (p);
2106
2107                       /* simplify_giv_expr expects that it can walk the insns
2108                          at m->insn forwards and see this old sequence we are
2109                          tossing here.  delete_insn does preserve the next
2110                          pointers, but when we skip over a NOTE we must fix
2111                          it up.  Otherwise that code walks into the non-deleted
2112                          insn stream.  */
2113                       while (p && GET_CODE (p) == NOTE)
2114                         p = NEXT_INSN (temp) = NEXT_INSN (p);
2115                     }
2116
2117                   /* The more regs we move, the less we like moving them.  */
2118                   threshold -= 3;
2119                 }
2120
2121               /* Any other movable that loads the same register
2122                  MUST be moved.  */
2123               already_moved[regno] = 1;
2124
2125               /* This reg has been moved out of one loop.  */
2126               moved_once[regno] = 1;
2127
2128               /* The reg set here is now invariant.  */
2129               if (! m->partial)
2130                 VARRAY_INT (set_in_loop, regno) = 0;
2131
2132               m->done = 1;
2133
2134               /* Change the length-of-life info for the register
2135                  to say it lives at least the full length of this loop.
2136                  This will help guide optimizations in outer loops.  */
2137
2138               if (uid_luid[REGNO_FIRST_UID (regno)] > INSN_LUID (loop_start))
2139                 /* This is the old insn before all the moved insns.
2140                    We can't use the moved insn because it is out of range
2141                    in uid_luid.  Only the old insns have luids.  */
2142                 REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2143               if (uid_luid[REGNO_LAST_UID (regno)] < INSN_LUID (loop_end))
2144                 REGNO_LAST_UID (regno) = INSN_UID (loop_end);
2145
2146               /* Combine with this moved insn any other matching movables.  */
2147
2148               if (! m->partial)
2149                 for (m1 = movables; m1; m1 = m1->next)
2150                   if (m1->match == m)
2151                     {
2152                       rtx temp;
2153
2154                       /* Schedule the reg loaded by M1
2155                          for replacement so that shares the reg of M.
2156                          If the modes differ (only possible in restricted
2157                          circumstances, make a SUBREG.
2158
2159                          Note this assumes that the target dependent files
2160                          treat REG and SUBREG equally, including within
2161                          GO_IF_LEGITIMATE_ADDRESS and in all the
2162                          predicates since we never verify that replacing the
2163                          original register with a SUBREG results in a
2164                          recognizable insn.  */
2165                       if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2166                         reg_map[m1->regno] = m->set_dest;
2167                       else
2168                         reg_map[m1->regno]
2169                           = gen_lowpart_common (GET_MODE (m1->set_dest),
2170                                                 m->set_dest);
2171                     
2172                       /* Get rid of the matching insn
2173                          and prevent further processing of it.  */
2174                       m1->done = 1;
2175
2176                       /* if library call, delete all insn except last, which
2177                          is deleted below */
2178                       if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2179                                                  NULL_RTX)))
2180                         {
2181                           for (temp = XEXP (temp, 0); temp != m1->insn;
2182                                temp = NEXT_INSN (temp))
2183                             delete_insn (temp);
2184                         }
2185                       delete_insn (m1->insn);
2186
2187                       /* Any other movable that loads the same register
2188                          MUST be moved.  */
2189                       already_moved[m1->regno] = 1;
2190
2191                       /* The reg merged here is now invariant,
2192                          if the reg it matches is invariant.  */
2193                       if (! m->partial)
2194                         VARRAY_INT (set_in_loop, m1->regno) = 0;
2195                     }
2196             }
2197           else if (loop_dump_stream)
2198             fprintf (loop_dump_stream, "not desirable");
2199         }
2200       else if (loop_dump_stream && !m->match)
2201         fprintf (loop_dump_stream, "not safe");
2202
2203       if (loop_dump_stream)
2204         fprintf (loop_dump_stream, "\n");
2205     }
2206
2207   if (new_start == 0)
2208     new_start = loop_start;
2209
2210   /* Go through all the instructions in the loop, making
2211      all the register substitutions scheduled in REG_MAP.  */
2212   for (p = new_start; p != loop_end; p = NEXT_INSN (p))
2213     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
2214         || GET_CODE (p) == CALL_INSN)
2215       {
2216         replace_regs (PATTERN (p), reg_map, nregs, 0);
2217         replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2218         INSN_CODE (p) = -1;
2219       }
2220
2221   /* Clean up.  */
2222   free (reg_map);
2223   free (already_moved);
2224 }
2225 \f
2226 #if 0
2227 /* Scan X and replace the address of any MEM in it with ADDR.
2228    REG is the address that MEM should have before the replacement.  */
2229
2230 static void
2231 replace_call_address (x, reg, addr)
2232      rtx x, reg, addr;
2233 {
2234   register enum rtx_code code;
2235   register int i;
2236   register const char *fmt;
2237
2238   if (x == 0)
2239     return;
2240   code = GET_CODE (x);
2241   switch (code)
2242     {
2243     case PC:
2244     case CC0:
2245     case CONST_INT:
2246     case CONST_DOUBLE:
2247     case CONST:
2248     case SYMBOL_REF:
2249     case LABEL_REF:
2250     case REG:
2251       return;
2252
2253     case SET:
2254       /* Short cut for very common case.  */
2255       replace_call_address (XEXP (x, 1), reg, addr);
2256       return;
2257
2258     case CALL:
2259       /* Short cut for very common case.  */
2260       replace_call_address (XEXP (x, 0), reg, addr);
2261       return;
2262
2263     case MEM:
2264       /* If this MEM uses a reg other than the one we expected,
2265          something is wrong.  */
2266       if (XEXP (x, 0) != reg)
2267         abort ();
2268       XEXP (x, 0) = addr;
2269       return;
2270       
2271     default:
2272       break;
2273     }
2274
2275   fmt = GET_RTX_FORMAT (code);
2276   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2277     {
2278       if (fmt[i] == 'e')
2279         replace_call_address (XEXP (x, i), reg, addr);
2280       else if (fmt[i] == 'E')
2281         {
2282           register int j;
2283           for (j = 0; j < XVECLEN (x, i); j++)
2284             replace_call_address (XVECEXP (x, i, j), reg, addr);
2285         }
2286     }
2287 }
2288 #endif
2289 \f
2290 /* Return the number of memory refs to addresses that vary
2291    in the rtx X.  */
2292
2293 static int
2294 count_nonfixed_reads (loop, x)
2295      const struct loop *loop;
2296      rtx x;
2297 {
2298   register enum rtx_code code;
2299   register int i;
2300   register const char *fmt;
2301   int value;
2302
2303   if (x == 0)
2304     return 0;
2305
2306   code = GET_CODE (x);
2307   switch (code)
2308     {
2309     case PC:
2310     case CC0:
2311     case CONST_INT:
2312     case CONST_DOUBLE:
2313     case CONST:
2314     case SYMBOL_REF:
2315     case LABEL_REF:
2316     case REG:
2317       return 0;
2318
2319     case MEM:
2320       return ((loop_invariant_p (loop, XEXP (x, 0)) != 1)
2321               + count_nonfixed_reads (loop, XEXP (x, 0)));
2322       
2323     default:
2324       break;
2325     }
2326
2327   value = 0;
2328   fmt = GET_RTX_FORMAT (code);
2329   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2330     {
2331       if (fmt[i] == 'e')
2332         value += count_nonfixed_reads (loop, XEXP (x, i));
2333       if (fmt[i] == 'E')
2334         {
2335           register int j;
2336           for (j = 0; j < XVECLEN (x, i); j++)
2337             value += count_nonfixed_reads (loop, XVECEXP (x, i, j));
2338         }
2339     }
2340   return value;
2341 }
2342
2343 \f
2344 #if 0
2345 /* P is an instruction that sets a register to the result of a ZERO_EXTEND.
2346    Replace it with an instruction to load just the low bytes
2347    if the machine supports such an instruction,
2348    and insert above LOOP_START an instruction to clear the register.  */
2349
2350 static void
2351 constant_high_bytes (p, loop_start)
2352      rtx p, loop_start;
2353 {
2354   register rtx new;
2355   register int insn_code_number;
2356
2357   /* Try to change (SET (REG ...) (ZERO_EXTEND (..:B ...)))
2358      to (SET (STRICT_LOW_PART (SUBREG:B (REG...))) ...).  */
2359
2360   new
2361     = gen_rtx_SET
2362       (VOIDmode,
2363        gen_rtx_STRICT_LOW_PART
2364        (VOIDmode,
2365         gen_rtx_SUBREG (GET_MODE (XEXP (SET_SRC (PATTERN (p)), 0)),
2366                         SET_DEST (PATTERN (p)), 0)),
2367        XEXP (SET_SRC (PATTERN (p)), 0));
2368
2369   insn_code_number = recog (new, p);
2370
2371   if (insn_code_number)
2372     {
2373       register int i;
2374
2375       /* Clear destination register before the loop.  */
2376       emit_insn_before (gen_rtx_SET (VOIDmode,
2377                                      SET_DEST (PATTERN (p)), const0_rtx),
2378                         loop_start);
2379
2380       /* Inside the loop, just load the low part.  */
2381       PATTERN (p) = new;
2382     }
2383 }
2384 #endif
2385 \f
2386 /* Scan a loop setting the elements `cont', `vtop', `loops_enclosed',
2387    `has_call', `has_volatile', and `has_tablejump' within LOOP.
2388    Set the global variables `unknown_address_altered',
2389    `unknown_constant_address_altered', and `num_mem_sets'.  Also, fill
2390    in the array `loop_mems' and the list `loop_store_mems'.  */
2391
2392 static void
2393 prescan_loop (loop)
2394      struct loop *loop;
2395 {
2396   register int level = 1;
2397   rtx insn;
2398   struct loop_info *loop_info = LOOP_INFO (loop);
2399   rtx start = loop->start;
2400   rtx end = loop->end;
2401   /* The label after END.  Jumping here is just like falling off the
2402      end of the loop.  We use next_nonnote_insn instead of next_label
2403      as a hedge against the (pathological) case where some actual insn
2404      might end up between the two.  */
2405   rtx exit_target = next_nonnote_insn (end);
2406
2407   loop_info->has_indirect_jump = indirect_jump_in_function;
2408   loop_info->has_call = 0;
2409   loop_info->has_volatile = 0;
2410   loop_info->has_tablejump = 0;
2411   loop_info->has_multiple_exit_targets = 0;
2412   loop->cont = 0;
2413   loop->vtop = 0;
2414   loop->level = 1;
2415
2416   unknown_address_altered = 0;
2417   unknown_constant_address_altered = 0;
2418   loop_store_mems = NULL_RTX;
2419   first_loop_store_insn = NULL_RTX;
2420   loop_mems_idx = 0;
2421   num_mem_sets = 0;
2422
2423   for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2424        insn = NEXT_INSN (insn))
2425     {
2426       if (GET_CODE (insn) == NOTE)
2427         {
2428           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2429             {
2430               ++level;
2431               /* Count number of loops contained in this one.  */
2432               loop->level++;
2433             }
2434           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2435             {
2436               --level;
2437               if (level == 0)
2438                 {
2439                   end = insn;
2440                   break;
2441                 }
2442             }
2443           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_CONT)
2444             {
2445               if (level == 1)
2446                 loop->cont = insn;
2447             }
2448           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_VTOP)
2449             {
2450               /* If there is a NOTE_INSN_LOOP_VTOP, then this is a for
2451                  or while style loop, with a loop exit test at the
2452                  start.  Thus, we can assume that the loop condition
2453                  was true when the loop was entered.  */
2454               if (level == 1)
2455                 loop->vtop = insn;
2456             }
2457         }
2458       else if (GET_CODE (insn) == CALL_INSN)
2459         {
2460           if (! CONST_CALL_P (insn))
2461             unknown_address_altered = 1;
2462           loop_info->has_call = 1;
2463         }
2464       else if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
2465         {
2466           rtx label1 = NULL_RTX;
2467           rtx label2 = NULL_RTX;
2468
2469           if (volatile_refs_p (PATTERN (insn)))
2470             loop_info->has_volatile = 1;
2471
2472           if (GET_CODE (insn) == JUMP_INSN
2473               && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2474                   || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2475             loop_info->has_tablejump = 1;
2476           
2477           note_stores (PATTERN (insn), note_addr_stored, NULL);
2478           if (! first_loop_store_insn && loop_store_mems)
2479             first_loop_store_insn = insn;
2480
2481           if (! loop_info->has_multiple_exit_targets
2482               && GET_CODE (insn) == JUMP_INSN
2483               && GET_CODE (PATTERN (insn)) == SET
2484               && SET_DEST (PATTERN (insn)) == pc_rtx)
2485             {
2486               if (GET_CODE (SET_SRC (PATTERN (insn))) == IF_THEN_ELSE)
2487                 {
2488                   label1 = XEXP (SET_SRC (PATTERN (insn)), 1);
2489                   label2 = XEXP (SET_SRC (PATTERN (insn)), 2);
2490                 }
2491               else
2492                 {
2493                   label1 = SET_SRC (PATTERN (insn));
2494                 }
2495
2496               do {
2497                 if (label1 && label1 != pc_rtx)
2498                   {
2499                     if (GET_CODE (label1) != LABEL_REF)
2500                       {
2501                         /* Something tricky.  */
2502                         loop_info->has_multiple_exit_targets = 1;
2503                         break;
2504                       }
2505                     else if (XEXP (label1, 0) != exit_target
2506                              && LABEL_OUTSIDE_LOOP_P (label1))
2507                       {
2508                         /* A jump outside the current loop.  */
2509                         loop_info->has_multiple_exit_targets = 1;
2510                         break;
2511                       }
2512                   }
2513
2514                 label1 = label2;
2515                 label2 = NULL_RTX;
2516               } while (label1);
2517             }
2518         }
2519       else if (GET_CODE (insn) == RETURN)
2520         loop_info->has_multiple_exit_targets = 1;
2521     }
2522
2523   /* Now, rescan the loop, setting up the LOOP_MEMS array.  */
2524   if (/* We can't tell what MEMs are aliased by what.  */
2525       ! unknown_address_altered 
2526       /* An exception thrown by a called function might land us
2527          anywhere.  */
2528       && ! loop_info->has_call
2529       /* We don't want loads for MEMs moved to a location before the
2530          one at which their stack memory becomes allocated.  (Note
2531          that this is not a problem for malloc, etc., since those
2532          require actual function calls.  */
2533       && ! current_function_calls_alloca
2534       /* There are ways to leave the loop other than falling off the
2535          end.  */
2536       && ! loop_info->has_multiple_exit_targets)
2537     for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2538          insn = NEXT_INSN (insn))
2539       for_each_rtx (&insn, insert_loop_mem, 0);
2540 }
2541 \f
2542 /* LOOP->CONT_DOMINATOR is now the last label between the loop start
2543    and the continue note that is a the destination of a (cond)jump after
2544    the continue note.  If there is any (cond)jump between the loop start
2545    and what we have so far as LOOP->CONT_DOMINATOR that has a
2546    target between LOOP->DOMINATOR and the continue note, move
2547    LOOP->CONT_DOMINATOR forward to that label; if a jump's
2548    destination cannot be determined, clear LOOP->CONT_DOMINATOR.  */
2549
2550 static void
2551 verify_dominator (loop)
2552      struct loop *loop;
2553 {
2554   rtx insn;
2555
2556   if (! loop->cont_dominator)
2557     /* This can happen for an empty loop, e.g. in
2558        gcc.c-torture/compile/920410-2.c  */
2559     return;
2560   if (loop->cont_dominator == const0_rtx)
2561     {
2562       loop->cont_dominator = 0;
2563       return;
2564     }
2565   for (insn = loop->start; insn != loop->cont_dominator;
2566        insn = NEXT_INSN (insn))
2567     {
2568       if (GET_CODE (insn) == JUMP_INSN
2569           && GET_CODE (PATTERN (insn)) != RETURN)
2570         {
2571           rtx label = JUMP_LABEL (insn);
2572           int label_luid;
2573
2574           /* If it is not a jump we can easily understand or for
2575              which we do not have jump target information in the JUMP_LABEL
2576              field (consider ADDR_VEC and ADDR_DIFF_VEC insns), then clear
2577              LOOP->CONT_DOMINATOR.  */
2578           if ((! condjump_p (insn)
2579                && ! condjump_in_parallel_p (insn))
2580               || label == NULL_RTX)
2581             {
2582               loop->cont_dominator = NULL_RTX;
2583               return;
2584             }
2585
2586           label_luid = INSN_LUID (label);
2587           if (label_luid < INSN_LUID (loop->cont)
2588               && (label_luid
2589                   > INSN_LUID (loop->cont)))
2590             loop->cont_dominator = label;
2591         }
2592     }
2593 }
2594
2595 /* Scan the function looking for loops.  Record the start and end of each loop.
2596    Also mark as invalid loops any loops that contain a setjmp or are branched
2597    to from outside the loop.  */
2598
2599 static void
2600 find_and_verify_loops (f, loops)
2601      rtx f;
2602      struct loops *loops;
2603 {
2604   rtx insn;
2605   rtx label;
2606   int num_loops;
2607   struct loop *current_loop;
2608   struct loop *next_loop;
2609   struct loop *loop;
2610
2611   num_loops = loops->num;
2612
2613   compute_luids (f, NULL_RTX, 0);
2614
2615   /* If there are jumps to undefined labels,
2616      treat them as jumps out of any/all loops.
2617      This also avoids writing past end of tables when there are no loops.  */
2618   uid_loop[0] = NULL;
2619
2620   /* Find boundaries of loops, mark which loops are contained within
2621      loops, and invalidate loops that have setjmp.  */
2622
2623   num_loops = 0;
2624   current_loop = NULL;
2625   for (insn = f; insn; insn = NEXT_INSN (insn))
2626     {
2627       if (GET_CODE (insn) == NOTE)
2628         switch (NOTE_LINE_NUMBER (insn))
2629           {
2630           case NOTE_INSN_LOOP_BEG:
2631             next_loop = loops->array + num_loops;
2632             next_loop->num = num_loops;
2633             num_loops++;
2634             next_loop->start = insn;
2635             next_loop->outer = current_loop;
2636             current_loop = next_loop;
2637             break;
2638
2639           case NOTE_INSN_SETJMP:
2640             /* In this case, we must invalidate our current loop and any
2641                enclosing loop.  */
2642             for (loop = current_loop; loop; loop = loop->outer)
2643               {
2644                 loop->invalid = 1;
2645                 if (loop_dump_stream)
2646                   fprintf (loop_dump_stream,
2647                            "\nLoop at %d ignored due to setjmp.\n",
2648                            INSN_UID (loop->start));
2649               }
2650             break;
2651
2652           case NOTE_INSN_LOOP_CONT:
2653             current_loop->cont = insn;
2654             break;
2655           case NOTE_INSN_LOOP_END:
2656             if (! current_loop)
2657               abort ();
2658
2659             current_loop->end = insn;
2660             verify_dominator (current_loop);
2661             current_loop = current_loop->outer;
2662             break;
2663
2664           default:
2665             break;
2666           }
2667       /* If for any loop, this is a jump insn between the NOTE_INSN_LOOP_CONT
2668          and NOTE_INSN_LOOP_END notes, update loop->dominator.  */
2669       else if (GET_CODE (insn) == JUMP_INSN
2670                && GET_CODE (PATTERN (insn)) != RETURN
2671                && current_loop)
2672         {
2673           rtx label = JUMP_LABEL (insn);
2674
2675           if (! condjump_p (insn) && ! condjump_in_parallel_p (insn))
2676             label = NULL_RTX;
2677
2678           loop = current_loop;
2679           do
2680             {
2681               /* First see if we care about this loop.  */
2682               if (loop->cont && loop->cont_dominator != const0_rtx)
2683                 {
2684                   /* If the jump destination is not known, invalidate
2685                      loop->const_dominator.  */
2686                   if (! label)
2687                     loop->cont_dominator = const0_rtx;
2688                   else
2689                     /* Check if the destination is between loop start and
2690                        cont.  */
2691                     if ((INSN_LUID (label)
2692                          < INSN_LUID (loop->cont))
2693                         && (INSN_LUID (label)
2694                             > INSN_LUID (loop->start))
2695                         /* And if there is no later destination already
2696                            recorded.  */
2697                         && (! loop->cont_dominator
2698                             || (INSN_LUID (label)
2699                                 > INSN_LUID (loop->cont_dominator))))
2700                       loop->cont_dominator = label;
2701                 }
2702               loop = loop->outer;
2703             }
2704           while (loop);
2705         }
2706
2707       /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2708          enclosing loop, but this doesn't matter.  */
2709       uid_loop[INSN_UID (insn)] = current_loop;
2710     }
2711
2712   /* Any loop containing a label used in an initializer must be invalidated,
2713      because it can be jumped into from anywhere.  */
2714
2715   for (label = forced_labels; label; label = XEXP (label, 1))
2716     {
2717       for (loop = uid_loop[INSN_UID (XEXP (label, 0))];
2718            loop; loop = loop->outer)
2719         loop->invalid = 1;
2720     }
2721
2722   /* Any loop containing a label used for an exception handler must be
2723      invalidated, because it can be jumped into from anywhere.  */
2724
2725   for (label = exception_handler_labels; label; label = XEXP (label, 1))
2726     {
2727       for (loop = uid_loop[INSN_UID (XEXP (label, 0))];
2728            loop; loop = loop->outer)
2729         loop->invalid = 1;
2730     }
2731
2732   /* Now scan all insn's in the function.  If any JUMP_INSN branches into a
2733      loop that it is not contained within, that loop is marked invalid.
2734      If any INSN or CALL_INSN uses a label's address, then the loop containing
2735      that label is marked invalid, because it could be jumped into from
2736      anywhere.
2737
2738      Also look for blocks of code ending in an unconditional branch that
2739      exits the loop.  If such a block is surrounded by a conditional 
2740      branch around the block, move the block elsewhere (see below) and
2741      invert the jump to point to the code block.  This may eliminate a
2742      label in our loop and will simplify processing by both us and a
2743      possible second cse pass.  */
2744
2745   for (insn = f; insn; insn = NEXT_INSN (insn))
2746     if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
2747       {
2748         struct loop *this_loop = uid_loop[INSN_UID (insn)];
2749
2750         if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2751           {
2752             rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2753             if (note)
2754               {
2755                 for (loop = uid_loop[INSN_UID (XEXP (note, 0))];
2756                      loop; loop = loop->outer)
2757                   loop->invalid = 1;
2758               }
2759           }
2760
2761         if (GET_CODE (insn) != JUMP_INSN)
2762           continue;
2763
2764         mark_loop_jump (PATTERN (insn), this_loop);
2765
2766         /* See if this is an unconditional branch outside the loop.  */
2767         if (this_loop
2768             && (GET_CODE (PATTERN (insn)) == RETURN
2769                 || (simplejump_p (insn)
2770                     && (uid_loop[INSN_UID (JUMP_LABEL (insn))]
2771                         != this_loop)))
2772             && get_max_uid () < max_uid_for_loop)
2773           {
2774             rtx p;
2775             rtx our_next = next_real_insn (insn);
2776             rtx last_insn_to_move = NEXT_INSN (insn);
2777             struct loop *dest_loop;
2778             struct loop *outer_loop = NULL;
2779
2780             /* Go backwards until we reach the start of the loop, a label,
2781                or a JUMP_INSN.  */
2782             for (p = PREV_INSN (insn);
2783                  GET_CODE (p) != CODE_LABEL
2784                  && ! (GET_CODE (p) == NOTE
2785                        && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2786                  && GET_CODE (p) != JUMP_INSN;
2787                  p = PREV_INSN (p))
2788               ;
2789
2790             /* Check for the case where we have a jump to an inner nested
2791                loop, and do not perform the optimization in that case.  */
2792
2793             if (JUMP_LABEL (insn))
2794               {
2795                 dest_loop = uid_loop[INSN_UID (JUMP_LABEL (insn))];
2796                 if (dest_loop)
2797                   {
2798                     for (outer_loop = dest_loop; outer_loop;
2799                          outer_loop = outer_loop->outer)
2800                       if (outer_loop == this_loop)
2801                         break;
2802                   }
2803               }
2804
2805             /* Make sure that the target of P is within the current loop.  */
2806
2807             if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2808                 && uid_loop[INSN_UID (JUMP_LABEL (p))] != this_loop)
2809               outer_loop = this_loop;
2810
2811             /* If we stopped on a JUMP_INSN to the next insn after INSN,
2812                we have a block of code to try to move.
2813
2814                We look backward and then forward from the target of INSN
2815                to find a BARRIER at the same loop depth as the target.
2816                If we find such a BARRIER, we make a new label for the start
2817                of the block, invert the jump in P and point it to that label,
2818                and move the block of code to the spot we found.  */
2819
2820             if (! outer_loop
2821                 && GET_CODE (p) == JUMP_INSN
2822                 && JUMP_LABEL (p) != 0
2823                 /* Just ignore jumps to labels that were never emitted.
2824                    These always indicate compilation errors.  */
2825                 && INSN_UID (JUMP_LABEL (p)) != 0
2826                 && condjump_p (p)
2827                 && ! simplejump_p (p)
2828                 && next_real_insn (JUMP_LABEL (p)) == our_next
2829                 /* If it's not safe to move the sequence, then we
2830                    mustn't try.  */
2831                 && insns_safe_to_move_p (p, NEXT_INSN (insn), 
2832                                          &last_insn_to_move))
2833               {
2834                 rtx target
2835                   = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2836                 struct loop *target_loop = uid_loop[INSN_UID (target)];
2837                 rtx loc, loc2;
2838
2839                 for (loc = target; loc; loc = PREV_INSN (loc))
2840                   if (GET_CODE (loc) == BARRIER
2841                       /* Don't move things inside a tablejump.  */
2842                       && ((loc2 = next_nonnote_insn (loc)) == 0
2843                           || GET_CODE (loc2) != CODE_LABEL
2844                           || (loc2 = next_nonnote_insn (loc2)) == 0
2845                           || GET_CODE (loc2) != JUMP_INSN
2846                           || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2847                               && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2848                       && uid_loop[INSN_UID (loc)] == target_loop)
2849                     break;
2850
2851                 if (loc == 0)
2852                   for (loc = target; loc; loc = NEXT_INSN (loc))
2853                     if (GET_CODE (loc) == BARRIER
2854                         /* Don't move things inside a tablejump.  */
2855                         && ((loc2 = next_nonnote_insn (loc)) == 0
2856                             || GET_CODE (loc2) != CODE_LABEL
2857                             || (loc2 = next_nonnote_insn (loc2)) == 0
2858                             || GET_CODE (loc2) != JUMP_INSN
2859                             || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2860                                 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2861                         && uid_loop[INSN_UID (loc)] == target_loop)
2862                       break;
2863
2864                 if (loc)
2865                   {
2866                     rtx cond_label = JUMP_LABEL (p);
2867                     rtx new_label = get_label_after (p);
2868
2869                     /* Ensure our label doesn't go away.  */
2870                     LABEL_NUSES (cond_label)++;
2871
2872                     /* Verify that uid_loop is large enough and that
2873                        we can invert P.  */
2874                    if (invert_jump (p, new_label))
2875                      {
2876                        rtx q, r;
2877
2878                        /* If no suitable BARRIER was found, create a suitable
2879                           one before TARGET.  Since TARGET is a fall through
2880                           path, we'll need to insert an jump around our block
2881                           and a add a BARRIER before TARGET.
2882
2883                           This creates an extra unconditional jump outside
2884                           the loop.  However, the benefits of removing rarely
2885                           executed instructions from inside the loop usually
2886                           outweighs the cost of the extra unconditional jump
2887                           outside the loop.  */
2888                        if (loc == 0)
2889                          {
2890                            rtx temp;
2891
2892                            temp = gen_jump (JUMP_LABEL (insn));
2893                            temp = emit_jump_insn_before (temp, target);
2894                            JUMP_LABEL (temp) = JUMP_LABEL (insn);
2895                            LABEL_NUSES (JUMP_LABEL (insn))++;
2896                            loc = emit_barrier_before (target);
2897                          }
2898
2899                        /* Include the BARRIER after INSN and copy the
2900                           block after LOC.  */
2901                        new_label = squeeze_notes (new_label, 
2902                                                   last_insn_to_move);
2903                        reorder_insns (new_label, last_insn_to_move, loc);
2904
2905                        /* All those insns are now in TARGET_LOOP.  */
2906                        for (q = new_label; 
2907                             q != NEXT_INSN (last_insn_to_move);
2908                             q = NEXT_INSN (q))
2909                          uid_loop[INSN_UID (q)] = target_loop;
2910
2911                        /* The label jumped to by INSN is no longer a loop exit.
2912                           Unless INSN does not have a label (e.g., it is a
2913                           RETURN insn), search loop->exit_labels to find
2914                           its label_ref, and remove it.  Also turn off
2915                           LABEL_OUTSIDE_LOOP_P bit.  */
2916                        if (JUMP_LABEL (insn))
2917                          {
2918                            for (q = 0,
2919                                 r = this_loop->exit_labels;
2920                                 r; q = r, r = LABEL_NEXTREF (r))
2921                              if (XEXP (r, 0) == JUMP_LABEL (insn))
2922                                {
2923                                  LABEL_OUTSIDE_LOOP_P (r) = 0;
2924                                  if (q)
2925                                    LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2926                                  else
2927                                    this_loop->exit_labels = LABEL_NEXTREF (r);
2928                                  break;
2929                                }
2930
2931                            for (loop = this_loop; loop && loop != target_loop;
2932                                 loop = loop->outer)
2933                              loop->exit_count--;
2934
2935                            /* If we didn't find it, then something is
2936                               wrong.  */
2937                            if (! r)
2938                              abort ();
2939                          }
2940
2941                        /* P is now a jump outside the loop, so it must be put
2942                           in loop->exit_labels, and marked as such.
2943                           The easiest way to do this is to just call
2944                           mark_loop_jump again for P.  */
2945                        mark_loop_jump (PATTERN (p), this_loop);
2946
2947                        /* If INSN now jumps to the insn after it,
2948                           delete INSN.  */
2949                        if (JUMP_LABEL (insn) != 0
2950                            && (next_real_insn (JUMP_LABEL (insn))
2951                                == next_real_insn (insn)))
2952                          delete_insn (insn);
2953                      }
2954
2955                     /* Continue the loop after where the conditional
2956                        branch used to jump, since the only branch insn
2957                        in the block (if it still remains) is an inter-loop
2958                        branch and hence needs no processing.  */
2959                     insn = NEXT_INSN (cond_label);
2960
2961                     if (--LABEL_NUSES (cond_label) == 0)
2962                       delete_insn (cond_label);
2963
2964                     /* This loop will be continued with NEXT_INSN (insn).  */
2965                     insn = PREV_INSN (insn);
2966                   }
2967               }
2968           }
2969       }
2970 }
2971
2972 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
2973    loops it is contained in, mark the target loop invalid.
2974
2975    For speed, we assume that X is part of a pattern of a JUMP_INSN.  */
2976
2977 static void
2978 mark_loop_jump (x, loop)
2979      rtx x;
2980      struct loop *loop;
2981 {
2982   struct loop *dest_loop;
2983   struct loop *outer_loop;
2984   int i;
2985
2986   switch (GET_CODE (x))
2987     {
2988     case PC:
2989     case USE:
2990     case CLOBBER:
2991     case REG:
2992     case MEM:
2993     case CONST_INT:
2994     case CONST_DOUBLE:
2995     case RETURN:
2996       return;
2997
2998     case CONST:
2999       /* There could be a label reference in here.  */
3000       mark_loop_jump (XEXP (x, 0), loop);
3001       return;
3002
3003     case PLUS:
3004     case MINUS:
3005     case MULT:
3006       mark_loop_jump (XEXP (x, 0), loop);
3007       mark_loop_jump (XEXP (x, 1), loop);
3008       return;
3009
3010     case LO_SUM:
3011       /* This may refer to a LABEL_REF or SYMBOL_REF.  */
3012       mark_loop_jump (XEXP (x, 1), loop);
3013       return;
3014
3015     case SIGN_EXTEND:
3016     case ZERO_EXTEND:
3017       mark_loop_jump (XEXP (x, 0), loop);
3018       return;
3019
3020     case LABEL_REF:
3021       dest_loop = uid_loop[INSN_UID (XEXP (x, 0))];
3022
3023       /* Link together all labels that branch outside the loop.  This
3024          is used by final_[bg]iv_value and the loop unrolling code.  Also
3025          mark this LABEL_REF so we know that this branch should predict
3026          false.  */
3027
3028       /* A check to make sure the label is not in an inner nested loop,
3029          since this does not count as a loop exit.  */
3030       if (dest_loop)
3031         {
3032           for (outer_loop = dest_loop; outer_loop;
3033                outer_loop = outer_loop->outer)
3034             if (outer_loop == loop)
3035               break;
3036         }
3037       else
3038         outer_loop = NULL;
3039
3040       if (loop && ! outer_loop)
3041         {
3042           LABEL_OUTSIDE_LOOP_P (x) = 1;
3043           LABEL_NEXTREF (x) = loop->exit_labels;
3044           loop->exit_labels = x;
3045
3046           for (outer_loop = loop;
3047                outer_loop && outer_loop != dest_loop;
3048                outer_loop = outer_loop->outer)
3049             outer_loop->exit_count++;
3050         }
3051
3052       /* If this is inside a loop, but not in the current loop or one enclosed
3053          by it, it invalidates at least one loop.  */
3054
3055       if (! dest_loop)
3056         return;
3057
3058       /* We must invalidate every nested loop containing the target of this
3059          label, except those that also contain the jump insn.  */
3060
3061       for (; dest_loop; dest_loop = dest_loop->outer)
3062         {
3063           /* Stop when we reach a loop that also contains the jump insn.  */
3064           for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3065             if (dest_loop == outer_loop)
3066               return;
3067
3068           /* If we get here, we know we need to invalidate a loop.  */
3069           if (loop_dump_stream && ! dest_loop->invalid)
3070             fprintf (loop_dump_stream,
3071                      "\nLoop at %d ignored due to multiple entry points.\n",
3072                      INSN_UID (dest_loop->start));
3073           
3074           dest_loop->invalid = 1;
3075         }
3076       return;
3077
3078     case SET:
3079       /* If this is not setting pc, ignore.  */
3080       if (SET_DEST (x) == pc_rtx)
3081         mark_loop_jump (SET_SRC (x), loop);
3082       return;
3083
3084     case IF_THEN_ELSE:
3085       mark_loop_jump (XEXP (x, 1), loop);
3086       mark_loop_jump (XEXP (x, 2), loop);
3087       return;
3088
3089     case PARALLEL:
3090     case ADDR_VEC:
3091       for (i = 0; i < XVECLEN (x, 0); i++)
3092         mark_loop_jump (XVECEXP (x, 0, i), loop);
3093       return;
3094
3095     case ADDR_DIFF_VEC:
3096       for (i = 0; i < XVECLEN (x, 1); i++)
3097         mark_loop_jump (XVECEXP (x, 1, i), loop);
3098       return;
3099
3100     default:
3101       /* Strictly speaking this is not a jump into the loop, only a possible
3102          jump out of the loop.  However, we have no way to link the destination
3103          of this jump onto the list of exit labels.  To be safe we mark this
3104          loop and any containing loops as invalid.  */
3105       if (loop)
3106         {
3107           for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3108             {
3109               if (loop_dump_stream && ! outer_loop->invalid)
3110                 fprintf (loop_dump_stream,
3111                          "\nLoop at %d ignored due to unknown exit jump.\n",
3112                          INSN_UID (outer_loop->start));
3113               outer_loop->invalid = 1;
3114             }
3115         }
3116       return;
3117     }
3118 }
3119 \f
3120 /* Return nonzero if there is a label in the range from
3121    insn INSN to and including the insn whose luid is END
3122    INSN must have an assigned luid (i.e., it must not have
3123    been previously created by loop.c).  */
3124
3125 static int
3126 labels_in_range_p (insn, end)
3127      rtx insn;
3128      int end;
3129 {
3130   while (insn && INSN_LUID (insn) <= end)
3131     {
3132       if (GET_CODE (insn) == CODE_LABEL)
3133         return 1;
3134       insn = NEXT_INSN (insn);
3135     }
3136
3137   return 0;
3138 }
3139
3140 /* Record that a memory reference X is being set.  */
3141
3142 static void
3143 note_addr_stored (x, y, data)
3144      rtx x;
3145      rtx y ATTRIBUTE_UNUSED;
3146      void *data ATTRIBUTE_UNUSED;
3147 {
3148   if (x == 0 || GET_CODE (x) != MEM)
3149     return;
3150
3151   /* Count number of memory writes.
3152      This affects heuristics in strength_reduce.  */
3153   num_mem_sets++;
3154
3155   /* BLKmode MEM means all memory is clobbered.  */
3156     if (GET_MODE (x) == BLKmode)
3157     {
3158       if (RTX_UNCHANGING_P (x))
3159         unknown_constant_address_altered = 1;
3160       else
3161         unknown_address_altered = 1;
3162
3163       return;
3164     }
3165
3166   loop_store_mems = gen_rtx_EXPR_LIST (VOIDmode, x, loop_store_mems);
3167 }
3168
3169 /* X is a value modified by an INSN that references a biv inside a loop
3170    exit test (ie, X is somehow related to the value of the biv).  If X
3171    is a pseudo that is used more than once, then the biv is (effectively)
3172    used more than once.  DATA is really an `int *', and is set if the
3173    biv is used more than once.  */
3174
3175 static void
3176 note_set_pseudo_multiple_uses (x, y, data)
3177      rtx x;
3178      rtx y ATTRIBUTE_UNUSED;
3179      void *data;
3180 {
3181   if (x == 0)
3182     return;
3183
3184   while (GET_CODE (x) == STRICT_LOW_PART
3185          || GET_CODE (x) == SIGN_EXTRACT
3186          || GET_CODE (x) == ZERO_EXTRACT
3187          || GET_CODE (x) == SUBREG)
3188     x = XEXP (x, 0);
3189
3190   if (GET_CODE (x) != REG || REGNO (x) < FIRST_PSEUDO_REGISTER)
3191     return;
3192
3193   /* If we do not have usage information, or if we know the register
3194      is used more than once, note that fact for check_dbra_loop.  */
3195   if (REGNO (x) >= max_reg_before_loop
3196       || ! VARRAY_RTX (reg_single_usage, REGNO (x))
3197       || VARRAY_RTX (reg_single_usage, REGNO (x)) == const0_rtx)
3198     *((int *) data) = 1;
3199 }
3200 \f
3201 /* Return nonzero if the rtx X is invariant over the current loop.
3202
3203    The value is 2 if we refer to something only conditionally invariant.
3204
3205    If `unknown_address_altered' is nonzero, no memory ref is invariant.
3206    Otherwise, a memory ref is invariant if it does not conflict with
3207    anything stored in `loop_store_mems'.  */
3208
3209 int
3210 loop_invariant_p (loop, x)
3211      const struct loop *loop;
3212      register rtx x;
3213 {
3214   register int i;
3215   register enum rtx_code code;
3216   register const char *fmt;
3217   int conditional = 0;
3218   rtx mem_list_entry;
3219
3220   if (x == 0)
3221     return 1;
3222   code = GET_CODE (x);
3223   switch (code)
3224     {
3225     case CONST_INT:
3226     case CONST_DOUBLE:
3227     case SYMBOL_REF:
3228     case CONST:
3229       return 1;
3230
3231     case LABEL_REF:
3232       /* A LABEL_REF is normally invariant, however, if we are unrolling
3233          loops, and this label is inside the loop, then it isn't invariant.
3234          This is because each unrolled copy of the loop body will have
3235          a copy of this label.  If this was invariant, then an insn loading
3236          the address of this label into a register might get moved outside
3237          the loop, and then each loop body would end up using the same label.
3238
3239          We don't know the loop bounds here though, so just fail for all
3240          labels.  */
3241       if (flag_unroll_loops)
3242         return 0;
3243       else
3244         return 1;
3245
3246     case PC:
3247     case CC0:
3248     case UNSPEC_VOLATILE:
3249       return 0;
3250
3251     case REG:
3252       /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3253          since the reg might be set by initialization within the loop.  */
3254
3255       if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3256            || x == arg_pointer_rtx)
3257           && ! current_function_has_nonlocal_goto)
3258         return 1;
3259
3260       if (LOOP_INFO (loop)->has_call
3261           && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3262         return 0;
3263
3264       if (VARRAY_INT (set_in_loop, REGNO (x)) < 0)
3265         return 2;
3266
3267       return VARRAY_INT (set_in_loop, REGNO (x)) == 0;
3268
3269     case MEM:
3270       /* Volatile memory references must be rejected.  Do this before
3271          checking for read-only items, so that volatile read-only items
3272          will be rejected also.  */
3273       if (MEM_VOLATILE_P (x))
3274         return 0;
3275
3276       /* If we had a subroutine call, any location in memory could
3277          have been clobbered.  We used to test here for volatile and
3278          readonly, but true_dependence knows how to do that better
3279          than we do. */
3280       if (RTX_UNCHANGING_P (x)
3281           ? unknown_constant_address_altered : unknown_address_altered)
3282         return 0;
3283
3284       /* See if there is any dependence between a store and this load.  */
3285       mem_list_entry = loop_store_mems;
3286       while (mem_list_entry)
3287         {
3288           if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3289                                x, rtx_varies_p))
3290             return 0;
3291
3292           mem_list_entry = XEXP (mem_list_entry, 1);
3293         }
3294
3295       /* It's not invalidated by a store in memory
3296          but we must still verify the address is invariant.  */
3297       break;
3298
3299     case ASM_OPERANDS:
3300       /* Don't mess with insns declared volatile.  */
3301       if (MEM_VOLATILE_P (x))
3302         return 0;
3303       break;
3304       
3305     default:
3306       break;
3307     }
3308
3309   fmt = GET_RTX_FORMAT (code);
3310   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3311     {
3312       if (fmt[i] == 'e')
3313         {
3314           int tem = loop_invariant_p (loop, XEXP (x, i));
3315           if (tem == 0)
3316             return 0;
3317           if (tem == 2)
3318             conditional = 1;
3319         }
3320       else if (fmt[i] == 'E')
3321         {
3322           register int j;
3323           for (j = 0; j < XVECLEN (x, i); j++)
3324             {
3325               int tem = loop_invariant_p (loop, XVECEXP (x, i, j));
3326               if (tem == 0)
3327                 return 0;
3328               if (tem == 2)
3329                 conditional = 1;
3330             }
3331
3332         }
3333     }
3334
3335   return 1 + conditional;
3336 }
3337
3338 \f
3339 /* Return nonzero if all the insns in the loop that set REG
3340    are INSN and the immediately following insns,
3341    and if each of those insns sets REG in an invariant way
3342    (not counting uses of REG in them).
3343
3344    The value is 2 if some of these insns are only conditionally invariant.
3345
3346    We assume that INSN itself is the first set of REG
3347    and that its source is invariant.  */
3348
3349 static int
3350 consec_sets_invariant_p (loop, reg, n_sets, insn)
3351      const struct loop *loop;
3352      int n_sets;
3353      rtx reg, insn;
3354 {
3355   register rtx p = insn;
3356   register int regno = REGNO (reg);
3357   rtx temp;
3358   /* Number of sets we have to insist on finding after INSN.  */
3359   int count = n_sets - 1;
3360   int old = VARRAY_INT (set_in_loop, regno);
3361   int value = 0;
3362   int this;
3363
3364   /* If N_SETS hit the limit, we can't rely on its value.  */
3365   if (n_sets == 127)
3366     return 0;
3367
3368   VARRAY_INT (set_in_loop, regno) = 0;
3369
3370   while (count > 0)
3371     {
3372       register enum rtx_code code;
3373       rtx set;
3374
3375       p = NEXT_INSN (p);
3376       code = GET_CODE (p);
3377
3378       /* If library call, skip to end of it.  */
3379       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3380         p = XEXP (temp, 0);
3381
3382       this = 0;
3383       if (code == INSN
3384           && (set = single_set (p))
3385           && GET_CODE (SET_DEST (set)) == REG
3386           && REGNO (SET_DEST (set)) == regno)
3387         {
3388           this = loop_invariant_p (loop, SET_SRC (set));
3389           if (this != 0)
3390             value |= this;
3391           else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3392             {
3393               /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3394                  If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3395                  notes are OK.  */
3396               this = (CONSTANT_P (XEXP (temp, 0))
3397                       || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3398                           && loop_invariant_p (loop, XEXP (temp, 0))));
3399               if (this != 0)
3400                 value |= this;
3401             }
3402         }
3403       if (this != 0)
3404         count--;
3405       else if (code != NOTE)
3406         {
3407           VARRAY_INT (set_in_loop, regno) = old;
3408           return 0;
3409         }
3410     }
3411
3412   VARRAY_INT (set_in_loop, regno) = old;
3413   /* If loop_invariant_p ever returned 2, we return 2.  */
3414   return 1 + (value & 2);
3415 }
3416
3417 #if 0
3418 /* I don't think this condition is sufficient to allow INSN
3419    to be moved, so we no longer test it.  */
3420
3421 /* Return 1 if all insns in the basic block of INSN and following INSN
3422    that set REG are invariant according to TABLE.  */
3423
3424 static int
3425 all_sets_invariant_p (reg, insn, table)
3426      rtx reg, insn;
3427      short *table;
3428 {
3429   register rtx p = insn;
3430   register int regno = REGNO (reg);
3431
3432   while (1)
3433     {
3434       register enum rtx_code code;
3435       p = NEXT_INSN (p);
3436       code = GET_CODE (p);
3437       if (code == CODE_LABEL || code == JUMP_INSN)
3438         return 1;
3439       if (code == INSN && GET_CODE (PATTERN (p)) == SET
3440           && GET_CODE (SET_DEST (PATTERN (p))) == REG
3441           && REGNO (SET_DEST (PATTERN (p))) == regno)
3442         {
3443           if (! loop_invariant_p (loop, SET_SRC (PATTERN (p)), table))
3444             return 0;
3445         }
3446     }
3447 }
3448 #endif /* 0 */
3449 \f
3450 /* Look at all uses (not sets) of registers in X.  For each, if it is
3451    the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3452    a different insn, set USAGE[REGNO] to const0_rtx.  */
3453
3454 static void
3455 find_single_use_in_loop (insn, x, usage)
3456      rtx insn;
3457      rtx x;
3458      varray_type usage;
3459 {
3460   enum rtx_code code = GET_CODE (x);
3461   const char *fmt = GET_RTX_FORMAT (code);
3462   int i, j;
3463
3464   if (code == REG)
3465     VARRAY_RTX (usage, REGNO (x))
3466       = (VARRAY_RTX (usage, REGNO (x)) != 0 
3467          && VARRAY_RTX (usage, REGNO (x)) != insn)
3468         ? const0_rtx : insn;
3469
3470   else if (code == SET)
3471     {
3472       /* Don't count SET_DEST if it is a REG; otherwise count things
3473          in SET_DEST because if a register is partially modified, it won't
3474          show up as a potential movable so we don't care how USAGE is set 
3475          for it.  */
3476       if (GET_CODE (SET_DEST (x)) != REG)
3477         find_single_use_in_loop (insn, SET_DEST (x), usage);
3478       find_single_use_in_loop (insn, SET_SRC (x), usage);
3479     }
3480   else
3481     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3482       {
3483         if (fmt[i] == 'e' && XEXP (x, i) != 0)
3484           find_single_use_in_loop (insn, XEXP (x, i), usage);
3485         else if (fmt[i] == 'E')
3486           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3487             find_single_use_in_loop (insn, XVECEXP (x, i, j), usage);
3488       }
3489 }
3490 \f
3491 /* Count and record any set in X which is contained in INSN.  Update
3492    MAY_NOT_MOVE and LAST_SET for any register set in X.  */
3493
3494 static void
3495 count_one_set (insn, x, may_not_move, last_set)
3496      rtx insn, x;
3497      varray_type may_not_move;
3498      rtx *last_set;
3499 {
3500   if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3501     /* Don't move a reg that has an explicit clobber.
3502        It's not worth the pain to try to do it correctly.  */
3503     VARRAY_CHAR (may_not_move, REGNO (XEXP (x, 0))) = 1;
3504
3505   if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3506     {
3507       rtx dest = SET_DEST (x);
3508       while (GET_CODE (dest) == SUBREG
3509              || GET_CODE (dest) == ZERO_EXTRACT
3510              || GET_CODE (dest) == SIGN_EXTRACT
3511              || GET_CODE (dest) == STRICT_LOW_PART)
3512         dest = XEXP (dest, 0);
3513       if (GET_CODE (dest) == REG)
3514         {
3515           register int regno = REGNO (dest);
3516           /* If this is the first setting of this reg
3517              in current basic block, and it was set before,
3518              it must be set in two basic blocks, so it cannot
3519              be moved out of the loop.  */
3520           if (VARRAY_INT (set_in_loop, regno) > 0 
3521               && last_set[regno] == 0)
3522             VARRAY_CHAR (may_not_move, regno) = 1;
3523           /* If this is not first setting in current basic block,
3524              see if reg was used in between previous one and this.
3525              If so, neither one can be moved.  */
3526           if (last_set[regno] != 0
3527               && reg_used_between_p (dest, last_set[regno], insn))
3528             VARRAY_CHAR (may_not_move, regno) = 1;
3529           if (VARRAY_INT (set_in_loop, regno) < 127)
3530             ++VARRAY_INT (set_in_loop, regno);
3531           last_set[regno] = insn;
3532         }
3533     }
3534 }
3535
3536 /* Increment SET_IN_LOOP at the index of each register
3537    that is modified by an insn between FROM and TO.
3538    If the value of an element of SET_IN_LOOP becomes 127 or more,
3539    stop incrementing it, to avoid overflow.
3540
3541    Store in SINGLE_USAGE[I] the single insn in which register I is
3542    used, if it is only used once.  Otherwise, it is set to 0 (for no
3543    uses) or const0_rtx for more than one use.  This parameter may be zero,
3544    in which case this processing is not done.
3545
3546    Store in *COUNT_PTR the number of actual instruction
3547    in the loop.  We use this to decide what is worth moving out.  */
3548
3549 /* last_set[n] is nonzero iff reg n has been set in the current basic block.
3550    In that case, it is the insn that last set reg n.  */
3551
3552 static void
3553 count_loop_regs_set (from, to, may_not_move, single_usage, count_ptr, nregs)
3554      register rtx from, to;
3555      varray_type may_not_move;
3556      varray_type single_usage;
3557      int *count_ptr;
3558      int nregs;
3559 {
3560   register rtx *last_set = (rtx *) xcalloc (nregs, sizeof (rtx));
3561   register rtx insn;
3562   register int count = 0;
3563
3564   for (insn = from; insn != to; insn = NEXT_INSN (insn))
3565     {
3566       if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
3567         {
3568           ++count;
3569
3570           /* Record registers that have exactly one use.  */
3571           find_single_use_in_loop (insn, PATTERN (insn), single_usage);
3572
3573           /* Include uses in REG_EQUAL notes.  */
3574           if (REG_NOTES (insn))
3575             find_single_use_in_loop (insn, REG_NOTES (insn), single_usage);
3576
3577           if (GET_CODE (PATTERN (insn)) == SET
3578               || GET_CODE (PATTERN (insn)) == CLOBBER)
3579             count_one_set (insn, PATTERN (insn), may_not_move, last_set);
3580           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
3581             {
3582               register int i;
3583               for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
3584                 count_one_set (insn, XVECEXP (PATTERN (insn), 0, i),
3585                                may_not_move, last_set);
3586             }
3587         }
3588
3589       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
3590         bzero ((char *) last_set, nregs * sizeof (rtx));
3591     }
3592   *count_ptr = count;
3593
3594   /* Clean up.  */
3595   free (last_set);
3596 }
3597 \f
3598 /* Given a loop that is bounded by LOOP->START and LOOP->END and that
3599    is entered at LOOP->SCAN_START, return 1 if the register set in SET
3600    contained in insn INSN is used by any insn that precedes INSN in
3601    cyclic order starting from the loop entry point.
3602
3603    We don't want to use INSN_LUID here because if we restrict INSN to those
3604    that have a valid INSN_LUID, it means we cannot move an invariant out
3605    from an inner loop past two loops.  */
3606
3607 static int
3608 loop_reg_used_before_p (loop, set, insn)
3609      const struct loop *loop;
3610      rtx set, insn;
3611 {
3612   rtx reg = SET_DEST (set);
3613   rtx p;
3614
3615   /* Scan forward checking for register usage.  If we hit INSN, we
3616      are done.  Otherwise, if we hit LOOP->END, wrap around to LOOP->START.  */
3617   for (p = loop->scan_start; p != insn; p = NEXT_INSN (p))
3618     {
3619       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
3620           && reg_overlap_mentioned_p (reg, PATTERN (p)))
3621         return 1;
3622
3623       if (p == loop->end)
3624         p = loop->start;
3625     }
3626
3627   return 0;
3628 }
3629 \f
3630 /* A "basic induction variable" or biv is a pseudo reg that is set
3631    (within this loop) only by incrementing or decrementing it.  */
3632 /* A "general induction variable" or giv is a pseudo reg whose
3633    value is a linear function of a biv.  */
3634
3635 /* Bivs are recognized by `basic_induction_var';
3636    Givs by `general_induction_var'.  */
3637
3638 /* Indexed by register number, indicates whether or not register is an
3639    induction variable, and if so what type.  */
3640
3641 varray_type reg_iv_type;
3642
3643 /* Indexed by register number, contains pointer to `struct induction'
3644    if register is an induction variable.  This holds general info for
3645    all induction variables.  */
3646
3647 varray_type reg_iv_info;
3648
3649 /* Indexed by register number, contains pointer to `struct iv_class'
3650    if register is a basic induction variable.  This holds info describing
3651    the class (a related group) of induction variables that the biv belongs
3652    to.  */
3653
3654 struct iv_class **reg_biv_class;
3655
3656 /* The head of a list which links together (via the next field)
3657    every iv class for the current loop.  */
3658
3659 struct iv_class *loop_iv_list;
3660
3661 /* Givs made from biv increments are always splittable for loop unrolling.
3662    Since there is no regscan info for them, we have to keep track of them
3663    separately.  */
3664 int first_increment_giv, last_increment_giv;
3665
3666 /* Communication with routines called via `note_stores'.  */
3667
3668 static rtx note_insn;
3669
3670 /* Dummy register to have non-zero DEST_REG for DEST_ADDR type givs.  */
3671
3672 static rtx addr_placeholder;
3673
3674 /* ??? Unfinished optimizations, and possible future optimizations,
3675    for the strength reduction code.  */
3676
3677 /* ??? The interaction of biv elimination, and recognition of 'constant'
3678    bivs, may cause problems.  */
3679
3680 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
3681    performance problems.
3682
3683    Perhaps don't eliminate things that can be combined with an addressing
3684    mode.  Find all givs that have the same biv, mult_val, and add_val;
3685    then for each giv, check to see if its only use dies in a following
3686    memory address.  If so, generate a new memory address and check to see
3687    if it is valid.   If it is valid, then store the modified memory address,
3688    otherwise, mark the giv as not done so that it will get its own iv.  */
3689
3690 /* ??? Could try to optimize branches when it is known that a biv is always
3691    positive.  */
3692
3693 /* ??? When replace a biv in a compare insn, we should replace with closest
3694    giv so that an optimized branch can still be recognized by the combiner,
3695    e.g. the VAX acb insn.  */
3696
3697 /* ??? Many of the checks involving uid_luid could be simplified if regscan
3698    was rerun in loop_optimize whenever a register was added or moved.
3699    Also, some of the optimizations could be a little less conservative.  */
3700 \f
3701 /* Perform strength reduction and induction variable elimination.  
3702
3703    Pseudo registers created during this function will be beyond the last
3704    valid index in several tables including n_times_set and regno_last_uid.
3705    This does not cause a problem here, because the added registers cannot be
3706    givs outside of their loop, and hence will never be reconsidered.
3707    But scan_loop must check regnos to make sure they are in bounds.   */
3708
3709 static void
3710 strength_reduce (loop, insn_count, unroll_p, bct_p)
3711      struct loop *loop;
3712      int insn_count;
3713      int unroll_p, bct_p ATTRIBUTE_UNUSED;
3714 {
3715   rtx p;
3716   rtx set;
3717   rtx inc_val;
3718   rtx mult_val;
3719   rtx dest_reg;
3720   rtx *location;
3721   /* This is 1 if current insn is not executed at least once for every loop
3722      iteration.  */
3723   int not_every_iteration = 0;
3724   /* This is 1 if current insn may be executed more than once for every
3725      loop iteration.  */
3726   int maybe_multiple = 0;
3727   /* This is 1 if we have past a branch back to the top of the loop
3728      (aka a loop latch).  */
3729   int past_loop_latch = 0;
3730   /* Temporary list pointers for traversing loop_iv_list.  */
3731   struct iv_class *bl, **backbl;
3732   struct loop_info *loop_info = LOOP_INFO (loop);
3733   /* Ratio of extra register life span we can justify
3734      for saving an instruction.  More if loop doesn't call subroutines
3735      since in that case saving an insn makes more difference
3736      and more registers are available.  */
3737   /* ??? could set this to last value of threshold in move_movables */
3738   int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
3739   /* Map of pseudo-register replacements.  */
3740   rtx *reg_map = NULL;
3741   int reg_map_size;
3742   int call_seen;
3743   rtx test;
3744   rtx end_insert_before;
3745   int loop_depth = 0;
3746   int n_extra_increment;
3747   int unrolled_insn_copies = 0;
3748   rtx loop_start = loop->start;
3749   rtx loop_end = loop->end;
3750   rtx loop_scan_start = loop->scan_start;
3751   rtx loop_top = loop->top;
3752   rtx loop_cont = loop->cont;
3753
3754   /* If loop_scan_start points to the loop exit test, we have to be wary of
3755      subversive use of gotos inside expression statements.  */
3756   if (prev_nonnote_insn (loop_scan_start) != prev_nonnote_insn (loop_start))
3757     maybe_multiple = back_branch_in_range_p (loop, loop_scan_start);
3758
3759   VARRAY_INT_INIT (reg_iv_type, max_reg_before_loop, "reg_iv_type");
3760   VARRAY_GENERIC_PTR_INIT (reg_iv_info, max_reg_before_loop, "reg_iv_info");
3761   reg_biv_class = (struct iv_class **)
3762     xcalloc (max_reg_before_loop, sizeof (struct iv_class *));
3763
3764   loop_iv_list = 0;
3765   addr_placeholder = gen_reg_rtx (Pmode);
3766
3767   /* Save insn immediately after the loop_end.  Insns inserted after loop_end
3768      must be put before this insn, so that they will appear in the right
3769      order (i.e. loop order). 
3770
3771      If loop_end is the end of the current function, then emit a 
3772      NOTE_INSN_DELETED after loop_end and set end_insert_before to the
3773      dummy note insn.  */
3774   if (NEXT_INSN (loop_end) != 0)
3775     end_insert_before = NEXT_INSN (loop_end);
3776   else
3777     end_insert_before = emit_note_after (NOTE_INSN_DELETED, loop_end);
3778
3779   /* Scan through loop to find all possible bivs.  */
3780
3781   for (p = next_insn_in_loop (loop, loop_scan_start);
3782        p != NULL_RTX;
3783        p = next_insn_in_loop (loop, p))
3784     {
3785       if (GET_CODE (p) == INSN
3786           && (set = single_set (p))
3787           && GET_CODE (SET_DEST (set)) == REG)
3788         {
3789           dest_reg = SET_DEST (set);
3790           if (REGNO (dest_reg) < max_reg_before_loop
3791               && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
3792               && REG_IV_TYPE (REGNO (dest_reg)) != NOT_BASIC_INDUCT)
3793             {
3794               int multi_insn_incr = 0;
3795
3796               if (basic_induction_var (loop, SET_SRC (set),
3797                                        GET_MODE (SET_SRC (set)),
3798                                        dest_reg, p, &inc_val, &mult_val,
3799                                        &location, &multi_insn_incr))
3800                 {
3801                   /* It is a possible basic induction variable.
3802                      Create and initialize an induction structure for it.  */
3803
3804                   struct induction *v
3805                     = (struct induction *) alloca (sizeof (struct induction));
3806
3807                   record_biv (v, p, dest_reg, inc_val, mult_val, location,
3808                               not_every_iteration, maybe_multiple, 
3809                               multi_insn_incr);
3810                   REG_IV_TYPE (REGNO (dest_reg)) = BASIC_INDUCT;
3811                 }
3812               else if (REGNO (dest_reg) < max_reg_before_loop)
3813                 REG_IV_TYPE (REGNO (dest_reg)) = NOT_BASIC_INDUCT;
3814             }
3815         }
3816
3817       /* Past CODE_LABEL, we get to insns that may be executed multiple
3818          times.  The only way we can be sure that they can't is if every
3819          jump insn between here and the end of the loop either
3820          returns, exits the loop, is a jump to a location that is still
3821          behind the label, or is a jump to the loop start.  */
3822
3823       if (GET_CODE (p) == CODE_LABEL)
3824         {
3825           rtx insn = p;
3826
3827           maybe_multiple = 0;
3828
3829           while (1)
3830             {
3831               insn = NEXT_INSN (insn);
3832               if (insn == loop_scan_start)
3833                 break;
3834               if (insn == loop_end)
3835                 {
3836                   if (loop_top != 0)
3837                     insn = loop_top;
3838                   else
3839                     break;
3840                   if (insn == loop_scan_start)
3841                     break;
3842                 }
3843
3844               if (GET_CODE (insn) == JUMP_INSN
3845                   && GET_CODE (PATTERN (insn)) != RETURN
3846                   && (! condjump_p (insn)
3847                       || (JUMP_LABEL (insn) != 0
3848                           && JUMP_LABEL (insn) != loop_scan_start
3849                           && ! loop_insn_first_p (p, JUMP_LABEL (insn)))))
3850                 {
3851                   maybe_multiple = 1;
3852                   break;
3853                 }
3854             }
3855         }
3856
3857       /* Past a jump, we get to insns for which we can't count
3858          on whether they will be executed during each iteration.  */
3859       /* This code appears twice in strength_reduce.  There is also similar
3860          code in scan_loop.  */
3861       if (GET_CODE (p) == JUMP_INSN
3862           /* If we enter the loop in the middle, and scan around to the
3863              beginning, don't set not_every_iteration for that.
3864              This can be any kind of jump, since we want to know if insns
3865              will be executed if the loop is executed.  */
3866           && ! (JUMP_LABEL (p) == loop_top
3867                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3868                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3869         {
3870           rtx label = 0;
3871
3872           /* If this is a jump outside the loop, then it also doesn't
3873              matter.  Check to see if the target of this branch is on the
3874              loop->exits_labels list.  */
3875              
3876           for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
3877             if (XEXP (label, 0) == JUMP_LABEL (p))
3878               break;
3879
3880           if (! label)
3881             not_every_iteration = 1;
3882         }
3883
3884       else if (GET_CODE (p) == NOTE)
3885         {
3886           /* At the virtual top of a converted loop, insns are again known to
3887              be executed each iteration: logically, the loop begins here
3888              even though the exit code has been duplicated.
3889
3890              Insns are also again known to be executed each iteration at
3891              the LOOP_CONT note.  */
3892           if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
3893                || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
3894               && loop_depth == 0)
3895             not_every_iteration = 0;
3896           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3897             loop_depth++;
3898           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
3899             loop_depth--;
3900         }
3901
3902       /* Note if we pass a loop latch.  If we do, then we can not clear
3903          NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
3904          a loop since a jump before the last CODE_LABEL may have started
3905          a new loop iteration.
3906
3907          Note that LOOP_TOP is only set for rotated loops and we need
3908          this check for all loops, so compare against the CODE_LABEL
3909          which immediately follows LOOP_START.  */
3910       if (GET_CODE (p) == JUMP_INSN 
3911           && JUMP_LABEL (p) == NEXT_INSN (loop_start))
3912         past_loop_latch = 1;
3913
3914       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3915          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3916          or not an insn is known to be executed each iteration of the
3917          loop, whether or not any iterations are known to occur.
3918
3919          Therefore, if we have just passed a label and have no more labels
3920          between here and the test insn of the loop, and we have not passed
3921          a jump to the top of the loop, then we know these insns will be
3922          executed each iteration.  */
3923
3924       if (not_every_iteration 
3925           && ! past_loop_latch
3926           && GET_CODE (p) == CODE_LABEL
3927           && no_labels_between_p (p, loop_end)
3928           && loop_insn_first_p (p, loop_cont))
3929         not_every_iteration = 0;
3930     }
3931
3932   /* Scan loop_iv_list to remove all regs that proved not to be bivs.
3933      Make a sanity check against n_times_set.  */
3934   for (backbl = &loop_iv_list, bl = *backbl; bl; bl = bl->next)
3935     {
3936       int fail = 0;
3937
3938       if (REG_IV_TYPE (bl->regno) != BASIC_INDUCT
3939           /* Above happens if register modified by subreg, etc.  */
3940           /* Make sure it is not recognized as a basic induction var: */
3941           || VARRAY_INT (n_times_set, bl->regno) != bl->biv_count
3942           /* If never incremented, it is invariant that we decided not to
3943              move.  So leave it alone.  */
3944           || ! bl->incremented)
3945         fail = 1;
3946       else if (bl->biv_count > 1)
3947         {
3948           /* ??? If we have multiple increments for this BIV, and any of
3949              them take multiple insns to perform the increment, drop the
3950              BIV, since the bit below that converts the extra increments
3951              into GIVs can't handle the multiple insn increment.  */
3952           
3953           struct induction *v;
3954           for (v = bl->biv; v ; v = v->next_iv)
3955             if (v->multi_insn_incr)
3956               fail = 1;
3957         }
3958
3959       if (fail)
3960         {
3961           if (loop_dump_stream)
3962             fprintf (loop_dump_stream, "Reg %d: biv discarded, %s\n",
3963                      bl->regno,
3964                      (REG_IV_TYPE (bl->regno) != BASIC_INDUCT
3965                       ? "not induction variable"
3966                       : (! bl->incremented ? "never incremented"
3967                          : "count error")));
3968           
3969           REG_IV_TYPE (bl->regno) = NOT_BASIC_INDUCT;
3970           *backbl = bl->next;
3971         }
3972       else
3973         {
3974           backbl = &bl->next;
3975
3976           if (loop_dump_stream)
3977             fprintf (loop_dump_stream, "Reg %d: biv verified\n", bl->regno);
3978         }
3979     }
3980
3981   /* Exit if there are no bivs.  */
3982   if (! loop_iv_list)
3983     {
3984       /* Can still unroll the loop anyways, but indicate that there is no
3985          strength reduction info available.  */
3986       if (unroll_p)
3987         unroll_loop (loop, insn_count, end_insert_before, 0);
3988
3989       goto egress;
3990     }
3991
3992   /* Find initial value for each biv by searching backwards from loop_start,
3993      halting at first label.  Also record any test condition.  */
3994
3995   call_seen = 0;
3996   for (p = loop_start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
3997     {
3998       note_insn = p;
3999
4000       if (GET_CODE (p) == CALL_INSN)
4001         call_seen = 1;
4002
4003       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4004           || GET_CODE (p) == CALL_INSN)
4005         note_stores (PATTERN (p), record_initial, NULL);
4006
4007       /* Record any test of a biv that branches around the loop if no store
4008          between it and the start of loop.  We only care about tests with
4009          constants and registers and only certain of those.  */
4010       if (GET_CODE (p) == JUMP_INSN
4011           && JUMP_LABEL (p) != 0
4012           && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop_end)
4013           && (test = get_condition_for_loop (loop, p)) != 0
4014           && GET_CODE (XEXP (test, 0)) == REG
4015           && REGNO (XEXP (test, 0)) < max_reg_before_loop
4016           && (bl = reg_biv_class[REGNO (XEXP (test, 0))]) != 0
4017           && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop_start)
4018           && bl->init_insn == 0)
4019         {
4020           /* If an NE test, we have an initial value!  */
4021           if (GET_CODE (test) == NE)
4022             {
4023               bl->init_insn = p;
4024               bl->init_set = gen_rtx_SET (VOIDmode,
4025                                           XEXP (test, 0), XEXP (test, 1));
4026             }
4027           else
4028             bl->initial_test = test;
4029         }
4030     }
4031
4032   /* Look at the each biv and see if we can say anything better about its
4033      initial value from any initializing insns set up above.  (This is done
4034      in two passes to avoid missing SETs in a PARALLEL.)  */
4035   for (backbl = &loop_iv_list; (bl = *backbl); backbl = &bl->next)
4036     {
4037       rtx src;
4038       rtx note;
4039
4040       if (! bl->init_insn)
4041         continue;
4042
4043       /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4044          is a constant, use the value of that.  */
4045       if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4046            && CONSTANT_P (XEXP (note, 0)))
4047           || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4048               && CONSTANT_P (XEXP (note, 0))))
4049         src = XEXP (note, 0);
4050       else
4051         src = SET_SRC (bl->init_set);
4052
4053       if (loop_dump_stream)
4054         fprintf (loop_dump_stream,
4055                  "Biv %d initialized at insn %d: initial value ",
4056                  bl->regno, INSN_UID (bl->init_insn));
4057
4058       if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4059            || GET_MODE (src) == VOIDmode)
4060           && valid_initial_value_p (src, bl->init_insn, call_seen, loop_start))
4061         {
4062           bl->initial_value = src;
4063
4064           if (loop_dump_stream)
4065             {
4066               if (GET_CODE (src) == CONST_INT)
4067                 {
4068                   fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (src));
4069                   fputc ('\n', loop_dump_stream);
4070                 }
4071               else
4072                 {
4073                   print_rtl (loop_dump_stream, src);
4074                   fprintf (loop_dump_stream, "\n");
4075                 }
4076             }
4077         }
4078       else
4079         {
4080           struct iv_class *bl2 = 0;
4081           rtx increment = NULL_RTX;
4082
4083           /* Biv initial value is not a simple move.  If it is the sum of
4084              another biv and a constant, check if both bivs are incremented
4085              in lockstep.  Then we are actually looking at a giv.
4086              For simplicity, we only handle the case where there is but a
4087              single increment, and the register is not used elsewhere.  */
4088           if (bl->biv_count == 1
4089               && bl->regno < max_reg_before_loop
4090               && uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4091               && GET_CODE (src) == PLUS
4092               && GET_CODE (XEXP (src, 0)) == REG
4093               && CONSTANT_P (XEXP (src, 1))
4094               && ((increment = biv_total_increment (bl)) != NULL_RTX))
4095             {
4096               int regno = REGNO (XEXP (src, 0));
4097
4098               for (bl2 = loop_iv_list; bl2; bl2 = bl2->next)
4099                 if (bl2->regno == regno)
4100                   break;
4101             }
4102         
4103           /* Now, can we transform this biv into a giv?  */
4104           if (bl2
4105               && bl2->biv_count == 1
4106               && rtx_equal_p (increment, biv_total_increment (bl2))
4107               /* init_insn is only set to insns that are before loop_start
4108                  without any intervening labels.  */
4109               && ! reg_set_between_p (bl2->biv->src_reg,
4110                                       PREV_INSN (bl->init_insn), loop_start)
4111               /* The register from BL2 must be set before the register from
4112                  BL is set, or we must be able to move the latter set after
4113                  the former set.  Currently there can't be any labels
4114                  in-between when biv_total_increment returns nonzero both times
4115                  but we test it here in case some day some real cfg analysis
4116                  gets used to set always_computable.  */
4117               && (loop_insn_first_p (bl2->biv->insn, bl->biv->insn)
4118                   ? no_labels_between_p (bl2->biv->insn, bl->biv->insn)
4119                   : (! reg_used_between_p (bl->biv->src_reg, bl->biv->insn,
4120                                            bl2->biv->insn)
4121                      && no_jumps_between_p (bl->biv->insn, bl2->biv->insn)))
4122               && validate_change (bl->biv->insn,
4123                                   &SET_SRC (single_set (bl->biv->insn)),
4124                                   copy_rtx (src), 0))
4125             {
4126               rtx dominator = loop->cont_dominator;
4127               rtx giv = bl->biv->src_reg;
4128               rtx giv_insn = bl->biv->insn;
4129               rtx after_giv = NEXT_INSN (giv_insn);
4130
4131               if (loop_dump_stream)
4132                 fprintf (loop_dump_stream, "is giv of biv %d\n", bl2->regno);
4133               /* Let this giv be discovered by the generic code.  */
4134               REG_IV_TYPE (bl->regno) = UNKNOWN_INDUCT;
4135               reg_biv_class[bl->regno] = (struct iv_class *) NULL_PTR;
4136               /* We can get better optimization if we can move the giv setting
4137                  before the first giv use.  */
4138               if (dominator
4139                   && ! loop_insn_first_p (dominator, loop_scan_start)
4140                   && ! reg_set_between_p (bl2->biv->src_reg, loop_start,
4141                                           dominator)
4142                   && ! reg_used_between_p (giv, loop_start, dominator)
4143                   && ! reg_used_between_p (giv, giv_insn, loop_end))
4144                 {
4145                   rtx p;
4146                   rtx next;
4147
4148                   for (next = NEXT_INSN (dominator); ; next = NEXT_INSN (next))
4149                     {
4150                       if ((GET_RTX_CLASS (GET_CODE (next)) == 'i'
4151                            && (reg_mentioned_p (giv, PATTERN (next))
4152                                || reg_set_p (bl2->biv->src_reg, next)))
4153                           || GET_CODE (next) == JUMP_INSN)
4154                         break;
4155 #ifdef HAVE_cc0
4156                       if (GET_RTX_CLASS (GET_CODE (next)) != 'i'
4157                           || ! sets_cc0_p (PATTERN (next)))
4158 #endif
4159                         dominator = next;
4160                     }
4161                   if (loop_dump_stream)
4162                     fprintf (loop_dump_stream, "move after insn %d\n",
4163                              INSN_UID (dominator));
4164                   /* Avoid problems with luids by actually moving the insn
4165                      and adjusting all luids in the range.  */
4166                   reorder_insns (giv_insn, giv_insn, dominator);
4167                   for (p = dominator; INSN_UID (p) >= max_uid_for_loop; )
4168                     p = PREV_INSN (p);
4169                   compute_luids (giv_insn, after_giv, INSN_LUID (p));
4170                   /* If the only purpose of the init insn is to initialize
4171                      this giv, delete it.  */
4172                   if (single_set (bl->init_insn)
4173                       && ! reg_used_between_p (giv, bl->init_insn, loop_start))
4174                     delete_insn (bl->init_insn);
4175                 }
4176               else if (! loop_insn_first_p (bl2->biv->insn, bl->biv->insn))
4177                 {
4178                   rtx p = PREV_INSN (giv_insn);
4179                   while (INSN_UID (p) >= max_uid_for_loop)
4180                     p = PREV_INSN (p);
4181                   reorder_insns (giv_insn, giv_insn, bl2->biv->insn);
4182                   compute_luids (after_giv, NEXT_INSN (giv_insn),
4183                                  INSN_LUID (p));
4184                 }
4185               /* Remove this biv from the chain.  */
4186               if (bl->next)
4187                 {
4188                   /* We move the following giv from *bl->next into *bl.
4189                      We have to update reg_biv_class for that moved biv
4190                      to point to its new address.  */
4191                   *bl = *bl->next;
4192                   reg_biv_class[bl->regno] = bl;
4193                 }
4194               else
4195                 {
4196                   *backbl = 0;
4197                   break;
4198                 }
4199             }
4200
4201           /* If we can't make it a giv,
4202              let biv keep initial value of "itself".  */
4203           else if (loop_dump_stream)
4204             fprintf (loop_dump_stream, "is complex\n");
4205         }
4206     }
4207
4208   /* If a biv is unconditionally incremented several times in a row, convert
4209      all but the last increment into a giv.  */
4210
4211   /* Get an upper bound for the number of registers
4212      we might have after all bivs have been processed.  */
4213   first_increment_giv = max_reg_num ();
4214   for (n_extra_increment = 0, bl = loop_iv_list; bl; bl = bl->next)
4215     n_extra_increment += bl->biv_count - 1;
4216
4217   /* If the loop contains volatile memory references do not allow any
4218      replacements to take place, since this could loose the volatile
4219      markers.  */
4220   if (n_extra_increment  && ! loop_info->has_volatile)
4221     {
4222       int nregs = first_increment_giv + n_extra_increment;
4223
4224       /* Reallocate reg_iv_type and reg_iv_info.  */
4225       VARRAY_GROW (reg_iv_type, nregs);
4226       VARRAY_GROW (reg_iv_info, nregs);
4227
4228       for (bl = loop_iv_list; bl; bl = bl->next)
4229         {
4230           struct induction **vp, *v, *next;
4231           int biv_dead_after_loop = 0;
4232
4233           /* The biv increments lists are in reverse order.  Fix this
4234              first.  */
4235           for (v = bl->biv, bl->biv = 0; v; v = next)
4236             {
4237               next = v->next_iv;
4238               v->next_iv = bl->biv;
4239               bl->biv = v;
4240             }
4241
4242           /* We must guard against the case that an early exit between v->insn
4243              and next->insn leaves the biv live after the loop, since that
4244              would mean that we'd be missing an increment for the final
4245              value.  The following test to set biv_dead_after_loop is like
4246              the first part of the test to set bl->eliminable.
4247              We don't check here if we can calculate the final value, since
4248              this can't succeed if we already know that there is a jump
4249              between v->insn and next->insn, yet next->always_executed is
4250              set and next->maybe_multiple is cleared.  Such a combination
4251              implies that the jump destination is outside the loop.
4252              If we want to make this check more sophisticated, we should
4253              check each branch between v->insn and next->insn individually
4254              to see if the biv is dead at its destination.  */
4255
4256           if (uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4257               && bl->init_insn
4258               && INSN_UID (bl->init_insn) < max_uid_for_loop
4259               && (uid_luid[REGNO_FIRST_UID (bl->regno)]
4260                   >= INSN_LUID (bl->init_insn))
4261 #ifdef HAVE_decrement_and_branch_until_zero
4262               && ! bl->nonneg
4263 #endif
4264               && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4265             biv_dead_after_loop = 1;
4266
4267           for (vp = &bl->biv, next = *vp; v = next, next = v->next_iv;)
4268             {
4269               HOST_WIDE_INT offset;
4270               rtx set, add_val, old_reg, dest_reg, last_use_insn, note;
4271               int old_regno, new_regno;
4272
4273               if (! v->always_executed
4274                   || v->maybe_multiple
4275                   || GET_CODE (v->add_val) != CONST_INT
4276                   || ! next->always_executed
4277                   || next->maybe_multiple
4278                   || ! CONSTANT_P (next->add_val)
4279                   || v->mult_val != const1_rtx
4280                   || next->mult_val != const1_rtx
4281                   || ! (biv_dead_after_loop
4282                         || no_jumps_between_p (v->insn, next->insn)))
4283                 {
4284                   vp = &v->next_iv;
4285                   continue;
4286                 }
4287               offset = INTVAL (v->add_val);
4288               set = single_set (v->insn);
4289               add_val = plus_constant (next->add_val, offset);
4290               old_reg = v->dest_reg;
4291               dest_reg = gen_reg_rtx (v->mode);
4292     
4293               /* Unlike reg_iv_type / reg_iv_info, the other three arrays
4294                  have been allocated with some slop space, so we may not
4295                  actually need to reallocate them.  If we do, the following
4296                  if statement will be executed just once in this loop.  */
4297               if ((unsigned) max_reg_num () > n_times_set->num_elements)
4298                 {
4299                   /* Grow all the remaining arrays.  */
4300                   VARRAY_GROW (set_in_loop, nregs);
4301                   VARRAY_GROW (n_times_set, nregs);
4302                   VARRAY_GROW (may_not_optimize, nregs);
4303                   VARRAY_GROW (reg_single_usage, nregs);
4304                 }
4305     
4306               if (! validate_change (next->insn, next->location, add_val, 0))
4307                 {
4308                   vp = &v->next_iv;
4309                   continue;
4310                 }
4311
4312               /* Here we can try to eliminate the increment by combining
4313                  it into the uses.  */
4314
4315               /* Set last_use_insn so that we can check against it.  */
4316
4317               for (last_use_insn = v->insn, p = NEXT_INSN (v->insn);
4318                    p != next->insn;
4319                    p = next_insn_in_loop (loop, p))
4320                 {
4321                   if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
4322                     continue;
4323                   if (reg_mentioned_p (old_reg, PATTERN (p)))
4324                     {
4325                       last_use_insn = p;
4326                     }
4327                 }
4328
4329               /* If we can't get the LUIDs for the insns, we can't
4330                  calculate the lifetime.  This is likely from unrolling
4331                  of an inner loop, so there is little point in making this
4332                  a DEST_REG giv anyways.  */
4333               if (INSN_UID (v->insn) >= max_uid_for_loop
4334                   || INSN_UID (last_use_insn) >= max_uid_for_loop
4335                   || ! validate_change (v->insn, &SET_DEST (set), dest_reg, 0))
4336                 {
4337                   /* Change the increment at NEXT back to what it was.  */
4338                   if (! validate_change (next->insn, next->location,
4339                       next->add_val, 0))
4340                     abort ();
4341                   vp = &v->next_iv;
4342                   continue;
4343                 }
4344               next->add_val = add_val;
4345               v->dest_reg = dest_reg;
4346               v->giv_type = DEST_REG;
4347               v->location = &SET_SRC (set);
4348               v->cant_derive = 0;
4349               v->combined_with = 0;
4350               v->maybe_dead = 0;
4351               v->derive_adjustment = 0;
4352               v->same = 0;
4353               v->ignore = 0;
4354               v->new_reg = 0;
4355               v->final_value = 0;
4356               v->same_insn = 0;
4357               v->auto_inc_opt = 0;
4358               v->unrolled = 0;
4359               v->shared = 0;
4360               v->derived_from = 0;
4361               v->always_computable = 1;
4362               v->always_executed = 1;
4363               v->replaceable = 1;
4364               v->no_const_addval = 0;
4365     
4366               old_regno = REGNO (old_reg);
4367               new_regno = REGNO (dest_reg);
4368               VARRAY_INT (set_in_loop, old_regno)--;
4369               VARRAY_INT (set_in_loop, new_regno) = 1;
4370               VARRAY_INT (n_times_set, old_regno)--;
4371               VARRAY_INT (n_times_set, new_regno) = 1;
4372               VARRAY_CHAR (may_not_optimize, new_regno) = 0;
4373     
4374               REG_IV_TYPE (new_regno) = GENERAL_INDUCT;
4375               REG_IV_INFO (new_regno) = v;
4376
4377               /* If next_insn has a REG_EQUAL note that mentiones OLD_REG,
4378                  it must be replaced.  */
4379               note = find_reg_note (next->insn, REG_EQUAL, NULL_RTX);
4380               if (note && reg_mentioned_p (old_reg, XEXP (note, 0)))
4381                 XEXP (note, 0) = copy_rtx (SET_SRC (single_set (next->insn)));
4382
4383               /* Remove the increment from the list of biv increments,
4384                  and record it as a giv.  */
4385               *vp = next;
4386               bl->biv_count--;
4387               v->next_iv = bl->giv;
4388               bl->giv = v;
4389               bl->giv_count++;
4390               v->benefit = rtx_cost (SET_SRC (set), SET);
4391               bl->total_benefit += v->benefit;
4392     
4393               /* Now replace the biv with DEST_REG in all insns between
4394                  the replaced increment and the next increment, and
4395                  remember the last insn that needed a replacement.  */
4396               for (last_use_insn = v->insn, p = NEXT_INSN (v->insn);
4397                    p != next->insn;
4398                    p = next_insn_in_loop (loop, p))
4399                 {
4400                   rtx note;
4401     
4402                   if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
4403                     continue;
4404                   if (reg_mentioned_p (old_reg, PATTERN (p)))
4405                     {
4406                       last_use_insn = p;
4407                       if (! validate_replace_rtx (old_reg, dest_reg, p))
4408                         abort ();
4409                     }
4410                   for (note = REG_NOTES (p); note; note = XEXP (note, 1))
4411                     {
4412                       if (GET_CODE (note) == EXPR_LIST)
4413                         XEXP (note, 0)
4414                           = replace_rtx (XEXP (note, 0), old_reg, dest_reg);
4415                     }
4416                 }
4417     
4418               v->last_use = last_use_insn;
4419               v->lifetime = INSN_LUID (last_use_insn) - INSN_LUID (v->insn);
4420               /* If the lifetime is zero, it means that this register is really
4421                  a dead store.  So mark this as a giv that can be ignored.
4422                  This will not prevent the biv from being eliminated.  */
4423               if (v->lifetime == 0)
4424                 v->ignore = 1;
4425
4426               if (loop_dump_stream)
4427                 fprintf (loop_dump_stream,
4428                          "Increment %d of biv %d converted to giv %d.\n",
4429                          INSN_UID (v->insn), old_regno, new_regno);
4430             }
4431         }
4432     }
4433   last_increment_giv = max_reg_num () - 1;
4434
4435   /* Search the loop for general induction variables.  */
4436
4437   /* A register is a giv if: it is only set once, it is a function of a
4438      biv and a constant (or invariant), and it is not a biv.  */
4439
4440   not_every_iteration = 0;
4441   loop_depth = 0;
4442   maybe_multiple = 0;
4443   p = loop_scan_start;
4444   while (1)
4445     {
4446       p = NEXT_INSN (p);
4447       /* At end of a straight-in loop, we are done.
4448          At end of a loop entered at the bottom, scan the top.  */
4449       if (p == loop_scan_start)
4450         break;
4451       if (p == loop_end)
4452         {
4453           if (loop_top != 0)
4454             p = loop_top;
4455           else
4456             break;
4457           if (p == loop_scan_start)
4458             break;
4459         }
4460
4461       /* Look for a general induction variable in a register.  */
4462       if (GET_CODE (p) == INSN
4463           && (set = single_set (p))
4464           && GET_CODE (SET_DEST (set)) == REG
4465           && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
4466         {
4467           rtx src_reg;
4468           rtx add_val;
4469           rtx mult_val;
4470           int benefit;
4471           rtx regnote = 0;
4472           rtx last_consec_insn;
4473
4474           dest_reg = SET_DEST (set);
4475           if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
4476             continue;
4477
4478           if (/* SET_SRC is a giv.  */
4479               (general_induction_var (loop, SET_SRC (set), &src_reg, &add_val,
4480                                       &mult_val, 0, &benefit)
4481                /* Equivalent expression is a giv.  */
4482                || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
4483                    && general_induction_var (loop, XEXP (regnote, 0), &src_reg,
4484                                              &add_val, &mult_val, 0,
4485                                              &benefit)))
4486               /* Don't try to handle any regs made by loop optimization.
4487                  We have nothing on them in regno_first_uid, etc.  */
4488               && REGNO (dest_reg) < max_reg_before_loop
4489               /* Don't recognize a BASIC_INDUCT_VAR here.  */
4490               && dest_reg != src_reg
4491               /* This must be the only place where the register is set.  */
4492               && (VARRAY_INT (n_times_set, REGNO (dest_reg)) == 1
4493                   /* or all sets must be consecutive and make a giv.  */
4494                   || (benefit = consec_sets_giv (loop, benefit, p,
4495                                                  src_reg, dest_reg,
4496                                                  &add_val, &mult_val,
4497                                                  &last_consec_insn))))
4498             {
4499               struct induction *v
4500                 = (struct induction *) alloca (sizeof (struct induction));
4501
4502               /* If this is a library call, increase benefit.  */
4503               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
4504                 benefit += libcall_benefit (p);
4505
4506               /* Skip the consecutive insns, if there are any.  */
4507               if (VARRAY_INT (n_times_set, REGNO (dest_reg)) != 1)
4508                 p = last_consec_insn;
4509
4510               record_giv (loop, v, p, src_reg, dest_reg, mult_val, add_val,
4511                           benefit, DEST_REG, not_every_iteration,
4512                           maybe_multiple, NULL_PTR);
4513
4514             }
4515         }
4516
4517 #ifndef DONT_REDUCE_ADDR
4518       /* Look for givs which are memory addresses.  */
4519       /* This resulted in worse code on a VAX 8600.  I wonder if it
4520          still does.  */
4521       if (GET_CODE (p) == INSN)
4522         find_mem_givs (loop, PATTERN (p), p, not_every_iteration,
4523                        maybe_multiple);
4524 #endif
4525
4526       /* Update the status of whether giv can derive other givs.  This can
4527          change when we pass a label or an insn that updates a biv.  */
4528       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4529         || GET_CODE (p) == CODE_LABEL)
4530         update_giv_derive (loop, p);
4531
4532       /* Past CODE_LABEL, we get to insns that may be executed multiple
4533          times.  The only way we can be sure that they can't is if every
4534          every jump insn between here and the end of the loop either
4535          returns, exits the loop, is a forward jump, or is a jump
4536          to the loop start.  */
4537
4538       if (GET_CODE (p) == CODE_LABEL)
4539         {
4540           rtx insn = p;
4541
4542           maybe_multiple = 0;
4543
4544           while (1)
4545             {
4546               insn = NEXT_INSN (insn);
4547               if (insn == loop_scan_start)
4548                 break;
4549               if (insn == loop_end)
4550                 {
4551                   if (loop_top != 0)
4552                     insn = loop_top;
4553                   else
4554                     break;
4555                   if (insn == loop_scan_start)
4556                     break;
4557                 }
4558
4559               if (GET_CODE (insn) == JUMP_INSN
4560                   && GET_CODE (PATTERN (insn)) != RETURN
4561                   && (! condjump_p (insn)
4562                       || (JUMP_LABEL (insn) != 0
4563                           && JUMP_LABEL (insn) != loop_scan_start
4564                           && (INSN_UID (JUMP_LABEL (insn)) >= max_uid_for_loop
4565                               || INSN_UID (insn) >= max_uid_for_loop
4566                               || (INSN_LUID (JUMP_LABEL (insn))
4567                                   < INSN_LUID (insn))))))
4568                 {
4569                   maybe_multiple = 1;
4570                   break;
4571                 }
4572             }
4573         }
4574
4575       /* Past a jump, we get to insns for which we can't count
4576          on whether they will be executed during each iteration.  */
4577       /* This code appears twice in strength_reduce.  There is also similar
4578          code in scan_loop.  */
4579       if (GET_CODE (p) == JUMP_INSN
4580           /* If we enter the loop in the middle, and scan around to the
4581              beginning, don't set not_every_iteration for that.
4582              This can be any kind of jump, since we want to know if insns
4583              will be executed if the loop is executed.  */
4584           && ! (JUMP_LABEL (p) == loop_top
4585                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
4586                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
4587         {
4588           rtx label = 0;
4589
4590           /* If this is a jump outside the loop, then it also doesn't
4591              matter.  Check to see if the target of this branch is on the
4592              loop->exits_labels list.  */
4593              
4594           for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
4595             if (XEXP (label, 0) == JUMP_LABEL (p))
4596               break;
4597
4598           if (! label)
4599             not_every_iteration = 1;
4600         }
4601
4602       else if (GET_CODE (p) == NOTE)
4603         {
4604           /* At the virtual top of a converted loop, insns are again known to
4605              be executed each iteration: logically, the loop begins here
4606              even though the exit code has been duplicated.
4607
4608              Insns are also again known to be executed each iteration at
4609              the LOOP_CONT note.  */
4610           if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
4611                || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
4612               && loop_depth == 0)
4613             not_every_iteration = 0;
4614           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
4615             loop_depth++;
4616           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
4617             loop_depth--;
4618         }
4619
4620       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4621          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4622          or not an insn is known to be executed each iteration of the
4623          loop, whether or not any iterations are known to occur.
4624
4625          Therefore, if we have just passed a label and have no more labels
4626          between here and the test insn of the loop, we know these insns
4627          will be executed each iteration.  */
4628
4629       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
4630           && no_labels_between_p (p, loop_end)
4631           && loop_insn_first_p (p, loop_cont))
4632         not_every_iteration = 0;
4633     }
4634
4635   /* Try to calculate and save the number of loop iterations.  This is
4636      set to zero if the actual number can not be calculated.  This must
4637      be called after all giv's have been identified, since otherwise it may
4638      fail if the iteration variable is a giv.  */
4639
4640   loop_iterations (loop);
4641
4642   /* Now for each giv for which we still don't know whether or not it is
4643      replaceable, check to see if it is replaceable because its final value
4644      can be calculated.  This must be done after loop_iterations is called,
4645      so that final_giv_value will work correctly.  */
4646
4647   for (bl = loop_iv_list; bl; bl = bl->next)
4648     {
4649       struct induction *v;
4650
4651       for (v = bl->giv; v; v = v->next_iv)
4652         if (! v->replaceable && ! v->not_replaceable)
4653           check_final_value (loop, v);
4654     }
4655
4656   /* Try to prove that the loop counter variable (if any) is always
4657      nonnegative; if so, record that fact with a REG_NONNEG note
4658      so that "decrement and branch until zero" insn can be used.  */
4659   check_dbra_loop (loop, insn_count);
4660
4661   /* Create reg_map to hold substitutions for replaceable giv regs.
4662      Some givs might have been made from biv increments, so look at
4663      reg_iv_type for a suitable size.  */
4664   reg_map_size = reg_iv_type->num_elements;
4665   reg_map = (rtx *) xcalloc (reg_map_size, sizeof (rtx));
4666
4667   /* Examine each iv class for feasibility of strength reduction/induction
4668      variable elimination.  */
4669
4670   for (bl = loop_iv_list; bl; bl = bl->next)
4671     {
4672       struct induction *v;
4673       int benefit;
4674       int all_reduced;
4675       rtx final_value = 0;
4676       unsigned int nregs;
4677
4678       /* Test whether it will be possible to eliminate this biv
4679          provided all givs are reduced.  This is possible if either
4680          the reg is not used outside the loop, or we can compute
4681          what its final value will be.
4682
4683          For architectures with a decrement_and_branch_until_zero insn,
4684          don't do this if we put a REG_NONNEG note on the endtest for
4685          this biv.  */
4686
4687       /* Compare against bl->init_insn rather than loop_start.
4688          We aren't concerned with any uses of the biv between
4689          init_insn and loop_start since these won't be affected
4690          by the value of the biv elsewhere in the function, so
4691          long as init_insn doesn't use the biv itself.
4692          March 14, 1989 -- self@bayes.arc.nasa.gov */
4693
4694       if ((uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4695            && bl->init_insn
4696            && INSN_UID (bl->init_insn) < max_uid_for_loop
4697            && uid_luid[REGNO_FIRST_UID (bl->regno)] >= INSN_LUID (bl->init_insn)
4698 #ifdef HAVE_decrement_and_branch_until_zero
4699            && ! bl->nonneg
4700 #endif
4701            && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4702           || ((final_value = final_biv_value (loop, bl))
4703 #ifdef HAVE_decrement_and_branch_until_zero
4704               && ! bl->nonneg
4705 #endif
4706               ))
4707         bl->eliminable = maybe_eliminate_biv (loop, bl, 0, threshold, 
4708                                               insn_count);
4709       else
4710         {
4711           if (loop_dump_stream)
4712             {
4713               fprintf (loop_dump_stream,
4714                        "Cannot eliminate biv %d.\n",
4715                        bl->regno);
4716               fprintf (loop_dump_stream,
4717                        "First use: insn %d, last use: insn %d.\n",
4718                        REGNO_FIRST_UID (bl->regno),
4719                        REGNO_LAST_UID (bl->regno));
4720             }
4721         }
4722
4723       /* Combine all giv's for this iv_class.  */
4724       combine_givs (bl);
4725
4726       /* This will be true at the end, if all givs which depend on this
4727          biv have been strength reduced.
4728          We can't (currently) eliminate the biv unless this is so.  */
4729       all_reduced = 1;
4730
4731       /* Check each giv in this class to see if we will benefit by reducing
4732          it.  Skip giv's combined with others.  */
4733       for (v = bl->giv; v; v = v->next_iv)
4734         {
4735           struct induction *tv;
4736
4737           if (v->ignore || v->same)
4738             continue;
4739
4740           benefit = v->benefit;
4741
4742           /* Reduce benefit if not replaceable, since we will insert
4743              a move-insn to replace the insn that calculates this giv.
4744              Don't do this unless the giv is a user variable, since it
4745              will often be marked non-replaceable because of the duplication
4746              of the exit code outside the loop.  In such a case, the copies
4747              we insert are dead and will be deleted.  So they don't have
4748              a cost.  Similar situations exist.  */
4749           /* ??? The new final_[bg]iv_value code does a much better job
4750              of finding replaceable giv's, and hence this code may no longer
4751              be necessary.  */
4752           if (! v->replaceable && ! bl->eliminable
4753               && REG_USERVAR_P (v->dest_reg))
4754             benefit -= copy_cost;
4755
4756           /* Decrease the benefit to count the add-insns that we will
4757              insert to increment the reduced reg for the giv.  */
4758           benefit -= add_cost * bl->biv_count;
4759
4760           /* Decide whether to strength-reduce this giv or to leave the code
4761              unchanged (recompute it from the biv each time it is used).
4762              This decision can be made independently for each giv.  */
4763
4764 #ifdef AUTO_INC_DEC
4765           /* Attempt to guess whether autoincrement will handle some of the
4766              new add insns; if so, increase BENEFIT (undo the subtraction of
4767              add_cost that was done above).  */
4768           if (v->giv_type == DEST_ADDR
4769               && GET_CODE (v->mult_val) == CONST_INT)
4770             {
4771               if (HAVE_POST_INCREMENT
4772                   && INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4773                 benefit += add_cost * bl->biv_count;
4774               else if (HAVE_PRE_INCREMENT
4775                        && INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4776                 benefit += add_cost * bl->biv_count;
4777               else if (HAVE_POST_DECREMENT
4778                        && -INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4779                 benefit += add_cost * bl->biv_count;
4780               else if (HAVE_PRE_DECREMENT
4781                        && -INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4782                 benefit += add_cost * bl->biv_count;
4783             }
4784 #endif
4785
4786           /* If an insn is not to be strength reduced, then set its ignore
4787              flag, and clear all_reduced.  */
4788
4789           /* A giv that depends on a reversed biv must be reduced if it is
4790              used after the loop exit, otherwise, it would have the wrong
4791              value after the loop exit.  To make it simple, just reduce all
4792              of such giv's whether or not we know they are used after the loop
4793              exit.  */
4794
4795           if ( ! flag_reduce_all_givs && v->lifetime * threshold * benefit < insn_count
4796               && ! bl->reversed )
4797             {
4798               if (loop_dump_stream)
4799                 fprintf (loop_dump_stream,
4800                          "giv of insn %d not worth while, %d vs %d.\n",
4801                          INSN_UID (v->insn),
4802                          v->lifetime * threshold * benefit, insn_count);
4803               v->ignore = 1;
4804               all_reduced = 0;
4805             }
4806           else
4807             {
4808               /* Check that we can increment the reduced giv without a
4809                  multiply insn.  If not, reject it.  */
4810
4811               for (tv = bl->biv; tv; tv = tv->next_iv)
4812                 if (tv->mult_val == const1_rtx
4813                     && ! product_cheap_p (tv->add_val, v->mult_val))
4814                   {
4815                     if (loop_dump_stream)
4816                       fprintf (loop_dump_stream,
4817                                "giv of insn %d: would need a multiply.\n",
4818                                INSN_UID (v->insn));
4819                     v->ignore = 1;
4820                     all_reduced = 0;
4821                     break;
4822                   }
4823             }
4824         }
4825
4826       /* Check for givs whose first use is their definition and whose
4827          last use is the definition of another giv.  If so, it is likely
4828          dead and should not be used to derive another giv nor to
4829          eliminate a biv.  */
4830       for (v = bl->giv; v; v = v->next_iv)
4831         {
4832           if (v->ignore
4833               || (v->same && v->same->ignore))
4834             continue;
4835
4836           if (v->last_use)
4837             {
4838               struct induction *v1;
4839
4840               for (v1 = bl->giv; v1; v1 = v1->next_iv)
4841                 if (v->last_use == v1->insn)
4842                   v->maybe_dead = 1;
4843             }
4844           else if (v->giv_type == DEST_REG
4845               && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4846             {
4847               struct induction *v1;
4848
4849               for (v1 = bl->giv; v1; v1 = v1->next_iv)
4850                 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4851                   v->maybe_dead = 1;
4852             }
4853         }
4854
4855       /* Now that we know which givs will be reduced, try to rearrange the
4856          combinations to reduce register pressure.
4857          recombine_givs calls find_life_end, which needs reg_iv_type and
4858          reg_iv_info to be valid for all pseudos.  We do the necessary
4859          reallocation here since it allows to check if there are still
4860          more bivs to process.  */
4861       nregs = max_reg_num ();
4862       if (nregs > reg_iv_type->num_elements)
4863         {
4864           /* If there are still more bivs to process, allocate some slack
4865              space so that we're not constantly reallocating these arrays.  */
4866           if (bl->next)
4867             nregs += nregs / 4;
4868           /* Reallocate reg_iv_type and reg_iv_info.  */
4869           VARRAY_GROW (reg_iv_type, nregs);
4870           VARRAY_GROW (reg_iv_info, nregs);
4871         }
4872       recombine_givs (loop, bl, unroll_p);
4873
4874       /* Reduce each giv that we decided to reduce.  */
4875
4876       for (v = bl->giv; v; v = v->next_iv)
4877         {
4878           struct induction *tv;
4879           if (! v->ignore && v->same == 0)
4880             {
4881               int auto_inc_opt = 0;
4882
4883               /* If the code for derived givs immediately below has already
4884                  allocated a new_reg, we must keep it.  */
4885               if (! v->new_reg)
4886                 v->new_reg = gen_reg_rtx (v->mode);
4887
4888               if (v->derived_from)
4889                 {
4890                   struct induction *d = v->derived_from;
4891
4892                   /* In case d->dest_reg is not replaceable, we have
4893                      to replace it in v->insn now.  */
4894                   if (! d->new_reg)
4895                     d->new_reg = gen_reg_rtx (d->mode);
4896                   PATTERN (v->insn)
4897                     = replace_rtx (PATTERN (v->insn), d->dest_reg, d->new_reg);
4898                   PATTERN (v->insn)
4899                     = replace_rtx (PATTERN (v->insn), v->dest_reg, v->new_reg);
4900                   /* For each place where the biv is incremented, add an
4901                      insn to set the new, reduced reg for the giv.
4902                      We used to do this only for biv_count != 1, but
4903                      this fails when there is a giv after a single biv
4904                      increment, e.g. when the last giv was expressed as
4905                      pre-decrement.  */
4906                   for (tv = bl->biv; tv; tv = tv->next_iv)
4907                     {
4908                       /* We always emit reduced giv increments before the
4909                          biv increment when bl->biv_count != 1.  So by
4910                          emitting the add insns for derived givs after the
4911                          biv increment, they pick up the updated value of
4912                          the reduced giv.
4913                          If the reduced giv is processed with
4914                          auto_inc_opt == 1, then it is incremented earlier
4915                          than the biv, hence we'll still pick up the right
4916                          value.
4917                          If it's processed with auto_inc_opt == -1,
4918                          that implies that the biv increment is before the
4919                          first reduced giv's use.  The derived giv's lifetime
4920                          is after the reduced giv's lifetime, hence in this
4921                          case, the biv increment doesn't matter.  */
4922                       emit_insn_after (copy_rtx (PATTERN (v->insn)), tv->insn);
4923                     }
4924                   continue;
4925                 }
4926
4927 #ifdef AUTO_INC_DEC
4928               /* If the target has auto-increment addressing modes, and
4929                  this is an address giv, then try to put the increment
4930                  immediately after its use, so that flow can create an
4931                  auto-increment addressing mode.  */
4932               if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4933                   && bl->biv->always_executed && ! bl->biv->maybe_multiple
4934                   /* We don't handle reversed biv's because bl->biv->insn
4935                      does not have a valid INSN_LUID.  */
4936                   && ! bl->reversed
4937                   && v->always_executed && ! v->maybe_multiple
4938                   && INSN_UID (v->insn) < max_uid_for_loop)
4939                 {
4940                   /* If other giv's have been combined with this one, then
4941                      this will work only if all uses of the other giv's occur
4942                      before this giv's insn.  This is difficult to check.
4943
4944                      We simplify this by looking for the common case where
4945                      there is one DEST_REG giv, and this giv's insn is the
4946                      last use of the dest_reg of that DEST_REG giv.  If the
4947                      increment occurs after the address giv, then we can
4948                      perform the optimization.  (Otherwise, the increment
4949                      would have to go before other_giv, and we would not be
4950                      able to combine it with the address giv to get an
4951                      auto-inc address.)  */
4952                   if (v->combined_with)
4953                     {
4954                       struct induction *other_giv = 0;
4955
4956                       for (tv = bl->giv; tv; tv = tv->next_iv)
4957                         if (tv->same == v)
4958                           {
4959                             if (other_giv)
4960                               break;
4961                             else
4962                               other_giv = tv;
4963                           }
4964                       if (! tv && other_giv
4965                           && REGNO (other_giv->dest_reg) < max_reg_before_loop
4966                           && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4967                               == INSN_UID (v->insn))
4968                           && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4969                         auto_inc_opt = 1;
4970                     }
4971                   /* Check for case where increment is before the address
4972                      giv.  Do this test in "loop order".  */
4973                   else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4974                             && (INSN_LUID (v->insn) < INSN_LUID (loop_scan_start)
4975                                 || (INSN_LUID (bl->biv->insn)
4976                                     > INSN_LUID (loop_scan_start))))
4977                            || (INSN_LUID (v->insn) < INSN_LUID (loop_scan_start)
4978                                && (INSN_LUID (loop_scan_start)
4979                                    < INSN_LUID (bl->biv->insn))))
4980                     auto_inc_opt = -1;
4981                   else
4982                     auto_inc_opt = 1;
4983
4984 #ifdef HAVE_cc0
4985                   {
4986                     rtx prev;
4987
4988                     /* We can't put an insn immediately after one setting
4989                        cc0, or immediately before one using cc0.  */
4990                     if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4991                         || (auto_inc_opt == -1
4992                             && (prev = prev_nonnote_insn (v->insn)) != 0
4993                             && GET_RTX_CLASS (GET_CODE (prev)) == 'i'
4994                             && sets_cc0_p (PATTERN (prev))))
4995                       auto_inc_opt = 0;
4996                   }
4997 #endif
4998
4999                   if (auto_inc_opt)
5000                     v->auto_inc_opt = 1;
5001                 }
5002 #endif
5003
5004               /* For each place where the biv is incremented, add an insn
5005                  to increment the new, reduced reg for the giv.  */
5006               for (tv = bl->biv; tv; tv = tv->next_iv)
5007                 {
5008                   rtx insert_before;
5009
5010                   if (! auto_inc_opt)
5011                     insert_before = tv->insn;
5012                   else if (auto_inc_opt == 1)
5013                     insert_before = NEXT_INSN (v->insn);
5014                   else
5015                     insert_before = v->insn;
5016
5017                   if (tv->mult_val == const1_rtx)
5018                     emit_iv_add_mult (tv->add_val, v->mult_val,
5019                                       v->new_reg, v->new_reg, insert_before);
5020                   else /* tv->mult_val == const0_rtx */
5021                     /* A multiply is acceptable here
5022                        since this is presumed to be seldom executed.  */
5023                     emit_iv_add_mult (tv->add_val, v->mult_val,
5024                                       v->add_val, v->new_reg, insert_before);
5025                 }
5026
5027               /* Add code at loop start to initialize giv's reduced reg.  */
5028
5029               emit_iv_add_mult (bl->initial_value, v->mult_val,
5030                                 v->add_val, v->new_reg, loop_start);
5031             }
5032         }
5033
5034       /* Rescan all givs.  If a giv is the same as a giv not reduced, mark it
5035          as not reduced.
5036          
5037          For each giv register that can be reduced now: if replaceable,
5038          substitute reduced reg wherever the old giv occurs;
5039          else add new move insn "giv_reg = reduced_reg".  */
5040
5041       for (v = bl->giv; v; v = v->next_iv)
5042         {
5043           if (v->same && v->same->ignore)
5044             v->ignore = 1;
5045
5046           if (v->ignore)
5047             continue;
5048
5049           /* Update expression if this was combined, in case other giv was
5050              replaced.  */
5051           if (v->same)
5052             v->new_reg = replace_rtx (v->new_reg,
5053                                       v->same->dest_reg, v->same->new_reg);
5054
5055           if (v->giv_type == DEST_ADDR)
5056             /* Store reduced reg as the address in the memref where we found
5057                this giv.  */
5058             validate_change (v->insn, v->location, v->new_reg, 0);
5059           else if (v->replaceable)
5060             {
5061               reg_map[REGNO (v->dest_reg)] = v->new_reg;
5062
5063 #if 0
5064               /* I can no longer duplicate the original problem.  Perhaps
5065                  this is unnecessary now?  */
5066
5067               /* Replaceable; it isn't strictly necessary to delete the old
5068                  insn and emit a new one, because v->dest_reg is now dead.
5069
5070                  However, especially when unrolling loops, the special
5071                  handling for (set REG0 REG1) in the second cse pass may
5072                  make v->dest_reg live again.  To avoid this problem, emit
5073                  an insn to set the original giv reg from the reduced giv.
5074                  We can not delete the original insn, since it may be part
5075                  of a LIBCALL, and the code in flow that eliminates dead
5076                  libcalls will fail if it is deleted.  */
5077               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
5078                                v->insn);
5079 #endif
5080             }
5081           else
5082             {
5083               /* Not replaceable; emit an insn to set the original giv reg from
5084                  the reduced giv, same as above.  */
5085               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
5086                                v->insn);
5087             }
5088
5089           /* When a loop is reversed, givs which depend on the reversed
5090              biv, and which are live outside the loop, must be set to their
5091              correct final value.  This insn is only needed if the giv is
5092              not replaceable.  The correct final value is the same as the
5093              value that the giv starts the reversed loop with.  */
5094           if (bl->reversed && ! v->replaceable)
5095             emit_iv_add_mult (bl->initial_value, v->mult_val,
5096                               v->add_val, v->dest_reg, end_insert_before);
5097           else if (v->final_value)
5098             {
5099               rtx insert_before;
5100
5101               /* If the loop has multiple exits, emit the insn before the
5102                  loop to ensure that it will always be executed no matter
5103                  how the loop exits.  Otherwise, emit the insn after the loop,
5104                  since this is slightly more efficient.  */
5105               if (loop->exit_count)
5106                 insert_before = loop_start;
5107               else
5108                 insert_before = end_insert_before;
5109               emit_insn_before (gen_move_insn (v->dest_reg, v->final_value),
5110                                 insert_before);
5111
5112 #if 0
5113               /* If the insn to set the final value of the giv was emitted
5114                  before the loop, then we must delete the insn inside the loop
5115                  that sets it.  If this is a LIBCALL, then we must delete
5116                  every insn in the libcall.  Note, however, that
5117                  final_giv_value will only succeed when there are multiple
5118                  exits if the giv is dead at each exit, hence it does not
5119                  matter that the original insn remains because it is dead
5120                  anyways.  */
5121               /* Delete the insn inside the loop that sets the giv since
5122                  the giv is now set before (or after) the loop.  */
5123               delete_insn (v->insn);
5124 #endif
5125             }
5126
5127           if (loop_dump_stream)
5128             {
5129               fprintf (loop_dump_stream, "giv at %d reduced to ",
5130                        INSN_UID (v->insn));
5131               print_rtl (loop_dump_stream, v->new_reg);
5132               fprintf (loop_dump_stream, "\n");
5133             }
5134         }
5135
5136       /* All the givs based on the biv bl have been reduced if they
5137          merit it.  */
5138
5139       /* For each giv not marked as maybe dead that has been combined with a
5140          second giv, clear any "maybe dead" mark on that second giv.
5141          v->new_reg will either be or refer to the register of the giv it
5142          combined with.
5143
5144          Doing this clearing avoids problems in biv elimination where a
5145          giv's new_reg is a complex value that can't be put in the insn but
5146          the giv combined with (with a reg as new_reg) is marked maybe_dead.
5147          Since the register will be used in either case, we'd prefer it be
5148          used from the simpler giv.  */
5149
5150       for (v = bl->giv; v; v = v->next_iv)
5151         if (! v->maybe_dead && v->same)
5152           v->same->maybe_dead = 0;
5153
5154       /* Try to eliminate the biv, if it is a candidate.
5155          This won't work if ! all_reduced,
5156          since the givs we planned to use might not have been reduced.
5157
5158          We have to be careful that we didn't initially think we could eliminate
5159          this biv because of a giv that we now think may be dead and shouldn't
5160          be used as a biv replacement.  
5161
5162          Also, there is the possibility that we may have a giv that looks
5163          like it can be used to eliminate a biv, but the resulting insn
5164          isn't valid.  This can happen, for example, on the 88k, where a 
5165          JUMP_INSN can compare a register only with zero.  Attempts to
5166          replace it with a compare with a constant will fail.
5167
5168          Note that in cases where this call fails, we may have replaced some
5169          of the occurrences of the biv with a giv, but no harm was done in
5170          doing so in the rare cases where it can occur.  */
5171
5172       if (all_reduced == 1 && bl->eliminable
5173           && maybe_eliminate_biv (loop, bl, 1, threshold, insn_count))
5174         {
5175           /* ?? If we created a new test to bypass the loop entirely,
5176              or otherwise drop straight in, based on this test, then
5177              we might want to rewrite it also.  This way some later
5178              pass has more hope of removing the initialization of this
5179              biv entirely.  */
5180
5181           /* If final_value != 0, then the biv may be used after loop end
5182              and we must emit an insn to set it just in case.
5183
5184              Reversed bivs already have an insn after the loop setting their
5185              value, so we don't need another one.  We can't calculate the
5186              proper final value for such a biv here anyways.  */
5187           if (final_value != 0 && ! bl->reversed)
5188             {
5189               rtx insert_before;
5190
5191               /* If the loop has multiple exits, emit the insn before the
5192                  loop to ensure that it will always be executed no matter
5193                  how the loop exits.  Otherwise, emit the insn after the
5194                  loop, since this is slightly more efficient.  */
5195               if (loop->exit_count)
5196                 insert_before = loop_start;
5197               else
5198                 insert_before = end_insert_before;
5199
5200               emit_insn_before (gen_move_insn (bl->biv->dest_reg, final_value),
5201                                 end_insert_before);
5202             }
5203
5204 #if 0
5205           /* Delete all of the instructions inside the loop which set
5206              the biv, as they are all dead.  If is safe to delete them,
5207              because an insn setting a biv will never be part of a libcall.  */
5208           /* However, deleting them will invalidate the regno_last_uid info,
5209              so keeping them around is more convenient.  Final_biv_value
5210              will only succeed when there are multiple exits if the biv
5211              is dead at each exit, hence it does not matter that the original
5212              insn remains, because it is dead anyways.  */
5213           for (v = bl->biv; v; v = v->next_iv)
5214             delete_insn (v->insn);
5215 #endif
5216
5217           if (loop_dump_stream)
5218             fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
5219                      bl->regno);
5220         }
5221     }
5222
5223   /* Go through all the instructions in the loop, making all the
5224      register substitutions scheduled in REG_MAP.  */
5225
5226   for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
5227     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5228         || GET_CODE (p) == CALL_INSN)
5229       {
5230         replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
5231         replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
5232         INSN_CODE (p) = -1;
5233       }
5234
5235   if (loop_info->n_iterations > 0)
5236     {
5237       /* When we completely unroll a loop we will likely not need the increment
5238          of the loop BIV and we will not need the conditional branch at the
5239          end of the loop.  */
5240       unrolled_insn_copies = insn_count - 2;
5241
5242 #ifdef HAVE_cc0
5243       /* When we completely unroll a loop on a HAVE_cc0 machine we will not
5244          need the comparison before the conditional branch at the end of the
5245          loop.  */
5246       unrolled_insn_copies -= 1;
5247 #endif
5248
5249       /* We'll need one copy for each loop iteration.  */
5250       unrolled_insn_copies *= loop_info->n_iterations;
5251
5252       /* A little slop to account for the ability to remove initialization
5253          code, better CSE, and other secondary benefits of completely
5254          unrolling some loops.  */
5255       unrolled_insn_copies -= 1;
5256
5257       /* Clamp the value.  */
5258       if (unrolled_insn_copies < 0)
5259         unrolled_insn_copies = 0;
5260     }
5261   
5262   /* Unroll loops from within strength reduction so that we can use the
5263      induction variable information that strength_reduce has already
5264      collected.  Always unroll loops that would be as small or smaller
5265      unrolled than when rolled.  */
5266   if (unroll_p
5267       || (loop_info->n_iterations > 0
5268           && unrolled_insn_copies <= insn_count))
5269     unroll_loop (loop, insn_count, end_insert_before, 1);
5270
5271 #ifdef HAVE_decrement_and_branch_on_count
5272   /* Instrument the loop with BCT insn.  */
5273   if (HAVE_decrement_and_branch_on_count && bct_p
5274       && flag_branch_on_count_reg)
5275     insert_bct (loop);
5276 #endif  /* HAVE_decrement_and_branch_on_count */
5277
5278   if (loop_dump_stream)
5279     fprintf (loop_dump_stream, "\n");
5280
5281 egress:
5282   VARRAY_FREE (reg_iv_type);
5283   VARRAY_FREE (reg_iv_info);
5284   free (reg_biv_class);
5285   if (reg_map)
5286     free (reg_map);
5287 }
5288 \f
5289 /* Return 1 if X is a valid source for an initial value (or as value being
5290    compared against in an initial test).
5291
5292    X must be either a register or constant and must not be clobbered between
5293    the current insn and the start of the loop.
5294
5295    INSN is the insn containing X.  */
5296
5297 static int
5298 valid_initial_value_p (x, insn, call_seen, loop_start)
5299      rtx x;
5300      rtx insn;
5301      int call_seen;
5302      rtx loop_start;
5303 {
5304   if (CONSTANT_P (x))
5305     return 1;
5306
5307   /* Only consider pseudos we know about initialized in insns whose luids
5308      we know.  */
5309   if (GET_CODE (x) != REG
5310       || REGNO (x) >= max_reg_before_loop)
5311     return 0;
5312
5313   /* Don't use call-clobbered registers across a call which clobbers it.  On
5314      some machines, don't use any hard registers at all.  */
5315   if (REGNO (x) < FIRST_PSEUDO_REGISTER
5316       && (SMALL_REGISTER_CLASSES
5317           || (call_used_regs[REGNO (x)] && call_seen)))
5318     return 0;
5319
5320   /* Don't use registers that have been clobbered before the start of the
5321      loop.  */
5322   if (reg_set_between_p (x, insn, loop_start))
5323     return 0;
5324
5325   return 1;
5326 }
5327 \f
5328 /* Scan X for memory refs and check each memory address
5329    as a possible giv.  INSN is the insn whose pattern X comes from.
5330    NOT_EVERY_ITERATION is 1 if the insn might not be executed during
5331    every loop iteration.  MAYBE_MULTIPLE is 1 if the insn might be executed
5332    more thanonce in each loop iteration.  */
5333
5334 static void
5335 find_mem_givs (loop, x, insn, not_every_iteration, maybe_multiple)
5336      const struct loop *loop;
5337      rtx x;
5338      rtx insn;
5339      int not_every_iteration, maybe_multiple;
5340 {
5341   register int i, j;
5342   register enum rtx_code code;
5343   register const char *fmt;
5344
5345   if (x == 0)
5346     return;
5347
5348   code = GET_CODE (x);
5349   switch (code)
5350     {
5351     case REG:
5352     case CONST_INT:
5353     case CONST:
5354     case CONST_DOUBLE:
5355     case SYMBOL_REF:
5356     case LABEL_REF:
5357     case PC:
5358     case CC0:
5359     case ADDR_VEC:
5360     case ADDR_DIFF_VEC:
5361     case USE:
5362     case CLOBBER:
5363       return;
5364
5365     case MEM:
5366       {
5367         rtx src_reg;
5368         rtx add_val;
5369         rtx mult_val;
5370         int benefit;
5371
5372         /* This code used to disable creating GIVs with mult_val == 1 and
5373            add_val == 0.  However, this leads to lost optimizations when 
5374            it comes time to combine a set of related DEST_ADDR GIVs, since
5375            this one would not be seen.   */
5376
5377         if (general_induction_var (loop, XEXP (x, 0), &src_reg, &add_val,
5378                                    &mult_val, 1, &benefit))
5379           {
5380             /* Found one; record it.  */
5381             struct induction *v
5382               = (struct induction *) oballoc (sizeof (struct induction));
5383
5384             record_giv (loop, v, insn, src_reg, addr_placeholder, mult_val,
5385                         add_val, benefit, DEST_ADDR, not_every_iteration,
5386                         maybe_multiple, &XEXP (x, 0));
5387
5388             v->mem_mode = GET_MODE (x);
5389           }
5390       }
5391       return;
5392
5393     default:
5394       break;
5395     }
5396
5397   /* Recursively scan the subexpressions for other mem refs.  */
5398
5399   fmt = GET_RTX_FORMAT (code);
5400   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5401     if (fmt[i] == 'e')
5402       find_mem_givs (loop, XEXP (x, i), insn, not_every_iteration,
5403                      maybe_multiple);
5404     else if (fmt[i] == 'E')
5405       for (j = 0; j < XVECLEN (x, i); j++)
5406         find_mem_givs (loop, XVECEXP (x, i, j), insn, not_every_iteration,
5407                        maybe_multiple);
5408 }
5409 \f
5410 /* Fill in the data about one biv update.
5411    V is the `struct induction' in which we record the biv.  (It is
5412    allocated by the caller, with alloca.)
5413    INSN is the insn that sets it.
5414    DEST_REG is the biv's reg.
5415
5416    MULT_VAL is const1_rtx if the biv is being incremented here, in which case
5417    INC_VAL is the increment.  Otherwise, MULT_VAL is const0_rtx and the biv is
5418    being set to INC_VAL.
5419
5420    NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
5421    executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
5422    can be executed more than once per iteration.  If MAYBE_MULTIPLE
5423    and NOT_EVERY_ITERATION are both zero, we know that the biv update is
5424    executed exactly once per iteration.  */
5425
5426 static void
5427 record_biv (v, insn, dest_reg, inc_val, mult_val, location,
5428             not_every_iteration, maybe_multiple, multi_insn_incr)
5429      struct induction *v;
5430      rtx insn;
5431      rtx dest_reg;
5432      rtx inc_val;
5433      rtx mult_val;
5434      rtx *location;
5435      int not_every_iteration;
5436      int maybe_multiple;
5437      int multi_insn_incr;
5438 {
5439   struct iv_class *bl;
5440
5441   v->insn = insn;
5442   v->src_reg = dest_reg;
5443   v->dest_reg = dest_reg;
5444   v->mult_val = mult_val;
5445   v->add_val = inc_val;
5446   v->location = location;
5447   v->mode = GET_MODE (dest_reg);
5448   v->always_computable = ! not_every_iteration;
5449   v->always_executed = ! not_every_iteration;
5450   v->maybe_multiple = maybe_multiple;
5451   v->multi_insn_incr = multi_insn_incr;
5452
5453   /* Add this to the reg's iv_class, creating a class
5454      if this is the first incrementation of the reg.  */
5455
5456   bl = reg_biv_class[REGNO (dest_reg)];
5457   if (bl == 0)
5458     {
5459       /* Create and initialize new iv_class.  */
5460
5461       bl = (struct iv_class *) oballoc (sizeof (struct iv_class));
5462
5463       bl->regno = REGNO (dest_reg);
5464       bl->biv = 0;
5465       bl->giv = 0;
5466       bl->biv_count = 0;
5467       bl->giv_count = 0;
5468
5469       /* Set initial value to the reg itself.  */
5470       bl->initial_value = dest_reg;
5471       /* We haven't seen the initializing insn yet */
5472       bl->init_insn = 0;
5473       bl->init_set = 0;
5474       bl->initial_test = 0;
5475       bl->incremented = 0;
5476       bl->eliminable = 0;
5477       bl->nonneg = 0;
5478       bl->reversed = 0;
5479       bl->total_benefit = 0;
5480
5481       /* Add this class to loop_iv_list.  */
5482       bl->next = loop_iv_list;
5483       loop_iv_list = bl;
5484
5485       /* Put it in the array of biv register classes.  */
5486       reg_biv_class[REGNO (dest_reg)] = bl;
5487     }
5488
5489   /* Update IV_CLASS entry for this biv.  */
5490   v->next_iv = bl->biv;
5491   bl->biv = v;
5492   bl->biv_count++;
5493   if (mult_val == const1_rtx)
5494     bl->incremented = 1;
5495
5496   if (loop_dump_stream)
5497     {
5498       fprintf (loop_dump_stream,
5499                "Insn %d: possible biv, reg %d,",
5500                INSN_UID (insn), REGNO (dest_reg));
5501       if (GET_CODE (inc_val) == CONST_INT)
5502         {
5503           fprintf (loop_dump_stream, " const =");
5504           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (inc_val));
5505           fputc ('\n', loop_dump_stream);
5506         }
5507       else
5508         {
5509           fprintf (loop_dump_stream, " const = ");
5510           print_rtl (loop_dump_stream, inc_val);
5511           fprintf (loop_dump_stream, "\n");
5512         }
5513     }
5514 }
5515 \f
5516 /* Fill in the data about one giv.
5517    V is the `struct induction' in which we record the giv.  (It is
5518    allocated by the caller, with alloca.)
5519    INSN is the insn that sets it.
5520    BENEFIT estimates the savings from deleting this insn.
5521    TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
5522    into a register or is used as a memory address.
5523
5524    SRC_REG is the biv reg which the giv is computed from.
5525    DEST_REG is the giv's reg (if the giv is stored in a reg).
5526    MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
5527    LOCATION points to the place where this giv's value appears in INSN.  */
5528
5529 static void
5530 record_giv (loop, v, insn, src_reg, dest_reg, mult_val, add_val, benefit,
5531             type, not_every_iteration, maybe_multiple, location)
5532      const struct loop *loop;
5533      struct induction *v;
5534      rtx insn;
5535      rtx src_reg;
5536      rtx dest_reg;
5537      rtx mult_val, add_val;
5538      int benefit;
5539      enum g_types type;
5540      int not_every_iteration, maybe_multiple;
5541      rtx *location;
5542 {
5543   struct induction *b;
5544   struct iv_class *bl;
5545   rtx set = single_set (insn);
5546
5547   v->insn = insn;
5548   v->src_reg = src_reg;
5549   v->giv_type = type;
5550   v->dest_reg = dest_reg;
5551   v->mult_val = mult_val;
5552   v->add_val = add_val;
5553   v->benefit = benefit;
5554   v->location = location;
5555   v->cant_derive = 0;
5556   v->combined_with = 0;
5557   v->maybe_multiple = maybe_multiple;
5558   v->multi_insn_incr = 0;
5559   v->maybe_dead = 0;
5560   v->derive_adjustment = 0;
5561   v->same = 0;
5562   v->ignore = 0;
5563   v->new_reg = 0;
5564   v->final_value = 0;
5565   v->same_insn = 0;
5566   v->auto_inc_opt = 0;
5567   v->unrolled = 0;
5568   v->shared = 0;
5569   v->derived_from = 0;
5570   v->last_use = 0;
5571
5572   /* The v->always_computable field is used in update_giv_derive, to
5573      determine whether a giv can be used to derive another giv.  For a
5574      DEST_REG giv, INSN computes a new value for the giv, so its value
5575      isn't computable if INSN insn't executed every iteration.
5576      However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
5577      it does not compute a new value.  Hence the value is always computable
5578      regardless of whether INSN is executed each iteration.  */
5579
5580   if (type == DEST_ADDR)
5581     v->always_computable = 1;
5582   else
5583     v->always_computable = ! not_every_iteration;
5584
5585   v->always_executed = ! not_every_iteration;
5586
5587   if (type == DEST_ADDR)
5588     {
5589       v->mode = GET_MODE (*location);
5590       v->lifetime = 1;
5591     }
5592   else /* type == DEST_REG */
5593     {
5594       v->mode = GET_MODE (SET_DEST (set));
5595
5596       v->lifetime = (uid_luid[REGNO_LAST_UID (REGNO (dest_reg))]
5597                      - uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))]);
5598
5599       /* If the lifetime is zero, it means that this register is
5600          really a dead store.  So mark this as a giv that can be
5601          ignored.  This will not prevent the biv from being eliminated.  */
5602       if (v->lifetime == 0)
5603         v->ignore = 1;
5604
5605       REG_IV_TYPE (REGNO (dest_reg)) = GENERAL_INDUCT;
5606       REG_IV_INFO (REGNO (dest_reg)) = v;
5607     }
5608
5609   /* Add the giv to the class of givs computed from one biv.  */
5610
5611   bl = reg_biv_class[REGNO (src_reg)];
5612   if (bl)
5613     {
5614       v->next_iv = bl->giv;
5615       bl->giv = v;
5616       /* Don't count DEST_ADDR.  This is supposed to count the number of
5617          insns that calculate givs.  */
5618       if (type == DEST_REG)
5619         bl->giv_count++;
5620       bl->total_benefit += benefit;
5621     }
5622   else
5623     /* Fatal error, biv missing for this giv?  */
5624     abort ();
5625
5626   if (type == DEST_ADDR)
5627     v->replaceable = 1;
5628   else
5629     {
5630       /* The giv can be replaced outright by the reduced register only if all
5631          of the following conditions are true:
5632          - the insn that sets the giv is always executed on any iteration
5633            on which the giv is used at all
5634            (there are two ways to deduce this:
5635             either the insn is executed on every iteration,
5636             or all uses follow that insn in the same basic block),
5637          - the giv is not used outside the loop
5638          - no assignments to the biv occur during the giv's lifetime.  */
5639
5640       if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
5641           /* Previous line always fails if INSN was moved by loop opt.  */
5642           && uid_luid[REGNO_LAST_UID (REGNO (dest_reg))] 
5643           < INSN_LUID (loop->end)
5644           && (! not_every_iteration
5645               || last_use_this_basic_block (dest_reg, insn)))
5646         {
5647           /* Now check that there are no assignments to the biv within the
5648              giv's lifetime.  This requires two separate checks.  */
5649
5650           /* Check each biv update, and fail if any are between the first
5651              and last use of the giv.
5652              
5653              If this loop contains an inner loop that was unrolled, then
5654              the insn modifying the biv may have been emitted by the loop
5655              unrolling code, and hence does not have a valid luid.  Just
5656              mark the biv as not replaceable in this case.  It is not very
5657              useful as a biv, because it is used in two different loops.
5658              It is very unlikely that we would be able to optimize the giv
5659              using this biv anyways.  */
5660
5661           v->replaceable = 1;
5662           for (b = bl->biv; b; b = b->next_iv)
5663             {
5664               if (INSN_UID (b->insn) >= max_uid_for_loop
5665                   || ((uid_luid[INSN_UID (b->insn)]
5666                        >= uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))])
5667                       && (uid_luid[INSN_UID (b->insn)]
5668                           <= uid_luid[REGNO_LAST_UID (REGNO (dest_reg))])))
5669                 {
5670                   v->replaceable = 0;
5671                   v->not_replaceable = 1;
5672                   break;
5673                 }
5674             }
5675
5676           /* If there are any backwards branches that go from after the
5677              biv update to before it, then this giv is not replaceable.  */
5678           if (v->replaceable)
5679             for (b = bl->biv; b; b = b->next_iv)
5680               if (back_branch_in_range_p (loop, b->insn))
5681                 {
5682                   v->replaceable = 0;
5683                   v->not_replaceable = 1;
5684                   break;
5685                 }
5686         }
5687       else
5688         {
5689           /* May still be replaceable, we don't have enough info here to
5690              decide.  */
5691           v->replaceable = 0;
5692           v->not_replaceable = 0;
5693         }
5694     }
5695
5696   /* Record whether the add_val contains a const_int, for later use by
5697      combine_givs.  */
5698   {
5699     rtx tem = add_val;
5700
5701     v->no_const_addval = 1;
5702     if (tem == const0_rtx)
5703       ;
5704     else if (GET_CODE (tem) == CONST_INT)
5705       v->no_const_addval = 0;
5706     else if (GET_CODE (tem) == PLUS)
5707       {
5708         while (1)
5709           {
5710             if (GET_CODE (XEXP (tem, 0)) == PLUS)
5711               tem = XEXP (tem, 0);
5712             else if (GET_CODE (XEXP (tem, 1)) == PLUS)
5713               tem = XEXP (tem, 1);
5714             else
5715               break;
5716           }
5717         if (GET_CODE (XEXP (tem, 1)) == CONST_INT)
5718           v->no_const_addval = 0;
5719       }
5720   }
5721
5722   if (loop_dump_stream)
5723     {
5724       if (type == DEST_REG)
5725         fprintf (loop_dump_stream, "Insn %d: giv reg %d",
5726                  INSN_UID (insn), REGNO (dest_reg));
5727       else
5728         fprintf (loop_dump_stream, "Insn %d: dest address",
5729                  INSN_UID (insn));
5730
5731       fprintf (loop_dump_stream, " src reg %d benefit %d",
5732                REGNO (src_reg), v->benefit);
5733       fprintf (loop_dump_stream, " lifetime %d",
5734                v->lifetime);
5735
5736       if (v->replaceable)
5737         fprintf (loop_dump_stream, " replaceable");
5738
5739       if (v->no_const_addval)
5740         fprintf (loop_dump_stream, " ncav");
5741
5742       if (GET_CODE (mult_val) == CONST_INT)
5743         {
5744           fprintf (loop_dump_stream, " mult ");
5745           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (mult_val));
5746         }
5747       else
5748         {
5749           fprintf (loop_dump_stream, " mult ");
5750           print_rtl (loop_dump_stream, mult_val);
5751         }
5752
5753       if (GET_CODE (add_val) == CONST_INT)
5754         {
5755           fprintf (loop_dump_stream, " add ");
5756           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (add_val));
5757         }
5758       else
5759         {
5760           fprintf (loop_dump_stream, " add ");
5761           print_rtl (loop_dump_stream, add_val);
5762         }
5763     }
5764
5765   if (loop_dump_stream)
5766     fprintf (loop_dump_stream, "\n");
5767
5768 }
5769
5770
5771 /* All this does is determine whether a giv can be made replaceable because
5772    its final value can be calculated.  This code can not be part of record_giv
5773    above, because final_giv_value requires that the number of loop iterations
5774    be known, and that can not be accurately calculated until after all givs
5775    have been identified.  */
5776
5777 static void
5778 check_final_value (loop, v)
5779      const struct loop *loop;
5780      struct induction *v;
5781 {
5782   struct iv_class *bl;
5783   rtx final_value = 0;
5784
5785   bl = reg_biv_class[REGNO (v->src_reg)];
5786
5787   /* DEST_ADDR givs will never reach here, because they are always marked
5788      replaceable above in record_giv.  */
5789
5790   /* The giv can be replaced outright by the reduced register only if all
5791      of the following conditions are true:
5792      - the insn that sets the giv is always executed on any iteration
5793        on which the giv is used at all
5794        (there are two ways to deduce this:
5795         either the insn is executed on every iteration,
5796         or all uses follow that insn in the same basic block),
5797      - its final value can be calculated (this condition is different
5798        than the one above in record_giv)
5799      - no assignments to the biv occur during the giv's lifetime.  */
5800
5801 #if 0
5802   /* This is only called now when replaceable is known to be false.  */
5803   /* Clear replaceable, so that it won't confuse final_giv_value.  */
5804   v->replaceable = 0;
5805 #endif
5806
5807   if ((final_value = final_giv_value (loop, v))
5808       && (v->always_computable || last_use_this_basic_block (v->dest_reg, v->insn)))
5809     {
5810       int biv_increment_seen = 0;
5811       rtx p = v->insn;
5812       rtx last_giv_use;
5813
5814       v->replaceable = 1;
5815
5816       /* When trying to determine whether or not a biv increment occurs
5817          during the lifetime of the giv, we can ignore uses of the variable
5818          outside the loop because final_value is true.  Hence we can not
5819          use regno_last_uid and regno_first_uid as above in record_giv.  */
5820
5821       /* Search the loop to determine whether any assignments to the
5822          biv occur during the giv's lifetime.  Start with the insn
5823          that sets the giv, and search around the loop until we come
5824          back to that insn again.
5825
5826          Also fail if there is a jump within the giv's lifetime that jumps
5827          to somewhere outside the lifetime but still within the loop.  This
5828          catches spaghetti code where the execution order is not linear, and
5829          hence the above test fails.  Here we assume that the giv lifetime
5830          does not extend from one iteration of the loop to the next, so as
5831          to make the test easier.  Since the lifetime isn't known yet,
5832          this requires two loops.  See also record_giv above.  */
5833
5834       last_giv_use = v->insn;
5835
5836       while (1)
5837         {
5838           p = NEXT_INSN (p);
5839           if (p == loop->end)
5840             p = NEXT_INSN (loop->start);
5841           if (p == v->insn)
5842             break;
5843
5844           if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5845               || GET_CODE (p) == CALL_INSN)
5846             {
5847               if (biv_increment_seen)
5848                 {
5849                   if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5850                     {
5851                       v->replaceable = 0;
5852                       v->not_replaceable = 1;
5853                       break;
5854                     }
5855                 }
5856               else if (reg_set_p (v->src_reg, PATTERN (p)))
5857                 biv_increment_seen = 1;
5858               else if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5859                 last_giv_use = p;
5860             }
5861         }
5862       
5863       /* Now that the lifetime of the giv is known, check for branches
5864          from within the lifetime to outside the lifetime if it is still
5865          replaceable.  */
5866
5867       if (v->replaceable)
5868         {
5869           p = v->insn;
5870           while (1)
5871             {
5872               p = NEXT_INSN (p);
5873               if (p == loop->end)
5874                 p = NEXT_INSN (loop->start);
5875               if (p == last_giv_use)
5876                 break;
5877
5878               if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
5879                   && LABEL_NAME (JUMP_LABEL (p))
5880                   && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
5881                        && loop_insn_first_p (loop->start, JUMP_LABEL (p)))
5882                       || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
5883                           && loop_insn_first_p (JUMP_LABEL (p), loop->end))))
5884                 {
5885                   v->replaceable = 0;
5886                   v->not_replaceable = 1;
5887
5888                   if (loop_dump_stream)
5889                     fprintf (loop_dump_stream,
5890                              "Found branch outside giv lifetime.\n");
5891
5892                   break;
5893                 }
5894             }
5895         }
5896
5897       /* If it is replaceable, then save the final value.  */
5898       if (v->replaceable)
5899         v->final_value = final_value;
5900     }
5901
5902   if (loop_dump_stream && v->replaceable)
5903     fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
5904              INSN_UID (v->insn), REGNO (v->dest_reg));
5905 }
5906 \f
5907 /* Update the status of whether a giv can derive other givs.
5908
5909    We need to do something special if there is or may be an update to the biv
5910    between the time the giv is defined and the time it is used to derive
5911    another giv.
5912
5913    In addition, a giv that is only conditionally set is not allowed to
5914    derive another giv once a label has been passed.
5915
5916    The cases we look at are when a label or an update to a biv is passed.  */
5917
5918 static void
5919 update_giv_derive (loop, p)
5920      const  struct loop *loop;
5921      rtx p;
5922 {
5923   struct iv_class *bl;
5924   struct induction *biv, *giv;
5925   rtx tem;
5926   int dummy;
5927
5928   /* Search all IV classes, then all bivs, and finally all givs.
5929
5930      There are three cases we are concerned with.  First we have the situation
5931      of a giv that is only updated conditionally.  In that case, it may not
5932      derive any givs after a label is passed.
5933
5934      The second case is when a biv update occurs, or may occur, after the
5935      definition of a giv.  For certain biv updates (see below) that are
5936      known to occur between the giv definition and use, we can adjust the
5937      giv definition.  For others, or when the biv update is conditional,
5938      we must prevent the giv from deriving any other givs.  There are two
5939      sub-cases within this case.
5940
5941      If this is a label, we are concerned with any biv update that is done
5942      conditionally, since it may be done after the giv is defined followed by
5943      a branch here (actually, we need to pass both a jump and a label, but
5944      this extra tracking doesn't seem worth it).
5945
5946      If this is a jump, we are concerned about any biv update that may be
5947      executed multiple times.  We are actually only concerned about
5948      backward jumps, but it is probably not worth performing the test
5949      on the jump again here.
5950
5951      If this is a biv update, we must adjust the giv status to show that a
5952      subsequent biv update was performed.  If this adjustment cannot be done,
5953      the giv cannot derive further givs.  */
5954
5955   for (bl = loop_iv_list; bl; bl = bl->next)
5956     for (biv = bl->biv; biv; biv = biv->next_iv)
5957       if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
5958           || biv->insn == p)
5959         {
5960           for (giv = bl->giv; giv; giv = giv->next_iv)
5961             {
5962               /* If cant_derive is already true, there is no point in
5963                  checking all of these conditions again.  */
5964               if (giv->cant_derive)
5965                 continue;
5966
5967               /* If this giv is conditionally set and we have passed a label,
5968                  it cannot derive anything.  */
5969               if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
5970                 giv->cant_derive = 1;
5971
5972               /* Skip givs that have mult_val == 0, since
5973                  they are really invariants.  Also skip those that are
5974                  replaceable, since we know their lifetime doesn't contain
5975                  any biv update.  */
5976               else if (giv->mult_val == const0_rtx || giv->replaceable)
5977                 continue;
5978
5979               /* The only way we can allow this giv to derive another
5980                  is if this is a biv increment and we can form the product
5981                  of biv->add_val and giv->mult_val.  In this case, we will
5982                  be able to compute a compensation.  */
5983               else if (biv->insn == p)
5984                 {
5985                   tem = 0;
5986
5987                   if (biv->mult_val == const1_rtx)
5988                     tem = simplify_giv_expr (loop,
5989                                              gen_rtx_MULT (giv->mode,
5990                                                            biv->add_val,
5991                                                            giv->mult_val),
5992                                              &dummy);
5993
5994                   if (tem && giv->derive_adjustment)
5995                     tem = simplify_giv_expr
5996                       (loop,
5997                        gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
5998                        &dummy);
5999
6000                   if (tem)
6001                     giv->derive_adjustment = tem;
6002                   else
6003                     giv->cant_derive = 1;
6004                 }
6005               else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
6006                        || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
6007                 giv->cant_derive = 1;
6008             }
6009         }
6010 }
6011 \f
6012 /* Check whether an insn is an increment legitimate for a basic induction var.
6013    X is the source of insn P, or a part of it.
6014    MODE is the mode in which X should be interpreted.
6015
6016    DEST_REG is the putative biv, also the destination of the insn.
6017    We accept patterns of these forms:
6018      REG = REG + INVARIANT (includes REG = REG - CONSTANT)
6019      REG = INVARIANT + REG
6020
6021    If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
6022    store the additive term into *INC_VAL, and store the place where
6023    we found the additive term into *LOCATION.
6024
6025    If X is an assignment of an invariant into DEST_REG, we set
6026    *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
6027
6028    We also want to detect a BIV when it corresponds to a variable
6029    whose mode was promoted via PROMOTED_MODE.  In that case, an increment
6030    of the variable may be a PLUS that adds a SUBREG of that variable to
6031    an invariant and then sign- or zero-extends the result of the PLUS
6032    into the variable.
6033
6034    Most GIVs in such cases will be in the promoted mode, since that is the
6035    probably the natural computation mode (and almost certainly the mode
6036    used for addresses) on the machine.  So we view the pseudo-reg containing
6037    the variable as the BIV, as if it were simply incremented.
6038
6039    Note that treating the entire pseudo as a BIV will result in making
6040    simple increments to any GIVs based on it.  However, if the variable
6041    overflows in its declared mode but not its promoted mode, the result will
6042    be incorrect.  This is acceptable if the variable is signed, since 
6043    overflows in such cases are undefined, but not if it is unsigned, since
6044    those overflows are defined.  So we only check for SIGN_EXTEND and
6045    not ZERO_EXTEND.
6046
6047    If we cannot find a biv, we return 0.  */
6048
6049 static int
6050 basic_induction_var (loop, x, mode, dest_reg, p, inc_val, mult_val,
6051                      location, multi_insn_incr)
6052      const struct loop *loop;
6053      register rtx x;
6054      enum machine_mode mode;
6055      rtx dest_reg;
6056      rtx p;
6057      rtx *inc_val;
6058      rtx *mult_val;
6059      rtx **location;
6060      int *multi_insn_incr;
6061 {
6062   register enum rtx_code code;
6063   rtx *argp, arg;
6064   rtx insn, set = 0;
6065
6066   code = GET_CODE (x);
6067   *location = NULL;
6068   switch (code)
6069     {
6070     case PLUS:
6071       if (rtx_equal_p (XEXP (x, 0), dest_reg)
6072           || (GET_CODE (XEXP (x, 0)) == SUBREG
6073               && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
6074               && SUBREG_REG (XEXP (x, 0)) == dest_reg))
6075         {
6076           argp = &XEXP (x, 1);
6077         }
6078       else if (rtx_equal_p (XEXP (x, 1), dest_reg)
6079                || (GET_CODE (XEXP (x, 1)) == SUBREG
6080                    && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
6081                    && SUBREG_REG (XEXP (x, 1)) == dest_reg))
6082         {
6083           argp = &XEXP (x, 0);
6084         }
6085       else
6086         return 0;
6087
6088       arg = *argp;
6089       if (loop_invariant_p (loop, arg) != 1)
6090         return 0;
6091
6092       *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
6093       *mult_val = const1_rtx;
6094       *location = argp;
6095       return 1;
6096
6097     case SUBREG:
6098       /* If this is a SUBREG for a promoted variable, check the inner
6099          value.  */
6100       if (SUBREG_PROMOTED_VAR_P (x))
6101         return basic_induction_var (loop, SUBREG_REG (x),
6102                                     GET_MODE (SUBREG_REG (x)),
6103                                     dest_reg, p, inc_val, mult_val, location,
6104                                     multi_insn_incr);
6105       return 0;
6106
6107     case REG:
6108       /* If this register is assigned in a previous insn, look at its
6109          source, but don't go outside the loop or past a label.  */
6110
6111       insn = p;
6112       while (1)
6113         {
6114           do {
6115             insn = PREV_INSN (insn);
6116           } while (insn && GET_CODE (insn) == NOTE
6117                    && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6118
6119           if (!insn)
6120             break;
6121           set = single_set (insn);
6122           if (set == 0)
6123             break;
6124
6125           if ((SET_DEST (set) == x
6126                || (GET_CODE (SET_DEST (set)) == SUBREG
6127                    && (GET_MODE_SIZE (GET_MODE (SET_DEST (set)))
6128                        <= UNITS_PER_WORD)
6129                    && (GET_MODE_CLASS (GET_MODE (SET_DEST (set)))
6130                        == MODE_INT)
6131                    && SUBREG_REG (SET_DEST (set)) == x))
6132               && basic_induction_var (loop, SET_SRC (set),
6133                                       (GET_MODE (SET_SRC (set)) == VOIDmode
6134                                        ? GET_MODE (x)
6135                                        : GET_MODE (SET_SRC (set))),
6136                                       dest_reg, insn,
6137                                       inc_val, mult_val, location,
6138                                       multi_insn_incr))
6139             {
6140               *multi_insn_incr = 1;
6141               return 1;
6142             }
6143         }
6144       /* ... fall through ...  */
6145
6146       /* Can accept constant setting of biv only when inside inner most loop.
6147          Otherwise, a biv of an inner loop may be incorrectly recognized
6148          as a biv of the outer loop,
6149          causing code to be moved INTO the inner loop.  */
6150     case MEM:
6151       if (loop_invariant_p (loop, x) != 1)
6152         return 0;
6153     case CONST_INT:
6154     case SYMBOL_REF:
6155     case CONST:
6156       /* convert_modes aborts if we try to convert to or from CCmode, so just
6157          exclude that case.  It is very unlikely that a condition code value
6158          would be a useful iterator anyways.  */
6159       if (loop->level == 1
6160           && GET_MODE_CLASS (mode) != MODE_CC
6161           && GET_MODE_CLASS (GET_MODE (dest_reg)) != MODE_CC)
6162         {
6163           /* Possible bug here?  Perhaps we don't know the mode of X.  */
6164           *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
6165           *mult_val = const0_rtx;
6166           return 1;
6167         }
6168       else
6169         return 0;
6170
6171     case SIGN_EXTEND:
6172       return basic_induction_var (loop, XEXP (x, 0), GET_MODE (XEXP (x, 0)),
6173                                   dest_reg, p, inc_val, mult_val, location,
6174                                   multi_insn_incr);
6175
6176     case ASHIFTRT:
6177       /* Similar, since this can be a sign extension.  */
6178       for (insn = PREV_INSN (p);
6179            (insn && GET_CODE (insn) == NOTE
6180             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6181            insn = PREV_INSN (insn))
6182         ;
6183
6184       if (insn)
6185         set = single_set (insn);
6186
6187       if (set && SET_DEST (set) == XEXP (x, 0)
6188           && GET_CODE (XEXP (x, 1)) == CONST_INT
6189           && INTVAL (XEXP (x, 1)) >= 0
6190           && GET_CODE (SET_SRC (set)) == ASHIFT
6191           && XEXP (x, 1) == XEXP (SET_SRC (set), 1)
6192           && basic_induction_var (loop, XEXP (SET_SRC (set), 0),
6193                                   GET_MODE (XEXP (x, 0)),
6194                                   dest_reg, insn, inc_val, mult_val,
6195                                   location, multi_insn_incr))
6196         {
6197           *multi_insn_incr = 1;
6198           return 1;
6199         }
6200       return 0;
6201
6202     default:
6203       return 0;
6204     }
6205 }
6206 \f
6207 /* A general induction variable (giv) is any quantity that is a linear
6208    function   of a basic induction variable,
6209    i.e. giv = biv * mult_val + add_val.
6210    The coefficients can be any loop invariant quantity.
6211    A giv need not be computed directly from the biv;
6212    it can be computed by way of other givs.  */
6213
6214 /* Determine whether X computes a giv.
6215    If it does, return a nonzero value
6216      which is the benefit from eliminating the computation of X;
6217    set *SRC_REG to the register of the biv that it is computed from;
6218    set *ADD_VAL and *MULT_VAL to the coefficients,
6219      such that the value of X is biv * mult + add;  */
6220
6221 static int
6222 general_induction_var (loop, x, src_reg, add_val, mult_val, is_addr, pbenefit)
6223      const struct loop *loop;
6224      rtx x;
6225      rtx *src_reg;
6226      rtx *add_val;
6227      rtx *mult_val;
6228      int is_addr;
6229      int *pbenefit;
6230 {
6231   rtx orig_x = x;
6232   char *storage;
6233
6234   /* If this is an invariant, forget it, it isn't a giv.  */
6235   if (loop_invariant_p (loop, x) == 1)
6236     return 0;
6237
6238   /* See if the expression could be a giv and get its form.
6239      Mark our place on the obstack in case we don't find a giv.  */
6240   storage = (char *) oballoc (0);
6241   *pbenefit = 0;
6242   x = simplify_giv_expr (loop, x, pbenefit);
6243   if (x == 0)
6244     {
6245       obfree (storage);
6246       return 0;
6247     }
6248
6249   switch (GET_CODE (x))
6250     {
6251     case USE:
6252     case CONST_INT:
6253       /* Since this is now an invariant and wasn't before, it must be a giv
6254          with MULT_VAL == 0.  It doesn't matter which BIV we associate this
6255          with.  */
6256       *src_reg = loop_iv_list->biv->dest_reg;
6257       *mult_val = const0_rtx;
6258       *add_val = x;
6259       break;
6260
6261     case REG:
6262       /* This is equivalent to a BIV.  */
6263       *src_reg = x;
6264       *mult_val = const1_rtx;
6265       *add_val = const0_rtx;
6266       break;
6267
6268     case PLUS:
6269       /* Either (plus (biv) (invar)) or
6270          (plus (mult (biv) (invar_1)) (invar_2)).  */
6271       if (GET_CODE (XEXP (x, 0)) == MULT)
6272         {
6273           *src_reg = XEXP (XEXP (x, 0), 0);
6274           *mult_val = XEXP (XEXP (x, 0), 1);
6275         }
6276       else
6277         {
6278           *src_reg = XEXP (x, 0);
6279           *mult_val = const1_rtx;
6280         }
6281       *add_val = XEXP (x, 1);
6282       break;
6283
6284     case MULT:
6285       /* ADD_VAL is zero.  */
6286       *src_reg = XEXP (x, 0);
6287       *mult_val = XEXP (x, 1);
6288       *add_val = const0_rtx;
6289       break;
6290
6291     default:
6292       abort ();
6293     }
6294
6295   /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
6296      unless they are CONST_INT).  */
6297   if (GET_CODE (*add_val) == USE)
6298     *add_val = XEXP (*add_val, 0);
6299   if (GET_CODE (*mult_val) == USE)
6300     *mult_val = XEXP (*mult_val, 0);
6301
6302   if (is_addr)
6303     {
6304 #ifdef ADDRESS_COST
6305       *pbenefit += ADDRESS_COST (orig_x) - reg_address_cost;
6306 #else
6307       *pbenefit += rtx_cost (orig_x, MEM) - reg_address_cost;
6308 #endif
6309     }
6310   else
6311     *pbenefit += rtx_cost (orig_x, SET);
6312
6313   /* Always return true if this is a giv so it will be detected as such,
6314      even if the benefit is zero or negative.  This allows elimination  
6315      of bivs that might otherwise not be eliminated.  */                
6316   return 1;                                                             
6317 }
6318 \f
6319 /* Given an expression, X, try to form it as a linear function of a biv.
6320    We will canonicalize it to be of the form
6321         (plus (mult (BIV) (invar_1))
6322               (invar_2))
6323    with possible degeneracies.
6324
6325    The invariant expressions must each be of a form that can be used as a
6326    machine operand.  We surround then with a USE rtx (a hack, but localized
6327    and certainly unambiguous!) if not a CONST_INT for simplicity in this
6328    routine; it is the caller's responsibility to strip them.
6329
6330    If no such canonicalization is possible (i.e., two biv's are used or an
6331    expression that is neither invariant nor a biv or giv), this routine
6332    returns 0.
6333
6334    For a non-zero return, the result will have a code of CONST_INT, USE,
6335    REG (for a BIV), PLUS, or MULT.  No other codes will occur.  
6336
6337    *BENEFIT will be incremented by the benefit of any sub-giv encountered.  */
6338
6339 static rtx sge_plus PARAMS ((enum machine_mode, rtx, rtx));
6340 static rtx sge_plus_constant PARAMS ((rtx, rtx));
6341 static int cmp_combine_givs_stats PARAMS ((const PTR, const PTR));
6342 static int cmp_recombine_givs_stats PARAMS ((const PTR, const PTR));
6343
6344 static rtx
6345 simplify_giv_expr (loop, x, benefit)
6346      const struct loop *loop;
6347      rtx x;
6348      int *benefit;
6349 {
6350   enum machine_mode mode = GET_MODE (x);
6351   rtx arg0, arg1;
6352   rtx tem;
6353
6354   /* If this is not an integer mode, or if we cannot do arithmetic in this
6355      mode, this can't be a giv.  */
6356   if (mode != VOIDmode
6357       && (GET_MODE_CLASS (mode) != MODE_INT
6358           || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
6359     return NULL_RTX;
6360
6361   switch (GET_CODE (x))
6362     {
6363     case PLUS:
6364       arg0 = simplify_giv_expr (loop, XEXP (x, 0), benefit);
6365       arg1 = simplify_giv_expr (loop, XEXP (x, 1), benefit);
6366       if (arg0 == 0 || arg1 == 0)
6367         return NULL_RTX;
6368
6369       /* Put constant last, CONST_INT last if both constant.  */
6370       if ((GET_CODE (arg0) == USE
6371            || GET_CODE (arg0) == CONST_INT)
6372           && ! ((GET_CODE (arg0) == USE
6373                  && GET_CODE (arg1) == USE)
6374                 || GET_CODE (arg1) == CONST_INT))
6375         tem = arg0, arg0 = arg1, arg1 = tem;
6376
6377       /* Handle addition of zero, then addition of an invariant.  */
6378       if (arg1 == const0_rtx)
6379         return arg0;
6380       else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
6381         switch (GET_CODE (arg0))
6382           {
6383           case CONST_INT:
6384           case USE:
6385             /* Adding two invariants must result in an invariant, so enclose
6386                addition operation inside a USE and return it.  */
6387             if (GET_CODE (arg0) == USE)
6388               arg0 = XEXP (arg0, 0);
6389             if (GET_CODE (arg1) == USE)
6390               arg1 = XEXP (arg1, 0);
6391
6392             if (GET_CODE (arg0) == CONST_INT)
6393               tem = arg0, arg0 = arg1, arg1 = tem;
6394             if (GET_CODE (arg1) == CONST_INT)
6395               tem = sge_plus_constant (arg0, arg1);
6396             else
6397               tem = sge_plus (mode, arg0, arg1);
6398
6399             if (GET_CODE (tem) != CONST_INT)
6400               tem = gen_rtx_USE (mode, tem);
6401             return tem;
6402
6403           case REG:
6404           case MULT:
6405             /* biv + invar or mult + invar.  Return sum.  */
6406             return gen_rtx_PLUS (mode, arg0, arg1);
6407
6408           case PLUS:
6409             /* (a + invar_1) + invar_2.  Associate.  */
6410             return
6411               simplify_giv_expr (loop,
6412                                  gen_rtx_PLUS (mode,
6413                                                XEXP (arg0, 0),
6414                                                gen_rtx_PLUS (mode,
6415                                                              XEXP (arg0, 1),
6416                                                              arg1)),
6417                                  benefit);
6418
6419           default:
6420             abort ();
6421           }
6422
6423       /* Each argument must be either REG, PLUS, or MULT.  Convert REG to
6424          MULT to reduce cases.  */
6425       if (GET_CODE (arg0) == REG)
6426         arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
6427       if (GET_CODE (arg1) == REG)
6428         arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
6429
6430       /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
6431          Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
6432          Recurse to associate the second PLUS.  */
6433       if (GET_CODE (arg1) == MULT)
6434         tem = arg0, arg0 = arg1, arg1 = tem;
6435
6436       if (GET_CODE (arg1) == PLUS)
6437           return
6438             simplify_giv_expr (loop,
6439                                gen_rtx_PLUS (mode,
6440                                              gen_rtx_PLUS (mode, arg0,
6441                                                            XEXP (arg1, 0)),
6442                                              XEXP (arg1, 1)),
6443                                benefit);
6444
6445       /* Now must have MULT + MULT.  Distribute if same biv, else not giv.  */
6446       if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
6447         return NULL_RTX;
6448
6449       if (!rtx_equal_p (arg0, arg1))
6450         return NULL_RTX;
6451
6452       return simplify_giv_expr (loop,
6453                                 gen_rtx_MULT (mode,
6454                                               XEXP (arg0, 0),
6455                                               gen_rtx_PLUS (mode,
6456                                                             XEXP (arg0, 1),
6457                                                             XEXP (arg1, 1))),
6458                                 benefit);
6459
6460     case MINUS:
6461       /* Handle "a - b" as "a + b * (-1)".  */
6462       return simplify_giv_expr (loop,
6463                                 gen_rtx_PLUS (mode,
6464                                               XEXP (x, 0),
6465                                               gen_rtx_MULT (mode,
6466                                                             XEXP (x, 1),
6467                                                             constm1_rtx)),
6468                                 benefit);
6469
6470     case MULT:
6471       arg0 = simplify_giv_expr (loop, XEXP (x, 0), benefit);
6472       arg1 = simplify_giv_expr (loop, XEXP (x, 1), benefit);
6473       if (arg0 == 0 || arg1 == 0)
6474         return NULL_RTX;
6475
6476       /* Put constant last, CONST_INT last if both constant.  */
6477       if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
6478           && GET_CODE (arg1) != CONST_INT)
6479         tem = arg0, arg0 = arg1, arg1 = tem;
6480
6481       /* If second argument is not now constant, not giv.  */
6482       if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
6483         return NULL_RTX;
6484
6485       /* Handle multiply by 0 or 1.  */
6486       if (arg1 == const0_rtx)
6487         return const0_rtx;
6488
6489       else if (arg1 == const1_rtx)
6490         return arg0;
6491
6492       switch (GET_CODE (arg0))
6493         {
6494         case REG:
6495           /* biv * invar.  Done.  */
6496           return gen_rtx_MULT (mode, arg0, arg1);
6497
6498         case CONST_INT:
6499           /* Product of two constants.  */
6500           return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
6501
6502         case USE:
6503           /* invar * invar.  It is a giv, but very few of these will 
6504              actually pay off, so limit to simple registers.  */
6505           if (GET_CODE (arg1) != CONST_INT)
6506             return NULL_RTX;
6507
6508           arg0 = XEXP (arg0, 0);
6509           if (GET_CODE (arg0) == REG)
6510             tem = gen_rtx_MULT (mode, arg0, arg1);
6511           else if (GET_CODE (arg0) == MULT
6512                    && GET_CODE (XEXP (arg0, 0)) == REG
6513                    && GET_CODE (XEXP (arg0, 1)) == CONST_INT)
6514             {
6515               tem = gen_rtx_MULT (mode, XEXP (arg0, 0), 
6516                                   GEN_INT (INTVAL (XEXP (arg0, 1))
6517                                            * INTVAL (arg1)));
6518             }
6519           else
6520             return NULL_RTX;
6521           return gen_rtx_USE (mode, tem);
6522
6523         case MULT:
6524           /* (a * invar_1) * invar_2.  Associate.  */
6525           return simplify_giv_expr (loop,
6526                                     gen_rtx_MULT (mode,
6527                                                   XEXP (arg0, 0),
6528                                                   gen_rtx_MULT (mode,
6529                                                                 XEXP (arg0, 1),
6530                                                                 arg1)),
6531                                     benefit);
6532
6533         case PLUS:
6534           /* (a + invar_1) * invar_2.  Distribute.  */
6535           return simplify_giv_expr (loop,
6536                                     gen_rtx_PLUS (mode,
6537                                                   gen_rtx_MULT (mode,
6538                                                                 XEXP (arg0, 0),
6539                                                                 arg1),
6540                                                   gen_rtx_MULT (mode,
6541                                                                 XEXP (arg0, 1),
6542                                                                 arg1)),
6543                                     benefit);
6544
6545         default:
6546           abort ();
6547         }
6548
6549     case ASHIFT:
6550       /* Shift by constant is multiply by power of two.  */
6551       if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6552         return 0;
6553
6554       return
6555         simplify_giv_expr (loop,
6556                            gen_rtx_MULT (mode,
6557                                          XEXP (x, 0),
6558                                          GEN_INT ((HOST_WIDE_INT) 1
6559                                                   << INTVAL (XEXP (x, 1)))),
6560                            benefit);
6561
6562     case NEG:
6563       /* "-a" is "a * (-1)" */
6564       return simplify_giv_expr (loop,
6565                                 gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
6566                                 benefit);
6567
6568     case NOT:
6569       /* "~a" is "-a - 1". Silly, but easy.  */
6570       return simplify_giv_expr (loop,
6571                                 gen_rtx_MINUS (mode,
6572                                                gen_rtx_NEG (mode, XEXP (x, 0)),
6573                                                const1_rtx),
6574                                 benefit);
6575
6576     case USE:
6577       /* Already in proper form for invariant.  */
6578       return x;
6579
6580     case REG:
6581       /* If this is a new register, we can't deal with it.  */
6582       if (REGNO (x) >= max_reg_before_loop)
6583         return 0;
6584
6585       /* Check for biv or giv.  */
6586       switch (REG_IV_TYPE (REGNO (x)))
6587         {
6588         case BASIC_INDUCT:
6589           return x;
6590         case GENERAL_INDUCT:
6591           {
6592             struct induction *v = REG_IV_INFO (REGNO (x));
6593
6594             /* Form expression from giv and add benefit.  Ensure this giv
6595                can derive another and subtract any needed adjustment if so.  */
6596             *benefit += v->benefit;
6597             if (v->cant_derive)
6598               return 0;
6599
6600             tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
6601                                                     v->src_reg, v->mult_val),
6602                                 v->add_val);
6603
6604             if (v->derive_adjustment)
6605               tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
6606             return simplify_giv_expr (loop, tem, benefit);
6607           }
6608
6609         default:
6610           /* If it isn't an induction variable, and it is invariant, we
6611              may be able to simplify things further by looking through
6612              the bits we just moved outside the loop.  */
6613           if (loop_invariant_p (loop, x) == 1)
6614             {
6615               struct movable *m;
6616
6617               for (m = the_movables; m ; m = m->next)
6618                 if (rtx_equal_p (x, m->set_dest))
6619                   {
6620                     /* Ok, we found a match.  Substitute and simplify.  */
6621
6622                     /* If we match another movable, we must use that, as 
6623                        this one is going away.  */
6624                     if (m->match)
6625                       return simplify_giv_expr (loop, m->match->set_dest, 
6626                                                 benefit);
6627
6628                     /* If consec is non-zero, this is a member of a group of
6629                        instructions that were moved together.  We handle this
6630                        case only to the point of seeking to the last insn and
6631                        looking for a REG_EQUAL.  Fail if we don't find one.  */
6632                     if (m->consec != 0)
6633                       {
6634                         int i = m->consec;
6635                         tem = m->insn;
6636                         do { tem = NEXT_INSN (tem); } while (--i > 0);
6637
6638                         tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
6639                         if (tem)
6640                           tem = XEXP (tem, 0);
6641                       }
6642                     else
6643                       {
6644                         tem = single_set (m->insn);
6645                         if (tem)
6646                           tem = SET_SRC (tem);
6647                       }
6648
6649                     if (tem)
6650                       {
6651                         /* What we are most interested in is pointer
6652                            arithmetic on invariants -- only take
6653                            patterns we may be able to do something with.  */
6654                         if (GET_CODE (tem) == PLUS
6655                             || GET_CODE (tem) == MULT
6656                             || GET_CODE (tem) == ASHIFT
6657                             || GET_CODE (tem) == CONST_INT
6658                             || GET_CODE (tem) == SYMBOL_REF)
6659                           {
6660                             tem = simplify_giv_expr (loop, tem, benefit);
6661                             if (tem)
6662                               return tem;
6663                           }
6664                         else if (GET_CODE (tem) == CONST
6665                             && GET_CODE (XEXP (tem, 0)) == PLUS
6666                             && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
6667                             && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
6668                           {
6669                             tem = simplify_giv_expr (loop, XEXP (tem, 0),
6670                                                      benefit);
6671                             if (tem)
6672                               return tem;
6673                           }
6674                       }
6675                     break;
6676                   }
6677             }
6678           break;
6679         }
6680
6681       /* Fall through to general case.  */
6682     default:
6683       /* If invariant, return as USE (unless CONST_INT).
6684          Otherwise, not giv.  */
6685       if (GET_CODE (x) == USE)
6686         x = XEXP (x, 0);
6687
6688       if (loop_invariant_p (loop, x) == 1)
6689         {
6690           if (GET_CODE (x) == CONST_INT)
6691             return x;
6692           if (GET_CODE (x) == CONST
6693               && GET_CODE (XEXP (x, 0)) == PLUS
6694               && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
6695               && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
6696             x = XEXP (x, 0);
6697           return gen_rtx_USE (mode, x);
6698         }
6699       else
6700         return 0;
6701     }
6702 }
6703
6704 /* This routine folds invariants such that there is only ever one
6705    CONST_INT in the summation.  It is only used by simplify_giv_expr.  */
6706
6707 static rtx
6708 sge_plus_constant (x, c)
6709      rtx x, c;
6710 {
6711   if (GET_CODE (x) == CONST_INT)
6712     return GEN_INT (INTVAL (x) + INTVAL (c));
6713   else if (GET_CODE (x) != PLUS)
6714     return gen_rtx_PLUS (GET_MODE (x), x, c);
6715   else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
6716     {
6717       return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
6718                            GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
6719     }
6720   else if (GET_CODE (XEXP (x, 0)) == PLUS
6721            || GET_CODE (XEXP (x, 1)) != PLUS)
6722     {
6723       return gen_rtx_PLUS (GET_MODE (x),
6724                            sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
6725     }
6726   else
6727     {
6728       return gen_rtx_PLUS (GET_MODE (x),
6729                            sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
6730     }
6731 }
6732
6733 static rtx
6734 sge_plus (mode, x, y)
6735      enum machine_mode mode;
6736      rtx x, y;
6737 {
6738   while (GET_CODE (y) == PLUS)
6739     {
6740       rtx a = XEXP (y, 0);
6741       if (GET_CODE (a) == CONST_INT)
6742         x = sge_plus_constant (x, a);
6743       else
6744         x = gen_rtx_PLUS (mode, x, a);
6745       y = XEXP (y, 1);
6746     }
6747   if (GET_CODE (y) == CONST_INT)
6748     x = sge_plus_constant (x, y);
6749   else
6750     x = gen_rtx_PLUS (mode, x, y);
6751   return x;
6752 }
6753 \f
6754 /* Help detect a giv that is calculated by several consecutive insns;
6755    for example,
6756       giv = biv * M
6757       giv = giv + A
6758    The caller has already identified the first insn P as having a giv as dest;
6759    we check that all other insns that set the same register follow
6760    immediately after P, that they alter nothing else,
6761    and that the result of the last is still a giv.
6762
6763    The value is 0 if the reg set in P is not really a giv.
6764    Otherwise, the value is the amount gained by eliminating
6765    all the consecutive insns that compute the value.
6766
6767    FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
6768    SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
6769
6770    The coefficients of the ultimate giv value are stored in
6771    *MULT_VAL and *ADD_VAL.  */
6772
6773 static int
6774 consec_sets_giv (loop, first_benefit, p, src_reg, dest_reg,
6775                  add_val, mult_val, last_consec_insn)
6776      const struct loop *loop;
6777      int first_benefit;
6778      rtx p;
6779      rtx src_reg;
6780      rtx dest_reg;
6781      rtx *add_val;
6782      rtx *mult_val;
6783      rtx *last_consec_insn;
6784 {
6785   int count;
6786   enum rtx_code code;
6787   int benefit;
6788   rtx temp;
6789   rtx set;
6790
6791   /* Indicate that this is a giv so that we can update the value produced in
6792      each insn of the multi-insn sequence. 
6793
6794      This induction structure will be used only by the call to
6795      general_induction_var below, so we can allocate it on our stack.
6796      If this is a giv, our caller will replace the induct var entry with
6797      a new induction structure.  */
6798   struct induction *v
6799     = (struct induction *) alloca (sizeof (struct induction));
6800   v->src_reg = src_reg;
6801   v->mult_val = *mult_val;
6802   v->add_val = *add_val;
6803   v->benefit = first_benefit;
6804   v->cant_derive = 0;
6805   v->derive_adjustment = 0;
6806
6807   REG_IV_TYPE (REGNO (dest_reg)) = GENERAL_INDUCT;
6808   REG_IV_INFO (REGNO (dest_reg)) = v;
6809
6810   count = VARRAY_INT (n_times_set, REGNO (dest_reg)) - 1;
6811
6812   while (count > 0)
6813     {
6814       p = NEXT_INSN (p);
6815       code = GET_CODE (p);
6816
6817       /* If libcall, skip to end of call sequence.  */
6818       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
6819         p = XEXP (temp, 0);
6820
6821       if (code == INSN
6822           && (set = single_set (p))
6823           && GET_CODE (SET_DEST (set)) == REG
6824           && SET_DEST (set) == dest_reg
6825           && (general_induction_var (loop, SET_SRC (set), &src_reg,
6826                                      add_val, mult_val, 0, &benefit)
6827               /* Giv created by equivalent expression.  */
6828               || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
6829                   && general_induction_var (loop, XEXP (temp, 0), &src_reg,
6830                                             add_val, mult_val, 0, &benefit)))
6831           && src_reg == v->src_reg)
6832         {
6833           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
6834             benefit += libcall_benefit (p);
6835
6836           count--;
6837           v->mult_val = *mult_val;
6838           v->add_val = *add_val;
6839           v->benefit = benefit;
6840         }
6841       else if (code != NOTE)
6842         {
6843           /* Allow insns that set something other than this giv to a
6844              constant.  Such insns are needed on machines which cannot
6845              include long constants and should not disqualify a giv.  */
6846           if (code == INSN
6847               && (set = single_set (p))
6848               && SET_DEST (set) != dest_reg
6849               && CONSTANT_P (SET_SRC (set)))
6850             continue;
6851
6852           REG_IV_TYPE (REGNO (dest_reg)) = UNKNOWN_INDUCT;
6853           return 0;
6854         }
6855     }
6856
6857   *last_consec_insn = p;
6858   return v->benefit;
6859 }
6860 \f
6861 /* Return an rtx, if any, that expresses giv G2 as a function of the register
6862    represented by G1.  If no such expression can be found, or it is clear that
6863    it cannot possibly be a valid address, 0 is returned. 
6864
6865    To perform the computation, we note that
6866         G1 = x * v + a          and
6867         G2 = y * v + b
6868    where `v' is the biv.
6869
6870    So G2 = (y/b) * G1 + (b - a*y/x).
6871
6872    Note that MULT = y/x.
6873
6874    Update: A and B are now allowed to be additive expressions such that
6875    B contains all variables in A.  That is, computing B-A will not require
6876    subtracting variables.  */
6877
6878 static rtx
6879 express_from_1 (a, b, mult)
6880      rtx a, b, mult;
6881 {
6882   /* If MULT is zero, then A*MULT is zero, and our expression is B.  */
6883
6884   if (mult == const0_rtx)
6885     return b;
6886
6887   /* If MULT is not 1, we cannot handle A with non-constants, since we
6888      would then be required to subtract multiples of the registers in A.
6889      This is theoretically possible, and may even apply to some Fortran
6890      constructs, but it is a lot of work and we do not attempt it here.  */
6891
6892   if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
6893     return NULL_RTX;
6894
6895   /* In general these structures are sorted top to bottom (down the PLUS
6896      chain), but not left to right across the PLUS.  If B is a higher
6897      order giv than A, we can strip one level and recurse.  If A is higher
6898      order, we'll eventually bail out, but won't know that until the end.
6899      If they are the same, we'll strip one level around this loop.  */
6900
6901   while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
6902     {
6903       rtx ra, rb, oa, ob, tmp;
6904
6905       ra = XEXP (a, 0), oa = XEXP (a, 1);
6906       if (GET_CODE (ra) == PLUS)
6907         tmp = ra, ra = oa, oa = tmp;
6908
6909       rb = XEXP (b, 0), ob = XEXP (b, 1);
6910       if (GET_CODE (rb) == PLUS)
6911         tmp = rb, rb = ob, ob = tmp;
6912
6913       if (rtx_equal_p (ra, rb))
6914         /* We matched: remove one reg completely.  */
6915         a = oa, b = ob;
6916       else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
6917         /* An alternate match.  */
6918         a = oa, b = rb;
6919       else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
6920         /* An alternate match.  */
6921         a = ra, b = ob;
6922       else
6923         {
6924           /* Indicates an extra register in B.  Strip one level from B and 
6925              recurse, hoping B was the higher order expression.  */
6926           ob = express_from_1 (a, ob, mult);
6927           if (ob == NULL_RTX)
6928             return NULL_RTX;
6929           return gen_rtx_PLUS (GET_MODE (b), rb, ob);
6930         }
6931     }
6932
6933   /* Here we are at the last level of A, go through the cases hoping to
6934      get rid of everything but a constant.  */
6935
6936   if (GET_CODE (a) == PLUS)
6937     {
6938       rtx ra, oa;
6939
6940       ra = XEXP (a, 0), oa = XEXP (a, 1);
6941       if (rtx_equal_p (oa, b))
6942         oa = ra;
6943       else if (!rtx_equal_p (ra, b))
6944         return NULL_RTX;
6945
6946       if (GET_CODE (oa) != CONST_INT)
6947         return NULL_RTX;
6948
6949       return GEN_INT (-INTVAL (oa) * INTVAL (mult));
6950     }
6951   else if (GET_CODE (a) == CONST_INT)
6952     {
6953       return plus_constant (b, -INTVAL (a) * INTVAL (mult));
6954     }
6955   else if (GET_CODE (b) == PLUS)
6956     {
6957       if (rtx_equal_p (a, XEXP (b, 0)))
6958         return XEXP (b, 1);
6959       else if (rtx_equal_p (a, XEXP (b, 1)))
6960         return XEXP (b, 0);
6961       else
6962         return NULL_RTX;
6963     }
6964   else if (rtx_equal_p (a, b))
6965     return const0_rtx;
6966
6967   return NULL_RTX;
6968 }
6969
6970 rtx
6971 express_from (g1, g2)
6972      struct induction *g1, *g2;
6973 {
6974   rtx mult, add;
6975
6976   /* The value that G1 will be multiplied by must be a constant integer.  Also,
6977      the only chance we have of getting a valid address is if b*c/a (see above
6978      for notation) is also an integer.  */
6979   if (GET_CODE (g1->mult_val) == CONST_INT
6980       && GET_CODE (g2->mult_val) == CONST_INT)
6981     {
6982       if (g1->mult_val == const0_rtx
6983           || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
6984         return NULL_RTX;
6985       mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
6986     }
6987   else if (rtx_equal_p (g1->mult_val, g2->mult_val))
6988     mult = const1_rtx;
6989   else
6990     {
6991       /* ??? Find out if the one is a multiple of the other?  */
6992       return NULL_RTX;
6993     }
6994
6995   add = express_from_1 (g1->add_val, g2->add_val, mult);
6996   if (add == NULL_RTX)
6997     {
6998       /* Failed.  If we've got a multiplication factor between G1 and G2,
6999          scale G1's addend and try again.  */
7000       if (INTVAL (mult) > 1)
7001         {
7002           rtx g1_add_val = g1->add_val;
7003           if (GET_CODE (g1_add_val) == MULT
7004               && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
7005             {
7006               HOST_WIDE_INT m;
7007               m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
7008               g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
7009                                          XEXP (g1_add_val, 0), GEN_INT (m));
7010             }
7011           else
7012             {
7013               g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
7014                                          mult);
7015             }
7016
7017           add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
7018         }
7019     }
7020   if (add == NULL_RTX)
7021     return NULL_RTX;
7022
7023   /* Form simplified final result.  */
7024   if (mult == const0_rtx)
7025     return add;
7026   else if (mult == const1_rtx)
7027     mult = g1->dest_reg;
7028   else
7029     mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
7030
7031   if (add == const0_rtx)
7032     return mult;
7033   else
7034     {
7035       if (GET_CODE (add) == PLUS
7036           && CONSTANT_P (XEXP (add, 1)))
7037         {
7038           rtx tem = XEXP (add, 1);
7039           mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
7040           add = tem;
7041         }
7042       
7043       return gen_rtx_PLUS (g2->mode, mult, add);
7044     }
7045   
7046 }
7047 \f
7048 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7049    represented by G1.  This indicates that G2 should be combined with G1 and
7050    that G2 can use (either directly or via an address expression) a register
7051    used to represent G1.  */
7052
7053 static rtx
7054 combine_givs_p (g1, g2)
7055      struct induction *g1, *g2;
7056 {
7057   rtx tem = express_from (g1, g2);
7058
7059   /* If these givs are identical, they can be combined.  We use the results
7060      of express_from because the addends are not in a canonical form, so
7061      rtx_equal_p is a weaker test.  */
7062   /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
7063      combination to be the other way round.  */
7064   if (tem == g1->dest_reg
7065       && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
7066     {
7067       return g1->dest_reg;
7068     }
7069
7070   /* If G2 can be expressed as a function of G1 and that function is valid
7071      as an address and no more expensive than using a register for G2,
7072      the expression of G2 in terms of G1 can be used.  */
7073   if (tem != NULL_RTX
7074       && g2->giv_type == DEST_ADDR
7075       && memory_address_p (g2->mem_mode, tem)
7076       /* ??? Looses, especially with -fforce-addr, where *g2->location
7077          will always be a register, and so anything more complicated
7078          gets discarded.  */
7079 #if 0
7080 #ifdef ADDRESS_COST
7081       && ADDRESS_COST (tem) <= ADDRESS_COST (*g2->location)
7082 #else
7083       && rtx_cost (tem, MEM) <= rtx_cost (*g2->location, MEM)
7084 #endif
7085 #endif
7086       )
7087     {
7088       return tem;
7089     }
7090
7091   return NULL_RTX;
7092 }
7093 \f
7094 struct combine_givs_stats
7095 {
7096   int giv_number;
7097   int total_benefit;
7098 };
7099
7100 static int
7101 cmp_combine_givs_stats (xp, yp)
7102      const PTR xp;
7103      const PTR yp;
7104 {
7105   const struct combine_givs_stats * const x =
7106     (const struct combine_givs_stats *) xp;
7107   const struct combine_givs_stats * const y =
7108     (const struct combine_givs_stats *) yp;
7109   int d;
7110   d = y->total_benefit - x->total_benefit;
7111   /* Stabilize the sort.  */
7112   if (!d)
7113     d = x->giv_number - y->giv_number;
7114   return d;
7115 }
7116
7117 /* Check all pairs of givs for iv_class BL and see if any can be combined with
7118    any other.  If so, point SAME to the giv combined with and set NEW_REG to
7119    be an expression (in terms of the other giv's DEST_REG) equivalent to the
7120    giv.  Also, update BENEFIT and related fields for cost/benefit analysis.  */
7121
7122 static void
7123 combine_givs (bl)
7124      struct iv_class *bl;
7125 {
7126   /* Additional benefit to add for being combined multiple times.  */
7127   const int extra_benefit = 3;
7128
7129   struct induction *g1, *g2, **giv_array;
7130   int i, j, k, giv_count;
7131   struct combine_givs_stats *stats;
7132   rtx *can_combine;
7133
7134   /* Count givs, because bl->giv_count is incorrect here.  */
7135   giv_count = 0;
7136   for (g1 = bl->giv; g1; g1 = g1->next_iv)
7137     if (!g1->ignore)
7138       giv_count++;
7139
7140   giv_array
7141     = (struct induction **) alloca (giv_count * sizeof (struct induction *));
7142   i = 0;
7143   for (g1 = bl->giv; g1; g1 = g1->next_iv)
7144     if (!g1->ignore)
7145       giv_array[i++] = g1;
7146
7147   stats = (struct combine_givs_stats *) xcalloc (giv_count, sizeof (*stats));
7148   can_combine = (rtx *) xcalloc (giv_count, giv_count * sizeof(rtx));
7149
7150   for (i = 0; i < giv_count; i++)
7151     {
7152       int this_benefit;
7153       rtx single_use;
7154
7155       g1 = giv_array[i];
7156       stats[i].giv_number = i;
7157
7158       /* If a DEST_REG GIV is used only once, do not allow it to combine
7159          with anything, for in doing so we will gain nothing that cannot
7160          be had by simply letting the GIV with which we would have combined
7161          to be reduced on its own.  The losage shows up in particular with 
7162          DEST_ADDR targets on hosts with reg+reg addressing, though it can
7163          be seen elsewhere as well.  */
7164       if (g1->giv_type == DEST_REG
7165           && (single_use = VARRAY_RTX (reg_single_usage, REGNO (g1->dest_reg)))
7166           && single_use != const0_rtx)
7167         continue;
7168
7169       this_benefit = g1->benefit;
7170       /* Add an additional weight for zero addends.  */
7171       if (g1->no_const_addval)
7172         this_benefit += 1;
7173
7174       for (j = 0; j < giv_count; j++)
7175         {
7176           rtx this_combine;
7177
7178           g2 = giv_array[j];
7179           if (g1 != g2
7180               && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
7181             {
7182               can_combine[i*giv_count + j] = this_combine;
7183               this_benefit += g2->benefit + extra_benefit;
7184             }
7185         }
7186       stats[i].total_benefit = this_benefit;
7187     }
7188
7189   /* Iterate, combining until we can't.  */
7190 restart:
7191   qsort (stats, giv_count, sizeof(*stats), cmp_combine_givs_stats);
7192
7193   if (loop_dump_stream)
7194     {
7195       fprintf (loop_dump_stream, "Sorted combine statistics:\n");
7196       for (k = 0; k < giv_count; k++)
7197         {
7198           g1 = giv_array[stats[k].giv_number];
7199           if (!g1->combined_with && !g1->same)
7200             fprintf (loop_dump_stream, " {%d, %d}", 
7201                      INSN_UID (giv_array[stats[k].giv_number]->insn),
7202                      stats[k].total_benefit);
7203         }
7204       putc ('\n', loop_dump_stream);
7205     }
7206
7207   for (k = 0; k < giv_count; k++)
7208     {
7209       int g1_add_benefit = 0;
7210
7211       i = stats[k].giv_number;
7212       g1 = giv_array[i];
7213
7214       /* If it has already been combined, skip.  */
7215       if (g1->combined_with || g1->same)
7216         continue;
7217
7218       for (j = 0; j < giv_count; j++)
7219         {
7220           g2 = giv_array[j];
7221           if (g1 != g2 && can_combine[i*giv_count + j]
7222               /* If it has already been combined, skip.  */
7223               && ! g2->same && ! g2->combined_with)
7224             {
7225               int l;
7226
7227               g2->new_reg = can_combine[i*giv_count + j];
7228               g2->same = g1;
7229               g1->combined_with++;
7230               g1->lifetime += g2->lifetime;
7231
7232               g1_add_benefit += g2->benefit;
7233
7234               /* ??? The new final_[bg]iv_value code does a much better job
7235                  of finding replaceable giv's, and hence this code may no
7236                  longer be necessary.  */
7237               if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
7238                 g1_add_benefit -= copy_cost;
7239                 
7240               /* To help optimize the next set of combinations, remove
7241                  this giv from the benefits of other potential mates.  */
7242               for (l = 0; l < giv_count; ++l)
7243                 {
7244                   int m = stats[l].giv_number;
7245                   if (can_combine[m*giv_count + j])
7246                     stats[l].total_benefit -= g2->benefit + extra_benefit;
7247                 }
7248
7249               if (loop_dump_stream)
7250                 fprintf (loop_dump_stream,
7251                          "giv at %d combined with giv at %d\n",
7252                          INSN_UID (g2->insn), INSN_UID (g1->insn));
7253             }
7254         }
7255
7256       /* To help optimize the next set of combinations, remove
7257          this giv from the benefits of other potential mates.  */
7258       if (g1->combined_with)
7259         {
7260           for (j = 0; j < giv_count; ++j)
7261             {
7262               int m = stats[j].giv_number;
7263               if (can_combine[m*giv_count + i])
7264                 stats[j].total_benefit -= g1->benefit + extra_benefit;
7265             }
7266
7267           g1->benefit += g1_add_benefit;
7268
7269           /* We've finished with this giv, and everything it touched.
7270              Restart the combination so that proper weights for the 
7271              rest of the givs are properly taken into account.  */
7272           /* ??? Ideally we would compact the arrays at this point, so
7273              as to not cover old ground.  But sanely compacting
7274              can_combine is tricky.  */
7275           goto restart;
7276         }
7277     }
7278
7279   /* Clean up.  */
7280   free (stats);
7281   free (can_combine);
7282 }
7283 \f
7284 struct recombine_givs_stats
7285 {
7286   int giv_number;
7287   int start_luid, end_luid;
7288 };
7289
7290 /* Used below as comparison function for qsort.  We want a ascending luid
7291    when scanning the array starting at the end, thus the arguments are
7292    used in reverse.  */
7293 static int
7294 cmp_recombine_givs_stats (xp, yp)
7295      const PTR xp;
7296      const PTR yp;
7297 {
7298   const struct recombine_givs_stats * const x =
7299     (const struct recombine_givs_stats *) xp;
7300   const struct recombine_givs_stats * const y =
7301     (const struct recombine_givs_stats *) yp;
7302   int d;
7303   d = y->start_luid - x->start_luid;
7304   /* Stabilize the sort.  */
7305   if (!d)
7306     d = y->giv_number - x->giv_number;
7307   return d;
7308 }
7309
7310 /* Scan X, which is a part of INSN, for the end of life of a giv.  Also
7311    look for the start of life of a giv where the start has not been seen
7312    yet to unlock the search for the end of its life.
7313    Only consider givs that belong to BIV.
7314    Return the total number of lifetime ends that have been found.  */
7315 static int
7316 find_life_end (x, stats, insn, biv)
7317      rtx x, insn, biv;
7318      struct recombine_givs_stats *stats;
7319 {
7320   enum rtx_code code;
7321   const char *fmt;
7322   int i, j;
7323   int retval;
7324
7325   code = GET_CODE (x);
7326   switch (code)
7327     {
7328     case SET:
7329       {
7330         rtx reg = SET_DEST (x);
7331         if (GET_CODE (reg) == REG)
7332           {
7333             int regno = REGNO (reg);
7334             struct induction *v = REG_IV_INFO (regno);
7335
7336             if (REG_IV_TYPE (regno) == GENERAL_INDUCT
7337                 && ! v->ignore
7338                 && v->src_reg == biv
7339                 && stats[v->ix].end_luid <= 0)
7340               {
7341                 /* If we see a 0 here for end_luid, it means that we have
7342                    scanned the entire loop without finding any use at all.
7343                    We must not predicate this code on a start_luid match
7344                    since that would make the test fail for givs that have
7345                    been hoisted out of inner loops.  */
7346                 if (stats[v->ix].end_luid == 0)
7347                   {
7348                     stats[v->ix].end_luid = stats[v->ix].start_luid;
7349                     return 1 + find_life_end (SET_SRC (x), stats, insn, biv);
7350                   }
7351                 else if (stats[v->ix].start_luid == INSN_LUID (insn))
7352                   stats[v->ix].end_luid = 0;
7353               }
7354             return find_life_end (SET_SRC (x), stats, insn, biv);
7355           }
7356         break;
7357       }
7358     case REG:
7359       {
7360         int regno = REGNO (x);
7361         struct induction *v = REG_IV_INFO (regno);
7362
7363         if (REG_IV_TYPE (regno) == GENERAL_INDUCT
7364             && ! v->ignore
7365             && v->src_reg == biv
7366             && stats[v->ix].end_luid == 0)
7367           {
7368             while (INSN_UID (insn) >= max_uid_for_loop)
7369               insn = NEXT_INSN (insn);
7370             stats[v->ix].end_luid = INSN_LUID (insn);
7371             return 1;
7372           }
7373         return 0;
7374       }
7375     case LABEL_REF:
7376     case CONST_DOUBLE:
7377     case CONST_INT:
7378     case CONST:
7379       return 0;
7380     default:
7381       break;
7382     }
7383   fmt = GET_RTX_FORMAT (code);
7384   retval = 0;
7385   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7386     {
7387       if (fmt[i] == 'e')
7388         retval += find_life_end (XEXP (x, i), stats, insn, biv);
7389
7390       else if (fmt[i] == 'E')
7391         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7392           retval += find_life_end (XVECEXP (x, i, j), stats, insn, biv);
7393     }
7394   return retval;
7395 }
7396
7397 /* For each giv that has been combined with another, look if
7398    we can combine it with the most recently used one instead.
7399    This tends to shorten giv lifetimes, and helps the next step:
7400    try to derive givs from other givs.  */
7401 static void
7402 recombine_givs (loop, bl, unroll_p)
7403      const struct loop *loop;
7404      struct iv_class *bl;
7405      int unroll_p;
7406 {
7407   struct induction *v, **giv_array, *last_giv;
7408   struct recombine_givs_stats *stats;
7409   int giv_count;
7410   int i, rescan;
7411   int ends_need_computing;
7412
7413   for (giv_count = 0, v = bl->giv; v; v = v->next_iv)
7414     {
7415       if (! v->ignore)
7416         giv_count++;
7417     }
7418   giv_array
7419     = (struct induction **) xmalloc (giv_count * sizeof (struct induction *));
7420   stats = (struct recombine_givs_stats *) xmalloc (giv_count * sizeof *stats);
7421
7422   /* Initialize stats and set up the ix field for each giv in stats to name
7423      the corresponding index into stats.  */
7424   for (i = 0, v = bl->giv; v; v = v->next_iv)
7425     {
7426       rtx p;
7427
7428       if (v->ignore)
7429         continue;
7430       giv_array[i] = v;
7431       stats[i].giv_number = i;
7432       /* If this giv has been hoisted out of an inner loop, use the luid of
7433          the previous insn.  */
7434       for (p = v->insn; INSN_UID (p) >= max_uid_for_loop; )
7435         p = PREV_INSN (p);
7436       stats[i].start_luid = INSN_LUID (p);
7437       i++;
7438     }
7439
7440   qsort (stats, giv_count, sizeof(*stats), cmp_recombine_givs_stats);
7441
7442   /* Set up the ix field for each giv in stats to name
7443      the corresponding index into stats, and
7444      do the actual most-recently-used recombination.  */
7445   for (last_giv = 0, i = giv_count - 1; i >= 0; i--)
7446     {
7447       v = giv_array[stats[i].giv_number];
7448       v->ix = i;
7449       if (v->same)
7450         {
7451           struct induction *old_same = v->same;
7452           rtx new_combine;
7453
7454           /* combine_givs_p actually says if we can make this transformation.
7455              The other tests are here only to avoid keeping a giv alive
7456              that could otherwise be eliminated.  */
7457           if (last_giv
7458               && ((old_same->maybe_dead && ! old_same->combined_with)
7459                   || ! last_giv->maybe_dead
7460                   || last_giv->combined_with)
7461               && (new_combine = combine_givs_p (last_giv, v)))
7462             {
7463               old_same->combined_with--;
7464               v->new_reg = new_combine;
7465               v->same = last_giv;
7466               last_giv->combined_with++;
7467               /* No need to update lifetimes / benefits here since we have
7468                  already decided what to reduce.  */
7469
7470               if (loop_dump_stream)
7471                 {
7472                   fprintf (loop_dump_stream,
7473                            "giv at %d recombined with giv at %d as ",
7474                            INSN_UID (v->insn), INSN_UID (last_giv->insn));
7475                   print_rtl (loop_dump_stream, v->new_reg);
7476                   putc ('\n', loop_dump_stream);
7477                 }
7478               continue;
7479             }
7480           v = v->same;
7481         }
7482       else if (v->giv_type != DEST_REG)
7483         continue;
7484       if (! last_giv
7485           || (last_giv->maybe_dead && ! last_giv->combined_with)
7486           || ! v->maybe_dead
7487           || v->combined_with)
7488         last_giv = v;
7489     }
7490
7491   ends_need_computing = 0;
7492   /* For each DEST_REG giv, compute lifetime starts, and try to compute
7493      lifetime ends from regscan info.  */
7494   for (i = giv_count - 1; i >= 0; i--)
7495     {
7496       v = giv_array[stats[i].giv_number];
7497       if (v->ignore)
7498         continue;
7499       if (v->giv_type == DEST_ADDR)
7500         {
7501           /* Loop unrolling of an inner loop can even create new DEST_REG
7502              givs.  */
7503           rtx p;
7504           for (p = v->insn; INSN_UID (p) >= max_uid_for_loop; )
7505             p = PREV_INSN (p);
7506           stats[i].start_luid = stats[i].end_luid = INSN_LUID (p);
7507           if (p != v->insn)
7508             stats[i].end_luid++;
7509         }
7510       else /* v->giv_type == DEST_REG */
7511         {
7512           if (v->last_use)
7513             {
7514               stats[i].start_luid = INSN_LUID (v->insn);
7515               stats[i].end_luid = INSN_LUID (v->last_use);
7516             }
7517           else if (INSN_UID (v->insn) >= max_uid_for_loop)
7518             {
7519               rtx p;
7520               /* This insn has been created by loop optimization on an inner
7521                  loop.  We don't have a proper start_luid that will match
7522                  when we see the first set.  But we do know that there will
7523                  be no use before the set, so we can set end_luid to 0 so that
7524                  we'll start looking for the last use right away.  */
7525               for (p = PREV_INSN (v->insn); INSN_UID (p) >= max_uid_for_loop; )
7526                 p = PREV_INSN (p);
7527               stats[i].start_luid = INSN_LUID (p);
7528               stats[i].end_luid = 0;
7529               ends_need_computing++;
7530             }
7531           else
7532             {
7533               int regno = REGNO (v->dest_reg);
7534               int count = VARRAY_INT (n_times_set, regno) - 1;
7535               rtx p = v->insn;
7536
7537               /* Find the first insn that sets the giv, so that we can verify
7538                  if this giv's lifetime wraps around the loop.  We also need
7539                  the luid of the first setting insn in order to detect the
7540                  last use properly.  */
7541               while (count)
7542                 {
7543                   p = prev_nonnote_insn (p);
7544                   if (reg_set_p (v->dest_reg, p))
7545                   count--;
7546                 }
7547
7548               stats[i].start_luid = INSN_LUID (p);
7549               if (stats[i].start_luid > uid_luid[REGNO_FIRST_UID (regno)])
7550                 {
7551                   stats[i].end_luid = -1;
7552                   ends_need_computing++;
7553                 }
7554               else
7555                 {
7556                   stats[i].end_luid = uid_luid[REGNO_LAST_UID (regno)];
7557                   if (stats[i].end_luid > INSN_LUID (loop->end))
7558                     {
7559                       stats[i].end_luid = -1;
7560                       ends_need_computing++;
7561                     }
7562                 }
7563             }
7564         }
7565     }
7566
7567   /* If the regscan information was unconclusive for one or more DEST_REG
7568      givs, scan the all insn in the loop to find out lifetime ends.  */
7569   if (ends_need_computing)
7570     {
7571       rtx biv = bl->biv->src_reg;
7572       rtx p = loop->end;
7573
7574       do
7575         {
7576           if (p == loop->start)
7577             p = loop->end;
7578           p = PREV_INSN (p);
7579           if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
7580             continue;
7581           ends_need_computing -= find_life_end (PATTERN (p), stats, p, biv);
7582         }
7583       while (ends_need_computing);
7584     }
7585
7586   /* Set start_luid back to the last insn that sets the giv.  This allows
7587      more combinations.  */
7588   for (i = giv_count - 1; i >= 0; i--)
7589     {
7590       v = giv_array[stats[i].giv_number];
7591       if (v->ignore)
7592         continue;
7593       if (INSN_UID (v->insn) < max_uid_for_loop)
7594         stats[i].start_luid = INSN_LUID (v->insn);
7595     }
7596
7597   /* Now adjust lifetime ends by taking combined givs into account.  */
7598   for (i = giv_count - 1; i >= 0; i--)
7599     {
7600       unsigned luid;
7601       int j;
7602
7603       v = giv_array[stats[i].giv_number];
7604       if (v->ignore)
7605         continue;
7606       if (v->same && ! v->same->ignore)
7607         {
7608           j = v->same->ix;
7609           luid = stats[i].start_luid;
7610           /* Use unsigned arithmetic to model loop wrap-around.  */
7611           if (luid - stats[j].start_luid
7612               > (unsigned) stats[j].end_luid - stats[j].start_luid)
7613             stats[j].end_luid = luid;
7614         }
7615     }
7616
7617   qsort (stats, giv_count, sizeof(*stats), cmp_recombine_givs_stats);
7618
7619   /* Try to derive DEST_REG givs from previous DEST_REG givs with the
7620      same mult_val and non-overlapping lifetime.  This reduces register
7621      pressure.
7622      Once we find a DEST_REG giv that is suitable to derive others from,
7623      we set last_giv to this giv, and try to derive as many other DEST_REG
7624      givs from it without joining overlapping lifetimes.  If we then
7625      encounter a DEST_REG giv that we can't derive, we set rescan to the
7626      index for this giv (unless rescan is already set).
7627      When we are finished with the current LAST_GIV (i.e. the inner loop
7628      terminates), we start again with rescan, which then becomes the new
7629      LAST_GIV.  */
7630   for (i = giv_count - 1; i >= 0; i = rescan)
7631     {
7632       int life_start = 0, life_end = 0;
7633
7634       for (last_giv = 0, rescan = -1; i >= 0; i--)
7635         {
7636           rtx sum;
7637
7638           v = giv_array[stats[i].giv_number];
7639           if (v->giv_type != DEST_REG || v->derived_from || v->same)
7640             continue;
7641           if (! last_giv)
7642             {
7643               /* Don't use a giv that's likely to be dead to derive
7644                  others - that would be likely to keep that giv alive.  */
7645               if (! v->maybe_dead || v->combined_with)
7646                 {
7647                   last_giv = v;
7648                   life_start = stats[i].start_luid;
7649                   life_end = stats[i].end_luid;
7650                 }
7651               continue;
7652             }
7653           /* Use unsigned arithmetic to model loop wrap around.  */
7654           if (((unsigned) stats[i].start_luid - life_start
7655                >= (unsigned) life_end - life_start)
7656               && ((unsigned) stats[i].end_luid - life_start
7657                   > (unsigned) life_end - life_start)
7658               /*  Check that the giv insn we're about to use for deriving
7659                   precedes all uses of that giv.  Note that initializing the
7660                   derived giv would defeat the purpose of reducing register
7661                   pressure.
7662                   ??? We could arrange to move the insn.  */
7663               && ((unsigned) stats[i].end_luid - INSN_LUID (loop->start)
7664                   > (unsigned) stats[i].start_luid - INSN_LUID (loop->start))
7665               && rtx_equal_p (last_giv->mult_val, v->mult_val)
7666               /* ??? Could handle libcalls, but would need more logic.  */
7667               && ! find_reg_note (v->insn, REG_RETVAL, NULL_RTX)
7668               /* We would really like to know if for any giv that v
7669                  is combined with, v->insn or any intervening biv increment
7670                  dominates that combined giv.  However, we
7671                  don't have this detailed control flow information.
7672                  N.B. since last_giv will be reduced, it is valid
7673                  anywhere in the loop, so we don't need to check the
7674                  validity of last_giv.
7675                  We rely here on the fact that v->always_executed implies that
7676                  there is no jump to someplace else in the loop before the
7677                  giv insn, and hence any insn that is executed before the
7678                  giv insn in the loop will have a lower luid.  */
7679               && (v->always_executed || ! v->combined_with)
7680               && (sum = express_from (last_giv, v))
7681               /* Make sure we don't make the add more expensive.  ADD_COST
7682                  doesn't take different costs of registers and constants into
7683                  account, so compare the cost of the actual SET_SRCs.  */
7684               && (rtx_cost (sum, SET)
7685                   <= rtx_cost (SET_SRC (single_set (v->insn)), SET))
7686               /* ??? unroll can't understand anything but reg + const_int
7687                  sums.  It would be cleaner to fix unroll.  */
7688               && ((GET_CODE (sum) == PLUS
7689                    && GET_CODE (XEXP (sum, 0)) == REG
7690                    && GET_CODE (XEXP (sum, 1)) == CONST_INT)
7691                   || ! unroll_p)
7692               && validate_change (v->insn, &PATTERN (v->insn),
7693                                   gen_rtx_SET (VOIDmode, v->dest_reg, sum), 0))
7694             {
7695               v->derived_from = last_giv;
7696               life_end = stats[i].end_luid;
7697
7698               if (loop_dump_stream)
7699                 {
7700                   fprintf (loop_dump_stream,
7701                            "giv at %d derived from %d as ",
7702                            INSN_UID (v->insn), INSN_UID (last_giv->insn));
7703                   print_rtl (loop_dump_stream, sum);
7704                   putc ('\n', loop_dump_stream);
7705                 }
7706             }
7707           else if (rescan < 0)
7708             rescan = i;
7709         }
7710     }
7711
7712   /* Clean up.  */
7713   free (giv_array);
7714   free (stats);
7715 }
7716 \f
7717 /* EMIT code before INSERT_BEFORE to set REG = B * M + A.  */
7718
7719 void
7720 emit_iv_add_mult (b, m, a, reg, insert_before)
7721      rtx b;          /* initial value of basic induction variable */
7722      rtx m;          /* multiplicative constant */
7723      rtx a;          /* additive constant */
7724      rtx reg;        /* destination register */
7725      rtx insert_before;
7726 {
7727   rtx seq;
7728   rtx result;
7729
7730   /* Prevent unexpected sharing of these rtx.  */
7731   a = copy_rtx (a);
7732   b = copy_rtx (b);
7733
7734   /* Increase the lifetime of any invariants moved further in code.  */
7735   update_reg_last_use (a, insert_before);
7736   update_reg_last_use (b, insert_before);
7737   update_reg_last_use (m, insert_before);
7738
7739   start_sequence ();
7740   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 0);
7741   if (reg != result)
7742     emit_move_insn (reg, result);
7743   seq = gen_sequence ();
7744   end_sequence ();
7745
7746   emit_insn_before (seq, insert_before);
7747
7748   /* It is entirely possible that the expansion created lots of new 
7749      registers.  Iterate over the sequence we just created and 
7750      record them all.  */
7751
7752   if (GET_CODE (seq) == SEQUENCE)
7753     {
7754       int i;
7755       for (i = 0; i < XVECLEN (seq, 0); ++i)
7756         {
7757           rtx set = single_set (XVECEXP (seq, 0, i));
7758           if (set && GET_CODE (SET_DEST (set)) == REG)
7759             record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
7760         }
7761     }
7762   else if (GET_CODE (seq) == SET
7763            && GET_CODE (SET_DEST (seq)) == REG)
7764     record_base_value (REGNO (SET_DEST (seq)), SET_SRC (seq), 0);
7765 }
7766 \f
7767 /* Test whether A * B can be computed without
7768    an actual multiply insn.  Value is 1 if so.  */
7769
7770 static int
7771 product_cheap_p (a, b)
7772      rtx a;
7773      rtx b;
7774 {
7775   int i;
7776   rtx tmp;
7777   struct obstack *old_rtl_obstack = rtl_obstack;
7778   char *storage = (char *) obstack_alloc (&temp_obstack, 0);
7779   int win = 1;
7780
7781   /* If only one is constant, make it B.  */
7782   if (GET_CODE (a) == CONST_INT)
7783     tmp = a, a = b, b = tmp;
7784
7785   /* If first constant, both constant, so don't need multiply.  */
7786   if (GET_CODE (a) == CONST_INT)
7787     return 1;
7788
7789   /* If second not constant, neither is constant, so would need multiply.  */
7790   if (GET_CODE (b) != CONST_INT)
7791     return 0;
7792
7793   /* One operand is constant, so might not need multiply insn.  Generate the
7794      code for the multiply and see if a call or multiply, or long sequence
7795      of insns is generated.  */
7796
7797   rtl_obstack = &temp_obstack;
7798   start_sequence ();
7799   expand_mult (GET_MODE (a), a, b, NULL_RTX, 0);
7800   tmp = gen_sequence ();
7801   end_sequence ();
7802
7803   if (GET_CODE (tmp) == SEQUENCE)
7804     {
7805       if (XVEC (tmp, 0) == 0)
7806         win = 1;
7807       else if (XVECLEN (tmp, 0) > 3)
7808         win = 0;
7809       else
7810         for (i = 0; i < XVECLEN (tmp, 0); i++)
7811           {
7812             rtx insn = XVECEXP (tmp, 0, i);
7813
7814             if (GET_CODE (insn) != INSN
7815                 || (GET_CODE (PATTERN (insn)) == SET
7816                     && GET_CODE (SET_SRC (PATTERN (insn))) == MULT)
7817                 || (GET_CODE (PATTERN (insn)) == PARALLEL
7818                     && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == SET
7819                     && GET_CODE (SET_SRC (XVECEXP (PATTERN (insn), 0, 0))) == MULT))
7820               {
7821                 win = 0;
7822                 break;
7823               }
7824           }
7825     }
7826   else if (GET_CODE (tmp) == SET
7827            && GET_CODE (SET_SRC (tmp)) == MULT)
7828     win = 0;
7829   else if (GET_CODE (tmp) == PARALLEL
7830            && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
7831            && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
7832     win = 0;
7833
7834   /* Free any storage we obtained in generating this multiply and restore rtl
7835      allocation to its normal obstack.  */
7836   obstack_free (&temp_obstack, storage);
7837   rtl_obstack = old_rtl_obstack;
7838
7839   return win;
7840 }
7841 \f
7842 /* Check to see if loop can be terminated by a "decrement and branch until
7843    zero" instruction.  If so, add a REG_NONNEG note to the branch insn if so.
7844    Also try reversing an increment loop to a decrement loop
7845    to see if the optimization can be performed.
7846    Value is nonzero if optimization was performed.  */
7847
7848 /* This is useful even if the architecture doesn't have such an insn,
7849    because it might change a loops which increments from 0 to n to a loop
7850    which decrements from n to 0.  A loop that decrements to zero is usually
7851    faster than one that increments from zero.  */
7852
7853 /* ??? This could be rewritten to use some of the loop unrolling procedures,
7854    such as approx_final_value, biv_total_increment, loop_iterations, and
7855    final_[bg]iv_value.  */
7856
7857 static int
7858 check_dbra_loop (loop, insn_count)
7859      struct loop *loop;
7860      int insn_count;
7861 {
7862   struct iv_class *bl;
7863   rtx reg;
7864   rtx jump_label;
7865   rtx final_value;
7866   rtx start_value;
7867   rtx new_add_val;
7868   rtx comparison;
7869   rtx before_comparison;
7870   rtx p;
7871   rtx jump;
7872   rtx first_compare;
7873   int compare_and_branch;
7874   rtx loop_start = loop->start;
7875   rtx loop_end = loop->end;
7876   struct loop_info *loop_info = LOOP_INFO (loop);
7877
7878   /* If last insn is a conditional branch, and the insn before tests a
7879      register value, try to optimize it.  Otherwise, we can't do anything.  */
7880
7881   jump = PREV_INSN (loop_end);
7882   comparison = get_condition_for_loop (loop, jump);
7883   if (comparison == 0)
7884     return 0;
7885
7886   /* Try to compute whether the compare/branch at the loop end is one or
7887      two instructions.  */
7888   get_condition (jump, &first_compare);
7889   if (first_compare == jump)
7890     compare_and_branch = 1;
7891   else if (first_compare == prev_nonnote_insn (jump))
7892     compare_and_branch = 2;
7893   else
7894     return 0;
7895
7896   /* Check all of the bivs to see if the compare uses one of them.
7897      Skip biv's set more than once because we can't guarantee that
7898      it will be zero on the last iteration.  Also skip if the biv is
7899      used between its update and the test insn.  */
7900
7901   for (bl = loop_iv_list; bl; bl = bl->next)
7902     {
7903       if (bl->biv_count == 1
7904           && ! bl->biv->maybe_multiple
7905           && bl->biv->dest_reg == XEXP (comparison, 0)
7906           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
7907                                    first_compare))
7908         break;
7909     }
7910
7911   if (! bl)
7912     return 0;
7913
7914   /* Look for the case where the basic induction variable is always
7915      nonnegative, and equals zero on the last iteration.
7916      In this case, add a reg_note REG_NONNEG, which allows the
7917      m68k DBRA instruction to be used.  */
7918
7919   if (((GET_CODE (comparison) == GT
7920         && GET_CODE (XEXP (comparison, 1)) == CONST_INT
7921         && INTVAL (XEXP (comparison, 1)) == -1)
7922        || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
7923       && GET_CODE (bl->biv->add_val) == CONST_INT
7924       && INTVAL (bl->biv->add_val) < 0)
7925     {
7926       /* Initial value must be greater than 0,
7927          init_val % -dec_value == 0 to ensure that it equals zero on
7928          the last iteration */
7929
7930       if (GET_CODE (bl->initial_value) == CONST_INT
7931           && INTVAL (bl->initial_value) > 0
7932           && (INTVAL (bl->initial_value)
7933               % (-INTVAL (bl->biv->add_val))) == 0)
7934         {
7935           /* register always nonnegative, add REG_NOTE to branch */
7936           REG_NOTES (PREV_INSN (loop_end))
7937             = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7938                                  REG_NOTES (PREV_INSN (loop_end)));
7939           bl->nonneg = 1;
7940
7941           return 1;
7942         }
7943
7944       /* If the decrement is 1 and the value was tested as >= 0 before
7945          the loop, then we can safely optimize.  */
7946       for (p = loop_start; p; p = PREV_INSN (p))
7947         {
7948           if (GET_CODE (p) == CODE_LABEL)
7949             break;
7950           if (GET_CODE (p) != JUMP_INSN)
7951             continue;
7952
7953           before_comparison = get_condition_for_loop (loop, p);
7954           if (before_comparison
7955               && XEXP (before_comparison, 0) == bl->biv->dest_reg
7956               && GET_CODE (before_comparison) == LT
7957               && XEXP (before_comparison, 1) == const0_rtx
7958               && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
7959               && INTVAL (bl->biv->add_val) == -1)
7960             {
7961               REG_NOTES (PREV_INSN (loop_end))
7962                 = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7963                                      REG_NOTES (PREV_INSN (loop_end)));
7964               bl->nonneg = 1;
7965
7966               return 1;
7967             }
7968         }
7969     }
7970   else if (GET_CODE (bl->biv->add_val) == CONST_INT
7971            && INTVAL (bl->biv->add_val) > 0)
7972     {
7973       /* Try to change inc to dec, so can apply above optimization.  */
7974       /* Can do this if:
7975          all registers modified are induction variables or invariant,
7976          all memory references have non-overlapping addresses
7977          (obviously true if only one write)
7978          allow 2 insns for the compare/jump at the end of the loop.  */
7979       /* Also, we must avoid any instructions which use both the reversed
7980          biv and another biv.  Such instructions will fail if the loop is
7981          reversed.  We meet this condition by requiring that either
7982          no_use_except_counting is true, or else that there is only
7983          one biv.  */
7984       int num_nonfixed_reads = 0;
7985       /* 1 if the iteration var is used only to count iterations.  */
7986       int no_use_except_counting = 0;
7987       /* 1 if the loop has no memory store, or it has a single memory store
7988          which is reversible.  */
7989       int reversible_mem_store = 1;
7990
7991       if (bl->giv_count == 0 && ! loop->exit_count)
7992         {
7993           rtx bivreg = regno_reg_rtx[bl->regno];
7994
7995           /* If there are no givs for this biv, and the only exit is the
7996              fall through at the end of the loop, then
7997              see if perhaps there are no uses except to count.  */
7998           no_use_except_counting = 1;
7999           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8000             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
8001               {
8002                 rtx set = single_set (p);
8003
8004                 if (set && GET_CODE (SET_DEST (set)) == REG
8005                     && REGNO (SET_DEST (set)) == bl->regno)
8006                   /* An insn that sets the biv is okay.  */
8007                   ;
8008                 else if ((p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
8009                           || p == prev_nonnote_insn (loop_end))
8010                          && reg_mentioned_p (bivreg, PATTERN (p)))
8011                   {
8012                     /* If either of these insns uses the biv and sets a pseudo
8013                        that has more than one usage, then the biv has uses
8014                        other than counting since it's used to derive a value
8015                        that is used more than one time.  */
8016                     int note_set_pseudo_multiple_uses_retval = 0;
8017                     note_stores (PATTERN (p), note_set_pseudo_multiple_uses,
8018                                  &note_set_pseudo_multiple_uses_retval);
8019                     if (note_set_pseudo_multiple_uses_retval)
8020                       {
8021                         no_use_except_counting = 0;
8022                         break;
8023                       }
8024                   }
8025                 else if (reg_mentioned_p (bivreg, PATTERN (p)))
8026                   {
8027                     no_use_except_counting = 0;
8028                     break;
8029                   }
8030               }
8031         }
8032
8033       if (no_use_except_counting)
8034         ; /* no need to worry about MEMs.  */
8035       else if (num_mem_sets <= 1)
8036         {
8037           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8038             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
8039               num_nonfixed_reads += count_nonfixed_reads (loop, PATTERN (p));
8040
8041           /* If the loop has a single store, and the destination address is
8042              invariant, then we can't reverse the loop, because this address
8043              might then have the wrong value at loop exit.
8044              This would work if the source was invariant also, however, in that
8045              case, the insn should have been moved out of the loop.  */
8046
8047           if (num_mem_sets == 1)
8048             {
8049               struct induction *v;
8050
8051               reversible_mem_store
8052                 = (! unknown_address_altered
8053                    && ! unknown_constant_address_altered
8054                    && ! loop_invariant_p (loop,
8055                                           XEXP (XEXP (loop_store_mems, 0),
8056                                                 0)));
8057
8058               /* If the store depends on a register that is set after the
8059                  store, it depends on the initial value, and is thus not
8060                  reversible.  */
8061               for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
8062                 {
8063                   if (v->giv_type == DEST_REG
8064                       && reg_mentioned_p (v->dest_reg,
8065                                          PATTERN (first_loop_store_insn)) 
8066                       && loop_insn_first_p (first_loop_store_insn, v->insn))
8067                     reversible_mem_store = 0;
8068                 }
8069             }
8070         }
8071       else
8072         return 0;
8073
8074       /* This code only acts for innermost loops.  Also it simplifies
8075          the memory address check by only reversing loops with
8076          zero or one memory access.
8077          Two memory accesses could involve parts of the same array,
8078          and that can't be reversed.
8079          If the biv is used only for counting, than we don't need to worry
8080          about all these things.  */
8081
8082       if ((num_nonfixed_reads <= 1
8083            && ! loop_info->has_call
8084            && ! loop_info->has_volatile
8085            && reversible_mem_store
8086            && (bl->giv_count + bl->biv_count + num_mem_sets
8087               + num_movables + compare_and_branch == insn_count)
8088            && (bl == loop_iv_list && bl->next == 0))
8089           || no_use_except_counting)
8090         {
8091           rtx tem;
8092
8093           /* Loop can be reversed.  */
8094           if (loop_dump_stream)
8095             fprintf (loop_dump_stream, "Can reverse loop\n");
8096
8097           /* Now check other conditions:
8098
8099              The increment must be a constant, as must the initial value,
8100              and the comparison code must be LT. 
8101
8102              This test can probably be improved since +/- 1 in the constant
8103              can be obtained by changing LT to LE and vice versa; this is
8104              confusing.  */
8105
8106           if (comparison
8107               /* for constants, LE gets turned into LT */
8108               && (GET_CODE (comparison) == LT
8109                   || (GET_CODE (comparison) == LE
8110                       && no_use_except_counting)))
8111             {
8112               HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
8113               rtx initial_value, comparison_value;
8114               int nonneg = 0;
8115               enum rtx_code cmp_code;
8116               int comparison_const_width;
8117               unsigned HOST_WIDE_INT comparison_sign_mask;
8118
8119               add_val = INTVAL (bl->biv->add_val);
8120               comparison_value = XEXP (comparison, 1);
8121               if (GET_MODE (comparison_value) == VOIDmode)
8122                 comparison_const_width
8123                   = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
8124               else
8125                 comparison_const_width
8126                   = GET_MODE_BITSIZE (GET_MODE (comparison_value));
8127               if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
8128                 comparison_const_width = HOST_BITS_PER_WIDE_INT;
8129               comparison_sign_mask
8130                 = (unsigned HOST_WIDE_INT)1 << (comparison_const_width - 1);
8131
8132               /* If the comparison value is not a loop invariant, then we
8133                  can not reverse this loop.
8134
8135                  ??? If the insns which initialize the comparison value as
8136                  a whole compute an invariant result, then we could move
8137                  them out of the loop and proceed with loop reversal.  */
8138               if (! loop_invariant_p (loop, comparison_value))
8139                 return 0;
8140
8141               if (GET_CODE (comparison_value) == CONST_INT)
8142                 comparison_val = INTVAL (comparison_value);
8143               initial_value = bl->initial_value;
8144                 
8145               /* Normalize the initial value if it is an integer and 
8146                  has no other use except as a counter.  This will allow
8147                  a few more loops to be reversed.  */
8148               if (no_use_except_counting
8149                   && GET_CODE (comparison_value) == CONST_INT
8150                   && GET_CODE (initial_value) == CONST_INT)
8151                 {
8152                   comparison_val = comparison_val - INTVAL (bl->initial_value);
8153                   /* The code below requires comparison_val to be a multiple
8154                      of add_val in order to do the loop reversal, so
8155                      round up comparison_val to a multiple of add_val.
8156                      Since comparison_value is constant, we know that the
8157                      current comparison code is LT.  */
8158                   comparison_val = comparison_val + add_val - 1;
8159                   comparison_val
8160                     -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
8161                   /* We postpone overflow checks for COMPARISON_VAL here;
8162                      even if there is an overflow, we might still be able to
8163                      reverse the loop, if converting the loop exit test to
8164                      NE is possible.  */
8165                   initial_value = const0_rtx;
8166                 }
8167
8168               /* First check if we can do a vanilla loop reversal.  */
8169               if (initial_value == const0_rtx
8170                   /* If we have a decrement_and_branch_on_count,
8171                      prefer the NE test, since this will allow that
8172                      instruction to be generated.  Note that we must
8173                      use a vanilla loop reversal if the biv is used to
8174                      calculate a giv or has a non-counting use.  */
8175 #if ! defined (HAVE_decrement_and_branch_until_zero) \
8176 && defined (HAVE_decrement_and_branch_on_count)
8177                   && (! (add_val == 1 && loop->vtop
8178                          && (bl->biv_count == 0
8179                              || no_use_except_counting)))
8180 #endif
8181                   && GET_CODE (comparison_value) == CONST_INT
8182                      /* Now do postponed overflow checks on COMPARISON_VAL.  */
8183                   && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
8184                         & comparison_sign_mask))
8185                 {
8186                   /* Register will always be nonnegative, with value
8187                      0 on last iteration */
8188                   add_adjust = add_val;
8189                   nonneg = 1;
8190                   cmp_code = GE;
8191                 }
8192               else if (add_val == 1 && loop->vtop
8193                        && (bl->biv_count == 0
8194                            || no_use_except_counting))
8195                 {
8196                   add_adjust = 0;
8197                   cmp_code = NE;
8198                 }
8199               else
8200                 return 0;
8201
8202               if (GET_CODE (comparison) == LE)
8203                 add_adjust -= add_val;
8204
8205               /* If the initial value is not zero, or if the comparison
8206                  value is not an exact multiple of the increment, then we
8207                  can not reverse this loop.  */
8208               if (initial_value == const0_rtx
8209                   && GET_CODE (comparison_value) == CONST_INT)
8210                 {
8211                   if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
8212                     return 0;
8213                 }
8214               else
8215                 {
8216                   if (! no_use_except_counting || add_val != 1)
8217                     return 0;
8218                 }
8219
8220               final_value = comparison_value;
8221
8222               /* Reset these in case we normalized the initial value
8223                  and comparison value above.  */
8224               if (GET_CODE (comparison_value) == CONST_INT
8225                   && GET_CODE (initial_value) == CONST_INT)
8226                 {
8227                   comparison_value = GEN_INT (comparison_val);
8228                   final_value
8229                     = GEN_INT (comparison_val + INTVAL (bl->initial_value));
8230                 }
8231               bl->initial_value = initial_value;
8232
8233               /* Save some info needed to produce the new insns.  */
8234               reg = bl->biv->dest_reg;
8235               jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 1);
8236               if (jump_label == pc_rtx)
8237                 jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 2);
8238               new_add_val = GEN_INT (- INTVAL (bl->biv->add_val));
8239
8240               /* Set start_value; if this is not a CONST_INT, we need
8241                  to generate a SUB.
8242                  Initialize biv to start_value before loop start.
8243                  The old initializing insn will be deleted as a
8244                  dead store by flow.c.  */
8245               if (initial_value == const0_rtx
8246                   && GET_CODE (comparison_value) == CONST_INT)
8247                 {
8248                   start_value = GEN_INT (comparison_val - add_adjust);
8249                   emit_insn_before (gen_move_insn (reg, start_value),
8250                                     loop_start);
8251                 }
8252               else if (GET_CODE (initial_value) == CONST_INT)
8253                 {
8254                   rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
8255                   enum machine_mode mode = GET_MODE (reg);
8256                   enum insn_code icode
8257                     = add_optab->handlers[(int) mode].insn_code;
8258
8259                   if (! (*insn_data[icode].operand[0].predicate) (reg, mode)
8260                       || ! ((*insn_data[icode].operand[1].predicate)
8261                             (comparison_value, mode))
8262                       || ! ((*insn_data[icode].operand[2].predicate)
8263                             (offset, mode)))
8264                     return 0;
8265                   start_value
8266                     = gen_rtx_PLUS (mode, comparison_value, offset);
8267                   emit_insn_before ((GEN_FCN (icode)
8268                                      (reg, comparison_value, offset)),
8269                                     loop_start);
8270                   if (GET_CODE (comparison) == LE)
8271                     final_value = gen_rtx_PLUS (mode, comparison_value,
8272                                                 GEN_INT (add_val));
8273                 }
8274               else if (! add_adjust)
8275                 {
8276                   enum machine_mode mode = GET_MODE (reg);
8277                   enum insn_code icode
8278                     = sub_optab->handlers[(int) mode].insn_code;
8279                   if (! (*insn_data[icode].operand[0].predicate) (reg, mode)
8280                       || ! ((*insn_data[icode].operand[1].predicate)
8281                             (comparison_value, mode))
8282                       || ! ((*insn_data[icode].operand[2].predicate)
8283                             (initial_value, mode)))
8284                     return 0;
8285                   start_value
8286                     = gen_rtx_MINUS (mode, comparison_value, initial_value);
8287                   emit_insn_before ((GEN_FCN (icode)
8288                                      (reg, comparison_value, initial_value)),
8289                                     loop_start);
8290                 }
8291               else
8292                 /* We could handle the other cases too, but it'll be
8293                    better to have a testcase first.  */
8294                 return 0;
8295
8296               /* We may not have a single insn which can increment a reg, so
8297                  create a sequence to hold all the insns from expand_inc.  */
8298               start_sequence ();
8299               expand_inc (reg, new_add_val);
8300               tem = gen_sequence ();
8301               end_sequence ();
8302
8303               p = emit_insn_before (tem, bl->biv->insn);
8304               delete_insn (bl->biv->insn);
8305                       
8306               /* Update biv info to reflect its new status.  */
8307               bl->biv->insn = p;
8308               bl->initial_value = start_value;
8309               bl->biv->add_val = new_add_val;
8310
8311               /* Update loop info.  */
8312               loop_info->initial_value = reg;
8313               loop_info->initial_equiv_value = reg;
8314               loop_info->final_value = const0_rtx;
8315               loop_info->final_equiv_value = const0_rtx;
8316               loop_info->comparison_value = const0_rtx;
8317               loop_info->comparison_code = cmp_code;
8318               loop_info->increment = new_add_val;
8319
8320               /* Inc LABEL_NUSES so that delete_insn will
8321                  not delete the label.  */
8322               LABEL_NUSES (XEXP (jump_label, 0)) ++;
8323
8324               /* Emit an insn after the end of the loop to set the biv's
8325                  proper exit value if it is used anywhere outside the loop.  */
8326               if ((REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
8327                   || ! bl->init_insn
8328                   || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
8329                 emit_insn_after (gen_move_insn (reg, final_value),
8330                                  loop_end);
8331
8332               /* Delete compare/branch at end of loop.  */
8333               delete_insn (PREV_INSN (loop_end));
8334               if (compare_and_branch == 2)
8335                 delete_insn (first_compare);
8336
8337               /* Add new compare/branch insn at end of loop.  */
8338               start_sequence ();
8339               emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
8340                                        GET_MODE (reg), 0, 0, 
8341                                        XEXP (jump_label, 0));
8342               tem = gen_sequence ();
8343               end_sequence ();
8344               emit_jump_insn_before (tem, loop_end);
8345
8346               for (tem = PREV_INSN (loop_end);
8347                    tem && GET_CODE (tem) != JUMP_INSN;
8348                    tem = PREV_INSN (tem))
8349                 ;
8350
8351               if (tem)
8352                 JUMP_LABEL (tem) = XEXP (jump_label, 0);
8353
8354               if (nonneg)
8355                 {
8356                   if (tem)
8357                     {
8358                       /* Increment of LABEL_NUSES done above.  */
8359                       /* Register is now always nonnegative,
8360                          so add REG_NONNEG note to the branch.  */
8361                       REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
8362                                                            REG_NOTES (tem));
8363                     }
8364                   bl->nonneg = 1;
8365                 }
8366
8367               /* No insn may reference both the reversed and another biv or it
8368                  will fail (see comment near the top of the loop reversal
8369                  code).
8370                  Earlier on, we have verified that the biv has no use except
8371                  counting, or it is the only biv in this function.
8372                  However, the code that computes no_use_except_counting does
8373                  not verify reg notes.  It's possible to have an insn that
8374                  references another biv, and has a REG_EQUAL note with an
8375                  expression based on the reversed biv.  To avoid this case,
8376                  remove all REG_EQUAL notes based on the reversed biv
8377                  here.  */
8378               for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8379                 if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
8380                   {
8381                     rtx *pnote;
8382                     rtx set = single_set (p);
8383                     /* If this is a set of a GIV based on the reversed biv, any
8384                        REG_EQUAL notes should still be correct.  */
8385                     if (! set
8386                         || GET_CODE (SET_DEST (set)) != REG
8387                         || (size_t) REGNO (SET_DEST (set)) >= reg_iv_type->num_elements
8388                         || REG_IV_TYPE (REGNO (SET_DEST (set))) != GENERAL_INDUCT
8389                         || REG_IV_INFO (REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
8390                       for (pnote = &REG_NOTES (p); *pnote;)
8391                         {
8392                           if (REG_NOTE_KIND (*pnote) == REG_EQUAL
8393                               && reg_mentioned_p (regno_reg_rtx[bl->regno],
8394                                                   XEXP (*pnote, 0)))
8395                             *pnote = XEXP (*pnote, 1);
8396                           else
8397                             pnote = &XEXP (*pnote, 1);
8398                         }
8399                   }
8400
8401               /* Mark that this biv has been reversed.  Each giv which depends
8402                  on this biv, and which is also live past the end of the loop
8403                  will have to be fixed up.  */
8404
8405               bl->reversed = 1;
8406
8407               if (loop_dump_stream)
8408                 {
8409                   fprintf (loop_dump_stream, "Reversed loop");
8410                   if (bl->nonneg)
8411                     fprintf (loop_dump_stream, " and added reg_nonneg\n");
8412                   else
8413                     fprintf (loop_dump_stream, "\n");
8414                 }
8415
8416               return 1;
8417             }
8418         }
8419     }
8420
8421   return 0;
8422 }
8423 \f
8424 /* Verify whether the biv BL appears to be eliminable,
8425    based on the insns in the loop that refer to it.
8426
8427    If ELIMINATE_P is non-zero, actually do the elimination.
8428
8429    THRESHOLD and INSN_COUNT are from loop_optimize and are used to
8430    determine whether invariant insns should be placed inside or at the
8431    start of the loop.  */
8432
8433 static int
8434 maybe_eliminate_biv (loop, bl, eliminate_p, threshold, insn_count)
8435      const struct loop *loop;
8436      struct iv_class *bl;
8437      int eliminate_p;
8438      int threshold, insn_count;
8439 {
8440   rtx reg = bl->biv->dest_reg;
8441   rtx loop_start = loop->start;
8442   rtx loop_end = loop->end;
8443   rtx p;
8444
8445   /* Scan all insns in the loop, stopping if we find one that uses the
8446      biv in a way that we cannot eliminate.  */
8447
8448   for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8449     {
8450       enum rtx_code code = GET_CODE (p);
8451       rtx where = threshold >= insn_count ? loop_start : p;
8452
8453       /* If this is a libcall that sets a giv, skip ahead to its end.  */
8454       if (GET_RTX_CLASS (code) == 'i')
8455         {
8456           rtx note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
8457
8458           if (note)
8459             {
8460               rtx last = XEXP (note, 0);
8461               rtx set = single_set (last);
8462
8463               if (set && GET_CODE (SET_DEST (set)) == REG)
8464                 {
8465                   int regno = REGNO (SET_DEST (set));
8466
8467                   if (regno < max_reg_before_loop
8468                       && REG_IV_TYPE (regno) == GENERAL_INDUCT
8469                       && REG_IV_INFO (regno)->src_reg == bl->biv->src_reg)
8470                     p = last;
8471                 }
8472             }
8473         }
8474       if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
8475           && reg_mentioned_p (reg, PATTERN (p))
8476           && ! maybe_eliminate_biv_1 (loop, PATTERN (p), p, bl,
8477                                       eliminate_p, where))
8478         {
8479           if (loop_dump_stream)
8480             fprintf (loop_dump_stream,
8481                      "Cannot eliminate biv %d: biv used in insn %d.\n",
8482                      bl->regno, INSN_UID (p));
8483           break;
8484         }
8485     }
8486
8487   if (p == loop_end)
8488     {
8489       if (loop_dump_stream)
8490         fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
8491                  bl->regno, eliminate_p ? "was" : "can be");
8492       return 1;
8493     }
8494
8495   return 0;
8496 }
8497 \f
8498 /* INSN and REFERENCE are instructions in the same insn chain.
8499    Return non-zero if INSN is first.  */
8500
8501 int
8502 loop_insn_first_p (insn, reference)
8503      rtx insn, reference;
8504 {
8505   rtx p, q;
8506
8507   for (p = insn, q = reference; ;)
8508     {
8509       /* Start with test for not first so that INSN == REFERENCE yields not
8510          first.  */
8511       if (q == insn || ! p)
8512         return 0;
8513       if (p == reference || ! q)
8514         return 1;
8515
8516       /* Either of P or Q might be a NOTE.  Notes have the same LUID as the
8517          previous insn, hence the <= comparison below does not work if
8518          P is a note.  */
8519       if (INSN_UID (p) < max_uid_for_loop
8520           && INSN_UID (q) < max_uid_for_loop
8521           && GET_CODE (p) != NOTE)
8522         return INSN_LUID (p) <= INSN_LUID (q);
8523
8524       if (INSN_UID (p) >= max_uid_for_loop
8525           || GET_CODE (p) == NOTE)
8526         p = NEXT_INSN (p);
8527       if (INSN_UID (q) >= max_uid_for_loop)
8528         q = NEXT_INSN (q);
8529     }
8530 }
8531
8532 /* We are trying to eliminate BIV in INSN using GIV.  Return non-zero if
8533    the offset that we have to take into account due to auto-increment /
8534    div derivation is zero.  */
8535 static int
8536 biv_elimination_giv_has_0_offset (biv, giv, insn)
8537      struct induction *biv, *giv;
8538      rtx insn;
8539 {
8540   /* If the giv V had the auto-inc address optimization applied
8541      to it, and INSN occurs between the giv insn and the biv
8542      insn, then we'd have to adjust the value used here.
8543      This is rare, so we don't bother to make this possible.  */
8544   if (giv->auto_inc_opt
8545       && ((loop_insn_first_p (giv->insn, insn)
8546            && loop_insn_first_p (insn, biv->insn))
8547           || (loop_insn_first_p (biv->insn, insn)
8548               && loop_insn_first_p (insn, giv->insn))))
8549     return 0;
8550
8551   /* If the giv V was derived from another giv, and INSN does
8552      not occur between the giv insn and the biv insn, then we'd
8553      have to adjust the value used here.  This is rare, so we don't
8554      bother to make this possible.  */
8555   if (giv->derived_from
8556       && ! (giv->always_executed
8557             && loop_insn_first_p (giv->insn, insn)
8558             && loop_insn_first_p (insn, biv->insn)))
8559     return 0;
8560   if (giv->same
8561       && giv->same->derived_from
8562       && ! (giv->same->always_executed
8563             && loop_insn_first_p (giv->same->insn, insn)
8564             && loop_insn_first_p (insn, biv->insn)))
8565     return 0;
8566
8567   return 1;
8568 }
8569
8570 /* If BL appears in X (part of the pattern of INSN), see if we can
8571    eliminate its use.  If so, return 1.  If not, return 0.
8572
8573    If BIV does not appear in X, return 1.
8574
8575    If ELIMINATE_P is non-zero, actually do the elimination.  WHERE indicates
8576    where extra insns should be added.  Depending on how many items have been
8577    moved out of the loop, it will either be before INSN or at the start of
8578    the loop.  */
8579
8580 static int
8581 maybe_eliminate_biv_1 (loop, x, insn, bl, eliminate_p, where)
8582      const struct loop *loop;
8583      rtx x, insn;
8584      struct iv_class *bl;
8585      int eliminate_p;
8586      rtx where;
8587 {
8588   enum rtx_code code = GET_CODE (x);
8589   rtx reg = bl->biv->dest_reg;
8590   enum machine_mode mode = GET_MODE (reg);
8591   struct induction *v;
8592   rtx arg, tem;
8593 #ifdef HAVE_cc0
8594   rtx new;
8595 #endif
8596   int arg_operand;
8597   const char *fmt;
8598   int i, j;
8599
8600   switch (code)
8601     {
8602     case REG:
8603       /* If we haven't already been able to do something with this BIV,
8604          we can't eliminate it.  */
8605       if (x == reg)
8606         return 0;
8607       return 1;
8608
8609     case SET:
8610       /* If this sets the BIV, it is not a problem.  */
8611       if (SET_DEST (x) == reg)
8612         return 1;
8613
8614       /* If this is an insn that defines a giv, it is also ok because
8615          it will go away when the giv is reduced.  */
8616       for (v = bl->giv; v; v = v->next_iv)
8617         if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
8618           return 1;
8619
8620 #ifdef HAVE_cc0
8621       if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
8622         {
8623           /* Can replace with any giv that was reduced and
8624              that has (MULT_VAL != 0) and (ADD_VAL == 0).
8625              Require a constant for MULT_VAL, so we know it's nonzero.
8626              ??? We disable this optimization to avoid potential
8627              overflows.  */
8628
8629           for (v = bl->giv; v; v = v->next_iv)
8630             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
8631                 && v->add_val == const0_rtx
8632                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8633                 && v->mode == mode
8634                 && 0)
8635               {
8636                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8637                   continue;
8638
8639                 if (! eliminate_p)
8640                   return 1;
8641
8642                 /* If the giv has the opposite direction of change,
8643                    then reverse the comparison.  */
8644                 if (INTVAL (v->mult_val) < 0)
8645                   new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
8646                                          const0_rtx, v->new_reg);
8647                 else
8648                   new = v->new_reg;
8649
8650                 /* We can probably test that giv's reduced reg.  */
8651                 if (validate_change (insn, &SET_SRC (x), new, 0))
8652                   return 1;
8653               }
8654
8655           /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
8656              replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
8657              Require a constant for MULT_VAL, so we know it's nonzero.
8658              ??? Do this only if ADD_VAL is a pointer to avoid a potential
8659              overflow problem.  */
8660
8661           for (v = bl->giv; v; v = v->next_iv)
8662             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
8663                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8664                 && v->mode == mode
8665                 && (GET_CODE (v->add_val) == SYMBOL_REF
8666                     || GET_CODE (v->add_val) == LABEL_REF
8667                     || GET_CODE (v->add_val) == CONST
8668                     || (GET_CODE (v->add_val) == REG
8669                         && REGNO_POINTER_FLAG (REGNO (v->add_val)))))
8670               {
8671                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8672                   continue;
8673
8674                 if (! eliminate_p)
8675                   return 1;
8676
8677                 /* If the giv has the opposite direction of change,
8678                    then reverse the comparison.  */
8679                 if (INTVAL (v->mult_val) < 0)
8680                   new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
8681                                          v->new_reg);
8682                 else
8683                   new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
8684                                          copy_rtx (v->add_val));
8685
8686                 /* Replace biv with the giv's reduced register.  */
8687                 update_reg_last_use (v->add_val, insn);
8688                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8689                   return 1;
8690
8691                 /* Insn doesn't support that constant or invariant.  Copy it
8692                    into a register (it will be a loop invariant.)  */
8693                 tem = gen_reg_rtx (GET_MODE (v->new_reg));
8694
8695                 emit_insn_before (gen_move_insn (tem, copy_rtx (v->add_val)),
8696                                   where);
8697
8698                 /* Substitute the new register for its invariant value in
8699                    the compare expression. */
8700                 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
8701                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8702                   return 1;
8703               }
8704         }
8705 #endif
8706       break;
8707
8708     case COMPARE:
8709     case EQ:  case NE:
8710     case GT:  case GE:  case GTU:  case GEU:
8711     case LT:  case LE:  case LTU:  case LEU:
8712       /* See if either argument is the biv.  */
8713       if (XEXP (x, 0) == reg)
8714         arg = XEXP (x, 1), arg_operand = 1;
8715       else if (XEXP (x, 1) == reg)
8716         arg = XEXP (x, 0), arg_operand = 0;
8717       else
8718         break;
8719
8720       if (CONSTANT_P (arg))
8721         {
8722           /* First try to replace with any giv that has constant positive
8723              mult_val and constant add_val.  We might be able to support
8724              negative mult_val, but it seems complex to do it in general.  */
8725
8726           for (v = bl->giv; v; v = v->next_iv)
8727             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
8728                 && (GET_CODE (v->add_val) == SYMBOL_REF
8729                     || GET_CODE (v->add_val) == LABEL_REF
8730                     || GET_CODE (v->add_val) == CONST
8731                     || (GET_CODE (v->add_val) == REG
8732                         && REGNO_POINTER_FLAG (REGNO (v->add_val))))
8733                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8734                 && v->mode == mode)
8735               {
8736                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8737                   continue;
8738
8739                 if (! eliminate_p)
8740                   return 1;
8741
8742                 /* Replace biv with the giv's reduced reg.  */
8743                 XEXP (x, 1-arg_operand) = v->new_reg;
8744
8745                 /* If all constants are actually constant integers and
8746                    the derived constant can be directly placed in the COMPARE,
8747                    do so.  */
8748                 if (GET_CODE (arg) == CONST_INT
8749                     && GET_CODE (v->mult_val) == CONST_INT
8750                     && GET_CODE (v->add_val) == CONST_INT
8751                     && validate_change (insn, &XEXP (x, arg_operand),
8752                                         GEN_INT (INTVAL (arg)
8753                                                  * INTVAL (v->mult_val)
8754                                                  + INTVAL (v->add_val)), 0))
8755                   return 1;
8756
8757                 /* Otherwise, load it into a register.  */
8758                 tem = gen_reg_rtx (mode);
8759                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
8760                 if (validate_change (insn, &XEXP (x, arg_operand), tem, 0))
8761                   return 1;
8762
8763                 /* If that failed, put back the change we made above.  */
8764                 XEXP (x, 1-arg_operand) = reg;
8765               }
8766           
8767           /* Look for giv with positive constant mult_val and nonconst add_val.
8768              Insert insns to calculate new compare value.  
8769              ??? Turn this off due to possible overflow.  */
8770
8771           for (v = bl->giv; v; v = v->next_iv)
8772             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
8773                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8774                 && v->mode == mode
8775                 && 0)
8776               {
8777                 rtx tem;
8778
8779                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8780                   continue;
8781
8782                 if (! eliminate_p)
8783                   return 1;
8784
8785                 tem = gen_reg_rtx (mode);
8786
8787                 /* Replace biv with giv's reduced register.  */
8788                 validate_change (insn, &XEXP (x, 1 - arg_operand),
8789                                  v->new_reg, 1);
8790
8791                 /* Compute value to compare against.  */
8792                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
8793                 /* Use it in this insn.  */
8794                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8795                 if (apply_change_group ())
8796                   return 1;
8797               }
8798         }
8799       else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
8800         {
8801           if (loop_invariant_p (loop, arg) == 1)
8802             {
8803               /* Look for giv with constant positive mult_val and nonconst
8804                  add_val. Insert insns to compute new compare value. 
8805                  ??? Turn this off due to possible overflow.  */
8806
8807               for (v = bl->giv; v; v = v->next_iv)
8808                 if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
8809                     && ! v->ignore && ! v->maybe_dead && v->always_computable
8810                     && v->mode == mode
8811                     && 0)
8812                   {
8813                     rtx tem;
8814
8815                     if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8816                       continue;
8817
8818                     if (! eliminate_p)
8819                       return 1;
8820
8821                     tem = gen_reg_rtx (mode);
8822
8823                     /* Replace biv with giv's reduced register.  */
8824                     validate_change (insn, &XEXP (x, 1 - arg_operand),
8825                                      v->new_reg, 1);
8826
8827                     /* Compute value to compare against.  */
8828                     emit_iv_add_mult (arg, v->mult_val, v->add_val,
8829                                       tem, where);
8830                     validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8831                     if (apply_change_group ())
8832                       return 1;
8833                   }
8834             }
8835
8836           /* This code has problems.  Basically, you can't know when
8837              seeing if we will eliminate BL, whether a particular giv
8838              of ARG will be reduced.  If it isn't going to be reduced,
8839              we can't eliminate BL.  We can try forcing it to be reduced,
8840              but that can generate poor code.
8841
8842              The problem is that the benefit of reducing TV, below should
8843              be increased if BL can actually be eliminated, but this means
8844              we might have to do a topological sort of the order in which
8845              we try to process biv.  It doesn't seem worthwhile to do
8846              this sort of thing now.  */
8847
8848 #if 0
8849           /* Otherwise the reg compared with had better be a biv.  */
8850           if (GET_CODE (arg) != REG
8851               || REG_IV_TYPE (REGNO (arg)) != BASIC_INDUCT)
8852             return 0;
8853
8854           /* Look for a pair of givs, one for each biv,
8855              with identical coefficients.  */
8856           for (v = bl->giv; v; v = v->next_iv)
8857             {
8858               struct induction *tv;
8859
8860               if (v->ignore || v->maybe_dead || v->mode != mode)
8861                 continue;
8862
8863               for (tv = reg_biv_class[REGNO (arg)]->giv; tv; tv = tv->next_iv)
8864                 if (! tv->ignore && ! tv->maybe_dead
8865                     && rtx_equal_p (tv->mult_val, v->mult_val)
8866                     && rtx_equal_p (tv->add_val, v->add_val)
8867                     && tv->mode == mode)
8868                   {
8869                     if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8870                       continue;
8871
8872                     if (! eliminate_p)
8873                       return 1;
8874
8875                     /* Replace biv with its giv's reduced reg.  */
8876                     XEXP (x, 1-arg_operand) = v->new_reg;
8877                     /* Replace other operand with the other giv's
8878                        reduced reg.  */
8879                     XEXP (x, arg_operand) = tv->new_reg;
8880                     return 1;
8881                   }
8882             }
8883 #endif
8884         }
8885
8886       /* If we get here, the biv can't be eliminated.  */
8887       return 0;
8888
8889     case MEM:
8890       /* If this address is a DEST_ADDR giv, it doesn't matter if the
8891          biv is used in it, since it will be replaced.  */
8892       for (v = bl->giv; v; v = v->next_iv)
8893         if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
8894           return 1;
8895       break;
8896
8897     default:
8898       break;
8899     }
8900
8901   /* See if any subexpression fails elimination.  */
8902   fmt = GET_RTX_FORMAT (code);
8903   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
8904     {
8905       switch (fmt[i])
8906         {
8907         case 'e':
8908           if (! maybe_eliminate_biv_1 (loop, XEXP (x, i), insn, bl, 
8909                                        eliminate_p, where))
8910             return 0;
8911           break;
8912
8913         case 'E':
8914           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8915             if (! maybe_eliminate_biv_1 (loop, XVECEXP (x, i, j), insn, bl,
8916                                          eliminate_p, where))
8917               return 0;
8918           break;
8919         }
8920     }
8921
8922   return 1;
8923 }  
8924 \f
8925 /* Return nonzero if the last use of REG
8926    is in an insn following INSN in the same basic block.  */
8927
8928 static int
8929 last_use_this_basic_block (reg, insn)
8930      rtx reg;
8931      rtx insn;
8932 {
8933   rtx n;
8934   for (n = insn;
8935        n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
8936        n = NEXT_INSN (n))
8937     {
8938       if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
8939         return 1;
8940     }
8941   return 0;
8942 }
8943 \f
8944 /* Called via `note_stores' to record the initial value of a biv.  Here we
8945    just record the location of the set and process it later.  */
8946
8947 static void
8948 record_initial (dest, set, data)
8949      rtx dest;
8950      rtx set;
8951      void *data ATTRIBUTE_UNUSED;
8952 {
8953   struct iv_class *bl;
8954
8955   if (GET_CODE (dest) != REG
8956       || REGNO (dest) >= max_reg_before_loop
8957       || REG_IV_TYPE (REGNO (dest)) != BASIC_INDUCT)
8958     return;
8959
8960   bl = reg_biv_class[REGNO (dest)];
8961
8962   /* If this is the first set found, record it.  */
8963   if (bl->init_insn == 0)
8964     {
8965       bl->init_insn = note_insn;
8966       bl->init_set = set;
8967     }
8968 }
8969 \f
8970 /* If any of the registers in X are "old" and currently have a last use earlier
8971    than INSN, update them to have a last use of INSN.  Their actual last use
8972    will be the previous insn but it will not have a valid uid_luid so we can't
8973    use it.  */
8974
8975 static void
8976 update_reg_last_use (x, insn)
8977      rtx x;
8978      rtx insn;
8979 {
8980   /* Check for the case where INSN does not have a valid luid.  In this case,
8981      there is no need to modify the regno_last_uid, as this can only happen
8982      when code is inserted after the loop_end to set a pseudo's final value,
8983      and hence this insn will never be the last use of x.  */
8984   if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
8985       && INSN_UID (insn) < max_uid_for_loop
8986       && uid_luid[REGNO_LAST_UID (REGNO (x))] < uid_luid[INSN_UID (insn)])
8987     REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
8988   else
8989     {
8990       register int i, j;
8991       register const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
8992       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8993         {
8994           if (fmt[i] == 'e')
8995             update_reg_last_use (XEXP (x, i), insn);
8996           else if (fmt[i] == 'E')
8997             for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8998               update_reg_last_use (XVECEXP (x, i, j), insn);
8999         }
9000     }
9001 }
9002 \f
9003 /* Given an insn INSN and condition COND, return the condition in a
9004    canonical form to simplify testing by callers.  Specifically:
9005
9006    (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
9007    (2) Both operands will be machine operands; (cc0) will have been replaced.
9008    (3) If an operand is a constant, it will be the second operand.
9009    (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
9010        for GE, GEU, and LEU.
9011
9012    If the condition cannot be understood, or is an inequality floating-point
9013    comparison which needs to be reversed, 0 will be returned.
9014
9015    If REVERSE is non-zero, then reverse the condition prior to canonizing it.
9016
9017    If EARLIEST is non-zero, it is a pointer to a place where the earliest
9018    insn used in locating the condition was found.  If a replacement test
9019    of the condition is desired, it should be placed in front of that
9020    insn and we will be sure that the inputs are still valid.  */
9021
9022 rtx
9023 canonicalize_condition (insn, cond, reverse, earliest)
9024      rtx insn;
9025      rtx cond;
9026      int reverse;
9027      rtx *earliest;
9028 {
9029   enum rtx_code code;
9030   rtx prev = insn;
9031   rtx set;
9032   rtx tem;
9033   rtx op0, op1;
9034   int reverse_code = 0;
9035   int did_reverse_condition = 0;
9036   enum machine_mode mode;
9037
9038   code = GET_CODE (cond);
9039   mode = GET_MODE (cond);
9040   op0 = XEXP (cond, 0);
9041   op1 = XEXP (cond, 1);
9042
9043   if (reverse)
9044     {
9045       code = reverse_condition (code);
9046       did_reverse_condition ^= 1;
9047     }
9048
9049   if (earliest)
9050     *earliest = insn;
9051
9052   /* If we are comparing a register with zero, see if the register is set
9053      in the previous insn to a COMPARE or a comparison operation.  Perform
9054      the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
9055      in cse.c  */
9056
9057   while (GET_RTX_CLASS (code) == '<' && op1 == CONST0_RTX (GET_MODE (op0)))
9058     {
9059       /* Set non-zero when we find something of interest.  */
9060       rtx x = 0;
9061
9062 #ifdef HAVE_cc0
9063       /* If comparison with cc0, import actual comparison from compare
9064          insn.  */
9065       if (op0 == cc0_rtx)
9066         {
9067           if ((prev = prev_nonnote_insn (prev)) == 0
9068               || GET_CODE (prev) != INSN
9069               || (set = single_set (prev)) == 0
9070               || SET_DEST (set) != cc0_rtx)
9071             return 0;
9072
9073           op0 = SET_SRC (set);
9074           op1 = CONST0_RTX (GET_MODE (op0));
9075           if (earliest)
9076             *earliest = prev;
9077         }
9078 #endif
9079
9080       /* If this is a COMPARE, pick up the two things being compared.  */
9081       if (GET_CODE (op0) == COMPARE)
9082         {
9083           op1 = XEXP (op0, 1);
9084           op0 = XEXP (op0, 0);
9085           continue;
9086         }
9087       else if (GET_CODE (op0) != REG)
9088         break;
9089
9090       /* Go back to the previous insn.  Stop if it is not an INSN.  We also
9091          stop if it isn't a single set or if it has a REG_INC note because
9092          we don't want to bother dealing with it.  */
9093
9094       if ((prev = prev_nonnote_insn (prev)) == 0
9095           || GET_CODE (prev) != INSN
9096           || FIND_REG_INC_NOTE (prev, 0)
9097           || (set = single_set (prev)) == 0)
9098         break;
9099
9100       /* If this is setting OP0, get what it sets it to if it looks
9101          relevant.  */
9102       if (rtx_equal_p (SET_DEST (set), op0))
9103         {
9104           enum machine_mode inner_mode = GET_MODE (SET_SRC (set));
9105
9106           /* ??? We may not combine comparisons done in a CCmode with
9107              comparisons not done in a CCmode.  This is to aid targets
9108              like Alpha that have an IEEE compliant EQ instruction, and
9109              a non-IEEE compliant BEQ instruction.  The use of CCmode is
9110              actually artificial, simply to prevent the combination, but
9111              should not affect other platforms.
9112
9113              However, we must allow VOIDmode comparisons to match either
9114              CCmode or non-CCmode comparison, because some ports have
9115              modeless comparisons inside branch patterns.
9116
9117              ??? This mode check should perhaps look more like the mode check
9118              in simplify_comparison in combine.  */
9119
9120           if ((GET_CODE (SET_SRC (set)) == COMPARE
9121                || (((code == NE
9122                      || (code == LT
9123                          && GET_MODE_CLASS (inner_mode) == MODE_INT
9124                          && (GET_MODE_BITSIZE (inner_mode)
9125                              <= HOST_BITS_PER_WIDE_INT)
9126                          && (STORE_FLAG_VALUE
9127                              & ((HOST_WIDE_INT) 1
9128                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9129 #ifdef FLOAT_STORE_FLAG_VALUE
9130                      || (code == LT
9131                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9132                          && (REAL_VALUE_NEGATIVE
9133                              (FLOAT_STORE_FLAG_VALUE (inner_mode))))
9134 #endif
9135                      ))
9136                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'))
9137               && (((GET_MODE_CLASS (mode) == MODE_CC)
9138                    == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9139                   || mode == VOIDmode || inner_mode == VOIDmode))
9140             x = SET_SRC (set);
9141           else if (((code == EQ
9142                      || (code == GE
9143                          && (GET_MODE_BITSIZE (inner_mode)
9144                              <= HOST_BITS_PER_WIDE_INT)
9145                          && GET_MODE_CLASS (inner_mode) == MODE_INT
9146                          && (STORE_FLAG_VALUE
9147                              & ((HOST_WIDE_INT) 1
9148                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9149 #ifdef FLOAT_STORE_FLAG_VALUE
9150                      || (code == GE
9151                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9152                          && (REAL_VALUE_NEGATIVE
9153                              (FLOAT_STORE_FLAG_VALUE (inner_mode))))
9154 #endif
9155                      ))
9156                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'
9157                    && (((GET_MODE_CLASS (mode) == MODE_CC)
9158                         == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9159                        || mode == VOIDmode || inner_mode == VOIDmode))
9160
9161             {
9162               /* We might have reversed a LT to get a GE here.  But this wasn't
9163                  actually the comparison of data, so we don't flag that we
9164                  have had to reverse the condition.  */
9165               did_reverse_condition ^= 1;
9166               reverse_code = 1;
9167               x = SET_SRC (set);
9168             }
9169           else
9170             break;
9171         }
9172
9173       else if (reg_set_p (op0, prev))
9174         /* If this sets OP0, but not directly, we have to give up.  */
9175         break;
9176
9177       if (x)
9178         {
9179           if (GET_RTX_CLASS (GET_CODE (x)) == '<')
9180             code = GET_CODE (x);
9181           if (reverse_code)
9182             {
9183               code = reverse_condition (code);
9184               if (code == UNKNOWN)
9185                 return 0;
9186               did_reverse_condition ^= 1;
9187               reverse_code = 0;
9188             }
9189
9190           op0 = XEXP (x, 0), op1 = XEXP (x, 1);
9191           if (earliest)
9192             *earliest = prev;
9193         }
9194     }
9195
9196   /* If constant is first, put it last.  */
9197   if (CONSTANT_P (op0))
9198     code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
9199
9200   /* If OP0 is the result of a comparison, we weren't able to find what
9201      was really being compared, so fail.  */
9202   if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
9203     return 0;
9204
9205   /* Canonicalize any ordered comparison with integers involving equality
9206      if we can do computations in the relevant mode and we do not
9207      overflow.  */
9208
9209   if (GET_CODE (op1) == CONST_INT
9210       && GET_MODE (op0) != VOIDmode
9211       && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
9212     {
9213       HOST_WIDE_INT const_val = INTVAL (op1);
9214       unsigned HOST_WIDE_INT uconst_val = const_val;
9215       unsigned HOST_WIDE_INT max_val
9216         = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
9217
9218       switch (code)
9219         {
9220         case LE:
9221           if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
9222             code = LT,  op1 = GEN_INT (const_val + 1);
9223           break;
9224
9225         /* When cross-compiling, const_val might be sign-extended from
9226            BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
9227         case GE:
9228           if ((HOST_WIDE_INT) (const_val & max_val)
9229               != (((HOST_WIDE_INT) 1
9230                    << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
9231             code = GT, op1 = GEN_INT (const_val - 1);
9232           break;
9233
9234         case LEU:
9235           if (uconst_val < max_val)
9236             code = LTU, op1 = GEN_INT (uconst_val + 1);
9237           break;
9238
9239         case GEU:
9240           if (uconst_val != 0)
9241             code = GTU, op1 = GEN_INT (uconst_val - 1);
9242           break;
9243
9244         default:
9245           break;
9246         }
9247     }
9248
9249   /* If this was floating-point and we reversed anything other than an
9250      EQ or NE or (UN)ORDERED, return zero.  */
9251   if (TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
9252       && did_reverse_condition
9253       && code != NE && code != EQ && code != UNORDERED && code != ORDERED
9254       && ! flag_fast_math
9255       && GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
9256     return 0;
9257
9258 #ifdef HAVE_cc0
9259   /* Never return CC0; return zero instead.  */
9260   if (op0 == cc0_rtx)
9261     return 0;
9262 #endif
9263
9264   return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
9265 }
9266
9267 /* Given a jump insn JUMP, return the condition that will cause it to branch
9268    to its JUMP_LABEL.  If the condition cannot be understood, or is an
9269    inequality floating-point comparison which needs to be reversed, 0 will
9270    be returned.
9271
9272    If EARLIEST is non-zero, it is a pointer to a place where the earliest
9273    insn used in locating the condition was found.  If a replacement test
9274    of the condition is desired, it should be placed in front of that
9275    insn and we will be sure that the inputs are still valid.  */
9276
9277 rtx
9278 get_condition (jump, earliest)
9279      rtx jump;
9280      rtx *earliest;
9281 {
9282   rtx cond;
9283   int reverse;
9284
9285   /* If this is not a standard conditional jump, we can't parse it.  */
9286   if (GET_CODE (jump) != JUMP_INSN
9287       || ! condjump_p (jump) || simplejump_p (jump))
9288     return 0;
9289
9290   cond = XEXP (SET_SRC (PATTERN (jump)), 0);
9291
9292   /* If this branches to JUMP_LABEL when the condition is false, reverse
9293      the condition.  */
9294   reverse
9295     = GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 2)) == LABEL_REF
9296       && XEXP (XEXP (SET_SRC (PATTERN (jump)), 2), 0) == JUMP_LABEL (jump);
9297
9298   return canonicalize_condition (jump, cond, reverse, earliest);
9299 }
9300
9301 /* Similar to above routine, except that we also put an invariant last
9302    unless both operands are invariants.  */
9303
9304 rtx
9305 get_condition_for_loop (loop, x)
9306      const struct loop *loop;
9307      rtx x;
9308 {
9309   rtx comparison = get_condition (x, NULL_PTR);
9310
9311   if (comparison == 0
9312       || ! loop_invariant_p (loop, XEXP (comparison, 0))
9313       || loop_invariant_p (loop, XEXP (comparison, 1)))
9314     return comparison;
9315
9316   return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
9317                          XEXP (comparison, 1), XEXP (comparison, 0));
9318 }
9319
9320 #ifdef HAVE_decrement_and_branch_on_count
9321 /* Instrument loop for insertion of bct instruction.  We distinguish between
9322    loops with compile-time bounds and those with run-time bounds. 
9323    Information from loop_iterations() is used to compute compile-time bounds.
9324    Run-time bounds should use loop preconditioning, but currently ignored.
9325  */
9326
9327 static void
9328 insert_bct (loop)
9329      struct loop *loop;
9330 {
9331   unsigned HOST_WIDE_INT n_iterations;
9332   rtx loop_start = loop->start;
9333   rtx loop_end = loop->end;
9334   struct loop_info *loop_info = LOOP_INFO (loop);  
9335   int loop_num = loop->num;
9336
9337 #if 0
9338   int increment_direction, compare_direction;
9339   /* If the loop condition is <= or >=, the number of iteration
9340       is 1 more than the range of the bounds of the loop.  */
9341   int add_iteration = 0;
9342   enum machine_mode loop_var_mode = word_mode;
9343 #endif
9344
9345   /* It's impossible to instrument a competely unrolled loop.  */
9346   if (loop_info->unroll_number == loop_info->n_iterations)
9347     return;
9348
9349   /* Make sure that the count register is not in use.  */
9350   if (loop_info->used_count_register)
9351     {
9352       if (loop_dump_stream)
9353         fprintf (loop_dump_stream,
9354                  "insert_bct %d: BCT instrumentation failed: count register already in use\n",
9355                  loop_num);
9356       return;
9357     }
9358
9359   /* Make sure that the function has no indirect jumps.  */
9360   if (indirect_jump_in_function)
9361     {
9362       if (loop_dump_stream)
9363         fprintf (loop_dump_stream,
9364                  "insert_bct %d: BCT instrumentation failed: indirect jump in function\n",
9365                  loop_num);
9366       return;
9367     }
9368
9369   /* Make sure that the last loop insn is a conditional jump.  */
9370   if (GET_CODE (PREV_INSN (loop_end)) != JUMP_INSN
9371       || ! condjump_p (PREV_INSN (loop_end))
9372       || simplejump_p (PREV_INSN (loop_end)))
9373     {
9374       if (loop_dump_stream)
9375         fprintf (loop_dump_stream,
9376                  "insert_bct %d: BCT instrumentation failed: invalid jump at loop end\n",
9377                  loop_num);
9378       return;
9379     }
9380
9381   /* Make sure that the loop does not contain a function call
9382      (the count register might be altered by the called function).  */
9383   if (loop_info->has_call)
9384     {
9385       if (loop_dump_stream)
9386         fprintf (loop_dump_stream,
9387                  "insert_bct %d: BCT instrumentation failed: function call in loop\n",
9388                  loop_num);
9389       return;
9390     }
9391
9392   /* Make sure that the loop does not jump via a table.
9393      (the count register might be used to perform the branch on table).  */
9394   if (loop_info->has_tablejump)
9395     {
9396       if (loop_dump_stream)
9397         fprintf (loop_dump_stream,
9398                  "insert_bct %d: BCT instrumentation failed: computed branch in the loop\n",
9399                  loop_num);
9400       return;
9401     }
9402
9403   /* Account for loop unrolling in instrumented iteration count.  */
9404   if (loop_info->unroll_number > 1)
9405     n_iterations = loop_info->n_iterations / loop_info->unroll_number;
9406   else
9407     n_iterations = loop_info->n_iterations;
9408
9409   if (n_iterations != 0 && n_iterations < 3)
9410     {
9411       /* Allow an enclosing outer loop to benefit if possible.  */
9412       if (loop_dump_stream)
9413         fprintf (loop_dump_stream,
9414                  "insert_bct %d: Too few iterations to benefit from BCT optimization\n",
9415                  loop_num);
9416       return;
9417     }
9418
9419   /* Try to instrument the loop.  */
9420
9421   /* Handle the simpler case, where the bounds are known at compile time.  */
9422   if (n_iterations > 0)
9423     {
9424       struct loop *outer_loop;
9425       struct loop_info *outer_loop_info;
9426
9427       /* Mark all enclosing loops that they cannot use count register.  */
9428       for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
9429         {
9430           outer_loop_info = LOOP_INFO (outer_loop);
9431           outer_loop_info->used_count_register = 1;
9432         }
9433       instrument_loop_bct (loop_start, loop_end, GEN_INT (n_iterations));
9434       return;
9435     }
9436
9437   /* Handle the more complex case, that the bounds are NOT known
9438      at compile time.  In this case we generate run_time calculation
9439      of the number of iterations.  */
9440
9441   if (loop_info->iteration_var == 0)
9442     {
9443       if (loop_dump_stream)
9444         fprintf (loop_dump_stream,
9445                  "insert_bct %d: BCT Runtime Instrumentation failed: no loop iteration variable found\n",
9446                  loop_num);
9447       return;
9448     }
9449
9450   if (GET_MODE_CLASS (GET_MODE (loop_info->iteration_var)) != MODE_INT
9451       || GET_MODE_SIZE (GET_MODE (loop_info->iteration_var)) != UNITS_PER_WORD)
9452     {
9453       if (loop_dump_stream)
9454         fprintf (loop_dump_stream,
9455                  "insert_bct %d: BCT Runtime Instrumentation failed: loop variable not integer\n",
9456                  loop_num);
9457       return;
9458     }
9459
9460   /* With runtime bounds, if the compare is of the form '!=' we give up */
9461   if (loop_info->comparison_code == NE)
9462     {
9463       if (loop_dump_stream)
9464         fprintf (loop_dump_stream,
9465                  "insert_bct %d: BCT Runtime Instrumentation failed: runtime bounds with != comparison\n",
9466                  loop_num);
9467       return;
9468     }
9469 /* Use common loop preconditioning code instead.  */
9470 #if 0
9471   else
9472     {
9473       /* We rely on the existence of run-time guard to ensure that the
9474          loop executes at least once.  */
9475       rtx sequence;
9476       rtx iterations_num_reg;
9477
9478       unsigned HOST_WIDE_INT increment_value_abs
9479         = INTVAL (increment) * increment_direction;
9480
9481       /* make sure that the increment is a power of two, otherwise (an
9482          expensive) divide is needed.  */
9483       if (exact_log2 (increment_value_abs) == -1)
9484         {
9485           if (loop_dump_stream)
9486             fprintf (loop_dump_stream,
9487                      "insert_bct: not instrumenting BCT because the increment is not power of 2\n");
9488           return;
9489         }
9490
9491       /* compute the number of iterations */
9492       start_sequence ();
9493       {
9494         rtx temp_reg;
9495
9496         /* Again, the number of iterations is calculated by:
9497            ;
9498            ;                  compare-val - initial-val + (increment -1) + additional-iteration
9499            ; num_iterations = -----------------------------------------------------------------
9500            ;                                           increment
9501          */
9502         /* ??? Do we have to call copy_rtx here before passing rtx to
9503            expand_binop?  */
9504         if (compare_direction > 0)
9505           {
9506             /* <, <= :the loop variable is increasing */
9507             temp_reg = expand_binop (loop_var_mode, sub_optab,
9508                                      comparison_value, initial_value,
9509                                      NULL_RTX, 0, OPTAB_LIB_WIDEN);
9510           }
9511         else
9512           {
9513             temp_reg = expand_binop (loop_var_mode, sub_optab,
9514                                      initial_value, comparison_value,
9515                                      NULL_RTX, 0, OPTAB_LIB_WIDEN);
9516           }
9517
9518         if (increment_value_abs - 1 + add_iteration != 0)
9519           temp_reg = expand_binop (loop_var_mode, add_optab, temp_reg,
9520                                    GEN_INT (increment_value_abs - 1
9521                                             + add_iteration),
9522                                    NULL_RTX, 0, OPTAB_LIB_WIDEN);
9523
9524         if (increment_value_abs != 1)
9525           iterations_num_reg = expand_binop (loop_var_mode, asr_optab,
9526                                              temp_reg,
9527                                              GEN_INT (exact_log2 (increment_value_abs)),
9528                                              NULL_RTX, 0, OPTAB_LIB_WIDEN);
9529         else
9530           iterations_num_reg = temp_reg;
9531       }
9532       sequence = gen_sequence ();
9533       end_sequence ();
9534       emit_insn_before (sequence, loop_start);
9535       instrument_loop_bct (loop_start, loop_end, iterations_num_reg);
9536     }
9537
9538   return;
9539 #endif /* Complex case */
9540 }
9541
9542 /* Instrument loop by inserting a bct in it as follows:
9543    1. A new counter register is created.
9544    2. In the head of the loop the new variable is initialized to the value
9545    passed in the loop_num_iterations parameter.
9546    3. At the end of the loop, comparison of the register with 0 is generated.
9547    The created comparison follows the pattern defined for the
9548    decrement_and_branch_on_count insn, so this insn will be generated.
9549    4. The branch on the old variable are deleted.  The compare must remain
9550    because it might be used elsewhere.  If the loop-variable or condition
9551    register are used elsewhere, they will be eliminated by flow.  */
9552
9553 static void
9554 instrument_loop_bct (loop_start, loop_end, loop_num_iterations)
9555      rtx loop_start, loop_end;
9556      rtx loop_num_iterations;
9557 {
9558   rtx counter_reg;
9559   rtx start_label;
9560   rtx sequence;
9561
9562   if (HAVE_decrement_and_branch_on_count)
9563     {
9564       if (loop_dump_stream)
9565         {
9566           fputs ("instrument_bct: Inserting BCT (", loop_dump_stream);
9567           if (GET_CODE (loop_num_iterations) == CONST_INT)
9568             fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC,
9569                      INTVAL (loop_num_iterations));
9570           else
9571             fputs ("runtime", loop_dump_stream);
9572           fputs (" iterations)", loop_dump_stream);
9573         }
9574
9575       /* Discard original jump to continue loop.  Original compare result
9576          may still be live, so it cannot be discarded explicitly.  */
9577       delete_insn (PREV_INSN (loop_end));
9578
9579       /* Insert the label which will delimit the start of the loop.  */
9580       start_label = gen_label_rtx ();
9581       emit_label_after (start_label, loop_start);
9582
9583       /* Insert initialization of the count register into the loop header.  */
9584       start_sequence ();
9585       counter_reg = gen_reg_rtx (word_mode);
9586       emit_insn (gen_move_insn (counter_reg, loop_num_iterations));
9587       sequence = gen_sequence ();
9588       end_sequence ();
9589       emit_insn_before (sequence, loop_start);
9590
9591       /* Insert new comparison on the count register instead of the
9592          old one, generating the needed BCT pattern (that will be
9593          later recognized by assembly generation phase).  */
9594       emit_jump_insn_before (gen_decrement_and_branch_on_count (counter_reg,
9595                                                                 start_label),
9596                              loop_end);
9597       LABEL_NUSES (start_label)++;
9598     }
9599
9600 }
9601 #endif /* HAVE_decrement_and_branch_on_count */
9602
9603 /* Scan the function and determine whether it has indirect (computed) jumps.
9604
9605    This is taken mostly from flow.c; similar code exists elsewhere
9606    in the compiler.  It may be useful to put this into rtlanal.c.  */
9607 static int
9608 indirect_jump_in_function_p (start)
9609      rtx start;
9610 {
9611   rtx insn;
9612
9613   for (insn = start; insn; insn = NEXT_INSN (insn))
9614     if (computed_jump_p (insn))
9615       return 1;
9616
9617   return 0;
9618 }
9619
9620 /* Add MEM to the LOOP_MEMS array, if appropriate.  See the
9621    documentation for LOOP_MEMS for the definition of `appropriate'.
9622    This function is called from prescan_loop via for_each_rtx.  */
9623
9624 static int
9625 insert_loop_mem (mem, data)
9626      rtx *mem;
9627      void *data ATTRIBUTE_UNUSED;
9628 {
9629   int i;
9630   rtx m = *mem;
9631
9632   if (m == NULL_RTX)
9633     return 0;
9634
9635   switch (GET_CODE (m))
9636     {
9637     case MEM:
9638       break;
9639
9640     case CLOBBER:
9641       /* We're not interested in MEMs that are only clobbered.  */
9642       return -1;
9643
9644     case CONST_DOUBLE:
9645       /* We're not interested in the MEM associated with a
9646          CONST_DOUBLE, so there's no need to traverse into this.  */
9647       return -1;
9648
9649     case EXPR_LIST:
9650       /* We're not interested in any MEMs that only appear in notes.  */
9651       return -1;
9652
9653     default:
9654       /* This is not a MEM.  */
9655       return 0;
9656     }
9657
9658   /* See if we've already seen this MEM.  */
9659   for (i = 0; i < loop_mems_idx; ++i)
9660     if (rtx_equal_p (m, loop_mems[i].mem)) 
9661       {
9662         if (GET_MODE (m) != GET_MODE (loop_mems[i].mem))
9663           /* The modes of the two memory accesses are different.  If
9664              this happens, something tricky is going on, and we just
9665              don't optimize accesses to this MEM.  */
9666           loop_mems[i].optimize = 0;
9667
9668         return 0;
9669       }
9670
9671   /* Resize the array, if necessary.  */
9672   if (loop_mems_idx == loop_mems_allocated) 
9673     {
9674       if (loop_mems_allocated != 0)
9675         loop_mems_allocated *= 2;
9676       else
9677         loop_mems_allocated = 32;
9678
9679       loop_mems = (loop_mem_info*) 
9680         xrealloc (loop_mems,
9681                   loop_mems_allocated * sizeof (loop_mem_info)); 
9682     }
9683
9684   /* Actually insert the MEM.  */
9685   loop_mems[loop_mems_idx].mem = m;
9686   /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
9687      because we can't put it in a register.  We still store it in the
9688      table, though, so that if we see the same address later, but in a
9689      non-BLK mode, we'll not think we can optimize it at that point.  */
9690   loop_mems[loop_mems_idx].optimize = (GET_MODE (m) != BLKmode);
9691   loop_mems[loop_mems_idx].reg = NULL_RTX;
9692   ++loop_mems_idx;
9693
9694   return 0;
9695 }
9696
9697 /* Like load_mems, but also ensures that SET_IN_LOOP,
9698    MAY_NOT_OPTIMIZE, REG_SINGLE_USAGE, and INSN_COUNT have the correct
9699    values after load_mems.  */
9700
9701 static void
9702 load_mems_and_recount_loop_regs_set (loop, insn_count)
9703      const struct loop *loop;
9704      int *insn_count;
9705 {
9706   int nregs = max_reg_num ();
9707
9708   load_mems (loop);
9709   
9710   /* Recalculate set_in_loop and friends since load_mems may have
9711      created new registers.  */
9712   if (max_reg_num () > nregs)
9713     {
9714       int i;
9715       int old_nregs;
9716
9717       old_nregs = nregs;
9718       nregs = max_reg_num ();
9719
9720       if ((unsigned) nregs > set_in_loop->num_elements)
9721         {
9722           /* Grow all the arrays.  */
9723           VARRAY_GROW (set_in_loop, nregs);
9724           VARRAY_GROW (n_times_set, nregs);
9725           VARRAY_GROW (may_not_optimize, nregs);
9726           VARRAY_GROW (reg_single_usage, nregs);
9727         }
9728       /* Clear the arrays */
9729       bzero ((char *) &set_in_loop->data, nregs * sizeof (int));
9730       bzero ((char *) &may_not_optimize->data, nregs * sizeof (char));
9731       bzero ((char *) &reg_single_usage->data, nregs * sizeof (rtx));
9732
9733       count_loop_regs_set (loop->top ? loop->top : loop->start, loop->end,
9734                            may_not_optimize, reg_single_usage,
9735                            insn_count, nregs); 
9736
9737       for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
9738         {
9739           VARRAY_CHAR (may_not_optimize, i) = 1;
9740           VARRAY_INT (set_in_loop, i) = 1;
9741         }
9742       
9743 #ifdef AVOID_CCMODE_COPIES
9744       /* Don't try to move insns which set CC registers if we should not
9745          create CCmode register copies.  */
9746       for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
9747         if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
9748           VARRAY_CHAR (may_not_optimize, i) = 1;
9749 #endif
9750
9751       /* Set n_times_set for the new registers.  */
9752       bcopy ((char *) (&set_in_loop->data.i[0] + old_nregs),
9753              (char *) (&n_times_set->data.i[0] + old_nregs),
9754              (nregs - old_nregs) * sizeof (int));
9755     }
9756 }
9757
9758 /* Move MEMs into registers for the duration of the loop.  */
9759
9760 static void
9761 load_mems (loop)
9762      const struct loop *loop;
9763 {
9764   int maybe_never = 0;
9765   int i;
9766   rtx p;
9767   rtx label = NULL_RTX;
9768   rtx end_label = NULL_RTX;
9769   /* Nonzero if the next instruction may never be executed.  */
9770   int next_maybe_never = 0;
9771   int last_max_reg = max_reg_num ();
9772
9773   if (loop_mems_idx == 0)
9774     return;
9775
9776   /* Check to see if it's possible that some instructions in the
9777      loop are never executed.  */
9778   for (p = next_insn_in_loop (loop, loop->scan_start); 
9779        p != NULL_RTX && ! maybe_never; 
9780        p = next_insn_in_loop (loop, p))
9781     {
9782       if (GET_CODE (p) == CODE_LABEL)
9783         maybe_never = 1;
9784       else if (GET_CODE (p) == JUMP_INSN
9785                /* If we enter the loop in the middle, and scan
9786                   around to the beginning, don't set maybe_never
9787                   for that.  This must be an unconditional jump,
9788                   otherwise the code at the top of the loop might
9789                   never be executed.  Unconditional jumps are
9790                   followed a by barrier then loop end.  */
9791                && ! (GET_CODE (p) == JUMP_INSN 
9792                      && JUMP_LABEL (p) == loop->top
9793                      && NEXT_INSN (NEXT_INSN (p)) == loop->end
9794                      && simplejump_p (p)))
9795         {
9796           if (!condjump_p (p))
9797             /* Something complicated.  */
9798             maybe_never = 1;
9799           else
9800             /* If there are any more instructions in the loop, they
9801                might not be reached.  */
9802             next_maybe_never = 1; 
9803         } 
9804       else if (next_maybe_never)
9805         maybe_never = 1;
9806     }
9807
9808   /* Actually move the MEMs.  */
9809   for (i = 0; i < loop_mems_idx; ++i) 
9810     {
9811       regset_head copies;
9812       int written = 0;
9813       rtx reg;
9814       rtx mem = loop_mems[i].mem;
9815       rtx mem_list_entry;
9816
9817       if (MEM_VOLATILE_P (mem) 
9818           || loop_invariant_p (loop, XEXP (mem, 0)) != 1)
9819         /* There's no telling whether or not MEM is modified.  */
9820         loop_mems[i].optimize = 0;
9821
9822       /* Go through the MEMs written to in the loop to see if this
9823          one is aliased by one of them.  */
9824       mem_list_entry = loop_store_mems;
9825       while (mem_list_entry)
9826         {
9827           if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
9828             written = 1;
9829           else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
9830                                     mem, rtx_varies_p))
9831             {
9832               /* MEM is indeed aliased by this store.  */
9833               loop_mems[i].optimize = 0;
9834               break;
9835             }
9836           mem_list_entry = XEXP (mem_list_entry, 1);
9837         }
9838
9839       if (flag_float_store && written
9840           && GET_MODE_CLASS (GET_MODE (mem)) == MODE_FLOAT)
9841         loop_mems[i].optimize = 0;
9842   
9843       /* If this MEM is written to, we must be sure that there
9844          are no reads from another MEM that aliases this one.  */ 
9845       if (loop_mems[i].optimize && written)
9846         {
9847           int j;
9848
9849           for (j = 0; j < loop_mems_idx; ++j)
9850             {
9851               if (j == i)
9852                 continue;
9853               else if (true_dependence (mem,
9854                                         VOIDmode,
9855                                         loop_mems[j].mem,
9856                                         rtx_varies_p))
9857                 {
9858                   /* It's not safe to hoist loop_mems[i] out of
9859                      the loop because writes to it might not be
9860                      seen by reads from loop_mems[j].  */
9861                   loop_mems[i].optimize = 0;
9862                   break;
9863                 }
9864             }
9865         }
9866
9867       if (maybe_never && may_trap_p (mem))
9868         /* We can't access the MEM outside the loop; it might
9869            cause a trap that wouldn't have happened otherwise.  */
9870         loop_mems[i].optimize = 0;
9871           
9872       if (!loop_mems[i].optimize)
9873         /* We thought we were going to lift this MEM out of the
9874            loop, but later discovered that we could not.  */
9875         continue;
9876
9877       INIT_REG_SET (&copies);
9878
9879       /* Allocate a pseudo for this MEM.  We set REG_USERVAR_P in
9880          order to keep scan_loop from moving stores to this MEM
9881          out of the loop just because this REG is neither a
9882          user-variable nor used in the loop test.  */
9883       reg = gen_reg_rtx (GET_MODE (mem));
9884       REG_USERVAR_P (reg) = 1;
9885       loop_mems[i].reg = reg;
9886
9887       /* Now, replace all references to the MEM with the
9888          corresponding pesudos.  */
9889       maybe_never = 0;
9890       for (p = next_insn_in_loop (loop, loop->scan_start);
9891            p != NULL_RTX;
9892            p = next_insn_in_loop (loop, p))
9893         {
9894           rtx_and_int ri;
9895           rtx set;
9896
9897           if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
9898             {
9899               /* See if this copies the mem into a register that isn't
9900                  modified afterwards.  We'll try to do copy propagation
9901                  a little further on.  */
9902               set = single_set (p);
9903               if (set
9904                   /* @@@ This test is _way_ too conservative.  */
9905                   && ! maybe_never
9906                   && GET_CODE (SET_DEST (set)) == REG
9907                   && REGNO (SET_DEST (set)) >= FIRST_PSEUDO_REGISTER
9908                   && REGNO (SET_DEST (set)) < last_max_reg
9909                   && VARRAY_INT (n_times_set, REGNO (SET_DEST (set))) == 1
9910                   && rtx_equal_p (SET_SRC (set), loop_mems[i].mem))
9911                 SET_REGNO_REG_SET (&copies, REGNO (SET_DEST (set)));
9912               ri.r = p;
9913               ri.i = i;
9914               for_each_rtx (&p, replace_loop_mem, &ri);
9915             }
9916
9917           if (GET_CODE (p) == CODE_LABEL
9918               || GET_CODE (p) == JUMP_INSN)
9919             maybe_never = 1;
9920         }
9921
9922       if (! apply_change_group ())
9923         /* We couldn't replace all occurrences of the MEM.  */
9924         loop_mems[i].optimize = 0;
9925       else
9926         {
9927           int j;
9928           rtx set;
9929
9930           /* Load the memory immediately before LOOP->START, which is
9931              the NOTE_LOOP_BEG.  */
9932           set = gen_move_insn (reg, mem);
9933           emit_insn_before (set, loop->start);
9934
9935           if (written)
9936             {
9937               if (label == NULL_RTX)
9938                 {
9939                   /* We must compute the former
9940                      right-after-the-end label before we insert
9941                      the new one.  */
9942                   end_label = next_label (loop->end);
9943                   label = gen_label_rtx ();
9944                   emit_label_after (label, loop->end);
9945                 }
9946
9947               /* Store the memory immediately after END, which is
9948                  the NOTE_LOOP_END.  */
9949               set = gen_move_insn (copy_rtx (mem), reg); 
9950               emit_insn_after (set, label);
9951             }
9952
9953           if (loop_dump_stream)
9954             {
9955               fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
9956                        REGNO (reg), (written ? "r/w" : "r/o"));
9957               print_rtl (loop_dump_stream, mem);
9958               fputc ('\n', loop_dump_stream);
9959             }
9960
9961           /* Attempt a bit of copy propagation.  This helps untangle the
9962              data flow, and enables {basic,general}_induction_var to find
9963              more bivs/givs.  */
9964           EXECUTE_IF_SET_IN_REG_SET
9965             (&copies, FIRST_PSEUDO_REGISTER, j,
9966              {
9967                try_copy_prop (loop, loop_mems[i].reg, j);
9968              });
9969           CLEAR_REG_SET (&copies);
9970         }
9971     }
9972
9973   if (label != NULL_RTX)
9974     {
9975       /* Now, we need to replace all references to the previous exit
9976          label with the new one.  */
9977       rtx_pair rr; 
9978       rr.r1 = end_label;
9979       rr.r2 = label;
9980
9981       for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
9982         {
9983           for_each_rtx (&p, replace_label, &rr);
9984
9985           /* If this is a JUMP_INSN, then we also need to fix the JUMP_LABEL
9986              field.  This is not handled by for_each_rtx because it doesn't
9987              handle unprinted ('0') fields.  We need to update JUMP_LABEL
9988              because the immediately following unroll pass will use it.
9989              replace_label would not work anyways, because that only handles
9990              LABEL_REFs.  */
9991           if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == end_label)
9992             JUMP_LABEL (p) = label;
9993         }
9994     }
9995 }
9996
9997 /* For communication between note_reg_stored and its caller.  */
9998 struct note_reg_stored_arg
9999 {
10000   int set_seen;
10001   rtx reg;
10002 };
10003
10004 /* Called via note_stores, record in SET_SEEN whether X, which is written,
10005    is equal to ARG.  */
10006 static void
10007 note_reg_stored (x, setter, arg)
10008      rtx x, setter ATTRIBUTE_UNUSED;
10009      void *arg;
10010 {
10011   struct note_reg_stored_arg *t = (struct note_reg_stored_arg *)arg;
10012   if (t->reg == x)
10013     t->set_seen = 1;
10014 }
10015
10016 /* Try to replace every occurrence of pseudo REGNO with REPLACEMENT.
10017    There must be exactly one insn that sets this pseudo; it will be
10018    deleted if all replacements succeed and we can prove that the register
10019    is not used after the loop.  */
10020 static void
10021 try_copy_prop (loop, replacement, regno)
10022      const struct loop *loop;
10023      rtx replacement;
10024      int regno;
10025 {
10026   /* This is the reg that we are copying from.  */
10027   rtx reg_rtx = regno_reg_rtx[regno];
10028   rtx init_insn = 0;
10029   rtx insn;
10030   /* These help keep track of whether we replaced all uses of the reg.  */
10031   int replaced_last = 0;
10032   int store_is_first = 0;
10033
10034   for (insn = next_insn_in_loop (loop, loop->scan_start);
10035        insn != NULL_RTX;
10036        insn = next_insn_in_loop (loop, insn))
10037     {
10038       rtx set;
10039
10040       /* Only substitute within one extended basic block from the initializing
10041          insn.  */
10042       if (GET_CODE (insn) == CODE_LABEL && init_insn)
10043         break;
10044
10045       if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
10046         continue;
10047
10048       /* Is this the initializing insn?  */
10049       set = single_set (insn);
10050       if (set
10051           && GET_CODE (SET_DEST (set)) == REG
10052           && REGNO (SET_DEST (set)) == regno)
10053         {
10054           if (init_insn)
10055             abort ();
10056
10057           init_insn = insn;
10058           if (REGNO_FIRST_UID (regno) == INSN_UID (insn))
10059             store_is_first = 1;
10060         }
10061
10062       /* Only substitute after seeing the initializing insn.  */
10063       if (init_insn && insn != init_insn)
10064         {       
10065           struct note_reg_stored_arg arg;
10066           rtx array[3];
10067           array[0] = reg_rtx;
10068           array[1] = replacement;
10069           array[2] = insn;
10070
10071           for_each_rtx (&insn, replace_loop_reg, array);
10072           if (REGNO_LAST_UID (regno) == INSN_UID (insn))
10073             replaced_last = 1;
10074
10075           /* Stop replacing when REPLACEMENT is modified.  */
10076           arg.reg = replacement;
10077           arg.set_seen = 0;
10078           note_stores (PATTERN (insn), note_reg_stored, &arg);
10079           if (arg.set_seen)
10080             break;
10081         }
10082     }
10083   if (! init_insn)
10084     abort ();
10085   if (apply_change_group ())
10086     {
10087       if (loop_dump_stream)
10088         fprintf (loop_dump_stream, "  Replaced reg %d", regno);
10089       if (store_is_first && replaced_last)
10090         {
10091           PUT_CODE (init_insn, NOTE);
10092           NOTE_LINE_NUMBER (init_insn) = NOTE_INSN_DELETED;
10093           if (loop_dump_stream)
10094             fprintf (loop_dump_stream, ", deleting init_insn (%d)",
10095                      INSN_UID (init_insn));
10096         }
10097       if (loop_dump_stream)
10098         fprintf (loop_dump_stream, ".\n");
10099     }
10100 }
10101
10102 /* Replace MEM with its associated pseudo register.  This function is
10103    called from load_mems via for_each_rtx.  DATA is actually an
10104    rtx_and_int * describing the instruction currently being scanned
10105    and the MEM we are currently replacing.  */
10106
10107 static int
10108 replace_loop_mem (mem, data)
10109      rtx *mem;
10110      void *data;
10111 {
10112   rtx_and_int *ri; 
10113   rtx insn;
10114   int i;
10115   rtx m = *mem;
10116
10117   if (m == NULL_RTX)
10118     return 0;
10119
10120   switch (GET_CODE (m))
10121     {
10122     case MEM:
10123       break;
10124
10125     case CONST_DOUBLE:
10126       /* We're not interested in the MEM associated with a
10127          CONST_DOUBLE, so there's no need to traverse into one.  */
10128       return -1;
10129
10130     default:
10131       /* This is not a MEM.  */
10132       return 0;
10133     }
10134
10135   ri = (rtx_and_int*) data;
10136   i = ri->i;
10137
10138   if (!rtx_equal_p (loop_mems[i].mem, m))
10139     /* This is not the MEM we are currently replacing.  */
10140     return 0;
10141
10142   insn = ri->r;
10143
10144   /* Actually replace the MEM.  */
10145   validate_change (insn, mem, loop_mems[i].reg, 1);
10146
10147   return 0;
10148 }
10149
10150 /* Replace one register with another.  Called through for_each_rtx; PX points
10151    to the rtx being scanned.  DATA is actually an array of three rtx's; the
10152    first one is the one to be replaced, and the second one the replacement.
10153    The third one is the current insn.  */
10154
10155 static int
10156 replace_loop_reg (px, data)
10157      rtx *px;
10158      void *data;
10159 {
10160   rtx x = *px;
10161   rtx *array = (rtx *)data;
10162
10163   if (x == NULL_RTX)
10164     return 0;
10165
10166   if (x == array[0])
10167     validate_change (array[2], px, array[1], 1);
10168
10169   return 0;
10170 }
10171
10172 /* Replace occurrences of the old exit label for the loop with the new
10173    one.  DATA is an rtx_pair containing the old and new labels,
10174    respectively.  */
10175
10176 static int
10177 replace_label (x, data)
10178      rtx *x;
10179      void *data;
10180 {
10181   rtx l = *x;
10182   rtx old_label = ((rtx_pair*) data)->r1;
10183   rtx new_label = ((rtx_pair*) data)->r2;
10184
10185   if (l == NULL_RTX)
10186     return 0;
10187
10188   if (GET_CODE (l) != LABEL_REF)
10189     return 0;
10190
10191   if (XEXP (l, 0) != old_label)
10192     return 0;
10193   
10194   XEXP (l, 0) = new_label;
10195   ++LABEL_NUSES (new_label);
10196   --LABEL_NUSES (old_label);
10197
10198   return 0;
10199 }