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