OSDN Git Service

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