2013-11-21 Edward Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / gcc / loop-unroll.c
blob1240f7ce024f29c7630e724ca940c4b2a5fa63ef
1 /* Loop unrolling and peeling.
2 Copyright (C) 2002-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "hard-reg-set.h"
27 #include "obstack.h"
28 #include "basic-block.h"
29 #include "cfgloop.h"
30 #include "params.h"
31 #include "expr.h"
32 #include "hash-table.h"
33 #include "recog.h"
34 #include "target.h"
35 #include "dumpfile.h"
37 /* This pass performs loop unrolling and peeling. We only perform these
38 optimizations on innermost loops (with single exception) because
39 the impact on performance is greatest here, and we want to avoid
40 unnecessary code size growth. The gain is caused by greater sequentiality
41 of code, better code to optimize for further passes and in some cases
42 by fewer testings of exit conditions. The main problem is code growth,
43 that impacts performance negatively due to effect of caches.
45 What we do:
47 -- complete peeling of once-rolling loops; this is the above mentioned
48 exception, as this causes loop to be cancelled completely and
49 does not cause code growth
50 -- complete peeling of loops that roll (small) constant times.
51 -- simple peeling of first iterations of loops that do not roll much
52 (according to profile feedback)
53 -- unrolling of loops that roll constant times; this is almost always
54 win, as we get rid of exit condition tests.
55 -- unrolling of loops that roll number of times that we can compute
56 in runtime; we also get rid of exit condition tests here, but there
57 is the extra expense for calculating the number of iterations
58 -- simple unrolling of remaining loops; this is performed only if we
59 are asked to, as the gain is questionable in this case and often
60 it may even slow down the code
61 For more detailed descriptions of each of those, see comments at
62 appropriate function below.
64 There is a lot of parameters (defined and described in params.def) that
65 control how much we unroll/peel.
67 ??? A great problem is that we don't have a good way how to determine
68 how many times we should unroll the loop; the experiments I have made
69 showed that this choice may affect performance in order of several %.
72 /* Information about induction variables to split. */
74 struct iv_to_split
76 rtx insn; /* The insn in that the induction variable occurs. */
77 rtx orig_var; /* The variable (register) for the IV before split. */
78 rtx base_var; /* The variable on that the values in the further
79 iterations are based. */
80 rtx step; /* Step of the induction variable. */
81 struct iv_to_split *next; /* Next entry in walking order. */
82 unsigned n_loc;
83 unsigned loc[3]; /* Location where the definition of the induction
84 variable occurs in the insn. For example if
85 N_LOC is 2, the expression is located at
86 XEXP (XEXP (single_set, loc[0]), loc[1]). */
89 /* Information about accumulators to expand. */
91 struct var_to_expand
93 rtx insn; /* The insn in that the variable expansion occurs. */
94 rtx reg; /* The accumulator which is expanded. */
95 vec<rtx> var_expansions; /* The copies of the accumulator which is expanded. */
96 struct var_to_expand *next; /* Next entry in walking order. */
97 enum rtx_code op; /* The type of the accumulation - addition, subtraction
98 or multiplication. */
99 int expansion_count; /* Count the number of expansions generated so far. */
100 int reuse_expansion; /* The expansion we intend to reuse to expand
101 the accumulator. If REUSE_EXPANSION is 0 reuse
102 the original accumulator. Else use
103 var_expansions[REUSE_EXPANSION - 1]. */
106 /* Hashtable helper for iv_to_split. */
108 struct iv_split_hasher : typed_free_remove <iv_to_split>
110 typedef iv_to_split value_type;
111 typedef iv_to_split compare_type;
112 static inline hashval_t hash (const value_type *);
113 static inline bool equal (const value_type *, const compare_type *);
117 /* A hash function for information about insns to split. */
119 inline hashval_t
120 iv_split_hasher::hash (const value_type *ivts)
122 return (hashval_t) INSN_UID (ivts->insn);
125 /* An equality functions for information about insns to split. */
127 inline bool
128 iv_split_hasher::equal (const value_type *i1, const compare_type *i2)
130 return i1->insn == i2->insn;
133 /* Hashtable helper for iv_to_split. */
135 struct var_expand_hasher : typed_free_remove <var_to_expand>
137 typedef var_to_expand value_type;
138 typedef var_to_expand compare_type;
139 static inline hashval_t hash (const value_type *);
140 static inline bool equal (const value_type *, const compare_type *);
143 /* Return a hash for VES. */
145 inline hashval_t
146 var_expand_hasher::hash (const value_type *ves)
148 return (hashval_t) INSN_UID (ves->insn);
151 /* Return true if I1 and I2 refer to the same instruction. */
153 inline bool
154 var_expand_hasher::equal (const value_type *i1, const compare_type *i2)
156 return i1->insn == i2->insn;
159 /* Information about optimization applied in
160 the unrolled loop. */
162 struct opt_info
164 hash_table <iv_split_hasher> insns_to_split; /* A hashtable of insns to
165 split. */
166 struct iv_to_split *iv_to_split_head; /* The first iv to split. */
167 struct iv_to_split **iv_to_split_tail; /* Pointer to the tail of the list. */
168 hash_table <var_expand_hasher> insns_with_var_to_expand; /* A hashtable of
169 insns with accumulators to expand. */
170 struct var_to_expand *var_to_expand_head; /* The first var to expand. */
171 struct var_to_expand **var_to_expand_tail; /* Pointer to the tail of the list. */
172 unsigned first_new_block; /* The first basic block that was
173 duplicated. */
174 basic_block loop_exit; /* The loop exit basic block. */
175 basic_block loop_preheader; /* The loop preheader basic block. */
178 static void decide_unrolling_and_peeling (int);
179 static void peel_loops_completely (int);
180 static void decide_peel_simple (struct loop *, int);
181 static void decide_peel_once_rolling (struct loop *, int);
182 static void decide_peel_completely (struct loop *, int);
183 static void decide_unroll_stupid (struct loop *, int);
184 static void decide_unroll_constant_iterations (struct loop *, int);
185 static void decide_unroll_runtime_iterations (struct loop *, int);
186 static void peel_loop_simple (struct loop *);
187 static void peel_loop_completely (struct loop *);
188 static void unroll_loop_stupid (struct loop *);
189 static void unroll_loop_constant_iterations (struct loop *);
190 static void unroll_loop_runtime_iterations (struct loop *);
191 static struct opt_info *analyze_insns_in_loop (struct loop *);
192 static void opt_info_start_duplication (struct opt_info *);
193 static void apply_opt_in_copies (struct opt_info *, unsigned, bool, bool);
194 static void free_opt_info (struct opt_info *);
195 static struct var_to_expand *analyze_insn_to_expand_var (struct loop*, rtx);
196 static bool referenced_in_one_insn_in_loop_p (struct loop *, rtx, int *);
197 static struct iv_to_split *analyze_iv_to_split_insn (rtx);
198 static void expand_var_during_unrolling (struct var_to_expand *, rtx);
199 static void insert_var_expansion_initialization (struct var_to_expand *,
200 basic_block);
201 static void combine_var_copies_in_loop_exit (struct var_to_expand *,
202 basic_block);
203 static rtx get_expansion (struct var_to_expand *);
205 /* Emit a message summarizing the unroll or peel that will be
206 performed for LOOP, along with the loop's location LOCUS, if
207 appropriate given the dump or -fopt-info settings. */
209 static void
210 report_unroll_peel (struct loop *loop, location_t locus)
212 struct niter_desc *desc;
213 int niters = 0;
214 int report_flags = MSG_OPTIMIZED_LOCATIONS | TDF_RTL | TDF_DETAILS;
216 if (loop->lpt_decision.decision == LPT_NONE)
217 return;
219 if (!dump_enabled_p ())
220 return;
222 /* In the special case where the loop never iterated, emit
223 a different message so that we don't report an unroll by 0.
224 This matches the equivalent message emitted during tree unrolling. */
225 if (loop->lpt_decision.decision == LPT_PEEL_COMPLETELY
226 && !loop->lpt_decision.times)
228 dump_printf_loc (report_flags, locus,
229 "loop turned into non-loop; it never loops.\n");
230 return;
233 desc = get_simple_loop_desc (loop);
235 if (desc->const_iter)
236 niters = desc->niter;
237 else if (loop->header->count)
238 niters = expected_loop_iterations (loop);
240 if (loop->lpt_decision.decision == LPT_PEEL_COMPLETELY)
241 dump_printf_loc (report_flags, locus,
242 "loop with %d iterations completely unrolled",
243 loop->lpt_decision.times + 1);
244 else
245 dump_printf_loc (report_flags, locus,
246 "loop %s %d times",
247 (loop->lpt_decision.decision == LPT_PEEL_SIMPLE
248 ? "peeled" : "unrolled"),
249 loop->lpt_decision.times);
250 if (profile_info)
251 dump_printf (report_flags,
252 " (header execution count %d",
253 (int)loop->header->count);
254 if (loop->lpt_decision.decision == LPT_PEEL_COMPLETELY)
255 dump_printf (report_flags,
256 "%s%s iterations %d)",
257 profile_info ? ", " : " (",
258 desc->const_iter ? "const" : "average",
259 niters);
260 else if (profile_info)
261 dump_printf (report_flags, ")");
263 dump_printf (report_flags, "\n");
266 /* Unroll and/or peel (depending on FLAGS) LOOPS. */
267 void
268 unroll_and_peel_loops (int flags)
270 struct loop *loop;
271 bool changed = false;
273 /* First perform complete loop peeling (it is almost surely a win,
274 and affects parameters for further decision a lot). */
275 peel_loops_completely (flags);
277 /* Now decide rest of unrolling and peeling. */
278 decide_unrolling_and_peeling (flags);
280 /* Scan the loops, inner ones first. */
281 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
283 /* And perform the appropriate transformations. */
284 switch (loop->lpt_decision.decision)
286 case LPT_PEEL_COMPLETELY:
287 /* Already done. */
288 gcc_unreachable ();
289 case LPT_PEEL_SIMPLE:
290 peel_loop_simple (loop);
291 changed = true;
292 break;
293 case LPT_UNROLL_CONSTANT:
294 unroll_loop_constant_iterations (loop);
295 changed = true;
296 break;
297 case LPT_UNROLL_RUNTIME:
298 unroll_loop_runtime_iterations (loop);
299 changed = true;
300 break;
301 case LPT_UNROLL_STUPID:
302 unroll_loop_stupid (loop);
303 changed = true;
304 break;
305 case LPT_NONE:
306 break;
307 default:
308 gcc_unreachable ();
312 if (changed)
314 calculate_dominance_info (CDI_DOMINATORS);
315 fix_loop_structure (NULL);
318 iv_analysis_done ();
321 /* Check whether exit of the LOOP is at the end of loop body. */
323 static bool
324 loop_exit_at_end_p (struct loop *loop)
326 struct niter_desc *desc = get_simple_loop_desc (loop);
327 rtx insn;
329 if (desc->in_edge->dest != loop->latch)
330 return false;
332 /* Check that the latch is empty. */
333 FOR_BB_INSNS (loop->latch, insn)
335 if (NONDEBUG_INSN_P (insn))
336 return false;
339 return true;
342 /* Depending on FLAGS, check whether to peel loops completely and do so. */
343 static void
344 peel_loops_completely (int flags)
346 struct loop *loop;
347 bool changed = false;
349 /* Scan the loops, the inner ones first. */
350 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
352 loop->lpt_decision.decision = LPT_NONE;
353 location_t locus = get_loop_location (loop);
355 if (dump_enabled_p ())
356 dump_printf_loc (TDF_RTL, locus,
357 ";; *** Considering loop %d at BB %d for "
358 "complete peeling ***\n",
359 loop->num, loop->header->index);
361 loop->ninsns = num_loop_insns (loop);
363 decide_peel_once_rolling (loop, flags);
364 if (loop->lpt_decision.decision == LPT_NONE)
365 decide_peel_completely (loop, flags);
367 if (loop->lpt_decision.decision == LPT_PEEL_COMPLETELY)
369 report_unroll_peel (loop, locus);
370 peel_loop_completely (loop);
371 changed = true;
375 if (changed)
377 calculate_dominance_info (CDI_DOMINATORS);
378 fix_loop_structure (NULL);
382 /* Decide whether unroll or peel loops (depending on FLAGS) and how much. */
383 static void
384 decide_unrolling_and_peeling (int flags)
386 struct loop *loop;
388 /* Scan the loops, inner ones first. */
389 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
391 loop->lpt_decision.decision = LPT_NONE;
392 location_t locus = get_loop_location (loop);
394 if (dump_enabled_p ())
395 dump_printf_loc (TDF_RTL, locus,
396 ";; *** Considering loop %d at BB %d for "
397 "unrolling and peeling ***\n",
398 loop->num, loop->header->index);
400 /* Do not peel cold areas. */
401 if (optimize_loop_for_size_p (loop))
403 if (dump_file)
404 fprintf (dump_file, ";; Not considering loop, cold area\n");
405 continue;
408 /* Can the loop be manipulated? */
409 if (!can_duplicate_loop_p (loop))
411 if (dump_file)
412 fprintf (dump_file,
413 ";; Not considering loop, cannot duplicate\n");
414 continue;
417 /* Skip non-innermost loops. */
418 if (loop->inner)
420 if (dump_file)
421 fprintf (dump_file, ";; Not considering loop, is not innermost\n");
422 continue;
425 loop->ninsns = num_loop_insns (loop);
426 loop->av_ninsns = average_num_loop_insns (loop);
428 /* Try transformations one by one in decreasing order of
429 priority. */
431 decide_unroll_constant_iterations (loop, flags);
432 if (loop->lpt_decision.decision == LPT_NONE)
433 decide_unroll_runtime_iterations (loop, flags);
434 if (loop->lpt_decision.decision == LPT_NONE)
435 decide_unroll_stupid (loop, flags);
436 if (loop->lpt_decision.decision == LPT_NONE)
437 decide_peel_simple (loop, flags);
439 report_unroll_peel (loop, locus);
443 /* Decide whether the LOOP is once rolling and suitable for complete
444 peeling. */
445 static void
446 decide_peel_once_rolling (struct loop *loop, int flags ATTRIBUTE_UNUSED)
448 struct niter_desc *desc;
450 if (dump_file)
451 fprintf (dump_file, "\n;; Considering peeling once rolling loop\n");
453 /* Is the loop small enough? */
454 if ((unsigned) PARAM_VALUE (PARAM_MAX_ONCE_PEELED_INSNS) < loop->ninsns)
456 if (dump_file)
457 fprintf (dump_file, ";; Not considering loop, is too big\n");
458 return;
461 /* Check for simple loops. */
462 desc = get_simple_loop_desc (loop);
464 /* Check number of iterations. */
465 if (!desc->simple_p
466 || desc->assumptions
467 || desc->infinite
468 || !desc->const_iter
469 || (desc->niter != 0
470 && get_max_loop_iterations_int (loop) != 0))
472 if (dump_file)
473 fprintf (dump_file,
474 ";; Unable to prove that the loop rolls exactly once\n");
475 return;
478 /* Success. */
479 loop->lpt_decision.decision = LPT_PEEL_COMPLETELY;
482 /* Decide whether the LOOP is suitable for complete peeling. */
483 static void
484 decide_peel_completely (struct loop *loop, int flags ATTRIBUTE_UNUSED)
486 unsigned npeel;
487 struct niter_desc *desc;
489 if (dump_file)
490 fprintf (dump_file, "\n;; Considering peeling completely\n");
492 /* Skip non-innermost loops. */
493 if (loop->inner)
495 if (dump_file)
496 fprintf (dump_file, ";; Not considering loop, is not innermost\n");
497 return;
500 /* Do not peel cold areas. */
501 if (optimize_loop_for_size_p (loop))
503 if (dump_file)
504 fprintf (dump_file, ";; Not considering loop, cold area\n");
505 return;
508 /* Can the loop be manipulated? */
509 if (!can_duplicate_loop_p (loop))
511 if (dump_file)
512 fprintf (dump_file,
513 ";; Not considering loop, cannot duplicate\n");
514 return;
517 /* npeel = number of iterations to peel. */
518 npeel = PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS) / loop->ninsns;
519 if (npeel > (unsigned) PARAM_VALUE (PARAM_MAX_COMPLETELY_PEEL_TIMES))
520 npeel = PARAM_VALUE (PARAM_MAX_COMPLETELY_PEEL_TIMES);
522 /* Is the loop small enough? */
523 if (!npeel)
525 if (dump_file)
526 fprintf (dump_file, ";; Not considering loop, is too big\n");
527 return;
530 /* Check for simple loops. */
531 desc = get_simple_loop_desc (loop);
533 /* Check number of iterations. */
534 if (!desc->simple_p
535 || desc->assumptions
536 || !desc->const_iter
537 || desc->infinite)
539 if (dump_file)
540 fprintf (dump_file,
541 ";; Unable to prove that the loop iterates constant times\n");
542 return;
545 if (desc->niter > npeel - 1)
547 if (dump_file)
549 fprintf (dump_file,
550 ";; Not peeling loop completely, rolls too much (");
551 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC, desc->niter);
552 fprintf (dump_file, " iterations > %d [maximum peelings])\n", npeel);
554 return;
557 /* Success. */
558 loop->lpt_decision.decision = LPT_PEEL_COMPLETELY;
561 /* Peel all iterations of LOOP, remove exit edges and cancel the loop
562 completely. The transformation done:
564 for (i = 0; i < 4; i++)
565 body;
569 i = 0;
570 body; i++;
571 body; i++;
572 body; i++;
573 body; i++;
575 static void
576 peel_loop_completely (struct loop *loop)
578 sbitmap wont_exit;
579 unsigned HOST_WIDE_INT npeel;
580 unsigned i;
581 vec<edge> remove_edges;
582 edge ein;
583 struct niter_desc *desc = get_simple_loop_desc (loop);
584 struct opt_info *opt_info = NULL;
586 npeel = desc->niter;
588 if (npeel)
590 bool ok;
592 wont_exit = sbitmap_alloc (npeel + 1);
593 bitmap_ones (wont_exit);
594 bitmap_clear_bit (wont_exit, 0);
595 if (desc->noloop_assumptions)
596 bitmap_clear_bit (wont_exit, 1);
598 remove_edges.create (0);
600 if (flag_split_ivs_in_unroller)
601 opt_info = analyze_insns_in_loop (loop);
603 opt_info_start_duplication (opt_info);
604 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
605 npeel,
606 wont_exit, desc->out_edge,
607 &remove_edges,
608 DLTHE_FLAG_UPDATE_FREQ
609 | DLTHE_FLAG_COMPLETTE_PEEL
610 | (opt_info
611 ? DLTHE_RECORD_COPY_NUMBER : 0));
612 gcc_assert (ok);
614 free (wont_exit);
616 if (opt_info)
618 apply_opt_in_copies (opt_info, npeel, false, true);
619 free_opt_info (opt_info);
622 /* Remove the exit edges. */
623 FOR_EACH_VEC_ELT (remove_edges, i, ein)
624 remove_path (ein);
625 remove_edges.release ();
628 ein = desc->in_edge;
629 free_simple_loop_desc (loop);
631 /* Now remove the unreachable part of the last iteration and cancel
632 the loop. */
633 remove_path (ein);
635 if (dump_file)
636 fprintf (dump_file, ";; Peeled loop completely, %d times\n", (int) npeel);
639 /* Decide whether to unroll LOOP iterating constant number of times
640 and how much. */
642 static void
643 decide_unroll_constant_iterations (struct loop *loop, int flags)
645 unsigned nunroll, nunroll_by_av, best_copies, best_unroll = 0, n_copies, i;
646 struct niter_desc *desc;
647 double_int iterations;
649 if (!(flags & UAP_UNROLL))
651 /* We were not asked to, just return back silently. */
652 return;
655 if (dump_file)
656 fprintf (dump_file,
657 "\n;; Considering unrolling loop with constant "
658 "number of iterations\n");
660 /* nunroll = total number of copies of the original loop body in
661 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
662 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
663 nunroll_by_av
664 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
665 if (nunroll > nunroll_by_av)
666 nunroll = nunroll_by_av;
667 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
668 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
670 /* Skip big loops. */
671 if (nunroll <= 1)
673 if (dump_file)
674 fprintf (dump_file, ";; Not considering loop, is too big\n");
675 return;
678 /* Check for simple loops. */
679 desc = get_simple_loop_desc (loop);
681 /* Check number of iterations. */
682 if (!desc->simple_p || !desc->const_iter || desc->assumptions)
684 if (dump_file)
685 fprintf (dump_file,
686 ";; Unable to prove that the loop iterates constant times\n");
687 return;
690 /* Check whether the loop rolls enough to consider.
691 Consult also loop bounds and profile; in the case the loop has more
692 than one exit it may well loop less than determined maximal number
693 of iterations. */
694 if (desc->niter < 2 * nunroll
695 || ((get_estimated_loop_iterations (loop, &iterations)
696 || get_max_loop_iterations (loop, &iterations))
697 && iterations.ult (double_int::from_shwi (2 * nunroll))))
699 if (dump_file)
700 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
701 return;
704 /* Success; now compute number of iterations to unroll. We alter
705 nunroll so that as few as possible copies of loop body are
706 necessary, while still not decreasing the number of unrollings
707 too much (at most by 1). */
708 best_copies = 2 * nunroll + 10;
710 i = 2 * nunroll + 2;
711 if (i - 1 >= desc->niter)
712 i = desc->niter - 2;
714 for (; i >= nunroll - 1; i--)
716 unsigned exit_mod = desc->niter % (i + 1);
718 if (!loop_exit_at_end_p (loop))
719 n_copies = exit_mod + i + 1;
720 else if (exit_mod != (unsigned) i
721 || desc->noloop_assumptions != NULL_RTX)
722 n_copies = exit_mod + i + 2;
723 else
724 n_copies = i + 1;
726 if (n_copies < best_copies)
728 best_copies = n_copies;
729 best_unroll = i;
733 loop->lpt_decision.decision = LPT_UNROLL_CONSTANT;
734 loop->lpt_decision.times = best_unroll;
737 /* Unroll LOOP with constant number of iterations LOOP->LPT_DECISION.TIMES times.
738 The transformation does this:
740 for (i = 0; i < 102; i++)
741 body;
743 ==> (LOOP->LPT_DECISION.TIMES == 3)
745 i = 0;
746 body; i++;
747 body; i++;
748 while (i < 102)
750 body; i++;
751 body; i++;
752 body; i++;
753 body; i++;
756 static void
757 unroll_loop_constant_iterations (struct loop *loop)
759 unsigned HOST_WIDE_INT niter;
760 unsigned exit_mod;
761 sbitmap wont_exit;
762 unsigned i;
763 vec<edge> remove_edges;
764 edge e;
765 unsigned max_unroll = loop->lpt_decision.times;
766 struct niter_desc *desc = get_simple_loop_desc (loop);
767 bool exit_at_end = loop_exit_at_end_p (loop);
768 struct opt_info *opt_info = NULL;
769 bool ok;
771 niter = desc->niter;
773 /* Should not get here (such loop should be peeled instead). */
774 gcc_assert (niter > max_unroll + 1);
776 exit_mod = niter % (max_unroll + 1);
778 wont_exit = sbitmap_alloc (max_unroll + 1);
779 bitmap_ones (wont_exit);
781 remove_edges.create (0);
782 if (flag_split_ivs_in_unroller
783 || flag_variable_expansion_in_unroller)
784 opt_info = analyze_insns_in_loop (loop);
786 if (!exit_at_end)
788 /* The exit is not at the end of the loop; leave exit test
789 in the first copy, so that the loops that start with test
790 of exit condition have continuous body after unrolling. */
792 if (dump_file)
793 fprintf (dump_file, ";; Condition at beginning of loop.\n");
795 /* Peel exit_mod iterations. */
796 bitmap_clear_bit (wont_exit, 0);
797 if (desc->noloop_assumptions)
798 bitmap_clear_bit (wont_exit, 1);
800 if (exit_mod)
802 opt_info_start_duplication (opt_info);
803 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
804 exit_mod,
805 wont_exit, desc->out_edge,
806 &remove_edges,
807 DLTHE_FLAG_UPDATE_FREQ
808 | (opt_info && exit_mod > 1
809 ? DLTHE_RECORD_COPY_NUMBER
810 : 0));
811 gcc_assert (ok);
813 if (opt_info && exit_mod > 1)
814 apply_opt_in_copies (opt_info, exit_mod, false, false);
816 desc->noloop_assumptions = NULL_RTX;
817 desc->niter -= exit_mod;
818 loop->nb_iterations_upper_bound -= double_int::from_uhwi (exit_mod);
819 if (loop->any_estimate
820 && double_int::from_uhwi (exit_mod).ule
821 (loop->nb_iterations_estimate))
822 loop->nb_iterations_estimate -= double_int::from_uhwi (exit_mod);
823 else
824 loop->any_estimate = false;
827 bitmap_set_bit (wont_exit, 1);
829 else
831 /* Leave exit test in last copy, for the same reason as above if
832 the loop tests the condition at the end of loop body. */
834 if (dump_file)
835 fprintf (dump_file, ";; Condition at end of loop.\n");
837 /* We know that niter >= max_unroll + 2; so we do not need to care of
838 case when we would exit before reaching the loop. So just peel
839 exit_mod + 1 iterations. */
840 if (exit_mod != max_unroll
841 || desc->noloop_assumptions)
843 bitmap_clear_bit (wont_exit, 0);
844 if (desc->noloop_assumptions)
845 bitmap_clear_bit (wont_exit, 1);
847 opt_info_start_duplication (opt_info);
848 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
849 exit_mod + 1,
850 wont_exit, desc->out_edge,
851 &remove_edges,
852 DLTHE_FLAG_UPDATE_FREQ
853 | (opt_info && exit_mod > 0
854 ? DLTHE_RECORD_COPY_NUMBER
855 : 0));
856 gcc_assert (ok);
858 if (opt_info && exit_mod > 0)
859 apply_opt_in_copies (opt_info, exit_mod + 1, false, false);
861 desc->niter -= exit_mod + 1;
862 loop->nb_iterations_upper_bound -= double_int::from_uhwi (exit_mod + 1);
863 if (loop->any_estimate
864 && double_int::from_uhwi (exit_mod + 1).ule
865 (loop->nb_iterations_estimate))
866 loop->nb_iterations_estimate -= double_int::from_uhwi (exit_mod + 1);
867 else
868 loop->any_estimate = false;
869 desc->noloop_assumptions = NULL_RTX;
871 bitmap_set_bit (wont_exit, 0);
872 bitmap_set_bit (wont_exit, 1);
875 bitmap_clear_bit (wont_exit, max_unroll);
878 /* Now unroll the loop. */
880 opt_info_start_duplication (opt_info);
881 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
882 max_unroll,
883 wont_exit, desc->out_edge,
884 &remove_edges,
885 DLTHE_FLAG_UPDATE_FREQ
886 | (opt_info
887 ? DLTHE_RECORD_COPY_NUMBER
888 : 0));
889 gcc_assert (ok);
891 if (opt_info)
893 apply_opt_in_copies (opt_info, max_unroll, true, true);
894 free_opt_info (opt_info);
897 free (wont_exit);
899 if (exit_at_end)
901 basic_block exit_block = get_bb_copy (desc->in_edge->src);
902 /* Find a new in and out edge; they are in the last copy we have made. */
904 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
906 desc->out_edge = EDGE_SUCC (exit_block, 0);
907 desc->in_edge = EDGE_SUCC (exit_block, 1);
909 else
911 desc->out_edge = EDGE_SUCC (exit_block, 1);
912 desc->in_edge = EDGE_SUCC (exit_block, 0);
916 desc->niter /= max_unroll + 1;
917 loop->nb_iterations_upper_bound
918 = loop->nb_iterations_upper_bound.udiv (double_int::from_uhwi (max_unroll
919 + 1),
920 TRUNC_DIV_EXPR);
921 if (loop->any_estimate)
922 loop->nb_iterations_estimate
923 = loop->nb_iterations_estimate.udiv (double_int::from_uhwi (max_unroll
924 + 1),
925 TRUNC_DIV_EXPR);
926 desc->niter_expr = GEN_INT (desc->niter);
928 /* Remove the edges. */
929 FOR_EACH_VEC_ELT (remove_edges, i, e)
930 remove_path (e);
931 remove_edges.release ();
933 if (dump_file)
934 fprintf (dump_file,
935 ";; Unrolled loop %d times, constant # of iterations %i insns\n",
936 max_unroll, num_loop_insns (loop));
939 /* Decide whether to unroll LOOP iterating runtime computable number of times
940 and how much. */
941 static void
942 decide_unroll_runtime_iterations (struct loop *loop, int flags)
944 unsigned nunroll, nunroll_by_av, i;
945 struct niter_desc *desc;
946 double_int iterations;
948 if (!(flags & UAP_UNROLL))
950 /* We were not asked to, just return back silently. */
951 return;
954 if (dump_file)
955 fprintf (dump_file,
956 "\n;; Considering unrolling loop with runtime "
957 "computable number of iterations\n");
959 /* nunroll = total number of copies of the original loop body in
960 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
961 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
962 nunroll_by_av = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
963 if (nunroll > nunroll_by_av)
964 nunroll = nunroll_by_av;
965 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
966 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
968 if (targetm.loop_unroll_adjust)
969 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
971 /* Skip big loops. */
972 if (nunroll <= 1)
974 if (dump_file)
975 fprintf (dump_file, ";; Not considering loop, is too big\n");
976 return;
979 /* Check for simple loops. */
980 desc = get_simple_loop_desc (loop);
982 /* Check simpleness. */
983 if (!desc->simple_p || desc->assumptions)
985 if (dump_file)
986 fprintf (dump_file,
987 ";; Unable to prove that the number of iterations "
988 "can be counted in runtime\n");
989 return;
992 if (desc->const_iter)
994 if (dump_file)
995 fprintf (dump_file, ";; Loop iterates constant times\n");
996 return;
999 /* Check whether the loop rolls. */
1000 if ((get_estimated_loop_iterations (loop, &iterations)
1001 || get_max_loop_iterations (loop, &iterations))
1002 && iterations.ult (double_int::from_shwi (2 * nunroll)))
1004 if (dump_file)
1005 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
1006 return;
1009 /* Success; now force nunroll to be power of 2, as we are unable to
1010 cope with overflows in computation of number of iterations. */
1011 for (i = 1; 2 * i <= nunroll; i *= 2)
1012 continue;
1014 loop->lpt_decision.decision = LPT_UNROLL_RUNTIME;
1015 loop->lpt_decision.times = i - 1;
1018 /* Splits edge E and inserts the sequence of instructions INSNS on it, and
1019 returns the newly created block. If INSNS is NULL_RTX, nothing is changed
1020 and NULL is returned instead. */
1022 basic_block
1023 split_edge_and_insert (edge e, rtx insns)
1025 basic_block bb;
1027 if (!insns)
1028 return NULL;
1029 bb = split_edge (e);
1030 emit_insn_after (insns, BB_END (bb));
1032 /* ??? We used to assume that INSNS can contain control flow insns, and
1033 that we had to try to find sub basic blocks in BB to maintain a valid
1034 CFG. For this purpose we used to set the BB_SUPERBLOCK flag on BB
1035 and call break_superblocks when going out of cfglayout mode. But it
1036 turns out that this never happens; and that if it does ever happen,
1037 the TODO_verify_flow at the end of the RTL loop passes would fail.
1039 There are two reasons why we expected we could have control flow insns
1040 in INSNS. The first is when a comparison has to be done in parts, and
1041 the second is when the number of iterations is computed for loops with
1042 the number of iterations known at runtime. In both cases, test cases
1043 to get control flow in INSNS appear to be impossible to construct:
1045 * If do_compare_rtx_and_jump needs several branches to do comparison
1046 in a mode that needs comparison by parts, we cannot analyze the
1047 number of iterations of the loop, and we never get to unrolling it.
1049 * The code in expand_divmod that was suspected to cause creation of
1050 branching code seems to be only accessed for signed division. The
1051 divisions used by # of iterations analysis are always unsigned.
1052 Problems might arise on architectures that emits branching code
1053 for some operations that may appear in the unroller (especially
1054 for division), but we have no such architectures.
1056 Considering all this, it was decided that we should for now assume
1057 that INSNS can in theory contain control flow insns, but in practice
1058 it never does. So we don't handle the theoretical case, and should
1059 a real failure ever show up, we have a pretty good clue for how to
1060 fix it. */
1062 return bb;
1065 /* Unroll LOOP for which we are able to count number of iterations in runtime
1066 LOOP->LPT_DECISION.TIMES times. The transformation does this (with some
1067 extra care for case n < 0):
1069 for (i = 0; i < n; i++)
1070 body;
1072 ==> (LOOP->LPT_DECISION.TIMES == 3)
1074 i = 0;
1075 mod = n % 4;
1077 switch (mod)
1079 case 3:
1080 body; i++;
1081 case 2:
1082 body; i++;
1083 case 1:
1084 body; i++;
1085 case 0: ;
1088 while (i < n)
1090 body; i++;
1091 body; i++;
1092 body; i++;
1093 body; i++;
1096 static void
1097 unroll_loop_runtime_iterations (struct loop *loop)
1099 rtx old_niter, niter, init_code, branch_code, tmp;
1100 unsigned i, j, p;
1101 basic_block preheader, *body, swtch, ezc_swtch;
1102 vec<basic_block> dom_bbs;
1103 sbitmap wont_exit;
1104 int may_exit_copy;
1105 unsigned n_peel;
1106 vec<edge> remove_edges;
1107 edge e;
1108 bool extra_zero_check, last_may_exit;
1109 unsigned max_unroll = loop->lpt_decision.times;
1110 struct niter_desc *desc = get_simple_loop_desc (loop);
1111 bool exit_at_end = loop_exit_at_end_p (loop);
1112 struct opt_info *opt_info = NULL;
1113 bool ok;
1115 if (flag_split_ivs_in_unroller
1116 || flag_variable_expansion_in_unroller)
1117 opt_info = analyze_insns_in_loop (loop);
1119 /* Remember blocks whose dominators will have to be updated. */
1120 dom_bbs.create (0);
1122 body = get_loop_body (loop);
1123 for (i = 0; i < loop->num_nodes; i++)
1125 vec<basic_block> ldom;
1126 basic_block bb;
1128 ldom = get_dominated_by (CDI_DOMINATORS, body[i]);
1129 FOR_EACH_VEC_ELT (ldom, j, bb)
1130 if (!flow_bb_inside_loop_p (loop, bb))
1131 dom_bbs.safe_push (bb);
1133 ldom.release ();
1135 free (body);
1137 if (!exit_at_end)
1139 /* Leave exit in first copy (for explanation why see comment in
1140 unroll_loop_constant_iterations). */
1141 may_exit_copy = 0;
1142 n_peel = max_unroll - 1;
1143 extra_zero_check = true;
1144 last_may_exit = false;
1146 else
1148 /* Leave exit in last copy (for explanation why see comment in
1149 unroll_loop_constant_iterations). */
1150 may_exit_copy = max_unroll;
1151 n_peel = max_unroll;
1152 extra_zero_check = false;
1153 last_may_exit = true;
1156 /* Get expression for number of iterations. */
1157 start_sequence ();
1158 old_niter = niter = gen_reg_rtx (desc->mode);
1159 tmp = force_operand (copy_rtx (desc->niter_expr), niter);
1160 if (tmp != niter)
1161 emit_move_insn (niter, tmp);
1163 /* Count modulo by ANDing it with max_unroll; we use the fact that
1164 the number of unrollings is a power of two, and thus this is correct
1165 even if there is overflow in the computation. */
1166 niter = expand_simple_binop (desc->mode, AND,
1167 niter, gen_int_mode (max_unroll, desc->mode),
1168 NULL_RTX, 0, OPTAB_LIB_WIDEN);
1170 init_code = get_insns ();
1171 end_sequence ();
1172 unshare_all_rtl_in_chain (init_code);
1174 /* Precondition the loop. */
1175 split_edge_and_insert (loop_preheader_edge (loop), init_code);
1177 remove_edges.create (0);
1179 wont_exit = sbitmap_alloc (max_unroll + 2);
1181 /* Peel the first copy of loop body (almost always we must leave exit test
1182 here; the only exception is when we have extra zero check and the number
1183 of iterations is reliable. Also record the place of (possible) extra
1184 zero check. */
1185 bitmap_clear (wont_exit);
1186 if (extra_zero_check
1187 && !desc->noloop_assumptions)
1188 bitmap_set_bit (wont_exit, 1);
1189 ezc_swtch = loop_preheader_edge (loop)->src;
1190 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
1191 1, wont_exit, desc->out_edge,
1192 &remove_edges,
1193 DLTHE_FLAG_UPDATE_FREQ);
1194 gcc_assert (ok);
1196 /* Record the place where switch will be built for preconditioning. */
1197 swtch = split_edge (loop_preheader_edge (loop));
1199 for (i = 0; i < n_peel; i++)
1201 /* Peel the copy. */
1202 bitmap_clear (wont_exit);
1203 if (i != n_peel - 1 || !last_may_exit)
1204 bitmap_set_bit (wont_exit, 1);
1205 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
1206 1, wont_exit, desc->out_edge,
1207 &remove_edges,
1208 DLTHE_FLAG_UPDATE_FREQ);
1209 gcc_assert (ok);
1211 /* Create item for switch. */
1212 j = n_peel - i - (extra_zero_check ? 0 : 1);
1213 p = REG_BR_PROB_BASE / (i + 2);
1215 preheader = split_edge (loop_preheader_edge (loop));
1216 branch_code = compare_and_jump_seq (copy_rtx (niter), GEN_INT (j), EQ,
1217 block_label (preheader), p,
1218 NULL_RTX);
1220 /* We rely on the fact that the compare and jump cannot be optimized out,
1221 and hence the cfg we create is correct. */
1222 gcc_assert (branch_code != NULL_RTX);
1224 swtch = split_edge_and_insert (single_pred_edge (swtch), branch_code);
1225 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
1226 single_pred_edge (swtch)->probability = REG_BR_PROB_BASE - p;
1227 e = make_edge (swtch, preheader,
1228 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
1229 e->count = RDIV (preheader->count * REG_BR_PROB_BASE, p);
1230 e->probability = p;
1233 if (extra_zero_check)
1235 /* Add branch for zero iterations. */
1236 p = REG_BR_PROB_BASE / (max_unroll + 1);
1237 swtch = ezc_swtch;
1238 preheader = split_edge (loop_preheader_edge (loop));
1239 branch_code = compare_and_jump_seq (copy_rtx (niter), const0_rtx, EQ,
1240 block_label (preheader), p,
1241 NULL_RTX);
1242 gcc_assert (branch_code != NULL_RTX);
1244 swtch = split_edge_and_insert (single_succ_edge (swtch), branch_code);
1245 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
1246 single_succ_edge (swtch)->probability = REG_BR_PROB_BASE - p;
1247 e = make_edge (swtch, preheader,
1248 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
1249 e->count = RDIV (preheader->count * REG_BR_PROB_BASE, p);
1250 e->probability = p;
1253 /* Recount dominators for outer blocks. */
1254 iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, false);
1256 /* And unroll loop. */
1258 bitmap_ones (wont_exit);
1259 bitmap_clear_bit (wont_exit, may_exit_copy);
1260 opt_info_start_duplication (opt_info);
1262 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
1263 max_unroll,
1264 wont_exit, desc->out_edge,
1265 &remove_edges,
1266 DLTHE_FLAG_UPDATE_FREQ
1267 | (opt_info
1268 ? DLTHE_RECORD_COPY_NUMBER
1269 : 0));
1270 gcc_assert (ok);
1272 if (opt_info)
1274 apply_opt_in_copies (opt_info, max_unroll, true, true);
1275 free_opt_info (opt_info);
1278 free (wont_exit);
1280 if (exit_at_end)
1282 basic_block exit_block = get_bb_copy (desc->in_edge->src);
1283 /* Find a new in and out edge; they are in the last copy we have
1284 made. */
1286 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
1288 desc->out_edge = EDGE_SUCC (exit_block, 0);
1289 desc->in_edge = EDGE_SUCC (exit_block, 1);
1291 else
1293 desc->out_edge = EDGE_SUCC (exit_block, 1);
1294 desc->in_edge = EDGE_SUCC (exit_block, 0);
1298 /* Remove the edges. */
1299 FOR_EACH_VEC_ELT (remove_edges, i, e)
1300 remove_path (e);
1301 remove_edges.release ();
1303 /* We must be careful when updating the number of iterations due to
1304 preconditioning and the fact that the value must be valid at entry
1305 of the loop. After passing through the above code, we see that
1306 the correct new number of iterations is this: */
1307 gcc_assert (!desc->const_iter);
1308 desc->niter_expr =
1309 simplify_gen_binary (UDIV, desc->mode, old_niter,
1310 gen_int_mode (max_unroll + 1, desc->mode));
1311 loop->nb_iterations_upper_bound
1312 = loop->nb_iterations_upper_bound.udiv (double_int::from_uhwi (max_unroll
1313 + 1),
1314 TRUNC_DIV_EXPR);
1315 if (loop->any_estimate)
1316 loop->nb_iterations_estimate
1317 = loop->nb_iterations_estimate.udiv (double_int::from_uhwi (max_unroll
1318 + 1),
1319 TRUNC_DIV_EXPR);
1320 if (exit_at_end)
1322 desc->niter_expr =
1323 simplify_gen_binary (MINUS, desc->mode, desc->niter_expr, const1_rtx);
1324 desc->noloop_assumptions = NULL_RTX;
1325 --loop->nb_iterations_upper_bound;
1326 if (loop->any_estimate
1327 && loop->nb_iterations_estimate != double_int_zero)
1328 --loop->nb_iterations_estimate;
1329 else
1330 loop->any_estimate = false;
1333 if (dump_file)
1334 fprintf (dump_file,
1335 ";; Unrolled loop %d times, counting # of iterations "
1336 "in runtime, %i insns\n",
1337 max_unroll, num_loop_insns (loop));
1339 dom_bbs.release ();
1342 /* Decide whether to simply peel LOOP and how much. */
1343 static void
1344 decide_peel_simple (struct loop *loop, int flags)
1346 unsigned npeel;
1347 double_int iterations;
1349 if (!(flags & UAP_PEEL))
1351 /* We were not asked to, just return back silently. */
1352 return;
1355 if (dump_file)
1356 fprintf (dump_file, "\n;; Considering simply peeling loop\n");
1358 /* npeel = number of iterations to peel. */
1359 npeel = PARAM_VALUE (PARAM_MAX_PEELED_INSNS) / loop->ninsns;
1360 if (npeel > (unsigned) PARAM_VALUE (PARAM_MAX_PEEL_TIMES))
1361 npeel = PARAM_VALUE (PARAM_MAX_PEEL_TIMES);
1363 /* Skip big loops. */
1364 if (!npeel)
1366 if (dump_file)
1367 fprintf (dump_file, ";; Not considering loop, is too big\n");
1368 return;
1371 /* Do not simply peel loops with branches inside -- it increases number
1372 of mispredicts.
1373 Exception is when we do have profile and we however have good chance
1374 to peel proper number of iterations loop will iterate in practice.
1375 TODO: this heuristic needs tunning; while for complette unrolling
1376 the branch inside loop mostly eliminates any improvements, for
1377 peeling it is not the case. Also a function call inside loop is
1378 also branch from branch prediction POV (and probably better reason
1379 to not unroll/peel). */
1380 if (num_loop_branches (loop) > 1
1381 && profile_status != PROFILE_READ)
1383 if (dump_file)
1384 fprintf (dump_file, ";; Not peeling, contains branches\n");
1385 return;
1388 /* If we have realistic estimate on number of iterations, use it. */
1389 if (get_estimated_loop_iterations (loop, &iterations))
1391 if (double_int::from_shwi (npeel).ule (iterations))
1393 if (dump_file)
1395 fprintf (dump_file, ";; Not peeling loop, rolls too much (");
1396 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
1397 (HOST_WIDEST_INT) (iterations.to_shwi () + 1));
1398 fprintf (dump_file, " iterations > %d [maximum peelings])\n",
1399 npeel);
1401 return;
1403 npeel = iterations.to_shwi () + 1;
1405 /* If we have small enough bound on iterations, we can still peel (completely
1406 unroll). */
1407 else if (get_max_loop_iterations (loop, &iterations)
1408 && iterations.ult (double_int::from_shwi (npeel)))
1409 npeel = iterations.to_shwi () + 1;
1410 else
1412 /* For now we have no good heuristics to decide whether loop peeling
1413 will be effective, so disable it. */
1414 if (dump_file)
1415 fprintf (dump_file,
1416 ";; Not peeling loop, no evidence it will be profitable\n");
1417 return;
1420 /* Success. */
1421 loop->lpt_decision.decision = LPT_PEEL_SIMPLE;
1422 loop->lpt_decision.times = npeel;
1425 /* Peel a LOOP LOOP->LPT_DECISION.TIMES times. The transformation does this:
1427 while (cond)
1428 body;
1430 ==> (LOOP->LPT_DECISION.TIMES == 3)
1432 if (!cond) goto end;
1433 body;
1434 if (!cond) goto end;
1435 body;
1436 if (!cond) goto end;
1437 body;
1438 while (cond)
1439 body;
1440 end: ;
1442 static void
1443 peel_loop_simple (struct loop *loop)
1445 sbitmap wont_exit;
1446 unsigned npeel = loop->lpt_decision.times;
1447 struct niter_desc *desc = get_simple_loop_desc (loop);
1448 struct opt_info *opt_info = NULL;
1449 bool ok;
1451 if (flag_split_ivs_in_unroller && npeel > 1)
1452 opt_info = analyze_insns_in_loop (loop);
1454 wont_exit = sbitmap_alloc (npeel + 1);
1455 bitmap_clear (wont_exit);
1457 opt_info_start_duplication (opt_info);
1459 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
1460 npeel, wont_exit, NULL,
1461 NULL, DLTHE_FLAG_UPDATE_FREQ
1462 | (opt_info
1463 ? DLTHE_RECORD_COPY_NUMBER
1464 : 0));
1465 gcc_assert (ok);
1467 free (wont_exit);
1469 if (opt_info)
1471 apply_opt_in_copies (opt_info, npeel, false, false);
1472 free_opt_info (opt_info);
1475 if (desc->simple_p)
1477 if (desc->const_iter)
1479 desc->niter -= npeel;
1480 desc->niter_expr = GEN_INT (desc->niter);
1481 desc->noloop_assumptions = NULL_RTX;
1483 else
1485 /* We cannot just update niter_expr, as its value might be clobbered
1486 inside loop. We could handle this by counting the number into
1487 temporary just like we do in runtime unrolling, but it does not
1488 seem worthwhile. */
1489 free_simple_loop_desc (loop);
1492 if (dump_file)
1493 fprintf (dump_file, ";; Peeling loop %d times\n", npeel);
1496 /* Decide whether to unroll LOOP stupidly and how much. */
1497 static void
1498 decide_unroll_stupid (struct loop *loop, int flags)
1500 unsigned nunroll, nunroll_by_av, i;
1501 struct niter_desc *desc;
1502 double_int iterations;
1504 if (!(flags & UAP_UNROLL_ALL))
1506 /* We were not asked to, just return back silently. */
1507 return;
1510 if (dump_file)
1511 fprintf (dump_file, "\n;; Considering unrolling loop stupidly\n");
1513 /* nunroll = total number of copies of the original loop body in
1514 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
1515 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
1516 nunroll_by_av
1517 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
1518 if (nunroll > nunroll_by_av)
1519 nunroll = nunroll_by_av;
1520 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
1521 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1523 if (targetm.loop_unroll_adjust)
1524 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
1526 /* Skip big loops. */
1527 if (nunroll <= 1)
1529 if (dump_file)
1530 fprintf (dump_file, ";; Not considering loop, is too big\n");
1531 return;
1534 /* Check for simple loops. */
1535 desc = get_simple_loop_desc (loop);
1537 /* Check simpleness. */
1538 if (desc->simple_p && !desc->assumptions)
1540 if (dump_file)
1541 fprintf (dump_file, ";; The loop is simple\n");
1542 return;
1545 /* Do not unroll loops with branches inside -- it increases number
1546 of mispredicts.
1547 TODO: this heuristic needs tunning; call inside the loop body
1548 is also relatively good reason to not unroll. */
1549 if (num_loop_branches (loop) > 1)
1551 if (dump_file)
1552 fprintf (dump_file, ";; Not unrolling, contains branches\n");
1553 return;
1556 /* Check whether the loop rolls. */
1557 if ((get_estimated_loop_iterations (loop, &iterations)
1558 || get_max_loop_iterations (loop, &iterations))
1559 && iterations.ult (double_int::from_shwi (2 * nunroll)))
1561 if (dump_file)
1562 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
1563 return;
1566 /* Success. Now force nunroll to be power of 2, as it seems that this
1567 improves results (partially because of better alignments, partially
1568 because of some dark magic). */
1569 for (i = 1; 2 * i <= nunroll; i *= 2)
1570 continue;
1572 loop->lpt_decision.decision = LPT_UNROLL_STUPID;
1573 loop->lpt_decision.times = i - 1;
1576 /* Unroll a LOOP LOOP->LPT_DECISION.TIMES times. The transformation does this:
1578 while (cond)
1579 body;
1581 ==> (LOOP->LPT_DECISION.TIMES == 3)
1583 while (cond)
1585 body;
1586 if (!cond) break;
1587 body;
1588 if (!cond) break;
1589 body;
1590 if (!cond) break;
1591 body;
1594 static void
1595 unroll_loop_stupid (struct loop *loop)
1597 sbitmap wont_exit;
1598 unsigned nunroll = loop->lpt_decision.times;
1599 struct niter_desc *desc = get_simple_loop_desc (loop);
1600 struct opt_info *opt_info = NULL;
1601 bool ok;
1603 if (flag_split_ivs_in_unroller
1604 || flag_variable_expansion_in_unroller)
1605 opt_info = analyze_insns_in_loop (loop);
1608 wont_exit = sbitmap_alloc (nunroll + 1);
1609 bitmap_clear (wont_exit);
1610 opt_info_start_duplication (opt_info);
1612 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
1613 nunroll, wont_exit,
1614 NULL, NULL,
1615 DLTHE_FLAG_UPDATE_FREQ
1616 | (opt_info
1617 ? DLTHE_RECORD_COPY_NUMBER
1618 : 0));
1619 gcc_assert (ok);
1621 if (opt_info)
1623 apply_opt_in_copies (opt_info, nunroll, true, true);
1624 free_opt_info (opt_info);
1627 free (wont_exit);
1629 if (desc->simple_p)
1631 /* We indeed may get here provided that there are nontrivial assumptions
1632 for a loop to be really simple. We could update the counts, but the
1633 problem is that we are unable to decide which exit will be taken
1634 (not really true in case the number of iterations is constant,
1635 but no one will do anything with this information, so we do not
1636 worry about it). */
1637 desc->simple_p = false;
1640 if (dump_file)
1641 fprintf (dump_file, ";; Unrolled loop %d times, %i insns\n",
1642 nunroll, num_loop_insns (loop));
1645 /* Returns true if REG is referenced in one nondebug insn in LOOP.
1646 Set *DEBUG_USES to the number of debug insns that reference the
1647 variable. */
1649 bool
1650 referenced_in_one_insn_in_loop_p (struct loop *loop, rtx reg,
1651 int *debug_uses)
1653 basic_block *body, bb;
1654 unsigned i;
1655 int count_ref = 0;
1656 rtx insn;
1658 body = get_loop_body (loop);
1659 for (i = 0; i < loop->num_nodes; i++)
1661 bb = body[i];
1663 FOR_BB_INSNS (bb, insn)
1664 if (!rtx_referenced_p (reg, insn))
1665 continue;
1666 else if (DEBUG_INSN_P (insn))
1667 ++*debug_uses;
1668 else if (++count_ref > 1)
1669 break;
1671 free (body);
1672 return (count_ref == 1);
1675 /* Reset the DEBUG_USES debug insns in LOOP that reference REG. */
1677 static void
1678 reset_debug_uses_in_loop (struct loop *loop, rtx reg, int debug_uses)
1680 basic_block *body, bb;
1681 unsigned i;
1682 rtx insn;
1684 body = get_loop_body (loop);
1685 for (i = 0; debug_uses && i < loop->num_nodes; i++)
1687 bb = body[i];
1689 FOR_BB_INSNS (bb, insn)
1690 if (!DEBUG_INSN_P (insn) || !rtx_referenced_p (reg, insn))
1691 continue;
1692 else
1694 validate_change (insn, &INSN_VAR_LOCATION_LOC (insn),
1695 gen_rtx_UNKNOWN_VAR_LOC (), 0);
1696 if (!--debug_uses)
1697 break;
1700 free (body);
1703 /* Determine whether INSN contains an accumulator
1704 which can be expanded into separate copies,
1705 one for each copy of the LOOP body.
1707 for (i = 0 ; i < n; i++)
1708 sum += a[i];
1712 sum += a[i]
1713 ....
1714 i = i+1;
1715 sum1 += a[i]
1716 ....
1717 i = i+1
1718 sum2 += a[i];
1719 ....
1721 Return NULL if INSN contains no opportunity for expansion of accumulator.
1722 Otherwise, allocate a VAR_TO_EXPAND structure, fill it with the relevant
1723 information and return a pointer to it.
1726 static struct var_to_expand *
1727 analyze_insn_to_expand_var (struct loop *loop, rtx insn)
1729 rtx set, dest, src;
1730 struct var_to_expand *ves;
1731 unsigned accum_pos;
1732 enum rtx_code code;
1733 int debug_uses = 0;
1735 set = single_set (insn);
1736 if (!set)
1737 return NULL;
1739 dest = SET_DEST (set);
1740 src = SET_SRC (set);
1741 code = GET_CODE (src);
1743 if (code != PLUS && code != MINUS && code != MULT && code != FMA)
1744 return NULL;
1746 if (FLOAT_MODE_P (GET_MODE (dest)))
1748 if (!flag_associative_math)
1749 return NULL;
1750 /* In the case of FMA, we're also changing the rounding. */
1751 if (code == FMA && !flag_unsafe_math_optimizations)
1752 return NULL;
1755 /* Hmm, this is a bit paradoxical. We know that INSN is a valid insn
1756 in MD. But if there is no optab to generate the insn, we can not
1757 perform the variable expansion. This can happen if an MD provides
1758 an insn but not a named pattern to generate it, for example to avoid
1759 producing code that needs additional mode switches like for x87/mmx.
1761 So we check have_insn_for which looks for an optab for the operation
1762 in SRC. If it doesn't exist, we can't perform the expansion even
1763 though INSN is valid. */
1764 if (!have_insn_for (code, GET_MODE (src)))
1765 return NULL;
1767 if (!REG_P (dest)
1768 && !(GET_CODE (dest) == SUBREG
1769 && REG_P (SUBREG_REG (dest))))
1770 return NULL;
1772 /* Find the accumulator use within the operation. */
1773 if (code == FMA)
1775 /* We only support accumulation via FMA in the ADD position. */
1776 if (!rtx_equal_p (dest, XEXP (src, 2)))
1777 return NULL;
1778 accum_pos = 2;
1780 else if (rtx_equal_p (dest, XEXP (src, 0)))
1781 accum_pos = 0;
1782 else if (rtx_equal_p (dest, XEXP (src, 1)))
1784 /* The method of expansion that we are using; which includes the
1785 initialization of the expansions with zero and the summation of
1786 the expansions at the end of the computation will yield wrong
1787 results for (x = something - x) thus avoid using it in that case. */
1788 if (code == MINUS)
1789 return NULL;
1790 accum_pos = 1;
1792 else
1793 return NULL;
1795 /* It must not otherwise be used. */
1796 if (code == FMA)
1798 if (rtx_referenced_p (dest, XEXP (src, 0))
1799 || rtx_referenced_p (dest, XEXP (src, 1)))
1800 return NULL;
1802 else if (rtx_referenced_p (dest, XEXP (src, 1 - accum_pos)))
1803 return NULL;
1805 /* It must be used in exactly one insn. */
1806 if (!referenced_in_one_insn_in_loop_p (loop, dest, &debug_uses))
1807 return NULL;
1809 if (dump_file)
1811 fprintf (dump_file, "\n;; Expanding Accumulator ");
1812 print_rtl (dump_file, dest);
1813 fprintf (dump_file, "\n");
1816 if (debug_uses)
1817 /* Instead of resetting the debug insns, we could replace each
1818 debug use in the loop with the sum or product of all expanded
1819 accummulators. Since we'll only know of all expansions at the
1820 end, we'd have to keep track of which vars_to_expand a debug
1821 insn in the loop references, take note of each copy of the
1822 debug insn during unrolling, and when it's all done, compute
1823 the sum or product of each variable and adjust the original
1824 debug insn and each copy thereof. What a pain! */
1825 reset_debug_uses_in_loop (loop, dest, debug_uses);
1827 /* Record the accumulator to expand. */
1828 ves = XNEW (struct var_to_expand);
1829 ves->insn = insn;
1830 ves->reg = copy_rtx (dest);
1831 ves->var_expansions.create (1);
1832 ves->next = NULL;
1833 ves->op = GET_CODE (src);
1834 ves->expansion_count = 0;
1835 ves->reuse_expansion = 0;
1836 return ves;
1839 /* Determine whether there is an induction variable in INSN that
1840 we would like to split during unrolling.
1842 I.e. replace
1844 i = i + 1;
1846 i = i + 1;
1848 i = i + 1;
1851 type chains by
1853 i0 = i + 1
1855 i = i0 + 1
1857 i = i0 + 2
1860 Return NULL if INSN contains no interesting IVs. Otherwise, allocate
1861 an IV_TO_SPLIT structure, fill it with the relevant information and return a
1862 pointer to it. */
1864 static struct iv_to_split *
1865 analyze_iv_to_split_insn (rtx insn)
1867 rtx set, dest;
1868 struct rtx_iv iv;
1869 struct iv_to_split *ivts;
1870 bool ok;
1872 /* For now we just split the basic induction variables. Later this may be
1873 extended for example by selecting also addresses of memory references. */
1874 set = single_set (insn);
1875 if (!set)
1876 return NULL;
1878 dest = SET_DEST (set);
1879 if (!REG_P (dest))
1880 return NULL;
1882 if (!biv_p (insn, dest))
1883 return NULL;
1885 ok = iv_analyze_result (insn, dest, &iv);
1887 /* This used to be an assert under the assumption that if biv_p returns
1888 true that iv_analyze_result must also return true. However, that
1889 assumption is not strictly correct as evidenced by pr25569.
1891 Returning NULL when iv_analyze_result returns false is safe and
1892 avoids the problems in pr25569 until the iv_analyze_* routines
1893 can be fixed, which is apparently hard and time consuming
1894 according to their author. */
1895 if (! ok)
1896 return NULL;
1898 if (iv.step == const0_rtx
1899 || iv.mode != iv.extend_mode)
1900 return NULL;
1902 /* Record the insn to split. */
1903 ivts = XNEW (struct iv_to_split);
1904 ivts->insn = insn;
1905 ivts->orig_var = dest;
1906 ivts->base_var = NULL_RTX;
1907 ivts->step = iv.step;
1908 ivts->next = NULL;
1909 ivts->n_loc = 1;
1910 ivts->loc[0] = 1;
1912 return ivts;
1915 /* Determines which of insns in LOOP can be optimized.
1916 Return a OPT_INFO struct with the relevant hash tables filled
1917 with all insns to be optimized. The FIRST_NEW_BLOCK field
1918 is undefined for the return value. */
1920 static struct opt_info *
1921 analyze_insns_in_loop (struct loop *loop)
1923 basic_block *body, bb;
1924 unsigned i;
1925 struct opt_info *opt_info = XCNEW (struct opt_info);
1926 rtx insn;
1927 struct iv_to_split *ivts = NULL;
1928 struct var_to_expand *ves = NULL;
1929 iv_to_split **slot1;
1930 var_to_expand **slot2;
1931 vec<edge> edges = get_loop_exit_edges (loop);
1932 edge exit;
1933 bool can_apply = false;
1935 iv_analysis_loop_init (loop);
1937 body = get_loop_body (loop);
1939 if (flag_split_ivs_in_unroller)
1941 opt_info->insns_to_split.create (5 * loop->num_nodes);
1942 opt_info->iv_to_split_head = NULL;
1943 opt_info->iv_to_split_tail = &opt_info->iv_to_split_head;
1946 /* Record the loop exit bb and loop preheader before the unrolling. */
1947 opt_info->loop_preheader = loop_preheader_edge (loop)->src;
1949 if (edges.length () == 1)
1951 exit = edges[0];
1952 if (!(exit->flags & EDGE_COMPLEX))
1954 opt_info->loop_exit = split_edge (exit);
1955 can_apply = true;
1959 if (flag_variable_expansion_in_unroller
1960 && can_apply)
1962 opt_info->insns_with_var_to_expand.create (5 * loop->num_nodes);
1963 opt_info->var_to_expand_head = NULL;
1964 opt_info->var_to_expand_tail = &opt_info->var_to_expand_head;
1967 for (i = 0; i < loop->num_nodes; i++)
1969 bb = body[i];
1970 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1971 continue;
1973 FOR_BB_INSNS (bb, insn)
1975 if (!INSN_P (insn))
1976 continue;
1978 if (opt_info->insns_to_split.is_created ())
1979 ivts = analyze_iv_to_split_insn (insn);
1981 if (ivts)
1983 slot1 = opt_info->insns_to_split.find_slot (ivts, INSERT);
1984 gcc_assert (*slot1 == NULL);
1985 *slot1 = ivts;
1986 *opt_info->iv_to_split_tail = ivts;
1987 opt_info->iv_to_split_tail = &ivts->next;
1988 continue;
1991 if (opt_info->insns_with_var_to_expand.is_created ())
1992 ves = analyze_insn_to_expand_var (loop, insn);
1994 if (ves)
1996 slot2 = opt_info->insns_with_var_to_expand.find_slot (ves, INSERT);
1997 gcc_assert (*slot2 == NULL);
1998 *slot2 = ves;
1999 *opt_info->var_to_expand_tail = ves;
2000 opt_info->var_to_expand_tail = &ves->next;
2005 edges.release ();
2006 free (body);
2007 return opt_info;
2010 /* Called just before loop duplication. Records start of duplicated area
2011 to OPT_INFO. */
2013 static void
2014 opt_info_start_duplication (struct opt_info *opt_info)
2016 if (opt_info)
2017 opt_info->first_new_block = last_basic_block;
2020 /* Determine the number of iterations between initialization of the base
2021 variable and the current copy (N_COPY). N_COPIES is the total number
2022 of newly created copies. UNROLLING is true if we are unrolling
2023 (not peeling) the loop. */
2025 static unsigned
2026 determine_split_iv_delta (unsigned n_copy, unsigned n_copies, bool unrolling)
2028 if (unrolling)
2030 /* If we are unrolling, initialization is done in the original loop
2031 body (number 0). */
2032 return n_copy;
2034 else
2036 /* If we are peeling, the copy in that the initialization occurs has
2037 number 1. The original loop (number 0) is the last. */
2038 if (n_copy)
2039 return n_copy - 1;
2040 else
2041 return n_copies;
2045 /* Locate in EXPR the expression corresponding to the location recorded
2046 in IVTS, and return a pointer to the RTX for this location. */
2048 static rtx *
2049 get_ivts_expr (rtx expr, struct iv_to_split *ivts)
2051 unsigned i;
2052 rtx *ret = &expr;
2054 for (i = 0; i < ivts->n_loc; i++)
2055 ret = &XEXP (*ret, ivts->loc[i]);
2057 return ret;
2060 /* Allocate basic variable for the induction variable chain. */
2062 static void
2063 allocate_basic_variable (struct iv_to_split *ivts)
2065 rtx expr = *get_ivts_expr (single_set (ivts->insn), ivts);
2067 ivts->base_var = gen_reg_rtx (GET_MODE (expr));
2070 /* Insert initialization of basic variable of IVTS before INSN, taking
2071 the initial value from INSN. */
2073 static void
2074 insert_base_initialization (struct iv_to_split *ivts, rtx insn)
2076 rtx expr = copy_rtx (*get_ivts_expr (single_set (insn), ivts));
2077 rtx seq;
2079 start_sequence ();
2080 expr = force_operand (expr, ivts->base_var);
2081 if (expr != ivts->base_var)
2082 emit_move_insn (ivts->base_var, expr);
2083 seq = get_insns ();
2084 end_sequence ();
2086 emit_insn_before (seq, insn);
2089 /* Replace the use of induction variable described in IVTS in INSN
2090 by base variable + DELTA * step. */
2092 static void
2093 split_iv (struct iv_to_split *ivts, rtx insn, unsigned delta)
2095 rtx expr, *loc, seq, incr, var;
2096 enum machine_mode mode = GET_MODE (ivts->base_var);
2097 rtx src, dest, set;
2099 /* Construct base + DELTA * step. */
2100 if (!delta)
2101 expr = ivts->base_var;
2102 else
2104 incr = simplify_gen_binary (MULT, mode,
2105 ivts->step, gen_int_mode (delta, mode));
2106 expr = simplify_gen_binary (PLUS, GET_MODE (ivts->base_var),
2107 ivts->base_var, incr);
2110 /* Figure out where to do the replacement. */
2111 loc = get_ivts_expr (single_set (insn), ivts);
2113 /* If we can make the replacement right away, we're done. */
2114 if (validate_change (insn, loc, expr, 0))
2115 return;
2117 /* Otherwise, force EXPR into a register and try again. */
2118 start_sequence ();
2119 var = gen_reg_rtx (mode);
2120 expr = force_operand (expr, var);
2121 if (expr != var)
2122 emit_move_insn (var, expr);
2123 seq = get_insns ();
2124 end_sequence ();
2125 emit_insn_before (seq, insn);
2127 if (validate_change (insn, loc, var, 0))
2128 return;
2130 /* The last chance. Try recreating the assignment in insn
2131 completely from scratch. */
2132 set = single_set (insn);
2133 gcc_assert (set);
2135 start_sequence ();
2136 *loc = var;
2137 src = copy_rtx (SET_SRC (set));
2138 dest = copy_rtx (SET_DEST (set));
2139 src = force_operand (src, dest);
2140 if (src != dest)
2141 emit_move_insn (dest, src);
2142 seq = get_insns ();
2143 end_sequence ();
2145 emit_insn_before (seq, insn);
2146 delete_insn (insn);
2150 /* Return one expansion of the accumulator recorded in struct VE. */
2152 static rtx
2153 get_expansion (struct var_to_expand *ve)
2155 rtx reg;
2157 if (ve->reuse_expansion == 0)
2158 reg = ve->reg;
2159 else
2160 reg = ve->var_expansions[ve->reuse_expansion - 1];
2162 if (ve->var_expansions.length () == (unsigned) ve->reuse_expansion)
2163 ve->reuse_expansion = 0;
2164 else
2165 ve->reuse_expansion++;
2167 return reg;
2171 /* Given INSN replace the uses of the accumulator recorded in VE
2172 with a new register. */
2174 static void
2175 expand_var_during_unrolling (struct var_to_expand *ve, rtx insn)
2177 rtx new_reg, set;
2178 bool really_new_expansion = false;
2180 set = single_set (insn);
2181 gcc_assert (set);
2183 /* Generate a new register only if the expansion limit has not been
2184 reached. Else reuse an already existing expansion. */
2185 if (PARAM_VALUE (PARAM_MAX_VARIABLE_EXPANSIONS) > ve->expansion_count)
2187 really_new_expansion = true;
2188 new_reg = gen_reg_rtx (GET_MODE (ve->reg));
2190 else
2191 new_reg = get_expansion (ve);
2193 validate_replace_rtx_group (SET_DEST (set), new_reg, insn);
2194 if (apply_change_group ())
2195 if (really_new_expansion)
2197 ve->var_expansions.safe_push (new_reg);
2198 ve->expansion_count++;
2202 /* Initialize the variable expansions in loop preheader. PLACE is the
2203 loop-preheader basic block where the initialization of the
2204 expansions should take place. The expansions are initialized with
2205 (-0) when the operation is plus or minus to honor sign zero. This
2206 way we can prevent cases where the sign of the final result is
2207 effected by the sign of the expansion. Here is an example to
2208 demonstrate this:
2210 for (i = 0 ; i < n; i++)
2211 sum += something;
2215 sum += something
2216 ....
2217 i = i+1;
2218 sum1 += something
2219 ....
2220 i = i+1
2221 sum2 += something;
2222 ....
2224 When SUM is initialized with -zero and SOMETHING is also -zero; the
2225 final result of sum should be -zero thus the expansions sum1 and sum2
2226 should be initialized with -zero as well (otherwise we will get +zero
2227 as the final result). */
2229 static void
2230 insert_var_expansion_initialization (struct var_to_expand *ve,
2231 basic_block place)
2233 rtx seq, var, zero_init;
2234 unsigned i;
2235 enum machine_mode mode = GET_MODE (ve->reg);
2236 bool honor_signed_zero_p = HONOR_SIGNED_ZEROS (mode);
2238 if (ve->var_expansions.length () == 0)
2239 return;
2241 start_sequence ();
2242 switch (ve->op)
2244 case FMA:
2245 /* Note that we only accumulate FMA via the ADD operand. */
2246 case PLUS:
2247 case MINUS:
2248 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
2250 if (honor_signed_zero_p)
2251 zero_init = simplify_gen_unary (NEG, mode, CONST0_RTX (mode), mode);
2252 else
2253 zero_init = CONST0_RTX (mode);
2254 emit_move_insn (var, zero_init);
2256 break;
2258 case MULT:
2259 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
2261 zero_init = CONST1_RTX (GET_MODE (var));
2262 emit_move_insn (var, zero_init);
2264 break;
2266 default:
2267 gcc_unreachable ();
2270 seq = get_insns ();
2271 end_sequence ();
2273 emit_insn_after (seq, BB_END (place));
2276 /* Combine the variable expansions at the loop exit. PLACE is the
2277 loop exit basic block where the summation of the expansions should
2278 take place. */
2280 static void
2281 combine_var_copies_in_loop_exit (struct var_to_expand *ve, basic_block place)
2283 rtx sum = ve->reg;
2284 rtx expr, seq, var, insn;
2285 unsigned i;
2287 if (ve->var_expansions.length () == 0)
2288 return;
2290 start_sequence ();
2291 switch (ve->op)
2293 case FMA:
2294 /* Note that we only accumulate FMA via the ADD operand. */
2295 case PLUS:
2296 case MINUS:
2297 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
2298 sum = simplify_gen_binary (PLUS, GET_MODE (ve->reg), var, sum);
2299 break;
2301 case MULT:
2302 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
2303 sum = simplify_gen_binary (MULT, GET_MODE (ve->reg), var, sum);
2304 break;
2306 default:
2307 gcc_unreachable ();
2310 expr = force_operand (sum, ve->reg);
2311 if (expr != ve->reg)
2312 emit_move_insn (ve->reg, expr);
2313 seq = get_insns ();
2314 end_sequence ();
2316 insn = BB_HEAD (place);
2317 while (!NOTE_INSN_BASIC_BLOCK_P (insn))
2318 insn = NEXT_INSN (insn);
2320 emit_insn_after (seq, insn);
2323 /* Strip away REG_EQUAL notes for IVs we're splitting.
2325 Updating REG_EQUAL notes for IVs we split is tricky: We
2326 cannot tell until after unrolling, DF-rescanning, and liveness
2327 updating, whether an EQ_USE is reached by the split IV while
2328 the IV reg is still live. See PR55006.
2330 ??? We cannot use remove_reg_equal_equiv_notes_for_regno,
2331 because RTL loop-iv requires us to defer rescanning insns and
2332 any notes attached to them. So resort to old techniques... */
2334 static void
2335 maybe_strip_eq_note_for_split_iv (struct opt_info *opt_info, rtx insn)
2337 struct iv_to_split *ivts;
2338 rtx note = find_reg_equal_equiv_note (insn);
2339 if (! note)
2340 return;
2341 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
2342 if (reg_mentioned_p (ivts->orig_var, note))
2344 remove_note (insn, note);
2345 return;
2349 /* Apply loop optimizations in loop copies using the
2350 data which gathered during the unrolling. Structure
2351 OPT_INFO record that data.
2353 UNROLLING is true if we unrolled (not peeled) the loop.
2354 REWRITE_ORIGINAL_BODY is true if we should also rewrite the original body of
2355 the loop (as it should happen in complete unrolling, but not in ordinary
2356 peeling of the loop). */
2358 static void
2359 apply_opt_in_copies (struct opt_info *opt_info,
2360 unsigned n_copies, bool unrolling,
2361 bool rewrite_original_loop)
2363 unsigned i, delta;
2364 basic_block bb, orig_bb;
2365 rtx insn, orig_insn, next;
2366 struct iv_to_split ivts_templ, *ivts;
2367 struct var_to_expand ve_templ, *ves;
2369 /* Sanity check -- we need to put initialization in the original loop
2370 body. */
2371 gcc_assert (!unrolling || rewrite_original_loop);
2373 /* Allocate the basic variables (i0). */
2374 if (opt_info->insns_to_split.is_created ())
2375 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
2376 allocate_basic_variable (ivts);
2378 for (i = opt_info->first_new_block; i < (unsigned) last_basic_block; i++)
2380 bb = BASIC_BLOCK (i);
2381 orig_bb = get_bb_original (bb);
2383 /* bb->aux holds position in copy sequence initialized by
2384 duplicate_loop_to_header_edge. */
2385 delta = determine_split_iv_delta ((size_t)bb->aux, n_copies,
2386 unrolling);
2387 bb->aux = 0;
2388 orig_insn = BB_HEAD (orig_bb);
2389 FOR_BB_INSNS_SAFE (bb, insn, next)
2391 if (!INSN_P (insn)
2392 || (DEBUG_INSN_P (insn)
2393 && TREE_CODE (INSN_VAR_LOCATION_DECL (insn)) == LABEL_DECL))
2394 continue;
2396 while (!INSN_P (orig_insn)
2397 || (DEBUG_INSN_P (orig_insn)
2398 && (TREE_CODE (INSN_VAR_LOCATION_DECL (orig_insn))
2399 == LABEL_DECL)))
2400 orig_insn = NEXT_INSN (orig_insn);
2402 ivts_templ.insn = orig_insn;
2403 ve_templ.insn = orig_insn;
2405 /* Apply splitting iv optimization. */
2406 if (opt_info->insns_to_split.is_created ())
2408 maybe_strip_eq_note_for_split_iv (opt_info, insn);
2410 ivts = opt_info->insns_to_split.find (&ivts_templ);
2412 if (ivts)
2414 gcc_assert (GET_CODE (PATTERN (insn))
2415 == GET_CODE (PATTERN (orig_insn)));
2417 if (!delta)
2418 insert_base_initialization (ivts, insn);
2419 split_iv (ivts, insn, delta);
2422 /* Apply variable expansion optimization. */
2423 if (unrolling && opt_info->insns_with_var_to_expand.is_created ())
2425 ves = (struct var_to_expand *)
2426 opt_info->insns_with_var_to_expand.find (&ve_templ);
2427 if (ves)
2429 gcc_assert (GET_CODE (PATTERN (insn))
2430 == GET_CODE (PATTERN (orig_insn)));
2431 expand_var_during_unrolling (ves, insn);
2434 orig_insn = NEXT_INSN (orig_insn);
2438 if (!rewrite_original_loop)
2439 return;
2441 /* Initialize the variable expansions in the loop preheader
2442 and take care of combining them at the loop exit. */
2443 if (opt_info->insns_with_var_to_expand.is_created ())
2445 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2446 insert_var_expansion_initialization (ves, opt_info->loop_preheader);
2447 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2448 combine_var_copies_in_loop_exit (ves, opt_info->loop_exit);
2451 /* Rewrite also the original loop body. Find them as originals of the blocks
2452 in the last copied iteration, i.e. those that have
2453 get_bb_copy (get_bb_original (bb)) == bb. */
2454 for (i = opt_info->first_new_block; i < (unsigned) last_basic_block; i++)
2456 bb = BASIC_BLOCK (i);
2457 orig_bb = get_bb_original (bb);
2458 if (get_bb_copy (orig_bb) != bb)
2459 continue;
2461 delta = determine_split_iv_delta (0, n_copies, unrolling);
2462 for (orig_insn = BB_HEAD (orig_bb);
2463 orig_insn != NEXT_INSN (BB_END (bb));
2464 orig_insn = next)
2466 next = NEXT_INSN (orig_insn);
2468 if (!INSN_P (orig_insn))
2469 continue;
2471 ivts_templ.insn = orig_insn;
2472 if (opt_info->insns_to_split.is_created ())
2474 maybe_strip_eq_note_for_split_iv (opt_info, orig_insn);
2476 ivts = (struct iv_to_split *)
2477 opt_info->insns_to_split.find (&ivts_templ);
2478 if (ivts)
2480 if (!delta)
2481 insert_base_initialization (ivts, orig_insn);
2482 split_iv (ivts, orig_insn, delta);
2483 continue;
2491 /* Release OPT_INFO. */
2493 static void
2494 free_opt_info (struct opt_info *opt_info)
2496 if (opt_info->insns_to_split.is_created ())
2497 opt_info->insns_to_split.dispose ();
2498 if (opt_info->insns_with_var_to_expand.is_created ())
2500 struct var_to_expand *ves;
2502 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2503 ves->var_expansions.release ();
2504 opt_info->insns_with_var_to_expand.dispose ();
2506 free (opt_info);