OSDN Git Service

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