OSDN Git Service

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