OSDN Git Service

update copyrights
[pf3gnuchains/gcc-fork.git] / gcc / loop.c
1 /* Perform various loop optimizations, including strength reduction.
2    Copyright (C) 1987, 88, 89, 91-97, 1998 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 "expr.h"
42 #include "insn-config.h"
43 #include "insn-flags.h"
44 #include "regs.h"
45 #include "hard-reg-set.h"
46 #include "recog.h"
47 #include "flags.h"
48 #include "real.h"
49 #include "loop.h"
50 #include "except.h"
51 #include "toplev.h"
52
53 /* Vector mapping INSN_UIDs to luids.
54    The luids are like uids but increase monotonically always.
55    We use them to see whether a jump comes from outside a given loop.  */
56
57 int *uid_luid;
58
59 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
60    number the insn is contained in.  */
61
62 int *uid_loop_num;
63
64 /* 1 + largest uid of any insn.  */
65
66 int max_uid_for_loop;
67
68 /* 1 + luid of last insn.  */
69
70 static int max_luid;
71
72 /* Number of loops detected in current function.  Used as index to the
73    next few tables.  */
74
75 static int max_loop_num;
76
77 /* Indexed by loop number, contains the first and last insn of each loop.  */
78
79 static rtx *loop_number_loop_starts, *loop_number_loop_ends;
80
81 /* For each loop, gives the containing loop number, -1 if none.  */
82
83 int *loop_outer_loop;
84
85 #ifdef HAVE_decrement_and_branch_on_count
86 /* Records whether resource in use by inner loop.  */
87
88 int *loop_used_count_register;
89 #endif  /* HAVE_decrement_and_branch_on_count */
90
91 /* For each loop, keep track of its unrolling factor.
92    Potential values:
93       0: unrolled
94       1: not unrolled.
95      -1: completely unrolled
96      >0: holds the unroll exact factor.  */
97 int *loop_unroll_factor;
98
99 /* Indexed by loop number, contains a nonzero value if the "loop" isn't
100    really a loop (an insn outside the loop branches into it).  */
101
102 static char *loop_invalid;
103
104 /* Indexed by loop number, links together all LABEL_REFs which refer to
105    code labels outside the loop.  Used by routines that need to know all
106    loop exits, such as final_biv_value and final_giv_value.
107
108    This does not include loop exits due to return instructions.  This is
109    because all bivs and givs are pseudos, and hence must be dead after a
110    return, so the presense of a return does not affect any of the
111    optimizations that use this info.  It is simpler to just not include return
112    instructions on this list.  */
113
114 rtx *loop_number_exit_labels;
115
116 /* Indexed by loop number, counts the number of LABEL_REFs on
117    loop_number_exit_labels for this loop and all loops nested inside it.  */
118
119 int *loop_number_exit_count;
120
121 /* Holds the number of loop iterations.  It is zero if the number could not be
122    calculated.  Must be unsigned since the number of iterations can
123    be as high as 2^wordsize-1.  For loops with a wider iterator, this number
124    will be zero if the number of loop iterations is too large for an
125    unsigned integer to hold.  */
126
127 unsigned HOST_WIDE_INT loop_n_iterations;
128
129 /* Nonzero if there is a subroutine call in the current loop.  */
130
131 static int loop_has_call;
132
133 /* Nonzero if there is a volatile memory reference in the current
134    loop.  */
135
136 static int loop_has_volatile;
137
138 /* Nonzero if there is a tablejump in the current loop.  */
139
140 static int loop_has_tablejump;
141
142 /* Added loop_continue which is the NOTE_INSN_LOOP_CONT of the
143    current loop.  A continue statement will generate a branch to
144    NEXT_INSN (loop_continue).  */
145
146 static rtx loop_continue;
147
148 /* Indexed by register number, contains the number of times the reg
149    is set during the loop being scanned.
150    During code motion, a negative value indicates a reg that has been
151    made a candidate; in particular -2 means that it is an candidate that
152    we know is equal to a constant and -1 means that it is an candidate
153    not known equal to a constant.
154    After code motion, regs moved have 0 (which is accurate now)
155    while the failed candidates have the original number of times set.
156
157    Therefore, at all times, == 0 indicates an invariant register;
158    < 0 a conditionally invariant one.  */
159
160 static varray_type n_times_set;
161
162 /* Original value of n_times_set; same except that this value
163    is not set negative for a reg whose sets have been made candidates
164    and not set to 0 for a reg that is moved.  */
165
166 static varray_type n_times_used;
167
168 /* Index by register number, 1 indicates that the register
169    cannot be moved or strength reduced.  */
170
171 static varray_type may_not_optimize;
172
173 /* Nonzero means reg N has already been moved out of one loop.
174    This reduces the desire to move it out of another.  */
175
176 static char *moved_once;
177
178 /* Array of MEMs that are stored in this loop. If there are too many to fit
179    here, we just turn on unknown_address_altered.  */
180
181 #define NUM_STORES 30
182 static rtx loop_store_mems[NUM_STORES];
183
184 /* Index of first available slot in above array.  */
185 static int loop_store_mems_idx;
186
187 typedef struct loop_mem_info {
188   rtx mem;      /* The MEM itself.  */
189   rtx reg;      /* Corresponding pseudo, if any.  */
190   int optimize; /* Nonzero if we can optimize access to this MEM.  */
191 } loop_mem_info;
192
193 /* Array of MEMs that are used (read or written) in this loop, but
194    cannot be aliased by anything in this loop, except perhaps
195    themselves.  In other words, if loop_mems[i] is altered during the
196    loop, it is altered by an expression that is rtx_equal_p to it.  */
197
198 static loop_mem_info *loop_mems;
199
200 /* The index of the next available slot in LOOP_MEMS.  */
201
202 static int loop_mems_idx;
203
204 /* The number of elements allocated in LOOP_MEMs.  */
205
206 static int loop_mems_allocated;
207
208 /* Nonzero if we don't know what MEMs were changed in the current loop.
209    This happens if the loop contains a call (in which case `loop_has_call'
210    will also be set) or if we store into more than NUM_STORES MEMs.  */
211
212 static int unknown_address_altered;
213
214 /* Count of movable (i.e. invariant) instructions discovered in the loop.  */
215 static int num_movables;
216
217 /* Count of memory write instructions discovered in the loop.  */
218 static int num_mem_sets;
219
220 /* Number of loops contained within the current one, including itself.  */
221 static int loops_enclosed;
222
223 /* Bound on pseudo register number before loop optimization.
224    A pseudo has valid regscan info if its number is < max_reg_before_loop.  */
225 int max_reg_before_loop;
226
227 /* This obstack is used in product_cheap_p to allocate its rtl.  It
228    may call gen_reg_rtx which, in turn, may reallocate regno_reg_rtx.
229    If we used the same obstack that it did, we would be deallocating
230    that array.  */
231
232 static struct obstack temp_obstack;
233
234 /* This is where the pointer to the obstack being used for RTL is stored.  */
235
236 extern struct obstack *rtl_obstack;
237
238 #define obstack_chunk_alloc xmalloc
239 #define obstack_chunk_free free
240 \f
241 /* During the analysis of a loop, a chain of `struct movable's
242    is made to record all the movable insns found.
243    Then the entire chain can be scanned to decide which to move.  */
244
245 struct movable
246 {
247   rtx insn;                     /* A movable insn */
248   rtx set_src;                  /* The expression this reg is set from.  */
249   rtx set_dest;                 /* The destination of this SET.  */
250   rtx dependencies;             /* When INSN is libcall, this is an EXPR_LIST
251                                    of any registers used within the LIBCALL.  */
252   int consec;                   /* Number of consecutive following insns 
253                                    that must be moved with this one.  */
254   int regno;                    /* The register it sets */
255   short lifetime;               /* lifetime of that register;
256                                    may be adjusted when matching movables
257                                    that load the same value are found.  */
258   short savings;                /* Number of insns we can move for this reg,
259                                    including other movables that force this
260                                    or match this one.  */
261   unsigned int cond : 1;        /* 1 if only conditionally movable */
262   unsigned int force : 1;       /* 1 means MUST move this insn */
263   unsigned int global : 1;      /* 1 means reg is live outside this loop */
264                 /* If PARTIAL is 1, GLOBAL means something different:
265                    that the reg is live outside the range from where it is set
266                    to the following label.  */
267   unsigned int done : 1;        /* 1 inhibits further processing of this */
268   
269   unsigned int partial : 1;     /* 1 means this reg is used for zero-extending.
270                                    In particular, moving it does not make it
271                                    invariant.  */
272   unsigned int move_insn : 1;   /* 1 means that we call emit_move_insn to
273                                    load SRC, rather than copying INSN.  */
274   unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
275                                     first insn of a consecutive sets group.  */
276   unsigned int is_equiv : 1;    /* 1 means a REG_EQUIV is present on INSN.  */
277   enum machine_mode savemode;   /* Nonzero means it is a mode for a low part
278                                    that we should avoid changing when clearing
279                                    the rest of the reg.  */
280   struct movable *match;        /* First entry for same value */
281   struct movable *forces;       /* An insn that must be moved if this is */
282   struct movable *next;
283 };
284
285 static struct movable *the_movables;
286
287 FILE *loop_dump_stream;
288
289 /* Forward declarations.  */
290
291 static void find_and_verify_loops PROTO((rtx));
292 static void mark_loop_jump PROTO((rtx, int));
293 static void prescan_loop PROTO((rtx, rtx));
294 static int reg_in_basic_block_p PROTO((rtx, rtx));
295 static int consec_sets_invariant_p PROTO((rtx, int, rtx));
296 static rtx libcall_other_reg PROTO((rtx, rtx));
297 static int labels_in_range_p PROTO((rtx, int));
298 static void count_one_set PROTO((rtx, rtx, varray_type, rtx *));
299
300 static void count_loop_regs_set PROTO((rtx, rtx, varray_type, varray_type,
301                                        int *, int)); 
302 static void note_addr_stored PROTO((rtx, rtx));
303 static int loop_reg_used_before_p PROTO((rtx, rtx, rtx, rtx, rtx));
304 static void scan_loop PROTO((rtx, rtx, int, int));
305 #if 0
306 static void replace_call_address PROTO((rtx, rtx, rtx));
307 #endif
308 static rtx skip_consec_insns PROTO((rtx, int));
309 static int libcall_benefit PROTO((rtx));
310 static void ignore_some_movables PROTO((struct movable *));
311 static void force_movables PROTO((struct movable *));
312 static void combine_movables PROTO((struct movable *, int));
313 static int regs_match_p PROTO((rtx, rtx, struct movable *));
314 static int rtx_equal_for_loop_p PROTO((rtx, rtx, struct movable *));
315 static void add_label_notes PROTO((rtx, rtx));
316 static void move_movables PROTO((struct movable *, int, int, rtx, rtx, int));
317 static int count_nonfixed_reads PROTO((rtx));
318 static void strength_reduce PROTO((rtx, rtx, rtx, int, rtx, rtx, int, int));
319 static void find_single_use_in_loop PROTO((rtx, rtx, varray_type));
320 static int valid_initial_value_p PROTO((rtx, rtx, int, rtx));
321 static void find_mem_givs PROTO((rtx, rtx, int, rtx, rtx));
322 static void record_biv PROTO((struct induction *, rtx, rtx, rtx, rtx, int, int));
323 static void check_final_value PROTO((struct induction *, rtx, rtx));
324 static void record_giv PROTO((struct induction *, rtx, rtx, rtx, rtx, rtx, int, enum g_types, int, rtx *, rtx, rtx));
325 static void update_giv_derive PROTO((rtx));
326 static int basic_induction_var PROTO((rtx, enum machine_mode, rtx, rtx, rtx *, rtx *));
327 static rtx simplify_giv_expr PROTO((rtx, int *));
328 static int general_induction_var PROTO((rtx, rtx *, rtx *, rtx *, int, int *));
329 static int consec_sets_giv PROTO((int, rtx, rtx, rtx, rtx *, rtx *));
330 static int check_dbra_loop PROTO((rtx, int, rtx));
331 static rtx express_from_1 PROTO((rtx, rtx, rtx));
332 static rtx express_from PROTO((struct induction *, struct induction *));
333 static rtx combine_givs_p PROTO((struct induction *, struct induction *));
334 static void combine_givs PROTO((struct iv_class *));
335 static int product_cheap_p PROTO((rtx, rtx));
336 static int maybe_eliminate_biv PROTO((struct iv_class *, rtx, rtx, int, int, int));
337 static int maybe_eliminate_biv_1 PROTO((rtx, rtx, struct iv_class *, int, rtx));
338 static int last_use_this_basic_block PROTO((rtx, rtx));
339 static void record_initial PROTO((rtx, rtx));
340 static void update_reg_last_use PROTO((rtx, rtx));
341 static rtx next_insn_in_loop PROTO((rtx, rtx, rtx, rtx));
342 static void load_mems_and_recount_loop_regs_set PROTO((rtx, rtx, rtx,
343                                                        rtx, varray_type, 
344                                                        int *));
345 static void load_mems PROTO((rtx, rtx, rtx, rtx));
346 static int insert_loop_mem PROTO((rtx *, void *));
347 static int replace_loop_mem PROTO((rtx *, void *));
348 static int replace_label PROTO((rtx *, void *));
349
350 typedef struct rtx_and_int {
351   rtx r;
352   int i;
353 } rtx_and_int;
354
355 typedef struct rtx_pair {
356   rtx r1;
357   rtx r2;
358 } rtx_pair;
359
360 /* Nonzero iff INSN is between START and END, inclusive.  */
361 #define INSN_IN_RANGE_P(INSN, START, END)       \
362   (INSN_UID (INSN) < max_uid_for_loop           \
363    && INSN_LUID (INSN) >= INSN_LUID (START)     \
364    && INSN_LUID (INSN) <= INSN_LUID (END))
365
366 #ifdef HAVE_decrement_and_branch_on_count
367 /* Test whether BCT applicable and safe.  */
368 static void insert_bct PROTO((rtx, rtx));
369
370 /* Auxiliary function that inserts the BCT pattern into the loop.  */
371 static void instrument_loop_bct PROTO((rtx, rtx, rtx));
372 #endif /* HAVE_decrement_and_branch_on_count */
373
374 /* Indirect_jump_in_function is computed once per function.  */
375 int indirect_jump_in_function = 0;
376 static int indirect_jump_in_function_p PROTO((rtx));
377
378 \f
379 /* Relative gain of eliminating various kinds of operations.  */
380 static int add_cost;
381 #if 0
382 static int shift_cost;
383 static int mult_cost;
384 #endif
385
386 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
387    copy the value of the strength reduced giv to its original register.  */
388 static int copy_cost;
389
390 /* Cost of using a register, to normalize the benefits of a giv.  */
391 static int reg_address_cost;
392
393
394 void
395 init_loop ()
396 {
397   char *free_point = (char *) oballoc (1);
398   rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
399
400   add_cost = rtx_cost (gen_rtx_PLUS (word_mode, reg, reg), SET);
401
402 #ifdef ADDRESS_COST
403   reg_address_cost = ADDRESS_COST (reg);
404 #else
405   reg_address_cost = rtx_cost (reg, MEM);
406 #endif
407
408   /* We multiply by 2 to reconcile the difference in scale between
409      these two ways of computing costs.  Otherwise the cost of a copy
410      will be far less than the cost of an add.  */
411
412   copy_cost = 2 * 2;
413
414   /* Free the objects we just allocated.  */
415   obfree (free_point);
416
417   /* Initialize the obstack used for rtl in product_cheap_p.  */
418   gcc_obstack_init (&temp_obstack);
419 }
420 \f
421 /* Entry point of this file.  Perform loop optimization
422    on the current function.  F is the first insn of the function
423    and DUMPFILE is a stream for output of a trace of actions taken
424    (or 0 if none should be output).  */
425
426 void
427 loop_optimize (f, dumpfile, unroll_p, bct_p)
428      /* f is the first instruction of a chain of insns for one function */
429      rtx f;
430      FILE *dumpfile;
431      int unroll_p, bct_p;
432 {
433   register rtx insn;
434   register int i;
435   rtx last_insn;
436
437   loop_dump_stream = dumpfile;
438
439   init_recog_no_volatile ();
440
441   max_reg_before_loop = max_reg_num ();
442
443   moved_once = (char *) alloca (max_reg_before_loop);
444   bzero (moved_once, max_reg_before_loop);
445
446   regs_may_share = 0;
447
448   /* Count the number of loops.  */
449
450   max_loop_num = 0;
451   for (insn = f; insn; insn = NEXT_INSN (insn))
452     {
453       if (GET_CODE (insn) == NOTE
454           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
455         max_loop_num++;
456     }
457
458   /* Don't waste time if no loops.  */
459   if (max_loop_num == 0)
460     return;
461
462   /* Get size to use for tables indexed by uids.
463      Leave some space for labels allocated by find_and_verify_loops.  */
464   max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
465
466   uid_luid = (int *) alloca (max_uid_for_loop * sizeof (int));
467   uid_loop_num = (int *) alloca (max_uid_for_loop * sizeof (int));
468
469   bzero ((char *) uid_luid, max_uid_for_loop * sizeof (int));
470   bzero ((char *) uid_loop_num, max_uid_for_loop * sizeof (int));
471
472   /* Allocate tables for recording each loop.  We set each entry, so they need
473      not be zeroed.  */
474   loop_number_loop_starts = (rtx *) alloca (max_loop_num * sizeof (rtx));
475   loop_number_loop_ends = (rtx *) alloca (max_loop_num * sizeof (rtx));
476   loop_outer_loop = (int *) alloca (max_loop_num * sizeof (int));
477   loop_invalid = (char *) alloca (max_loop_num * sizeof (char));
478   loop_number_exit_labels = (rtx *) alloca (max_loop_num * sizeof (rtx));
479   loop_number_exit_count = (int *) alloca (max_loop_num * sizeof (int));
480
481   /* This is initialized by the unrolling code, so we go ahead
482      and clear them just in case we are not performing loop
483      unrolling.  */
484   loop_unroll_factor = (int *) alloca (max_loop_num *sizeof (int));
485   bzero ((char *) loop_unroll_factor, max_loop_num * sizeof (int));
486
487 #ifdef HAVE_decrement_and_branch_on_count
488   /* Allocate for BCT optimization */
489   loop_used_count_register = (int *) alloca (max_loop_num * sizeof (int));
490   bzero ((char *) loop_used_count_register, max_loop_num * sizeof (int));
491 #endif  /* HAVE_decrement_and_branch_on_count */
492
493   /* Find and process each loop.
494      First, find them, and record them in order of their beginnings.  */
495   find_and_verify_loops (f);
496
497   /* Now find all register lifetimes.  This must be done after
498      find_and_verify_loops, because it might reorder the insns in the
499      function.  */
500   reg_scan (f, max_reg_num (), 1);
501
502   /* This must occur after reg_scan so that registers created by gcse
503      will have entries in the register tables.
504
505      We could have added a call to reg_scan after gcse_main in toplev.c,
506      but moving this call to init_alias_analysis is more efficient.  */
507   init_alias_analysis ();
508
509   /* See if we went too far.  */
510   if (get_max_uid () > max_uid_for_loop)
511     abort ();
512   /* Now reset it to the actual size we need.  See above.  */
513   max_uid_for_loop = get_max_uid () + 1;
514
515   /* Compute the mapping from uids to luids.
516      LUIDs are numbers assigned to insns, like uids,
517      except that luids increase monotonically through the code.
518      Don't assign luids to line-number NOTEs, so that the distance in luids
519      between two insns is not affected by -g.  */
520
521   for (insn = f, i = 0; insn; insn = NEXT_INSN (insn))
522     {
523       last_insn = insn;
524       if (GET_CODE (insn) != NOTE
525           || NOTE_LINE_NUMBER (insn) <= 0)
526         uid_luid[INSN_UID (insn)] = ++i;
527       else
528         /* Give a line number note the same luid as preceding insn.  */
529         uid_luid[INSN_UID (insn)] = i;
530     }
531
532   max_luid = i + 1;
533
534   /* Don't leave gaps in uid_luid for insns that have been
535      deleted.  It is possible that the first or last insn
536      using some register has been deleted by cross-jumping.
537      Make sure that uid_luid for that former insn's uid
538      points to the general area where that insn used to be.  */
539   for (i = 0; i < max_uid_for_loop; i++)
540     {
541       uid_luid[0] = uid_luid[i];
542       if (uid_luid[0] != 0)
543         break;
544     }
545   for (i = 0; i < max_uid_for_loop; i++)
546     if (uid_luid[i] == 0)
547       uid_luid[i] = uid_luid[i - 1];
548
549   /* Create a mapping from loops to BLOCK tree nodes.  */
550   if (unroll_p && write_symbols != NO_DEBUG)
551     find_loop_tree_blocks ();
552
553   /* Determine if the function has indirect jump.  On some systems
554      this prevents low overhead loop instructions from being used.  */
555   indirect_jump_in_function = indirect_jump_in_function_p (f);
556
557   /* Now scan the loops, last ones first, since this means inner ones are done
558      before outer ones.  */
559   for (i = max_loop_num-1; i >= 0; i--)
560     if (! loop_invalid[i] && loop_number_loop_ends[i])
561       scan_loop (loop_number_loop_starts[i], loop_number_loop_ends[i],
562                  unroll_p, bct_p);
563
564   /* If debugging and unrolling loops, we must replicate the tree nodes
565      corresponding to the blocks inside the loop, so that the original one
566      to one mapping will remain.  */
567   if (unroll_p && write_symbols != NO_DEBUG)
568     unroll_block_trees ();
569
570   end_alias_analysis ();
571 }
572 \f
573 /* Returns the next insn, in execution order, after INSN.  START and
574    END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
575    respectively.  LOOP_TOP, if non-NULL, is the top of the loop in the
576    insn-stream; it is used with loops that are entered near the
577    bottom.  */
578
579 static rtx
580 next_insn_in_loop (insn, start, end, loop_top)
581      rtx insn;
582      rtx start;
583      rtx end;
584      rtx loop_top;
585 {
586   insn = NEXT_INSN (insn);
587
588   if (insn == end)
589     {
590       if (loop_top)
591         /* Go to the top of the loop, and continue there.  */
592         insn = loop_top;
593       else
594         /* We're done.  */
595         insn = NULL_RTX;
596     }
597
598   if (insn == start)
599     /* We're done.  */
600     insn = NULL_RTX;
601
602   return insn;
603 }
604
605 /* Optimize one loop whose start is LOOP_START and end is END.
606    LOOP_START is the NOTE_INSN_LOOP_BEG and END is the matching
607    NOTE_INSN_LOOP_END.  */
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, unroll_p, bct_p)
617      rtx loop_start, end;
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   /* If we have calls, contains the insn in which a register was used
651      if it was used exactly once; contains const0_rtx if it was used more
652      than once.  */
653   varray_type reg_single_usage = 0;
654   /* Nonzero if we are scanning instructions in a sub-loop.  */
655   int loop_depth = 0;
656   int nregs;
657
658   /* Determine whether this loop starts with a jump down to a test at
659      the end.  This will occur for a small number of loops with a test
660      that is too complex to duplicate in front of the loop.
661
662      We search for the first insn or label in the loop, skipping NOTEs.
663      However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
664      (because we might have a loop executed only once that contains a
665      loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
666      (in case we have a degenerate loop).
667
668      Note that if we mistakenly think that a loop is entered at the top
669      when, in fact, it is entered at the exit test, the only effect will be
670      slightly poorer optimization.  Making the opposite error can generate
671      incorrect code.  Since very few loops now start with a jump to the 
672      exit test, the code here to detect that case is very conservative.  */
673
674   for (p = NEXT_INSN (loop_start);
675        p != end
676          && GET_CODE (p) != CODE_LABEL && GET_RTX_CLASS (GET_CODE (p)) != 'i'
677          && (GET_CODE (p) != NOTE
678              || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
679                  && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
680        p = NEXT_INSN (p))
681     ;
682
683   scan_start = p;
684
685   /* Set up variables describing this loop.  */
686   prescan_loop (loop_start, end);
687   threshold = (loop_has_call ? 1 : 2) * (1 + n_non_fixed_regs);
688
689   /* If loop has a jump before the first label,
690      the true entry is the target of that jump.
691      Start scan from there.
692      But record in LOOP_TOP the place where the end-test jumps
693      back to so we can scan that after the end of the loop.  */
694   if (GET_CODE (p) == JUMP_INSN)
695     {
696       loop_entry_jump = p;
697
698       /* Loop entry must be unconditional jump (and not a RETURN)  */
699       if (simplejump_p (p)
700           && JUMP_LABEL (p) != 0
701           /* Check to see whether the jump actually
702              jumps out of the loop (meaning it's no loop).
703              This case can happen for things like
704              do {..} while (0).  If this label was generated previously
705              by loop, we can't tell anything about it and have to reject
706              the loop.  */
707           && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, end))
708         {
709           loop_top = next_label (scan_start);
710           scan_start = JUMP_LABEL (p);
711         }
712     }
713
714   /* If SCAN_START was an insn created by loop, we don't know its luid
715      as required by loop_reg_used_before_p.  So skip such loops.  (This
716      test may never be true, but it's best to play it safe.) 
717
718      Also, skip loops where we do not start scanning at a label.  This
719      test also rejects loops starting with a JUMP_INSN that failed the
720      test above.  */
721
722   if (INSN_UID (scan_start) >= max_uid_for_loop
723       || GET_CODE (scan_start) != CODE_LABEL)
724     {
725       if (loop_dump_stream)
726         fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
727                  INSN_UID (loop_start), INSN_UID (end));
728       return;
729     }
730
731   /* Count number of times each reg is set during this loop.
732      Set VARRAY_CHAR (may_not_optimize, I) if it is not safe to move out
733      the setting of register I.  If this loop has calls, set
734      VARRAY_RTX (reg_single_usage, I).  */
735   
736   /* Allocate extra space for REGS that might be created by
737      load_mems.  We allocate a little extra slop as well, in the hopes
738      that even after the moving of movables creates some new registers
739      we won't have to reallocate these arrays.  However, we do grow
740      the arrays, if necessary, in load_mems_recount_loop_regs_set.  */
741   nregs = max_reg_num () + loop_mems_idx + 16;
742   VARRAY_INT_INIT (n_times_set, nregs, "n_times_set");
743   VARRAY_INT_INIT (n_times_used, nregs, "n_times_used");
744   VARRAY_CHAR_INIT (may_not_optimize, nregs, "may_not_optimize");
745
746   if (loop_has_call)
747     VARRAY_RTX_INIT (reg_single_usage, nregs, "reg_single_usage");
748
749   count_loop_regs_set (loop_top ? loop_top : loop_start, end,
750                        may_not_optimize, reg_single_usage, &insn_count, nregs);
751
752   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
753     {
754       VARRAY_CHAR (may_not_optimize, i) = 1;
755       VARRAY_INT (n_times_set, i) = 1;
756     }
757
758 #ifdef AVOID_CCMODE_COPIES
759   /* Don't try to move insns which set CC registers if we should not
760      create CCmode register copies.  */
761   for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
762     if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
763       VARRAY_CHAR (may_not_optimize, i) = 1;
764 #endif
765
766   bcopy ((char *) &n_times_set->data, 
767          (char *) &n_times_used->data, nregs * sizeof (int));
768
769   if (loop_dump_stream)
770     {
771       fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
772                INSN_UID (loop_start), INSN_UID (end), insn_count);
773       if (loop_continue)
774         fprintf (loop_dump_stream, "Continue at insn %d.\n",
775                  INSN_UID (loop_continue));
776     }
777
778   /* Scan through the loop finding insns that are safe to move.
779      Set n_times_set negative for the reg being set, so that
780      this reg will be considered invariant for subsequent insns.
781      We consider whether subsequent insns use the reg
782      in deciding whether it is worth actually moving.
783
784      MAYBE_NEVER is nonzero if we have passed a conditional jump insn
785      and therefore it is possible that the insns we are scanning
786      would never be executed.  At such times, we must make sure
787      that it is safe to execute the insn once instead of zero times.
788      When MAYBE_NEVER is 0, all insns will be executed at least once
789      so that is not a problem.  */
790
791   for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top); 
792        p != NULL_RTX;
793        p = next_insn_in_loop (p, scan_start, end, loop_top))
794     {
795       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
796           && find_reg_note (p, REG_LIBCALL, NULL_RTX))
797         in_libcall = 1;
798       else if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
799                && find_reg_note (p, REG_RETVAL, NULL_RTX))
800         in_libcall = 0;
801
802       if (GET_CODE (p) == INSN
803           && (set = single_set (p))
804           && GET_CODE (SET_DEST (set)) == REG
805           && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
806         {
807           int tem1 = 0;
808           int tem2 = 0;
809           int move_insn = 0;
810           rtx src = SET_SRC (set);
811           rtx dependencies = 0;
812
813           /* Figure out what to use as a source of this insn.  If a REG_EQUIV
814              note is given or if a REG_EQUAL note with a constant operand is
815              specified, use it as the source and mark that we should move
816              this insn by calling emit_move_insn rather that duplicating the
817              insn.
818
819              Otherwise, only use the REG_EQUAL contents if a REG_RETVAL note
820              is present.  */
821           temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
822           if (temp)
823             src = XEXP (temp, 0), move_insn = 1;
824           else 
825             {
826               temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
827               if (temp && CONSTANT_P (XEXP (temp, 0)))
828                 src = XEXP (temp, 0), move_insn = 1;
829               if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
830                 {
831                   src = XEXP (temp, 0);
832                   /* A libcall block can use regs that don't appear in
833                      the equivalent expression.  To move the libcall,
834                      we must move those regs too.  */
835                   dependencies = libcall_other_reg (p, src);
836                 }
837             }
838
839           /* Don't try to optimize a register that was made
840              by loop-optimization for an inner loop.
841              We don't know its life-span, so we can't compute the benefit.  */
842           if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
843             ;
844           else if (/* The set is not guaranteed to be executed one
845                       the loop starts, or the value before the set is
846                       needed before the set occurs... */
847                    (maybe_never
848                     || loop_reg_used_before_p (set, p, loop_start,
849                                                scan_start, end))
850                    /* And the register is used in basic blocks other
851                       than the one where it is set (meaning that
852                       something after this point in the loop might
853                       depend on its value before the set).  */
854                    && !reg_in_basic_block_p (p, SET_DEST (set)))
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 (n_times_set, 
865                                    REGNO (SET_DEST (set))) == 1
866                        || (tem1
867                            = consec_sets_invariant_p 
868                            (SET_DEST (set),
869                             VARRAY_INT (n_times_set, 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 (reg_single_usage && VARRAY_RTX (reg_single_usage, regno) != 0
897                   && VARRAY_RTX (reg_single_usage, regno) != const0_rtx
898                   && REGNO_FIRST_UID (regno) == INSN_UID (p)
899                   && (REGNO_LAST_UID (regno)
900                       == INSN_UID (VARRAY_RTX (reg_single_usage, regno)))
901                   && VARRAY_INT (n_times_set, regno) == 1
902                   && ! side_effects_p (SET_SRC (set))
903                   && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
904                   && (! SMALL_REGISTER_CLASSES
905                       || (! (GET_CODE (SET_SRC (set)) == REG
906                              && REGNO (SET_SRC (set)) < FIRST_PSEUDO_REGISTER)))
907                   /* This test is not redundant; SET_SRC (set) might be
908                      a call-clobbered register and the life of REGNO
909                      might span a call.  */
910                   && ! modified_between_p (SET_SRC (set), p,
911                                            VARRAY_RTX
912                                            (reg_single_usage, regno)) 
913                   && no_labels_between_p (p, VARRAY_RTX (reg_single_usage, regno))
914                   && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
915                                            VARRAY_RTX
916                                            (reg_single_usage, regno))) 
917                 {
918                   /* Replace any usage in a REG_EQUAL note.  Must copy the
919                      new source, so that we don't get rtx sharing between the
920                      SET_SOURCE and REG_NOTES of insn p.  */
921                   REG_NOTES (VARRAY_RTX (reg_single_usage, regno))
922                     = replace_rtx (REG_NOTES (VARRAY_RTX
923                                               (reg_single_usage, regno)), 
924                                    SET_DEST (set), copy_rtx (SET_SRC (set)));
925                                    
926                   PUT_CODE (p, NOTE);
927                   NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED;
928                   NOTE_SOURCE_FILE (p) = 0;
929                   VARRAY_INT (n_times_set, regno) = 0;
930                   continue;
931                 }
932
933               m = (struct movable *) alloca (sizeof (struct movable));
934               m->next = 0;
935               m->insn = p;
936               m->set_src = src;
937               m->dependencies = dependencies;
938               m->set_dest = SET_DEST (set);
939               m->force = 0;
940               m->consec = VARRAY_INT (n_times_set, 
941                                       REGNO (SET_DEST (set))) - 1;
942               m->done = 0;
943               m->forces = 0;
944               m->partial = 0;
945               m->move_insn = move_insn;
946               m->move_insn_first = 0;
947               m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
948               m->savemode = VOIDmode;
949               m->regno = regno;
950               /* Set M->cond if either invariant_p or consec_sets_invariant_p
951                  returned 2 (only conditionally invariant).  */
952               m->cond = ((tem | tem1 | tem2) > 1);
953               m->global = (uid_luid[REGNO_LAST_UID (regno)] > INSN_LUID (end)
954                            || uid_luid[REGNO_FIRST_UID (regno)] < INSN_LUID (loop_start));
955               m->match = 0;
956               m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
957                              - uid_luid[REGNO_FIRST_UID (regno)]);
958               m->savings = VARRAY_INT (n_times_used, regno);
959               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
960                 m->savings += libcall_benefit (p);
961               VARRAY_INT (n_times_set, regno) = move_insn ? -2 : -1;
962               /* Add M to the end of the chain MOVABLES.  */
963               if (movables == 0)
964                 movables = m;
965               else
966                 last_movable->next = m;
967               last_movable = m;
968
969               if (m->consec > 0)
970                 {
971                   /* It is possible for the first instruction to have a
972                      REG_EQUAL note but a non-invariant SET_SRC, so we must
973                      remember the status of the first instruction in case
974                      the last instruction doesn't have a REG_EQUAL note.  */
975                   m->move_insn_first = m->move_insn;
976
977                   /* Skip this insn, not checking REG_LIBCALL notes.  */
978                   p = next_nonnote_insn (p);
979                   /* Skip the consecutive insns, if there are any.  */
980                   p = skip_consec_insns (p, m->consec);
981                   /* Back up to the last insn of the consecutive group.  */
982                   p = prev_nonnote_insn (p);
983
984                   /* We must now reset m->move_insn, m->is_equiv, and possibly
985                      m->set_src to correspond to the effects of all the
986                      insns.  */
987                   temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
988                   if (temp)
989                     m->set_src = XEXP (temp, 0), m->move_insn = 1;
990                   else
991                     {
992                       temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
993                       if (temp && CONSTANT_P (XEXP (temp, 0)))
994                         m->set_src = XEXP (temp, 0), m->move_insn = 1;
995                       else
996                         m->move_insn = 0;
997
998                     }
999                   m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
1000                 }
1001             }
1002           /* If this register is always set within a STRICT_LOW_PART
1003              or set to zero, then its high bytes are constant.
1004              So clear them outside the loop and within the loop
1005              just load the low bytes.
1006              We must check that the machine has an instruction to do so.
1007              Also, if the value loaded into the register
1008              depends on the same register, this cannot be done.  */
1009           else if (SET_SRC (set) == const0_rtx
1010                    && GET_CODE (NEXT_INSN (p)) == INSN
1011                    && (set1 = single_set (NEXT_INSN (p)))
1012                    && GET_CODE (set1) == SET
1013                    && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
1014                    && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
1015                    && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
1016                        == SET_DEST (set))
1017                    && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1018             {
1019               register int regno = REGNO (SET_DEST (set));
1020               if (VARRAY_INT (n_times_set, regno) == 2)
1021                 {
1022                   register struct movable *m;
1023                   m = (struct movable *) alloca (sizeof (struct movable));
1024                   m->next = 0;
1025                   m->insn = p;
1026                   m->set_dest = SET_DEST (set);
1027                   m->dependencies = 0;
1028                   m->force = 0;
1029                   m->consec = 0;
1030                   m->done = 0;
1031                   m->forces = 0;
1032                   m->move_insn = 0;
1033                   m->move_insn_first = 0;
1034                   m->partial = 1;
1035                   /* If the insn may not be executed on some cycles,
1036                      we can't clear the whole reg; clear just high part.
1037                      Not even if the reg is used only within this loop.
1038                      Consider this:
1039                      while (1)
1040                        while (s != t) {
1041                          if (foo ()) x = *s;
1042                          use (x);
1043                        }
1044                      Clearing x before the inner loop could clobber a value
1045                      being saved from the last time around the outer loop.
1046                      However, if the reg is not used outside this loop
1047                      and all uses of the register are in the same
1048                      basic block as the store, there is no problem.
1049
1050                      If this insn was made by loop, we don't know its
1051                      INSN_LUID and hence must make a conservative
1052                      assumption.  */
1053                   m->global = (INSN_UID (p) >= max_uid_for_loop
1054                                || (uid_luid[REGNO_LAST_UID (regno)]
1055                                    > INSN_LUID (end))
1056                                || (uid_luid[REGNO_FIRST_UID (regno)]
1057                                    < INSN_LUID (p))
1058                                || (labels_in_range_p
1059                                    (p, uid_luid[REGNO_FIRST_UID (regno)])));
1060                   if (maybe_never && m->global)
1061                     m->savemode = GET_MODE (SET_SRC (set1));
1062                   else
1063                     m->savemode = VOIDmode;
1064                   m->regno = regno;
1065                   m->cond = 0;
1066                   m->match = 0;
1067                   m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
1068                                  - uid_luid[REGNO_FIRST_UID (regno)]);
1069                   m->savings = 1;
1070                   VARRAY_INT (n_times_set, regno) = -1;
1071                   /* Add M to the end of the chain MOVABLES.  */
1072                   if (movables == 0)
1073                     movables = m;
1074                   else
1075                     last_movable->next = m;
1076                   last_movable = m;
1077                 }
1078             }
1079         }
1080       /* Past a call insn, we get to insns which might not be executed
1081          because the call might exit.  This matters for insns that trap.
1082          Call insns inside a REG_LIBCALL/REG_RETVAL block always return,
1083          so they don't count.  */
1084       else if (GET_CODE (p) == CALL_INSN && ! in_libcall)
1085         call_passed = 1;
1086       /* Past a label or a jump, we get to insns for which we
1087          can't count on whether or how many times they will be
1088          executed during each iteration.  Therefore, we can
1089          only move out sets of trivial variables
1090          (those not used after the loop).  */
1091       /* Similar code appears twice in strength_reduce.  */
1092       else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
1093                /* If we enter the loop in the middle, and scan around to the
1094                   beginning, don't set maybe_never for that.  This must be an
1095                   unconditional jump, otherwise the code at the top of the
1096                   loop might never be executed.  Unconditional jumps are
1097                   followed a by barrier then loop end.  */
1098                && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop_top
1099                      && NEXT_INSN (NEXT_INSN (p)) == end
1100                      && simplejump_p (p)))
1101         maybe_never = 1;
1102       else if (GET_CODE (p) == NOTE)
1103         {
1104           /* At the virtual top of a converted loop, insns are again known to
1105              be executed: logically, the loop begins here even though the exit
1106              code has been duplicated.  */
1107           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1108             maybe_never = call_passed = 0;
1109           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1110             loop_depth++;
1111           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1112             loop_depth--;
1113         }
1114     }
1115
1116   /* If one movable subsumes another, ignore that other.  */
1117
1118   ignore_some_movables (movables);
1119
1120   /* For each movable insn, see if the reg that it loads
1121      leads when it dies right into another conditionally movable insn.
1122      If so, record that the second insn "forces" the first one,
1123      since the second can be moved only if the first is.  */
1124
1125   force_movables (movables);
1126
1127   /* See if there are multiple movable insns that load the same value.
1128      If there are, make all but the first point at the first one
1129      through the `match' field, and add the priorities of them
1130      all together as the priority of the first.  */
1131
1132   combine_movables (movables, nregs);
1133         
1134   /* Now consider each movable insn to decide whether it is worth moving.
1135      Store 0 in n_times_set for each reg that is moved.
1136
1137      Generally this increases code size, so do not move moveables when
1138      optimizing for code size.  */
1139
1140   if (! optimize_size)
1141     move_movables (movables, threshold,
1142                    insn_count, loop_start, end, nregs);
1143
1144   /* Now candidates that still are negative are those not moved.
1145      Change n_times_set to indicate that those are not actually invariant.  */
1146   for (i = 0; i < nregs; i++)
1147     if (VARRAY_INT (n_times_set, i) < 0)
1148       VARRAY_INT (n_times_set, i) = VARRAY_INT (n_times_used, i);
1149
1150   /* Now that we've moved some things out of the loop, we able to
1151      hoist even more memory references.  There's no need to pass
1152      reg_single_usage this time, since we're done with it.  */
1153   load_mems_and_recount_loop_regs_set (scan_start, end, loop_top,
1154                                        loop_start, 0,
1155                                        &insn_count);
1156
1157   if (flag_strength_reduce)
1158     {
1159       the_movables = movables;
1160       strength_reduce (scan_start, end, loop_top,
1161                        insn_count, loop_start, end, unroll_p, bct_p);
1162     }
1163
1164   VARRAY_FREE (n_times_set);
1165   VARRAY_FREE (n_times_used);
1166   VARRAY_FREE (may_not_optimize);
1167   VARRAY_FREE (reg_single_usage);
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   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 static 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_used, 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_used, 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 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 (n_times_set, 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 (n_times_set, 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 thet 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   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_used, m->forces->regno) == 1))
1825             {
1826               int count;
1827               register struct movable *m1;
1828               rtx first;
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 (n_times_set, 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                       if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2163                         reg_map[m1->regno] = m->set_dest;
2164                       else
2165                         reg_map[m1->regno]
2166                           = gen_lowpart_common (GET_MODE (m1->set_dest),
2167                                                 m->set_dest);
2168                     
2169                       /* Get rid of the matching insn
2170                          and prevent further processing of it.  */
2171                       m1->done = 1;
2172
2173                       /* if library call, delete all insn except last, which
2174                          is deleted below */
2175                       if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2176                                                  NULL_RTX)))
2177                         {
2178                           for (temp = XEXP (temp, 0); temp != m1->insn;
2179                                temp = NEXT_INSN (temp))
2180                             delete_insn (temp);
2181                         }
2182                       delete_insn (m1->insn);
2183
2184                       /* Any other movable that loads the same register
2185                          MUST be moved.  */
2186                       already_moved[m1->regno] = 1;
2187
2188                       /* The reg merged here is now invariant,
2189                          if the reg it matches is invariant.  */
2190                       if (! m->partial)
2191                         VARRAY_INT (n_times_set, m1->regno) = 0;
2192                     }
2193             }
2194           else if (loop_dump_stream)
2195             fprintf (loop_dump_stream, "not desirable");
2196         }
2197       else if (loop_dump_stream && !m->match)
2198         fprintf (loop_dump_stream, "not safe");
2199
2200       if (loop_dump_stream)
2201         fprintf (loop_dump_stream, "\n");
2202     }
2203
2204   if (new_start == 0)
2205     new_start = loop_start;
2206
2207   /* Go through all the instructions in the loop, making
2208      all the register substitutions scheduled in REG_MAP.  */
2209   for (p = new_start; p != end; p = NEXT_INSN (p))
2210     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
2211         || GET_CODE (p) == CALL_INSN)
2212       {
2213         replace_regs (PATTERN (p), reg_map, nregs, 0);
2214         replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2215         INSN_CODE (p) = -1;
2216       }
2217 }
2218 \f
2219 #if 0
2220 /* Scan X and replace the address of any MEM in it with ADDR.
2221    REG is the address that MEM should have before the replacement.  */
2222
2223 static void
2224 replace_call_address (x, reg, addr)
2225      rtx x, reg, addr;
2226 {
2227   register enum rtx_code code;
2228   register int i;
2229   register char *fmt;
2230
2231   if (x == 0)
2232     return;
2233   code = GET_CODE (x);
2234   switch (code)
2235     {
2236     case PC:
2237     case CC0:
2238     case CONST_INT:
2239     case CONST_DOUBLE:
2240     case CONST:
2241     case SYMBOL_REF:
2242     case LABEL_REF:
2243     case REG:
2244       return;
2245
2246     case SET:
2247       /* Short cut for very common case.  */
2248       replace_call_address (XEXP (x, 1), reg, addr);
2249       return;
2250
2251     case CALL:
2252       /* Short cut for very common case.  */
2253       replace_call_address (XEXP (x, 0), reg, addr);
2254       return;
2255
2256     case MEM:
2257       /* If this MEM uses a reg other than the one we expected,
2258          something is wrong.  */
2259       if (XEXP (x, 0) != reg)
2260         abort ();
2261       XEXP (x, 0) = addr;
2262       return;
2263       
2264     default:
2265       break;
2266     }
2267
2268   fmt = GET_RTX_FORMAT (code);
2269   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2270     {
2271       if (fmt[i] == 'e')
2272         replace_call_address (XEXP (x, i), reg, addr);
2273       if (fmt[i] == 'E')
2274         {
2275           register int j;
2276           for (j = 0; j < XVECLEN (x, i); j++)
2277             replace_call_address (XVECEXP (x, i, j), reg, addr);
2278         }
2279     }
2280 }
2281 #endif
2282 \f
2283 /* Return the number of memory refs to addresses that vary
2284    in the rtx X.  */
2285
2286 static int
2287 count_nonfixed_reads (x)
2288      rtx x;
2289 {
2290   register enum rtx_code code;
2291   register int i;
2292   register char *fmt;
2293   int value;
2294
2295   if (x == 0)
2296     return 0;
2297
2298   code = GET_CODE (x);
2299   switch (code)
2300     {
2301     case PC:
2302     case CC0:
2303     case CONST_INT:
2304     case CONST_DOUBLE:
2305     case CONST:
2306     case SYMBOL_REF:
2307     case LABEL_REF:
2308     case REG:
2309       return 0;
2310
2311     case MEM:
2312       return ((invariant_p (XEXP (x, 0)) != 1)
2313               + count_nonfixed_reads (XEXP (x, 0)));
2314       
2315     default:
2316       break;
2317     }
2318
2319   value = 0;
2320   fmt = GET_RTX_FORMAT (code);
2321   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2322     {
2323       if (fmt[i] == 'e')
2324         value += count_nonfixed_reads (XEXP (x, i));
2325       if (fmt[i] == 'E')
2326         {
2327           register int j;
2328           for (j = 0; j < XVECLEN (x, i); j++)
2329             value += count_nonfixed_reads (XVECEXP (x, i, j));
2330         }
2331     }
2332   return value;
2333 }
2334
2335 \f
2336 #if 0
2337 /* P is an instruction that sets a register to the result of a ZERO_EXTEND.
2338    Replace it with an instruction to load just the low bytes
2339    if the machine supports such an instruction,
2340    and insert above LOOP_START an instruction to clear the register.  */
2341
2342 static void
2343 constant_high_bytes (p, loop_start)
2344      rtx p, loop_start;
2345 {
2346   register rtx new;
2347   register int insn_code_number;
2348
2349   /* Try to change (SET (REG ...) (ZERO_EXTEND (..:B ...)))
2350      to (SET (STRICT_LOW_PART (SUBREG:B (REG...))) ...).  */
2351
2352   new = gen_rtx_SET (VOIDmode,
2353                      gen_rtx_STRICT_LOW_PART (VOIDmode,
2354                                               gen_rtx_SUBREG (GET_MODE (XEXP (SET_SRC (PATTERN (p)), 0)),
2355                                    SET_DEST (PATTERN (p)),
2356                                    0)),
2357                  XEXP (SET_SRC (PATTERN (p)), 0));
2358   insn_code_number = recog (new, p);
2359
2360   if (insn_code_number)
2361     {
2362       register int i;
2363
2364       /* Clear destination register before the loop.  */
2365       emit_insn_before (gen_rtx_SET (VOIDmode, SET_DEST (PATTERN (p)),
2366                                      const0_rtx),
2367                         loop_start);
2368
2369       /* Inside the loop, just load the low part.  */
2370       PATTERN (p) = new;
2371     }
2372 }
2373 #endif
2374 \f
2375 /* Scan a loop setting the variables `unknown_address_altered',
2376    `num_mem_sets', `loop_continue', `loops_enclosed', `loop_has_call',
2377    `loop_has_volatile', and `loop_has_tablejump'.
2378    Also, fill in the arrays `loop_mems' and `loop_store_mems'.  */
2379
2380 static void
2381 prescan_loop (start, end)
2382      rtx start, end;
2383 {
2384   register int level = 1;
2385   rtx insn;
2386   int loop_has_multiple_exit_targets = 0;
2387   /* The label after END.  Jumping here is just like falling off the
2388      end of the loop.  We use next_nonnote_insn instead of next_label
2389      as a hedge against the (pathological) case where some actual insn
2390      might end up between the two.  */
2391   rtx exit_target = next_nonnote_insn (end);
2392   if (exit_target == NULL_RTX || GET_CODE (exit_target) != CODE_LABEL)
2393     loop_has_multiple_exit_targets = 1;
2394
2395   unknown_address_altered = 0;
2396   loop_has_call = 0;
2397   loop_has_volatile = 0;
2398   loop_has_tablejump = 0;
2399   loop_store_mems_idx = 0;
2400   loop_mems_idx = 0;
2401
2402   num_mem_sets = 0;
2403   loops_enclosed = 1;
2404   loop_continue = 0;
2405
2406   for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2407        insn = NEXT_INSN (insn))
2408     {
2409       if (GET_CODE (insn) == NOTE)
2410         {
2411           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2412             {
2413               ++level;
2414               /* Count number of loops contained in this one.  */
2415               loops_enclosed++;
2416             }
2417           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2418             {
2419               --level;
2420               if (level == 0)
2421                 {
2422                   end = insn;
2423                   break;
2424                 }
2425             }
2426           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_CONT)
2427             {
2428               if (level == 1)
2429                 loop_continue = insn;
2430             }
2431         }
2432       else if (GET_CODE (insn) == CALL_INSN)
2433         {
2434           if (! CONST_CALL_P (insn))
2435             unknown_address_altered = 1;
2436           loop_has_call = 1;
2437         }
2438       else if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
2439         {
2440           rtx label1 = NULL_RTX;
2441           rtx label2 = NULL_RTX;
2442
2443           if (volatile_refs_p (PATTERN (insn)))
2444             loop_has_volatile = 1;
2445
2446           if (GET_CODE (insn) == JUMP_INSN
2447               && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2448                   || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2449             loop_has_tablejump = 1;
2450           
2451           note_stores (PATTERN (insn), note_addr_stored);
2452
2453           if (! loop_has_multiple_exit_targets
2454               && GET_CODE (insn) == JUMP_INSN
2455               && GET_CODE (PATTERN (insn)) == SET
2456               && SET_DEST (PATTERN (insn)) == pc_rtx)
2457             {
2458               if (GET_CODE (SET_SRC (PATTERN (insn))) == IF_THEN_ELSE)
2459                 {
2460                   label1 = XEXP (SET_SRC (PATTERN (insn)), 1);
2461                   label2 = XEXP (SET_SRC (PATTERN (insn)), 2);
2462                 }
2463               else
2464                 {
2465                   label1 = SET_SRC (PATTERN (insn));
2466                 }
2467
2468               do {
2469                 if (label1 && label1 != pc_rtx)
2470                   {
2471                     if (GET_CODE (label1) != LABEL_REF)
2472                       {
2473                         /* Something tricky.  */
2474                         loop_has_multiple_exit_targets = 1;
2475                         break;
2476                       }
2477                     else if (XEXP (label1, 0) != exit_target
2478                              && LABEL_OUTSIDE_LOOP_P (label1))
2479                       {
2480                         /* A jump outside the current loop.  */
2481                         loop_has_multiple_exit_targets = 1;
2482                         break;
2483                       }
2484                   }
2485
2486                 label1 = label2;
2487                 label2 = NULL_RTX;
2488               } while (label1);
2489             }
2490         }
2491       else if (GET_CODE (insn) == RETURN)
2492         loop_has_multiple_exit_targets = 1;
2493     }
2494
2495   /* Now, rescan the loop, setting up the LOOP_MEMS array.  */
2496   if (/* We can't tell what MEMs are aliased by what.  */
2497       !unknown_address_altered 
2498       /* An exception thrown by a called function might land us
2499          anywhere.  */
2500       && !loop_has_call
2501       /* We don't want loads for MEMs moved to a location before the
2502          one at which their stack memory becomes allocated.  (Note
2503          that this is not a problem for malloc, etc., since those
2504          require actual function calls.  */
2505       && !current_function_calls_alloca
2506       /* There are ways to leave the loop other than falling off the
2507          end.  */
2508       && !loop_has_multiple_exit_targets)
2509     for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2510          insn = NEXT_INSN (insn))
2511       for_each_rtx (&insn, insert_loop_mem, 0);
2512 }
2513 \f
2514 /* Scan the function looking for loops.  Record the start and end of each loop.
2515    Also mark as invalid loops any loops that contain a setjmp or are branched
2516    to from outside the loop.  */
2517
2518 static void
2519 find_and_verify_loops (f)
2520      rtx f;
2521 {
2522   rtx insn, label;
2523   int current_loop = -1;
2524   int next_loop = -1;
2525   int loop;
2526
2527   /* If there are jumps to undefined labels,
2528      treat them as jumps out of any/all loops.
2529      This also avoids writing past end of tables when there are no loops.  */
2530   uid_loop_num[0] = -1;
2531
2532   /* Find boundaries of loops, mark which loops are contained within
2533      loops, and invalidate loops that have setjmp.  */
2534
2535   for (insn = f; insn; insn = NEXT_INSN (insn))
2536     {
2537       if (GET_CODE (insn) == NOTE)
2538         switch (NOTE_LINE_NUMBER (insn))
2539           {
2540           case NOTE_INSN_LOOP_BEG:
2541             loop_number_loop_starts[++next_loop] =  insn;
2542             loop_number_loop_ends[next_loop] = 0;
2543             loop_outer_loop[next_loop] = current_loop;
2544             loop_invalid[next_loop] = 0;
2545             loop_number_exit_labels[next_loop] = 0;
2546             loop_number_exit_count[next_loop] = 0;
2547             current_loop = next_loop;
2548             break;
2549
2550           case NOTE_INSN_SETJMP:
2551             /* In this case, we must invalidate our current loop and any
2552                enclosing loop.  */
2553             for (loop = current_loop; loop != -1; loop = loop_outer_loop[loop])
2554               {
2555                 loop_invalid[loop] = 1;
2556                 if (loop_dump_stream)
2557                   fprintf (loop_dump_stream,
2558                            "\nLoop at %d ignored due to setjmp.\n",
2559                            INSN_UID (loop_number_loop_starts[loop]));
2560               }
2561             break;
2562
2563           case NOTE_INSN_LOOP_END:
2564             if (current_loop == -1)
2565               abort ();
2566
2567             loop_number_loop_ends[current_loop] = insn;
2568             current_loop = loop_outer_loop[current_loop];
2569             break;
2570
2571           default:
2572             break;
2573           }
2574
2575       /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2576          enclosing loop, but this doesn't matter.  */
2577       uid_loop_num[INSN_UID (insn)] = current_loop;
2578     }
2579
2580   /* Any loop containing a label used in an initializer must be invalidated,
2581      because it can be jumped into from anywhere.  */
2582
2583   for (label = forced_labels; label; label = XEXP (label, 1))
2584     {
2585       int loop_num;
2586
2587       for (loop_num = uid_loop_num[INSN_UID (XEXP (label, 0))];
2588            loop_num != -1;
2589            loop_num = loop_outer_loop[loop_num])
2590         loop_invalid[loop_num] = 1;
2591     }
2592
2593   /* Any loop containing a label used for an exception handler must be
2594      invalidated, because it can be jumped into from anywhere.  */
2595
2596   for (label = exception_handler_labels; label; label = XEXP (label, 1))
2597     {
2598       int loop_num;
2599
2600       for (loop_num = uid_loop_num[INSN_UID (XEXP (label, 0))];
2601            loop_num != -1;
2602            loop_num = loop_outer_loop[loop_num])
2603         loop_invalid[loop_num] = 1;
2604     }
2605
2606   /* Now scan all insn's in the function.  If any JUMP_INSN branches into a
2607      loop that it is not contained within, that loop is marked invalid.
2608      If any INSN or CALL_INSN uses a label's address, then the loop containing
2609      that label is marked invalid, because it could be jumped into from
2610      anywhere.
2611
2612      Also look for blocks of code ending in an unconditional branch that
2613      exits the loop.  If such a block is surrounded by a conditional 
2614      branch around the block, move the block elsewhere (see below) and
2615      invert the jump to point to the code block.  This may eliminate a
2616      label in our loop and will simplify processing by both us and a
2617      possible second cse pass.  */
2618
2619   for (insn = f; insn; insn = NEXT_INSN (insn))
2620     if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
2621       {
2622         int this_loop_num = uid_loop_num[INSN_UID (insn)];
2623
2624         if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2625           {
2626             rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2627             if (note)
2628               {
2629                 int loop_num;
2630
2631                 for (loop_num = uid_loop_num[INSN_UID (XEXP (note, 0))];
2632                      loop_num != -1;
2633                      loop_num = loop_outer_loop[loop_num])
2634                   loop_invalid[loop_num] = 1;
2635               }
2636           }
2637
2638         if (GET_CODE (insn) != JUMP_INSN)
2639           continue;
2640
2641         mark_loop_jump (PATTERN (insn), this_loop_num);
2642
2643         /* See if this is an unconditional branch outside the loop.  */
2644         if (this_loop_num != -1
2645             && (GET_CODE (PATTERN (insn)) == RETURN
2646                 || (simplejump_p (insn)
2647                     && (uid_loop_num[INSN_UID (JUMP_LABEL (insn))]
2648                         != this_loop_num)))
2649             && get_max_uid () < max_uid_for_loop)
2650           {
2651             rtx p;
2652             rtx our_next = next_real_insn (insn);
2653             int dest_loop;
2654             int outer_loop = -1;
2655
2656             /* Go backwards until we reach the start of the loop, a label,
2657                or a JUMP_INSN.  */
2658             for (p = PREV_INSN (insn);
2659                  GET_CODE (p) != CODE_LABEL
2660                  && ! (GET_CODE (p) == NOTE
2661                        && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2662                  && GET_CODE (p) != JUMP_INSN;
2663                  p = PREV_INSN (p))
2664               ;
2665
2666             /* Check for the case where we have a jump to an inner nested
2667                loop, and do not perform the optimization in that case.  */
2668
2669             if (JUMP_LABEL (insn))
2670               {
2671                 dest_loop = uid_loop_num[INSN_UID (JUMP_LABEL (insn))];
2672                 if (dest_loop != -1)
2673                   {
2674                     for (outer_loop = dest_loop; outer_loop != -1;
2675                          outer_loop = loop_outer_loop[outer_loop])
2676                       if (outer_loop == this_loop_num)
2677                         break;
2678                   }
2679               }
2680
2681             /* Make sure that the target of P is within the current loop.  */
2682
2683             if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2684                 && uid_loop_num[INSN_UID (JUMP_LABEL (p))] != this_loop_num)
2685               outer_loop = this_loop_num;
2686
2687             /* If we stopped on a JUMP_INSN to the next insn after INSN,
2688                we have a block of code to try to move.
2689
2690                We look backward and then forward from the target of INSN
2691                to find a BARRIER at the same loop depth as the target.
2692                If we find such a BARRIER, we make a new label for the start
2693                of the block, invert the jump in P and point it to that label,
2694                and move the block of code to the spot we found.  */
2695
2696             if (outer_loop == -1
2697                 && GET_CODE (p) == JUMP_INSN
2698                 && JUMP_LABEL (p) != 0
2699                 /* Just ignore jumps to labels that were never emitted.
2700                    These always indicate compilation errors.  */
2701                 && INSN_UID (JUMP_LABEL (p)) != 0
2702                 && condjump_p (p)
2703                 && ! simplejump_p (p)
2704                 && next_real_insn (JUMP_LABEL (p)) == our_next)
2705               {
2706                 rtx target
2707                   = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2708                 int target_loop_num = uid_loop_num[INSN_UID (target)];
2709                 rtx loc;
2710
2711                 for (loc = target; loc; loc = PREV_INSN (loc))
2712                   if (GET_CODE (loc) == BARRIER
2713                       && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2714                     break;
2715
2716                 if (loc == 0)
2717                   for (loc = target; loc; loc = NEXT_INSN (loc))
2718                     if (GET_CODE (loc) == BARRIER
2719                         && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2720                       break;
2721
2722                 if (loc)
2723                   {
2724                     rtx cond_label = JUMP_LABEL (p);
2725                     rtx new_label = get_label_after (p);
2726
2727                     /* Ensure our label doesn't go away.  */
2728                     LABEL_NUSES (cond_label)++;
2729
2730                     /* Verify that uid_loop_num is large enough and that
2731                        we can invert P.  */
2732                    if (invert_jump (p, new_label))
2733                      {
2734                        rtx q, r;
2735
2736                        /* If no suitable BARRIER was found, create a suitable
2737                           one before TARGET.  Since TARGET is a fall through
2738                           path, we'll need to insert an jump around our block
2739                           and a add a BARRIER before TARGET.
2740
2741                           This creates an extra unconditional jump outside
2742                           the loop.  However, the benefits of removing rarely
2743                           executed instructions from inside the loop usually
2744                           outweighs the cost of the extra unconditional jump
2745                           outside the loop.  */
2746                        if (loc == 0)
2747                          {
2748                            rtx temp;
2749
2750                            temp = gen_jump (JUMP_LABEL (insn));
2751                            temp = emit_jump_insn_before (temp, target);
2752                            JUMP_LABEL (temp) = JUMP_LABEL (insn);
2753                            LABEL_NUSES (JUMP_LABEL (insn))++;
2754                            loc = emit_barrier_before (target);
2755                          }
2756
2757                        /* Include the BARRIER after INSN and copy the
2758                           block after LOC.  */
2759                        new_label = squeeze_notes (new_label, NEXT_INSN (insn));
2760                        reorder_insns (new_label, NEXT_INSN (insn), loc);
2761
2762                        /* All those insns are now in TARGET_LOOP_NUM.  */
2763                        for (q = new_label; q != NEXT_INSN (NEXT_INSN (insn));
2764                             q = NEXT_INSN (q))
2765                          uid_loop_num[INSN_UID (q)] = target_loop_num;
2766
2767                        /* The label jumped to by INSN is no longer a loop exit.
2768                           Unless INSN does not have a label (e.g., it is a
2769                           RETURN insn), search loop_number_exit_labels to find
2770                           its label_ref, and remove it.  Also turn off
2771                           LABEL_OUTSIDE_LOOP_P bit.  */
2772                        if (JUMP_LABEL (insn))
2773                          {
2774                            int loop_num;
2775
2776                            for (q = 0,
2777                                 r = loop_number_exit_labels[this_loop_num];
2778                                 r; q = r, r = LABEL_NEXTREF (r))
2779                              if (XEXP (r, 0) == JUMP_LABEL (insn))
2780                                {
2781                                  LABEL_OUTSIDE_LOOP_P (r) = 0;
2782                                  if (q)
2783                                    LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2784                                  else
2785                                    loop_number_exit_labels[this_loop_num]
2786                                      = LABEL_NEXTREF (r);
2787                                  break;
2788                                }
2789
2790                            for (loop_num = this_loop_num;
2791                                 loop_num != -1 && loop_num != target_loop_num;
2792                                 loop_num = loop_outer_loop[loop_num])
2793                              loop_number_exit_count[loop_num]--;
2794
2795                            /* If we didn't find it, then something is wrong.  */
2796                            if (! r)
2797                              abort ();
2798                          }
2799
2800                        /* P is now a jump outside the loop, so it must be put
2801                           in loop_number_exit_labels, and marked as such.
2802                           The easiest way to do this is to just call
2803                           mark_loop_jump again for P.  */
2804                        mark_loop_jump (PATTERN (p), this_loop_num);
2805
2806                        /* If INSN now jumps to the insn after it,
2807                           delete INSN.  */
2808                        if (JUMP_LABEL (insn) != 0
2809                            && (next_real_insn (JUMP_LABEL (insn))
2810                                == next_real_insn (insn)))
2811                          delete_insn (insn);
2812                      }
2813
2814                     /* Continue the loop after where the conditional
2815                        branch used to jump, since the only branch insn
2816                        in the block (if it still remains) is an inter-loop
2817                        branch and hence needs no processing.  */
2818                     insn = NEXT_INSN (cond_label);
2819
2820                     if (--LABEL_NUSES (cond_label) == 0)
2821                       delete_insn (cond_label);
2822
2823                     /* This loop will be continued with NEXT_INSN (insn).  */
2824                     insn = PREV_INSN (insn);
2825                   }
2826               }
2827           }
2828       }
2829 }
2830
2831 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
2832    loops it is contained in, mark the target loop invalid.
2833
2834    For speed, we assume that X is part of a pattern of a JUMP_INSN.  */
2835
2836 static void
2837 mark_loop_jump (x, loop_num)
2838      rtx x;
2839      int loop_num;
2840 {
2841   int dest_loop;
2842   int outer_loop;
2843   int i;
2844
2845   switch (GET_CODE (x))
2846     {
2847     case PC:
2848     case USE:
2849     case CLOBBER:
2850     case REG:
2851     case MEM:
2852     case CONST_INT:
2853     case CONST_DOUBLE:
2854     case RETURN:
2855       return;
2856
2857     case CONST:
2858       /* There could be a label reference in here.  */
2859       mark_loop_jump (XEXP (x, 0), loop_num);
2860       return;
2861
2862     case PLUS:
2863     case MINUS:
2864     case MULT:
2865       mark_loop_jump (XEXP (x, 0), loop_num);
2866       mark_loop_jump (XEXP (x, 1), loop_num);
2867       return;
2868
2869     case SIGN_EXTEND:
2870     case ZERO_EXTEND:
2871       mark_loop_jump (XEXP (x, 0), loop_num);
2872       return;
2873
2874     case LABEL_REF:
2875       dest_loop = uid_loop_num[INSN_UID (XEXP (x, 0))];
2876
2877       /* Link together all labels that branch outside the loop.  This
2878          is used by final_[bg]iv_value and the loop unrolling code.  Also
2879          mark this LABEL_REF so we know that this branch should predict
2880          false.  */
2881
2882       /* A check to make sure the label is not in an inner nested loop,
2883          since this does not count as a loop exit.  */
2884       if (dest_loop != -1)
2885         {
2886           for (outer_loop = dest_loop; outer_loop != -1;
2887                outer_loop = loop_outer_loop[outer_loop])
2888             if (outer_loop == loop_num)
2889               break;
2890         }
2891       else
2892         outer_loop = -1;
2893
2894       if (loop_num != -1 && outer_loop == -1)
2895         {
2896           LABEL_OUTSIDE_LOOP_P (x) = 1;
2897           LABEL_NEXTREF (x) = loop_number_exit_labels[loop_num];
2898           loop_number_exit_labels[loop_num] = x;
2899
2900           for (outer_loop = loop_num;
2901                outer_loop != -1 && outer_loop != dest_loop;
2902                outer_loop = loop_outer_loop[outer_loop])
2903             loop_number_exit_count[outer_loop]++;
2904         }
2905
2906       /* If this is inside a loop, but not in the current loop or one enclosed
2907          by it, it invalidates at least one loop.  */
2908
2909       if (dest_loop == -1)
2910         return;
2911
2912       /* We must invalidate every nested loop containing the target of this
2913          label, except those that also contain the jump insn.  */
2914
2915       for (; dest_loop != -1; dest_loop = loop_outer_loop[dest_loop])
2916         {
2917           /* Stop when we reach a loop that also contains the jump insn.  */
2918           for (outer_loop = loop_num; outer_loop != -1;
2919                outer_loop = loop_outer_loop[outer_loop])
2920             if (dest_loop == outer_loop)
2921               return;
2922
2923           /* If we get here, we know we need to invalidate a loop.  */
2924           if (loop_dump_stream && ! loop_invalid[dest_loop])
2925             fprintf (loop_dump_stream,
2926                      "\nLoop at %d ignored due to multiple entry points.\n",
2927                      INSN_UID (loop_number_loop_starts[dest_loop]));
2928           
2929           loop_invalid[dest_loop] = 1;
2930         }
2931       return;
2932
2933     case SET:
2934       /* If this is not setting pc, ignore.  */
2935       if (SET_DEST (x) == pc_rtx)
2936         mark_loop_jump (SET_SRC (x), loop_num);
2937       return;
2938
2939     case IF_THEN_ELSE:
2940       mark_loop_jump (XEXP (x, 1), loop_num);
2941       mark_loop_jump (XEXP (x, 2), loop_num);
2942       return;
2943
2944     case PARALLEL:
2945     case ADDR_VEC:
2946       for (i = 0; i < XVECLEN (x, 0); i++)
2947         mark_loop_jump (XVECEXP (x, 0, i), loop_num);
2948       return;
2949
2950     case ADDR_DIFF_VEC:
2951       for (i = 0; i < XVECLEN (x, 1); i++)
2952         mark_loop_jump (XVECEXP (x, 1, i), loop_num);
2953       return;
2954
2955     default:
2956       /* Treat anything else (such as a symbol_ref)
2957          as a branch out of this loop, but not into any loop.  */
2958
2959       if (loop_num != -1)
2960         {
2961 #ifdef HAVE_decrement_and_branch_on_count
2962           LABEL_OUTSIDE_LOOP_P (x) = 1;
2963           LABEL_NEXTREF (x) = loop_number_exit_labels[loop_num];
2964 #endif  /* HAVE_decrement_and_branch_on_count */
2965
2966           loop_number_exit_labels[loop_num] = x;
2967
2968           for (outer_loop = loop_num; outer_loop != -1;
2969                outer_loop = loop_outer_loop[outer_loop])
2970             loop_number_exit_count[outer_loop]++;
2971         }
2972       return;
2973     }
2974 }
2975 \f
2976 /* Return nonzero if there is a label in the range from
2977    insn INSN to and including the insn whose luid is END
2978    INSN must have an assigned luid (i.e., it must not have
2979    been previously created by loop.c).  */
2980
2981 static int
2982 labels_in_range_p (insn, end)
2983      rtx insn;
2984      int end;
2985 {
2986   while (insn && INSN_LUID (insn) <= end)
2987     {
2988       if (GET_CODE (insn) == CODE_LABEL)
2989         return 1;
2990       insn = NEXT_INSN (insn);
2991     }
2992
2993   return 0;
2994 }
2995
2996 /* Record that a memory reference X is being set.  */
2997
2998 static void
2999 note_addr_stored (x, y)
3000      rtx x;
3001      rtx y ATTRIBUTE_UNUSED;
3002 {
3003   register int i;
3004
3005   if (x == 0 || GET_CODE (x) != MEM)
3006     return;
3007
3008   /* Count number of memory writes.
3009      This affects heuristics in strength_reduce.  */
3010   num_mem_sets++;
3011
3012   /* BLKmode MEM means all memory is clobbered.  */
3013   if (GET_MODE (x) == BLKmode)
3014     unknown_address_altered = 1;
3015
3016   if (unknown_address_altered)
3017     return;
3018
3019   for (i = 0; i < loop_store_mems_idx; i++)
3020     if (rtx_equal_p (XEXP (loop_store_mems[i], 0), XEXP (x, 0))
3021         && MEM_IN_STRUCT_P (x) == MEM_IN_STRUCT_P (loop_store_mems[i]))
3022       {
3023         /* We are storing at the same address as previously noted.  Save the
3024            wider reference.  */
3025         if (GET_MODE_SIZE (GET_MODE (x))
3026             > GET_MODE_SIZE (GET_MODE (loop_store_mems[i])))
3027           loop_store_mems[i] = x;
3028         break;
3029       }
3030
3031   if (i == NUM_STORES)
3032     unknown_address_altered = 1;
3033
3034   else if (i == loop_store_mems_idx)
3035     loop_store_mems[loop_store_mems_idx++] = x;
3036 }
3037 \f
3038 /* Return nonzero if the rtx X is invariant over the current loop.
3039
3040    The value is 2 if we refer to something only conditionally invariant.
3041
3042    If `unknown_address_altered' is nonzero, no memory ref is invariant.
3043    Otherwise, a memory ref is invariant if it does not conflict with
3044    anything stored in `loop_store_mems'.  */
3045
3046 int
3047 invariant_p (x)
3048      register rtx x;
3049 {
3050   register int i;
3051   register enum rtx_code code;
3052   register char *fmt;
3053   int conditional = 0;
3054
3055   if (x == 0)
3056     return 1;
3057   code = GET_CODE (x);
3058   switch (code)
3059     {
3060     case CONST_INT:
3061     case CONST_DOUBLE:
3062     case SYMBOL_REF:
3063     case CONST:
3064       return 1;
3065
3066     case LABEL_REF:
3067       /* A LABEL_REF is normally invariant, however, if we are unrolling
3068          loops, and this label is inside the loop, then it isn't invariant.
3069          This is because each unrolled copy of the loop body will have
3070          a copy of this label.  If this was invariant, then an insn loading
3071          the address of this label into a register might get moved outside
3072          the loop, and then each loop body would end up using the same label.
3073
3074          We don't know the loop bounds here though, so just fail for all
3075          labels.  */
3076       if (flag_unroll_loops)
3077         return 0;
3078       else
3079         return 1;
3080
3081     case PC:
3082     case CC0:
3083     case UNSPEC_VOLATILE:
3084       return 0;
3085
3086     case REG:
3087       /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3088          since the reg might be set by initialization within the loop.  */
3089
3090       if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3091            || x == arg_pointer_rtx)
3092           && ! current_function_has_nonlocal_goto)
3093         return 1;
3094
3095       if (loop_has_call
3096           && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3097         return 0;
3098
3099       if (VARRAY_INT (n_times_set, REGNO (x)) < 0)
3100         return 2;
3101
3102       return VARRAY_INT (n_times_set, REGNO (x)) == 0;
3103
3104     case MEM:
3105       /* Volatile memory references must be rejected.  Do this before
3106          checking for read-only items, so that volatile read-only items
3107          will be rejected also.  */
3108       if (MEM_VOLATILE_P (x))
3109         return 0;
3110
3111       /* Read-only items (such as constants in a constant pool) are
3112          invariant if their address is.  */
3113       if (RTX_UNCHANGING_P (x))
3114         break;
3115
3116       /* If we filled the table (or had a subroutine call), any location
3117          in memory could have been clobbered.  */
3118       if (unknown_address_altered)
3119         return 0;
3120
3121       /* See if there is any dependence between a store and this load.  */
3122       for (i = loop_store_mems_idx - 1; i >= 0; i--)
3123         if (true_dependence (loop_store_mems[i], VOIDmode, x, rtx_varies_p))
3124           return 0;
3125
3126       /* It's not invalidated by a store in memory
3127          but we must still verify the address is invariant.  */
3128       break;
3129
3130     case ASM_OPERANDS:
3131       /* Don't mess with insns declared volatile.  */
3132       if (MEM_VOLATILE_P (x))
3133         return 0;
3134       break;
3135       
3136     default:
3137       break;
3138     }
3139
3140   fmt = GET_RTX_FORMAT (code);
3141   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3142     {
3143       if (fmt[i] == 'e')
3144         {
3145           int tem = invariant_p (XEXP (x, i));
3146           if (tem == 0)
3147             return 0;
3148           if (tem == 2)
3149             conditional = 1;
3150         }
3151       else if (fmt[i] == 'E')
3152         {
3153           register int j;
3154           for (j = 0; j < XVECLEN (x, i); j++)
3155             {
3156               int tem = invariant_p (XVECEXP (x, i, j));
3157               if (tem == 0)
3158                 return 0;
3159               if (tem == 2)
3160                 conditional = 1;
3161             }
3162
3163         }
3164     }
3165
3166   return 1 + conditional;
3167 }
3168
3169 \f
3170 /* Return nonzero if all the insns in the loop that set REG
3171    are INSN and the immediately following insns,
3172    and if each of those insns sets REG in an invariant way
3173    (not counting uses of REG in them).
3174
3175    The value is 2 if some of these insns are only conditionally invariant.
3176
3177    We assume that INSN itself is the first set of REG
3178    and that its source is invariant.  */
3179
3180 static int
3181 consec_sets_invariant_p (reg, n_sets, insn)
3182      int n_sets;
3183      rtx reg, insn;
3184 {
3185   register rtx p = insn;
3186   register int regno = REGNO (reg);
3187   rtx temp;
3188   /* Number of sets we have to insist on finding after INSN.  */
3189   int count = n_sets - 1;
3190   int old = VARRAY_INT (n_times_set, regno);
3191   int value = 0;
3192   int this;
3193
3194   /* If N_SETS hit the limit, we can't rely on its value.  */
3195   if (n_sets == 127)
3196     return 0;
3197
3198   VARRAY_INT (n_times_set, regno) = 0;
3199
3200   while (count > 0)
3201     {
3202       register enum rtx_code code;
3203       rtx set;
3204
3205       p = NEXT_INSN (p);
3206       code = GET_CODE (p);
3207
3208       /* If library call, skip to end of it.  */
3209       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3210         p = XEXP (temp, 0);
3211
3212       this = 0;
3213       if (code == INSN
3214           && (set = single_set (p))
3215           && GET_CODE (SET_DEST (set)) == REG
3216           && REGNO (SET_DEST (set)) == regno)
3217         {
3218           this = invariant_p (SET_SRC (set));
3219           if (this != 0)
3220             value |= this;
3221           else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3222             {
3223               /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3224                  If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3225                  notes are OK.  */
3226               this = (CONSTANT_P (XEXP (temp, 0))
3227                       || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3228                           && invariant_p (XEXP (temp, 0))));
3229               if (this != 0)
3230                 value |= this;
3231             }
3232         }
3233       if (this != 0)
3234         count--;
3235       else if (code != NOTE)
3236         {
3237           VARRAY_INT (n_times_set, regno) = old;
3238           return 0;
3239         }
3240     }
3241
3242   VARRAY_INT (n_times_set, regno) = old;
3243   /* If invariant_p ever returned 2, we return 2.  */
3244   return 1 + (value & 2);
3245 }
3246
3247 #if 0
3248 /* I don't think this condition is sufficient to allow INSN
3249    to be moved, so we no longer test it.  */
3250
3251 /* Return 1 if all insns in the basic block of INSN and following INSN
3252    that set REG are invariant according to TABLE.  */
3253
3254 static int
3255 all_sets_invariant_p (reg, insn, table)
3256      rtx reg, insn;
3257      short *table;
3258 {
3259   register rtx p = insn;
3260   register int regno = REGNO (reg);
3261
3262   while (1)
3263     {
3264       register enum rtx_code code;
3265       p = NEXT_INSN (p);
3266       code = GET_CODE (p);
3267       if (code == CODE_LABEL || code == JUMP_INSN)
3268         return 1;
3269       if (code == INSN && GET_CODE (PATTERN (p)) == SET
3270           && GET_CODE (SET_DEST (PATTERN (p))) == REG
3271           && REGNO (SET_DEST (PATTERN (p))) == regno)
3272         {
3273           if (!invariant_p (SET_SRC (PATTERN (p)), table))
3274             return 0;
3275         }
3276     }
3277 }
3278 #endif /* 0 */
3279 \f
3280 /* Look at all uses (not sets) of registers in X.  For each, if it is
3281    the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3282    a different insn, set USAGE[REGNO] to const0_rtx.  */
3283
3284 static void
3285 find_single_use_in_loop (insn, x, usage)
3286      rtx insn;
3287      rtx x;
3288      varray_type usage;
3289 {
3290   enum rtx_code code = GET_CODE (x);
3291   char *fmt = GET_RTX_FORMAT (code);
3292   int i, j;
3293
3294   if (code == REG)
3295     VARRAY_RTX (usage, REGNO (x))
3296       = (VARRAY_RTX (usage, REGNO (x)) != 0 
3297          && VARRAY_RTX (usage, REGNO (x)) != insn)
3298         ? const0_rtx : insn;
3299
3300   else if (code == SET)
3301     {
3302       /* Don't count SET_DEST if it is a REG; otherwise count things
3303          in SET_DEST because if a register is partially modified, it won't
3304          show up as a potential movable so we don't care how USAGE is set 
3305          for it.  */
3306       if (GET_CODE (SET_DEST (x)) != REG)
3307         find_single_use_in_loop (insn, SET_DEST (x), usage);
3308       find_single_use_in_loop (insn, SET_SRC (x), usage);
3309     }
3310   else
3311     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3312       {
3313         if (fmt[i] == 'e' && XEXP (x, i) != 0)
3314           find_single_use_in_loop (insn, XEXP (x, i), usage);
3315         else if (fmt[i] == 'E')
3316           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3317             find_single_use_in_loop (insn, XVECEXP (x, i, j), usage);
3318       }
3319 }
3320 \f
3321 /* Count and record any set in X which is contained in INSN.  Update
3322    MAY_NOT_MOVE and LAST_SET for any register set in X.  */
3323
3324 static void
3325 count_one_set (insn, x, may_not_move, last_set)
3326      rtx insn, x;
3327      varray_type may_not_move;
3328      rtx *last_set;
3329 {
3330   if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3331     /* Don't move a reg that has an explicit clobber.
3332        It's not worth the pain to try to do it correctly.  */
3333     VARRAY_CHAR (may_not_move, REGNO (XEXP (x, 0))) = 1;
3334
3335   if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3336     {
3337       rtx dest = SET_DEST (x);
3338       while (GET_CODE (dest) == SUBREG
3339              || GET_CODE (dest) == ZERO_EXTRACT
3340              || GET_CODE (dest) == SIGN_EXTRACT
3341              || GET_CODE (dest) == STRICT_LOW_PART)
3342         dest = XEXP (dest, 0);
3343       if (GET_CODE (dest) == REG)
3344         {
3345           register int regno = REGNO (dest);
3346           /* If this is the first setting of this reg
3347              in current basic block, and it was set before,
3348              it must be set in two basic blocks, so it cannot
3349              be moved out of the loop.  */
3350           if (VARRAY_INT (n_times_set, regno) > 0 
3351               && last_set[regno] == 0)
3352             VARRAY_CHAR (may_not_move, regno) = 1;
3353           /* If this is not first setting in current basic block,
3354              see if reg was used in between previous one and this.
3355              If so, neither one can be moved.  */
3356           if (last_set[regno] != 0
3357               && reg_used_between_p (dest, last_set[regno], insn))
3358             VARRAY_CHAR (may_not_move, regno) = 1;
3359           if (VARRAY_INT (n_times_set, regno) < 127)
3360             ++VARRAY_INT (n_times_set, regno);
3361           last_set[regno] = insn;
3362         }
3363     }
3364 }
3365
3366 /* Increment N_TIMES_SET at the index of each register
3367    that is modified by an insn between FROM and TO.
3368    If the value of an element of N_TIMES_SET becomes 127 or more,
3369    stop incrementing it, to avoid overflow.
3370
3371    Store in SINGLE_USAGE[I] the single insn in which register I is
3372    used, if it is only used once.  Otherwise, it is set to 0 (for no
3373    uses) or const0_rtx for more than one use.  This parameter may be zero,
3374    in which case this processing is not done.
3375
3376    Store in *COUNT_PTR the number of actual instruction
3377    in the loop.  We use this to decide what is worth moving out.  */
3378
3379 /* last_set[n] is nonzero iff reg n has been set in the current basic block.
3380    In that case, it is the insn that last set reg n.  */
3381
3382 static void
3383 count_loop_regs_set (from, to, may_not_move, single_usage, count_ptr, nregs)
3384      register rtx from, to;
3385      varray_type may_not_move;
3386      varray_type single_usage;
3387      int *count_ptr;
3388      int nregs;
3389 {
3390   register rtx *last_set = (rtx *) alloca (nregs * sizeof (rtx));
3391   register rtx insn;
3392   register int count = 0;
3393
3394   bzero ((char *) last_set, nregs * sizeof (rtx));
3395   for (insn = from; insn != to; insn = NEXT_INSN (insn))
3396     {
3397       if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
3398         {
3399           ++count;
3400
3401           /* If requested, record registers that have exactly one use.  */
3402           if (single_usage)
3403             {
3404               find_single_use_in_loop (insn, PATTERN (insn), single_usage);
3405
3406               /* Include uses in REG_EQUAL notes.  */
3407               if (REG_NOTES (insn))
3408                 find_single_use_in_loop (insn, REG_NOTES (insn), single_usage);
3409             }
3410
3411           if (GET_CODE (PATTERN (insn)) == SET
3412               || GET_CODE (PATTERN (insn)) == CLOBBER)
3413             count_one_set (insn, PATTERN (insn), may_not_move, last_set);
3414           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
3415             {
3416               register int i;
3417               for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
3418                 count_one_set (insn, XVECEXP (PATTERN (insn), 0, i),
3419                                may_not_move, last_set);
3420             }
3421         }
3422
3423       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
3424         bzero ((char *) last_set, nregs * sizeof (rtx));
3425     }
3426   *count_ptr = count;
3427 }
3428 \f
3429 /* Given a loop that is bounded by LOOP_START and LOOP_END
3430    and that is entered at SCAN_START,
3431    return 1 if the register set in SET contained in insn INSN is used by
3432    any insn that precedes INSN in cyclic order starting
3433    from the loop entry point.
3434
3435    We don't want to use INSN_LUID here because if we restrict INSN to those
3436    that have a valid INSN_LUID, it means we cannot move an invariant out
3437    from an inner loop past two loops.  */
3438
3439 static int
3440 loop_reg_used_before_p (set, insn, loop_start, scan_start, loop_end)
3441      rtx set, insn, loop_start, scan_start, loop_end;
3442 {
3443   rtx reg = SET_DEST (set);
3444   rtx p;
3445
3446   /* Scan forward checking for register usage.  If we hit INSN, we
3447      are done.  Otherwise, if we hit LOOP_END, wrap around to LOOP_START.  */
3448   for (p = scan_start; p != insn; p = NEXT_INSN (p))
3449     {
3450       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
3451           && reg_overlap_mentioned_p (reg, PATTERN (p)))
3452         return 1;
3453
3454       if (p == loop_end)
3455         p = loop_start;
3456     }
3457
3458   return 0;
3459 }
3460 \f
3461 /* A "basic induction variable" or biv is a pseudo reg that is set
3462    (within this loop) only by incrementing or decrementing it.  */
3463 /* A "general induction variable" or giv is a pseudo reg whose
3464    value is a linear function of a biv.  */
3465
3466 /* Bivs are recognized by `basic_induction_var';
3467    Givs by `general_induction_var'.  */
3468
3469 /* Indexed by register number, indicates whether or not register is an
3470    induction variable, and if so what type.  */
3471
3472 enum iv_mode *reg_iv_type;
3473
3474 /* Indexed by register number, contains pointer to `struct induction'
3475    if register is an induction variable.  This holds general info for
3476    all induction variables.  */
3477
3478 struct induction **reg_iv_info;
3479
3480 /* Indexed by register number, contains pointer to `struct iv_class'
3481    if register is a basic induction variable.  This holds info describing
3482    the class (a related group) of induction variables that the biv belongs
3483    to.  */
3484
3485 struct iv_class **reg_biv_class;
3486
3487 /* The head of a list which links together (via the next field)
3488    every iv class for the current loop.  */
3489
3490 struct iv_class *loop_iv_list;
3491
3492 /* Communication with routines called via `note_stores'.  */
3493
3494 static rtx note_insn;
3495
3496 /* Dummy register to have non-zero DEST_REG for DEST_ADDR type givs.  */
3497
3498 static rtx addr_placeholder;
3499
3500 /* ??? Unfinished optimizations, and possible future optimizations,
3501    for the strength reduction code.  */
3502
3503 /* ??? The interaction of biv elimination, and recognition of 'constant'
3504    bivs, may cause problems.  */
3505
3506 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
3507    performance problems.
3508
3509    Perhaps don't eliminate things that can be combined with an addressing
3510    mode.  Find all givs that have the same biv, mult_val, and add_val;
3511    then for each giv, check to see if its only use dies in a following
3512    memory address.  If so, generate a new memory address and check to see
3513    if it is valid.   If it is valid, then store the modified memory address,
3514    otherwise, mark the giv as not done so that it will get its own iv.  */
3515
3516 /* ??? Could try to optimize branches when it is known that a biv is always
3517    positive.  */
3518
3519 /* ??? When replace a biv in a compare insn, we should replace with closest
3520    giv so that an optimized branch can still be recognized by the combiner,
3521    e.g. the VAX acb insn.  */
3522
3523 /* ??? Many of the checks involving uid_luid could be simplified if regscan
3524    was rerun in loop_optimize whenever a register was added or moved.
3525    Also, some of the optimizations could be a little less conservative.  */
3526 \f
3527 /* Perform strength reduction and induction variable elimination.  
3528
3529    Pseudo registers created during this function will be beyond the last
3530    valid index in several tables including n_times_set and regno_last_uid.
3531    This does not cause a problem here, because the added registers cannot be
3532    givs outside of their loop, and hence will never be reconsidered.
3533    But scan_loop must check regnos to make sure they are in bounds. 
3534    
3535    SCAN_START is the first instruction in the loop, as the loop would
3536    actually be executed.  END is the NOTE_INSN_LOOP_END.  LOOP_TOP is
3537    the first instruction in the loop, as it is layed out in the
3538    instruction stream.  LOOP_START is the NOTE_INSN_LOOP_BEG.  */
3539
3540 static void
3541 strength_reduce (scan_start, end, loop_top, insn_count,
3542                  loop_start, loop_end, unroll_p, bct_p)
3543      rtx scan_start;
3544      rtx end;
3545      rtx loop_top;
3546      int insn_count;
3547      rtx loop_start;
3548      rtx loop_end;
3549      int unroll_p, bct_p ATTRIBUTE_UNUSED;
3550 {
3551   rtx p;
3552   rtx set;
3553   rtx inc_val;
3554   rtx mult_val;
3555   rtx dest_reg;
3556   /* This is 1 if current insn is not executed at least once for every loop
3557      iteration.  */
3558   int not_every_iteration = 0;
3559   /* This is 1 if current insn may be executed more than once for every
3560      loop iteration.  */
3561   int maybe_multiple = 0;
3562   /* Temporary list pointers for traversing loop_iv_list.  */
3563   struct iv_class *bl, **backbl;
3564   /* Ratio of extra register life span we can justify
3565      for saving an instruction.  More if loop doesn't call subroutines
3566      since in that case saving an insn makes more difference
3567      and more registers are available.  */
3568   /* ??? could set this to last value of threshold in move_movables */
3569   int threshold = (loop_has_call ? 1 : 2) * (3 + n_non_fixed_regs);
3570   /* Map of pseudo-register replacements.  */
3571   rtx *reg_map;
3572   int call_seen;
3573   rtx test;
3574   rtx end_insert_before;
3575   int loop_depth = 0;
3576
3577   reg_iv_type = (enum iv_mode *) alloca (max_reg_before_loop
3578                                          * sizeof (enum iv_mode));
3579   bzero ((char *) reg_iv_type, max_reg_before_loop * sizeof (enum iv_mode));
3580   reg_iv_info = (struct induction **)
3581     alloca (max_reg_before_loop * sizeof (struct induction *));
3582   bzero ((char *) reg_iv_info, (max_reg_before_loop
3583                                 * sizeof (struct induction *)));
3584   reg_biv_class = (struct iv_class **)
3585     alloca (max_reg_before_loop * sizeof (struct iv_class *));
3586   bzero ((char *) reg_biv_class, (max_reg_before_loop
3587                                   * sizeof (struct iv_class *)));
3588
3589   loop_iv_list = 0;
3590   addr_placeholder = gen_reg_rtx (Pmode);
3591
3592   /* Save insn immediately after the loop_end.  Insns inserted after loop_end
3593      must be put before this insn, so that they will appear in the right
3594      order (i.e. loop order). 
3595
3596      If loop_end is the end of the current function, then emit a 
3597      NOTE_INSN_DELETED after loop_end and set end_insert_before to the
3598      dummy note insn.  */
3599   if (NEXT_INSN (loop_end) != 0)
3600     end_insert_before = NEXT_INSN (loop_end);
3601   else
3602     end_insert_before = emit_note_after (NOTE_INSN_DELETED, loop_end);
3603
3604   /* Scan through loop to find all possible bivs.  */
3605
3606   for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top);
3607        p != NULL_RTX;
3608        p = next_insn_in_loop (p, scan_start, end, loop_top))
3609     {
3610       if (GET_CODE (p) == INSN
3611           && (set = single_set (p))
3612           && GET_CODE (SET_DEST (set)) == REG)
3613         {
3614           dest_reg = SET_DEST (set);
3615           if (REGNO (dest_reg) < max_reg_before_loop
3616               && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
3617               && reg_iv_type[REGNO (dest_reg)] != NOT_BASIC_INDUCT)
3618             {
3619               if (basic_induction_var (SET_SRC (set), GET_MODE (SET_SRC (set)),
3620                                        dest_reg, p, &inc_val, &mult_val))
3621                 {
3622                   /* It is a possible basic induction variable.
3623                      Create and initialize an induction structure for it.  */
3624
3625                   struct induction *v
3626                     = (struct induction *) alloca (sizeof (struct induction));
3627
3628                   record_biv (v, p, dest_reg, inc_val, mult_val,
3629                               not_every_iteration, maybe_multiple);
3630                   reg_iv_type[REGNO (dest_reg)] = BASIC_INDUCT;
3631                 }
3632               else if (REGNO (dest_reg) < max_reg_before_loop)
3633                 reg_iv_type[REGNO (dest_reg)] = NOT_BASIC_INDUCT;
3634             }
3635         }
3636
3637       /* Past CODE_LABEL, we get to insns that may be executed multiple
3638          times.  The only way we can be sure that they can't is if every
3639          jump insn between here and the end of the loop either
3640          returns, exits the loop, is a forward jump, or is a jump
3641          to the loop start.  */
3642
3643       if (GET_CODE (p) == CODE_LABEL)
3644         {
3645           rtx insn = p;
3646
3647           maybe_multiple = 0;
3648
3649           while (1)
3650             {
3651               insn = NEXT_INSN (insn);
3652               if (insn == scan_start)
3653                 break;
3654               if (insn == end)
3655                 {
3656                   if (loop_top != 0)
3657                     insn = loop_top;
3658                   else
3659                     break;
3660                   if (insn == scan_start)
3661                     break;
3662                 }
3663
3664               if (GET_CODE (insn) == JUMP_INSN
3665                   && GET_CODE (PATTERN (insn)) != RETURN
3666                   && (! condjump_p (insn)
3667                       || (JUMP_LABEL (insn) != 0
3668                           && JUMP_LABEL (insn) != scan_start
3669                           && (INSN_UID (JUMP_LABEL (insn)) >= max_uid_for_loop
3670                               || INSN_UID (insn) >= max_uid_for_loop
3671                               || (INSN_LUID (JUMP_LABEL (insn))
3672                                   < INSN_LUID (insn))))))
3673                 {
3674                   maybe_multiple = 1;
3675                   break;
3676                 }
3677             }
3678         }
3679
3680       /* Past a jump, we get to insns for which we can't count
3681          on whether they will be executed during each iteration.  */
3682       /* This code appears twice in strength_reduce.  There is also similar
3683          code in scan_loop.  */
3684       if (GET_CODE (p) == JUMP_INSN
3685           /* If we enter the loop in the middle, and scan around to the
3686              beginning, don't set not_every_iteration for that.
3687              This can be any kind of jump, since we want to know if insns
3688              will be executed if the loop is executed.  */
3689           && ! (JUMP_LABEL (p) == loop_top
3690                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3691                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3692         {
3693           rtx label = 0;
3694
3695           /* If this is a jump outside the loop, then it also doesn't
3696              matter.  Check to see if the target of this branch is on the
3697              loop_number_exits_labels list.  */
3698              
3699           for (label = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
3700                label;
3701                label = LABEL_NEXTREF (label))
3702             if (XEXP (label, 0) == JUMP_LABEL (p))
3703               break;
3704
3705           if (! label)
3706             not_every_iteration = 1;
3707         }
3708
3709       else if (GET_CODE (p) == NOTE)
3710         {
3711           /* At the virtual top of a converted loop, insns are again known to
3712              be executed each iteration: logically, the loop begins here
3713              even though the exit code has been duplicated.  */
3714           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
3715             not_every_iteration = 0;
3716           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3717             loop_depth++;
3718           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
3719             loop_depth--;
3720         }
3721
3722       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3723          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3724          or not an insn is known to be executed each iteration of the
3725          loop, whether or not any iterations are known to occur.
3726
3727          Therefore, if we have just passed a label and have no more labels
3728          between here and the test insn of the loop, we know these insns
3729          will be executed each iteration.  */
3730
3731       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
3732           && no_labels_between_p (p, loop_end))
3733         not_every_iteration = 0;
3734     }
3735
3736   /* Scan loop_iv_list to remove all regs that proved not to be bivs.
3737      Make a sanity check against n_times_set.  */
3738   for (backbl = &loop_iv_list, bl = *backbl; bl; bl = bl->next)
3739     {
3740       if (reg_iv_type[bl->regno] != BASIC_INDUCT
3741           /* Above happens if register modified by subreg, etc.  */
3742           /* Make sure it is not recognized as a basic induction var: */
3743           || VARRAY_INT (n_times_set, bl->regno) != bl->biv_count
3744           /* If never incremented, it is invariant that we decided not to
3745              move.  So leave it alone.  */
3746           || ! bl->incremented)
3747         {
3748           if (loop_dump_stream)
3749             fprintf (loop_dump_stream, "Reg %d: biv discarded, %s\n",
3750                      bl->regno,
3751                      (reg_iv_type[bl->regno] != BASIC_INDUCT
3752                       ? "not induction variable"
3753                       : (! bl->incremented ? "never incremented"
3754                          : "count error")));
3755           
3756           reg_iv_type[bl->regno] = NOT_BASIC_INDUCT;
3757           *backbl = bl->next;
3758         }
3759       else
3760         {
3761           backbl = &bl->next;
3762
3763           if (loop_dump_stream)
3764             fprintf (loop_dump_stream, "Reg %d: biv verified\n", bl->regno);
3765         }
3766     }
3767
3768   /* Exit if there are no bivs.  */
3769   if (! loop_iv_list)
3770     {
3771       /* Can still unroll the loop anyways, but indicate that there is no
3772          strength reduction info available.  */
3773       if (unroll_p)
3774         unroll_loop (loop_end, insn_count, loop_start, end_insert_before, 0);
3775
3776       return;
3777     }
3778
3779   /* Find initial value for each biv by searching backwards from loop_start,
3780      halting at first label.  Also record any test condition.  */
3781
3782   call_seen = 0;
3783   for (p = loop_start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
3784     {
3785       note_insn = p;
3786
3787       if (GET_CODE (p) == CALL_INSN)
3788         call_seen = 1;
3789
3790       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3791           || GET_CODE (p) == CALL_INSN)
3792         note_stores (PATTERN (p), record_initial);
3793
3794       /* Record any test of a biv that branches around the loop if no store
3795          between it and the start of loop.  We only care about tests with
3796          constants and registers and only certain of those.  */
3797       if (GET_CODE (p) == JUMP_INSN
3798           && JUMP_LABEL (p) != 0
3799           && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop_end)
3800           && (test = get_condition_for_loop (p)) != 0
3801           && GET_CODE (XEXP (test, 0)) == REG
3802           && REGNO (XEXP (test, 0)) < max_reg_before_loop
3803           && (bl = reg_biv_class[REGNO (XEXP (test, 0))]) != 0
3804           && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop_start)
3805           && bl->init_insn == 0)
3806         {
3807           /* If an NE test, we have an initial value!  */
3808           if (GET_CODE (test) == NE)
3809             {
3810               bl->init_insn = p;
3811               bl->init_set = gen_rtx_SET (VOIDmode,
3812                                           XEXP (test, 0), XEXP (test, 1));
3813             }
3814           else
3815             bl->initial_test = test;
3816         }
3817     }
3818
3819   /* Look at the each biv and see if we can say anything better about its
3820      initial value from any initializing insns set up above.  (This is done
3821      in two passes to avoid missing SETs in a PARALLEL.)  */
3822   for (bl = loop_iv_list; bl; bl = bl->next)
3823     {
3824       rtx src;
3825       rtx note;
3826
3827       if (! bl->init_insn)
3828         continue;
3829
3830       /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
3831          is a constant, use the value of that.  */
3832       if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
3833            && CONSTANT_P (XEXP (note, 0)))
3834           || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
3835               && CONSTANT_P (XEXP (note, 0))))
3836         src = XEXP (note, 0);
3837       else
3838         src = SET_SRC (bl->init_set);
3839
3840       if (loop_dump_stream)
3841         fprintf (loop_dump_stream,
3842                  "Biv %d initialized at insn %d: initial value ",
3843                  bl->regno, INSN_UID (bl->init_insn));
3844
3845       if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
3846            || GET_MODE (src) == VOIDmode)
3847           && valid_initial_value_p (src, bl->init_insn, call_seen, loop_start))
3848         {
3849           bl->initial_value = src;
3850
3851           if (loop_dump_stream)
3852             {
3853               if (GET_CODE (src) == CONST_INT)
3854                 {
3855                   fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (src));
3856                   fputc ('\n', loop_dump_stream);
3857                 }
3858               else
3859                 {
3860                   print_rtl (loop_dump_stream, src);
3861                   fprintf (loop_dump_stream, "\n");
3862                 }
3863             }
3864         }
3865       else
3866         {
3867           /* Biv initial value is not simple move,
3868              so let it keep initial value of "itself".  */
3869
3870           if (loop_dump_stream)
3871             fprintf (loop_dump_stream, "is complex\n");
3872         }
3873     }
3874
3875   /* Search the loop for general induction variables.  */
3876
3877   /* A register is a giv if: it is only set once, it is a function of a
3878      biv and a constant (or invariant), and it is not a biv.  */
3879
3880   not_every_iteration = 0;
3881   loop_depth = 0;
3882   p = scan_start;
3883   while (1)
3884     {
3885       p = NEXT_INSN (p);
3886       /* At end of a straight-in loop, we are done.
3887          At end of a loop entered at the bottom, scan the top.  */
3888       if (p == scan_start)
3889         break;
3890       if (p == end)
3891         {
3892           if (loop_top != 0)
3893             p = loop_top;
3894           else
3895             break;
3896           if (p == scan_start)
3897             break;
3898         }
3899
3900       /* Look for a general induction variable in a register.  */
3901       if (GET_CODE (p) == INSN
3902           && (set = single_set (p))
3903           && GET_CODE (SET_DEST (set)) == REG
3904           && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
3905         {
3906           rtx src_reg;
3907           rtx add_val;
3908           rtx mult_val;
3909           int benefit;
3910           rtx regnote = 0;
3911
3912           dest_reg = SET_DEST (set);
3913           if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
3914             continue;
3915
3916           if (/* SET_SRC is a giv.  */
3917               (general_induction_var (SET_SRC (set), &src_reg, &add_val,
3918                                       &mult_val, 0, &benefit)
3919                /* Equivalent expression is a giv.  */
3920                || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
3921                    && general_induction_var (XEXP (regnote, 0), &src_reg,
3922                                              &add_val, &mult_val, 0,
3923                                              &benefit)))
3924               /* Don't try to handle any regs made by loop optimization.
3925                  We have nothing on them in regno_first_uid, etc.  */
3926               && REGNO (dest_reg) < max_reg_before_loop
3927               /* Don't recognize a BASIC_INDUCT_VAR here.  */
3928               && dest_reg != src_reg
3929               /* This must be the only place where the register is set.  */
3930               && (VARRAY_INT (n_times_set, REGNO (dest_reg)) == 1
3931                   /* or all sets must be consecutive and make a giv.  */
3932                   || (benefit = consec_sets_giv (benefit, p,
3933                                                  src_reg, dest_reg,
3934                                                  &add_val, &mult_val))))
3935             {
3936               int count;
3937               struct induction *v
3938                 = (struct induction *) alloca (sizeof (struct induction));
3939               rtx temp;
3940
3941               /* If this is a library call, increase benefit.  */
3942               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
3943                 benefit += libcall_benefit (p);
3944
3945               /* Skip the consecutive insns, if there are any.  */
3946               for (count = VARRAY_INT (n_times_set, REGNO (dest_reg)) - 1;
3947                    count > 0; count--)
3948                 {
3949                   /* If first insn of libcall sequence, skip to end.
3950                      Do this at start of loop, since INSN is guaranteed to
3951                      be an insn here.  */
3952                   if (GET_CODE (p) != NOTE
3953                       && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3954                     p = XEXP (temp, 0);
3955
3956                   do p = NEXT_INSN (p);
3957                   while (GET_CODE (p) == NOTE);
3958                 }
3959
3960               record_giv (v, p, src_reg, dest_reg, mult_val, add_val, benefit,
3961                           DEST_REG, not_every_iteration, NULL_PTR, loop_start,
3962                           loop_end);
3963
3964             }
3965         }
3966
3967 #ifndef DONT_REDUCE_ADDR
3968       /* Look for givs which are memory addresses.  */
3969       /* This resulted in worse code on a VAX 8600.  I wonder if it
3970          still does.  */
3971       if (GET_CODE (p) == INSN)
3972         find_mem_givs (PATTERN (p), p, not_every_iteration, loop_start,
3973                        loop_end);
3974 #endif
3975
3976       /* Update the status of whether giv can derive other givs.  This can
3977          change when we pass a label or an insn that updates a biv.  */
3978       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3979         || GET_CODE (p) == CODE_LABEL)
3980         update_giv_derive (p);
3981
3982       /* Past a jump, we get to insns for which we can't count
3983          on whether they will be executed during each iteration.  */
3984       /* This code appears twice in strength_reduce.  There is also similar
3985          code in scan_loop.  */
3986       if (GET_CODE (p) == JUMP_INSN
3987           /* If we enter the loop in the middle, and scan around to the
3988              beginning, don't set not_every_iteration for that.
3989              This can be any kind of jump, since we want to know if insns
3990              will be executed if the loop is executed.  */
3991           && ! (JUMP_LABEL (p) == loop_top
3992                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3993                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3994         {
3995           rtx label = 0;
3996
3997           /* If this is a jump outside the loop, then it also doesn't
3998              matter.  Check to see if the target of this branch is on the
3999              loop_number_exits_labels list.  */
4000              
4001           for (label = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
4002                label;
4003                label = LABEL_NEXTREF (label))
4004             if (XEXP (label, 0) == JUMP_LABEL (p))
4005               break;
4006
4007           if (! label)
4008             not_every_iteration = 1;
4009         }
4010
4011       else if (GET_CODE (p) == NOTE)
4012         {
4013           /* At the virtual top of a converted loop, insns are again known to
4014              be executed each iteration: logically, the loop begins here
4015              even though the exit code has been duplicated.  */
4016           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
4017             not_every_iteration = 0;
4018           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
4019             loop_depth++;
4020           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
4021             loop_depth--;
4022         }
4023
4024       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4025          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4026          or not an insn is known to be executed each iteration of the
4027          loop, whether or not any iterations are known to occur.
4028
4029          Therefore, if we have just passed a label and have no more labels
4030          between here and the test insn of the loop, we know these insns
4031          will be executed each iteration.  */
4032
4033       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
4034           && no_labels_between_p (p, loop_end))
4035         not_every_iteration = 0;
4036     }
4037
4038   /* Try to calculate and save the number of loop iterations.  This is
4039      set to zero if the actual number can not be calculated.  This must
4040      be called after all giv's have been identified, since otherwise it may
4041      fail if the iteration variable is a giv.  */
4042
4043   loop_n_iterations = loop_iterations (loop_start, loop_end);
4044
4045   /* Now for each giv for which we still don't know whether or not it is
4046      replaceable, check to see if it is replaceable because its final value
4047      can be calculated.  This must be done after loop_iterations is called,
4048      so that final_giv_value will work correctly.  */
4049
4050   for (bl = loop_iv_list; bl; bl = bl->next)
4051     {
4052       struct induction *v;
4053
4054       for (v = bl->giv; v; v = v->next_iv)
4055         if (! v->replaceable && ! v->not_replaceable)
4056           check_final_value (v, loop_start, loop_end);
4057     }
4058
4059   /* Try to prove that the loop counter variable (if any) is always
4060      nonnegative; if so, record that fact with a REG_NONNEG note
4061      so that "decrement and branch until zero" insn can be used.  */
4062   check_dbra_loop (loop_end, insn_count, loop_start);
4063
4064   /* Create reg_map to hold substitutions for replaceable giv regs.  */
4065   reg_map = (rtx *) alloca (max_reg_before_loop * sizeof (rtx));
4066   bzero ((char *) reg_map, max_reg_before_loop * sizeof (rtx));
4067
4068   /* Examine each iv class for feasibility of strength reduction/induction
4069      variable elimination.  */
4070
4071   for (bl = loop_iv_list; bl; bl = bl->next)
4072     {
4073       struct induction *v;
4074       int benefit;
4075       int all_reduced;
4076       rtx final_value = 0;
4077
4078       /* Test whether it will be possible to eliminate this biv
4079          provided all givs are reduced.  This is possible if either
4080          the reg is not used outside the loop, or we can compute
4081          what its final value will be.
4082
4083          For architectures with a decrement_and_branch_until_zero insn,
4084          don't do this if we put a REG_NONNEG note on the endtest for
4085          this biv.  */
4086
4087       /* Compare against bl->init_insn rather than loop_start.
4088          We aren't concerned with any uses of the biv between
4089          init_insn and loop_start since these won't be affected
4090          by the value of the biv elsewhere in the function, so
4091          long as init_insn doesn't use the biv itself.
4092          March 14, 1989 -- self@bayes.arc.nasa.gov */
4093
4094       if ((uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4095            && bl->init_insn
4096            && INSN_UID (bl->init_insn) < max_uid_for_loop
4097            && uid_luid[REGNO_FIRST_UID (bl->regno)] >= INSN_LUID (bl->init_insn)
4098 #ifdef HAVE_decrement_and_branch_until_zero
4099            && ! bl->nonneg
4100 #endif
4101            && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4102           || ((final_value = final_biv_value (bl, loop_start, loop_end))
4103 #ifdef HAVE_decrement_and_branch_until_zero
4104               && ! bl->nonneg
4105 #endif
4106               ))
4107         bl->eliminable = maybe_eliminate_biv (bl, loop_start, end, 0,
4108                                               threshold, insn_count);
4109       else
4110         {
4111           if (loop_dump_stream)
4112             {
4113               fprintf (loop_dump_stream,
4114                        "Cannot eliminate biv %d.\n",
4115                        bl->regno);
4116               fprintf (loop_dump_stream,
4117                        "First use: insn %d, last use: insn %d.\n",
4118                        REGNO_FIRST_UID (bl->regno),
4119                        REGNO_LAST_UID (bl->regno));
4120             }
4121         }
4122
4123       /* Combine all giv's for this iv_class.  */
4124       combine_givs (bl);
4125
4126       /* This will be true at the end, if all givs which depend on this
4127          biv have been strength reduced.
4128          We can't (currently) eliminate the biv unless this is so.  */
4129       all_reduced = 1;
4130
4131       /* Check each giv in this class to see if we will benefit by reducing
4132          it.  Skip giv's combined with others.  */
4133       for (v = bl->giv; v; v = v->next_iv)
4134         {
4135           struct induction *tv;
4136
4137           if (v->ignore || v->same)
4138             continue;
4139
4140           benefit = v->benefit;
4141
4142           /* Reduce benefit if not replaceable, since we will insert
4143              a move-insn to replace the insn that calculates this giv.
4144              Don't do this unless the giv is a user variable, since it
4145              will often be marked non-replaceable because of the duplication
4146              of the exit code outside the loop.  In such a case, the copies
4147              we insert are dead and will be deleted.  So they don't have
4148              a cost.  Similar situations exist.  */
4149           /* ??? The new final_[bg]iv_value code does a much better job
4150              of finding replaceable giv's, and hence this code may no longer
4151              be necessary.  */
4152           if (! v->replaceable && ! bl->eliminable
4153               && REG_USERVAR_P (v->dest_reg))
4154             benefit -= copy_cost;
4155
4156           /* Decrease the benefit to count the add-insns that we will
4157              insert to increment the reduced reg for the giv.  */
4158           benefit -= add_cost * bl->biv_count;
4159
4160           /* Decide whether to strength-reduce this giv or to leave the code
4161              unchanged (recompute it from the biv each time it is used).
4162              This decision can be made independently for each giv.  */
4163
4164 #ifdef AUTO_INC_DEC
4165           /* Attempt to guess whether autoincrement will handle some of the
4166              new add insns; if so, increase BENEFIT (undo the subtraction of
4167              add_cost that was done above).  */
4168           if (v->giv_type == DEST_ADDR
4169               && GET_CODE (v->mult_val) == CONST_INT)
4170             {
4171 #if defined (HAVE_POST_INCREMENT) || defined (HAVE_PRE_INCREMENT)
4172               if (INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4173                 benefit += add_cost * bl->biv_count;
4174 #endif
4175 #if defined (HAVE_POST_DECREMENT) || defined (HAVE_PRE_DECREMENT)
4176               if (-INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4177                 benefit += add_cost * bl->biv_count;
4178 #endif
4179             }
4180 #endif
4181
4182           /* If an insn is not to be strength reduced, then set its ignore
4183              flag, and clear all_reduced.  */
4184
4185           /* A giv that depends on a reversed biv must be reduced if it is
4186              used after the loop exit, otherwise, it would have the wrong
4187              value after the loop exit.  To make it simple, just reduce all
4188              of such giv's whether or not we know they are used after the loop
4189              exit.  */
4190
4191           if ( ! flag_reduce_all_givs && v->lifetime * threshold * benefit < insn_count
4192               && ! bl->reversed )
4193             {
4194               if (loop_dump_stream)
4195                 fprintf (loop_dump_stream,
4196                          "giv of insn %d not worth while, %d vs %d.\n",
4197                          INSN_UID (v->insn),
4198                          v->lifetime * threshold * benefit, insn_count);
4199               v->ignore = 1;
4200               all_reduced = 0;
4201             }
4202           else
4203             {
4204               /* Check that we can increment the reduced giv without a
4205                  multiply insn.  If not, reject it.  */
4206
4207               for (tv = bl->biv; tv; tv = tv->next_iv)
4208                 if (tv->mult_val == const1_rtx
4209                     && ! product_cheap_p (tv->add_val, v->mult_val))
4210                   {
4211                     if (loop_dump_stream)
4212                       fprintf (loop_dump_stream,
4213                                "giv of insn %d: would need a multiply.\n",
4214                                INSN_UID (v->insn));
4215                     v->ignore = 1;
4216                     all_reduced = 0;
4217                     break;
4218                   }
4219             }
4220         }
4221
4222       /* Reduce each giv that we decided to reduce.  */
4223
4224       for (v = bl->giv; v; v = v->next_iv)
4225         {
4226           struct induction *tv;
4227           if (! v->ignore && v->same == 0)
4228             {
4229               int auto_inc_opt = 0;
4230
4231               v->new_reg = gen_reg_rtx (v->mode);
4232
4233 #ifdef AUTO_INC_DEC
4234               /* If the target has auto-increment addressing modes, and
4235                  this is an address giv, then try to put the increment
4236                  immediately after its use, so that flow can create an
4237                  auto-increment addressing mode.  */
4238               if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4239                   && bl->biv->always_executed && ! bl->biv->maybe_multiple
4240                   /* We don't handle reversed biv's because bl->biv->insn
4241                      does not have a valid INSN_LUID.  */
4242                   && ! bl->reversed
4243                   && v->always_executed && ! v->maybe_multiple
4244                   && INSN_UID (v->insn) < max_uid_for_loop)
4245                 {
4246                   /* If other giv's have been combined with this one, then
4247                      this will work only if all uses of the other giv's occur
4248                      before this giv's insn.  This is difficult to check.
4249
4250                      We simplify this by looking for the common case where
4251                      there is one DEST_REG giv, and this giv's insn is the
4252                      last use of the dest_reg of that DEST_REG giv.  If the
4253                      increment occurs after the address giv, then we can
4254                      perform the optimization.  (Otherwise, the increment
4255                      would have to go before other_giv, and we would not be
4256                      able to combine it with the address giv to get an
4257                      auto-inc address.)  */
4258                   if (v->combined_with)
4259                     {
4260                       struct induction *other_giv = 0;
4261
4262                       for (tv = bl->giv; tv; tv = tv->next_iv)
4263                         if (tv->same == v)
4264                           {
4265                             if (other_giv)
4266                               break;
4267                             else
4268                               other_giv = tv;
4269                           }
4270                       if (! tv && other_giv
4271                           && REGNO (other_giv->dest_reg) < max_reg_before_loop
4272                           && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4273                               == INSN_UID (v->insn))
4274                           && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4275                         auto_inc_opt = 1;
4276                     }
4277                   /* Check for case where increment is before the address
4278                      giv.  Do this test in "loop order".  */
4279                   else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4280                             && (INSN_LUID (v->insn) < INSN_LUID (scan_start)
4281                                 || (INSN_LUID (bl->biv->insn)
4282                                     > INSN_LUID (scan_start))))
4283                            || (INSN_LUID (v->insn) < INSN_LUID (scan_start)
4284                                && (INSN_LUID (scan_start)
4285                                    < INSN_LUID (bl->biv->insn))))
4286                     auto_inc_opt = -1;
4287                   else
4288                     auto_inc_opt = 1;
4289
4290 #ifdef HAVE_cc0
4291                   {
4292                     rtx prev;
4293
4294                     /* We can't put an insn immediately after one setting
4295                        cc0, or immediately before one using cc0.  */
4296                     if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4297                         || (auto_inc_opt == -1
4298                             && (prev = prev_nonnote_insn (v->insn)) != 0
4299                             && GET_RTX_CLASS (GET_CODE (prev)) == 'i'
4300                             && sets_cc0_p (PATTERN (prev))))
4301                       auto_inc_opt = 0;
4302                   }
4303 #endif
4304
4305                   if (auto_inc_opt)
4306                     v->auto_inc_opt = 1;
4307                 }
4308 #endif
4309
4310               /* For each place where the biv is incremented, add an insn
4311                  to increment the new, reduced reg for the giv.  */
4312               for (tv = bl->biv; tv; tv = tv->next_iv)
4313                 {
4314                   rtx insert_before;
4315
4316                   if (! auto_inc_opt)
4317                     insert_before = tv->insn;
4318                   else if (auto_inc_opt == 1)
4319                     insert_before = NEXT_INSN (v->insn);
4320                   else
4321                     insert_before = v->insn;
4322
4323                   if (tv->mult_val == const1_rtx)
4324                     emit_iv_add_mult (tv->add_val, v->mult_val,
4325                                       v->new_reg, v->new_reg, insert_before);
4326                   else /* tv->mult_val == const0_rtx */
4327                     /* A multiply is acceptable here
4328                        since this is presumed to be seldom executed.  */
4329                     emit_iv_add_mult (tv->add_val, v->mult_val,
4330                                       v->add_val, v->new_reg, insert_before);
4331                 }
4332
4333               /* Add code at loop start to initialize giv's reduced reg.  */
4334
4335               emit_iv_add_mult (bl->initial_value, v->mult_val,
4336                                 v->add_val, v->new_reg, loop_start);
4337             }
4338         }
4339
4340       /* Rescan all givs.  If a giv is the same as a giv not reduced, mark it
4341          as not reduced.
4342          
4343          For each giv register that can be reduced now: if replaceable,
4344          substitute reduced reg wherever the old giv occurs;
4345          else add new move insn "giv_reg = reduced_reg".
4346
4347          Also check for givs whose first use is their definition and whose
4348          last use is the definition of another giv.  If so, it is likely
4349          dead and should not be used to eliminate a biv.  */
4350       for (v = bl->giv; v; v = v->next_iv)
4351         {
4352           if (v->same && v->same->ignore)
4353             v->ignore = 1;
4354
4355           if (v->ignore)
4356             continue;
4357
4358           if (v->giv_type == DEST_REG
4359               && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4360             {
4361               struct induction *v1;
4362
4363               for (v1 = bl->giv; v1; v1 = v1->next_iv)
4364                 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4365                   v->maybe_dead = 1;
4366             }
4367
4368           /* Update expression if this was combined, in case other giv was
4369              replaced.  */
4370           if (v->same)
4371             v->new_reg = replace_rtx (v->new_reg,
4372                                       v->same->dest_reg, v->same->new_reg);
4373
4374           if (v->giv_type == DEST_ADDR)
4375             /* Store reduced reg as the address in the memref where we found
4376                this giv.  */
4377             validate_change (v->insn, v->location, v->new_reg, 0);
4378           else if (v->replaceable)
4379             {
4380               reg_map[REGNO (v->dest_reg)] = v->new_reg;
4381
4382 #if 0
4383               /* I can no longer duplicate the original problem.  Perhaps
4384                  this is unnecessary now?  */
4385
4386               /* Replaceable; it isn't strictly necessary to delete the old
4387                  insn and emit a new one, because v->dest_reg is now dead.
4388
4389                  However, especially when unrolling loops, the special
4390                  handling for (set REG0 REG1) in the second cse pass may
4391                  make v->dest_reg live again.  To avoid this problem, emit
4392                  an insn to set the original giv reg from the reduced giv.
4393                  We can not delete the original insn, since it may be part
4394                  of a LIBCALL, and the code in flow that eliminates dead
4395                  libcalls will fail if it is deleted.  */
4396               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
4397                                v->insn);
4398 #endif
4399             }
4400           else
4401             {
4402               /* Not replaceable; emit an insn to set the original giv reg from
4403                  the reduced giv, same as above.  */
4404               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
4405                                v->insn);
4406             }
4407
4408           /* When a loop is reversed, givs which depend on the reversed
4409              biv, and which are live outside the loop, must be set to their
4410              correct final value.  This insn is only needed if the giv is
4411              not replaceable.  The correct final value is the same as the
4412              value that the giv starts the reversed loop with.  */
4413           if (bl->reversed && ! v->replaceable)
4414             emit_iv_add_mult (bl->initial_value, v->mult_val,
4415                               v->add_val, v->dest_reg, end_insert_before);
4416           else if (v->final_value)
4417             {
4418               rtx insert_before;
4419
4420               /* If the loop has multiple exits, emit the insn before the
4421                  loop to ensure that it will always be executed no matter
4422                  how the loop exits.  Otherwise, emit the insn after the loop,
4423                  since this is slightly more efficient.  */
4424               if (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
4425                 insert_before = loop_start;
4426               else
4427                 insert_before = end_insert_before;
4428               emit_insn_before (gen_move_insn (v->dest_reg, v->final_value),
4429                                 insert_before);
4430
4431 #if 0
4432               /* If the insn to set the final value of the giv was emitted
4433                  before the loop, then we must delete the insn inside the loop
4434                  that sets it.  If this is a LIBCALL, then we must delete
4435                  every insn in the libcall.  Note, however, that
4436                  final_giv_value will only succeed when there are multiple
4437                  exits if the giv is dead at each exit, hence it does not
4438                  matter that the original insn remains because it is dead
4439                  anyways.  */
4440               /* Delete the insn inside the loop that sets the giv since
4441                  the giv is now set before (or after) the loop.  */
4442               delete_insn (v->insn);
4443 #endif
4444             }
4445
4446           if (loop_dump_stream)
4447             {
4448               fprintf (loop_dump_stream, "giv at %d reduced to ",
4449                        INSN_UID (v->insn));
4450               print_rtl (loop_dump_stream, v->new_reg);
4451               fprintf (loop_dump_stream, "\n");
4452             }
4453         }
4454
4455       /* All the givs based on the biv bl have been reduced if they
4456          merit it.  */
4457
4458       /* For each giv not marked as maybe dead that has been combined with a
4459          second giv, clear any "maybe dead" mark on that second giv.
4460          v->new_reg will either be or refer to the register of the giv it
4461          combined with.
4462
4463          Doing this clearing avoids problems in biv elimination where a
4464          giv's new_reg is a complex value that can't be put in the insn but
4465          the giv combined with (with a reg as new_reg) is marked maybe_dead.
4466          Since the register will be used in either case, we'd prefer it be
4467          used from the simpler giv.  */
4468
4469       for (v = bl->giv; v; v = v->next_iv)
4470         if (! v->maybe_dead && v->same)
4471           v->same->maybe_dead = 0;
4472
4473       /* Try to eliminate the biv, if it is a candidate.
4474          This won't work if ! all_reduced,
4475          since the givs we planned to use might not have been reduced.
4476
4477          We have to be careful that we didn't initially think we could eliminate
4478          this biv because of a giv that we now think may be dead and shouldn't
4479          be used as a biv replacement.  
4480
4481          Also, there is the possibility that we may have a giv that looks
4482          like it can be used to eliminate a biv, but the resulting insn
4483          isn't valid.  This can happen, for example, on the 88k, where a 
4484          JUMP_INSN can compare a register only with zero.  Attempts to
4485          replace it with a compare with a constant will fail.
4486
4487          Note that in cases where this call fails, we may have replaced some
4488          of the occurrences of the biv with a giv, but no harm was done in
4489          doing so in the rare cases where it can occur.  */
4490
4491       if (all_reduced == 1 && bl->eliminable
4492           && maybe_eliminate_biv (bl, loop_start, end, 1,
4493                                   threshold, insn_count))
4494
4495         {
4496           /* ?? If we created a new test to bypass the loop entirely,
4497              or otherwise drop straight in, based on this test, then
4498              we might want to rewrite it also.  This way some later
4499              pass has more hope of removing the initialization of this
4500              biv entirely.  */
4501
4502           /* If final_value != 0, then the biv may be used after loop end
4503              and we must emit an insn to set it just in case.
4504
4505              Reversed bivs already have an insn after the loop setting their
4506              value, so we don't need another one.  We can't calculate the
4507              proper final value for such a biv here anyways.  */
4508           if (final_value != 0 && ! bl->reversed)
4509             {
4510               rtx insert_before;
4511
4512               /* If the loop has multiple exits, emit the insn before the
4513                  loop to ensure that it will always be executed no matter
4514                  how the loop exits.  Otherwise, emit the insn after the
4515                  loop, since this is slightly more efficient.  */
4516               if (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
4517                 insert_before = loop_start;
4518               else
4519                 insert_before = end_insert_before;
4520
4521               emit_insn_before (gen_move_insn (bl->biv->dest_reg, final_value),
4522                                 end_insert_before);
4523             }
4524
4525 #if 0
4526           /* Delete all of the instructions inside the loop which set
4527              the biv, as they are all dead.  If is safe to delete them,
4528              because an insn setting a biv will never be part of a libcall.  */
4529           /* However, deleting them will invalidate the regno_last_uid info,
4530              so keeping them around is more convenient.  Final_biv_value
4531              will only succeed when there are multiple exits if the biv
4532              is dead at each exit, hence it does not matter that the original
4533              insn remains, because it is dead anyways.  */
4534           for (v = bl->biv; v; v = v->next_iv)
4535             delete_insn (v->insn);
4536 #endif
4537
4538           if (loop_dump_stream)
4539             fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
4540                      bl->regno);
4541         }
4542     }
4543
4544   /* Go through all the instructions in the loop, making all the
4545      register substitutions scheduled in REG_MAP.  */
4546
4547   for (p = loop_start; p != end; p = NEXT_INSN (p))
4548     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4549         || GET_CODE (p) == CALL_INSN)
4550       {
4551         replace_regs (PATTERN (p), reg_map, max_reg_before_loop, 0);
4552         replace_regs (REG_NOTES (p), reg_map, max_reg_before_loop, 0);
4553         INSN_CODE (p) = -1;
4554       }
4555
4556   /* Unroll loops from within strength reduction so that we can use the
4557      induction variable information that strength_reduce has already
4558      collected.  */
4559   
4560   if (unroll_p)
4561     unroll_loop (loop_end, insn_count, loop_start, end_insert_before, 1);
4562
4563 #ifdef HAVE_decrement_and_branch_on_count
4564   /* Instrument the loop with BCT insn.  */
4565   if (HAVE_decrement_and_branch_on_count && bct_p
4566       && flag_branch_on_count_reg)
4567     insert_bct (loop_start, loop_end);
4568 #endif  /* HAVE_decrement_and_branch_on_count */
4569
4570   if (loop_dump_stream)
4571     fprintf (loop_dump_stream, "\n");
4572 }
4573 \f
4574 /* Return 1 if X is a valid source for an initial value (or as value being
4575    compared against in an initial test).
4576
4577    X must be either a register or constant and must not be clobbered between
4578    the current insn and the start of the loop.
4579
4580    INSN is the insn containing X.  */
4581
4582 static int
4583 valid_initial_value_p (x, insn, call_seen, loop_start)
4584      rtx x;
4585      rtx insn;
4586      int call_seen;
4587      rtx loop_start;
4588 {
4589   if (CONSTANT_P (x))
4590     return 1;
4591
4592   /* Only consider pseudos we know about initialized in insns whose luids
4593      we know.  */
4594   if (GET_CODE (x) != REG
4595       || REGNO (x) >= max_reg_before_loop)
4596     return 0;
4597
4598   /* Don't use call-clobbered registers across a call which clobbers it.  On
4599      some machines, don't use any hard registers at all.  */
4600   if (REGNO (x) < FIRST_PSEUDO_REGISTER
4601       && (SMALL_REGISTER_CLASSES
4602           || (call_used_regs[REGNO (x)] && call_seen)))
4603     return 0;
4604
4605   /* Don't use registers that have been clobbered before the start of the
4606      loop.  */
4607   if (reg_set_between_p (x, insn, loop_start))
4608     return 0;
4609
4610   return 1;
4611 }
4612 \f
4613 /* Scan X for memory refs and check each memory address
4614    as a possible giv.  INSN is the insn whose pattern X comes from.
4615    NOT_EVERY_ITERATION is 1 if the insn might not be executed during
4616    every loop iteration.  */
4617
4618 static void
4619 find_mem_givs (x, insn, not_every_iteration, loop_start, loop_end)
4620      rtx x;
4621      rtx insn;
4622      int not_every_iteration;
4623      rtx loop_start, loop_end;
4624 {
4625   register int i, j;
4626   register enum rtx_code code;
4627   register char *fmt;
4628
4629   if (x == 0)
4630     return;
4631
4632   code = GET_CODE (x);
4633   switch (code)
4634     {
4635     case REG:
4636     case CONST_INT:
4637     case CONST:
4638     case CONST_DOUBLE:
4639     case SYMBOL_REF:
4640     case LABEL_REF:
4641     case PC:
4642     case CC0:
4643     case ADDR_VEC:
4644     case ADDR_DIFF_VEC:
4645     case USE:
4646     case CLOBBER:
4647       return;
4648
4649     case MEM:
4650       {
4651         rtx src_reg;
4652         rtx add_val;
4653         rtx mult_val;
4654         int benefit;
4655
4656         /* This code used to disable creating GIVs with mult_val == 1 and
4657            add_val == 0.  However, this leads to lost optimizations when 
4658            it comes time to combine a set of related DEST_ADDR GIVs, since
4659            this one would not be seen.   */
4660
4661         if (general_induction_var (XEXP (x, 0), &src_reg, &add_val,
4662                                    &mult_val, 1, &benefit))
4663           {
4664             /* Found one; record it.  */
4665             struct induction *v
4666               = (struct induction *) oballoc (sizeof (struct induction));
4667
4668             record_giv (v, insn, src_reg, addr_placeholder, mult_val,
4669                         add_val, benefit, DEST_ADDR, not_every_iteration,
4670                         &XEXP (x, 0), loop_start, loop_end);
4671
4672             v->mem_mode = GET_MODE (x);
4673           }
4674       }
4675       return;
4676
4677     default:
4678       break;
4679     }
4680
4681   /* Recursively scan the subexpressions for other mem refs.  */
4682
4683   fmt = GET_RTX_FORMAT (code);
4684   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4685     if (fmt[i] == 'e')
4686       find_mem_givs (XEXP (x, i), insn, not_every_iteration, loop_start,
4687                      loop_end);
4688     else if (fmt[i] == 'E')
4689       for (j = 0; j < XVECLEN (x, i); j++)
4690         find_mem_givs (XVECEXP (x, i, j), insn, not_every_iteration,
4691                        loop_start, loop_end);
4692 }
4693 \f
4694 /* Fill in the data about one biv update.
4695    V is the `struct induction' in which we record the biv.  (It is
4696    allocated by the caller, with alloca.)
4697    INSN is the insn that sets it.
4698    DEST_REG is the biv's reg.
4699
4700    MULT_VAL is const1_rtx if the biv is being incremented here, in which case
4701    INC_VAL is the increment.  Otherwise, MULT_VAL is const0_rtx and the biv is
4702    being set to INC_VAL.
4703
4704    NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
4705    executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
4706    can be executed more than once per iteration.  If MAYBE_MULTIPLE
4707    and NOT_EVERY_ITERATION are both zero, we know that the biv update is
4708    executed exactly once per iteration.  */
4709
4710 static void
4711 record_biv (v, insn, dest_reg, inc_val, mult_val,
4712             not_every_iteration, maybe_multiple)
4713      struct induction *v;
4714      rtx insn;
4715      rtx dest_reg;
4716      rtx inc_val;
4717      rtx mult_val;
4718      int not_every_iteration;
4719      int maybe_multiple;
4720 {
4721   struct iv_class *bl;
4722
4723   v->insn = insn;
4724   v->src_reg = dest_reg;
4725   v->dest_reg = dest_reg;
4726   v->mult_val = mult_val;
4727   v->add_val = inc_val;
4728   v->mode = GET_MODE (dest_reg);
4729   v->always_computable = ! not_every_iteration;
4730   v->always_executed = ! not_every_iteration;
4731   v->maybe_multiple = maybe_multiple;
4732
4733   /* Add this to the reg's iv_class, creating a class
4734      if this is the first incrementation of the reg.  */
4735
4736   bl = reg_biv_class[REGNO (dest_reg)];
4737   if (bl == 0)
4738     {
4739       /* Create and initialize new iv_class.  */
4740
4741       bl = (struct iv_class *) oballoc (sizeof (struct iv_class));
4742
4743       bl->regno = REGNO (dest_reg);
4744       bl->biv = 0;
4745       bl->giv = 0;
4746       bl->biv_count = 0;
4747       bl->giv_count = 0;
4748
4749       /* Set initial value to the reg itself.  */
4750       bl->initial_value = dest_reg;
4751       /* We haven't seen the initializing insn yet */
4752       bl->init_insn = 0;
4753       bl->init_set = 0;
4754       bl->initial_test = 0;
4755       bl->incremented = 0;
4756       bl->eliminable = 0;
4757       bl->nonneg = 0;
4758       bl->reversed = 0;
4759       bl->total_benefit = 0;
4760
4761       /* Add this class to loop_iv_list.  */
4762       bl->next = loop_iv_list;
4763       loop_iv_list = bl;
4764
4765       /* Put it in the array of biv register classes.  */
4766       reg_biv_class[REGNO (dest_reg)] = bl;
4767     }
4768
4769   /* Update IV_CLASS entry for this biv.  */
4770   v->next_iv = bl->biv;
4771   bl->biv = v;
4772   bl->biv_count++;
4773   if (mult_val == const1_rtx)
4774     bl->incremented = 1;
4775
4776   if (loop_dump_stream)
4777     {
4778       fprintf (loop_dump_stream,
4779                "Insn %d: possible biv, reg %d,",
4780                INSN_UID (insn), REGNO (dest_reg));
4781       if (GET_CODE (inc_val) == CONST_INT)
4782         {
4783           fprintf (loop_dump_stream, " const =");
4784           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (inc_val));
4785           fputc ('\n', loop_dump_stream);
4786         }
4787       else
4788         {
4789           fprintf (loop_dump_stream, " const = ");
4790           print_rtl (loop_dump_stream, inc_val);
4791           fprintf (loop_dump_stream, "\n");
4792         }
4793     }
4794 }
4795 \f
4796 /* Fill in the data about one giv.
4797    V is the `struct induction' in which we record the giv.  (It is
4798    allocated by the caller, with alloca.)
4799    INSN is the insn that sets it.
4800    BENEFIT estimates the savings from deleting this insn.
4801    TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
4802    into a register or is used as a memory address.
4803
4804    SRC_REG is the biv reg which the giv is computed from.
4805    DEST_REG is the giv's reg (if the giv is stored in a reg).
4806    MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
4807    LOCATION points to the place where this giv's value appears in INSN.  */
4808
4809 static void
4810 record_giv (v, insn, src_reg, dest_reg, mult_val, add_val, benefit,
4811             type, not_every_iteration, location, loop_start, loop_end)
4812      struct induction *v;
4813      rtx insn;
4814      rtx src_reg;
4815      rtx dest_reg;
4816      rtx mult_val, add_val;
4817      int benefit;
4818      enum g_types type;
4819      int not_every_iteration;
4820      rtx *location;
4821      rtx loop_start, loop_end;
4822 {
4823   struct induction *b;
4824   struct iv_class *bl;
4825   rtx set = single_set (insn);
4826
4827   v->insn = insn;
4828   v->src_reg = src_reg;
4829   v->giv_type = type;
4830   v->dest_reg = dest_reg;
4831   v->mult_val = mult_val;
4832   v->add_val = add_val;
4833   v->benefit = benefit;
4834   v->location = location;
4835   v->cant_derive = 0;
4836   v->combined_with = 0;
4837   v->maybe_multiple = 0;
4838   v->maybe_dead = 0;
4839   v->derive_adjustment = 0;
4840   v->same = 0;
4841   v->ignore = 0;
4842   v->new_reg = 0;
4843   v->final_value = 0;
4844   v->same_insn = 0;
4845   v->auto_inc_opt = 0;
4846   v->unrolled = 0;
4847   v->shared = 0;
4848
4849   /* The v->always_computable field is used in update_giv_derive, to
4850      determine whether a giv can be used to derive another giv.  For a
4851      DEST_REG giv, INSN computes a new value for the giv, so its value
4852      isn't computable if INSN insn't executed every iteration.
4853      However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
4854      it does not compute a new value.  Hence the value is always computable
4855      regardless of whether INSN is executed each iteration.  */
4856
4857   if (type == DEST_ADDR)
4858     v->always_computable = 1;
4859   else
4860     v->always_computable = ! not_every_iteration;
4861
4862   v->always_executed = ! not_every_iteration;
4863
4864   if (type == DEST_ADDR)
4865     {
4866       v->mode = GET_MODE (*location);
4867       v->lifetime = 1;
4868       v->times_used = 1;
4869     }
4870   else /* type == DEST_REG */
4871     {
4872       v->mode = GET_MODE (SET_DEST (set));
4873
4874       v->lifetime = (uid_luid[REGNO_LAST_UID (REGNO (dest_reg))]
4875                      - uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))]);
4876
4877       v->times_used = VARRAY_INT (n_times_used, REGNO (dest_reg));
4878
4879       /* If the lifetime is zero, it means that this register is
4880          really a dead store.  So mark this as a giv that can be
4881          ignored.  This will not prevent the biv from being eliminated.  */
4882       if (v->lifetime == 0)
4883         v->ignore = 1;
4884
4885       reg_iv_type[REGNO (dest_reg)] = GENERAL_INDUCT;
4886       reg_iv_info[REGNO (dest_reg)] = v;
4887     }
4888
4889   /* Add the giv to the class of givs computed from one biv.  */
4890
4891   bl = reg_biv_class[REGNO (src_reg)];
4892   if (bl)
4893     {
4894       v->next_iv = bl->giv;
4895       bl->giv = v;
4896       /* Don't count DEST_ADDR.  This is supposed to count the number of
4897          insns that calculate givs.  */
4898       if (type == DEST_REG)
4899         bl->giv_count++;
4900       bl->total_benefit += benefit;
4901     }
4902   else
4903     /* Fatal error, biv missing for this giv?  */
4904     abort ();
4905
4906   if (type == DEST_ADDR)
4907     v->replaceable = 1;
4908   else
4909     {
4910       /* The giv can be replaced outright by the reduced register only if all
4911          of the following conditions are true:
4912          - the insn that sets the giv is always executed on any iteration
4913            on which the giv is used at all
4914            (there are two ways to deduce this:
4915             either the insn is executed on every iteration,
4916             or all uses follow that insn in the same basic block),
4917          - the giv is not used outside the loop
4918          - no assignments to the biv occur during the giv's lifetime.  */
4919
4920       if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
4921           /* Previous line always fails if INSN was moved by loop opt.  */
4922           && uid_luid[REGNO_LAST_UID (REGNO (dest_reg))] < INSN_LUID (loop_end)
4923           && (! not_every_iteration
4924               || last_use_this_basic_block (dest_reg, insn)))
4925         {
4926           /* Now check that there are no assignments to the biv within the
4927              giv's lifetime.  This requires two separate checks.  */
4928
4929           /* Check each biv update, and fail if any are between the first
4930              and last use of the giv.
4931              
4932              If this loop contains an inner loop that was unrolled, then
4933              the insn modifying the biv may have been emitted by the loop
4934              unrolling code, and hence does not have a valid luid.  Just
4935              mark the biv as not replaceable in this case.  It is not very
4936              useful as a biv, because it is used in two different loops.
4937              It is very unlikely that we would be able to optimize the giv
4938              using this biv anyways.  */
4939
4940           v->replaceable = 1;
4941           for (b = bl->biv; b; b = b->next_iv)
4942             {
4943               if (INSN_UID (b->insn) >= max_uid_for_loop
4944                   || ((uid_luid[INSN_UID (b->insn)]
4945                        >= uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))])
4946                       && (uid_luid[INSN_UID (b->insn)]
4947                           <= uid_luid[REGNO_LAST_UID (REGNO (dest_reg))])))
4948                 {
4949                   v->replaceable = 0;
4950                   v->not_replaceable = 1;
4951                   break;
4952                 }
4953             }
4954
4955           /* If there are any backwards branches that go from after the
4956              biv update to before it, then this giv is not replaceable.  */
4957           if (v->replaceable)
4958             for (b = bl->biv; b; b = b->next_iv)
4959               if (back_branch_in_range_p (b->insn, loop_start, loop_end))
4960                 {
4961                   v->replaceable = 0;
4962                   v->not_replaceable = 1;
4963                   break;
4964                 }
4965         }
4966       else
4967         {
4968           /* May still be replaceable, we don't have enough info here to
4969              decide.  */
4970           v->replaceable = 0;
4971           v->not_replaceable = 0;
4972         }
4973     }
4974
4975   /* Record whether the add_val contains a const_int, for later use by
4976      combine_givs.  */
4977   {
4978     rtx tem = add_val;
4979
4980     v->no_const_addval = 1;
4981     if (tem == const0_rtx)
4982       ;
4983     else if (GET_CODE (tem) == CONST_INT)
4984       v->no_const_addval = 0;
4985     else if (GET_CODE (tem) == PLUS)
4986       {
4987         while (1)
4988           {
4989             if (GET_CODE (XEXP (tem, 0)) == PLUS)
4990               tem = XEXP (tem, 0);
4991             else if (GET_CODE (XEXP (tem, 1)) == PLUS)
4992               tem = XEXP (tem, 1);
4993             else
4994               break;
4995           }
4996         if (GET_CODE (XEXP (tem, 1)) == CONST_INT)
4997           v->no_const_addval = 0;
4998       }
4999   }
5000
5001   if (loop_dump_stream)
5002     {
5003       if (type == DEST_REG)
5004         fprintf (loop_dump_stream, "Insn %d: giv reg %d",
5005                  INSN_UID (insn), REGNO (dest_reg));
5006       else
5007         fprintf (loop_dump_stream, "Insn %d: dest address",
5008                  INSN_UID (insn));
5009
5010       fprintf (loop_dump_stream, " src reg %d benefit %d",
5011                REGNO (src_reg), v->benefit);
5012       fprintf (loop_dump_stream, " used %d lifetime %d",
5013                v->times_used, v->lifetime);
5014
5015       if (v->replaceable)
5016         fprintf (loop_dump_stream, " replaceable");
5017
5018       if (v->no_const_addval)
5019         fprintf (loop_dump_stream, " ncav");
5020
5021       if (GET_CODE (mult_val) == CONST_INT)
5022         {
5023           fprintf (loop_dump_stream, " mult ");
5024           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (mult_val));
5025         }
5026       else
5027         {
5028           fprintf (loop_dump_stream, " mult ");
5029           print_rtl (loop_dump_stream, mult_val);
5030         }
5031
5032       if (GET_CODE (add_val) == CONST_INT)
5033         {
5034           fprintf (loop_dump_stream, " add ");
5035           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (add_val));
5036         }
5037       else
5038         {
5039           fprintf (loop_dump_stream, " add ");
5040           print_rtl (loop_dump_stream, add_val);
5041         }
5042     }
5043
5044   if (loop_dump_stream)
5045     fprintf (loop_dump_stream, "\n");
5046
5047 }
5048
5049
5050 /* All this does is determine whether a giv can be made replaceable because
5051    its final value can be calculated.  This code can not be part of record_giv
5052    above, because final_giv_value requires that the number of loop iterations
5053    be known, and that can not be accurately calculated until after all givs
5054    have been identified.  */
5055
5056 static void
5057 check_final_value (v, loop_start, loop_end)
5058      struct induction *v;
5059      rtx loop_start, loop_end;
5060 {
5061   struct iv_class *bl;
5062   rtx final_value = 0;
5063
5064   bl = reg_biv_class[REGNO (v->src_reg)];
5065
5066   /* DEST_ADDR givs will never reach here, because they are always marked
5067      replaceable above in record_giv.  */
5068
5069   /* The giv can be replaced outright by the reduced register only if all
5070      of the following conditions are true:
5071      - the insn that sets the giv is always executed on any iteration
5072        on which the giv is used at all
5073        (there are two ways to deduce this:
5074         either the insn is executed on every iteration,
5075         or all uses follow that insn in the same basic block),
5076      - its final value can be calculated (this condition is different
5077        than the one above in record_giv)
5078      - no assignments to the biv occur during the giv's lifetime.  */
5079
5080 #if 0
5081   /* This is only called now when replaceable is known to be false.  */
5082   /* Clear replaceable, so that it won't confuse final_giv_value.  */
5083   v->replaceable = 0;
5084 #endif
5085
5086   if ((final_value = final_giv_value (v, loop_start, loop_end))
5087       && (v->always_computable || last_use_this_basic_block (v->dest_reg, v->insn)))
5088     {
5089       int biv_increment_seen = 0;
5090       rtx p = v->insn;
5091       rtx last_giv_use;
5092
5093       v->replaceable = 1;
5094
5095       /* When trying to determine whether or not a biv increment occurs
5096          during the lifetime of the giv, we can ignore uses of the variable
5097          outside the loop because final_value is true.  Hence we can not
5098          use regno_last_uid and regno_first_uid as above in record_giv.  */
5099
5100       /* Search the loop to determine whether any assignments to the
5101          biv occur during the giv's lifetime.  Start with the insn
5102          that sets the giv, and search around the loop until we come
5103          back to that insn again.
5104
5105          Also fail if there is a jump within the giv's lifetime that jumps
5106          to somewhere outside the lifetime but still within the loop.  This
5107          catches spaghetti code where the execution order is not linear, and
5108          hence the above test fails.  Here we assume that the giv lifetime
5109          does not extend from one iteration of the loop to the next, so as
5110          to make the test easier.  Since the lifetime isn't known yet,
5111          this requires two loops.  See also record_giv above.  */
5112
5113       last_giv_use = v->insn;
5114
5115       while (1)
5116         {
5117           p = NEXT_INSN (p);
5118           if (p == loop_end)
5119             p = NEXT_INSN (loop_start);
5120           if (p == v->insn)
5121             break;
5122
5123           if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5124               || GET_CODE (p) == CALL_INSN)
5125             {
5126               if (biv_increment_seen)
5127                 {
5128                   if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5129                     {
5130                       v->replaceable = 0;
5131                       v->not_replaceable = 1;
5132                       break;
5133                     }
5134                 }
5135               else if (reg_set_p (v->src_reg, PATTERN (p)))
5136                 biv_increment_seen = 1;
5137               else if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5138                 last_giv_use = p;
5139             }
5140         }
5141       
5142       /* Now that the lifetime of the giv is known, check for branches
5143          from within the lifetime to outside the lifetime if it is still
5144          replaceable.  */
5145
5146       if (v->replaceable)
5147         {
5148           p = v->insn;
5149           while (1)
5150             {
5151               p = NEXT_INSN (p);
5152               if (p == loop_end)
5153                 p = NEXT_INSN (loop_start);
5154               if (p == last_giv_use)
5155                 break;
5156
5157               if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
5158                   && LABEL_NAME (JUMP_LABEL (p))
5159                   && ((INSN_UID (JUMP_LABEL (p)) >= max_uid_for_loop)
5160                       || (INSN_UID (v->insn) >= max_uid_for_loop)
5161                       || (INSN_UID (last_giv_use) >= max_uid_for_loop)
5162                       || (INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (v->insn)
5163                           && INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop_start))
5164                       || (INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (last_giv_use)
5165                           && INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop_end))))
5166                 {
5167                   v->replaceable = 0;
5168                   v->not_replaceable = 1;
5169
5170                   if (loop_dump_stream)
5171                     fprintf (loop_dump_stream,
5172                              "Found branch outside giv lifetime.\n");
5173
5174                   break;
5175                 }
5176             }
5177         }
5178
5179       /* If it is replaceable, then save the final value.  */
5180       if (v->replaceable)
5181         v->final_value = final_value;
5182     }
5183
5184   if (loop_dump_stream && v->replaceable)
5185     fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
5186              INSN_UID (v->insn), REGNO (v->dest_reg));
5187 }
5188 \f
5189 /* Update the status of whether a giv can derive other givs.
5190
5191    We need to do something special if there is or may be an update to the biv
5192    between the time the giv is defined and the time it is used to derive
5193    another giv.
5194
5195    In addition, a giv that is only conditionally set is not allowed to
5196    derive another giv once a label has been passed.
5197
5198    The cases we look at are when a label or an update to a biv is passed.  */
5199
5200 static void
5201 update_giv_derive (p)
5202      rtx p;
5203 {
5204   struct iv_class *bl;
5205   struct induction *biv, *giv;
5206   rtx tem;
5207   int dummy;
5208
5209   /* Search all IV classes, then all bivs, and finally all givs.
5210
5211      There are three cases we are concerned with.  First we have the situation
5212      of a giv that is only updated conditionally.  In that case, it may not
5213      derive any givs after a label is passed.
5214
5215      The second case is when a biv update occurs, or may occur, after the
5216      definition of a giv.  For certain biv updates (see below) that are
5217      known to occur between the giv definition and use, we can adjust the
5218      giv definition.  For others, or when the biv update is conditional,
5219      we must prevent the giv from deriving any other givs.  There are two
5220      sub-cases within this case.
5221
5222      If this is a label, we are concerned with any biv update that is done
5223      conditionally, since it may be done after the giv is defined followed by
5224      a branch here (actually, we need to pass both a jump and a label, but
5225      this extra tracking doesn't seem worth it).
5226
5227      If this is a jump, we are concerned about any biv update that may be
5228      executed multiple times.  We are actually only concerned about
5229      backward jumps, but it is probably not worth performing the test
5230      on the jump again here.
5231
5232      If this is a biv update, we must adjust the giv status to show that a
5233      subsequent biv update was performed.  If this adjustment cannot be done,
5234      the giv cannot derive further givs.  */
5235
5236   for (bl = loop_iv_list; bl; bl = bl->next)
5237     for (biv = bl->biv; biv; biv = biv->next_iv)
5238       if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
5239           || biv->insn == p)
5240         {
5241           for (giv = bl->giv; giv; giv = giv->next_iv)
5242             {
5243               /* If cant_derive is already true, there is no point in
5244                  checking all of these conditions again.  */
5245               if (giv->cant_derive)
5246                 continue;
5247
5248               /* If this giv is conditionally set and we have passed a label,
5249                  it cannot derive anything.  */
5250               if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
5251                 giv->cant_derive = 1;
5252
5253               /* Skip givs that have mult_val == 0, since
5254                  they are really invariants.  Also skip those that are
5255                  replaceable, since we know their lifetime doesn't contain
5256                  any biv update.  */
5257               else if (giv->mult_val == const0_rtx || giv->replaceable)
5258                 continue;
5259
5260               /* The only way we can allow this giv to derive another
5261                  is if this is a biv increment and we can form the product
5262                  of biv->add_val and giv->mult_val.  In this case, we will
5263                  be able to compute a compensation.  */
5264               else if (biv->insn == p)
5265                 {
5266                   tem = 0;
5267
5268                   if (biv->mult_val == const1_rtx)
5269                     tem = simplify_giv_expr (gen_rtx_MULT (giv->mode,
5270                                                            biv->add_val,
5271                                                            giv->mult_val),
5272                                              &dummy);
5273
5274                   if (tem && giv->derive_adjustment)
5275                     tem = simplify_giv_expr (gen_rtx_PLUS (giv->mode, tem,
5276                                                            giv->derive_adjustment),
5277                                              &dummy);
5278                   if (tem)
5279                     giv->derive_adjustment = tem;
5280                   else
5281                     giv->cant_derive = 1;
5282                 }
5283               else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
5284                        || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
5285                 giv->cant_derive = 1;
5286             }
5287         }
5288 }
5289 \f
5290 /* Check whether an insn is an increment legitimate for a basic induction var.
5291    X is the source of insn P, or a part of it.
5292    MODE is the mode in which X should be interpreted.
5293
5294    DEST_REG is the putative biv, also the destination of the insn.
5295    We accept patterns of these forms:
5296      REG = REG + INVARIANT (includes REG = REG - CONSTANT)
5297      REG = INVARIANT + REG
5298
5299    If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
5300    and store the additive term into *INC_VAL.
5301
5302    If X is an assignment of an invariant into DEST_REG, we set
5303    *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
5304
5305    We also want to detect a BIV when it corresponds to a variable
5306    whose mode was promoted via PROMOTED_MODE.  In that case, an increment
5307    of the variable may be a PLUS that adds a SUBREG of that variable to
5308    an invariant and then sign- or zero-extends the result of the PLUS
5309    into the variable.
5310
5311    Most GIVs in such cases will be in the promoted mode, since that is the
5312    probably the natural computation mode (and almost certainly the mode
5313    used for addresses) on the machine.  So we view the pseudo-reg containing
5314    the variable as the BIV, as if it were simply incremented.
5315
5316    Note that treating the entire pseudo as a BIV will result in making
5317    simple increments to any GIVs based on it.  However, if the variable
5318    overflows in its declared mode but not its promoted mode, the result will
5319    be incorrect.  This is acceptable if the variable is signed, since 
5320    overflows in such cases are undefined, but not if it is unsigned, since
5321    those overflows are defined.  So we only check for SIGN_EXTEND and
5322    not ZERO_EXTEND.
5323
5324    If we cannot find a biv, we return 0.  */
5325
5326 static int
5327 basic_induction_var (x, mode, dest_reg, p, inc_val, mult_val)
5328      register rtx x;
5329      enum machine_mode mode;
5330      rtx p;
5331      rtx dest_reg;
5332      rtx *inc_val;
5333      rtx *mult_val;
5334 {
5335   register enum rtx_code code;
5336   rtx arg;
5337   rtx insn, set = 0;
5338
5339   code = GET_CODE (x);
5340   switch (code)
5341     {
5342     case PLUS:
5343       if (rtx_equal_p (XEXP (x, 0), dest_reg)
5344           || (GET_CODE (XEXP (x, 0)) == SUBREG
5345               && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
5346               && SUBREG_REG (XEXP (x, 0)) == dest_reg))
5347         arg = XEXP (x, 1);
5348       else if (rtx_equal_p (XEXP (x, 1), dest_reg)
5349                || (GET_CODE (XEXP (x, 1)) == SUBREG
5350                    && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
5351                    && SUBREG_REG (XEXP (x, 1)) == dest_reg))
5352         arg = XEXP (x, 0);
5353       else
5354         return 0;
5355
5356       if (invariant_p (arg) != 1)
5357         return 0;
5358
5359       *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
5360       *mult_val = const1_rtx;
5361       return 1;
5362
5363     case SUBREG:
5364       /* If this is a SUBREG for a promoted variable, check the inner
5365          value.  */
5366       if (SUBREG_PROMOTED_VAR_P (x))
5367         return basic_induction_var (SUBREG_REG (x), GET_MODE (SUBREG_REG (x)),
5368                                     dest_reg, p, inc_val, mult_val);
5369       return 0;
5370
5371     case REG:
5372       /* If this register is assigned in a previous insn, look at its
5373          source, but don't go outside the loop or past a label.  */
5374
5375       insn = p;
5376       while (1)
5377         {
5378           do {
5379             insn = PREV_INSN (insn);
5380           } while (insn && GET_CODE (insn) == NOTE
5381                    && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
5382
5383           if (!insn)
5384             break;
5385           set = single_set (insn);
5386           if (set == 0)
5387             break;
5388
5389           if ((SET_DEST (set) == x
5390                || (GET_CODE (SET_DEST (set)) == SUBREG
5391                    && (GET_MODE_SIZE (GET_MODE (SET_DEST (set)))
5392                        <= UNITS_PER_WORD)
5393                    && SUBREG_REG (SET_DEST (set)) == x))
5394               && basic_induction_var (SET_SRC (set),
5395                                       (GET_MODE (SET_SRC (set)) == VOIDmode
5396                                        ? GET_MODE (x)
5397                                        : GET_MODE (SET_SRC (set))),
5398                                       dest_reg, insn,
5399                                       inc_val, mult_val))
5400             return 1;
5401         }
5402       /* ... fall through ...  */
5403
5404       /* Can accept constant setting of biv only when inside inner most loop.
5405          Otherwise, a biv of an inner loop may be incorrectly recognized
5406          as a biv of the outer loop,
5407          causing code to be moved INTO the inner loop.  */
5408     case MEM:
5409       if (invariant_p (x) != 1)
5410         return 0;
5411     case CONST_INT:
5412     case SYMBOL_REF:
5413     case CONST:
5414       /* convert_modes aborts if we try to convert to or from CCmode, so just
5415          exclude that case.  It is very unlikely that a condition code value
5416          would be a useful iterator anyways.  */
5417       if (loops_enclosed == 1
5418           && GET_MODE_CLASS (mode) != MODE_CC
5419           && GET_MODE_CLASS (GET_MODE (dest_reg)) != MODE_CC)
5420         {
5421           /* Possible bug here?  Perhaps we don't know the mode of X.  */
5422           *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
5423           *mult_val = const0_rtx;
5424           return 1;
5425         }
5426       else
5427         return 0;
5428
5429     case SIGN_EXTEND:
5430       return basic_induction_var (XEXP (x, 0), GET_MODE (XEXP (x, 0)),
5431                                   dest_reg, p, inc_val, mult_val);
5432
5433     case ASHIFTRT:
5434       /* Similar, since this can be a sign extension.  */
5435       for (insn = PREV_INSN (p);
5436            (insn && GET_CODE (insn) == NOTE
5437             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
5438            insn = PREV_INSN (insn))
5439         ;
5440
5441       if (insn)
5442         set = single_set (insn);
5443
5444       if (set && SET_DEST (set) == XEXP (x, 0)
5445           && GET_CODE (XEXP (x, 1)) == CONST_INT
5446           && INTVAL (XEXP (x, 1)) >= 0
5447           && GET_CODE (SET_SRC (set)) == ASHIFT
5448           && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
5449         return basic_induction_var (XEXP (SET_SRC (set), 0),
5450                                     GET_MODE (XEXP (x, 0)),
5451                                     dest_reg, insn, inc_val, mult_val);
5452       return 0;
5453
5454     default:
5455       return 0;
5456     }
5457 }
5458 \f
5459 /* A general induction variable (giv) is any quantity that is a linear
5460    function   of a basic induction variable,
5461    i.e. giv = biv * mult_val + add_val.
5462    The coefficients can be any loop invariant quantity.
5463    A giv need not be computed directly from the biv;
5464    it can be computed by way of other givs.  */
5465
5466 /* Determine whether X computes a giv.
5467    If it does, return a nonzero value
5468      which is the benefit from eliminating the computation of X;
5469    set *SRC_REG to the register of the biv that it is computed from;
5470    set *ADD_VAL and *MULT_VAL to the coefficients,
5471      such that the value of X is biv * mult + add;  */
5472
5473 static int
5474 general_induction_var (x, src_reg, add_val, mult_val, is_addr, pbenefit)
5475      rtx x;
5476      rtx *src_reg;
5477      rtx *add_val;
5478      rtx *mult_val;
5479      int is_addr;
5480      int *pbenefit;
5481 {
5482   rtx orig_x = x;
5483   char *storage;
5484
5485   /* If this is an invariant, forget it, it isn't a giv.  */
5486   if (invariant_p (x) == 1)
5487     return 0;
5488
5489   /* See if the expression could be a giv and get its form.
5490      Mark our place on the obstack in case we don't find a giv.  */
5491   storage = (char *) oballoc (0);
5492   *pbenefit = 0;
5493   x = simplify_giv_expr (x, pbenefit);
5494   if (x == 0)
5495     {
5496       obfree (storage);
5497       return 0;
5498     }
5499
5500   switch (GET_CODE (x))
5501     {
5502     case USE:
5503     case CONST_INT:
5504       /* Since this is now an invariant and wasn't before, it must be a giv
5505          with MULT_VAL == 0.  It doesn't matter which BIV we associate this
5506          with.  */
5507       *src_reg = loop_iv_list->biv->dest_reg;
5508       *mult_val = const0_rtx;
5509       *add_val = x;
5510       break;
5511
5512     case REG:
5513       /* This is equivalent to a BIV.  */
5514       *src_reg = x;
5515       *mult_val = const1_rtx;
5516       *add_val = const0_rtx;
5517       break;
5518
5519     case PLUS:
5520       /* Either (plus (biv) (invar)) or
5521          (plus (mult (biv) (invar_1)) (invar_2)).  */
5522       if (GET_CODE (XEXP (x, 0)) == MULT)
5523         {
5524           *src_reg = XEXP (XEXP (x, 0), 0);
5525           *mult_val = XEXP (XEXP (x, 0), 1);
5526         }
5527       else
5528         {
5529           *src_reg = XEXP (x, 0);
5530           *mult_val = const1_rtx;
5531         }
5532       *add_val = XEXP (x, 1);
5533       break;
5534
5535     case MULT:
5536       /* ADD_VAL is zero.  */
5537       *src_reg = XEXP (x, 0);
5538       *mult_val = XEXP (x, 1);
5539       *add_val = const0_rtx;
5540       break;
5541
5542     default:
5543       abort ();
5544     }
5545
5546   /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
5547      unless they are CONST_INT).  */
5548   if (GET_CODE (*add_val) == USE)
5549     *add_val = XEXP (*add_val, 0);
5550   if (GET_CODE (*mult_val) == USE)
5551     *mult_val = XEXP (*mult_val, 0);
5552
5553   if (is_addr)
5554     {
5555 #ifdef ADDRESS_COST
5556       *pbenefit += ADDRESS_COST (orig_x) - reg_address_cost;
5557 #else
5558       *pbenefit += rtx_cost (orig_x, MEM) - reg_address_cost;
5559 #endif
5560     }
5561   else
5562     *pbenefit += rtx_cost (orig_x, SET);
5563
5564   /* Always return true if this is a giv so it will be detected as such,
5565      even if the benefit is zero or negative.  This allows elimination  
5566      of bivs that might otherwise not be eliminated.  */                
5567   return 1;                                                             
5568 }
5569 \f
5570 /* Given an expression, X, try to form it as a linear function of a biv.
5571    We will canonicalize it to be of the form
5572         (plus (mult (BIV) (invar_1))
5573               (invar_2))
5574    with possible degeneracies.
5575
5576    The invariant expressions must each be of a form that can be used as a
5577    machine operand.  We surround then with a USE rtx (a hack, but localized
5578    and certainly unambiguous!) if not a CONST_INT for simplicity in this
5579    routine; it is the caller's responsibility to strip them.
5580
5581    If no such canonicalization is possible (i.e., two biv's are used or an
5582    expression that is neither invariant nor a biv or giv), this routine
5583    returns 0.
5584
5585    For a non-zero return, the result will have a code of CONST_INT, USE,
5586    REG (for a BIV), PLUS, or MULT.  No other codes will occur.  
5587
5588    *BENEFIT will be incremented by the benefit of any sub-giv encountered.  */
5589
5590 static rtx sge_plus PROTO ((enum machine_mode, rtx, rtx));
5591 static rtx sge_plus_constant PROTO ((rtx, rtx));
5592
5593 static rtx
5594 simplify_giv_expr (x, benefit)
5595      rtx x;
5596      int *benefit;
5597 {
5598   enum machine_mode mode = GET_MODE (x);
5599   rtx arg0, arg1;
5600   rtx tem;
5601
5602   /* If this is not an integer mode, or if we cannot do arithmetic in this
5603      mode, this can't be a giv.  */
5604   if (mode != VOIDmode
5605       && (GET_MODE_CLASS (mode) != MODE_INT
5606           || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
5607     return NULL_RTX;
5608
5609   switch (GET_CODE (x))
5610     {
5611     case PLUS:
5612       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
5613       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
5614       if (arg0 == 0 || arg1 == 0)
5615         return NULL_RTX;
5616
5617       /* Put constant last, CONST_INT last if both constant.  */
5618       if ((GET_CODE (arg0) == USE
5619            || GET_CODE (arg0) == CONST_INT)
5620           && ! ((GET_CODE (arg0) == USE
5621                  && GET_CODE (arg1) == USE)
5622                 || GET_CODE (arg1) == CONST_INT))
5623         tem = arg0, arg0 = arg1, arg1 = tem;
5624
5625       /* Handle addition of zero, then addition of an invariant.  */
5626       if (arg1 == const0_rtx)
5627         return arg0;
5628       else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
5629         switch (GET_CODE (arg0))
5630           {
5631           case CONST_INT:
5632           case USE:
5633             /* Adding two invariants must result in an invariant, so enclose
5634                addition operation inside a USE and return it.  */
5635             if (GET_CODE (arg0) == USE)
5636               arg0 = XEXP (arg0, 0);
5637             if (GET_CODE (arg1) == USE)
5638               arg1 = XEXP (arg1, 0);
5639
5640             if (GET_CODE (arg0) == CONST_INT)
5641               tem = arg0, arg0 = arg1, arg1 = tem;
5642             if (GET_CODE (arg1) == CONST_INT)
5643               tem = sge_plus_constant (arg0, arg1);
5644             else
5645               tem = sge_plus (mode, arg0, arg1);
5646
5647             if (GET_CODE (tem) != CONST_INT)
5648               tem = gen_rtx_USE (mode, tem);
5649             return tem;
5650
5651           case REG:
5652           case MULT:
5653             /* biv + invar or mult + invar.  Return sum.  */
5654             return gen_rtx_PLUS (mode, arg0, arg1);
5655
5656           case PLUS:
5657             /* (a + invar_1) + invar_2.  Associate.  */
5658             return simplify_giv_expr (
5659                 gen_rtx_PLUS (mode, XEXP (arg0, 0),
5660                               gen_rtx_PLUS (mode, XEXP (arg0, 1), arg1)),
5661                 benefit);
5662
5663           default:
5664             abort ();
5665           }
5666
5667       /* Each argument must be either REG, PLUS, or MULT.  Convert REG to
5668          MULT to reduce cases.  */
5669       if (GET_CODE (arg0) == REG)
5670         arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
5671       if (GET_CODE (arg1) == REG)
5672         arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
5673
5674       /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
5675          Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
5676          Recurse to associate the second PLUS.  */
5677       if (GET_CODE (arg1) == MULT)
5678         tem = arg0, arg0 = arg1, arg1 = tem;
5679
5680       if (GET_CODE (arg1) == PLUS)
5681           return simplify_giv_expr (gen_rtx_PLUS (mode,
5682                                                   gen_rtx_PLUS (mode, arg0,
5683                                                                 XEXP (arg1, 0)),
5684                                                   XEXP (arg1, 1)),
5685                                     benefit);
5686
5687       /* Now must have MULT + MULT.  Distribute if same biv, else not giv.  */
5688       if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
5689         return NULL_RTX;
5690
5691       if (!rtx_equal_p (arg0, arg1))
5692         return NULL_RTX;
5693
5694       return simplify_giv_expr (gen_rtx_MULT (mode,
5695                                               XEXP (arg0, 0),
5696                                               gen_rtx_PLUS (mode,
5697                                                             XEXP (arg0, 1),
5698                                                             XEXP (arg1, 1))),
5699                                 benefit);
5700
5701     case MINUS:
5702       /* Handle "a - b" as "a + b * (-1)".  */
5703       return simplify_giv_expr (gen_rtx_PLUS (mode,
5704                                               XEXP (x, 0),
5705                                               gen_rtx_MULT (mode, XEXP (x, 1),
5706                                                             constm1_rtx)),
5707                                 benefit);
5708
5709     case MULT:
5710       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
5711       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
5712       if (arg0 == 0 || arg1 == 0)
5713         return NULL_RTX;
5714
5715       /* Put constant last, CONST_INT last if both constant.  */
5716       if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
5717           && GET_CODE (arg1) != CONST_INT)
5718         tem = arg0, arg0 = arg1, arg1 = tem;
5719
5720       /* If second argument is not now constant, not giv.  */
5721       if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
5722         return NULL_RTX;
5723
5724       /* Handle multiply by 0 or 1.  */
5725       if (arg1 == const0_rtx)
5726         return const0_rtx;
5727
5728       else if (arg1 == const1_rtx)
5729         return arg0;
5730
5731       switch (GET_CODE (arg0))
5732         {
5733         case REG:
5734           /* biv * invar.  Done.  */
5735           return gen_rtx_MULT (mode, arg0, arg1);
5736
5737         case CONST_INT:
5738           /* Product of two constants.  */
5739           return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
5740
5741         case USE:
5742           /* invar * invar.  It is a giv, but very few of these will 
5743              actually pay off, so limit to simple registers.  */
5744           if (GET_CODE (arg1) != CONST_INT)
5745             return NULL_RTX;
5746
5747           arg0 = XEXP (arg0, 0);
5748           if (GET_CODE (arg0) == REG)
5749             tem = gen_rtx_MULT (mode, arg0, arg1);
5750           else if (GET_CODE (arg0) == MULT
5751                    && GET_CODE (XEXP (arg0, 0)) == REG
5752                    && GET_CODE (XEXP (arg0, 1)) == CONST_INT)
5753             {
5754               tem = gen_rtx_MULT (mode, XEXP (arg0, 0), 
5755                                   GEN_INT (INTVAL (XEXP (arg0, 1))
5756                                            * INTVAL (arg1)));
5757             }
5758           else
5759             return NULL_RTX;
5760           return gen_rtx_USE (mode, tem);
5761
5762         case MULT:
5763           /* (a * invar_1) * invar_2.  Associate.  */
5764           return simplify_giv_expr (gen_rtx_MULT (mode, XEXP (arg0, 0),
5765                                                   gen_rtx_MULT (mode,
5766                                                                 XEXP (arg0, 1),
5767                                                                 arg1)),
5768                                     benefit);
5769
5770         case PLUS:
5771           /* (a + invar_1) * invar_2.  Distribute.  */
5772           return simplify_giv_expr (gen_rtx_PLUS (mode,
5773                                                   gen_rtx_MULT (mode,
5774                                                                 XEXP (arg0, 0),
5775                                                                 arg1),
5776                                                   gen_rtx_MULT (mode,
5777                                                                 XEXP (arg0, 1),
5778                                                                 arg1)),
5779                                     benefit);
5780
5781         default:
5782           abort ();
5783         }
5784
5785     case ASHIFT:
5786       /* Shift by constant is multiply by power of two.  */
5787       if (GET_CODE (XEXP (x, 1)) != CONST_INT)
5788         return 0;
5789
5790       return simplify_giv_expr (gen_rtx_MULT (mode,
5791                                               XEXP (x, 0),
5792                                               GEN_INT ((HOST_WIDE_INT) 1
5793                                                        << INTVAL (XEXP (x, 1)))),
5794                                 benefit);
5795
5796     case NEG:
5797       /* "-a" is "a * (-1)" */
5798       return simplify_giv_expr (gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
5799                                 benefit);
5800
5801     case NOT:
5802       /* "~a" is "-a - 1". Silly, but easy.  */
5803       return simplify_giv_expr (gen_rtx_MINUS (mode,
5804                                                gen_rtx_NEG (mode, XEXP (x, 0)),
5805                                                const1_rtx),
5806                                 benefit);
5807
5808     case USE:
5809       /* Already in proper form for invariant.  */
5810       return x;
5811
5812     case REG:
5813       /* If this is a new register, we can't deal with it.  */
5814       if (REGNO (x) >= max_reg_before_loop)
5815         return 0;
5816
5817       /* Check for biv or giv.  */
5818       switch (reg_iv_type[REGNO (x)])
5819         {
5820         case BASIC_INDUCT:
5821           return x;
5822         case GENERAL_INDUCT:
5823           {
5824             struct induction *v = reg_iv_info[REGNO (x)];
5825
5826             /* Form expression from giv and add benefit.  Ensure this giv
5827                can derive another and subtract any needed adjustment if so.  */
5828             *benefit += v->benefit;
5829             if (v->cant_derive)
5830               return 0;
5831
5832             tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode, v->src_reg,
5833                                                     v->mult_val),
5834                            v->add_val);
5835             if (v->derive_adjustment)
5836               tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
5837             return simplify_giv_expr (tem, benefit);
5838           }
5839
5840         default:
5841           /* If it isn't an induction variable, and it is invariant, we
5842              may be able to simplify things further by looking through
5843              the bits we just moved outside the loop.  */
5844           if (invariant_p (x) == 1)
5845             {
5846               struct movable *m;
5847
5848               for (m = the_movables; m ; m = m->next)
5849                 if (rtx_equal_p (x, m->set_dest))
5850                   {
5851                     /* Ok, we found a match.  Substitute and simplify.  */
5852
5853                     /* If we match another movable, we must use that, as 
5854                        this one is going away.  */
5855                     if (m->match)
5856                       return simplify_giv_expr (m->match->set_dest, benefit);
5857
5858                     /* If consec is non-zero, this is a member of a group of
5859                        instructions that were moved together.  We handle this
5860                        case only to the point of seeking to the last insn and
5861                        looking for a REG_EQUAL.  Fail if we don't find one.  */
5862                     if (m->consec != 0)
5863                       {
5864                         int i = m->consec;
5865                         tem = m->insn;
5866                         do { tem = NEXT_INSN (tem); } while (--i > 0);
5867
5868                         tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
5869                         if (tem)
5870                           tem = XEXP (tem, 0);
5871                       }
5872                     else
5873                       {
5874                         tem = single_set (m->insn);
5875                         if (tem)
5876                           tem = SET_SRC (tem);
5877                       }
5878
5879                     if (tem)
5880                       {
5881                         /* What we are most interested in is pointer
5882                            arithmetic on invariants -- only take
5883                            patterns we may be able to do something with.  */
5884                         if (GET_CODE (tem) == PLUS
5885                             || GET_CODE (tem) == MULT
5886                             || GET_CODE (tem) == ASHIFT
5887                             || GET_CODE (tem) == CONST_INT
5888                             || GET_CODE (tem) == SYMBOL_REF)
5889                           {
5890                             tem = simplify_giv_expr (tem, benefit);
5891                             if (tem)
5892                               return tem;
5893                           }
5894                         else if (GET_CODE (tem) == CONST
5895                             && GET_CODE (XEXP (tem, 0)) == PLUS
5896                             && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
5897                             && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
5898                           {
5899                             tem = simplify_giv_expr (XEXP (tem, 0), benefit);
5900                             if (tem)
5901                               return tem;
5902                           }
5903                       }
5904                     break;
5905                   }
5906             }
5907           break;
5908         }
5909
5910       /* Fall through to general case.  */
5911     default:
5912       /* If invariant, return as USE (unless CONST_INT).
5913          Otherwise, not giv.  */
5914       if (GET_CODE (x) == USE)
5915         x = XEXP (x, 0);
5916
5917       if (invariant_p (x) == 1)
5918         {
5919           if (GET_CODE (x) == CONST_INT)
5920             return x;
5921           if (GET_CODE (x) == CONST
5922               && GET_CODE (XEXP (x, 0)) == PLUS
5923               && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
5924               && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
5925             x = XEXP (x, 0);
5926           return gen_rtx_USE (mode, x);
5927         }
5928       else
5929         return 0;
5930     }
5931 }
5932
5933 /* This routine folds invariants such that there is only ever one
5934    CONST_INT in the summation.  It is only used by simplify_giv_expr.  */
5935
5936 static rtx
5937 sge_plus_constant (x, c)
5938      rtx x, c;
5939 {
5940   if (GET_CODE (x) == CONST_INT)
5941     return GEN_INT (INTVAL (x) + INTVAL (c));
5942   else if (GET_CODE (x) != PLUS)
5943     return gen_rtx_PLUS (GET_MODE (x), x, c);
5944   else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
5945     {
5946       return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
5947                            GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
5948     }
5949   else if (GET_CODE (XEXP (x, 0)) == PLUS
5950            || GET_CODE (XEXP (x, 1)) != PLUS)
5951     {
5952       return gen_rtx_PLUS (GET_MODE (x),
5953                            sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
5954     }
5955   else
5956     {
5957       return gen_rtx_PLUS (GET_MODE (x),
5958                            sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
5959     }
5960 }
5961
5962 static rtx
5963 sge_plus (mode, x, y)
5964      enum machine_mode mode;
5965      rtx x, y;
5966 {
5967   while (GET_CODE (y) == PLUS)
5968     {
5969       rtx a = XEXP (y, 0);
5970       if (GET_CODE (a) == CONST_INT)
5971         x = sge_plus_constant (x, a);
5972       else
5973         x = gen_rtx_PLUS (mode, x, a);
5974       y = XEXP (y, 1);
5975     }
5976   if (GET_CODE (y) == CONST_INT)
5977     x = sge_plus_constant (x, y);
5978   else
5979     x = gen_rtx_PLUS (mode, x, y);
5980   return x;
5981 }
5982 \f
5983 /* Help detect a giv that is calculated by several consecutive insns;
5984    for example,
5985       giv = biv * M
5986       giv = giv + A
5987    The caller has already identified the first insn P as having a giv as dest;
5988    we check that all other insns that set the same register follow
5989    immediately after P, that they alter nothing else,
5990    and that the result of the last is still a giv.
5991
5992    The value is 0 if the reg set in P is not really a giv.
5993    Otherwise, the value is the amount gained by eliminating
5994    all the consecutive insns that compute the value.
5995
5996    FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
5997    SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
5998
5999    The coefficients of the ultimate giv value are stored in
6000    *MULT_VAL and *ADD_VAL.  */
6001
6002 static int
6003 consec_sets_giv (first_benefit, p, src_reg, dest_reg,
6004                  add_val, mult_val)
6005      int first_benefit;
6006      rtx p;
6007      rtx src_reg;
6008      rtx dest_reg;
6009      rtx *add_val;
6010      rtx *mult_val;
6011 {
6012   int count;
6013   enum rtx_code code;
6014   int benefit;
6015   rtx temp;
6016   rtx set;
6017
6018   /* Indicate that this is a giv so that we can update the value produced in
6019      each insn of the multi-insn sequence. 
6020
6021      This induction structure will be used only by the call to
6022      general_induction_var below, so we can allocate it on our stack.
6023      If this is a giv, our caller will replace the induct var entry with
6024      a new induction structure.  */
6025   struct induction *v
6026     = (struct induction *) alloca (sizeof (struct induction));
6027   v->src_reg = src_reg;
6028   v->mult_val = *mult_val;
6029   v->add_val = *add_val;
6030   v->benefit = first_benefit;
6031   v->cant_derive = 0;
6032   v->derive_adjustment = 0;
6033
6034   reg_iv_type[REGNO (dest_reg)] = GENERAL_INDUCT;
6035   reg_iv_info[REGNO (dest_reg)] = v;
6036
6037   count = VARRAY_INT (n_times_set, REGNO (dest_reg)) - 1;
6038
6039   while (count > 0)
6040     {
6041       p = NEXT_INSN (p);
6042       code = GET_CODE (p);
6043
6044       /* If libcall, skip to end of call sequence.  */
6045       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
6046         p = XEXP (temp, 0);
6047
6048       if (code == INSN
6049           && (set = single_set (p))
6050           && GET_CODE (SET_DEST (set)) == REG
6051           && SET_DEST (set) == dest_reg
6052           && (general_induction_var (SET_SRC (set), &src_reg,
6053                                      add_val, mult_val, 0, &benefit)
6054               /* Giv created by equivalent expression.  */
6055               || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
6056                   && general_induction_var (XEXP (temp, 0), &src_reg,
6057                                             add_val, mult_val, 0, &benefit)))
6058           && src_reg == v->src_reg)
6059         {
6060           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
6061             benefit += libcall_benefit (p);
6062
6063           count--;
6064           v->mult_val = *mult_val;
6065           v->add_val = *add_val;
6066           v->benefit = benefit;
6067         }
6068       else if (code != NOTE)
6069         {
6070           /* Allow insns that set something other than this giv to a
6071              constant.  Such insns are needed on machines which cannot
6072              include long constants and should not disqualify a giv.  */
6073           if (code == INSN
6074               && (set = single_set (p))
6075               && SET_DEST (set) != dest_reg
6076               && CONSTANT_P (SET_SRC (set)))
6077             continue;
6078
6079           reg_iv_type[REGNO (dest_reg)] = UNKNOWN_INDUCT;
6080           return 0;
6081         }
6082     }
6083
6084   return v->benefit;
6085 }
6086 \f
6087 /* Return an rtx, if any, that expresses giv G2 as a function of the register
6088    represented by G1.  If no such expression can be found, or it is clear that
6089    it cannot possibly be a valid address, 0 is returned. 
6090
6091    To perform the computation, we note that
6092         G1 = x * v + a          and
6093         G2 = y * v + b
6094    where `v' is the biv.
6095
6096    So G2 = (y/b) * G1 + (b - a*y/x).
6097
6098    Note that MULT = y/x.
6099
6100    Update: A and B are now allowed to be additive expressions such that
6101    B contains all variables in A.  That is, computing B-A will not require
6102    subtracting variables.  */
6103
6104 static rtx
6105 express_from_1 (a, b, mult)
6106      rtx a, b, mult;
6107 {
6108   /* If MULT is zero, then A*MULT is zero, and our expression is B.  */
6109
6110   if (mult == const0_rtx)
6111     return b;
6112
6113   /* If MULT is not 1, we cannot handle A with non-constants, since we
6114      would then be required to subtract multiples of the registers in A.
6115      This is theoretically possible, and may even apply to some Fortran
6116      constructs, but it is a lot of work and we do not attempt it here.  */
6117
6118   if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
6119     return NULL_RTX;
6120
6121   /* In general these structures are sorted top to bottom (down the PLUS
6122      chain), but not left to right across the PLUS.  If B is a higher
6123      order giv than A, we can strip one level and recurse.  If A is higher
6124      order, we'll eventually bail out, but won't know that until the end.
6125      If they are the same, we'll strip one level around this loop.  */
6126
6127   while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
6128     {
6129       rtx ra, rb, oa, ob, tmp;
6130
6131       ra = XEXP (a, 0), oa = XEXP (a, 1);
6132       if (GET_CODE (ra) == PLUS)
6133         tmp = ra, ra = oa, oa = tmp;
6134
6135       rb = XEXP (b, 0), ob = XEXP (b, 1);
6136       if (GET_CODE (rb) == PLUS)
6137         tmp = rb, rb = ob, ob = tmp;
6138
6139       if (rtx_equal_p (ra, rb))
6140         /* We matched: remove one reg completely.  */
6141         a = oa, b = ob;
6142       else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
6143         /* An alternate match.  */
6144         a = oa, b = rb;
6145       else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
6146         /* An alternate match.  */
6147         a = ra, b = ob;
6148       else
6149         {
6150           /* Indicates an extra register in B.  Strip one level from B and 
6151              recurse, hoping B was the higher order expression.  */
6152           ob = express_from_1 (a, ob, mult);
6153           if (ob == NULL_RTX)
6154             return NULL_RTX;
6155           return gen_rtx_PLUS (GET_MODE (b), rb, ob);
6156         }
6157     }
6158
6159   /* Here we are at the last level of A, go through the cases hoping to
6160      get rid of everything but a constant.  */
6161
6162   if (GET_CODE (a) == PLUS)
6163     {
6164       rtx ra, oa;
6165
6166       ra = XEXP (a, 0), oa = XEXP (a, 1);
6167       if (rtx_equal_p (oa, b))
6168         oa = ra;
6169       else if (!rtx_equal_p (ra, b))
6170         return NULL_RTX;
6171
6172       if (GET_CODE (oa) != CONST_INT)
6173         return NULL_RTX;
6174
6175       return GEN_INT (-INTVAL (oa) * INTVAL (mult));
6176     }
6177   else if (GET_CODE (a) == CONST_INT)
6178     {
6179       return plus_constant (b, -INTVAL (a) * INTVAL (mult));
6180     }
6181   else if (GET_CODE (b) == PLUS)
6182     {
6183       if (rtx_equal_p (a, XEXP (b, 0)))
6184         return XEXP (b, 1);
6185       else if (rtx_equal_p (a, XEXP (b, 1)))
6186         return XEXP (b, 0);
6187       else
6188         return NULL_RTX;
6189     }
6190   else if (rtx_equal_p (a, b))
6191     return const0_rtx;
6192
6193   return NULL_RTX;
6194 }
6195
6196 static rtx
6197 express_from (g1, g2)
6198      struct induction *g1, *g2;
6199 {
6200   rtx mult, add;
6201
6202   /* The value that G1 will be multiplied by must be a constant integer.  Also,
6203      the only chance we have of getting a valid address is if b*c/a (see above
6204      for notation) is also an integer.  */
6205   if (GET_CODE (g1->mult_val) == CONST_INT
6206       && GET_CODE (g2->mult_val) == CONST_INT)
6207     {
6208       if (g1->mult_val == const0_rtx
6209           || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
6210         return NULL_RTX;
6211       mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
6212     }
6213   else if (rtx_equal_p (g1->mult_val, g2->mult_val))
6214     mult = const1_rtx;
6215   else
6216     {
6217       /* ??? Find out if the one is a multiple of the other?  */
6218       return NULL_RTX;
6219     }
6220
6221   add = express_from_1 (g1->add_val, g2->add_val, mult);
6222   if (add == NULL_RTX)
6223     return NULL_RTX;
6224
6225   /* Form simplified final result.  */
6226   if (mult == const0_rtx)
6227     return add;
6228   else if (mult == const1_rtx)
6229     mult = g1->dest_reg;
6230   else
6231     mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
6232
6233   if (add == const0_rtx)
6234     return mult;
6235   else
6236     {
6237       if (GET_CODE (add) == PLUS
6238           && CONSTANT_P (XEXP (add, 1)))
6239         {
6240           rtx tem = XEXP (add, 1);
6241           mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
6242           add = tem;
6243         }
6244       
6245       return gen_rtx_PLUS (g2->mode, mult, add);
6246     }
6247   
6248 }
6249 \f
6250 /* Return an rtx, if any, that expresses giv G2 as a function of the register
6251    represented by G1.  This indicates that G2 should be combined with G1 and
6252    that G2 can use (either directly or via an address expression) a register
6253    used to represent G1.  */
6254
6255 static rtx
6256 combine_givs_p (g1, g2)
6257      struct induction *g1, *g2;
6258 {
6259   rtx tem = express_from (g1, g2);
6260
6261   /* If these givs are identical, they can be combined.  We use the results
6262      of express_from because the addends are not in a canonical form, so
6263      rtx_equal_p is a weaker test.  */
6264   if (tem == g1->dest_reg)
6265     {
6266       return g1->dest_reg;
6267     }
6268
6269   /* If G2 can be expressed as a function of G1 and that function is valid
6270      as an address and no more expensive than using a register for G2,
6271      the expression of G2 in terms of G1 can be used.  */
6272   if (tem != NULL_RTX
6273       && g2->giv_type == DEST_ADDR
6274       && memory_address_p (g2->mem_mode, tem)
6275       /* ??? Looses, especially with -fforce-addr, where *g2->location
6276          will always be a register, and so anything more complicated
6277          gets discarded.  */
6278 #if 0
6279 #ifdef ADDRESS_COST
6280       && ADDRESS_COST (tem) <= ADDRESS_COST (*g2->location)
6281 #else
6282       && rtx_cost (tem, MEM) <= rtx_cost (*g2->location, MEM)
6283 #endif
6284 #endif
6285       )
6286     {
6287       return tem;
6288     }
6289
6290   return NULL_RTX;
6291 }
6292 \f
6293 struct combine_givs_stats
6294 {
6295   int giv_number;
6296   int total_benefit;
6297 };
6298
6299 static int
6300 cmp_combine_givs_stats (x, y)
6301      struct combine_givs_stats *x, *y;
6302 {
6303   int d;
6304   d = y->total_benefit - x->total_benefit;
6305   /* Stabilize the sort.  */
6306   if (!d)
6307     d = x->giv_number - y->giv_number;
6308   return d;
6309 }
6310
6311 /* If one of these givs is a DEST_REG that was only used once, by the
6312    other giv, this is actually a single use.  Return 0 if this is not
6313    the case, -1 if g1 is the DEST_REG involved, and 1 if it was g2.  */
6314
6315 static int
6316 combine_givs_used_once (g1, g2)
6317      struct induction *g1, *g2;
6318 {
6319   if (g1->giv_type == DEST_REG
6320       && VARRAY_INT (n_times_used, REGNO (g1->dest_reg)) == 1
6321       && reg_mentioned_p (g1->dest_reg, PATTERN (g2->insn)))
6322     return -1;
6323
6324   if (g2->giv_type == DEST_REG
6325       && VARRAY_INT (n_times_used, REGNO (g2->dest_reg)) == 1
6326       && reg_mentioned_p (g2->dest_reg, PATTERN (g1->insn)))
6327     return 1;
6328
6329   return 0;
6330 }
6331  
6332 static int
6333 combine_givs_benefit_from (g1, g2)
6334      struct induction *g1, *g2;
6335 {
6336   int tmp = combine_givs_used_once (g1, g2);
6337   if (tmp < 0)
6338     return 0;
6339   else if (tmp > 0)
6340     return g2->benefit - g1->benefit;
6341   else
6342     return g2->benefit;
6343 }
6344
6345 /* Check all pairs of givs for iv_class BL and see if any can be combined with
6346    any other.  If so, point SAME to the giv combined with and set NEW_REG to
6347    be an expression (in terms of the other giv's DEST_REG) equivalent to the
6348    giv.  Also, update BENEFIT and related fields for cost/benefit analysis.  */
6349
6350 static void
6351 combine_givs (bl)
6352      struct iv_class *bl;
6353 {
6354   struct induction *g1, *g2, **giv_array;
6355   int i, j, k, giv_count;
6356   struct combine_givs_stats *stats;
6357   rtx *can_combine;
6358
6359   /* Count givs, because bl->giv_count is incorrect here.  */
6360   giv_count = 0;
6361   for (g1 = bl->giv; g1; g1 = g1->next_iv)
6362     if (!g1->ignore)
6363       giv_count++;
6364
6365   giv_array
6366     = (struct induction **) alloca (giv_count * sizeof (struct induction *));
6367   i = 0;
6368   for (g1 = bl->giv; g1; g1 = g1->next_iv)
6369     if (!g1->ignore)
6370       giv_array[i++] = g1;
6371
6372   stats = (struct combine_givs_stats *) alloca (giv_count * sizeof (*stats));
6373   bzero ((char *) stats, giv_count * sizeof (*stats));
6374
6375   can_combine = (rtx *) alloca (giv_count * giv_count * sizeof(rtx));
6376   bzero ((char *) can_combine, giv_count * giv_count * sizeof(rtx));
6377
6378   for (i = 0; i < giv_count; i++)
6379     {
6380       int this_benefit;
6381
6382       g1 = giv_array[i];
6383
6384       this_benefit = g1->benefit;
6385       /* Add an additional weight for zero addends.  */
6386       if (g1->no_const_addval)
6387         this_benefit += 1;
6388       for (j = 0; j < giv_count; j++)
6389         {
6390           rtx this_combine;
6391
6392           g2 = giv_array[j];
6393           if (g1 != g2
6394               && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
6395             {
6396               can_combine[i*giv_count + j] = this_combine;
6397               this_benefit += combine_givs_benefit_from (g1, g2);
6398               /* Add an additional weight for being reused more times.  */
6399               this_benefit += 3;
6400             }
6401         }
6402       stats[i].giv_number = i;
6403       stats[i].total_benefit = this_benefit;
6404     }
6405
6406   /* Iterate, combining until we can't.  */
6407 restart:
6408   qsort (stats, giv_count, sizeof(*stats), cmp_combine_givs_stats);
6409
6410   if (loop_dump_stream)
6411     {
6412       fprintf (loop_dump_stream, "Sorted combine statistics:\n");
6413       for (k = 0; k < giv_count; k++)
6414         {
6415           g1 = giv_array[stats[k].giv_number];
6416           if (!g1->combined_with && !g1->same)
6417             fprintf (loop_dump_stream, " {%d, %d}", 
6418                      INSN_UID (giv_array[stats[k].giv_number]->insn),
6419                      stats[k].total_benefit);
6420         }
6421       putc ('\n', loop_dump_stream);
6422     }
6423
6424   for (k = 0; k < giv_count; k++)
6425     {
6426       int g1_add_benefit = 0;
6427
6428       i = stats[k].giv_number;
6429       g1 = giv_array[i];
6430
6431       /* If it has already been combined, skip.  */
6432       if (g1->combined_with || g1->same)
6433         continue;
6434
6435       for (j = 0; j < giv_count; j++)
6436         {
6437           g2 = giv_array[j];
6438           if (g1 != g2 && can_combine[i*giv_count + j]
6439               /* If it has already been combined, skip.  */
6440               && ! g2->same && ! g2->combined_with)
6441             {
6442               int l;
6443
6444               g2->new_reg = can_combine[i*giv_count + j];
6445               g2->same = g1;
6446               g1->combined_with = 1;
6447               if (!combine_givs_used_once (g1, g2))
6448                 g1->times_used += 1;
6449               g1->lifetime += g2->lifetime;
6450
6451               g1_add_benefit += combine_givs_benefit_from (g1, g2);
6452
6453               /* ??? The new final_[bg]iv_value code does a much better job
6454                  of finding replaceable giv's, and hence this code may no
6455                  longer be necessary.  */
6456               if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
6457                 g1_add_benefit -= copy_cost;
6458                 
6459               /* To help optimize the next set of combinations, remove
6460                  this giv from the benefits of other potential mates.  */
6461               for (l = 0; l < giv_count; ++l)
6462                 {
6463                   int m = stats[l].giv_number;
6464                   if (can_combine[m*giv_count + j])
6465                     {
6466                       /* Remove additional weight for being reused.  */
6467                       stats[l].total_benefit -= 3 + 
6468                         combine_givs_benefit_from (giv_array[m], g2);
6469                     }
6470                 }
6471
6472               if (loop_dump_stream)
6473                 fprintf (loop_dump_stream,
6474                          "giv at %d combined with giv at %d\n",
6475                          INSN_UID (g2->insn), INSN_UID (g1->insn));
6476             }
6477         }
6478
6479       /* To help optimize the next set of combinations, remove
6480          this giv from the benefits of other potential mates.  */
6481       if (g1->combined_with)
6482         {
6483           for (j = 0; j < giv_count; ++j)
6484             {
6485               int m = stats[j].giv_number;
6486               if (can_combine[m*giv_count + j])
6487                 {
6488                   /* Remove additional weight for being reused.  */
6489                   stats[j].total_benefit -= 3 + 
6490                     combine_givs_benefit_from (giv_array[m], g1);
6491                 }
6492             }
6493
6494           g1->benefit += g1_add_benefit;
6495
6496           /* We've finished with this giv, and everything it touched.
6497              Restart the combination so that proper weights for the 
6498              rest of the givs are properly taken into account.  */
6499           /* ??? Ideally we would compact the arrays at this point, so
6500              as to not cover old ground.  But sanely compacting
6501              can_combine is tricky.  */
6502           goto restart;
6503         }
6504     }
6505 }
6506 \f
6507 /* EMIT code before INSERT_BEFORE to set REG = B * M + A.  */
6508
6509 void
6510 emit_iv_add_mult (b, m, a, reg, insert_before)
6511      rtx b;          /* initial value of basic induction variable */
6512      rtx m;          /* multiplicative constant */
6513      rtx a;          /* additive constant */
6514      rtx reg;        /* destination register */
6515      rtx insert_before;
6516 {
6517   rtx seq;
6518   rtx result;
6519
6520   /* Prevent unexpected sharing of these rtx.  */
6521   a = copy_rtx (a);
6522   b = copy_rtx (b);
6523
6524   /* Increase the lifetime of any invariants moved further in code.  */
6525   update_reg_last_use (a, insert_before);
6526   update_reg_last_use (b, insert_before);
6527   update_reg_last_use (m, insert_before);
6528
6529   start_sequence ();
6530   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 0);
6531   if (reg != result)
6532     emit_move_insn (reg, result);
6533   seq = gen_sequence ();
6534   end_sequence ();
6535
6536   emit_insn_before (seq, insert_before);
6537
6538   /* It is entirely possible that the expansion created lots of new 
6539      registers.  Iterate over the sequence we just created and 
6540      record them all.  */
6541
6542   if (GET_CODE (seq) == SEQUENCE)
6543     {
6544       int i;
6545       for (i = 0; i < XVECLEN (seq, 0); ++i)
6546         {
6547           rtx set = single_set (XVECEXP (seq, 0, i));
6548           if (set && GET_CODE (SET_DEST (set)) == REG)
6549             record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
6550         }
6551     }
6552   else if (GET_CODE (seq) == SET
6553            && GET_CODE (SET_DEST (seq)) == REG)
6554     record_base_value (REGNO (SET_DEST (seq)), SET_SRC (seq), 0);
6555 }
6556 \f
6557 /* Test whether A * B can be computed without
6558    an actual multiply insn.  Value is 1 if so.  */
6559
6560 static int
6561 product_cheap_p (a, b)
6562      rtx a;
6563      rtx b;
6564 {
6565   int i;
6566   rtx tmp;
6567   struct obstack *old_rtl_obstack = rtl_obstack;
6568   char *storage = (char *) obstack_alloc (&temp_obstack, 0);
6569   int win = 1;
6570
6571   /* If only one is constant, make it B.  */
6572   if (GET_CODE (a) == CONST_INT)
6573     tmp = a, a = b, b = tmp;
6574
6575   /* If first constant, both constant, so don't need multiply.  */
6576   if (GET_CODE (a) == CONST_INT)
6577     return 1;
6578
6579   /* If second not constant, neither is constant, so would need multiply.  */
6580   if (GET_CODE (b) != CONST_INT)
6581     return 0;
6582
6583   /* One operand is constant, so might not need multiply insn.  Generate the
6584      code for the multiply and see if a call or multiply, or long sequence
6585      of insns is generated.  */
6586
6587   rtl_obstack = &temp_obstack;
6588   start_sequence ();
6589   expand_mult (GET_MODE (a), a, b, NULL_RTX, 0);
6590   tmp = gen_sequence ();
6591   end_sequence ();
6592
6593   if (GET_CODE (tmp) == SEQUENCE)
6594     {
6595       if (XVEC (tmp, 0) == 0)
6596         win = 1;
6597       else if (XVECLEN (tmp, 0) > 3)
6598         win = 0;
6599       else
6600         for (i = 0; i < XVECLEN (tmp, 0); i++)
6601           {
6602             rtx insn = XVECEXP (tmp, 0, i);
6603
6604             if (GET_CODE (insn) != INSN
6605                 || (GET_CODE (PATTERN (insn)) == SET
6606                     && GET_CODE (SET_SRC (PATTERN (insn))) == MULT)
6607                 || (GET_CODE (PATTERN (insn)) == PARALLEL
6608                     && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == SET
6609                     && GET_CODE (SET_SRC (XVECEXP (PATTERN (insn), 0, 0))) == MULT))
6610               {
6611                 win = 0;
6612                 break;
6613               }
6614           }
6615     }
6616   else if (GET_CODE (tmp) == SET
6617            && GET_CODE (SET_SRC (tmp)) == MULT)
6618     win = 0;
6619   else if (GET_CODE (tmp) == PARALLEL
6620            && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
6621            && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
6622     win = 0;
6623
6624   /* Free any storage we obtained in generating this multiply and restore rtl
6625      allocation to its normal obstack.  */
6626   obstack_free (&temp_obstack, storage);
6627   rtl_obstack = old_rtl_obstack;
6628
6629   return win;
6630 }
6631 \f
6632 /* Check to see if loop can be terminated by a "decrement and branch until
6633    zero" instruction.  If so, add a REG_NONNEG note to the branch insn if so.
6634    Also try reversing an increment loop to a decrement loop
6635    to see if the optimization can be performed.
6636    Value is nonzero if optimization was performed.  */
6637
6638 /* This is useful even if the architecture doesn't have such an insn,
6639    because it might change a loops which increments from 0 to n to a loop
6640    which decrements from n to 0.  A loop that decrements to zero is usually
6641    faster than one that increments from zero.  */
6642
6643 /* ??? This could be rewritten to use some of the loop unrolling procedures,
6644    such as approx_final_value, biv_total_increment, loop_iterations, and
6645    final_[bg]iv_value.  */
6646
6647 static int
6648 check_dbra_loop (loop_end, insn_count, loop_start)
6649      rtx loop_end;
6650      int insn_count;
6651      rtx loop_start;
6652 {
6653   struct iv_class *bl;
6654   rtx reg;
6655   rtx jump_label;
6656   rtx final_value;
6657   rtx start_value;
6658   rtx new_add_val;
6659   rtx comparison;
6660   rtx before_comparison;
6661   rtx p;
6662   rtx jump;
6663   rtx first_compare;
6664   int compare_and_branch;
6665
6666   /* If last insn is a conditional branch, and the insn before tests a
6667      register value, try to optimize it.  Otherwise, we can't do anything.  */
6668
6669   jump = PREV_INSN (loop_end);
6670   comparison = get_condition_for_loop (jump);
6671   if (comparison == 0)
6672     return 0;
6673
6674   /* Try to compute whether the compare/branch at the loop end is one or
6675      two instructions.  */
6676   get_condition (jump, &first_compare);
6677   if (first_compare == jump)
6678     compare_and_branch = 1;
6679   else if (first_compare == prev_nonnote_insn (jump))
6680     compare_and_branch = 2;
6681   else
6682     return 0;
6683
6684   /* Check all of the bivs to see if the compare uses one of them.
6685      Skip biv's set more than once because we can't guarantee that
6686      it will be zero on the last iteration.  Also skip if the biv is
6687      used between its update and the test insn.  */
6688
6689   for (bl = loop_iv_list; bl; bl = bl->next)
6690     {
6691       if (bl->biv_count == 1
6692           && bl->biv->dest_reg == XEXP (comparison, 0)
6693           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
6694                                    first_compare))
6695         break;
6696     }
6697
6698   if (! bl)
6699     return 0;
6700
6701   /* Look for the case where the basic induction variable is always
6702      nonnegative, and equals zero on the last iteration.
6703      In this case, add a reg_note REG_NONNEG, which allows the
6704      m68k DBRA instruction to be used.  */
6705
6706   if (((GET_CODE (comparison) == GT
6707         && GET_CODE (XEXP (comparison, 1)) == CONST_INT
6708         && INTVAL (XEXP (comparison, 1)) == -1)
6709        || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
6710       && GET_CODE (bl->biv->add_val) == CONST_INT
6711       && INTVAL (bl->biv->add_val) < 0)
6712     {
6713       /* Initial value must be greater than 0,
6714          init_val % -dec_value == 0 to ensure that it equals zero on
6715          the last iteration */
6716
6717       if (GET_CODE (bl->initial_value) == CONST_INT
6718           && INTVAL (bl->initial_value) > 0
6719           && (INTVAL (bl->initial_value)
6720               % (-INTVAL (bl->biv->add_val))) == 0)
6721         {
6722           /* register always nonnegative, add REG_NOTE to branch */
6723           REG_NOTES (PREV_INSN (loop_end))
6724             = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
6725                                  REG_NOTES (PREV_INSN (loop_end)));
6726           bl->nonneg = 1;
6727
6728           return 1;
6729         }
6730
6731       /* If the decrement is 1 and the value was tested as >= 0 before
6732          the loop, then we can safely optimize.  */
6733       for (p = loop_start; p; p = PREV_INSN (p))
6734         {
6735           if (GET_CODE (p) == CODE_LABEL)
6736             break;
6737           if (GET_CODE (p) != JUMP_INSN)
6738             continue;
6739
6740           before_comparison = get_condition_for_loop (p);
6741           if (before_comparison
6742               && XEXP (before_comparison, 0) == bl->biv->dest_reg
6743               && GET_CODE (before_comparison) == LT
6744               && XEXP (before_comparison, 1) == const0_rtx
6745               && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
6746               && INTVAL (bl->biv->add_val) == -1)
6747             {
6748               REG_NOTES (PREV_INSN (loop_end))
6749                 = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
6750                                      REG_NOTES (PREV_INSN (loop_end)));
6751               bl->nonneg = 1;
6752
6753               return 1;
6754             }
6755         }
6756     }
6757   else if (INTVAL (bl->biv->add_val) > 0)
6758     {
6759       /* Try to change inc to dec, so can apply above optimization.  */
6760       /* Can do this if:
6761          all registers modified are induction variables or invariant,
6762          all memory references have non-overlapping addresses
6763          (obviously true if only one write)
6764          allow 2 insns for the compare/jump at the end of the loop.  */
6765       /* Also, we must avoid any instructions which use both the reversed
6766          biv and another biv.  Such instructions will fail if the loop is
6767          reversed.  We meet this condition by requiring that either
6768          no_use_except_counting is true, or else that there is only
6769          one biv.  */
6770       int num_nonfixed_reads = 0;
6771       /* 1 if the iteration var is used only to count iterations.  */
6772       int no_use_except_counting = 0;
6773       /* 1 if the loop has no memory store, or it has a single memory store
6774          which is reversible.  */
6775       int reversible_mem_store = 1;
6776
6777       if (bl->giv_count == 0
6778           && ! loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
6779         {
6780           rtx bivreg = regno_reg_rtx[bl->regno];
6781
6782           /* If there are no givs for this biv, and the only exit is the
6783              fall through at the end of the loop, then
6784              see if perhaps there are no uses except to count.  */
6785           no_use_except_counting = 1;
6786           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
6787             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
6788               {
6789                 rtx set = single_set (p);
6790
6791                 if (set && GET_CODE (SET_DEST (set)) == REG
6792                     && REGNO (SET_DEST (set)) == bl->regno)
6793                   /* An insn that sets the biv is okay.  */
6794                   ;
6795                 else if (p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
6796                          || p == prev_nonnote_insn (loop_end))
6797                   /* Don't bother about the end test.  */
6798                   ;
6799                 else if (reg_mentioned_p (bivreg, PATTERN (p)))
6800                   {
6801                     no_use_except_counting = 0;
6802                     break;
6803                   }
6804               }
6805         }
6806
6807       if (no_use_except_counting)
6808         ; /* no need to worry about MEMs.  */
6809       else if (num_mem_sets <= 1)
6810         {
6811           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
6812             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
6813               num_nonfixed_reads += count_nonfixed_reads (PATTERN (p));
6814
6815           /* If the loop has a single store, and the destination address is
6816              invariant, then we can't reverse the loop, because this address
6817              might then have the wrong value at loop exit.
6818              This would work if the source was invariant also, however, in that
6819              case, the insn should have been moved out of the loop.  */
6820
6821           if (num_mem_sets == 1)
6822             reversible_mem_store
6823               = (! unknown_address_altered
6824                  && ! invariant_p (XEXP (loop_store_mems[0], 0)));
6825         }
6826       else
6827         return 0;
6828
6829       /* This code only acts for innermost loops.  Also it simplifies
6830          the memory address check by only reversing loops with
6831          zero or one memory access.
6832          Two memory accesses could involve parts of the same array,
6833          and that can't be reversed.
6834          If the biv is used only for counting, than we don't need to worry
6835          about all these things.  */
6836
6837       if ((num_nonfixed_reads <= 1
6838            && !loop_has_call
6839            && !loop_has_volatile
6840            && reversible_mem_store
6841            && (bl->giv_count + bl->biv_count + num_mem_sets
6842               + num_movables + compare_and_branch == insn_count)
6843            && (bl == loop_iv_list && bl->next == 0))
6844           || no_use_except_counting)
6845         {
6846           rtx tem;
6847
6848           /* Loop can be reversed.  */
6849           if (loop_dump_stream)
6850             fprintf (loop_dump_stream, "Can reverse loop\n");
6851
6852           /* Now check other conditions:
6853
6854              The increment must be a constant, as must the initial value,
6855              and the comparison code must be LT. 
6856
6857              This test can probably be improved since +/- 1 in the constant
6858              can be obtained by changing LT to LE and vice versa; this is
6859              confusing.  */
6860
6861           if (comparison
6862               /* for constants, LE gets turned into LT */
6863               && (GET_CODE (comparison) == LT
6864                   || (GET_CODE (comparison) == LE
6865                       && no_use_except_counting)))
6866             {
6867               HOST_WIDE_INT add_val, add_adjust, comparison_val;
6868               rtx initial_value, comparison_value;
6869               int nonneg = 0;
6870               enum rtx_code cmp_code;
6871               int comparison_const_width;
6872               unsigned HOST_WIDE_INT comparison_sign_mask;
6873               rtx vtop;
6874
6875               add_val = INTVAL (bl->biv->add_val);
6876               comparison_value = XEXP (comparison, 1);
6877               comparison_const_width
6878                 = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 1)));
6879               if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
6880                 comparison_const_width = HOST_BITS_PER_WIDE_INT;
6881               comparison_sign_mask
6882                 = (unsigned HOST_WIDE_INT)1 << (comparison_const_width - 1);
6883
6884               /* If the comparison value is not a loop invariant, then we
6885                  can not reverse this loop.
6886
6887                  ??? If the insns which initialize the comparison value as
6888                  a whole compute an invariant result, then we could move
6889                  them out of the loop and proceed with loop reversal.  */
6890               if (!invariant_p (comparison_value))
6891                 return 0;
6892
6893               if (GET_CODE (comparison_value) == CONST_INT)
6894                 comparison_val = INTVAL (comparison_value);
6895               initial_value = bl->initial_value;
6896                 
6897               /* Normalize the initial value if it is an integer and 
6898                  has no other use except as a counter.  This will allow
6899                  a few more loops to be reversed.  */
6900               if (no_use_except_counting
6901                   && GET_CODE (comparison_value) == CONST_INT
6902                   && GET_CODE (initial_value) == CONST_INT)
6903                 {
6904                   comparison_val = comparison_val - INTVAL (bl->initial_value);
6905                   /* The code below requires comparison_val to be a multiple
6906                      of add_val in order to do the loop reversal, so
6907                      round up comparison_val to a multiple of add_val.
6908                      Since comparison_value is constant, we know that the
6909                      current comparison code is LT.  */
6910                   comparison_val = comparison_val + add_val - 1;
6911                   comparison_val
6912                     -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
6913                   /* We postpone overflow checks for COMPARISON_VAL here;
6914                      even if there is an overflow, we might still be able to
6915                      reverse the loop, if converting the loop exit test to
6916                      NE is possible.  */
6917                   initial_value = const0_rtx;
6918                 }
6919
6920               /* Check if there is a NOTE_INSN_LOOP_VTOP note.  If there is,
6921                  that means that this is a for or while style loop, with
6922                  a loop exit test at the start.  Thus, we can assume that
6923                  the loop condition was true when the loop was entered.
6924                  This allows us to change the loop exit condition to an
6925                  equality test.
6926                  We start at the end and search backwards for the previous
6927                  NOTE.  If there is no NOTE_INSN_LOOP_VTOP for this loop,
6928                  the search will stop at the NOTE_INSN_LOOP_CONT.  */
6929               vtop = loop_end;
6930               do
6931                 vtop = PREV_INSN (vtop);
6932               while (GET_CODE (vtop) != NOTE
6933                      || NOTE_LINE_NUMBER (vtop) > 0
6934                      || NOTE_LINE_NUMBER (vtop) == NOTE_REPEATED_LINE_NUMBER
6935                      || NOTE_LINE_NUMBER (vtop) == NOTE_INSN_DELETED);
6936               if (NOTE_LINE_NUMBER (vtop) != NOTE_INSN_LOOP_VTOP)
6937                 vtop = NULL_RTX;
6938                 
6939               /* First check if we can do a vanilla loop reversal.  */
6940               if (initial_value == const0_rtx
6941                   /* If we have a decrement_and_branch_on_count, prefer
6942                      the NE test, since this will allow that instruction to
6943                      be generated.  Note that we must use a vanilla loop
6944                      reversal if the biv is used to calculate a giv or has
6945                      a non-counting use.  */
6946 #if ! defined (HAVE_decrement_and_branch_until_zero) && defined (HAVE_decrement_and_branch_on_count)
6947                   && (! (add_val == 1 && vtop
6948                          && (bl->biv_count == 0
6949                              || no_use_except_counting)))
6950 #endif
6951                   && GET_CODE (comparison_value) == CONST_INT
6952                      /* Now do postponed overflow checks on COMPARISON_VAL.  */
6953                   && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
6954                         & comparison_sign_mask))
6955                 {
6956                   /* Register will always be nonnegative, with value
6957                      0 on last iteration */
6958                   add_adjust = add_val;
6959                   nonneg = 1;
6960                   cmp_code = GE;
6961                 }
6962               else if (add_val == 1 && vtop
6963                        && (bl->biv_count == 0
6964                            || no_use_except_counting))
6965                 {
6966                   add_adjust = 0;
6967                   cmp_code = NE;
6968                 }
6969               else
6970                 return 0;
6971
6972               if (GET_CODE (comparison) == LE)
6973                 add_adjust -= add_val;
6974
6975               /* If the initial value is not zero, or if the comparison
6976                  value is not an exact multiple of the increment, then we
6977                  can not reverse this loop.  */
6978               if (initial_value == const0_rtx
6979                   && GET_CODE (comparison_value) == CONST_INT)
6980                 {
6981                   if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
6982                     return 0;
6983                 }
6984               else
6985                 {
6986                   if (! no_use_except_counting || add_val != 1)
6987                     return 0;
6988                 }
6989
6990               final_value = comparison_value;
6991
6992               /* Reset these in case we normalized the initial value
6993                  and comparison value above.  */
6994               if (GET_CODE (comparison_value) == CONST_INT
6995                   && GET_CODE (initial_value) == CONST_INT)
6996                 {
6997                   comparison_value = GEN_INT (comparison_val);
6998                   final_value
6999                     = GEN_INT (comparison_val + INTVAL (bl->initial_value));
7000                 }
7001               bl->initial_value = initial_value;
7002
7003               /* Save some info needed to produce the new insns.  */
7004               reg = bl->biv->dest_reg;
7005               jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 1);
7006               if (jump_label == pc_rtx)
7007                 jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 2);
7008               new_add_val = GEN_INT (- INTVAL (bl->biv->add_val));
7009
7010               /* Set start_value; if this is not a CONST_INT, we need
7011                  to generate a SUB.
7012                  Initialize biv to start_value before loop start.
7013                  The old initializing insn will be deleted as a
7014                  dead store by flow.c.  */
7015               if (initial_value == const0_rtx
7016                   && GET_CODE (comparison_value) == CONST_INT)
7017                 {
7018                   start_value = GEN_INT (comparison_val - add_adjust);
7019                   emit_insn_before (gen_move_insn (reg, start_value),
7020                                     loop_start);
7021                 }
7022               else if (GET_CODE (initial_value) == CONST_INT)
7023                 {
7024                   rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
7025                   enum machine_mode mode = GET_MODE (reg);
7026                   enum insn_code icode
7027                     = add_optab->handlers[(int) mode].insn_code;
7028                   if (! (*insn_operand_predicate[icode][0]) (reg, mode)
7029                       || ! ((*insn_operand_predicate[icode][1])
7030                             (comparison_value, mode))
7031                       || ! (*insn_operand_predicate[icode][2]) (offset, mode))
7032                     return 0;
7033                   start_value
7034                     = gen_rtx_PLUS (mode, comparison_value, offset);
7035                   emit_insn_before ((GEN_FCN (icode)
7036                                      (reg, comparison_value, offset)),
7037                                     loop_start);
7038                   if (GET_CODE (comparison) == LE)
7039                     final_value = gen_rtx_PLUS (mode, comparison_value,
7040                                                 GEN_INT (add_val));
7041                 }
7042               else if (! add_adjust)
7043                 {
7044                   enum machine_mode mode = GET_MODE (reg);
7045                   enum insn_code icode
7046                     = sub_optab->handlers[(int) mode].insn_code;
7047                   if (! (*insn_operand_predicate[icode][0]) (reg, mode)
7048                       || ! ((*insn_operand_predicate[icode][1])
7049                             (comparison_value, mode))
7050                       || ! ((*insn_operand_predicate[icode][2])
7051                             (initial_value, mode)))
7052                     return 0;
7053                   start_value
7054                     = gen_rtx_MINUS (mode, comparison_value, initial_value);
7055                   emit_insn_before ((GEN_FCN (icode)
7056                                      (reg, comparison_value, initial_value)),
7057                                     loop_start);
7058                 }
7059               else
7060                 /* We could handle the other cases too, but it'll be
7061                    better to have a testcase first.  */
7062                 return 0;
7063
7064               /* We may not have a single insn which can increment a reg, so
7065                  create a sequence to hold all the insns from expand_inc.  */
7066               start_sequence ();
7067               expand_inc (reg, new_add_val);
7068               tem = gen_sequence ();
7069               end_sequence ();
7070
7071               p = emit_insn_before (tem, bl->biv->insn);
7072               delete_insn (bl->biv->insn);
7073                       
7074               /* Update biv info to reflect its new status.  */
7075               bl->biv->insn = p;
7076               bl->initial_value = start_value;
7077               bl->biv->add_val = new_add_val;
7078
7079               /* Inc LABEL_NUSES so that delete_insn will
7080                  not delete the label.  */
7081               LABEL_NUSES (XEXP (jump_label, 0)) ++;
7082
7083               /* Emit an insn after the end of the loop to set the biv's
7084                  proper exit value if it is used anywhere outside the loop.  */
7085               if ((REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
7086                   || ! bl->init_insn
7087                   || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
7088                 emit_insn_after (gen_move_insn (reg, final_value),
7089                                  loop_end);
7090
7091               /* Delete compare/branch at end of loop.  */
7092               delete_insn (PREV_INSN (loop_end));
7093               if (compare_and_branch == 2)
7094                 delete_insn (first_compare);
7095
7096               /* Add new compare/branch insn at end of loop.  */
7097               start_sequence ();
7098               emit_cmp_insn (reg, const0_rtx, cmp_code, NULL_RTX,
7099                              GET_MODE (reg), 0, 0);
7100               emit_jump_insn ((*bcc_gen_fctn[(int) cmp_code])
7101                               (XEXP (jump_label, 0)));
7102               tem = gen_sequence ();
7103               end_sequence ();
7104               emit_jump_insn_before (tem, loop_end);
7105
7106               if (nonneg)
7107                 {
7108                   for (tem = PREV_INSN (loop_end);
7109                        tem && GET_CODE (tem) != JUMP_INSN;
7110                        tem = PREV_INSN (tem))
7111                     ;
7112                   if (tem)
7113                     {
7114                       JUMP_LABEL (tem) = XEXP (jump_label, 0);
7115
7116                       /* Increment of LABEL_NUSES done above.  */
7117                       /* Register is now always nonnegative,
7118                          so add REG_NONNEG note to the branch.  */
7119                       REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7120                                                            REG_NOTES (tem));
7121                     }
7122                   bl->nonneg = 1;
7123                 }
7124
7125               /* Mark that this biv has been reversed.  Each giv which depends
7126                  on this biv, and which is also live past the end of the loop
7127                  will have to be fixed up.  */
7128
7129               bl->reversed = 1;
7130
7131               if (loop_dump_stream)
7132                 fprintf (loop_dump_stream,
7133                          "Reversed loop and added reg_nonneg\n");
7134
7135               return 1;
7136             }
7137         }
7138     }
7139
7140   return 0;
7141 }
7142 \f
7143 /* Verify whether the biv BL appears to be eliminable,
7144    based on the insns in the loop that refer to it.
7145    LOOP_START is the first insn of the loop, and END is the end insn.
7146
7147    If ELIMINATE_P is non-zero, actually do the elimination.
7148
7149    THRESHOLD and INSN_COUNT are from loop_optimize and are used to
7150    determine whether invariant insns should be placed inside or at the
7151    start of the loop.  */
7152
7153 static int
7154 maybe_eliminate_biv (bl, loop_start, end, eliminate_p, threshold, insn_count)
7155      struct iv_class *bl;
7156      rtx loop_start;
7157      rtx end;
7158      int eliminate_p;
7159      int threshold, insn_count;
7160 {
7161   rtx reg = bl->biv->dest_reg;
7162   rtx p;
7163
7164   /* Scan all insns in the loop, stopping if we find one that uses the
7165      biv in a way that we cannot eliminate.  */
7166
7167   for (p = loop_start; p != end; p = NEXT_INSN (p))
7168     {
7169       enum rtx_code code = GET_CODE (p);
7170       rtx where = threshold >= insn_count ? loop_start : p;
7171
7172       if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
7173           && reg_mentioned_p (reg, PATTERN (p))
7174           && ! maybe_eliminate_biv_1 (PATTERN (p), p, bl, eliminate_p, where))
7175         {
7176           if (loop_dump_stream)
7177             fprintf (loop_dump_stream,
7178                      "Cannot eliminate biv %d: biv used in insn %d.\n",
7179                      bl->regno, INSN_UID (p));
7180           break;
7181         }
7182     }
7183
7184   if (p == end)
7185     {
7186       if (loop_dump_stream)
7187         fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
7188                  bl->regno, eliminate_p ? "was" : "can be");
7189       return 1;
7190     }
7191
7192   return 0;
7193 }
7194 \f
7195 /* If BL appears in X (part of the pattern of INSN), see if we can
7196    eliminate its use.  If so, return 1.  If not, return 0.
7197
7198    If BIV does not appear in X, return 1.
7199
7200    If ELIMINATE_P is non-zero, actually do the elimination.  WHERE indicates
7201    where extra insns should be added.  Depending on how many items have been
7202    moved out of the loop, it will either be before INSN or at the start of
7203    the loop.  */
7204
7205 static int
7206 maybe_eliminate_biv_1 (x, insn, bl, eliminate_p, where)
7207      rtx x, insn;
7208      struct iv_class *bl;
7209      int eliminate_p;
7210      rtx where;
7211 {
7212   enum rtx_code code = GET_CODE (x);
7213   rtx reg = bl->biv->dest_reg;
7214   enum machine_mode mode = GET_MODE (reg);
7215   struct induction *v;
7216   rtx arg, tem;
7217 #ifdef HAVE_cc0
7218   rtx new;
7219 #endif
7220   int arg_operand;
7221   char *fmt;
7222   int i, j;
7223
7224   switch (code)
7225     {
7226     case REG:
7227       /* If we haven't already been able to do something with this BIV,
7228          we can't eliminate it.  */
7229       if (x == reg)
7230         return 0;
7231       return 1;
7232
7233     case SET:
7234       /* If this sets the BIV, it is not a problem.  */
7235       if (SET_DEST (x) == reg)
7236         return 1;
7237
7238       /* If this is an insn that defines a giv, it is also ok because
7239          it will go away when the giv is reduced.  */
7240       for (v = bl->giv; v; v = v->next_iv)
7241         if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
7242           return 1;
7243
7244 #ifdef HAVE_cc0
7245       if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
7246         {
7247           /* Can replace with any giv that was reduced and
7248              that has (MULT_VAL != 0) and (ADD_VAL == 0).
7249              Require a constant for MULT_VAL, so we know it's nonzero.
7250              ??? We disable this optimization to avoid potential
7251              overflows.  */
7252
7253           for (v = bl->giv; v; v = v->next_iv)
7254             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
7255                 && v->add_val == const0_rtx
7256                 && ! v->ignore && ! v->maybe_dead && v->always_computable
7257                 && v->mode == mode
7258                 && 0)
7259               {
7260                 /* If the giv V had the auto-inc address optimization applied
7261                    to it, and INSN occurs between the giv insn and the biv
7262                    insn, then we must adjust the value used here.
7263                    This is rare, so we don't bother to do so.  */
7264                 if (v->auto_inc_opt
7265                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
7266                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
7267                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
7268                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
7269                   continue;
7270
7271                 if (! eliminate_p)
7272                   return 1;
7273
7274                 /* If the giv has the opposite direction of change,
7275                    then reverse the comparison.  */
7276                 if (INTVAL (v->mult_val) < 0)
7277                   new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
7278                                          const0_rtx, v->new_reg);
7279                 else
7280                   new = v->new_reg;
7281
7282                 /* We can probably test that giv's reduced reg.  */
7283                 if (validate_change (insn, &SET_SRC (x), new, 0))
7284                   return 1;
7285               }
7286
7287           /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
7288              replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
7289              Require a constant for MULT_VAL, so we know it's nonzero.
7290              ??? Do this only if ADD_VAL is a pointer to avoid a potential
7291              overflow problem.  */
7292
7293           for (v = bl->giv; v; v = v->next_iv)
7294             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
7295                 && ! v->ignore && ! v->maybe_dead && v->always_computable
7296                 && v->mode == mode
7297                 && (GET_CODE (v->add_val) == SYMBOL_REF
7298                     || GET_CODE (v->add_val) == LABEL_REF
7299                     || GET_CODE (v->add_val) == CONST
7300                     || (GET_CODE (v->add_val) == REG
7301                         && REGNO_POINTER_FLAG (REGNO (v->add_val)))))
7302               {
7303                 /* If the giv V had the auto-inc address optimization applied
7304                    to it, and INSN occurs between the giv insn and the biv
7305                    insn, then we must adjust the value used here.
7306                    This is rare, so we don't bother to do so.  */
7307                 if (v->auto_inc_opt
7308                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
7309                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
7310                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
7311                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
7312                   continue;
7313
7314                 if (! eliminate_p)
7315                   return 1;
7316
7317                 /* If the giv has the opposite direction of change,
7318                    then reverse the comparison.  */
7319                 if (INTVAL (v->mult_val) < 0)
7320                   new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
7321                                          v->new_reg);
7322                 else
7323                   new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
7324                                          copy_rtx (v->add_val));
7325
7326                 /* Replace biv with the giv's reduced register.  */
7327                 update_reg_last_use (v->add_val, insn);
7328                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
7329                   return 1;
7330
7331                 /* Insn doesn't support that constant or invariant.  Copy it
7332                    into a register (it will be a loop invariant.)  */
7333                 tem = gen_reg_rtx (GET_MODE (v->new_reg));
7334
7335                 emit_insn_before (gen_move_insn (tem, copy_rtx (v->add_val)),
7336                                   where);
7337
7338                 /* Substitute the new register for its invariant value in
7339                    the compare expression. */
7340                 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
7341                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
7342                   return 1;
7343               }
7344         }
7345 #endif
7346       break;
7347
7348     case COMPARE:
7349     case EQ:  case NE:
7350     case GT:  case GE:  case GTU:  case GEU:
7351     case LT:  case LE:  case LTU:  case LEU:
7352       /* See if either argument is the biv.  */
7353       if (XEXP (x, 0) == reg)
7354         arg = XEXP (x, 1), arg_operand = 1;
7355       else if (XEXP (x, 1) == reg)
7356         arg = XEXP (x, 0), arg_operand = 0;
7357       else
7358         break;
7359
7360       if (CONSTANT_P (arg))
7361         {
7362           /* First try to replace with any giv that has constant positive
7363              mult_val and constant add_val.  We might be able to support
7364              negative mult_val, but it seems complex to do it in general.  */
7365
7366           for (v = bl->giv; v; v = v->next_iv)
7367             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
7368                 && (GET_CODE (v->add_val) == SYMBOL_REF
7369                     || GET_CODE (v->add_val) == LABEL_REF
7370                     || GET_CODE (v->add_val) == CONST
7371                     || (GET_CODE (v->add_val) == REG
7372                         && REGNO_POINTER_FLAG (REGNO (v->add_val))))
7373                 && ! v->ignore && ! v->maybe_dead && v->always_computable
7374                 && v->mode == mode)
7375               {
7376                 /* If the giv V had the auto-inc address optimization applied
7377                    to it, and INSN occurs between the giv insn and the biv
7378                    insn, then we must adjust the value used here.
7379                    This is rare, so we don't bother to do so.  */
7380                 if (v->auto_inc_opt
7381                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
7382                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
7383                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
7384                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
7385                   continue;
7386
7387                 if (! eliminate_p)
7388                   return 1;
7389
7390                 /* Replace biv with the giv's reduced reg.  */
7391                 XEXP (x, 1-arg_operand) = v->new_reg;
7392
7393                 /* If all constants are actually constant integers and
7394                    the derived constant can be directly placed in the COMPARE,
7395                    do so.  */
7396                 if (GET_CODE (arg) == CONST_INT
7397                     && GET_CODE (v->mult_val) == CONST_INT
7398                     && GET_CODE (v->add_val) == CONST_INT
7399                     && validate_change (insn, &XEXP (x, arg_operand),
7400                                         GEN_INT (INTVAL (arg)
7401                                                  * INTVAL (v->mult_val)
7402                                                  + INTVAL (v->add_val)), 0))
7403                   return 1;
7404
7405                 /* Otherwise, load it into a register.  */
7406                 tem = gen_reg_rtx (mode);
7407                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
7408                 if (validate_change (insn, &XEXP (x, arg_operand), tem, 0))
7409                   return 1;
7410
7411                 /* If that failed, put back the change we made above.  */
7412                 XEXP (x, 1-arg_operand) = reg;
7413               }
7414           
7415           /* Look for giv with positive constant mult_val and nonconst add_val.
7416              Insert insns to calculate new compare value.  
7417              ??? Turn this off due to possible overflow.  */
7418
7419           for (v = bl->giv; v; v = v->next_iv)
7420             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
7421                 && ! v->ignore && ! v->maybe_dead && v->always_computable
7422                 && v->mode == mode
7423                 && 0)
7424               {
7425                 rtx tem;
7426
7427                 /* If the giv V had the auto-inc address optimization applied
7428                    to it, and INSN occurs between the giv insn and the biv
7429                    insn, then we must adjust the value used here.
7430                    This is rare, so we don't bother to do so.  */
7431                 if (v->auto_inc_opt
7432                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
7433                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
7434                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
7435                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
7436                   continue;
7437
7438                 if (! eliminate_p)
7439                   return 1;
7440
7441                 tem = gen_reg_rtx (mode);
7442
7443                 /* Replace biv with giv's reduced register.  */
7444                 validate_change (insn, &XEXP (x, 1 - arg_operand),
7445                                  v->new_reg, 1);
7446
7447                 /* Compute value to compare against.  */
7448                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
7449                 /* Use it in this insn.  */
7450                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
7451                 if (apply_change_group ())
7452                   return 1;
7453               }
7454         }
7455       else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
7456         {
7457           if (invariant_p (arg) == 1)
7458             {
7459               /* Look for giv with constant positive mult_val and nonconst
7460                  add_val. Insert insns to compute new compare value. 
7461                  ??? Turn this off due to possible overflow.  */
7462
7463               for (v = bl->giv; v; v = v->next_iv)
7464                 if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
7465                     && ! v->ignore && ! v->maybe_dead && v->always_computable
7466                     && v->mode == mode
7467                     && 0)
7468                   {
7469                     rtx tem;
7470
7471                     /* If the giv V had the auto-inc address optimization applied
7472                        to it, and INSN occurs between the giv insn and the biv
7473                        insn, then we must adjust the value used here.
7474                        This is rare, so we don't bother to do so.  */
7475                     if (v->auto_inc_opt
7476                         && ((INSN_LUID (v->insn) < INSN_LUID (insn)
7477                              && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
7478                             || (INSN_LUID (v->insn) > INSN_LUID (insn)
7479                                 && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
7480                       continue;
7481
7482                     if (! eliminate_p)
7483                       return 1;
7484
7485                     tem = gen_reg_rtx (mode);
7486
7487                     /* Replace biv with giv's reduced register.  */
7488                     validate_change (insn, &XEXP (x, 1 - arg_operand),
7489                                      v->new_reg, 1);
7490
7491                     /* Compute value to compare against.  */
7492                     emit_iv_add_mult (arg, v->mult_val, v->add_val,
7493                                       tem, where);
7494                     validate_change (insn, &XEXP (x, arg_operand), tem, 1);
7495                     if (apply_change_group ())
7496                       return 1;
7497                   }
7498             }
7499
7500           /* This code has problems.  Basically, you can't know when
7501              seeing if we will eliminate BL, whether a particular giv
7502              of ARG will be reduced.  If it isn't going to be reduced,
7503              we can't eliminate BL.  We can try forcing it to be reduced,
7504              but that can generate poor code.
7505
7506              The problem is that the benefit of reducing TV, below should
7507              be increased if BL can actually be eliminated, but this means
7508              we might have to do a topological sort of the order in which
7509              we try to process biv.  It doesn't seem worthwhile to do
7510              this sort of thing now.  */
7511
7512 #if 0
7513           /* Otherwise the reg compared with had better be a biv.  */
7514           if (GET_CODE (arg) != REG
7515               || reg_iv_type[REGNO (arg)] != BASIC_INDUCT)
7516             return 0;
7517
7518           /* Look for a pair of givs, one for each biv,
7519              with identical coefficients.  */
7520           for (v = bl->giv; v; v = v->next_iv)
7521             {
7522               struct induction *tv;
7523
7524               if (v->ignore || v->maybe_dead || v->mode != mode)
7525                 continue;
7526
7527               for (tv = reg_biv_class[REGNO (arg)]->giv; tv; tv = tv->next_iv)
7528                 if (! tv->ignore && ! tv->maybe_dead
7529                     && rtx_equal_p (tv->mult_val, v->mult_val)
7530                     && rtx_equal_p (tv->add_val, v->add_val)
7531                     && tv->mode == mode)
7532                   {
7533                     /* If the giv V had the auto-inc address optimization applied
7534                        to it, and INSN occurs between the giv insn and the biv
7535                        insn, then we must adjust the value used here.
7536                        This is rare, so we don't bother to do so.  */
7537                     if (v->auto_inc_opt
7538                         && ((INSN_LUID (v->insn) < INSN_LUID (insn)
7539                              && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
7540                             || (INSN_LUID (v->insn) > INSN_LUID (insn)
7541                                 && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
7542                       continue;
7543
7544                     if (! eliminate_p)
7545                       return 1;
7546
7547                     /* Replace biv with its giv's reduced reg.  */
7548                     XEXP (x, 1-arg_operand) = v->new_reg;
7549                     /* Replace other operand with the other giv's
7550                        reduced reg.  */
7551                     XEXP (x, arg_operand) = tv->new_reg;
7552                     return 1;
7553                   }
7554             }
7555 #endif
7556         }
7557
7558       /* If we get here, the biv can't be eliminated.  */
7559       return 0;
7560
7561     case MEM:
7562       /* If this address is a DEST_ADDR giv, it doesn't matter if the
7563          biv is used in it, since it will be replaced.  */
7564       for (v = bl->giv; v; v = v->next_iv)
7565         if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
7566           return 1;
7567       break;
7568
7569     default:
7570       break;
7571     }
7572
7573   /* See if any subexpression fails elimination.  */
7574   fmt = GET_RTX_FORMAT (code);
7575   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7576     {
7577       switch (fmt[i])
7578         {
7579         case 'e':
7580           if (! maybe_eliminate_biv_1 (XEXP (x, i), insn, bl, 
7581                                        eliminate_p, where))
7582             return 0;
7583           break;
7584
7585         case 'E':
7586           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7587             if (! maybe_eliminate_biv_1 (XVECEXP (x, i, j), insn, bl,
7588                                          eliminate_p, where))
7589               return 0;
7590           break;
7591         }
7592     }
7593
7594   return 1;
7595 }  
7596 \f
7597 /* Return nonzero if the last use of REG
7598    is in an insn following INSN in the same basic block.  */
7599
7600 static int
7601 last_use_this_basic_block (reg, insn)
7602      rtx reg;
7603      rtx insn;
7604 {
7605   rtx n;
7606   for (n = insn;
7607        n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
7608        n = NEXT_INSN (n))
7609     {
7610       if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
7611         return 1;
7612     }
7613   return 0;
7614 }
7615 \f
7616 /* Called via `note_stores' to record the initial value of a biv.  Here we
7617    just record the location of the set and process it later.  */
7618
7619 static void
7620 record_initial (dest, set)
7621      rtx dest;
7622      rtx set;
7623 {
7624   struct iv_class *bl;
7625
7626   if (GET_CODE (dest) != REG
7627       || REGNO (dest) >= max_reg_before_loop
7628       || reg_iv_type[REGNO (dest)] != BASIC_INDUCT)
7629     return;
7630
7631   bl = reg_biv_class[REGNO (dest)];
7632
7633   /* If this is the first set found, record it.  */
7634   if (bl->init_insn == 0)
7635     {
7636       bl->init_insn = note_insn;
7637       bl->init_set = set;
7638     }
7639 }
7640 \f
7641 /* If any of the registers in X are "old" and currently have a last use earlier
7642    than INSN, update them to have a last use of INSN.  Their actual last use
7643    will be the previous insn but it will not have a valid uid_luid so we can't
7644    use it.  */
7645
7646 static void
7647 update_reg_last_use (x, insn)
7648      rtx x;
7649      rtx insn;
7650 {
7651   /* Check for the case where INSN does not have a valid luid.  In this case,
7652      there is no need to modify the regno_last_uid, as this can only happen
7653      when code is inserted after the loop_end to set a pseudo's final value,
7654      and hence this insn will never be the last use of x.  */
7655   if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
7656       && INSN_UID (insn) < max_uid_for_loop
7657       && uid_luid[REGNO_LAST_UID (REGNO (x))] < uid_luid[INSN_UID (insn)])
7658     REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
7659   else
7660     {
7661       register int i, j;
7662       register char *fmt = GET_RTX_FORMAT (GET_CODE (x));
7663       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
7664         {
7665           if (fmt[i] == 'e')
7666             update_reg_last_use (XEXP (x, i), insn);
7667           else if (fmt[i] == 'E')
7668             for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7669               update_reg_last_use (XVECEXP (x, i, j), insn);
7670         }
7671     }
7672 }
7673 \f
7674 /* Given a jump insn JUMP, return the condition that will cause it to branch
7675    to its JUMP_LABEL.  If the condition cannot be understood, or is an
7676    inequality floating-point comparison which needs to be reversed, 0 will
7677    be returned.
7678
7679    If EARLIEST is non-zero, it is a pointer to a place where the earliest
7680    insn used in locating the condition was found.  If a replacement test
7681    of the condition is desired, it should be placed in front of that
7682    insn and we will be sure that the inputs are still valid.
7683
7684    The condition will be returned in a canonical form to simplify testing by
7685    callers.  Specifically:
7686
7687    (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
7688    (2) Both operands will be machine operands; (cc0) will have been replaced.
7689    (3) If an operand is a constant, it will be the second operand.
7690    (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
7691        for GE, GEU, and LEU.  */
7692
7693 rtx
7694 get_condition (jump, earliest)
7695      rtx jump;
7696      rtx *earliest;
7697 {
7698   enum rtx_code code;
7699   rtx prev = jump;
7700   rtx set;
7701   rtx tem;
7702   rtx op0, op1;
7703   int reverse_code = 0;
7704   int did_reverse_condition = 0;
7705   enum machine_mode mode;
7706
7707   /* If this is not a standard conditional jump, we can't parse it.  */
7708   if (GET_CODE (jump) != JUMP_INSN
7709       || ! condjump_p (jump) || simplejump_p (jump))
7710     return 0;
7711
7712   code = GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 0));
7713   mode = GET_MODE (XEXP (SET_SRC (PATTERN (jump)), 0));
7714   op0 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 0);
7715   op1 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 1);
7716
7717   if (earliest)
7718     *earliest = jump;
7719
7720   /* If this branches to JUMP_LABEL when the condition is false, reverse
7721      the condition.  */
7722   if (GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 2)) == LABEL_REF
7723       && XEXP (XEXP (SET_SRC (PATTERN (jump)), 2), 0) == JUMP_LABEL (jump))
7724     code = reverse_condition (code), did_reverse_condition ^= 1;
7725
7726   /* If we are comparing a register with zero, see if the register is set
7727      in the previous insn to a COMPARE or a comparison operation.  Perform
7728      the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
7729      in cse.c  */
7730
7731   while (GET_RTX_CLASS (code) == '<' && op1 == CONST0_RTX (GET_MODE (op0)))
7732     {
7733       /* Set non-zero when we find something of interest.  */
7734       rtx x = 0;
7735
7736 #ifdef HAVE_cc0
7737       /* If comparison with cc0, import actual comparison from compare
7738          insn.  */
7739       if (op0 == cc0_rtx)
7740         {
7741           if ((prev = prev_nonnote_insn (prev)) == 0
7742               || GET_CODE (prev) != INSN
7743               || (set = single_set (prev)) == 0
7744               || SET_DEST (set) != cc0_rtx)
7745             return 0;
7746
7747           op0 = SET_SRC (set);
7748           op1 = CONST0_RTX (GET_MODE (op0));
7749           if (earliest)
7750             *earliest = prev;
7751         }
7752 #endif
7753
7754       /* If this is a COMPARE, pick up the two things being compared.  */
7755       if (GET_CODE (op0) == COMPARE)
7756         {
7757           op1 = XEXP (op0, 1);
7758           op0 = XEXP (op0, 0);
7759           continue;
7760         }
7761       else if (GET_CODE (op0) != REG)
7762         break;
7763
7764       /* Go back to the previous insn.  Stop if it is not an INSN.  We also
7765          stop if it isn't a single set or if it has a REG_INC note because
7766          we don't want to bother dealing with it.  */
7767
7768       if ((prev = prev_nonnote_insn (prev)) == 0
7769           || GET_CODE (prev) != INSN
7770           || FIND_REG_INC_NOTE (prev, 0)
7771           || (set = single_set (prev)) == 0)
7772         break;
7773
7774       /* If this is setting OP0, get what it sets it to if it looks
7775          relevant.  */
7776       if (rtx_equal_p (SET_DEST (set), op0))
7777         {
7778           enum machine_mode inner_mode = GET_MODE (SET_SRC (set));
7779
7780           /* ??? We may not combine comparisons done in a CCmode with
7781              comparisons not done in a CCmode.  This is to aid targets
7782              like Alpha that have an IEEE compliant EQ instruction, and
7783              a non-IEEE compliant BEQ instruction.  The use of CCmode is
7784              actually artificial, simply to prevent the combination, but
7785              should not affect other platforms.
7786
7787              However, we must allow VOIDmode comparisons to match either
7788              CCmode or non-CCmode comparison, because some ports have
7789              modeless comparisons inside branch patterns.
7790
7791              ??? This mode check should perhaps look more like the mode check
7792              in simplify_comparison in combine.  */
7793
7794           if ((GET_CODE (SET_SRC (set)) == COMPARE
7795                || (((code == NE
7796                      || (code == LT
7797                          && GET_MODE_CLASS (inner_mode) == MODE_INT
7798                          && (GET_MODE_BITSIZE (inner_mode)
7799                              <= HOST_BITS_PER_WIDE_INT)
7800                          && (STORE_FLAG_VALUE
7801                              & ((HOST_WIDE_INT) 1
7802                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
7803 #ifdef FLOAT_STORE_FLAG_VALUE
7804                      || (code == LT
7805                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
7806                          && FLOAT_STORE_FLAG_VALUE < 0)
7807 #endif
7808                      ))
7809                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'))
7810               && (((GET_MODE_CLASS (mode) == MODE_CC)
7811                    == (GET_MODE_CLASS (inner_mode) == MODE_CC))
7812                   || mode == VOIDmode || inner_mode == VOIDmode))
7813             x = SET_SRC (set);
7814           else if (((code == EQ
7815                      || (code == GE
7816                          && (GET_MODE_BITSIZE (inner_mode)
7817                              <= HOST_BITS_PER_WIDE_INT)
7818                          && GET_MODE_CLASS (inner_mode) == MODE_INT
7819                          && (STORE_FLAG_VALUE
7820                              & ((HOST_WIDE_INT) 1
7821                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
7822 #ifdef FLOAT_STORE_FLAG_VALUE
7823                      || (code == GE
7824                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
7825                          && FLOAT_STORE_FLAG_VALUE < 0)
7826 #endif
7827                      ))
7828                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'
7829                    && (((GET_MODE_CLASS (mode) == MODE_CC)
7830                         == (GET_MODE_CLASS (inner_mode) == MODE_CC))
7831                        || mode == VOIDmode || inner_mode == VOIDmode))
7832
7833             {
7834               /* We might have reversed a LT to get a GE here.  But this wasn't
7835                  actually the comparison of data, so we don't flag that we
7836                  have had to reverse the condition.  */
7837               did_reverse_condition ^= 1;
7838               reverse_code = 1;
7839               x = SET_SRC (set);
7840             }
7841           else
7842             break;
7843         }
7844
7845       else if (reg_set_p (op0, prev))
7846         /* If this sets OP0, but not directly, we have to give up.  */
7847         break;
7848
7849       if (x)
7850         {
7851           if (GET_RTX_CLASS (GET_CODE (x)) == '<')
7852             code = GET_CODE (x);
7853           if (reverse_code)
7854             {
7855               code = reverse_condition (code);
7856               did_reverse_condition ^= 1;
7857               reverse_code = 0;
7858             }
7859
7860           op0 = XEXP (x, 0), op1 = XEXP (x, 1);
7861           if (earliest)
7862             *earliest = prev;
7863         }
7864     }
7865
7866   /* If constant is first, put it last.  */
7867   if (CONSTANT_P (op0))
7868     code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
7869
7870   /* If OP0 is the result of a comparison, we weren't able to find what
7871      was really being compared, so fail.  */
7872   if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
7873     return 0;
7874
7875   /* Canonicalize any ordered comparison with integers involving equality
7876      if we can do computations in the relevant mode and we do not
7877      overflow.  */
7878
7879   if (GET_CODE (op1) == CONST_INT
7880       && GET_MODE (op0) != VOIDmode
7881       && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
7882     {
7883       HOST_WIDE_INT const_val = INTVAL (op1);
7884       unsigned HOST_WIDE_INT uconst_val = const_val;
7885       unsigned HOST_WIDE_INT max_val
7886         = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
7887
7888       switch (code)
7889         {
7890         case LE:
7891           if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
7892             code = LT,  op1 = GEN_INT (const_val + 1);
7893           break;
7894
7895         /* When cross-compiling, const_val might be sign-extended from
7896            BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
7897         case GE:
7898           if ((HOST_WIDE_INT) (const_val & max_val)
7899               != (((HOST_WIDE_INT) 1
7900                    << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
7901             code = GT, op1 = GEN_INT (const_val - 1);
7902           break;
7903
7904         case LEU:
7905           if (uconst_val < max_val)
7906             code = LTU, op1 = GEN_INT (uconst_val + 1);
7907           break;
7908
7909         case GEU:
7910           if (uconst_val != 0)
7911             code = GTU, op1 = GEN_INT (uconst_val - 1);
7912           break;
7913
7914         default:
7915           break;
7916         }
7917     }
7918
7919   /* If this was floating-point and we reversed anything other than an
7920      EQ or NE, return zero.  */
7921   if (TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
7922       && did_reverse_condition && code != NE && code != EQ
7923       && ! flag_fast_math
7924       && GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
7925     return 0;
7926
7927 #ifdef HAVE_cc0
7928   /* Never return CC0; return zero instead.  */
7929   if (op0 == cc0_rtx)
7930     return 0;
7931 #endif
7932
7933   return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
7934 }
7935
7936 /* Similar to above routine, except that we also put an invariant last
7937    unless both operands are invariants.  */
7938
7939 rtx
7940 get_condition_for_loop (x)
7941      rtx x;
7942 {
7943   rtx comparison = get_condition (x, NULL_PTR);
7944
7945   if (comparison == 0
7946       || ! invariant_p (XEXP (comparison, 0))
7947       || invariant_p (XEXP (comparison, 1)))
7948     return comparison;
7949
7950   return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
7951                          XEXP (comparison, 1), XEXP (comparison, 0));
7952 }
7953
7954 #ifdef HAVE_decrement_and_branch_on_count
7955 /* Instrument loop for insertion of bct instruction.  We distinguish between
7956    loops with compile-time bounds and those with run-time bounds. 
7957    Information from loop_iterations() is used to compute compile-time bounds.
7958    Run-time bounds should use loop preconditioning, but currently ignored.
7959  */
7960
7961 static void
7962 insert_bct (loop_start, loop_end)
7963      rtx loop_start, loop_end;
7964 {
7965   int i;
7966   unsigned HOST_WIDE_INT n_iterations;
7967
7968   int increment_direction, compare_direction;
7969
7970   /* If the loop condition is <= or >=, the number of iteration
7971       is 1 more than the range of the bounds of the loop.  */
7972   int add_iteration = 0;
7973
7974   enum machine_mode loop_var_mode = word_mode;
7975
7976   int loop_num = uid_loop_num [INSN_UID (loop_start)];
7977
7978   /* It's impossible to instrument a competely unrolled loop.  */
7979   if (loop_unroll_factor [loop_num] == -1)
7980     return;
7981
7982   /* Make sure that the count register is not in use.  */
7983   if (loop_used_count_register [loop_num])
7984     {
7985       if (loop_dump_stream)
7986         fprintf (loop_dump_stream,
7987                  "insert_bct %d: BCT instrumentation failed: count register already in use\n",
7988                  loop_num);
7989       return;
7990     }
7991
7992   /* Make sure that the function has no indirect jumps.  */
7993   if (indirect_jump_in_function)
7994     {
7995       if (loop_dump_stream)
7996         fprintf (loop_dump_stream,
7997                  "insert_bct %d: BCT instrumentation failed: indirect jump in function\n",
7998                  loop_num);
7999       return;
8000     }
8001
8002   /* Make sure that the last loop insn is a conditional jump.  */
8003   if (GET_CODE (PREV_INSN (loop_end)) != JUMP_INSN
8004       || ! condjump_p (PREV_INSN (loop_end))
8005       || simplejump_p (PREV_INSN (loop_end)))
8006     {
8007       if (loop_dump_stream)
8008         fprintf (loop_dump_stream,
8009                  "insert_bct %d: BCT instrumentation failed: invalid jump at loop end\n",
8010                  loop_num);
8011       return;
8012     }
8013
8014   /* Make sure that the loop does not contain a function call
8015      (the count register might be altered by the called function).  */
8016   if (loop_has_call)
8017     {
8018       if (loop_dump_stream)
8019         fprintf (loop_dump_stream,
8020                  "insert_bct %d: BCT instrumentation failed: function call in loop\n",
8021                  loop_num);
8022       return;
8023     }
8024
8025   /* Make sure that the loop does not jump via a table.
8026      (the count register might be used to perform the branch on table).  */
8027   if (loop_has_tablejump)
8028     {
8029       if (loop_dump_stream)
8030         fprintf (loop_dump_stream,
8031                  "insert_bct %d: BCT instrumentation failed: computed branch in the loop\n",
8032                  loop_num);
8033       return;
8034     }
8035
8036   /* Account for loop unrolling in instrumented iteration count.  */
8037   if (loop_unroll_factor [loop_num] > 1)
8038     n_iterations = loop_n_iterations / loop_unroll_factor [loop_num];
8039   else
8040     n_iterations = loop_n_iterations;
8041
8042   if (n_iterations != 0 && n_iterations < 3)
8043     {
8044       /* Allow an enclosing outer loop to benefit if possible.  */
8045       if (loop_dump_stream)
8046         fprintf (loop_dump_stream,
8047                  "insert_bct %d: Too few iterations to benefit from BCT optimization\n",
8048                  loop_num);
8049       return;
8050     }
8051
8052   /* Try to instrument the loop.  */
8053
8054   /* Handle the simpler case, where the bounds are known at compile time.  */
8055   if (n_iterations > 0)
8056     {
8057       /* Mark all enclosing loops that they cannot use count register.  */
8058       for (i = loop_num; i != -1; i = loop_outer_loop[i])
8059         loop_used_count_register[i] = 1;
8060       instrument_loop_bct (loop_start, loop_end, GEN_INT (n_iterations));
8061       return;
8062     }
8063
8064   /* Handle the more complex case, that the bounds are NOT known
8065      at compile time.  In this case we generate run_time calculation
8066      of the number of iterations.  */
8067
8068   if (loop_iteration_var == 0)
8069     {
8070       if (loop_dump_stream)
8071         fprintf (loop_dump_stream,
8072                  "insert_bct %d: BCT Runtime Instrumentation failed: no loop iteration variable found\n",
8073                  loop_num);
8074       return;
8075     }
8076
8077   if (GET_MODE_CLASS (GET_MODE (loop_iteration_var)) != MODE_INT
8078       || GET_MODE_SIZE (GET_MODE (loop_iteration_var)) != UNITS_PER_WORD)
8079     {
8080       if (loop_dump_stream)
8081         fprintf (loop_dump_stream,
8082                  "insert_bct %d: BCT Runtime Instrumentation failed: loop variable not integer\n",
8083                  loop_num);
8084       return;
8085     }
8086
8087   /* With runtime bounds, if the compare is of the form '!=' we give up */
8088   if (loop_comparison_code == NE)
8089     {
8090       if (loop_dump_stream)
8091         fprintf (loop_dump_stream,
8092                  "insert_bct %d: BCT Runtime Instrumentation failed: runtime bounds with != comparison\n",
8093                  loop_num);
8094       return;
8095     }
8096 /* Use common loop preconditioning code instead.  */
8097 #if 0
8098   else
8099     {
8100       /* We rely on the existence of run-time guard to ensure that the
8101          loop executes at least once.  */
8102       rtx sequence;
8103       rtx iterations_num_reg;
8104
8105       unsigned HOST_WIDE_INT increment_value_abs
8106         = INTVAL (increment) * increment_direction;
8107
8108       /* make sure that the increment is a power of two, otherwise (an
8109          expensive) divide is needed.  */
8110       if (exact_log2 (increment_value_abs) == -1)
8111         {
8112           if (loop_dump_stream)
8113             fprintf (loop_dump_stream,
8114                      "insert_bct: not instrumenting BCT because the increment is not power of 2\n");
8115           return;
8116         }
8117
8118       /* compute the number of iterations */
8119       start_sequence ();
8120       {
8121         rtx temp_reg;
8122
8123         /* Again, the number of iterations is calculated by:
8124            ;
8125            ;                  compare-val - initial-val + (increment -1) + additional-iteration
8126            ; num_iterations = -----------------------------------------------------------------
8127            ;                                           increment
8128          */
8129         /* ??? Do we have to call copy_rtx here before passing rtx to
8130            expand_binop?  */
8131         if (compare_direction > 0)
8132           {
8133             /* <, <= :the loop variable is increasing */
8134             temp_reg = expand_binop (loop_var_mode, sub_optab,
8135                                      comparison_value, initial_value,
8136                                      NULL_RTX, 0, OPTAB_LIB_WIDEN);
8137           }
8138         else
8139           {
8140             temp_reg = expand_binop (loop_var_mode, sub_optab,
8141                                      initial_value, comparison_value,
8142                                      NULL_RTX, 0, OPTAB_LIB_WIDEN);
8143           }
8144
8145         if (increment_value_abs - 1 + add_iteration != 0)
8146           temp_reg = expand_binop (loop_var_mode, add_optab, temp_reg,
8147                                    GEN_INT (increment_value_abs - 1
8148                                             + add_iteration),
8149                                    NULL_RTX, 0, OPTAB_LIB_WIDEN);
8150
8151         if (increment_value_abs != 1)
8152           {
8153             /* ??? This will generate an expensive divide instruction for
8154                most targets.  The original authors apparently expected this
8155                to be a shift, since they test for power-of-2 divisors above,
8156                but just naively generating a divide instruction will not give 
8157                a shift.  It happens to work for the PowerPC target because
8158                the rs6000.md file has a divide pattern that emits shifts.
8159                It will probably not work for any other target.  */
8160             iterations_num_reg = expand_binop (loop_var_mode, sdiv_optab,
8161                                                temp_reg,
8162                                                GEN_INT (increment_value_abs),
8163                                                NULL_RTX, 0, OPTAB_LIB_WIDEN);
8164           }
8165         else
8166           iterations_num_reg = temp_reg;
8167       }
8168       sequence = gen_sequence ();
8169       end_sequence ();
8170       emit_insn_before (sequence, loop_start);
8171       instrument_loop_bct (loop_start, loop_end, iterations_num_reg);
8172     }
8173
8174   return;
8175 #endif /* Complex case */
8176 }
8177
8178 /* Instrument loop by inserting a bct in it as follows:
8179    1. A new counter register is created.
8180    2. In the head of the loop the new variable is initialized to the value
8181    passed in the loop_num_iterations parameter.
8182    3. At the end of the loop, comparison of the register with 0 is generated.
8183    The created comparison follows the pattern defined for the
8184    decrement_and_branch_on_count insn, so this insn will be generated.
8185    4. The branch on the old variable are deleted.  The compare must remain
8186    because it might be used elsewhere.  If the loop-variable or condition
8187    register are used elsewhere, they will be eliminated by flow.  */
8188
8189 static void
8190 instrument_loop_bct (loop_start, loop_end, loop_num_iterations)
8191      rtx loop_start, loop_end;
8192      rtx loop_num_iterations;
8193 {
8194   rtx counter_reg;
8195   rtx start_label;
8196   rtx sequence;
8197
8198   if (HAVE_decrement_and_branch_on_count)
8199     {
8200       if (loop_dump_stream)
8201         {
8202           fputs ("instrument_bct: Inserting BCT (", loop_dump_stream);
8203           if (GET_CODE (loop_num_iterations) == CONST_INT)
8204             fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC,
8205                      INTVAL (loop_num_iterations));
8206           else
8207             fputs ("runtime", loop_dump_stream);
8208           fputs (" iterations)", loop_dump_stream);
8209         }
8210
8211       /* Discard original jump to continue loop.  Original compare result
8212          may still be live, so it cannot be discarded explicitly.  */
8213       delete_insn (PREV_INSN (loop_end));
8214
8215       /* Insert the label which will delimit the start of the loop.  */
8216       start_label = gen_label_rtx ();
8217       emit_label_after (start_label, loop_start);
8218
8219       /* Insert initialization of the count register into the loop header.  */
8220       start_sequence ();
8221       counter_reg = gen_reg_rtx (word_mode);
8222       emit_insn (gen_move_insn (counter_reg, loop_num_iterations));
8223       sequence = gen_sequence ();
8224       end_sequence ();
8225       emit_insn_before (sequence, loop_start);
8226
8227       /* Insert new comparison on the count register instead of the
8228          old one, generating the needed BCT pattern (that will be
8229          later recognized by assembly generation phase).  */
8230       emit_jump_insn_before (gen_decrement_and_branch_on_count (counter_reg,
8231                                                                 start_label),
8232                              loop_end);
8233       LABEL_NUSES (start_label)++;
8234     }
8235
8236 }
8237 #endif /* HAVE_decrement_and_branch_on_count */
8238
8239 /* Scan the function and determine whether it has indirect (computed) jumps.
8240
8241    This is taken mostly from flow.c; similar code exists elsewhere
8242    in the compiler.  It may be useful to put this into rtlanal.c.  */
8243 static int
8244 indirect_jump_in_function_p (start)
8245      rtx start;
8246 {
8247   rtx insn;
8248
8249   for (insn = start; insn; insn = NEXT_INSN (insn))
8250     if (computed_jump_p (insn))
8251       return 1;
8252
8253   return 0;
8254 }
8255
8256 /* Add MEM to the LOOP_MEMS array, if appropriate.  See the
8257    documentation for LOOP_MEMS for the definition of `appropriate'.
8258    This function is called from prescan_loop via for_each_rtx.  */
8259
8260 static int
8261 insert_loop_mem (mem, data)
8262      rtx *mem;
8263      void *data ATTRIBUTE_UNUSED;
8264 {
8265   int i;
8266   rtx m = *mem;
8267
8268   if (m == NULL_RTX)
8269     return 0;
8270
8271   switch (GET_CODE (m))
8272     {
8273     case MEM:
8274       break;
8275
8276     case CONST_DOUBLE:
8277       /* We're not interested in the MEM associated with a
8278          CONST_DOUBLE, so there's no need to traverse into this.  */
8279       return -1;
8280
8281     default:
8282       /* This is not a MEM.  */
8283       return 0;
8284     }
8285
8286   /* See if we've already seen this MEM.  */
8287   for (i = 0; i < loop_mems_idx; ++i)
8288     if (rtx_equal_p (m, loop_mems[i].mem)) 
8289       {
8290         if (GET_MODE (m) != GET_MODE (loop_mems[i].mem))
8291           /* The modes of the two memory accesses are different.  If
8292              this happens, something tricky is going on, and we just
8293              don't optimize accesses to this MEM.  */
8294           loop_mems[i].optimize = 0;
8295
8296         return 0;
8297       }
8298
8299   /* Resize the array, if necessary.  */
8300   if (loop_mems_idx == loop_mems_allocated) 
8301     {
8302       if (loop_mems_allocated != 0)
8303         loop_mems_allocated *= 2;
8304       else
8305         loop_mems_allocated = 32;
8306
8307       loop_mems = (loop_mem_info*) 
8308         xrealloc (loop_mems,
8309                   loop_mems_allocated * sizeof (loop_mem_info)); 
8310     }
8311
8312   /* Actually insert the MEM.  */
8313   loop_mems[loop_mems_idx].mem = m;
8314   /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
8315      because we can't put it in a register.  We still store it in the
8316      table, though, so that if we see the same address later, but in a
8317      non-BLK mode, we'll not think we can optimize it at that point.  */
8318   loop_mems[loop_mems_idx].optimize = (GET_MODE (m) != BLKmode);
8319   loop_mems[loop_mems_idx].reg = NULL_RTX;
8320   ++loop_mems_idx;
8321
8322   return 0;
8323 }
8324
8325 /* Like load_mems, but also ensures that N_TIMES_SET,
8326    MAY_NOT_OPTIMIZE, REG_SINGLE_USAGE, and INSN_COUNT have the correct
8327    values after load_mems.  */
8328
8329 static void
8330 load_mems_and_recount_loop_regs_set (scan_start, end, loop_top, start,
8331                                      reg_single_usage, insn_count)
8332      rtx scan_start;
8333      rtx end;
8334      rtx loop_top;
8335      rtx start;
8336      varray_type reg_single_usage;
8337      int *insn_count;
8338 {
8339   int nregs = max_reg_num ();
8340
8341   load_mems (scan_start, end, loop_top, start);
8342   
8343   /* Recalculate n_times_set and friends since load_mems may have
8344      created new registers.  */
8345   if (max_reg_num () > nregs)
8346     {
8347       int i;
8348       int old_nregs;
8349
8350       old_nregs = nregs;
8351       nregs = max_reg_num ();
8352
8353       if ((unsigned) nregs > n_times_set->num_elements)
8354         {
8355           /* Grow all the arrays.  */
8356           VARRAY_GROW (n_times_set, nregs);
8357           VARRAY_GROW (n_times_used, nregs);
8358           VARRAY_GROW (may_not_optimize, nregs);
8359           if (reg_single_usage)
8360             VARRAY_GROW (reg_single_usage, nregs);
8361         }
8362       /* Clear the arrays */
8363       bzero ((char *) &n_times_set->data, nregs * sizeof (int));
8364       bzero ((char *) &may_not_optimize->data, nregs * sizeof (char));
8365       if (reg_single_usage)
8366         bzero ((char *) &reg_single_usage->data, nregs * sizeof (rtx));
8367
8368       count_loop_regs_set (loop_top ? loop_top : start, end,
8369                            may_not_optimize, reg_single_usage,
8370                            insn_count, nregs); 
8371
8372       for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
8373         {
8374           VARRAY_CHAR (may_not_optimize, i) = 1;
8375           VARRAY_INT (n_times_set, i) = 1;
8376         }
8377       
8378 #ifdef AVOID_CCMODE_COPIES
8379       /* Don't try to move insns which set CC registers if we should not
8380          create CCmode register copies.  */
8381       for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
8382         if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
8383           VARRAY_CHAR (may_not_optimize, i) = 1;
8384 #endif
8385
8386       /* Set n_times_used for the new registers.  */
8387       bcopy ((char *) (&n_times_set->data.i[0] + old_nregs),
8388              (char *) (&n_times_used->data.i[0] + old_nregs),
8389              (nregs - old_nregs) * sizeof (int));
8390     }
8391 }
8392
8393 /* Move MEMs into registers for the duration of the loop.  SCAN_START
8394    is the first instruction in the loop (as it is executed).  The
8395    other parameters are as for next_insn_in_loop.  */
8396
8397 static void
8398 load_mems (scan_start, end, loop_top, start)
8399      rtx scan_start;
8400      rtx end;
8401      rtx loop_top;
8402      rtx start;
8403 {
8404   int maybe_never = 0;
8405   int i;
8406   rtx p;
8407   rtx label = NULL_RTX;
8408   rtx end_label;
8409
8410   if (loop_mems_idx > 0) 
8411     {
8412       /* Nonzero if the next instruction may never be executed.  */
8413       int next_maybe_never = 0;
8414
8415       /* Check to see if it's possible that some instructions in the
8416          loop are never executed.  */
8417       for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top); 
8418            p != NULL_RTX && !maybe_never; 
8419            p = next_insn_in_loop (p, scan_start, end, loop_top))
8420         {
8421           if (GET_CODE (p) == CODE_LABEL)
8422             maybe_never = 1;
8423           else if (GET_CODE (p) == JUMP_INSN
8424                    /* If we enter the loop in the middle, and scan
8425                       around to the beginning, don't set maybe_never
8426                       for that.  This must be an unconditional jump,
8427                       otherwise the code at the top of the loop might
8428                       never be executed.  Unconditional jumps are
8429                       followed a by barrier then loop end.  */
8430                    && ! (GET_CODE (p) == JUMP_INSN 
8431                          && JUMP_LABEL (p) == loop_top
8432                          && NEXT_INSN (NEXT_INSN (p)) == end
8433                          && simplejump_p (p)))
8434             {
8435               if (!condjump_p (p))
8436                 /* Something complicated.  */
8437                 maybe_never = 1;
8438               else
8439                 /* If there are any more instructions in the loop, they
8440                    might not be reached.  */
8441                 next_maybe_never = 1; 
8442             } 
8443           else if (next_maybe_never)
8444             maybe_never = 1;
8445         }
8446
8447       /* Actually move the MEMs.  */
8448       for (i = 0; i < loop_mems_idx; ++i) 
8449         {
8450           int j;
8451           int written = 0;
8452           rtx reg;
8453           rtx mem = loop_mems[i].mem;
8454
8455           if (MEM_VOLATILE_P (mem) 
8456               || invariant_p (XEXP (mem, 0)) != 1)
8457             /* There's no telling whether or not MEM is modified.  */
8458             loop_mems[i].optimize = 0;
8459
8460           /* Go through the MEMs written to in the loop to see if this
8461              one is aliased by one of them.  */
8462           for (j = 0; j < loop_store_mems_idx; ++j) 
8463             {
8464               if (rtx_equal_p (mem, loop_store_mems[j]))
8465                 written = 1;
8466               else if (true_dependence (loop_store_mems[j], VOIDmode,
8467                                         mem, rtx_varies_p))
8468                 {
8469                   /* MEM is indeed aliased by this store.  */
8470                   loop_mems[i].optimize = 0;
8471                   break;
8472                 }
8473             }
8474           
8475           /* If this MEM is written to, we must be sure that there
8476              are no reads from another MEM that aliases this one.  */ 
8477           if (loop_mems[i].optimize && written)
8478             {
8479               int j;
8480
8481               for (j = 0; j < loop_mems_idx; ++j)
8482                 {
8483                   if (j == i)
8484                     continue;
8485                   else if (true_dependence (mem,
8486                                             VOIDmode,
8487                                             loop_mems[j].mem,
8488                                             rtx_varies_p))
8489                     {
8490                       /* It's not safe to hoist loop_mems[i] out of
8491                          the loop because writes to it might not be
8492                          seen by reads from loop_mems[j].  */
8493                       loop_mems[i].optimize = 0;
8494                       break;
8495                     }
8496                 }
8497             }
8498
8499           if (maybe_never && may_trap_p (mem))
8500             /* We can't access the MEM outside the loop; it might
8501                cause a trap that wouldn't have happened otherwise.  */
8502             loop_mems[i].optimize = 0;
8503           
8504           if (!loop_mems[i].optimize)
8505             /* We thought we were going to lift this MEM out of the
8506                loop, but later discovered that we could not.  */
8507             continue;
8508
8509           /* Allocate a pseudo for this MEM.  We set REG_USERVAR_P in
8510              order to keep scan_loop from moving stores to this MEM
8511              out of the loop just because this REG is neither a
8512              user-variable nor used in the loop test.  */
8513           reg = gen_reg_rtx (GET_MODE (mem));
8514           REG_USERVAR_P (reg) = 1;
8515           loop_mems[i].reg = reg;
8516
8517           /* Now, replace all references to the MEM with the
8518              corresponding pesudos.  */
8519           for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top);
8520                p != NULL_RTX;
8521                p = next_insn_in_loop (p, scan_start, end, loop_top))
8522             {
8523               rtx_and_int ri;
8524               ri.r = p;
8525               ri.i = i;
8526               for_each_rtx (&p, replace_loop_mem, &ri);
8527             }
8528
8529           if (!apply_change_group ())
8530             /* We couldn't replace all occurrences of the MEM.  */
8531             loop_mems[i].optimize = 0;
8532           else
8533             {
8534               rtx set;
8535
8536               /* Load the memory immediately before START, which is
8537                  the NOTE_LOOP_BEG.  */
8538               set = gen_rtx_SET (GET_MODE (reg), reg, mem);
8539               emit_insn_before (set, start);
8540
8541               if (written)
8542                 {
8543                   if (label == NULL_RTX)
8544                     {
8545                       /* We must compute the former
8546                          right-after-the-end label before we insert
8547                          the new one.  */
8548                       end_label = next_label (end);
8549                       label = gen_label_rtx ();
8550                       emit_label_after (label, end);
8551                     }
8552
8553                   /* Store the memory immediately after END, which is
8554                    the NOTE_LOOP_END.  */
8555                   set = gen_rtx_SET (GET_MODE (reg), copy_rtx (mem), reg); 
8556                   emit_insn_after (set, label);
8557                 }
8558
8559               if (loop_dump_stream)
8560                 {
8561                   fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
8562                            REGNO (reg), (written ? "r/w" : "r/o"));
8563                   print_rtl (loop_dump_stream, mem);
8564                   fputc ('\n', loop_dump_stream);
8565                 }
8566             }
8567         }
8568     }
8569
8570   if (label != NULL_RTX)
8571     {
8572       /* Now, we need to replace all references to the previous exit
8573          label with the new one.  */
8574       rtx_pair rr; 
8575       rr.r1 = end_label;
8576       rr.r2 = label;
8577
8578       for (p = start; p != end; p = NEXT_INSN (p))
8579         {
8580           for_each_rtx (&p, replace_label, &rr);
8581
8582           /* If this is a JUMP_INSN, then we also need to fix the JUMP_LABEL
8583              field.  This is not handled by for_each_rtx because it doesn't
8584              handle unprinted ('0') fields.  We need to update JUMP_LABEL
8585              because the immediately following unroll pass will use it.
8586              replace_label would not work anyways, because that only handles
8587              LABEL_REFs.  */
8588           if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == end_label)
8589             JUMP_LABEL (p) = label;
8590         }
8591     }
8592 }
8593
8594 /* Replace MEM with its associated pseudo register.  This function is
8595    called from load_mems via for_each_rtx.  DATA is actually an
8596    rtx_and_int * describing the instruction currently being scanned
8597    and the MEM we are currently replacing.  */
8598
8599 static int
8600 replace_loop_mem (mem, data)
8601      rtx *mem;
8602      void *data;
8603 {
8604   rtx_and_int *ri; 
8605   rtx insn;
8606   int i;
8607   rtx m = *mem;
8608
8609   if (m == NULL_RTX)
8610     return 0;
8611
8612   switch (GET_CODE (m))
8613     {
8614     case MEM:
8615       break;
8616
8617     case CONST_DOUBLE:
8618       /* We're not interested in the MEM associated with a
8619          CONST_DOUBLE, so there's no need to traverse into one.  */
8620       return -1;
8621
8622     default:
8623       /* This is not a MEM.  */
8624       return 0;
8625     }
8626
8627   ri = (rtx_and_int*) data;
8628   i = ri->i;
8629
8630   if (!rtx_equal_p (loop_mems[i].mem, m))
8631     /* This is not the MEM we are currently replacing.  */
8632     return 0;
8633
8634   insn = ri->r;
8635
8636   /* Actually replace the MEM.  */
8637   validate_change (insn, mem, loop_mems[i].reg, 1);
8638
8639   return 0;
8640 }
8641
8642 /* Replace occurrences of the old exit label for the loop with the new
8643    one.  DATA is an rtx_pair containing the old and new labels,
8644    respectively.  */
8645
8646 static int
8647 replace_label (x, data)
8648      rtx *x;
8649      void *data;
8650 {
8651   rtx l = *x;
8652   rtx old_label = ((rtx_pair*) data)->r1;
8653   rtx new_label = ((rtx_pair*) data)->r2;
8654
8655   if (l == NULL_RTX)
8656     return 0;
8657
8658   if (GET_CODE (l) != LABEL_REF)
8659     return 0;
8660
8661   if (XEXP (l, 0) != old_label)
8662     return 0;
8663   
8664   XEXP (l, 0) = new_label;
8665   ++LABEL_NUSES (new_label);
8666   --LABEL_NUSES (old_label);
8667
8668   return 0;
8669 }
8670