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