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