OSDN Git Service

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