OSDN Git Service

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