OSDN Git Service

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