* gcc_update: libjava/configure.in -> configure.ac.
[official-gcc.git] / gcc / loop.c
blobc8a16e0850d8eb4f36351fcb566348e1b5ef8dd6
1 /* Perform various loop optimizations, including strength reduction.
2 Copyright (C) 1987, 1988, 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA. */
22 /* This is the loop optimization pass of the compiler.
23 It finds invariant computations within loops and moves them
24 to the beginning of the loop. Then it identifies basic and
25 general induction variables.
27 Basic induction variables (BIVs) are a pseudo registers which are set within
28 a loop only by incrementing or decrementing its value. General induction
29 variables (GIVs) are pseudo registers with a value which is a linear function
30 of a basic induction variable. BIVs are recognized by `basic_induction_var';
31 GIVs by `general_induction_var'.
33 Once induction variables are identified, strength reduction is applied to the
34 general induction variables, and induction variable elimination is applied to
35 the basic induction variables.
37 It also finds cases where
38 a register is set within the loop by zero-extending a narrower value
39 and changes these to zero the entire register once before the loop
40 and merely copy the low part within the loop.
42 Most of the complexity is in heuristics to decide when it is worth
43 while to do these things. */
45 #include "config.h"
46 #include "system.h"
47 #include "coretypes.h"
48 #include "tm.h"
49 #include "rtl.h"
50 #include "tm_p.h"
51 #include "function.h"
52 #include "expr.h"
53 #include "hard-reg-set.h"
54 #include "basic-block.h"
55 #include "insn-config.h"
56 #include "regs.h"
57 #include "recog.h"
58 #include "flags.h"
59 #include "real.h"
60 #include "loop.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"
70 /* Not really meaningful values, but at least something. */
71 #ifndef SIMULTANEOUS_PREFETCHES
72 #define SIMULTANEOUS_PREFETCHES 3
73 #endif
74 #ifndef PREFETCH_BLOCK
75 #define PREFETCH_BLOCK 32
76 #endif
77 #ifndef HAVE_prefetch
78 #define HAVE_prefetch 0
79 #define CODE_FOR_prefetch 0
80 #define gen_prefetch(a,b,c) (abort(), NULL_RTX)
81 #endif
83 /* Give up the prefetch optimizations once we exceed a given threshold.
84 It is unlikely that we would be able to optimize something in a loop
85 with so many detected prefetches. */
86 #define MAX_PREFETCHES 100
87 /* The number of prefetch blocks that are beneficial to fetch at once before
88 a loop with a known (and low) iteration count. */
89 #define PREFETCH_BLOCKS_BEFORE_LOOP_MAX 6
90 /* For very tiny loops it is not worthwhile to prefetch even before the loop,
91 since it is likely that the data are already in the cache. */
92 #define PREFETCH_BLOCKS_BEFORE_LOOP_MIN 2
94 /* Parameterize some prefetch heuristics so they can be turned on and off
95 easily for performance testing on new architectures. These can be
96 defined in target-dependent files. */
98 /* Prefetch is worthwhile only when loads/stores are dense. */
99 #ifndef PREFETCH_ONLY_DENSE_MEM
100 #define PREFETCH_ONLY_DENSE_MEM 1
101 #endif
103 /* Define what we mean by "dense" loads and stores; This value divided by 256
104 is the minimum percentage of memory references that worth prefetching. */
105 #ifndef PREFETCH_DENSE_MEM
106 #define PREFETCH_DENSE_MEM 220
107 #endif
109 /* Do not prefetch for a loop whose iteration count is known to be low. */
110 #ifndef PREFETCH_NO_LOW_LOOPCNT
111 #define PREFETCH_NO_LOW_LOOPCNT 1
112 #endif
114 /* Define what we mean by a "low" iteration count. */
115 #ifndef PREFETCH_LOW_LOOPCNT
116 #define PREFETCH_LOW_LOOPCNT 32
117 #endif
119 /* Do not prefetch for a loop that contains a function call; such a loop is
120 probably not an internal loop. */
121 #ifndef PREFETCH_NO_CALL
122 #define PREFETCH_NO_CALL 1
123 #endif
125 /* Do not prefetch accesses with an extreme stride. */
126 #ifndef PREFETCH_NO_EXTREME_STRIDE
127 #define PREFETCH_NO_EXTREME_STRIDE 1
128 #endif
130 /* Define what we mean by an "extreme" stride. */
131 #ifndef PREFETCH_EXTREME_STRIDE
132 #define PREFETCH_EXTREME_STRIDE 4096
133 #endif
135 /* Define a limit to how far apart indices can be and still be merged
136 into a single prefetch. */
137 #ifndef PREFETCH_EXTREME_DIFFERENCE
138 #define PREFETCH_EXTREME_DIFFERENCE 4096
139 #endif
141 /* Issue prefetch instructions before the loop to fetch data to be used
142 in the first few loop iterations. */
143 #ifndef PREFETCH_BEFORE_LOOP
144 #define PREFETCH_BEFORE_LOOP 1
145 #endif
147 /* Do not handle reversed order prefetches (negative stride). */
148 #ifndef PREFETCH_NO_REVERSE_ORDER
149 #define PREFETCH_NO_REVERSE_ORDER 1
150 #endif
152 /* Prefetch even if the GIV is in conditional code. */
153 #ifndef PREFETCH_CONDITIONAL
154 #define PREFETCH_CONDITIONAL 1
155 #endif
157 #define LOOP_REG_LIFETIME(LOOP, REGNO) \
158 ((REGNO_LAST_LUID (REGNO) - REGNO_FIRST_LUID (REGNO)))
160 #define LOOP_REG_GLOBAL_P(LOOP, REGNO) \
161 ((REGNO_LAST_LUID (REGNO) > INSN_LUID ((LOOP)->end) \
162 || REGNO_FIRST_LUID (REGNO) < INSN_LUID ((LOOP)->start)))
164 #define LOOP_REGNO_NREGS(REGNO, SET_DEST) \
165 ((REGNO) < FIRST_PSEUDO_REGISTER \
166 ? (int) hard_regno_nregs[(REGNO)][GET_MODE (SET_DEST)] : 1)
169 /* Vector mapping INSN_UIDs to luids.
170 The luids are like uids but increase monotonically always.
171 We use them to see whether a jump comes from outside a given loop. */
173 int *uid_luid;
175 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
176 number the insn is contained in. */
178 struct loop **uid_loop;
180 /* 1 + largest uid of any insn. */
182 int max_uid_for_loop;
184 /* Number of loops detected in current function. Used as index to the
185 next few tables. */
187 static int max_loop_num;
189 /* Bound on pseudo register number before loop optimization.
190 A pseudo has valid regscan info if its number is < max_reg_before_loop. */
191 unsigned int max_reg_before_loop;
193 /* The value to pass to the next call of reg_scan_update. */
194 static int loop_max_reg;
196 /* During the analysis of a loop, a chain of `struct movable's
197 is made to record all the movable insns found.
198 Then the entire chain can be scanned to decide which to move. */
200 struct movable
202 rtx insn; /* A movable insn */
203 rtx set_src; /* The expression this reg is set from. */
204 rtx set_dest; /* The destination of this SET. */
205 rtx dependencies; /* When INSN is libcall, this is an EXPR_LIST
206 of any registers used within the LIBCALL. */
207 int consec; /* Number of consecutive following insns
208 that must be moved with this one. */
209 unsigned int regno; /* The register it sets */
210 short lifetime; /* lifetime of that register;
211 may be adjusted when matching movables
212 that load the same value are found. */
213 short savings; /* Number of insns we can move for this reg,
214 including other movables that force this
215 or match this one. */
216 ENUM_BITFIELD(machine_mode) savemode : 8; /* Nonzero means it is a mode for
217 a low part that we should avoid changing when
218 clearing the rest of the reg. */
219 unsigned int cond : 1; /* 1 if only conditionally movable */
220 unsigned int force : 1; /* 1 means MUST move this insn */
221 unsigned int global : 1; /* 1 means reg is live outside this loop */
222 /* If PARTIAL is 1, GLOBAL means something different:
223 that the reg is live outside the range from where it is set
224 to the following label. */
225 unsigned int done : 1; /* 1 inhibits further processing of this */
227 unsigned int partial : 1; /* 1 means this reg is used for zero-extending.
228 In particular, moving it does not make it
229 invariant. */
230 unsigned int move_insn : 1; /* 1 means that we call emit_move_insn to
231 load SRC, rather than copying INSN. */
232 unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
233 first insn of a consecutive sets group. */
234 unsigned int is_equiv : 1; /* 1 means a REG_EQUIV is present on INSN. */
235 unsigned int insert_temp : 1; /* 1 means we copy to a new pseudo and replace
236 the original insn with a copy from that
237 pseudo, rather than deleting it. */
238 struct movable *match; /* First entry for same value */
239 struct movable *forces; /* An insn that must be moved if this is */
240 struct movable *next;
244 FILE *loop_dump_stream;
246 /* Forward declarations. */
248 static void invalidate_loops_containing_label (rtx);
249 static void find_and_verify_loops (rtx, struct loops *);
250 static void mark_loop_jump (rtx, struct loop *);
251 static void prescan_loop (struct loop *);
252 static int reg_in_basic_block_p (rtx, rtx);
253 static int consec_sets_invariant_p (const struct loop *, rtx, int, rtx);
254 static int labels_in_range_p (rtx, int);
255 static void count_one_set (struct loop_regs *, rtx, rtx, rtx *);
256 static void note_addr_stored (rtx, rtx, void *);
257 static void note_set_pseudo_multiple_uses (rtx, rtx, void *);
258 static int loop_reg_used_before_p (const struct loop *, rtx, rtx);
259 static rtx find_regs_nested (rtx, rtx);
260 static void scan_loop (struct loop*, int);
261 #if 0
262 static void replace_call_address (rtx, rtx, rtx);
263 #endif
264 static rtx skip_consec_insns (rtx, int);
265 static int libcall_benefit (rtx);
266 static rtx libcall_other_reg (rtx, rtx);
267 static void record_excess_regs (rtx, rtx, rtx *);
268 static void ignore_some_movables (struct loop_movables *);
269 static void force_movables (struct loop_movables *);
270 static void combine_movables (struct loop_movables *, struct loop_regs *);
271 static int num_unmoved_movables (const struct loop *);
272 static int regs_match_p (rtx, rtx, struct loop_movables *);
273 static int rtx_equal_for_loop_p (rtx, rtx, struct loop_movables *,
274 struct loop_regs *);
275 static void add_label_notes (rtx, rtx);
276 static void move_movables (struct loop *loop, struct loop_movables *, int,
277 int);
278 static void loop_movables_add (struct loop_movables *, struct movable *);
279 static void loop_movables_free (struct loop_movables *);
280 static int count_nonfixed_reads (const struct loop *, rtx);
281 static void loop_bivs_find (struct loop *);
282 static void loop_bivs_init_find (struct loop *);
283 static void loop_bivs_check (struct loop *);
284 static void loop_givs_find (struct loop *);
285 static void loop_givs_check (struct loop *);
286 static int loop_biv_eliminable_p (struct loop *, struct iv_class *, int, int);
287 static int loop_giv_reduce_benefit (struct loop *, struct iv_class *,
288 struct induction *, rtx);
289 static void loop_givs_dead_check (struct loop *, struct iv_class *);
290 static void loop_givs_reduce (struct loop *, struct iv_class *);
291 static void loop_givs_rescan (struct loop *, struct iv_class *, rtx *);
292 static void loop_ivs_free (struct loop *);
293 static void strength_reduce (struct loop *, int);
294 static void find_single_use_in_loop (struct loop_regs *, rtx, rtx);
295 static int valid_initial_value_p (rtx, rtx, int, rtx);
296 static void find_mem_givs (const struct loop *, rtx, rtx, int, int);
297 static void record_biv (struct loop *, struct induction *, rtx, rtx, rtx,
298 rtx, rtx *, int, int);
299 static void check_final_value (const struct loop *, struct induction *);
300 static void loop_ivs_dump (const struct loop *, FILE *, int);
301 static void loop_iv_class_dump (const struct iv_class *, FILE *, int);
302 static void loop_biv_dump (const struct induction *, FILE *, int);
303 static void loop_giv_dump (const struct induction *, FILE *, int);
304 static void record_giv (const struct loop *, struct induction *, rtx, rtx,
305 rtx, rtx, rtx, rtx, int, enum g_types, int, int,
306 rtx *);
307 static void update_giv_derive (const struct loop *, rtx);
308 static void check_ext_dependent_givs (const struct loop *, struct iv_class *);
309 static int basic_induction_var (const struct loop *, rtx, enum machine_mode,
310 rtx, rtx, rtx *, rtx *, rtx **);
311 static rtx simplify_giv_expr (const struct loop *, rtx, rtx *, int *);
312 static int general_induction_var (const struct loop *loop, rtx, rtx *, rtx *,
313 rtx *, rtx *, int, int *, enum machine_mode);
314 static int consec_sets_giv (const struct loop *, int, rtx, rtx, rtx, rtx *,
315 rtx *, rtx *, rtx *);
316 static int check_dbra_loop (struct loop *, int);
317 static rtx express_from_1 (rtx, rtx, rtx);
318 static rtx combine_givs_p (struct induction *, struct induction *);
319 static int cmp_combine_givs_stats (const void *, const void *);
320 static void combine_givs (struct loop_regs *, struct iv_class *);
321 static int product_cheap_p (rtx, rtx);
322 static int maybe_eliminate_biv (const struct loop *, struct iv_class *, int,
323 int, int);
324 static int maybe_eliminate_biv_1 (const struct loop *, rtx, rtx,
325 struct iv_class *, int, basic_block, rtx);
326 static int last_use_this_basic_block (rtx, rtx);
327 static void record_initial (rtx, rtx, void *);
328 static void update_reg_last_use (rtx, rtx);
329 static rtx next_insn_in_loop (const struct loop *, rtx);
330 static void loop_regs_scan (const struct loop *, int);
331 static int count_insns_in_loop (const struct loop *);
332 static int find_mem_in_note_1 (rtx *, void *);
333 static rtx find_mem_in_note (rtx);
334 static void load_mems (const struct loop *);
335 static int insert_loop_mem (rtx *, void *);
336 static int replace_loop_mem (rtx *, void *);
337 static void replace_loop_mems (rtx, rtx, rtx, int);
338 static int replace_loop_reg (rtx *, void *);
339 static void replace_loop_regs (rtx insn, rtx, rtx);
340 static void note_reg_stored (rtx, rtx, void *);
341 static void try_copy_prop (const struct loop *, rtx, unsigned int);
342 static void try_swap_copy_prop (const struct loop *, rtx, unsigned int);
343 static rtx check_insn_for_givs (struct loop *, rtx, int, int);
344 static rtx check_insn_for_bivs (struct loop *, rtx, int, int);
345 static rtx gen_add_mult (rtx, rtx, rtx, rtx);
346 static void loop_regs_update (const struct loop *, rtx);
347 static int iv_add_mult_cost (rtx, rtx, rtx, rtx);
349 static rtx loop_insn_emit_after (const struct loop *, basic_block, rtx, rtx);
350 static rtx loop_call_insn_emit_before (const struct loop *, basic_block,
351 rtx, rtx);
352 static rtx loop_call_insn_hoist (const struct loop *, rtx);
353 static rtx loop_insn_sink_or_swim (const struct loop *, rtx);
355 static void loop_dump_aux (const struct loop *, FILE *, int);
356 static void loop_delete_insns (rtx, rtx);
357 static HOST_WIDE_INT remove_constant_addition (rtx *);
358 static rtx gen_load_of_final_value (rtx, rtx);
359 void debug_ivs (const struct loop *);
360 void debug_iv_class (const struct iv_class *);
361 void debug_biv (const struct induction *);
362 void debug_giv (const struct induction *);
363 void debug_loop (const struct loop *);
364 void debug_loops (const struct loops *);
366 typedef struct loop_replace_args
368 rtx match;
369 rtx replacement;
370 rtx insn;
371 } loop_replace_args;
373 /* Nonzero iff INSN is between START and END, inclusive. */
374 #define INSN_IN_RANGE_P(INSN, START, END) \
375 (INSN_UID (INSN) < max_uid_for_loop \
376 && INSN_LUID (INSN) >= INSN_LUID (START) \
377 && INSN_LUID (INSN) <= INSN_LUID (END))
379 /* Indirect_jump_in_function is computed once per function. */
380 static int indirect_jump_in_function;
381 static int indirect_jump_in_function_p (rtx);
383 static int compute_luids (rtx, rtx, int);
385 static int biv_elimination_giv_has_0_offset (struct induction *,
386 struct induction *, rtx);
388 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
389 copy the value of the strength reduced giv to its original register. */
390 static int copy_cost;
392 /* Cost of using a register, to normalize the benefits of a giv. */
393 static int reg_address_cost;
395 void
396 init_loop (void)
398 rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
400 reg_address_cost = address_cost (reg, SImode);
402 copy_cost = COSTS_N_INSNS (1);
405 /* Compute the mapping from uids to luids.
406 LUIDs are numbers assigned to insns, like uids,
407 except that luids increase monotonically through the code.
408 Start at insn START and stop just before END. Assign LUIDs
409 starting with PREV_LUID + 1. Return the last assigned LUID + 1. */
410 static int
411 compute_luids (rtx start, rtx end, int prev_luid)
413 int i;
414 rtx insn;
416 for (insn = start, i = prev_luid; insn != end; insn = NEXT_INSN (insn))
418 if (INSN_UID (insn) >= max_uid_for_loop)
419 continue;
420 /* Don't assign luids to line-number NOTEs, so that the distance in
421 luids between two insns is not affected by -g. */
422 if (!NOTE_P (insn)
423 || NOTE_LINE_NUMBER (insn) <= 0)
424 uid_luid[INSN_UID (insn)] = ++i;
425 else
426 /* Give a line number note the same luid as preceding insn. */
427 uid_luid[INSN_UID (insn)] = i;
429 return i + 1;
432 /* Entry point of this file. Perform loop optimization
433 on the current function. F is the first insn of the function
434 and DUMPFILE is a stream for output of a trace of actions taken
435 (or 0 if none should be output). */
437 void
438 loop_optimize (rtx f, FILE *dumpfile, int flags)
440 rtx insn;
441 int i;
442 struct loops loops_data;
443 struct loops *loops = &loops_data;
444 struct loop_info *loops_info;
446 loop_dump_stream = dumpfile;
448 init_recog_no_volatile ();
450 max_reg_before_loop = max_reg_num ();
451 loop_max_reg = max_reg_before_loop;
453 regs_may_share = 0;
455 /* Count the number of loops. */
457 max_loop_num = 0;
458 for (insn = f; insn; insn = NEXT_INSN (insn))
460 if (NOTE_P (insn)
461 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
462 max_loop_num++;
465 /* Don't waste time if no loops. */
466 if (max_loop_num == 0)
467 return;
469 loops->num = max_loop_num;
471 /* Get size to use for tables indexed by uids.
472 Leave some space for labels allocated by find_and_verify_loops. */
473 max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
475 uid_luid = xcalloc (max_uid_for_loop, sizeof (int));
476 uid_loop = xcalloc (max_uid_for_loop, sizeof (struct loop *));
478 /* Allocate storage for array of loops. */
479 loops->array = xcalloc (loops->num, sizeof (struct loop));
481 /* Find and process each loop.
482 First, find them, and record them in order of their beginnings. */
483 find_and_verify_loops (f, loops);
485 /* Allocate and initialize auxiliary loop information. */
486 loops_info = xcalloc (loops->num, sizeof (struct loop_info));
487 for (i = 0; i < (int) loops->num; i++)
488 loops->array[i].aux = loops_info + i;
490 /* Now find all register lifetimes. This must be done after
491 find_and_verify_loops, because it might reorder the insns in the
492 function. */
493 reg_scan (f, max_reg_before_loop, 1);
495 /* This must occur after reg_scan so that registers created by gcse
496 will have entries in the register tables.
498 We could have added a call to reg_scan after gcse_main in toplev.c,
499 but moving this call to init_alias_analysis is more efficient. */
500 init_alias_analysis ();
502 /* See if we went too far. Note that get_max_uid already returns
503 one more that the maximum uid of all insn. */
504 if (get_max_uid () > max_uid_for_loop)
505 abort ();
506 /* Now reset it to the actual size we need. See above. */
507 max_uid_for_loop = get_max_uid ();
509 /* find_and_verify_loops has already called compute_luids, but it
510 might have rearranged code afterwards, so we need to recompute
511 the luids now. */
512 compute_luids (f, NULL_RTX, 0);
514 /* Don't leave gaps in uid_luid for insns that have been
515 deleted. It is possible that the first or last insn
516 using some register has been deleted by cross-jumping.
517 Make sure that uid_luid for that former insn's uid
518 points to the general area where that insn used to be. */
519 for (i = 0; i < max_uid_for_loop; i++)
521 uid_luid[0] = uid_luid[i];
522 if (uid_luid[0] != 0)
523 break;
525 for (i = 0; i < max_uid_for_loop; i++)
526 if (uid_luid[i] == 0)
527 uid_luid[i] = uid_luid[i - 1];
529 /* Determine if the function has indirect jump. On some systems
530 this prevents low overhead loop instructions from being used. */
531 indirect_jump_in_function = indirect_jump_in_function_p (f);
533 /* Now scan the loops, last ones first, since this means inner ones are done
534 before outer ones. */
535 for (i = max_loop_num - 1; i >= 0; i--)
537 struct loop *loop = &loops->array[i];
539 if (! loop->invalid && loop->end)
541 scan_loop (loop, flags);
542 ggc_collect ();
546 end_alias_analysis ();
548 /* Clean up. */
549 for (i = 0; i < (int) loops->num; i++)
550 free (loops_info[i].mems);
552 free (uid_luid);
553 free (uid_loop);
554 free (loops_info);
555 free (loops->array);
558 /* Returns the next insn, in execution order, after INSN. START and
559 END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
560 respectively. LOOP->TOP, if non-NULL, is the top of the loop in the
561 insn-stream; it is used with loops that are entered near the
562 bottom. */
564 static rtx
565 next_insn_in_loop (const struct loop *loop, rtx insn)
567 insn = NEXT_INSN (insn);
569 if (insn == loop->end)
571 if (loop->top)
572 /* Go to the top of the loop, and continue there. */
573 insn = loop->top;
574 else
575 /* We're done. */
576 insn = NULL_RTX;
579 if (insn == loop->scan_start)
580 /* We're done. */
581 insn = NULL_RTX;
583 return insn;
586 /* Find any register references hidden inside X and add them to
587 the dependency list DEPS. This is used to look inside CLOBBER (MEM
588 when checking whether a PARALLEL can be pulled out of a loop. */
590 static rtx
591 find_regs_nested (rtx deps, rtx x)
593 enum rtx_code code = GET_CODE (x);
594 if (code == REG)
595 deps = gen_rtx_EXPR_LIST (VOIDmode, x, deps);
596 else
598 const char *fmt = GET_RTX_FORMAT (code);
599 int i, j;
600 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
602 if (fmt[i] == 'e')
603 deps = find_regs_nested (deps, XEXP (x, i));
604 else if (fmt[i] == 'E')
605 for (j = 0; j < XVECLEN (x, i); j++)
606 deps = find_regs_nested (deps, XVECEXP (x, i, j));
609 return deps;
612 /* Optimize one loop described by LOOP. */
614 /* ??? Could also move memory writes out of loops if the destination address
615 is invariant, the source is invariant, the memory write is not volatile,
616 and if we can prove that no read inside the loop can read this address
617 before the write occurs. If there is a read of this address after the
618 write, then we can also mark the memory read as invariant. */
620 static void
621 scan_loop (struct loop *loop, int flags)
623 struct loop_info *loop_info = LOOP_INFO (loop);
624 struct loop_regs *regs = LOOP_REGS (loop);
625 int i;
626 rtx loop_start = loop->start;
627 rtx loop_end = loop->end;
628 rtx p;
629 /* 1 if we are scanning insns that could be executed zero times. */
630 int maybe_never = 0;
631 /* 1 if we are scanning insns that might never be executed
632 due to a subroutine call which might exit before they are reached. */
633 int call_passed = 0;
634 /* Number of insns in the loop. */
635 int insn_count;
636 int tem;
637 rtx temp, update_start, update_end;
638 /* The SET from an insn, if it is the only SET in the insn. */
639 rtx set, set1;
640 /* Chain describing insns movable in current loop. */
641 struct loop_movables *movables = LOOP_MOVABLES (loop);
642 /* Ratio of extra register life span we can justify
643 for saving an instruction. More if loop doesn't call subroutines
644 since in that case saving an insn makes more difference
645 and more registers are available. */
646 int threshold;
647 /* Nonzero if we are scanning instructions in a sub-loop. */
648 int loop_depth = 0;
649 int in_libcall;
651 loop->top = 0;
653 movables->head = 0;
654 movables->last = 0;
656 /* Determine whether this loop starts with a jump down to a test at
657 the end. This will occur for a small number of loops with a test
658 that is too complex to duplicate in front of the loop.
660 We search for the first insn or label in the loop, skipping NOTEs.
661 However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
662 (because we might have a loop executed only once that contains a
663 loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
664 (in case we have a degenerate loop).
666 Note that if we mistakenly think that a loop is entered at the top
667 when, in fact, it is entered at the exit test, the only effect will be
668 slightly poorer optimization. Making the opposite error can generate
669 incorrect code. Since very few loops now start with a jump to the
670 exit test, the code here to detect that case is very conservative. */
672 for (p = NEXT_INSN (loop_start);
673 p != loop_end
674 && !LABEL_P (p) && ! INSN_P (p)
675 && (!NOTE_P (p)
676 || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
677 && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
678 p = NEXT_INSN (p))
681 loop->scan_start = p;
683 /* If loop end is the end of the current function, then emit a
684 NOTE_INSN_DELETED after loop_end and set loop->sink to the dummy
685 note insn. This is the position we use when sinking insns out of
686 the loop. */
687 if (NEXT_INSN (loop->end) != 0)
688 loop->sink = NEXT_INSN (loop->end);
689 else
690 loop->sink = emit_note_after (NOTE_INSN_DELETED, loop->end);
692 /* Set up variables describing this loop. */
693 prescan_loop (loop);
694 threshold = (loop_info->has_call ? 1 : 2) * (1 + n_non_fixed_regs);
696 /* If loop has a jump before the first label,
697 the true entry is the target of that jump.
698 Start scan from there.
699 But record in LOOP->TOP the place where the end-test jumps
700 back to so we can scan that after the end of the loop. */
701 if (JUMP_P (p)
702 /* Loop entry must be unconditional jump (and not a RETURN) */
703 && any_uncondjump_p (p)
704 && JUMP_LABEL (p) != 0
705 /* Check to see whether the jump actually
706 jumps out of the loop (meaning it's no loop).
707 This case can happen for things like
708 do {..} while (0). If this label was generated previously
709 by loop, we can't tell anything about it and have to reject
710 the loop. */
711 && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, loop_end))
713 loop->top = next_label (loop->scan_start);
714 loop->scan_start = JUMP_LABEL (p);
717 /* If LOOP->SCAN_START was an insn created by loop, we don't know its luid
718 as required by loop_reg_used_before_p. So skip such loops. (This
719 test may never be true, but it's best to play it safe.)
721 Also, skip loops where we do not start scanning at a label. This
722 test also rejects loops starting with a JUMP_INSN that failed the
723 test above. */
725 if (INSN_UID (loop->scan_start) >= max_uid_for_loop
726 || !LABEL_P (loop->scan_start))
728 if (loop_dump_stream)
729 fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
730 INSN_UID (loop_start), INSN_UID (loop_end));
731 return;
734 /* Allocate extra space for REGs that might be created by load_mems.
735 We allocate a little extra slop as well, in the hopes that we
736 won't have to reallocate the regs array. */
737 loop_regs_scan (loop, loop_info->mems_idx + 16);
738 insn_count = count_insns_in_loop (loop);
740 if (loop_dump_stream)
742 fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
743 INSN_UID (loop_start), INSN_UID (loop_end), insn_count);
744 if (loop->cont)
745 fprintf (loop_dump_stream, "Continue at insn %d.\n",
746 INSN_UID (loop->cont));
749 /* Scan through the loop finding insns that are safe to move.
750 Set REGS->ARRAY[I].SET_IN_LOOP negative for the reg I being set, so that
751 this reg will be considered invariant for subsequent insns.
752 We consider whether subsequent insns use the reg
753 in deciding whether it is worth actually moving.
755 MAYBE_NEVER is nonzero if we have passed a conditional jump insn
756 and therefore it is possible that the insns we are scanning
757 would never be executed. At such times, we must make sure
758 that it is safe to execute the insn once instead of zero times.
759 When MAYBE_NEVER is 0, all insns will be executed at least once
760 so that is not a problem. */
762 for (in_libcall = 0, p = next_insn_in_loop (loop, loop->scan_start);
763 p != NULL_RTX;
764 p = next_insn_in_loop (loop, p))
766 if (in_libcall && INSN_P (p) && find_reg_note (p, REG_RETVAL, NULL_RTX))
767 in_libcall--;
768 if (NONJUMP_INSN_P (p))
770 temp = find_reg_note (p, REG_LIBCALL, NULL_RTX);
771 if (temp)
772 in_libcall++;
773 if (! in_libcall
774 && (set = single_set (p))
775 && REG_P (SET_DEST (set))
776 #ifdef PIC_OFFSET_TABLE_REG_CALL_CLOBBERED
777 && SET_DEST (set) != pic_offset_table_rtx
778 #endif
779 && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
781 int tem1 = 0;
782 int tem2 = 0;
783 int move_insn = 0;
784 int insert_temp = 0;
785 rtx src = SET_SRC (set);
786 rtx dependencies = 0;
788 /* Figure out what to use as a source of this insn. If a
789 REG_EQUIV note is given or if a REG_EQUAL note with a
790 constant operand is specified, use it as the source and
791 mark that we should move this insn by calling
792 emit_move_insn rather that duplicating the insn.
794 Otherwise, only use the REG_EQUAL contents if a REG_RETVAL
795 note is present. */
796 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
797 if (temp)
798 src = XEXP (temp, 0), move_insn = 1;
799 else
801 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
802 if (temp && CONSTANT_P (XEXP (temp, 0)))
803 src = XEXP (temp, 0), move_insn = 1;
804 if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
806 src = XEXP (temp, 0);
807 /* A libcall block can use regs that don't appear in
808 the equivalent expression. To move the libcall,
809 we must move those regs too. */
810 dependencies = libcall_other_reg (p, src);
814 /* For parallels, add any possible uses to the dependencies, as
815 we can't move the insn without resolving them first.
816 MEMs inside CLOBBERs may also reference registers; these
817 count as implicit uses. */
818 if (GET_CODE (PATTERN (p)) == PARALLEL)
820 for (i = 0; i < XVECLEN (PATTERN (p), 0); i++)
822 rtx x = XVECEXP (PATTERN (p), 0, i);
823 if (GET_CODE (x) == USE)
824 dependencies
825 = gen_rtx_EXPR_LIST (VOIDmode, XEXP (x, 0),
826 dependencies);
827 else if (GET_CODE (x) == CLOBBER
828 && MEM_P (XEXP (x, 0)))
829 dependencies = find_regs_nested (dependencies,
830 XEXP (XEXP (x, 0), 0));
834 if (/* The register is used in basic blocks other
835 than the one where it is set (meaning that
836 something after this point in the loop might
837 depend on its value before the set). */
838 ! reg_in_basic_block_p (p, SET_DEST (set))
839 /* And the set is not guaranteed to be executed once
840 the loop starts, or the value before the set is
841 needed before the set occurs...
843 ??? Note we have quadratic behavior here, mitigated
844 by the fact that the previous test will often fail for
845 large loops. Rather than re-scanning the entire loop
846 each time for register usage, we should build tables
847 of the register usage and use them here instead. */
848 && (maybe_never
849 || loop_reg_used_before_p (loop, set, p)))
850 /* It is unsafe to move the set. However, it may be OK to
851 move the source into a new pseudo, and substitute a
852 reg-to-reg copy for the original insn.
854 This code used to consider it OK to move a set of a variable
855 which was not created by the user and not used in an exit
856 test.
857 That behavior is incorrect and was removed. */
858 insert_temp = 1;
860 /* Don't try to optimize a MODE_CC set with a constant
861 source. It probably will be combined with a conditional
862 jump. */
863 if (GET_MODE_CLASS (GET_MODE (SET_DEST (set))) == MODE_CC
864 && CONSTANT_P (src))
866 /* Don't try to optimize a register that was made
867 by loop-optimization for an inner loop.
868 We don't know its life-span, so we can't compute
869 the benefit. */
870 else if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
872 /* Don't move the source and add a reg-to-reg copy:
873 - with -Os (this certainly increases size),
874 - if the mode doesn't support copy operations (obviously),
875 - if the source is already a reg (the motion will gain nothing),
876 - if the source is a legitimate constant (likewise). */
877 else if (insert_temp
878 && (optimize_size
879 || ! can_copy_p (GET_MODE (SET_SRC (set)))
880 || REG_P (SET_SRC (set))
881 || (CONSTANT_P (SET_SRC (set))
882 && LEGITIMATE_CONSTANT_P (SET_SRC (set)))))
884 else if ((tem = loop_invariant_p (loop, src))
885 && (dependencies == 0
886 || (tem2
887 = loop_invariant_p (loop, dependencies)) != 0)
888 && (regs->array[REGNO (SET_DEST (set))].set_in_loop == 1
889 || (tem1
890 = consec_sets_invariant_p
891 (loop, SET_DEST (set),
892 regs->array[REGNO (SET_DEST (set))].set_in_loop,
893 p)))
894 /* If the insn can cause a trap (such as divide by zero),
895 can't move it unless it's guaranteed to be executed
896 once loop is entered. Even a function call might
897 prevent the trap insn from being reached
898 (since it might exit!) */
899 && ! ((maybe_never || call_passed)
900 && may_trap_p (src)))
902 struct movable *m;
903 int regno = REGNO (SET_DEST (set));
905 /* A potential lossage is where we have a case where two insns
906 can be combined as long as they are both in the loop, but
907 we move one of them outside the loop. For large loops,
908 this can lose. The most common case of this is the address
909 of a function being called.
911 Therefore, if this register is marked as being used
912 exactly once if we are in a loop with calls
913 (a "large loop"), see if we can replace the usage of
914 this register with the source of this SET. If we can,
915 delete this insn.
917 Don't do this if P has a REG_RETVAL note or if we have
918 SMALL_REGISTER_CLASSES and SET_SRC is a hard register. */
920 if (loop_info->has_call
921 && regs->array[regno].single_usage != 0
922 && regs->array[regno].single_usage != const0_rtx
923 && REGNO_FIRST_UID (regno) == INSN_UID (p)
924 && (REGNO_LAST_UID (regno)
925 == INSN_UID (regs->array[regno].single_usage))
926 && regs->array[regno].set_in_loop == 1
927 && GET_CODE (SET_SRC (set)) != ASM_OPERANDS
928 && ! side_effects_p (SET_SRC (set))
929 && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
930 && (! SMALL_REGISTER_CLASSES
931 || (! (REG_P (SET_SRC (set))
932 && (REGNO (SET_SRC (set))
933 < FIRST_PSEUDO_REGISTER))))
934 && regno >= FIRST_PSEUDO_REGISTER
935 /* This test is not redundant; SET_SRC (set) might be
936 a call-clobbered register and the life of REGNO
937 might span a call. */
938 && ! modified_between_p (SET_SRC (set), p,
939 regs->array[regno].single_usage)
940 && no_labels_between_p (p,
941 regs->array[regno].single_usage)
942 && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
943 regs->array[regno].single_usage))
945 /* Replace any usage in a REG_EQUAL note. Must copy
946 the new source, so that we don't get rtx sharing
947 between the SET_SOURCE and REG_NOTES of insn p. */
948 REG_NOTES (regs->array[regno].single_usage)
949 = (replace_rtx
950 (REG_NOTES (regs->array[regno].single_usage),
951 SET_DEST (set), copy_rtx (SET_SRC (set))));
953 delete_insn (p);
954 for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
955 i++)
956 regs->array[regno+i].set_in_loop = 0;
957 continue;
960 m = xmalloc (sizeof (struct movable));
961 m->next = 0;
962 m->insn = p;
963 m->set_src = src;
964 m->dependencies = dependencies;
965 m->set_dest = SET_DEST (set);
966 m->force = 0;
967 m->consec
968 = regs->array[REGNO (SET_DEST (set))].set_in_loop - 1;
969 m->done = 0;
970 m->forces = 0;
971 m->partial = 0;
972 m->move_insn = move_insn;
973 m->move_insn_first = 0;
974 m->insert_temp = insert_temp;
975 m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
976 m->savemode = VOIDmode;
977 m->regno = regno;
978 /* Set M->cond if either loop_invariant_p
979 or consec_sets_invariant_p returned 2
980 (only conditionally invariant). */
981 m->cond = ((tem | tem1 | tem2) > 1);
982 m->global = LOOP_REG_GLOBAL_P (loop, regno);
983 m->match = 0;
984 m->lifetime = LOOP_REG_LIFETIME (loop, regno);
985 m->savings = regs->array[regno].n_times_set;
986 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
987 m->savings += libcall_benefit (p);
988 for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set)); i++)
989 regs->array[regno+i].set_in_loop = move_insn ? -2 : -1;
990 /* Add M to the end of the chain MOVABLES. */
991 loop_movables_add (movables, m);
993 if (m->consec > 0)
995 /* It is possible for the first instruction to have a
996 REG_EQUAL note but a non-invariant SET_SRC, so we must
997 remember the status of the first instruction in case
998 the last instruction doesn't have a REG_EQUAL note. */
999 m->move_insn_first = m->move_insn;
1001 /* Skip this insn, not checking REG_LIBCALL notes. */
1002 p = next_nonnote_insn (p);
1003 /* Skip the consecutive insns, if there are any. */
1004 p = skip_consec_insns (p, m->consec);
1005 /* Back up to the last insn of the consecutive group. */
1006 p = prev_nonnote_insn (p);
1008 /* We must now reset m->move_insn, m->is_equiv, and
1009 possibly m->set_src to correspond to the effects of
1010 all the insns. */
1011 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
1012 if (temp)
1013 m->set_src = XEXP (temp, 0), m->move_insn = 1;
1014 else
1016 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
1017 if (temp && CONSTANT_P (XEXP (temp, 0)))
1018 m->set_src = XEXP (temp, 0), m->move_insn = 1;
1019 else
1020 m->move_insn = 0;
1023 m->is_equiv
1024 = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
1027 /* If this register is always set within a STRICT_LOW_PART
1028 or set to zero, then its high bytes are constant.
1029 So clear them outside the loop and within the loop
1030 just load the low bytes.
1031 We must check that the machine has an instruction to do so.
1032 Also, if the value loaded into the register
1033 depends on the same register, this cannot be done. */
1034 else if (SET_SRC (set) == const0_rtx
1035 && NONJUMP_INSN_P (NEXT_INSN (p))
1036 && (set1 = single_set (NEXT_INSN (p)))
1037 && GET_CODE (set1) == SET
1038 && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
1039 && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
1040 && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
1041 == SET_DEST (set))
1042 && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1044 int regno = REGNO (SET_DEST (set));
1045 if (regs->array[regno].set_in_loop == 2)
1047 struct movable *m;
1048 m = xmalloc (sizeof (struct movable));
1049 m->next = 0;
1050 m->insn = p;
1051 m->set_dest = SET_DEST (set);
1052 m->dependencies = 0;
1053 m->force = 0;
1054 m->consec = 0;
1055 m->done = 0;
1056 m->forces = 0;
1057 m->move_insn = 0;
1058 m->move_insn_first = 0;
1059 m->insert_temp = insert_temp;
1060 m->partial = 1;
1061 /* If the insn may not be executed on some cycles,
1062 we can't clear the whole reg; clear just high part.
1063 Not even if the reg is used only within this loop.
1064 Consider this:
1065 while (1)
1066 while (s != t) {
1067 if (foo ()) x = *s;
1068 use (x);
1070 Clearing x before the inner loop could clobber a value
1071 being saved from the last time around the outer loop.
1072 However, if the reg is not used outside this loop
1073 and all uses of the register are in the same
1074 basic block as the store, there is no problem.
1076 If this insn was made by loop, we don't know its
1077 INSN_LUID and hence must make a conservative
1078 assumption. */
1079 m->global = (INSN_UID (p) >= max_uid_for_loop
1080 || LOOP_REG_GLOBAL_P (loop, regno)
1081 || (labels_in_range_p
1082 (p, REGNO_FIRST_LUID (regno))));
1083 if (maybe_never && m->global)
1084 m->savemode = GET_MODE (SET_SRC (set1));
1085 else
1086 m->savemode = VOIDmode;
1087 m->regno = regno;
1088 m->cond = 0;
1089 m->match = 0;
1090 m->lifetime = LOOP_REG_LIFETIME (loop, regno);
1091 m->savings = 1;
1092 for (i = 0;
1093 i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
1094 i++)
1095 regs->array[regno+i].set_in_loop = -1;
1096 /* Add M to the end of the chain MOVABLES. */
1097 loop_movables_add (movables, m);
1102 /* Past a call insn, we get to insns which might not be executed
1103 because the call might exit. This matters for insns that trap.
1104 Constant and pure call insns always return, so they don't count. */
1105 else if (CALL_P (p) && ! CONST_OR_PURE_CALL_P (p))
1106 call_passed = 1;
1107 /* Past a label or a jump, we get to insns for which we
1108 can't count on whether or how many times they will be
1109 executed during each iteration. Therefore, we can
1110 only move out sets of trivial variables
1111 (those not used after the loop). */
1112 /* Similar code appears twice in strength_reduce. */
1113 else if ((LABEL_P (p) || JUMP_P (p))
1114 /* If we enter the loop in the middle, and scan around to the
1115 beginning, don't set maybe_never for that. This must be an
1116 unconditional jump, otherwise the code at the top of the
1117 loop might never be executed. Unconditional jumps are
1118 followed by a barrier then the loop_end. */
1119 && ! (JUMP_P (p) && JUMP_LABEL (p) == loop->top
1120 && NEXT_INSN (NEXT_INSN (p)) == loop_end
1121 && any_uncondjump_p (p)))
1122 maybe_never = 1;
1123 else if (NOTE_P (p))
1125 /* At the virtual top of a converted loop, insns are again known to
1126 be executed: logically, the loop begins here even though the exit
1127 code has been duplicated. */
1128 if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1129 maybe_never = call_passed = 0;
1130 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1131 loop_depth++;
1132 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1133 loop_depth--;
1137 /* If one movable subsumes another, ignore that other. */
1139 ignore_some_movables (movables);
1141 /* For each movable insn, see if the reg that it loads
1142 leads when it dies right into another conditionally movable insn.
1143 If so, record that the second insn "forces" the first one,
1144 since the second can be moved only if the first is. */
1146 force_movables (movables);
1148 /* See if there are multiple movable insns that load the same value.
1149 If there are, make all but the first point at the first one
1150 through the `match' field, and add the priorities of them
1151 all together as the priority of the first. */
1153 combine_movables (movables, regs);
1155 /* Now consider each movable insn to decide whether it is worth moving.
1156 Store 0 in regs->array[I].set_in_loop for each reg I that is moved.
1158 For machines with few registers this increases code size, so do not
1159 move moveables when optimizing for code size on such machines.
1160 (The 18 below is the value for i386.) */
1162 if (!optimize_size
1163 || (reg_class_size[GENERAL_REGS] > 18 && !loop_info->has_call))
1165 move_movables (loop, movables, threshold, insn_count);
1167 /* Recalculate regs->array if move_movables has created new
1168 registers. */
1169 if (max_reg_num () > regs->num)
1171 loop_regs_scan (loop, 0);
1172 for (update_start = loop_start;
1173 PREV_INSN (update_start)
1174 && !LABEL_P (PREV_INSN (update_start));
1175 update_start = PREV_INSN (update_start))
1177 update_end = NEXT_INSN (loop_end);
1179 reg_scan_update (update_start, update_end, loop_max_reg);
1180 loop_max_reg = max_reg_num ();
1184 /* Now candidates that still are negative are those not moved.
1185 Change regs->array[I].set_in_loop to indicate that those are not actually
1186 invariant. */
1187 for (i = 0; i < regs->num; i++)
1188 if (regs->array[i].set_in_loop < 0)
1189 regs->array[i].set_in_loop = regs->array[i].n_times_set;
1191 /* Now that we've moved some things out of the loop, we might be able to
1192 hoist even more memory references. */
1193 load_mems (loop);
1195 /* Recalculate regs->array if load_mems has created new registers. */
1196 if (max_reg_num () > regs->num)
1197 loop_regs_scan (loop, 0);
1199 for (update_start = loop_start;
1200 PREV_INSN (update_start)
1201 && !LABEL_P (PREV_INSN (update_start));
1202 update_start = PREV_INSN (update_start))
1204 update_end = NEXT_INSN (loop_end);
1206 reg_scan_update (update_start, update_end, loop_max_reg);
1207 loop_max_reg = max_reg_num ();
1209 if (flag_strength_reduce)
1211 if (update_end && LABEL_P (update_end))
1212 /* Ensure our label doesn't go away. */
1213 LABEL_NUSES (update_end)++;
1215 strength_reduce (loop, flags);
1217 reg_scan_update (update_start, update_end, loop_max_reg);
1218 loop_max_reg = max_reg_num ();
1220 if (update_end && LABEL_P (update_end)
1221 && --LABEL_NUSES (update_end) == 0)
1222 delete_related_insns (update_end);
1226 /* The movable information is required for strength reduction. */
1227 loop_movables_free (movables);
1229 free (regs->array);
1230 regs->array = 0;
1231 regs->num = 0;
1234 /* Add elements to *OUTPUT to record all the pseudo-regs
1235 mentioned in IN_THIS but not mentioned in NOT_IN_THIS. */
1237 static void
1238 record_excess_regs (rtx in_this, rtx not_in_this, rtx *output)
1240 enum rtx_code code;
1241 const char *fmt;
1242 int i;
1244 code = GET_CODE (in_this);
1246 switch (code)
1248 case PC:
1249 case CC0:
1250 case CONST_INT:
1251 case CONST_DOUBLE:
1252 case CONST:
1253 case SYMBOL_REF:
1254 case LABEL_REF:
1255 return;
1257 case REG:
1258 if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1259 && ! reg_mentioned_p (in_this, not_in_this))
1260 *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1261 return;
1263 default:
1264 break;
1267 fmt = GET_RTX_FORMAT (code);
1268 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1270 int j;
1272 switch (fmt[i])
1274 case 'E':
1275 for (j = 0; j < XVECLEN (in_this, i); j++)
1276 record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1277 break;
1279 case 'e':
1280 record_excess_regs (XEXP (in_this, i), not_in_this, output);
1281 break;
1286 /* Check what regs are referred to in the libcall block ending with INSN,
1287 aside from those mentioned in the equivalent value.
1288 If there are none, return 0.
1289 If there are one or more, return an EXPR_LIST containing all of them. */
1291 static rtx
1292 libcall_other_reg (rtx insn, rtx equiv)
1294 rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1295 rtx p = XEXP (note, 0);
1296 rtx output = 0;
1298 /* First, find all the regs used in the libcall block
1299 that are not mentioned as inputs to the result. */
1301 while (p != insn)
1303 if (INSN_P (p))
1304 record_excess_regs (PATTERN (p), equiv, &output);
1305 p = NEXT_INSN (p);
1308 return output;
1311 /* Return 1 if all uses of REG
1312 are between INSN and the end of the basic block. */
1314 static int
1315 reg_in_basic_block_p (rtx insn, rtx reg)
1317 int regno = REGNO (reg);
1318 rtx p;
1320 if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1321 return 0;
1323 /* Search this basic block for the already recorded last use of the reg. */
1324 for (p = insn; p; p = NEXT_INSN (p))
1326 switch (GET_CODE (p))
1328 case NOTE:
1329 break;
1331 case INSN:
1332 case CALL_INSN:
1333 /* Ordinary insn: if this is the last use, we win. */
1334 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1335 return 1;
1336 break;
1338 case JUMP_INSN:
1339 /* Jump insn: if this is the last use, we win. */
1340 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1341 return 1;
1342 /* Otherwise, it's the end of the basic block, so we lose. */
1343 return 0;
1345 case CODE_LABEL:
1346 case BARRIER:
1347 /* It's the end of the basic block, so we lose. */
1348 return 0;
1350 default:
1351 break;
1355 /* The "last use" that was recorded can't be found after the first
1356 use. This can happen when the last use was deleted while
1357 processing an inner loop, this inner loop was then completely
1358 unrolled, and the outer loop is always exited after the inner loop,
1359 so that everything after the first use becomes a single basic block. */
1360 return 1;
1363 /* Compute the benefit of eliminating the insns in the block whose
1364 last insn is LAST. This may be a group of insns used to compute a
1365 value directly or can contain a library call. */
1367 static int
1368 libcall_benefit (rtx last)
1370 rtx insn;
1371 int benefit = 0;
1373 for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1374 insn != last; insn = NEXT_INSN (insn))
1376 if (CALL_P (insn))
1377 benefit += 10; /* Assume at least this many insns in a library
1378 routine. */
1379 else if (NONJUMP_INSN_P (insn)
1380 && GET_CODE (PATTERN (insn)) != USE
1381 && GET_CODE (PATTERN (insn)) != CLOBBER)
1382 benefit++;
1385 return benefit;
1388 /* Skip COUNT insns from INSN, counting library calls as 1 insn. */
1390 static rtx
1391 skip_consec_insns (rtx insn, int count)
1393 for (; count > 0; count--)
1395 rtx temp;
1397 /* If first insn of libcall sequence, skip to end. */
1398 /* Do this at start of loop, since INSN is guaranteed to
1399 be an insn here. */
1400 if (!NOTE_P (insn)
1401 && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1402 insn = XEXP (temp, 0);
1405 insn = NEXT_INSN (insn);
1406 while (NOTE_P (insn));
1409 return insn;
1412 /* Ignore any movable whose insn falls within a libcall
1413 which is part of another movable.
1414 We make use of the fact that the movable for the libcall value
1415 was made later and so appears later on the chain. */
1417 static void
1418 ignore_some_movables (struct loop_movables *movables)
1420 struct movable *m, *m1;
1422 for (m = movables->head; m; m = m->next)
1424 /* Is this a movable for the value of a libcall? */
1425 rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1426 if (note)
1428 rtx insn;
1429 /* Check for earlier movables inside that range,
1430 and mark them invalid. We cannot use LUIDs here because
1431 insns created by loop.c for prior loops don't have LUIDs.
1432 Rather than reject all such insns from movables, we just
1433 explicitly check each insn in the libcall (since invariant
1434 libcalls aren't that common). */
1435 for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1436 for (m1 = movables->head; m1 != m; m1 = m1->next)
1437 if (m1->insn == insn)
1438 m1->done = 1;
1443 /* For each movable insn, see if the reg that it loads
1444 leads when it dies right into another conditionally movable insn.
1445 If so, record that the second insn "forces" the first one,
1446 since the second can be moved only if the first is. */
1448 static void
1449 force_movables (struct loop_movables *movables)
1451 struct movable *m, *m1;
1453 for (m1 = movables->head; m1; m1 = m1->next)
1454 /* Omit this if moving just the (SET (REG) 0) of a zero-extend. */
1455 if (!m1->partial && !m1->done)
1457 int regno = m1->regno;
1458 for (m = m1->next; m; m = m->next)
1459 /* ??? Could this be a bug? What if CSE caused the
1460 register of M1 to be used after this insn?
1461 Since CSE does not update regno_last_uid,
1462 this insn M->insn might not be where it dies.
1463 But very likely this doesn't matter; what matters is
1464 that M's reg is computed from M1's reg. */
1465 if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1466 && !m->done)
1467 break;
1468 if (m != 0 && m->set_src == m1->set_dest
1469 /* If m->consec, m->set_src isn't valid. */
1470 && m->consec == 0)
1471 m = 0;
1473 /* Increase the priority of the moving the first insn
1474 since it permits the second to be moved as well.
1475 Likewise for insns already forced by the first insn. */
1476 if (m != 0)
1478 struct movable *m2;
1480 m->forces = m1;
1481 for (m2 = m1; m2; m2 = m2->forces)
1483 m2->lifetime += m->lifetime;
1484 m2->savings += m->savings;
1490 /* Find invariant expressions that are equal and can be combined into
1491 one register. */
1493 static void
1494 combine_movables (struct loop_movables *movables, struct loop_regs *regs)
1496 struct movable *m;
1497 char *matched_regs = xmalloc (regs->num);
1498 enum machine_mode mode;
1500 /* Regs that are set more than once are not allowed to match
1501 or be matched. I'm no longer sure why not. */
1502 /* Only pseudo registers are allowed to match or be matched,
1503 since move_movables does not validate the change. */
1504 /* Perhaps testing m->consec_sets would be more appropriate here? */
1506 for (m = movables->head; m; m = m->next)
1507 if (m->match == 0 && regs->array[m->regno].n_times_set == 1
1508 && m->regno >= FIRST_PSEUDO_REGISTER
1509 && !m->insert_temp
1510 && !m->partial)
1512 struct movable *m1;
1513 int regno = m->regno;
1515 memset (matched_regs, 0, regs->num);
1516 matched_regs[regno] = 1;
1518 /* We want later insns to match the first one. Don't make the first
1519 one match any later ones. So start this loop at m->next. */
1520 for (m1 = m->next; m1; m1 = m1->next)
1521 if (m != m1 && m1->match == 0
1522 && !m1->insert_temp
1523 && regs->array[m1->regno].n_times_set == 1
1524 && m1->regno >= FIRST_PSEUDO_REGISTER
1525 /* A reg used outside the loop mustn't be eliminated. */
1526 && !m1->global
1527 /* A reg used for zero-extending mustn't be eliminated. */
1528 && !m1->partial
1529 && (matched_regs[m1->regno]
1532 /* Can combine regs with different modes loaded from the
1533 same constant only if the modes are the same or
1534 if both are integer modes with M wider or the same
1535 width as M1. The check for integer is redundant, but
1536 safe, since the only case of differing destination
1537 modes with equal sources is when both sources are
1538 VOIDmode, i.e., CONST_INT. */
1539 (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1540 || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1541 && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1542 && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1543 >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1544 /* See if the source of M1 says it matches M. */
1545 && ((REG_P (m1->set_src)
1546 && matched_regs[REGNO (m1->set_src)])
1547 || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1548 movables, regs))))
1549 && ((m->dependencies == m1->dependencies)
1550 || rtx_equal_p (m->dependencies, m1->dependencies)))
1552 m->lifetime += m1->lifetime;
1553 m->savings += m1->savings;
1554 m1->done = 1;
1555 m1->match = m;
1556 matched_regs[m1->regno] = 1;
1560 /* Now combine the regs used for zero-extension.
1561 This can be done for those not marked `global'
1562 provided their lives don't overlap. */
1564 for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1565 mode = GET_MODE_WIDER_MODE (mode))
1567 struct movable *m0 = 0;
1569 /* Combine all the registers for extension from mode MODE.
1570 Don't combine any that are used outside this loop. */
1571 for (m = movables->head; m; m = m->next)
1572 if (m->partial && ! m->global
1573 && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1575 struct movable *m1;
1577 int first = REGNO_FIRST_LUID (m->regno);
1578 int last = REGNO_LAST_LUID (m->regno);
1580 if (m0 == 0)
1582 /* First one: don't check for overlap, just record it. */
1583 m0 = m;
1584 continue;
1587 /* Make sure they extend to the same mode.
1588 (Almost always true.) */
1589 if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1590 continue;
1592 /* We already have one: check for overlap with those
1593 already combined together. */
1594 for (m1 = movables->head; m1 != m; m1 = m1->next)
1595 if (m1 == m0 || (m1->partial && m1->match == m0))
1596 if (! (REGNO_FIRST_LUID (m1->regno) > last
1597 || REGNO_LAST_LUID (m1->regno) < first))
1598 goto overlap;
1600 /* No overlap: we can combine this with the others. */
1601 m0->lifetime += m->lifetime;
1602 m0->savings += m->savings;
1603 m->done = 1;
1604 m->match = m0;
1606 overlap:
1611 /* Clean up. */
1612 free (matched_regs);
1615 /* Returns the number of movable instructions in LOOP that were not
1616 moved outside the loop. */
1618 static int
1619 num_unmoved_movables (const struct loop *loop)
1621 int num = 0;
1622 struct movable *m;
1624 for (m = LOOP_MOVABLES (loop)->head; m; m = m->next)
1625 if (!m->done)
1626 ++num;
1628 return num;
1632 /* Return 1 if regs X and Y will become the same if moved. */
1634 static int
1635 regs_match_p (rtx x, rtx y, struct loop_movables *movables)
1637 unsigned int xn = REGNO (x);
1638 unsigned int yn = REGNO (y);
1639 struct movable *mx, *my;
1641 for (mx = movables->head; mx; mx = mx->next)
1642 if (mx->regno == xn)
1643 break;
1645 for (my = movables->head; my; my = my->next)
1646 if (my->regno == yn)
1647 break;
1649 return (mx && my
1650 && ((mx->match == my->match && mx->match != 0)
1651 || mx->match == my
1652 || mx == my->match));
1655 /* Return 1 if X and Y are identical-looking rtx's.
1656 This is the Lisp function EQUAL for rtx arguments.
1658 If two registers are matching movables or a movable register and an
1659 equivalent constant, consider them equal. */
1661 static int
1662 rtx_equal_for_loop_p (rtx x, rtx y, struct loop_movables *movables,
1663 struct loop_regs *regs)
1665 int i;
1666 int j;
1667 struct movable *m;
1668 enum rtx_code code;
1669 const char *fmt;
1671 if (x == y)
1672 return 1;
1673 if (x == 0 || y == 0)
1674 return 0;
1676 code = GET_CODE (x);
1678 /* If we have a register and a constant, they may sometimes be
1679 equal. */
1680 if (REG_P (x) && regs->array[REGNO (x)].set_in_loop == -2
1681 && CONSTANT_P (y))
1683 for (m = movables->head; m; m = m->next)
1684 if (m->move_insn && m->regno == REGNO (x)
1685 && rtx_equal_p (m->set_src, y))
1686 return 1;
1688 else if (REG_P (y) && regs->array[REGNO (y)].set_in_loop == -2
1689 && CONSTANT_P (x))
1691 for (m = movables->head; m; m = m->next)
1692 if (m->move_insn && m->regno == REGNO (y)
1693 && rtx_equal_p (m->set_src, x))
1694 return 1;
1697 /* Otherwise, rtx's of different codes cannot be equal. */
1698 if (code != GET_CODE (y))
1699 return 0;
1701 /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1702 (REG:SI x) and (REG:HI x) are NOT equivalent. */
1704 if (GET_MODE (x) != GET_MODE (y))
1705 return 0;
1707 /* These three types of rtx's can be compared nonrecursively. */
1708 if (code == REG)
1709 return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1711 if (code == LABEL_REF)
1712 return XEXP (x, 0) == XEXP (y, 0);
1713 if (code == SYMBOL_REF)
1714 return XSTR (x, 0) == XSTR (y, 0);
1716 /* Compare the elements. If any pair of corresponding elements
1717 fail to match, return 0 for the whole things. */
1719 fmt = GET_RTX_FORMAT (code);
1720 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1722 switch (fmt[i])
1724 case 'w':
1725 if (XWINT (x, i) != XWINT (y, i))
1726 return 0;
1727 break;
1729 case 'i':
1730 if (XINT (x, i) != XINT (y, i))
1731 return 0;
1732 break;
1734 case 'E':
1735 /* Two vectors must have the same length. */
1736 if (XVECLEN (x, i) != XVECLEN (y, i))
1737 return 0;
1739 /* And the corresponding elements must match. */
1740 for (j = 0; j < XVECLEN (x, i); j++)
1741 if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j),
1742 movables, regs) == 0)
1743 return 0;
1744 break;
1746 case 'e':
1747 if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables, regs)
1748 == 0)
1749 return 0;
1750 break;
1752 case 's':
1753 if (strcmp (XSTR (x, i), XSTR (y, i)))
1754 return 0;
1755 break;
1757 case 'u':
1758 /* These are just backpointers, so they don't matter. */
1759 break;
1761 case '0':
1762 break;
1764 /* It is believed that rtx's at this level will never
1765 contain anything but integers and other rtx's,
1766 except for within LABEL_REFs and SYMBOL_REFs. */
1767 default:
1768 abort ();
1771 return 1;
1774 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1775 insns in INSNS which use the reference. LABEL_NUSES for CODE_LABEL
1776 references is incremented once for each added note. */
1778 static void
1779 add_label_notes (rtx x, rtx insns)
1781 enum rtx_code code = GET_CODE (x);
1782 int i, j;
1783 const char *fmt;
1784 rtx insn;
1786 if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1788 /* This code used to ignore labels that referred to dispatch tables to
1789 avoid flow generating (slightly) worse code.
1791 We no longer ignore such label references (see LABEL_REF handling in
1792 mark_jump_label for additional information). */
1793 for (insn = insns; insn; insn = NEXT_INSN (insn))
1794 if (reg_mentioned_p (XEXP (x, 0), insn))
1796 REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, XEXP (x, 0),
1797 REG_NOTES (insn));
1798 if (LABEL_P (XEXP (x, 0)))
1799 LABEL_NUSES (XEXP (x, 0))++;
1803 fmt = GET_RTX_FORMAT (code);
1804 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1806 if (fmt[i] == 'e')
1807 add_label_notes (XEXP (x, i), insns);
1808 else if (fmt[i] == 'E')
1809 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1810 add_label_notes (XVECEXP (x, i, j), insns);
1814 /* Scan MOVABLES, and move the insns that deserve to be moved.
1815 If two matching movables are combined, replace one reg with the
1816 other throughout. */
1818 static void
1819 move_movables (struct loop *loop, struct loop_movables *movables,
1820 int threshold, int insn_count)
1822 struct loop_regs *regs = LOOP_REGS (loop);
1823 int nregs = regs->num;
1824 rtx new_start = 0;
1825 struct movable *m;
1826 rtx p;
1827 rtx loop_start = loop->start;
1828 rtx loop_end = loop->end;
1829 /* Map of pseudo-register replacements to handle combining
1830 when we move several insns that load the same value
1831 into different pseudo-registers. */
1832 rtx *reg_map = xcalloc (nregs, sizeof (rtx));
1833 char *already_moved = xcalloc (nregs, sizeof (char));
1835 for (m = movables->head; m; m = m->next)
1837 /* Describe this movable insn. */
1839 if (loop_dump_stream)
1841 fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1842 INSN_UID (m->insn), m->regno, m->lifetime);
1843 if (m->consec > 0)
1844 fprintf (loop_dump_stream, "consec %d, ", m->consec);
1845 if (m->cond)
1846 fprintf (loop_dump_stream, "cond ");
1847 if (m->force)
1848 fprintf (loop_dump_stream, "force ");
1849 if (m->global)
1850 fprintf (loop_dump_stream, "global ");
1851 if (m->done)
1852 fprintf (loop_dump_stream, "done ");
1853 if (m->move_insn)
1854 fprintf (loop_dump_stream, "move-insn ");
1855 if (m->match)
1856 fprintf (loop_dump_stream, "matches %d ",
1857 INSN_UID (m->match->insn));
1858 if (m->forces)
1859 fprintf (loop_dump_stream, "forces %d ",
1860 INSN_UID (m->forces->insn));
1863 /* Ignore the insn if it's already done (it matched something else).
1864 Otherwise, see if it is now safe to move. */
1866 if (!m->done
1867 && (! m->cond
1868 || (1 == loop_invariant_p (loop, m->set_src)
1869 && (m->dependencies == 0
1870 || 1 == loop_invariant_p (loop, m->dependencies))
1871 && (m->consec == 0
1872 || 1 == consec_sets_invariant_p (loop, m->set_dest,
1873 m->consec + 1,
1874 m->insn))))
1875 && (! m->forces || m->forces->done))
1877 int regno;
1878 rtx p;
1879 int savings = m->savings;
1881 /* We have an insn that is safe to move.
1882 Compute its desirability. */
1884 p = m->insn;
1885 regno = m->regno;
1887 if (loop_dump_stream)
1888 fprintf (loop_dump_stream, "savings %d ", savings);
1890 if (regs->array[regno].moved_once && loop_dump_stream)
1891 fprintf (loop_dump_stream, "halved since already moved ");
1893 /* An insn MUST be moved if we already moved something else
1894 which is safe only if this one is moved too: that is,
1895 if already_moved[REGNO] is nonzero. */
1897 /* An insn is desirable to move if the new lifetime of the
1898 register is no more than THRESHOLD times the old lifetime.
1899 If it's not desirable, it means the loop is so big
1900 that moving won't speed things up much,
1901 and it is liable to make register usage worse. */
1903 /* It is also desirable to move if it can be moved at no
1904 extra cost because something else was already moved. */
1906 if (already_moved[regno]
1907 || flag_move_all_movables
1908 || (threshold * savings * m->lifetime) >=
1909 (regs->array[regno].moved_once ? insn_count * 2 : insn_count)
1910 || (m->forces && m->forces->done
1911 && regs->array[m->forces->regno].n_times_set == 1))
1913 int count;
1914 struct movable *m1;
1915 rtx first = NULL_RTX;
1916 rtx newreg = NULL_RTX;
1918 if (m->insert_temp)
1919 newreg = gen_reg_rtx (GET_MODE (m->set_dest));
1921 /* Now move the insns that set the reg. */
1923 if (m->partial && m->match)
1925 rtx newpat, i1;
1926 rtx r1, r2;
1927 /* Find the end of this chain of matching regs.
1928 Thus, we load each reg in the chain from that one reg.
1929 And that reg is loaded with 0 directly,
1930 since it has ->match == 0. */
1931 for (m1 = m; m1->match; m1 = m1->match);
1932 newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1933 SET_DEST (PATTERN (m1->insn)));
1934 i1 = loop_insn_hoist (loop, newpat);
1936 /* Mark the moved, invariant reg as being allowed to
1937 share a hard reg with the other matching invariant. */
1938 REG_NOTES (i1) = REG_NOTES (m->insn);
1939 r1 = SET_DEST (PATTERN (m->insn));
1940 r2 = SET_DEST (PATTERN (m1->insn));
1941 regs_may_share
1942 = gen_rtx_EXPR_LIST (VOIDmode, r1,
1943 gen_rtx_EXPR_LIST (VOIDmode, r2,
1944 regs_may_share));
1945 delete_insn (m->insn);
1947 if (new_start == 0)
1948 new_start = i1;
1950 if (loop_dump_stream)
1951 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1953 /* If we are to re-generate the item being moved with a
1954 new move insn, first delete what we have and then emit
1955 the move insn before the loop. */
1956 else if (m->move_insn)
1958 rtx i1, temp, seq;
1960 for (count = m->consec; count >= 0; count--)
1962 /* If this is the first insn of a library call sequence,
1963 something is very wrong. */
1964 if (!NOTE_P (p)
1965 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1966 abort ();
1968 /* If this is the last insn of a libcall sequence, then
1969 delete every insn in the sequence except the last.
1970 The last insn is handled in the normal manner. */
1971 if (!NOTE_P (p)
1972 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1974 temp = XEXP (temp, 0);
1975 while (temp != p)
1976 temp = delete_insn (temp);
1979 temp = p;
1980 p = delete_insn (p);
1982 /* simplify_giv_expr expects that it can walk the insns
1983 at m->insn forwards and see this old sequence we are
1984 tossing here. delete_insn does preserve the next
1985 pointers, but when we skip over a NOTE we must fix
1986 it up. Otherwise that code walks into the non-deleted
1987 insn stream. */
1988 while (p && NOTE_P (p))
1989 p = NEXT_INSN (temp) = NEXT_INSN (p);
1991 if (m->insert_temp)
1993 /* Replace the original insn with a move from
1994 our newly created temp. */
1995 start_sequence ();
1996 emit_move_insn (m->set_dest, newreg);
1997 seq = get_insns ();
1998 end_sequence ();
1999 emit_insn_before (seq, p);
2003 start_sequence ();
2004 emit_move_insn (m->insert_temp ? newreg : m->set_dest,
2005 m->set_src);
2006 seq = get_insns ();
2007 end_sequence ();
2009 add_label_notes (m->set_src, seq);
2011 i1 = loop_insn_hoist (loop, seq);
2012 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2013 set_unique_reg_note (i1,
2014 m->is_equiv ? REG_EQUIV : REG_EQUAL,
2015 m->set_src);
2017 if (loop_dump_stream)
2018 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
2020 /* The more regs we move, the less we like moving them. */
2021 threshold -= 3;
2023 else
2025 for (count = m->consec; count >= 0; count--)
2027 rtx i1, temp;
2029 /* If first insn of libcall sequence, skip to end. */
2030 /* Do this at start of loop, since p is guaranteed to
2031 be an insn here. */
2032 if (!NOTE_P (p)
2033 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
2034 p = XEXP (temp, 0);
2036 /* If last insn of libcall sequence, move all
2037 insns except the last before the loop. The last
2038 insn is handled in the normal manner. */
2039 if (!NOTE_P (p)
2040 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
2042 rtx fn_address = 0;
2043 rtx fn_reg = 0;
2044 rtx fn_address_insn = 0;
2046 first = 0;
2047 for (temp = XEXP (temp, 0); temp != p;
2048 temp = NEXT_INSN (temp))
2050 rtx body;
2051 rtx n;
2052 rtx next;
2054 if (NOTE_P (temp))
2055 continue;
2057 body = PATTERN (temp);
2059 /* Find the next insn after TEMP,
2060 not counting USE or NOTE insns. */
2061 for (next = NEXT_INSN (temp); next != p;
2062 next = NEXT_INSN (next))
2063 if (! (NONJUMP_INSN_P (next)
2064 && GET_CODE (PATTERN (next)) == USE)
2065 && !NOTE_P (next))
2066 break;
2068 /* If that is the call, this may be the insn
2069 that loads the function address.
2071 Extract the function address from the insn
2072 that loads it into a register.
2073 If this insn was cse'd, we get incorrect code.
2075 So emit a new move insn that copies the
2076 function address into the register that the
2077 call insn will use. flow.c will delete any
2078 redundant stores that we have created. */
2079 if (CALL_P (next)
2080 && GET_CODE (body) == SET
2081 && REG_P (SET_DEST (body))
2082 && (n = find_reg_note (temp, REG_EQUAL,
2083 NULL_RTX)))
2085 fn_reg = SET_SRC (body);
2086 if (!REG_P (fn_reg))
2087 fn_reg = SET_DEST (body);
2088 fn_address = XEXP (n, 0);
2089 fn_address_insn = temp;
2091 /* We have the call insn.
2092 If it uses the register we suspect it might,
2093 load it with the correct address directly. */
2094 if (CALL_P (temp)
2095 && fn_address != 0
2096 && reg_referenced_p (fn_reg, body))
2097 loop_insn_emit_after (loop, 0, fn_address_insn,
2098 gen_move_insn
2099 (fn_reg, fn_address));
2101 if (CALL_P (temp))
2103 i1 = loop_call_insn_hoist (loop, body);
2104 /* Because the USAGE information potentially
2105 contains objects other than hard registers
2106 we need to copy it. */
2107 if (CALL_INSN_FUNCTION_USAGE (temp))
2108 CALL_INSN_FUNCTION_USAGE (i1)
2109 = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
2111 else
2112 i1 = loop_insn_hoist (loop, body);
2113 if (first == 0)
2114 first = i1;
2115 if (temp == fn_address_insn)
2116 fn_address_insn = i1;
2117 REG_NOTES (i1) = REG_NOTES (temp);
2118 REG_NOTES (temp) = NULL;
2119 delete_insn (temp);
2121 if (new_start == 0)
2122 new_start = first;
2124 if (m->savemode != VOIDmode)
2126 /* P sets REG to zero; but we should clear only
2127 the bits that are not covered by the mode
2128 m->savemode. */
2129 rtx reg = m->set_dest;
2130 rtx sequence;
2131 rtx tem;
2133 start_sequence ();
2134 tem = expand_simple_binop
2135 (GET_MODE (reg), AND, reg,
2136 GEN_INT ((((HOST_WIDE_INT) 1
2137 << GET_MODE_BITSIZE (m->savemode)))
2138 - 1),
2139 reg, 1, OPTAB_LIB_WIDEN);
2140 if (tem == 0)
2141 abort ();
2142 if (tem != reg)
2143 emit_move_insn (reg, tem);
2144 sequence = get_insns ();
2145 end_sequence ();
2146 i1 = loop_insn_hoist (loop, sequence);
2148 else if (CALL_P (p))
2150 i1 = loop_call_insn_hoist (loop, PATTERN (p));
2151 /* Because the USAGE information potentially
2152 contains objects other than hard registers
2153 we need to copy it. */
2154 if (CALL_INSN_FUNCTION_USAGE (p))
2155 CALL_INSN_FUNCTION_USAGE (i1)
2156 = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2158 else if (count == m->consec && m->move_insn_first)
2160 rtx seq;
2161 /* The SET_SRC might not be invariant, so we must
2162 use the REG_EQUAL note. */
2163 start_sequence ();
2164 emit_move_insn (m->insert_temp ? newreg : m->set_dest,
2165 m->set_src);
2166 seq = get_insns ();
2167 end_sequence ();
2169 add_label_notes (m->set_src, seq);
2171 i1 = loop_insn_hoist (loop, seq);
2172 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2173 set_unique_reg_note (i1, m->is_equiv ? REG_EQUIV
2174 : REG_EQUAL, m->set_src);
2176 else if (m->insert_temp)
2178 rtx *reg_map2 = xcalloc (REGNO (newreg),
2179 sizeof(rtx));
2180 reg_map2 [m->regno] = newreg;
2182 i1 = loop_insn_hoist (loop, copy_rtx (PATTERN (p)));
2183 replace_regs (i1, reg_map2, REGNO (newreg), 1);
2184 free (reg_map2);
2186 else
2187 i1 = loop_insn_hoist (loop, PATTERN (p));
2189 if (REG_NOTES (i1) == 0)
2191 REG_NOTES (i1) = REG_NOTES (p);
2192 REG_NOTES (p) = NULL;
2194 /* If there is a REG_EQUAL note present whose value
2195 is not loop invariant, then delete it, since it
2196 may cause problems with later optimization passes.
2197 It is possible for cse to create such notes
2198 like this as a result of record_jump_cond. */
2200 if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2201 && ! loop_invariant_p (loop, XEXP (temp, 0)))
2202 remove_note (i1, temp);
2205 if (new_start == 0)
2206 new_start = i1;
2208 if (loop_dump_stream)
2209 fprintf (loop_dump_stream, " moved to %d",
2210 INSN_UID (i1));
2212 /* If library call, now fix the REG_NOTES that contain
2213 insn pointers, namely REG_LIBCALL on FIRST
2214 and REG_RETVAL on I1. */
2215 if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2217 XEXP (temp, 0) = first;
2218 temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2219 XEXP (temp, 0) = i1;
2222 temp = p;
2223 delete_insn (p);
2224 p = NEXT_INSN (p);
2226 /* simplify_giv_expr expects that it can walk the insns
2227 at m->insn forwards and see this old sequence we are
2228 tossing here. delete_insn does preserve the next
2229 pointers, but when we skip over a NOTE we must fix
2230 it up. Otherwise that code walks into the non-deleted
2231 insn stream. */
2232 while (p && NOTE_P (p))
2233 p = NEXT_INSN (temp) = NEXT_INSN (p);
2235 if (m->insert_temp)
2237 rtx seq;
2238 /* Replace the original insn with a move from
2239 our newly created temp. */
2240 start_sequence ();
2241 emit_move_insn (m->set_dest, newreg);
2242 seq = get_insns ();
2243 end_sequence ();
2244 emit_insn_before (seq, p);
2248 /* The more regs we move, the less we like moving them. */
2249 threshold -= 3;
2252 m->done = 1;
2254 if (!m->insert_temp)
2256 /* Any other movable that loads the same register
2257 MUST be moved. */
2258 already_moved[regno] = 1;
2260 /* This reg has been moved out of one loop. */
2261 regs->array[regno].moved_once = 1;
2263 /* The reg set here is now invariant. */
2264 if (! m->partial)
2266 int i;
2267 for (i = 0; i < LOOP_REGNO_NREGS (regno, m->set_dest); i++)
2268 regs->array[regno+i].set_in_loop = 0;
2271 /* Change the length-of-life info for the register
2272 to say it lives at least the full length of this loop.
2273 This will help guide optimizations in outer loops. */
2275 if (REGNO_FIRST_LUID (regno) > INSN_LUID (loop_start))
2276 /* This is the old insn before all the moved insns.
2277 We can't use the moved insn because it is out of range
2278 in uid_luid. Only the old insns have luids. */
2279 REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2280 if (REGNO_LAST_LUID (regno) < INSN_LUID (loop_end))
2281 REGNO_LAST_UID (regno) = INSN_UID (loop_end);
2284 /* Combine with this moved insn any other matching movables. */
2286 if (! m->partial)
2287 for (m1 = movables->head; m1; m1 = m1->next)
2288 if (m1->match == m)
2290 rtx temp;
2292 /* Schedule the reg loaded by M1
2293 for replacement so that shares the reg of M.
2294 If the modes differ (only possible in restricted
2295 circumstances, make a SUBREG.
2297 Note this assumes that the target dependent files
2298 treat REG and SUBREG equally, including within
2299 GO_IF_LEGITIMATE_ADDRESS and in all the
2300 predicates since we never verify that replacing the
2301 original register with a SUBREG results in a
2302 recognizable insn. */
2303 if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2304 reg_map[m1->regno] = m->set_dest;
2305 else
2306 reg_map[m1->regno]
2307 = gen_lowpart_common (GET_MODE (m1->set_dest),
2308 m->set_dest);
2310 /* Get rid of the matching insn
2311 and prevent further processing of it. */
2312 m1->done = 1;
2314 /* If library call, delete all insns. */
2315 if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2316 NULL_RTX)))
2317 delete_insn_chain (XEXP (temp, 0), m1->insn);
2318 else
2319 delete_insn (m1->insn);
2321 /* Any other movable that loads the same register
2322 MUST be moved. */
2323 already_moved[m1->regno] = 1;
2325 /* The reg merged here is now invariant,
2326 if the reg it matches is invariant. */
2327 if (! m->partial)
2329 int i;
2330 for (i = 0;
2331 i < LOOP_REGNO_NREGS (regno, m1->set_dest);
2332 i++)
2333 regs->array[m1->regno+i].set_in_loop = 0;
2337 else if (loop_dump_stream)
2338 fprintf (loop_dump_stream, "not desirable");
2340 else if (loop_dump_stream && !m->match)
2341 fprintf (loop_dump_stream, "not safe");
2343 if (loop_dump_stream)
2344 fprintf (loop_dump_stream, "\n");
2347 if (new_start == 0)
2348 new_start = loop_start;
2350 /* Go through all the instructions in the loop, making
2351 all the register substitutions scheduled in REG_MAP. */
2352 for (p = new_start; p != loop_end; p = NEXT_INSN (p))
2353 if (INSN_P (p))
2355 replace_regs (PATTERN (p), reg_map, nregs, 0);
2356 replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2357 INSN_CODE (p) = -1;
2360 /* Clean up. */
2361 free (reg_map);
2362 free (already_moved);
2366 static void
2367 loop_movables_add (struct loop_movables *movables, struct movable *m)
2369 if (movables->head == 0)
2370 movables->head = m;
2371 else
2372 movables->last->next = m;
2373 movables->last = m;
2377 static void
2378 loop_movables_free (struct loop_movables *movables)
2380 struct movable *m;
2381 struct movable *m_next;
2383 for (m = movables->head; m; m = m_next)
2385 m_next = m->next;
2386 free (m);
2390 #if 0
2391 /* Scan X and replace the address of any MEM in it with ADDR.
2392 REG is the address that MEM should have before the replacement. */
2394 static void
2395 replace_call_address (rtx x, rtx reg, rtx addr)
2397 enum rtx_code code;
2398 int i;
2399 const char *fmt;
2401 if (x == 0)
2402 return;
2403 code = GET_CODE (x);
2404 switch (code)
2406 case PC:
2407 case CC0:
2408 case CONST_INT:
2409 case CONST_DOUBLE:
2410 case CONST:
2411 case SYMBOL_REF:
2412 case LABEL_REF:
2413 case REG:
2414 return;
2416 case SET:
2417 /* Short cut for very common case. */
2418 replace_call_address (XEXP (x, 1), reg, addr);
2419 return;
2421 case CALL:
2422 /* Short cut for very common case. */
2423 replace_call_address (XEXP (x, 0), reg, addr);
2424 return;
2426 case MEM:
2427 /* If this MEM uses a reg other than the one we expected,
2428 something is wrong. */
2429 if (XEXP (x, 0) != reg)
2430 abort ();
2431 XEXP (x, 0) = addr;
2432 return;
2434 default:
2435 break;
2438 fmt = GET_RTX_FORMAT (code);
2439 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2441 if (fmt[i] == 'e')
2442 replace_call_address (XEXP (x, i), reg, addr);
2443 else if (fmt[i] == 'E')
2445 int j;
2446 for (j = 0; j < XVECLEN (x, i); j++)
2447 replace_call_address (XVECEXP (x, i, j), reg, addr);
2451 #endif
2453 /* Return the number of memory refs to addresses that vary
2454 in the rtx X. */
2456 static int
2457 count_nonfixed_reads (const struct loop *loop, rtx x)
2459 enum rtx_code code;
2460 int i;
2461 const char *fmt;
2462 int value;
2464 if (x == 0)
2465 return 0;
2467 code = GET_CODE (x);
2468 switch (code)
2470 case PC:
2471 case CC0:
2472 case CONST_INT:
2473 case CONST_DOUBLE:
2474 case CONST:
2475 case SYMBOL_REF:
2476 case LABEL_REF:
2477 case REG:
2478 return 0;
2480 case MEM:
2481 return ((loop_invariant_p (loop, XEXP (x, 0)) != 1)
2482 + count_nonfixed_reads (loop, XEXP (x, 0)));
2484 default:
2485 break;
2488 value = 0;
2489 fmt = GET_RTX_FORMAT (code);
2490 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2492 if (fmt[i] == 'e')
2493 value += count_nonfixed_reads (loop, XEXP (x, i));
2494 if (fmt[i] == 'E')
2496 int j;
2497 for (j = 0; j < XVECLEN (x, i); j++)
2498 value += count_nonfixed_reads (loop, XVECEXP (x, i, j));
2501 return value;
2504 /* Scan a loop setting the elements `cont', `vtop', `loops_enclosed',
2505 `has_call', `has_nonconst_call', `has_volatile', `has_tablejump',
2506 `unknown_address_altered', `unknown_constant_address_altered', and
2507 `num_mem_sets' in LOOP. Also, fill in the array `mems' and the
2508 list `store_mems' in LOOP. */
2510 static void
2511 prescan_loop (struct loop *loop)
2513 int level = 1;
2514 rtx insn;
2515 struct loop_info *loop_info = LOOP_INFO (loop);
2516 rtx start = loop->start;
2517 rtx end = loop->end;
2518 /* The label after END. Jumping here is just like falling off the
2519 end of the loop. We use next_nonnote_insn instead of next_label
2520 as a hedge against the (pathological) case where some actual insn
2521 might end up between the two. */
2522 rtx exit_target = next_nonnote_insn (end);
2524 loop_info->has_indirect_jump = indirect_jump_in_function;
2525 loop_info->pre_header_has_call = 0;
2526 loop_info->has_call = 0;
2527 loop_info->has_nonconst_call = 0;
2528 loop_info->has_prefetch = 0;
2529 loop_info->has_volatile = 0;
2530 loop_info->has_tablejump = 0;
2531 loop_info->has_multiple_exit_targets = 0;
2532 loop->level = 1;
2534 loop_info->unknown_address_altered = 0;
2535 loop_info->unknown_constant_address_altered = 0;
2536 loop_info->store_mems = NULL_RTX;
2537 loop_info->first_loop_store_insn = NULL_RTX;
2538 loop_info->mems_idx = 0;
2539 loop_info->num_mem_sets = 0;
2540 /* If loop opts run twice, this was set on 1st pass for 2nd. */
2541 loop_info->preconditioned = NOTE_PRECONDITIONED (end);
2543 for (insn = start; insn && !LABEL_P (insn);
2544 insn = PREV_INSN (insn))
2546 if (CALL_P (insn))
2548 loop_info->pre_header_has_call = 1;
2549 break;
2553 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2554 insn = NEXT_INSN (insn))
2556 switch (GET_CODE (insn))
2558 case NOTE:
2559 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2561 ++level;
2562 /* Count number of loops contained in this one. */
2563 loop->level++;
2565 else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2566 --level;
2567 break;
2569 case CALL_INSN:
2570 if (! CONST_OR_PURE_CALL_P (insn))
2572 loop_info->unknown_address_altered = 1;
2573 loop_info->has_nonconst_call = 1;
2575 else if (pure_call_p (insn))
2576 loop_info->has_nonconst_call = 1;
2577 loop_info->has_call = 1;
2578 if (can_throw_internal (insn))
2579 loop_info->has_multiple_exit_targets = 1;
2581 /* Calls initializing constant objects have CLOBBER of MEM /u in the
2582 attached FUNCTION_USAGE expression list, not accounted for by the
2583 code above. We should note these to avoid missing dependencies in
2584 later references. */
2586 rtx fusage_entry;
2588 for (fusage_entry = CALL_INSN_FUNCTION_USAGE (insn);
2589 fusage_entry; fusage_entry = XEXP (fusage_entry, 1))
2591 rtx fusage = XEXP (fusage_entry, 0);
2593 if (GET_CODE (fusage) == CLOBBER
2594 && MEM_P (XEXP (fusage, 0))
2595 && RTX_UNCHANGING_P (XEXP (fusage, 0)))
2597 note_stores (fusage, note_addr_stored, loop_info);
2598 if (! loop_info->first_loop_store_insn
2599 && loop_info->store_mems)
2600 loop_info->first_loop_store_insn = insn;
2604 break;
2606 case JUMP_INSN:
2607 if (! loop_info->has_multiple_exit_targets)
2609 rtx set = pc_set (insn);
2611 if (set)
2613 rtx src = SET_SRC (set);
2614 rtx label1, label2;
2616 if (GET_CODE (src) == IF_THEN_ELSE)
2618 label1 = XEXP (src, 1);
2619 label2 = XEXP (src, 2);
2621 else
2623 label1 = src;
2624 label2 = NULL_RTX;
2629 if (label1 && label1 != pc_rtx)
2631 if (GET_CODE (label1) != LABEL_REF)
2633 /* Something tricky. */
2634 loop_info->has_multiple_exit_targets = 1;
2635 break;
2637 else if (XEXP (label1, 0) != exit_target
2638 && LABEL_OUTSIDE_LOOP_P (label1))
2640 /* A jump outside the current loop. */
2641 loop_info->has_multiple_exit_targets = 1;
2642 break;
2646 label1 = label2;
2647 label2 = NULL_RTX;
2649 while (label1);
2651 else
2653 /* A return, or something tricky. */
2654 loop_info->has_multiple_exit_targets = 1;
2657 /* Fall through. */
2659 case INSN:
2660 if (volatile_refs_p (PATTERN (insn)))
2661 loop_info->has_volatile = 1;
2663 if (JUMP_P (insn)
2664 && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2665 || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2666 loop_info->has_tablejump = 1;
2668 note_stores (PATTERN (insn), note_addr_stored, loop_info);
2669 if (! loop_info->first_loop_store_insn && loop_info->store_mems)
2670 loop_info->first_loop_store_insn = insn;
2672 if (flag_non_call_exceptions && can_throw_internal (insn))
2673 loop_info->has_multiple_exit_targets = 1;
2674 break;
2676 default:
2677 break;
2681 /* Now, rescan the loop, setting up the LOOP_MEMS array. */
2682 if (/* An exception thrown by a called function might land us
2683 anywhere. */
2684 ! loop_info->has_nonconst_call
2685 /* We don't want loads for MEMs moved to a location before the
2686 one at which their stack memory becomes allocated. (Note
2687 that this is not a problem for malloc, etc., since those
2688 require actual function calls. */
2689 && ! current_function_calls_alloca
2690 /* There are ways to leave the loop other than falling off the
2691 end. */
2692 && ! loop_info->has_multiple_exit_targets)
2693 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2694 insn = NEXT_INSN (insn))
2695 for_each_rtx (&insn, insert_loop_mem, loop_info);
2697 /* BLKmode MEMs are added to LOOP_STORE_MEM as necessary so
2698 that loop_invariant_p and load_mems can use true_dependence
2699 to determine what is really clobbered. */
2700 if (loop_info->unknown_address_altered)
2702 rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
2704 loop_info->store_mems
2705 = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
2707 if (loop_info->unknown_constant_address_altered)
2709 rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
2711 RTX_UNCHANGING_P (mem) = 1;
2712 loop_info->store_mems
2713 = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
2717 /* Invalidate all loops containing LABEL. */
2719 static void
2720 invalidate_loops_containing_label (rtx label)
2722 struct loop *loop;
2723 for (loop = uid_loop[INSN_UID (label)]; loop; loop = loop->outer)
2724 loop->invalid = 1;
2727 /* Scan the function looking for loops. Record the start and end of each loop.
2728 Also mark as invalid loops any loops that contain a setjmp or are branched
2729 to from outside the loop. */
2731 static void
2732 find_and_verify_loops (rtx f, struct loops *loops)
2734 rtx insn;
2735 rtx label;
2736 int num_loops;
2737 struct loop *current_loop;
2738 struct loop *next_loop;
2739 struct loop *loop;
2741 num_loops = loops->num;
2743 compute_luids (f, NULL_RTX, 0);
2745 /* If there are jumps to undefined labels,
2746 treat them as jumps out of any/all loops.
2747 This also avoids writing past end of tables when there are no loops. */
2748 uid_loop[0] = NULL;
2750 /* Find boundaries of loops, mark which loops are contained within
2751 loops, and invalidate loops that have setjmp. */
2753 num_loops = 0;
2754 current_loop = NULL;
2755 for (insn = f; insn; insn = NEXT_INSN (insn))
2757 if (NOTE_P (insn))
2758 switch (NOTE_LINE_NUMBER (insn))
2760 case NOTE_INSN_LOOP_BEG:
2761 next_loop = loops->array + num_loops;
2762 next_loop->num = num_loops;
2763 num_loops++;
2764 next_loop->start = insn;
2765 next_loop->outer = current_loop;
2766 current_loop = next_loop;
2767 break;
2769 case NOTE_INSN_LOOP_CONT:
2770 current_loop->cont = insn;
2771 break;
2773 case NOTE_INSN_LOOP_VTOP:
2774 current_loop->vtop = insn;
2775 break;
2777 case NOTE_INSN_LOOP_END:
2778 if (! current_loop)
2779 abort ();
2781 current_loop->end = insn;
2782 current_loop = current_loop->outer;
2783 break;
2785 default:
2786 break;
2789 if (CALL_P (insn)
2790 && find_reg_note (insn, REG_SETJMP, NULL))
2792 /* In this case, we must invalidate our current loop and any
2793 enclosing loop. */
2794 for (loop = current_loop; loop; loop = loop->outer)
2796 loop->invalid = 1;
2797 if (loop_dump_stream)
2798 fprintf (loop_dump_stream,
2799 "\nLoop at %d ignored due to setjmp.\n",
2800 INSN_UID (loop->start));
2804 /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2805 enclosing loop, but this doesn't matter. */
2806 uid_loop[INSN_UID (insn)] = current_loop;
2809 /* Any loop containing a label used in an initializer must be invalidated,
2810 because it can be jumped into from anywhere. */
2811 for (label = forced_labels; label; label = XEXP (label, 1))
2812 invalidate_loops_containing_label (XEXP (label, 0));
2814 /* Any loop containing a label used for an exception handler must be
2815 invalidated, because it can be jumped into from anywhere. */
2816 for_each_eh_label (invalidate_loops_containing_label);
2818 /* Now scan all insn's in the function. If any JUMP_INSN branches into a
2819 loop that it is not contained within, that loop is marked invalid.
2820 If any INSN or CALL_INSN uses a label's address, then the loop containing
2821 that label is marked invalid, because it could be jumped into from
2822 anywhere.
2824 Also look for blocks of code ending in an unconditional branch that
2825 exits the loop. If such a block is surrounded by a conditional
2826 branch around the block, move the block elsewhere (see below) and
2827 invert the jump to point to the code block. This may eliminate a
2828 label in our loop and will simplify processing by both us and a
2829 possible second cse pass. */
2831 for (insn = f; insn; insn = NEXT_INSN (insn))
2832 if (INSN_P (insn))
2834 struct loop *this_loop = uid_loop[INSN_UID (insn)];
2836 if (NONJUMP_INSN_P (insn) || CALL_P (insn))
2838 rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2839 if (note)
2840 invalidate_loops_containing_label (XEXP (note, 0));
2843 if (!JUMP_P (insn))
2844 continue;
2846 mark_loop_jump (PATTERN (insn), this_loop);
2848 /* See if this is an unconditional branch outside the loop. */
2849 if (this_loop
2850 && (GET_CODE (PATTERN (insn)) == RETURN
2851 || (any_uncondjump_p (insn)
2852 && onlyjump_p (insn)
2853 && (uid_loop[INSN_UID (JUMP_LABEL (insn))]
2854 != this_loop)))
2855 && get_max_uid () < max_uid_for_loop)
2857 rtx p;
2858 rtx our_next = next_real_insn (insn);
2859 rtx last_insn_to_move = NEXT_INSN (insn);
2860 struct loop *dest_loop;
2861 struct loop *outer_loop = NULL;
2863 /* Go backwards until we reach the start of the loop, a label,
2864 or a JUMP_INSN. */
2865 for (p = PREV_INSN (insn);
2866 !LABEL_P (p)
2867 && ! (NOTE_P (p)
2868 && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2869 && !JUMP_P (p);
2870 p = PREV_INSN (p))
2873 /* Check for the case where we have a jump to an inner nested
2874 loop, and do not perform the optimization in that case. */
2876 if (JUMP_LABEL (insn))
2878 dest_loop = uid_loop[INSN_UID (JUMP_LABEL (insn))];
2879 if (dest_loop)
2881 for (outer_loop = dest_loop; outer_loop;
2882 outer_loop = outer_loop->outer)
2883 if (outer_loop == this_loop)
2884 break;
2888 /* Make sure that the target of P is within the current loop. */
2890 if (JUMP_P (p) && JUMP_LABEL (p)
2891 && uid_loop[INSN_UID (JUMP_LABEL (p))] != this_loop)
2892 outer_loop = this_loop;
2894 /* If we stopped on a JUMP_INSN to the next insn after INSN,
2895 we have a block of code to try to move.
2897 We look backward and then forward from the target of INSN
2898 to find a BARRIER at the same loop depth as the target.
2899 If we find such a BARRIER, we make a new label for the start
2900 of the block, invert the jump in P and point it to that label,
2901 and move the block of code to the spot we found. */
2903 if (! outer_loop
2904 && JUMP_P (p)
2905 && JUMP_LABEL (p) != 0
2906 /* Just ignore jumps to labels that were never emitted.
2907 These always indicate compilation errors. */
2908 && INSN_UID (JUMP_LABEL (p)) != 0
2909 && any_condjump_p (p) && onlyjump_p (p)
2910 && next_real_insn (JUMP_LABEL (p)) == our_next
2911 /* If it's not safe to move the sequence, then we
2912 mustn't try. */
2913 && insns_safe_to_move_p (p, NEXT_INSN (insn),
2914 &last_insn_to_move))
2916 rtx target
2917 = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2918 struct loop *target_loop = uid_loop[INSN_UID (target)];
2919 rtx loc, loc2;
2920 rtx tmp;
2922 /* Search for possible garbage past the conditional jumps
2923 and look for the last barrier. */
2924 for (tmp = last_insn_to_move;
2925 tmp && !LABEL_P (tmp); tmp = NEXT_INSN (tmp))
2926 if (BARRIER_P (tmp))
2927 last_insn_to_move = tmp;
2929 for (loc = target; loc; loc = PREV_INSN (loc))
2930 if (BARRIER_P (loc)
2931 /* Don't move things inside a tablejump. */
2932 && ((loc2 = next_nonnote_insn (loc)) == 0
2933 || !LABEL_P (loc2)
2934 || (loc2 = next_nonnote_insn (loc2)) == 0
2935 || !JUMP_P (loc2)
2936 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2937 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2938 && uid_loop[INSN_UID (loc)] == target_loop)
2939 break;
2941 if (loc == 0)
2942 for (loc = target; loc; loc = NEXT_INSN (loc))
2943 if (BARRIER_P (loc)
2944 /* Don't move things inside a tablejump. */
2945 && ((loc2 = next_nonnote_insn (loc)) == 0
2946 || !LABEL_P (loc2)
2947 || (loc2 = next_nonnote_insn (loc2)) == 0
2948 || !JUMP_P (loc2)
2949 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2950 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2951 && uid_loop[INSN_UID (loc)] == target_loop)
2952 break;
2954 if (loc)
2956 rtx cond_label = JUMP_LABEL (p);
2957 rtx new_label = get_label_after (p);
2959 /* Ensure our label doesn't go away. */
2960 LABEL_NUSES (cond_label)++;
2962 /* Verify that uid_loop is large enough and that
2963 we can invert P. */
2964 if (invert_jump (p, new_label, 1))
2966 rtx q, r;
2968 /* If no suitable BARRIER was found, create a suitable
2969 one before TARGET. Since TARGET is a fall through
2970 path, we'll need to insert a jump around our block
2971 and add a BARRIER before TARGET.
2973 This creates an extra unconditional jump outside
2974 the loop. However, the benefits of removing rarely
2975 executed instructions from inside the loop usually
2976 outweighs the cost of the extra unconditional jump
2977 outside the loop. */
2978 if (loc == 0)
2980 rtx temp;
2982 temp = gen_jump (JUMP_LABEL (insn));
2983 temp = emit_jump_insn_before (temp, target);
2984 JUMP_LABEL (temp) = JUMP_LABEL (insn);
2985 LABEL_NUSES (JUMP_LABEL (insn))++;
2986 loc = emit_barrier_before (target);
2989 /* Include the BARRIER after INSN and copy the
2990 block after LOC. */
2991 if (squeeze_notes (&new_label, &last_insn_to_move))
2992 abort ();
2993 reorder_insns (new_label, last_insn_to_move, loc);
2995 /* All those insns are now in TARGET_LOOP. */
2996 for (q = new_label;
2997 q != NEXT_INSN (last_insn_to_move);
2998 q = NEXT_INSN (q))
2999 uid_loop[INSN_UID (q)] = target_loop;
3001 /* The label jumped to by INSN is no longer a loop
3002 exit. Unless INSN does not have a label (e.g.,
3003 it is a RETURN insn), search loop->exit_labels
3004 to find its label_ref, and remove it. Also turn
3005 off LABEL_OUTSIDE_LOOP_P bit. */
3006 if (JUMP_LABEL (insn))
3008 for (q = 0, r = this_loop->exit_labels;
3010 q = r, r = LABEL_NEXTREF (r))
3011 if (XEXP (r, 0) == JUMP_LABEL (insn))
3013 LABEL_OUTSIDE_LOOP_P (r) = 0;
3014 if (q)
3015 LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
3016 else
3017 this_loop->exit_labels = LABEL_NEXTREF (r);
3018 break;
3021 for (loop = this_loop; loop && loop != target_loop;
3022 loop = loop->outer)
3023 loop->exit_count--;
3025 /* If we didn't find it, then something is
3026 wrong. */
3027 if (! r)
3028 abort ();
3031 /* P is now a jump outside the loop, so it must be put
3032 in loop->exit_labels, and marked as such.
3033 The easiest way to do this is to just call
3034 mark_loop_jump again for P. */
3035 mark_loop_jump (PATTERN (p), this_loop);
3037 /* If INSN now jumps to the insn after it,
3038 delete INSN. */
3039 if (JUMP_LABEL (insn) != 0
3040 && (next_real_insn (JUMP_LABEL (insn))
3041 == next_real_insn (insn)))
3042 delete_related_insns (insn);
3045 /* Continue the loop after where the conditional
3046 branch used to jump, since the only branch insn
3047 in the block (if it still remains) is an inter-loop
3048 branch and hence needs no processing. */
3049 insn = NEXT_INSN (cond_label);
3051 if (--LABEL_NUSES (cond_label) == 0)
3052 delete_related_insns (cond_label);
3054 /* This loop will be continued with NEXT_INSN (insn). */
3055 insn = PREV_INSN (insn);
3062 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
3063 loops it is contained in, mark the target loop invalid.
3065 For speed, we assume that X is part of a pattern of a JUMP_INSN. */
3067 static void
3068 mark_loop_jump (rtx x, struct loop *loop)
3070 struct loop *dest_loop;
3071 struct loop *outer_loop;
3072 int i;
3074 switch (GET_CODE (x))
3076 case PC:
3077 case USE:
3078 case CLOBBER:
3079 case REG:
3080 case MEM:
3081 case CONST_INT:
3082 case CONST_DOUBLE:
3083 case RETURN:
3084 return;
3086 case CONST:
3087 /* There could be a label reference in here. */
3088 mark_loop_jump (XEXP (x, 0), loop);
3089 return;
3091 case PLUS:
3092 case MINUS:
3093 case MULT:
3094 mark_loop_jump (XEXP (x, 0), loop);
3095 mark_loop_jump (XEXP (x, 1), loop);
3096 return;
3098 case LO_SUM:
3099 /* This may refer to a LABEL_REF or SYMBOL_REF. */
3100 mark_loop_jump (XEXP (x, 1), loop);
3101 return;
3103 case SIGN_EXTEND:
3104 case ZERO_EXTEND:
3105 mark_loop_jump (XEXP (x, 0), loop);
3106 return;
3108 case LABEL_REF:
3109 dest_loop = uid_loop[INSN_UID (XEXP (x, 0))];
3111 /* Link together all labels that branch outside the loop. This
3112 is used by final_[bg]iv_value and the loop unrolling code. Also
3113 mark this LABEL_REF so we know that this branch should predict
3114 false. */
3116 /* A check to make sure the label is not in an inner nested loop,
3117 since this does not count as a loop exit. */
3118 if (dest_loop)
3120 for (outer_loop = dest_loop; outer_loop;
3121 outer_loop = outer_loop->outer)
3122 if (outer_loop == loop)
3123 break;
3125 else
3126 outer_loop = NULL;
3128 if (loop && ! outer_loop)
3130 LABEL_OUTSIDE_LOOP_P (x) = 1;
3131 LABEL_NEXTREF (x) = loop->exit_labels;
3132 loop->exit_labels = x;
3134 for (outer_loop = loop;
3135 outer_loop && outer_loop != dest_loop;
3136 outer_loop = outer_loop->outer)
3137 outer_loop->exit_count++;
3140 /* If this is inside a loop, but not in the current loop or one enclosed
3141 by it, it invalidates at least one loop. */
3143 if (! dest_loop)
3144 return;
3146 /* We must invalidate every nested loop containing the target of this
3147 label, except those that also contain the jump insn. */
3149 for (; dest_loop; dest_loop = dest_loop->outer)
3151 /* Stop when we reach a loop that also contains the jump insn. */
3152 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3153 if (dest_loop == outer_loop)
3154 return;
3156 /* If we get here, we know we need to invalidate a loop. */
3157 if (loop_dump_stream && ! dest_loop->invalid)
3158 fprintf (loop_dump_stream,
3159 "\nLoop at %d ignored due to multiple entry points.\n",
3160 INSN_UID (dest_loop->start));
3162 dest_loop->invalid = 1;
3164 return;
3166 case SET:
3167 /* If this is not setting pc, ignore. */
3168 if (SET_DEST (x) == pc_rtx)
3169 mark_loop_jump (SET_SRC (x), loop);
3170 return;
3172 case IF_THEN_ELSE:
3173 mark_loop_jump (XEXP (x, 1), loop);
3174 mark_loop_jump (XEXP (x, 2), loop);
3175 return;
3177 case PARALLEL:
3178 case ADDR_VEC:
3179 for (i = 0; i < XVECLEN (x, 0); i++)
3180 mark_loop_jump (XVECEXP (x, 0, i), loop);
3181 return;
3183 case ADDR_DIFF_VEC:
3184 for (i = 0; i < XVECLEN (x, 1); i++)
3185 mark_loop_jump (XVECEXP (x, 1, i), loop);
3186 return;
3188 default:
3189 /* Strictly speaking this is not a jump into the loop, only a possible
3190 jump out of the loop. However, we have no way to link the destination
3191 of this jump onto the list of exit labels. To be safe we mark this
3192 loop and any containing loops as invalid. */
3193 if (loop)
3195 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3197 if (loop_dump_stream && ! outer_loop->invalid)
3198 fprintf (loop_dump_stream,
3199 "\nLoop at %d ignored due to unknown exit jump.\n",
3200 INSN_UID (outer_loop->start));
3201 outer_loop->invalid = 1;
3204 return;
3208 /* Return nonzero if there is a label in the range from
3209 insn INSN to and including the insn whose luid is END
3210 INSN must have an assigned luid (i.e., it must not have
3211 been previously created by loop.c). */
3213 static int
3214 labels_in_range_p (rtx insn, int end)
3216 while (insn && INSN_LUID (insn) <= end)
3218 if (LABEL_P (insn))
3219 return 1;
3220 insn = NEXT_INSN (insn);
3223 return 0;
3226 /* Record that a memory reference X is being set. */
3228 static void
3229 note_addr_stored (rtx x, rtx y ATTRIBUTE_UNUSED,
3230 void *data ATTRIBUTE_UNUSED)
3232 struct loop_info *loop_info = data;
3234 if (x == 0 || !MEM_P (x))
3235 return;
3237 /* Count number of memory writes.
3238 This affects heuristics in strength_reduce. */
3239 loop_info->num_mem_sets++;
3241 /* BLKmode MEM means all memory is clobbered. */
3242 if (GET_MODE (x) == BLKmode)
3244 if (RTX_UNCHANGING_P (x))
3245 loop_info->unknown_constant_address_altered = 1;
3246 else
3247 loop_info->unknown_address_altered = 1;
3249 return;
3252 loop_info->store_mems = gen_rtx_EXPR_LIST (VOIDmode, x,
3253 loop_info->store_mems);
3256 /* X is a value modified by an INSN that references a biv inside a loop
3257 exit test (ie, X is somehow related to the value of the biv). If X
3258 is a pseudo that is used more than once, then the biv is (effectively)
3259 used more than once. DATA is a pointer to a loop_regs structure. */
3261 static void
3262 note_set_pseudo_multiple_uses (rtx x, rtx y ATTRIBUTE_UNUSED, void *data)
3264 struct loop_regs *regs = (struct loop_regs *) data;
3266 if (x == 0)
3267 return;
3269 while (GET_CODE (x) == STRICT_LOW_PART
3270 || GET_CODE (x) == SIGN_EXTRACT
3271 || GET_CODE (x) == ZERO_EXTRACT
3272 || GET_CODE (x) == SUBREG)
3273 x = XEXP (x, 0);
3275 if (!REG_P (x) || REGNO (x) < FIRST_PSEUDO_REGISTER)
3276 return;
3278 /* If we do not have usage information, or if we know the register
3279 is used more than once, note that fact for check_dbra_loop. */
3280 if (REGNO (x) >= max_reg_before_loop
3281 || ! regs->array[REGNO (x)].single_usage
3282 || regs->array[REGNO (x)].single_usage == const0_rtx)
3283 regs->multiple_uses = 1;
3286 /* Return nonzero if the rtx X is invariant over the current loop.
3288 The value is 2 if we refer to something only conditionally invariant.
3290 A memory ref is invariant if it is not volatile and does not conflict
3291 with anything stored in `loop_info->store_mems'. */
3294 loop_invariant_p (const struct loop *loop, rtx x)
3296 struct loop_info *loop_info = LOOP_INFO (loop);
3297 struct loop_regs *regs = LOOP_REGS (loop);
3298 int i;
3299 enum rtx_code code;
3300 const char *fmt;
3301 int conditional = 0;
3302 rtx mem_list_entry;
3304 if (x == 0)
3305 return 1;
3306 code = GET_CODE (x);
3307 switch (code)
3309 case CONST_INT:
3310 case CONST_DOUBLE:
3311 case SYMBOL_REF:
3312 case CONST:
3313 return 1;
3315 case LABEL_REF:
3316 /* A LABEL_REF is normally invariant, however, if we are unrolling
3317 loops, and this label is inside the loop, then it isn't invariant.
3318 This is because each unrolled copy of the loop body will have
3319 a copy of this label. If this was invariant, then an insn loading
3320 the address of this label into a register might get moved outside
3321 the loop, and then each loop body would end up using the same label.
3323 We don't know the loop bounds here though, so just fail for all
3324 labels. */
3325 if (flag_old_unroll_loops)
3326 return 0;
3327 else
3328 return 1;
3330 case PC:
3331 case CC0:
3332 case UNSPEC_VOLATILE:
3333 return 0;
3335 case REG:
3336 /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3337 since the reg might be set by initialization within the loop. */
3339 if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3340 || x == arg_pointer_rtx || x == pic_offset_table_rtx)
3341 && ! current_function_has_nonlocal_goto)
3342 return 1;
3344 if (LOOP_INFO (loop)->has_call
3345 && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3346 return 0;
3348 /* Out-of-range regs can occur when we are called from unrolling.
3349 These registers created by the unroller are set in the loop,
3350 hence are never invariant.
3351 Other out-of-range regs can be generated by load_mems; those that
3352 are written to in the loop are not invariant, while those that are
3353 not written to are invariant. It would be easy for load_mems
3354 to set n_times_set correctly for these registers, however, there
3355 is no easy way to distinguish them from registers created by the
3356 unroller. */
3358 if (REGNO (x) >= (unsigned) regs->num)
3359 return 0;
3361 if (regs->array[REGNO (x)].set_in_loop < 0)
3362 return 2;
3364 return regs->array[REGNO (x)].set_in_loop == 0;
3366 case MEM:
3367 /* Volatile memory references must be rejected. Do this before
3368 checking for read-only items, so that volatile read-only items
3369 will be rejected also. */
3370 if (MEM_VOLATILE_P (x))
3371 return 0;
3373 /* See if there is any dependence between a store and this load. */
3374 mem_list_entry = loop_info->store_mems;
3375 while (mem_list_entry)
3377 if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3378 x, rtx_varies_p))
3379 return 0;
3381 mem_list_entry = XEXP (mem_list_entry, 1);
3384 /* It's not invalidated by a store in memory
3385 but we must still verify the address is invariant. */
3386 break;
3388 case ASM_OPERANDS:
3389 /* Don't mess with insns declared volatile. */
3390 if (MEM_VOLATILE_P (x))
3391 return 0;
3392 break;
3394 default:
3395 break;
3398 fmt = GET_RTX_FORMAT (code);
3399 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3401 if (fmt[i] == 'e')
3403 int tem = loop_invariant_p (loop, XEXP (x, i));
3404 if (tem == 0)
3405 return 0;
3406 if (tem == 2)
3407 conditional = 1;
3409 else if (fmt[i] == 'E')
3411 int j;
3412 for (j = 0; j < XVECLEN (x, i); j++)
3414 int tem = loop_invariant_p (loop, XVECEXP (x, i, j));
3415 if (tem == 0)
3416 return 0;
3417 if (tem == 2)
3418 conditional = 1;
3424 return 1 + conditional;
3427 /* Return nonzero if all the insns in the loop that set REG
3428 are INSN and the immediately following insns,
3429 and if each of those insns sets REG in an invariant way
3430 (not counting uses of REG in them).
3432 The value is 2 if some of these insns are only conditionally invariant.
3434 We assume that INSN itself is the first set of REG
3435 and that its source is invariant. */
3437 static int
3438 consec_sets_invariant_p (const struct loop *loop, rtx reg, int n_sets,
3439 rtx insn)
3441 struct loop_regs *regs = LOOP_REGS (loop);
3442 rtx p = insn;
3443 unsigned int regno = REGNO (reg);
3444 rtx temp;
3445 /* Number of sets we have to insist on finding after INSN. */
3446 int count = n_sets - 1;
3447 int old = regs->array[regno].set_in_loop;
3448 int value = 0;
3449 int this;
3451 /* If N_SETS hit the limit, we can't rely on its value. */
3452 if (n_sets == 127)
3453 return 0;
3455 regs->array[regno].set_in_loop = 0;
3457 while (count > 0)
3459 enum rtx_code code;
3460 rtx set;
3462 p = NEXT_INSN (p);
3463 code = GET_CODE (p);
3465 /* If library call, skip to end of it. */
3466 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3467 p = XEXP (temp, 0);
3469 this = 0;
3470 if (code == INSN
3471 && (set = single_set (p))
3472 && REG_P (SET_DEST (set))
3473 && REGNO (SET_DEST (set)) == regno)
3475 this = loop_invariant_p (loop, SET_SRC (set));
3476 if (this != 0)
3477 value |= this;
3478 else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3480 /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3481 If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3482 notes are OK. */
3483 this = (CONSTANT_P (XEXP (temp, 0))
3484 || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3485 && loop_invariant_p (loop, XEXP (temp, 0))));
3486 if (this != 0)
3487 value |= this;
3490 if (this != 0)
3491 count--;
3492 else if (code != NOTE)
3494 regs->array[regno].set_in_loop = old;
3495 return 0;
3499 regs->array[regno].set_in_loop = old;
3500 /* If loop_invariant_p ever returned 2, we return 2. */
3501 return 1 + (value & 2);
3504 /* Look at all uses (not sets) of registers in X. For each, if it is
3505 the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3506 a different insn, set USAGE[REGNO] to const0_rtx. */
3508 static void
3509 find_single_use_in_loop (struct loop_regs *regs, rtx insn, rtx x)
3511 enum rtx_code code = GET_CODE (x);
3512 const char *fmt = GET_RTX_FORMAT (code);
3513 int i, j;
3515 if (code == REG)
3516 regs->array[REGNO (x)].single_usage
3517 = (regs->array[REGNO (x)].single_usage != 0
3518 && regs->array[REGNO (x)].single_usage != insn)
3519 ? const0_rtx : insn;
3521 else if (code == SET)
3523 /* Don't count SET_DEST if it is a REG; otherwise count things
3524 in SET_DEST because if a register is partially modified, it won't
3525 show up as a potential movable so we don't care how USAGE is set
3526 for it. */
3527 if (!REG_P (SET_DEST (x)))
3528 find_single_use_in_loop (regs, insn, SET_DEST (x));
3529 find_single_use_in_loop (regs, insn, SET_SRC (x));
3531 else
3532 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3534 if (fmt[i] == 'e' && XEXP (x, i) != 0)
3535 find_single_use_in_loop (regs, insn, XEXP (x, i));
3536 else if (fmt[i] == 'E')
3537 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3538 find_single_use_in_loop (regs, insn, XVECEXP (x, i, j));
3542 /* Count and record any set in X which is contained in INSN. Update
3543 REGS->array[I].MAY_NOT_OPTIMIZE and LAST_SET for any register I set
3544 in X. */
3546 static void
3547 count_one_set (struct loop_regs *regs, rtx insn, rtx x, rtx *last_set)
3549 if (GET_CODE (x) == CLOBBER && REG_P (XEXP (x, 0)))
3550 /* Don't move a reg that has an explicit clobber.
3551 It's not worth the pain to try to do it correctly. */
3552 regs->array[REGNO (XEXP (x, 0))].may_not_optimize = 1;
3554 if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3556 rtx dest = SET_DEST (x);
3557 while (GET_CODE (dest) == SUBREG
3558 || GET_CODE (dest) == ZERO_EXTRACT
3559 || GET_CODE (dest) == SIGN_EXTRACT
3560 || GET_CODE (dest) == STRICT_LOW_PART)
3561 dest = XEXP (dest, 0);
3562 if (REG_P (dest))
3564 int i;
3565 int regno = REGNO (dest);
3566 for (i = 0; i < LOOP_REGNO_NREGS (regno, dest); i++)
3568 /* If this is the first setting of this reg
3569 in current basic block, and it was set before,
3570 it must be set in two basic blocks, so it cannot
3571 be moved out of the loop. */
3572 if (regs->array[regno].set_in_loop > 0
3573 && last_set[regno] == 0)
3574 regs->array[regno+i].may_not_optimize = 1;
3575 /* If this is not first setting in current basic block,
3576 see if reg was used in between previous one and this.
3577 If so, neither one can be moved. */
3578 if (last_set[regno] != 0
3579 && reg_used_between_p (dest, last_set[regno], insn))
3580 regs->array[regno+i].may_not_optimize = 1;
3581 if (regs->array[regno+i].set_in_loop < 127)
3582 ++regs->array[regno+i].set_in_loop;
3583 last_set[regno+i] = insn;
3589 /* Given a loop that is bounded by LOOP->START and LOOP->END and that
3590 is entered at LOOP->SCAN_START, return 1 if the register set in SET
3591 contained in insn INSN is used by any insn that precedes INSN in
3592 cyclic order starting from the loop entry point.
3594 We don't want to use INSN_LUID here because if we restrict INSN to those
3595 that have a valid INSN_LUID, it means we cannot move an invariant out
3596 from an inner loop past two loops. */
3598 static int
3599 loop_reg_used_before_p (const struct loop *loop, rtx set, rtx insn)
3601 rtx reg = SET_DEST (set);
3602 rtx p;
3604 /* Scan forward checking for register usage. If we hit INSN, we
3605 are done. Otherwise, if we hit LOOP->END, wrap around to LOOP->START. */
3606 for (p = loop->scan_start; p != insn; p = NEXT_INSN (p))
3608 if (INSN_P (p) && reg_overlap_mentioned_p (reg, PATTERN (p)))
3609 return 1;
3611 if (p == loop->end)
3612 p = loop->start;
3615 return 0;
3619 /* Information we collect about arrays that we might want to prefetch. */
3620 struct prefetch_info
3622 struct iv_class *class; /* Class this prefetch is based on. */
3623 struct induction *giv; /* GIV this prefetch is based on. */
3624 rtx base_address; /* Start prefetching from this address plus
3625 index. */
3626 HOST_WIDE_INT index;
3627 HOST_WIDE_INT stride; /* Prefetch stride in bytes in each
3628 iteration. */
3629 unsigned int bytes_accessed; /* Sum of sizes of all accesses to this
3630 prefetch area in one iteration. */
3631 unsigned int total_bytes; /* Total bytes loop will access in this block.
3632 This is set only for loops with known
3633 iteration counts and is 0xffffffff
3634 otherwise. */
3635 int prefetch_in_loop; /* Number of prefetch insns in loop. */
3636 int prefetch_before_loop; /* Number of prefetch insns before loop. */
3637 unsigned int write : 1; /* 1 for read/write prefetches. */
3640 /* Data used by check_store function. */
3641 struct check_store_data
3643 rtx mem_address;
3644 int mem_write;
3647 static void check_store (rtx, rtx, void *);
3648 static void emit_prefetch_instructions (struct loop *);
3649 static int rtx_equal_for_prefetch_p (rtx, rtx);
3651 /* Set mem_write when mem_address is found. Used as callback to
3652 note_stores. */
3653 static void
3654 check_store (rtx x, rtx pat ATTRIBUTE_UNUSED, void *data)
3656 struct check_store_data *d = (struct check_store_data *) data;
3658 if ((MEM_P (x)) && rtx_equal_p (d->mem_address, XEXP (x, 0)))
3659 d->mem_write = 1;
3662 /* Like rtx_equal_p, but attempts to swap commutative operands. This is
3663 important to get some addresses combined. Later more sophisticated
3664 transformations can be added when necessary.
3666 ??? Same trick with swapping operand is done at several other places.
3667 It can be nice to develop some common way to handle this. */
3669 static int
3670 rtx_equal_for_prefetch_p (rtx x, rtx y)
3672 int i;
3673 int j;
3674 enum rtx_code code = GET_CODE (x);
3675 const char *fmt;
3677 if (x == y)
3678 return 1;
3679 if (code != GET_CODE (y))
3680 return 0;
3682 if (COMMUTATIVE_ARITH_P (x))
3684 return ((rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 0))
3685 && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 1)))
3686 || (rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 1))
3687 && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 0))));
3690 /* Compare the elements. If any pair of corresponding elements fails to
3691 match, return 0 for the whole thing. */
3693 fmt = GET_RTX_FORMAT (code);
3694 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3696 switch (fmt[i])
3698 case 'w':
3699 if (XWINT (x, i) != XWINT (y, i))
3700 return 0;
3701 break;
3703 case 'i':
3704 if (XINT (x, i) != XINT (y, i))
3705 return 0;
3706 break;
3708 case 'E':
3709 /* Two vectors must have the same length. */
3710 if (XVECLEN (x, i) != XVECLEN (y, i))
3711 return 0;
3713 /* And the corresponding elements must match. */
3714 for (j = 0; j < XVECLEN (x, i); j++)
3715 if (rtx_equal_for_prefetch_p (XVECEXP (x, i, j),
3716 XVECEXP (y, i, j)) == 0)
3717 return 0;
3718 break;
3720 case 'e':
3721 if (rtx_equal_for_prefetch_p (XEXP (x, i), XEXP (y, i)) == 0)
3722 return 0;
3723 break;
3725 case 's':
3726 if (strcmp (XSTR (x, i), XSTR (y, i)))
3727 return 0;
3728 break;
3730 case 'u':
3731 /* These are just backpointers, so they don't matter. */
3732 break;
3734 case '0':
3735 break;
3737 /* It is believed that rtx's at this level will never
3738 contain anything but integers and other rtx's,
3739 except for within LABEL_REFs and SYMBOL_REFs. */
3740 default:
3741 abort ();
3744 return 1;
3747 /* Remove constant addition value from the expression X (when present)
3748 and return it. */
3750 static HOST_WIDE_INT
3751 remove_constant_addition (rtx *x)
3753 HOST_WIDE_INT addval = 0;
3754 rtx exp = *x;
3756 /* Avoid clobbering a shared CONST expression. */
3757 if (GET_CODE (exp) == CONST)
3759 if (GET_CODE (XEXP (exp, 0)) == PLUS
3760 && GET_CODE (XEXP (XEXP (exp, 0), 0)) == SYMBOL_REF
3761 && GET_CODE (XEXP (XEXP (exp, 0), 1)) == CONST_INT)
3763 *x = XEXP (XEXP (exp, 0), 0);
3764 return INTVAL (XEXP (XEXP (exp, 0), 1));
3766 return 0;
3769 if (GET_CODE (exp) == CONST_INT)
3771 addval = INTVAL (exp);
3772 *x = const0_rtx;
3775 /* For plus expression recurse on ourself. */
3776 else if (GET_CODE (exp) == PLUS)
3778 addval += remove_constant_addition (&XEXP (exp, 0));
3779 addval += remove_constant_addition (&XEXP (exp, 1));
3781 /* In case our parameter was constant, remove extra zero from the
3782 expression. */
3783 if (XEXP (exp, 0) == const0_rtx)
3784 *x = XEXP (exp, 1);
3785 else if (XEXP (exp, 1) == const0_rtx)
3786 *x = XEXP (exp, 0);
3789 return addval;
3792 /* Attempt to identify accesses to arrays that are most likely to cause cache
3793 misses, and emit prefetch instructions a few prefetch blocks forward.
3795 To detect the arrays we use the GIV information that was collected by the
3796 strength reduction pass.
3798 The prefetch instructions are generated after the GIV information is done
3799 and before the strength reduction process. The new GIVs are injected into
3800 the strength reduction tables, so the prefetch addresses are optimized as
3801 well.
3803 GIVs are split into base address, stride, and constant addition values.
3804 GIVs with the same address, stride and close addition values are combined
3805 into a single prefetch. Also writes to GIVs are detected, so that prefetch
3806 for write instructions can be used for the block we write to, on machines
3807 that support write prefetches.
3809 Several heuristics are used to determine when to prefetch. They are
3810 controlled by defined symbols that can be overridden for each target. */
3812 static void
3813 emit_prefetch_instructions (struct loop *loop)
3815 int num_prefetches = 0;
3816 int num_real_prefetches = 0;
3817 int num_real_write_prefetches = 0;
3818 int num_prefetches_before = 0;
3819 int num_write_prefetches_before = 0;
3820 int ahead = 0;
3821 int i;
3822 struct iv_class *bl;
3823 struct induction *iv;
3824 struct prefetch_info info[MAX_PREFETCHES];
3825 struct loop_ivs *ivs = LOOP_IVS (loop);
3827 if (!HAVE_prefetch)
3828 return;
3830 /* Consider only loops w/o calls. When a call is done, the loop is probably
3831 slow enough to read the memory. */
3832 if (PREFETCH_NO_CALL && LOOP_INFO (loop)->has_call)
3834 if (loop_dump_stream)
3835 fprintf (loop_dump_stream, "Prefetch: ignoring loop: has call.\n");
3837 return;
3840 /* Don't prefetch in loops known to have few iterations. */
3841 if (PREFETCH_NO_LOW_LOOPCNT
3842 && LOOP_INFO (loop)->n_iterations
3843 && LOOP_INFO (loop)->n_iterations <= PREFETCH_LOW_LOOPCNT)
3845 if (loop_dump_stream)
3846 fprintf (loop_dump_stream,
3847 "Prefetch: ignoring loop: not enough iterations.\n");
3848 return;
3851 /* Search all induction variables and pick those interesting for the prefetch
3852 machinery. */
3853 for (bl = ivs->list; bl; bl = bl->next)
3855 struct induction *biv = bl->biv, *biv1;
3856 int basestride = 0;
3858 biv1 = biv;
3860 /* Expect all BIVs to be executed in each iteration. This makes our
3861 analysis more conservative. */
3862 while (biv1)
3864 /* Discard non-constant additions that we can't handle well yet, and
3865 BIVs that are executed multiple times; such BIVs ought to be
3866 handled in the nested loop. We accept not_every_iteration BIVs,
3867 since these only result in larger strides and make our
3868 heuristics more conservative. */
3869 if (GET_CODE (biv->add_val) != CONST_INT)
3871 if (loop_dump_stream)
3873 fprintf (loop_dump_stream,
3874 "Prefetch: ignoring biv %d: non-constant addition at insn %d:",
3875 REGNO (biv->src_reg), INSN_UID (biv->insn));
3876 print_rtl (loop_dump_stream, biv->add_val);
3877 fprintf (loop_dump_stream, "\n");
3879 break;
3882 if (biv->maybe_multiple)
3884 if (loop_dump_stream)
3886 fprintf (loop_dump_stream,
3887 "Prefetch: ignoring biv %d: maybe_multiple at insn %i:",
3888 REGNO (biv->src_reg), INSN_UID (biv->insn));
3889 print_rtl (loop_dump_stream, biv->add_val);
3890 fprintf (loop_dump_stream, "\n");
3892 break;
3895 basestride += INTVAL (biv1->add_val);
3896 biv1 = biv1->next_iv;
3899 if (biv1 || !basestride)
3900 continue;
3902 for (iv = bl->giv; iv; iv = iv->next_iv)
3904 rtx address;
3905 rtx temp;
3906 HOST_WIDE_INT index = 0;
3907 int add = 1;
3908 HOST_WIDE_INT stride = 0;
3909 int stride_sign = 1;
3910 struct check_store_data d;
3911 const char *ignore_reason = NULL;
3912 int size = GET_MODE_SIZE (GET_MODE (iv));
3914 /* See whether an induction variable is interesting to us and if
3915 not, report the reason. */
3916 if (iv->giv_type != DEST_ADDR)
3917 ignore_reason = "giv is not a destination address";
3919 /* We are interested only in constant stride memory references
3920 in order to be able to compute density easily. */
3921 else if (GET_CODE (iv->mult_val) != CONST_INT)
3922 ignore_reason = "stride is not constant";
3924 else
3926 stride = INTVAL (iv->mult_val) * basestride;
3927 if (stride < 0)
3929 stride = -stride;
3930 stride_sign = -1;
3933 /* On some targets, reversed order prefetches are not
3934 worthwhile. */
3935 if (PREFETCH_NO_REVERSE_ORDER && stride_sign < 0)
3936 ignore_reason = "reversed order stride";
3938 /* Prefetch of accesses with an extreme stride might not be
3939 worthwhile, either. */
3940 else if (PREFETCH_NO_EXTREME_STRIDE
3941 && stride > PREFETCH_EXTREME_STRIDE)
3942 ignore_reason = "extreme stride";
3944 /* Ignore GIVs with varying add values; we can't predict the
3945 value for the next iteration. */
3946 else if (!loop_invariant_p (loop, iv->add_val))
3947 ignore_reason = "giv has varying add value";
3949 /* Ignore GIVs in the nested loops; they ought to have been
3950 handled already. */
3951 else if (iv->maybe_multiple)
3952 ignore_reason = "giv is in nested loop";
3955 if (ignore_reason != NULL)
3957 if (loop_dump_stream)
3958 fprintf (loop_dump_stream,
3959 "Prefetch: ignoring giv at %d: %s.\n",
3960 INSN_UID (iv->insn), ignore_reason);
3961 continue;
3964 /* Determine the pointer to the basic array we are examining. It is
3965 the sum of the BIV's initial value and the GIV's add_val. */
3966 address = copy_rtx (iv->add_val);
3967 temp = copy_rtx (bl->initial_value);
3969 address = simplify_gen_binary (PLUS, Pmode, temp, address);
3970 index = remove_constant_addition (&address);
3972 d.mem_write = 0;
3973 d.mem_address = *iv->location;
3975 /* When the GIV is not always executed, we might be better off by
3976 not dirtying the cache pages. */
3977 if (PREFETCH_CONDITIONAL || iv->always_executed)
3978 note_stores (PATTERN (iv->insn), check_store, &d);
3979 else
3981 if (loop_dump_stream)
3982 fprintf (loop_dump_stream, "Prefetch: Ignoring giv at %d: %s\n",
3983 INSN_UID (iv->insn), "in conditional code.");
3984 continue;
3987 /* Attempt to find another prefetch to the same array and see if we
3988 can merge this one. */
3989 for (i = 0; i < num_prefetches; i++)
3990 if (rtx_equal_for_prefetch_p (address, info[i].base_address)
3991 && stride == info[i].stride)
3993 /* In case both access same array (same location
3994 just with small difference in constant indexes), merge
3995 the prefetches. Just do the later and the earlier will
3996 get prefetched from previous iteration.
3997 The artificial threshold should not be too small,
3998 but also not bigger than small portion of memory usually
3999 traversed by single loop. */
4000 if (index >= info[i].index
4001 && index - info[i].index < PREFETCH_EXTREME_DIFFERENCE)
4003 info[i].write |= d.mem_write;
4004 info[i].bytes_accessed += size;
4005 info[i].index = index;
4006 info[i].giv = iv;
4007 info[i].class = bl;
4008 info[num_prefetches].base_address = address;
4009 add = 0;
4010 break;
4013 if (index < info[i].index
4014 && info[i].index - index < PREFETCH_EXTREME_DIFFERENCE)
4016 info[i].write |= d.mem_write;
4017 info[i].bytes_accessed += size;
4018 add = 0;
4019 break;
4023 /* Merging failed. */
4024 if (add)
4026 info[num_prefetches].giv = iv;
4027 info[num_prefetches].class = bl;
4028 info[num_prefetches].index = index;
4029 info[num_prefetches].stride = stride;
4030 info[num_prefetches].base_address = address;
4031 info[num_prefetches].write = d.mem_write;
4032 info[num_prefetches].bytes_accessed = size;
4033 num_prefetches++;
4034 if (num_prefetches >= MAX_PREFETCHES)
4036 if (loop_dump_stream)
4037 fprintf (loop_dump_stream,
4038 "Maximal number of prefetches exceeded.\n");
4039 return;
4045 for (i = 0; i < num_prefetches; i++)
4047 int density;
4049 /* Attempt to calculate the total number of bytes fetched by all
4050 iterations of the loop. Avoid overflow. */
4051 if (LOOP_INFO (loop)->n_iterations
4052 && ((unsigned HOST_WIDE_INT) (0xffffffff / info[i].stride)
4053 >= LOOP_INFO (loop)->n_iterations))
4054 info[i].total_bytes = info[i].stride * LOOP_INFO (loop)->n_iterations;
4055 else
4056 info[i].total_bytes = 0xffffffff;
4058 density = info[i].bytes_accessed * 100 / info[i].stride;
4060 /* Prefetch might be worthwhile only when the loads/stores are dense. */
4061 if (PREFETCH_ONLY_DENSE_MEM)
4062 if (density * 256 > PREFETCH_DENSE_MEM * 100
4063 && (info[i].total_bytes / PREFETCH_BLOCK
4064 >= PREFETCH_BLOCKS_BEFORE_LOOP_MIN))
4066 info[i].prefetch_before_loop = 1;
4067 info[i].prefetch_in_loop
4068 = (info[i].total_bytes / PREFETCH_BLOCK
4069 > PREFETCH_BLOCKS_BEFORE_LOOP_MAX);
4071 else
4073 info[i].prefetch_in_loop = 0, info[i].prefetch_before_loop = 0;
4074 if (loop_dump_stream)
4075 fprintf (loop_dump_stream,
4076 "Prefetch: ignoring giv at %d: %d%% density is too low.\n",
4077 INSN_UID (info[i].giv->insn), density);
4079 else
4080 info[i].prefetch_in_loop = 1, info[i].prefetch_before_loop = 1;
4082 /* Find how many prefetch instructions we'll use within the loop. */
4083 if (info[i].prefetch_in_loop != 0)
4085 info[i].prefetch_in_loop = ((info[i].stride + PREFETCH_BLOCK - 1)
4086 / PREFETCH_BLOCK);
4087 num_real_prefetches += info[i].prefetch_in_loop;
4088 if (info[i].write)
4089 num_real_write_prefetches += info[i].prefetch_in_loop;
4093 /* Determine how many iterations ahead to prefetch within the loop, based
4094 on how many prefetches we currently expect to do within the loop. */
4095 if (num_real_prefetches != 0)
4097 if ((ahead = SIMULTANEOUS_PREFETCHES / num_real_prefetches) == 0)
4099 if (loop_dump_stream)
4100 fprintf (loop_dump_stream,
4101 "Prefetch: ignoring prefetches within loop: ahead is zero; %d < %d\n",
4102 SIMULTANEOUS_PREFETCHES, num_real_prefetches);
4103 num_real_prefetches = 0, num_real_write_prefetches = 0;
4106 /* We'll also use AHEAD to determine how many prefetch instructions to
4107 emit before a loop, so don't leave it zero. */
4108 if (ahead == 0)
4109 ahead = PREFETCH_BLOCKS_BEFORE_LOOP_MAX;
4111 for (i = 0; i < num_prefetches; i++)
4113 /* Update if we've decided not to prefetch anything within the loop. */
4114 if (num_real_prefetches == 0)
4115 info[i].prefetch_in_loop = 0;
4117 /* Find how many prefetch instructions we'll use before the loop. */
4118 if (info[i].prefetch_before_loop != 0)
4120 int n = info[i].total_bytes / PREFETCH_BLOCK;
4121 if (n > ahead)
4122 n = ahead;
4123 info[i].prefetch_before_loop = n;
4124 num_prefetches_before += n;
4125 if (info[i].write)
4126 num_write_prefetches_before += n;
4129 if (loop_dump_stream)
4131 if (info[i].prefetch_in_loop == 0
4132 && info[i].prefetch_before_loop == 0)
4133 continue;
4134 fprintf (loop_dump_stream, "Prefetch insn: %d",
4135 INSN_UID (info[i].giv->insn));
4136 fprintf (loop_dump_stream,
4137 "; in loop: %d; before: %d; %s\n",
4138 info[i].prefetch_in_loop,
4139 info[i].prefetch_before_loop,
4140 info[i].write ? "read/write" : "read only");
4141 fprintf (loop_dump_stream,
4142 " density: %d%%; bytes_accessed: %u; total_bytes: %u\n",
4143 (int) (info[i].bytes_accessed * 100 / info[i].stride),
4144 info[i].bytes_accessed, info[i].total_bytes);
4145 fprintf (loop_dump_stream, " index: " HOST_WIDE_INT_PRINT_DEC
4146 "; stride: " HOST_WIDE_INT_PRINT_DEC "; address: ",
4147 info[i].index, info[i].stride);
4148 print_rtl (loop_dump_stream, info[i].base_address);
4149 fprintf (loop_dump_stream, "\n");
4153 if (num_real_prefetches + num_prefetches_before > 0)
4155 /* Record that this loop uses prefetch instructions. */
4156 LOOP_INFO (loop)->has_prefetch = 1;
4158 if (loop_dump_stream)
4160 fprintf (loop_dump_stream, "Real prefetches needed within loop: %d (write: %d)\n",
4161 num_real_prefetches, num_real_write_prefetches);
4162 fprintf (loop_dump_stream, "Real prefetches needed before loop: %d (write: %d)\n",
4163 num_prefetches_before, num_write_prefetches_before);
4167 for (i = 0; i < num_prefetches; i++)
4169 int y;
4171 for (y = 0; y < info[i].prefetch_in_loop; y++)
4173 rtx loc = copy_rtx (*info[i].giv->location);
4174 rtx insn;
4175 int bytes_ahead = PREFETCH_BLOCK * (ahead + y);
4176 rtx before_insn = info[i].giv->insn;
4177 rtx prev_insn = PREV_INSN (info[i].giv->insn);
4178 rtx seq;
4180 /* We can save some effort by offsetting the address on
4181 architectures with offsettable memory references. */
4182 if (offsettable_address_p (0, VOIDmode, loc))
4183 loc = plus_constant (loc, bytes_ahead);
4184 else
4186 rtx reg = gen_reg_rtx (Pmode);
4187 loop_iv_add_mult_emit_before (loop, loc, const1_rtx,
4188 GEN_INT (bytes_ahead), reg,
4189 0, before_insn);
4190 loc = reg;
4193 start_sequence ();
4194 /* Make sure the address operand is valid for prefetch. */
4195 if (! (*insn_data[(int)CODE_FOR_prefetch].operand[0].predicate)
4196 (loc, insn_data[(int)CODE_FOR_prefetch].operand[0].mode))
4197 loc = force_reg (Pmode, loc);
4198 emit_insn (gen_prefetch (loc, GEN_INT (info[i].write),
4199 GEN_INT (3)));
4200 seq = get_insns ();
4201 end_sequence ();
4202 emit_insn_before (seq, before_insn);
4204 /* Check all insns emitted and record the new GIV
4205 information. */
4206 insn = NEXT_INSN (prev_insn);
4207 while (insn != before_insn)
4209 insn = check_insn_for_givs (loop, insn,
4210 info[i].giv->always_executed,
4211 info[i].giv->maybe_multiple);
4212 insn = NEXT_INSN (insn);
4216 if (PREFETCH_BEFORE_LOOP)
4218 /* Emit insns before the loop to fetch the first cache lines or,
4219 if we're not prefetching within the loop, everything we expect
4220 to need. */
4221 for (y = 0; y < info[i].prefetch_before_loop; y++)
4223 rtx reg = gen_reg_rtx (Pmode);
4224 rtx loop_start = loop->start;
4225 rtx init_val = info[i].class->initial_value;
4226 rtx add_val = simplify_gen_binary (PLUS, Pmode,
4227 info[i].giv->add_val,
4228 GEN_INT (y * PREFETCH_BLOCK));
4230 /* Functions called by LOOP_IV_ADD_EMIT_BEFORE expect a
4231 non-constant INIT_VAL to have the same mode as REG, which
4232 in this case we know to be Pmode. */
4233 if (GET_MODE (init_val) != Pmode && !CONSTANT_P (init_val))
4235 rtx seq;
4237 start_sequence ();
4238 init_val = convert_to_mode (Pmode, init_val, 0);
4239 seq = get_insns ();
4240 end_sequence ();
4241 loop_insn_emit_before (loop, 0, loop_start, seq);
4243 loop_iv_add_mult_emit_before (loop, init_val,
4244 info[i].giv->mult_val,
4245 add_val, reg, 0, loop_start);
4246 emit_insn_before (gen_prefetch (reg, GEN_INT (info[i].write),
4247 GEN_INT (3)),
4248 loop_start);
4253 return;
4256 /* Communication with routines called via `note_stores'. */
4258 static rtx note_insn;
4260 /* Dummy register to have nonzero DEST_REG for DEST_ADDR type givs. */
4262 static rtx addr_placeholder;
4264 /* ??? Unfinished optimizations, and possible future optimizations,
4265 for the strength reduction code. */
4267 /* ??? The interaction of biv elimination, and recognition of 'constant'
4268 bivs, may cause problems. */
4270 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
4271 performance problems.
4273 Perhaps don't eliminate things that can be combined with an addressing
4274 mode. Find all givs that have the same biv, mult_val, and add_val;
4275 then for each giv, check to see if its only use dies in a following
4276 memory address. If so, generate a new memory address and check to see
4277 if it is valid. If it is valid, then store the modified memory address,
4278 otherwise, mark the giv as not done so that it will get its own iv. */
4280 /* ??? Could try to optimize branches when it is known that a biv is always
4281 positive. */
4283 /* ??? When replace a biv in a compare insn, we should replace with closest
4284 giv so that an optimized branch can still be recognized by the combiner,
4285 e.g. the VAX acb insn. */
4287 /* ??? Many of the checks involving uid_luid could be simplified if regscan
4288 was rerun in loop_optimize whenever a register was added or moved.
4289 Also, some of the optimizations could be a little less conservative. */
4291 /* Scan the loop body and call FNCALL for each insn. In the addition to the
4292 LOOP and INSN parameters pass MAYBE_MULTIPLE and NOT_EVERY_ITERATION to the
4293 callback.
4295 NOT_EVERY_ITERATION is 1 if current insn is not known to be executed at
4296 least once for every loop iteration except for the last one.
4298 MAYBE_MULTIPLE is 1 if current insn may be executed more than once for every
4299 loop iteration.
4301 void
4302 for_each_insn_in_loop (struct loop *loop, loop_insn_callback fncall)
4304 int not_every_iteration = 0;
4305 int maybe_multiple = 0;
4306 int past_loop_latch = 0;
4307 int loop_depth = 0;
4308 rtx p;
4310 /* If loop_scan_start points to the loop exit test, we have to be wary of
4311 subversive use of gotos inside expression statements. */
4312 if (prev_nonnote_insn (loop->scan_start) != prev_nonnote_insn (loop->start))
4313 maybe_multiple = back_branch_in_range_p (loop, loop->scan_start);
4315 /* Scan through loop and update NOT_EVERY_ITERATION and MAYBE_MULTIPLE. */
4316 for (p = next_insn_in_loop (loop, loop->scan_start);
4317 p != NULL_RTX;
4318 p = next_insn_in_loop (loop, p))
4320 p = fncall (loop, p, not_every_iteration, maybe_multiple);
4322 /* Past CODE_LABEL, we get to insns that may be executed multiple
4323 times. The only way we can be sure that they can't is if every
4324 jump insn between here and the end of the loop either
4325 returns, exits the loop, is a jump to a location that is still
4326 behind the label, or is a jump to the loop start. */
4328 if (LABEL_P (p))
4330 rtx insn = p;
4332 maybe_multiple = 0;
4334 while (1)
4336 insn = NEXT_INSN (insn);
4337 if (insn == loop->scan_start)
4338 break;
4339 if (insn == loop->end)
4341 if (loop->top != 0)
4342 insn = loop->top;
4343 else
4344 break;
4345 if (insn == loop->scan_start)
4346 break;
4349 if (JUMP_P (insn)
4350 && GET_CODE (PATTERN (insn)) != RETURN
4351 && (!any_condjump_p (insn)
4352 || (JUMP_LABEL (insn) != 0
4353 && JUMP_LABEL (insn) != loop->scan_start
4354 && !loop_insn_first_p (p, JUMP_LABEL (insn)))))
4356 maybe_multiple = 1;
4357 break;
4362 /* Past a jump, we get to insns for which we can't count
4363 on whether they will be executed during each iteration. */
4364 /* This code appears twice in strength_reduce. There is also similar
4365 code in scan_loop. */
4366 if (JUMP_P (p)
4367 /* If we enter the loop in the middle, and scan around to the
4368 beginning, don't set not_every_iteration for that.
4369 This can be any kind of jump, since we want to know if insns
4370 will be executed if the loop is executed. */
4371 && !(JUMP_LABEL (p) == loop->top
4372 && ((NEXT_INSN (NEXT_INSN (p)) == loop->end
4373 && any_uncondjump_p (p))
4374 || (NEXT_INSN (p) == loop->end && any_condjump_p (p)))))
4376 rtx label = 0;
4378 /* If this is a jump outside the loop, then it also doesn't
4379 matter. Check to see if the target of this branch is on the
4380 loop->exits_labels list. */
4382 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
4383 if (XEXP (label, 0) == JUMP_LABEL (p))
4384 break;
4386 if (!label)
4387 not_every_iteration = 1;
4390 else if (NOTE_P (p))
4392 /* At the virtual top of a converted loop, insns are again known to
4393 be executed each iteration: logically, the loop begins here
4394 even though the exit code has been duplicated.
4396 Insns are also again known to be executed each iteration at
4397 the LOOP_CONT note. */
4398 if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
4399 || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
4400 && loop_depth == 0)
4401 not_every_iteration = 0;
4402 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
4403 loop_depth++;
4404 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
4405 loop_depth--;
4408 /* Note if we pass a loop latch. If we do, then we can not clear
4409 NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
4410 a loop since a jump before the last CODE_LABEL may have started
4411 a new loop iteration.
4413 Note that LOOP_TOP is only set for rotated loops and we need
4414 this check for all loops, so compare against the CODE_LABEL
4415 which immediately follows LOOP_START. */
4416 if (JUMP_P (p)
4417 && JUMP_LABEL (p) == NEXT_INSN (loop->start))
4418 past_loop_latch = 1;
4420 /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4421 an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4422 or not an insn is known to be executed each iteration of the
4423 loop, whether or not any iterations are known to occur.
4425 Therefore, if we have just passed a label and have no more labels
4426 between here and the test insn of the loop, and we have not passed
4427 a jump to the top of the loop, then we know these insns will be
4428 executed each iteration. */
4430 if (not_every_iteration
4431 && !past_loop_latch
4432 && LABEL_P (p)
4433 && no_labels_between_p (p, loop->end)
4434 && loop_insn_first_p (p, loop->cont))
4435 not_every_iteration = 0;
4439 static void
4440 loop_bivs_find (struct loop *loop)
4442 struct loop_regs *regs = LOOP_REGS (loop);
4443 struct loop_ivs *ivs = LOOP_IVS (loop);
4444 /* Temporary list pointers for traversing ivs->list. */
4445 struct iv_class *bl, **backbl;
4447 ivs->list = 0;
4449 for_each_insn_in_loop (loop, check_insn_for_bivs);
4451 /* Scan ivs->list to remove all regs that proved not to be bivs.
4452 Make a sanity check against regs->n_times_set. */
4453 for (backbl = &ivs->list, bl = *backbl; bl; bl = bl->next)
4455 if (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4456 /* Above happens if register modified by subreg, etc. */
4457 /* Make sure it is not recognized as a basic induction var: */
4458 || regs->array[bl->regno].n_times_set != bl->biv_count
4459 /* If never incremented, it is invariant that we decided not to
4460 move. So leave it alone. */
4461 || ! bl->incremented)
4463 if (loop_dump_stream)
4464 fprintf (loop_dump_stream, "Biv %d: discarded, %s\n",
4465 bl->regno,
4466 (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4467 ? "not induction variable"
4468 : (! bl->incremented ? "never incremented"
4469 : "count error")));
4471 REG_IV_TYPE (ivs, bl->regno) = NOT_BASIC_INDUCT;
4472 *backbl = bl->next;
4474 else
4476 backbl = &bl->next;
4478 if (loop_dump_stream)
4479 fprintf (loop_dump_stream, "Biv %d: verified\n", bl->regno);
4485 /* Determine how BIVS are initialized by looking through pre-header
4486 extended basic block. */
4487 static void
4488 loop_bivs_init_find (struct loop *loop)
4490 struct loop_ivs *ivs = LOOP_IVS (loop);
4491 /* Temporary list pointers for traversing ivs->list. */
4492 struct iv_class *bl;
4493 int call_seen;
4494 rtx p;
4496 /* Find initial value for each biv by searching backwards from loop_start,
4497 halting at first label. Also record any test condition. */
4499 call_seen = 0;
4500 for (p = loop->start; p && !LABEL_P (p); p = PREV_INSN (p))
4502 rtx test;
4504 note_insn = p;
4506 if (CALL_P (p))
4507 call_seen = 1;
4509 if (INSN_P (p))
4510 note_stores (PATTERN (p), record_initial, ivs);
4512 /* Record any test of a biv that branches around the loop if no store
4513 between it and the start of loop. We only care about tests with
4514 constants and registers and only certain of those. */
4515 if (JUMP_P (p)
4516 && JUMP_LABEL (p) != 0
4517 && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop->end)
4518 && (test = get_condition_for_loop (loop, p)) != 0
4519 && REG_P (XEXP (test, 0))
4520 && REGNO (XEXP (test, 0)) < max_reg_before_loop
4521 && (bl = REG_IV_CLASS (ivs, REGNO (XEXP (test, 0)))) != 0
4522 && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop->start)
4523 && bl->init_insn == 0)
4525 /* If an NE test, we have an initial value! */
4526 if (GET_CODE (test) == NE)
4528 bl->init_insn = p;
4529 bl->init_set = gen_rtx_SET (VOIDmode,
4530 XEXP (test, 0), XEXP (test, 1));
4532 else
4533 bl->initial_test = test;
4539 /* Look at the each biv and see if we can say anything better about its
4540 initial value from any initializing insns set up above. (This is done
4541 in two passes to avoid missing SETs in a PARALLEL.) */
4542 static void
4543 loop_bivs_check (struct loop *loop)
4545 struct loop_ivs *ivs = LOOP_IVS (loop);
4546 /* Temporary list pointers for traversing ivs->list. */
4547 struct iv_class *bl;
4548 struct iv_class **backbl;
4550 for (backbl = &ivs->list; (bl = *backbl); backbl = &bl->next)
4552 rtx src;
4553 rtx note;
4555 if (! bl->init_insn)
4556 continue;
4558 /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4559 is a constant, use the value of that. */
4560 if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4561 && CONSTANT_P (XEXP (note, 0)))
4562 || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4563 && CONSTANT_P (XEXP (note, 0))))
4564 src = XEXP (note, 0);
4565 else
4566 src = SET_SRC (bl->init_set);
4568 if (loop_dump_stream)
4569 fprintf (loop_dump_stream,
4570 "Biv %d: initialized at insn %d: initial value ",
4571 bl->regno, INSN_UID (bl->init_insn));
4573 if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4574 || GET_MODE (src) == VOIDmode)
4575 && valid_initial_value_p (src, bl->init_insn,
4576 LOOP_INFO (loop)->pre_header_has_call,
4577 loop->start))
4579 bl->initial_value = src;
4581 if (loop_dump_stream)
4583 print_simple_rtl (loop_dump_stream, src);
4584 fputc ('\n', loop_dump_stream);
4587 /* If we can't make it a giv,
4588 let biv keep initial value of "itself". */
4589 else if (loop_dump_stream)
4590 fprintf (loop_dump_stream, "is complex\n");
4595 /* Search the loop for general induction variables. */
4597 static void
4598 loop_givs_find (struct loop* loop)
4600 for_each_insn_in_loop (loop, check_insn_for_givs);
4604 /* For each giv for which we still don't know whether or not it is
4605 replaceable, check to see if it is replaceable because its final value
4606 can be calculated. */
4608 static void
4609 loop_givs_check (struct loop *loop)
4611 struct loop_ivs *ivs = LOOP_IVS (loop);
4612 struct iv_class *bl;
4614 for (bl = ivs->list; bl; bl = bl->next)
4616 struct induction *v;
4618 for (v = bl->giv; v; v = v->next_iv)
4619 if (! v->replaceable && ! v->not_replaceable)
4620 check_final_value (loop, v);
4625 /* Return nonzero if it is possible to eliminate the biv BL provided
4626 all givs are reduced. This is possible if either the reg is not
4627 used outside the loop, or we can compute what its final value will
4628 be. */
4630 static int
4631 loop_biv_eliminable_p (struct loop *loop, struct iv_class *bl,
4632 int threshold, int insn_count)
4634 /* For architectures with a decrement_and_branch_until_zero insn,
4635 don't do this if we put a REG_NONNEG note on the endtest for this
4636 biv. */
4638 #ifdef HAVE_decrement_and_branch_until_zero
4639 if (bl->nonneg)
4641 if (loop_dump_stream)
4642 fprintf (loop_dump_stream,
4643 "Cannot eliminate nonneg biv %d.\n", bl->regno);
4644 return 0;
4646 #endif
4648 /* Check that biv is used outside loop or if it has a final value.
4649 Compare against bl->init_insn rather than loop->start. We aren't
4650 concerned with any uses of the biv between init_insn and
4651 loop->start since these won't be affected by the value of the biv
4652 elsewhere in the function, so long as init_insn doesn't use the
4653 biv itself. */
4655 if ((REGNO_LAST_LUID (bl->regno) < INSN_LUID (loop->end)
4656 && bl->init_insn
4657 && INSN_UID (bl->init_insn) < max_uid_for_loop
4658 && REGNO_FIRST_LUID (bl->regno) >= INSN_LUID (bl->init_insn)
4659 && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4660 || (bl->final_value = final_biv_value (loop, bl)))
4661 return maybe_eliminate_biv (loop, bl, 0, threshold, insn_count);
4663 if (loop_dump_stream)
4665 fprintf (loop_dump_stream,
4666 "Cannot eliminate biv %d.\n",
4667 bl->regno);
4668 fprintf (loop_dump_stream,
4669 "First use: insn %d, last use: insn %d.\n",
4670 REGNO_FIRST_UID (bl->regno),
4671 REGNO_LAST_UID (bl->regno));
4673 return 0;
4677 /* Reduce each giv of BL that we have decided to reduce. */
4679 static void
4680 loop_givs_reduce (struct loop *loop, struct iv_class *bl)
4682 struct induction *v;
4684 for (v = bl->giv; v; v = v->next_iv)
4686 struct induction *tv;
4687 if (! v->ignore && v->same == 0)
4689 int auto_inc_opt = 0;
4691 /* If the code for derived givs immediately below has already
4692 allocated a new_reg, we must keep it. */
4693 if (! v->new_reg)
4694 v->new_reg = gen_reg_rtx (v->mode);
4696 #ifdef AUTO_INC_DEC
4697 /* If the target has auto-increment addressing modes, and
4698 this is an address giv, then try to put the increment
4699 immediately after its use, so that flow can create an
4700 auto-increment addressing mode. */
4701 /* Don't do this for loops entered at the bottom, to avoid
4702 this invalid transformation:
4703 jmp L; -> jmp L;
4704 TOP: TOP:
4705 use giv use giv
4706 L: inc giv
4707 inc biv L:
4708 test biv test giv
4709 cbr TOP cbr TOP
4711 if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4712 && bl->biv->always_executed && ! bl->biv->maybe_multiple
4713 /* We don't handle reversed biv's because bl->biv->insn
4714 does not have a valid INSN_LUID. */
4715 && ! bl->reversed
4716 && v->always_executed && ! v->maybe_multiple
4717 && INSN_UID (v->insn) < max_uid_for_loop
4718 && !loop->top)
4720 /* If other giv's have been combined with this one, then
4721 this will work only if all uses of the other giv's occur
4722 before this giv's insn. This is difficult to check.
4724 We simplify this by looking for the common case where
4725 there is one DEST_REG giv, and this giv's insn is the
4726 last use of the dest_reg of that DEST_REG giv. If the
4727 increment occurs after the address giv, then we can
4728 perform the optimization. (Otherwise, the increment
4729 would have to go before other_giv, and we would not be
4730 able to combine it with the address giv to get an
4731 auto-inc address.) */
4732 if (v->combined_with)
4734 struct induction *other_giv = 0;
4736 for (tv = bl->giv; tv; tv = tv->next_iv)
4737 if (tv->same == v)
4739 if (other_giv)
4740 break;
4741 else
4742 other_giv = tv;
4744 if (! tv && other_giv
4745 && REGNO (other_giv->dest_reg) < max_reg_before_loop
4746 && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4747 == INSN_UID (v->insn))
4748 && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4749 auto_inc_opt = 1;
4751 /* Check for case where increment is before the address
4752 giv. Do this test in "loop order". */
4753 else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4754 && (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
4755 || (INSN_LUID (bl->biv->insn)
4756 > INSN_LUID (loop->scan_start))))
4757 || (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
4758 && (INSN_LUID (loop->scan_start)
4759 < INSN_LUID (bl->biv->insn))))
4760 auto_inc_opt = -1;
4761 else
4762 auto_inc_opt = 1;
4764 #ifdef HAVE_cc0
4766 rtx prev;
4768 /* We can't put an insn immediately after one setting
4769 cc0, or immediately before one using cc0. */
4770 if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4771 || (auto_inc_opt == -1
4772 && (prev = prev_nonnote_insn (v->insn)) != 0
4773 && INSN_P (prev)
4774 && sets_cc0_p (PATTERN (prev))))
4775 auto_inc_opt = 0;
4777 #endif
4779 if (auto_inc_opt)
4780 v->auto_inc_opt = 1;
4782 #endif
4784 /* For each place where the biv is incremented, add an insn
4785 to increment the new, reduced reg for the giv. */
4786 for (tv = bl->biv; tv; tv = tv->next_iv)
4788 rtx insert_before;
4790 /* Skip if location is the same as a previous one. */
4791 if (tv->same)
4792 continue;
4793 if (! auto_inc_opt)
4794 insert_before = NEXT_INSN (tv->insn);
4795 else if (auto_inc_opt == 1)
4796 insert_before = NEXT_INSN (v->insn);
4797 else
4798 insert_before = v->insn;
4800 if (tv->mult_val == const1_rtx)
4801 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
4802 v->new_reg, v->new_reg,
4803 0, insert_before);
4804 else /* tv->mult_val == const0_rtx */
4805 /* A multiply is acceptable here
4806 since this is presumed to be seldom executed. */
4807 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
4808 v->add_val, v->new_reg,
4809 0, insert_before);
4812 /* Add code at loop start to initialize giv's reduced reg. */
4814 loop_iv_add_mult_hoist (loop,
4815 extend_value_for_giv (v, bl->initial_value),
4816 v->mult_val, v->add_val, v->new_reg);
4822 /* Check for givs whose first use is their definition and whose
4823 last use is the definition of another giv. If so, it is likely
4824 dead and should not be used to derive another giv nor to
4825 eliminate a biv. */
4827 static void
4828 loop_givs_dead_check (struct loop *loop ATTRIBUTE_UNUSED, struct iv_class *bl)
4830 struct induction *v;
4832 for (v = bl->giv; v; v = v->next_iv)
4834 if (v->ignore
4835 || (v->same && v->same->ignore))
4836 continue;
4838 if (v->giv_type == DEST_REG
4839 && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4841 struct induction *v1;
4843 for (v1 = bl->giv; v1; v1 = v1->next_iv)
4844 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4845 v->maybe_dead = 1;
4851 static void
4852 loop_givs_rescan (struct loop *loop, struct iv_class *bl, rtx *reg_map)
4854 struct induction *v;
4856 for (v = bl->giv; v; v = v->next_iv)
4858 if (v->same && v->same->ignore)
4859 v->ignore = 1;
4861 if (v->ignore)
4862 continue;
4864 /* Update expression if this was combined, in case other giv was
4865 replaced. */
4866 if (v->same)
4867 v->new_reg = replace_rtx (v->new_reg,
4868 v->same->dest_reg, v->same->new_reg);
4870 /* See if this register is known to be a pointer to something. If
4871 so, see if we can find the alignment. First see if there is a
4872 destination register that is a pointer. If so, this shares the
4873 alignment too. Next see if we can deduce anything from the
4874 computational information. If not, and this is a DEST_ADDR
4875 giv, at least we know that it's a pointer, though we don't know
4876 the alignment. */
4877 if (REG_P (v->new_reg)
4878 && v->giv_type == DEST_REG
4879 && REG_POINTER (v->dest_reg))
4880 mark_reg_pointer (v->new_reg,
4881 REGNO_POINTER_ALIGN (REGNO (v->dest_reg)));
4882 else if (REG_P (v->new_reg)
4883 && REG_POINTER (v->src_reg))
4885 unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->src_reg));
4887 if (align == 0
4888 || GET_CODE (v->add_val) != CONST_INT
4889 || INTVAL (v->add_val) % (align / BITS_PER_UNIT) != 0)
4890 align = 0;
4892 mark_reg_pointer (v->new_reg, align);
4894 else if (REG_P (v->new_reg)
4895 && REG_P (v->add_val)
4896 && REG_POINTER (v->add_val))
4898 unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->add_val));
4900 if (align == 0 || GET_CODE (v->mult_val) != CONST_INT
4901 || INTVAL (v->mult_val) % (align / BITS_PER_UNIT) != 0)
4902 align = 0;
4904 mark_reg_pointer (v->new_reg, align);
4906 else if (REG_P (v->new_reg) && v->giv_type == DEST_ADDR)
4907 mark_reg_pointer (v->new_reg, 0);
4909 if (v->giv_type == DEST_ADDR)
4910 /* Store reduced reg as the address in the memref where we found
4911 this giv. */
4912 validate_change (v->insn, v->location, v->new_reg, 0);
4913 else if (v->replaceable)
4915 reg_map[REGNO (v->dest_reg)] = v->new_reg;
4917 else
4919 rtx original_insn = v->insn;
4920 rtx note;
4922 /* Not replaceable; emit an insn to set the original giv reg from
4923 the reduced giv, same as above. */
4924 v->insn = loop_insn_emit_after (loop, 0, original_insn,
4925 gen_move_insn (v->dest_reg,
4926 v->new_reg));
4928 /* The original insn may have a REG_EQUAL note. This note is
4929 now incorrect and may result in invalid substitutions later.
4930 The original insn is dead, but may be part of a libcall
4931 sequence, which doesn't seem worth the bother of handling. */
4932 note = find_reg_note (original_insn, REG_EQUAL, NULL_RTX);
4933 if (note)
4934 remove_note (original_insn, note);
4937 /* When a loop is reversed, givs which depend on the reversed
4938 biv, and which are live outside the loop, must be set to their
4939 correct final value. This insn is only needed if the giv is
4940 not replaceable. The correct final value is the same as the
4941 value that the giv starts the reversed loop with. */
4942 if (bl->reversed && ! v->replaceable)
4943 loop_iv_add_mult_sink (loop,
4944 extend_value_for_giv (v, bl->initial_value),
4945 v->mult_val, v->add_val, v->dest_reg);
4946 else if (v->final_value)
4947 loop_insn_sink_or_swim (loop,
4948 gen_load_of_final_value (v->dest_reg,
4949 v->final_value));
4951 if (loop_dump_stream)
4953 fprintf (loop_dump_stream, "giv at %d reduced to ",
4954 INSN_UID (v->insn));
4955 print_simple_rtl (loop_dump_stream, v->new_reg);
4956 fprintf (loop_dump_stream, "\n");
4962 static int
4963 loop_giv_reduce_benefit (struct loop *loop ATTRIBUTE_UNUSED,
4964 struct iv_class *bl, struct induction *v,
4965 rtx test_reg)
4967 int add_cost;
4968 int benefit;
4970 benefit = v->benefit;
4971 PUT_MODE (test_reg, v->mode);
4972 add_cost = iv_add_mult_cost (bl->biv->add_val, v->mult_val,
4973 test_reg, test_reg);
4975 /* Reduce benefit if not replaceable, since we will insert a
4976 move-insn to replace the insn that calculates this giv. Don't do
4977 this unless the giv is a user variable, since it will often be
4978 marked non-replaceable because of the duplication of the exit
4979 code outside the loop. In such a case, the copies we insert are
4980 dead and will be deleted. So they don't have a cost. Similar
4981 situations exist. */
4982 /* ??? The new final_[bg]iv_value code does a much better job of
4983 finding replaceable giv's, and hence this code may no longer be
4984 necessary. */
4985 if (! v->replaceable && ! bl->eliminable
4986 && REG_USERVAR_P (v->dest_reg))
4987 benefit -= copy_cost;
4989 /* Decrease the benefit to count the add-insns that we will insert
4990 to increment the reduced reg for the giv. ??? This can
4991 overestimate the run-time cost of the additional insns, e.g. if
4992 there are multiple basic blocks that increment the biv, but only
4993 one of these blocks is executed during each iteration. There is
4994 no good way to detect cases like this with the current structure
4995 of the loop optimizer. This code is more accurate for
4996 determining code size than run-time benefits. */
4997 benefit -= add_cost * bl->biv_count;
4999 /* Decide whether to strength-reduce this giv or to leave the code
5000 unchanged (recompute it from the biv each time it is used). This
5001 decision can be made independently for each giv. */
5003 #ifdef AUTO_INC_DEC
5004 /* Attempt to guess whether autoincrement will handle some of the
5005 new add insns; if so, increase BENEFIT (undo the subtraction of
5006 add_cost that was done above). */
5007 if (v->giv_type == DEST_ADDR
5008 /* Increasing the benefit is risky, since this is only a guess.
5009 Avoid increasing register pressure in cases where there would
5010 be no other benefit from reducing this giv. */
5011 && benefit > 0
5012 && GET_CODE (v->mult_val) == CONST_INT)
5014 int size = GET_MODE_SIZE (GET_MODE (v->mem));
5016 if (HAVE_POST_INCREMENT
5017 && INTVAL (v->mult_val) == size)
5018 benefit += add_cost * bl->biv_count;
5019 else if (HAVE_PRE_INCREMENT
5020 && INTVAL (v->mult_val) == size)
5021 benefit += add_cost * bl->biv_count;
5022 else if (HAVE_POST_DECREMENT
5023 && -INTVAL (v->mult_val) == size)
5024 benefit += add_cost * bl->biv_count;
5025 else if (HAVE_PRE_DECREMENT
5026 && -INTVAL (v->mult_val) == size)
5027 benefit += add_cost * bl->biv_count;
5029 #endif
5031 return benefit;
5035 /* Free IV structures for LOOP. */
5037 static void
5038 loop_ivs_free (struct loop *loop)
5040 struct loop_ivs *ivs = LOOP_IVS (loop);
5041 struct iv_class *iv = ivs->list;
5043 free (ivs->regs);
5045 while (iv)
5047 struct iv_class *next = iv->next;
5048 struct induction *induction;
5049 struct induction *next_induction;
5051 for (induction = iv->biv; induction; induction = next_induction)
5053 next_induction = induction->next_iv;
5054 free (induction);
5056 for (induction = iv->giv; induction; induction = next_induction)
5058 next_induction = induction->next_iv;
5059 free (induction);
5062 free (iv);
5063 iv = next;
5068 /* Perform strength reduction and induction variable elimination.
5070 Pseudo registers created during this function will be beyond the
5071 last valid index in several tables including
5072 REGS->ARRAY[I].N_TIMES_SET and REGNO_LAST_UID. This does not cause a
5073 problem here, because the added registers cannot be givs outside of
5074 their loop, and hence will never be reconsidered. But scan_loop
5075 must check regnos to make sure they are in bounds. */
5077 static void
5078 strength_reduce (struct loop *loop, int flags)
5080 struct loop_info *loop_info = LOOP_INFO (loop);
5081 struct loop_regs *regs = LOOP_REGS (loop);
5082 struct loop_ivs *ivs = LOOP_IVS (loop);
5083 rtx p;
5084 /* Temporary list pointer for traversing ivs->list. */
5085 struct iv_class *bl;
5086 /* Ratio of extra register life span we can justify
5087 for saving an instruction. More if loop doesn't call subroutines
5088 since in that case saving an insn makes more difference
5089 and more registers are available. */
5090 /* ??? could set this to last value of threshold in move_movables */
5091 int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
5092 /* Map of pseudo-register replacements. */
5093 rtx *reg_map = NULL;
5094 int reg_map_size;
5095 int unrolled_insn_copies = 0;
5096 rtx test_reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
5097 int insn_count = count_insns_in_loop (loop);
5099 addr_placeholder = gen_reg_rtx (Pmode);
5101 ivs->n_regs = max_reg_before_loop;
5102 ivs->regs = xcalloc (ivs->n_regs, sizeof (struct iv));
5104 /* Find all BIVs in loop. */
5105 loop_bivs_find (loop);
5107 /* Exit if there are no bivs. */
5108 if (! ivs->list)
5110 /* Can still unroll the loop anyways, but indicate that there is no
5111 strength reduction info available. */
5112 if (flags & LOOP_UNROLL)
5113 unroll_loop (loop, insn_count, 0);
5115 loop_ivs_free (loop);
5116 return;
5119 /* Determine how BIVS are initialized by looking through pre-header
5120 extended basic block. */
5121 loop_bivs_init_find (loop);
5123 /* Look at the each biv and see if we can say anything better about its
5124 initial value from any initializing insns set up above. */
5125 loop_bivs_check (loop);
5127 /* Search the loop for general induction variables. */
5128 loop_givs_find (loop);
5130 /* Try to calculate and save the number of loop iterations. This is
5131 set to zero if the actual number can not be calculated. This must
5132 be called after all giv's have been identified, since otherwise it may
5133 fail if the iteration variable is a giv. */
5134 loop_iterations (loop);
5136 #ifdef HAVE_prefetch
5137 if (flags & LOOP_PREFETCH)
5138 emit_prefetch_instructions (loop);
5139 #endif
5141 /* Now for each giv for which we still don't know whether or not it is
5142 replaceable, check to see if it is replaceable because its final value
5143 can be calculated. This must be done after loop_iterations is called,
5144 so that final_giv_value will work correctly. */
5145 loop_givs_check (loop);
5147 /* Try to prove that the loop counter variable (if any) is always
5148 nonnegative; if so, record that fact with a REG_NONNEG note
5149 so that "decrement and branch until zero" insn can be used. */
5150 check_dbra_loop (loop, insn_count);
5152 /* Create reg_map to hold substitutions for replaceable giv regs.
5153 Some givs might have been made from biv increments, so look at
5154 ivs->reg_iv_type for a suitable size. */
5155 reg_map_size = ivs->n_regs;
5156 reg_map = xcalloc (reg_map_size, sizeof (rtx));
5158 /* Examine each iv class for feasibility of strength reduction/induction
5159 variable elimination. */
5161 for (bl = ivs->list; bl; bl = bl->next)
5163 struct induction *v;
5164 int benefit;
5166 /* Test whether it will be possible to eliminate this biv
5167 provided all givs are reduced. */
5168 bl->eliminable = loop_biv_eliminable_p (loop, bl, threshold, insn_count);
5170 /* This will be true at the end, if all givs which depend on this
5171 biv have been strength reduced.
5172 We can't (currently) eliminate the biv unless this is so. */
5173 bl->all_reduced = 1;
5175 /* Check each extension dependent giv in this class to see if its
5176 root biv is safe from wrapping in the interior mode. */
5177 check_ext_dependent_givs (loop, bl);
5179 /* Combine all giv's for this iv_class. */
5180 combine_givs (regs, bl);
5182 for (v = bl->giv; v; v = v->next_iv)
5184 struct induction *tv;
5186 if (v->ignore || v->same)
5187 continue;
5189 benefit = loop_giv_reduce_benefit (loop, bl, v, test_reg);
5191 /* If an insn is not to be strength reduced, then set its ignore
5192 flag, and clear bl->all_reduced. */
5194 /* A giv that depends on a reversed biv must be reduced if it is
5195 used after the loop exit, otherwise, it would have the wrong
5196 value after the loop exit. To make it simple, just reduce all
5197 of such giv's whether or not we know they are used after the loop
5198 exit. */
5200 if (! flag_reduce_all_givs
5201 && v->lifetime * threshold * benefit < insn_count
5202 && ! bl->reversed)
5204 if (loop_dump_stream)
5205 fprintf (loop_dump_stream,
5206 "giv of insn %d not worth while, %d vs %d.\n",
5207 INSN_UID (v->insn),
5208 v->lifetime * threshold * benefit, insn_count);
5209 v->ignore = 1;
5210 bl->all_reduced = 0;
5212 else
5214 /* Check that we can increment the reduced giv without a
5215 multiply insn. If not, reject it. */
5217 for (tv = bl->biv; tv; tv = tv->next_iv)
5218 if (tv->mult_val == const1_rtx
5219 && ! product_cheap_p (tv->add_val, v->mult_val))
5221 if (loop_dump_stream)
5222 fprintf (loop_dump_stream,
5223 "giv of insn %d: would need a multiply.\n",
5224 INSN_UID (v->insn));
5225 v->ignore = 1;
5226 bl->all_reduced = 0;
5227 break;
5232 /* Check for givs whose first use is their definition and whose
5233 last use is the definition of another giv. If so, it is likely
5234 dead and should not be used to derive another giv nor to
5235 eliminate a biv. */
5236 loop_givs_dead_check (loop, bl);
5238 /* Reduce each giv that we decided to reduce. */
5239 loop_givs_reduce (loop, bl);
5241 /* Rescan all givs. If a giv is the same as a giv not reduced, mark it
5242 as not reduced.
5244 For each giv register that can be reduced now: if replaceable,
5245 substitute reduced reg wherever the old giv occurs;
5246 else add new move insn "giv_reg = reduced_reg". */
5247 loop_givs_rescan (loop, bl, reg_map);
5249 /* All the givs based on the biv bl have been reduced if they
5250 merit it. */
5252 /* For each giv not marked as maybe dead that has been combined with a
5253 second giv, clear any "maybe dead" mark on that second giv.
5254 v->new_reg will either be or refer to the register of the giv it
5255 combined with.
5257 Doing this clearing avoids problems in biv elimination where
5258 a giv's new_reg is a complex value that can't be put in the
5259 insn but the giv combined with (with a reg as new_reg) is
5260 marked maybe_dead. Since the register will be used in either
5261 case, we'd prefer it be used from the simpler giv. */
5263 for (v = bl->giv; v; v = v->next_iv)
5264 if (! v->maybe_dead && v->same)
5265 v->same->maybe_dead = 0;
5267 /* Try to eliminate the biv, if it is a candidate.
5268 This won't work if ! bl->all_reduced,
5269 since the givs we planned to use might not have been reduced.
5271 We have to be careful that we didn't initially think we could
5272 eliminate this biv because of a giv that we now think may be
5273 dead and shouldn't be used as a biv replacement.
5275 Also, there is the possibility that we may have a giv that looks
5276 like it can be used to eliminate a biv, but the resulting insn
5277 isn't valid. This can happen, for example, on the 88k, where a
5278 JUMP_INSN can compare a register only with zero. Attempts to
5279 replace it with a compare with a constant will fail.
5281 Note that in cases where this call fails, we may have replaced some
5282 of the occurrences of the biv with a giv, but no harm was done in
5283 doing so in the rare cases where it can occur. */
5285 if (bl->all_reduced == 1 && bl->eliminable
5286 && maybe_eliminate_biv (loop, bl, 1, threshold, insn_count))
5288 /* ?? If we created a new test to bypass the loop entirely,
5289 or otherwise drop straight in, based on this test, then
5290 we might want to rewrite it also. This way some later
5291 pass has more hope of removing the initialization of this
5292 biv entirely. */
5294 /* If final_value != 0, then the biv may be used after loop end
5295 and we must emit an insn to set it just in case.
5297 Reversed bivs already have an insn after the loop setting their
5298 value, so we don't need another one. We can't calculate the
5299 proper final value for such a biv here anyways. */
5300 if (bl->final_value && ! bl->reversed)
5301 loop_insn_sink_or_swim (loop,
5302 gen_load_of_final_value (bl->biv->dest_reg,
5303 bl->final_value));
5305 if (loop_dump_stream)
5306 fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
5307 bl->regno);
5309 /* See above note wrt final_value. But since we couldn't eliminate
5310 the biv, we must set the value after the loop instead of before. */
5311 else if (bl->final_value && ! bl->reversed)
5312 loop_insn_sink (loop, gen_load_of_final_value (bl->biv->dest_reg,
5313 bl->final_value));
5316 /* Go through all the instructions in the loop, making all the
5317 register substitutions scheduled in REG_MAP. */
5319 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
5320 if (INSN_P (p))
5322 replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
5323 replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
5324 INSN_CODE (p) = -1;
5327 if (loop_info->n_iterations > 0)
5329 /* When we completely unroll a loop we will likely not need the increment
5330 of the loop BIV and we will not need the conditional branch at the
5331 end of the loop. */
5332 unrolled_insn_copies = insn_count - 2;
5334 #ifdef HAVE_cc0
5335 /* When we completely unroll a loop on a HAVE_cc0 machine we will not
5336 need the comparison before the conditional branch at the end of the
5337 loop. */
5338 unrolled_insn_copies -= 1;
5339 #endif
5341 /* We'll need one copy for each loop iteration. */
5342 unrolled_insn_copies *= loop_info->n_iterations;
5344 /* A little slop to account for the ability to remove initialization
5345 code, better CSE, and other secondary benefits of completely
5346 unrolling some loops. */
5347 unrolled_insn_copies -= 1;
5349 /* Clamp the value. */
5350 if (unrolled_insn_copies < 0)
5351 unrolled_insn_copies = 0;
5354 /* Unroll loops from within strength reduction so that we can use the
5355 induction variable information that strength_reduce has already
5356 collected. Always unroll loops that would be as small or smaller
5357 unrolled than when rolled. */
5358 if ((flags & LOOP_UNROLL)
5359 || ((flags & LOOP_AUTO_UNROLL)
5360 && loop_info->n_iterations > 0
5361 && unrolled_insn_copies <= insn_count))
5362 unroll_loop (loop, insn_count, 1);
5364 if (loop_dump_stream)
5365 fprintf (loop_dump_stream, "\n");
5367 loop_ivs_free (loop);
5368 if (reg_map)
5369 free (reg_map);
5372 /*Record all basic induction variables calculated in the insn. */
5373 static rtx
5374 check_insn_for_bivs (struct loop *loop, rtx p, int not_every_iteration,
5375 int maybe_multiple)
5377 struct loop_ivs *ivs = LOOP_IVS (loop);
5378 rtx set;
5379 rtx dest_reg;
5380 rtx inc_val;
5381 rtx mult_val;
5382 rtx *location;
5384 if (NONJUMP_INSN_P (p)
5385 && (set = single_set (p))
5386 && REG_P (SET_DEST (set)))
5388 dest_reg = SET_DEST (set);
5389 if (REGNO (dest_reg) < max_reg_before_loop
5390 && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
5391 && REG_IV_TYPE (ivs, REGNO (dest_reg)) != NOT_BASIC_INDUCT)
5393 if (basic_induction_var (loop, SET_SRC (set),
5394 GET_MODE (SET_SRC (set)),
5395 dest_reg, p, &inc_val, &mult_val,
5396 &location))
5398 /* It is a possible basic induction variable.
5399 Create and initialize an induction structure for it. */
5401 struct induction *v = xmalloc (sizeof (struct induction));
5403 record_biv (loop, v, p, dest_reg, inc_val, mult_val, location,
5404 not_every_iteration, maybe_multiple);
5405 REG_IV_TYPE (ivs, REGNO (dest_reg)) = BASIC_INDUCT;
5407 else if (REGNO (dest_reg) < ivs->n_regs)
5408 REG_IV_TYPE (ivs, REGNO (dest_reg)) = NOT_BASIC_INDUCT;
5411 return p;
5414 /* Record all givs calculated in the insn.
5415 A register is a giv if: it is only set once, it is a function of a
5416 biv and a constant (or invariant), and it is not a biv. */
5417 static rtx
5418 check_insn_for_givs (struct loop *loop, rtx p, int not_every_iteration,
5419 int maybe_multiple)
5421 struct loop_regs *regs = LOOP_REGS (loop);
5423 rtx set;
5424 /* Look for a general induction variable in a register. */
5425 if (NONJUMP_INSN_P (p)
5426 && (set = single_set (p))
5427 && REG_P (SET_DEST (set))
5428 && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
5430 rtx src_reg;
5431 rtx dest_reg;
5432 rtx add_val;
5433 rtx mult_val;
5434 rtx ext_val;
5435 int benefit;
5436 rtx regnote = 0;
5437 rtx last_consec_insn;
5439 dest_reg = SET_DEST (set);
5440 if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
5441 return p;
5443 if (/* SET_SRC is a giv. */
5444 (general_induction_var (loop, SET_SRC (set), &src_reg, &add_val,
5445 &mult_val, &ext_val, 0, &benefit, VOIDmode)
5446 /* Equivalent expression is a giv. */
5447 || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
5448 && general_induction_var (loop, XEXP (regnote, 0), &src_reg,
5449 &add_val, &mult_val, &ext_val, 0,
5450 &benefit, VOIDmode)))
5451 /* Don't try to handle any regs made by loop optimization.
5452 We have nothing on them in regno_first_uid, etc. */
5453 && REGNO (dest_reg) < max_reg_before_loop
5454 /* Don't recognize a BASIC_INDUCT_VAR here. */
5455 && dest_reg != src_reg
5456 /* This must be the only place where the register is set. */
5457 && (regs->array[REGNO (dest_reg)].n_times_set == 1
5458 /* or all sets must be consecutive and make a giv. */
5459 || (benefit = consec_sets_giv (loop, benefit, p,
5460 src_reg, dest_reg,
5461 &add_val, &mult_val, &ext_val,
5462 &last_consec_insn))))
5464 struct induction *v = xmalloc (sizeof (struct induction));
5466 /* If this is a library call, increase benefit. */
5467 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
5468 benefit += libcall_benefit (p);
5470 /* Skip the consecutive insns, if there are any. */
5471 if (regs->array[REGNO (dest_reg)].n_times_set != 1)
5472 p = last_consec_insn;
5474 record_giv (loop, v, p, src_reg, dest_reg, mult_val, add_val,
5475 ext_val, benefit, DEST_REG, not_every_iteration,
5476 maybe_multiple, (rtx*) 0);
5481 /* Look for givs which are memory addresses. */
5482 if (NONJUMP_INSN_P (p))
5483 find_mem_givs (loop, PATTERN (p), p, not_every_iteration,
5484 maybe_multiple);
5486 /* Update the status of whether giv can derive other givs. This can
5487 change when we pass a label or an insn that updates a biv. */
5488 if (INSN_P (p) || LABEL_P (p))
5489 update_giv_derive (loop, p);
5490 return p;
5493 /* Return 1 if X is a valid source for an initial value (or as value being
5494 compared against in an initial test).
5496 X must be either a register or constant and must not be clobbered between
5497 the current insn and the start of the loop.
5499 INSN is the insn containing X. */
5501 static int
5502 valid_initial_value_p (rtx x, rtx insn, int call_seen, rtx loop_start)
5504 if (CONSTANT_P (x))
5505 return 1;
5507 /* Only consider pseudos we know about initialized in insns whose luids
5508 we know. */
5509 if (!REG_P (x)
5510 || REGNO (x) >= max_reg_before_loop)
5511 return 0;
5513 /* Don't use call-clobbered registers across a call which clobbers it. On
5514 some machines, don't use any hard registers at all. */
5515 if (REGNO (x) < FIRST_PSEUDO_REGISTER
5516 && (SMALL_REGISTER_CLASSES
5517 || (call_used_regs[REGNO (x)] && call_seen)))
5518 return 0;
5520 /* Don't use registers that have been clobbered before the start of the
5521 loop. */
5522 if (reg_set_between_p (x, insn, loop_start))
5523 return 0;
5525 return 1;
5528 /* Scan X for memory refs and check each memory address
5529 as a possible giv. INSN is the insn whose pattern X comes from.
5530 NOT_EVERY_ITERATION is 1 if the insn might not be executed during
5531 every loop iteration. MAYBE_MULTIPLE is 1 if the insn might be executed
5532 more than once in each loop iteration. */
5534 static void
5535 find_mem_givs (const struct loop *loop, rtx x, rtx insn,
5536 int not_every_iteration, int maybe_multiple)
5538 int i, j;
5539 enum rtx_code code;
5540 const char *fmt;
5542 if (x == 0)
5543 return;
5545 code = GET_CODE (x);
5546 switch (code)
5548 case REG:
5549 case CONST_INT:
5550 case CONST:
5551 case CONST_DOUBLE:
5552 case SYMBOL_REF:
5553 case LABEL_REF:
5554 case PC:
5555 case CC0:
5556 case ADDR_VEC:
5557 case ADDR_DIFF_VEC:
5558 case USE:
5559 case CLOBBER:
5560 return;
5562 case MEM:
5564 rtx src_reg;
5565 rtx add_val;
5566 rtx mult_val;
5567 rtx ext_val;
5568 int benefit;
5570 /* This code used to disable creating GIVs with mult_val == 1 and
5571 add_val == 0. However, this leads to lost optimizations when
5572 it comes time to combine a set of related DEST_ADDR GIVs, since
5573 this one would not be seen. */
5575 if (general_induction_var (loop, XEXP (x, 0), &src_reg, &add_val,
5576 &mult_val, &ext_val, 1, &benefit,
5577 GET_MODE (x)))
5579 /* Found one; record it. */
5580 struct induction *v = xmalloc (sizeof (struct induction));
5582 record_giv (loop, v, insn, src_reg, addr_placeholder, mult_val,
5583 add_val, ext_val, benefit, DEST_ADDR,
5584 not_every_iteration, maybe_multiple, &XEXP (x, 0));
5586 v->mem = x;
5589 return;
5591 default:
5592 break;
5595 /* Recursively scan the subexpressions for other mem refs. */
5597 fmt = GET_RTX_FORMAT (code);
5598 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5599 if (fmt[i] == 'e')
5600 find_mem_givs (loop, XEXP (x, i), insn, not_every_iteration,
5601 maybe_multiple);
5602 else if (fmt[i] == 'E')
5603 for (j = 0; j < XVECLEN (x, i); j++)
5604 find_mem_givs (loop, XVECEXP (x, i, j), insn, not_every_iteration,
5605 maybe_multiple);
5608 /* Fill in the data about one biv update.
5609 V is the `struct induction' in which we record the biv. (It is
5610 allocated by the caller, with alloca.)
5611 INSN is the insn that sets it.
5612 DEST_REG is the biv's reg.
5614 MULT_VAL is const1_rtx if the biv is being incremented here, in which case
5615 INC_VAL is the increment. Otherwise, MULT_VAL is const0_rtx and the biv is
5616 being set to INC_VAL.
5618 NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
5619 executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
5620 can be executed more than once per iteration. If MAYBE_MULTIPLE
5621 and NOT_EVERY_ITERATION are both zero, we know that the biv update is
5622 executed exactly once per iteration. */
5624 static void
5625 record_biv (struct loop *loop, struct induction *v, rtx insn, rtx dest_reg,
5626 rtx inc_val, rtx mult_val, rtx *location,
5627 int not_every_iteration, int maybe_multiple)
5629 struct loop_ivs *ivs = LOOP_IVS (loop);
5630 struct iv_class *bl;
5632 v->insn = insn;
5633 v->src_reg = dest_reg;
5634 v->dest_reg = dest_reg;
5635 v->mult_val = mult_val;
5636 v->add_val = inc_val;
5637 v->ext_dependent = NULL_RTX;
5638 v->location = location;
5639 v->mode = GET_MODE (dest_reg);
5640 v->always_computable = ! not_every_iteration;
5641 v->always_executed = ! not_every_iteration;
5642 v->maybe_multiple = maybe_multiple;
5643 v->same = 0;
5645 /* Add this to the reg's iv_class, creating a class
5646 if this is the first incrementation of the reg. */
5648 bl = REG_IV_CLASS (ivs, REGNO (dest_reg));
5649 if (bl == 0)
5651 /* Create and initialize new iv_class. */
5653 bl = xmalloc (sizeof (struct iv_class));
5655 bl->regno = REGNO (dest_reg);
5656 bl->biv = 0;
5657 bl->giv = 0;
5658 bl->biv_count = 0;
5659 bl->giv_count = 0;
5661 /* Set initial value to the reg itself. */
5662 bl->initial_value = dest_reg;
5663 bl->final_value = 0;
5664 /* We haven't seen the initializing insn yet. */
5665 bl->init_insn = 0;
5666 bl->init_set = 0;
5667 bl->initial_test = 0;
5668 bl->incremented = 0;
5669 bl->eliminable = 0;
5670 bl->nonneg = 0;
5671 bl->reversed = 0;
5672 bl->total_benefit = 0;
5674 /* Add this class to ivs->list. */
5675 bl->next = ivs->list;
5676 ivs->list = bl;
5678 /* Put it in the array of biv register classes. */
5679 REG_IV_CLASS (ivs, REGNO (dest_reg)) = bl;
5681 else
5683 /* Check if location is the same as a previous one. */
5684 struct induction *induction;
5685 for (induction = bl->biv; induction; induction = induction->next_iv)
5686 if (location == induction->location)
5688 v->same = induction;
5689 break;
5693 /* Update IV_CLASS entry for this biv. */
5694 v->next_iv = bl->biv;
5695 bl->biv = v;
5696 bl->biv_count++;
5697 if (mult_val == const1_rtx)
5698 bl->incremented = 1;
5700 if (loop_dump_stream)
5701 loop_biv_dump (v, loop_dump_stream, 0);
5704 /* Fill in the data about one giv.
5705 V is the `struct induction' in which we record the giv. (It is
5706 allocated by the caller, with alloca.)
5707 INSN is the insn that sets it.
5708 BENEFIT estimates the savings from deleting this insn.
5709 TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
5710 into a register or is used as a memory address.
5712 SRC_REG is the biv reg which the giv is computed from.
5713 DEST_REG is the giv's reg (if the giv is stored in a reg).
5714 MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
5715 LOCATION points to the place where this giv's value appears in INSN. */
5717 static void
5718 record_giv (const struct loop *loop, struct induction *v, rtx insn,
5719 rtx src_reg, rtx dest_reg, rtx mult_val, rtx add_val,
5720 rtx ext_val, int benefit, enum g_types type,
5721 int not_every_iteration, int maybe_multiple, rtx *location)
5723 struct loop_ivs *ivs = LOOP_IVS (loop);
5724 struct induction *b;
5725 struct iv_class *bl;
5726 rtx set = single_set (insn);
5727 rtx temp;
5729 /* Attempt to prove constantness of the values. Don't let simplify_rtx
5730 undo the MULT canonicalization that we performed earlier. */
5731 temp = simplify_rtx (add_val);
5732 if (temp
5733 && ! (GET_CODE (add_val) == MULT
5734 && GET_CODE (temp) == ASHIFT))
5735 add_val = temp;
5737 v->insn = insn;
5738 v->src_reg = src_reg;
5739 v->giv_type = type;
5740 v->dest_reg = dest_reg;
5741 v->mult_val = mult_val;
5742 v->add_val = add_val;
5743 v->ext_dependent = ext_val;
5744 v->benefit = benefit;
5745 v->location = location;
5746 v->cant_derive = 0;
5747 v->combined_with = 0;
5748 v->maybe_multiple = maybe_multiple;
5749 v->maybe_dead = 0;
5750 v->derive_adjustment = 0;
5751 v->same = 0;
5752 v->ignore = 0;
5753 v->new_reg = 0;
5754 v->final_value = 0;
5755 v->same_insn = 0;
5756 v->auto_inc_opt = 0;
5757 v->unrolled = 0;
5758 v->shared = 0;
5760 /* The v->always_computable field is used in update_giv_derive, to
5761 determine whether a giv can be used to derive another giv. For a
5762 DEST_REG giv, INSN computes a new value for the giv, so its value
5763 isn't computable if INSN insn't executed every iteration.
5764 However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
5765 it does not compute a new value. Hence the value is always computable
5766 regardless of whether INSN is executed each iteration. */
5768 if (type == DEST_ADDR)
5769 v->always_computable = 1;
5770 else
5771 v->always_computable = ! not_every_iteration;
5773 v->always_executed = ! not_every_iteration;
5775 if (type == DEST_ADDR)
5777 v->mode = GET_MODE (*location);
5778 v->lifetime = 1;
5780 else /* type == DEST_REG */
5782 v->mode = GET_MODE (SET_DEST (set));
5784 v->lifetime = LOOP_REG_LIFETIME (loop, REGNO (dest_reg));
5786 /* If the lifetime is zero, it means that this register is
5787 really a dead store. So mark this as a giv that can be
5788 ignored. This will not prevent the biv from being eliminated. */
5789 if (v->lifetime == 0)
5790 v->ignore = 1;
5792 REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
5793 REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
5796 /* Add the giv to the class of givs computed from one biv. */
5798 bl = REG_IV_CLASS (ivs, REGNO (src_reg));
5799 if (bl)
5801 v->next_iv = bl->giv;
5802 bl->giv = v;
5803 /* Don't count DEST_ADDR. This is supposed to count the number of
5804 insns that calculate givs. */
5805 if (type == DEST_REG)
5806 bl->giv_count++;
5807 bl->total_benefit += benefit;
5809 else
5810 /* Fatal error, biv missing for this giv? */
5811 abort ();
5813 if (type == DEST_ADDR)
5815 v->replaceable = 1;
5816 v->not_replaceable = 0;
5818 else
5820 /* The giv can be replaced outright by the reduced register only if all
5821 of the following conditions are true:
5822 - the insn that sets the giv is always executed on any iteration
5823 on which the giv is used at all
5824 (there are two ways to deduce this:
5825 either the insn is executed on every iteration,
5826 or all uses follow that insn in the same basic block),
5827 - the giv is not used outside the loop
5828 - no assignments to the biv occur during the giv's lifetime. */
5830 if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
5831 /* Previous line always fails if INSN was moved by loop opt. */
5832 && REGNO_LAST_LUID (REGNO (dest_reg))
5833 < INSN_LUID (loop->end)
5834 && (! not_every_iteration
5835 || last_use_this_basic_block (dest_reg, insn)))
5837 /* Now check that there are no assignments to the biv within the
5838 giv's lifetime. This requires two separate checks. */
5840 /* Check each biv update, and fail if any are between the first
5841 and last use of the giv.
5843 If this loop contains an inner loop that was unrolled, then
5844 the insn modifying the biv may have been emitted by the loop
5845 unrolling code, and hence does not have a valid luid. Just
5846 mark the biv as not replaceable in this case. It is not very
5847 useful as a biv, because it is used in two different loops.
5848 It is very unlikely that we would be able to optimize the giv
5849 using this biv anyways. */
5851 v->replaceable = 1;
5852 v->not_replaceable = 0;
5853 for (b = bl->biv; b; b = b->next_iv)
5855 if (INSN_UID (b->insn) >= max_uid_for_loop
5856 || ((INSN_LUID (b->insn)
5857 >= REGNO_FIRST_LUID (REGNO (dest_reg)))
5858 && (INSN_LUID (b->insn)
5859 <= REGNO_LAST_LUID (REGNO (dest_reg)))))
5861 v->replaceable = 0;
5862 v->not_replaceable = 1;
5863 break;
5867 /* If there are any backwards branches that go from after the
5868 biv update to before it, then this giv is not replaceable. */
5869 if (v->replaceable)
5870 for (b = bl->biv; b; b = b->next_iv)
5871 if (back_branch_in_range_p (loop, b->insn))
5873 v->replaceable = 0;
5874 v->not_replaceable = 1;
5875 break;
5878 else
5880 /* May still be replaceable, we don't have enough info here to
5881 decide. */
5882 v->replaceable = 0;
5883 v->not_replaceable = 0;
5887 /* Record whether the add_val contains a const_int, for later use by
5888 combine_givs. */
5890 rtx tem = add_val;
5892 v->no_const_addval = 1;
5893 if (tem == const0_rtx)
5895 else if (CONSTANT_P (add_val))
5896 v->no_const_addval = 0;
5897 if (GET_CODE (tem) == PLUS)
5899 while (1)
5901 if (GET_CODE (XEXP (tem, 0)) == PLUS)
5902 tem = XEXP (tem, 0);
5903 else if (GET_CODE (XEXP (tem, 1)) == PLUS)
5904 tem = XEXP (tem, 1);
5905 else
5906 break;
5908 if (CONSTANT_P (XEXP (tem, 1)))
5909 v->no_const_addval = 0;
5913 if (loop_dump_stream)
5914 loop_giv_dump (v, loop_dump_stream, 0);
5917 /* All this does is determine whether a giv can be made replaceable because
5918 its final value can be calculated. This code can not be part of record_giv
5919 above, because final_giv_value requires that the number of loop iterations
5920 be known, and that can not be accurately calculated until after all givs
5921 have been identified. */
5923 static void
5924 check_final_value (const struct loop *loop, struct induction *v)
5926 rtx final_value = 0;
5928 /* DEST_ADDR givs will never reach here, because they are always marked
5929 replaceable above in record_giv. */
5931 /* The giv can be replaced outright by the reduced register only if all
5932 of the following conditions are true:
5933 - the insn that sets the giv is always executed on any iteration
5934 on which the giv is used at all
5935 (there are two ways to deduce this:
5936 either the insn is executed on every iteration,
5937 or all uses follow that insn in the same basic block),
5938 - its final value can be calculated (this condition is different
5939 than the one above in record_giv)
5940 - it's not used before the it's set
5941 - no assignments to the biv occur during the giv's lifetime. */
5943 #if 0
5944 /* This is only called now when replaceable is known to be false. */
5945 /* Clear replaceable, so that it won't confuse final_giv_value. */
5946 v->replaceable = 0;
5947 #endif
5949 if ((final_value = final_giv_value (loop, v))
5950 && (v->always_executed
5951 || last_use_this_basic_block (v->dest_reg, v->insn)))
5953 int biv_increment_seen = 0, before_giv_insn = 0;
5954 rtx p = v->insn;
5955 rtx last_giv_use;
5957 v->replaceable = 1;
5958 v->not_replaceable = 0;
5960 /* When trying to determine whether or not a biv increment occurs
5961 during the lifetime of the giv, we can ignore uses of the variable
5962 outside the loop because final_value is true. Hence we can not
5963 use regno_last_uid and regno_first_uid as above in record_giv. */
5965 /* Search the loop to determine whether any assignments to the
5966 biv occur during the giv's lifetime. Start with the insn
5967 that sets the giv, and search around the loop until we come
5968 back to that insn again.
5970 Also fail if there is a jump within the giv's lifetime that jumps
5971 to somewhere outside the lifetime but still within the loop. This
5972 catches spaghetti code where the execution order is not linear, and
5973 hence the above test fails. Here we assume that the giv lifetime
5974 does not extend from one iteration of the loop to the next, so as
5975 to make the test easier. Since the lifetime isn't known yet,
5976 this requires two loops. See also record_giv above. */
5978 last_giv_use = v->insn;
5980 while (1)
5982 p = NEXT_INSN (p);
5983 if (p == loop->end)
5985 before_giv_insn = 1;
5986 p = NEXT_INSN (loop->start);
5988 if (p == v->insn)
5989 break;
5991 if (INSN_P (p))
5993 /* It is possible for the BIV increment to use the GIV if we
5994 have a cycle. Thus we must be sure to check each insn for
5995 both BIV and GIV uses, and we must check for BIV uses
5996 first. */
5998 if (! biv_increment_seen
5999 && reg_set_p (v->src_reg, PATTERN (p)))
6000 biv_increment_seen = 1;
6002 if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
6004 if (biv_increment_seen || before_giv_insn)
6006 v->replaceable = 0;
6007 v->not_replaceable = 1;
6008 break;
6010 last_giv_use = p;
6015 /* Now that the lifetime of the giv is known, check for branches
6016 from within the lifetime to outside the lifetime if it is still
6017 replaceable. */
6019 if (v->replaceable)
6021 p = v->insn;
6022 while (1)
6024 p = NEXT_INSN (p);
6025 if (p == loop->end)
6026 p = NEXT_INSN (loop->start);
6027 if (p == last_giv_use)
6028 break;
6030 if (JUMP_P (p) && JUMP_LABEL (p)
6031 && LABEL_NAME (JUMP_LABEL (p))
6032 && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
6033 && loop_insn_first_p (loop->start, JUMP_LABEL (p)))
6034 || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
6035 && loop_insn_first_p (JUMP_LABEL (p), loop->end))))
6037 v->replaceable = 0;
6038 v->not_replaceable = 1;
6040 if (loop_dump_stream)
6041 fprintf (loop_dump_stream,
6042 "Found branch outside giv lifetime.\n");
6044 break;
6049 /* If it is replaceable, then save the final value. */
6050 if (v->replaceable)
6051 v->final_value = final_value;
6054 if (loop_dump_stream && v->replaceable)
6055 fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
6056 INSN_UID (v->insn), REGNO (v->dest_reg));
6059 /* Update the status of whether a giv can derive other givs.
6061 We need to do something special if there is or may be an update to the biv
6062 between the time the giv is defined and the time it is used to derive
6063 another giv.
6065 In addition, a giv that is only conditionally set is not allowed to
6066 derive another giv once a label has been passed.
6068 The cases we look at are when a label or an update to a biv is passed. */
6070 static void
6071 update_giv_derive (const struct loop *loop, rtx p)
6073 struct loop_ivs *ivs = LOOP_IVS (loop);
6074 struct iv_class *bl;
6075 struct induction *biv, *giv;
6076 rtx tem;
6077 int dummy;
6079 /* Search all IV classes, then all bivs, and finally all givs.
6081 There are three cases we are concerned with. First we have the situation
6082 of a giv that is only updated conditionally. In that case, it may not
6083 derive any givs after a label is passed.
6085 The second case is when a biv update occurs, or may occur, after the
6086 definition of a giv. For certain biv updates (see below) that are
6087 known to occur between the giv definition and use, we can adjust the
6088 giv definition. For others, or when the biv update is conditional,
6089 we must prevent the giv from deriving any other givs. There are two
6090 sub-cases within this case.
6092 If this is a label, we are concerned with any biv update that is done
6093 conditionally, since it may be done after the giv is defined followed by
6094 a branch here (actually, we need to pass both a jump and a label, but
6095 this extra tracking doesn't seem worth it).
6097 If this is a jump, we are concerned about any biv update that may be
6098 executed multiple times. We are actually only concerned about
6099 backward jumps, but it is probably not worth performing the test
6100 on the jump again here.
6102 If this is a biv update, we must adjust the giv status to show that a
6103 subsequent biv update was performed. If this adjustment cannot be done,
6104 the giv cannot derive further givs. */
6106 for (bl = ivs->list; bl; bl = bl->next)
6107 for (biv = bl->biv; biv; biv = biv->next_iv)
6108 if (LABEL_P (p) || JUMP_P (p)
6109 || biv->insn == p)
6111 /* Skip if location is the same as a previous one. */
6112 if (biv->same)
6113 continue;
6115 for (giv = bl->giv; giv; giv = giv->next_iv)
6117 /* If cant_derive is already true, there is no point in
6118 checking all of these conditions again. */
6119 if (giv->cant_derive)
6120 continue;
6122 /* If this giv is conditionally set and we have passed a label,
6123 it cannot derive anything. */
6124 if (LABEL_P (p) && ! giv->always_computable)
6125 giv->cant_derive = 1;
6127 /* Skip givs that have mult_val == 0, since
6128 they are really invariants. Also skip those that are
6129 replaceable, since we know their lifetime doesn't contain
6130 any biv update. */
6131 else if (giv->mult_val == const0_rtx || giv->replaceable)
6132 continue;
6134 /* The only way we can allow this giv to derive another
6135 is if this is a biv increment and we can form the product
6136 of biv->add_val and giv->mult_val. In this case, we will
6137 be able to compute a compensation. */
6138 else if (biv->insn == p)
6140 rtx ext_val_dummy;
6142 tem = 0;
6143 if (biv->mult_val == const1_rtx)
6144 tem = simplify_giv_expr (loop,
6145 gen_rtx_MULT (giv->mode,
6146 biv->add_val,
6147 giv->mult_val),
6148 &ext_val_dummy, &dummy);
6150 if (tem && giv->derive_adjustment)
6151 tem = simplify_giv_expr
6152 (loop,
6153 gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
6154 &ext_val_dummy, &dummy);
6156 if (tem)
6157 giv->derive_adjustment = tem;
6158 else
6159 giv->cant_derive = 1;
6161 else if ((LABEL_P (p) && ! biv->always_computable)
6162 || (JUMP_P (p) && biv->maybe_multiple))
6163 giv->cant_derive = 1;
6168 /* Check whether an insn is an increment legitimate for a basic induction var.
6169 X is the source of insn P, or a part of it.
6170 MODE is the mode in which X should be interpreted.
6172 DEST_REG is the putative biv, also the destination of the insn.
6173 We accept patterns of these forms:
6174 REG = REG + INVARIANT (includes REG = REG - CONSTANT)
6175 REG = INVARIANT + REG
6177 If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
6178 store the additive term into *INC_VAL, and store the place where
6179 we found the additive term into *LOCATION.
6181 If X is an assignment of an invariant into DEST_REG, we set
6182 *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
6184 We also want to detect a BIV when it corresponds to a variable
6185 whose mode was promoted. In that case, an increment
6186 of the variable may be a PLUS that adds a SUBREG of that variable to
6187 an invariant and then sign- or zero-extends the result of the PLUS
6188 into the variable.
6190 Most GIVs in such cases will be in the promoted mode, since that is the
6191 probably the natural computation mode (and almost certainly the mode
6192 used for addresses) on the machine. So we view the pseudo-reg containing
6193 the variable as the BIV, as if it were simply incremented.
6195 Note that treating the entire pseudo as a BIV will result in making
6196 simple increments to any GIVs based on it. However, if the variable
6197 overflows in its declared mode but not its promoted mode, the result will
6198 be incorrect. This is acceptable if the variable is signed, since
6199 overflows in such cases are undefined, but not if it is unsigned, since
6200 those overflows are defined. So we only check for SIGN_EXTEND and
6201 not ZERO_EXTEND.
6203 If we cannot find a biv, we return 0. */
6205 static int
6206 basic_induction_var (const struct loop *loop, rtx x, enum machine_mode mode,
6207 rtx dest_reg, rtx p, rtx *inc_val, rtx *mult_val,
6208 rtx **location)
6210 enum rtx_code code;
6211 rtx *argp, arg;
6212 rtx insn, set = 0, last, inc;
6214 code = GET_CODE (x);
6215 *location = NULL;
6216 switch (code)
6218 case PLUS:
6219 if (rtx_equal_p (XEXP (x, 0), dest_reg)
6220 || (GET_CODE (XEXP (x, 0)) == SUBREG
6221 && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
6222 && SUBREG_REG (XEXP (x, 0)) == dest_reg))
6224 argp = &XEXP (x, 1);
6226 else if (rtx_equal_p (XEXP (x, 1), dest_reg)
6227 || (GET_CODE (XEXP (x, 1)) == SUBREG
6228 && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
6229 && SUBREG_REG (XEXP (x, 1)) == dest_reg))
6231 argp = &XEXP (x, 0);
6233 else
6234 return 0;
6236 arg = *argp;
6237 if (loop_invariant_p (loop, arg) != 1)
6238 return 0;
6240 /* convert_modes can emit new instructions, e.g. when arg is a loop
6241 invariant MEM and dest_reg has a different mode.
6242 These instructions would be emitted after the end of the function
6243 and then *inc_val would be an uninitialized pseudo.
6244 Detect this and bail in this case.
6245 Other alternatives to solve this can be introducing a convert_modes
6246 variant which is allowed to fail but not allowed to emit new
6247 instructions, emit these instructions before loop start and let
6248 it be garbage collected if *inc_val is never used or saving the
6249 *inc_val initialization sequence generated here and when *inc_val
6250 is going to be actually used, emit it at some suitable place. */
6251 last = get_last_insn ();
6252 inc = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
6253 if (get_last_insn () != last)
6255 delete_insns_since (last);
6256 return 0;
6259 *inc_val = inc;
6260 *mult_val = const1_rtx;
6261 *location = argp;
6262 return 1;
6264 case SUBREG:
6265 /* If what's inside the SUBREG is a BIV, then the SUBREG. This will
6266 handle addition of promoted variables.
6267 ??? The comment at the start of this function is wrong: promoted
6268 variable increments don't look like it says they do. */
6269 return basic_induction_var (loop, SUBREG_REG (x),
6270 GET_MODE (SUBREG_REG (x)),
6271 dest_reg, p, inc_val, mult_val, location);
6273 case REG:
6274 /* If this register is assigned in a previous insn, look at its
6275 source, but don't go outside the loop or past a label. */
6277 /* If this sets a register to itself, we would repeat any previous
6278 biv increment if we applied this strategy blindly. */
6279 if (rtx_equal_p (dest_reg, x))
6280 return 0;
6282 insn = p;
6283 while (1)
6285 rtx dest;
6288 insn = PREV_INSN (insn);
6290 while (insn && NOTE_P (insn)
6291 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6293 if (!insn)
6294 break;
6295 set = single_set (insn);
6296 if (set == 0)
6297 break;
6298 dest = SET_DEST (set);
6299 if (dest == x
6300 || (GET_CODE (dest) == SUBREG
6301 && (GET_MODE_SIZE (GET_MODE (dest)) <= UNITS_PER_WORD)
6302 && (GET_MODE_CLASS (GET_MODE (dest)) == MODE_INT)
6303 && SUBREG_REG (dest) == x))
6304 return basic_induction_var (loop, SET_SRC (set),
6305 (GET_MODE (SET_SRC (set)) == VOIDmode
6306 ? GET_MODE (x)
6307 : GET_MODE (SET_SRC (set))),
6308 dest_reg, insn,
6309 inc_val, mult_val, location);
6311 while (GET_CODE (dest) == SIGN_EXTRACT
6312 || GET_CODE (dest) == ZERO_EXTRACT
6313 || GET_CODE (dest) == SUBREG
6314 || GET_CODE (dest) == STRICT_LOW_PART)
6315 dest = XEXP (dest, 0);
6316 if (dest == x)
6317 break;
6319 /* Fall through. */
6321 /* Can accept constant setting of biv only when inside inner most loop.
6322 Otherwise, a biv of an inner loop may be incorrectly recognized
6323 as a biv of the outer loop,
6324 causing code to be moved INTO the inner loop. */
6325 case MEM:
6326 if (loop_invariant_p (loop, x) != 1)
6327 return 0;
6328 case CONST_INT:
6329 case SYMBOL_REF:
6330 case CONST:
6331 /* convert_modes aborts if we try to convert to or from CCmode, so just
6332 exclude that case. It is very unlikely that a condition code value
6333 would be a useful iterator anyways. convert_modes aborts if we try to
6334 convert a float mode to non-float or vice versa too. */
6335 if (loop->level == 1
6336 && GET_MODE_CLASS (mode) == GET_MODE_CLASS (GET_MODE (dest_reg))
6337 && GET_MODE_CLASS (mode) != MODE_CC)
6339 /* Possible bug here? Perhaps we don't know the mode of X. */
6340 last = get_last_insn ();
6341 inc = convert_modes (GET_MODE (dest_reg), mode, x, 0);
6342 if (get_last_insn () != last)
6344 delete_insns_since (last);
6345 return 0;
6348 *inc_val = inc;
6349 *mult_val = const0_rtx;
6350 return 1;
6352 else
6353 return 0;
6355 case SIGN_EXTEND:
6356 /* Ignore this BIV if signed arithmetic overflow is defined. */
6357 if (flag_wrapv)
6358 return 0;
6359 return basic_induction_var (loop, XEXP (x, 0), GET_MODE (XEXP (x, 0)),
6360 dest_reg, p, inc_val, mult_val, location);
6362 case ASHIFTRT:
6363 /* Similar, since this can be a sign extension. */
6364 for (insn = PREV_INSN (p);
6365 (insn && NOTE_P (insn)
6366 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6367 insn = PREV_INSN (insn))
6370 if (insn)
6371 set = single_set (insn);
6373 if (! rtx_equal_p (dest_reg, XEXP (x, 0))
6374 && set && SET_DEST (set) == XEXP (x, 0)
6375 && GET_CODE (XEXP (x, 1)) == CONST_INT
6376 && INTVAL (XEXP (x, 1)) >= 0
6377 && GET_CODE (SET_SRC (set)) == ASHIFT
6378 && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
6379 return basic_induction_var (loop, XEXP (SET_SRC (set), 0),
6380 GET_MODE (XEXP (x, 0)),
6381 dest_reg, insn, inc_val, mult_val,
6382 location);
6383 return 0;
6385 default:
6386 return 0;
6390 /* A general induction variable (giv) is any quantity that is a linear
6391 function of a basic induction variable,
6392 i.e. giv = biv * mult_val + add_val.
6393 The coefficients can be any loop invariant quantity.
6394 A giv need not be computed directly from the biv;
6395 it can be computed by way of other givs. */
6397 /* Determine whether X computes a giv.
6398 If it does, return a nonzero value
6399 which is the benefit from eliminating the computation of X;
6400 set *SRC_REG to the register of the biv that it is computed from;
6401 set *ADD_VAL and *MULT_VAL to the coefficients,
6402 such that the value of X is biv * mult + add; */
6404 static int
6405 general_induction_var (const struct loop *loop, rtx x, rtx *src_reg,
6406 rtx *add_val, rtx *mult_val, rtx *ext_val,
6407 int is_addr, int *pbenefit,
6408 enum machine_mode addr_mode)
6410 struct loop_ivs *ivs = LOOP_IVS (loop);
6411 rtx orig_x = x;
6413 /* If this is an invariant, forget it, it isn't a giv. */
6414 if (loop_invariant_p (loop, x) == 1)
6415 return 0;
6417 *pbenefit = 0;
6418 *ext_val = NULL_RTX;
6419 x = simplify_giv_expr (loop, x, ext_val, pbenefit);
6420 if (x == 0)
6421 return 0;
6423 switch (GET_CODE (x))
6425 case USE:
6426 case CONST_INT:
6427 /* Since this is now an invariant and wasn't before, it must be a giv
6428 with MULT_VAL == 0. It doesn't matter which BIV we associate this
6429 with. */
6430 *src_reg = ivs->list->biv->dest_reg;
6431 *mult_val = const0_rtx;
6432 *add_val = x;
6433 break;
6435 case REG:
6436 /* This is equivalent to a BIV. */
6437 *src_reg = x;
6438 *mult_val = const1_rtx;
6439 *add_val = const0_rtx;
6440 break;
6442 case PLUS:
6443 /* Either (plus (biv) (invar)) or
6444 (plus (mult (biv) (invar_1)) (invar_2)). */
6445 if (GET_CODE (XEXP (x, 0)) == MULT)
6447 *src_reg = XEXP (XEXP (x, 0), 0);
6448 *mult_val = XEXP (XEXP (x, 0), 1);
6450 else
6452 *src_reg = XEXP (x, 0);
6453 *mult_val = const1_rtx;
6455 *add_val = XEXP (x, 1);
6456 break;
6458 case MULT:
6459 /* ADD_VAL is zero. */
6460 *src_reg = XEXP (x, 0);
6461 *mult_val = XEXP (x, 1);
6462 *add_val = const0_rtx;
6463 break;
6465 default:
6466 abort ();
6469 /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
6470 unless they are CONST_INT). */
6471 if (GET_CODE (*add_val) == USE)
6472 *add_val = XEXP (*add_val, 0);
6473 if (GET_CODE (*mult_val) == USE)
6474 *mult_val = XEXP (*mult_val, 0);
6476 if (is_addr)
6477 *pbenefit += address_cost (orig_x, addr_mode) - reg_address_cost;
6478 else
6479 *pbenefit += rtx_cost (orig_x, SET);
6481 /* Always return true if this is a giv so it will be detected as such,
6482 even if the benefit is zero or negative. This allows elimination
6483 of bivs that might otherwise not be eliminated. */
6484 return 1;
6487 /* Given an expression, X, try to form it as a linear function of a biv.
6488 We will canonicalize it to be of the form
6489 (plus (mult (BIV) (invar_1))
6490 (invar_2))
6491 with possible degeneracies.
6493 The invariant expressions must each be of a form that can be used as a
6494 machine operand. We surround then with a USE rtx (a hack, but localized
6495 and certainly unambiguous!) if not a CONST_INT for simplicity in this
6496 routine; it is the caller's responsibility to strip them.
6498 If no such canonicalization is possible (i.e., two biv's are used or an
6499 expression that is neither invariant nor a biv or giv), this routine
6500 returns 0.
6502 For a nonzero return, the result will have a code of CONST_INT, USE,
6503 REG (for a BIV), PLUS, or MULT. No other codes will occur.
6505 *BENEFIT will be incremented by the benefit of any sub-giv encountered. */
6507 static rtx sge_plus (enum machine_mode, rtx, rtx);
6508 static rtx sge_plus_constant (rtx, rtx);
6510 static rtx
6511 simplify_giv_expr (const struct loop *loop, rtx x, rtx *ext_val, int *benefit)
6513 struct loop_ivs *ivs = LOOP_IVS (loop);
6514 struct loop_regs *regs = LOOP_REGS (loop);
6515 enum machine_mode mode = GET_MODE (x);
6516 rtx arg0, arg1;
6517 rtx tem;
6519 /* If this is not an integer mode, or if we cannot do arithmetic in this
6520 mode, this can't be a giv. */
6521 if (mode != VOIDmode
6522 && (GET_MODE_CLASS (mode) != MODE_INT
6523 || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
6524 return NULL_RTX;
6526 switch (GET_CODE (x))
6528 case PLUS:
6529 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6530 arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
6531 if (arg0 == 0 || arg1 == 0)
6532 return NULL_RTX;
6534 /* Put constant last, CONST_INT last if both constant. */
6535 if ((GET_CODE (arg0) == USE
6536 || GET_CODE (arg0) == CONST_INT)
6537 && ! ((GET_CODE (arg0) == USE
6538 && GET_CODE (arg1) == USE)
6539 || GET_CODE (arg1) == CONST_INT))
6540 tem = arg0, arg0 = arg1, arg1 = tem;
6542 /* Handle addition of zero, then addition of an invariant. */
6543 if (arg1 == const0_rtx)
6544 return arg0;
6545 else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
6546 switch (GET_CODE (arg0))
6548 case CONST_INT:
6549 case USE:
6550 /* Adding two invariants must result in an invariant, so enclose
6551 addition operation inside a USE and return it. */
6552 if (GET_CODE (arg0) == USE)
6553 arg0 = XEXP (arg0, 0);
6554 if (GET_CODE (arg1) == USE)
6555 arg1 = XEXP (arg1, 0);
6557 if (GET_CODE (arg0) == CONST_INT)
6558 tem = arg0, arg0 = arg1, arg1 = tem;
6559 if (GET_CODE (arg1) == CONST_INT)
6560 tem = sge_plus_constant (arg0, arg1);
6561 else
6562 tem = sge_plus (mode, arg0, arg1);
6564 if (GET_CODE (tem) != CONST_INT)
6565 tem = gen_rtx_USE (mode, tem);
6566 return tem;
6568 case REG:
6569 case MULT:
6570 /* biv + invar or mult + invar. Return sum. */
6571 return gen_rtx_PLUS (mode, arg0, arg1);
6573 case PLUS:
6574 /* (a + invar_1) + invar_2. Associate. */
6575 return
6576 simplify_giv_expr (loop,
6577 gen_rtx_PLUS (mode,
6578 XEXP (arg0, 0),
6579 gen_rtx_PLUS (mode,
6580 XEXP (arg0, 1),
6581 arg1)),
6582 ext_val, benefit);
6584 default:
6585 abort ();
6588 /* Each argument must be either REG, PLUS, or MULT. Convert REG to
6589 MULT to reduce cases. */
6590 if (REG_P (arg0))
6591 arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
6592 if (REG_P (arg1))
6593 arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
6595 /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
6596 Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
6597 Recurse to associate the second PLUS. */
6598 if (GET_CODE (arg1) == MULT)
6599 tem = arg0, arg0 = arg1, arg1 = tem;
6601 if (GET_CODE (arg1) == PLUS)
6602 return
6603 simplify_giv_expr (loop,
6604 gen_rtx_PLUS (mode,
6605 gen_rtx_PLUS (mode, arg0,
6606 XEXP (arg1, 0)),
6607 XEXP (arg1, 1)),
6608 ext_val, benefit);
6610 /* Now must have MULT + MULT. Distribute if same biv, else not giv. */
6611 if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
6612 return NULL_RTX;
6614 if (!rtx_equal_p (arg0, arg1))
6615 return NULL_RTX;
6617 return simplify_giv_expr (loop,
6618 gen_rtx_MULT (mode,
6619 XEXP (arg0, 0),
6620 gen_rtx_PLUS (mode,
6621 XEXP (arg0, 1),
6622 XEXP (arg1, 1))),
6623 ext_val, benefit);
6625 case MINUS:
6626 /* Handle "a - b" as "a + b * (-1)". */
6627 return simplify_giv_expr (loop,
6628 gen_rtx_PLUS (mode,
6629 XEXP (x, 0),
6630 gen_rtx_MULT (mode,
6631 XEXP (x, 1),
6632 constm1_rtx)),
6633 ext_val, benefit);
6635 case MULT:
6636 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6637 arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
6638 if (arg0 == 0 || arg1 == 0)
6639 return NULL_RTX;
6641 /* Put constant last, CONST_INT last if both constant. */
6642 if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
6643 && GET_CODE (arg1) != CONST_INT)
6644 tem = arg0, arg0 = arg1, arg1 = tem;
6646 /* If second argument is not now constant, not giv. */
6647 if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
6648 return NULL_RTX;
6650 /* Handle multiply by 0 or 1. */
6651 if (arg1 == const0_rtx)
6652 return const0_rtx;
6654 else if (arg1 == const1_rtx)
6655 return arg0;
6657 switch (GET_CODE (arg0))
6659 case REG:
6660 /* biv * invar. Done. */
6661 return gen_rtx_MULT (mode, arg0, arg1);
6663 case CONST_INT:
6664 /* Product of two constants. */
6665 return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
6667 case USE:
6668 /* invar * invar is a giv, but attempt to simplify it somehow. */
6669 if (GET_CODE (arg1) != CONST_INT)
6670 return NULL_RTX;
6672 arg0 = XEXP (arg0, 0);
6673 if (GET_CODE (arg0) == MULT)
6675 /* (invar_0 * invar_1) * invar_2. Associate. */
6676 return simplify_giv_expr (loop,
6677 gen_rtx_MULT (mode,
6678 XEXP (arg0, 0),
6679 gen_rtx_MULT (mode,
6680 XEXP (arg0,
6682 arg1)),
6683 ext_val, benefit);
6685 /* Propagate the MULT expressions to the innermost nodes. */
6686 else if (GET_CODE (arg0) == PLUS)
6688 /* (invar_0 + invar_1) * invar_2. Distribute. */
6689 return simplify_giv_expr (loop,
6690 gen_rtx_PLUS (mode,
6691 gen_rtx_MULT (mode,
6692 XEXP (arg0,
6694 arg1),
6695 gen_rtx_MULT (mode,
6696 XEXP (arg0,
6698 arg1)),
6699 ext_val, benefit);
6701 return gen_rtx_USE (mode, gen_rtx_MULT (mode, arg0, arg1));
6703 case MULT:
6704 /* (a * invar_1) * invar_2. Associate. */
6705 return simplify_giv_expr (loop,
6706 gen_rtx_MULT (mode,
6707 XEXP (arg0, 0),
6708 gen_rtx_MULT (mode,
6709 XEXP (arg0, 1),
6710 arg1)),
6711 ext_val, benefit);
6713 case PLUS:
6714 /* (a + invar_1) * invar_2. Distribute. */
6715 return simplify_giv_expr (loop,
6716 gen_rtx_PLUS (mode,
6717 gen_rtx_MULT (mode,
6718 XEXP (arg0, 0),
6719 arg1),
6720 gen_rtx_MULT (mode,
6721 XEXP (arg0, 1),
6722 arg1)),
6723 ext_val, benefit);
6725 default:
6726 abort ();
6729 case ASHIFT:
6730 /* Shift by constant is multiply by power of two. */
6731 if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6732 return 0;
6734 return
6735 simplify_giv_expr (loop,
6736 gen_rtx_MULT (mode,
6737 XEXP (x, 0),
6738 GEN_INT ((HOST_WIDE_INT) 1
6739 << INTVAL (XEXP (x, 1)))),
6740 ext_val, benefit);
6742 case NEG:
6743 /* "-a" is "a * (-1)" */
6744 return simplify_giv_expr (loop,
6745 gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
6746 ext_val, benefit);
6748 case NOT:
6749 /* "~a" is "-a - 1". Silly, but easy. */
6750 return simplify_giv_expr (loop,
6751 gen_rtx_MINUS (mode,
6752 gen_rtx_NEG (mode, XEXP (x, 0)),
6753 const1_rtx),
6754 ext_val, benefit);
6756 case USE:
6757 /* Already in proper form for invariant. */
6758 return x;
6760 case SIGN_EXTEND:
6761 case ZERO_EXTEND:
6762 case TRUNCATE:
6763 /* Conditionally recognize extensions of simple IVs. After we've
6764 computed loop traversal counts and verified the range of the
6765 source IV, we'll reevaluate this as a GIV. */
6766 if (*ext_val == NULL_RTX)
6768 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6769 if (arg0 && *ext_val == NULL_RTX && REG_P (arg0))
6771 *ext_val = gen_rtx_fmt_e (GET_CODE (x), mode, arg0);
6772 return arg0;
6775 goto do_default;
6777 case REG:
6778 /* If this is a new register, we can't deal with it. */
6779 if (REGNO (x) >= max_reg_before_loop)
6780 return 0;
6782 /* Check for biv or giv. */
6783 switch (REG_IV_TYPE (ivs, REGNO (x)))
6785 case BASIC_INDUCT:
6786 return x;
6787 case GENERAL_INDUCT:
6789 struct induction *v = REG_IV_INFO (ivs, REGNO (x));
6791 /* Form expression from giv and add benefit. Ensure this giv
6792 can derive another and subtract any needed adjustment if so. */
6794 /* Increasing the benefit here is risky. The only case in which it
6795 is arguably correct is if this is the only use of V. In other
6796 cases, this will artificially inflate the benefit of the current
6797 giv, and lead to suboptimal code. Thus, it is disabled, since
6798 potentially not reducing an only marginally beneficial giv is
6799 less harmful than reducing many givs that are not really
6800 beneficial. */
6802 rtx single_use = regs->array[REGNO (x)].single_usage;
6803 if (single_use && single_use != const0_rtx)
6804 *benefit += v->benefit;
6807 if (v->cant_derive)
6808 return 0;
6810 tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
6811 v->src_reg, v->mult_val),
6812 v->add_val);
6814 if (v->derive_adjustment)
6815 tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
6816 arg0 = simplify_giv_expr (loop, tem, ext_val, benefit);
6817 if (*ext_val)
6819 if (!v->ext_dependent)
6820 return arg0;
6822 else
6824 *ext_val = v->ext_dependent;
6825 return arg0;
6827 return 0;
6830 default:
6831 do_default:
6832 /* If it isn't an induction variable, and it is invariant, we
6833 may be able to simplify things further by looking through
6834 the bits we just moved outside the loop. */
6835 if (loop_invariant_p (loop, x) == 1)
6837 struct movable *m;
6838 struct loop_movables *movables = LOOP_MOVABLES (loop);
6840 for (m = movables->head; m; m = m->next)
6841 if (rtx_equal_p (x, m->set_dest))
6843 /* Ok, we found a match. Substitute and simplify. */
6845 /* If we match another movable, we must use that, as
6846 this one is going away. */
6847 if (m->match)
6848 return simplify_giv_expr (loop, m->match->set_dest,
6849 ext_val, benefit);
6851 /* If consec is nonzero, this is a member of a group of
6852 instructions that were moved together. We handle this
6853 case only to the point of seeking to the last insn and
6854 looking for a REG_EQUAL. Fail if we don't find one. */
6855 if (m->consec != 0)
6857 int i = m->consec;
6858 tem = m->insn;
6861 tem = NEXT_INSN (tem);
6863 while (--i > 0);
6865 tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
6866 if (tem)
6867 tem = XEXP (tem, 0);
6869 else
6871 tem = single_set (m->insn);
6872 if (tem)
6873 tem = SET_SRC (tem);
6876 if (tem)
6878 /* What we are most interested in is pointer
6879 arithmetic on invariants -- only take
6880 patterns we may be able to do something with. */
6881 if (GET_CODE (tem) == PLUS
6882 || GET_CODE (tem) == MULT
6883 || GET_CODE (tem) == ASHIFT
6884 || GET_CODE (tem) == CONST_INT
6885 || GET_CODE (tem) == SYMBOL_REF)
6887 tem = simplify_giv_expr (loop, tem, ext_val,
6888 benefit);
6889 if (tem)
6890 return tem;
6892 else if (GET_CODE (tem) == CONST
6893 && GET_CODE (XEXP (tem, 0)) == PLUS
6894 && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
6895 && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
6897 tem = simplify_giv_expr (loop, XEXP (tem, 0),
6898 ext_val, benefit);
6899 if (tem)
6900 return tem;
6903 break;
6906 break;
6909 /* Fall through to general case. */
6910 default:
6911 /* If invariant, return as USE (unless CONST_INT).
6912 Otherwise, not giv. */
6913 if (GET_CODE (x) == USE)
6914 x = XEXP (x, 0);
6916 if (loop_invariant_p (loop, x) == 1)
6918 if (GET_CODE (x) == CONST_INT)
6919 return x;
6920 if (GET_CODE (x) == CONST
6921 && GET_CODE (XEXP (x, 0)) == PLUS
6922 && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
6923 && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
6924 x = XEXP (x, 0);
6925 return gen_rtx_USE (mode, x);
6927 else
6928 return 0;
6932 /* This routine folds invariants such that there is only ever one
6933 CONST_INT in the summation. It is only used by simplify_giv_expr. */
6935 static rtx
6936 sge_plus_constant (rtx x, rtx c)
6938 if (GET_CODE (x) == CONST_INT)
6939 return GEN_INT (INTVAL (x) + INTVAL (c));
6940 else if (GET_CODE (x) != PLUS)
6941 return gen_rtx_PLUS (GET_MODE (x), x, c);
6942 else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
6944 return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
6945 GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
6947 else if (GET_CODE (XEXP (x, 0)) == PLUS
6948 || GET_CODE (XEXP (x, 1)) != PLUS)
6950 return gen_rtx_PLUS (GET_MODE (x),
6951 sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
6953 else
6955 return gen_rtx_PLUS (GET_MODE (x),
6956 sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
6960 static rtx
6961 sge_plus (enum machine_mode mode, rtx x, rtx y)
6963 while (GET_CODE (y) == PLUS)
6965 rtx a = XEXP (y, 0);
6966 if (GET_CODE (a) == CONST_INT)
6967 x = sge_plus_constant (x, a);
6968 else
6969 x = gen_rtx_PLUS (mode, x, a);
6970 y = XEXP (y, 1);
6972 if (GET_CODE (y) == CONST_INT)
6973 x = sge_plus_constant (x, y);
6974 else
6975 x = gen_rtx_PLUS (mode, x, y);
6976 return x;
6979 /* Help detect a giv that is calculated by several consecutive insns;
6980 for example,
6981 giv = biv * M
6982 giv = giv + A
6983 The caller has already identified the first insn P as having a giv as dest;
6984 we check that all other insns that set the same register follow
6985 immediately after P, that they alter nothing else,
6986 and that the result of the last is still a giv.
6988 The value is 0 if the reg set in P is not really a giv.
6989 Otherwise, the value is the amount gained by eliminating
6990 all the consecutive insns that compute the value.
6992 FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
6993 SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
6995 The coefficients of the ultimate giv value are stored in
6996 *MULT_VAL and *ADD_VAL. */
6998 static int
6999 consec_sets_giv (const struct loop *loop, int first_benefit, rtx p,
7000 rtx src_reg, rtx dest_reg, rtx *add_val, rtx *mult_val,
7001 rtx *ext_val, rtx *last_consec_insn)
7003 struct loop_ivs *ivs = LOOP_IVS (loop);
7004 struct loop_regs *regs = LOOP_REGS (loop);
7005 int count;
7006 enum rtx_code code;
7007 int benefit;
7008 rtx temp;
7009 rtx set;
7011 /* Indicate that this is a giv so that we can update the value produced in
7012 each insn of the multi-insn sequence.
7014 This induction structure will be used only by the call to
7015 general_induction_var below, so we can allocate it on our stack.
7016 If this is a giv, our caller will replace the induct var entry with
7017 a new induction structure. */
7018 struct induction *v;
7020 if (REG_IV_TYPE (ivs, REGNO (dest_reg)) != UNKNOWN_INDUCT)
7021 return 0;
7023 v = alloca (sizeof (struct induction));
7024 v->src_reg = src_reg;
7025 v->mult_val = *mult_val;
7026 v->add_val = *add_val;
7027 v->benefit = first_benefit;
7028 v->cant_derive = 0;
7029 v->derive_adjustment = 0;
7030 v->ext_dependent = NULL_RTX;
7032 REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
7033 REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
7035 count = regs->array[REGNO (dest_reg)].n_times_set - 1;
7037 while (count > 0)
7039 p = NEXT_INSN (p);
7040 code = GET_CODE (p);
7042 /* If libcall, skip to end of call sequence. */
7043 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
7044 p = XEXP (temp, 0);
7046 if (code == INSN
7047 && (set = single_set (p))
7048 && REG_P (SET_DEST (set))
7049 && SET_DEST (set) == dest_reg
7050 && (general_induction_var (loop, SET_SRC (set), &src_reg,
7051 add_val, mult_val, ext_val, 0,
7052 &benefit, VOIDmode)
7053 /* Giv created by equivalent expression. */
7054 || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
7055 && general_induction_var (loop, XEXP (temp, 0), &src_reg,
7056 add_val, mult_val, ext_val, 0,
7057 &benefit, VOIDmode)))
7058 && src_reg == v->src_reg)
7060 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
7061 benefit += libcall_benefit (p);
7063 count--;
7064 v->mult_val = *mult_val;
7065 v->add_val = *add_val;
7066 v->benefit += benefit;
7068 else if (code != NOTE)
7070 /* Allow insns that set something other than this giv to a
7071 constant. Such insns are needed on machines which cannot
7072 include long constants and should not disqualify a giv. */
7073 if (code == INSN
7074 && (set = single_set (p))
7075 && SET_DEST (set) != dest_reg
7076 && CONSTANT_P (SET_SRC (set)))
7077 continue;
7079 REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
7080 return 0;
7084 REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
7085 *last_consec_insn = p;
7086 return v->benefit;
7089 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7090 represented by G1. If no such expression can be found, or it is clear that
7091 it cannot possibly be a valid address, 0 is returned.
7093 To perform the computation, we note that
7094 G1 = x * v + a and
7095 G2 = y * v + b
7096 where `v' is the biv.
7098 So G2 = (y/b) * G1 + (b - a*y/x).
7100 Note that MULT = y/x.
7102 Update: A and B are now allowed to be additive expressions such that
7103 B contains all variables in A. That is, computing B-A will not require
7104 subtracting variables. */
7106 static rtx
7107 express_from_1 (rtx a, rtx b, rtx mult)
7109 /* If MULT is zero, then A*MULT is zero, and our expression is B. */
7111 if (mult == const0_rtx)
7112 return b;
7114 /* If MULT is not 1, we cannot handle A with non-constants, since we
7115 would then be required to subtract multiples of the registers in A.
7116 This is theoretically possible, and may even apply to some Fortran
7117 constructs, but it is a lot of work and we do not attempt it here. */
7119 if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
7120 return NULL_RTX;
7122 /* In general these structures are sorted top to bottom (down the PLUS
7123 chain), but not left to right across the PLUS. If B is a higher
7124 order giv than A, we can strip one level and recurse. If A is higher
7125 order, we'll eventually bail out, but won't know that until the end.
7126 If they are the same, we'll strip one level around this loop. */
7128 while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
7130 rtx ra, rb, oa, ob, tmp;
7132 ra = XEXP (a, 0), oa = XEXP (a, 1);
7133 if (GET_CODE (ra) == PLUS)
7134 tmp = ra, ra = oa, oa = tmp;
7136 rb = XEXP (b, 0), ob = XEXP (b, 1);
7137 if (GET_CODE (rb) == PLUS)
7138 tmp = rb, rb = ob, ob = tmp;
7140 if (rtx_equal_p (ra, rb))
7141 /* We matched: remove one reg completely. */
7142 a = oa, b = ob;
7143 else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
7144 /* An alternate match. */
7145 a = oa, b = rb;
7146 else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
7147 /* An alternate match. */
7148 a = ra, b = ob;
7149 else
7151 /* Indicates an extra register in B. Strip one level from B and
7152 recurse, hoping B was the higher order expression. */
7153 ob = express_from_1 (a, ob, mult);
7154 if (ob == NULL_RTX)
7155 return NULL_RTX;
7156 return gen_rtx_PLUS (GET_MODE (b), rb, ob);
7160 /* Here we are at the last level of A, go through the cases hoping to
7161 get rid of everything but a constant. */
7163 if (GET_CODE (a) == PLUS)
7165 rtx ra, oa;
7167 ra = XEXP (a, 0), oa = XEXP (a, 1);
7168 if (rtx_equal_p (oa, b))
7169 oa = ra;
7170 else if (!rtx_equal_p (ra, b))
7171 return NULL_RTX;
7173 if (GET_CODE (oa) != CONST_INT)
7174 return NULL_RTX;
7176 return GEN_INT (-INTVAL (oa) * INTVAL (mult));
7178 else if (GET_CODE (a) == CONST_INT)
7180 return plus_constant (b, -INTVAL (a) * INTVAL (mult));
7182 else if (CONSTANT_P (a))
7184 enum machine_mode mode_a = GET_MODE (a);
7185 enum machine_mode mode_b = GET_MODE (b);
7186 enum machine_mode mode = mode_b == VOIDmode ? mode_a : mode_b;
7187 return simplify_gen_binary (MINUS, mode, b, a);
7189 else if (GET_CODE (b) == PLUS)
7191 if (rtx_equal_p (a, XEXP (b, 0)))
7192 return XEXP (b, 1);
7193 else if (rtx_equal_p (a, XEXP (b, 1)))
7194 return XEXP (b, 0);
7195 else
7196 return NULL_RTX;
7198 else if (rtx_equal_p (a, b))
7199 return const0_rtx;
7201 return NULL_RTX;
7205 express_from (struct induction *g1, struct induction *g2)
7207 rtx mult, add;
7209 /* The value that G1 will be multiplied by must be a constant integer. Also,
7210 the only chance we have of getting a valid address is if b*c/a (see above
7211 for notation) is also an integer. */
7212 if (GET_CODE (g1->mult_val) == CONST_INT
7213 && GET_CODE (g2->mult_val) == CONST_INT)
7215 if (g1->mult_val == const0_rtx
7216 || (g1->mult_val == constm1_rtx
7217 && INTVAL (g2->mult_val)
7218 == (HOST_WIDE_INT) 1 << (HOST_BITS_PER_WIDE_INT - 1))
7219 || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
7220 return NULL_RTX;
7221 mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
7223 else if (rtx_equal_p (g1->mult_val, g2->mult_val))
7224 mult = const1_rtx;
7225 else
7227 /* ??? Find out if the one is a multiple of the other? */
7228 return NULL_RTX;
7231 add = express_from_1 (g1->add_val, g2->add_val, mult);
7232 if (add == NULL_RTX)
7234 /* Failed. If we've got a multiplication factor between G1 and G2,
7235 scale G1's addend and try again. */
7236 if (INTVAL (mult) > 1)
7238 rtx g1_add_val = g1->add_val;
7239 if (GET_CODE (g1_add_val) == MULT
7240 && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
7242 HOST_WIDE_INT m;
7243 m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
7244 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
7245 XEXP (g1_add_val, 0), GEN_INT (m));
7247 else
7249 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
7250 mult);
7253 add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
7256 if (add == NULL_RTX)
7257 return NULL_RTX;
7259 /* Form simplified final result. */
7260 if (mult == const0_rtx)
7261 return add;
7262 else if (mult == const1_rtx)
7263 mult = g1->dest_reg;
7264 else
7265 mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
7267 if (add == const0_rtx)
7268 return mult;
7269 else
7271 if (GET_CODE (add) == PLUS
7272 && CONSTANT_P (XEXP (add, 1)))
7274 rtx tem = XEXP (add, 1);
7275 mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
7276 add = tem;
7279 return gen_rtx_PLUS (g2->mode, mult, add);
7283 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7284 represented by G1. This indicates that G2 should be combined with G1 and
7285 that G2 can use (either directly or via an address expression) a register
7286 used to represent G1. */
7288 static rtx
7289 combine_givs_p (struct induction *g1, struct induction *g2)
7291 rtx comb, ret;
7293 /* With the introduction of ext dependent givs, we must care for modes.
7294 G2 must not use a wider mode than G1. */
7295 if (GET_MODE_SIZE (g1->mode) < GET_MODE_SIZE (g2->mode))
7296 return NULL_RTX;
7298 ret = comb = express_from (g1, g2);
7299 if (comb == NULL_RTX)
7300 return NULL_RTX;
7301 if (g1->mode != g2->mode)
7302 ret = gen_lowpart (g2->mode, comb);
7304 /* If these givs are identical, they can be combined. We use the results
7305 of express_from because the addends are not in a canonical form, so
7306 rtx_equal_p is a weaker test. */
7307 /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
7308 combination to be the other way round. */
7309 if (comb == g1->dest_reg
7310 && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
7312 return ret;
7315 /* If G2 can be expressed as a function of G1 and that function is valid
7316 as an address and no more expensive than using a register for G2,
7317 the expression of G2 in terms of G1 can be used. */
7318 if (ret != NULL_RTX
7319 && g2->giv_type == DEST_ADDR
7320 && memory_address_p (GET_MODE (g2->mem), ret))
7321 return ret;
7323 return NULL_RTX;
7326 /* Check each extension dependent giv in this class to see if its
7327 root biv is safe from wrapping in the interior mode, which would
7328 make the giv illegal. */
7330 static void
7331 check_ext_dependent_givs (const struct loop *loop, struct iv_class *bl)
7333 struct loop_info *loop_info = LOOP_INFO (loop);
7334 int ze_ok = 0, se_ok = 0, info_ok = 0;
7335 enum machine_mode biv_mode = GET_MODE (bl->biv->src_reg);
7336 HOST_WIDE_INT start_val;
7337 unsigned HOST_WIDE_INT u_end_val = 0;
7338 unsigned HOST_WIDE_INT u_start_val = 0;
7339 rtx incr = pc_rtx;
7340 struct induction *v;
7342 /* Make sure the iteration data is available. We must have
7343 constants in order to be certain of no overflow. */
7344 if (loop_info->n_iterations > 0
7345 && bl->initial_value
7346 && GET_CODE (bl->initial_value) == CONST_INT
7347 && (incr = biv_total_increment (bl))
7348 && GET_CODE (incr) == CONST_INT
7349 /* Make sure the host can represent the arithmetic. */
7350 && HOST_BITS_PER_WIDE_INT >= GET_MODE_BITSIZE (biv_mode))
7352 unsigned HOST_WIDE_INT abs_incr, total_incr;
7353 HOST_WIDE_INT s_end_val;
7354 int neg_incr;
7356 info_ok = 1;
7357 start_val = INTVAL (bl->initial_value);
7358 u_start_val = start_val;
7360 neg_incr = 0, abs_incr = INTVAL (incr);
7361 if (INTVAL (incr) < 0)
7362 neg_incr = 1, abs_incr = -abs_incr;
7363 total_incr = abs_incr * loop_info->n_iterations;
7365 /* Check for host arithmetic overflow. */
7366 if (total_incr / loop_info->n_iterations == abs_incr)
7368 unsigned HOST_WIDE_INT u_max;
7369 HOST_WIDE_INT s_max;
7371 u_end_val = start_val + (neg_incr ? -total_incr : total_incr);
7372 s_end_val = u_end_val;
7373 u_max = GET_MODE_MASK (biv_mode);
7374 s_max = u_max >> 1;
7376 /* Check zero extension of biv ok. */
7377 if (start_val >= 0
7378 /* Check for host arithmetic overflow. */
7379 && (neg_incr
7380 ? u_end_val < u_start_val
7381 : u_end_val > u_start_val)
7382 /* Check for target arithmetic overflow. */
7383 && (neg_incr
7384 ? 1 /* taken care of with host overflow */
7385 : u_end_val <= u_max))
7387 ze_ok = 1;
7390 /* Check sign extension of biv ok. */
7391 /* ??? While it is true that overflow with signed and pointer
7392 arithmetic is undefined, I fear too many programmers don't
7393 keep this fact in mind -- myself included on occasion.
7394 So leave alone with the signed overflow optimizations. */
7395 if (start_val >= -s_max - 1
7396 /* Check for host arithmetic overflow. */
7397 && (neg_incr
7398 ? s_end_val < start_val
7399 : s_end_val > start_val)
7400 /* Check for target arithmetic overflow. */
7401 && (neg_incr
7402 ? s_end_val >= -s_max - 1
7403 : s_end_val <= s_max))
7405 se_ok = 1;
7410 /* If we know the BIV is compared at run-time against an
7411 invariant value, and the increment is +/- 1, we may also
7412 be able to prove that the BIV cannot overflow. */
7413 else if (bl->biv->src_reg == loop_info->iteration_var
7414 && loop_info->comparison_value
7415 && loop_invariant_p (loop, loop_info->comparison_value)
7416 && (incr = biv_total_increment (bl))
7417 && GET_CODE (incr) == CONST_INT)
7419 /* If the increment is +1, and the exit test is a <,
7420 the BIV cannot overflow. (For <=, we have the
7421 problematic case that the comparison value might
7422 be the maximum value of the range.) */
7423 if (INTVAL (incr) == 1)
7425 if (loop_info->comparison_code == LT)
7426 se_ok = ze_ok = 1;
7427 else if (loop_info->comparison_code == LTU)
7428 ze_ok = 1;
7431 /* Likewise for increment -1 and exit test >. */
7432 if (INTVAL (incr) == -1)
7434 if (loop_info->comparison_code == GT)
7435 se_ok = ze_ok = 1;
7436 else if (loop_info->comparison_code == GTU)
7437 ze_ok = 1;
7441 /* Invalidate givs that fail the tests. */
7442 for (v = bl->giv; v; v = v->next_iv)
7443 if (v->ext_dependent)
7445 enum rtx_code code = GET_CODE (v->ext_dependent);
7446 int ok = 0;
7448 switch (code)
7450 case SIGN_EXTEND:
7451 ok = se_ok;
7452 break;
7453 case ZERO_EXTEND:
7454 ok = ze_ok;
7455 break;
7457 case TRUNCATE:
7458 /* We don't know whether this value is being used as either
7459 signed or unsigned, so to safely truncate we must satisfy
7460 both. The initial check here verifies the BIV itself;
7461 once that is successful we may check its range wrt the
7462 derived GIV. This works only if we were able to determine
7463 constant start and end values above. */
7464 if (se_ok && ze_ok && info_ok)
7466 enum machine_mode outer_mode = GET_MODE (v->ext_dependent);
7467 unsigned HOST_WIDE_INT max = GET_MODE_MASK (outer_mode) >> 1;
7469 /* We know from the above that both endpoints are nonnegative,
7470 and that there is no wrapping. Verify that both endpoints
7471 are within the (signed) range of the outer mode. */
7472 if (u_start_val <= max && u_end_val <= max)
7473 ok = 1;
7475 break;
7477 default:
7478 abort ();
7481 if (ok)
7483 if (loop_dump_stream)
7485 fprintf (loop_dump_stream,
7486 "Verified ext dependent giv at %d of reg %d\n",
7487 INSN_UID (v->insn), bl->regno);
7490 else
7492 if (loop_dump_stream)
7494 const char *why;
7496 if (info_ok)
7497 why = "biv iteration values overflowed";
7498 else
7500 if (incr == pc_rtx)
7501 incr = biv_total_increment (bl);
7502 if (incr == const1_rtx)
7503 why = "biv iteration info incomplete; incr by 1";
7504 else
7505 why = "biv iteration info incomplete";
7508 fprintf (loop_dump_stream,
7509 "Failed ext dependent giv at %d, %s\n",
7510 INSN_UID (v->insn), why);
7512 v->ignore = 1;
7513 bl->all_reduced = 0;
7518 /* Generate a version of VALUE in a mode appropriate for initializing V. */
7521 extend_value_for_giv (struct induction *v, rtx value)
7523 rtx ext_dep = v->ext_dependent;
7525 if (! ext_dep)
7526 return value;
7528 /* Recall that check_ext_dependent_givs verified that the known bounds
7529 of a biv did not overflow or wrap with respect to the extension for
7530 the giv. Therefore, constants need no additional adjustment. */
7531 if (CONSTANT_P (value) && GET_MODE (value) == VOIDmode)
7532 return value;
7534 /* Otherwise, we must adjust the value to compensate for the
7535 differing modes of the biv and the giv. */
7536 return gen_rtx_fmt_e (GET_CODE (ext_dep), GET_MODE (ext_dep), value);
7539 struct combine_givs_stats
7541 int giv_number;
7542 int total_benefit;
7545 static int
7546 cmp_combine_givs_stats (const void *xp, const void *yp)
7548 const struct combine_givs_stats * const x =
7549 (const struct combine_givs_stats *) xp;
7550 const struct combine_givs_stats * const y =
7551 (const struct combine_givs_stats *) yp;
7552 int d;
7553 d = y->total_benefit - x->total_benefit;
7554 /* Stabilize the sort. */
7555 if (!d)
7556 d = x->giv_number - y->giv_number;
7557 return d;
7560 /* Check all pairs of givs for iv_class BL and see if any can be combined with
7561 any other. If so, point SAME to the giv combined with and set NEW_REG to
7562 be an expression (in terms of the other giv's DEST_REG) equivalent to the
7563 giv. Also, update BENEFIT and related fields for cost/benefit analysis. */
7565 static void
7566 combine_givs (struct loop_regs *regs, struct iv_class *bl)
7568 /* Additional benefit to add for being combined multiple times. */
7569 const int extra_benefit = 3;
7571 struct induction *g1, *g2, **giv_array;
7572 int i, j, k, giv_count;
7573 struct combine_givs_stats *stats;
7574 rtx *can_combine;
7576 /* Count givs, because bl->giv_count is incorrect here. */
7577 giv_count = 0;
7578 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7579 if (!g1->ignore)
7580 giv_count++;
7582 giv_array = alloca (giv_count * sizeof (struct induction *));
7583 i = 0;
7584 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7585 if (!g1->ignore)
7586 giv_array[i++] = g1;
7588 stats = xcalloc (giv_count, sizeof (*stats));
7589 can_combine = xcalloc (giv_count, giv_count * sizeof (rtx));
7591 for (i = 0; i < giv_count; i++)
7593 int this_benefit;
7594 rtx single_use;
7596 g1 = giv_array[i];
7597 stats[i].giv_number = i;
7599 /* If a DEST_REG GIV is used only once, do not allow it to combine
7600 with anything, for in doing so we will gain nothing that cannot
7601 be had by simply letting the GIV with which we would have combined
7602 to be reduced on its own. The losage shows up in particular with
7603 DEST_ADDR targets on hosts with reg+reg addressing, though it can
7604 be seen elsewhere as well. */
7605 if (g1->giv_type == DEST_REG
7606 && (single_use = regs->array[REGNO (g1->dest_reg)].single_usage)
7607 && single_use != const0_rtx)
7608 continue;
7610 this_benefit = g1->benefit;
7611 /* Add an additional weight for zero addends. */
7612 if (g1->no_const_addval)
7613 this_benefit += 1;
7615 for (j = 0; j < giv_count; j++)
7617 rtx this_combine;
7619 g2 = giv_array[j];
7620 if (g1 != g2
7621 && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
7623 can_combine[i * giv_count + j] = this_combine;
7624 this_benefit += g2->benefit + extra_benefit;
7627 stats[i].total_benefit = this_benefit;
7630 /* Iterate, combining until we can't. */
7631 restart:
7632 qsort (stats, giv_count, sizeof (*stats), cmp_combine_givs_stats);
7634 if (loop_dump_stream)
7636 fprintf (loop_dump_stream, "Sorted combine statistics:\n");
7637 for (k = 0; k < giv_count; k++)
7639 g1 = giv_array[stats[k].giv_number];
7640 if (!g1->combined_with && !g1->same)
7641 fprintf (loop_dump_stream, " {%d, %d}",
7642 INSN_UID (giv_array[stats[k].giv_number]->insn),
7643 stats[k].total_benefit);
7645 putc ('\n', loop_dump_stream);
7648 for (k = 0; k < giv_count; k++)
7650 int g1_add_benefit = 0;
7652 i = stats[k].giv_number;
7653 g1 = giv_array[i];
7655 /* If it has already been combined, skip. */
7656 if (g1->combined_with || g1->same)
7657 continue;
7659 for (j = 0; j < giv_count; j++)
7661 g2 = giv_array[j];
7662 if (g1 != g2 && can_combine[i * giv_count + j]
7663 /* If it has already been combined, skip. */
7664 && ! g2->same && ! g2->combined_with)
7666 int l;
7668 g2->new_reg = can_combine[i * giv_count + j];
7669 g2->same = g1;
7670 /* For destination, we now may replace by mem expression instead
7671 of register. This changes the costs considerably, so add the
7672 compensation. */
7673 if (g2->giv_type == DEST_ADDR)
7674 g2->benefit = (g2->benefit + reg_address_cost
7675 - address_cost (g2->new_reg,
7676 GET_MODE (g2->mem)));
7677 g1->combined_with++;
7678 g1->lifetime += g2->lifetime;
7680 g1_add_benefit += g2->benefit;
7682 /* ??? The new final_[bg]iv_value code does a much better job
7683 of finding replaceable giv's, and hence this code may no
7684 longer be necessary. */
7685 if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
7686 g1_add_benefit -= copy_cost;
7688 /* To help optimize the next set of combinations, remove
7689 this giv from the benefits of other potential mates. */
7690 for (l = 0; l < giv_count; ++l)
7692 int m = stats[l].giv_number;
7693 if (can_combine[m * giv_count + j])
7694 stats[l].total_benefit -= g2->benefit + extra_benefit;
7697 if (loop_dump_stream)
7698 fprintf (loop_dump_stream,
7699 "giv at %d combined with giv at %d; new benefit %d + %d, lifetime %d\n",
7700 INSN_UID (g2->insn), INSN_UID (g1->insn),
7701 g1->benefit, g1_add_benefit, g1->lifetime);
7705 /* To help optimize the next set of combinations, remove
7706 this giv from the benefits of other potential mates. */
7707 if (g1->combined_with)
7709 for (j = 0; j < giv_count; ++j)
7711 int m = stats[j].giv_number;
7712 if (can_combine[m * giv_count + i])
7713 stats[j].total_benefit -= g1->benefit + extra_benefit;
7716 g1->benefit += g1_add_benefit;
7718 /* We've finished with this giv, and everything it touched.
7719 Restart the combination so that proper weights for the
7720 rest of the givs are properly taken into account. */
7721 /* ??? Ideally we would compact the arrays at this point, so
7722 as to not cover old ground. But sanely compacting
7723 can_combine is tricky. */
7724 goto restart;
7728 /* Clean up. */
7729 free (stats);
7730 free (can_combine);
7733 /* Generate sequence for REG = B * M + A. B is the initial value of
7734 the basic induction variable, M a multiplicative constant, A an
7735 additive constant and REG the destination register. */
7737 static rtx
7738 gen_add_mult (rtx b, rtx m, rtx a, rtx reg)
7740 rtx seq;
7741 rtx result;
7743 start_sequence ();
7744 /* Use unsigned arithmetic. */
7745 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
7746 if (reg != result)
7747 emit_move_insn (reg, result);
7748 seq = get_insns ();
7749 end_sequence ();
7751 return seq;
7755 /* Update registers created in insn sequence SEQ. */
7757 static void
7758 loop_regs_update (const struct loop *loop ATTRIBUTE_UNUSED, rtx seq)
7760 rtx insn;
7762 /* Update register info for alias analysis. */
7764 insn = seq;
7765 while (insn != NULL_RTX)
7767 rtx set = single_set (insn);
7769 if (set && REG_P (SET_DEST (set)))
7770 record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
7772 insn = NEXT_INSN (insn);
7777 /* EMIT code before BEFORE_BB/BEFORE_INSN to set REG = B * M + A. B
7778 is the initial value of the basic induction variable, M a
7779 multiplicative constant, A an additive constant and REG the
7780 destination register. */
7782 void
7783 loop_iv_add_mult_emit_before (const struct loop *loop, rtx b, rtx m, rtx a,
7784 rtx reg, basic_block before_bb, rtx before_insn)
7786 rtx seq;
7788 if (! before_insn)
7790 loop_iv_add_mult_hoist (loop, b, m, a, reg);
7791 return;
7794 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7795 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7797 /* Increase the lifetime of any invariants moved further in code. */
7798 update_reg_last_use (a, before_insn);
7799 update_reg_last_use (b, before_insn);
7800 update_reg_last_use (m, before_insn);
7802 /* It is possible that the expansion created lots of new registers.
7803 Iterate over the sequence we just created and record them all. We
7804 must do this before inserting the sequence. */
7805 loop_regs_update (loop, seq);
7807 loop_insn_emit_before (loop, before_bb, before_insn, seq);
7811 /* Emit insns in loop pre-header to set REG = B * M + A. B is the
7812 initial value of the basic induction variable, M a multiplicative
7813 constant, A an additive constant and REG the destination
7814 register. */
7816 void
7817 loop_iv_add_mult_sink (const struct loop *loop, rtx b, rtx m, rtx a, rtx reg)
7819 rtx seq;
7821 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7822 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7824 /* Increase the lifetime of any invariants moved further in code.
7825 ???? Is this really necessary? */
7826 update_reg_last_use (a, loop->sink);
7827 update_reg_last_use (b, loop->sink);
7828 update_reg_last_use (m, loop->sink);
7830 /* It is possible that the expansion created lots of new registers.
7831 Iterate over the sequence we just created and record them all. We
7832 must do this before inserting the sequence. */
7833 loop_regs_update (loop, seq);
7835 loop_insn_sink (loop, seq);
7839 /* Emit insns after loop to set REG = B * M + A. B is the initial
7840 value of the basic induction variable, M a multiplicative constant,
7841 A an additive constant and REG the destination register. */
7843 void
7844 loop_iv_add_mult_hoist (const struct loop *loop, rtx b, rtx m, rtx a, rtx reg)
7846 rtx seq;
7848 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7849 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7851 /* It is possible that the expansion created lots of new registers.
7852 Iterate over the sequence we just created and record them all. We
7853 must do this before inserting the sequence. */
7854 loop_regs_update (loop, seq);
7856 loop_insn_hoist (loop, seq);
7861 /* Similar to gen_add_mult, but compute cost rather than generating
7862 sequence. */
7864 static int
7865 iv_add_mult_cost (rtx b, rtx m, rtx a, rtx reg)
7867 int cost = 0;
7868 rtx last, result;
7870 start_sequence ();
7871 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
7872 if (reg != result)
7873 emit_move_insn (reg, result);
7874 last = get_last_insn ();
7875 while (last)
7877 rtx t = single_set (last);
7878 if (t)
7879 cost += rtx_cost (SET_SRC (t), SET);
7880 last = PREV_INSN (last);
7882 end_sequence ();
7883 return cost;
7886 /* Test whether A * B can be computed without
7887 an actual multiply insn. Value is 1 if so.
7889 ??? This function stinks because it generates a ton of wasted RTL
7890 ??? and as a result fragments GC memory to no end. There are other
7891 ??? places in the compiler which are invoked a lot and do the same
7892 ??? thing, generate wasted RTL just to see if something is possible. */
7894 static int
7895 product_cheap_p (rtx a, rtx b)
7897 rtx tmp;
7898 int win, n_insns;
7900 /* If only one is constant, make it B. */
7901 if (GET_CODE (a) == CONST_INT)
7902 tmp = a, a = b, b = tmp;
7904 /* If first constant, both constant, so don't need multiply. */
7905 if (GET_CODE (a) == CONST_INT)
7906 return 1;
7908 /* If second not constant, neither is constant, so would need multiply. */
7909 if (GET_CODE (b) != CONST_INT)
7910 return 0;
7912 /* One operand is constant, so might not need multiply insn. Generate the
7913 code for the multiply and see if a call or multiply, or long sequence
7914 of insns is generated. */
7916 start_sequence ();
7917 expand_mult (GET_MODE (a), a, b, NULL_RTX, 1);
7918 tmp = get_insns ();
7919 end_sequence ();
7921 win = 1;
7922 if (INSN_P (tmp))
7924 n_insns = 0;
7925 while (tmp != NULL_RTX)
7927 rtx next = NEXT_INSN (tmp);
7929 if (++n_insns > 3
7930 || !NONJUMP_INSN_P (tmp)
7931 || (GET_CODE (PATTERN (tmp)) == SET
7932 && GET_CODE (SET_SRC (PATTERN (tmp))) == MULT)
7933 || (GET_CODE (PATTERN (tmp)) == PARALLEL
7934 && GET_CODE (XVECEXP (PATTERN (tmp), 0, 0)) == SET
7935 && GET_CODE (SET_SRC (XVECEXP (PATTERN (tmp), 0, 0))) == MULT))
7937 win = 0;
7938 break;
7941 tmp = next;
7944 else if (GET_CODE (tmp) == SET
7945 && GET_CODE (SET_SRC (tmp)) == MULT)
7946 win = 0;
7947 else if (GET_CODE (tmp) == PARALLEL
7948 && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
7949 && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
7950 win = 0;
7952 return win;
7955 /* Check to see if loop can be terminated by a "decrement and branch until
7956 zero" instruction. If so, add a REG_NONNEG note to the branch insn if so.
7957 Also try reversing an increment loop to a decrement loop
7958 to see if the optimization can be performed.
7959 Value is nonzero if optimization was performed. */
7961 /* This is useful even if the architecture doesn't have such an insn,
7962 because it might change a loops which increments from 0 to n to a loop
7963 which decrements from n to 0. A loop that decrements to zero is usually
7964 faster than one that increments from zero. */
7966 /* ??? This could be rewritten to use some of the loop unrolling procedures,
7967 such as approx_final_value, biv_total_increment, loop_iterations, and
7968 final_[bg]iv_value. */
7970 static int
7971 check_dbra_loop (struct loop *loop, int insn_count)
7973 struct loop_info *loop_info = LOOP_INFO (loop);
7974 struct loop_regs *regs = LOOP_REGS (loop);
7975 struct loop_ivs *ivs = LOOP_IVS (loop);
7976 struct iv_class *bl;
7977 rtx reg;
7978 enum machine_mode mode;
7979 rtx jump_label;
7980 rtx final_value;
7981 rtx start_value;
7982 rtx new_add_val;
7983 rtx comparison;
7984 rtx before_comparison;
7985 rtx p;
7986 rtx jump;
7987 rtx first_compare;
7988 int compare_and_branch;
7989 rtx loop_start = loop->start;
7990 rtx loop_end = loop->end;
7992 /* If last insn is a conditional branch, and the insn before tests a
7993 register value, try to optimize it. Otherwise, we can't do anything. */
7995 jump = PREV_INSN (loop_end);
7996 comparison = get_condition_for_loop (loop, jump);
7997 if (comparison == 0)
7998 return 0;
7999 if (!onlyjump_p (jump))
8000 return 0;
8002 /* Try to compute whether the compare/branch at the loop end is one or
8003 two instructions. */
8004 get_condition (jump, &first_compare, false, true);
8005 if (first_compare == jump)
8006 compare_and_branch = 1;
8007 else if (first_compare == prev_nonnote_insn (jump))
8008 compare_and_branch = 2;
8009 else
8010 return 0;
8013 /* If more than one condition is present to control the loop, then
8014 do not proceed, as this function does not know how to rewrite
8015 loop tests with more than one condition.
8017 Look backwards from the first insn in the last comparison
8018 sequence and see if we've got another comparison sequence. */
8020 rtx jump1;
8021 if ((jump1 = prev_nonnote_insn (first_compare)) != loop->cont)
8022 if (JUMP_P (jump1))
8023 return 0;
8026 /* Check all of the bivs to see if the compare uses one of them.
8027 Skip biv's set more than once because we can't guarantee that
8028 it will be zero on the last iteration. Also skip if the biv is
8029 used between its update and the test insn. */
8031 for (bl = ivs->list; bl; bl = bl->next)
8033 if (bl->biv_count == 1
8034 && ! bl->biv->maybe_multiple
8035 && bl->biv->dest_reg == XEXP (comparison, 0)
8036 && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
8037 first_compare))
8038 break;
8041 /* Try swapping the comparison to identify a suitable biv. */
8042 if (!bl)
8043 for (bl = ivs->list; bl; bl = bl->next)
8044 if (bl->biv_count == 1
8045 && ! bl->biv->maybe_multiple
8046 && bl->biv->dest_reg == XEXP (comparison, 1)
8047 && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
8048 first_compare))
8050 comparison = gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)),
8051 VOIDmode,
8052 XEXP (comparison, 1),
8053 XEXP (comparison, 0));
8054 break;
8057 if (! bl)
8058 return 0;
8060 /* Look for the case where the basic induction variable is always
8061 nonnegative, and equals zero on the last iteration.
8062 In this case, add a reg_note REG_NONNEG, which allows the
8063 m68k DBRA instruction to be used. */
8065 if (((GET_CODE (comparison) == GT && XEXP (comparison, 1) == constm1_rtx)
8066 || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
8067 && GET_CODE (bl->biv->add_val) == CONST_INT
8068 && INTVAL (bl->biv->add_val) < 0)
8070 /* Initial value must be greater than 0,
8071 init_val % -dec_value == 0 to ensure that it equals zero on
8072 the last iteration */
8074 if (GET_CODE (bl->initial_value) == CONST_INT
8075 && INTVAL (bl->initial_value) > 0
8076 && (INTVAL (bl->initial_value)
8077 % (-INTVAL (bl->biv->add_val))) == 0)
8079 /* Register always nonnegative, add REG_NOTE to branch. */
8080 if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
8081 REG_NOTES (jump)
8082 = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
8083 REG_NOTES (jump));
8084 bl->nonneg = 1;
8086 return 1;
8089 /* If the decrement is 1 and the value was tested as >= 0 before
8090 the loop, then we can safely optimize. */
8091 for (p = loop_start; p; p = PREV_INSN (p))
8093 if (LABEL_P (p))
8094 break;
8095 if (!JUMP_P (p))
8096 continue;
8098 before_comparison = get_condition_for_loop (loop, p);
8099 if (before_comparison
8100 && XEXP (before_comparison, 0) == bl->biv->dest_reg
8101 && (GET_CODE (before_comparison) == LT
8102 || GET_CODE (before_comparison) == LTU)
8103 && XEXP (before_comparison, 1) == const0_rtx
8104 && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
8105 && INTVAL (bl->biv->add_val) == -1)
8107 if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
8108 REG_NOTES (jump)
8109 = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
8110 REG_NOTES (jump));
8111 bl->nonneg = 1;
8113 return 1;
8117 else if (GET_CODE (bl->biv->add_val) == CONST_INT
8118 && INTVAL (bl->biv->add_val) > 0)
8120 /* Try to change inc to dec, so can apply above optimization. */
8121 /* Can do this if:
8122 all registers modified are induction variables or invariant,
8123 all memory references have non-overlapping addresses
8124 (obviously true if only one write)
8125 allow 2 insns for the compare/jump at the end of the loop. */
8126 /* Also, we must avoid any instructions which use both the reversed
8127 biv and another biv. Such instructions will fail if the loop is
8128 reversed. We meet this condition by requiring that either
8129 no_use_except_counting is true, or else that there is only
8130 one biv. */
8131 int num_nonfixed_reads = 0;
8132 /* 1 if the iteration var is used only to count iterations. */
8133 int no_use_except_counting = 0;
8134 /* 1 if the loop has no memory store, or it has a single memory store
8135 which is reversible. */
8136 int reversible_mem_store = 1;
8138 if (bl->giv_count == 0
8139 && !loop->exit_count
8140 && !loop_info->has_multiple_exit_targets)
8142 rtx bivreg = regno_reg_rtx[bl->regno];
8143 struct iv_class *blt;
8145 /* If there are no givs for this biv, and the only exit is the
8146 fall through at the end of the loop, then
8147 see if perhaps there are no uses except to count. */
8148 no_use_except_counting = 1;
8149 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8150 if (INSN_P (p))
8152 rtx set = single_set (p);
8154 if (set && REG_P (SET_DEST (set))
8155 && REGNO (SET_DEST (set)) == bl->regno)
8156 /* An insn that sets the biv is okay. */
8158 else if (!reg_mentioned_p (bivreg, PATTERN (p)))
8159 /* An insn that doesn't mention the biv is okay. */
8161 else if (p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
8162 || p == prev_nonnote_insn (loop_end))
8164 /* If either of these insns uses the biv and sets a pseudo
8165 that has more than one usage, then the biv has uses
8166 other than counting since it's used to derive a value
8167 that is used more than one time. */
8168 note_stores (PATTERN (p), note_set_pseudo_multiple_uses,
8169 regs);
8170 if (regs->multiple_uses)
8172 no_use_except_counting = 0;
8173 break;
8176 else
8178 no_use_except_counting = 0;
8179 break;
8183 /* A biv has uses besides counting if it is used to set
8184 another biv. */
8185 for (blt = ivs->list; blt; blt = blt->next)
8186 if (blt->init_set
8187 && reg_mentioned_p (bivreg, SET_SRC (blt->init_set)))
8189 no_use_except_counting = 0;
8190 break;
8194 if (no_use_except_counting)
8195 /* No need to worry about MEMs. */
8197 else if (loop_info->num_mem_sets <= 1)
8199 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8200 if (INSN_P (p))
8201 num_nonfixed_reads += count_nonfixed_reads (loop, PATTERN (p));
8203 /* If the loop has a single store, and the destination address is
8204 invariant, then we can't reverse the loop, because this address
8205 might then have the wrong value at loop exit.
8206 This would work if the source was invariant also, however, in that
8207 case, the insn should have been moved out of the loop. */
8209 if (loop_info->num_mem_sets == 1)
8211 struct induction *v;
8213 /* If we could prove that each of the memory locations
8214 written to was different, then we could reverse the
8215 store -- but we don't presently have any way of
8216 knowing that. */
8217 reversible_mem_store = 0;
8219 /* If the store depends on a register that is set after the
8220 store, it depends on the initial value, and is thus not
8221 reversible. */
8222 for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
8224 if (v->giv_type == DEST_REG
8225 && reg_mentioned_p (v->dest_reg,
8226 PATTERN (loop_info->first_loop_store_insn))
8227 && loop_insn_first_p (loop_info->first_loop_store_insn,
8228 v->insn))
8229 reversible_mem_store = 0;
8233 else
8234 return 0;
8236 /* This code only acts for innermost loops. Also it simplifies
8237 the memory address check by only reversing loops with
8238 zero or one memory access.
8239 Two memory accesses could involve parts of the same array,
8240 and that can't be reversed.
8241 If the biv is used only for counting, than we don't need to worry
8242 about all these things. */
8244 if ((num_nonfixed_reads <= 1
8245 && ! loop_info->has_nonconst_call
8246 && ! loop_info->has_prefetch
8247 && ! loop_info->has_volatile
8248 && reversible_mem_store
8249 && (bl->giv_count + bl->biv_count + loop_info->num_mem_sets
8250 + num_unmoved_movables (loop) + compare_and_branch == insn_count)
8251 && (bl == ivs->list && bl->next == 0))
8252 || (no_use_except_counting && ! loop_info->has_prefetch))
8254 rtx tem;
8256 /* Loop can be reversed. */
8257 if (loop_dump_stream)
8258 fprintf (loop_dump_stream, "Can reverse loop\n");
8260 /* Now check other conditions:
8262 The increment must be a constant, as must the initial value,
8263 and the comparison code must be LT.
8265 This test can probably be improved since +/- 1 in the constant
8266 can be obtained by changing LT to LE and vice versa; this is
8267 confusing. */
8269 if (comparison
8270 /* for constants, LE gets turned into LT */
8271 && (GET_CODE (comparison) == LT
8272 || (GET_CODE (comparison) == LE
8273 && no_use_except_counting)
8274 || GET_CODE (comparison) == LTU))
8276 HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
8277 rtx initial_value, comparison_value;
8278 int nonneg = 0;
8279 enum rtx_code cmp_code;
8280 int comparison_const_width;
8281 unsigned HOST_WIDE_INT comparison_sign_mask;
8282 bool keep_first_compare;
8284 add_val = INTVAL (bl->biv->add_val);
8285 comparison_value = XEXP (comparison, 1);
8286 if (GET_MODE (comparison_value) == VOIDmode)
8287 comparison_const_width
8288 = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
8289 else
8290 comparison_const_width
8291 = GET_MODE_BITSIZE (GET_MODE (comparison_value));
8292 if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
8293 comparison_const_width = HOST_BITS_PER_WIDE_INT;
8294 comparison_sign_mask
8295 = (unsigned HOST_WIDE_INT) 1 << (comparison_const_width - 1);
8297 /* If the comparison value is not a loop invariant, then we
8298 can not reverse this loop.
8300 ??? If the insns which initialize the comparison value as
8301 a whole compute an invariant result, then we could move
8302 them out of the loop and proceed with loop reversal. */
8303 if (! loop_invariant_p (loop, comparison_value))
8304 return 0;
8306 if (GET_CODE (comparison_value) == CONST_INT)
8307 comparison_val = INTVAL (comparison_value);
8308 initial_value = bl->initial_value;
8310 /* Normalize the initial value if it is an integer and
8311 has no other use except as a counter. This will allow
8312 a few more loops to be reversed. */
8313 if (no_use_except_counting
8314 && GET_CODE (comparison_value) == CONST_INT
8315 && GET_CODE (initial_value) == CONST_INT)
8317 comparison_val = comparison_val - INTVAL (bl->initial_value);
8318 /* The code below requires comparison_val to be a multiple
8319 of add_val in order to do the loop reversal, so
8320 round up comparison_val to a multiple of add_val.
8321 Since comparison_value is constant, we know that the
8322 current comparison code is LT. */
8323 comparison_val = comparison_val + add_val - 1;
8324 comparison_val
8325 -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
8326 /* We postpone overflow checks for COMPARISON_VAL here;
8327 even if there is an overflow, we might still be able to
8328 reverse the loop, if converting the loop exit test to
8329 NE is possible. */
8330 initial_value = const0_rtx;
8333 /* First check if we can do a vanilla loop reversal. */
8334 if (initial_value == const0_rtx
8335 /* If we have a decrement_and_branch_on_count,
8336 prefer the NE test, since this will allow that
8337 instruction to be generated. Note that we must
8338 use a vanilla loop reversal if the biv is used to
8339 calculate a giv or has a non-counting use. */
8340 #if ! defined (HAVE_decrement_and_branch_until_zero) \
8341 && defined (HAVE_decrement_and_branch_on_count)
8342 && (! (add_val == 1 && loop->vtop
8343 && (bl->biv_count == 0
8344 || no_use_except_counting)))
8345 #endif
8346 && GET_CODE (comparison_value) == CONST_INT
8347 /* Now do postponed overflow checks on COMPARISON_VAL. */
8348 && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
8349 & comparison_sign_mask))
8351 /* Register will always be nonnegative, with value
8352 0 on last iteration */
8353 add_adjust = add_val;
8354 nonneg = 1;
8355 cmp_code = GE;
8357 else if (add_val == 1 && loop->vtop
8358 && (bl->biv_count == 0
8359 || no_use_except_counting))
8361 add_adjust = 0;
8362 cmp_code = NE;
8364 else
8365 return 0;
8367 if (GET_CODE (comparison) == LE)
8368 add_adjust -= add_val;
8370 /* If the initial value is not zero, or if the comparison
8371 value is not an exact multiple of the increment, then we
8372 can not reverse this loop. */
8373 if (initial_value == const0_rtx
8374 && GET_CODE (comparison_value) == CONST_INT)
8376 if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
8377 return 0;
8379 else
8381 if (! no_use_except_counting || add_val != 1)
8382 return 0;
8385 final_value = comparison_value;
8387 /* Reset these in case we normalized the initial value
8388 and comparison value above. */
8389 if (GET_CODE (comparison_value) == CONST_INT
8390 && GET_CODE (initial_value) == CONST_INT)
8392 comparison_value = GEN_INT (comparison_val);
8393 final_value
8394 = GEN_INT (comparison_val + INTVAL (bl->initial_value));
8396 bl->initial_value = initial_value;
8398 /* Save some info needed to produce the new insns. */
8399 reg = bl->biv->dest_reg;
8400 mode = GET_MODE (reg);
8401 jump_label = condjump_label (PREV_INSN (loop_end));
8402 new_add_val = GEN_INT (-INTVAL (bl->biv->add_val));
8404 /* Set start_value; if this is not a CONST_INT, we need
8405 to generate a SUB.
8406 Initialize biv to start_value before loop start.
8407 The old initializing insn will be deleted as a
8408 dead store by flow.c. */
8409 if (initial_value == const0_rtx
8410 && GET_CODE (comparison_value) == CONST_INT)
8412 start_value
8413 = gen_int_mode (comparison_val - add_adjust, mode);
8414 loop_insn_hoist (loop, gen_move_insn (reg, start_value));
8416 else if (GET_CODE (initial_value) == CONST_INT)
8418 rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
8419 rtx add_insn = gen_add3_insn (reg, comparison_value, offset);
8421 if (add_insn == 0)
8422 return 0;
8424 start_value
8425 = gen_rtx_PLUS (mode, comparison_value, offset);
8426 loop_insn_hoist (loop, add_insn);
8427 if (GET_CODE (comparison) == LE)
8428 final_value = gen_rtx_PLUS (mode, comparison_value,
8429 GEN_INT (add_val));
8431 else if (! add_adjust)
8433 rtx sub_insn = gen_sub3_insn (reg, comparison_value,
8434 initial_value);
8436 if (sub_insn == 0)
8437 return 0;
8438 start_value
8439 = gen_rtx_MINUS (mode, comparison_value, initial_value);
8440 loop_insn_hoist (loop, sub_insn);
8442 else
8443 /* We could handle the other cases too, but it'll be
8444 better to have a testcase first. */
8445 return 0;
8447 /* We may not have a single insn which can increment a reg, so
8448 create a sequence to hold all the insns from expand_inc. */
8449 start_sequence ();
8450 expand_inc (reg, new_add_val);
8451 tem = get_insns ();
8452 end_sequence ();
8454 p = loop_insn_emit_before (loop, 0, bl->biv->insn, tem);
8455 delete_insn (bl->biv->insn);
8457 /* Update biv info to reflect its new status. */
8458 bl->biv->insn = p;
8459 bl->initial_value = start_value;
8460 bl->biv->add_val = new_add_val;
8462 /* Update loop info. */
8463 loop_info->initial_value = reg;
8464 loop_info->initial_equiv_value = reg;
8465 loop_info->final_value = const0_rtx;
8466 loop_info->final_equiv_value = const0_rtx;
8467 loop_info->comparison_value = const0_rtx;
8468 loop_info->comparison_code = cmp_code;
8469 loop_info->increment = new_add_val;
8471 /* Inc LABEL_NUSES so that delete_insn will
8472 not delete the label. */
8473 LABEL_NUSES (XEXP (jump_label, 0))++;
8475 /* If we have a separate comparison insn that does more
8476 than just set cc0, the result of the comparison might
8477 be used outside the loop. */
8478 keep_first_compare = (compare_and_branch == 2
8479 #ifdef HAVE_CC0
8480 && sets_cc0_p (first_compare) <= 0
8481 #endif
8484 /* Emit an insn after the end of the loop to set the biv's
8485 proper exit value if it is used anywhere outside the loop. */
8486 if (keep_first_compare
8487 || (REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
8488 || ! bl->init_insn
8489 || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
8490 loop_insn_sink (loop, gen_load_of_final_value (reg, final_value));
8492 if (keep_first_compare)
8493 loop_insn_sink (loop, PATTERN (first_compare));
8495 /* Delete compare/branch at end of loop. */
8496 delete_related_insns (PREV_INSN (loop_end));
8497 if (compare_and_branch == 2)
8498 delete_related_insns (first_compare);
8500 /* Add new compare/branch insn at end of loop. */
8501 start_sequence ();
8502 emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
8503 mode, 0,
8504 XEXP (jump_label, 0));
8505 tem = get_insns ();
8506 end_sequence ();
8507 emit_jump_insn_before (tem, loop_end);
8509 for (tem = PREV_INSN (loop_end);
8510 tem && !JUMP_P (tem);
8511 tem = PREV_INSN (tem))
8514 if (tem)
8515 JUMP_LABEL (tem) = XEXP (jump_label, 0);
8517 if (nonneg)
8519 if (tem)
8521 /* Increment of LABEL_NUSES done above. */
8522 /* Register is now always nonnegative,
8523 so add REG_NONNEG note to the branch. */
8524 REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, reg,
8525 REG_NOTES (tem));
8527 bl->nonneg = 1;
8530 /* No insn may reference both the reversed and another biv or it
8531 will fail (see comment near the top of the loop reversal
8532 code).
8533 Earlier on, we have verified that the biv has no use except
8534 counting, or it is the only biv in this function.
8535 However, the code that computes no_use_except_counting does
8536 not verify reg notes. It's possible to have an insn that
8537 references another biv, and has a REG_EQUAL note with an
8538 expression based on the reversed biv. To avoid this case,
8539 remove all REG_EQUAL notes based on the reversed biv
8540 here. */
8541 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8542 if (INSN_P (p))
8544 rtx *pnote;
8545 rtx set = single_set (p);
8546 /* If this is a set of a GIV based on the reversed biv, any
8547 REG_EQUAL notes should still be correct. */
8548 if (! set
8549 || !REG_P (SET_DEST (set))
8550 || (size_t) REGNO (SET_DEST (set)) >= ivs->n_regs
8551 || REG_IV_TYPE (ivs, REGNO (SET_DEST (set))) != GENERAL_INDUCT
8552 || REG_IV_INFO (ivs, REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
8553 for (pnote = &REG_NOTES (p); *pnote;)
8555 if (REG_NOTE_KIND (*pnote) == REG_EQUAL
8556 && reg_mentioned_p (regno_reg_rtx[bl->regno],
8557 XEXP (*pnote, 0)))
8558 *pnote = XEXP (*pnote, 1);
8559 else
8560 pnote = &XEXP (*pnote, 1);
8564 /* Mark that this biv has been reversed. Each giv which depends
8565 on this biv, and which is also live past the end of the loop
8566 will have to be fixed up. */
8568 bl->reversed = 1;
8570 if (loop_dump_stream)
8572 fprintf (loop_dump_stream, "Reversed loop");
8573 if (bl->nonneg)
8574 fprintf (loop_dump_stream, " and added reg_nonneg\n");
8575 else
8576 fprintf (loop_dump_stream, "\n");
8579 return 1;
8584 return 0;
8587 /* Verify whether the biv BL appears to be eliminable,
8588 based on the insns in the loop that refer to it.
8590 If ELIMINATE_P is nonzero, actually do the elimination.
8592 THRESHOLD and INSN_COUNT are from loop_optimize and are used to
8593 determine whether invariant insns should be placed inside or at the
8594 start of the loop. */
8596 static int
8597 maybe_eliminate_biv (const struct loop *loop, struct iv_class *bl,
8598 int eliminate_p, int threshold, int insn_count)
8600 struct loop_ivs *ivs = LOOP_IVS (loop);
8601 rtx reg = bl->biv->dest_reg;
8602 rtx p;
8604 /* Scan all insns in the loop, stopping if we find one that uses the
8605 biv in a way that we cannot eliminate. */
8607 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
8609 enum rtx_code code = GET_CODE (p);
8610 basic_block where_bb = 0;
8611 rtx where_insn = threshold >= insn_count ? 0 : p;
8612 rtx note;
8614 /* If this is a libcall that sets a giv, skip ahead to its end. */
8615 if (INSN_P (p))
8617 note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
8619 if (note)
8621 rtx last = XEXP (note, 0);
8622 rtx set = single_set (last);
8624 if (set && REG_P (SET_DEST (set)))
8626 unsigned int regno = REGNO (SET_DEST (set));
8628 if (regno < ivs->n_regs
8629 && REG_IV_TYPE (ivs, regno) == GENERAL_INDUCT
8630 && REG_IV_INFO (ivs, regno)->src_reg == bl->biv->src_reg)
8631 p = last;
8636 /* Closely examine the insn if the biv is mentioned. */
8637 if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
8638 && reg_mentioned_p (reg, PATTERN (p))
8639 && ! maybe_eliminate_biv_1 (loop, PATTERN (p), p, bl,
8640 eliminate_p, where_bb, where_insn))
8642 if (loop_dump_stream)
8643 fprintf (loop_dump_stream,
8644 "Cannot eliminate biv %d: biv used in insn %d.\n",
8645 bl->regno, INSN_UID (p));
8646 break;
8649 /* If we are eliminating, kill REG_EQUAL notes mentioning the biv. */
8650 if (eliminate_p
8651 && (note = find_reg_note (p, REG_EQUAL, NULL_RTX)) != NULL_RTX
8652 && reg_mentioned_p (reg, XEXP (note, 0)))
8653 remove_note (p, note);
8656 if (p == loop->end)
8658 if (loop_dump_stream)
8659 fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
8660 bl->regno, eliminate_p ? "was" : "can be");
8661 return 1;
8664 return 0;
8667 /* INSN and REFERENCE are instructions in the same insn chain.
8668 Return nonzero if INSN is first. */
8671 loop_insn_first_p (rtx insn, rtx reference)
8673 rtx p, q;
8675 for (p = insn, q = reference;;)
8677 /* Start with test for not first so that INSN == REFERENCE yields not
8678 first. */
8679 if (q == insn || ! p)
8680 return 0;
8681 if (p == reference || ! q)
8682 return 1;
8684 /* Either of P or Q might be a NOTE. Notes have the same LUID as the
8685 previous insn, hence the <= comparison below does not work if
8686 P is a note. */
8687 if (INSN_UID (p) < max_uid_for_loop
8688 && INSN_UID (q) < max_uid_for_loop
8689 && !NOTE_P (p))
8690 return INSN_LUID (p) <= INSN_LUID (q);
8692 if (INSN_UID (p) >= max_uid_for_loop
8693 || NOTE_P (p))
8694 p = NEXT_INSN (p);
8695 if (INSN_UID (q) >= max_uid_for_loop)
8696 q = NEXT_INSN (q);
8700 /* We are trying to eliminate BIV in INSN using GIV. Return nonzero if
8701 the offset that we have to take into account due to auto-increment /
8702 div derivation is zero. */
8703 static int
8704 biv_elimination_giv_has_0_offset (struct induction *biv,
8705 struct induction *giv, rtx insn)
8707 /* If the giv V had the auto-inc address optimization applied
8708 to it, and INSN occurs between the giv insn and the biv
8709 insn, then we'd have to adjust the value used here.
8710 This is rare, so we don't bother to make this possible. */
8711 if (giv->auto_inc_opt
8712 && ((loop_insn_first_p (giv->insn, insn)
8713 && loop_insn_first_p (insn, biv->insn))
8714 || (loop_insn_first_p (biv->insn, insn)
8715 && loop_insn_first_p (insn, giv->insn))))
8716 return 0;
8718 return 1;
8721 /* If BL appears in X (part of the pattern of INSN), see if we can
8722 eliminate its use. If so, return 1. If not, return 0.
8724 If BIV does not appear in X, return 1.
8726 If ELIMINATE_P is nonzero, actually do the elimination.
8727 WHERE_INSN/WHERE_BB indicate where extra insns should be added.
8728 Depending on how many items have been moved out of the loop, it
8729 will either be before INSN (when WHERE_INSN is nonzero) or at the
8730 start of the loop (when WHERE_INSN is zero). */
8732 static int
8733 maybe_eliminate_biv_1 (const struct loop *loop, rtx x, rtx insn,
8734 struct iv_class *bl, int eliminate_p,
8735 basic_block where_bb, rtx where_insn)
8737 enum rtx_code code = GET_CODE (x);
8738 rtx reg = bl->biv->dest_reg;
8739 enum machine_mode mode = GET_MODE (reg);
8740 struct induction *v;
8741 rtx arg, tem;
8742 #ifdef HAVE_cc0
8743 rtx new;
8744 #endif
8745 int arg_operand;
8746 const char *fmt;
8747 int i, j;
8749 switch (code)
8751 case REG:
8752 /* If we haven't already been able to do something with this BIV,
8753 we can't eliminate it. */
8754 if (x == reg)
8755 return 0;
8756 return 1;
8758 case SET:
8759 /* If this sets the BIV, it is not a problem. */
8760 if (SET_DEST (x) == reg)
8761 return 1;
8763 /* If this is an insn that defines a giv, it is also ok because
8764 it will go away when the giv is reduced. */
8765 for (v = bl->giv; v; v = v->next_iv)
8766 if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
8767 return 1;
8769 #ifdef HAVE_cc0
8770 if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
8772 /* Can replace with any giv that was reduced and
8773 that has (MULT_VAL != 0) and (ADD_VAL == 0).
8774 Require a constant for MULT_VAL, so we know it's nonzero.
8775 ??? We disable this optimization to avoid potential
8776 overflows. */
8778 for (v = bl->giv; v; v = v->next_iv)
8779 if (GET_CODE (v->mult_val) == CONST_INT && v->mult_val != const0_rtx
8780 && v->add_val == const0_rtx
8781 && ! v->ignore && ! v->maybe_dead && v->always_computable
8782 && v->mode == mode
8783 && 0)
8785 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8786 continue;
8788 if (! eliminate_p)
8789 return 1;
8791 /* If the giv has the opposite direction of change,
8792 then reverse the comparison. */
8793 if (INTVAL (v->mult_val) < 0)
8794 new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
8795 const0_rtx, v->new_reg);
8796 else
8797 new = v->new_reg;
8799 /* We can probably test that giv's reduced reg. */
8800 if (validate_change (insn, &SET_SRC (x), new, 0))
8801 return 1;
8804 /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
8805 replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
8806 Require a constant for MULT_VAL, so we know it's nonzero.
8807 ??? Do this only if ADD_VAL is a pointer to avoid a potential
8808 overflow problem. */
8810 for (v = bl->giv; v; v = v->next_iv)
8811 if (GET_CODE (v->mult_val) == CONST_INT
8812 && v->mult_val != const0_rtx
8813 && ! v->ignore && ! v->maybe_dead && v->always_computable
8814 && v->mode == mode
8815 && (GET_CODE (v->add_val) == SYMBOL_REF
8816 || GET_CODE (v->add_val) == LABEL_REF
8817 || GET_CODE (v->add_val) == CONST
8818 || (REG_P (v->add_val)
8819 && REG_POINTER (v->add_val))))
8821 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8822 continue;
8824 if (! eliminate_p)
8825 return 1;
8827 /* If the giv has the opposite direction of change,
8828 then reverse the comparison. */
8829 if (INTVAL (v->mult_val) < 0)
8830 new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
8831 v->new_reg);
8832 else
8833 new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
8834 copy_rtx (v->add_val));
8836 /* Replace biv with the giv's reduced register. */
8837 update_reg_last_use (v->add_val, insn);
8838 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8839 return 1;
8841 /* Insn doesn't support that constant or invariant. Copy it
8842 into a register (it will be a loop invariant.) */
8843 tem = gen_reg_rtx (GET_MODE (v->new_reg));
8845 loop_insn_emit_before (loop, 0, where_insn,
8846 gen_move_insn (tem,
8847 copy_rtx (v->add_val)));
8849 /* Substitute the new register for its invariant value in
8850 the compare expression. */
8851 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
8852 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8853 return 1;
8856 #endif
8857 break;
8859 case COMPARE:
8860 case EQ: case NE:
8861 case GT: case GE: case GTU: case GEU:
8862 case LT: case LE: case LTU: case LEU:
8863 /* See if either argument is the biv. */
8864 if (XEXP (x, 0) == reg)
8865 arg = XEXP (x, 1), arg_operand = 1;
8866 else if (XEXP (x, 1) == reg)
8867 arg = XEXP (x, 0), arg_operand = 0;
8868 else
8869 break;
8871 if (CONSTANT_P (arg))
8873 /* First try to replace with any giv that has constant positive
8874 mult_val and constant add_val. We might be able to support
8875 negative mult_val, but it seems complex to do it in general. */
8877 for (v = bl->giv; v; v = v->next_iv)
8878 if (GET_CODE (v->mult_val) == CONST_INT
8879 && INTVAL (v->mult_val) > 0
8880 && (GET_CODE (v->add_val) == SYMBOL_REF
8881 || GET_CODE (v->add_val) == LABEL_REF
8882 || GET_CODE (v->add_val) == CONST
8883 || (REG_P (v->add_val)
8884 && REG_POINTER (v->add_val)))
8885 && ! v->ignore && ! v->maybe_dead && v->always_computable
8886 && v->mode == mode)
8888 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8889 continue;
8891 /* Don't eliminate if the linear combination that makes up
8892 the giv overflows when it is applied to ARG. */
8893 if (GET_CODE (arg) == CONST_INT)
8895 rtx add_val;
8897 if (GET_CODE (v->add_val) == CONST_INT)
8898 add_val = v->add_val;
8899 else
8900 add_val = const0_rtx;
8902 if (const_mult_add_overflow_p (arg, v->mult_val,
8903 add_val, mode, 1))
8904 continue;
8907 if (! eliminate_p)
8908 return 1;
8910 /* Replace biv with the giv's reduced reg. */
8911 validate_change (insn, &XEXP (x, 1 - arg_operand), v->new_reg, 1);
8913 /* If all constants are actually constant integers and
8914 the derived constant can be directly placed in the COMPARE,
8915 do so. */
8916 if (GET_CODE (arg) == CONST_INT
8917 && GET_CODE (v->add_val) == CONST_INT)
8919 tem = expand_mult_add (arg, NULL_RTX, v->mult_val,
8920 v->add_val, mode, 1);
8922 else
8924 /* Otherwise, load it into a register. */
8925 tem = gen_reg_rtx (mode);
8926 loop_iv_add_mult_emit_before (loop, arg,
8927 v->mult_val, v->add_val,
8928 tem, where_bb, where_insn);
8931 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8933 if (apply_change_group ())
8934 return 1;
8937 /* Look for giv with positive constant mult_val and nonconst add_val.
8938 Insert insns to calculate new compare value.
8939 ??? Turn this off due to possible overflow. */
8941 for (v = bl->giv; v; v = v->next_iv)
8942 if (GET_CODE (v->mult_val) == CONST_INT
8943 && INTVAL (v->mult_val) > 0
8944 && ! v->ignore && ! v->maybe_dead && v->always_computable
8945 && v->mode == mode
8946 && 0)
8948 rtx tem;
8950 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8951 continue;
8953 if (! eliminate_p)
8954 return 1;
8956 tem = gen_reg_rtx (mode);
8958 /* Replace biv with giv's reduced register. */
8959 validate_change (insn, &XEXP (x, 1 - arg_operand),
8960 v->new_reg, 1);
8962 /* Compute value to compare against. */
8963 loop_iv_add_mult_emit_before (loop, arg,
8964 v->mult_val, v->add_val,
8965 tem, where_bb, where_insn);
8966 /* Use it in this insn. */
8967 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8968 if (apply_change_group ())
8969 return 1;
8972 else if (REG_P (arg) || MEM_P (arg))
8974 if (loop_invariant_p (loop, arg) == 1)
8976 /* Look for giv with constant positive mult_val and nonconst
8977 add_val. Insert insns to compute new compare value.
8978 ??? Turn this off due to possible overflow. */
8980 for (v = bl->giv; v; v = v->next_iv)
8981 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
8982 && ! v->ignore && ! v->maybe_dead && v->always_computable
8983 && v->mode == mode
8984 && 0)
8986 rtx tem;
8988 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8989 continue;
8991 if (! eliminate_p)
8992 return 1;
8994 tem = gen_reg_rtx (mode);
8996 /* Replace biv with giv's reduced register. */
8997 validate_change (insn, &XEXP (x, 1 - arg_operand),
8998 v->new_reg, 1);
9000 /* Compute value to compare against. */
9001 loop_iv_add_mult_emit_before (loop, arg,
9002 v->mult_val, v->add_val,
9003 tem, where_bb, where_insn);
9004 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9005 if (apply_change_group ())
9006 return 1;
9010 /* This code has problems. Basically, you can't know when
9011 seeing if we will eliminate BL, whether a particular giv
9012 of ARG will be reduced. If it isn't going to be reduced,
9013 we can't eliminate BL. We can try forcing it to be reduced,
9014 but that can generate poor code.
9016 The problem is that the benefit of reducing TV, below should
9017 be increased if BL can actually be eliminated, but this means
9018 we might have to do a topological sort of the order in which
9019 we try to process biv. It doesn't seem worthwhile to do
9020 this sort of thing now. */
9022 #if 0
9023 /* Otherwise the reg compared with had better be a biv. */
9024 if (!REG_P (arg)
9025 || REG_IV_TYPE (ivs, REGNO (arg)) != BASIC_INDUCT)
9026 return 0;
9028 /* Look for a pair of givs, one for each biv,
9029 with identical coefficients. */
9030 for (v = bl->giv; v; v = v->next_iv)
9032 struct induction *tv;
9034 if (v->ignore || v->maybe_dead || v->mode != mode)
9035 continue;
9037 for (tv = REG_IV_CLASS (ivs, REGNO (arg))->giv; tv;
9038 tv = tv->next_iv)
9039 if (! tv->ignore && ! tv->maybe_dead
9040 && rtx_equal_p (tv->mult_val, v->mult_val)
9041 && rtx_equal_p (tv->add_val, v->add_val)
9042 && tv->mode == mode)
9044 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9045 continue;
9047 if (! eliminate_p)
9048 return 1;
9050 /* Replace biv with its giv's reduced reg. */
9051 XEXP (x, 1 - arg_operand) = v->new_reg;
9052 /* Replace other operand with the other giv's
9053 reduced reg. */
9054 XEXP (x, arg_operand) = tv->new_reg;
9055 return 1;
9058 #endif
9061 /* If we get here, the biv can't be eliminated. */
9062 return 0;
9064 case MEM:
9065 /* If this address is a DEST_ADDR giv, it doesn't matter if the
9066 biv is used in it, since it will be replaced. */
9067 for (v = bl->giv; v; v = v->next_iv)
9068 if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
9069 return 1;
9070 break;
9072 default:
9073 break;
9076 /* See if any subexpression fails elimination. */
9077 fmt = GET_RTX_FORMAT (code);
9078 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
9080 switch (fmt[i])
9082 case 'e':
9083 if (! maybe_eliminate_biv_1 (loop, XEXP (x, i), insn, bl,
9084 eliminate_p, where_bb, where_insn))
9085 return 0;
9086 break;
9088 case 'E':
9089 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9090 if (! maybe_eliminate_biv_1 (loop, XVECEXP (x, i, j), insn, bl,
9091 eliminate_p, where_bb, where_insn))
9092 return 0;
9093 break;
9097 return 1;
9100 /* Return nonzero if the last use of REG
9101 is in an insn following INSN in the same basic block. */
9103 static int
9104 last_use_this_basic_block (rtx reg, rtx insn)
9106 rtx n;
9107 for (n = insn;
9108 n && !LABEL_P (n) && !JUMP_P (n);
9109 n = NEXT_INSN (n))
9111 if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
9112 return 1;
9114 return 0;
9117 /* Called via `note_stores' to record the initial value of a biv. Here we
9118 just record the location of the set and process it later. */
9120 static void
9121 record_initial (rtx dest, rtx set, void *data ATTRIBUTE_UNUSED)
9123 struct loop_ivs *ivs = (struct loop_ivs *) data;
9124 struct iv_class *bl;
9126 if (!REG_P (dest)
9127 || REGNO (dest) >= ivs->n_regs
9128 || REG_IV_TYPE (ivs, REGNO (dest)) != BASIC_INDUCT)
9129 return;
9131 bl = REG_IV_CLASS (ivs, REGNO (dest));
9133 /* If this is the first set found, record it. */
9134 if (bl->init_insn == 0)
9136 bl->init_insn = note_insn;
9137 bl->init_set = set;
9141 /* If any of the registers in X are "old" and currently have a last use earlier
9142 than INSN, update them to have a last use of INSN. Their actual last use
9143 will be the previous insn but it will not have a valid uid_luid so we can't
9144 use it. X must be a source expression only. */
9146 static void
9147 update_reg_last_use (rtx x, rtx insn)
9149 /* Check for the case where INSN does not have a valid luid. In this case,
9150 there is no need to modify the regno_last_uid, as this can only happen
9151 when code is inserted after the loop_end to set a pseudo's final value,
9152 and hence this insn will never be the last use of x.
9153 ???? This comment is not correct. See for example loop_givs_reduce.
9154 This may insert an insn before another new insn. */
9155 if (REG_P (x) && REGNO (x) < max_reg_before_loop
9156 && INSN_UID (insn) < max_uid_for_loop
9157 && REGNO_LAST_LUID (REGNO (x)) < INSN_LUID (insn))
9159 REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
9161 else
9163 int i, j;
9164 const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
9165 for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
9167 if (fmt[i] == 'e')
9168 update_reg_last_use (XEXP (x, i), insn);
9169 else if (fmt[i] == 'E')
9170 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9171 update_reg_last_use (XVECEXP (x, i, j), insn);
9176 /* Given an insn INSN and condition COND, return the condition in a
9177 canonical form to simplify testing by callers. Specifically:
9179 (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
9180 (2) Both operands will be machine operands; (cc0) will have been replaced.
9181 (3) If an operand is a constant, it will be the second operand.
9182 (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
9183 for GE, GEU, and LEU.
9185 If the condition cannot be understood, or is an inequality floating-point
9186 comparison which needs to be reversed, 0 will be returned.
9188 If REVERSE is nonzero, then reverse the condition prior to canonizing it.
9190 If EARLIEST is nonzero, it is a pointer to a place where the earliest
9191 insn used in locating the condition was found. If a replacement test
9192 of the condition is desired, it should be placed in front of that
9193 insn and we will be sure that the inputs are still valid.
9195 If WANT_REG is nonzero, we wish the condition to be relative to that
9196 register, if possible. Therefore, do not canonicalize the condition
9197 further. If ALLOW_CC_MODE is nonzero, allow the condition returned
9198 to be a compare to a CC mode register.
9200 If VALID_AT_INSN_P, the condition must be valid at both *EARLIEST
9201 and at INSN. */
9204 canonicalize_condition (rtx insn, rtx cond, int reverse, rtx *earliest,
9205 rtx want_reg, int allow_cc_mode, int valid_at_insn_p)
9207 enum rtx_code code;
9208 rtx prev = insn;
9209 rtx set;
9210 rtx tem;
9211 rtx op0, op1;
9212 int reverse_code = 0;
9213 enum machine_mode mode;
9215 code = GET_CODE (cond);
9216 mode = GET_MODE (cond);
9217 op0 = XEXP (cond, 0);
9218 op1 = XEXP (cond, 1);
9220 if (reverse)
9221 code = reversed_comparison_code (cond, insn);
9222 if (code == UNKNOWN)
9223 return 0;
9225 if (earliest)
9226 *earliest = insn;
9228 /* If we are comparing a register with zero, see if the register is set
9229 in the previous insn to a COMPARE or a comparison operation. Perform
9230 the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
9231 in cse.c */
9233 while ((GET_RTX_CLASS (code) == RTX_COMPARE
9234 || GET_RTX_CLASS (code) == RTX_COMM_COMPARE)
9235 && op1 == CONST0_RTX (GET_MODE (op0))
9236 && op0 != want_reg)
9238 /* Set nonzero when we find something of interest. */
9239 rtx x = 0;
9241 #ifdef HAVE_cc0
9242 /* If comparison with cc0, import actual comparison from compare
9243 insn. */
9244 if (op0 == cc0_rtx)
9246 if ((prev = prev_nonnote_insn (prev)) == 0
9247 || !NONJUMP_INSN_P (prev)
9248 || (set = single_set (prev)) == 0
9249 || SET_DEST (set) != cc0_rtx)
9250 return 0;
9252 op0 = SET_SRC (set);
9253 op1 = CONST0_RTX (GET_MODE (op0));
9254 if (earliest)
9255 *earliest = prev;
9257 #endif
9259 /* If this is a COMPARE, pick up the two things being compared. */
9260 if (GET_CODE (op0) == COMPARE)
9262 op1 = XEXP (op0, 1);
9263 op0 = XEXP (op0, 0);
9264 continue;
9266 else if (!REG_P (op0))
9267 break;
9269 /* Go back to the previous insn. Stop if it is not an INSN. We also
9270 stop if it isn't a single set or if it has a REG_INC note because
9271 we don't want to bother dealing with it. */
9273 if ((prev = prev_nonnote_insn (prev)) == 0
9274 || !NONJUMP_INSN_P (prev)
9275 || FIND_REG_INC_NOTE (prev, NULL_RTX))
9276 break;
9278 set = set_of (op0, prev);
9280 if (set
9281 && (GET_CODE (set) != SET
9282 || !rtx_equal_p (SET_DEST (set), op0)))
9283 break;
9285 /* If this is setting OP0, get what it sets it to if it looks
9286 relevant. */
9287 if (set)
9289 enum machine_mode inner_mode = GET_MODE (SET_DEST (set));
9290 #ifdef FLOAT_STORE_FLAG_VALUE
9291 REAL_VALUE_TYPE fsfv;
9292 #endif
9294 /* ??? We may not combine comparisons done in a CCmode with
9295 comparisons not done in a CCmode. This is to aid targets
9296 like Alpha that have an IEEE compliant EQ instruction, and
9297 a non-IEEE compliant BEQ instruction. The use of CCmode is
9298 actually artificial, simply to prevent the combination, but
9299 should not affect other platforms.
9301 However, we must allow VOIDmode comparisons to match either
9302 CCmode or non-CCmode comparison, because some ports have
9303 modeless comparisons inside branch patterns.
9305 ??? This mode check should perhaps look more like the mode check
9306 in simplify_comparison in combine. */
9308 if ((GET_CODE (SET_SRC (set)) == COMPARE
9309 || (((code == NE
9310 || (code == LT
9311 && GET_MODE_CLASS (inner_mode) == MODE_INT
9312 && (GET_MODE_BITSIZE (inner_mode)
9313 <= HOST_BITS_PER_WIDE_INT)
9314 && (STORE_FLAG_VALUE
9315 & ((HOST_WIDE_INT) 1
9316 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9317 #ifdef FLOAT_STORE_FLAG_VALUE
9318 || (code == LT
9319 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9320 && (fsfv = FLOAT_STORE_FLAG_VALUE (inner_mode),
9321 REAL_VALUE_NEGATIVE (fsfv)))
9322 #endif
9324 && COMPARISON_P (SET_SRC (set))))
9325 && (((GET_MODE_CLASS (mode) == MODE_CC)
9326 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9327 || mode == VOIDmode || inner_mode == VOIDmode))
9328 x = SET_SRC (set);
9329 else if (((code == EQ
9330 || (code == GE
9331 && (GET_MODE_BITSIZE (inner_mode)
9332 <= HOST_BITS_PER_WIDE_INT)
9333 && GET_MODE_CLASS (inner_mode) == MODE_INT
9334 && (STORE_FLAG_VALUE
9335 & ((HOST_WIDE_INT) 1
9336 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9337 #ifdef FLOAT_STORE_FLAG_VALUE
9338 || (code == GE
9339 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9340 && (fsfv = FLOAT_STORE_FLAG_VALUE (inner_mode),
9341 REAL_VALUE_NEGATIVE (fsfv)))
9342 #endif
9344 && COMPARISON_P (SET_SRC (set))
9345 && (((GET_MODE_CLASS (mode) == MODE_CC)
9346 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9347 || mode == VOIDmode || inner_mode == VOIDmode))
9350 reverse_code = 1;
9351 x = SET_SRC (set);
9353 else
9354 break;
9357 else if (reg_set_p (op0, prev))
9358 /* If this sets OP0, but not directly, we have to give up. */
9359 break;
9361 if (x)
9363 /* If the caller is expecting the condition to be valid at INSN,
9364 make sure X doesn't change before INSN. */
9365 if (valid_at_insn_p)
9366 if (modified_in_p (x, prev) || modified_between_p (x, prev, insn))
9367 break;
9368 if (COMPARISON_P (x))
9369 code = GET_CODE (x);
9370 if (reverse_code)
9372 code = reversed_comparison_code (x, prev);
9373 if (code == UNKNOWN)
9374 return 0;
9375 reverse_code = 0;
9378 op0 = XEXP (x, 0), op1 = XEXP (x, 1);
9379 if (earliest)
9380 *earliest = prev;
9384 /* If constant is first, put it last. */
9385 if (CONSTANT_P (op0))
9386 code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
9388 /* If OP0 is the result of a comparison, we weren't able to find what
9389 was really being compared, so fail. */
9390 if (!allow_cc_mode
9391 && GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
9392 return 0;
9394 /* Canonicalize any ordered comparison with integers involving equality
9395 if we can do computations in the relevant mode and we do not
9396 overflow. */
9398 if (GET_MODE_CLASS (GET_MODE (op0)) != MODE_CC
9399 && GET_CODE (op1) == CONST_INT
9400 && GET_MODE (op0) != VOIDmode
9401 && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
9403 HOST_WIDE_INT const_val = INTVAL (op1);
9404 unsigned HOST_WIDE_INT uconst_val = const_val;
9405 unsigned HOST_WIDE_INT max_val
9406 = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
9408 switch (code)
9410 case LE:
9411 if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
9412 code = LT, op1 = gen_int_mode (const_val + 1, GET_MODE (op0));
9413 break;
9415 /* When cross-compiling, const_val might be sign-extended from
9416 BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
9417 case GE:
9418 if ((HOST_WIDE_INT) (const_val & max_val)
9419 != (((HOST_WIDE_INT) 1
9420 << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
9421 code = GT, op1 = gen_int_mode (const_val - 1, GET_MODE (op0));
9422 break;
9424 case LEU:
9425 if (uconst_val < max_val)
9426 code = LTU, op1 = gen_int_mode (uconst_val + 1, GET_MODE (op0));
9427 break;
9429 case GEU:
9430 if (uconst_val != 0)
9431 code = GTU, op1 = gen_int_mode (uconst_val - 1, GET_MODE (op0));
9432 break;
9434 default:
9435 break;
9439 /* Never return CC0; return zero instead. */
9440 if (CC0_P (op0))
9441 return 0;
9443 return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
9446 /* Given a jump insn JUMP, return the condition that will cause it to branch
9447 to its JUMP_LABEL. If the condition cannot be understood, or is an
9448 inequality floating-point comparison which needs to be reversed, 0 will
9449 be returned.
9451 If EARLIEST is nonzero, it is a pointer to a place where the earliest
9452 insn used in locating the condition was found. If a replacement test
9453 of the condition is desired, it should be placed in front of that
9454 insn and we will be sure that the inputs are still valid. If EARLIEST
9455 is null, the returned condition will be valid at INSN.
9457 If ALLOW_CC_MODE is nonzero, allow the condition returned to be a
9458 compare CC mode register.
9460 VALID_AT_INSN_P is the same as for canonicalize_condition. */
9463 get_condition (rtx jump, rtx *earliest, int allow_cc_mode, int valid_at_insn_p)
9465 rtx cond;
9466 int reverse;
9467 rtx set;
9469 /* If this is not a standard conditional jump, we can't parse it. */
9470 if (!JUMP_P (jump)
9471 || ! any_condjump_p (jump))
9472 return 0;
9473 set = pc_set (jump);
9475 cond = XEXP (SET_SRC (set), 0);
9477 /* If this branches to JUMP_LABEL when the condition is false, reverse
9478 the condition. */
9479 reverse
9480 = GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
9481 && XEXP (XEXP (SET_SRC (set), 2), 0) == JUMP_LABEL (jump);
9483 return canonicalize_condition (jump, cond, reverse, earliest, NULL_RTX,
9484 allow_cc_mode, valid_at_insn_p);
9487 /* Similar to above routine, except that we also put an invariant last
9488 unless both operands are invariants. */
9491 get_condition_for_loop (const struct loop *loop, rtx x)
9493 rtx comparison = get_condition (x, (rtx*) 0, false, true);
9495 if (comparison == 0
9496 || ! loop_invariant_p (loop, XEXP (comparison, 0))
9497 || loop_invariant_p (loop, XEXP (comparison, 1)))
9498 return comparison;
9500 return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
9501 XEXP (comparison, 1), XEXP (comparison, 0));
9504 /* Scan the function and determine whether it has indirect (computed) jumps.
9506 This is taken mostly from flow.c; similar code exists elsewhere
9507 in the compiler. It may be useful to put this into rtlanal.c. */
9508 static int
9509 indirect_jump_in_function_p (rtx start)
9511 rtx insn;
9513 for (insn = start; insn; insn = NEXT_INSN (insn))
9514 if (computed_jump_p (insn))
9515 return 1;
9517 return 0;
9520 /* Add MEM to the LOOP_MEMS array, if appropriate. See the
9521 documentation for LOOP_MEMS for the definition of `appropriate'.
9522 This function is called from prescan_loop via for_each_rtx. */
9524 static int
9525 insert_loop_mem (rtx *mem, void *data ATTRIBUTE_UNUSED)
9527 struct loop_info *loop_info = data;
9528 int i;
9529 rtx m = *mem;
9531 if (m == NULL_RTX)
9532 return 0;
9534 switch (GET_CODE (m))
9536 case MEM:
9537 break;
9539 case CLOBBER:
9540 /* We're not interested in MEMs that are only clobbered. */
9541 return -1;
9543 case CONST_DOUBLE:
9544 /* We're not interested in the MEM associated with a
9545 CONST_DOUBLE, so there's no need to traverse into this. */
9546 return -1;
9548 case EXPR_LIST:
9549 /* We're not interested in any MEMs that only appear in notes. */
9550 return -1;
9552 default:
9553 /* This is not a MEM. */
9554 return 0;
9557 /* See if we've already seen this MEM. */
9558 for (i = 0; i < loop_info->mems_idx; ++i)
9559 if (rtx_equal_p (m, loop_info->mems[i].mem))
9561 if (MEM_VOLATILE_P (m) && !MEM_VOLATILE_P (loop_info->mems[i].mem))
9562 loop_info->mems[i].mem = m;
9563 if (GET_MODE (m) != GET_MODE (loop_info->mems[i].mem))
9564 /* The modes of the two memory accesses are different. If
9565 this happens, something tricky is going on, and we just
9566 don't optimize accesses to this MEM. */
9567 loop_info->mems[i].optimize = 0;
9569 return 0;
9572 /* Resize the array, if necessary. */
9573 if (loop_info->mems_idx == loop_info->mems_allocated)
9575 if (loop_info->mems_allocated != 0)
9576 loop_info->mems_allocated *= 2;
9577 else
9578 loop_info->mems_allocated = 32;
9580 loop_info->mems = xrealloc (loop_info->mems,
9581 loop_info->mems_allocated * sizeof (loop_mem_info));
9584 /* Actually insert the MEM. */
9585 loop_info->mems[loop_info->mems_idx].mem = m;
9586 /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
9587 because we can't put it in a register. We still store it in the
9588 table, though, so that if we see the same address later, but in a
9589 non-BLK mode, we'll not think we can optimize it at that point. */
9590 loop_info->mems[loop_info->mems_idx].optimize = (GET_MODE (m) != BLKmode);
9591 loop_info->mems[loop_info->mems_idx].reg = NULL_RTX;
9592 ++loop_info->mems_idx;
9594 return 0;
9598 /* Allocate REGS->ARRAY or reallocate it if it is too small.
9600 Increment REGS->ARRAY[I].SET_IN_LOOP at the index I of each
9601 register that is modified by an insn between FROM and TO. If the
9602 value of an element of REGS->array[I].SET_IN_LOOP becomes 127 or
9603 more, stop incrementing it, to avoid overflow.
9605 Store in REGS->ARRAY[I].SINGLE_USAGE the single insn in which
9606 register I is used, if it is only used once. Otherwise, it is set
9607 to 0 (for no uses) or const0_rtx for more than one use. This
9608 parameter may be zero, in which case this processing is not done.
9610 Set REGS->ARRAY[I].MAY_NOT_OPTIMIZE nonzero if we should not
9611 optimize register I. */
9613 static void
9614 loop_regs_scan (const struct loop *loop, int extra_size)
9616 struct loop_regs *regs = LOOP_REGS (loop);
9617 int old_nregs;
9618 /* last_set[n] is nonzero iff reg n has been set in the current
9619 basic block. In that case, it is the insn that last set reg n. */
9620 rtx *last_set;
9621 rtx insn;
9622 int i;
9624 old_nregs = regs->num;
9625 regs->num = max_reg_num ();
9627 /* Grow the regs array if not allocated or too small. */
9628 if (regs->num >= regs->size)
9630 regs->size = regs->num + extra_size;
9632 regs->array = xrealloc (regs->array, regs->size * sizeof (*regs->array));
9634 /* Zero the new elements. */
9635 memset (regs->array + old_nregs, 0,
9636 (regs->size - old_nregs) * sizeof (*regs->array));
9639 /* Clear previously scanned fields but do not clear n_times_set. */
9640 for (i = 0; i < old_nregs; i++)
9642 regs->array[i].set_in_loop = 0;
9643 regs->array[i].may_not_optimize = 0;
9644 regs->array[i].single_usage = NULL_RTX;
9647 last_set = xcalloc (regs->num, sizeof (rtx));
9649 /* Scan the loop, recording register usage. */
9650 for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
9651 insn = NEXT_INSN (insn))
9653 if (INSN_P (insn))
9655 /* Record registers that have exactly one use. */
9656 find_single_use_in_loop (regs, insn, PATTERN (insn));
9658 /* Include uses in REG_EQUAL notes. */
9659 if (REG_NOTES (insn))
9660 find_single_use_in_loop (regs, insn, REG_NOTES (insn));
9662 if (GET_CODE (PATTERN (insn)) == SET
9663 || GET_CODE (PATTERN (insn)) == CLOBBER)
9664 count_one_set (regs, insn, PATTERN (insn), last_set);
9665 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
9667 int i;
9668 for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
9669 count_one_set (regs, insn, XVECEXP (PATTERN (insn), 0, i),
9670 last_set);
9674 if (LABEL_P (insn) || JUMP_P (insn))
9675 memset (last_set, 0, regs->num * sizeof (rtx));
9677 /* Invalidate all registers used for function argument passing.
9678 We check rtx_varies_p for the same reason as below, to allow
9679 optimizing PIC calculations. */
9680 if (CALL_P (insn))
9682 rtx link;
9683 for (link = CALL_INSN_FUNCTION_USAGE (insn);
9684 link;
9685 link = XEXP (link, 1))
9687 rtx op, reg;
9689 if (GET_CODE (op = XEXP (link, 0)) == USE
9690 && REG_P (reg = XEXP (op, 0))
9691 && rtx_varies_p (reg, 1))
9692 regs->array[REGNO (reg)].may_not_optimize = 1;
9697 /* Invalidate all hard registers clobbered by calls. With one exception:
9698 a call-clobbered PIC register is still function-invariant for our
9699 purposes, since we can hoist any PIC calculations out of the loop.
9700 Thus the call to rtx_varies_p. */
9701 if (LOOP_INFO (loop)->has_call)
9702 for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
9703 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, i)
9704 && rtx_varies_p (regno_reg_rtx[i], 1))
9706 regs->array[i].may_not_optimize = 1;
9707 regs->array[i].set_in_loop = 1;
9710 #ifdef AVOID_CCMODE_COPIES
9711 /* Don't try to move insns which set CC registers if we should not
9712 create CCmode register copies. */
9713 for (i = regs->num - 1; i >= FIRST_PSEUDO_REGISTER; i--)
9714 if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
9715 regs->array[i].may_not_optimize = 1;
9716 #endif
9718 /* Set regs->array[I].n_times_set for the new registers. */
9719 for (i = old_nregs; i < regs->num; i++)
9720 regs->array[i].n_times_set = regs->array[i].set_in_loop;
9722 free (last_set);
9725 /* Returns the number of real INSNs in the LOOP. */
9727 static int
9728 count_insns_in_loop (const struct loop *loop)
9730 int count = 0;
9731 rtx insn;
9733 for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
9734 insn = NEXT_INSN (insn))
9735 if (INSN_P (insn))
9736 ++count;
9738 return count;
9741 /* Move MEMs into registers for the duration of the loop. */
9743 static void
9744 load_mems (const struct loop *loop)
9746 struct loop_info *loop_info = LOOP_INFO (loop);
9747 struct loop_regs *regs = LOOP_REGS (loop);
9748 int maybe_never = 0;
9749 int i;
9750 rtx p, prev_ebb_head;
9751 rtx label = NULL_RTX;
9752 rtx end_label;
9753 /* Nonzero if the next instruction may never be executed. */
9754 int next_maybe_never = 0;
9755 unsigned int last_max_reg = max_reg_num ();
9757 if (loop_info->mems_idx == 0)
9758 return;
9760 /* We cannot use next_label here because it skips over normal insns. */
9761 end_label = next_nonnote_insn (loop->end);
9762 if (end_label && !LABEL_P (end_label))
9763 end_label = NULL_RTX;
9765 /* Check to see if it's possible that some instructions in the loop are
9766 never executed. Also check if there is a goto out of the loop other
9767 than right after the end of the loop. */
9768 for (p = next_insn_in_loop (loop, loop->scan_start);
9769 p != NULL_RTX;
9770 p = next_insn_in_loop (loop, p))
9772 if (LABEL_P (p))
9773 maybe_never = 1;
9774 else if (JUMP_P (p)
9775 /* If we enter the loop in the middle, and scan
9776 around to the beginning, don't set maybe_never
9777 for that. This must be an unconditional jump,
9778 otherwise the code at the top of the loop might
9779 never be executed. Unconditional jumps are
9780 followed a by barrier then loop end. */
9781 && ! (JUMP_P (p)
9782 && JUMP_LABEL (p) == loop->top
9783 && NEXT_INSN (NEXT_INSN (p)) == loop->end
9784 && any_uncondjump_p (p)))
9786 /* If this is a jump outside of the loop but not right
9787 after the end of the loop, we would have to emit new fixup
9788 sequences for each such label. */
9789 if (/* If we can't tell where control might go when this
9790 JUMP_INSN is executed, we must be conservative. */
9791 !JUMP_LABEL (p)
9792 || (JUMP_LABEL (p) != end_label
9793 && (INSN_UID (JUMP_LABEL (p)) >= max_uid_for_loop
9794 || INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop->start)
9795 || INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop->end))))
9796 return;
9798 if (!any_condjump_p (p))
9799 /* Something complicated. */
9800 maybe_never = 1;
9801 else
9802 /* If there are any more instructions in the loop, they
9803 might not be reached. */
9804 next_maybe_never = 1;
9806 else if (next_maybe_never)
9807 maybe_never = 1;
9810 /* Find start of the extended basic block that enters the loop. */
9811 for (p = loop->start;
9812 PREV_INSN (p) && !LABEL_P (p);
9813 p = PREV_INSN (p))
9815 prev_ebb_head = p;
9817 cselib_init (true);
9819 /* Build table of mems that get set to constant values before the
9820 loop. */
9821 for (; p != loop->start; p = NEXT_INSN (p))
9822 cselib_process_insn (p);
9824 /* Actually move the MEMs. */
9825 for (i = 0; i < loop_info->mems_idx; ++i)
9827 regset_head load_copies;
9828 regset_head store_copies;
9829 int written = 0;
9830 rtx reg;
9831 rtx mem = loop_info->mems[i].mem;
9832 rtx mem_list_entry;
9834 if (MEM_VOLATILE_P (mem)
9835 || loop_invariant_p (loop, XEXP (mem, 0)) != 1)
9836 /* There's no telling whether or not MEM is modified. */
9837 loop_info->mems[i].optimize = 0;
9839 /* Go through the MEMs written to in the loop to see if this
9840 one is aliased by one of them. */
9841 mem_list_entry = loop_info->store_mems;
9842 while (mem_list_entry)
9844 if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
9845 written = 1;
9846 else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
9847 mem, rtx_varies_p))
9849 /* MEM is indeed aliased by this store. */
9850 loop_info->mems[i].optimize = 0;
9851 break;
9853 mem_list_entry = XEXP (mem_list_entry, 1);
9856 if (flag_float_store && written
9857 && GET_MODE_CLASS (GET_MODE (mem)) == MODE_FLOAT)
9858 loop_info->mems[i].optimize = 0;
9860 /* If this MEM is written to, we must be sure that there
9861 are no reads from another MEM that aliases this one. */
9862 if (loop_info->mems[i].optimize && written)
9864 int j;
9866 for (j = 0; j < loop_info->mems_idx; ++j)
9868 if (j == i)
9869 continue;
9870 else if (true_dependence (mem,
9871 VOIDmode,
9872 loop_info->mems[j].mem,
9873 rtx_varies_p))
9875 /* It's not safe to hoist loop_info->mems[i] out of
9876 the loop because writes to it might not be
9877 seen by reads from loop_info->mems[j]. */
9878 loop_info->mems[i].optimize = 0;
9879 break;
9884 if (maybe_never && may_trap_p (mem))
9885 /* We can't access the MEM outside the loop; it might
9886 cause a trap that wouldn't have happened otherwise. */
9887 loop_info->mems[i].optimize = 0;
9889 if (!loop_info->mems[i].optimize)
9890 /* We thought we were going to lift this MEM out of the
9891 loop, but later discovered that we could not. */
9892 continue;
9894 INIT_REG_SET (&load_copies);
9895 INIT_REG_SET (&store_copies);
9897 /* Allocate a pseudo for this MEM. We set REG_USERVAR_P in
9898 order to keep scan_loop from moving stores to this MEM
9899 out of the loop just because this REG is neither a
9900 user-variable nor used in the loop test. */
9901 reg = gen_reg_rtx (GET_MODE (mem));
9902 REG_USERVAR_P (reg) = 1;
9903 loop_info->mems[i].reg = reg;
9905 /* Now, replace all references to the MEM with the
9906 corresponding pseudos. */
9907 maybe_never = 0;
9908 for (p = next_insn_in_loop (loop, loop->scan_start);
9909 p != NULL_RTX;
9910 p = next_insn_in_loop (loop, p))
9912 if (INSN_P (p))
9914 rtx set;
9916 set = single_set (p);
9918 /* See if this copies the mem into a register that isn't
9919 modified afterwards. We'll try to do copy propagation
9920 a little further on. */
9921 if (set
9922 /* @@@ This test is _way_ too conservative. */
9923 && ! maybe_never
9924 && REG_P (SET_DEST (set))
9925 && REGNO (SET_DEST (set)) >= FIRST_PSEUDO_REGISTER
9926 && REGNO (SET_DEST (set)) < last_max_reg
9927 && regs->array[REGNO (SET_DEST (set))].n_times_set == 1
9928 && rtx_equal_p (SET_SRC (set), mem))
9929 SET_REGNO_REG_SET (&load_copies, REGNO (SET_DEST (set)));
9931 /* See if this copies the mem from a register that isn't
9932 modified afterwards. We'll try to remove the
9933 redundant copy later on by doing a little register
9934 renaming and copy propagation. This will help
9935 to untangle things for the BIV detection code. */
9936 if (set
9937 && ! maybe_never
9938 && REG_P (SET_SRC (set))
9939 && REGNO (SET_SRC (set)) >= FIRST_PSEUDO_REGISTER
9940 && REGNO (SET_SRC (set)) < last_max_reg
9941 && regs->array[REGNO (SET_SRC (set))].n_times_set == 1
9942 && rtx_equal_p (SET_DEST (set), mem))
9943 SET_REGNO_REG_SET (&store_copies, REGNO (SET_SRC (set)));
9945 /* If this is a call which uses / clobbers this memory
9946 location, we must not change the interface here. */
9947 if (CALL_P (p)
9948 && reg_mentioned_p (loop_info->mems[i].mem,
9949 CALL_INSN_FUNCTION_USAGE (p)))
9951 cancel_changes (0);
9952 loop_info->mems[i].optimize = 0;
9953 break;
9955 else
9956 /* Replace the memory reference with the shadow register. */
9957 replace_loop_mems (p, loop_info->mems[i].mem,
9958 loop_info->mems[i].reg, written);
9961 if (LABEL_P (p)
9962 || JUMP_P (p))
9963 maybe_never = 1;
9966 if (! loop_info->mems[i].optimize)
9967 ; /* We found we couldn't do the replacement, so do nothing. */
9968 else if (! apply_change_group ())
9969 /* We couldn't replace all occurrences of the MEM. */
9970 loop_info->mems[i].optimize = 0;
9971 else
9973 /* Load the memory immediately before LOOP->START, which is
9974 the NOTE_LOOP_BEG. */
9975 cselib_val *e = cselib_lookup (mem, VOIDmode, 0);
9976 rtx set;
9977 rtx best = mem;
9978 int j;
9979 struct elt_loc_list *const_equiv = 0;
9981 if (e)
9983 struct elt_loc_list *equiv;
9984 struct elt_loc_list *best_equiv = 0;
9985 for (equiv = e->locs; equiv; equiv = equiv->next)
9987 if (CONSTANT_P (equiv->loc))
9988 const_equiv = equiv;
9989 else if (REG_P (equiv->loc)
9990 /* Extending hard register lifetimes causes crash
9991 on SRC targets. Doing so on non-SRC is
9992 probably also not good idea, since we most
9993 probably have pseudoregister equivalence as
9994 well. */
9995 && REGNO (equiv->loc) >= FIRST_PSEUDO_REGISTER)
9996 best_equiv = equiv;
9998 /* Use the constant equivalence if that is cheap enough. */
9999 if (! best_equiv)
10000 best_equiv = const_equiv;
10001 else if (const_equiv
10002 && (rtx_cost (const_equiv->loc, SET)
10003 <= rtx_cost (best_equiv->loc, SET)))
10005 best_equiv = const_equiv;
10006 const_equiv = 0;
10009 /* If best_equiv is nonzero, we know that MEM is set to a
10010 constant or register before the loop. We will use this
10011 knowledge to initialize the shadow register with that
10012 constant or reg rather than by loading from MEM. */
10013 if (best_equiv)
10014 best = copy_rtx (best_equiv->loc);
10017 set = gen_move_insn (reg, best);
10018 set = loop_insn_hoist (loop, set);
10019 if (REG_P (best))
10021 for (p = prev_ebb_head; p != loop->start; p = NEXT_INSN (p))
10022 if (REGNO_LAST_UID (REGNO (best)) == INSN_UID (p))
10024 REGNO_LAST_UID (REGNO (best)) = INSN_UID (set);
10025 break;
10029 if (const_equiv)
10030 set_unique_reg_note (set, REG_EQUAL, copy_rtx (const_equiv->loc));
10032 if (written)
10034 if (label == NULL_RTX)
10036 label = gen_label_rtx ();
10037 emit_label_after (label, loop->end);
10040 /* Store the memory immediately after END, which is
10041 the NOTE_LOOP_END. */
10042 set = gen_move_insn (copy_rtx (mem), reg);
10043 loop_insn_emit_after (loop, 0, label, set);
10046 if (loop_dump_stream)
10048 fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
10049 REGNO (reg), (written ? "r/w" : "r/o"));
10050 print_rtl (loop_dump_stream, mem);
10051 fputc ('\n', loop_dump_stream);
10054 /* Attempt a bit of copy propagation. This helps untangle the
10055 data flow, and enables {basic,general}_induction_var to find
10056 more bivs/givs. */
10057 EXECUTE_IF_SET_IN_REG_SET
10058 (&load_copies, FIRST_PSEUDO_REGISTER, j,
10060 try_copy_prop (loop, reg, j);
10062 CLEAR_REG_SET (&load_copies);
10064 EXECUTE_IF_SET_IN_REG_SET
10065 (&store_copies, FIRST_PSEUDO_REGISTER, j,
10067 try_swap_copy_prop (loop, reg, j);
10069 CLEAR_REG_SET (&store_copies);
10073 /* Now, we need to replace all references to the previous exit
10074 label with the new one. */
10075 if (label != NULL_RTX && end_label != NULL_RTX)
10076 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
10077 if (JUMP_P (p) && JUMP_LABEL (p) == end_label)
10078 redirect_jump (p, label, false);
10080 cselib_finish ();
10083 /* For communication between note_reg_stored and its caller. */
10084 struct note_reg_stored_arg
10086 int set_seen;
10087 rtx reg;
10090 /* Called via note_stores, record in SET_SEEN whether X, which is written,
10091 is equal to ARG. */
10092 static void
10093 note_reg_stored (rtx x, rtx setter ATTRIBUTE_UNUSED, void *arg)
10095 struct note_reg_stored_arg *t = (struct note_reg_stored_arg *) arg;
10096 if (t->reg == x)
10097 t->set_seen = 1;
10100 /* Try to replace every occurrence of pseudo REGNO with REPLACEMENT.
10101 There must be exactly one insn that sets this pseudo; it will be
10102 deleted if all replacements succeed and we can prove that the register
10103 is not used after the loop. */
10105 static void
10106 try_copy_prop (const struct loop *loop, rtx replacement, unsigned int regno)
10108 /* This is the reg that we are copying from. */
10109 rtx reg_rtx = regno_reg_rtx[regno];
10110 rtx init_insn = 0;
10111 rtx insn;
10112 /* These help keep track of whether we replaced all uses of the reg. */
10113 int replaced_last = 0;
10114 int store_is_first = 0;
10116 for (insn = next_insn_in_loop (loop, loop->scan_start);
10117 insn != NULL_RTX;
10118 insn = next_insn_in_loop (loop, insn))
10120 rtx set;
10122 /* Only substitute within one extended basic block from the initializing
10123 insn. */
10124 if (LABEL_P (insn) && init_insn)
10125 break;
10127 if (! INSN_P (insn))
10128 continue;
10130 /* Is this the initializing insn? */
10131 set = single_set (insn);
10132 if (set
10133 && REG_P (SET_DEST (set))
10134 && REGNO (SET_DEST (set)) == regno)
10136 if (init_insn)
10137 abort ();
10139 init_insn = insn;
10140 if (REGNO_FIRST_UID (regno) == INSN_UID (insn))
10141 store_is_first = 1;
10144 /* Only substitute after seeing the initializing insn. */
10145 if (init_insn && insn != init_insn)
10147 struct note_reg_stored_arg arg;
10149 replace_loop_regs (insn, reg_rtx, replacement);
10150 if (REGNO_LAST_UID (regno) == INSN_UID (insn))
10151 replaced_last = 1;
10153 /* Stop replacing when REPLACEMENT is modified. */
10154 arg.reg = replacement;
10155 arg.set_seen = 0;
10156 note_stores (PATTERN (insn), note_reg_stored, &arg);
10157 if (arg.set_seen)
10159 rtx note = find_reg_note (insn, REG_EQUAL, NULL);
10161 /* It is possible that we've turned previously valid REG_EQUAL to
10162 invalid, as we change the REGNO to REPLACEMENT and unlike REGNO,
10163 REPLACEMENT is modified, we get different meaning. */
10164 if (note && reg_mentioned_p (replacement, XEXP (note, 0)))
10165 remove_note (insn, note);
10166 break;
10170 if (! init_insn)
10171 abort ();
10172 if (apply_change_group ())
10174 if (loop_dump_stream)
10175 fprintf (loop_dump_stream, " Replaced reg %d", regno);
10176 if (store_is_first && replaced_last)
10178 rtx first;
10179 rtx retval_note;
10181 /* Assume we're just deleting INIT_INSN. */
10182 first = init_insn;
10183 /* Look for REG_RETVAL note. If we're deleting the end of
10184 the libcall sequence, the whole sequence can go. */
10185 retval_note = find_reg_note (init_insn, REG_RETVAL, NULL_RTX);
10186 /* If we found a REG_RETVAL note, find the first instruction
10187 in the sequence. */
10188 if (retval_note)
10189 first = XEXP (retval_note, 0);
10191 /* Delete the instructions. */
10192 loop_delete_insns (first, init_insn);
10194 if (loop_dump_stream)
10195 fprintf (loop_dump_stream, ".\n");
10199 /* Replace all the instructions from FIRST up to and including LAST
10200 with NOTE_INSN_DELETED notes. */
10202 static void
10203 loop_delete_insns (rtx first, rtx last)
10205 while (1)
10207 if (loop_dump_stream)
10208 fprintf (loop_dump_stream, ", deleting init_insn (%d)",
10209 INSN_UID (first));
10210 delete_insn (first);
10212 /* If this was the LAST instructions we're supposed to delete,
10213 we're done. */
10214 if (first == last)
10215 break;
10217 first = NEXT_INSN (first);
10221 /* Try to replace occurrences of pseudo REGNO with REPLACEMENT within
10222 loop LOOP if the order of the sets of these registers can be
10223 swapped. There must be exactly one insn within the loop that sets
10224 this pseudo followed immediately by a move insn that sets
10225 REPLACEMENT with REGNO. */
10226 static void
10227 try_swap_copy_prop (const struct loop *loop, rtx replacement,
10228 unsigned int regno)
10230 rtx insn;
10231 rtx set = NULL_RTX;
10232 unsigned int new_regno;
10234 new_regno = REGNO (replacement);
10236 for (insn = next_insn_in_loop (loop, loop->scan_start);
10237 insn != NULL_RTX;
10238 insn = next_insn_in_loop (loop, insn))
10240 /* Search for the insn that copies REGNO to NEW_REGNO? */
10241 if (INSN_P (insn)
10242 && (set = single_set (insn))
10243 && REG_P (SET_DEST (set))
10244 && REGNO (SET_DEST (set)) == new_regno
10245 && REG_P (SET_SRC (set))
10246 && REGNO (SET_SRC (set)) == regno)
10247 break;
10250 if (insn != NULL_RTX)
10252 rtx prev_insn;
10253 rtx prev_set;
10255 /* Some DEF-USE info would come in handy here to make this
10256 function more general. For now, just check the previous insn
10257 which is the most likely candidate for setting REGNO. */
10259 prev_insn = PREV_INSN (insn);
10261 if (INSN_P (insn)
10262 && (prev_set = single_set (prev_insn))
10263 && REG_P (SET_DEST (prev_set))
10264 && REGNO (SET_DEST (prev_set)) == regno)
10266 /* We have:
10267 (set (reg regno) (expr))
10268 (set (reg new_regno) (reg regno))
10270 so try converting this to:
10271 (set (reg new_regno) (expr))
10272 (set (reg regno) (reg new_regno))
10274 The former construct is often generated when a global
10275 variable used for an induction variable is shadowed by a
10276 register (NEW_REGNO). The latter construct improves the
10277 chances of GIV replacement and BIV elimination. */
10279 validate_change (prev_insn, &SET_DEST (prev_set),
10280 replacement, 1);
10281 validate_change (insn, &SET_DEST (set),
10282 SET_SRC (set), 1);
10283 validate_change (insn, &SET_SRC (set),
10284 replacement, 1);
10286 if (apply_change_group ())
10288 if (loop_dump_stream)
10289 fprintf (loop_dump_stream,
10290 " Swapped set of reg %d at %d with reg %d at %d.\n",
10291 regno, INSN_UID (insn),
10292 new_regno, INSN_UID (prev_insn));
10294 /* Update first use of REGNO. */
10295 if (REGNO_FIRST_UID (regno) == INSN_UID (prev_insn))
10296 REGNO_FIRST_UID (regno) = INSN_UID (insn);
10298 /* Now perform copy propagation to hopefully
10299 remove all uses of REGNO within the loop. */
10300 try_copy_prop (loop, replacement, regno);
10306 /* Worker function for find_mem_in_note, called via for_each_rtx. */
10308 static int
10309 find_mem_in_note_1 (rtx *x, void *data)
10311 if (*x != NULL_RTX && MEM_P (*x))
10313 rtx *res = (rtx *) data;
10314 *res = *x;
10315 return 1;
10317 return 0;
10320 /* Returns the first MEM found in NOTE by depth-first search. */
10322 static rtx
10323 find_mem_in_note (rtx note)
10325 if (note && for_each_rtx (&note, find_mem_in_note_1, &note))
10326 return note;
10327 return NULL_RTX;
10330 /* Replace MEM with its associated pseudo register. This function is
10331 called from load_mems via for_each_rtx. DATA is actually a pointer
10332 to a structure describing the instruction currently being scanned
10333 and the MEM we are currently replacing. */
10335 static int
10336 replace_loop_mem (rtx *mem, void *data)
10338 loop_replace_args *args = (loop_replace_args *) data;
10339 rtx m = *mem;
10341 if (m == NULL_RTX)
10342 return 0;
10344 switch (GET_CODE (m))
10346 case MEM:
10347 break;
10349 case CONST_DOUBLE:
10350 /* We're not interested in the MEM associated with a
10351 CONST_DOUBLE, so there's no need to traverse into one. */
10352 return -1;
10354 default:
10355 /* This is not a MEM. */
10356 return 0;
10359 if (!rtx_equal_p (args->match, m))
10360 /* This is not the MEM we are currently replacing. */
10361 return 0;
10363 /* Actually replace the MEM. */
10364 validate_change (args->insn, mem, args->replacement, 1);
10366 return 0;
10369 static void
10370 replace_loop_mems (rtx insn, rtx mem, rtx reg, int written)
10372 loop_replace_args args;
10374 args.insn = insn;
10375 args.match = mem;
10376 args.replacement = reg;
10378 for_each_rtx (&insn, replace_loop_mem, &args);
10380 /* If we hoist a mem write out of the loop, then REG_EQUAL
10381 notes referring to the mem are no longer valid. */
10382 if (written)
10384 rtx note, sub;
10385 rtx *link;
10387 for (link = &REG_NOTES (insn); (note = *link); link = &XEXP (note, 1))
10389 if (REG_NOTE_KIND (note) == REG_EQUAL
10390 && (sub = find_mem_in_note (note))
10391 && true_dependence (mem, VOIDmode, sub, rtx_varies_p))
10393 /* Remove the note. */
10394 validate_change (NULL_RTX, link, XEXP (note, 1), 1);
10395 break;
10401 /* Replace one register with another. Called through for_each_rtx; PX points
10402 to the rtx being scanned. DATA is actually a pointer to
10403 a structure of arguments. */
10405 static int
10406 replace_loop_reg (rtx *px, void *data)
10408 rtx x = *px;
10409 loop_replace_args *args = (loop_replace_args *) data;
10411 if (x == NULL_RTX)
10412 return 0;
10414 if (x == args->match)
10415 validate_change (args->insn, px, args->replacement, 1);
10417 return 0;
10420 static void
10421 replace_loop_regs (rtx insn, rtx reg, rtx replacement)
10423 loop_replace_args args;
10425 args.insn = insn;
10426 args.match = reg;
10427 args.replacement = replacement;
10429 for_each_rtx (&insn, replace_loop_reg, &args);
10432 /* Emit insn for PATTERN after WHERE_INSN in basic block WHERE_BB
10433 (ignored in the interim). */
10435 static rtx
10436 loop_insn_emit_after (const struct loop *loop ATTRIBUTE_UNUSED,
10437 basic_block where_bb ATTRIBUTE_UNUSED, rtx where_insn,
10438 rtx pattern)
10440 return emit_insn_after (pattern, where_insn);
10444 /* If WHERE_INSN is nonzero emit insn for PATTERN before WHERE_INSN
10445 in basic block WHERE_BB (ignored in the interim) within the loop
10446 otherwise hoist PATTERN into the loop pre-header. */
10449 loop_insn_emit_before (const struct loop *loop,
10450 basic_block where_bb ATTRIBUTE_UNUSED,
10451 rtx where_insn, rtx pattern)
10453 if (! where_insn)
10454 return loop_insn_hoist (loop, pattern);
10455 return emit_insn_before (pattern, where_insn);
10459 /* Emit call insn for PATTERN before WHERE_INSN in basic block
10460 WHERE_BB (ignored in the interim) within the loop. */
10462 static rtx
10463 loop_call_insn_emit_before (const struct loop *loop ATTRIBUTE_UNUSED,
10464 basic_block where_bb ATTRIBUTE_UNUSED,
10465 rtx where_insn, rtx pattern)
10467 return emit_call_insn_before (pattern, where_insn);
10471 /* Hoist insn for PATTERN into the loop pre-header. */
10474 loop_insn_hoist (const struct loop *loop, rtx pattern)
10476 return loop_insn_emit_before (loop, 0, loop->start, pattern);
10480 /* Hoist call insn for PATTERN into the loop pre-header. */
10482 static rtx
10483 loop_call_insn_hoist (const struct loop *loop, rtx pattern)
10485 return loop_call_insn_emit_before (loop, 0, loop->start, pattern);
10489 /* Sink insn for PATTERN after the loop end. */
10492 loop_insn_sink (const struct loop *loop, rtx pattern)
10494 return loop_insn_emit_before (loop, 0, loop->sink, pattern);
10497 /* bl->final_value can be either general_operand or PLUS of general_operand
10498 and constant. Emit sequence of instructions to load it into REG. */
10499 static rtx
10500 gen_load_of_final_value (rtx reg, rtx final_value)
10502 rtx seq;
10503 start_sequence ();
10504 final_value = force_operand (final_value, reg);
10505 if (final_value != reg)
10506 emit_move_insn (reg, final_value);
10507 seq = get_insns ();
10508 end_sequence ();
10509 return seq;
10512 /* If the loop has multiple exits, emit insn for PATTERN before the
10513 loop to ensure that it will always be executed no matter how the
10514 loop exits. Otherwise, emit the insn for PATTERN after the loop,
10515 since this is slightly more efficient. */
10517 static rtx
10518 loop_insn_sink_or_swim (const struct loop *loop, rtx pattern)
10520 if (loop->exit_count)
10521 return loop_insn_hoist (loop, pattern);
10522 else
10523 return loop_insn_sink (loop, pattern);
10526 static void
10527 loop_ivs_dump (const struct loop *loop, FILE *file, int verbose)
10529 struct iv_class *bl;
10530 int iv_num = 0;
10532 if (! loop || ! file)
10533 return;
10535 for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
10536 iv_num++;
10538 fprintf (file, "Loop %d: %d IV classes\n", loop->num, iv_num);
10540 for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
10542 loop_iv_class_dump (bl, file, verbose);
10543 fputc ('\n', file);
10548 static void
10549 loop_iv_class_dump (const struct iv_class *bl, FILE *file,
10550 int verbose ATTRIBUTE_UNUSED)
10552 struct induction *v;
10553 rtx incr;
10554 int i;
10556 if (! bl || ! file)
10557 return;
10559 fprintf (file, "IV class for reg %d, benefit %d\n",
10560 bl->regno, bl->total_benefit);
10562 fprintf (file, " Init insn %d", INSN_UID (bl->init_insn));
10563 if (bl->initial_value)
10565 fprintf (file, ", init val: ");
10566 print_simple_rtl (file, bl->initial_value);
10568 if (bl->initial_test)
10570 fprintf (file, ", init test: ");
10571 print_simple_rtl (file, bl->initial_test);
10573 fputc ('\n', file);
10575 if (bl->final_value)
10577 fprintf (file, " Final val: ");
10578 print_simple_rtl (file, bl->final_value);
10579 fputc ('\n', file);
10582 if ((incr = biv_total_increment (bl)))
10584 fprintf (file, " Total increment: ");
10585 print_simple_rtl (file, incr);
10586 fputc ('\n', file);
10589 /* List the increments. */
10590 for (i = 0, v = bl->biv; v; v = v->next_iv, i++)
10592 fprintf (file, " Inc%d: insn %d, incr: ", i, INSN_UID (v->insn));
10593 print_simple_rtl (file, v->add_val);
10594 fputc ('\n', file);
10597 /* List the givs. */
10598 for (i = 0, v = bl->giv; v; v = v->next_iv, i++)
10600 fprintf (file, " Giv%d: insn %d, benefit %d, ",
10601 i, INSN_UID (v->insn), v->benefit);
10602 if (v->giv_type == DEST_ADDR)
10603 print_simple_rtl (file, v->mem);
10604 else
10605 print_simple_rtl (file, single_set (v->insn));
10606 fputc ('\n', file);
10611 static void
10612 loop_biv_dump (const struct induction *v, FILE *file, int verbose)
10614 if (! v || ! file)
10615 return;
10617 fprintf (file,
10618 "Biv %d: insn %d",
10619 REGNO (v->dest_reg), INSN_UID (v->insn));
10620 fprintf (file, " const ");
10621 print_simple_rtl (file, v->add_val);
10623 if (verbose && v->final_value)
10625 fputc ('\n', file);
10626 fprintf (file, " final ");
10627 print_simple_rtl (file, v->final_value);
10630 fputc ('\n', file);
10634 static void
10635 loop_giv_dump (const struct induction *v, FILE *file, int verbose)
10637 if (! v || ! file)
10638 return;
10640 if (v->giv_type == DEST_REG)
10641 fprintf (file, "Giv %d: insn %d",
10642 REGNO (v->dest_reg), INSN_UID (v->insn));
10643 else
10644 fprintf (file, "Dest address: insn %d",
10645 INSN_UID (v->insn));
10647 fprintf (file, " src reg %d benefit %d",
10648 REGNO (v->src_reg), v->benefit);
10649 fprintf (file, " lifetime %d",
10650 v->lifetime);
10652 if (v->replaceable)
10653 fprintf (file, " replaceable");
10655 if (v->no_const_addval)
10656 fprintf (file, " ncav");
10658 if (v->ext_dependent)
10660 switch (GET_CODE (v->ext_dependent))
10662 case SIGN_EXTEND:
10663 fprintf (file, " ext se");
10664 break;
10665 case ZERO_EXTEND:
10666 fprintf (file, " ext ze");
10667 break;
10668 case TRUNCATE:
10669 fprintf (file, " ext tr");
10670 break;
10671 default:
10672 abort ();
10676 fputc ('\n', file);
10677 fprintf (file, " mult ");
10678 print_simple_rtl (file, v->mult_val);
10680 fputc ('\n', file);
10681 fprintf (file, " add ");
10682 print_simple_rtl (file, v->add_val);
10684 if (verbose && v->final_value)
10686 fputc ('\n', file);
10687 fprintf (file, " final ");
10688 print_simple_rtl (file, v->final_value);
10691 fputc ('\n', file);
10695 void
10696 debug_ivs (const struct loop *loop)
10698 loop_ivs_dump (loop, stderr, 1);
10702 void
10703 debug_iv_class (const struct iv_class *bl)
10705 loop_iv_class_dump (bl, stderr, 1);
10709 void
10710 debug_biv (const struct induction *v)
10712 loop_biv_dump (v, stderr, 1);
10716 void
10717 debug_giv (const struct induction *v)
10719 loop_giv_dump (v, stderr, 1);
10723 #define LOOP_BLOCK_NUM_1(INSN) \
10724 ((INSN) ? (BLOCK_FOR_INSN (INSN) ? BLOCK_NUM (INSN) : - 1) : -1)
10726 /* The notes do not have an assigned block, so look at the next insn. */
10727 #define LOOP_BLOCK_NUM(INSN) \
10728 ((INSN) ? (NOTE_P (INSN) \
10729 ? LOOP_BLOCK_NUM_1 (next_nonnote_insn (INSN)) \
10730 : LOOP_BLOCK_NUM_1 (INSN)) \
10731 : -1)
10733 #define LOOP_INSN_UID(INSN) ((INSN) ? INSN_UID (INSN) : -1)
10735 static void
10736 loop_dump_aux (const struct loop *loop, FILE *file,
10737 int verbose ATTRIBUTE_UNUSED)
10739 rtx label;
10741 if (! loop || ! file)
10742 return;
10744 /* Print diagnostics to compare our concept of a loop with
10745 what the loop notes say. */
10746 if (! PREV_INSN (BB_HEAD (loop->first))
10747 || !NOTE_P (PREV_INSN (BB_HEAD (loop->first)))
10748 || NOTE_LINE_NUMBER (PREV_INSN (BB_HEAD (loop->first)))
10749 != NOTE_INSN_LOOP_BEG)
10750 fprintf (file, ";; No NOTE_INSN_LOOP_BEG at %d\n",
10751 INSN_UID (PREV_INSN (BB_HEAD (loop->first))));
10752 if (! NEXT_INSN (BB_END (loop->last))
10753 || !NOTE_P (NEXT_INSN (BB_END (loop->last)))
10754 || NOTE_LINE_NUMBER (NEXT_INSN (BB_END (loop->last)))
10755 != NOTE_INSN_LOOP_END)
10756 fprintf (file, ";; No NOTE_INSN_LOOP_END at %d\n",
10757 INSN_UID (NEXT_INSN (BB_END (loop->last))));
10759 if (loop->start)
10761 fprintf (file,
10762 ";; start %d (%d), cont dom %d (%d), cont %d (%d), vtop %d (%d), end %d (%d)\n",
10763 LOOP_BLOCK_NUM (loop->start),
10764 LOOP_INSN_UID (loop->start),
10765 LOOP_BLOCK_NUM (loop->cont),
10766 LOOP_INSN_UID (loop->cont),
10767 LOOP_BLOCK_NUM (loop->cont),
10768 LOOP_INSN_UID (loop->cont),
10769 LOOP_BLOCK_NUM (loop->vtop),
10770 LOOP_INSN_UID (loop->vtop),
10771 LOOP_BLOCK_NUM (loop->end),
10772 LOOP_INSN_UID (loop->end));
10773 fprintf (file, ";; top %d (%d), scan start %d (%d)\n",
10774 LOOP_BLOCK_NUM (loop->top),
10775 LOOP_INSN_UID (loop->top),
10776 LOOP_BLOCK_NUM (loop->scan_start),
10777 LOOP_INSN_UID (loop->scan_start));
10778 fprintf (file, ";; exit_count %d", loop->exit_count);
10779 if (loop->exit_count)
10781 fputs (", labels:", file);
10782 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
10784 fprintf (file, " %d ",
10785 LOOP_INSN_UID (XEXP (label, 0)));
10788 fputs ("\n", file);
10790 /* This can happen when a marked loop appears as two nested loops,
10791 say from while (a || b) {}. The inner loop won't match
10792 the loop markers but the outer one will. */
10793 if (LOOP_BLOCK_NUM (loop->cont) != loop->latch->index)
10794 fprintf (file, ";; NOTE_INSN_LOOP_CONT not in loop latch\n");
10798 /* Call this function from the debugger to dump LOOP. */
10800 void
10801 debug_loop (const struct loop *loop)
10803 flow_loop_dump (loop, stderr, loop_dump_aux, 1);
10806 /* Call this function from the debugger to dump LOOPS. */
10808 void
10809 debug_loops (const struct loops *loops)
10811 flow_loops_dump (loops, stderr, loop_dump_aux, 1);