OSDN Git Service

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