OSDN Git Service

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