OSDN Git Service

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