Do not bias REG_N_REFS by loop_depth when optimising for size.
[official-gcc.git] / gcc / loop.c
blob096967808ace1398f699678051387606fad548e6
1 /* Perform various loop optimizations, including strength reduction.
2 Copyright (C) 1987, 1988, 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000 Free Software Foundation, Inc.
5 This file is part of GNU CC.
7 GNU CC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU CC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU CC; see the file COPYING. If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
23 /* This is the loop optimization pass of the compiler.
24 It finds invariant computations within loops and moves them
25 to the beginning of the loop. Then it identifies basic and
26 general induction variables. Strength reduction is applied to the general
27 induction variables, and induction variable elimination is applied to
28 the basic induction variables.
30 It also finds cases where
31 a register is set within the loop by zero-extending a narrower value
32 and changes these to zero the entire register once before the loop
33 and merely copy the low part within the loop.
35 Most of the complexity is in heuristics to decide when it is worth
36 while to do these things. */
38 #include "config.h"
39 #include "system.h"
40 #include "rtl.h"
41 #include "tm_p.h"
42 #include "obstack.h"
43 #include "function.h"
44 #include "expr.h"
45 #include "basic-block.h"
46 #include "insn-config.h"
47 #include "insn-flags.h"
48 #include "regs.h"
49 #include "hard-reg-set.h"
50 #include "recog.h"
51 #include "flags.h"
52 #include "real.h"
53 #include "loop.h"
54 #include "cselib.h"
55 #include "except.h"
56 #include "toplev.h"
58 /* Vector mapping INSN_UIDs to luids.
59 The luids are like uids but increase monotonically always.
60 We use them to see whether a jump comes from outside a given loop. */
62 int *uid_luid;
64 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
65 number the insn is contained in. */
67 struct loop **uid_loop;
69 /* 1 + largest uid of any insn. */
71 int max_uid_for_loop;
73 /* 1 + luid of last insn. */
75 static int max_luid;
77 /* Number of loops detected in current function. Used as index to the
78 next few tables. */
80 static int max_loop_num;
82 /* Indexed by register number, contains the number of times the reg
83 is set during the loop being scanned.
84 During code motion, a negative value indicates a reg that has been
85 made a candidate; in particular -2 means that it is an candidate that
86 we know is equal to a constant and -1 means that it is an candidate
87 not known equal to a constant.
88 After code motion, regs moved have 0 (which is accurate now)
89 while the failed candidates have the original number of times set.
91 Therefore, at all times, == 0 indicates an invariant register;
92 < 0 a conditionally invariant one. */
94 static varray_type set_in_loop;
96 /* Original value of set_in_loop; same except that this value
97 is not set negative for a reg whose sets have been made candidates
98 and not set to 0 for a reg that is moved. */
100 static varray_type n_times_set;
102 /* Index by register number, 1 indicates that the register
103 cannot be moved or strength reduced. */
105 static varray_type may_not_optimize;
107 /* Contains the insn in which a register was used if it was used
108 exactly once; contains const0_rtx if it was used more than once. */
110 static varray_type reg_single_usage;
112 /* Nonzero means reg N has already been moved out of one loop.
113 This reduces the desire to move it out of another. */
115 static char *moved_once;
117 /* List of MEMs that are stored in this loop. */
119 static rtx loop_store_mems;
121 /* The insn where the first of these was found. */
122 static rtx first_loop_store_insn;
124 typedef struct loop_mem_info {
125 rtx mem; /* The MEM itself. */
126 rtx reg; /* Corresponding pseudo, if any. */
127 int optimize; /* Nonzero if we can optimize access to this MEM. */
128 } loop_mem_info;
130 /* Array of MEMs that are used (read or written) in this loop, but
131 cannot be aliased by anything in this loop, except perhaps
132 themselves. In other words, if loop_mems[i] is altered during the
133 loop, it is altered by an expression that is rtx_equal_p to it. */
135 static loop_mem_info *loop_mems;
137 /* The index of the next available slot in LOOP_MEMS. */
139 static int loop_mems_idx;
141 /* The number of elements allocated in LOOP_MEMs. */
143 static int loop_mems_allocated;
145 /* Nonzero if we don't know what MEMs were changed in the current
146 loop. This happens if the loop contains a call (in which case
147 `loop_info->has_call' will also be set) or if we store into more
148 than NUM_STORES MEMs. */
150 static int unknown_address_altered;
152 /* The above doesn't count any readonly memory locations that are stored.
153 This does. */
155 static int unknown_constant_address_altered;
157 /* Count of movable (i.e. invariant) instructions discovered in the loop. */
158 static int num_movables;
160 /* Count of memory write instructions discovered in the loop. */
161 static int num_mem_sets;
163 /* Bound on pseudo register number before loop optimization.
164 A pseudo has valid regscan info if its number is < max_reg_before_loop. */
165 unsigned int max_reg_before_loop;
167 /* The value to pass to the next call of reg_scan_update. */
168 static int loop_max_reg;
170 /* This obstack is used in product_cheap_p to allocate its rtl. It
171 may call gen_reg_rtx which, in turn, may reallocate regno_reg_rtx.
172 If we used the same obstack that it did, we would be deallocating
173 that array. */
175 static struct obstack temp_obstack;
177 /* This is where the pointer to the obstack being used for RTL is stored. */
179 extern struct obstack *rtl_obstack;
181 #define obstack_chunk_alloc xmalloc
182 #define obstack_chunk_free free
184 /* During the analysis of a loop, a chain of `struct movable's
185 is made to record all the movable insns found.
186 Then the entire chain can be scanned to decide which to move. */
188 struct movable
190 rtx insn; /* A movable insn */
191 rtx set_src; /* The expression this reg is set from. */
192 rtx set_dest; /* The destination of this SET. */
193 rtx dependencies; /* When INSN is libcall, this is an EXPR_LIST
194 of any registers used within the LIBCALL. */
195 int consec; /* Number of consecutive following insns
196 that must be moved with this one. */
197 unsigned int regno; /* The register it sets */
198 short lifetime; /* lifetime of that register;
199 may be adjusted when matching movables
200 that load the same value are found. */
201 short savings; /* Number of insns we can move for this reg,
202 including other movables that force this
203 or match this one. */
204 unsigned int cond : 1; /* 1 if only conditionally movable */
205 unsigned int force : 1; /* 1 means MUST move this insn */
206 unsigned int global : 1; /* 1 means reg is live outside this loop */
207 /* If PARTIAL is 1, GLOBAL means something different:
208 that the reg is live outside the range from where it is set
209 to the following label. */
210 unsigned int done : 1; /* 1 inhibits further processing of this */
212 unsigned int partial : 1; /* 1 means this reg is used for zero-extending.
213 In particular, moving it does not make it
214 invariant. */
215 unsigned int move_insn : 1; /* 1 means that we call emit_move_insn to
216 load SRC, rather than copying INSN. */
217 unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
218 first insn of a consecutive sets group. */
219 unsigned int is_equiv : 1; /* 1 means a REG_EQUIV is present on INSN. */
220 enum machine_mode savemode; /* Nonzero means it is a mode for a low part
221 that we should avoid changing when clearing
222 the rest of the reg. */
223 struct movable *match; /* First entry for same value */
224 struct movable *forces; /* An insn that must be moved if this is */
225 struct movable *next;
228 static struct movable *the_movables;
230 FILE *loop_dump_stream;
232 /* Forward declarations. */
234 static void verify_dominator PARAMS ((struct loop *));
235 static void find_and_verify_loops PARAMS ((rtx, struct loops *));
236 static void mark_loop_jump PARAMS ((rtx, struct loop *));
237 static void prescan_loop PARAMS ((struct loop *));
238 static int reg_in_basic_block_p PARAMS ((rtx, rtx));
239 static int consec_sets_invariant_p PARAMS ((const struct loop *,
240 rtx, int, rtx));
241 static int labels_in_range_p PARAMS ((rtx, int));
242 static void count_one_set PARAMS ((rtx, rtx, varray_type, rtx *));
244 static void count_loop_regs_set PARAMS ((rtx, rtx, varray_type, varray_type,
245 int *, int));
246 static void note_addr_stored PARAMS ((rtx, rtx, void *));
247 static void note_set_pseudo_multiple_uses PARAMS ((rtx, rtx, void *));
248 static int loop_reg_used_before_p PARAMS ((const struct loop *, rtx, rtx));
249 static void scan_loop PARAMS ((struct loop*, int, int));
250 #if 0
251 static void replace_call_address PARAMS ((rtx, rtx, rtx));
252 #endif
253 static rtx skip_consec_insns PARAMS ((rtx, int));
254 static int libcall_benefit PARAMS ((rtx));
255 static void ignore_some_movables PARAMS ((struct movable *));
256 static void force_movables PARAMS ((struct movable *));
257 static void combine_movables PARAMS ((struct movable *, int));
258 static int regs_match_p PARAMS ((rtx, rtx, struct movable *));
259 static int rtx_equal_for_loop_p PARAMS ((rtx, rtx, struct movable *));
260 static void add_label_notes PARAMS ((rtx, rtx));
261 static void move_movables PARAMS ((struct loop *loop, struct movable *,
262 int, int, int));
263 static int count_nonfixed_reads PARAMS ((const struct loop *, rtx));
264 static void strength_reduce PARAMS ((struct loop *, int, int, int));
265 static void find_single_use_in_loop PARAMS ((rtx, rtx, varray_type));
266 static int valid_initial_value_p PARAMS ((rtx, rtx, int, rtx));
267 static void find_mem_givs PARAMS ((const struct loop *, rtx, rtx, int, int));
268 static void record_biv PARAMS ((struct induction *, rtx, rtx, rtx, rtx, rtx *,
269 int, int, int));
270 static void check_final_value PARAMS ((const struct loop *,
271 struct induction *));
272 static void record_giv PARAMS ((const struct loop *, struct induction *,
273 rtx, rtx, rtx, rtx, rtx, int, enum g_types,
274 int, int, rtx *));
275 static void update_giv_derive PARAMS ((const struct loop *, rtx));
276 static int basic_induction_var PARAMS ((const struct loop *, rtx,
277 enum machine_mode, rtx, rtx,
278 rtx *, rtx *, rtx **, int *));
279 static rtx simplify_giv_expr PARAMS ((const struct loop *, rtx, int *));
280 static int general_induction_var PARAMS ((const struct loop *loop, rtx, rtx *,
281 rtx *, rtx *, int, int *, enum machine_mode));
282 static int consec_sets_giv PARAMS ((const struct loop *, int, rtx,
283 rtx, rtx, rtx *, rtx *, rtx *));
284 static int check_dbra_loop PARAMS ((struct loop *, int));
285 static rtx express_from_1 PARAMS ((rtx, rtx, rtx));
286 static rtx combine_givs_p PARAMS ((struct induction *, struct induction *));
287 static void combine_givs PARAMS ((struct iv_class *));
288 struct recombine_givs_stats;
289 static int find_life_end PARAMS ((rtx, struct recombine_givs_stats *,
290 rtx, rtx));
291 static void recombine_givs PARAMS ((const struct loop *, struct iv_class *,
292 int));
293 static int product_cheap_p PARAMS ((rtx, rtx));
294 static int maybe_eliminate_biv PARAMS ((const struct loop *, struct iv_class *,
295 int, int, int));
296 static int maybe_eliminate_biv_1 PARAMS ((const struct loop *, rtx, rtx,
297 struct iv_class *, int, rtx));
298 static int last_use_this_basic_block PARAMS ((rtx, rtx));
299 static void record_initial PARAMS ((rtx, rtx, void *));
300 static void update_reg_last_use PARAMS ((rtx, rtx));
301 static rtx next_insn_in_loop PARAMS ((const struct loop *, rtx));
302 static void load_mems_and_recount_loop_regs_set PARAMS ((const struct loop*,
303 int *));
304 static void load_mems PARAMS ((const struct loop *));
305 static int insert_loop_mem PARAMS ((rtx *, void *));
306 static int replace_loop_mem PARAMS ((rtx *, void *));
307 static int replace_loop_reg PARAMS ((rtx *, void *));
308 static void note_reg_stored PARAMS ((rtx, rtx, void *));
309 static void try_copy_prop PARAMS ((const struct loop *, rtx, unsigned int));
310 static int replace_label PARAMS ((rtx *, void *));
311 static rtx check_insn_for_givs PARAMS((struct loop *, rtx, int, int));
312 static rtx check_insn_for_bivs PARAMS((struct loop *, rtx, int, int));
314 typedef struct rtx_and_int {
315 rtx r;
316 int i;
317 } rtx_and_int;
319 typedef struct rtx_pair {
320 rtx r1;
321 rtx r2;
322 } rtx_pair;
324 /* Nonzero iff INSN is between START and END, inclusive. */
325 #define INSN_IN_RANGE_P(INSN, START, END) \
326 (INSN_UID (INSN) < max_uid_for_loop \
327 && INSN_LUID (INSN) >= INSN_LUID (START) \
328 && INSN_LUID (INSN) <= INSN_LUID (END))
330 #ifdef HAVE_decrement_and_branch_on_count
331 /* Test whether BCT applicable and safe. */
332 static void insert_bct PARAMS ((struct loop *));
334 /* Auxiliary function that inserts the BCT pattern into the loop. */
335 static void instrument_loop_bct PARAMS ((rtx, rtx, rtx));
336 #endif /* HAVE_decrement_and_branch_on_count */
338 /* Indirect_jump_in_function is computed once per function. */
339 int indirect_jump_in_function = 0;
340 static int indirect_jump_in_function_p PARAMS ((rtx));
342 static int compute_luids PARAMS ((rtx, rtx, int));
344 static int biv_elimination_giv_has_0_offset PARAMS ((struct induction *,
345 struct induction *, rtx));
347 /* Relative gain of eliminating various kinds of operations. */
348 static int add_cost;
349 #if 0
350 static int shift_cost;
351 static int mult_cost;
352 #endif
354 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
355 copy the value of the strength reduced giv to its original register. */
356 static int copy_cost;
358 /* Cost of using a register, to normalize the benefits of a giv. */
359 static int reg_address_cost;
362 void
363 init_loop ()
365 char *free_point = (char *) oballoc (1);
366 rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
368 add_cost = rtx_cost (gen_rtx_PLUS (word_mode, reg, reg), SET);
370 reg_address_cost = address_cost (reg, SImode);
372 /* We multiply by 2 to reconcile the difference in scale between
373 these two ways of computing costs. Otherwise the cost of a copy
374 will be far less than the cost of an add. */
376 copy_cost = 2 * 2;
378 /* Free the objects we just allocated. */
379 obfree (free_point);
381 /* Initialize the obstack used for rtl in product_cheap_p. */
382 gcc_obstack_init (&temp_obstack);
385 /* Compute the mapping from uids to luids.
386 LUIDs are numbers assigned to insns, like uids,
387 except that luids increase monotonically through the code.
388 Start at insn START and stop just before END. Assign LUIDs
389 starting with PREV_LUID + 1. Return the last assigned LUID + 1. */
390 static int
391 compute_luids (start, end, prev_luid)
392 rtx start, end;
393 int prev_luid;
395 int i;
396 rtx insn;
398 for (insn = start, i = prev_luid; insn != end; insn = NEXT_INSN (insn))
400 if (INSN_UID (insn) >= max_uid_for_loop)
401 continue;
402 /* Don't assign luids to line-number NOTEs, so that the distance in
403 luids between two insns is not affected by -g. */
404 if (GET_CODE (insn) != NOTE
405 || NOTE_LINE_NUMBER (insn) <= 0)
406 uid_luid[INSN_UID (insn)] = ++i;
407 else
408 /* Give a line number note the same luid as preceding insn. */
409 uid_luid[INSN_UID (insn)] = i;
411 return i + 1;
414 /* Entry point of this file. Perform loop optimization
415 on the current function. F is the first insn of the function
416 and DUMPFILE is a stream for output of a trace of actions taken
417 (or 0 if none should be output). */
419 void
420 loop_optimize (f, dumpfile, unroll_p, bct_p)
421 /* f is the first instruction of a chain of insns for one function */
422 rtx f;
423 FILE *dumpfile;
424 int unroll_p, bct_p;
426 register rtx insn;
427 register int i;
428 struct loops loops_data;
429 struct loops *loops = &loops_data;
430 struct loop_info *loops_info;
432 loop_dump_stream = dumpfile;
434 init_recog_no_volatile ();
436 max_reg_before_loop = max_reg_num ();
437 loop_max_reg = max_reg_before_loop;
439 regs_may_share = 0;
441 /* Count the number of loops. */
443 max_loop_num = 0;
444 for (insn = f; insn; insn = NEXT_INSN (insn))
446 if (GET_CODE (insn) == NOTE
447 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
448 max_loop_num++;
451 /* Don't waste time if no loops. */
452 if (max_loop_num == 0)
453 return;
455 loops->num = max_loop_num;
457 moved_once = (char *) xcalloc (max_reg_before_loop, sizeof (char));
459 /* Get size to use for tables indexed by uids.
460 Leave some space for labels allocated by find_and_verify_loops. */
461 max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
463 uid_luid = (int *) xcalloc (max_uid_for_loop, sizeof (int));
464 uid_loop = (struct loop **) xcalloc (max_uid_for_loop,
465 sizeof (struct loop *));
467 /* Allocate storage for array of loops. */
468 loops->array = (struct loop *)
469 xcalloc (loops->num, sizeof (struct loop));
471 /* Find and process each loop.
472 First, find them, and record them in order of their beginnings. */
473 find_and_verify_loops (f, loops);
475 /* Allocate and initialize auxiliary loop information. */
476 loops_info = xcalloc (loops->num, sizeof (struct loop_info));
477 for (i = 0; i < loops->num; i++)
478 loops->array[i].aux = loops_info + i;
480 /* Now find all register lifetimes. This must be done after
481 find_and_verify_loops, because it might reorder the insns in the
482 function. */
483 reg_scan (f, max_reg_before_loop, 1);
485 /* This must occur after reg_scan so that registers created by gcse
486 will have entries in the register tables.
488 We could have added a call to reg_scan after gcse_main in toplev.c,
489 but moving this call to init_alias_analysis is more efficient. */
490 init_alias_analysis ();
492 /* See if we went too far. Note that get_max_uid already returns
493 one more that the maximum uid of all insn. */
494 if (get_max_uid () > max_uid_for_loop)
495 abort ();
496 /* Now reset it to the actual size we need. See above. */
497 max_uid_for_loop = get_max_uid ();
499 /* find_and_verify_loops has already called compute_luids, but it
500 might have rearranged code afterwards, so we need to recompute
501 the luids now. */
502 max_luid = compute_luids (f, NULL_RTX, 0);
504 /* Don't leave gaps in uid_luid for insns that have been
505 deleted. It is possible that the first or last insn
506 using some register has been deleted by cross-jumping.
507 Make sure that uid_luid for that former insn's uid
508 points to the general area where that insn used to be. */
509 for (i = 0; i < max_uid_for_loop; i++)
511 uid_luid[0] = uid_luid[i];
512 if (uid_luid[0] != 0)
513 break;
515 for (i = 0; i < max_uid_for_loop; i++)
516 if (uid_luid[i] == 0)
517 uid_luid[i] = uid_luid[i - 1];
519 /* Determine if the function has indirect jump. On some systems
520 this prevents low overhead loop instructions from being used. */
521 indirect_jump_in_function = indirect_jump_in_function_p (f);
523 /* Now scan the loops, last ones first, since this means inner ones are done
524 before outer ones. */
525 for (i = max_loop_num - 1; i >= 0; i--)
527 struct loop *loop = &loops->array[i];
529 if (! loop->invalid && loop->end)
530 scan_loop (loop, unroll_p, bct_p);
533 /* If there were lexical blocks inside the loop, they have been
534 replicated. We will now have more than one NOTE_INSN_BLOCK_BEG
535 and NOTE_INSN_BLOCK_END for each such block. We must duplicate
536 the BLOCKs as well. */
537 if (write_symbols != NO_DEBUG)
538 reorder_blocks ();
540 end_alias_analysis ();
542 /* Clean up. */
543 free (moved_once);
544 free (uid_luid);
545 free (uid_loop);
546 free (loops_info);
547 free (loops->array);
550 /* Returns the next insn, in execution order, after INSN. START and
551 END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
552 respectively. LOOP->TOP, if non-NULL, is the top of the loop in the
553 insn-stream; it is used with loops that are entered near the
554 bottom. */
556 static rtx
557 next_insn_in_loop (loop, insn)
558 const struct loop *loop;
559 rtx insn;
561 insn = NEXT_INSN (insn);
563 if (insn == loop->end)
565 if (loop->top)
566 /* Go to the top of the loop, and continue there. */
567 insn = loop->top;
568 else
569 /* We're done. */
570 insn = NULL_RTX;
573 if (insn == loop->scan_start)
574 /* We're done. */
575 insn = NULL_RTX;
577 return insn;
580 /* Optimize one loop described by LOOP. */
582 /* ??? Could also move memory writes out of loops if the destination address
583 is invariant, the source is invariant, the memory write is not volatile,
584 and if we can prove that no read inside the loop can read this address
585 before the write occurs. If there is a read of this address after the
586 write, then we can also mark the memory read as invariant. */
588 static void
589 scan_loop (loop, unroll_p, bct_p)
590 struct loop *loop;
591 int unroll_p, bct_p;
593 register int i;
594 rtx loop_start = loop->start;
595 rtx loop_end = loop->end;
596 /* Additional information about the current loop being processed
597 that is used to compute the number of loop iterations for loop
598 unrolling and doloop optimization. */
599 struct loop_info *loop_info = LOOP_INFO (loop);
600 rtx p;
601 /* 1 if we are scanning insns that could be executed zero times. */
602 int maybe_never = 0;
603 /* 1 if we are scanning insns that might never be executed
604 due to a subroutine call which might exit before they are reached. */
605 int call_passed = 0;
606 /* Jump insn that enters the loop, or 0 if control drops in. */
607 rtx loop_entry_jump = 0;
608 /* Number of insns in the loop. */
609 int insn_count;
610 int in_libcall = 0;
611 int tem;
612 rtx temp, update_start, update_end;
613 /* The SET from an insn, if it is the only SET in the insn. */
614 rtx set, set1;
615 /* Chain describing insns movable in current loop. */
616 struct movable *movables = 0;
617 /* Last element in `movables' -- so we can add elements at the end. */
618 struct movable *last_movable = 0;
619 /* Ratio of extra register life span we can justify
620 for saving an instruction. More if loop doesn't call subroutines
621 since in that case saving an insn makes more difference
622 and more registers are available. */
623 int threshold;
624 /* Nonzero if we are scanning instructions in a sub-loop. */
625 int loop_depth = 0;
626 int nregs;
628 loop->top = 0;
630 /* Determine whether this loop starts with a jump down to a test at
631 the end. This will occur for a small number of loops with a test
632 that is too complex to duplicate in front of the loop.
634 We search for the first insn or label in the loop, skipping NOTEs.
635 However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
636 (because we might have a loop executed only once that contains a
637 loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
638 (in case we have a degenerate loop).
640 Note that if we mistakenly think that a loop is entered at the top
641 when, in fact, it is entered at the exit test, the only effect will be
642 slightly poorer optimization. Making the opposite error can generate
643 incorrect code. Since very few loops now start with a jump to the
644 exit test, the code here to detect that case is very conservative. */
646 for (p = NEXT_INSN (loop_start);
647 p != loop_end
648 && GET_CODE (p) != CODE_LABEL && GET_RTX_CLASS (GET_CODE (p)) != 'i'
649 && (GET_CODE (p) != NOTE
650 || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
651 && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
652 p = NEXT_INSN (p))
655 loop->scan_start = p;
657 /* Set up variables describing this loop. */
658 prescan_loop (loop);
659 threshold = (loop_info->has_call ? 1 : 2) * (1 + n_non_fixed_regs);
661 /* If loop has a jump before the first label,
662 the true entry is the target of that jump.
663 Start scan from there.
664 But record in LOOP->TOP the place where the end-test jumps
665 back to so we can scan that after the end of the loop. */
666 if (GET_CODE (p) == JUMP_INSN)
668 loop_entry_jump = p;
670 /* Loop entry must be unconditional jump (and not a RETURN) */
671 if (simplejump_p (p)
672 && JUMP_LABEL (p) != 0
673 /* Check to see whether the jump actually
674 jumps out of the loop (meaning it's no loop).
675 This case can happen for things like
676 do {..} while (0). If this label was generated previously
677 by loop, we can't tell anything about it and have to reject
678 the loop. */
679 && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, loop_end))
681 loop->top = next_label (loop->scan_start);
682 loop->scan_start = JUMP_LABEL (p);
686 /* If LOOP->SCAN_START was an insn created by loop, we don't know its luid
687 as required by loop_reg_used_before_p. So skip such loops. (This
688 test may never be true, but it's best to play it safe.)
690 Also, skip loops where we do not start scanning at a label. This
691 test also rejects loops starting with a JUMP_INSN that failed the
692 test above. */
694 if (INSN_UID (loop->scan_start) >= max_uid_for_loop
695 || GET_CODE (loop->scan_start) != CODE_LABEL)
697 if (loop_dump_stream)
698 fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
699 INSN_UID (loop_start), INSN_UID (loop_end));
700 return;
703 /* Count number of times each reg is set during this loop.
704 Set VARRAY_CHAR (may_not_optimize, I) if it is not safe to move out
705 the setting of register I. Set VARRAY_RTX (reg_single_usage, I). */
707 /* Allocate extra space for REGS that might be created by
708 load_mems. We allocate a little extra slop as well, in the hopes
709 that even after the moving of movables creates some new registers
710 we won't have to reallocate these arrays. However, we do grow
711 the arrays, if necessary, in load_mems_recount_loop_regs_set. */
712 nregs = max_reg_num () + loop_mems_idx + 16;
713 VARRAY_INT_INIT (set_in_loop, nregs, "set_in_loop");
714 VARRAY_INT_INIT (n_times_set, nregs, "n_times_set");
715 VARRAY_CHAR_INIT (may_not_optimize, nregs, "may_not_optimize");
716 VARRAY_RTX_INIT (reg_single_usage, nregs, "reg_single_usage");
718 count_loop_regs_set (loop->top ? loop->top : loop->start, loop->end,
719 may_not_optimize, reg_single_usage, &insn_count, nregs);
721 for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
723 VARRAY_CHAR (may_not_optimize, i) = 1;
724 VARRAY_INT (set_in_loop, i) = 1;
727 #ifdef AVOID_CCMODE_COPIES
728 /* Don't try to move insns which set CC registers if we should not
729 create CCmode register copies. */
730 for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
731 if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
732 VARRAY_CHAR (may_not_optimize, i) = 1;
733 #endif
735 bcopy ((char *) &set_in_loop->data,
736 (char *) &n_times_set->data, nregs * sizeof (int));
738 if (loop_dump_stream)
740 fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
741 INSN_UID (loop_start), INSN_UID (loop_end), insn_count);
742 if (loop->cont)
743 fprintf (loop_dump_stream, "Continue at insn %d.\n",
744 INSN_UID (loop->cont));
747 /* Scan through the loop finding insns that are safe to move.
748 Set set_in_loop negative for the reg being set, so that
749 this reg will be considered invariant for subsequent insns.
750 We consider whether subsequent insns use the reg
751 in deciding whether it is worth actually moving.
753 MAYBE_NEVER is nonzero if we have passed a conditional jump insn
754 and therefore it is possible that the insns we are scanning
755 would never be executed. At such times, we must make sure
756 that it is safe to execute the insn once instead of zero times.
757 When MAYBE_NEVER is 0, all insns will be executed at least once
758 so that is not a problem. */
760 for (p = next_insn_in_loop (loop, loop->scan_start);
761 p != NULL_RTX;
762 p = next_insn_in_loop (loop, p))
764 if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
765 && find_reg_note (p, REG_LIBCALL, NULL_RTX))
766 in_libcall = 1;
767 else if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
768 && find_reg_note (p, REG_RETVAL, NULL_RTX))
769 in_libcall = 0;
771 if (GET_CODE (p) == INSN
772 && (set = single_set (p))
773 && GET_CODE (SET_DEST (set)) == REG
774 && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
776 int tem1 = 0;
777 int tem2 = 0;
778 int move_insn = 0;
779 rtx src = SET_SRC (set);
780 rtx dependencies = 0;
782 /* Figure out what to use as a source of this insn. If a REG_EQUIV
783 note is given or if a REG_EQUAL note with a constant operand is
784 specified, use it as the source and mark that we should move
785 this insn by calling emit_move_insn rather that duplicating the
786 insn.
788 Otherwise, only use the REG_EQUAL contents if a REG_RETVAL note
789 is present. */
790 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
791 if (temp)
792 src = XEXP (temp, 0), move_insn = 1;
793 else
795 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
796 if (temp && CONSTANT_P (XEXP (temp, 0)))
797 src = XEXP (temp, 0), move_insn = 1;
798 if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
800 src = XEXP (temp, 0);
801 /* A libcall block can use regs that don't appear in
802 the equivalent expression. To move the libcall,
803 we must move those regs too. */
804 dependencies = libcall_other_reg (p, src);
808 /* Don't try to optimize a register that was made
809 by loop-optimization for an inner loop.
810 We don't know its life-span, so we can't compute the benefit. */
811 if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
813 else if (/* The register is used in basic blocks other
814 than the one where it is set (meaning that
815 something after this point in the loop might
816 depend on its value before the set). */
817 ! reg_in_basic_block_p (p, SET_DEST (set))
818 /* And the set is not guaranteed to be executed one
819 the loop starts, or the value before the set is
820 needed before the set occurs...
822 ??? Note we have quadratic behaviour here, mitigated
823 by the fact that the previous test will often fail for
824 large loops. Rather than re-scanning the entire loop
825 each time for register usage, we should build tables
826 of the register usage and use them here instead. */
827 && (maybe_never
828 || loop_reg_used_before_p (loop, set, p)))
829 /* It is unsafe to move the set.
831 This code used to consider it OK to move a set of a variable
832 which was not created by the user and not used in an exit test.
833 That behavior is incorrect and was removed. */
835 else if ((tem = loop_invariant_p (loop, src))
836 && (dependencies == 0
837 || (tem2 = loop_invariant_p (loop, dependencies)) != 0)
838 && (VARRAY_INT (set_in_loop,
839 REGNO (SET_DEST (set))) == 1
840 || (tem1
841 = consec_sets_invariant_p
842 (loop, SET_DEST (set),
843 VARRAY_INT (set_in_loop, REGNO (SET_DEST (set))),
844 p)))
845 /* If the insn can cause a trap (such as divide by zero),
846 can't move it unless it's guaranteed to be executed
847 once loop is entered. Even a function call might
848 prevent the trap insn from being reached
849 (since it might exit!) */
850 && ! ((maybe_never || call_passed)
851 && may_trap_p (src)))
853 register struct movable *m;
854 register int regno = REGNO (SET_DEST (set));
856 /* A potential lossage is where we have a case where two insns
857 can be combined as long as they are both in the loop, but
858 we move one of them outside the loop. For large loops,
859 this can lose. The most common case of this is the address
860 of a function being called.
862 Therefore, if this register is marked as being used exactly
863 once if we are in a loop with calls (a "large loop"), see if
864 we can replace the usage of this register with the source
865 of this SET. If we can, delete this insn.
867 Don't do this if P has a REG_RETVAL note or if we have
868 SMALL_REGISTER_CLASSES and SET_SRC is a hard register. */
870 if (loop_info->has_call
871 && VARRAY_RTX (reg_single_usage, regno) != 0
872 && VARRAY_RTX (reg_single_usage, regno) != const0_rtx
873 && REGNO_FIRST_UID (regno) == INSN_UID (p)
874 && (REGNO_LAST_UID (regno)
875 == INSN_UID (VARRAY_RTX (reg_single_usage, regno)))
876 && VARRAY_INT (set_in_loop, regno) == 1
877 && ! side_effects_p (SET_SRC (set))
878 && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
879 && (! SMALL_REGISTER_CLASSES
880 || (! (GET_CODE (SET_SRC (set)) == REG
881 && REGNO (SET_SRC (set)) < FIRST_PSEUDO_REGISTER)))
882 /* This test is not redundant; SET_SRC (set) might be
883 a call-clobbered register and the life of REGNO
884 might span a call. */
885 && ! modified_between_p (SET_SRC (set), p,
886 VARRAY_RTX
887 (reg_single_usage, regno))
888 && no_labels_between_p (p, VARRAY_RTX (reg_single_usage, regno))
889 && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
890 VARRAY_RTX
891 (reg_single_usage, regno)))
893 /* Replace any usage in a REG_EQUAL note. Must copy the
894 new source, so that we don't get rtx sharing between the
895 SET_SOURCE and REG_NOTES of insn p. */
896 REG_NOTES (VARRAY_RTX (reg_single_usage, regno))
897 = replace_rtx (REG_NOTES (VARRAY_RTX
898 (reg_single_usage, regno)),
899 SET_DEST (set), copy_rtx (SET_SRC (set)));
901 PUT_CODE (p, NOTE);
902 NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED;
903 NOTE_SOURCE_FILE (p) = 0;
904 VARRAY_INT (set_in_loop, regno) = 0;
905 continue;
908 m = (struct movable *) alloca (sizeof (struct movable));
909 m->next = 0;
910 m->insn = p;
911 m->set_src = src;
912 m->dependencies = dependencies;
913 m->set_dest = SET_DEST (set);
914 m->force = 0;
915 m->consec = VARRAY_INT (set_in_loop,
916 REGNO (SET_DEST (set))) - 1;
917 m->done = 0;
918 m->forces = 0;
919 m->partial = 0;
920 m->move_insn = move_insn;
921 m->move_insn_first = 0;
922 m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
923 m->savemode = VOIDmode;
924 m->regno = regno;
925 /* Set M->cond if either loop_invariant_p
926 or consec_sets_invariant_p returned 2
927 (only conditionally invariant). */
928 m->cond = ((tem | tem1 | tem2) > 1);
929 m->global = (uid_luid[REGNO_LAST_UID (regno)]
930 > INSN_LUID (loop_end)
931 || uid_luid[REGNO_FIRST_UID (regno)] < INSN_LUID (loop_start));
932 m->match = 0;
933 m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
934 - uid_luid[REGNO_FIRST_UID (regno)]);
935 m->savings = VARRAY_INT (n_times_set, regno);
936 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
937 m->savings += libcall_benefit (p);
938 VARRAY_INT (set_in_loop, regno) = move_insn ? -2 : -1;
939 /* Add M to the end of the chain MOVABLES. */
940 if (movables == 0)
941 movables = m;
942 else
943 last_movable->next = m;
944 last_movable = m;
946 if (m->consec > 0)
948 /* It is possible for the first instruction to have a
949 REG_EQUAL note but a non-invariant SET_SRC, so we must
950 remember the status of the first instruction in case
951 the last instruction doesn't have a REG_EQUAL note. */
952 m->move_insn_first = m->move_insn;
954 /* Skip this insn, not checking REG_LIBCALL notes. */
955 p = next_nonnote_insn (p);
956 /* Skip the consecutive insns, if there are any. */
957 p = skip_consec_insns (p, m->consec);
958 /* Back up to the last insn of the consecutive group. */
959 p = prev_nonnote_insn (p);
961 /* We must now reset m->move_insn, m->is_equiv, and possibly
962 m->set_src to correspond to the effects of all the
963 insns. */
964 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
965 if (temp)
966 m->set_src = XEXP (temp, 0), m->move_insn = 1;
967 else
969 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
970 if (temp && CONSTANT_P (XEXP (temp, 0)))
971 m->set_src = XEXP (temp, 0), m->move_insn = 1;
972 else
973 m->move_insn = 0;
976 m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
979 /* If this register is always set within a STRICT_LOW_PART
980 or set to zero, then its high bytes are constant.
981 So clear them outside the loop and within the loop
982 just load the low bytes.
983 We must check that the machine has an instruction to do so.
984 Also, if the value loaded into the register
985 depends on the same register, this cannot be done. */
986 else if (SET_SRC (set) == const0_rtx
987 && GET_CODE (NEXT_INSN (p)) == INSN
988 && (set1 = single_set (NEXT_INSN (p)))
989 && GET_CODE (set1) == SET
990 && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
991 && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
992 && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
993 == SET_DEST (set))
994 && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
996 register int regno = REGNO (SET_DEST (set));
997 if (VARRAY_INT (set_in_loop, regno) == 2)
999 register struct movable *m;
1000 m = (struct movable *) alloca (sizeof (struct movable));
1001 m->next = 0;
1002 m->insn = p;
1003 m->set_dest = SET_DEST (set);
1004 m->dependencies = 0;
1005 m->force = 0;
1006 m->consec = 0;
1007 m->done = 0;
1008 m->forces = 0;
1009 m->move_insn = 0;
1010 m->move_insn_first = 0;
1011 m->partial = 1;
1012 /* If the insn may not be executed on some cycles,
1013 we can't clear the whole reg; clear just high part.
1014 Not even if the reg is used only within this loop.
1015 Consider this:
1016 while (1)
1017 while (s != t) {
1018 if (foo ()) x = *s;
1019 use (x);
1021 Clearing x before the inner loop could clobber a value
1022 being saved from the last time around the outer loop.
1023 However, if the reg is not used outside this loop
1024 and all uses of the register are in the same
1025 basic block as the store, there is no problem.
1027 If this insn was made by loop, we don't know its
1028 INSN_LUID and hence must make a conservative
1029 assumption. */
1030 m->global = (INSN_UID (p) >= max_uid_for_loop
1031 || (uid_luid[REGNO_LAST_UID (regno)]
1032 > INSN_LUID (loop_end))
1033 || (uid_luid[REGNO_FIRST_UID (regno)]
1034 < INSN_LUID (p))
1035 || (labels_in_range_p
1036 (p, uid_luid[REGNO_FIRST_UID (regno)])));
1037 if (maybe_never && m->global)
1038 m->savemode = GET_MODE (SET_SRC (set1));
1039 else
1040 m->savemode = VOIDmode;
1041 m->regno = regno;
1042 m->cond = 0;
1043 m->match = 0;
1044 m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
1045 - uid_luid[REGNO_FIRST_UID (regno)]);
1046 m->savings = 1;
1047 VARRAY_INT (set_in_loop, regno) = -1;
1048 /* Add M to the end of the chain MOVABLES. */
1049 if (movables == 0)
1050 movables = m;
1051 else
1052 last_movable->next = m;
1053 last_movable = m;
1057 /* Past a call insn, we get to insns which might not be executed
1058 because the call might exit. This matters for insns that trap.
1059 Call insns inside a REG_LIBCALL/REG_RETVAL block always return,
1060 so they don't count. */
1061 else if (GET_CODE (p) == CALL_INSN && ! in_libcall)
1062 call_passed = 1;
1063 /* Past a label or a jump, we get to insns for which we
1064 can't count on whether or how many times they will be
1065 executed during each iteration. Therefore, we can
1066 only move out sets of trivial variables
1067 (those not used after the loop). */
1068 /* Similar code appears twice in strength_reduce. */
1069 else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
1070 /* If we enter the loop in the middle, and scan around to the
1071 beginning, don't set maybe_never for that. This must be an
1072 unconditional jump, otherwise the code at the top of the
1073 loop might never be executed. Unconditional jumps are
1074 followed a by barrier then loop end. */
1075 && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop->top
1076 && NEXT_INSN (NEXT_INSN (p)) == loop_end
1077 && simplejump_p (p)))
1078 maybe_never = 1;
1079 else if (GET_CODE (p) == NOTE)
1081 /* At the virtual top of a converted loop, insns are again known to
1082 be executed: logically, the loop begins here even though the exit
1083 code has been duplicated. */
1084 if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1085 maybe_never = call_passed = 0;
1086 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1087 loop_depth++;
1088 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1089 loop_depth--;
1093 /* If one movable subsumes another, ignore that other. */
1095 ignore_some_movables (movables);
1097 /* For each movable insn, see if the reg that it loads
1098 leads when it dies right into another conditionally movable insn.
1099 If so, record that the second insn "forces" the first one,
1100 since the second can be moved only if the first is. */
1102 force_movables (movables);
1104 /* See if there are multiple movable insns that load the same value.
1105 If there are, make all but the first point at the first one
1106 through the `match' field, and add the priorities of them
1107 all together as the priority of the first. */
1109 combine_movables (movables, nregs);
1111 /* Now consider each movable insn to decide whether it is worth moving.
1112 Store 0 in set_in_loop for each reg that is moved.
1114 Generally this increases code size, so do not move moveables when
1115 optimizing for code size. */
1117 if (! optimize_size)
1118 move_movables (loop, movables, threshold, insn_count, nregs);
1120 /* Now candidates that still are negative are those not moved.
1121 Change set_in_loop to indicate that those are not actually invariant. */
1122 for (i = 0; i < nregs; i++)
1123 if (VARRAY_INT (set_in_loop, i) < 0)
1124 VARRAY_INT (set_in_loop, i) = VARRAY_INT (n_times_set, i);
1126 /* Now that we've moved some things out of the loop, we might be able to
1127 hoist even more memory references. */
1128 load_mems_and_recount_loop_regs_set (loop, &insn_count);
1130 for (update_start = loop_start;
1131 PREV_INSN (update_start)
1132 && GET_CODE (PREV_INSN (update_start)) != CODE_LABEL;
1133 update_start = PREV_INSN (update_start))
1135 update_end = NEXT_INSN (loop_end);
1137 reg_scan_update (update_start, update_end, loop_max_reg);
1138 loop_max_reg = max_reg_num ();
1140 if (flag_strength_reduce)
1142 the_movables = movables;
1143 strength_reduce (loop, insn_count, unroll_p, bct_p);
1145 reg_scan_update (update_start, update_end, loop_max_reg);
1146 loop_max_reg = max_reg_num ();
1149 VARRAY_FREE (reg_single_usage);
1150 VARRAY_FREE (set_in_loop);
1151 VARRAY_FREE (n_times_set);
1152 VARRAY_FREE (may_not_optimize);
1155 /* Add elements to *OUTPUT to record all the pseudo-regs
1156 mentioned in IN_THIS but not mentioned in NOT_IN_THIS. */
1158 void
1159 record_excess_regs (in_this, not_in_this, output)
1160 rtx in_this, not_in_this;
1161 rtx *output;
1163 enum rtx_code code;
1164 const char *fmt;
1165 int i;
1167 code = GET_CODE (in_this);
1169 switch (code)
1171 case PC:
1172 case CC0:
1173 case CONST_INT:
1174 case CONST_DOUBLE:
1175 case CONST:
1176 case SYMBOL_REF:
1177 case LABEL_REF:
1178 return;
1180 case REG:
1181 if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1182 && ! reg_mentioned_p (in_this, not_in_this))
1183 *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1184 return;
1186 default:
1187 break;
1190 fmt = GET_RTX_FORMAT (code);
1191 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1193 int j;
1195 switch (fmt[i])
1197 case 'E':
1198 for (j = 0; j < XVECLEN (in_this, i); j++)
1199 record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1200 break;
1202 case 'e':
1203 record_excess_regs (XEXP (in_this, i), not_in_this, output);
1204 break;
1209 /* Check what regs are referred to in the libcall block ending with INSN,
1210 aside from those mentioned in the equivalent value.
1211 If there are none, return 0.
1212 If there are one or more, return an EXPR_LIST containing all of them. */
1215 libcall_other_reg (insn, equiv)
1216 rtx insn, equiv;
1218 rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1219 rtx p = XEXP (note, 0);
1220 rtx output = 0;
1222 /* First, find all the regs used in the libcall block
1223 that are not mentioned as inputs to the result. */
1225 while (p != insn)
1227 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1228 || GET_CODE (p) == CALL_INSN)
1229 record_excess_regs (PATTERN (p), equiv, &output);
1230 p = NEXT_INSN (p);
1233 return output;
1236 /* Return 1 if all uses of REG
1237 are between INSN and the end of the basic block. */
1239 static int
1240 reg_in_basic_block_p (insn, reg)
1241 rtx insn, reg;
1243 int regno = REGNO (reg);
1244 rtx p;
1246 if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1247 return 0;
1249 /* Search this basic block for the already recorded last use of the reg. */
1250 for (p = insn; p; p = NEXT_INSN (p))
1252 switch (GET_CODE (p))
1254 case NOTE:
1255 break;
1257 case INSN:
1258 case CALL_INSN:
1259 /* Ordinary insn: if this is the last use, we win. */
1260 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1261 return 1;
1262 break;
1264 case JUMP_INSN:
1265 /* Jump insn: if this is the last use, we win. */
1266 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1267 return 1;
1268 /* Otherwise, it's the end of the basic block, so we lose. */
1269 return 0;
1271 case CODE_LABEL:
1272 case BARRIER:
1273 /* It's the end of the basic block, so we lose. */
1274 return 0;
1276 default:
1277 break;
1281 /* The "last use" that was recorded can't be found after the first
1282 use. This can happen when the last use was deleted while
1283 processing an inner loop, this inner loop was then completely
1284 unrolled, and the outer loop is always exited after the inner loop,
1285 so that everything after the first use becomes a single basic block. */
1286 return 1;
1289 /* Compute the benefit of eliminating the insns in the block whose
1290 last insn is LAST. This may be a group of insns used to compute a
1291 value directly or can contain a library call. */
1293 static int
1294 libcall_benefit (last)
1295 rtx last;
1297 rtx insn;
1298 int benefit = 0;
1300 for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1301 insn != last; insn = NEXT_INSN (insn))
1303 if (GET_CODE (insn) == CALL_INSN)
1304 benefit += 10; /* Assume at least this many insns in a library
1305 routine. */
1306 else if (GET_CODE (insn) == INSN
1307 && GET_CODE (PATTERN (insn)) != USE
1308 && GET_CODE (PATTERN (insn)) != CLOBBER)
1309 benefit++;
1312 return benefit;
1315 /* Skip COUNT insns from INSN, counting library calls as 1 insn. */
1317 static rtx
1318 skip_consec_insns (insn, count)
1319 rtx insn;
1320 int count;
1322 for (; count > 0; count--)
1324 rtx temp;
1326 /* If first insn of libcall sequence, skip to end. */
1327 /* Do this at start of loop, since INSN is guaranteed to
1328 be an insn here. */
1329 if (GET_CODE (insn) != NOTE
1330 && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1331 insn = XEXP (temp, 0);
1333 do insn = NEXT_INSN (insn);
1334 while (GET_CODE (insn) == NOTE);
1337 return insn;
1340 /* Ignore any movable whose insn falls within a libcall
1341 which is part of another movable.
1342 We make use of the fact that the movable for the libcall value
1343 was made later and so appears later on the chain. */
1345 static void
1346 ignore_some_movables (movables)
1347 struct movable *movables;
1349 register struct movable *m, *m1;
1351 for (m = movables; m; m = m->next)
1353 /* Is this a movable for the value of a libcall? */
1354 rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1355 if (note)
1357 rtx insn;
1358 /* Check for earlier movables inside that range,
1359 and mark them invalid. We cannot use LUIDs here because
1360 insns created by loop.c for prior loops don't have LUIDs.
1361 Rather than reject all such insns from movables, we just
1362 explicitly check each insn in the libcall (since invariant
1363 libcalls aren't that common). */
1364 for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1365 for (m1 = movables; m1 != m; m1 = m1->next)
1366 if (m1->insn == insn)
1367 m1->done = 1;
1372 /* For each movable insn, see if the reg that it loads
1373 leads when it dies right into another conditionally movable insn.
1374 If so, record that the second insn "forces" the first one,
1375 since the second can be moved only if the first is. */
1377 static void
1378 force_movables (movables)
1379 struct movable *movables;
1381 register struct movable *m, *m1;
1382 for (m1 = movables; m1; m1 = m1->next)
1383 /* Omit this if moving just the (SET (REG) 0) of a zero-extend. */
1384 if (!m1->partial && !m1->done)
1386 int regno = m1->regno;
1387 for (m = m1->next; m; m = m->next)
1388 /* ??? Could this be a bug? What if CSE caused the
1389 register of M1 to be used after this insn?
1390 Since CSE does not update regno_last_uid,
1391 this insn M->insn might not be where it dies.
1392 But very likely this doesn't matter; what matters is
1393 that M's reg is computed from M1's reg. */
1394 if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1395 && !m->done)
1396 break;
1397 if (m != 0 && m->set_src == m1->set_dest
1398 /* If m->consec, m->set_src isn't valid. */
1399 && m->consec == 0)
1400 m = 0;
1402 /* Increase the priority of the moving the first insn
1403 since it permits the second to be moved as well. */
1404 if (m != 0)
1406 m->forces = m1;
1407 m1->lifetime += m->lifetime;
1408 m1->savings += m->savings;
1413 /* Find invariant expressions that are equal and can be combined into
1414 one register. */
1416 static void
1417 combine_movables (movables, nregs)
1418 struct movable *movables;
1419 int nregs;
1421 register struct movable *m;
1422 char *matched_regs = (char *) xmalloc (nregs);
1423 enum machine_mode mode;
1425 /* Regs that are set more than once are not allowed to match
1426 or be matched. I'm no longer sure why not. */
1427 /* Perhaps testing m->consec_sets would be more appropriate here? */
1429 for (m = movables; m; m = m->next)
1430 if (m->match == 0 && VARRAY_INT (n_times_set, m->regno) == 1 && !m->partial)
1432 register struct movable *m1;
1433 int regno = m->regno;
1435 bzero (matched_regs, nregs);
1436 matched_regs[regno] = 1;
1438 /* We want later insns to match the first one. Don't make the first
1439 one match any later ones. So start this loop at m->next. */
1440 for (m1 = m->next; m1; m1 = m1->next)
1441 if (m != m1 && m1->match == 0 && VARRAY_INT (n_times_set, m1->regno) == 1
1442 /* A reg used outside the loop mustn't be eliminated. */
1443 && !m1->global
1444 /* A reg used for zero-extending mustn't be eliminated. */
1445 && !m1->partial
1446 && (matched_regs[m1->regno]
1449 /* Can combine regs with different modes loaded from the
1450 same constant only if the modes are the same or
1451 if both are integer modes with M wider or the same
1452 width as M1. The check for integer is redundant, but
1453 safe, since the only case of differing destination
1454 modes with equal sources is when both sources are
1455 VOIDmode, i.e., CONST_INT. */
1456 (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1457 || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1458 && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1459 && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1460 >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1461 /* See if the source of M1 says it matches M. */
1462 && ((GET_CODE (m1->set_src) == REG
1463 && matched_regs[REGNO (m1->set_src)])
1464 || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1465 movables))))
1466 && ((m->dependencies == m1->dependencies)
1467 || rtx_equal_p (m->dependencies, m1->dependencies)))
1469 m->lifetime += m1->lifetime;
1470 m->savings += m1->savings;
1471 m1->done = 1;
1472 m1->match = m;
1473 matched_regs[m1->regno] = 1;
1477 /* Now combine the regs used for zero-extension.
1478 This can be done for those not marked `global'
1479 provided their lives don't overlap. */
1481 for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1482 mode = GET_MODE_WIDER_MODE (mode))
1484 register struct movable *m0 = 0;
1486 /* Combine all the registers for extension from mode MODE.
1487 Don't combine any that are used outside this loop. */
1488 for (m = movables; m; m = m->next)
1489 if (m->partial && ! m->global
1490 && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1492 register struct movable *m1;
1493 int first = uid_luid[REGNO_FIRST_UID (m->regno)];
1494 int last = uid_luid[REGNO_LAST_UID (m->regno)];
1496 if (m0 == 0)
1498 /* First one: don't check for overlap, just record it. */
1499 m0 = m;
1500 continue;
1503 /* Make sure they extend to the same mode.
1504 (Almost always true.) */
1505 if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1506 continue;
1508 /* We already have one: check for overlap with those
1509 already combined together. */
1510 for (m1 = movables; m1 != m; m1 = m1->next)
1511 if (m1 == m0 || (m1->partial && m1->match == m0))
1512 if (! (uid_luid[REGNO_FIRST_UID (m1->regno)] > last
1513 || uid_luid[REGNO_LAST_UID (m1->regno)] < first))
1514 goto overlap;
1516 /* No overlap: we can combine this with the others. */
1517 m0->lifetime += m->lifetime;
1518 m0->savings += m->savings;
1519 m->done = 1;
1520 m->match = m0;
1522 overlap: ;
1526 /* Clean up. */
1527 free (matched_regs);
1530 /* Return 1 if regs X and Y will become the same if moved. */
1532 static int
1533 regs_match_p (x, y, movables)
1534 rtx x, y;
1535 struct movable *movables;
1537 unsigned int xn = REGNO (x);
1538 unsigned int yn = REGNO (y);
1539 struct movable *mx, *my;
1541 for (mx = movables; mx; mx = mx->next)
1542 if (mx->regno == xn)
1543 break;
1545 for (my = movables; my; my = my->next)
1546 if (my->regno == yn)
1547 break;
1549 return (mx && my
1550 && ((mx->match == my->match && mx->match != 0)
1551 || mx->match == my
1552 || mx == my->match));
1555 /* Return 1 if X and Y are identical-looking rtx's.
1556 This is the Lisp function EQUAL for rtx arguments.
1558 If two registers are matching movables or a movable register and an
1559 equivalent constant, consider them equal. */
1561 static int
1562 rtx_equal_for_loop_p (x, y, movables)
1563 rtx x, y;
1564 struct movable *movables;
1566 register int i;
1567 register int j;
1568 register struct movable *m;
1569 register enum rtx_code code;
1570 register const char *fmt;
1572 if (x == y)
1573 return 1;
1574 if (x == 0 || y == 0)
1575 return 0;
1577 code = GET_CODE (x);
1579 /* If we have a register and a constant, they may sometimes be
1580 equal. */
1581 if (GET_CODE (x) == REG && VARRAY_INT (set_in_loop, REGNO (x)) == -2
1582 && CONSTANT_P (y))
1584 for (m = movables; m; m = m->next)
1585 if (m->move_insn && m->regno == REGNO (x)
1586 && rtx_equal_p (m->set_src, y))
1587 return 1;
1589 else if (GET_CODE (y) == REG && VARRAY_INT (set_in_loop, REGNO (y)) == -2
1590 && CONSTANT_P (x))
1592 for (m = movables; m; m = m->next)
1593 if (m->move_insn && m->regno == REGNO (y)
1594 && rtx_equal_p (m->set_src, x))
1595 return 1;
1598 /* Otherwise, rtx's of different codes cannot be equal. */
1599 if (code != GET_CODE (y))
1600 return 0;
1602 /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1603 (REG:SI x) and (REG:HI x) are NOT equivalent. */
1605 if (GET_MODE (x) != GET_MODE (y))
1606 return 0;
1608 /* These three types of rtx's can be compared nonrecursively. */
1609 if (code == REG)
1610 return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1612 if (code == LABEL_REF)
1613 return XEXP (x, 0) == XEXP (y, 0);
1614 if (code == SYMBOL_REF)
1615 return XSTR (x, 0) == XSTR (y, 0);
1617 /* Compare the elements. If any pair of corresponding elements
1618 fail to match, return 0 for the whole things. */
1620 fmt = GET_RTX_FORMAT (code);
1621 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1623 switch (fmt[i])
1625 case 'w':
1626 if (XWINT (x, i) != XWINT (y, i))
1627 return 0;
1628 break;
1630 case 'i':
1631 if (XINT (x, i) != XINT (y, i))
1632 return 0;
1633 break;
1635 case 'E':
1636 /* Two vectors must have the same length. */
1637 if (XVECLEN (x, i) != XVECLEN (y, i))
1638 return 0;
1640 /* And the corresponding elements must match. */
1641 for (j = 0; j < XVECLEN (x, i); j++)
1642 if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j), movables) == 0)
1643 return 0;
1644 break;
1646 case 'e':
1647 if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables) == 0)
1648 return 0;
1649 break;
1651 case 's':
1652 if (strcmp (XSTR (x, i), XSTR (y, i)))
1653 return 0;
1654 break;
1656 case 'u':
1657 /* These are just backpointers, so they don't matter. */
1658 break;
1660 case '0':
1661 break;
1663 /* It is believed that rtx's at this level will never
1664 contain anything but integers and other rtx's,
1665 except for within LABEL_REFs and SYMBOL_REFs. */
1666 default:
1667 abort ();
1670 return 1;
1673 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1674 insns in INSNS which use the reference. */
1676 static void
1677 add_label_notes (x, insns)
1678 rtx x;
1679 rtx insns;
1681 enum rtx_code code = GET_CODE (x);
1682 int i, j;
1683 const char *fmt;
1684 rtx insn;
1686 if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1688 /* This code used to ignore labels that referred to dispatch tables to
1689 avoid flow generating (slighly) worse code.
1691 We no longer ignore such label references (see LABEL_REF handling in
1692 mark_jump_label for additional information). */
1693 for (insn = insns; insn; insn = NEXT_INSN (insn))
1694 if (reg_mentioned_p (XEXP (x, 0), insn))
1695 REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_LABEL, XEXP (x, 0),
1696 REG_NOTES (insn));
1699 fmt = GET_RTX_FORMAT (code);
1700 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1702 if (fmt[i] == 'e')
1703 add_label_notes (XEXP (x, i), insns);
1704 else if (fmt[i] == 'E')
1705 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1706 add_label_notes (XVECEXP (x, i, j), insns);
1710 /* Scan MOVABLES, and move the insns that deserve to be moved.
1711 If two matching movables are combined, replace one reg with the
1712 other throughout. */
1714 static void
1715 move_movables (loop, movables, threshold, insn_count, nregs)
1716 struct loop *loop;
1717 struct movable *movables;
1718 int threshold;
1719 int insn_count;
1720 int nregs;
1722 rtx new_start = 0;
1723 register struct movable *m;
1724 register rtx p;
1725 rtx loop_start = loop->start;
1726 rtx loop_end = loop->end;
1727 /* Map of pseudo-register replacements to handle combining
1728 when we move several insns that load the same value
1729 into different pseudo-registers. */
1730 rtx *reg_map = (rtx *) xcalloc (nregs, sizeof (rtx));
1731 char *already_moved = (char *) xcalloc (nregs, sizeof (char));
1733 num_movables = 0;
1735 for (m = movables; m; m = m->next)
1737 /* Describe this movable insn. */
1739 if (loop_dump_stream)
1741 fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1742 INSN_UID (m->insn), m->regno, m->lifetime);
1743 if (m->consec > 0)
1744 fprintf (loop_dump_stream, "consec %d, ", m->consec);
1745 if (m->cond)
1746 fprintf (loop_dump_stream, "cond ");
1747 if (m->force)
1748 fprintf (loop_dump_stream, "force ");
1749 if (m->global)
1750 fprintf (loop_dump_stream, "global ");
1751 if (m->done)
1752 fprintf (loop_dump_stream, "done ");
1753 if (m->move_insn)
1754 fprintf (loop_dump_stream, "move-insn ");
1755 if (m->match)
1756 fprintf (loop_dump_stream, "matches %d ",
1757 INSN_UID (m->match->insn));
1758 if (m->forces)
1759 fprintf (loop_dump_stream, "forces %d ",
1760 INSN_UID (m->forces->insn));
1763 /* Count movables. Value used in heuristics in strength_reduce. */
1764 num_movables++;
1766 /* Ignore the insn if it's already done (it matched something else).
1767 Otherwise, see if it is now safe to move. */
1769 if (!m->done
1770 && (! m->cond
1771 || (1 == loop_invariant_p (loop, m->set_src)
1772 && (m->dependencies == 0
1773 || 1 == loop_invariant_p (loop, m->dependencies))
1774 && (m->consec == 0
1775 || 1 == consec_sets_invariant_p (loop, m->set_dest,
1776 m->consec + 1,
1777 m->insn))))
1778 && (! m->forces || m->forces->done))
1780 register int regno;
1781 register rtx p;
1782 int savings = m->savings;
1784 /* We have an insn that is safe to move.
1785 Compute its desirability. */
1787 p = m->insn;
1788 regno = m->regno;
1790 if (loop_dump_stream)
1791 fprintf (loop_dump_stream, "savings %d ", savings);
1793 if (moved_once[regno] && loop_dump_stream)
1794 fprintf (loop_dump_stream, "halved since already moved ");
1796 /* An insn MUST be moved if we already moved something else
1797 which is safe only if this one is moved too: that is,
1798 if already_moved[REGNO] is nonzero. */
1800 /* An insn is desirable to move if the new lifetime of the
1801 register is no more than THRESHOLD times the old lifetime.
1802 If it's not desirable, it means the loop is so big
1803 that moving won't speed things up much,
1804 and it is liable to make register usage worse. */
1806 /* It is also desirable to move if it can be moved at no
1807 extra cost because something else was already moved. */
1809 if (already_moved[regno]
1810 || flag_move_all_movables
1811 || (threshold * savings * m->lifetime) >=
1812 (moved_once[regno] ? insn_count * 2 : insn_count)
1813 || (m->forces && m->forces->done
1814 && VARRAY_INT (n_times_set, m->forces->regno) == 1))
1816 int count;
1817 register struct movable *m1;
1818 rtx first = NULL_RTX;
1820 /* Now move the insns that set the reg. */
1822 if (m->partial && m->match)
1824 rtx newpat, i1;
1825 rtx r1, r2;
1826 /* Find the end of this chain of matching regs.
1827 Thus, we load each reg in the chain from that one reg.
1828 And that reg is loaded with 0 directly,
1829 since it has ->match == 0. */
1830 for (m1 = m; m1->match; m1 = m1->match);
1831 newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1832 SET_DEST (PATTERN (m1->insn)));
1833 i1 = emit_insn_before (newpat, loop_start);
1835 /* Mark the moved, invariant reg as being allowed to
1836 share a hard reg with the other matching invariant. */
1837 REG_NOTES (i1) = REG_NOTES (m->insn);
1838 r1 = SET_DEST (PATTERN (m->insn));
1839 r2 = SET_DEST (PATTERN (m1->insn));
1840 regs_may_share
1841 = gen_rtx_EXPR_LIST (VOIDmode, r1,
1842 gen_rtx_EXPR_LIST (VOIDmode, r2,
1843 regs_may_share));
1844 delete_insn (m->insn);
1846 if (new_start == 0)
1847 new_start = i1;
1849 if (loop_dump_stream)
1850 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1852 /* If we are to re-generate the item being moved with a
1853 new move insn, first delete what we have and then emit
1854 the move insn before the loop. */
1855 else if (m->move_insn)
1857 rtx i1, temp;
1859 for (count = m->consec; count >= 0; count--)
1861 /* If this is the first insn of a library call sequence,
1862 skip to the end. */
1863 if (GET_CODE (p) != NOTE
1864 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1865 p = XEXP (temp, 0);
1867 /* If this is the last insn of a libcall sequence, then
1868 delete every insn in the sequence except the last.
1869 The last insn is handled in the normal manner. */
1870 if (GET_CODE (p) != NOTE
1871 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1873 temp = XEXP (temp, 0);
1874 while (temp != p)
1875 temp = delete_insn (temp);
1878 temp = p;
1879 p = delete_insn (p);
1881 /* simplify_giv_expr expects that it can walk the insns
1882 at m->insn forwards and see this old sequence we are
1883 tossing here. delete_insn does preserve the next
1884 pointers, but when we skip over a NOTE we must fix
1885 it up. Otherwise that code walks into the non-deleted
1886 insn stream. */
1887 while (p && GET_CODE (p) == NOTE)
1888 p = NEXT_INSN (temp) = NEXT_INSN (p);
1891 start_sequence ();
1892 emit_move_insn (m->set_dest, m->set_src);
1893 temp = get_insns ();
1894 end_sequence ();
1896 add_label_notes (m->set_src, temp);
1898 i1 = emit_insns_before (temp, loop_start);
1899 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
1900 REG_NOTES (i1)
1901 = gen_rtx_EXPR_LIST (m->is_equiv ? REG_EQUIV : REG_EQUAL,
1902 m->set_src, REG_NOTES (i1));
1904 if (loop_dump_stream)
1905 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1907 /* The more regs we move, the less we like moving them. */
1908 threshold -= 3;
1910 else
1912 for (count = m->consec; count >= 0; count--)
1914 rtx i1, temp;
1916 /* If first insn of libcall sequence, skip to end. */
1917 /* Do this at start of loop, since p is guaranteed to
1918 be an insn here. */
1919 if (GET_CODE (p) != NOTE
1920 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1921 p = XEXP (temp, 0);
1923 /* If last insn of libcall sequence, move all
1924 insns except the last before the loop. The last
1925 insn is handled in the normal manner. */
1926 if (GET_CODE (p) != NOTE
1927 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1929 rtx fn_address = 0;
1930 rtx fn_reg = 0;
1931 rtx fn_address_insn = 0;
1933 first = 0;
1934 for (temp = XEXP (temp, 0); temp != p;
1935 temp = NEXT_INSN (temp))
1937 rtx body;
1938 rtx n;
1939 rtx next;
1941 if (GET_CODE (temp) == NOTE)
1942 continue;
1944 body = PATTERN (temp);
1946 /* Find the next insn after TEMP,
1947 not counting USE or NOTE insns. */
1948 for (next = NEXT_INSN (temp); next != p;
1949 next = NEXT_INSN (next))
1950 if (! (GET_CODE (next) == INSN
1951 && GET_CODE (PATTERN (next)) == USE)
1952 && GET_CODE (next) != NOTE)
1953 break;
1955 /* If that is the call, this may be the insn
1956 that loads the function address.
1958 Extract the function address from the insn
1959 that loads it into a register.
1960 If this insn was cse'd, we get incorrect code.
1962 So emit a new move insn that copies the
1963 function address into the register that the
1964 call insn will use. flow.c will delete any
1965 redundant stores that we have created. */
1966 if (GET_CODE (next) == CALL_INSN
1967 && GET_CODE (body) == SET
1968 && GET_CODE (SET_DEST (body)) == REG
1969 && (n = find_reg_note (temp, REG_EQUAL,
1970 NULL_RTX)))
1972 fn_reg = SET_SRC (body);
1973 if (GET_CODE (fn_reg) != REG)
1974 fn_reg = SET_DEST (body);
1975 fn_address = XEXP (n, 0);
1976 fn_address_insn = temp;
1978 /* We have the call insn.
1979 If it uses the register we suspect it might,
1980 load it with the correct address directly. */
1981 if (GET_CODE (temp) == CALL_INSN
1982 && fn_address != 0
1983 && reg_referenced_p (fn_reg, body))
1984 emit_insn_after (gen_move_insn (fn_reg,
1985 fn_address),
1986 fn_address_insn);
1988 if (GET_CODE (temp) == CALL_INSN)
1990 i1 = emit_call_insn_before (body, loop_start);
1991 /* Because the USAGE information potentially
1992 contains objects other than hard registers
1993 we need to copy it. */
1994 if (CALL_INSN_FUNCTION_USAGE (temp))
1995 CALL_INSN_FUNCTION_USAGE (i1)
1996 = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
1998 else
1999 i1 = emit_insn_before (body, loop_start);
2000 if (first == 0)
2001 first = i1;
2002 if (temp == fn_address_insn)
2003 fn_address_insn = i1;
2004 REG_NOTES (i1) = REG_NOTES (temp);
2005 delete_insn (temp);
2007 if (new_start == 0)
2008 new_start = first;
2010 if (m->savemode != VOIDmode)
2012 /* P sets REG to zero; but we should clear only
2013 the bits that are not covered by the mode
2014 m->savemode. */
2015 rtx reg = m->set_dest;
2016 rtx sequence;
2017 rtx tem;
2019 start_sequence ();
2020 tem = expand_binop
2021 (GET_MODE (reg), and_optab, reg,
2022 GEN_INT ((((HOST_WIDE_INT) 1
2023 << GET_MODE_BITSIZE (m->savemode)))
2024 - 1),
2025 reg, 1, OPTAB_LIB_WIDEN);
2026 if (tem == 0)
2027 abort ();
2028 if (tem != reg)
2029 emit_move_insn (reg, tem);
2030 sequence = gen_sequence ();
2031 end_sequence ();
2032 i1 = emit_insn_before (sequence, loop_start);
2034 else if (GET_CODE (p) == CALL_INSN)
2036 i1 = emit_call_insn_before (PATTERN (p), loop_start);
2037 /* Because the USAGE information potentially
2038 contains objects other than hard registers
2039 we need to copy it. */
2040 if (CALL_INSN_FUNCTION_USAGE (p))
2041 CALL_INSN_FUNCTION_USAGE (i1)
2042 = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2044 else if (count == m->consec && m->move_insn_first)
2046 /* The SET_SRC might not be invariant, so we must
2047 use the REG_EQUAL note. */
2048 start_sequence ();
2049 emit_move_insn (m->set_dest, m->set_src);
2050 temp = get_insns ();
2051 end_sequence ();
2053 add_label_notes (m->set_src, temp);
2055 i1 = emit_insns_before (temp, loop_start);
2056 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2057 REG_NOTES (i1)
2058 = gen_rtx_EXPR_LIST ((m->is_equiv ? REG_EQUIV
2059 : REG_EQUAL),
2060 m->set_src, REG_NOTES (i1));
2062 else
2063 i1 = emit_insn_before (PATTERN (p), loop_start);
2065 if (REG_NOTES (i1) == 0)
2067 REG_NOTES (i1) = REG_NOTES (p);
2069 /* If there is a REG_EQUAL note present whose value
2070 is not loop invariant, then delete it, since it
2071 may cause problems with later optimization passes.
2072 It is possible for cse to create such notes
2073 like this as a result of record_jump_cond. */
2075 if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2076 && ! loop_invariant_p (loop, XEXP (temp, 0)))
2077 remove_note (i1, temp);
2080 if (new_start == 0)
2081 new_start = i1;
2083 if (loop_dump_stream)
2084 fprintf (loop_dump_stream, " moved to %d",
2085 INSN_UID (i1));
2087 /* If library call, now fix the REG_NOTES that contain
2088 insn pointers, namely REG_LIBCALL on FIRST
2089 and REG_RETVAL on I1. */
2090 if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2092 XEXP (temp, 0) = first;
2093 temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2094 XEXP (temp, 0) = i1;
2097 temp = p;
2098 delete_insn (p);
2099 p = NEXT_INSN (p);
2101 /* simplify_giv_expr expects that it can walk the insns
2102 at m->insn forwards and see this old sequence we are
2103 tossing here. delete_insn does preserve the next
2104 pointers, but when we skip over a NOTE we must fix
2105 it up. Otherwise that code walks into the non-deleted
2106 insn stream. */
2107 while (p && GET_CODE (p) == NOTE)
2108 p = NEXT_INSN (temp) = NEXT_INSN (p);
2111 /* The more regs we move, the less we like moving them. */
2112 threshold -= 3;
2115 /* Any other movable that loads the same register
2116 MUST be moved. */
2117 already_moved[regno] = 1;
2119 /* This reg has been moved out of one loop. */
2120 moved_once[regno] = 1;
2122 /* The reg set here is now invariant. */
2123 if (! m->partial)
2124 VARRAY_INT (set_in_loop, regno) = 0;
2126 m->done = 1;
2128 /* Change the length-of-life info for the register
2129 to say it lives at least the full length of this loop.
2130 This will help guide optimizations in outer loops. */
2132 if (uid_luid[REGNO_FIRST_UID (regno)] > INSN_LUID (loop_start))
2133 /* This is the old insn before all the moved insns.
2134 We can't use the moved insn because it is out of range
2135 in uid_luid. Only the old insns have luids. */
2136 REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2137 if (uid_luid[REGNO_LAST_UID (regno)] < INSN_LUID (loop_end))
2138 REGNO_LAST_UID (regno) = INSN_UID (loop_end);
2140 /* Combine with this moved insn any other matching movables. */
2142 if (! m->partial)
2143 for (m1 = movables; m1; m1 = m1->next)
2144 if (m1->match == m)
2146 rtx temp;
2148 /* Schedule the reg loaded by M1
2149 for replacement so that shares the reg of M.
2150 If the modes differ (only possible in restricted
2151 circumstances, make a SUBREG.
2153 Note this assumes that the target dependent files
2154 treat REG and SUBREG equally, including within
2155 GO_IF_LEGITIMATE_ADDRESS and in all the
2156 predicates since we never verify that replacing the
2157 original register with a SUBREG results in a
2158 recognizable insn. */
2159 if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2160 reg_map[m1->regno] = m->set_dest;
2161 else
2162 reg_map[m1->regno]
2163 = gen_lowpart_common (GET_MODE (m1->set_dest),
2164 m->set_dest);
2166 /* Get rid of the matching insn
2167 and prevent further processing of it. */
2168 m1->done = 1;
2170 /* if library call, delete all insn except last, which
2171 is deleted below */
2172 if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2173 NULL_RTX)))
2175 for (temp = XEXP (temp, 0); temp != m1->insn;
2176 temp = NEXT_INSN (temp))
2177 delete_insn (temp);
2179 delete_insn (m1->insn);
2181 /* Any other movable that loads the same register
2182 MUST be moved. */
2183 already_moved[m1->regno] = 1;
2185 /* The reg merged here is now invariant,
2186 if the reg it matches is invariant. */
2187 if (! m->partial)
2188 VARRAY_INT (set_in_loop, m1->regno) = 0;
2191 else if (loop_dump_stream)
2192 fprintf (loop_dump_stream, "not desirable");
2194 else if (loop_dump_stream && !m->match)
2195 fprintf (loop_dump_stream, "not safe");
2197 if (loop_dump_stream)
2198 fprintf (loop_dump_stream, "\n");
2201 if (new_start == 0)
2202 new_start = loop_start;
2204 /* Go through all the instructions in the loop, making
2205 all the register substitutions scheduled in REG_MAP. */
2206 for (p = new_start; p != loop_end; p = NEXT_INSN (p))
2207 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
2208 || GET_CODE (p) == CALL_INSN)
2210 replace_regs (PATTERN (p), reg_map, nregs, 0);
2211 replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2212 INSN_CODE (p) = -1;
2215 /* Clean up. */
2216 free (reg_map);
2217 free (already_moved);
2220 #if 0
2221 /* Scan X and replace the address of any MEM in it with ADDR.
2222 REG is the address that MEM should have before the replacement. */
2224 static void
2225 replace_call_address (x, reg, addr)
2226 rtx x, reg, addr;
2228 register enum rtx_code code;
2229 register int i;
2230 register const char *fmt;
2232 if (x == 0)
2233 return;
2234 code = GET_CODE (x);
2235 switch (code)
2237 case PC:
2238 case CC0:
2239 case CONST_INT:
2240 case CONST_DOUBLE:
2241 case CONST:
2242 case SYMBOL_REF:
2243 case LABEL_REF:
2244 case REG:
2245 return;
2247 case SET:
2248 /* Short cut for very common case. */
2249 replace_call_address (XEXP (x, 1), reg, addr);
2250 return;
2252 case CALL:
2253 /* Short cut for very common case. */
2254 replace_call_address (XEXP (x, 0), reg, addr);
2255 return;
2257 case MEM:
2258 /* If this MEM uses a reg other than the one we expected,
2259 something is wrong. */
2260 if (XEXP (x, 0) != reg)
2261 abort ();
2262 XEXP (x, 0) = addr;
2263 return;
2265 default:
2266 break;
2269 fmt = GET_RTX_FORMAT (code);
2270 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2272 if (fmt[i] == 'e')
2273 replace_call_address (XEXP (x, i), reg, addr);
2274 else if (fmt[i] == 'E')
2276 register int j;
2277 for (j = 0; j < XVECLEN (x, i); j++)
2278 replace_call_address (XVECEXP (x, i, j), reg, addr);
2282 #endif
2284 /* Return the number of memory refs to addresses that vary
2285 in the rtx X. */
2287 static int
2288 count_nonfixed_reads (loop, x)
2289 const struct loop *loop;
2290 rtx x;
2292 register enum rtx_code code;
2293 register int i;
2294 register const char *fmt;
2295 int value;
2297 if (x == 0)
2298 return 0;
2300 code = GET_CODE (x);
2301 switch (code)
2303 case PC:
2304 case CC0:
2305 case CONST_INT:
2306 case CONST_DOUBLE:
2307 case CONST:
2308 case SYMBOL_REF:
2309 case LABEL_REF:
2310 case REG:
2311 return 0;
2313 case MEM:
2314 return ((loop_invariant_p (loop, XEXP (x, 0)) != 1)
2315 + count_nonfixed_reads (loop, XEXP (x, 0)));
2317 default:
2318 break;
2321 value = 0;
2322 fmt = GET_RTX_FORMAT (code);
2323 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2325 if (fmt[i] == 'e')
2326 value += count_nonfixed_reads (loop, XEXP (x, i));
2327 if (fmt[i] == 'E')
2329 register int j;
2330 for (j = 0; j < XVECLEN (x, i); j++)
2331 value += count_nonfixed_reads (loop, XVECEXP (x, i, j));
2334 return value;
2338 #if 0
2339 /* P is an instruction that sets a register to the result of a ZERO_EXTEND.
2340 Replace it with an instruction to load just the low bytes
2341 if the machine supports such an instruction,
2342 and insert above LOOP_START an instruction to clear the register. */
2344 static void
2345 constant_high_bytes (p, loop_start)
2346 rtx p, loop_start;
2348 register rtx new;
2349 register int insn_code_number;
2351 /* Try to change (SET (REG ...) (ZERO_EXTEND (..:B ...)))
2352 to (SET (STRICT_LOW_PART (SUBREG:B (REG...))) ...). */
2355 = gen_rtx_SET
2356 (VOIDmode,
2357 gen_rtx_STRICT_LOW_PART
2358 (VOIDmode,
2359 gen_rtx_SUBREG (GET_MODE (XEXP (SET_SRC (PATTERN (p)), 0)),
2360 SET_DEST (PATTERN (p)), 0)),
2361 XEXP (SET_SRC (PATTERN (p)), 0));
2363 insn_code_number = recog (new, p);
2365 if (insn_code_number)
2367 register int i;
2369 /* Clear destination register before the loop. */
2370 emit_insn_before (gen_rtx_SET (VOIDmode,
2371 SET_DEST (PATTERN (p)), const0_rtx),
2372 loop_start);
2374 /* Inside the loop, just load the low part. */
2375 PATTERN (p) = new;
2378 #endif
2380 /* Scan a loop setting the elements `cont', `vtop', `loops_enclosed',
2381 `has_call', `has_volatile', and `has_tablejump' within LOOP.
2382 Set the global variables `unknown_address_altered',
2383 `unknown_constant_address_altered', and `num_mem_sets'. Also, fill
2384 in the array `loop_mems' and the list `loop_store_mems'. */
2386 static void
2387 prescan_loop (loop)
2388 struct loop *loop;
2390 register int level = 1;
2391 rtx insn;
2392 struct loop_info *loop_info = LOOP_INFO (loop);
2393 rtx start = loop->start;
2394 rtx end = loop->end;
2395 /* The label after END. Jumping here is just like falling off the
2396 end of the loop. We use next_nonnote_insn instead of next_label
2397 as a hedge against the (pathological) case where some actual insn
2398 might end up between the two. */
2399 rtx exit_target = next_nonnote_insn (end);
2401 loop_info->has_indirect_jump = indirect_jump_in_function;
2402 loop_info->has_call = 0;
2403 loop_info->has_volatile = 0;
2404 loop_info->has_tablejump = 0;
2405 loop_info->has_multiple_exit_targets = 0;
2406 loop->cont = 0;
2407 loop->vtop = 0;
2408 loop->level = 1;
2410 unknown_address_altered = 0;
2411 unknown_constant_address_altered = 0;
2412 loop_store_mems = NULL_RTX;
2413 first_loop_store_insn = NULL_RTX;
2414 loop_mems_idx = 0;
2415 num_mem_sets = 0;
2417 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2418 insn = NEXT_INSN (insn))
2420 if (GET_CODE (insn) == NOTE)
2422 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2424 ++level;
2425 /* Count number of loops contained in this one. */
2426 loop->level++;
2428 else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2430 --level;
2431 if (level == 0)
2433 end = insn;
2434 break;
2437 else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_CONT)
2439 if (level == 1)
2440 loop->cont = insn;
2442 else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_VTOP)
2444 /* If there is a NOTE_INSN_LOOP_VTOP, then this is a for
2445 or while style loop, with a loop exit test at the
2446 start. Thus, we can assume that the loop condition
2447 was true when the loop was entered. */
2448 if (level == 1)
2449 loop->vtop = insn;
2452 else if (GET_CODE (insn) == CALL_INSN)
2454 if (! CONST_CALL_P (insn))
2455 unknown_address_altered = 1;
2456 loop_info->has_call = 1;
2458 else if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
2460 rtx label1 = NULL_RTX;
2461 rtx label2 = NULL_RTX;
2463 if (volatile_refs_p (PATTERN (insn)))
2464 loop_info->has_volatile = 1;
2466 if (GET_CODE (insn) == JUMP_INSN
2467 && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2468 || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2469 loop_info->has_tablejump = 1;
2471 note_stores (PATTERN (insn), note_addr_stored, NULL);
2472 if (! first_loop_store_insn && loop_store_mems)
2473 first_loop_store_insn = insn;
2475 if (! loop_info->has_multiple_exit_targets
2476 && GET_CODE (insn) == JUMP_INSN
2477 && GET_CODE (PATTERN (insn)) == SET
2478 && SET_DEST (PATTERN (insn)) == pc_rtx)
2480 if (GET_CODE (SET_SRC (PATTERN (insn))) == IF_THEN_ELSE)
2482 label1 = XEXP (SET_SRC (PATTERN (insn)), 1);
2483 label2 = XEXP (SET_SRC (PATTERN (insn)), 2);
2485 else
2487 label1 = SET_SRC (PATTERN (insn));
2490 do {
2491 if (label1 && label1 != pc_rtx)
2493 if (GET_CODE (label1) != LABEL_REF)
2495 /* Something tricky. */
2496 loop_info->has_multiple_exit_targets = 1;
2497 break;
2499 else if (XEXP (label1, 0) != exit_target
2500 && LABEL_OUTSIDE_LOOP_P (label1))
2502 /* A jump outside the current loop. */
2503 loop_info->has_multiple_exit_targets = 1;
2504 break;
2508 label1 = label2;
2509 label2 = NULL_RTX;
2510 } while (label1);
2513 else if (GET_CODE (insn) == RETURN)
2514 loop_info->has_multiple_exit_targets = 1;
2517 /* Now, rescan the loop, setting up the LOOP_MEMS array. */
2518 if (/* We can't tell what MEMs are aliased by what. */
2519 ! unknown_address_altered
2520 /* An exception thrown by a called function might land us
2521 anywhere. */
2522 && ! loop_info->has_call
2523 /* We don't want loads for MEMs moved to a location before the
2524 one at which their stack memory becomes allocated. (Note
2525 that this is not a problem for malloc, etc., since those
2526 require actual function calls. */
2527 && ! current_function_calls_alloca
2528 /* There are ways to leave the loop other than falling off the
2529 end. */
2530 && ! loop_info->has_multiple_exit_targets)
2531 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2532 insn = NEXT_INSN (insn))
2533 for_each_rtx (&insn, insert_loop_mem, 0);
2536 /* LOOP->CONT_DOMINATOR is now the last label between the loop start
2537 and the continue note that is a the destination of a (cond)jump after
2538 the continue note. If there is any (cond)jump between the loop start
2539 and what we have so far as LOOP->CONT_DOMINATOR that has a
2540 target between LOOP->DOMINATOR and the continue note, move
2541 LOOP->CONT_DOMINATOR forward to that label; if a jump's
2542 destination cannot be determined, clear LOOP->CONT_DOMINATOR. */
2544 static void
2545 verify_dominator (loop)
2546 struct loop *loop;
2548 rtx insn;
2550 if (! loop->cont_dominator)
2551 /* This can happen for an empty loop, e.g. in
2552 gcc.c-torture/compile/920410-2.c */
2553 return;
2554 if (loop->cont_dominator == const0_rtx)
2556 loop->cont_dominator = 0;
2557 return;
2559 for (insn = loop->start; insn != loop->cont_dominator;
2560 insn = NEXT_INSN (insn))
2562 if (GET_CODE (insn) == JUMP_INSN
2563 && GET_CODE (PATTERN (insn)) != RETURN)
2565 rtx label = JUMP_LABEL (insn);
2566 int label_luid;
2568 /* If it is not a jump we can easily understand or for
2569 which we do not have jump target information in the JUMP_LABEL
2570 field (consider ADDR_VEC and ADDR_DIFF_VEC insns), then clear
2571 LOOP->CONT_DOMINATOR. */
2572 if ((! condjump_p (insn)
2573 && ! condjump_in_parallel_p (insn))
2574 || label == NULL_RTX)
2576 loop->cont_dominator = NULL_RTX;
2577 return;
2580 label_luid = INSN_LUID (label);
2581 if (label_luid < INSN_LUID (loop->cont)
2582 && (label_luid
2583 > INSN_LUID (loop->cont)))
2584 loop->cont_dominator = label;
2589 /* Scan the function looking for loops. Record the start and end of each loop.
2590 Also mark as invalid loops any loops that contain a setjmp or are branched
2591 to from outside the loop. */
2593 static void
2594 find_and_verify_loops (f, loops)
2595 rtx f;
2596 struct loops *loops;
2598 rtx insn;
2599 rtx label;
2600 int num_loops;
2601 struct loop *current_loop;
2602 struct loop *next_loop;
2603 struct loop *loop;
2605 num_loops = loops->num;
2607 compute_luids (f, NULL_RTX, 0);
2609 /* If there are jumps to undefined labels,
2610 treat them as jumps out of any/all loops.
2611 This also avoids writing past end of tables when there are no loops. */
2612 uid_loop[0] = NULL;
2614 /* Find boundaries of loops, mark which loops are contained within
2615 loops, and invalidate loops that have setjmp. */
2617 num_loops = 0;
2618 current_loop = NULL;
2619 for (insn = f; insn; insn = NEXT_INSN (insn))
2621 if (GET_CODE (insn) == NOTE)
2622 switch (NOTE_LINE_NUMBER (insn))
2624 case NOTE_INSN_LOOP_BEG:
2625 next_loop = loops->array + num_loops;
2626 next_loop->num = num_loops;
2627 num_loops++;
2628 next_loop->start = insn;
2629 next_loop->outer = current_loop;
2630 current_loop = next_loop;
2631 break;
2633 case NOTE_INSN_SETJMP:
2634 /* In this case, we must invalidate our current loop and any
2635 enclosing loop. */
2636 for (loop = current_loop; loop; loop = loop->outer)
2638 loop->invalid = 1;
2639 if (loop_dump_stream)
2640 fprintf (loop_dump_stream,
2641 "\nLoop at %d ignored due to setjmp.\n",
2642 INSN_UID (loop->start));
2644 break;
2646 case NOTE_INSN_LOOP_CONT:
2647 current_loop->cont = insn;
2648 break;
2649 case NOTE_INSN_LOOP_END:
2650 if (! current_loop)
2651 abort ();
2653 current_loop->end = insn;
2654 verify_dominator (current_loop);
2655 current_loop = current_loop->outer;
2656 break;
2658 default:
2659 break;
2661 /* If for any loop, this is a jump insn between the NOTE_INSN_LOOP_CONT
2662 and NOTE_INSN_LOOP_END notes, update loop->dominator. */
2663 else if (GET_CODE (insn) == JUMP_INSN
2664 && GET_CODE (PATTERN (insn)) != RETURN
2665 && current_loop)
2667 rtx label = JUMP_LABEL (insn);
2669 if (! condjump_p (insn) && ! condjump_in_parallel_p (insn))
2670 label = NULL_RTX;
2672 loop = current_loop;
2675 /* First see if we care about this loop. */
2676 if (loop->cont && loop->cont_dominator != const0_rtx)
2678 /* If the jump destination is not known, invalidate
2679 loop->const_dominator. */
2680 if (! label)
2681 loop->cont_dominator = const0_rtx;
2682 else
2683 /* Check if the destination is between loop start and
2684 cont. */
2685 if ((INSN_LUID (label)
2686 < INSN_LUID (loop->cont))
2687 && (INSN_LUID (label)
2688 > INSN_LUID (loop->start))
2689 /* And if there is no later destination already
2690 recorded. */
2691 && (! loop->cont_dominator
2692 || (INSN_LUID (label)
2693 > INSN_LUID (loop->cont_dominator))))
2694 loop->cont_dominator = label;
2696 loop = loop->outer;
2698 while (loop);
2701 /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2702 enclosing loop, but this doesn't matter. */
2703 uid_loop[INSN_UID (insn)] = current_loop;
2706 /* Any loop containing a label used in an initializer must be invalidated,
2707 because it can be jumped into from anywhere. */
2709 for (label = forced_labels; label; label = XEXP (label, 1))
2711 for (loop = uid_loop[INSN_UID (XEXP (label, 0))];
2712 loop; loop = loop->outer)
2713 loop->invalid = 1;
2716 /* Any loop containing a label used for an exception handler must be
2717 invalidated, because it can be jumped into from anywhere. */
2719 for (label = exception_handler_labels; label; label = XEXP (label, 1))
2721 for (loop = uid_loop[INSN_UID (XEXP (label, 0))];
2722 loop; loop = loop->outer)
2723 loop->invalid = 1;
2726 /* Now scan all insn's in the function. If any JUMP_INSN branches into a
2727 loop that it is not contained within, that loop is marked invalid.
2728 If any INSN or CALL_INSN uses a label's address, then the loop containing
2729 that label is marked invalid, because it could be jumped into from
2730 anywhere.
2732 Also look for blocks of code ending in an unconditional branch that
2733 exits the loop. If such a block is surrounded by a conditional
2734 branch around the block, move the block elsewhere (see below) and
2735 invert the jump to point to the code block. This may eliminate a
2736 label in our loop and will simplify processing by both us and a
2737 possible second cse pass. */
2739 for (insn = f; insn; insn = NEXT_INSN (insn))
2740 if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
2742 struct loop *this_loop = uid_loop[INSN_UID (insn)];
2744 if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2746 rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2747 if (note)
2749 for (loop = uid_loop[INSN_UID (XEXP (note, 0))];
2750 loop; loop = loop->outer)
2751 loop->invalid = 1;
2755 if (GET_CODE (insn) != JUMP_INSN)
2756 continue;
2758 mark_loop_jump (PATTERN (insn), this_loop);
2760 /* See if this is an unconditional branch outside the loop. */
2761 if (this_loop
2762 && (GET_CODE (PATTERN (insn)) == RETURN
2763 || (simplejump_p (insn)
2764 && (uid_loop[INSN_UID (JUMP_LABEL (insn))]
2765 != this_loop)))
2766 && get_max_uid () < max_uid_for_loop)
2768 rtx p;
2769 rtx our_next = next_real_insn (insn);
2770 rtx last_insn_to_move = NEXT_INSN (insn);
2771 struct loop *dest_loop;
2772 struct loop *outer_loop = NULL;
2774 /* Go backwards until we reach the start of the loop, a label,
2775 or a JUMP_INSN. */
2776 for (p = PREV_INSN (insn);
2777 GET_CODE (p) != CODE_LABEL
2778 && ! (GET_CODE (p) == NOTE
2779 && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2780 && GET_CODE (p) != JUMP_INSN;
2781 p = PREV_INSN (p))
2784 /* Check for the case where we have a jump to an inner nested
2785 loop, and do not perform the optimization in that case. */
2787 if (JUMP_LABEL (insn))
2789 dest_loop = uid_loop[INSN_UID (JUMP_LABEL (insn))];
2790 if (dest_loop)
2792 for (outer_loop = dest_loop; outer_loop;
2793 outer_loop = outer_loop->outer)
2794 if (outer_loop == this_loop)
2795 break;
2799 /* Make sure that the target of P is within the current loop. */
2801 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2802 && uid_loop[INSN_UID (JUMP_LABEL (p))] != this_loop)
2803 outer_loop = this_loop;
2805 /* If we stopped on a JUMP_INSN to the next insn after INSN,
2806 we have a block of code to try to move.
2808 We look backward and then forward from the target of INSN
2809 to find a BARRIER at the same loop depth as the target.
2810 If we find such a BARRIER, we make a new label for the start
2811 of the block, invert the jump in P and point it to that label,
2812 and move the block of code to the spot we found. */
2814 if (! outer_loop
2815 && GET_CODE (p) == JUMP_INSN
2816 && JUMP_LABEL (p) != 0
2817 /* Just ignore jumps to labels that were never emitted.
2818 These always indicate compilation errors. */
2819 && INSN_UID (JUMP_LABEL (p)) != 0
2820 && condjump_p (p)
2821 && ! simplejump_p (p)
2822 && next_real_insn (JUMP_LABEL (p)) == our_next
2823 /* If it's not safe to move the sequence, then we
2824 mustn't try. */
2825 && insns_safe_to_move_p (p, NEXT_INSN (insn),
2826 &last_insn_to_move))
2828 rtx target
2829 = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2830 struct loop *target_loop = uid_loop[INSN_UID (target)];
2831 rtx loc, loc2;
2833 for (loc = target; loc; loc = PREV_INSN (loc))
2834 if (GET_CODE (loc) == BARRIER
2835 /* Don't move things inside a tablejump. */
2836 && ((loc2 = next_nonnote_insn (loc)) == 0
2837 || GET_CODE (loc2) != CODE_LABEL
2838 || (loc2 = next_nonnote_insn (loc2)) == 0
2839 || GET_CODE (loc2) != JUMP_INSN
2840 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2841 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2842 && uid_loop[INSN_UID (loc)] == target_loop)
2843 break;
2845 if (loc == 0)
2846 for (loc = target; loc; loc = NEXT_INSN (loc))
2847 if (GET_CODE (loc) == BARRIER
2848 /* Don't move things inside a tablejump. */
2849 && ((loc2 = next_nonnote_insn (loc)) == 0
2850 || GET_CODE (loc2) != CODE_LABEL
2851 || (loc2 = next_nonnote_insn (loc2)) == 0
2852 || GET_CODE (loc2) != JUMP_INSN
2853 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2854 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2855 && uid_loop[INSN_UID (loc)] == target_loop)
2856 break;
2858 if (loc)
2860 rtx cond_label = JUMP_LABEL (p);
2861 rtx new_label = get_label_after (p);
2863 /* Ensure our label doesn't go away. */
2864 LABEL_NUSES (cond_label)++;
2866 /* Verify that uid_loop is large enough and that
2867 we can invert P. */
2868 if (invert_jump (p, new_label))
2870 rtx q, r;
2872 /* If no suitable BARRIER was found, create a suitable
2873 one before TARGET. Since TARGET is a fall through
2874 path, we'll need to insert an jump around our block
2875 and a add a BARRIER before TARGET.
2877 This creates an extra unconditional jump outside
2878 the loop. However, the benefits of removing rarely
2879 executed instructions from inside the loop usually
2880 outweighs the cost of the extra unconditional jump
2881 outside the loop. */
2882 if (loc == 0)
2884 rtx temp;
2886 temp = gen_jump (JUMP_LABEL (insn));
2887 temp = emit_jump_insn_before (temp, target);
2888 JUMP_LABEL (temp) = JUMP_LABEL (insn);
2889 LABEL_NUSES (JUMP_LABEL (insn))++;
2890 loc = emit_barrier_before (target);
2893 /* Include the BARRIER after INSN and copy the
2894 block after LOC. */
2895 new_label = squeeze_notes (new_label,
2896 last_insn_to_move);
2897 reorder_insns (new_label, last_insn_to_move, loc);
2899 /* All those insns are now in TARGET_LOOP. */
2900 for (q = new_label;
2901 q != NEXT_INSN (last_insn_to_move);
2902 q = NEXT_INSN (q))
2903 uid_loop[INSN_UID (q)] = target_loop;
2905 /* The label jumped to by INSN is no longer a loop exit.
2906 Unless INSN does not have a label (e.g., it is a
2907 RETURN insn), search loop->exit_labels to find
2908 its label_ref, and remove it. Also turn off
2909 LABEL_OUTSIDE_LOOP_P bit. */
2910 if (JUMP_LABEL (insn))
2912 for (q = 0,
2913 r = this_loop->exit_labels;
2914 r; q = r, r = LABEL_NEXTREF (r))
2915 if (XEXP (r, 0) == JUMP_LABEL (insn))
2917 LABEL_OUTSIDE_LOOP_P (r) = 0;
2918 if (q)
2919 LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2920 else
2921 this_loop->exit_labels = LABEL_NEXTREF (r);
2922 break;
2925 for (loop = this_loop; loop && loop != target_loop;
2926 loop = loop->outer)
2927 loop->exit_count--;
2929 /* If we didn't find it, then something is
2930 wrong. */
2931 if (! r)
2932 abort ();
2935 /* P is now a jump outside the loop, so it must be put
2936 in loop->exit_labels, and marked as such.
2937 The easiest way to do this is to just call
2938 mark_loop_jump again for P. */
2939 mark_loop_jump (PATTERN (p), this_loop);
2941 /* If INSN now jumps to the insn after it,
2942 delete INSN. */
2943 if (JUMP_LABEL (insn) != 0
2944 && (next_real_insn (JUMP_LABEL (insn))
2945 == next_real_insn (insn)))
2946 delete_insn (insn);
2949 /* Continue the loop after where the conditional
2950 branch used to jump, since the only branch insn
2951 in the block (if it still remains) is an inter-loop
2952 branch and hence needs no processing. */
2953 insn = NEXT_INSN (cond_label);
2955 if (--LABEL_NUSES (cond_label) == 0)
2956 delete_insn (cond_label);
2958 /* This loop will be continued with NEXT_INSN (insn). */
2959 insn = PREV_INSN (insn);
2966 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
2967 loops it is contained in, mark the target loop invalid.
2969 For speed, we assume that X is part of a pattern of a JUMP_INSN. */
2971 static void
2972 mark_loop_jump (x, loop)
2973 rtx x;
2974 struct loop *loop;
2976 struct loop *dest_loop;
2977 struct loop *outer_loop;
2978 int i;
2980 switch (GET_CODE (x))
2982 case PC:
2983 case USE:
2984 case CLOBBER:
2985 case REG:
2986 case MEM:
2987 case CONST_INT:
2988 case CONST_DOUBLE:
2989 case RETURN:
2990 return;
2992 case CONST:
2993 /* There could be a label reference in here. */
2994 mark_loop_jump (XEXP (x, 0), loop);
2995 return;
2997 case PLUS:
2998 case MINUS:
2999 case MULT:
3000 mark_loop_jump (XEXP (x, 0), loop);
3001 mark_loop_jump (XEXP (x, 1), loop);
3002 return;
3004 case LO_SUM:
3005 /* This may refer to a LABEL_REF or SYMBOL_REF. */
3006 mark_loop_jump (XEXP (x, 1), loop);
3007 return;
3009 case SIGN_EXTEND:
3010 case ZERO_EXTEND:
3011 mark_loop_jump (XEXP (x, 0), loop);
3012 return;
3014 case LABEL_REF:
3015 dest_loop = uid_loop[INSN_UID (XEXP (x, 0))];
3017 /* Link together all labels that branch outside the loop. This
3018 is used by final_[bg]iv_value and the loop unrolling code. Also
3019 mark this LABEL_REF so we know that this branch should predict
3020 false. */
3022 /* A check to make sure the label is not in an inner nested loop,
3023 since this does not count as a loop exit. */
3024 if (dest_loop)
3026 for (outer_loop = dest_loop; outer_loop;
3027 outer_loop = outer_loop->outer)
3028 if (outer_loop == loop)
3029 break;
3031 else
3032 outer_loop = NULL;
3034 if (loop && ! outer_loop)
3036 LABEL_OUTSIDE_LOOP_P (x) = 1;
3037 LABEL_NEXTREF (x) = loop->exit_labels;
3038 loop->exit_labels = x;
3040 for (outer_loop = loop;
3041 outer_loop && outer_loop != dest_loop;
3042 outer_loop = outer_loop->outer)
3043 outer_loop->exit_count++;
3046 /* If this is inside a loop, but not in the current loop or one enclosed
3047 by it, it invalidates at least one loop. */
3049 if (! dest_loop)
3050 return;
3052 /* We must invalidate every nested loop containing the target of this
3053 label, except those that also contain the jump insn. */
3055 for (; dest_loop; dest_loop = dest_loop->outer)
3057 /* Stop when we reach a loop that also contains the jump insn. */
3058 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3059 if (dest_loop == outer_loop)
3060 return;
3062 /* If we get here, we know we need to invalidate a loop. */
3063 if (loop_dump_stream && ! dest_loop->invalid)
3064 fprintf (loop_dump_stream,
3065 "\nLoop at %d ignored due to multiple entry points.\n",
3066 INSN_UID (dest_loop->start));
3068 dest_loop->invalid = 1;
3070 return;
3072 case SET:
3073 /* If this is not setting pc, ignore. */
3074 if (SET_DEST (x) == pc_rtx)
3075 mark_loop_jump (SET_SRC (x), loop);
3076 return;
3078 case IF_THEN_ELSE:
3079 mark_loop_jump (XEXP (x, 1), loop);
3080 mark_loop_jump (XEXP (x, 2), loop);
3081 return;
3083 case PARALLEL:
3084 case ADDR_VEC:
3085 for (i = 0; i < XVECLEN (x, 0); i++)
3086 mark_loop_jump (XVECEXP (x, 0, i), loop);
3087 return;
3089 case ADDR_DIFF_VEC:
3090 for (i = 0; i < XVECLEN (x, 1); i++)
3091 mark_loop_jump (XVECEXP (x, 1, i), loop);
3092 return;
3094 default:
3095 /* Strictly speaking this is not a jump into the loop, only a possible
3096 jump out of the loop. However, we have no way to link the destination
3097 of this jump onto the list of exit labels. To be safe we mark this
3098 loop and any containing loops as invalid. */
3099 if (loop)
3101 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3103 if (loop_dump_stream && ! outer_loop->invalid)
3104 fprintf (loop_dump_stream,
3105 "\nLoop at %d ignored due to unknown exit jump.\n",
3106 INSN_UID (outer_loop->start));
3107 outer_loop->invalid = 1;
3110 return;
3114 /* Return nonzero if there is a label in the range from
3115 insn INSN to and including the insn whose luid is END
3116 INSN must have an assigned luid (i.e., it must not have
3117 been previously created by loop.c). */
3119 static int
3120 labels_in_range_p (insn, end)
3121 rtx insn;
3122 int end;
3124 while (insn && INSN_LUID (insn) <= end)
3126 if (GET_CODE (insn) == CODE_LABEL)
3127 return 1;
3128 insn = NEXT_INSN (insn);
3131 return 0;
3134 /* Record that a memory reference X is being set. */
3136 static void
3137 note_addr_stored (x, y, data)
3138 rtx x;
3139 rtx y ATTRIBUTE_UNUSED;
3140 void *data ATTRIBUTE_UNUSED;
3142 if (x == 0 || GET_CODE (x) != MEM)
3143 return;
3145 /* Count number of memory writes.
3146 This affects heuristics in strength_reduce. */
3147 num_mem_sets++;
3149 /* BLKmode MEM means all memory is clobbered. */
3150 if (GET_MODE (x) == BLKmode)
3152 if (RTX_UNCHANGING_P (x))
3153 unknown_constant_address_altered = 1;
3154 else
3155 unknown_address_altered = 1;
3157 return;
3160 loop_store_mems = gen_rtx_EXPR_LIST (VOIDmode, x, loop_store_mems);
3163 /* X is a value modified by an INSN that references a biv inside a loop
3164 exit test (ie, X is somehow related to the value of the biv). If X
3165 is a pseudo that is used more than once, then the biv is (effectively)
3166 used more than once. DATA is really an `int *', and is set if the
3167 biv is used more than once. */
3169 static void
3170 note_set_pseudo_multiple_uses (x, y, data)
3171 rtx x;
3172 rtx y ATTRIBUTE_UNUSED;
3173 void *data;
3175 if (x == 0)
3176 return;
3178 while (GET_CODE (x) == STRICT_LOW_PART
3179 || GET_CODE (x) == SIGN_EXTRACT
3180 || GET_CODE (x) == ZERO_EXTRACT
3181 || GET_CODE (x) == SUBREG)
3182 x = XEXP (x, 0);
3184 if (GET_CODE (x) != REG || REGNO (x) < FIRST_PSEUDO_REGISTER)
3185 return;
3187 /* If we do not have usage information, or if we know the register
3188 is used more than once, note that fact for check_dbra_loop. */
3189 if (REGNO (x) >= max_reg_before_loop
3190 || ! VARRAY_RTX (reg_single_usage, REGNO (x))
3191 || VARRAY_RTX (reg_single_usage, REGNO (x)) == const0_rtx)
3192 *((int *) data) = 1;
3195 /* Return nonzero if the rtx X is invariant over the current loop.
3197 The value is 2 if we refer to something only conditionally invariant.
3199 If `unknown_address_altered' is nonzero, no memory ref is invariant.
3200 Otherwise, a memory ref is invariant if it does not conflict with
3201 anything stored in `loop_store_mems'. */
3204 loop_invariant_p (loop, x)
3205 const struct loop *loop;
3206 register rtx x;
3208 register int i;
3209 register enum rtx_code code;
3210 register const char *fmt;
3211 int conditional = 0;
3212 rtx mem_list_entry;
3214 if (x == 0)
3215 return 1;
3216 code = GET_CODE (x);
3217 switch (code)
3219 case CONST_INT:
3220 case CONST_DOUBLE:
3221 case SYMBOL_REF:
3222 case CONST:
3223 return 1;
3225 case LABEL_REF:
3226 /* A LABEL_REF is normally invariant, however, if we are unrolling
3227 loops, and this label is inside the loop, then it isn't invariant.
3228 This is because each unrolled copy of the loop body will have
3229 a copy of this label. If this was invariant, then an insn loading
3230 the address of this label into a register might get moved outside
3231 the loop, and then each loop body would end up using the same label.
3233 We don't know the loop bounds here though, so just fail for all
3234 labels. */
3235 if (flag_unroll_loops)
3236 return 0;
3237 else
3238 return 1;
3240 case PC:
3241 case CC0:
3242 case UNSPEC_VOLATILE:
3243 return 0;
3245 case REG:
3246 /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3247 since the reg might be set by initialization within the loop. */
3249 if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3250 || x == arg_pointer_rtx)
3251 && ! current_function_has_nonlocal_goto)
3252 return 1;
3254 if (LOOP_INFO (loop)->has_call
3255 && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3256 return 0;
3258 if (VARRAY_INT (set_in_loop, REGNO (x)) < 0)
3259 return 2;
3261 return VARRAY_INT (set_in_loop, REGNO (x)) == 0;
3263 case MEM:
3264 /* Volatile memory references must be rejected. Do this before
3265 checking for read-only items, so that volatile read-only items
3266 will be rejected also. */
3267 if (MEM_VOLATILE_P (x))
3268 return 0;
3270 /* If we had a subroutine call, any location in memory could
3271 have been clobbered. We used to test here for volatile and
3272 readonly, but true_dependence knows how to do that better
3273 than we do. */
3274 if (RTX_UNCHANGING_P (x)
3275 ? unknown_constant_address_altered : unknown_address_altered)
3276 return 0;
3278 /* See if there is any dependence between a store and this load. */
3279 mem_list_entry = loop_store_mems;
3280 while (mem_list_entry)
3282 if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3283 x, rtx_varies_p))
3284 return 0;
3286 mem_list_entry = XEXP (mem_list_entry, 1);
3289 /* It's not invalidated by a store in memory
3290 but we must still verify the address is invariant. */
3291 break;
3293 case ASM_OPERANDS:
3294 /* Don't mess with insns declared volatile. */
3295 if (MEM_VOLATILE_P (x))
3296 return 0;
3297 break;
3299 default:
3300 break;
3303 fmt = GET_RTX_FORMAT (code);
3304 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3306 if (fmt[i] == 'e')
3308 int tem = loop_invariant_p (loop, XEXP (x, i));
3309 if (tem == 0)
3310 return 0;
3311 if (tem == 2)
3312 conditional = 1;
3314 else if (fmt[i] == 'E')
3316 register int j;
3317 for (j = 0; j < XVECLEN (x, i); j++)
3319 int tem = loop_invariant_p (loop, XVECEXP (x, i, j));
3320 if (tem == 0)
3321 return 0;
3322 if (tem == 2)
3323 conditional = 1;
3329 return 1 + conditional;
3333 /* Return nonzero if all the insns in the loop that set REG
3334 are INSN and the immediately following insns,
3335 and if each of those insns sets REG in an invariant way
3336 (not counting uses of REG in them).
3338 The value is 2 if some of these insns are only conditionally invariant.
3340 We assume that INSN itself is the first set of REG
3341 and that its source is invariant. */
3343 static int
3344 consec_sets_invariant_p (loop, reg, n_sets, insn)
3345 const struct loop *loop;
3346 int n_sets;
3347 rtx reg, insn;
3349 rtx p = insn;
3350 unsigned int regno = REGNO (reg);
3351 rtx temp;
3352 /* Number of sets we have to insist on finding after INSN. */
3353 int count = n_sets - 1;
3354 int old = VARRAY_INT (set_in_loop, regno);
3355 int value = 0;
3356 int this;
3358 /* If N_SETS hit the limit, we can't rely on its value. */
3359 if (n_sets == 127)
3360 return 0;
3362 VARRAY_INT (set_in_loop, regno) = 0;
3364 while (count > 0)
3366 register enum rtx_code code;
3367 rtx set;
3369 p = NEXT_INSN (p);
3370 code = GET_CODE (p);
3372 /* If library call, skip to end of it. */
3373 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3374 p = XEXP (temp, 0);
3376 this = 0;
3377 if (code == INSN
3378 && (set = single_set (p))
3379 && GET_CODE (SET_DEST (set)) == REG
3380 && REGNO (SET_DEST (set)) == regno)
3382 this = loop_invariant_p (loop, SET_SRC (set));
3383 if (this != 0)
3384 value |= this;
3385 else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3387 /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3388 If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3389 notes are OK. */
3390 this = (CONSTANT_P (XEXP (temp, 0))
3391 || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3392 && loop_invariant_p (loop, XEXP (temp, 0))));
3393 if (this != 0)
3394 value |= this;
3397 if (this != 0)
3398 count--;
3399 else if (code != NOTE)
3401 VARRAY_INT (set_in_loop, regno) = old;
3402 return 0;
3406 VARRAY_INT (set_in_loop, regno) = old;
3407 /* If loop_invariant_p ever returned 2, we return 2. */
3408 return 1 + (value & 2);
3411 #if 0
3412 /* I don't think this condition is sufficient to allow INSN
3413 to be moved, so we no longer test it. */
3415 /* Return 1 if all insns in the basic block of INSN and following INSN
3416 that set REG are invariant according to TABLE. */
3418 static int
3419 all_sets_invariant_p (reg, insn, table)
3420 rtx reg, insn;
3421 short *table;
3423 register rtx p = insn;
3424 register int regno = REGNO (reg);
3426 while (1)
3428 register enum rtx_code code;
3429 p = NEXT_INSN (p);
3430 code = GET_CODE (p);
3431 if (code == CODE_LABEL || code == JUMP_INSN)
3432 return 1;
3433 if (code == INSN && GET_CODE (PATTERN (p)) == SET
3434 && GET_CODE (SET_DEST (PATTERN (p))) == REG
3435 && REGNO (SET_DEST (PATTERN (p))) == regno)
3437 if (! loop_invariant_p (loop, SET_SRC (PATTERN (p)), table))
3438 return 0;
3442 #endif /* 0 */
3444 /* Look at all uses (not sets) of registers in X. For each, if it is
3445 the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3446 a different insn, set USAGE[REGNO] to const0_rtx. */
3448 static void
3449 find_single_use_in_loop (insn, x, usage)
3450 rtx insn;
3451 rtx x;
3452 varray_type usage;
3454 enum rtx_code code = GET_CODE (x);
3455 const char *fmt = GET_RTX_FORMAT (code);
3456 int i, j;
3458 if (code == REG)
3459 VARRAY_RTX (usage, REGNO (x))
3460 = (VARRAY_RTX (usage, REGNO (x)) != 0
3461 && VARRAY_RTX (usage, REGNO (x)) != insn)
3462 ? const0_rtx : insn;
3464 else if (code == SET)
3466 /* Don't count SET_DEST if it is a REG; otherwise count things
3467 in SET_DEST because if a register is partially modified, it won't
3468 show up as a potential movable so we don't care how USAGE is set
3469 for it. */
3470 if (GET_CODE (SET_DEST (x)) != REG)
3471 find_single_use_in_loop (insn, SET_DEST (x), usage);
3472 find_single_use_in_loop (insn, SET_SRC (x), usage);
3474 else
3475 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3477 if (fmt[i] == 'e' && XEXP (x, i) != 0)
3478 find_single_use_in_loop (insn, XEXP (x, i), usage);
3479 else if (fmt[i] == 'E')
3480 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3481 find_single_use_in_loop (insn, XVECEXP (x, i, j), usage);
3485 /* Count and record any set in X which is contained in INSN. Update
3486 MAY_NOT_MOVE and LAST_SET for any register set in X. */
3488 static void
3489 count_one_set (insn, x, may_not_move, last_set)
3490 rtx insn, x;
3491 varray_type may_not_move;
3492 rtx *last_set;
3494 if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3495 /* Don't move a reg that has an explicit clobber.
3496 It's not worth the pain to try to do it correctly. */
3497 VARRAY_CHAR (may_not_move, REGNO (XEXP (x, 0))) = 1;
3499 if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3501 rtx dest = SET_DEST (x);
3502 while (GET_CODE (dest) == SUBREG
3503 || GET_CODE (dest) == ZERO_EXTRACT
3504 || GET_CODE (dest) == SIGN_EXTRACT
3505 || GET_CODE (dest) == STRICT_LOW_PART)
3506 dest = XEXP (dest, 0);
3507 if (GET_CODE (dest) == REG)
3509 register int regno = REGNO (dest);
3510 /* If this is the first setting of this reg
3511 in current basic block, and it was set before,
3512 it must be set in two basic blocks, so it cannot
3513 be moved out of the loop. */
3514 if (VARRAY_INT (set_in_loop, regno) > 0
3515 && last_set[regno] == 0)
3516 VARRAY_CHAR (may_not_move, regno) = 1;
3517 /* If this is not first setting in current basic block,
3518 see if reg was used in between previous one and this.
3519 If so, neither one can be moved. */
3520 if (last_set[regno] != 0
3521 && reg_used_between_p (dest, last_set[regno], insn))
3522 VARRAY_CHAR (may_not_move, regno) = 1;
3523 if (VARRAY_INT (set_in_loop, regno) < 127)
3524 ++VARRAY_INT (set_in_loop, regno);
3525 last_set[regno] = insn;
3530 /* Increment SET_IN_LOOP at the index of each register
3531 that is modified by an insn between FROM and TO.
3532 If the value of an element of SET_IN_LOOP becomes 127 or more,
3533 stop incrementing it, to avoid overflow.
3535 Store in SINGLE_USAGE[I] the single insn in which register I is
3536 used, if it is only used once. Otherwise, it is set to 0 (for no
3537 uses) or const0_rtx for more than one use. This parameter may be zero,
3538 in which case this processing is not done.
3540 Store in *COUNT_PTR the number of actual instruction
3541 in the loop. We use this to decide what is worth moving out. */
3543 /* last_set[n] is nonzero iff reg n has been set in the current basic block.
3544 In that case, it is the insn that last set reg n. */
3546 static void
3547 count_loop_regs_set (from, to, may_not_move, single_usage, count_ptr, nregs)
3548 register rtx from, to;
3549 varray_type may_not_move;
3550 varray_type single_usage;
3551 int *count_ptr;
3552 int nregs;
3554 register rtx *last_set = (rtx *) xcalloc (nregs, sizeof (rtx));
3555 register rtx insn;
3556 register int count = 0;
3558 for (insn = from; insn != to; insn = NEXT_INSN (insn))
3560 if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
3562 ++count;
3564 /* Record registers that have exactly one use. */
3565 find_single_use_in_loop (insn, PATTERN (insn), single_usage);
3567 /* Include uses in REG_EQUAL notes. */
3568 if (REG_NOTES (insn))
3569 find_single_use_in_loop (insn, REG_NOTES (insn), single_usage);
3571 if (GET_CODE (PATTERN (insn)) == SET
3572 || GET_CODE (PATTERN (insn)) == CLOBBER)
3573 count_one_set (insn, PATTERN (insn), may_not_move, last_set);
3574 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
3576 register int i;
3577 for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
3578 count_one_set (insn, XVECEXP (PATTERN (insn), 0, i),
3579 may_not_move, last_set);
3583 if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
3584 bzero ((char *) last_set, nregs * sizeof (rtx));
3586 *count_ptr = count;
3588 /* Clean up. */
3589 free (last_set);
3592 /* Given a loop that is bounded by LOOP->START and LOOP->END and that
3593 is entered at LOOP->SCAN_START, return 1 if the register set in SET
3594 contained in insn INSN is used by any insn that precedes INSN in
3595 cyclic order starting from the loop entry point.
3597 We don't want to use INSN_LUID here because if we restrict INSN to those
3598 that have a valid INSN_LUID, it means we cannot move an invariant out
3599 from an inner loop past two loops. */
3601 static int
3602 loop_reg_used_before_p (loop, set, insn)
3603 const struct loop *loop;
3604 rtx set, insn;
3606 rtx reg = SET_DEST (set);
3607 rtx p;
3609 /* Scan forward checking for register usage. If we hit INSN, we
3610 are done. Otherwise, if we hit LOOP->END, wrap around to LOOP->START. */
3611 for (p = loop->scan_start; p != insn; p = NEXT_INSN (p))
3613 if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
3614 && reg_overlap_mentioned_p (reg, PATTERN (p)))
3615 return 1;
3617 if (p == loop->end)
3618 p = loop->start;
3621 return 0;
3624 /* A "basic induction variable" or biv is a pseudo reg that is set
3625 (within this loop) only by incrementing or decrementing it. */
3626 /* A "general induction variable" or giv is a pseudo reg whose
3627 value is a linear function of a biv. */
3629 /* Bivs are recognized by `basic_induction_var';
3630 Givs by `general_induction_var'. */
3632 /* Indexed by register number, indicates whether or not register is an
3633 induction variable, and if so what type. */
3635 varray_type reg_iv_type;
3637 /* Indexed by register number, contains pointer to `struct induction'
3638 if register is an induction variable. This holds general info for
3639 all induction variables. */
3641 varray_type reg_iv_info;
3643 /* Indexed by register number, contains pointer to `struct iv_class'
3644 if register is a basic induction variable. This holds info describing
3645 the class (a related group) of induction variables that the biv belongs
3646 to. */
3648 struct iv_class **reg_biv_class;
3650 /* The head of a list which links together (via the next field)
3651 every iv class for the current loop. */
3653 struct iv_class *loop_iv_list;
3655 /* Givs made from biv increments are always splittable for loop unrolling.
3656 Since there is no regscan info for them, we have to keep track of them
3657 separately. */
3658 unsigned int first_increment_giv, last_increment_giv;
3660 /* Communication with routines called via `note_stores'. */
3662 static rtx note_insn;
3664 /* Dummy register to have non-zero DEST_REG for DEST_ADDR type givs. */
3666 static rtx addr_placeholder;
3668 /* ??? Unfinished optimizations, and possible future optimizations,
3669 for the strength reduction code. */
3671 /* ??? The interaction of biv elimination, and recognition of 'constant'
3672 bivs, may cause problems. */
3674 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
3675 performance problems.
3677 Perhaps don't eliminate things that can be combined with an addressing
3678 mode. Find all givs that have the same biv, mult_val, and add_val;
3679 then for each giv, check to see if its only use dies in a following
3680 memory address. If so, generate a new memory address and check to see
3681 if it is valid. If it is valid, then store the modified memory address,
3682 otherwise, mark the giv as not done so that it will get its own iv. */
3684 /* ??? Could try to optimize branches when it is known that a biv is always
3685 positive. */
3687 /* ??? When replace a biv in a compare insn, we should replace with closest
3688 giv so that an optimized branch can still be recognized by the combiner,
3689 e.g. the VAX acb insn. */
3691 /* ??? Many of the checks involving uid_luid could be simplified if regscan
3692 was rerun in loop_optimize whenever a register was added or moved.
3693 Also, some of the optimizations could be a little less conservative. */
3695 /* Scan the loop body and call FNCALL for each insn. In the addition to the
3696 LOOP and INSN parameters pass MAYBE_MULTIPLE and NOT_EVERY_ITERATION to the
3697 callback.
3699 NOT_EVERY_ITERATION if current insn is not executed at least once for every
3700 loop iteration except for the last one.
3702 MAYBE_MULTIPLE is 1 if current insn may be executed more than once for every
3703 loop iteration.
3705 void
3706 for_each_insn_in_loop (loop, fncall)
3707 struct loop *loop;
3708 loop_insn_callback fncall;
3710 /* This is 1 if current insn is not executed at least once for every loop
3711 iteration. */
3712 int not_every_iteration = 0;
3713 int maybe_multiple = 0;
3714 int past_loop_latch = 0;
3715 int loop_depth = 0;
3716 rtx p;
3718 /* If loop_scan_start points to the loop exit test, we have to be wary of
3719 subversive use of gotos inside expression statements. */
3720 if (prev_nonnote_insn (loop->scan_start) != prev_nonnote_insn (loop->start))
3721 maybe_multiple = back_branch_in_range_p (loop, loop->scan_start);
3723 /* Scan through loop to find all possible bivs. */
3725 for (p = next_insn_in_loop (loop, loop->scan_start);
3726 p != NULL_RTX;
3727 p = next_insn_in_loop (loop, p))
3729 p = fncall (loop, p, not_every_iteration, maybe_multiple);
3731 /* Past CODE_LABEL, we get to insns that may be executed multiple
3732 times. The only way we can be sure that they can't is if every
3733 jump insn between here and the end of the loop either
3734 returns, exits the loop, is a jump to a location that is still
3735 behind the label, or is a jump to the loop start. */
3737 if (GET_CODE (p) == CODE_LABEL)
3739 rtx insn = p;
3741 maybe_multiple = 0;
3743 while (1)
3745 insn = NEXT_INSN (insn);
3746 if (insn == loop->scan_start)
3747 break;
3748 if (insn == loop->end)
3750 if (loop->top != 0)
3751 insn = loop->top;
3752 else
3753 break;
3754 if (insn == loop->scan_start)
3755 break;
3758 if (GET_CODE (insn) == JUMP_INSN
3759 && GET_CODE (PATTERN (insn)) != RETURN
3760 && (!condjump_p (insn)
3761 || (JUMP_LABEL (insn) != 0
3762 && JUMP_LABEL (insn) != loop->scan_start
3763 && !loop_insn_first_p (p, JUMP_LABEL (insn)))))
3765 maybe_multiple = 1;
3766 break;
3771 /* Past a jump, we get to insns for which we can't count
3772 on whether they will be executed during each iteration. */
3773 /* This code appears twice in strength_reduce. There is also similar
3774 code in scan_loop. */
3775 if (GET_CODE (p) == JUMP_INSN
3776 /* If we enter the loop in the middle, and scan around to the
3777 beginning, don't set not_every_iteration for that.
3778 This can be any kind of jump, since we want to know if insns
3779 will be executed if the loop is executed. */
3780 && !(JUMP_LABEL (p) == loop->top
3781 && ((NEXT_INSN (NEXT_INSN (p)) == loop->end && simplejump_p (p))
3782 || (NEXT_INSN (p) == loop->end && condjump_p (p)))))
3784 rtx label = 0;
3786 /* If this is a jump outside the loop, then it also doesn't
3787 matter. Check to see if the target of this branch is on the
3788 loop->exits_labels list. */
3790 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
3791 if (XEXP (label, 0) == JUMP_LABEL (p))
3792 break;
3794 if (!label)
3795 not_every_iteration = 1;
3798 else if (GET_CODE (p) == NOTE)
3800 /* At the virtual top of a converted loop, insns are again known to
3801 be executed each iteration: logically, the loop begins here
3802 even though the exit code has been duplicated.
3804 Insns are also again known to be executed each iteration at
3805 the LOOP_CONT note. */
3806 if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
3807 || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
3808 && loop_depth == 0)
3809 not_every_iteration = 0;
3810 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3811 loop_depth++;
3812 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
3813 loop_depth--;
3816 /* Note if we pass a loop latch. If we do, then we can not clear
3817 NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
3818 a loop since a jump before the last CODE_LABEL may have started
3819 a new loop iteration.
3821 Note that LOOP_TOP is only set for rotated loops and we need
3822 this check for all loops, so compare against the CODE_LABEL
3823 which immediately follows LOOP_START. */
3824 if (GET_CODE (p) == JUMP_INSN
3825 && JUMP_LABEL (p) == NEXT_INSN (loop->start))
3826 past_loop_latch = 1;
3828 /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3829 an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3830 or not an insn is known to be executed each iteration of the
3831 loop, whether or not any iterations are known to occur.
3833 Therefore, if we have just passed a label and have no more labels
3834 between here and the test insn of the loop, and we have not passed
3835 a jump to the top of the loop, then we know these insns will be
3836 executed each iteration. */
3838 if (not_every_iteration
3839 && !past_loop_latch
3840 && GET_CODE (p) == CODE_LABEL
3841 && no_labels_between_p (p, loop->end)
3842 && loop_insn_first_p (p, loop->cont))
3843 not_every_iteration = 0;
3847 /* Perform strength reduction and induction variable elimination.
3849 Pseudo registers created during this function will be beyond the last
3850 valid index in several tables including n_times_set and regno_last_uid.
3851 This does not cause a problem here, because the added registers cannot be
3852 givs outside of their loop, and hence will never be reconsidered.
3853 But scan_loop must check regnos to make sure they are in bounds. */
3855 static void
3856 strength_reduce (loop, insn_count, unroll_p, bct_p)
3857 struct loop *loop;
3858 int insn_count;
3859 int unroll_p, bct_p ATTRIBUTE_UNUSED;
3861 rtx p;
3862 /* Temporary list pointers for traversing loop_iv_list. */
3863 struct iv_class *bl, **backbl;
3864 struct loop_info *loop_info = LOOP_INFO (loop);
3865 /* Ratio of extra register life span we can justify
3866 for saving an instruction. More if loop doesn't call subroutines
3867 since in that case saving an insn makes more difference
3868 and more registers are available. */
3869 /* ??? could set this to last value of threshold in move_movables */
3870 int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
3871 /* Map of pseudo-register replacements. */
3872 rtx *reg_map = NULL;
3873 int reg_map_size;
3874 int call_seen;
3875 rtx test;
3876 rtx end_insert_before;
3877 int n_extra_increment;
3878 int unrolled_insn_copies = 0;
3879 rtx loop_start = loop->start;
3880 rtx loop_end = loop->end;
3881 rtx loop_scan_start = loop->scan_start;
3883 VARRAY_INT_INIT (reg_iv_type, max_reg_before_loop, "reg_iv_type");
3884 VARRAY_GENERIC_PTR_INIT (reg_iv_info, max_reg_before_loop, "reg_iv_info");
3885 reg_biv_class = (struct iv_class **)
3886 xcalloc (max_reg_before_loop, sizeof (struct iv_class *));
3888 loop_iv_list = 0;
3889 addr_placeholder = gen_reg_rtx (Pmode);
3891 /* Save insn immediately after the loop_end. Insns inserted after loop_end
3892 must be put before this insn, so that they will appear in the right
3893 order (i.e. loop order).
3895 If loop_end is the end of the current function, then emit a
3896 NOTE_INSN_DELETED after loop_end and set end_insert_before to the
3897 dummy note insn. */
3898 if (NEXT_INSN (loop_end) != 0)
3899 end_insert_before = NEXT_INSN (loop_end);
3900 else
3901 end_insert_before = emit_note_after (NOTE_INSN_DELETED, loop_end);
3903 for_each_insn_in_loop (loop, check_insn_for_bivs);
3905 /* Scan loop_iv_list to remove all regs that proved not to be bivs.
3906 Make a sanity check against n_times_set. */
3907 for (backbl = &loop_iv_list, bl = *backbl; bl; bl = bl->next)
3909 int fail = 0;
3911 if (REG_IV_TYPE (bl->regno) != BASIC_INDUCT
3912 /* Above happens if register modified by subreg, etc. */
3913 /* Make sure it is not recognized as a basic induction var: */
3914 || VARRAY_INT (n_times_set, bl->regno) != bl->biv_count
3915 /* If never incremented, it is invariant that we decided not to
3916 move. So leave it alone. */
3917 || ! bl->incremented)
3918 fail = 1;
3919 else if (bl->biv_count > 1)
3921 /* ??? If we have multiple increments for this BIV, and any of
3922 them take multiple insns to perform the increment, drop the
3923 BIV, since the bit below that converts the extra increments
3924 into GIVs can't handle the multiple insn increment. */
3926 struct induction *v;
3927 for (v = bl->biv; v ; v = v->next_iv)
3928 if (v->multi_insn_incr)
3929 fail = 1;
3932 if (fail)
3934 if (loop_dump_stream)
3935 fprintf (loop_dump_stream, "Reg %d: biv discarded, %s\n",
3936 bl->regno,
3937 (REG_IV_TYPE (bl->regno) != BASIC_INDUCT
3938 ? "not induction variable"
3939 : (! bl->incremented ? "never incremented"
3940 : "count error")));
3942 REG_IV_TYPE (bl->regno) = NOT_BASIC_INDUCT;
3943 *backbl = bl->next;
3945 else
3947 backbl = &bl->next;
3949 if (loop_dump_stream)
3950 fprintf (loop_dump_stream, "Reg %d: biv verified\n", bl->regno);
3954 /* Exit if there are no bivs. */
3955 if (! loop_iv_list)
3957 /* Can still unroll the loop anyways, but indicate that there is no
3958 strength reduction info available. */
3959 if (unroll_p)
3960 unroll_loop (loop, insn_count, end_insert_before, 0);
3962 goto egress;
3965 /* Find initial value for each biv by searching backwards from loop_start,
3966 halting at first label. Also record any test condition. */
3968 call_seen = 0;
3969 for (p = loop_start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
3971 note_insn = p;
3973 if (GET_CODE (p) == CALL_INSN)
3974 call_seen = 1;
3976 if (INSN_P (p))
3977 note_stores (PATTERN (p), record_initial, NULL);
3979 /* Record any test of a biv that branches around the loop if no store
3980 between it and the start of loop. We only care about tests with
3981 constants and registers and only certain of those. */
3982 if (GET_CODE (p) == JUMP_INSN
3983 && JUMP_LABEL (p) != 0
3984 && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop_end)
3985 && (test = get_condition_for_loop (loop, p)) != 0
3986 && GET_CODE (XEXP (test, 0)) == REG
3987 && REGNO (XEXP (test, 0)) < max_reg_before_loop
3988 && (bl = reg_biv_class[REGNO (XEXP (test, 0))]) != 0
3989 && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop_start)
3990 && bl->init_insn == 0)
3992 /* If an NE test, we have an initial value! */
3993 if (GET_CODE (test) == NE)
3995 bl->init_insn = p;
3996 bl->init_set = gen_rtx_SET (VOIDmode,
3997 XEXP (test, 0), XEXP (test, 1));
3999 else
4000 bl->initial_test = test;
4004 /* Look at the each biv and see if we can say anything better about its
4005 initial value from any initializing insns set up above. (This is done
4006 in two passes to avoid missing SETs in a PARALLEL.) */
4007 for (backbl = &loop_iv_list; (bl = *backbl); backbl = &bl->next)
4009 rtx src;
4010 rtx note;
4012 if (! bl->init_insn)
4013 continue;
4015 /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4016 is a constant, use the value of that. */
4017 if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4018 && CONSTANT_P (XEXP (note, 0)))
4019 || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4020 && CONSTANT_P (XEXP (note, 0))))
4021 src = XEXP (note, 0);
4022 else
4023 src = SET_SRC (bl->init_set);
4025 if (loop_dump_stream)
4026 fprintf (loop_dump_stream,
4027 "Biv %d initialized at insn %d: initial value ",
4028 bl->regno, INSN_UID (bl->init_insn));
4030 if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4031 || GET_MODE (src) == VOIDmode)
4032 && valid_initial_value_p (src, bl->init_insn, call_seen, loop_start))
4034 bl->initial_value = src;
4036 if (loop_dump_stream)
4038 if (GET_CODE (src) == CONST_INT)
4040 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (src));
4041 fputc ('\n', loop_dump_stream);
4043 else
4045 print_rtl (loop_dump_stream, src);
4046 fprintf (loop_dump_stream, "\n");
4050 else
4052 struct iv_class *bl2 = 0;
4053 rtx increment = NULL_RTX;
4055 /* Biv initial value is not a simple move. If it is the sum of
4056 another biv and a constant, check if both bivs are incremented
4057 in lockstep. Then we are actually looking at a giv.
4058 For simplicity, we only handle the case where there is but a
4059 single increment, and the register is not used elsewhere. */
4060 if (bl->biv_count == 1
4061 && bl->regno < max_reg_before_loop
4062 && uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4063 && GET_CODE (src) == PLUS
4064 && GET_CODE (XEXP (src, 0)) == REG
4065 && CONSTANT_P (XEXP (src, 1))
4066 && ((increment = biv_total_increment (bl)) != NULL_RTX))
4068 unsigned int regno = REGNO (XEXP (src, 0));
4070 for (bl2 = loop_iv_list; bl2; bl2 = bl2->next)
4071 if (bl2->regno == regno)
4072 break;
4075 /* Now, can we transform this biv into a giv? */
4076 if (bl2
4077 && bl2->biv_count == 1
4078 && rtx_equal_p (increment, biv_total_increment (bl2))
4079 /* init_insn is only set to insns that are before loop_start
4080 without any intervening labels. */
4081 && ! reg_set_between_p (bl2->biv->src_reg,
4082 PREV_INSN (bl->init_insn), loop_start)
4083 /* The register from BL2 must be set before the register from
4084 BL is set, or we must be able to move the latter set after
4085 the former set. Currently there can't be any labels
4086 in-between when biv_total_increment returns nonzero both times
4087 but we test it here in case some day some real cfg analysis
4088 gets used to set always_computable. */
4089 && (loop_insn_first_p (bl2->biv->insn, bl->biv->insn)
4090 ? no_labels_between_p (bl2->biv->insn, bl->biv->insn)
4091 : (! reg_used_between_p (bl->biv->src_reg, bl->biv->insn,
4092 bl2->biv->insn)
4093 && no_jumps_between_p (bl->biv->insn, bl2->biv->insn)))
4094 && validate_change (bl->biv->insn,
4095 &SET_SRC (single_set (bl->biv->insn)),
4096 copy_rtx (src), 0))
4098 rtx dominator = loop->cont_dominator;
4099 rtx giv = bl->biv->src_reg;
4100 rtx giv_insn = bl->biv->insn;
4101 rtx after_giv = NEXT_INSN (giv_insn);
4103 if (loop_dump_stream)
4104 fprintf (loop_dump_stream, "is giv of biv %d\n", bl2->regno);
4105 /* Let this giv be discovered by the generic code. */
4106 REG_IV_TYPE (bl->regno) = UNKNOWN_INDUCT;
4107 reg_biv_class[bl->regno] = (struct iv_class *) NULL_PTR;
4108 /* We can get better optimization if we can move the giv setting
4109 before the first giv use. */
4110 if (dominator
4111 && ! loop_insn_first_p (dominator, loop_scan_start)
4112 && ! reg_set_between_p (bl2->biv->src_reg, loop_start,
4113 dominator)
4114 && ! reg_used_between_p (giv, loop_start, dominator)
4115 && ! reg_used_between_p (giv, giv_insn, loop_end))
4117 rtx p;
4118 rtx next;
4120 for (next = NEXT_INSN (dominator); ; next = NEXT_INSN (next))
4122 if ((INSN_P (next)
4123 && (reg_mentioned_p (giv, PATTERN (next))
4124 || reg_set_p (bl2->biv->src_reg, next)))
4125 || GET_CODE (next) == JUMP_INSN)
4126 break;
4127 #ifdef HAVE_cc0
4128 if (! INSN_P (next)
4129 || ! sets_cc0_p (PATTERN (next)))
4130 #endif
4131 dominator = next;
4133 if (loop_dump_stream)
4134 fprintf (loop_dump_stream, "move after insn %d\n",
4135 INSN_UID (dominator));
4136 /* Avoid problems with luids by actually moving the insn
4137 and adjusting all luids in the range. */
4138 reorder_insns (giv_insn, giv_insn, dominator);
4139 for (p = dominator; INSN_UID (p) >= max_uid_for_loop; )
4140 p = PREV_INSN (p);
4141 compute_luids (giv_insn, after_giv, INSN_LUID (p));
4142 /* If the only purpose of the init insn is to initialize
4143 this giv, delete it. */
4144 if (single_set (bl->init_insn)
4145 && ! reg_used_between_p (giv, bl->init_insn, loop_start))
4146 delete_insn (bl->init_insn);
4148 else if (! loop_insn_first_p (bl2->biv->insn, bl->biv->insn))
4150 rtx p = PREV_INSN (giv_insn);
4151 while (INSN_UID (p) >= max_uid_for_loop)
4152 p = PREV_INSN (p);
4153 reorder_insns (giv_insn, giv_insn, bl2->biv->insn);
4154 compute_luids (after_giv, NEXT_INSN (giv_insn),
4155 INSN_LUID (p));
4157 /* Remove this biv from the chain. */
4158 *backbl = bl->next;
4161 /* If we can't make it a giv,
4162 let biv keep initial value of "itself". */
4163 else if (loop_dump_stream)
4164 fprintf (loop_dump_stream, "is complex\n");
4168 /* If a biv is unconditionally incremented several times in a row, convert
4169 all but the last increment into a giv. */
4171 /* Get an upper bound for the number of registers
4172 we might have after all bivs have been processed. */
4173 first_increment_giv = max_reg_num ();
4174 for (n_extra_increment = 0, bl = loop_iv_list; bl; bl = bl->next)
4175 n_extra_increment += bl->biv_count - 1;
4177 /* If the loop contains volatile memory references do not allow any
4178 replacements to take place, since this could loose the volatile
4179 markers. */
4180 if (n_extra_increment && ! loop_info->has_volatile)
4182 unsigned int nregs = first_increment_giv + n_extra_increment;
4184 /* Reallocate reg_iv_type and reg_iv_info. */
4185 VARRAY_GROW (reg_iv_type, nregs);
4186 VARRAY_GROW (reg_iv_info, nregs);
4188 for (bl = loop_iv_list; bl; bl = bl->next)
4190 struct induction **vp, *v, *next;
4191 int biv_dead_after_loop = 0;
4193 /* The biv increments lists are in reverse order. Fix this
4194 first. */
4195 for (v = bl->biv, bl->biv = 0; v; v = next)
4197 next = v->next_iv;
4198 v->next_iv = bl->biv;
4199 bl->biv = v;
4202 /* We must guard against the case that an early exit between v->insn
4203 and next->insn leaves the biv live after the loop, since that
4204 would mean that we'd be missing an increment for the final
4205 value. The following test to set biv_dead_after_loop is like
4206 the first part of the test to set bl->eliminable.
4207 We don't check here if we can calculate the final value, since
4208 this can't succeed if we already know that there is a jump
4209 between v->insn and next->insn, yet next->always_executed is
4210 set and next->maybe_multiple is cleared. Such a combination
4211 implies that the jump destination is outside the loop.
4212 If we want to make this check more sophisticated, we should
4213 check each branch between v->insn and next->insn individually
4214 to see if the biv is dead at its destination. */
4216 if (uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4217 && bl->init_insn
4218 && INSN_UID (bl->init_insn) < max_uid_for_loop
4219 && (uid_luid[REGNO_FIRST_UID (bl->regno)]
4220 >= INSN_LUID (bl->init_insn))
4221 #ifdef HAVE_decrement_and_branch_until_zero
4222 && ! bl->nonneg
4223 #endif
4224 && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4225 biv_dead_after_loop = 1;
4227 for (vp = &bl->biv, next = *vp; v = next, next = v->next_iv;)
4229 HOST_WIDE_INT offset;
4230 rtx set, add_val, old_reg, dest_reg, last_use_insn, note;
4231 int old_regno, new_regno;
4233 if (! v->always_executed
4234 || v->maybe_multiple
4235 || GET_CODE (v->add_val) != CONST_INT
4236 || ! next->always_executed
4237 || next->maybe_multiple
4238 || ! CONSTANT_P (next->add_val)
4239 || v->mult_val != const1_rtx
4240 || next->mult_val != const1_rtx
4241 || ! (biv_dead_after_loop
4242 || no_jumps_between_p (v->insn, next->insn)))
4244 vp = &v->next_iv;
4245 continue;
4247 offset = INTVAL (v->add_val);
4248 set = single_set (v->insn);
4249 add_val = plus_constant (next->add_val, offset);
4250 old_reg = v->dest_reg;
4251 dest_reg = gen_reg_rtx (v->mode);
4253 /* Unlike reg_iv_type / reg_iv_info, the other three arrays
4254 have been allocated with some slop space, so we may not
4255 actually need to reallocate them. If we do, the following
4256 if statement will be executed just once in this loop. */
4257 if ((unsigned) max_reg_num () > n_times_set->num_elements)
4259 /* Grow all the remaining arrays. */
4260 VARRAY_GROW (set_in_loop, nregs);
4261 VARRAY_GROW (n_times_set, nregs);
4262 VARRAY_GROW (may_not_optimize, nregs);
4263 VARRAY_GROW (reg_single_usage, nregs);
4266 if (! validate_change (next->insn, next->location, add_val, 0))
4268 vp = &v->next_iv;
4269 continue;
4272 /* Here we can try to eliminate the increment by combining
4273 it into the uses. */
4275 /* Set last_use_insn so that we can check against it. */
4277 for (last_use_insn = v->insn, p = NEXT_INSN (v->insn);
4278 p != next->insn;
4279 p = next_insn_in_loop (loop, p))
4281 if (!INSN_P (p))
4282 continue;
4283 if (reg_mentioned_p (old_reg, PATTERN (p)))
4285 last_use_insn = p;
4289 /* If we can't get the LUIDs for the insns, we can't
4290 calculate the lifetime. This is likely from unrolling
4291 of an inner loop, so there is little point in making this
4292 a DEST_REG giv anyways. */
4293 if (INSN_UID (v->insn) >= max_uid_for_loop
4294 || INSN_UID (last_use_insn) >= max_uid_for_loop
4295 || ! validate_change (v->insn, &SET_DEST (set), dest_reg, 0))
4297 /* Change the increment at NEXT back to what it was. */
4298 if (! validate_change (next->insn, next->location,
4299 next->add_val, 0))
4300 abort ();
4301 vp = &v->next_iv;
4302 continue;
4304 next->add_val = add_val;
4305 v->dest_reg = dest_reg;
4306 v->giv_type = DEST_REG;
4307 v->location = &SET_SRC (set);
4308 v->cant_derive = 0;
4309 v->combined_with = 0;
4310 v->maybe_dead = 0;
4311 v->derive_adjustment = 0;
4312 v->same = 0;
4313 v->ignore = 0;
4314 v->new_reg = 0;
4315 v->final_value = 0;
4316 v->same_insn = 0;
4317 v->auto_inc_opt = 0;
4318 v->unrolled = 0;
4319 v->shared = 0;
4320 v->derived_from = 0;
4321 v->always_computable = 1;
4322 v->always_executed = 1;
4323 v->replaceable = 1;
4324 v->no_const_addval = 0;
4326 old_regno = REGNO (old_reg);
4327 new_regno = REGNO (dest_reg);
4328 VARRAY_INT (set_in_loop, old_regno)--;
4329 VARRAY_INT (set_in_loop, new_regno) = 1;
4330 VARRAY_INT (n_times_set, old_regno)--;
4331 VARRAY_INT (n_times_set, new_regno) = 1;
4332 VARRAY_CHAR (may_not_optimize, new_regno) = 0;
4334 REG_IV_TYPE (new_regno) = GENERAL_INDUCT;
4335 REG_IV_INFO (new_regno) = v;
4337 /* If next_insn has a REG_EQUAL note that mentiones OLD_REG,
4338 it must be replaced. */
4339 note = find_reg_note (next->insn, REG_EQUAL, NULL_RTX);
4340 if (note && reg_mentioned_p (old_reg, XEXP (note, 0)))
4341 XEXP (note, 0) = copy_rtx (SET_SRC (single_set (next->insn)));
4343 /* Remove the increment from the list of biv increments,
4344 and record it as a giv. */
4345 *vp = next;
4346 bl->biv_count--;
4347 v->next_iv = bl->giv;
4348 bl->giv = v;
4349 bl->giv_count++;
4350 v->benefit = rtx_cost (SET_SRC (set), SET);
4351 bl->total_benefit += v->benefit;
4353 /* Now replace the biv with DEST_REG in all insns between
4354 the replaced increment and the next increment, and
4355 remember the last insn that needed a replacement. */
4356 for (last_use_insn = v->insn, p = NEXT_INSN (v->insn);
4357 p != next->insn;
4358 p = next_insn_in_loop (loop, p))
4360 rtx note;
4362 if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
4363 continue;
4364 if (reg_mentioned_p (old_reg, PATTERN (p)))
4366 last_use_insn = p;
4367 if (! validate_replace_rtx (old_reg, dest_reg, p))
4368 abort ();
4370 for (note = REG_NOTES (p); note; note = XEXP (note, 1))
4372 if (GET_CODE (note) == EXPR_LIST)
4373 XEXP (note, 0)
4374 = replace_rtx (XEXP (note, 0), old_reg, dest_reg);
4378 v->last_use = last_use_insn;
4379 v->lifetime = INSN_LUID (last_use_insn) - INSN_LUID (v->insn);
4380 /* If the lifetime is zero, it means that this register is really
4381 a dead store. So mark this as a giv that can be ignored.
4382 This will not prevent the biv from being eliminated. */
4383 if (v->lifetime == 0)
4384 v->ignore = 1;
4386 if (loop_dump_stream)
4387 fprintf (loop_dump_stream,
4388 "Increment %d of biv %d converted to giv %d.\n",
4389 INSN_UID (v->insn), old_regno, new_regno);
4393 last_increment_giv = max_reg_num () - 1;
4395 /* Search the loop for general induction variables. */
4397 for_each_insn_in_loop (loop, check_insn_for_givs);
4399 /* Try to calculate and save the number of loop iterations. This is
4400 set to zero if the actual number can not be calculated. This must
4401 be called after all giv's have been identified, since otherwise it may
4402 fail if the iteration variable is a giv. */
4404 loop_iterations (loop);
4406 /* Now for each giv for which we still don't know whether or not it is
4407 replaceable, check to see if it is replaceable because its final value
4408 can be calculated. This must be done after loop_iterations is called,
4409 so that final_giv_value will work correctly. */
4411 for (bl = loop_iv_list; bl; bl = bl->next)
4413 struct induction *v;
4415 for (v = bl->giv; v; v = v->next_iv)
4416 if (! v->replaceable && ! v->not_replaceable)
4417 check_final_value (loop, v);
4420 /* Try to prove that the loop counter variable (if any) is always
4421 nonnegative; if so, record that fact with a REG_NONNEG note
4422 so that "decrement and branch until zero" insn can be used. */
4423 check_dbra_loop (loop, insn_count);
4425 /* Create reg_map to hold substitutions for replaceable giv regs.
4426 Some givs might have been made from biv increments, so look at
4427 reg_iv_type for a suitable size. */
4428 reg_map_size = reg_iv_type->num_elements;
4429 reg_map = (rtx *) xcalloc (reg_map_size, sizeof (rtx));
4431 /* Examine each iv class for feasibility of strength reduction/induction
4432 variable elimination. */
4434 for (bl = loop_iv_list; bl; bl = bl->next)
4436 struct induction *v;
4437 int benefit;
4438 int all_reduced;
4439 rtx final_value = 0;
4440 unsigned int nregs;
4442 /* Test whether it will be possible to eliminate this biv
4443 provided all givs are reduced. This is possible if either
4444 the reg is not used outside the loop, or we can compute
4445 what its final value will be.
4447 For architectures with a decrement_and_branch_until_zero insn,
4448 don't do this if we put a REG_NONNEG note on the endtest for
4449 this biv. */
4451 /* Compare against bl->init_insn rather than loop_start.
4452 We aren't concerned with any uses of the biv between
4453 init_insn and loop_start since these won't be affected
4454 by the value of the biv elsewhere in the function, so
4455 long as init_insn doesn't use the biv itself.
4456 March 14, 1989 -- self@bayes.arc.nasa.gov */
4458 if ((uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4459 && bl->init_insn
4460 && INSN_UID (bl->init_insn) < max_uid_for_loop
4461 && uid_luid[REGNO_FIRST_UID (bl->regno)] >= INSN_LUID (bl->init_insn)
4462 #ifdef HAVE_decrement_and_branch_until_zero
4463 && ! bl->nonneg
4464 #endif
4465 && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4466 || ((final_value = final_biv_value (loop, bl))
4467 #ifdef HAVE_decrement_and_branch_until_zero
4468 && ! bl->nonneg
4469 #endif
4471 bl->eliminable = maybe_eliminate_biv (loop, bl, 0, threshold,
4472 insn_count);
4473 else
4475 if (loop_dump_stream)
4477 fprintf (loop_dump_stream,
4478 "Cannot eliminate biv %d.\n",
4479 bl->regno);
4480 fprintf (loop_dump_stream,
4481 "First use: insn %d, last use: insn %d.\n",
4482 REGNO_FIRST_UID (bl->regno),
4483 REGNO_LAST_UID (bl->regno));
4487 /* Combine all giv's for this iv_class. */
4488 combine_givs (bl);
4490 /* This will be true at the end, if all givs which depend on this
4491 biv have been strength reduced.
4492 We can't (currently) eliminate the biv unless this is so. */
4493 all_reduced = 1;
4495 /* Check each giv in this class to see if we will benefit by reducing
4496 it. Skip giv's combined with others. */
4497 for (v = bl->giv; v; v = v->next_iv)
4499 struct induction *tv;
4501 if (v->ignore || v->same)
4502 continue;
4504 benefit = v->benefit;
4506 /* Reduce benefit if not replaceable, since we will insert
4507 a move-insn to replace the insn that calculates this giv.
4508 Don't do this unless the giv is a user variable, since it
4509 will often be marked non-replaceable because of the duplication
4510 of the exit code outside the loop. In such a case, the copies
4511 we insert are dead and will be deleted. So they don't have
4512 a cost. Similar situations exist. */
4513 /* ??? The new final_[bg]iv_value code does a much better job
4514 of finding replaceable giv's, and hence this code may no longer
4515 be necessary. */
4516 if (! v->replaceable && ! bl->eliminable
4517 && REG_USERVAR_P (v->dest_reg))
4518 benefit -= copy_cost;
4520 /* Decrease the benefit to count the add-insns that we will
4521 insert to increment the reduced reg for the giv. */
4522 benefit -= add_cost * bl->biv_count;
4524 /* Decide whether to strength-reduce this giv or to leave the code
4525 unchanged (recompute it from the biv each time it is used).
4526 This decision can be made independently for each giv. */
4528 #ifdef AUTO_INC_DEC
4529 /* Attempt to guess whether autoincrement will handle some of the
4530 new add insns; if so, increase BENEFIT (undo the subtraction of
4531 add_cost that was done above). */
4532 if (v->giv_type == DEST_ADDR
4533 && GET_CODE (v->mult_val) == CONST_INT)
4535 if (HAVE_POST_INCREMENT
4536 && INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4537 benefit += add_cost * bl->biv_count;
4538 else if (HAVE_PRE_INCREMENT
4539 && INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4540 benefit += add_cost * bl->biv_count;
4541 else if (HAVE_POST_DECREMENT
4542 && -INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4543 benefit += add_cost * bl->biv_count;
4544 else if (HAVE_PRE_DECREMENT
4545 && -INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4546 benefit += add_cost * bl->biv_count;
4548 #endif
4550 /* If an insn is not to be strength reduced, then set its ignore
4551 flag, and clear all_reduced. */
4553 /* A giv that depends on a reversed biv must be reduced if it is
4554 used after the loop exit, otherwise, it would have the wrong
4555 value after the loop exit. To make it simple, just reduce all
4556 of such giv's whether or not we know they are used after the loop
4557 exit. */
4559 if ( ! flag_reduce_all_givs && v->lifetime * threshold * benefit < insn_count
4560 && ! bl->reversed )
4562 if (loop_dump_stream)
4563 fprintf (loop_dump_stream,
4564 "giv of insn %d not worth while, %d vs %d.\n",
4565 INSN_UID (v->insn),
4566 v->lifetime * threshold * benefit, insn_count);
4567 v->ignore = 1;
4568 all_reduced = 0;
4570 else
4572 /* Check that we can increment the reduced giv without a
4573 multiply insn. If not, reject it. */
4575 for (tv = bl->biv; tv; tv = tv->next_iv)
4576 if (tv->mult_val == const1_rtx
4577 && ! product_cheap_p (tv->add_val, v->mult_val))
4579 if (loop_dump_stream)
4580 fprintf (loop_dump_stream,
4581 "giv of insn %d: would need a multiply.\n",
4582 INSN_UID (v->insn));
4583 v->ignore = 1;
4584 all_reduced = 0;
4585 break;
4590 /* Check for givs whose first use is their definition and whose
4591 last use is the definition of another giv. If so, it is likely
4592 dead and should not be used to derive another giv nor to
4593 eliminate a biv. */
4594 for (v = bl->giv; v; v = v->next_iv)
4596 if (v->ignore
4597 || (v->same && v->same->ignore))
4598 continue;
4600 if (v->last_use)
4602 struct induction *v1;
4604 for (v1 = bl->giv; v1; v1 = v1->next_iv)
4605 if (v->last_use == v1->insn)
4606 v->maybe_dead = 1;
4608 else if (v->giv_type == DEST_REG
4609 && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4611 struct induction *v1;
4613 for (v1 = bl->giv; v1; v1 = v1->next_iv)
4614 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4615 v->maybe_dead = 1;
4619 /* Now that we know which givs will be reduced, try to rearrange the
4620 combinations to reduce register pressure.
4621 recombine_givs calls find_life_end, which needs reg_iv_type and
4622 reg_iv_info to be valid for all pseudos. We do the necessary
4623 reallocation here since it allows to check if there are still
4624 more bivs to process. */
4625 nregs = max_reg_num ();
4626 if (nregs > reg_iv_type->num_elements)
4628 /* If there are still more bivs to process, allocate some slack
4629 space so that we're not constantly reallocating these arrays. */
4630 if (bl->next)
4631 nregs += nregs / 4;
4632 /* Reallocate reg_iv_type and reg_iv_info. */
4633 VARRAY_GROW (reg_iv_type, nregs);
4634 VARRAY_GROW (reg_iv_info, nregs);
4636 recombine_givs (loop, bl, unroll_p);
4638 /* Reduce each giv that we decided to reduce. */
4640 for (v = bl->giv; v; v = v->next_iv)
4642 struct induction *tv;
4643 if (! v->ignore && v->same == 0)
4645 int auto_inc_opt = 0;
4647 /* If the code for derived givs immediately below has already
4648 allocated a new_reg, we must keep it. */
4649 if (! v->new_reg)
4650 v->new_reg = gen_reg_rtx (v->mode);
4652 if (v->derived_from)
4654 struct induction *d = v->derived_from;
4656 /* In case d->dest_reg is not replaceable, we have
4657 to replace it in v->insn now. */
4658 if (! d->new_reg)
4659 d->new_reg = gen_reg_rtx (d->mode);
4660 PATTERN (v->insn)
4661 = replace_rtx (PATTERN (v->insn), d->dest_reg, d->new_reg);
4662 PATTERN (v->insn)
4663 = replace_rtx (PATTERN (v->insn), v->dest_reg, v->new_reg);
4664 /* For each place where the biv is incremented, add an
4665 insn to set the new, reduced reg for the giv.
4666 We used to do this only for biv_count != 1, but
4667 this fails when there is a giv after a single biv
4668 increment, e.g. when the last giv was expressed as
4669 pre-decrement. */
4670 for (tv = bl->biv; tv; tv = tv->next_iv)
4672 /* We always emit reduced giv increments before the
4673 biv increment when bl->biv_count != 1. So by
4674 emitting the add insns for derived givs after the
4675 biv increment, they pick up the updated value of
4676 the reduced giv.
4677 If the reduced giv is processed with
4678 auto_inc_opt == 1, then it is incremented earlier
4679 than the biv, hence we'll still pick up the right
4680 value.
4681 If it's processed with auto_inc_opt == -1,
4682 that implies that the biv increment is before the
4683 first reduced giv's use. The derived giv's lifetime
4684 is after the reduced giv's lifetime, hence in this
4685 case, the biv increment doesn't matter. */
4686 emit_insn_after (copy_rtx (PATTERN (v->insn)), tv->insn);
4688 continue;
4691 #ifdef AUTO_INC_DEC
4692 /* If the target has auto-increment addressing modes, and
4693 this is an address giv, then try to put the increment
4694 immediately after its use, so that flow can create an
4695 auto-increment addressing mode. */
4696 if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4697 && bl->biv->always_executed && ! bl->biv->maybe_multiple
4698 /* We don't handle reversed biv's because bl->biv->insn
4699 does not have a valid INSN_LUID. */
4700 && ! bl->reversed
4701 && v->always_executed && ! v->maybe_multiple
4702 && INSN_UID (v->insn) < max_uid_for_loop)
4704 /* If other giv's have been combined with this one, then
4705 this will work only if all uses of the other giv's occur
4706 before this giv's insn. This is difficult to check.
4708 We simplify this by looking for the common case where
4709 there is one DEST_REG giv, and this giv's insn is the
4710 last use of the dest_reg of that DEST_REG giv. If the
4711 increment occurs after the address giv, then we can
4712 perform the optimization. (Otherwise, the increment
4713 would have to go before other_giv, and we would not be
4714 able to combine it with the address giv to get an
4715 auto-inc address.) */
4716 if (v->combined_with)
4718 struct induction *other_giv = 0;
4720 for (tv = bl->giv; tv; tv = tv->next_iv)
4721 if (tv->same == v)
4723 if (other_giv)
4724 break;
4725 else
4726 other_giv = tv;
4728 if (! tv && other_giv
4729 && REGNO (other_giv->dest_reg) < max_reg_before_loop
4730 && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4731 == INSN_UID (v->insn))
4732 && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4733 auto_inc_opt = 1;
4735 /* Check for case where increment is before the address
4736 giv. Do this test in "loop order". */
4737 else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4738 && (INSN_LUID (v->insn) < INSN_LUID (loop_scan_start)
4739 || (INSN_LUID (bl->biv->insn)
4740 > INSN_LUID (loop_scan_start))))
4741 || (INSN_LUID (v->insn) < INSN_LUID (loop_scan_start)
4742 && (INSN_LUID (loop_scan_start)
4743 < INSN_LUID (bl->biv->insn))))
4744 auto_inc_opt = -1;
4745 else
4746 auto_inc_opt = 1;
4748 #ifdef HAVE_cc0
4750 rtx prev;
4752 /* We can't put an insn immediately after one setting
4753 cc0, or immediately before one using cc0. */
4754 if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4755 || (auto_inc_opt == -1
4756 && (prev = prev_nonnote_insn (v->insn)) != 0
4757 && GET_RTX_CLASS (GET_CODE (prev)) == 'i'
4758 && sets_cc0_p (PATTERN (prev))))
4759 auto_inc_opt = 0;
4761 #endif
4763 if (auto_inc_opt)
4764 v->auto_inc_opt = 1;
4766 #endif
4768 /* For each place where the biv is incremented, add an insn
4769 to increment the new, reduced reg for the giv. */
4770 for (tv = bl->biv; tv; tv = tv->next_iv)
4772 rtx insert_before;
4774 if (! auto_inc_opt)
4775 insert_before = tv->insn;
4776 else if (auto_inc_opt == 1)
4777 insert_before = NEXT_INSN (v->insn);
4778 else
4779 insert_before = v->insn;
4781 if (tv->mult_val == const1_rtx)
4782 emit_iv_add_mult (tv->add_val, v->mult_val,
4783 v->new_reg, v->new_reg, insert_before);
4784 else /* tv->mult_val == const0_rtx */
4785 /* A multiply is acceptable here
4786 since this is presumed to be seldom executed. */
4787 emit_iv_add_mult (tv->add_val, v->mult_val,
4788 v->add_val, v->new_reg, insert_before);
4791 /* Add code at loop start to initialize giv's reduced reg. */
4793 emit_iv_add_mult (bl->initial_value, v->mult_val,
4794 v->add_val, v->new_reg, loop_start);
4798 /* Rescan all givs. If a giv is the same as a giv not reduced, mark it
4799 as not reduced.
4801 For each giv register that can be reduced now: if replaceable,
4802 substitute reduced reg wherever the old giv occurs;
4803 else add new move insn "giv_reg = reduced_reg". */
4805 for (v = bl->giv; v; v = v->next_iv)
4807 if (v->same && v->same->ignore)
4808 v->ignore = 1;
4810 if (v->ignore)
4811 continue;
4813 /* Update expression if this was combined, in case other giv was
4814 replaced. */
4815 if (v->same)
4816 v->new_reg = replace_rtx (v->new_reg,
4817 v->same->dest_reg, v->same->new_reg);
4819 if (v->giv_type == DEST_ADDR)
4820 /* Store reduced reg as the address in the memref where we found
4821 this giv. */
4822 validate_change (v->insn, v->location, v->new_reg, 0);
4823 else if (v->replaceable)
4825 reg_map[REGNO (v->dest_reg)] = v->new_reg;
4827 #if 0
4828 /* I can no longer duplicate the original problem. Perhaps
4829 this is unnecessary now? */
4831 /* Replaceable; it isn't strictly necessary to delete the old
4832 insn and emit a new one, because v->dest_reg is now dead.
4834 However, especially when unrolling loops, the special
4835 handling for (set REG0 REG1) in the second cse pass may
4836 make v->dest_reg live again. To avoid this problem, emit
4837 an insn to set the original giv reg from the reduced giv.
4838 We can not delete the original insn, since it may be part
4839 of a LIBCALL, and the code in flow that eliminates dead
4840 libcalls will fail if it is deleted. */
4841 emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
4842 v->insn);
4843 #endif
4845 else
4847 /* Not replaceable; emit an insn to set the original giv reg from
4848 the reduced giv, same as above. */
4849 emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
4850 v->insn);
4853 /* When a loop is reversed, givs which depend on the reversed
4854 biv, and which are live outside the loop, must be set to their
4855 correct final value. This insn is only needed if the giv is
4856 not replaceable. The correct final value is the same as the
4857 value that the giv starts the reversed loop with. */
4858 if (bl->reversed && ! v->replaceable)
4859 emit_iv_add_mult (bl->initial_value, v->mult_val,
4860 v->add_val, v->dest_reg, end_insert_before);
4861 else if (v->final_value)
4863 rtx insert_before;
4865 /* If the loop has multiple exits, emit the insn before the
4866 loop to ensure that it will always be executed no matter
4867 how the loop exits. Otherwise, emit the insn after the loop,
4868 since this is slightly more efficient. */
4869 if (loop->exit_count)
4870 insert_before = loop_start;
4871 else
4872 insert_before = end_insert_before;
4873 emit_insn_before (gen_move_insn (v->dest_reg, v->final_value),
4874 insert_before);
4876 #if 0
4877 /* If the insn to set the final value of the giv was emitted
4878 before the loop, then we must delete the insn inside the loop
4879 that sets it. If this is a LIBCALL, then we must delete
4880 every insn in the libcall. Note, however, that
4881 final_giv_value will only succeed when there are multiple
4882 exits if the giv is dead at each exit, hence it does not
4883 matter that the original insn remains because it is dead
4884 anyways. */
4885 /* Delete the insn inside the loop that sets the giv since
4886 the giv is now set before (or after) the loop. */
4887 delete_insn (v->insn);
4888 #endif
4891 if (loop_dump_stream)
4893 fprintf (loop_dump_stream, "giv at %d reduced to ",
4894 INSN_UID (v->insn));
4895 print_rtl (loop_dump_stream, v->new_reg);
4896 fprintf (loop_dump_stream, "\n");
4900 /* All the givs based on the biv bl have been reduced if they
4901 merit it. */
4903 /* For each giv not marked as maybe dead that has been combined with a
4904 second giv, clear any "maybe dead" mark on that second giv.
4905 v->new_reg will either be or refer to the register of the giv it
4906 combined with.
4908 Doing this clearing avoids problems in biv elimination where a
4909 giv's new_reg is a complex value that can't be put in the insn but
4910 the giv combined with (with a reg as new_reg) is marked maybe_dead.
4911 Since the register will be used in either case, we'd prefer it be
4912 used from the simpler giv. */
4914 for (v = bl->giv; v; v = v->next_iv)
4915 if (! v->maybe_dead && v->same)
4916 v->same->maybe_dead = 0;
4918 /* Try to eliminate the biv, if it is a candidate.
4919 This won't work if ! all_reduced,
4920 since the givs we planned to use might not have been reduced.
4922 We have to be careful that we didn't initially think we could eliminate
4923 this biv because of a giv that we now think may be dead and shouldn't
4924 be used as a biv replacement.
4926 Also, there is the possibility that we may have a giv that looks
4927 like it can be used to eliminate a biv, but the resulting insn
4928 isn't valid. This can happen, for example, on the 88k, where a
4929 JUMP_INSN can compare a register only with zero. Attempts to
4930 replace it with a compare with a constant will fail.
4932 Note that in cases where this call fails, we may have replaced some
4933 of the occurrences of the biv with a giv, but no harm was done in
4934 doing so in the rare cases where it can occur. */
4936 if (all_reduced == 1 && bl->eliminable
4937 && maybe_eliminate_biv (loop, bl, 1, threshold, insn_count))
4939 /* ?? If we created a new test to bypass the loop entirely,
4940 or otherwise drop straight in, based on this test, then
4941 we might want to rewrite it also. This way some later
4942 pass has more hope of removing the initialization of this
4943 biv entirely. */
4945 /* If final_value != 0, then the biv may be used after loop end
4946 and we must emit an insn to set it just in case.
4948 Reversed bivs already have an insn after the loop setting their
4949 value, so we don't need another one. We can't calculate the
4950 proper final value for such a biv here anyways. */
4951 if (final_value != 0 && ! bl->reversed)
4953 rtx insert_before;
4955 /* If the loop has multiple exits, emit the insn before the
4956 loop to ensure that it will always be executed no matter
4957 how the loop exits. Otherwise, emit the insn after the
4958 loop, since this is slightly more efficient. */
4959 if (loop->exit_count)
4960 insert_before = loop_start;
4961 else
4962 insert_before = end_insert_before;
4964 emit_insn_before (gen_move_insn (bl->biv->dest_reg, final_value),
4965 end_insert_before);
4968 #if 0
4969 /* Delete all of the instructions inside the loop which set
4970 the biv, as they are all dead. If is safe to delete them,
4971 because an insn setting a biv will never be part of a libcall. */
4972 /* However, deleting them will invalidate the regno_last_uid info,
4973 so keeping them around is more convenient. Final_biv_value
4974 will only succeed when there are multiple exits if the biv
4975 is dead at each exit, hence it does not matter that the original
4976 insn remains, because it is dead anyways. */
4977 for (v = bl->biv; v; v = v->next_iv)
4978 delete_insn (v->insn);
4979 #endif
4981 if (loop_dump_stream)
4982 fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
4983 bl->regno);
4987 /* Go through all the instructions in the loop, making all the
4988 register substitutions scheduled in REG_MAP. */
4990 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
4991 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4992 || GET_CODE (p) == CALL_INSN)
4994 replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
4995 replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
4996 INSN_CODE (p) = -1;
4999 if (loop_info->n_iterations > 0)
5001 /* When we completely unroll a loop we will likely not need the increment
5002 of the loop BIV and we will not need the conditional branch at the
5003 end of the loop. */
5004 unrolled_insn_copies = insn_count - 2;
5006 #ifdef HAVE_cc0
5007 /* When we completely unroll a loop on a HAVE_cc0 machine we will not
5008 need the comparison before the conditional branch at the end of the
5009 loop. */
5010 unrolled_insn_copies -= 1;
5011 #endif
5013 /* We'll need one copy for each loop iteration. */
5014 unrolled_insn_copies *= loop_info->n_iterations;
5016 /* A little slop to account for the ability to remove initialization
5017 code, better CSE, and other secondary benefits of completely
5018 unrolling some loops. */
5019 unrolled_insn_copies -= 1;
5021 /* Clamp the value. */
5022 if (unrolled_insn_copies < 0)
5023 unrolled_insn_copies = 0;
5026 /* Unroll loops from within strength reduction so that we can use the
5027 induction variable information that strength_reduce has already
5028 collected. Always unroll loops that would be as small or smaller
5029 unrolled than when rolled. */
5030 if (unroll_p
5031 || (loop_info->n_iterations > 0
5032 && unrolled_insn_copies <= insn_count))
5033 unroll_loop (loop, insn_count, end_insert_before, 1);
5035 #ifdef HAVE_decrement_and_branch_on_count
5036 /* Instrument the loop with BCT insn. */
5037 if (HAVE_decrement_and_branch_on_count && bct_p
5038 && flag_branch_on_count_reg)
5039 insert_bct (loop);
5040 #endif /* HAVE_decrement_and_branch_on_count */
5042 if (loop_dump_stream)
5043 fprintf (loop_dump_stream, "\n");
5045 egress:
5046 VARRAY_FREE (reg_iv_type);
5047 VARRAY_FREE (reg_iv_info);
5048 free (reg_biv_class);
5049 if (reg_map)
5050 free (reg_map);
5053 /*Record all basic induction variables calculated in the insn. */
5054 static rtx
5055 check_insn_for_bivs (loop, p, not_every_iteration, maybe_multiple)
5056 struct loop *loop;
5057 rtx p;
5058 int not_every_iteration;
5059 int maybe_multiple;
5061 rtx set;
5062 rtx dest_reg;
5063 rtx inc_val;
5064 rtx mult_val;
5065 rtx *location;
5067 if (GET_CODE (p) == INSN
5068 && (set = single_set (p))
5069 && GET_CODE (SET_DEST (set)) == REG)
5071 dest_reg = SET_DEST (set);
5072 if (REGNO (dest_reg) < max_reg_before_loop
5073 && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
5074 && REG_IV_TYPE (REGNO (dest_reg)) != NOT_BASIC_INDUCT)
5076 int multi_insn_incr = 0;
5078 if (basic_induction_var (loop, SET_SRC (set),
5079 GET_MODE (SET_SRC (set)),
5080 dest_reg, p, &inc_val, &mult_val,
5081 &location, &multi_insn_incr))
5083 /* It is a possible basic induction variable.
5084 Create and initialize an induction structure for it. */
5086 struct induction *v
5087 = (struct induction *) oballoc (sizeof (struct induction));
5089 record_biv (v, p, dest_reg, inc_val, mult_val, location,
5090 not_every_iteration, maybe_multiple,
5091 multi_insn_incr);
5092 REG_IV_TYPE (REGNO (dest_reg)) = BASIC_INDUCT;
5094 else if (REGNO (dest_reg) < max_reg_before_loop)
5095 REG_IV_TYPE (REGNO (dest_reg)) = NOT_BASIC_INDUCT;
5098 return p;
5101 /* Record all givs calculated in the insn.
5102 A register is a giv if: it is only set once, it is a function of a
5103 biv and a constant (or invariant), and it is not a biv. */
5104 static rtx
5105 check_insn_for_givs (loop, p, not_every_iteration, maybe_multiple)
5106 struct loop *loop;
5107 rtx p;
5108 int not_every_iteration;
5109 int maybe_multiple;
5111 rtx set;
5112 /* Look for a general induction variable in a register. */
5113 if (GET_CODE (p) == INSN
5114 && (set = single_set (p))
5115 && GET_CODE (SET_DEST (set)) == REG
5116 && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
5118 rtx src_reg;
5119 rtx dest_reg;
5120 rtx add_val;
5121 rtx mult_val;
5122 int benefit;
5123 rtx regnote = 0;
5124 rtx last_consec_insn;
5126 dest_reg = SET_DEST (set);
5127 if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
5128 return p;
5130 if (/* SET_SRC is a giv. */
5131 (general_induction_var (loop, SET_SRC (set), &src_reg, &add_val,
5132 &mult_val, 0, &benefit, VOIDmode)
5133 /* Equivalent expression is a giv. */
5134 || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
5135 && general_induction_var (loop, XEXP (regnote, 0), &src_reg,
5136 &add_val, &mult_val, 0,
5137 &benefit, VOIDmode)))
5138 /* Don't try to handle any regs made by loop optimization.
5139 We have nothing on them in regno_first_uid, etc. */
5140 && REGNO (dest_reg) < max_reg_before_loop
5141 /* Don't recognize a BASIC_INDUCT_VAR here. */
5142 && dest_reg != src_reg
5143 /* This must be the only place where the register is set. */
5144 && (VARRAY_INT (n_times_set, REGNO (dest_reg)) == 1
5145 /* or all sets must be consecutive and make a giv. */
5146 || (benefit = consec_sets_giv (loop, benefit, p,
5147 src_reg, dest_reg,
5148 &add_val, &mult_val,
5149 &last_consec_insn))))
5151 struct induction *v
5152 = (struct induction *) oballoc (sizeof (struct induction));
5154 /* If this is a library call, increase benefit. */
5155 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
5156 benefit += libcall_benefit (p);
5158 /* Skip the consecutive insns, if there are any. */
5159 if (VARRAY_INT (n_times_set, REGNO (dest_reg)) != 1)
5160 p = last_consec_insn;
5162 record_giv (loop, v, p, src_reg, dest_reg, mult_val, add_val,
5163 benefit, DEST_REG, not_every_iteration,
5164 maybe_multiple, NULL_PTR);
5169 #ifndef DONT_REDUCE_ADDR
5170 /* Look for givs which are memory addresses. */
5171 /* This resulted in worse code on a VAX 8600. I wonder if it
5172 still does. */
5173 if (GET_CODE (p) == INSN)
5174 find_mem_givs (loop, PATTERN (p), p, not_every_iteration,
5175 maybe_multiple);
5176 #endif
5178 /* Update the status of whether giv can derive other givs. This can
5179 change when we pass a label or an insn that updates a biv. */
5180 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5181 || GET_CODE (p) == CODE_LABEL)
5182 update_giv_derive (loop, p);
5183 return p;
5186 /* Return 1 if X is a valid source for an initial value (or as value being
5187 compared against in an initial test).
5189 X must be either a register or constant and must not be clobbered between
5190 the current insn and the start of the loop.
5192 INSN is the insn containing X. */
5194 static int
5195 valid_initial_value_p (x, insn, call_seen, loop_start)
5196 rtx x;
5197 rtx insn;
5198 int call_seen;
5199 rtx loop_start;
5201 if (CONSTANT_P (x))
5202 return 1;
5204 /* Only consider pseudos we know about initialized in insns whose luids
5205 we know. */
5206 if (GET_CODE (x) != REG
5207 || REGNO (x) >= max_reg_before_loop)
5208 return 0;
5210 /* Don't use call-clobbered registers across a call which clobbers it. On
5211 some machines, don't use any hard registers at all. */
5212 if (REGNO (x) < FIRST_PSEUDO_REGISTER
5213 && (SMALL_REGISTER_CLASSES
5214 || (call_used_regs[REGNO (x)] && call_seen)))
5215 return 0;
5217 /* Don't use registers that have been clobbered before the start of the
5218 loop. */
5219 if (reg_set_between_p (x, insn, loop_start))
5220 return 0;
5222 return 1;
5225 /* Scan X for memory refs and check each memory address
5226 as a possible giv. INSN is the insn whose pattern X comes from.
5227 NOT_EVERY_ITERATION is 1 if the insn might not be executed during
5228 every loop iteration. MAYBE_MULTIPLE is 1 if the insn might be executed
5229 more thanonce in each loop iteration. */
5231 static void
5232 find_mem_givs (loop, x, insn, not_every_iteration, maybe_multiple)
5233 const struct loop *loop;
5234 rtx x;
5235 rtx insn;
5236 int not_every_iteration, maybe_multiple;
5238 register int i, j;
5239 register enum rtx_code code;
5240 register const char *fmt;
5242 if (x == 0)
5243 return;
5245 code = GET_CODE (x);
5246 switch (code)
5248 case REG:
5249 case CONST_INT:
5250 case CONST:
5251 case CONST_DOUBLE:
5252 case SYMBOL_REF:
5253 case LABEL_REF:
5254 case PC:
5255 case CC0:
5256 case ADDR_VEC:
5257 case ADDR_DIFF_VEC:
5258 case USE:
5259 case CLOBBER:
5260 return;
5262 case MEM:
5264 rtx src_reg;
5265 rtx add_val;
5266 rtx mult_val;
5267 int benefit;
5269 /* This code used to disable creating GIVs with mult_val == 1 and
5270 add_val == 0. However, this leads to lost optimizations when
5271 it comes time to combine a set of related DEST_ADDR GIVs, since
5272 this one would not be seen. */
5274 if (general_induction_var (loop, XEXP (x, 0), &src_reg, &add_val,
5275 &mult_val, 1, &benefit, GET_MODE (x)))
5277 /* Found one; record it. */
5278 struct induction *v
5279 = (struct induction *) oballoc (sizeof (struct induction));
5281 record_giv (loop, v, insn, src_reg, addr_placeholder, mult_val,
5282 add_val, benefit, DEST_ADDR, not_every_iteration,
5283 maybe_multiple, &XEXP (x, 0));
5285 v->mem_mode = GET_MODE (x);
5288 return;
5290 default:
5291 break;
5294 /* Recursively scan the subexpressions for other mem refs. */
5296 fmt = GET_RTX_FORMAT (code);
5297 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5298 if (fmt[i] == 'e')
5299 find_mem_givs (loop, XEXP (x, i), insn, not_every_iteration,
5300 maybe_multiple);
5301 else if (fmt[i] == 'E')
5302 for (j = 0; j < XVECLEN (x, i); j++)
5303 find_mem_givs (loop, XVECEXP (x, i, j), insn, not_every_iteration,
5304 maybe_multiple);
5307 /* Fill in the data about one biv update.
5308 V is the `struct induction' in which we record the biv. (It is
5309 allocated by the caller, with alloca.)
5310 INSN is the insn that sets it.
5311 DEST_REG is the biv's reg.
5313 MULT_VAL is const1_rtx if the biv is being incremented here, in which case
5314 INC_VAL is the increment. Otherwise, MULT_VAL is const0_rtx and the biv is
5315 being set to INC_VAL.
5317 NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
5318 executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
5319 can be executed more than once per iteration. If MAYBE_MULTIPLE
5320 and NOT_EVERY_ITERATION are both zero, we know that the biv update is
5321 executed exactly once per iteration. */
5323 static void
5324 record_biv (v, insn, dest_reg, inc_val, mult_val, location,
5325 not_every_iteration, maybe_multiple, multi_insn_incr)
5326 struct induction *v;
5327 rtx insn;
5328 rtx dest_reg;
5329 rtx inc_val;
5330 rtx mult_val;
5331 rtx *location;
5332 int not_every_iteration;
5333 int maybe_multiple;
5334 int multi_insn_incr;
5336 struct iv_class *bl;
5338 v->insn = insn;
5339 v->src_reg = dest_reg;
5340 v->dest_reg = dest_reg;
5341 v->mult_val = mult_val;
5342 v->add_val = inc_val;
5343 v->location = location;
5344 v->mode = GET_MODE (dest_reg);
5345 v->always_computable = ! not_every_iteration;
5346 v->always_executed = ! not_every_iteration;
5347 v->maybe_multiple = maybe_multiple;
5348 v->multi_insn_incr = multi_insn_incr;
5350 /* Add this to the reg's iv_class, creating a class
5351 if this is the first incrementation of the reg. */
5353 bl = reg_biv_class[REGNO (dest_reg)];
5354 if (bl == 0)
5356 /* Create and initialize new iv_class. */
5358 bl = (struct iv_class *) oballoc (sizeof (struct iv_class));
5360 bl->regno = REGNO (dest_reg);
5361 bl->biv = 0;
5362 bl->giv = 0;
5363 bl->biv_count = 0;
5364 bl->giv_count = 0;
5366 /* Set initial value to the reg itself. */
5367 bl->initial_value = dest_reg;
5368 /* We haven't seen the initializing insn yet */
5369 bl->init_insn = 0;
5370 bl->init_set = 0;
5371 bl->initial_test = 0;
5372 bl->incremented = 0;
5373 bl->eliminable = 0;
5374 bl->nonneg = 0;
5375 bl->reversed = 0;
5376 bl->total_benefit = 0;
5378 /* Add this class to loop_iv_list. */
5379 bl->next = loop_iv_list;
5380 loop_iv_list = bl;
5382 /* Put it in the array of biv register classes. */
5383 reg_biv_class[REGNO (dest_reg)] = bl;
5386 /* Update IV_CLASS entry for this biv. */
5387 v->next_iv = bl->biv;
5388 bl->biv = v;
5389 bl->biv_count++;
5390 if (mult_val == const1_rtx)
5391 bl->incremented = 1;
5393 if (loop_dump_stream)
5395 fprintf (loop_dump_stream,
5396 "Insn %d: possible biv, reg %d,",
5397 INSN_UID (insn), REGNO (dest_reg));
5398 if (GET_CODE (inc_val) == CONST_INT)
5400 fprintf (loop_dump_stream, " const =");
5401 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (inc_val));
5402 fputc ('\n', loop_dump_stream);
5404 else
5406 fprintf (loop_dump_stream, " const = ");
5407 print_rtl (loop_dump_stream, inc_val);
5408 fprintf (loop_dump_stream, "\n");
5413 /* Fill in the data about one giv.
5414 V is the `struct induction' in which we record the giv. (It is
5415 allocated by the caller, with alloca.)
5416 INSN is the insn that sets it.
5417 BENEFIT estimates the savings from deleting this insn.
5418 TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
5419 into a register or is used as a memory address.
5421 SRC_REG is the biv reg which the giv is computed from.
5422 DEST_REG is the giv's reg (if the giv is stored in a reg).
5423 MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
5424 LOCATION points to the place where this giv's value appears in INSN. */
5426 static void
5427 record_giv (loop, v, insn, src_reg, dest_reg, mult_val, add_val, benefit,
5428 type, not_every_iteration, maybe_multiple, location)
5429 const struct loop *loop;
5430 struct induction *v;
5431 rtx insn;
5432 rtx src_reg;
5433 rtx dest_reg;
5434 rtx mult_val, add_val;
5435 int benefit;
5436 enum g_types type;
5437 int not_every_iteration, maybe_multiple;
5438 rtx *location;
5440 struct induction *b;
5441 struct iv_class *bl;
5442 rtx set = single_set (insn);
5443 rtx temp;
5445 /* Attempt to prove constantness of the values. */
5446 temp = simplify_rtx (add_val);
5447 if (temp)
5448 add_val = temp;
5450 v->insn = insn;
5451 v->src_reg = src_reg;
5452 v->giv_type = type;
5453 v->dest_reg = dest_reg;
5454 v->mult_val = mult_val;
5455 v->add_val = add_val;
5456 v->benefit = benefit;
5457 v->location = location;
5458 v->cant_derive = 0;
5459 v->combined_with = 0;
5460 v->maybe_multiple = maybe_multiple;
5461 v->multi_insn_incr = 0;
5462 v->maybe_dead = 0;
5463 v->derive_adjustment = 0;
5464 v->same = 0;
5465 v->ignore = 0;
5466 v->new_reg = 0;
5467 v->final_value = 0;
5468 v->same_insn = 0;
5469 v->auto_inc_opt = 0;
5470 v->unrolled = 0;
5471 v->shared = 0;
5472 v->derived_from = 0;
5473 v->last_use = 0;
5475 /* The v->always_computable field is used in update_giv_derive, to
5476 determine whether a giv can be used to derive another giv. For a
5477 DEST_REG giv, INSN computes a new value for the giv, so its value
5478 isn't computable if INSN insn't executed every iteration.
5479 However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
5480 it does not compute a new value. Hence the value is always computable
5481 regardless of whether INSN is executed each iteration. */
5483 if (type == DEST_ADDR)
5484 v->always_computable = 1;
5485 else
5486 v->always_computable = ! not_every_iteration;
5488 v->always_executed = ! not_every_iteration;
5490 if (type == DEST_ADDR)
5492 v->mode = GET_MODE (*location);
5493 v->lifetime = 1;
5495 else /* type == DEST_REG */
5497 v->mode = GET_MODE (SET_DEST (set));
5499 v->lifetime = (uid_luid[REGNO_LAST_UID (REGNO (dest_reg))]
5500 - uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))]);
5502 /* If the lifetime is zero, it means that this register is
5503 really a dead store. So mark this as a giv that can be
5504 ignored. This will not prevent the biv from being eliminated. */
5505 if (v->lifetime == 0)
5506 v->ignore = 1;
5508 REG_IV_TYPE (REGNO (dest_reg)) = GENERAL_INDUCT;
5509 REG_IV_INFO (REGNO (dest_reg)) = v;
5512 /* Add the giv to the class of givs computed from one biv. */
5514 bl = reg_biv_class[REGNO (src_reg)];
5515 if (bl)
5517 v->next_iv = bl->giv;
5518 bl->giv = v;
5519 /* Don't count DEST_ADDR. This is supposed to count the number of
5520 insns that calculate givs. */
5521 if (type == DEST_REG)
5522 bl->giv_count++;
5523 bl->total_benefit += benefit;
5525 else
5526 /* Fatal error, biv missing for this giv? */
5527 abort ();
5529 if (type == DEST_ADDR)
5530 v->replaceable = 1;
5531 else
5533 /* The giv can be replaced outright by the reduced register only if all
5534 of the following conditions are true:
5535 - the insn that sets the giv is always executed on any iteration
5536 on which the giv is used at all
5537 (there are two ways to deduce this:
5538 either the insn is executed on every iteration,
5539 or all uses follow that insn in the same basic block),
5540 - the giv is not used outside the loop
5541 - no assignments to the biv occur during the giv's lifetime. */
5543 if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
5544 /* Previous line always fails if INSN was moved by loop opt. */
5545 && uid_luid[REGNO_LAST_UID (REGNO (dest_reg))]
5546 < INSN_LUID (loop->end)
5547 && (! not_every_iteration
5548 || last_use_this_basic_block (dest_reg, insn)))
5550 /* Now check that there are no assignments to the biv within the
5551 giv's lifetime. This requires two separate checks. */
5553 /* Check each biv update, and fail if any are between the first
5554 and last use of the giv.
5556 If this loop contains an inner loop that was unrolled, then
5557 the insn modifying the biv may have been emitted by the loop
5558 unrolling code, and hence does not have a valid luid. Just
5559 mark the biv as not replaceable in this case. It is not very
5560 useful as a biv, because it is used in two different loops.
5561 It is very unlikely that we would be able to optimize the giv
5562 using this biv anyways. */
5564 v->replaceable = 1;
5565 for (b = bl->biv; b; b = b->next_iv)
5567 if (INSN_UID (b->insn) >= max_uid_for_loop
5568 || ((uid_luid[INSN_UID (b->insn)]
5569 >= uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))])
5570 && (uid_luid[INSN_UID (b->insn)]
5571 <= uid_luid[REGNO_LAST_UID (REGNO (dest_reg))])))
5573 v->replaceable = 0;
5574 v->not_replaceable = 1;
5575 break;
5579 /* If there are any backwards branches that go from after the
5580 biv update to before it, then this giv is not replaceable. */
5581 if (v->replaceable)
5582 for (b = bl->biv; b; b = b->next_iv)
5583 if (back_branch_in_range_p (loop, b->insn))
5585 v->replaceable = 0;
5586 v->not_replaceable = 1;
5587 break;
5590 else
5592 /* May still be replaceable, we don't have enough info here to
5593 decide. */
5594 v->replaceable = 0;
5595 v->not_replaceable = 0;
5599 /* Record whether the add_val contains a const_int, for later use by
5600 combine_givs. */
5602 rtx tem = add_val;
5604 v->no_const_addval = 1;
5605 if (tem == const0_rtx)
5607 else if (CONSTANT_P (add_val))
5608 v->no_const_addval = 0;
5609 if (GET_CODE (tem) == PLUS)
5611 while (1)
5613 if (GET_CODE (XEXP (tem, 0)) == PLUS)
5614 tem = XEXP (tem, 0);
5615 else if (GET_CODE (XEXP (tem, 1)) == PLUS)
5616 tem = XEXP (tem, 1);
5617 else
5618 break;
5620 if (CONSTANT_P (XEXP (tem, 1)))
5621 v->no_const_addval = 0;
5625 if (loop_dump_stream)
5627 if (type == DEST_REG)
5628 fprintf (loop_dump_stream, "Insn %d: giv reg %d",
5629 INSN_UID (insn), REGNO (dest_reg));
5630 else
5631 fprintf (loop_dump_stream, "Insn %d: dest address",
5632 INSN_UID (insn));
5634 fprintf (loop_dump_stream, " src reg %d benefit %d",
5635 REGNO (src_reg), v->benefit);
5636 fprintf (loop_dump_stream, " lifetime %d",
5637 v->lifetime);
5639 if (v->replaceable)
5640 fprintf (loop_dump_stream, " replaceable");
5642 if (v->no_const_addval)
5643 fprintf (loop_dump_stream, " ncav");
5645 if (GET_CODE (mult_val) == CONST_INT)
5647 fprintf (loop_dump_stream, " mult ");
5648 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (mult_val));
5650 else
5652 fprintf (loop_dump_stream, " mult ");
5653 print_rtl (loop_dump_stream, mult_val);
5656 if (GET_CODE (add_val) == CONST_INT)
5658 fprintf (loop_dump_stream, " add ");
5659 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (add_val));
5661 else
5663 fprintf (loop_dump_stream, " add ");
5664 print_rtl (loop_dump_stream, add_val);
5668 if (loop_dump_stream)
5669 fprintf (loop_dump_stream, "\n");
5674 /* All this does is determine whether a giv can be made replaceable because
5675 its final value can be calculated. This code can not be part of record_giv
5676 above, because final_giv_value requires that the number of loop iterations
5677 be known, and that can not be accurately calculated until after all givs
5678 have been identified. */
5680 static void
5681 check_final_value (loop, v)
5682 const struct loop *loop;
5683 struct induction *v;
5685 struct iv_class *bl;
5686 rtx final_value = 0;
5688 bl = reg_biv_class[REGNO (v->src_reg)];
5690 /* DEST_ADDR givs will never reach here, because they are always marked
5691 replaceable above in record_giv. */
5693 /* The giv can be replaced outright by the reduced register only if all
5694 of the following conditions are true:
5695 - the insn that sets the giv is always executed on any iteration
5696 on which the giv is used at all
5697 (there are two ways to deduce this:
5698 either the insn is executed on every iteration,
5699 or all uses follow that insn in the same basic block),
5700 - its final value can be calculated (this condition is different
5701 than the one above in record_giv)
5702 - no assignments to the biv occur during the giv's lifetime. */
5704 #if 0
5705 /* This is only called now when replaceable is known to be false. */
5706 /* Clear replaceable, so that it won't confuse final_giv_value. */
5707 v->replaceable = 0;
5708 #endif
5710 if ((final_value = final_giv_value (loop, v))
5711 && (v->always_computable || last_use_this_basic_block (v->dest_reg, v->insn)))
5713 int biv_increment_seen = 0;
5714 rtx p = v->insn;
5715 rtx last_giv_use;
5717 v->replaceable = 1;
5719 /* When trying to determine whether or not a biv increment occurs
5720 during the lifetime of the giv, we can ignore uses of the variable
5721 outside the loop because final_value is true. Hence we can not
5722 use regno_last_uid and regno_first_uid as above in record_giv. */
5724 /* Search the loop to determine whether any assignments to the
5725 biv occur during the giv's lifetime. Start with the insn
5726 that sets the giv, and search around the loop until we come
5727 back to that insn again.
5729 Also fail if there is a jump within the giv's lifetime that jumps
5730 to somewhere outside the lifetime but still within the loop. This
5731 catches spaghetti code where the execution order is not linear, and
5732 hence the above test fails. Here we assume that the giv lifetime
5733 does not extend from one iteration of the loop to the next, so as
5734 to make the test easier. Since the lifetime isn't known yet,
5735 this requires two loops. See also record_giv above. */
5737 last_giv_use = v->insn;
5739 while (1)
5741 p = NEXT_INSN (p);
5742 if (p == loop->end)
5743 p = NEXT_INSN (loop->start);
5744 if (p == v->insn)
5745 break;
5747 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5748 || GET_CODE (p) == CALL_INSN)
5750 if (biv_increment_seen)
5752 if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5754 v->replaceable = 0;
5755 v->not_replaceable = 1;
5756 break;
5759 else if (reg_set_p (v->src_reg, PATTERN (p)))
5760 biv_increment_seen = 1;
5761 else if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5762 last_giv_use = p;
5766 /* Now that the lifetime of the giv is known, check for branches
5767 from within the lifetime to outside the lifetime if it is still
5768 replaceable. */
5770 if (v->replaceable)
5772 p = v->insn;
5773 while (1)
5775 p = NEXT_INSN (p);
5776 if (p == loop->end)
5777 p = NEXT_INSN (loop->start);
5778 if (p == last_giv_use)
5779 break;
5781 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
5782 && LABEL_NAME (JUMP_LABEL (p))
5783 && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
5784 && loop_insn_first_p (loop->start, JUMP_LABEL (p)))
5785 || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
5786 && loop_insn_first_p (JUMP_LABEL (p), loop->end))))
5788 v->replaceable = 0;
5789 v->not_replaceable = 1;
5791 if (loop_dump_stream)
5792 fprintf (loop_dump_stream,
5793 "Found branch outside giv lifetime.\n");
5795 break;
5800 /* If it is replaceable, then save the final value. */
5801 if (v->replaceable)
5802 v->final_value = final_value;
5805 if (loop_dump_stream && v->replaceable)
5806 fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
5807 INSN_UID (v->insn), REGNO (v->dest_reg));
5810 /* Update the status of whether a giv can derive other givs.
5812 We need to do something special if there is or may be an update to the biv
5813 between the time the giv is defined and the time it is used to derive
5814 another giv.
5816 In addition, a giv that is only conditionally set is not allowed to
5817 derive another giv once a label has been passed.
5819 The cases we look at are when a label or an update to a biv is passed. */
5821 static void
5822 update_giv_derive (loop, p)
5823 const struct loop *loop;
5824 rtx p;
5826 struct iv_class *bl;
5827 struct induction *biv, *giv;
5828 rtx tem;
5829 int dummy;
5831 /* Search all IV classes, then all bivs, and finally all givs.
5833 There are three cases we are concerned with. First we have the situation
5834 of a giv that is only updated conditionally. In that case, it may not
5835 derive any givs after a label is passed.
5837 The second case is when a biv update occurs, or may occur, after the
5838 definition of a giv. For certain biv updates (see below) that are
5839 known to occur between the giv definition and use, we can adjust the
5840 giv definition. For others, or when the biv update is conditional,
5841 we must prevent the giv from deriving any other givs. There are two
5842 sub-cases within this case.
5844 If this is a label, we are concerned with any biv update that is done
5845 conditionally, since it may be done after the giv is defined followed by
5846 a branch here (actually, we need to pass both a jump and a label, but
5847 this extra tracking doesn't seem worth it).
5849 If this is a jump, we are concerned about any biv update that may be
5850 executed multiple times. We are actually only concerned about
5851 backward jumps, but it is probably not worth performing the test
5852 on the jump again here.
5854 If this is a biv update, we must adjust the giv status to show that a
5855 subsequent biv update was performed. If this adjustment cannot be done,
5856 the giv cannot derive further givs. */
5858 for (bl = loop_iv_list; bl; bl = bl->next)
5859 for (biv = bl->biv; biv; biv = biv->next_iv)
5860 if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
5861 || biv->insn == p)
5863 for (giv = bl->giv; giv; giv = giv->next_iv)
5865 /* If cant_derive is already true, there is no point in
5866 checking all of these conditions again. */
5867 if (giv->cant_derive)
5868 continue;
5870 /* If this giv is conditionally set and we have passed a label,
5871 it cannot derive anything. */
5872 if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
5873 giv->cant_derive = 1;
5875 /* Skip givs that have mult_val == 0, since
5876 they are really invariants. Also skip those that are
5877 replaceable, since we know their lifetime doesn't contain
5878 any biv update. */
5879 else if (giv->mult_val == const0_rtx || giv->replaceable)
5880 continue;
5882 /* The only way we can allow this giv to derive another
5883 is if this is a biv increment and we can form the product
5884 of biv->add_val and giv->mult_val. In this case, we will
5885 be able to compute a compensation. */
5886 else if (biv->insn == p)
5888 tem = 0;
5890 if (biv->mult_val == const1_rtx)
5891 tem = simplify_giv_expr (loop,
5892 gen_rtx_MULT (giv->mode,
5893 biv->add_val,
5894 giv->mult_val),
5895 &dummy);
5897 if (tem && giv->derive_adjustment)
5898 tem = simplify_giv_expr
5899 (loop,
5900 gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
5901 &dummy);
5903 if (tem)
5904 giv->derive_adjustment = tem;
5905 else
5906 giv->cant_derive = 1;
5908 else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
5909 || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
5910 giv->cant_derive = 1;
5915 /* Check whether an insn is an increment legitimate for a basic induction var.
5916 X is the source of insn P, or a part of it.
5917 MODE is the mode in which X should be interpreted.
5919 DEST_REG is the putative biv, also the destination of the insn.
5920 We accept patterns of these forms:
5921 REG = REG + INVARIANT (includes REG = REG - CONSTANT)
5922 REG = INVARIANT + REG
5924 If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
5925 store the additive term into *INC_VAL, and store the place where
5926 we found the additive term into *LOCATION.
5928 If X is an assignment of an invariant into DEST_REG, we set
5929 *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
5931 We also want to detect a BIV when it corresponds to a variable
5932 whose mode was promoted via PROMOTED_MODE. In that case, an increment
5933 of the variable may be a PLUS that adds a SUBREG of that variable to
5934 an invariant and then sign- or zero-extends the result of the PLUS
5935 into the variable.
5937 Most GIVs in such cases will be in the promoted mode, since that is the
5938 probably the natural computation mode (and almost certainly the mode
5939 used for addresses) on the machine. So we view the pseudo-reg containing
5940 the variable as the BIV, as if it were simply incremented.
5942 Note that treating the entire pseudo as a BIV will result in making
5943 simple increments to any GIVs based on it. However, if the variable
5944 overflows in its declared mode but not its promoted mode, the result will
5945 be incorrect. This is acceptable if the variable is signed, since
5946 overflows in such cases are undefined, but not if it is unsigned, since
5947 those overflows are defined. So we only check for SIGN_EXTEND and
5948 not ZERO_EXTEND.
5950 If we cannot find a biv, we return 0. */
5952 static int
5953 basic_induction_var (loop, x, mode, dest_reg, p, inc_val, mult_val,
5954 location, multi_insn_incr)
5955 const struct loop *loop;
5956 register rtx x;
5957 enum machine_mode mode;
5958 rtx dest_reg;
5959 rtx p;
5960 rtx *inc_val;
5961 rtx *mult_val;
5962 rtx **location;
5963 int *multi_insn_incr;
5965 register enum rtx_code code;
5966 rtx *argp, arg;
5967 rtx insn, set = 0;
5969 code = GET_CODE (x);
5970 *location = NULL;
5971 switch (code)
5973 case PLUS:
5974 if (rtx_equal_p (XEXP (x, 0), dest_reg)
5975 || (GET_CODE (XEXP (x, 0)) == SUBREG
5976 && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
5977 && SUBREG_REG (XEXP (x, 0)) == dest_reg))
5979 argp = &XEXP (x, 1);
5981 else if (rtx_equal_p (XEXP (x, 1), dest_reg)
5982 || (GET_CODE (XEXP (x, 1)) == SUBREG
5983 && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
5984 && SUBREG_REG (XEXP (x, 1)) == dest_reg))
5986 argp = &XEXP (x, 0);
5988 else
5989 return 0;
5991 arg = *argp;
5992 if (loop_invariant_p (loop, arg) != 1)
5993 return 0;
5995 *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
5996 *mult_val = const1_rtx;
5997 *location = argp;
5998 return 1;
6000 case SUBREG:
6001 /* If this is a SUBREG for a promoted variable, check the inner
6002 value. */
6003 if (SUBREG_PROMOTED_VAR_P (x))
6004 return basic_induction_var (loop, SUBREG_REG (x),
6005 GET_MODE (SUBREG_REG (x)),
6006 dest_reg, p, inc_val, mult_val, location,
6007 multi_insn_incr);
6008 return 0;
6010 case REG:
6011 /* If this register is assigned in a previous insn, look at its
6012 source, but don't go outside the loop or past a label. */
6014 insn = p;
6015 while (1)
6017 do {
6018 insn = PREV_INSN (insn);
6019 } while (insn && GET_CODE (insn) == NOTE
6020 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6022 if (!insn)
6023 break;
6024 set = single_set (insn);
6025 if (set == 0)
6026 break;
6028 if ((SET_DEST (set) == x
6029 || (GET_CODE (SET_DEST (set)) == SUBREG
6030 && (GET_MODE_SIZE (GET_MODE (SET_DEST (set)))
6031 <= UNITS_PER_WORD)
6032 && (GET_MODE_CLASS (GET_MODE (SET_DEST (set)))
6033 == MODE_INT)
6034 && SUBREG_REG (SET_DEST (set)) == x))
6035 && basic_induction_var (loop, SET_SRC (set),
6036 (GET_MODE (SET_SRC (set)) == VOIDmode
6037 ? GET_MODE (x)
6038 : GET_MODE (SET_SRC (set))),
6039 dest_reg, insn,
6040 inc_val, mult_val, location,
6041 multi_insn_incr))
6043 *multi_insn_incr = 1;
6044 return 1;
6047 /* ... fall through ... */
6049 /* Can accept constant setting of biv only when inside inner most loop.
6050 Otherwise, a biv of an inner loop may be incorrectly recognized
6051 as a biv of the outer loop,
6052 causing code to be moved INTO the inner loop. */
6053 case MEM:
6054 if (loop_invariant_p (loop, x) != 1)
6055 return 0;
6056 case CONST_INT:
6057 case SYMBOL_REF:
6058 case CONST:
6059 /* convert_modes aborts if we try to convert to or from CCmode, so just
6060 exclude that case. It is very unlikely that a condition code value
6061 would be a useful iterator anyways. */
6062 if (loop->level == 1
6063 && GET_MODE_CLASS (mode) != MODE_CC
6064 && GET_MODE_CLASS (GET_MODE (dest_reg)) != MODE_CC)
6066 /* Possible bug here? Perhaps we don't know the mode of X. */
6067 *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
6068 *mult_val = const0_rtx;
6069 return 1;
6071 else
6072 return 0;
6074 case SIGN_EXTEND:
6075 return basic_induction_var (loop, XEXP (x, 0), GET_MODE (XEXP (x, 0)),
6076 dest_reg, p, inc_val, mult_val, location,
6077 multi_insn_incr);
6079 case ASHIFTRT:
6080 /* Similar, since this can be a sign extension. */
6081 for (insn = PREV_INSN (p);
6082 (insn && GET_CODE (insn) == NOTE
6083 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6084 insn = PREV_INSN (insn))
6087 if (insn)
6088 set = single_set (insn);
6090 if (set && SET_DEST (set) == XEXP (x, 0)
6091 && GET_CODE (XEXP (x, 1)) == CONST_INT
6092 && INTVAL (XEXP (x, 1)) >= 0
6093 && GET_CODE (SET_SRC (set)) == ASHIFT
6094 && XEXP (x, 1) == XEXP (SET_SRC (set), 1)
6095 && basic_induction_var (loop, XEXP (SET_SRC (set), 0),
6096 GET_MODE (XEXP (x, 0)),
6097 dest_reg, insn, inc_val, mult_val,
6098 location, multi_insn_incr))
6100 *multi_insn_incr = 1;
6101 return 1;
6103 return 0;
6105 default:
6106 return 0;
6110 /* A general induction variable (giv) is any quantity that is a linear
6111 function of a basic induction variable,
6112 i.e. giv = biv * mult_val + add_val.
6113 The coefficients can be any loop invariant quantity.
6114 A giv need not be computed directly from the biv;
6115 it can be computed by way of other givs. */
6117 /* Determine whether X computes a giv.
6118 If it does, return a nonzero value
6119 which is the benefit from eliminating the computation of X;
6120 set *SRC_REG to the register of the biv that it is computed from;
6121 set *ADD_VAL and *MULT_VAL to the coefficients,
6122 such that the value of X is biv * mult + add; */
6124 static int
6125 general_induction_var (loop, x, src_reg, add_val, mult_val, is_addr,
6126 pbenefit, addr_mode)
6127 const struct loop *loop;
6128 rtx x;
6129 rtx *src_reg;
6130 rtx *add_val;
6131 rtx *mult_val;
6132 int is_addr;
6133 int *pbenefit;
6134 enum machine_mode addr_mode;
6136 rtx orig_x = x;
6137 char *storage;
6139 /* If this is an invariant, forget it, it isn't a giv. */
6140 if (loop_invariant_p (loop, x) == 1)
6141 return 0;
6143 /* See if the expression could be a giv and get its form.
6144 Mark our place on the obstack in case we don't find a giv. */
6145 storage = (char *) oballoc (0);
6146 *pbenefit = 0;
6147 x = simplify_giv_expr (loop, x, pbenefit);
6148 if (x == 0)
6150 obfree (storage);
6151 return 0;
6154 switch (GET_CODE (x))
6156 case USE:
6157 case CONST_INT:
6158 /* Since this is now an invariant and wasn't before, it must be a giv
6159 with MULT_VAL == 0. It doesn't matter which BIV we associate this
6160 with. */
6161 *src_reg = loop_iv_list->biv->dest_reg;
6162 *mult_val = const0_rtx;
6163 *add_val = x;
6164 break;
6166 case REG:
6167 /* This is equivalent to a BIV. */
6168 *src_reg = x;
6169 *mult_val = const1_rtx;
6170 *add_val = const0_rtx;
6171 break;
6173 case PLUS:
6174 /* Either (plus (biv) (invar)) or
6175 (plus (mult (biv) (invar_1)) (invar_2)). */
6176 if (GET_CODE (XEXP (x, 0)) == MULT)
6178 *src_reg = XEXP (XEXP (x, 0), 0);
6179 *mult_val = XEXP (XEXP (x, 0), 1);
6181 else
6183 *src_reg = XEXP (x, 0);
6184 *mult_val = const1_rtx;
6186 *add_val = XEXP (x, 1);
6187 break;
6189 case MULT:
6190 /* ADD_VAL is zero. */
6191 *src_reg = XEXP (x, 0);
6192 *mult_val = XEXP (x, 1);
6193 *add_val = const0_rtx;
6194 break;
6196 default:
6197 abort ();
6200 /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
6201 unless they are CONST_INT). */
6202 if (GET_CODE (*add_val) == USE)
6203 *add_val = XEXP (*add_val, 0);
6204 if (GET_CODE (*mult_val) == USE)
6205 *mult_val = XEXP (*mult_val, 0);
6207 if (is_addr)
6208 *pbenefit += address_cost (orig_x, addr_mode) - reg_address_cost;
6209 else
6210 *pbenefit += rtx_cost (orig_x, SET);
6212 /* Always return true if this is a giv so it will be detected as such,
6213 even if the benefit is zero or negative. This allows elimination
6214 of bivs that might otherwise not be eliminated. */
6215 return 1;
6218 /* Given an expression, X, try to form it as a linear function of a biv.
6219 We will canonicalize it to be of the form
6220 (plus (mult (BIV) (invar_1))
6221 (invar_2))
6222 with possible degeneracies.
6224 The invariant expressions must each be of a form that can be used as a
6225 machine operand. We surround then with a USE rtx (a hack, but localized
6226 and certainly unambiguous!) if not a CONST_INT for simplicity in this
6227 routine; it is the caller's responsibility to strip them.
6229 If no such canonicalization is possible (i.e., two biv's are used or an
6230 expression that is neither invariant nor a biv or giv), this routine
6231 returns 0.
6233 For a non-zero return, the result will have a code of CONST_INT, USE,
6234 REG (for a BIV), PLUS, or MULT. No other codes will occur.
6236 *BENEFIT will be incremented by the benefit of any sub-giv encountered. */
6238 static rtx sge_plus PARAMS ((enum machine_mode, rtx, rtx));
6239 static rtx sge_plus_constant PARAMS ((rtx, rtx));
6240 static int cmp_combine_givs_stats PARAMS ((const PTR, const PTR));
6241 static int cmp_recombine_givs_stats PARAMS ((const PTR, const PTR));
6243 static rtx
6244 simplify_giv_expr (loop, x, benefit)
6245 const struct loop *loop;
6246 rtx x;
6247 int *benefit;
6249 enum machine_mode mode = GET_MODE (x);
6250 rtx arg0, arg1;
6251 rtx tem;
6253 /* If this is not an integer mode, or if we cannot do arithmetic in this
6254 mode, this can't be a giv. */
6255 if (mode != VOIDmode
6256 && (GET_MODE_CLASS (mode) != MODE_INT
6257 || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
6258 return NULL_RTX;
6260 switch (GET_CODE (x))
6262 case PLUS:
6263 arg0 = simplify_giv_expr (loop, XEXP (x, 0), benefit);
6264 arg1 = simplify_giv_expr (loop, XEXP (x, 1), benefit);
6265 if (arg0 == 0 || arg1 == 0)
6266 return NULL_RTX;
6268 /* Put constant last, CONST_INT last if both constant. */
6269 if ((GET_CODE (arg0) == USE
6270 || GET_CODE (arg0) == CONST_INT)
6271 && ! ((GET_CODE (arg0) == USE
6272 && GET_CODE (arg1) == USE)
6273 || GET_CODE (arg1) == CONST_INT))
6274 tem = arg0, arg0 = arg1, arg1 = tem;
6276 /* Handle addition of zero, then addition of an invariant. */
6277 if (arg1 == const0_rtx)
6278 return arg0;
6279 else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
6280 switch (GET_CODE (arg0))
6282 case CONST_INT:
6283 case USE:
6284 /* Adding two invariants must result in an invariant, so enclose
6285 addition operation inside a USE and return it. */
6286 if (GET_CODE (arg0) == USE)
6287 arg0 = XEXP (arg0, 0);
6288 if (GET_CODE (arg1) == USE)
6289 arg1 = XEXP (arg1, 0);
6291 if (GET_CODE (arg0) == CONST_INT)
6292 tem = arg0, arg0 = arg1, arg1 = tem;
6293 if (GET_CODE (arg1) == CONST_INT)
6294 tem = sge_plus_constant (arg0, arg1);
6295 else
6296 tem = sge_plus (mode, arg0, arg1);
6298 if (GET_CODE (tem) != CONST_INT)
6299 tem = gen_rtx_USE (mode, tem);
6300 return tem;
6302 case REG:
6303 case MULT:
6304 /* biv + invar or mult + invar. Return sum. */
6305 return gen_rtx_PLUS (mode, arg0, arg1);
6307 case PLUS:
6308 /* (a + invar_1) + invar_2. Associate. */
6309 return
6310 simplify_giv_expr (loop,
6311 gen_rtx_PLUS (mode,
6312 XEXP (arg0, 0),
6313 gen_rtx_PLUS (mode,
6314 XEXP (arg0, 1),
6315 arg1)),
6316 benefit);
6318 default:
6319 abort ();
6322 /* Each argument must be either REG, PLUS, or MULT. Convert REG to
6323 MULT to reduce cases. */
6324 if (GET_CODE (arg0) == REG)
6325 arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
6326 if (GET_CODE (arg1) == REG)
6327 arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
6329 /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
6330 Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
6331 Recurse to associate the second PLUS. */
6332 if (GET_CODE (arg1) == MULT)
6333 tem = arg0, arg0 = arg1, arg1 = tem;
6335 if (GET_CODE (arg1) == PLUS)
6336 return
6337 simplify_giv_expr (loop,
6338 gen_rtx_PLUS (mode,
6339 gen_rtx_PLUS (mode, arg0,
6340 XEXP (arg1, 0)),
6341 XEXP (arg1, 1)),
6342 benefit);
6344 /* Now must have MULT + MULT. Distribute if same biv, else not giv. */
6345 if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
6346 return NULL_RTX;
6348 if (!rtx_equal_p (arg0, arg1))
6349 return NULL_RTX;
6351 return simplify_giv_expr (loop,
6352 gen_rtx_MULT (mode,
6353 XEXP (arg0, 0),
6354 gen_rtx_PLUS (mode,
6355 XEXP (arg0, 1),
6356 XEXP (arg1, 1))),
6357 benefit);
6359 case MINUS:
6360 /* Handle "a - b" as "a + b * (-1)". */
6361 return simplify_giv_expr (loop,
6362 gen_rtx_PLUS (mode,
6363 XEXP (x, 0),
6364 gen_rtx_MULT (mode,
6365 XEXP (x, 1),
6366 constm1_rtx)),
6367 benefit);
6369 case MULT:
6370 arg0 = simplify_giv_expr (loop, XEXP (x, 0), benefit);
6371 arg1 = simplify_giv_expr (loop, XEXP (x, 1), benefit);
6372 if (arg0 == 0 || arg1 == 0)
6373 return NULL_RTX;
6375 /* Put constant last, CONST_INT last if both constant. */
6376 if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
6377 && GET_CODE (arg1) != CONST_INT)
6378 tem = arg0, arg0 = arg1, arg1 = tem;
6380 /* If second argument is not now constant, not giv. */
6381 if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
6382 return NULL_RTX;
6384 /* Handle multiply by 0 or 1. */
6385 if (arg1 == const0_rtx)
6386 return const0_rtx;
6388 else if (arg1 == const1_rtx)
6389 return arg0;
6391 switch (GET_CODE (arg0))
6393 case REG:
6394 /* biv * invar. Done. */
6395 return gen_rtx_MULT (mode, arg0, arg1);
6397 case CONST_INT:
6398 /* Product of two constants. */
6399 return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
6401 case USE:
6402 /* invar * invar is a giv, but attempt to simplify it somehow. */
6403 if (GET_CODE (arg1) != CONST_INT)
6404 return NULL_RTX;
6406 arg0 = XEXP (arg0, 0);
6407 if (GET_CODE (arg0) == MULT)
6409 /* (invar_0 * invar_1) * invar_2. Associate. */
6410 return simplify_giv_expr (loop,
6411 gen_rtx_MULT (mode,
6412 XEXP (arg0, 0),
6413 gen_rtx_MULT (mode,
6414 XEXP (arg0,
6416 arg1)),
6417 benefit);
6419 /* Porpagate the MULT expressions to the intermost nodes. */
6420 else if (GET_CODE (arg0) == PLUS)
6422 /* (invar_0 + invar_1) * invar_2. Distribute. */
6423 return simplify_giv_expr (loop,
6424 gen_rtx_PLUS (mode,
6425 gen_rtx_MULT (mode,
6426 XEXP (arg0,
6428 arg1),
6429 gen_rtx_MULT (mode,
6430 XEXP (arg0,
6432 arg1)),
6433 benefit);
6435 return gen_rtx_USE (mode, gen_rtx_MULT (mode, arg0, arg1));
6437 case MULT:
6438 /* (a * invar_1) * invar_2. Associate. */
6439 return simplify_giv_expr (loop,
6440 gen_rtx_MULT (mode,
6441 XEXP (arg0, 0),
6442 gen_rtx_MULT (mode,
6443 XEXP (arg0, 1),
6444 arg1)),
6445 benefit);
6447 case PLUS:
6448 /* (a + invar_1) * invar_2. Distribute. */
6449 return simplify_giv_expr (loop,
6450 gen_rtx_PLUS (mode,
6451 gen_rtx_MULT (mode,
6452 XEXP (arg0, 0),
6453 arg1),
6454 gen_rtx_MULT (mode,
6455 XEXP (arg0, 1),
6456 arg1)),
6457 benefit);
6459 default:
6460 abort ();
6463 case ASHIFT:
6464 /* Shift by constant is multiply by power of two. */
6465 if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6466 return 0;
6468 return
6469 simplify_giv_expr (loop,
6470 gen_rtx_MULT (mode,
6471 XEXP (x, 0),
6472 GEN_INT ((HOST_WIDE_INT) 1
6473 << INTVAL (XEXP (x, 1)))),
6474 benefit);
6476 case NEG:
6477 /* "-a" is "a * (-1)" */
6478 return simplify_giv_expr (loop,
6479 gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
6480 benefit);
6482 case NOT:
6483 /* "~a" is "-a - 1". Silly, but easy. */
6484 return simplify_giv_expr (loop,
6485 gen_rtx_MINUS (mode,
6486 gen_rtx_NEG (mode, XEXP (x, 0)),
6487 const1_rtx),
6488 benefit);
6490 case USE:
6491 /* Already in proper form for invariant. */
6492 return x;
6494 case REG:
6495 /* If this is a new register, we can't deal with it. */
6496 if (REGNO (x) >= max_reg_before_loop)
6497 return 0;
6499 /* Check for biv or giv. */
6500 switch (REG_IV_TYPE (REGNO (x)))
6502 case BASIC_INDUCT:
6503 return x;
6504 case GENERAL_INDUCT:
6506 struct induction *v = REG_IV_INFO (REGNO (x));
6508 /* Form expression from giv and add benefit. Ensure this giv
6509 can derive another and subtract any needed adjustment if so. */
6510 *benefit += v->benefit;
6511 if (v->cant_derive)
6512 return 0;
6514 tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
6515 v->src_reg, v->mult_val),
6516 v->add_val);
6518 if (v->derive_adjustment)
6519 tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
6520 return simplify_giv_expr (loop, tem, benefit);
6523 default:
6524 /* If it isn't an induction variable, and it is invariant, we
6525 may be able to simplify things further by looking through
6526 the bits we just moved outside the loop. */
6527 if (loop_invariant_p (loop, x) == 1)
6529 struct movable *m;
6531 for (m = the_movables; m ; m = m->next)
6532 if (rtx_equal_p (x, m->set_dest))
6534 /* Ok, we found a match. Substitute and simplify. */
6536 /* If we match another movable, we must use that, as
6537 this one is going away. */
6538 if (m->match)
6539 return simplify_giv_expr (loop, m->match->set_dest,
6540 benefit);
6542 /* If consec is non-zero, this is a member of a group of
6543 instructions that were moved together. We handle this
6544 case only to the point of seeking to the last insn and
6545 looking for a REG_EQUAL. Fail if we don't find one. */
6546 if (m->consec != 0)
6548 int i = m->consec;
6549 tem = m->insn;
6550 do { tem = NEXT_INSN (tem); } while (--i > 0);
6552 tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
6553 if (tem)
6554 tem = XEXP (tem, 0);
6556 else
6558 tem = single_set (m->insn);
6559 if (tem)
6560 tem = SET_SRC (tem);
6563 if (tem)
6565 /* What we are most interested in is pointer
6566 arithmetic on invariants -- only take
6567 patterns we may be able to do something with. */
6568 if (GET_CODE (tem) == PLUS
6569 || GET_CODE (tem) == MULT
6570 || GET_CODE (tem) == ASHIFT
6571 || GET_CODE (tem) == CONST_INT
6572 || GET_CODE (tem) == SYMBOL_REF)
6574 tem = simplify_giv_expr (loop, tem, benefit);
6575 if (tem)
6576 return tem;
6578 else if (GET_CODE (tem) == CONST
6579 && GET_CODE (XEXP (tem, 0)) == PLUS
6580 && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
6581 && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
6583 tem = simplify_giv_expr (loop, XEXP (tem, 0),
6584 benefit);
6585 if (tem)
6586 return tem;
6589 break;
6592 break;
6595 /* Fall through to general case. */
6596 default:
6597 /* If invariant, return as USE (unless CONST_INT).
6598 Otherwise, not giv. */
6599 if (GET_CODE (x) == USE)
6600 x = XEXP (x, 0);
6602 if (loop_invariant_p (loop, x) == 1)
6604 if (GET_CODE (x) == CONST_INT)
6605 return x;
6606 if (GET_CODE (x) == CONST
6607 && GET_CODE (XEXP (x, 0)) == PLUS
6608 && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
6609 && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
6610 x = XEXP (x, 0);
6611 return gen_rtx_USE (mode, x);
6613 else
6614 return 0;
6618 /* This routine folds invariants such that there is only ever one
6619 CONST_INT in the summation. It is only used by simplify_giv_expr. */
6621 static rtx
6622 sge_plus_constant (x, c)
6623 rtx x, c;
6625 if (GET_CODE (x) == CONST_INT)
6626 return GEN_INT (INTVAL (x) + INTVAL (c));
6627 else if (GET_CODE (x) != PLUS)
6628 return gen_rtx_PLUS (GET_MODE (x), x, c);
6629 else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
6631 return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
6632 GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
6634 else if (GET_CODE (XEXP (x, 0)) == PLUS
6635 || GET_CODE (XEXP (x, 1)) != PLUS)
6637 return gen_rtx_PLUS (GET_MODE (x),
6638 sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
6640 else
6642 return gen_rtx_PLUS (GET_MODE (x),
6643 sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
6647 static rtx
6648 sge_plus (mode, x, y)
6649 enum machine_mode mode;
6650 rtx x, y;
6652 while (GET_CODE (y) == PLUS)
6654 rtx a = XEXP (y, 0);
6655 if (GET_CODE (a) == CONST_INT)
6656 x = sge_plus_constant (x, a);
6657 else
6658 x = gen_rtx_PLUS (mode, x, a);
6659 y = XEXP (y, 1);
6661 if (GET_CODE (y) == CONST_INT)
6662 x = sge_plus_constant (x, y);
6663 else
6664 x = gen_rtx_PLUS (mode, x, y);
6665 return x;
6668 /* Help detect a giv that is calculated by several consecutive insns;
6669 for example,
6670 giv = biv * M
6671 giv = giv + A
6672 The caller has already identified the first insn P as having a giv as dest;
6673 we check that all other insns that set the same register follow
6674 immediately after P, that they alter nothing else,
6675 and that the result of the last is still a giv.
6677 The value is 0 if the reg set in P is not really a giv.
6678 Otherwise, the value is the amount gained by eliminating
6679 all the consecutive insns that compute the value.
6681 FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
6682 SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
6684 The coefficients of the ultimate giv value are stored in
6685 *MULT_VAL and *ADD_VAL. */
6687 static int
6688 consec_sets_giv (loop, first_benefit, p, src_reg, dest_reg,
6689 add_val, mult_val, last_consec_insn)
6690 const struct loop *loop;
6691 int first_benefit;
6692 rtx p;
6693 rtx src_reg;
6694 rtx dest_reg;
6695 rtx *add_val;
6696 rtx *mult_val;
6697 rtx *last_consec_insn;
6699 int count;
6700 enum rtx_code code;
6701 int benefit;
6702 rtx temp;
6703 rtx set;
6705 /* Indicate that this is a giv so that we can update the value produced in
6706 each insn of the multi-insn sequence.
6708 This induction structure will be used only by the call to
6709 general_induction_var below, so we can allocate it on our stack.
6710 If this is a giv, our caller will replace the induct var entry with
6711 a new induction structure. */
6712 struct induction *v
6713 = (struct induction *) alloca (sizeof (struct induction));
6714 v->src_reg = src_reg;
6715 v->mult_val = *mult_val;
6716 v->add_val = *add_val;
6717 v->benefit = first_benefit;
6718 v->cant_derive = 0;
6719 v->derive_adjustment = 0;
6721 REG_IV_TYPE (REGNO (dest_reg)) = GENERAL_INDUCT;
6722 REG_IV_INFO (REGNO (dest_reg)) = v;
6724 count = VARRAY_INT (n_times_set, REGNO (dest_reg)) - 1;
6726 while (count > 0)
6728 p = NEXT_INSN (p);
6729 code = GET_CODE (p);
6731 /* If libcall, skip to end of call sequence. */
6732 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
6733 p = XEXP (temp, 0);
6735 if (code == INSN
6736 && (set = single_set (p))
6737 && GET_CODE (SET_DEST (set)) == REG
6738 && SET_DEST (set) == dest_reg
6739 && (general_induction_var (loop, SET_SRC (set), &src_reg,
6740 add_val, mult_val, 0, &benefit, VOIDmode)
6741 /* Giv created by equivalent expression. */
6742 || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
6743 && general_induction_var (loop, XEXP (temp, 0), &src_reg,
6744 add_val, mult_val, 0, &benefit,
6745 VOIDmode)))
6746 && src_reg == v->src_reg)
6748 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
6749 benefit += libcall_benefit (p);
6751 count--;
6752 v->mult_val = *mult_val;
6753 v->add_val = *add_val;
6754 v->benefit = benefit;
6756 else if (code != NOTE)
6758 /* Allow insns that set something other than this giv to a
6759 constant. Such insns are needed on machines which cannot
6760 include long constants and should not disqualify a giv. */
6761 if (code == INSN
6762 && (set = single_set (p))
6763 && SET_DEST (set) != dest_reg
6764 && CONSTANT_P (SET_SRC (set)))
6765 continue;
6767 REG_IV_TYPE (REGNO (dest_reg)) = UNKNOWN_INDUCT;
6768 return 0;
6772 *last_consec_insn = p;
6773 return v->benefit;
6776 /* Return an rtx, if any, that expresses giv G2 as a function of the register
6777 represented by G1. If no such expression can be found, or it is clear that
6778 it cannot possibly be a valid address, 0 is returned.
6780 To perform the computation, we note that
6781 G1 = x * v + a and
6782 G2 = y * v + b
6783 where `v' is the biv.
6785 So G2 = (y/b) * G1 + (b - a*y/x).
6787 Note that MULT = y/x.
6789 Update: A and B are now allowed to be additive expressions such that
6790 B contains all variables in A. That is, computing B-A will not require
6791 subtracting variables. */
6793 static rtx
6794 express_from_1 (a, b, mult)
6795 rtx a, b, mult;
6797 /* If MULT is zero, then A*MULT is zero, and our expression is B. */
6799 if (mult == const0_rtx)
6800 return b;
6802 /* If MULT is not 1, we cannot handle A with non-constants, since we
6803 would then be required to subtract multiples of the registers in A.
6804 This is theoretically possible, and may even apply to some Fortran
6805 constructs, but it is a lot of work and we do not attempt it here. */
6807 if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
6808 return NULL_RTX;
6810 /* In general these structures are sorted top to bottom (down the PLUS
6811 chain), but not left to right across the PLUS. If B is a higher
6812 order giv than A, we can strip one level and recurse. If A is higher
6813 order, we'll eventually bail out, but won't know that until the end.
6814 If they are the same, we'll strip one level around this loop. */
6816 while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
6818 rtx ra, rb, oa, ob, tmp;
6820 ra = XEXP (a, 0), oa = XEXP (a, 1);
6821 if (GET_CODE (ra) == PLUS)
6822 tmp = ra, ra = oa, oa = tmp;
6824 rb = XEXP (b, 0), ob = XEXP (b, 1);
6825 if (GET_CODE (rb) == PLUS)
6826 tmp = rb, rb = ob, ob = tmp;
6828 if (rtx_equal_p (ra, rb))
6829 /* We matched: remove one reg completely. */
6830 a = oa, b = ob;
6831 else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
6832 /* An alternate match. */
6833 a = oa, b = rb;
6834 else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
6835 /* An alternate match. */
6836 a = ra, b = ob;
6837 else
6839 /* Indicates an extra register in B. Strip one level from B and
6840 recurse, hoping B was the higher order expression. */
6841 ob = express_from_1 (a, ob, mult);
6842 if (ob == NULL_RTX)
6843 return NULL_RTX;
6844 return gen_rtx_PLUS (GET_MODE (b), rb, ob);
6848 /* Here we are at the last level of A, go through the cases hoping to
6849 get rid of everything but a constant. */
6851 if (GET_CODE (a) == PLUS)
6853 rtx ra, oa;
6855 ra = XEXP (a, 0), oa = XEXP (a, 1);
6856 if (rtx_equal_p (oa, b))
6857 oa = ra;
6858 else if (!rtx_equal_p (ra, b))
6859 return NULL_RTX;
6861 if (GET_CODE (oa) != CONST_INT)
6862 return NULL_RTX;
6864 return GEN_INT (-INTVAL (oa) * INTVAL (mult));
6866 else if (GET_CODE (a) == CONST_INT)
6868 return plus_constant (b, -INTVAL (a) * INTVAL (mult));
6870 else if (CONSTANT_P (a))
6872 return simplify_gen_binary (MINUS, GET_MODE (b), const0_rtx, a);
6874 else if (GET_CODE (b) == PLUS)
6876 if (rtx_equal_p (a, XEXP (b, 0)))
6877 return XEXP (b, 1);
6878 else if (rtx_equal_p (a, XEXP (b, 1)))
6879 return XEXP (b, 0);
6880 else
6881 return NULL_RTX;
6883 else if (rtx_equal_p (a, b))
6884 return const0_rtx;
6886 return NULL_RTX;
6890 express_from (g1, g2)
6891 struct induction *g1, *g2;
6893 rtx mult, add;
6895 /* The value that G1 will be multiplied by must be a constant integer. Also,
6896 the only chance we have of getting a valid address is if b*c/a (see above
6897 for notation) is also an integer. */
6898 if (GET_CODE (g1->mult_val) == CONST_INT
6899 && GET_CODE (g2->mult_val) == CONST_INT)
6901 if (g1->mult_val == const0_rtx
6902 || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
6903 return NULL_RTX;
6904 mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
6906 else if (rtx_equal_p (g1->mult_val, g2->mult_val))
6907 mult = const1_rtx;
6908 else
6910 /* ??? Find out if the one is a multiple of the other? */
6911 return NULL_RTX;
6914 add = express_from_1 (g1->add_val, g2->add_val, mult);
6915 if (add == NULL_RTX)
6917 /* Failed. If we've got a multiplication factor between G1 and G2,
6918 scale G1's addend and try again. */
6919 if (INTVAL (mult) > 1)
6921 rtx g1_add_val = g1->add_val;
6922 if (GET_CODE (g1_add_val) == MULT
6923 && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
6925 HOST_WIDE_INT m;
6926 m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
6927 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
6928 XEXP (g1_add_val, 0), GEN_INT (m));
6930 else
6932 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
6933 mult);
6936 add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
6939 if (add == NULL_RTX)
6940 return NULL_RTX;
6942 /* Form simplified final result. */
6943 if (mult == const0_rtx)
6944 return add;
6945 else if (mult == const1_rtx)
6946 mult = g1->dest_reg;
6947 else
6948 mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
6950 if (add == const0_rtx)
6951 return mult;
6952 else
6954 if (GET_CODE (add) == PLUS
6955 && CONSTANT_P (XEXP (add, 1)))
6957 rtx tem = XEXP (add, 1);
6958 mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
6959 add = tem;
6962 return gen_rtx_PLUS (g2->mode, mult, add);
6967 /* Return an rtx, if any, that expresses giv G2 as a function of the register
6968 represented by G1. This indicates that G2 should be combined with G1 and
6969 that G2 can use (either directly or via an address expression) a register
6970 used to represent G1. */
6972 static rtx
6973 combine_givs_p (g1, g2)
6974 struct induction *g1, *g2;
6976 rtx tem = express_from (g1, g2);
6978 /* If these givs are identical, they can be combined. We use the results
6979 of express_from because the addends are not in a canonical form, so
6980 rtx_equal_p is a weaker test. */
6981 /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
6982 combination to be the other way round. */
6983 if (tem == g1->dest_reg
6984 && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
6986 return g1->dest_reg;
6989 /* If G2 can be expressed as a function of G1 and that function is valid
6990 as an address and no more expensive than using a register for G2,
6991 the expression of G2 in terms of G1 can be used. */
6992 if (tem != NULL_RTX
6993 && g2->giv_type == DEST_ADDR
6994 && memory_address_p (g2->mem_mode, tem)
6995 /* ??? Looses, especially with -fforce-addr, where *g2->location
6996 will always be a register, and so anything more complicated
6997 gets discarded. */
6998 #if 0
6999 #ifdef ADDRESS_COST
7000 && ADDRESS_COST (tem) <= ADDRESS_COST (*g2->location)
7001 #else
7002 && rtx_cost (tem, MEM) <= rtx_cost (*g2->location, MEM)
7003 #endif
7004 #endif
7007 return tem;
7010 return NULL_RTX;
7013 struct combine_givs_stats
7015 int giv_number;
7016 int total_benefit;
7019 static int
7020 cmp_combine_givs_stats (xp, yp)
7021 const PTR xp;
7022 const PTR yp;
7024 const struct combine_givs_stats * const x =
7025 (const struct combine_givs_stats *) xp;
7026 const struct combine_givs_stats * const y =
7027 (const struct combine_givs_stats *) yp;
7028 int d;
7029 d = y->total_benefit - x->total_benefit;
7030 /* Stabilize the sort. */
7031 if (!d)
7032 d = x->giv_number - y->giv_number;
7033 return d;
7036 /* Check all pairs of givs for iv_class BL and see if any can be combined with
7037 any other. If so, point SAME to the giv combined with and set NEW_REG to
7038 be an expression (in terms of the other giv's DEST_REG) equivalent to the
7039 giv. Also, update BENEFIT and related fields for cost/benefit analysis. */
7041 static void
7042 combine_givs (bl)
7043 struct iv_class *bl;
7045 /* Additional benefit to add for being combined multiple times. */
7046 const int extra_benefit = 3;
7048 struct induction *g1, *g2, **giv_array;
7049 int i, j, k, giv_count;
7050 struct combine_givs_stats *stats;
7051 rtx *can_combine;
7053 /* Count givs, because bl->giv_count is incorrect here. */
7054 giv_count = 0;
7055 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7056 if (!g1->ignore)
7057 giv_count++;
7059 giv_array
7060 = (struct induction **) alloca (giv_count * sizeof (struct induction *));
7061 i = 0;
7062 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7063 if (!g1->ignore)
7064 giv_array[i++] = g1;
7066 stats = (struct combine_givs_stats *) xcalloc (giv_count, sizeof (*stats));
7067 can_combine = (rtx *) xcalloc (giv_count, giv_count * sizeof(rtx));
7069 for (i = 0; i < giv_count; i++)
7071 int this_benefit;
7072 rtx single_use;
7074 g1 = giv_array[i];
7075 stats[i].giv_number = i;
7077 /* If a DEST_REG GIV is used only once, do not allow it to combine
7078 with anything, for in doing so we will gain nothing that cannot
7079 be had by simply letting the GIV with which we would have combined
7080 to be reduced on its own. The losage shows up in particular with
7081 DEST_ADDR targets on hosts with reg+reg addressing, though it can
7082 be seen elsewhere as well. */
7083 if (g1->giv_type == DEST_REG
7084 && (single_use = VARRAY_RTX (reg_single_usage, REGNO (g1->dest_reg)))
7085 && single_use != const0_rtx)
7086 continue;
7088 this_benefit = g1->benefit;
7089 /* Add an additional weight for zero addends. */
7090 if (g1->no_const_addval)
7091 this_benefit += 1;
7093 for (j = 0; j < giv_count; j++)
7095 rtx this_combine;
7097 g2 = giv_array[j];
7098 if (g1 != g2
7099 && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
7101 can_combine[i*giv_count + j] = this_combine;
7102 this_benefit += g2->benefit + extra_benefit;
7105 stats[i].total_benefit = this_benefit;
7108 /* Iterate, combining until we can't. */
7109 restart:
7110 qsort (stats, giv_count, sizeof(*stats), cmp_combine_givs_stats);
7112 if (loop_dump_stream)
7114 fprintf (loop_dump_stream, "Sorted combine statistics:\n");
7115 for (k = 0; k < giv_count; k++)
7117 g1 = giv_array[stats[k].giv_number];
7118 if (!g1->combined_with && !g1->same)
7119 fprintf (loop_dump_stream, " {%d, %d}",
7120 INSN_UID (giv_array[stats[k].giv_number]->insn),
7121 stats[k].total_benefit);
7123 putc ('\n', loop_dump_stream);
7126 for (k = 0; k < giv_count; k++)
7128 int g1_add_benefit = 0;
7130 i = stats[k].giv_number;
7131 g1 = giv_array[i];
7133 /* If it has already been combined, skip. */
7134 if (g1->combined_with || g1->same)
7135 continue;
7137 for (j = 0; j < giv_count; j++)
7139 g2 = giv_array[j];
7140 if (g1 != g2 && can_combine[i*giv_count + j]
7141 /* If it has already been combined, skip. */
7142 && ! g2->same && ! g2->combined_with)
7144 int l;
7146 g2->new_reg = can_combine[i*giv_count + j];
7147 g2->same = g1;
7148 g1->combined_with++;
7149 g1->lifetime += g2->lifetime;
7151 g1_add_benefit += g2->benefit;
7153 /* ??? The new final_[bg]iv_value code does a much better job
7154 of finding replaceable giv's, and hence this code may no
7155 longer be necessary. */
7156 if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
7157 g1_add_benefit -= copy_cost;
7159 /* To help optimize the next set of combinations, remove
7160 this giv from the benefits of other potential mates. */
7161 for (l = 0; l < giv_count; ++l)
7163 int m = stats[l].giv_number;
7164 if (can_combine[m*giv_count + j])
7165 stats[l].total_benefit -= g2->benefit + extra_benefit;
7168 if (loop_dump_stream)
7169 fprintf (loop_dump_stream,
7170 "giv at %d combined with giv at %d\n",
7171 INSN_UID (g2->insn), INSN_UID (g1->insn));
7175 /* To help optimize the next set of combinations, remove
7176 this giv from the benefits of other potential mates. */
7177 if (g1->combined_with)
7179 for (j = 0; j < giv_count; ++j)
7181 int m = stats[j].giv_number;
7182 if (can_combine[m*giv_count + i])
7183 stats[j].total_benefit -= g1->benefit + extra_benefit;
7186 g1->benefit += g1_add_benefit;
7188 /* We've finished with this giv, and everything it touched.
7189 Restart the combination so that proper weights for the
7190 rest of the givs are properly taken into account. */
7191 /* ??? Ideally we would compact the arrays at this point, so
7192 as to not cover old ground. But sanely compacting
7193 can_combine is tricky. */
7194 goto restart;
7198 /* Clean up. */
7199 free (stats);
7200 free (can_combine);
7203 struct recombine_givs_stats
7205 int giv_number;
7206 int start_luid, end_luid;
7209 /* Used below as comparison function for qsort. We want a ascending luid
7210 when scanning the array starting at the end, thus the arguments are
7211 used in reverse. */
7212 static int
7213 cmp_recombine_givs_stats (xp, yp)
7214 const PTR xp;
7215 const PTR yp;
7217 const struct recombine_givs_stats * const x =
7218 (const struct recombine_givs_stats *) xp;
7219 const struct recombine_givs_stats * const y =
7220 (const struct recombine_givs_stats *) yp;
7221 int d;
7222 d = y->start_luid - x->start_luid;
7223 /* Stabilize the sort. */
7224 if (!d)
7225 d = y->giv_number - x->giv_number;
7226 return d;
7229 /* Scan X, which is a part of INSN, for the end of life of a giv. Also
7230 look for the start of life of a giv where the start has not been seen
7231 yet to unlock the search for the end of its life.
7232 Only consider givs that belong to BIV.
7233 Return the total number of lifetime ends that have been found. */
7234 static int
7235 find_life_end (x, stats, insn, biv)
7236 rtx x, insn, biv;
7237 struct recombine_givs_stats *stats;
7239 enum rtx_code code;
7240 const char *fmt;
7241 int i, j;
7242 int retval;
7244 code = GET_CODE (x);
7245 switch (code)
7247 case SET:
7249 rtx reg = SET_DEST (x);
7250 if (GET_CODE (reg) == REG)
7252 int regno = REGNO (reg);
7253 struct induction *v = REG_IV_INFO (regno);
7255 if (REG_IV_TYPE (regno) == GENERAL_INDUCT
7256 && ! v->ignore
7257 && v->src_reg == biv
7258 && stats[v->ix].end_luid <= 0)
7260 /* If we see a 0 here for end_luid, it means that we have
7261 scanned the entire loop without finding any use at all.
7262 We must not predicate this code on a start_luid match
7263 since that would make the test fail for givs that have
7264 been hoisted out of inner loops. */
7265 if (stats[v->ix].end_luid == 0)
7267 stats[v->ix].end_luid = stats[v->ix].start_luid;
7268 return 1 + find_life_end (SET_SRC (x), stats, insn, biv);
7270 else if (stats[v->ix].start_luid == INSN_LUID (insn))
7271 stats[v->ix].end_luid = 0;
7273 return find_life_end (SET_SRC (x), stats, insn, biv);
7275 break;
7277 case REG:
7279 int regno = REGNO (x);
7280 struct induction *v = REG_IV_INFO (regno);
7282 if (REG_IV_TYPE (regno) == GENERAL_INDUCT
7283 && ! v->ignore
7284 && v->src_reg == biv
7285 && stats[v->ix].end_luid == 0)
7287 while (INSN_UID (insn) >= max_uid_for_loop)
7288 insn = NEXT_INSN (insn);
7289 stats[v->ix].end_luid = INSN_LUID (insn);
7290 return 1;
7292 return 0;
7294 case LABEL_REF:
7295 case CONST_DOUBLE:
7296 case CONST_INT:
7297 case CONST:
7298 return 0;
7299 default:
7300 break;
7302 fmt = GET_RTX_FORMAT (code);
7303 retval = 0;
7304 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7306 if (fmt[i] == 'e')
7307 retval += find_life_end (XEXP (x, i), stats, insn, biv);
7309 else if (fmt[i] == 'E')
7310 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7311 retval += find_life_end (XVECEXP (x, i, j), stats, insn, biv);
7313 return retval;
7316 /* For each giv that has been combined with another, look if
7317 we can combine it with the most recently used one instead.
7318 This tends to shorten giv lifetimes, and helps the next step:
7319 try to derive givs from other givs. */
7320 static void
7321 recombine_givs (loop, bl, unroll_p)
7322 const struct loop *loop;
7323 struct iv_class *bl;
7324 int unroll_p;
7326 struct induction *v, **giv_array, *last_giv;
7327 struct recombine_givs_stats *stats;
7328 int giv_count;
7329 int i, rescan;
7330 int ends_need_computing;
7332 for (giv_count = 0, v = bl->giv; v; v = v->next_iv)
7334 if (! v->ignore)
7335 giv_count++;
7337 giv_array
7338 = (struct induction **) xmalloc (giv_count * sizeof (struct induction *));
7339 stats = (struct recombine_givs_stats *) xmalloc (giv_count * sizeof *stats);
7341 /* Initialize stats and set up the ix field for each giv in stats to name
7342 the corresponding index into stats. */
7343 for (i = 0, v = bl->giv; v; v = v->next_iv)
7345 rtx p;
7347 if (v->ignore)
7348 continue;
7349 giv_array[i] = v;
7350 stats[i].giv_number = i;
7351 /* If this giv has been hoisted out of an inner loop, use the luid of
7352 the previous insn. */
7353 for (p = v->insn; INSN_UID (p) >= max_uid_for_loop; )
7354 p = PREV_INSN (p);
7355 stats[i].start_luid = INSN_LUID (p);
7356 i++;
7359 qsort (stats, giv_count, sizeof(*stats), cmp_recombine_givs_stats);
7361 /* Set up the ix field for each giv in stats to name
7362 the corresponding index into stats, and
7363 do the actual most-recently-used recombination. */
7364 for (last_giv = 0, i = giv_count - 1; i >= 0; i--)
7366 v = giv_array[stats[i].giv_number];
7367 v->ix = i;
7368 if (v->same)
7370 struct induction *old_same = v->same;
7371 rtx new_combine;
7373 /* combine_givs_p actually says if we can make this transformation.
7374 The other tests are here only to avoid keeping a giv alive
7375 that could otherwise be eliminated. */
7376 if (last_giv
7377 && ((old_same->maybe_dead && ! old_same->combined_with)
7378 || ! last_giv->maybe_dead
7379 || last_giv->combined_with)
7380 && (new_combine = combine_givs_p (last_giv, v)))
7382 old_same->combined_with--;
7383 v->new_reg = new_combine;
7384 v->same = last_giv;
7385 last_giv->combined_with++;
7386 /* No need to update lifetimes / benefits here since we have
7387 already decided what to reduce. */
7389 if (loop_dump_stream)
7391 fprintf (loop_dump_stream,
7392 "giv at %d recombined with giv at %d as ",
7393 INSN_UID (v->insn), INSN_UID (last_giv->insn));
7394 print_rtl (loop_dump_stream, v->new_reg);
7395 putc ('\n', loop_dump_stream);
7397 continue;
7399 v = v->same;
7401 else if (v->giv_type != DEST_REG)
7402 continue;
7403 if (! last_giv
7404 || (last_giv->maybe_dead && ! last_giv->combined_with)
7405 || ! v->maybe_dead
7406 || v->combined_with)
7407 last_giv = v;
7410 ends_need_computing = 0;
7411 /* For each DEST_REG giv, compute lifetime starts, and try to compute
7412 lifetime ends from regscan info. */
7413 for (i = giv_count - 1; i >= 0; i--)
7415 v = giv_array[stats[i].giv_number];
7416 if (v->ignore)
7417 continue;
7418 if (v->giv_type == DEST_ADDR)
7420 /* Loop unrolling of an inner loop can even create new DEST_REG
7421 givs. */
7422 rtx p;
7423 for (p = v->insn; INSN_UID (p) >= max_uid_for_loop; )
7424 p = PREV_INSN (p);
7425 stats[i].start_luid = stats[i].end_luid = INSN_LUID (p);
7426 if (p != v->insn)
7427 stats[i].end_luid++;
7429 else /* v->giv_type == DEST_REG */
7431 if (v->last_use)
7433 stats[i].start_luid = INSN_LUID (v->insn);
7434 stats[i].end_luid = INSN_LUID (v->last_use);
7436 else if (INSN_UID (v->insn) >= max_uid_for_loop)
7438 rtx p;
7439 /* This insn has been created by loop optimization on an inner
7440 loop. We don't have a proper start_luid that will match
7441 when we see the first set. But we do know that there will
7442 be no use before the set, so we can set end_luid to 0 so that
7443 we'll start looking for the last use right away. */
7444 for (p = PREV_INSN (v->insn); INSN_UID (p) >= max_uid_for_loop; )
7445 p = PREV_INSN (p);
7446 stats[i].start_luid = INSN_LUID (p);
7447 stats[i].end_luid = 0;
7448 ends_need_computing++;
7450 else
7452 int regno = REGNO (v->dest_reg);
7453 int count = VARRAY_INT (n_times_set, regno) - 1;
7454 rtx p = v->insn;
7456 /* Find the first insn that sets the giv, so that we can verify
7457 if this giv's lifetime wraps around the loop. We also need
7458 the luid of the first setting insn in order to detect the
7459 last use properly. */
7460 while (count)
7462 p = prev_nonnote_insn (p);
7463 if (reg_set_p (v->dest_reg, p))
7464 count--;
7467 stats[i].start_luid = INSN_LUID (p);
7468 if (stats[i].start_luid > uid_luid[REGNO_FIRST_UID (regno)])
7470 stats[i].end_luid = -1;
7471 ends_need_computing++;
7473 else
7475 stats[i].end_luid = uid_luid[REGNO_LAST_UID (regno)];
7476 if (stats[i].end_luid > INSN_LUID (loop->end))
7478 stats[i].end_luid = -1;
7479 ends_need_computing++;
7486 /* If the regscan information was unconclusive for one or more DEST_REG
7487 givs, scan the all insn in the loop to find out lifetime ends. */
7488 if (ends_need_computing)
7490 rtx biv = bl->biv->src_reg;
7491 rtx p = loop->end;
7495 if (p == loop->start)
7496 p = loop->end;
7497 p = PREV_INSN (p);
7498 if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
7499 continue;
7500 ends_need_computing -= find_life_end (PATTERN (p), stats, p, biv);
7502 while (ends_need_computing);
7505 /* Set start_luid back to the last insn that sets the giv. This allows
7506 more combinations. */
7507 for (i = giv_count - 1; i >= 0; i--)
7509 v = giv_array[stats[i].giv_number];
7510 if (v->ignore)
7511 continue;
7512 if (INSN_UID (v->insn) < max_uid_for_loop)
7513 stats[i].start_luid = INSN_LUID (v->insn);
7516 /* Now adjust lifetime ends by taking combined givs into account. */
7517 for (i = giv_count - 1; i >= 0; i--)
7519 unsigned luid;
7520 int j;
7522 v = giv_array[stats[i].giv_number];
7523 if (v->ignore)
7524 continue;
7525 if (v->same && ! v->same->ignore)
7527 j = v->same->ix;
7528 luid = stats[i].start_luid;
7529 /* Use unsigned arithmetic to model loop wrap-around. */
7530 if (luid - stats[j].start_luid
7531 > (unsigned) stats[j].end_luid - stats[j].start_luid)
7532 stats[j].end_luid = luid;
7536 qsort (stats, giv_count, sizeof(*stats), cmp_recombine_givs_stats);
7538 /* Try to derive DEST_REG givs from previous DEST_REG givs with the
7539 same mult_val and non-overlapping lifetime. This reduces register
7540 pressure.
7541 Once we find a DEST_REG giv that is suitable to derive others from,
7542 we set last_giv to this giv, and try to derive as many other DEST_REG
7543 givs from it without joining overlapping lifetimes. If we then
7544 encounter a DEST_REG giv that we can't derive, we set rescan to the
7545 index for this giv (unless rescan is already set).
7546 When we are finished with the current LAST_GIV (i.e. the inner loop
7547 terminates), we start again with rescan, which then becomes the new
7548 LAST_GIV. */
7549 for (i = giv_count - 1; i >= 0; i = rescan)
7551 int life_start = 0, life_end = 0;
7553 for (last_giv = 0, rescan = -1; i >= 0; i--)
7555 rtx sum;
7557 v = giv_array[stats[i].giv_number];
7558 if (v->giv_type != DEST_REG || v->derived_from || v->same)
7559 continue;
7560 if (! last_giv)
7562 /* Don't use a giv that's likely to be dead to derive
7563 others - that would be likely to keep that giv alive. */
7564 if (! v->maybe_dead || v->combined_with)
7566 last_giv = v;
7567 life_start = stats[i].start_luid;
7568 life_end = stats[i].end_luid;
7570 continue;
7572 /* Use unsigned arithmetic to model loop wrap around. */
7573 if (((unsigned) stats[i].start_luid - life_start
7574 >= (unsigned) life_end - life_start)
7575 && ((unsigned) stats[i].end_luid - life_start
7576 > (unsigned) life_end - life_start)
7577 /* Check that the giv insn we're about to use for deriving
7578 precedes all uses of that giv. Note that initializing the
7579 derived giv would defeat the purpose of reducing register
7580 pressure.
7581 ??? We could arrange to move the insn. */
7582 && ((unsigned) stats[i].end_luid - INSN_LUID (loop->start)
7583 > (unsigned) stats[i].start_luid - INSN_LUID (loop->start))
7584 && rtx_equal_p (last_giv->mult_val, v->mult_val)
7585 /* ??? Could handle libcalls, but would need more logic. */
7586 && ! find_reg_note (v->insn, REG_RETVAL, NULL_RTX)
7587 /* We would really like to know if for any giv that v
7588 is combined with, v->insn or any intervening biv increment
7589 dominates that combined giv. However, we
7590 don't have this detailed control flow information.
7591 N.B. since last_giv will be reduced, it is valid
7592 anywhere in the loop, so we don't need to check the
7593 validity of last_giv.
7594 We rely here on the fact that v->always_executed implies that
7595 there is no jump to someplace else in the loop before the
7596 giv insn, and hence any insn that is executed before the
7597 giv insn in the loop will have a lower luid. */
7598 && (v->always_executed || ! v->combined_with)
7599 && (sum = express_from (last_giv, v))
7600 /* Make sure we don't make the add more expensive. ADD_COST
7601 doesn't take different costs of registers and constants into
7602 account, so compare the cost of the actual SET_SRCs. */
7603 && (rtx_cost (sum, SET)
7604 <= rtx_cost (SET_SRC (single_set (v->insn)), SET))
7605 /* ??? unroll can't understand anything but reg + const_int
7606 sums. It would be cleaner to fix unroll. */
7607 && ((GET_CODE (sum) == PLUS
7608 && GET_CODE (XEXP (sum, 0)) == REG
7609 && GET_CODE (XEXP (sum, 1)) == CONST_INT)
7610 || ! unroll_p)
7611 && validate_change (v->insn, &PATTERN (v->insn),
7612 gen_rtx_SET (VOIDmode, v->dest_reg, sum), 0))
7614 v->derived_from = last_giv;
7615 life_end = stats[i].end_luid;
7617 if (loop_dump_stream)
7619 fprintf (loop_dump_stream,
7620 "giv at %d derived from %d as ",
7621 INSN_UID (v->insn), INSN_UID (last_giv->insn));
7622 print_rtl (loop_dump_stream, sum);
7623 putc ('\n', loop_dump_stream);
7626 else if (rescan < 0)
7627 rescan = i;
7631 /* Clean up. */
7632 free (giv_array);
7633 free (stats);
7636 /* EMIT code before INSERT_BEFORE to set REG = B * M + A. */
7638 void
7639 emit_iv_add_mult (b, m, a, reg, insert_before)
7640 rtx b; /* initial value of basic induction variable */
7641 rtx m; /* multiplicative constant */
7642 rtx a; /* additive constant */
7643 rtx reg; /* destination register */
7644 rtx insert_before;
7646 rtx seq;
7647 rtx result;
7649 /* Prevent unexpected sharing of these rtx. */
7650 a = copy_rtx (a);
7651 b = copy_rtx (b);
7653 /* Increase the lifetime of any invariants moved further in code. */
7654 update_reg_last_use (a, insert_before);
7655 update_reg_last_use (b, insert_before);
7656 update_reg_last_use (m, insert_before);
7658 start_sequence ();
7659 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 0);
7660 if (reg != result)
7661 emit_move_insn (reg, result);
7662 seq = gen_sequence ();
7663 end_sequence ();
7665 emit_insn_before (seq, insert_before);
7667 /* It is entirely possible that the expansion created lots of new
7668 registers. Iterate over the sequence we just created and
7669 record them all. */
7671 if (GET_CODE (seq) == SEQUENCE)
7673 int i;
7674 for (i = 0; i < XVECLEN (seq, 0); ++i)
7676 rtx set = single_set (XVECEXP (seq, 0, i));
7677 if (set && GET_CODE (SET_DEST (set)) == REG)
7678 record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
7681 else if (GET_CODE (seq) == SET
7682 && GET_CODE (SET_DEST (seq)) == REG)
7683 record_base_value (REGNO (SET_DEST (seq)), SET_SRC (seq), 0);
7686 /* Test whether A * B can be computed without
7687 an actual multiply insn. Value is 1 if so. */
7689 static int
7690 product_cheap_p (a, b)
7691 rtx a;
7692 rtx b;
7694 int i;
7695 rtx tmp;
7696 struct obstack *old_rtl_obstack = rtl_obstack;
7697 char *storage = (char *) obstack_alloc (&temp_obstack, 0);
7698 int win = 1;
7700 /* If only one is constant, make it B. */
7701 if (GET_CODE (a) == CONST_INT)
7702 tmp = a, a = b, b = tmp;
7704 /* If first constant, both constant, so don't need multiply. */
7705 if (GET_CODE (a) == CONST_INT)
7706 return 1;
7708 /* If second not constant, neither is constant, so would need multiply. */
7709 if (GET_CODE (b) != CONST_INT)
7710 return 0;
7712 /* One operand is constant, so might not need multiply insn. Generate the
7713 code for the multiply and see if a call or multiply, or long sequence
7714 of insns is generated. */
7716 rtl_obstack = &temp_obstack;
7717 start_sequence ();
7718 expand_mult (GET_MODE (a), a, b, NULL_RTX, 0);
7719 tmp = gen_sequence ();
7720 end_sequence ();
7722 if (GET_CODE (tmp) == SEQUENCE)
7724 if (XVEC (tmp, 0) == 0)
7725 win = 1;
7726 else if (XVECLEN (tmp, 0) > 3)
7727 win = 0;
7728 else
7729 for (i = 0; i < XVECLEN (tmp, 0); i++)
7731 rtx insn = XVECEXP (tmp, 0, i);
7733 if (GET_CODE (insn) != INSN
7734 || (GET_CODE (PATTERN (insn)) == SET
7735 && GET_CODE (SET_SRC (PATTERN (insn))) == MULT)
7736 || (GET_CODE (PATTERN (insn)) == PARALLEL
7737 && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == SET
7738 && GET_CODE (SET_SRC (XVECEXP (PATTERN (insn), 0, 0))) == MULT))
7740 win = 0;
7741 break;
7745 else if (GET_CODE (tmp) == SET
7746 && GET_CODE (SET_SRC (tmp)) == MULT)
7747 win = 0;
7748 else if (GET_CODE (tmp) == PARALLEL
7749 && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
7750 && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
7751 win = 0;
7753 /* Free any storage we obtained in generating this multiply and restore rtl
7754 allocation to its normal obstack. */
7755 obstack_free (&temp_obstack, storage);
7756 rtl_obstack = old_rtl_obstack;
7758 return win;
7761 /* Check to see if loop can be terminated by a "decrement and branch until
7762 zero" instruction. If so, add a REG_NONNEG note to the branch insn if so.
7763 Also try reversing an increment loop to a decrement loop
7764 to see if the optimization can be performed.
7765 Value is nonzero if optimization was performed. */
7767 /* This is useful even if the architecture doesn't have such an insn,
7768 because it might change a loops which increments from 0 to n to a loop
7769 which decrements from n to 0. A loop that decrements to zero is usually
7770 faster than one that increments from zero. */
7772 /* ??? This could be rewritten to use some of the loop unrolling procedures,
7773 such as approx_final_value, biv_total_increment, loop_iterations, and
7774 final_[bg]iv_value. */
7776 static int
7777 check_dbra_loop (loop, insn_count)
7778 struct loop *loop;
7779 int insn_count;
7781 struct iv_class *bl;
7782 rtx reg;
7783 rtx jump_label;
7784 rtx final_value;
7785 rtx start_value;
7786 rtx new_add_val;
7787 rtx comparison;
7788 rtx before_comparison;
7789 rtx p;
7790 rtx jump;
7791 rtx first_compare;
7792 int compare_and_branch;
7793 rtx loop_start = loop->start;
7794 rtx loop_end = loop->end;
7795 struct loop_info *loop_info = LOOP_INFO (loop);
7797 /* If last insn is a conditional branch, and the insn before tests a
7798 register value, try to optimize it. Otherwise, we can't do anything. */
7800 jump = PREV_INSN (loop_end);
7801 comparison = get_condition_for_loop (loop, jump);
7802 if (comparison == 0)
7803 return 0;
7805 /* Try to compute whether the compare/branch at the loop end is one or
7806 two instructions. */
7807 get_condition (jump, &first_compare);
7808 if (first_compare == jump)
7809 compare_and_branch = 1;
7810 else if (first_compare == prev_nonnote_insn (jump))
7811 compare_and_branch = 2;
7812 else
7813 return 0;
7815 /* Check all of the bivs to see if the compare uses one of them.
7816 Skip biv's set more than once because we can't guarantee that
7817 it will be zero on the last iteration. Also skip if the biv is
7818 used between its update and the test insn. */
7820 for (bl = loop_iv_list; bl; bl = bl->next)
7822 if (bl->biv_count == 1
7823 && ! bl->biv->maybe_multiple
7824 && bl->biv->dest_reg == XEXP (comparison, 0)
7825 && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
7826 first_compare))
7827 break;
7830 if (! bl)
7831 return 0;
7833 /* Look for the case where the basic induction variable is always
7834 nonnegative, and equals zero on the last iteration.
7835 In this case, add a reg_note REG_NONNEG, which allows the
7836 m68k DBRA instruction to be used. */
7838 if (((GET_CODE (comparison) == GT
7839 && GET_CODE (XEXP (comparison, 1)) == CONST_INT
7840 && INTVAL (XEXP (comparison, 1)) == -1)
7841 || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
7842 && GET_CODE (bl->biv->add_val) == CONST_INT
7843 && INTVAL (bl->biv->add_val) < 0)
7845 /* Initial value must be greater than 0,
7846 init_val % -dec_value == 0 to ensure that it equals zero on
7847 the last iteration */
7849 if (GET_CODE (bl->initial_value) == CONST_INT
7850 && INTVAL (bl->initial_value) > 0
7851 && (INTVAL (bl->initial_value)
7852 % (-INTVAL (bl->biv->add_val))) == 0)
7854 /* register always nonnegative, add REG_NOTE to branch */
7855 REG_NOTES (PREV_INSN (loop_end))
7856 = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7857 REG_NOTES (PREV_INSN (loop_end)));
7858 bl->nonneg = 1;
7860 return 1;
7863 /* If the decrement is 1 and the value was tested as >= 0 before
7864 the loop, then we can safely optimize. */
7865 for (p = loop_start; p; p = PREV_INSN (p))
7867 if (GET_CODE (p) == CODE_LABEL)
7868 break;
7869 if (GET_CODE (p) != JUMP_INSN)
7870 continue;
7872 before_comparison = get_condition_for_loop (loop, p);
7873 if (before_comparison
7874 && XEXP (before_comparison, 0) == bl->biv->dest_reg
7875 && GET_CODE (before_comparison) == LT
7876 && XEXP (before_comparison, 1) == const0_rtx
7877 && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
7878 && INTVAL (bl->biv->add_val) == -1)
7880 REG_NOTES (PREV_INSN (loop_end))
7881 = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7882 REG_NOTES (PREV_INSN (loop_end)));
7883 bl->nonneg = 1;
7885 return 1;
7889 else if (GET_CODE (bl->biv->add_val) == CONST_INT
7890 && INTVAL (bl->biv->add_val) > 0)
7892 /* Try to change inc to dec, so can apply above optimization. */
7893 /* Can do this if:
7894 all registers modified are induction variables or invariant,
7895 all memory references have non-overlapping addresses
7896 (obviously true if only one write)
7897 allow 2 insns for the compare/jump at the end of the loop. */
7898 /* Also, we must avoid any instructions which use both the reversed
7899 biv and another biv. Such instructions will fail if the loop is
7900 reversed. We meet this condition by requiring that either
7901 no_use_except_counting is true, or else that there is only
7902 one biv. */
7903 int num_nonfixed_reads = 0;
7904 /* 1 if the iteration var is used only to count iterations. */
7905 int no_use_except_counting = 0;
7906 /* 1 if the loop has no memory store, or it has a single memory store
7907 which is reversible. */
7908 int reversible_mem_store = 1;
7910 if (bl->giv_count == 0 && ! loop->exit_count)
7912 rtx bivreg = regno_reg_rtx[bl->regno];
7914 /* If there are no givs for this biv, and the only exit is the
7915 fall through at the end of the loop, then
7916 see if perhaps there are no uses except to count. */
7917 no_use_except_counting = 1;
7918 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
7919 if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
7921 rtx set = single_set (p);
7923 if (set && GET_CODE (SET_DEST (set)) == REG
7924 && REGNO (SET_DEST (set)) == bl->regno)
7925 /* An insn that sets the biv is okay. */
7927 else if ((p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
7928 || p == prev_nonnote_insn (loop_end))
7929 && reg_mentioned_p (bivreg, PATTERN (p)))
7931 /* If either of these insns uses the biv and sets a pseudo
7932 that has more than one usage, then the biv has uses
7933 other than counting since it's used to derive a value
7934 that is used more than one time. */
7935 int note_set_pseudo_multiple_uses_retval = 0;
7936 note_stores (PATTERN (p), note_set_pseudo_multiple_uses,
7937 &note_set_pseudo_multiple_uses_retval);
7938 if (note_set_pseudo_multiple_uses_retval)
7940 no_use_except_counting = 0;
7941 break;
7944 else if (reg_mentioned_p (bivreg, PATTERN (p)))
7946 no_use_except_counting = 0;
7947 break;
7952 if (no_use_except_counting)
7953 ; /* no need to worry about MEMs. */
7954 else if (num_mem_sets <= 1)
7956 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
7957 if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
7958 num_nonfixed_reads += count_nonfixed_reads (loop, PATTERN (p));
7960 /* If the loop has a single store, and the destination address is
7961 invariant, then we can't reverse the loop, because this address
7962 might then have the wrong value at loop exit.
7963 This would work if the source was invariant also, however, in that
7964 case, the insn should have been moved out of the loop. */
7966 if (num_mem_sets == 1)
7968 struct induction *v;
7970 reversible_mem_store
7971 = (! unknown_address_altered
7972 && ! unknown_constant_address_altered
7973 && ! loop_invariant_p (loop,
7974 XEXP (XEXP (loop_store_mems, 0),
7975 0)));
7977 /* If the store depends on a register that is set after the
7978 store, it depends on the initial value, and is thus not
7979 reversible. */
7980 for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
7982 if (v->giv_type == DEST_REG
7983 && reg_mentioned_p (v->dest_reg,
7984 PATTERN (first_loop_store_insn))
7985 && loop_insn_first_p (first_loop_store_insn, v->insn))
7986 reversible_mem_store = 0;
7990 else
7991 return 0;
7993 /* This code only acts for innermost loops. Also it simplifies
7994 the memory address check by only reversing loops with
7995 zero or one memory access.
7996 Two memory accesses could involve parts of the same array,
7997 and that can't be reversed.
7998 If the biv is used only for counting, than we don't need to worry
7999 about all these things. */
8001 if ((num_nonfixed_reads <= 1
8002 && ! loop_info->has_call
8003 && ! loop_info->has_volatile
8004 && reversible_mem_store
8005 && (bl->giv_count + bl->biv_count + num_mem_sets
8006 + num_movables + compare_and_branch == insn_count)
8007 && (bl == loop_iv_list && bl->next == 0))
8008 || no_use_except_counting)
8010 rtx tem;
8012 /* Loop can be reversed. */
8013 if (loop_dump_stream)
8014 fprintf (loop_dump_stream, "Can reverse loop\n");
8016 /* Now check other conditions:
8018 The increment must be a constant, as must the initial value,
8019 and the comparison code must be LT.
8021 This test can probably be improved since +/- 1 in the constant
8022 can be obtained by changing LT to LE and vice versa; this is
8023 confusing. */
8025 if (comparison
8026 /* for constants, LE gets turned into LT */
8027 && (GET_CODE (comparison) == LT
8028 || (GET_CODE (comparison) == LE
8029 && no_use_except_counting)))
8031 HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
8032 rtx initial_value, comparison_value;
8033 int nonneg = 0;
8034 enum rtx_code cmp_code;
8035 int comparison_const_width;
8036 unsigned HOST_WIDE_INT comparison_sign_mask;
8038 add_val = INTVAL (bl->biv->add_val);
8039 comparison_value = XEXP (comparison, 1);
8040 if (GET_MODE (comparison_value) == VOIDmode)
8041 comparison_const_width
8042 = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
8043 else
8044 comparison_const_width
8045 = GET_MODE_BITSIZE (GET_MODE (comparison_value));
8046 if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
8047 comparison_const_width = HOST_BITS_PER_WIDE_INT;
8048 comparison_sign_mask
8049 = (unsigned HOST_WIDE_INT)1 << (comparison_const_width - 1);
8051 /* If the comparison value is not a loop invariant, then we
8052 can not reverse this loop.
8054 ??? If the insns which initialize the comparison value as
8055 a whole compute an invariant result, then we could move
8056 them out of the loop and proceed with loop reversal. */
8057 if (! loop_invariant_p (loop, comparison_value))
8058 return 0;
8060 if (GET_CODE (comparison_value) == CONST_INT)
8061 comparison_val = INTVAL (comparison_value);
8062 initial_value = bl->initial_value;
8064 /* Normalize the initial value if it is an integer and
8065 has no other use except as a counter. This will allow
8066 a few more loops to be reversed. */
8067 if (no_use_except_counting
8068 && GET_CODE (comparison_value) == CONST_INT
8069 && GET_CODE (initial_value) == CONST_INT)
8071 comparison_val = comparison_val - INTVAL (bl->initial_value);
8072 /* The code below requires comparison_val to be a multiple
8073 of add_val in order to do the loop reversal, so
8074 round up comparison_val to a multiple of add_val.
8075 Since comparison_value is constant, we know that the
8076 current comparison code is LT. */
8077 comparison_val = comparison_val + add_val - 1;
8078 comparison_val
8079 -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
8080 /* We postpone overflow checks for COMPARISON_VAL here;
8081 even if there is an overflow, we might still be able to
8082 reverse the loop, if converting the loop exit test to
8083 NE is possible. */
8084 initial_value = const0_rtx;
8087 /* First check if we can do a vanilla loop reversal. */
8088 if (initial_value == const0_rtx
8089 /* If we have a decrement_and_branch_on_count,
8090 prefer the NE test, since this will allow that
8091 instruction to be generated. Note that we must
8092 use a vanilla loop reversal if the biv is used to
8093 calculate a giv or has a non-counting use. */
8094 #if ! defined (HAVE_decrement_and_branch_until_zero) \
8095 && defined (HAVE_decrement_and_branch_on_count)
8096 && (! (add_val == 1 && loop->vtop
8097 && (bl->biv_count == 0
8098 || no_use_except_counting)))
8099 #endif
8100 && GET_CODE (comparison_value) == CONST_INT
8101 /* Now do postponed overflow checks on COMPARISON_VAL. */
8102 && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
8103 & comparison_sign_mask))
8105 /* Register will always be nonnegative, with value
8106 0 on last iteration */
8107 add_adjust = add_val;
8108 nonneg = 1;
8109 cmp_code = GE;
8111 else if (add_val == 1 && loop->vtop
8112 && (bl->biv_count == 0
8113 || no_use_except_counting))
8115 add_adjust = 0;
8116 cmp_code = NE;
8118 else
8119 return 0;
8121 if (GET_CODE (comparison) == LE)
8122 add_adjust -= add_val;
8124 /* If the initial value is not zero, or if the comparison
8125 value is not an exact multiple of the increment, then we
8126 can not reverse this loop. */
8127 if (initial_value == const0_rtx
8128 && GET_CODE (comparison_value) == CONST_INT)
8130 if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
8131 return 0;
8133 else
8135 if (! no_use_except_counting || add_val != 1)
8136 return 0;
8139 final_value = comparison_value;
8141 /* Reset these in case we normalized the initial value
8142 and comparison value above. */
8143 if (GET_CODE (comparison_value) == CONST_INT
8144 && GET_CODE (initial_value) == CONST_INT)
8146 comparison_value = GEN_INT (comparison_val);
8147 final_value
8148 = GEN_INT (comparison_val + INTVAL (bl->initial_value));
8150 bl->initial_value = initial_value;
8152 /* Save some info needed to produce the new insns. */
8153 reg = bl->biv->dest_reg;
8154 jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 1);
8155 if (jump_label == pc_rtx)
8156 jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 2);
8157 new_add_val = GEN_INT (- INTVAL (bl->biv->add_val));
8159 /* Set start_value; if this is not a CONST_INT, we need
8160 to generate a SUB.
8161 Initialize biv to start_value before loop start.
8162 The old initializing insn will be deleted as a
8163 dead store by flow.c. */
8164 if (initial_value == const0_rtx
8165 && GET_CODE (comparison_value) == CONST_INT)
8167 start_value = GEN_INT (comparison_val - add_adjust);
8168 emit_insn_before (gen_move_insn (reg, start_value),
8169 loop_start);
8171 else if (GET_CODE (initial_value) == CONST_INT)
8173 rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
8174 enum machine_mode mode = GET_MODE (reg);
8175 enum insn_code icode
8176 = add_optab->handlers[(int) mode].insn_code;
8178 if (! (*insn_data[icode].operand[0].predicate) (reg, mode)
8179 || ! ((*insn_data[icode].operand[1].predicate)
8180 (comparison_value, mode))
8181 || ! ((*insn_data[icode].operand[2].predicate)
8182 (offset, mode)))
8183 return 0;
8184 start_value
8185 = gen_rtx_PLUS (mode, comparison_value, offset);
8186 emit_insn_before ((GEN_FCN (icode)
8187 (reg, comparison_value, offset)),
8188 loop_start);
8189 if (GET_CODE (comparison) == LE)
8190 final_value = gen_rtx_PLUS (mode, comparison_value,
8191 GEN_INT (add_val));
8193 else if (! add_adjust)
8195 enum machine_mode mode = GET_MODE (reg);
8196 enum insn_code icode
8197 = sub_optab->handlers[(int) mode].insn_code;
8198 if (! (*insn_data[icode].operand[0].predicate) (reg, mode)
8199 || ! ((*insn_data[icode].operand[1].predicate)
8200 (comparison_value, mode))
8201 || ! ((*insn_data[icode].operand[2].predicate)
8202 (initial_value, mode)))
8203 return 0;
8204 start_value
8205 = gen_rtx_MINUS (mode, comparison_value, initial_value);
8206 emit_insn_before ((GEN_FCN (icode)
8207 (reg, comparison_value, initial_value)),
8208 loop_start);
8210 else
8211 /* We could handle the other cases too, but it'll be
8212 better to have a testcase first. */
8213 return 0;
8215 /* We may not have a single insn which can increment a reg, so
8216 create a sequence to hold all the insns from expand_inc. */
8217 start_sequence ();
8218 expand_inc (reg, new_add_val);
8219 tem = gen_sequence ();
8220 end_sequence ();
8222 p = emit_insn_before (tem, bl->biv->insn);
8223 delete_insn (bl->biv->insn);
8225 /* Update biv info to reflect its new status. */
8226 bl->biv->insn = p;
8227 bl->initial_value = start_value;
8228 bl->biv->add_val = new_add_val;
8230 /* Update loop info. */
8231 loop_info->initial_value = reg;
8232 loop_info->initial_equiv_value = reg;
8233 loop_info->final_value = const0_rtx;
8234 loop_info->final_equiv_value = const0_rtx;
8235 loop_info->comparison_value = const0_rtx;
8236 loop_info->comparison_code = cmp_code;
8237 loop_info->increment = new_add_val;
8239 /* Inc LABEL_NUSES so that delete_insn will
8240 not delete the label. */
8241 LABEL_NUSES (XEXP (jump_label, 0)) ++;
8243 /* Emit an insn after the end of the loop to set the biv's
8244 proper exit value if it is used anywhere outside the loop. */
8245 if ((REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
8246 || ! bl->init_insn
8247 || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
8248 emit_insn_after (gen_move_insn (reg, final_value),
8249 loop_end);
8251 /* Delete compare/branch at end of loop. */
8252 delete_insn (PREV_INSN (loop_end));
8253 if (compare_and_branch == 2)
8254 delete_insn (first_compare);
8256 /* Add new compare/branch insn at end of loop. */
8257 start_sequence ();
8258 emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
8259 GET_MODE (reg), 0, 0,
8260 XEXP (jump_label, 0));
8261 tem = gen_sequence ();
8262 end_sequence ();
8263 emit_jump_insn_before (tem, loop_end);
8265 for (tem = PREV_INSN (loop_end);
8266 tem && GET_CODE (tem) != JUMP_INSN;
8267 tem = PREV_INSN (tem))
8270 if (tem)
8271 JUMP_LABEL (tem) = XEXP (jump_label, 0);
8273 if (nonneg)
8275 if (tem)
8277 /* Increment of LABEL_NUSES done above. */
8278 /* Register is now always nonnegative,
8279 so add REG_NONNEG note to the branch. */
8280 REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
8281 REG_NOTES (tem));
8283 bl->nonneg = 1;
8286 /* No insn may reference both the reversed and another biv or it
8287 will fail (see comment near the top of the loop reversal
8288 code).
8289 Earlier on, we have verified that the biv has no use except
8290 counting, or it is the only biv in this function.
8291 However, the code that computes no_use_except_counting does
8292 not verify reg notes. It's possible to have an insn that
8293 references another biv, and has a REG_EQUAL note with an
8294 expression based on the reversed biv. To avoid this case,
8295 remove all REG_EQUAL notes based on the reversed biv
8296 here. */
8297 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8298 if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
8300 rtx *pnote;
8301 rtx set = single_set (p);
8302 /* If this is a set of a GIV based on the reversed biv, any
8303 REG_EQUAL notes should still be correct. */
8304 if (! set
8305 || GET_CODE (SET_DEST (set)) != REG
8306 || (size_t) REGNO (SET_DEST (set)) >= reg_iv_type->num_elements
8307 || REG_IV_TYPE (REGNO (SET_DEST (set))) != GENERAL_INDUCT
8308 || REG_IV_INFO (REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
8309 for (pnote = &REG_NOTES (p); *pnote;)
8311 if (REG_NOTE_KIND (*pnote) == REG_EQUAL
8312 && reg_mentioned_p (regno_reg_rtx[bl->regno],
8313 XEXP (*pnote, 0)))
8314 *pnote = XEXP (*pnote, 1);
8315 else
8316 pnote = &XEXP (*pnote, 1);
8320 /* Mark that this biv has been reversed. Each giv which depends
8321 on this biv, and which is also live past the end of the loop
8322 will have to be fixed up. */
8324 bl->reversed = 1;
8326 if (loop_dump_stream)
8328 fprintf (loop_dump_stream, "Reversed loop");
8329 if (bl->nonneg)
8330 fprintf (loop_dump_stream, " and added reg_nonneg\n");
8331 else
8332 fprintf (loop_dump_stream, "\n");
8335 return 1;
8340 return 0;
8343 /* Verify whether the biv BL appears to be eliminable,
8344 based on the insns in the loop that refer to it.
8346 If ELIMINATE_P is non-zero, actually do the elimination.
8348 THRESHOLD and INSN_COUNT are from loop_optimize and are used to
8349 determine whether invariant insns should be placed inside or at the
8350 start of the loop. */
8352 static int
8353 maybe_eliminate_biv (loop, bl, eliminate_p, threshold, insn_count)
8354 const struct loop *loop;
8355 struct iv_class *bl;
8356 int eliminate_p;
8357 int threshold, insn_count;
8359 rtx reg = bl->biv->dest_reg;
8360 rtx loop_start = loop->start;
8361 rtx loop_end = loop->end;
8362 rtx p;
8364 /* Scan all insns in the loop, stopping if we find one that uses the
8365 biv in a way that we cannot eliminate. */
8367 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8369 enum rtx_code code = GET_CODE (p);
8370 rtx where = threshold >= insn_count ? loop_start : p;
8372 /* If this is a libcall that sets a giv, skip ahead to its end. */
8373 if (GET_RTX_CLASS (code) == 'i')
8375 rtx note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
8377 if (note)
8379 rtx last = XEXP (note, 0);
8380 rtx set = single_set (last);
8382 if (set && GET_CODE (SET_DEST (set)) == REG)
8384 unsigned int regno = REGNO (SET_DEST (set));
8386 if (regno < max_reg_before_loop
8387 && REG_IV_TYPE (regno) == GENERAL_INDUCT
8388 && REG_IV_INFO (regno)->src_reg == bl->biv->src_reg)
8389 p = last;
8393 if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
8394 && reg_mentioned_p (reg, PATTERN (p))
8395 && ! maybe_eliminate_biv_1 (loop, PATTERN (p), p, bl,
8396 eliminate_p, where))
8398 if (loop_dump_stream)
8399 fprintf (loop_dump_stream,
8400 "Cannot eliminate biv %d: biv used in insn %d.\n",
8401 bl->regno, INSN_UID (p));
8402 break;
8406 if (p == loop_end)
8408 if (loop_dump_stream)
8409 fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
8410 bl->regno, eliminate_p ? "was" : "can be");
8411 return 1;
8414 return 0;
8417 /* INSN and REFERENCE are instructions in the same insn chain.
8418 Return non-zero if INSN is first. */
8421 loop_insn_first_p (insn, reference)
8422 rtx insn, reference;
8424 rtx p, q;
8426 for (p = insn, q = reference; ;)
8428 /* Start with test for not first so that INSN == REFERENCE yields not
8429 first. */
8430 if (q == insn || ! p)
8431 return 0;
8432 if (p == reference || ! q)
8433 return 1;
8435 /* Either of P or Q might be a NOTE. Notes have the same LUID as the
8436 previous insn, hence the <= comparison below does not work if
8437 P is a note. */
8438 if (INSN_UID (p) < max_uid_for_loop
8439 && INSN_UID (q) < max_uid_for_loop
8440 && GET_CODE (p) != NOTE)
8441 return INSN_LUID (p) <= INSN_LUID (q);
8443 if (INSN_UID (p) >= max_uid_for_loop
8444 || GET_CODE (p) == NOTE)
8445 p = NEXT_INSN (p);
8446 if (INSN_UID (q) >= max_uid_for_loop)
8447 q = NEXT_INSN (q);
8451 /* We are trying to eliminate BIV in INSN using GIV. Return non-zero if
8452 the offset that we have to take into account due to auto-increment /
8453 div derivation is zero. */
8454 static int
8455 biv_elimination_giv_has_0_offset (biv, giv, insn)
8456 struct induction *biv, *giv;
8457 rtx insn;
8459 /* If the giv V had the auto-inc address optimization applied
8460 to it, and INSN occurs between the giv insn and the biv
8461 insn, then we'd have to adjust the value used here.
8462 This is rare, so we don't bother to make this possible. */
8463 if (giv->auto_inc_opt
8464 && ((loop_insn_first_p (giv->insn, insn)
8465 && loop_insn_first_p (insn, biv->insn))
8466 || (loop_insn_first_p (biv->insn, insn)
8467 && loop_insn_first_p (insn, giv->insn))))
8468 return 0;
8470 /* If the giv V was derived from another giv, and INSN does
8471 not occur between the giv insn and the biv insn, then we'd
8472 have to adjust the value used here. This is rare, so we don't
8473 bother to make this possible. */
8474 if (giv->derived_from
8475 && ! (giv->always_executed
8476 && loop_insn_first_p (giv->insn, insn)
8477 && loop_insn_first_p (insn, biv->insn)))
8478 return 0;
8479 if (giv->same
8480 && giv->same->derived_from
8481 && ! (giv->same->always_executed
8482 && loop_insn_first_p (giv->same->insn, insn)
8483 && loop_insn_first_p (insn, biv->insn)))
8484 return 0;
8486 return 1;
8489 /* If BL appears in X (part of the pattern of INSN), see if we can
8490 eliminate its use. If so, return 1. If not, return 0.
8492 If BIV does not appear in X, return 1.
8494 If ELIMINATE_P is non-zero, actually do the elimination. WHERE indicates
8495 where extra insns should be added. Depending on how many items have been
8496 moved out of the loop, it will either be before INSN or at the start of
8497 the loop. */
8499 static int
8500 maybe_eliminate_biv_1 (loop, x, insn, bl, eliminate_p, where)
8501 const struct loop *loop;
8502 rtx x, insn;
8503 struct iv_class *bl;
8504 int eliminate_p;
8505 rtx where;
8507 enum rtx_code code = GET_CODE (x);
8508 rtx reg = bl->biv->dest_reg;
8509 enum machine_mode mode = GET_MODE (reg);
8510 struct induction *v;
8511 rtx arg, tem;
8512 #ifdef HAVE_cc0
8513 rtx new;
8514 #endif
8515 int arg_operand;
8516 const char *fmt;
8517 int i, j;
8519 switch (code)
8521 case REG:
8522 /* If we haven't already been able to do something with this BIV,
8523 we can't eliminate it. */
8524 if (x == reg)
8525 return 0;
8526 return 1;
8528 case SET:
8529 /* If this sets the BIV, it is not a problem. */
8530 if (SET_DEST (x) == reg)
8531 return 1;
8533 /* If this is an insn that defines a giv, it is also ok because
8534 it will go away when the giv is reduced. */
8535 for (v = bl->giv; v; v = v->next_iv)
8536 if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
8537 return 1;
8539 #ifdef HAVE_cc0
8540 if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
8542 /* Can replace with any giv that was reduced and
8543 that has (MULT_VAL != 0) and (ADD_VAL == 0).
8544 Require a constant for MULT_VAL, so we know it's nonzero.
8545 ??? We disable this optimization to avoid potential
8546 overflows. */
8548 for (v = bl->giv; v; v = v->next_iv)
8549 if (GET_CODE (v->mult_val) == CONST_INT && v->mult_val != const0_rtx
8550 && v->add_val == const0_rtx
8551 && ! v->ignore && ! v->maybe_dead && v->always_computable
8552 && v->mode == mode
8553 && 0)
8555 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8556 continue;
8558 if (! eliminate_p)
8559 return 1;
8561 /* If the giv has the opposite direction of change,
8562 then reverse the comparison. */
8563 if (INTVAL (v->mult_val) < 0)
8564 new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
8565 const0_rtx, v->new_reg);
8566 else
8567 new = v->new_reg;
8569 /* We can probably test that giv's reduced reg. */
8570 if (validate_change (insn, &SET_SRC (x), new, 0))
8571 return 1;
8574 /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
8575 replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
8576 Require a constant for MULT_VAL, so we know it's nonzero.
8577 ??? Do this only if ADD_VAL is a pointer to avoid a potential
8578 overflow problem. */
8580 for (v = bl->giv; v; v = v->next_iv)
8581 if (GET_CODE (v->mult_val) == CONST_INT && v->mult_val != const0_rtx
8582 && ! v->ignore && ! v->maybe_dead && v->always_computable
8583 && v->mode == mode
8584 && (GET_CODE (v->add_val) == SYMBOL_REF
8585 || GET_CODE (v->add_val) == LABEL_REF
8586 || GET_CODE (v->add_val) == CONST
8587 || (GET_CODE (v->add_val) == REG
8588 && REGNO_POINTER_FLAG (REGNO (v->add_val)))))
8590 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8591 continue;
8593 if (! eliminate_p)
8594 return 1;
8596 /* If the giv has the opposite direction of change,
8597 then reverse the comparison. */
8598 if (INTVAL (v->mult_val) < 0)
8599 new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
8600 v->new_reg);
8601 else
8602 new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
8603 copy_rtx (v->add_val));
8605 /* Replace biv with the giv's reduced register. */
8606 update_reg_last_use (v->add_val, insn);
8607 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8608 return 1;
8610 /* Insn doesn't support that constant or invariant. Copy it
8611 into a register (it will be a loop invariant.) */
8612 tem = gen_reg_rtx (GET_MODE (v->new_reg));
8614 emit_insn_before (gen_move_insn (tem, copy_rtx (v->add_val)),
8615 where);
8617 /* Substitute the new register for its invariant value in
8618 the compare expression. */
8619 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
8620 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8621 return 1;
8624 #endif
8625 break;
8627 case COMPARE:
8628 case EQ: case NE:
8629 case GT: case GE: case GTU: case GEU:
8630 case LT: case LE: case LTU: case LEU:
8631 /* See if either argument is the biv. */
8632 if (XEXP (x, 0) == reg)
8633 arg = XEXP (x, 1), arg_operand = 1;
8634 else if (XEXP (x, 1) == reg)
8635 arg = XEXP (x, 0), arg_operand = 0;
8636 else
8637 break;
8639 if (CONSTANT_P (arg))
8641 /* First try to replace with any giv that has constant positive
8642 mult_val and constant add_val. We might be able to support
8643 negative mult_val, but it seems complex to do it in general. */
8645 for (v = bl->giv; v; v = v->next_iv)
8646 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
8647 && (GET_CODE (v->add_val) == SYMBOL_REF
8648 || GET_CODE (v->add_val) == LABEL_REF
8649 || GET_CODE (v->add_val) == CONST
8650 || (GET_CODE (v->add_val) == REG
8651 && REGNO_POINTER_FLAG (REGNO (v->add_val))))
8652 && ! v->ignore && ! v->maybe_dead && v->always_computable
8653 && v->mode == mode)
8655 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8656 continue;
8658 if (! eliminate_p)
8659 return 1;
8661 /* Replace biv with the giv's reduced reg. */
8662 validate_change (insn, &XEXP (x, 1-arg_operand), v->new_reg, 1);
8664 /* If all constants are actually constant integers and
8665 the derived constant can be directly placed in the COMPARE,
8666 do so. */
8667 if (GET_CODE (arg) == CONST_INT
8668 && GET_CODE (v->mult_val) == CONST_INT
8669 && GET_CODE (v->add_val) == CONST_INT)
8671 validate_change (insn, &XEXP (x, arg_operand),
8672 GEN_INT (INTVAL (arg)
8673 * INTVAL (v->mult_val)
8674 + INTVAL (v->add_val)), 1);
8676 else
8678 /* Otherwise, load it into a register. */
8679 tem = gen_reg_rtx (mode);
8680 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
8681 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8683 if (apply_change_group ())
8684 return 1;
8687 /* Look for giv with positive constant mult_val and nonconst add_val.
8688 Insert insns to calculate new compare value.
8689 ??? Turn this off due to possible overflow. */
8691 for (v = bl->giv; v; v = v->next_iv)
8692 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
8693 && ! v->ignore && ! v->maybe_dead && v->always_computable
8694 && v->mode == mode
8695 && 0)
8697 rtx tem;
8699 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8700 continue;
8702 if (! eliminate_p)
8703 return 1;
8705 tem = gen_reg_rtx (mode);
8707 /* Replace biv with giv's reduced register. */
8708 validate_change (insn, &XEXP (x, 1 - arg_operand),
8709 v->new_reg, 1);
8711 /* Compute value to compare against. */
8712 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
8713 /* Use it in this insn. */
8714 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8715 if (apply_change_group ())
8716 return 1;
8719 else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
8721 if (loop_invariant_p (loop, arg) == 1)
8723 /* Look for giv with constant positive mult_val and nonconst
8724 add_val. Insert insns to compute new compare value.
8725 ??? Turn this off due to possible overflow. */
8727 for (v = bl->giv; v; v = v->next_iv)
8728 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
8729 && ! v->ignore && ! v->maybe_dead && v->always_computable
8730 && v->mode == mode
8731 && 0)
8733 rtx tem;
8735 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8736 continue;
8738 if (! eliminate_p)
8739 return 1;
8741 tem = gen_reg_rtx (mode);
8743 /* Replace biv with giv's reduced register. */
8744 validate_change (insn, &XEXP (x, 1 - arg_operand),
8745 v->new_reg, 1);
8747 /* Compute value to compare against. */
8748 emit_iv_add_mult (arg, v->mult_val, v->add_val,
8749 tem, where);
8750 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8751 if (apply_change_group ())
8752 return 1;
8756 /* This code has problems. Basically, you can't know when
8757 seeing if we will eliminate BL, whether a particular giv
8758 of ARG will be reduced. If it isn't going to be reduced,
8759 we can't eliminate BL. We can try forcing it to be reduced,
8760 but that can generate poor code.
8762 The problem is that the benefit of reducing TV, below should
8763 be increased if BL can actually be eliminated, but this means
8764 we might have to do a topological sort of the order in which
8765 we try to process biv. It doesn't seem worthwhile to do
8766 this sort of thing now. */
8768 #if 0
8769 /* Otherwise the reg compared with had better be a biv. */
8770 if (GET_CODE (arg) != REG
8771 || REG_IV_TYPE (REGNO (arg)) != BASIC_INDUCT)
8772 return 0;
8774 /* Look for a pair of givs, one for each biv,
8775 with identical coefficients. */
8776 for (v = bl->giv; v; v = v->next_iv)
8778 struct induction *tv;
8780 if (v->ignore || v->maybe_dead || v->mode != mode)
8781 continue;
8783 for (tv = reg_biv_class[REGNO (arg)]->giv; tv; tv = tv->next_iv)
8784 if (! tv->ignore && ! tv->maybe_dead
8785 && rtx_equal_p (tv->mult_val, v->mult_val)
8786 && rtx_equal_p (tv->add_val, v->add_val)
8787 && tv->mode == mode)
8789 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8790 continue;
8792 if (! eliminate_p)
8793 return 1;
8795 /* Replace biv with its giv's reduced reg. */
8796 XEXP (x, 1-arg_operand) = v->new_reg;
8797 /* Replace other operand with the other giv's
8798 reduced reg. */
8799 XEXP (x, arg_operand) = tv->new_reg;
8800 return 1;
8803 #endif
8806 /* If we get here, the biv can't be eliminated. */
8807 return 0;
8809 case MEM:
8810 /* If this address is a DEST_ADDR giv, it doesn't matter if the
8811 biv is used in it, since it will be replaced. */
8812 for (v = bl->giv; v; v = v->next_iv)
8813 if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
8814 return 1;
8815 break;
8817 default:
8818 break;
8821 /* See if any subexpression fails elimination. */
8822 fmt = GET_RTX_FORMAT (code);
8823 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
8825 switch (fmt[i])
8827 case 'e':
8828 if (! maybe_eliminate_biv_1 (loop, XEXP (x, i), insn, bl,
8829 eliminate_p, where))
8830 return 0;
8831 break;
8833 case 'E':
8834 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8835 if (! maybe_eliminate_biv_1 (loop, XVECEXP (x, i, j), insn, bl,
8836 eliminate_p, where))
8837 return 0;
8838 break;
8842 return 1;
8845 /* Return nonzero if the last use of REG
8846 is in an insn following INSN in the same basic block. */
8848 static int
8849 last_use_this_basic_block (reg, insn)
8850 rtx reg;
8851 rtx insn;
8853 rtx n;
8854 for (n = insn;
8855 n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
8856 n = NEXT_INSN (n))
8858 if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
8859 return 1;
8861 return 0;
8864 /* Called via `note_stores' to record the initial value of a biv. Here we
8865 just record the location of the set and process it later. */
8867 static void
8868 record_initial (dest, set, data)
8869 rtx dest;
8870 rtx set;
8871 void *data ATTRIBUTE_UNUSED;
8873 struct iv_class *bl;
8875 if (GET_CODE (dest) != REG
8876 || REGNO (dest) >= max_reg_before_loop
8877 || REG_IV_TYPE (REGNO (dest)) != BASIC_INDUCT)
8878 return;
8880 bl = reg_biv_class[REGNO (dest)];
8882 /* If this is the first set found, record it. */
8883 if (bl->init_insn == 0)
8885 bl->init_insn = note_insn;
8886 bl->init_set = set;
8890 /* If any of the registers in X are "old" and currently have a last use earlier
8891 than INSN, update them to have a last use of INSN. Their actual last use
8892 will be the previous insn but it will not have a valid uid_luid so we can't
8893 use it. */
8895 static void
8896 update_reg_last_use (x, insn)
8897 rtx x;
8898 rtx insn;
8900 /* Check for the case where INSN does not have a valid luid. In this case,
8901 there is no need to modify the regno_last_uid, as this can only happen
8902 when code is inserted after the loop_end to set a pseudo's final value,
8903 and hence this insn will never be the last use of x. */
8904 if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
8905 && INSN_UID (insn) < max_uid_for_loop
8906 && uid_luid[REGNO_LAST_UID (REGNO (x))] < uid_luid[INSN_UID (insn)])
8907 REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
8908 else
8910 register int i, j;
8911 register const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
8912 for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8914 if (fmt[i] == 'e')
8915 update_reg_last_use (XEXP (x, i), insn);
8916 else if (fmt[i] == 'E')
8917 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8918 update_reg_last_use (XVECEXP (x, i, j), insn);
8923 /* Given an insn INSN and condition COND, return the condition in a
8924 canonical form to simplify testing by callers. Specifically:
8926 (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
8927 (2) Both operands will be machine operands; (cc0) will have been replaced.
8928 (3) If an operand is a constant, it will be the second operand.
8929 (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
8930 for GE, GEU, and LEU.
8932 If the condition cannot be understood, or is an inequality floating-point
8933 comparison which needs to be reversed, 0 will be returned.
8935 If REVERSE is non-zero, then reverse the condition prior to canonizing it.
8937 If EARLIEST is non-zero, it is a pointer to a place where the earliest
8938 insn used in locating the condition was found. If a replacement test
8939 of the condition is desired, it should be placed in front of that
8940 insn and we will be sure that the inputs are still valid.
8942 If WANT_REG is non-zero, we wish the condition to be relative to that
8943 register, if possible. Therefore, do not canonicalize the condition
8944 further. */
8947 canonicalize_condition (insn, cond, reverse, earliest, want_reg)
8948 rtx insn;
8949 rtx cond;
8950 int reverse;
8951 rtx *earliest;
8952 rtx want_reg;
8954 enum rtx_code code;
8955 rtx prev = insn;
8956 rtx set;
8957 rtx tem;
8958 rtx op0, op1;
8959 int reverse_code = 0;
8960 int did_reverse_condition = 0;
8961 enum machine_mode mode;
8963 code = GET_CODE (cond);
8964 mode = GET_MODE (cond);
8965 op0 = XEXP (cond, 0);
8966 op1 = XEXP (cond, 1);
8968 if (reverse)
8970 code = reverse_condition (code);
8971 did_reverse_condition ^= 1;
8974 if (earliest)
8975 *earliest = insn;
8977 /* If we are comparing a register with zero, see if the register is set
8978 in the previous insn to a COMPARE or a comparison operation. Perform
8979 the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
8980 in cse.c */
8982 while (GET_RTX_CLASS (code) == '<'
8983 && op1 == CONST0_RTX (GET_MODE (op0))
8984 && op0 != want_reg)
8986 /* Set non-zero when we find something of interest. */
8987 rtx x = 0;
8989 #ifdef HAVE_cc0
8990 /* If comparison with cc0, import actual comparison from compare
8991 insn. */
8992 if (op0 == cc0_rtx)
8994 if ((prev = prev_nonnote_insn (prev)) == 0
8995 || GET_CODE (prev) != INSN
8996 || (set = single_set (prev)) == 0
8997 || SET_DEST (set) != cc0_rtx)
8998 return 0;
9000 op0 = SET_SRC (set);
9001 op1 = CONST0_RTX (GET_MODE (op0));
9002 if (earliest)
9003 *earliest = prev;
9005 #endif
9007 /* If this is a COMPARE, pick up the two things being compared. */
9008 if (GET_CODE (op0) == COMPARE)
9010 op1 = XEXP (op0, 1);
9011 op0 = XEXP (op0, 0);
9012 continue;
9014 else if (GET_CODE (op0) != REG)
9015 break;
9017 /* Go back to the previous insn. Stop if it is not an INSN. We also
9018 stop if it isn't a single set or if it has a REG_INC note because
9019 we don't want to bother dealing with it. */
9021 if ((prev = prev_nonnote_insn (prev)) == 0
9022 || GET_CODE (prev) != INSN
9023 || FIND_REG_INC_NOTE (prev, 0)
9024 || (set = single_set (prev)) == 0)
9025 break;
9027 /* If this is setting OP0, get what it sets it to if it looks
9028 relevant. */
9029 if (rtx_equal_p (SET_DEST (set), op0))
9031 enum machine_mode inner_mode = GET_MODE (SET_SRC (set));
9033 /* ??? We may not combine comparisons done in a CCmode with
9034 comparisons not done in a CCmode. This is to aid targets
9035 like Alpha that have an IEEE compliant EQ instruction, and
9036 a non-IEEE compliant BEQ instruction. The use of CCmode is
9037 actually artificial, simply to prevent the combination, but
9038 should not affect other platforms.
9040 However, we must allow VOIDmode comparisons to match either
9041 CCmode or non-CCmode comparison, because some ports have
9042 modeless comparisons inside branch patterns.
9044 ??? This mode check should perhaps look more like the mode check
9045 in simplify_comparison in combine. */
9047 if ((GET_CODE (SET_SRC (set)) == COMPARE
9048 || (((code == NE
9049 || (code == LT
9050 && GET_MODE_CLASS (inner_mode) == MODE_INT
9051 && (GET_MODE_BITSIZE (inner_mode)
9052 <= HOST_BITS_PER_WIDE_INT)
9053 && (STORE_FLAG_VALUE
9054 & ((HOST_WIDE_INT) 1
9055 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9056 #ifdef FLOAT_STORE_FLAG_VALUE
9057 || (code == LT
9058 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9059 && (REAL_VALUE_NEGATIVE
9060 (FLOAT_STORE_FLAG_VALUE (inner_mode))))
9061 #endif
9063 && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'))
9064 && (((GET_MODE_CLASS (mode) == MODE_CC)
9065 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9066 || mode == VOIDmode || inner_mode == VOIDmode))
9067 x = SET_SRC (set);
9068 else if (((code == EQ
9069 || (code == GE
9070 && (GET_MODE_BITSIZE (inner_mode)
9071 <= HOST_BITS_PER_WIDE_INT)
9072 && GET_MODE_CLASS (inner_mode) == MODE_INT
9073 && (STORE_FLAG_VALUE
9074 & ((HOST_WIDE_INT) 1
9075 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9076 #ifdef FLOAT_STORE_FLAG_VALUE
9077 || (code == GE
9078 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9079 && (REAL_VALUE_NEGATIVE
9080 (FLOAT_STORE_FLAG_VALUE (inner_mode))))
9081 #endif
9083 && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'
9084 && (((GET_MODE_CLASS (mode) == MODE_CC)
9085 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9086 || mode == VOIDmode || inner_mode == VOIDmode))
9089 /* We might have reversed a LT to get a GE here. But this wasn't
9090 actually the comparison of data, so we don't flag that we
9091 have had to reverse the condition. */
9092 did_reverse_condition ^= 1;
9093 reverse_code = 1;
9094 x = SET_SRC (set);
9096 else
9097 break;
9100 else if (reg_set_p (op0, prev))
9101 /* If this sets OP0, but not directly, we have to give up. */
9102 break;
9104 if (x)
9106 if (GET_RTX_CLASS (GET_CODE (x)) == '<')
9107 code = GET_CODE (x);
9108 if (reverse_code)
9110 code = reverse_condition (code);
9111 if (code == UNKNOWN)
9112 return 0;
9113 did_reverse_condition ^= 1;
9114 reverse_code = 0;
9117 op0 = XEXP (x, 0), op1 = XEXP (x, 1);
9118 if (earliest)
9119 *earliest = prev;
9123 /* If constant is first, put it last. */
9124 if (CONSTANT_P (op0))
9125 code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
9127 /* If OP0 is the result of a comparison, we weren't able to find what
9128 was really being compared, so fail. */
9129 if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
9130 return 0;
9132 /* Canonicalize any ordered comparison with integers involving equality
9133 if we can do computations in the relevant mode and we do not
9134 overflow. */
9136 if (GET_CODE (op1) == CONST_INT
9137 && GET_MODE (op0) != VOIDmode
9138 && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
9140 HOST_WIDE_INT const_val = INTVAL (op1);
9141 unsigned HOST_WIDE_INT uconst_val = const_val;
9142 unsigned HOST_WIDE_INT max_val
9143 = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
9145 switch (code)
9147 case LE:
9148 if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
9149 code = LT, op1 = GEN_INT (const_val + 1);
9150 break;
9152 /* When cross-compiling, const_val might be sign-extended from
9153 BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
9154 case GE:
9155 if ((HOST_WIDE_INT) (const_val & max_val)
9156 != (((HOST_WIDE_INT) 1
9157 << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
9158 code = GT, op1 = GEN_INT (const_val - 1);
9159 break;
9161 case LEU:
9162 if (uconst_val < max_val)
9163 code = LTU, op1 = GEN_INT (uconst_val + 1);
9164 break;
9166 case GEU:
9167 if (uconst_val != 0)
9168 code = GTU, op1 = GEN_INT (uconst_val - 1);
9169 break;
9171 default:
9172 break;
9176 /* If this was floating-point and we reversed anything other than an
9177 EQ or NE or (UN)ORDERED, return zero. */
9178 if (TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
9179 && did_reverse_condition
9180 && code != NE && code != EQ && code != UNORDERED && code != ORDERED
9181 && ! flag_fast_math
9182 && GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
9183 return 0;
9185 #ifdef HAVE_cc0
9186 /* Never return CC0; return zero instead. */
9187 if (op0 == cc0_rtx)
9188 return 0;
9189 #endif
9191 return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
9194 /* Given a jump insn JUMP, return the condition that will cause it to branch
9195 to its JUMP_LABEL. If the condition cannot be understood, or is an
9196 inequality floating-point comparison which needs to be reversed, 0 will
9197 be returned.
9199 If EARLIEST is non-zero, it is a pointer to a place where the earliest
9200 insn used in locating the condition was found. If a replacement test
9201 of the condition is desired, it should be placed in front of that
9202 insn and we will be sure that the inputs are still valid. */
9205 get_condition (jump, earliest)
9206 rtx jump;
9207 rtx *earliest;
9209 rtx cond;
9210 int reverse;
9212 /* If this is not a standard conditional jump, we can't parse it. */
9213 if (GET_CODE (jump) != JUMP_INSN
9214 || ! condjump_p (jump) || simplejump_p (jump))
9215 return 0;
9217 cond = XEXP (SET_SRC (PATTERN (jump)), 0);
9219 /* If this branches to JUMP_LABEL when the condition is false, reverse
9220 the condition. */
9221 reverse
9222 = GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 2)) == LABEL_REF
9223 && XEXP (XEXP (SET_SRC (PATTERN (jump)), 2), 0) == JUMP_LABEL (jump);
9225 return canonicalize_condition (jump, cond, reverse, earliest, NULL_RTX);
9228 /* Similar to above routine, except that we also put an invariant last
9229 unless both operands are invariants. */
9232 get_condition_for_loop (loop, x)
9233 const struct loop *loop;
9234 rtx x;
9236 rtx comparison = get_condition (x, NULL_PTR);
9238 if (comparison == 0
9239 || ! loop_invariant_p (loop, XEXP (comparison, 0))
9240 || loop_invariant_p (loop, XEXP (comparison, 1)))
9241 return comparison;
9243 return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
9244 XEXP (comparison, 1), XEXP (comparison, 0));
9247 #ifdef HAVE_decrement_and_branch_on_count
9248 /* Instrument loop for insertion of bct instruction. We distinguish between
9249 loops with compile-time bounds and those with run-time bounds.
9250 Information from loop_iterations() is used to compute compile-time bounds.
9251 Run-time bounds should use loop preconditioning, but currently ignored.
9254 static void
9255 insert_bct (loop)
9256 struct loop *loop;
9258 unsigned HOST_WIDE_INT n_iterations;
9259 rtx loop_start = loop->start;
9260 rtx loop_end = loop->end;
9261 struct loop_info *loop_info = LOOP_INFO (loop);
9262 int loop_num = loop->num;
9264 #if 0
9265 int increment_direction, compare_direction;
9266 /* If the loop condition is <= or >=, the number of iteration
9267 is 1 more than the range of the bounds of the loop. */
9268 int add_iteration = 0;
9269 enum machine_mode loop_var_mode = word_mode;
9270 #endif
9272 /* It's impossible to instrument a competely unrolled loop. */
9273 if (loop_info->unroll_number == loop_info->n_iterations)
9274 return;
9276 /* Make sure that the count register is not in use. */
9277 if (loop_info->used_count_register)
9279 if (loop_dump_stream)
9280 fprintf (loop_dump_stream,
9281 "insert_bct %d: BCT instrumentation failed: count register already in use\n",
9282 loop_num);
9283 return;
9286 /* Make sure that the function has no indirect jumps. */
9287 if (indirect_jump_in_function)
9289 if (loop_dump_stream)
9290 fprintf (loop_dump_stream,
9291 "insert_bct %d: BCT instrumentation failed: indirect jump in function\n",
9292 loop_num);
9293 return;
9296 /* Make sure that the last loop insn is a conditional jump. */
9297 if (GET_CODE (PREV_INSN (loop_end)) != JUMP_INSN
9298 || ! condjump_p (PREV_INSN (loop_end))
9299 || simplejump_p (PREV_INSN (loop_end)))
9301 if (loop_dump_stream)
9302 fprintf (loop_dump_stream,
9303 "insert_bct %d: BCT instrumentation failed: invalid jump at loop end\n",
9304 loop_num);
9305 return;
9308 /* Make sure that the loop does not contain a function call
9309 (the count register might be altered by the called function). */
9310 if (loop_info->has_call)
9312 if (loop_dump_stream)
9313 fprintf (loop_dump_stream,
9314 "insert_bct %d: BCT instrumentation failed: function call in loop\n",
9315 loop_num);
9316 return;
9319 /* Make sure that the loop does not jump via a table.
9320 (the count register might be used to perform the branch on table). */
9321 if (loop_info->has_tablejump)
9323 if (loop_dump_stream)
9324 fprintf (loop_dump_stream,
9325 "insert_bct %d: BCT instrumentation failed: computed branch in the loop\n",
9326 loop_num);
9327 return;
9330 /* Account for loop unrolling in instrumented iteration count. */
9331 if (loop_info->unroll_number > 1)
9332 n_iterations = loop_info->n_iterations / loop_info->unroll_number;
9333 else
9334 n_iterations = loop_info->n_iterations;
9336 if (n_iterations != 0 && n_iterations < 3)
9338 /* Allow an enclosing outer loop to benefit if possible. */
9339 if (loop_dump_stream)
9340 fprintf (loop_dump_stream,
9341 "insert_bct %d: Too few iterations to benefit from BCT optimization\n",
9342 loop_num);
9343 return;
9346 /* Try to instrument the loop. */
9348 /* Handle the simpler case, where the bounds are known at compile time. */
9349 if (n_iterations > 0)
9351 struct loop *outer_loop;
9352 struct loop_info *outer_loop_info;
9354 /* Mark all enclosing loops that they cannot use count register. */
9355 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
9357 outer_loop_info = LOOP_INFO (outer_loop);
9358 outer_loop_info->used_count_register = 1;
9360 instrument_loop_bct (loop_start, loop_end, GEN_INT (n_iterations));
9361 return;
9364 /* Handle the more complex case, that the bounds are NOT known
9365 at compile time. In this case we generate run_time calculation
9366 of the number of iterations. */
9368 if (loop_info->iteration_var == 0)
9370 if (loop_dump_stream)
9371 fprintf (loop_dump_stream,
9372 "insert_bct %d: BCT Runtime Instrumentation failed: no loop iteration variable found\n",
9373 loop_num);
9374 return;
9377 if (GET_MODE_CLASS (GET_MODE (loop_info->iteration_var)) != MODE_INT
9378 || GET_MODE_SIZE (GET_MODE (loop_info->iteration_var)) != UNITS_PER_WORD)
9380 if (loop_dump_stream)
9381 fprintf (loop_dump_stream,
9382 "insert_bct %d: BCT Runtime Instrumentation failed: loop variable not integer\n",
9383 loop_num);
9384 return;
9387 /* With runtime bounds, if the compare is of the form '!=' we give up */
9388 if (loop_info->comparison_code == NE)
9390 if (loop_dump_stream)
9391 fprintf (loop_dump_stream,
9392 "insert_bct %d: BCT Runtime Instrumentation failed: runtime bounds with != comparison\n",
9393 loop_num);
9394 return;
9396 /* Use common loop preconditioning code instead. */
9397 #if 0
9398 else
9400 /* We rely on the existence of run-time guard to ensure that the
9401 loop executes at least once. */
9402 rtx sequence;
9403 rtx iterations_num_reg;
9405 unsigned HOST_WIDE_INT increment_value_abs
9406 = INTVAL (increment) * increment_direction;
9408 /* make sure that the increment is a power of two, otherwise (an
9409 expensive) divide is needed. */
9410 if (exact_log2 (increment_value_abs) == -1)
9412 if (loop_dump_stream)
9413 fprintf (loop_dump_stream,
9414 "insert_bct: not instrumenting BCT because the increment is not power of 2\n");
9415 return;
9418 /* compute the number of iterations */
9419 start_sequence ();
9421 rtx temp_reg;
9423 /* Again, the number of iterations is calculated by:
9425 ; compare-val - initial-val + (increment -1) + additional-iteration
9426 ; num_iterations = -----------------------------------------------------------------
9427 ; increment
9429 /* ??? Do we have to call copy_rtx here before passing rtx to
9430 expand_binop? */
9431 if (compare_direction > 0)
9433 /* <, <= :the loop variable is increasing */
9434 temp_reg = expand_binop (loop_var_mode, sub_optab,
9435 comparison_value, initial_value,
9436 NULL_RTX, 0, OPTAB_LIB_WIDEN);
9438 else
9440 temp_reg = expand_binop (loop_var_mode, sub_optab,
9441 initial_value, comparison_value,
9442 NULL_RTX, 0, OPTAB_LIB_WIDEN);
9445 if (increment_value_abs - 1 + add_iteration != 0)
9446 temp_reg = expand_binop (loop_var_mode, add_optab, temp_reg,
9447 GEN_INT (increment_value_abs - 1
9448 + add_iteration),
9449 NULL_RTX, 0, OPTAB_LIB_WIDEN);
9451 if (increment_value_abs != 1)
9452 iterations_num_reg = expand_binop (loop_var_mode, asr_optab,
9453 temp_reg,
9454 GEN_INT (exact_log2 (increment_value_abs)),
9455 NULL_RTX, 0, OPTAB_LIB_WIDEN);
9456 else
9457 iterations_num_reg = temp_reg;
9459 sequence = gen_sequence ();
9460 end_sequence ();
9461 emit_insn_before (sequence, loop_start);
9462 instrument_loop_bct (loop_start, loop_end, iterations_num_reg);
9465 return;
9466 #endif /* Complex case */
9469 /* Instrument loop by inserting a bct in it as follows:
9470 1. A new counter register is created.
9471 2. In the head of the loop the new variable is initialized to the value
9472 passed in the loop_num_iterations parameter.
9473 3. At the end of the loop, comparison of the register with 0 is generated.
9474 The created comparison follows the pattern defined for the
9475 decrement_and_branch_on_count insn, so this insn will be generated.
9476 4. The branch on the old variable are deleted. The compare must remain
9477 because it might be used elsewhere. If the loop-variable or condition
9478 register are used elsewhere, they will be eliminated by flow. */
9480 static void
9481 instrument_loop_bct (loop_start, loop_end, loop_num_iterations)
9482 rtx loop_start, loop_end;
9483 rtx loop_num_iterations;
9485 rtx counter_reg;
9486 rtx start_label;
9487 rtx sequence;
9489 if (HAVE_decrement_and_branch_on_count)
9491 if (loop_dump_stream)
9493 fputs ("instrument_bct: Inserting BCT (", loop_dump_stream);
9494 if (GET_CODE (loop_num_iterations) == CONST_INT)
9495 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC,
9496 INTVAL (loop_num_iterations));
9497 else
9498 fputs ("runtime", loop_dump_stream);
9499 fputs (" iterations)", loop_dump_stream);
9502 /* Discard original jump to continue loop. Original compare result
9503 may still be live, so it cannot be discarded explicitly. */
9504 delete_insn (PREV_INSN (loop_end));
9506 /* Insert the label which will delimit the start of the loop. */
9507 start_label = gen_label_rtx ();
9508 emit_label_after (start_label, loop_start);
9510 /* Insert initialization of the count register into the loop header. */
9511 start_sequence ();
9512 counter_reg = gen_reg_rtx (word_mode);
9513 emit_insn (gen_move_insn (counter_reg, loop_num_iterations));
9514 sequence = gen_sequence ();
9515 end_sequence ();
9516 emit_insn_before (sequence, loop_start);
9518 /* Insert new comparison on the count register instead of the
9519 old one, generating the needed BCT pattern (that will be
9520 later recognized by assembly generation phase). */
9521 emit_jump_insn_before (gen_decrement_and_branch_on_count (counter_reg,
9522 start_label),
9523 loop_end);
9524 LABEL_NUSES (start_label)++;
9528 #endif /* HAVE_decrement_and_branch_on_count */
9530 /* Scan the function and determine whether it has indirect (computed) jumps.
9532 This is taken mostly from flow.c; similar code exists elsewhere
9533 in the compiler. It may be useful to put this into rtlanal.c. */
9534 static int
9535 indirect_jump_in_function_p (start)
9536 rtx start;
9538 rtx insn;
9540 for (insn = start; insn; insn = NEXT_INSN (insn))
9541 if (computed_jump_p (insn))
9542 return 1;
9544 return 0;
9547 /* Add MEM to the LOOP_MEMS array, if appropriate. See the
9548 documentation for LOOP_MEMS for the definition of `appropriate'.
9549 This function is called from prescan_loop via for_each_rtx. */
9551 static int
9552 insert_loop_mem (mem, data)
9553 rtx *mem;
9554 void *data ATTRIBUTE_UNUSED;
9556 int i;
9557 rtx m = *mem;
9559 if (m == NULL_RTX)
9560 return 0;
9562 switch (GET_CODE (m))
9564 case MEM:
9565 break;
9567 case CLOBBER:
9568 /* We're not interested in MEMs that are only clobbered. */
9569 return -1;
9571 case CONST_DOUBLE:
9572 /* We're not interested in the MEM associated with a
9573 CONST_DOUBLE, so there's no need to traverse into this. */
9574 return -1;
9576 case EXPR_LIST:
9577 /* We're not interested in any MEMs that only appear in notes. */
9578 return -1;
9580 default:
9581 /* This is not a MEM. */
9582 return 0;
9585 /* See if we've already seen this MEM. */
9586 for (i = 0; i < loop_mems_idx; ++i)
9587 if (rtx_equal_p (m, loop_mems[i].mem))
9589 if (GET_MODE (m) != GET_MODE (loop_mems[i].mem))
9590 /* The modes of the two memory accesses are different. If
9591 this happens, something tricky is going on, and we just
9592 don't optimize accesses to this MEM. */
9593 loop_mems[i].optimize = 0;
9595 return 0;
9598 /* Resize the array, if necessary. */
9599 if (loop_mems_idx == loop_mems_allocated)
9601 if (loop_mems_allocated != 0)
9602 loop_mems_allocated *= 2;
9603 else
9604 loop_mems_allocated = 32;
9606 loop_mems = (loop_mem_info*)
9607 xrealloc (loop_mems,
9608 loop_mems_allocated * sizeof (loop_mem_info));
9611 /* Actually insert the MEM. */
9612 loop_mems[loop_mems_idx].mem = m;
9613 /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
9614 because we can't put it in a register. We still store it in the
9615 table, though, so that if we see the same address later, but in a
9616 non-BLK mode, we'll not think we can optimize it at that point. */
9617 loop_mems[loop_mems_idx].optimize = (GET_MODE (m) != BLKmode);
9618 loop_mems[loop_mems_idx].reg = NULL_RTX;
9619 ++loop_mems_idx;
9621 return 0;
9624 /* Like load_mems, but also ensures that SET_IN_LOOP,
9625 MAY_NOT_OPTIMIZE, REG_SINGLE_USAGE, and INSN_COUNT have the correct
9626 values after load_mems. */
9628 static void
9629 load_mems_and_recount_loop_regs_set (loop, insn_count)
9630 const struct loop *loop;
9631 int *insn_count;
9633 int nregs = max_reg_num ();
9635 load_mems (loop);
9637 /* Recalculate set_in_loop and friends since load_mems may have
9638 created new registers. */
9639 if (max_reg_num () > nregs)
9641 int i;
9642 int old_nregs;
9644 old_nregs = nregs;
9645 nregs = max_reg_num ();
9647 if ((unsigned) nregs > set_in_loop->num_elements)
9649 /* Grow all the arrays. */
9650 VARRAY_GROW (set_in_loop, nregs);
9651 VARRAY_GROW (n_times_set, nregs);
9652 VARRAY_GROW (may_not_optimize, nregs);
9653 VARRAY_GROW (reg_single_usage, nregs);
9655 /* Clear the arrays */
9656 bzero ((char *) &set_in_loop->data, nregs * sizeof (int));
9657 bzero ((char *) &may_not_optimize->data, nregs * sizeof (char));
9658 bzero ((char *) &reg_single_usage->data, nregs * sizeof (rtx));
9660 count_loop_regs_set (loop->top ? loop->top : loop->start, loop->end,
9661 may_not_optimize, reg_single_usage,
9662 insn_count, nregs);
9664 for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
9666 VARRAY_CHAR (may_not_optimize, i) = 1;
9667 VARRAY_INT (set_in_loop, i) = 1;
9670 #ifdef AVOID_CCMODE_COPIES
9671 /* Don't try to move insns which set CC registers if we should not
9672 create CCmode register copies. */
9673 for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
9674 if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
9675 VARRAY_CHAR (may_not_optimize, i) = 1;
9676 #endif
9678 /* Set n_times_set for the new registers. */
9679 bcopy ((char *) (&set_in_loop->data.i[0] + old_nregs),
9680 (char *) (&n_times_set->data.i[0] + old_nregs),
9681 (nregs - old_nregs) * sizeof (int));
9685 /* Move MEMs into registers for the duration of the loop. */
9687 static void
9688 load_mems (loop)
9689 const struct loop *loop;
9691 int maybe_never = 0;
9692 int i;
9693 rtx p;
9694 rtx label = NULL_RTX;
9695 rtx end_label = NULL_RTX;
9696 /* Nonzero if the next instruction may never be executed. */
9697 int next_maybe_never = 0;
9698 int last_max_reg = max_reg_num ();
9700 if (loop_mems_idx == 0)
9701 return;
9703 /* Find start of the extended basic block that enters the loop. */
9704 for (p = loop->start;
9705 PREV_INSN (p) && GET_CODE (p) != CODE_LABEL;
9706 p = PREV_INSN (p))
9709 cselib_init ();
9711 /* Build table of mems that get set to constant values before the
9712 loop. */
9713 for (; p != loop->start; p = NEXT_INSN (p))
9714 cselib_process_insn (p);
9716 /* Check to see if it's possible that some instructions in the
9717 loop are never executed. */
9718 for (p = next_insn_in_loop (loop, loop->scan_start);
9719 p != NULL_RTX && ! maybe_never;
9720 p = next_insn_in_loop (loop, p))
9722 if (GET_CODE (p) == CODE_LABEL)
9723 maybe_never = 1;
9724 else if (GET_CODE (p) == JUMP_INSN
9725 /* If we enter the loop in the middle, and scan
9726 around to the beginning, don't set maybe_never
9727 for that. This must be an unconditional jump,
9728 otherwise the code at the top of the loop might
9729 never be executed. Unconditional jumps are
9730 followed a by barrier then loop end. */
9731 && ! (GET_CODE (p) == JUMP_INSN
9732 && JUMP_LABEL (p) == loop->top
9733 && NEXT_INSN (NEXT_INSN (p)) == loop->end
9734 && simplejump_p (p)))
9736 if (!condjump_p (p))
9737 /* Something complicated. */
9738 maybe_never = 1;
9739 else
9740 /* If there are any more instructions in the loop, they
9741 might not be reached. */
9742 next_maybe_never = 1;
9744 else if (next_maybe_never)
9745 maybe_never = 1;
9748 /* Actually move the MEMs. */
9749 for (i = 0; i < loop_mems_idx; ++i)
9751 regset_head copies;
9752 int written = 0;
9753 rtx reg;
9754 rtx mem = loop_mems[i].mem;
9755 rtx mem_list_entry;
9757 if (MEM_VOLATILE_P (mem)
9758 || loop_invariant_p (loop, XEXP (mem, 0)) != 1)
9759 /* There's no telling whether or not MEM is modified. */
9760 loop_mems[i].optimize = 0;
9762 /* Go through the MEMs written to in the loop to see if this
9763 one is aliased by one of them. */
9764 mem_list_entry = loop_store_mems;
9765 while (mem_list_entry)
9767 if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
9768 written = 1;
9769 else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
9770 mem, rtx_varies_p))
9772 /* MEM is indeed aliased by this store. */
9773 loop_mems[i].optimize = 0;
9774 break;
9776 mem_list_entry = XEXP (mem_list_entry, 1);
9779 if (flag_float_store && written
9780 && GET_MODE_CLASS (GET_MODE (mem)) == MODE_FLOAT)
9781 loop_mems[i].optimize = 0;
9783 /* If this MEM is written to, we must be sure that there
9784 are no reads from another MEM that aliases this one. */
9785 if (loop_mems[i].optimize && written)
9787 int j;
9789 for (j = 0; j < loop_mems_idx; ++j)
9791 if (j == i)
9792 continue;
9793 else if (true_dependence (mem,
9794 VOIDmode,
9795 loop_mems[j].mem,
9796 rtx_varies_p))
9798 /* It's not safe to hoist loop_mems[i] out of
9799 the loop because writes to it might not be
9800 seen by reads from loop_mems[j]. */
9801 loop_mems[i].optimize = 0;
9802 break;
9807 if (maybe_never && may_trap_p (mem))
9808 /* We can't access the MEM outside the loop; it might
9809 cause a trap that wouldn't have happened otherwise. */
9810 loop_mems[i].optimize = 0;
9812 if (!loop_mems[i].optimize)
9813 /* We thought we were going to lift this MEM out of the
9814 loop, but later discovered that we could not. */
9815 continue;
9817 INIT_REG_SET (&copies);
9819 /* Allocate a pseudo for this MEM. We set REG_USERVAR_P in
9820 order to keep scan_loop from moving stores to this MEM
9821 out of the loop just because this REG is neither a
9822 user-variable nor used in the loop test. */
9823 reg = gen_reg_rtx (GET_MODE (mem));
9824 REG_USERVAR_P (reg) = 1;
9825 loop_mems[i].reg = reg;
9827 /* Now, replace all references to the MEM with the
9828 corresponding pesudos. */
9829 maybe_never = 0;
9830 for (p = next_insn_in_loop (loop, loop->scan_start);
9831 p != NULL_RTX;
9832 p = next_insn_in_loop (loop, p))
9834 rtx_and_int ri;
9835 rtx set;
9837 if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
9839 /* See if this copies the mem into a register that isn't
9840 modified afterwards. We'll try to do copy propagation
9841 a little further on. */
9842 set = single_set (p);
9843 if (set
9844 /* @@@ This test is _way_ too conservative. */
9845 && ! maybe_never
9846 && GET_CODE (SET_DEST (set)) == REG
9847 && REGNO (SET_DEST (set)) >= FIRST_PSEUDO_REGISTER
9848 && REGNO (SET_DEST (set)) < last_max_reg
9849 && VARRAY_INT (n_times_set, REGNO (SET_DEST (set))) == 1
9850 && rtx_equal_p (SET_SRC (set), loop_mems[i].mem))
9851 SET_REGNO_REG_SET (&copies, REGNO (SET_DEST (set)));
9852 ri.r = p;
9853 ri.i = i;
9854 for_each_rtx (&p, replace_loop_mem, &ri);
9857 if (GET_CODE (p) == CODE_LABEL
9858 || GET_CODE (p) == JUMP_INSN)
9859 maybe_never = 1;
9862 if (! apply_change_group ())
9863 /* We couldn't replace all occurrences of the MEM. */
9864 loop_mems[i].optimize = 0;
9865 else
9867 /* Load the memory immediately before LOOP->START, which is
9868 the NOTE_LOOP_BEG. */
9869 cselib_val *e = cselib_lookup (mem, VOIDmode, 0);
9870 rtx set;
9871 rtx best = mem;
9872 int j;
9873 struct elt_loc_list *const_equiv = 0;
9875 if (e)
9877 struct elt_loc_list *equiv;
9878 struct elt_loc_list *best_equiv = 0;
9879 for (equiv = e->locs; equiv; equiv = equiv->next)
9881 if (CONSTANT_P (equiv->loc))
9882 const_equiv = equiv;
9883 else if (GET_CODE (equiv->loc) == REG
9884 /* Extending hard register lifetimes cuases crash
9885 on SRC targets. Doing so on non-SRC is
9886 probably also not good idea, since we most
9887 probably have pseudoregister equivalence as
9888 well. */
9889 && REGNO (equiv->loc) >= FIRST_PSEUDO_REGISTER)
9890 best_equiv = equiv;
9892 /* Use the constant equivalence if that is cheap enough. */
9893 if (! best_equiv)
9894 best_equiv = const_equiv;
9895 else if (const_equiv
9896 && (rtx_cost (const_equiv->loc, SET)
9897 <= rtx_cost (best_equiv->loc, SET)))
9899 best_equiv = const_equiv;
9900 const_equiv = 0;
9903 /* If best_equiv is nonzero, we know that MEM is set to a
9904 constant or register before the loop. We will use this
9905 knowledge to initialize the shadow register with that
9906 constant or reg rather than by loading from MEM. */
9907 if (best_equiv)
9908 best = copy_rtx (best_equiv->loc);
9910 set = gen_move_insn (reg, best);
9911 set = emit_insn_before (set, loop->start);
9912 if (const_equiv)
9913 REG_NOTES (set) = gen_rtx_EXPR_LIST (REG_EQUAL,
9914 copy_rtx (const_equiv->loc),
9915 REG_NOTES (set));
9917 if (written)
9919 if (label == NULL_RTX)
9921 /* We must compute the former
9922 right-after-the-end label before we insert
9923 the new one. */
9924 end_label = next_label (loop->end);
9925 label = gen_label_rtx ();
9926 emit_label_after (label, loop->end);
9929 /* Store the memory immediately after END, which is
9930 the NOTE_LOOP_END. */
9931 set = gen_move_insn (copy_rtx (mem), reg);
9932 emit_insn_after (set, label);
9935 if (loop_dump_stream)
9937 fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
9938 REGNO (reg), (written ? "r/w" : "r/o"));
9939 print_rtl (loop_dump_stream, mem);
9940 fputc ('\n', loop_dump_stream);
9943 /* Attempt a bit of copy propagation. This helps untangle the
9944 data flow, and enables {basic,general}_induction_var to find
9945 more bivs/givs. */
9946 EXECUTE_IF_SET_IN_REG_SET
9947 (&copies, FIRST_PSEUDO_REGISTER, j,
9949 try_copy_prop (loop, loop_mems[i].reg, j);
9951 CLEAR_REG_SET (&copies);
9955 if (label != NULL_RTX)
9957 /* Now, we need to replace all references to the previous exit
9958 label with the new one. */
9959 rtx_pair rr;
9960 rr.r1 = end_label;
9961 rr.r2 = label;
9963 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
9965 for_each_rtx (&p, replace_label, &rr);
9967 /* If this is a JUMP_INSN, then we also need to fix the JUMP_LABEL
9968 field. This is not handled by for_each_rtx because it doesn't
9969 handle unprinted ('0') fields. We need to update JUMP_LABEL
9970 because the immediately following unroll pass will use it.
9971 replace_label would not work anyways, because that only handles
9972 LABEL_REFs. */
9973 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == end_label)
9974 JUMP_LABEL (p) = label;
9978 cselib_finish ();
9981 /* For communication between note_reg_stored and its caller. */
9982 struct note_reg_stored_arg
9984 int set_seen;
9985 rtx reg;
9988 /* Called via note_stores, record in SET_SEEN whether X, which is written,
9989 is equal to ARG. */
9990 static void
9991 note_reg_stored (x, setter, arg)
9992 rtx x, setter ATTRIBUTE_UNUSED;
9993 void *arg;
9995 struct note_reg_stored_arg *t = (struct note_reg_stored_arg *)arg;
9996 if (t->reg == x)
9997 t->set_seen = 1;
10000 /* Try to replace every occurrence of pseudo REGNO with REPLACEMENT.
10001 There must be exactly one insn that sets this pseudo; it will be
10002 deleted if all replacements succeed and we can prove that the register
10003 is not used after the loop. */
10005 static void
10006 try_copy_prop (loop, replacement, regno)
10007 const struct loop *loop;
10008 rtx replacement;
10009 unsigned int regno;
10011 /* This is the reg that we are copying from. */
10012 rtx reg_rtx = regno_reg_rtx[regno];
10013 rtx init_insn = 0;
10014 rtx insn;
10015 /* These help keep track of whether we replaced all uses of the reg. */
10016 int replaced_last = 0;
10017 int store_is_first = 0;
10019 for (insn = next_insn_in_loop (loop, loop->scan_start);
10020 insn != NULL_RTX;
10021 insn = next_insn_in_loop (loop, insn))
10023 rtx set;
10025 /* Only substitute within one extended basic block from the initializing
10026 insn. */
10027 if (GET_CODE (insn) == CODE_LABEL && init_insn)
10028 break;
10030 if (GET_RTX_CLASS (GET_CODE (insn)) != 'i')
10031 continue;
10033 /* Is this the initializing insn? */
10034 set = single_set (insn);
10035 if (set
10036 && GET_CODE (SET_DEST (set)) == REG
10037 && REGNO (SET_DEST (set)) == regno)
10039 if (init_insn)
10040 abort ();
10042 init_insn = insn;
10043 if (REGNO_FIRST_UID (regno) == INSN_UID (insn))
10044 store_is_first = 1;
10047 /* Only substitute after seeing the initializing insn. */
10048 if (init_insn && insn != init_insn)
10050 struct note_reg_stored_arg arg;
10051 rtx array[3];
10052 array[0] = reg_rtx;
10053 array[1] = replacement;
10054 array[2] = insn;
10056 for_each_rtx (&insn, replace_loop_reg, array);
10057 if (REGNO_LAST_UID (regno) == INSN_UID (insn))
10058 replaced_last = 1;
10060 /* Stop replacing when REPLACEMENT is modified. */
10061 arg.reg = replacement;
10062 arg.set_seen = 0;
10063 note_stores (PATTERN (insn), note_reg_stored, &arg);
10064 if (arg.set_seen)
10065 break;
10068 if (! init_insn)
10069 abort ();
10070 if (apply_change_group ())
10072 if (loop_dump_stream)
10073 fprintf (loop_dump_stream, " Replaced reg %d", regno);
10074 if (store_is_first && replaced_last)
10076 PUT_CODE (init_insn, NOTE);
10077 NOTE_LINE_NUMBER (init_insn) = NOTE_INSN_DELETED;
10078 if (loop_dump_stream)
10079 fprintf (loop_dump_stream, ", deleting init_insn (%d)",
10080 INSN_UID (init_insn));
10082 if (loop_dump_stream)
10083 fprintf (loop_dump_stream, ".\n");
10087 /* Replace MEM with its associated pseudo register. This function is
10088 called from load_mems via for_each_rtx. DATA is actually an
10089 rtx_and_int * describing the instruction currently being scanned
10090 and the MEM we are currently replacing. */
10092 static int
10093 replace_loop_mem (mem, data)
10094 rtx *mem;
10095 void *data;
10097 rtx_and_int *ri;
10098 rtx insn;
10099 int i;
10100 rtx m = *mem;
10102 if (m == NULL_RTX)
10103 return 0;
10105 switch (GET_CODE (m))
10107 case MEM:
10108 break;
10110 case CONST_DOUBLE:
10111 /* We're not interested in the MEM associated with a
10112 CONST_DOUBLE, so there's no need to traverse into one. */
10113 return -1;
10115 default:
10116 /* This is not a MEM. */
10117 return 0;
10120 ri = (rtx_and_int*) data;
10121 i = ri->i;
10123 if (!rtx_equal_p (loop_mems[i].mem, m))
10124 /* This is not the MEM we are currently replacing. */
10125 return 0;
10127 insn = ri->r;
10129 /* Actually replace the MEM. */
10130 validate_change (insn, mem, loop_mems[i].reg, 1);
10132 return 0;
10135 /* Replace one register with another. Called through for_each_rtx; PX points
10136 to the rtx being scanned. DATA is actually an array of three rtx's; the
10137 first one is the one to be replaced, and the second one the replacement.
10138 The third one is the current insn. */
10140 static int
10141 replace_loop_reg (px, data)
10142 rtx *px;
10143 void *data;
10145 rtx x = *px;
10146 rtx *array = (rtx *)data;
10148 if (x == NULL_RTX)
10149 return 0;
10151 if (x == array[0])
10152 validate_change (array[2], px, array[1], 1);
10154 return 0;
10157 /* Replace occurrences of the old exit label for the loop with the new
10158 one. DATA is an rtx_pair containing the old and new labels,
10159 respectively. */
10161 static int
10162 replace_label (x, data)
10163 rtx *x;
10164 void *data;
10166 rtx l = *x;
10167 rtx old_label = ((rtx_pair*) data)->r1;
10168 rtx new_label = ((rtx_pair*) data)->r2;
10170 if (l == NULL_RTX)
10171 return 0;
10173 if (GET_CODE (l) != LABEL_REF)
10174 return 0;
10176 if (XEXP (l, 0) != old_label)
10177 return 0;
10179 XEXP (l, 0) = new_label;
10180 ++LABEL_NUSES (new_label);
10181 --LABEL_NUSES (old_label);
10183 return 0;