OSDN Git Service

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