OSDN Git Service

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