1 /* Induction variable optimizations.
2 Copyright (C) 2003-2024 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
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 /* This pass tries to find the optimal set of induction variables for the loop.
21 It optimizes just the basic linear induction variables (although adding
22 support for other types should not be too hard). It includes the
23 optimizations commonly known as strength reduction, induction variable
24 coalescing and induction variable elimination. It does it in the
27 1) The interesting uses of induction variables are found. This includes
29 -- uses of induction variables in non-linear expressions
30 -- addresses of arrays
31 -- comparisons of induction variables
33 Note the interesting uses are categorized and handled in group.
34 Generally, address type uses are grouped together if their iv bases
35 are different in constant offset.
37 2) Candidates for the induction variables are found. This includes
39 -- old induction variables
40 -- the variables defined by expressions derived from the "interesting
43 3) The optimal (w.r. to a cost function) set of variables is chosen. The
44 cost function assigns a cost to sets of induction variables and consists
47 -- The group/use costs. Each of the interesting groups/uses chooses
48 the best induction variable in the set and adds its cost to the sum.
49 The cost reflects the time spent on modifying the induction variables
50 value to be usable for the given purpose (adding base and offset for
52 -- The variable costs. Each of the variables has a cost assigned that
53 reflects the costs associated with incrementing the value of the
54 variable. The original variables are somewhat preferred.
55 -- The set cost. Depending on the size of the set, extra cost may be
56 added to reflect register pressure.
58 All the costs are defined in a machine-specific way, using the target
59 hooks and machine descriptions to determine them.
61 4) The trees are transformed to use the new variables, the dead code is
64 All of this is done loop by loop. Doing it globally is theoretically
65 possible, it might give a better performance and it might enable us
66 to decide costs more precisely, but getting all the interactions right
69 For the targets supporting low-overhead loops, IVOPTs has to take care of
70 the loops which will probably be transformed in RTL doloop optimization,
71 to try to make selected IV candidate set optimal. The process of doloop
74 1) Analyze the current loop will be transformed to doloop or not, find and
75 mark its compare type IV use as doloop use (iv_group field doloop_p), and
76 set flag doloop_use_p of ivopts_data to notify subsequent processings on
77 doloop. See analyze_and_mark_doloop_use and its callees for the details.
78 The target hook predict_doloop_p can be used for target specific checks.
80 2) Add one doloop dedicated IV cand {(may_be_zero ? 1 : (niter + 1)), +, -1},
81 set flag doloop_p of iv_cand, step cost is set as zero and no extra cost
82 like biv. For cost determination between doloop IV cand and IV use, the
83 target hooks doloop_cost_for_generic and doloop_cost_for_address are
84 provided to add on extra costs for generic type and address type IV use.
85 Zero cost is assigned to the pair between doloop IV cand and doloop IV
86 use, and bound zero is set for IV elimination.
88 3) With the cost setting in step 2), the current cost model based IV
89 selection algorithm will process as usual, pick up doloop dedicated IV if
94 #include "coretypes.h"
100 #include "tree-pass.h"
101 #include "memmodel.h"
105 #include "insn-config.h"
106 #include "emit-rtl.h"
109 #include "gimple-pretty-print.h"
111 #include "fold-const.h"
112 #include "stor-layout.h"
114 #include "gimplify.h"
115 #include "gimple-iterator.h"
116 #include "gimplify-me.h"
117 #include "tree-cfg.h"
118 #include "tree-ssa-loop-ivopts.h"
119 #include "tree-ssa-loop-manip.h"
120 #include "tree-ssa-loop-niter.h"
121 #include "tree-ssa-loop.h"
124 #include "tree-dfa.h"
125 #include "tree-ssa.h"
127 #include "tree-scalar-evolution.h"
128 #include "tree-affine.h"
129 #include "tree-ssa-propagate.h"
130 #include "tree-ssa-address.h"
131 #include "builtins.h"
132 #include "tree-vectorizer.h"
136 /* For lang_hooks.types.type_for_mode. */
137 #include "langhooks.h"
139 /* FIXME: Expressions are expanded to RTL in this pass to determine the
140 cost of different addressing modes. This should be moved to a TBD
141 interface between the GIMPLE and RTL worlds. */
143 /* The infinite cost. */
144 #define INFTY 1000000000
146 /* Returns the expected number of loop iterations for LOOP.
147 The average trip count is computed from profile data if it
150 static inline HOST_WIDE_INT
151 avg_loop_niter (class loop
*loop
)
153 HOST_WIDE_INT niter
= estimated_stmt_executions_int (loop
);
156 niter
= likely_max_stmt_executions_int (loop
);
158 if (niter
== -1 || niter
> param_avg_loop_niter
)
159 return param_avg_loop_niter
;
167 /* Representation of the induction variable. */
170 tree base
; /* Initial value of the iv. */
171 tree base_object
; /* A memory object to that the induction variable points. */
172 tree step
; /* Step of the iv (constant only). */
173 tree ssa_name
; /* The ssa name with the value. */
174 struct iv_use
*nonlin_use
; /* The identifier in the use if it is the case. */
175 bool biv_p
; /* Is it a biv? */
176 bool no_overflow
; /* True if the iv doesn't overflow. */
177 bool have_address_use
;/* For biv, indicate if it's used in any address
181 /* Per-ssa version information (induction variable descriptions, etc.). */
184 tree name
; /* The ssa name. */
185 struct iv
*iv
; /* Induction variable description. */
186 bool has_nonlin_use
; /* For a loop-level invariant, whether it is used in
187 an expression that is not an induction variable. */
188 bool preserve_biv
; /* For the original biv, whether to preserve it. */
189 unsigned inv_id
; /* Id of an invariant. */
195 USE_NONLINEAR_EXPR
, /* Use in a nonlinear expression. */
196 USE_REF_ADDRESS
, /* Use is an address for an explicit memory
198 USE_PTR_ADDRESS
, /* Use is a pointer argument to a function in
199 cases where the expansion of the function
200 will turn the argument into a normal address. */
201 USE_COMPARE
/* Use is a compare. */
204 /* Cost of a computation. */
208 comp_cost (): cost (0), complexity (0), scratch (0)
211 comp_cost (int64_t cost
, unsigned complexity
, int64_t scratch
= 0)
212 : cost (cost
), complexity (complexity
), scratch (scratch
)
215 /* Returns true if COST is infinite. */
216 bool infinite_cost_p ();
218 /* Adds costs COST1 and COST2. */
219 friend comp_cost
operator+ (comp_cost cost1
, comp_cost cost2
);
221 /* Adds COST to the comp_cost. */
222 comp_cost
operator+= (comp_cost cost
);
224 /* Adds constant C to this comp_cost. */
225 comp_cost
operator+= (HOST_WIDE_INT c
);
227 /* Subtracts constant C to this comp_cost. */
228 comp_cost
operator-= (HOST_WIDE_INT c
);
230 /* Divide the comp_cost by constant C. */
231 comp_cost
operator/= (HOST_WIDE_INT c
);
233 /* Multiply the comp_cost by constant C. */
234 comp_cost
operator*= (HOST_WIDE_INT c
);
236 /* Subtracts costs COST1 and COST2. */
237 friend comp_cost
operator- (comp_cost cost1
, comp_cost cost2
);
239 /* Subtracts COST from this comp_cost. */
240 comp_cost
operator-= (comp_cost cost
);
242 /* Returns true if COST1 is smaller than COST2. */
243 friend bool operator< (comp_cost cost1
, comp_cost cost2
);
245 /* Returns true if COST1 and COST2 are equal. */
246 friend bool operator== (comp_cost cost1
, comp_cost cost2
);
248 /* Returns true if COST1 is smaller or equal than COST2. */
249 friend bool operator<= (comp_cost cost1
, comp_cost cost2
);
251 int64_t cost
; /* The runtime cost. */
252 unsigned complexity
; /* The estimate of the complexity of the code for
253 the computation (in no concrete units --
254 complexity field should be larger for more
255 complex expressions and addressing modes). */
256 int64_t scratch
; /* Scratch used during cost computation. */
259 static const comp_cost no_cost
;
260 static const comp_cost
infinite_cost (INFTY
, 0, INFTY
);
263 comp_cost::infinite_cost_p ()
265 return cost
== INFTY
;
269 operator+ (comp_cost cost1
, comp_cost cost2
)
271 if (cost1
.infinite_cost_p () || cost2
.infinite_cost_p ())
272 return infinite_cost
;
274 gcc_assert (cost1
.cost
+ cost2
.cost
< infinite_cost
.cost
);
275 cost1
.cost
+= cost2
.cost
;
276 cost1
.complexity
+= cost2
.complexity
;
282 operator- (comp_cost cost1
, comp_cost cost2
)
284 if (cost1
.infinite_cost_p ())
285 return infinite_cost
;
287 gcc_assert (!cost2
.infinite_cost_p ());
288 gcc_assert (cost1
.cost
- cost2
.cost
< infinite_cost
.cost
);
290 cost1
.cost
-= cost2
.cost
;
291 cost1
.complexity
-= cost2
.complexity
;
297 comp_cost::operator+= (comp_cost cost
)
299 *this = *this + cost
;
304 comp_cost::operator+= (HOST_WIDE_INT c
)
309 if (infinite_cost_p ())
312 gcc_assert (this->cost
+ c
< infinite_cost
.cost
);
319 comp_cost::operator-= (HOST_WIDE_INT c
)
321 if (infinite_cost_p ())
324 gcc_assert (this->cost
- c
< infinite_cost
.cost
);
331 comp_cost::operator/= (HOST_WIDE_INT c
)
334 if (infinite_cost_p ())
343 comp_cost::operator*= (HOST_WIDE_INT c
)
345 if (infinite_cost_p ())
348 gcc_assert (this->cost
* c
< infinite_cost
.cost
);
355 comp_cost::operator-= (comp_cost cost
)
357 *this = *this - cost
;
362 operator< (comp_cost cost1
, comp_cost cost2
)
364 if (cost1
.cost
== cost2
.cost
)
365 return cost1
.complexity
< cost2
.complexity
;
367 return cost1
.cost
< cost2
.cost
;
371 operator== (comp_cost cost1
, comp_cost cost2
)
373 return cost1
.cost
== cost2
.cost
374 && cost1
.complexity
== cost2
.complexity
;
378 operator<= (comp_cost cost1
, comp_cost cost2
)
380 return cost1
< cost2
|| cost1
== cost2
;
383 struct iv_inv_expr_ent
;
385 /* The candidate - cost pair. */
389 struct iv_cand
*cand
; /* The candidate. */
390 comp_cost cost
; /* The cost. */
391 enum tree_code comp
; /* For iv elimination, the comparison. */
392 bitmap inv_vars
; /* The list of invariant ssa_vars that have to be
393 preserved when representing iv_use with iv_cand. */
394 bitmap inv_exprs
; /* The list of newly created invariant expressions
395 when representing iv_use with iv_cand. */
396 tree value
; /* For final value elimination, the expression for
397 the final value of the iv. For iv elimination,
398 the new bound to compare with. */
404 unsigned id
; /* The id of the use. */
405 unsigned group_id
; /* The group id the use belongs to. */
406 enum use_type type
; /* Type of the use. */
407 tree mem_type
; /* The memory type to use when testing whether an
408 address is legitimate, and what the address's
410 struct iv
*iv
; /* The induction variable it is based on. */
411 gimple
*stmt
; /* Statement in that it occurs. */
412 tree
*op_p
; /* The place where it occurs. */
414 tree addr_base
; /* Base address with const offset stripped. */
415 poly_uint64 addr_offset
;
416 /* Const offset stripped from base address. */
422 /* The id of the group. */
424 /* Uses of the group are of the same type. */
426 /* The set of "related" IV candidates, plus the important ones. */
427 bitmap related_cands
;
428 /* Number of IV candidates in the cost_map. */
429 unsigned n_map_members
;
430 /* The costs wrto the iv candidates. */
431 class cost_pair
*cost_map
;
432 /* The selected candidate for the group. */
433 struct iv_cand
*selected
;
434 /* To indicate this is a doloop use group. */
436 /* Uses in the group. */
437 vec
<struct iv_use
*> vuses
;
440 /* The position where the iv is computed. */
443 IP_NORMAL
, /* At the end, just before the exit condition. */
444 IP_END
, /* At the end of the latch block. */
445 IP_BEFORE_USE
, /* Immediately before a specific use. */
446 IP_AFTER_USE
, /* Immediately after a specific use. */
447 IP_ORIGINAL
/* The original biv. */
450 /* The induction variable candidate. */
453 unsigned id
; /* The number of the candidate. */
454 bool important
; /* Whether this is an "important" candidate, i.e. such
455 that it should be considered by all uses. */
456 bool involves_undefs
; /* Whether the IV involves undefined values. */
457 ENUM_BITFIELD(iv_position
) pos
: 8; /* Where it is computed. */
458 gimple
*incremented_at
;/* For original biv, the statement where it is
460 tree var_before
; /* The variable used for it before increment. */
461 tree var_after
; /* The variable used for it after increment. */
462 struct iv
*iv
; /* The value of the candidate. NULL for
463 "pseudocandidate" used to indicate the possibility
464 to replace the final value of an iv by direct
465 computation of the value. */
466 unsigned cost
; /* Cost of the candidate. */
467 unsigned cost_step
; /* Cost of the candidate's increment operation. */
468 struct iv_use
*ainc_use
; /* For IP_{BEFORE,AFTER}_USE candidates, the place
469 where it is incremented. */
470 bitmap inv_vars
; /* The list of invariant ssa_vars used in step of the
472 bitmap inv_exprs
; /* If step is more complicated than a single ssa_var,
473 handle it as a new invariant expression which will
474 be hoisted out of loop. */
475 struct iv
*orig_iv
; /* The original iv if this cand is added from biv with
477 bool doloop_p
; /* Whether this is a doloop candidate. */
480 /* Hashtable entry for common candidate derived from iv uses. */
486 /* IV uses from which this common candidate is derived. */
487 auto_vec
<struct iv_use
*> uses
;
491 /* Hashtable helpers. */
493 struct iv_common_cand_hasher
: delete_ptr_hash
<iv_common_cand
>
495 static inline hashval_t
hash (const iv_common_cand
*);
496 static inline bool equal (const iv_common_cand
*, const iv_common_cand
*);
499 /* Hash function for possible common candidates. */
502 iv_common_cand_hasher::hash (const iv_common_cand
*ccand
)
507 /* Hash table equality function for common candidates. */
510 iv_common_cand_hasher::equal (const iv_common_cand
*ccand1
,
511 const iv_common_cand
*ccand2
)
513 return (ccand1
->hash
== ccand2
->hash
514 && operand_equal_p (ccand1
->base
, ccand2
->base
, 0)
515 && operand_equal_p (ccand1
->step
, ccand2
->step
, 0)
516 && (TYPE_PRECISION (TREE_TYPE (ccand1
->base
))
517 == TYPE_PRECISION (TREE_TYPE (ccand2
->base
))));
520 /* Loop invariant expression hashtable entry. */
522 struct iv_inv_expr_ent
524 /* Tree expression of the entry. */
526 /* Unique indentifier. */
532 /* Sort iv_inv_expr_ent pair A and B by id field. */
535 sort_iv_inv_expr_ent (const void *a
, const void *b
)
537 const iv_inv_expr_ent
* const *e1
= (const iv_inv_expr_ent
* const *) (a
);
538 const iv_inv_expr_ent
* const *e2
= (const iv_inv_expr_ent
* const *) (b
);
540 unsigned id1
= (*e1
)->id
;
541 unsigned id2
= (*e2
)->id
;
551 /* Hashtable helpers. */
553 struct iv_inv_expr_hasher
: free_ptr_hash
<iv_inv_expr_ent
>
555 static inline hashval_t
hash (const iv_inv_expr_ent
*);
556 static inline bool equal (const iv_inv_expr_ent
*, const iv_inv_expr_ent
*);
559 /* Return true if uses of type TYPE represent some form of address. */
562 address_p (use_type type
)
564 return type
== USE_REF_ADDRESS
|| type
== USE_PTR_ADDRESS
;
567 /* Hash function for loop invariant expressions. */
570 iv_inv_expr_hasher::hash (const iv_inv_expr_ent
*expr
)
575 /* Hash table equality function for expressions. */
578 iv_inv_expr_hasher::equal (const iv_inv_expr_ent
*expr1
,
579 const iv_inv_expr_ent
*expr2
)
581 return expr1
->hash
== expr2
->hash
582 && operand_equal_p (expr1
->expr
, expr2
->expr
, 0);
587 /* The currently optimized loop. */
588 class loop
*current_loop
;
591 /* Numbers of iterations for all exits of the current loop. */
592 hash_map
<edge
, tree_niter_desc
*> *niters
;
594 /* Number of registers used in it. */
597 /* The size of version_info array allocated. */
598 unsigned version_info_size
;
600 /* The array of information for the ssa names. */
601 struct version_info
*version_info
;
603 /* The hashtable of loop invariant expressions created
605 hash_table
<iv_inv_expr_hasher
> *inv_expr_tab
;
607 /* The bitmap of indices in version_info whose value was changed. */
610 /* The uses of induction variables. */
611 vec
<iv_group
*> vgroups
;
613 /* The candidates. */
614 vec
<iv_cand
*> vcands
;
616 /* A bitmap of important candidates. */
617 bitmap important_candidates
;
619 /* Cache used by tree_to_aff_combination_expand. */
620 hash_map
<tree
, name_expansion
*> *name_expansion_cache
;
622 /* The hashtable of common candidates derived from iv uses. */
623 hash_table
<iv_common_cand_hasher
> *iv_common_cand_tab
;
625 /* The common candidates. */
626 vec
<iv_common_cand
*> iv_common_cands
;
628 /* Hash map recording base object information of tree exp. */
629 hash_map
<tree
, tree
> *base_object_map
;
631 /* The maximum invariant variable id. */
632 unsigned max_inv_var_id
;
634 /* The maximum invariant expression id. */
635 unsigned max_inv_expr_id
;
637 /* Number of no_overflow BIVs which are not used in memory address. */
638 unsigned bivs_not_used_in_addr
;
640 /* Obstack for iv structure. */
641 struct obstack iv_obstack
;
643 /* Whether to consider just related and important candidates when replacing a
645 bool consider_all_candidates
;
647 /* Are we optimizing for speed? */
650 /* Whether the loop body includes any function calls. */
651 bool body_includes_call
;
653 /* Whether the loop body can only be exited via single exit. */
654 bool loop_single_exit_p
;
656 /* Whether the loop has doloop comparison use. */
660 /* An assignment of iv candidates to uses. */
665 /* The number of uses covered by the assignment. */
668 /* Number of uses that cannot be expressed by the candidates in the set. */
671 /* Candidate assigned to a use, together with the related costs. */
672 class cost_pair
**cand_for_group
;
674 /* Number of times each candidate is used. */
675 unsigned *n_cand_uses
;
677 /* The candidates used. */
680 /* The number of candidates in the set. */
683 /* The number of invariants needed, including both invariant variants and
684 invariant expressions. */
687 /* Total cost of expressing uses. */
688 comp_cost cand_use_cost
;
690 /* Total cost of candidates. */
693 /* Number of times each invariant variable is used. */
694 unsigned *n_inv_var_uses
;
696 /* Number of times each invariant expression is used. */
697 unsigned *n_inv_expr_uses
;
699 /* Total cost of the assignment. */
703 /* Difference of two iv candidate assignments. */
708 struct iv_group
*group
;
710 /* An old assignment (for rollback purposes). */
711 class cost_pair
*old_cp
;
713 /* A new assignment. */
714 class cost_pair
*new_cp
;
716 /* Next change in the list. */
717 struct iv_ca_delta
*next
;
720 /* Bound on number of candidates below that all candidates are considered. */
722 #define CONSIDER_ALL_CANDIDATES_BOUND \
723 ((unsigned) param_iv_consider_all_candidates_bound)
725 /* If there are more iv occurrences, we just give up (it is quite unlikely that
726 optimizing such a loop would help, and it would take ages). */
728 #define MAX_CONSIDERED_GROUPS \
729 ((unsigned) param_iv_max_considered_uses)
731 /* If there are at most this number of ivs in the set, try removing unnecessary
732 ivs from the set always. */
734 #define ALWAYS_PRUNE_CAND_SET_BOUND \
735 ((unsigned) param_iv_always_prune_cand_set_bound)
737 /* The list of trees for that the decl_rtl field must be reset is stored
740 static vec
<tree
> decl_rtl_to_reset
;
742 static comp_cost
force_expr_to_var_cost (tree
, bool);
744 /* The single loop exit if it dominates the latch, NULL otherwise. */
747 single_dom_exit (class loop
*loop
)
749 edge exit
= single_exit (loop
);
754 if (!just_once_each_iteration_p (loop
, exit
->src
))
760 /* Dumps information about the induction variable IV to FILE. Don't dump
761 variable's name if DUMP_NAME is FALSE. The information is dumped with
762 preceding spaces indicated by INDENT_LEVEL. */
765 dump_iv (FILE *file
, struct iv
*iv
, bool dump_name
, unsigned indent_level
)
768 const char spaces
[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'};
770 if (indent_level
> 4)
772 p
= spaces
+ 8 - (indent_level
<< 1);
774 fprintf (file
, "%sIV struct:\n", p
);
775 if (iv
->ssa_name
&& dump_name
)
777 fprintf (file
, "%s SSA_NAME:\t", p
);
778 print_generic_expr (file
, iv
->ssa_name
, TDF_SLIM
);
779 fprintf (file
, "\n");
782 fprintf (file
, "%s Type:\t", p
);
783 print_generic_expr (file
, TREE_TYPE (iv
->base
), TDF_SLIM
);
784 fprintf (file
, "\n");
786 fprintf (file
, "%s Base:\t", p
);
787 print_generic_expr (file
, iv
->base
, TDF_SLIM
);
788 fprintf (file
, "\n");
790 fprintf (file
, "%s Step:\t", p
);
791 print_generic_expr (file
, iv
->step
, TDF_SLIM
);
792 fprintf (file
, "\n");
796 fprintf (file
, "%s Object:\t", p
);
797 print_generic_expr (file
, iv
->base_object
, TDF_SLIM
);
798 fprintf (file
, "\n");
801 fprintf (file
, "%s Biv:\t%c\n", p
, iv
->biv_p
? 'Y' : 'N');
803 fprintf (file
, "%s Overflowness wrto loop niter:\t%s\n",
804 p
, iv
->no_overflow
? "No-overflow" : "Overflow");
807 /* Dumps information about the USE to FILE. */
810 dump_use (FILE *file
, struct iv_use
*use
)
812 fprintf (file
, " Use %d.%d:\n", use
->group_id
, use
->id
);
813 fprintf (file
, " At stmt:\t");
814 print_gimple_stmt (file
, use
->stmt
, 0);
815 fprintf (file
, " At pos:\t");
817 print_generic_expr (file
, *use
->op_p
, TDF_SLIM
);
818 fprintf (file
, "\n");
819 dump_iv (file
, use
->iv
, false, 2);
822 /* Dumps information about the uses to FILE. */
825 dump_groups (FILE *file
, struct ivopts_data
*data
)
828 struct iv_group
*group
;
830 for (i
= 0; i
< data
->vgroups
.length (); i
++)
832 group
= data
->vgroups
[i
];
833 fprintf (file
, "Group %d:\n", group
->id
);
834 if (group
->type
== USE_NONLINEAR_EXPR
)
835 fprintf (file
, " Type:\tGENERIC\n");
836 else if (group
->type
== USE_REF_ADDRESS
)
837 fprintf (file
, " Type:\tREFERENCE ADDRESS\n");
838 else if (group
->type
== USE_PTR_ADDRESS
)
839 fprintf (file
, " Type:\tPOINTER ARGUMENT ADDRESS\n");
842 gcc_assert (group
->type
== USE_COMPARE
);
843 fprintf (file
, " Type:\tCOMPARE\n");
845 for (j
= 0; j
< group
->vuses
.length (); j
++)
846 dump_use (file
, group
->vuses
[j
]);
850 /* Dumps information about induction variable candidate CAND to FILE. */
853 dump_cand (FILE *file
, struct iv_cand
*cand
)
855 struct iv
*iv
= cand
->iv
;
857 fprintf (file
, "Candidate %d:\n", cand
->id
);
860 fprintf (file
, " Depend on inv.vars: ");
861 dump_bitmap (file
, cand
->inv_vars
);
865 fprintf (file
, " Depend on inv.exprs: ");
866 dump_bitmap (file
, cand
->inv_exprs
);
869 if (cand
->var_before
)
871 fprintf (file
, " Var befor: ");
872 print_generic_expr (file
, cand
->var_before
, TDF_SLIM
);
873 fprintf (file
, "\n");
877 fprintf (file
, " Var after: ");
878 print_generic_expr (file
, cand
->var_after
, TDF_SLIM
);
879 fprintf (file
, "\n");
885 fprintf (file
, " Incr POS: before exit test\n");
889 fprintf (file
, " Incr POS: before use %d\n", cand
->ainc_use
->id
);
893 fprintf (file
, " Incr POS: after use %d\n", cand
->ainc_use
->id
);
897 fprintf (file
, " Incr POS: at end\n");
901 fprintf (file
, " Incr POS: orig biv\n");
905 dump_iv (file
, iv
, false, 1);
908 /* Returns the info for ssa version VER. */
910 static inline struct version_info
*
911 ver_info (struct ivopts_data
*data
, unsigned ver
)
913 return data
->version_info
+ ver
;
916 /* Returns the info for ssa name NAME. */
918 static inline struct version_info
*
919 name_info (struct ivopts_data
*data
, tree name
)
921 return ver_info (data
, SSA_NAME_VERSION (name
));
924 /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
928 stmt_after_ip_normal_pos (class loop
*loop
, gimple
*stmt
)
930 basic_block bb
= ip_normal_pos (loop
), sbb
= gimple_bb (stmt
);
934 if (sbb
== loop
->latch
)
940 return stmt
== last_nondebug_stmt (bb
);
943 /* Returns true if STMT if after the place where the original induction
944 variable CAND is incremented. If TRUE_IF_EQUAL is set, we return true
945 if the positions are identical. */
948 stmt_after_inc_pos (struct iv_cand
*cand
, gimple
*stmt
, bool true_if_equal
)
950 basic_block cand_bb
= gimple_bb (cand
->incremented_at
);
951 basic_block stmt_bb
= gimple_bb (stmt
);
953 if (!dominated_by_p (CDI_DOMINATORS
, stmt_bb
, cand_bb
))
956 if (stmt_bb
!= cand_bb
)
960 && gimple_uid (stmt
) == gimple_uid (cand
->incremented_at
))
962 return gimple_uid (stmt
) > gimple_uid (cand
->incremented_at
);
965 /* Returns true if STMT if after the place where the induction variable
966 CAND is incremented in LOOP. */
969 stmt_after_increment (class loop
*loop
, struct iv_cand
*cand
, gimple
*stmt
)
977 return stmt_after_ip_normal_pos (loop
, stmt
);
981 return stmt_after_inc_pos (cand
, stmt
, false);
984 return stmt_after_inc_pos (cand
, stmt
, true);
991 /* walk_tree callback for contains_abnormal_ssa_name_p. */
994 contains_abnormal_ssa_name_p_1 (tree
*tp
, int *walk_subtrees
, void *)
996 if (TREE_CODE (*tp
) == SSA_NAME
997 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (*tp
))
1006 /* Returns true if EXPR contains a ssa name that occurs in an
1007 abnormal phi node. */
1010 contains_abnormal_ssa_name_p (tree expr
)
1012 return walk_tree_without_duplicates
1013 (&expr
, contains_abnormal_ssa_name_p_1
, NULL
) != NULL_TREE
;
1016 /* Returns the structure describing number of iterations determined from
1017 EXIT of DATA->current_loop, or NULL if something goes wrong. */
1019 static class tree_niter_desc
*
1020 niter_for_exit (struct ivopts_data
*data
, edge exit
)
1022 class tree_niter_desc
*desc
;
1023 tree_niter_desc
**slot
;
1027 data
->niters
= new hash_map
<edge
, tree_niter_desc
*>;
1031 slot
= data
->niters
->get (exit
);
1035 /* Try to determine number of iterations. We cannot safely work with ssa
1036 names that appear in phi nodes on abnormal edges, so that we do not
1037 create overlapping life ranges for them (PR 27283). */
1038 desc
= XNEW (class tree_niter_desc
);
1039 ::new (static_cast<void*> (desc
)) tree_niter_desc ();
1040 if (!number_of_iterations_exit (data
->current_loop
,
1042 || contains_abnormal_ssa_name_p (desc
->niter
))
1044 desc
->~tree_niter_desc ();
1048 data
->niters
->put (exit
, desc
);
1056 /* Returns the structure describing number of iterations determined from
1057 single dominating exit of DATA->current_loop, or NULL if something
1060 static class tree_niter_desc
*
1061 niter_for_single_dom_exit (struct ivopts_data
*data
)
1063 edge exit
= single_dom_exit (data
->current_loop
);
1068 return niter_for_exit (data
, exit
);
1071 /* Initializes data structures used by the iv optimization pass, stored
1075 tree_ssa_iv_optimize_init (struct ivopts_data
*data
)
1077 data
->version_info_size
= 2 * num_ssa_names
;
1078 data
->version_info
= XCNEWVEC (struct version_info
, data
->version_info_size
);
1079 data
->relevant
= BITMAP_ALLOC (NULL
);
1080 data
->important_candidates
= BITMAP_ALLOC (NULL
);
1081 data
->max_inv_var_id
= 0;
1082 data
->max_inv_expr_id
= 0;
1083 data
->niters
= NULL
;
1084 data
->vgroups
.create (20);
1085 data
->vcands
.create (20);
1086 data
->inv_expr_tab
= new hash_table
<iv_inv_expr_hasher
> (10);
1087 data
->name_expansion_cache
= NULL
;
1088 data
->base_object_map
= NULL
;
1089 data
->iv_common_cand_tab
= new hash_table
<iv_common_cand_hasher
> (10);
1090 data
->iv_common_cands
.create (20);
1091 decl_rtl_to_reset
.create (20);
1092 gcc_obstack_init (&data
->iv_obstack
);
1095 /* walk_tree callback for determine_base_object. */
1098 determine_base_object_1 (tree
*tp
, int *walk_subtrees
, void *wdata
)
1100 tree_code code
= TREE_CODE (*tp
);
1101 tree obj
= NULL_TREE
;
1102 if (code
== ADDR_EXPR
)
1104 tree base
= get_base_address (TREE_OPERAND (*tp
, 0));
1107 else if (TREE_CODE (base
) != MEM_REF
)
1108 obj
= fold_convert (ptr_type_node
, build_fold_addr_expr (base
));
1110 else if (code
== SSA_NAME
&& POINTER_TYPE_P (TREE_TYPE (*tp
)))
1111 obj
= fold_convert (ptr_type_node
, *tp
);
1120 /* Record special node for multiple base objects and stop. */
1121 if (*static_cast<tree
*> (wdata
))
1123 *static_cast<tree
*> (wdata
) = integer_zero_node
;
1124 return integer_zero_node
;
1126 /* Record the base object and continue looking. */
1127 *static_cast<tree
*> (wdata
) = obj
;
1131 /* Returns a memory object to that EXPR points with caching. Return NULL if we
1132 are able to determine that it does not point to any such object; specially
1133 return integer_zero_node if EXPR contains multiple base objects. */
1136 determine_base_object (struct ivopts_data
*data
, tree expr
)
1138 tree
*slot
, obj
= NULL_TREE
;
1139 if (data
->base_object_map
)
1141 if ((slot
= data
->base_object_map
->get(expr
)) != NULL
)
1145 data
->base_object_map
= new hash_map
<tree
, tree
>;
1147 (void) walk_tree_without_duplicates (&expr
, determine_base_object_1
, &obj
);
1148 data
->base_object_map
->put (expr
, obj
);
1152 /* Return true if address expression with non-DECL_P operand appears
1156 contain_complex_addr_expr (tree expr
)
1161 switch (TREE_CODE (expr
))
1163 case POINTER_PLUS_EXPR
:
1166 res
|= contain_complex_addr_expr (TREE_OPERAND (expr
, 0));
1167 res
|= contain_complex_addr_expr (TREE_OPERAND (expr
, 1));
1171 return (!DECL_P (TREE_OPERAND (expr
, 0)));
1180 /* Allocates an induction variable with given initial value BASE and step STEP
1181 for loop LOOP. NO_OVERFLOW implies the iv doesn't overflow. */
1184 alloc_iv (struct ivopts_data
*data
, tree base
, tree step
,
1185 bool no_overflow
= false)
1188 struct iv
*iv
= (struct iv
*) obstack_alloc (&data
->iv_obstack
,
1189 sizeof (struct iv
));
1190 gcc_assert (step
!= NULL_TREE
);
1192 /* Lower address expression in base except ones with DECL_P as operand.
1194 1) More accurate cost can be computed for address expressions;
1195 2) Duplicate candidates won't be created for bases in different
1196 forms, like &a[0] and &a. */
1198 if ((TREE_CODE (expr
) == ADDR_EXPR
&& !DECL_P (TREE_OPERAND (expr
, 0)))
1199 || contain_complex_addr_expr (expr
))
1202 tree_to_aff_combination (expr
, TREE_TYPE (expr
), &comb
);
1203 base
= fold_convert (TREE_TYPE (base
), aff_combination_to_tree (&comb
));
1207 iv
->base_object
= determine_base_object (data
, base
);
1210 iv
->nonlin_use
= NULL
;
1211 iv
->ssa_name
= NULL_TREE
;
1213 && !iv_can_overflow_p (data
->current_loop
, TREE_TYPE (base
),
1216 iv
->no_overflow
= no_overflow
;
1217 iv
->have_address_use
= false;
1222 /* Sets STEP and BASE for induction variable IV. NO_OVERFLOW implies the IV
1223 doesn't overflow. */
1226 set_iv (struct ivopts_data
*data
, tree iv
, tree base
, tree step
,
1229 struct version_info
*info
= name_info (data
, iv
);
1231 gcc_assert (!info
->iv
);
1233 bitmap_set_bit (data
->relevant
, SSA_NAME_VERSION (iv
));
1234 info
->iv
= alloc_iv (data
, base
, step
, no_overflow
);
1235 info
->iv
->ssa_name
= iv
;
1238 /* Finds induction variable declaration for VAR. */
1241 get_iv (struct ivopts_data
*data
, tree var
)
1244 tree type
= TREE_TYPE (var
);
1246 if (!POINTER_TYPE_P (type
)
1247 && !INTEGRAL_TYPE_P (type
))
1250 if (!name_info (data
, var
)->iv
)
1252 bb
= gimple_bb (SSA_NAME_DEF_STMT (var
));
1255 || !flow_bb_inside_loop_p (data
->current_loop
, bb
))
1257 if (POINTER_TYPE_P (type
))
1259 set_iv (data
, var
, var
, build_int_cst (type
, 0), true);
1263 return name_info (data
, var
)->iv
;
1266 /* Return the first non-invariant ssa var found in EXPR. */
1269 extract_single_var_from_expr (tree expr
)
1273 enum tree_code code
;
1275 if (!expr
|| is_gimple_min_invariant (expr
))
1278 code
= TREE_CODE (expr
);
1279 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code
)))
1281 n
= TREE_OPERAND_LENGTH (expr
);
1282 for (i
= 0; i
< n
; i
++)
1284 tmp
= extract_single_var_from_expr (TREE_OPERAND (expr
, i
));
1290 return (TREE_CODE (expr
) == SSA_NAME
) ? expr
: NULL
;
1293 /* Finds basic ivs. */
1296 find_bivs (struct ivopts_data
*data
)
1300 tree step
, type
, base
, stop
;
1302 class loop
*loop
= data
->current_loop
;
1305 for (psi
= gsi_start_phis (loop
->header
); !gsi_end_p (psi
); gsi_next (&psi
))
1309 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi
)))
1312 if (virtual_operand_p (PHI_RESULT (phi
)))
1315 if (!simple_iv (loop
, loop
, PHI_RESULT (phi
), &iv
, true))
1318 if (integer_zerop (iv
.step
))
1322 base
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_preheader_edge (loop
));
1323 /* Stop expanding iv base at the first ssa var referred by iv step.
1324 Ideally we should stop at any ssa var, because that's expensive
1325 and unusual to happen, we just do it on the first one.
1327 See PR64705 for the rationale. */
1328 stop
= extract_single_var_from_expr (step
);
1329 base
= expand_simple_operations (base
, stop
);
1330 if (contains_abnormal_ssa_name_p (base
)
1331 || contains_abnormal_ssa_name_p (step
))
1334 type
= TREE_TYPE (PHI_RESULT (phi
));
1335 base
= fold_convert (type
, base
);
1338 if (POINTER_TYPE_P (type
))
1339 step
= convert_to_ptrofftype (step
);
1341 step
= fold_convert (type
, step
);
1344 set_iv (data
, PHI_RESULT (phi
), base
, step
, iv
.no_overflow
);
1351 /* Marks basic ivs. */
1354 mark_bivs (struct ivopts_data
*data
)
1359 struct iv
*iv
, *incr_iv
;
1360 class loop
*loop
= data
->current_loop
;
1361 basic_block incr_bb
;
1364 data
->bivs_not_used_in_addr
= 0;
1365 for (psi
= gsi_start_phis (loop
->header
); !gsi_end_p (psi
); gsi_next (&psi
))
1369 iv
= get_iv (data
, PHI_RESULT (phi
));
1373 var
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_latch_edge (loop
));
1374 def
= SSA_NAME_DEF_STMT (var
);
1375 /* Don't mark iv peeled from other one as biv. */
1377 && gimple_code (def
) == GIMPLE_PHI
1378 && gimple_bb (def
) == loop
->header
)
1381 incr_iv
= get_iv (data
, var
);
1385 /* If the increment is in the subloop, ignore it. */
1386 incr_bb
= gimple_bb (SSA_NAME_DEF_STMT (var
));
1387 if (incr_bb
->loop_father
!= data
->current_loop
1388 || (incr_bb
->flags
& BB_IRREDUCIBLE_LOOP
))
1392 incr_iv
->biv_p
= true;
1393 if (iv
->no_overflow
)
1394 data
->bivs_not_used_in_addr
++;
1395 if (incr_iv
->no_overflow
)
1396 data
->bivs_not_used_in_addr
++;
1400 /* Checks whether STMT defines a linear induction variable and stores its
1401 parameters to IV. */
1404 find_givs_in_stmt_scev (struct ivopts_data
*data
, gimple
*stmt
, affine_iv
*iv
)
1407 class loop
*loop
= data
->current_loop
;
1409 iv
->base
= NULL_TREE
;
1410 iv
->step
= NULL_TREE
;
1412 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
1415 lhs
= gimple_assign_lhs (stmt
);
1416 if (TREE_CODE (lhs
) != SSA_NAME
)
1419 if (!simple_iv (loop
, loop_containing_stmt (stmt
), lhs
, iv
, true))
1422 /* Stop expanding iv base at the first ssa var referred by iv step.
1423 Ideally we should stop at any ssa var, because that's expensive
1424 and unusual to happen, we just do it on the first one.
1426 See PR64705 for the rationale. */
1427 stop
= extract_single_var_from_expr (iv
->step
);
1428 iv
->base
= expand_simple_operations (iv
->base
, stop
);
1429 if (contains_abnormal_ssa_name_p (iv
->base
)
1430 || contains_abnormal_ssa_name_p (iv
->step
))
1433 /* If STMT could throw, then do not consider STMT as defining a GIV.
1434 While this will suppress optimizations, we cannot safely delete this
1435 GIV and associated statements, even if it appears it is not used. */
1436 if (stmt_could_throw_p (cfun
, stmt
))
1442 /* Finds general ivs in statement STMT. */
1445 find_givs_in_stmt (struct ivopts_data
*data
, gimple
*stmt
)
1449 if (!find_givs_in_stmt_scev (data
, stmt
, &iv
))
1452 set_iv (data
, gimple_assign_lhs (stmt
), iv
.base
, iv
.step
, iv
.no_overflow
);
1455 /* Finds general ivs in basic block BB. */
1458 find_givs_in_bb (struct ivopts_data
*data
, basic_block bb
)
1460 gimple_stmt_iterator bsi
;
1462 for (bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
1463 find_givs_in_stmt (data
, gsi_stmt (bsi
));
1466 /* Finds general ivs. */
1469 find_givs (struct ivopts_data
*data
, basic_block
*body
)
1471 class loop
*loop
= data
->current_loop
;
1474 for (i
= 0; i
< loop
->num_nodes
; i
++)
1475 find_givs_in_bb (data
, body
[i
]);
1478 /* For each ssa name defined in LOOP determines whether it is an induction
1479 variable and if so, its initial value and step. */
1482 find_induction_variables (struct ivopts_data
*data
, basic_block
*body
)
1487 if (!find_bivs (data
))
1490 find_givs (data
, body
);
1493 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1495 class tree_niter_desc
*niter
= niter_for_single_dom_exit (data
);
1499 fprintf (dump_file
, " number of iterations ");
1500 print_generic_expr (dump_file
, niter
->niter
, TDF_SLIM
);
1501 if (!integer_zerop (niter
->may_be_zero
))
1503 fprintf (dump_file
, "; zero if ");
1504 print_generic_expr (dump_file
, niter
->may_be_zero
, TDF_SLIM
);
1506 fprintf (dump_file
, "\n");
1509 fprintf (dump_file
, "\n<Induction Vars>:\n");
1510 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, i
, bi
)
1512 struct version_info
*info
= ver_info (data
, i
);
1513 if (info
->iv
&& info
->iv
->step
&& !integer_zerop (info
->iv
->step
))
1514 dump_iv (dump_file
, ver_info (data
, i
)->iv
, true, 0);
1521 /* Records a use of TYPE at *USE_P in STMT whose value is IV in GROUP.
1522 For address type use, ADDR_BASE is the stripped IV base, ADDR_OFFSET
1523 is the const offset stripped from IV base and MEM_TYPE is the type
1524 of the memory being addressed. For uses of other types, ADDR_BASE
1525 and ADDR_OFFSET are zero by default and MEM_TYPE is NULL_TREE. */
1527 static struct iv_use
*
1528 record_use (struct iv_group
*group
, tree
*use_p
, struct iv
*iv
,
1529 gimple
*stmt
, enum use_type type
, tree mem_type
,
1530 tree addr_base
, poly_uint64 addr_offset
)
1532 struct iv_use
*use
= XCNEW (struct iv_use
);
1534 use
->id
= group
->vuses
.length ();
1535 use
->group_id
= group
->id
;
1537 use
->mem_type
= mem_type
;
1541 use
->addr_base
= addr_base
;
1542 use
->addr_offset
= addr_offset
;
1544 group
->vuses
.safe_push (use
);
1548 /* Checks whether OP is a loop-level invariant and if so, records it.
1549 NONLINEAR_USE is true if the invariant is used in a way we do not
1550 handle specially. */
1553 record_invariant (struct ivopts_data
*data
, tree op
, bool nonlinear_use
)
1556 struct version_info
*info
;
1558 if (TREE_CODE (op
) != SSA_NAME
1559 || virtual_operand_p (op
))
1562 bb
= gimple_bb (SSA_NAME_DEF_STMT (op
));
1564 && flow_bb_inside_loop_p (data
->current_loop
, bb
))
1567 info
= name_info (data
, op
);
1569 info
->has_nonlin_use
|= nonlinear_use
;
1571 info
->inv_id
= ++data
->max_inv_var_id
;
1572 bitmap_set_bit (data
->relevant
, SSA_NAME_VERSION (op
));
1575 /* Record a group of TYPE. */
1577 static struct iv_group
*
1578 record_group (struct ivopts_data
*data
, enum use_type type
)
1580 struct iv_group
*group
= XCNEW (struct iv_group
);
1582 group
->id
= data
->vgroups
.length ();
1584 group
->related_cands
= BITMAP_ALLOC (NULL
);
1585 group
->vuses
.create (1);
1586 group
->doloop_p
= false;
1588 data
->vgroups
.safe_push (group
);
1592 /* Record a use of TYPE at *USE_P in STMT whose value is IV in a group.
1593 New group will be created if there is no existing group for the use.
1594 MEM_TYPE is the type of memory being addressed, or NULL if this
1595 isn't an address reference. */
1597 static struct iv_use
*
1598 record_group_use (struct ivopts_data
*data
, tree
*use_p
,
1599 struct iv
*iv
, gimple
*stmt
, enum use_type type
,
1602 tree addr_base
= NULL
;
1603 struct iv_group
*group
= NULL
;
1604 poly_uint64 addr_offset
= 0;
1606 /* Record non address type use in a new group. */
1607 if (address_p (type
))
1611 gcc_assert (POINTER_TYPE_P (TREE_TYPE (iv
->base
)));
1613 split_constant_offset (iv
->base
, &addr_base
, &addr_toffset
);
1614 addr_offset
= int_cst_value (addr_toffset
);
1615 for (i
= 0; i
< data
->vgroups
.length (); i
++)
1619 group
= data
->vgroups
[i
];
1620 use
= group
->vuses
[0];
1621 if (!address_p (use
->type
))
1624 /* Check if it has the same stripped base and step. */
1625 if (operand_equal_p (iv
->base_object
, use
->iv
->base_object
, 0)
1626 && operand_equal_p (iv
->step
, use
->iv
->step
, 0)
1627 && operand_equal_p (addr_base
, use
->addr_base
, 0))
1630 if (i
== data
->vgroups
.length ())
1635 group
= record_group (data
, type
);
1637 return record_use (group
, use_p
, iv
, stmt
, type
, mem_type
,
1638 addr_base
, addr_offset
);
1641 /* Checks whether the use OP is interesting and if so, records it. */
1643 static struct iv_use
*
1644 find_interesting_uses_op (struct ivopts_data
*data
, tree op
)
1650 if (TREE_CODE (op
) != SSA_NAME
)
1653 iv
= get_iv (data
, op
);
1659 gcc_assert (iv
->nonlin_use
->type
== USE_NONLINEAR_EXPR
);
1660 return iv
->nonlin_use
;
1663 if (integer_zerop (iv
->step
))
1665 record_invariant (data
, op
, true);
1669 stmt
= SSA_NAME_DEF_STMT (op
);
1670 gcc_assert (gimple_code (stmt
) == GIMPLE_PHI
|| is_gimple_assign (stmt
));
1672 use
= record_group_use (data
, NULL
, iv
, stmt
, USE_NONLINEAR_EXPR
, NULL_TREE
);
1673 iv
->nonlin_use
= use
;
1677 /* Indicate how compare type iv_use can be handled. */
1678 enum comp_iv_rewrite
1681 /* We may rewrite compare type iv_use by expressing value of the iv_use. */
1683 /* We may rewrite compare type iv_uses on both sides of comparison by
1684 expressing value of each iv_use. */
1686 /* We may rewrite compare type iv_use by expressing value of the iv_use
1687 or by eliminating it with other iv_cand. */
1691 /* Given a condition in statement STMT, checks whether it is a compare
1692 of an induction variable and an invariant. If this is the case,
1693 CONTROL_VAR is set to location of the iv, BOUND to the location of
1694 the invariant, IV_VAR and IV_BOUND are set to the corresponding
1695 induction variable descriptions, and true is returned. If this is not
1696 the case, CONTROL_VAR and BOUND are set to the arguments of the
1697 condition and false is returned. */
1699 static enum comp_iv_rewrite
1700 extract_cond_operands (struct ivopts_data
*data
, gimple
*stmt
,
1701 tree
**control_var
, tree
**bound
,
1702 struct iv
**iv_var
, struct iv
**iv_bound
)
1704 /* The objects returned when COND has constant operands. */
1705 static struct iv const_iv
;
1707 tree
*op0
= &zero
, *op1
= &zero
;
1708 struct iv
*iv0
= &const_iv
, *iv1
= &const_iv
;
1709 enum comp_iv_rewrite rewrite_type
= COMP_IV_NA
;
1711 if (gimple_code (stmt
) == GIMPLE_COND
)
1713 gcond
*cond_stmt
= as_a
<gcond
*> (stmt
);
1714 op0
= gimple_cond_lhs_ptr (cond_stmt
);
1715 op1
= gimple_cond_rhs_ptr (cond_stmt
);
1719 op0
= gimple_assign_rhs1_ptr (stmt
);
1720 op1
= gimple_assign_rhs2_ptr (stmt
);
1723 zero
= integer_zero_node
;
1724 const_iv
.step
= integer_zero_node
;
1726 if (TREE_CODE (*op0
) == SSA_NAME
)
1727 iv0
= get_iv (data
, *op0
);
1728 if (TREE_CODE (*op1
) == SSA_NAME
)
1729 iv1
= get_iv (data
, *op1
);
1731 /* If both sides of comparison are IVs. We can express ivs on both end. */
1732 if (iv0
&& iv1
&& !integer_zerop (iv0
->step
) && !integer_zerop (iv1
->step
))
1734 rewrite_type
= COMP_IV_EXPR_2
;
1738 /* If none side of comparison is IV. */
1739 if ((!iv0
|| integer_zerop (iv0
->step
))
1740 && (!iv1
|| integer_zerop (iv1
->step
)))
1743 /* Control variable may be on the other side. */
1744 if (!iv0
|| integer_zerop (iv0
->step
))
1746 std::swap (op0
, op1
);
1747 std::swap (iv0
, iv1
);
1749 /* If one side is IV and the other side isn't loop invariant. */
1751 rewrite_type
= COMP_IV_EXPR
;
1752 /* If one side is IV and the other side is loop invariant. */
1753 else if (!integer_zerop (iv0
->step
) && integer_zerop (iv1
->step
))
1754 rewrite_type
= COMP_IV_ELIM
;
1766 return rewrite_type
;
1769 /* Checks whether the condition in STMT is interesting and if so,
1773 find_interesting_uses_cond (struct ivopts_data
*data
, gimple
*stmt
)
1775 tree
*var_p
, *bound_p
;
1776 struct iv
*var_iv
, *bound_iv
;
1777 enum comp_iv_rewrite ret
;
1779 ret
= extract_cond_operands (data
, stmt
,
1780 &var_p
, &bound_p
, &var_iv
, &bound_iv
);
1781 if (ret
== COMP_IV_NA
)
1783 find_interesting_uses_op (data
, *var_p
);
1784 find_interesting_uses_op (data
, *bound_p
);
1788 record_group_use (data
, var_p
, var_iv
, stmt
, USE_COMPARE
, NULL_TREE
);
1789 /* Record compare type iv_use for iv on the other side of comparison. */
1790 if (ret
== COMP_IV_EXPR_2
)
1791 record_group_use (data
, bound_p
, bound_iv
, stmt
, USE_COMPARE
, NULL_TREE
);
1794 /* Returns the outermost loop EXPR is obviously invariant in
1795 relative to the loop LOOP, i.e. if all its operands are defined
1796 outside of the returned loop. Returns NULL if EXPR is not
1797 even obviously invariant in LOOP. */
1800 outermost_invariant_loop_for_expr (class loop
*loop
, tree expr
)
1805 if (is_gimple_min_invariant (expr
))
1806 return current_loops
->tree_root
;
1808 if (TREE_CODE (expr
) == SSA_NAME
)
1810 def_bb
= gimple_bb (SSA_NAME_DEF_STMT (expr
));
1813 if (flow_bb_inside_loop_p (loop
, def_bb
))
1815 return superloop_at_depth (loop
,
1816 loop_depth (def_bb
->loop_father
) + 1);
1819 return current_loops
->tree_root
;
1825 unsigned maxdepth
= 0;
1826 len
= TREE_OPERAND_LENGTH (expr
);
1827 for (i
= 0; i
< len
; i
++)
1830 if (!TREE_OPERAND (expr
, i
))
1833 ivloop
= outermost_invariant_loop_for_expr (loop
, TREE_OPERAND (expr
, i
));
1836 maxdepth
= MAX (maxdepth
, loop_depth (ivloop
));
1839 return superloop_at_depth (loop
, maxdepth
);
1842 /* Returns true if expression EXPR is obviously invariant in LOOP,
1843 i.e. if all its operands are defined outside of the LOOP. LOOP
1844 should not be the function body. */
1847 expr_invariant_in_loop_p (class loop
*loop
, tree expr
)
1852 gcc_assert (loop_depth (loop
) > 0);
1854 if (is_gimple_min_invariant (expr
))
1857 if (TREE_CODE (expr
) == SSA_NAME
)
1859 def_bb
= gimple_bb (SSA_NAME_DEF_STMT (expr
));
1861 && flow_bb_inside_loop_p (loop
, def_bb
))
1870 len
= TREE_OPERAND_LENGTH (expr
);
1871 for (i
= 0; i
< len
; i
++)
1872 if (TREE_OPERAND (expr
, i
)
1873 && !expr_invariant_in_loop_p (loop
, TREE_OPERAND (expr
, i
)))
1879 /* Given expression EXPR which computes inductive values with respect
1880 to loop recorded in DATA, this function returns biv from which EXPR
1881 is derived by tracing definition chains of ssa variables in EXPR. */
1884 find_deriving_biv_for_expr (struct ivopts_data
*data
, tree expr
)
1889 enum tree_code code
;
1892 if (expr
== NULL_TREE
)
1895 if (is_gimple_min_invariant (expr
))
1898 code
= TREE_CODE (expr
);
1899 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code
)))
1901 n
= TREE_OPERAND_LENGTH (expr
);
1902 for (i
= 0; i
< n
; i
++)
1904 iv
= find_deriving_biv_for_expr (data
, TREE_OPERAND (expr
, i
));
1910 /* Stop if it's not ssa name. */
1911 if (code
!= SSA_NAME
)
1914 iv
= get_iv (data
, expr
);
1915 if (!iv
|| integer_zerop (iv
->step
))
1920 stmt
= SSA_NAME_DEF_STMT (expr
);
1921 if (gphi
*phi
= dyn_cast
<gphi
*> (stmt
))
1924 use_operand_p use_p
;
1925 basic_block phi_bb
= gimple_bb (phi
);
1927 /* Skip loop header PHI that doesn't define biv. */
1928 if (phi_bb
->loop_father
== data
->current_loop
)
1931 if (virtual_operand_p (gimple_phi_result (phi
)))
1934 FOR_EACH_PHI_ARG (use_p
, phi
, iter
, SSA_OP_USE
)
1936 tree use
= USE_FROM_PTR (use_p
);
1937 iv
= find_deriving_biv_for_expr (data
, use
);
1943 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
1946 e1
= gimple_assign_rhs1 (stmt
);
1947 code
= gimple_assign_rhs_code (stmt
);
1948 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1949 return find_deriving_biv_for_expr (data
, e1
);
1956 case POINTER_PLUS_EXPR
:
1957 /* Increments, decrements and multiplications by a constant
1959 e2
= gimple_assign_rhs2 (stmt
);
1960 iv
= find_deriving_biv_for_expr (data
, e2
);
1966 /* Casts are simple. */
1967 return find_deriving_biv_for_expr (data
, e1
);
1976 /* Record BIV, its predecessor and successor that they are used in
1977 address type uses. */
1980 record_biv_for_address_use (struct ivopts_data
*data
, struct iv
*biv
)
1983 tree type
, base_1
, base_2
;
1986 if (!biv
|| !biv
->biv_p
|| integer_zerop (biv
->step
)
1987 || biv
->have_address_use
|| !biv
->no_overflow
)
1990 type
= TREE_TYPE (biv
->base
);
1991 if (!INTEGRAL_TYPE_P (type
))
1994 biv
->have_address_use
= true;
1995 data
->bivs_not_used_in_addr
--;
1996 base_1
= fold_build2 (PLUS_EXPR
, type
, biv
->base
, biv
->step
);
1997 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, i
, bi
)
1999 struct iv
*iv
= ver_info (data
, i
)->iv
;
2001 if (!iv
|| !iv
->biv_p
|| integer_zerop (iv
->step
)
2002 || iv
->have_address_use
|| !iv
->no_overflow
)
2005 if (type
!= TREE_TYPE (iv
->base
)
2006 || !INTEGRAL_TYPE_P (TREE_TYPE (iv
->base
)))
2009 if (!operand_equal_p (biv
->step
, iv
->step
, 0))
2012 base_2
= fold_build2 (PLUS_EXPR
, type
, iv
->base
, iv
->step
);
2013 if (operand_equal_p (base_1
, iv
->base
, 0)
2014 || operand_equal_p (base_2
, biv
->base
, 0))
2016 iv
->have_address_use
= true;
2017 data
->bivs_not_used_in_addr
--;
2022 /* Cumulates the steps of indices into DATA and replaces their values with the
2023 initial ones. Returns false when the value of the index cannot be determined.
2024 Callback for for_each_index. */
2026 struct ifs_ivopts_data
2028 struct ivopts_data
*ivopts_data
;
2034 idx_find_step (tree base
, tree
*idx
, void *data
)
2036 struct ifs_ivopts_data
*dta
= (struct ifs_ivopts_data
*) data
;
2038 bool use_overflow_semantics
= false;
2039 tree step
, iv_base
, iv_step
, lbound
, off
;
2040 class loop
*loop
= dta
->ivopts_data
->current_loop
;
2042 /* If base is a component ref, require that the offset of the reference
2044 if (TREE_CODE (base
) == COMPONENT_REF
)
2046 off
= component_ref_field_offset (base
);
2047 return expr_invariant_in_loop_p (loop
, off
);
2050 /* If base is array, first check whether we will be able to move the
2051 reference out of the loop (in order to take its address in strength
2052 reduction). In order for this to work we need both lower bound
2053 and step to be loop invariants. */
2054 if (TREE_CODE (base
) == ARRAY_REF
|| TREE_CODE (base
) == ARRAY_RANGE_REF
)
2056 /* Moreover, for a range, the size needs to be invariant as well. */
2057 if (TREE_CODE (base
) == ARRAY_RANGE_REF
2058 && !expr_invariant_in_loop_p (loop
, TYPE_SIZE (TREE_TYPE (base
))))
2061 step
= array_ref_element_size (base
);
2062 lbound
= array_ref_low_bound (base
);
2064 if (!expr_invariant_in_loop_p (loop
, step
)
2065 || !expr_invariant_in_loop_p (loop
, lbound
))
2069 if (TREE_CODE (*idx
) != SSA_NAME
)
2072 iv
= get_iv (dta
->ivopts_data
, *idx
);
2076 /* XXX We produce for a base of *D42 with iv->base being &x[0]
2077 *&x[0], which is not folded and does not trigger the
2078 ARRAY_REF path below. */
2081 if (integer_zerop (iv
->step
))
2084 if (TREE_CODE (base
) == ARRAY_REF
|| TREE_CODE (base
) == ARRAY_RANGE_REF
)
2086 step
= array_ref_element_size (base
);
2088 /* We only handle addresses whose step is an integer constant. */
2089 if (TREE_CODE (step
) != INTEGER_CST
)
2093 /* The step for pointer arithmetics already is 1 byte. */
2094 step
= size_one_node
;
2098 if (iv
->no_overflow
&& nowrap_type_p (TREE_TYPE (iv_step
)))
2099 use_overflow_semantics
= true;
2101 if (!convert_affine_scev (dta
->ivopts_data
->current_loop
,
2102 sizetype
, &iv_base
, &iv_step
, dta
->stmt
,
2103 use_overflow_semantics
))
2105 /* The index might wrap. */
2109 step
= fold_build2 (MULT_EXPR
, sizetype
, step
, iv_step
);
2110 dta
->step
= fold_build2 (PLUS_EXPR
, sizetype
, dta
->step
, step
);
2112 if (dta
->ivopts_data
->bivs_not_used_in_addr
)
2115 iv
= find_deriving_biv_for_expr (dta
->ivopts_data
, iv
->ssa_name
);
2117 record_biv_for_address_use (dta
->ivopts_data
, iv
);
2122 /* Records use in index IDX. Callback for for_each_index. Ivopts data
2123 object is passed to it in DATA. */
2126 idx_record_use (tree base
, tree
*idx
,
2129 struct ivopts_data
*data
= (struct ivopts_data
*) vdata
;
2130 find_interesting_uses_op (data
, *idx
);
2131 if (TREE_CODE (base
) == ARRAY_REF
|| TREE_CODE (base
) == ARRAY_RANGE_REF
)
2133 if (TREE_OPERAND (base
, 2))
2134 find_interesting_uses_op (data
, TREE_OPERAND (base
, 2));
2135 if (TREE_OPERAND (base
, 3))
2136 find_interesting_uses_op (data
, TREE_OPERAND (base
, 3));
2141 /* If we can prove that TOP = cst * BOT for some constant cst,
2142 store cst to MUL and return true. Otherwise return false.
2143 The returned value is always sign-extended, regardless of the
2144 signedness of TOP and BOT. */
2147 constant_multiple_of (tree top
, tree bot
, widest_int
*mul
)
2150 enum tree_code code
;
2151 unsigned precision
= TYPE_PRECISION (TREE_TYPE (top
));
2152 widest_int res
, p0
, p1
;
2157 if (operand_equal_p (top
, bot
, 0))
2163 code
= TREE_CODE (top
);
2167 mby
= TREE_OPERAND (top
, 1);
2168 if (TREE_CODE (mby
) != INTEGER_CST
)
2171 if (!constant_multiple_of (TREE_OPERAND (top
, 0), bot
, &res
))
2174 *mul
= wi::sext (res
* wi::to_widest (mby
), precision
);
2179 if (!constant_multiple_of (TREE_OPERAND (top
, 0), bot
, &p0
)
2180 || !constant_multiple_of (TREE_OPERAND (top
, 1), bot
, &p1
))
2183 if (code
== MINUS_EXPR
)
2185 *mul
= wi::sext (p0
+ p1
, precision
);
2189 if (TREE_CODE (bot
) != INTEGER_CST
)
2192 p0
= widest_int::from (wi::to_wide (top
), SIGNED
);
2193 p1
= widest_int::from (wi::to_wide (bot
), SIGNED
);
2196 *mul
= wi::sext (wi::divmod_trunc (p0
, p1
, SIGNED
, &res
), precision
);
2200 if (POLY_INT_CST_P (top
)
2201 && POLY_INT_CST_P (bot
)
2202 && constant_multiple_p (wi::to_poly_widest (top
),
2203 wi::to_poly_widest (bot
), mul
))
2210 /* Return true if memory reference REF with step STEP may be unaligned. */
2213 may_be_unaligned_p (tree ref
, tree step
)
2215 /* TARGET_MEM_REFs are translated directly to valid MEMs on the target,
2216 thus they are not misaligned. */
2217 if (TREE_CODE (ref
) == TARGET_MEM_REF
)
2220 unsigned int align
= TYPE_ALIGN (TREE_TYPE (ref
));
2221 if (GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref
))) > align
)
2222 align
= GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref
)));
2224 unsigned HOST_WIDE_INT bitpos
;
2225 unsigned int ref_align
;
2226 get_object_alignment_1 (ref
, &ref_align
, &bitpos
);
2227 if (ref_align
< align
2228 || (bitpos
% align
) != 0
2229 || (bitpos
% BITS_PER_UNIT
) != 0)
2232 unsigned int trailing_zeros
= tree_ctz (step
);
2233 if (trailing_zeros
< HOST_BITS_PER_INT
2234 && (1U << trailing_zeros
) * BITS_PER_UNIT
< align
)
2240 /* Return true if EXPR may be non-addressable. */
2243 may_be_nonaddressable_p (tree expr
)
2245 switch (TREE_CODE (expr
))
2248 /* Check if it's a register variable. */
2249 return DECL_HARD_REGISTER (expr
);
2251 case TARGET_MEM_REF
:
2252 /* TARGET_MEM_REFs are translated directly to valid MEMs on the
2253 target, thus they are always addressable. */
2257 /* Likewise for MEM_REFs, modulo the storage order. */
2258 return REF_REVERSE_STORAGE_ORDER (expr
);
2261 if (REF_REVERSE_STORAGE_ORDER (expr
))
2263 return may_be_nonaddressable_p (TREE_OPERAND (expr
, 0));
2266 if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr
, 0))))
2268 return DECL_NONADDRESSABLE_P (TREE_OPERAND (expr
, 1))
2269 || may_be_nonaddressable_p (TREE_OPERAND (expr
, 0));
2272 case ARRAY_RANGE_REF
:
2273 if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr
, 0))))
2275 return may_be_nonaddressable_p (TREE_OPERAND (expr
, 0));
2277 case VIEW_CONVERT_EXPR
:
2278 /* This kind of view-conversions may wrap non-addressable objects
2279 and make them look addressable. After some processing the
2280 non-addressability may be uncovered again, causing ADDR_EXPRs
2281 of inappropriate objects to be built. */
2282 if (is_gimple_reg (TREE_OPERAND (expr
, 0))
2283 || !is_gimple_addressable (TREE_OPERAND (expr
, 0)))
2285 return may_be_nonaddressable_p (TREE_OPERAND (expr
, 0));
2297 /* Finds addresses in *OP_P inside STMT. */
2300 find_interesting_uses_address (struct ivopts_data
*data
, gimple
*stmt
,
2303 tree base
= *op_p
, step
= size_zero_node
;
2305 struct ifs_ivopts_data ifs_ivopts_data
;
2307 /* Do not play with volatile memory references. A bit too conservative,
2308 perhaps, but safe. */
2309 if (gimple_has_volatile_ops (stmt
))
2312 /* Ignore bitfields for now. Not really something terribly complicated
2314 if (TREE_CODE (base
) == BIT_FIELD_REF
)
2317 base
= unshare_expr (base
);
2319 if (TREE_CODE (base
) == TARGET_MEM_REF
)
2321 tree type
= build_pointer_type (TREE_TYPE (base
));
2325 && TREE_CODE (TMR_BASE (base
)) == SSA_NAME
)
2327 civ
= get_iv (data
, TMR_BASE (base
));
2331 TMR_BASE (base
) = civ
->base
;
2334 if (TMR_INDEX2 (base
)
2335 && TREE_CODE (TMR_INDEX2 (base
)) == SSA_NAME
)
2337 civ
= get_iv (data
, TMR_INDEX2 (base
));
2341 TMR_INDEX2 (base
) = civ
->base
;
2344 if (TMR_INDEX (base
)
2345 && TREE_CODE (TMR_INDEX (base
)) == SSA_NAME
)
2347 civ
= get_iv (data
, TMR_INDEX (base
));
2351 TMR_INDEX (base
) = civ
->base
;
2356 if (TMR_STEP (base
))
2357 astep
= fold_build2 (MULT_EXPR
, type
, TMR_STEP (base
), astep
);
2359 step
= fold_build2 (PLUS_EXPR
, type
, step
, astep
);
2363 if (integer_zerop (step
))
2365 base
= tree_mem_ref_addr (type
, base
);
2369 ifs_ivopts_data
.ivopts_data
= data
;
2370 ifs_ivopts_data
.stmt
= stmt
;
2371 ifs_ivopts_data
.step
= size_zero_node
;
2372 if (!for_each_index (&base
, idx_find_step
, &ifs_ivopts_data
)
2373 || integer_zerop (ifs_ivopts_data
.step
))
2375 step
= ifs_ivopts_data
.step
;
2377 /* Check that the base expression is addressable. This needs
2378 to be done after substituting bases of IVs into it. */
2379 if (may_be_nonaddressable_p (base
))
2382 /* Moreover, on strict alignment platforms, check that it is
2383 sufficiently aligned. */
2384 if (STRICT_ALIGNMENT
&& may_be_unaligned_p (base
, step
))
2387 base
= build_fold_addr_expr (base
);
2389 /* Substituting bases of IVs into the base expression might
2390 have caused folding opportunities. */
2391 if (TREE_CODE (base
) == ADDR_EXPR
)
2393 tree
*ref
= &TREE_OPERAND (base
, 0);
2394 while (handled_component_p (*ref
))
2395 ref
= &TREE_OPERAND (*ref
, 0);
2396 if (TREE_CODE (*ref
) == MEM_REF
)
2398 tree tem
= fold_binary (MEM_REF
, TREE_TYPE (*ref
),
2399 TREE_OPERAND (*ref
, 0),
2400 TREE_OPERAND (*ref
, 1));
2407 civ
= alloc_iv (data
, base
, step
);
2408 /* Fail if base object of this memory reference is unknown. */
2409 if (civ
->base_object
== NULL_TREE
)
2412 record_group_use (data
, op_p
, civ
, stmt
, USE_REF_ADDRESS
, TREE_TYPE (*op_p
));
2416 for_each_index (op_p
, idx_record_use
, data
);
2419 /* Finds and records invariants used in STMT. */
2422 find_invariants_stmt (struct ivopts_data
*data
, gimple
*stmt
)
2425 use_operand_p use_p
;
2428 FOR_EACH_PHI_OR_STMT_USE (use_p
, stmt
, iter
, SSA_OP_USE
)
2430 op
= USE_FROM_PTR (use_p
);
2431 record_invariant (data
, op
, false);
2435 /* CALL calls an internal function. If operand *OP_P will become an
2436 address when the call is expanded, return the type of the memory
2437 being addressed, otherwise return null. */
2440 get_mem_type_for_internal_fn (gcall
*call
, tree
*op_p
)
2442 switch (gimple_call_internal_fn (call
))
2445 case IFN_MASK_LOAD_LANES
:
2446 case IFN_MASK_LEN_LOAD_LANES
:
2448 case IFN_MASK_LEN_LOAD
:
2449 if (op_p
== gimple_call_arg_ptr (call
, 0))
2450 return TREE_TYPE (gimple_call_lhs (call
));
2453 case IFN_MASK_STORE
:
2454 case IFN_MASK_STORE_LANES
:
2455 case IFN_MASK_LEN_STORE_LANES
:
2457 case IFN_MASK_LEN_STORE
:
2459 if (op_p
== gimple_call_arg_ptr (call
, 0))
2461 internal_fn ifn
= gimple_call_internal_fn (call
);
2462 int index
= internal_fn_stored_value_index (ifn
);
2463 return TREE_TYPE (gimple_call_arg (call
, index
));
2473 /* IV is a (non-address) iv that describes operand *OP_P of STMT.
2474 Return true if the operand will become an address when STMT
2475 is expanded and record the associated address use if so. */
2478 find_address_like_use (struct ivopts_data
*data
, gimple
*stmt
, tree
*op_p
,
2481 /* Fail if base object of this memory reference is unknown. */
2482 if (iv
->base_object
== NULL_TREE
)
2485 tree mem_type
= NULL_TREE
;
2486 if (gcall
*call
= dyn_cast
<gcall
*> (stmt
))
2487 if (gimple_call_internal_p (call
))
2488 mem_type
= get_mem_type_for_internal_fn (call
, op_p
);
2491 iv
= alloc_iv (data
, iv
->base
, iv
->step
);
2492 record_group_use (data
, op_p
, iv
, stmt
, USE_PTR_ADDRESS
, mem_type
);
2498 /* Finds interesting uses of induction variables in the statement STMT. */
2501 find_interesting_uses_stmt (struct ivopts_data
*data
, gimple
*stmt
)
2504 tree op
, *lhs
, *rhs
;
2506 use_operand_p use_p
;
2507 enum tree_code code
;
2509 find_invariants_stmt (data
, stmt
);
2511 if (gimple_code (stmt
) == GIMPLE_COND
)
2513 find_interesting_uses_cond (data
, stmt
);
2517 if (is_gimple_assign (stmt
))
2519 lhs
= gimple_assign_lhs_ptr (stmt
);
2520 rhs
= gimple_assign_rhs1_ptr (stmt
);
2522 if (TREE_CODE (*lhs
) == SSA_NAME
)
2524 /* If the statement defines an induction variable, the uses are not
2525 interesting by themselves. */
2527 iv
= get_iv (data
, *lhs
);
2529 if (iv
&& !integer_zerop (iv
->step
))
2533 code
= gimple_assign_rhs_code (stmt
);
2534 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
2535 && (REFERENCE_CLASS_P (*rhs
)
2536 || is_gimple_val (*rhs
)))
2538 if (REFERENCE_CLASS_P (*rhs
))
2539 find_interesting_uses_address (data
, stmt
, rhs
);
2541 find_interesting_uses_op (data
, *rhs
);
2543 if (REFERENCE_CLASS_P (*lhs
))
2544 find_interesting_uses_address (data
, stmt
, lhs
);
2547 else if (TREE_CODE_CLASS (code
) == tcc_comparison
)
2549 find_interesting_uses_cond (data
, stmt
);
2553 /* TODO -- we should also handle address uses of type
2555 memory = call (whatever);
2562 if (gimple_code (stmt
) == GIMPLE_PHI
2563 && gimple_bb (stmt
) == data
->current_loop
->header
)
2565 iv
= get_iv (data
, PHI_RESULT (stmt
));
2567 if (iv
&& !integer_zerop (iv
->step
))
2571 FOR_EACH_PHI_OR_STMT_USE (use_p
, stmt
, iter
, SSA_OP_USE
)
2573 op
= USE_FROM_PTR (use_p
);
2575 if (TREE_CODE (op
) != SSA_NAME
)
2578 iv
= get_iv (data
, op
);
2582 if (!find_address_like_use (data
, stmt
, use_p
->use
, iv
))
2583 find_interesting_uses_op (data
, op
);
2587 /* Finds interesting uses of induction variables outside of loops
2588 on loop exit edge EXIT. */
2591 find_interesting_uses_outside (struct ivopts_data
*data
, edge exit
)
2597 for (psi
= gsi_start_phis (exit
->dest
); !gsi_end_p (psi
); gsi_next (&psi
))
2600 def
= PHI_ARG_DEF_FROM_EDGE (phi
, exit
);
2601 if (!virtual_operand_p (def
))
2602 find_interesting_uses_op (data
, def
);
2606 /* Return TRUE if OFFSET is within the range of [base + offset] addressing
2607 mode for memory reference represented by USE. */
2609 static GTY (()) vec
<rtx
, va_gc
> *addr_list
;
2612 addr_offset_valid_p (struct iv_use
*use
, poly_int64 offset
)
2615 unsigned list_index
;
2616 addr_space_t as
= TYPE_ADDR_SPACE (TREE_TYPE (use
->iv
->base
));
2617 machine_mode addr_mode
, mem_mode
= TYPE_MODE (use
->mem_type
);
2619 list_index
= (unsigned) as
* MAX_MACHINE_MODE
+ (unsigned) mem_mode
;
2620 if (list_index
>= vec_safe_length (addr_list
))
2621 vec_safe_grow_cleared (addr_list
, list_index
+ MAX_MACHINE_MODE
, true);
2623 addr
= (*addr_list
)[list_index
];
2626 addr_mode
= targetm
.addr_space
.address_mode (as
);
2627 reg
= gen_raw_REG (addr_mode
, LAST_VIRTUAL_REGISTER
+ 1);
2628 addr
= gen_rtx_fmt_ee (PLUS
, addr_mode
, reg
, NULL_RTX
);
2629 (*addr_list
)[list_index
] = addr
;
2632 addr_mode
= GET_MODE (addr
);
2634 XEXP (addr
, 1) = gen_int_mode (offset
, addr_mode
);
2635 return (memory_address_addr_space_p (mem_mode
, addr
, as
));
2638 /* Comparison function to sort group in ascending order of addr_offset. */
2641 group_compare_offset (const void *a
, const void *b
)
2643 const struct iv_use
*const *u1
= (const struct iv_use
*const *) a
;
2644 const struct iv_use
*const *u2
= (const struct iv_use
*const *) b
;
2646 return compare_sizes_for_sort ((*u1
)->addr_offset
, (*u2
)->addr_offset
);
2649 /* Check if small groups should be split. Return true if no group
2650 contains more than two uses with distinct addr_offsets. Return
2651 false otherwise. We want to split such groups because:
2653 1) Small groups don't have much benefit and may interfer with
2654 general candidate selection.
2655 2) Size for problem with only small groups is usually small and
2656 general algorithm can handle it well.
2658 TODO -- Above claim may not hold when we want to merge memory
2659 accesses with conseuctive addresses. */
2662 split_small_address_groups_p (struct ivopts_data
*data
)
2664 unsigned int i
, j
, distinct
= 1;
2666 struct iv_group
*group
;
2668 for (i
= 0; i
< data
->vgroups
.length (); i
++)
2670 group
= data
->vgroups
[i
];
2671 if (group
->vuses
.length () == 1)
2674 gcc_assert (address_p (group
->type
));
2675 if (group
->vuses
.length () == 2)
2677 if (compare_sizes_for_sort (group
->vuses
[0]->addr_offset
,
2678 group
->vuses
[1]->addr_offset
) > 0)
2679 std::swap (group
->vuses
[0], group
->vuses
[1]);
2682 group
->vuses
.qsort (group_compare_offset
);
2688 for (pre
= group
->vuses
[0], j
= 1; j
< group
->vuses
.length (); j
++)
2690 if (maybe_ne (group
->vuses
[j
]->addr_offset
, pre
->addr_offset
))
2692 pre
= group
->vuses
[j
];
2701 return (distinct
<= 2);
2704 /* For each group of address type uses, this function further groups
2705 these uses according to the maximum offset supported by target's
2706 [base + offset] addressing mode. */
2709 split_address_groups (struct ivopts_data
*data
)
2712 /* Always split group. */
2713 bool split_p
= split_small_address_groups_p (data
);
2715 for (i
= 0; i
< data
->vgroups
.length (); i
++)
2717 struct iv_group
*new_group
= NULL
;
2718 struct iv_group
*group
= data
->vgroups
[i
];
2719 struct iv_use
*use
= group
->vuses
[0];
2722 use
->group_id
= group
->id
;
2723 if (group
->vuses
.length () == 1)
2726 gcc_assert (address_p (use
->type
));
2728 for (j
= 1; j
< group
->vuses
.length ();)
2730 struct iv_use
*next
= group
->vuses
[j
];
2731 poly_int64 offset
= next
->addr_offset
- use
->addr_offset
;
2733 /* Split group if aksed to, or the offset against the first
2734 use can't fit in offset part of addressing mode. IV uses
2735 having the same offset are still kept in one group. */
2736 if (maybe_ne (offset
, 0)
2737 && (split_p
|| !addr_offset_valid_p (use
, offset
)))
2740 new_group
= record_group (data
, group
->type
);
2741 group
->vuses
.ordered_remove (j
);
2742 new_group
->vuses
.safe_push (next
);
2747 next
->group_id
= group
->id
;
2753 /* Finds uses of the induction variables that are interesting. */
2756 find_interesting_uses (struct ivopts_data
*data
, basic_block
*body
)
2759 gimple_stmt_iterator bsi
;
2763 for (i
= 0; i
< data
->current_loop
->num_nodes
; i
++)
2768 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2769 if (e
->dest
!= EXIT_BLOCK_PTR_FOR_FN (cfun
)
2770 && !flow_bb_inside_loop_p (data
->current_loop
, e
->dest
))
2771 find_interesting_uses_outside (data
, e
);
2773 for (bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
2774 find_interesting_uses_stmt (data
, gsi_stmt (bsi
));
2775 for (bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
2776 if (!is_gimple_debug (gsi_stmt (bsi
)))
2777 find_interesting_uses_stmt (data
, gsi_stmt (bsi
));
2780 split_address_groups (data
);
2782 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2784 fprintf (dump_file
, "\n<IV Groups>:\n");
2785 dump_groups (dump_file
, data
);
2786 fprintf (dump_file
, "\n");
2790 /* Strips constant offsets from EXPR and stores them to OFFSET. If INSIDE_ADDR
2791 is true, assume we are inside an address. If TOP_COMPREF is true, assume
2792 we are at the top-level of the processed address. */
2795 strip_offset_1 (tree expr
, bool inside_addr
, bool top_compref
,
2798 tree op0
= NULL_TREE
, op1
= NULL_TREE
, tmp
, step
;
2799 enum tree_code code
;
2800 tree type
, orig_type
= TREE_TYPE (expr
);
2801 poly_int64 off0
, off1
;
2803 tree orig_expr
= expr
;
2807 type
= TREE_TYPE (expr
);
2808 code
= TREE_CODE (expr
);
2813 case POINTER_PLUS_EXPR
:
2816 op0
= TREE_OPERAND (expr
, 0);
2817 op1
= TREE_OPERAND (expr
, 1);
2819 op0
= strip_offset_1 (op0
, false, false, &off0
);
2820 op1
= strip_offset_1 (op1
, false, false, &off1
);
2822 *offset
= (code
== MINUS_EXPR
? off0
- off1
: off0
+ off1
);
2823 if (op0
== TREE_OPERAND (expr
, 0)
2824 && op1
== TREE_OPERAND (expr
, 1))
2827 if (integer_zerop (op1
))
2829 else if (integer_zerop (op0
))
2831 if (code
== MINUS_EXPR
)
2833 if (TYPE_OVERFLOW_UNDEFINED (type
))
2835 type
= unsigned_type_for (type
);
2836 op1
= fold_convert (type
, op1
);
2838 expr
= fold_build1 (NEGATE_EXPR
, type
, op1
);
2845 if (TYPE_OVERFLOW_UNDEFINED (type
))
2847 type
= unsigned_type_for (type
);
2848 if (code
== POINTER_PLUS_EXPR
)
2850 op0
= fold_convert (type
, op0
);
2851 op1
= fold_convert (type
, op1
);
2853 expr
= fold_build2 (code
, type
, op0
, op1
);
2856 return fold_convert (orig_type
, expr
);
2859 op1
= TREE_OPERAND (expr
, 1);
2860 if (!cst_and_fits_in_hwi (op1
))
2863 op0
= TREE_OPERAND (expr
, 0);
2864 op0
= strip_offset_1 (op0
, false, false, &off0
);
2865 if (op0
== TREE_OPERAND (expr
, 0))
2868 *offset
= off0
* int_cst_value (op1
);
2869 if (integer_zerop (op0
))
2873 if (TYPE_OVERFLOW_UNDEFINED (type
))
2875 type
= unsigned_type_for (type
);
2876 op0
= fold_convert (type
, op0
);
2877 op1
= fold_convert (type
, op1
);
2879 expr
= fold_build2 (MULT_EXPR
, type
, op0
, op1
);
2882 return fold_convert (orig_type
, expr
);
2885 case ARRAY_RANGE_REF
:
2889 step
= array_ref_element_size (expr
);
2890 if (!cst_and_fits_in_hwi (step
))
2893 st
= int_cst_value (step
);
2894 op1
= TREE_OPERAND (expr
, 1);
2895 op1
= strip_offset_1 (op1
, false, false, &off1
);
2896 *offset
= off1
* st
;
2899 && integer_zerop (op1
))
2901 /* Strip the component reference completely. */
2902 op0
= TREE_OPERAND (expr
, 0);
2903 op0
= strip_offset_1 (op0
, inside_addr
, top_compref
, &off0
);
2916 tmp
= component_ref_field_offset (expr
);
2917 field
= TREE_OPERAND (expr
, 1);
2919 && cst_and_fits_in_hwi (tmp
)
2920 && cst_and_fits_in_hwi (DECL_FIELD_BIT_OFFSET (field
)))
2922 HOST_WIDE_INT boffset
, abs_off
;
2924 /* Strip the component reference completely. */
2925 op0
= TREE_OPERAND (expr
, 0);
2926 op0
= strip_offset_1 (op0
, inside_addr
, top_compref
, &off0
);
2927 boffset
= int_cst_value (DECL_FIELD_BIT_OFFSET (field
));
2928 abs_off
= abs_hwi (boffset
) / BITS_PER_UNIT
;
2932 *offset
= off0
+ int_cst_value (tmp
) + abs_off
;
2939 op0
= TREE_OPERAND (expr
, 0);
2940 op0
= strip_offset_1 (op0
, true, true, &off0
);
2943 if (op0
== TREE_OPERAND (expr
, 0))
2946 expr
= build_fold_addr_expr (op0
);
2947 return fold_convert (orig_type
, expr
);
2950 /* ??? Offset operand? */
2951 inside_addr
= false;
2955 if (ptrdiff_tree_p (expr
, offset
) && maybe_ne (*offset
, 0))
2956 return build_int_cst (orig_type
, 0);
2960 /* Default handling of expressions for that we want to recurse into
2961 the first operand. */
2962 op0
= TREE_OPERAND (expr
, 0);
2963 op0
= strip_offset_1 (op0
, inside_addr
, false, &off0
);
2966 if (op0
== TREE_OPERAND (expr
, 0)
2967 && (!op1
|| op1
== TREE_OPERAND (expr
, 1)))
2970 expr
= copy_node (expr
);
2971 TREE_OPERAND (expr
, 0) = op0
;
2973 TREE_OPERAND (expr
, 1) = op1
;
2975 /* Inside address, we might strip the top level component references,
2976 thus changing type of the expression. Handling of ADDR_EXPR
2978 expr
= fold_convert (orig_type
, expr
);
2983 /* Strips constant offsets from EXPR and stores them to OFFSET. */
2986 strip_offset (tree expr
, poly_uint64
*offset
)
2989 tree core
= strip_offset_1 (expr
, false, false, &off
);
2994 /* Returns variant of TYPE that can be used as base for different uses.
2995 We return unsigned type with the same precision, which avoids problems
2999 generic_type_for (tree type
)
3001 if (POINTER_TYPE_P (type
))
3002 return unsigned_type_for (type
);
3004 if (TYPE_UNSIGNED (type
))
3007 return unsigned_type_for (type
);
3010 /* Private data for walk_tree. */
3012 struct walk_tree_data
3015 struct ivopts_data
*idata
;
3018 /* Callback function for walk_tree, it records invariants and symbol
3019 reference in *EXPR_P. DATA is the structure storing result info. */
3022 find_inv_vars_cb (tree
*expr_p
, int *ws ATTRIBUTE_UNUSED
, void *data
)
3025 struct version_info
*info
;
3026 struct walk_tree_data
*wdata
= (struct walk_tree_data
*) data
;
3028 if (TREE_CODE (op
) != SSA_NAME
)
3031 info
= name_info (wdata
->idata
, op
);
3032 /* Because we expand simple operations when finding IVs, loop invariant
3033 variable that isn't referred by the original loop could be used now.
3034 Record such invariant variables here. */
3037 struct ivopts_data
*idata
= wdata
->idata
;
3038 basic_block bb
= gimple_bb (SSA_NAME_DEF_STMT (op
));
3040 if (!bb
|| !flow_bb_inside_loop_p (idata
->current_loop
, bb
))
3042 tree steptype
= TREE_TYPE (op
);
3043 if (POINTER_TYPE_P (steptype
))
3044 steptype
= sizetype
;
3045 set_iv (idata
, op
, op
, build_int_cst (steptype
, 0), true);
3046 record_invariant (idata
, op
, false);
3049 if (!info
->inv_id
|| info
->has_nonlin_use
)
3052 if (!*wdata
->inv_vars
)
3053 *wdata
->inv_vars
= BITMAP_ALLOC (NULL
);
3054 bitmap_set_bit (*wdata
->inv_vars
, info
->inv_id
);
3059 /* Records invariants in *EXPR_P. INV_VARS is the bitmap to that we should
3063 find_inv_vars (struct ivopts_data
*data
, tree
*expr_p
, bitmap
*inv_vars
)
3065 struct walk_tree_data wdata
;
3071 wdata
.inv_vars
= inv_vars
;
3072 walk_tree (expr_p
, find_inv_vars_cb
, &wdata
, NULL
);
3075 /* Get entry from invariant expr hash table for INV_EXPR. New entry
3076 will be recorded if it doesn't exist yet. Given below two exprs:
3077 inv_expr + cst1, inv_expr + cst2
3078 It's hard to make decision whether constant part should be stripped
3079 or not. We choose to not strip based on below facts:
3080 1) We need to count ADD cost for constant part if it's stripped,
3081 which isn't always trivial where this functions is called.
3082 2) Stripping constant away may be conflict with following loop
3083 invariant hoisting pass.
3084 3) Not stripping constant away results in more invariant exprs,
3085 which usually leads to decision preferring lower reg pressure. */
3087 static iv_inv_expr_ent
*
3088 get_loop_invariant_expr (struct ivopts_data
*data
, tree inv_expr
)
3090 STRIP_NOPS (inv_expr
);
3092 if (poly_int_tree_p (inv_expr
)
3093 || TREE_CODE (inv_expr
) == SSA_NAME
)
3096 /* Don't strip constant part away as we used to. */
3098 /* Stores EXPR in DATA->inv_expr_tab, return pointer to iv_inv_expr_ent. */
3099 struct iv_inv_expr_ent ent
;
3100 ent
.expr
= inv_expr
;
3101 ent
.hash
= iterative_hash_expr (inv_expr
, 0);
3102 struct iv_inv_expr_ent
**slot
= data
->inv_expr_tab
->find_slot (&ent
, INSERT
);
3106 *slot
= XNEW (struct iv_inv_expr_ent
);
3107 (*slot
)->expr
= inv_expr
;
3108 (*slot
)->hash
= ent
.hash
;
3109 (*slot
)->id
= ++data
->max_inv_expr_id
;
3116 /* Return *TP if it is an SSA_NAME marked with TREE_VISITED, i.e., as
3117 unsuitable as ivopts candidates for potentially involving undefined
3121 find_ssa_undef (tree
*tp
, int *walk_subtrees
, void *bb_
)
3123 basic_block bb
= (basic_block
) bb_
;
3124 if (TREE_CODE (*tp
) == SSA_NAME
3125 && ssa_name_maybe_undef_p (*tp
)
3126 && !ssa_name_any_use_dominates_bb_p (*tp
, bb
))
3133 /* Adds a candidate BASE + STEP * i. Important field is set to IMPORTANT and
3134 position to POS. If USE is not NULL, the candidate is set as related to
3135 it. If both BASE and STEP are NULL, we add a pseudocandidate for the
3136 replacement of the final value of the iv by a direct computation. */
3138 static struct iv_cand
*
3139 add_candidate_1 (struct ivopts_data
*data
, tree base
, tree step
, bool important
,
3140 enum iv_position pos
, struct iv_use
*use
,
3141 gimple
*incremented_at
, struct iv
*orig_iv
= NULL
,
3142 bool doloop
= false)
3145 struct iv_cand
*cand
= NULL
;
3146 tree type
, orig_type
;
3148 gcc_assert (base
&& step
);
3150 /* -fkeep-gc-roots-live means that we have to keep a real pointer
3151 live, but the ivopts code may replace a real pointer with one
3152 pointing before or after the memory block that is then adjusted
3153 into the memory block during the loop. FIXME: It would likely be
3154 better to actually force the pointer live and still use ivopts;
3155 for example, it would be enough to write the pointer into memory
3156 and keep it there until after the loop. */
3157 if (flag_keep_gc_roots_live
&& POINTER_TYPE_P (TREE_TYPE (base
)))
3160 /* If BASE contains undefined SSA names make sure we only record
3162 bool involves_undefs
= false;
3163 if (walk_tree (&base
, find_ssa_undef
, data
->current_loop
->header
, NULL
))
3165 if (pos
!= IP_ORIGINAL
)
3168 involves_undefs
= true;
3171 /* For non-original variables, make sure their values are computed in a type
3172 that does not invoke undefined behavior on overflows (since in general,
3173 we cannot prove that these induction variables are non-wrapping). */
3174 if (pos
!= IP_ORIGINAL
)
3176 orig_type
= TREE_TYPE (base
);
3177 type
= generic_type_for (orig_type
);
3178 if (type
!= orig_type
)
3180 base
= fold_convert (type
, base
);
3181 step
= fold_convert (type
, step
);
3185 for (i
= 0; i
< data
->vcands
.length (); i
++)
3187 cand
= data
->vcands
[i
];
3189 if (cand
->pos
!= pos
)
3192 if (cand
->incremented_at
!= incremented_at
3193 || ((pos
== IP_AFTER_USE
|| pos
== IP_BEFORE_USE
)
3194 && cand
->ainc_use
!= use
))
3197 if (operand_equal_p (base
, cand
->iv
->base
, 0)
3198 && operand_equal_p (step
, cand
->iv
->step
, 0)
3199 && (TYPE_PRECISION (TREE_TYPE (base
))
3200 == TYPE_PRECISION (TREE_TYPE (cand
->iv
->base
))))
3204 if (i
== data
->vcands
.length ())
3206 cand
= XCNEW (struct iv_cand
);
3208 cand
->iv
= alloc_iv (data
, base
, step
);
3210 if (pos
!= IP_ORIGINAL
)
3213 cand
->var_before
= create_tmp_var_raw (TREE_TYPE (base
), "doloop");
3215 cand
->var_before
= create_tmp_var_raw (TREE_TYPE (base
), "ivtmp");
3216 cand
->var_after
= cand
->var_before
;
3218 cand
->important
= important
;
3219 cand
->involves_undefs
= involves_undefs
;
3220 cand
->incremented_at
= incremented_at
;
3221 cand
->doloop_p
= doloop
;
3222 data
->vcands
.safe_push (cand
);
3224 if (!poly_int_tree_p (step
))
3226 find_inv_vars (data
, &step
, &cand
->inv_vars
);
3228 iv_inv_expr_ent
*inv_expr
= get_loop_invariant_expr (data
, step
);
3229 /* Share bitmap between inv_vars and inv_exprs for cand. */
3230 if (inv_expr
!= NULL
)
3232 cand
->inv_exprs
= cand
->inv_vars
;
3233 cand
->inv_vars
= NULL
;
3234 if (cand
->inv_exprs
)
3235 bitmap_clear (cand
->inv_exprs
);
3237 cand
->inv_exprs
= BITMAP_ALLOC (NULL
);
3239 bitmap_set_bit (cand
->inv_exprs
, inv_expr
->id
);
3243 if (pos
== IP_AFTER_USE
|| pos
== IP_BEFORE_USE
)
3244 cand
->ainc_use
= use
;
3246 cand
->ainc_use
= NULL
;
3248 cand
->orig_iv
= orig_iv
;
3249 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3250 dump_cand (dump_file
, cand
);
3253 cand
->important
|= important
;
3254 cand
->doloop_p
|= doloop
;
3256 /* Relate candidate to the group for which it is added. */
3258 bitmap_set_bit (data
->vgroups
[use
->group_id
]->related_cands
, i
);
3263 /* Returns true if incrementing the induction variable at the end of the LOOP
3266 The purpose is to avoid splitting latch edge with a biv increment, thus
3267 creating a jump, possibly confusing other optimization passes and leaving
3268 less freedom to scheduler. So we allow IP_END only if IP_NORMAL is not
3269 available (so we do not have a better alternative), or if the latch edge
3270 is already nonempty. */
3273 allow_ip_end_pos_p (class loop
*loop
)
3275 if (!ip_normal_pos (loop
))
3278 if (!empty_block_p (ip_end_pos (loop
)))
3284 /* If possible, adds autoincrement candidates BASE + STEP * i based on use USE.
3285 Important field is set to IMPORTANT. */
3288 add_autoinc_candidates (struct ivopts_data
*data
, tree base
, tree step
,
3289 bool important
, struct iv_use
*use
)
3291 basic_block use_bb
= gimple_bb (use
->stmt
);
3292 machine_mode mem_mode
;
3293 unsigned HOST_WIDE_INT cstepi
;
3295 /* If we insert the increment in any position other than the standard
3296 ones, we must ensure that it is incremented once per iteration.
3297 It must not be in an inner nested loop, or one side of an if
3299 if (use_bb
->loop_father
!= data
->current_loop
3300 || !dominated_by_p (CDI_DOMINATORS
, data
->current_loop
->latch
, use_bb
)
3301 || stmt_can_throw_internal (cfun
, use
->stmt
)
3302 || !cst_and_fits_in_hwi (step
))
3305 cstepi
= int_cst_value (step
);
3307 mem_mode
= TYPE_MODE (use
->mem_type
);
3308 if (((USE_LOAD_PRE_INCREMENT (mem_mode
)
3309 || USE_STORE_PRE_INCREMENT (mem_mode
))
3310 && known_eq (GET_MODE_SIZE (mem_mode
), cstepi
))
3311 || ((USE_LOAD_PRE_DECREMENT (mem_mode
)
3312 || USE_STORE_PRE_DECREMENT (mem_mode
))
3313 && known_eq (GET_MODE_SIZE (mem_mode
), -cstepi
)))
3315 enum tree_code code
= MINUS_EXPR
;
3317 tree new_step
= step
;
3319 if (POINTER_TYPE_P (TREE_TYPE (base
)))
3321 new_step
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (step
), step
);
3322 code
= POINTER_PLUS_EXPR
;
3325 new_step
= fold_convert (TREE_TYPE (base
), new_step
);
3326 new_base
= fold_build2 (code
, TREE_TYPE (base
), base
, new_step
);
3327 add_candidate_1 (data
, new_base
, step
, important
, IP_BEFORE_USE
, use
,
3330 if (((USE_LOAD_POST_INCREMENT (mem_mode
)
3331 || USE_STORE_POST_INCREMENT (mem_mode
))
3332 && known_eq (GET_MODE_SIZE (mem_mode
), cstepi
))
3333 || ((USE_LOAD_POST_DECREMENT (mem_mode
)
3334 || USE_STORE_POST_DECREMENT (mem_mode
))
3335 && known_eq (GET_MODE_SIZE (mem_mode
), -cstepi
)))
3337 add_candidate_1 (data
, base
, step
, important
, IP_AFTER_USE
, use
,
3342 /* Adds a candidate BASE + STEP * i. Important field is set to IMPORTANT and
3343 position to POS. If USE is not NULL, the candidate is set as related to
3344 it. The candidate computation is scheduled before exit condition and at
3348 add_candidate (struct ivopts_data
*data
, tree base
, tree step
, bool important
,
3349 struct iv_use
*use
, struct iv
*orig_iv
= NULL
,
3350 bool doloop
= false)
3352 if (ip_normal_pos (data
->current_loop
))
3353 add_candidate_1 (data
, base
, step
, important
, IP_NORMAL
, use
, NULL
, orig_iv
,
3355 /* Exclude doloop candidate here since it requires decrement then comparison
3356 and jump, the IP_END position doesn't match. */
3357 if (!doloop
&& ip_end_pos (data
->current_loop
)
3358 && allow_ip_end_pos_p (data
->current_loop
))
3359 add_candidate_1 (data
, base
, step
, important
, IP_END
, use
, NULL
, orig_iv
);
3362 /* Adds standard iv candidates. */
3365 add_standard_iv_candidates (struct ivopts_data
*data
)
3367 add_candidate (data
, integer_zero_node
, integer_one_node
, true, NULL
);
3369 /* The same for a double-integer type if it is still fast enough. */
3371 (long_integer_type_node
) > TYPE_PRECISION (integer_type_node
)
3372 && TYPE_PRECISION (long_integer_type_node
) <= BITS_PER_WORD
)
3373 add_candidate (data
, build_int_cst (long_integer_type_node
, 0),
3374 build_int_cst (long_integer_type_node
, 1), true, NULL
);
3376 /* The same for a double-integer type if it is still fast enough. */
3378 (long_long_integer_type_node
) > TYPE_PRECISION (long_integer_type_node
)
3379 && TYPE_PRECISION (long_long_integer_type_node
) <= BITS_PER_WORD
)
3380 add_candidate (data
, build_int_cst (long_long_integer_type_node
, 0),
3381 build_int_cst (long_long_integer_type_node
, 1), true, NULL
);
3385 /* Adds candidates bases on the old induction variable IV. */
3388 add_iv_candidate_for_biv (struct ivopts_data
*data
, struct iv
*iv
)
3392 struct iv_cand
*cand
;
3394 /* Check if this biv is used in address type use. */
3395 if (iv
->no_overflow
&& iv
->have_address_use
3396 && INTEGRAL_TYPE_P (TREE_TYPE (iv
->base
))
3397 && TYPE_PRECISION (TREE_TYPE (iv
->base
)) < TYPE_PRECISION (sizetype
))
3399 tree base
= fold_convert (sizetype
, iv
->base
);
3400 tree step
= fold_convert (sizetype
, iv
->step
);
3402 /* Add iv cand of same precision as index part in TARGET_MEM_REF. */
3403 add_candidate (data
, base
, step
, true, NULL
, iv
);
3404 /* Add iv cand of the original type only if it has nonlinear use. */
3406 add_candidate (data
, iv
->base
, iv
->step
, true, NULL
);
3409 add_candidate (data
, iv
->base
, iv
->step
, true, NULL
);
3411 /* The same, but with initial value zero. */
3412 if (POINTER_TYPE_P (TREE_TYPE (iv
->base
)))
3413 add_candidate (data
, size_int (0), iv
->step
, true, NULL
);
3415 add_candidate (data
, build_int_cst (TREE_TYPE (iv
->base
), 0),
3416 iv
->step
, true, NULL
);
3418 phi
= SSA_NAME_DEF_STMT (iv
->ssa_name
);
3419 if (gimple_code (phi
) == GIMPLE_PHI
)
3421 /* Additionally record the possibility of leaving the original iv
3423 def
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_latch_edge (data
->current_loop
));
3424 /* Don't add candidate if it's from another PHI node because
3425 it's an affine iv appearing in the form of PEELED_CHREC. */
3426 phi
= SSA_NAME_DEF_STMT (def
);
3427 if (gimple_code (phi
) != GIMPLE_PHI
)
3429 cand
= add_candidate_1 (data
,
3430 iv
->base
, iv
->step
, true, IP_ORIGINAL
, NULL
,
3431 SSA_NAME_DEF_STMT (def
));
3434 cand
->var_before
= iv
->ssa_name
;
3435 cand
->var_after
= def
;
3439 gcc_assert (gimple_bb (phi
) == data
->current_loop
->header
);
3443 /* Adds candidates based on the old induction variables. */
3446 add_iv_candidate_for_bivs (struct ivopts_data
*data
)
3452 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, i
, bi
)
3454 iv
= ver_info (data
, i
)->iv
;
3455 if (iv
&& iv
->biv_p
&& !integer_zerop (iv
->step
))
3456 add_iv_candidate_for_biv (data
, iv
);
3460 /* Record common candidate {BASE, STEP} derived from USE in hashtable. */
3463 record_common_cand (struct ivopts_data
*data
, tree base
,
3464 tree step
, struct iv_use
*use
)
3466 class iv_common_cand ent
;
3467 class iv_common_cand
**slot
;
3471 ent
.hash
= iterative_hash_expr (base
, 0);
3472 ent
.hash
= iterative_hash_expr (step
, ent
.hash
);
3474 slot
= data
->iv_common_cand_tab
->find_slot (&ent
, INSERT
);
3477 *slot
= new iv_common_cand ();
3478 (*slot
)->base
= base
;
3479 (*slot
)->step
= step
;
3480 (*slot
)->uses
.create (8);
3481 (*slot
)->hash
= ent
.hash
;
3482 data
->iv_common_cands
.safe_push ((*slot
));
3485 gcc_assert (use
!= NULL
);
3486 (*slot
)->uses
.safe_push (use
);
3490 /* Comparison function used to sort common candidates. */
3493 common_cand_cmp (const void *p1
, const void *p2
)
3496 const class iv_common_cand
*const *const ccand1
3497 = (const class iv_common_cand
*const *)p1
;
3498 const class iv_common_cand
*const *const ccand2
3499 = (const class iv_common_cand
*const *)p2
;
3501 n1
= (*ccand1
)->uses
.length ();
3502 n2
= (*ccand2
)->uses
.length ();
3506 /* Adds IV candidates based on common candidated recorded. */
3509 add_iv_candidate_derived_from_uses (struct ivopts_data
*data
)
3512 struct iv_cand
*cand_1
, *cand_2
;
3514 data
->iv_common_cands
.qsort (common_cand_cmp
);
3515 for (i
= 0; i
< data
->iv_common_cands
.length (); i
++)
3517 class iv_common_cand
*ptr
= data
->iv_common_cands
[i
];
3519 /* Only add IV candidate if it's derived from multiple uses. */
3520 if (ptr
->uses
.length () <= 1)
3525 if (ip_normal_pos (data
->current_loop
))
3526 cand_1
= add_candidate_1 (data
, ptr
->base
, ptr
->step
,
3527 false, IP_NORMAL
, NULL
, NULL
);
3529 if (ip_end_pos (data
->current_loop
)
3530 && allow_ip_end_pos_p (data
->current_loop
))
3531 cand_2
= add_candidate_1 (data
, ptr
->base
, ptr
->step
,
3532 false, IP_END
, NULL
, NULL
);
3534 /* Bind deriving uses and the new candidates. */
3535 for (j
= 0; j
< ptr
->uses
.length (); j
++)
3537 struct iv_group
*group
= data
->vgroups
[ptr
->uses
[j
]->group_id
];
3539 bitmap_set_bit (group
->related_cands
, cand_1
->id
);
3541 bitmap_set_bit (group
->related_cands
, cand_2
->id
);
3545 /* Release data since it is useless from this point. */
3546 data
->iv_common_cand_tab
->empty ();
3547 data
->iv_common_cands
.truncate (0);
3550 /* Adds candidates based on the value of USE's iv. */
3553 add_iv_candidate_for_use (struct ivopts_data
*data
, struct iv_use
*use
)
3557 struct iv
*iv
= use
->iv
;
3558 tree basetype
= TREE_TYPE (iv
->base
);
3560 /* Don't add candidate for iv_use with non integer, pointer or non-mode
3561 precision types, instead, add candidate for the corresponding scev in
3562 unsigned type with the same precision. See PR93674 for more info. */
3563 if ((TREE_CODE (basetype
) != INTEGER_TYPE
&& !POINTER_TYPE_P (basetype
))
3564 || !type_has_mode_precision_p (basetype
))
3566 basetype
= lang_hooks
.types
.type_for_mode (TYPE_MODE (basetype
),
3567 TYPE_UNSIGNED (basetype
));
3568 add_candidate (data
, fold_convert (basetype
, iv
->base
),
3569 fold_convert (basetype
, iv
->step
), false, NULL
);
3573 add_candidate (data
, iv
->base
, iv
->step
, false, use
);
3575 /* Record common candidate for use in case it can be shared by others. */
3576 record_common_cand (data
, iv
->base
, iv
->step
, use
);
3578 /* Record common candidate with initial value zero. */
3579 basetype
= TREE_TYPE (iv
->base
);
3580 if (POINTER_TYPE_P (basetype
))
3581 basetype
= sizetype
;
3582 record_common_cand (data
, build_int_cst (basetype
, 0), iv
->step
, use
);
3584 /* Compare the cost of an address with an unscaled index with the cost of
3585 an address with a scaled index and add candidate if useful. */
3588 && poly_int_tree_p (iv
->step
, &step
)
3589 && address_p (use
->type
))
3591 poly_int64 new_step
;
3592 unsigned int fact
= preferred_mem_scale_factor
3594 TYPE_MODE (use
->mem_type
),
3595 optimize_loop_for_speed_p (data
->current_loop
));
3598 && multiple_p (step
, fact
, &new_step
))
3599 add_candidate (data
, size_int (0),
3600 wide_int_to_tree (sizetype
, new_step
),
3604 /* Record common candidate with constant offset stripped in base.
3605 Like the use itself, we also add candidate directly for it. */
3606 base
= strip_offset (iv
->base
, &offset
);
3607 if (maybe_ne (offset
, 0U) || base
!= iv
->base
)
3609 record_common_cand (data
, base
, iv
->step
, use
);
3610 add_candidate (data
, base
, iv
->step
, false, use
);
3613 /* Record common candidate with base_object removed in base. */
3616 if (iv
->base_object
!= NULL
&& TREE_CODE (base
) == POINTER_PLUS_EXPR
)
3618 tree step
= iv
->step
;
3621 base
= TREE_OPERAND (base
, 1);
3622 step
= fold_convert (sizetype
, step
);
3623 record_common_cand (data
, base
, step
, use
);
3624 /* Also record common candidate with offset stripped. */
3625 tree alt_base
, alt_offset
;
3626 split_constant_offset (base
, &alt_base
, &alt_offset
);
3627 if (!integer_zerop (alt_offset
))
3628 record_common_cand (data
, alt_base
, step
, use
);
3631 /* At last, add auto-incremental candidates. Make such variables
3632 important since other iv uses with same base object may be based
3634 if (use
!= NULL
&& address_p (use
->type
))
3635 add_autoinc_candidates (data
, iv
->base
, iv
->step
, true, use
);
3638 /* Adds candidates based on the uses. */
3641 add_iv_candidate_for_groups (struct ivopts_data
*data
)
3645 /* Only add candidate for the first use in group. */
3646 for (i
= 0; i
< data
->vgroups
.length (); i
++)
3648 struct iv_group
*group
= data
->vgroups
[i
];
3650 gcc_assert (group
->vuses
[0] != NULL
);
3651 add_iv_candidate_for_use (data
, group
->vuses
[0]);
3653 add_iv_candidate_derived_from_uses (data
);
3656 /* Record important candidates and add them to related_cands bitmaps. */
3659 record_important_candidates (struct ivopts_data
*data
)
3662 struct iv_group
*group
;
3664 for (i
= 0; i
< data
->vcands
.length (); i
++)
3666 struct iv_cand
*cand
= data
->vcands
[i
];
3668 if (cand
->important
)
3669 bitmap_set_bit (data
->important_candidates
, i
);
3672 data
->consider_all_candidates
= (data
->vcands
.length ()
3673 <= CONSIDER_ALL_CANDIDATES_BOUND
);
3675 /* Add important candidates to groups' related_cands bitmaps. */
3676 for (i
= 0; i
< data
->vgroups
.length (); i
++)
3678 group
= data
->vgroups
[i
];
3679 bitmap_ior_into (group
->related_cands
, data
->important_candidates
);
3683 /* Allocates the data structure mapping the (use, candidate) pairs to costs.
3684 If consider_all_candidates is true, we use a two-dimensional array, otherwise
3685 we allocate a simple list to every use. */
3688 alloc_use_cost_map (struct ivopts_data
*data
)
3690 unsigned i
, size
, s
;
3692 for (i
= 0; i
< data
->vgroups
.length (); i
++)
3694 struct iv_group
*group
= data
->vgroups
[i
];
3696 if (data
->consider_all_candidates
)
3697 size
= data
->vcands
.length ();
3700 s
= bitmap_count_bits (group
->related_cands
);
3702 /* Round up to the power of two, so that moduling by it is fast. */
3703 size
= s
? (1 << ceil_log2 (s
)) : 1;
3706 group
->n_map_members
= size
;
3707 group
->cost_map
= XCNEWVEC (class cost_pair
, size
);
3711 /* Sets cost of (GROUP, CAND) pair to COST and record that it depends
3712 on invariants INV_VARS and that the value used in expressing it is
3713 VALUE, and in case of iv elimination the comparison operator is COMP. */
3716 set_group_iv_cost (struct ivopts_data
*data
,
3717 struct iv_group
*group
, struct iv_cand
*cand
,
3718 comp_cost cost
, bitmap inv_vars
, tree value
,
3719 enum tree_code comp
, bitmap inv_exprs
)
3723 if (cost
.infinite_cost_p ())
3725 BITMAP_FREE (inv_vars
);
3726 BITMAP_FREE (inv_exprs
);
3730 if (data
->consider_all_candidates
)
3732 group
->cost_map
[cand
->id
].cand
= cand
;
3733 group
->cost_map
[cand
->id
].cost
= cost
;
3734 group
->cost_map
[cand
->id
].inv_vars
= inv_vars
;
3735 group
->cost_map
[cand
->id
].inv_exprs
= inv_exprs
;
3736 group
->cost_map
[cand
->id
].value
= value
;
3737 group
->cost_map
[cand
->id
].comp
= comp
;
3741 /* n_map_members is a power of two, so this computes modulo. */
3742 s
= cand
->id
& (group
->n_map_members
- 1);
3743 for (i
= s
; i
< group
->n_map_members
; i
++)
3744 if (!group
->cost_map
[i
].cand
)
3746 for (i
= 0; i
< s
; i
++)
3747 if (!group
->cost_map
[i
].cand
)
3753 group
->cost_map
[i
].cand
= cand
;
3754 group
->cost_map
[i
].cost
= cost
;
3755 group
->cost_map
[i
].inv_vars
= inv_vars
;
3756 group
->cost_map
[i
].inv_exprs
= inv_exprs
;
3757 group
->cost_map
[i
].value
= value
;
3758 group
->cost_map
[i
].comp
= comp
;
3761 /* Gets cost of (GROUP, CAND) pair. */
3763 static class cost_pair
*
3764 get_group_iv_cost (struct ivopts_data
*data
, struct iv_group
*group
,
3765 struct iv_cand
*cand
)
3768 class cost_pair
*ret
;
3773 if (data
->consider_all_candidates
)
3775 ret
= group
->cost_map
+ cand
->id
;
3782 /* n_map_members is a power of two, so this computes modulo. */
3783 s
= cand
->id
& (group
->n_map_members
- 1);
3784 for (i
= s
; i
< group
->n_map_members
; i
++)
3785 if (group
->cost_map
[i
].cand
== cand
)
3786 return group
->cost_map
+ i
;
3787 else if (group
->cost_map
[i
].cand
== NULL
)
3789 for (i
= 0; i
< s
; i
++)
3790 if (group
->cost_map
[i
].cand
== cand
)
3791 return group
->cost_map
+ i
;
3792 else if (group
->cost_map
[i
].cand
== NULL
)
3798 /* Produce DECL_RTL for object obj so it looks like it is stored in memory. */
3800 produce_memory_decl_rtl (tree obj
, int *regno
)
3802 addr_space_t as
= TYPE_ADDR_SPACE (TREE_TYPE (obj
));
3803 machine_mode address_mode
= targetm
.addr_space
.address_mode (as
);
3807 if (TREE_STATIC (obj
) || DECL_EXTERNAL (obj
))
3809 const char *name
= IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj
));
3810 x
= gen_rtx_SYMBOL_REF (address_mode
, name
);
3811 SET_SYMBOL_REF_DECL (x
, obj
);
3812 x
= gen_rtx_MEM (DECL_MODE (obj
), x
);
3813 set_mem_addr_space (x
, as
);
3814 targetm
.encode_section_info (obj
, x
, true);
3818 x
= gen_raw_REG (address_mode
, (*regno
)++);
3819 x
= gen_rtx_MEM (DECL_MODE (obj
), x
);
3820 set_mem_addr_space (x
, as
);
3826 /* Prepares decl_rtl for variables referred in *EXPR_P. Callback for
3827 walk_tree. DATA contains the actual fake register number. */
3830 prepare_decl_rtl (tree
*expr_p
, int *ws
, void *data
)
3832 tree obj
= NULL_TREE
;
3834 int *regno
= (int *) data
;
3836 switch (TREE_CODE (*expr_p
))
3839 for (expr_p
= &TREE_OPERAND (*expr_p
, 0);
3840 handled_component_p (*expr_p
);
3841 expr_p
= &TREE_OPERAND (*expr_p
, 0))
3844 if (DECL_P (obj
) && HAS_RTL_P (obj
) && !DECL_RTL_SET_P (obj
))
3845 x
= produce_memory_decl_rtl (obj
, regno
);
3850 obj
= SSA_NAME_VAR (*expr_p
);
3851 /* Defer handling of anonymous SSA_NAMEs to the expander. */
3854 if (!DECL_RTL_SET_P (obj
))
3855 x
= gen_raw_REG (DECL_MODE (obj
), (*regno
)++);
3864 if (DECL_RTL_SET_P (obj
))
3867 if (DECL_MODE (obj
) == BLKmode
)
3868 x
= produce_memory_decl_rtl (obj
, regno
);
3870 x
= gen_raw_REG (DECL_MODE (obj
), (*regno
)++);
3880 decl_rtl_to_reset
.safe_push (obj
);
3881 SET_DECL_RTL (obj
, x
);
3887 /* Predict whether the given loop will be transformed in the RTL
3888 doloop_optimize pass. Attempt to duplicate some doloop_optimize checks.
3889 This is only for target independent checks, see targetm.predict_doloop_p
3890 for the target dependent ones.
3892 Note that according to some initial investigation, some checks like costly
3893 niter check and invalid stmt scanning don't have much gains among general
3894 cases, so keep this as simple as possible first.
3896 Some RTL specific checks seems unable to be checked in gimple, if any new
3897 checks or easy checks _are_ missing here, please add them. */
3900 generic_predict_doloop_p (struct ivopts_data
*data
)
3902 class loop
*loop
= data
->current_loop
;
3904 /* Call target hook for target dependent checks. */
3905 if (!targetm
.predict_doloop_p (loop
))
3907 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3908 fprintf (dump_file
, "Predict doloop failure due to"
3909 " target specific checks.\n");
3913 /* Similar to doloop_optimize, check iteration description to know it's
3914 suitable or not. Keep it as simple as possible, feel free to extend it
3915 if you find any multiple exits cases matter. */
3916 edge exit
= single_dom_exit (loop
);
3917 class tree_niter_desc
*niter_desc
;
3918 if (!exit
|| !(niter_desc
= niter_for_exit (data
, exit
)))
3920 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3921 fprintf (dump_file
, "Predict doloop failure due to"
3922 " unexpected niters.\n");
3926 /* Similar to doloop_optimize, check whether iteration count too small
3927 and not profitable. */
3928 HOST_WIDE_INT est_niter
= get_estimated_loop_iterations_int (loop
);
3929 if (est_niter
== -1)
3930 est_niter
= get_likely_max_loop_iterations_int (loop
);
3931 if (est_niter
>= 0 && est_niter
< 3)
3933 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3935 "Predict doloop failure due to"
3936 " too few iterations (%u).\n",
3937 (unsigned int) est_niter
);
3944 /* Determines cost of the computation of EXPR. */
3947 computation_cost (tree expr
, bool speed
)
3951 tree type
= TREE_TYPE (expr
);
3953 /* Avoid using hard regs in ways which may be unsupported. */
3954 int regno
= LAST_VIRTUAL_REGISTER
+ 1;
3955 struct cgraph_node
*node
= cgraph_node::get (current_function_decl
);
3956 enum node_frequency real_frequency
= node
->frequency
;
3958 node
->frequency
= NODE_FREQUENCY_NORMAL
;
3959 crtl
->maybe_hot_insn_p
= speed
;
3960 walk_tree (&expr
, prepare_decl_rtl
, ®no
, NULL
);
3962 rslt
= expand_expr (expr
, NULL_RTX
, TYPE_MODE (type
), EXPAND_NORMAL
);
3965 default_rtl_profile ();
3966 node
->frequency
= real_frequency
;
3968 cost
= seq_cost (seq
, speed
);
3970 cost
+= address_cost (XEXP (rslt
, 0), TYPE_MODE (type
),
3971 TYPE_ADDR_SPACE (type
), speed
);
3972 else if (!REG_P (rslt
))
3973 cost
+= set_src_cost (rslt
, TYPE_MODE (type
), speed
);
3978 /* Returns variable containing the value of candidate CAND at statement AT. */
3981 var_at_stmt (class loop
*loop
, struct iv_cand
*cand
, gimple
*stmt
)
3983 if (stmt_after_increment (loop
, cand
, stmt
))
3984 return cand
->var_after
;
3986 return cand
->var_before
;
3989 /* If A is (TYPE) BA and B is (TYPE) BB, and the types of BA and BB have the
3990 same precision that is at least as wide as the precision of TYPE, stores
3991 BA to A and BB to B, and returns the type of BA. Otherwise, returns the
3995 determine_common_wider_type (tree
*a
, tree
*b
)
3997 tree wider_type
= NULL
;
3999 tree atype
= TREE_TYPE (*a
);
4001 if (CONVERT_EXPR_P (*a
))
4003 suba
= TREE_OPERAND (*a
, 0);
4004 wider_type
= TREE_TYPE (suba
);
4005 if (TYPE_PRECISION (wider_type
) < TYPE_PRECISION (atype
))
4011 if (CONVERT_EXPR_P (*b
))
4013 subb
= TREE_OPERAND (*b
, 0);
4014 if (TYPE_PRECISION (wider_type
) != TYPE_PRECISION (TREE_TYPE (subb
)))
4025 /* Determines the expression by that USE is expressed from induction variable
4026 CAND at statement AT in LOOP. The expression is stored in two parts in a
4027 decomposed form. The invariant part is stored in AFF_INV; while variant
4028 part in AFF_VAR. Store ratio of CAND.step over USE.step in PRAT if it's
4029 non-null. Returns false if USE cannot be expressed using CAND. */
4032 get_computation_aff_1 (class loop
*loop
, gimple
*at
, struct iv_use
*use
,
4033 struct iv_cand
*cand
, class aff_tree
*aff_inv
,
4034 class aff_tree
*aff_var
, widest_int
*prat
= NULL
)
4036 tree ubase
= use
->iv
->base
, ustep
= use
->iv
->step
;
4037 tree cbase
= cand
->iv
->base
, cstep
= cand
->iv
->step
;
4038 tree common_type
, uutype
, var
, cstep_common
;
4039 tree utype
= TREE_TYPE (ubase
), ctype
= TREE_TYPE (cbase
);
4043 /* We must have a precision to express the values of use. */
4044 if (TYPE_PRECISION (utype
) > TYPE_PRECISION (ctype
))
4047 var
= var_at_stmt (loop
, cand
, at
);
4048 uutype
= unsigned_type_for (utype
);
4050 /* If the conversion is not noop, perform it. */
4051 if (TYPE_PRECISION (utype
) < TYPE_PRECISION (ctype
))
4053 if (cand
->orig_iv
!= NULL
&& CONVERT_EXPR_P (cbase
)
4054 && (CONVERT_EXPR_P (cstep
) || poly_int_tree_p (cstep
)))
4056 tree inner_base
, inner_step
, inner_type
;
4057 inner_base
= TREE_OPERAND (cbase
, 0);
4058 if (CONVERT_EXPR_P (cstep
))
4059 inner_step
= TREE_OPERAND (cstep
, 0);
4063 inner_type
= TREE_TYPE (inner_base
);
4064 /* If candidate is added from a biv whose type is smaller than
4065 ctype, we know both candidate and the biv won't overflow.
4066 In this case, it's safe to skip the convertion in candidate.
4067 As an example, (unsigned short)((unsigned long)A) equals to
4068 (unsigned short)A, if A has a type no larger than short. */
4069 if (TYPE_PRECISION (inner_type
) <= TYPE_PRECISION (uutype
))
4075 cbase
= fold_convert (uutype
, cbase
);
4076 cstep
= fold_convert (uutype
, cstep
);
4077 var
= fold_convert (uutype
, var
);
4080 /* Ratio is 1 when computing the value of biv cand by itself.
4081 We can't rely on constant_multiple_of in this case because the
4082 use is created after the original biv is selected. The call
4083 could fail because of inconsistent fold behavior. See PR68021
4084 for more information. */
4085 if (cand
->pos
== IP_ORIGINAL
&& cand
->incremented_at
== use
->stmt
)
4087 gcc_assert (is_gimple_assign (use
->stmt
));
4088 gcc_assert (use
->iv
->ssa_name
== cand
->var_after
);
4089 gcc_assert (gimple_assign_lhs (use
->stmt
) == cand
->var_after
);
4092 else if (!constant_multiple_of (ustep
, cstep
, &rat
))
4098 /* In case both UBASE and CBASE are shortened to UUTYPE from some common
4099 type, we achieve better folding by computing their difference in this
4100 wider type, and cast the result to UUTYPE. We do not need to worry about
4101 overflows, as all the arithmetics will in the end be performed in UUTYPE
4103 common_type
= determine_common_wider_type (&ubase
, &cbase
);
4105 /* use = ubase - ratio * cbase + ratio * var. */
4106 tree_to_aff_combination (ubase
, common_type
, aff_inv
);
4107 tree_to_aff_combination (cbase
, common_type
, &aff_cbase
);
4108 tree_to_aff_combination (var
, uutype
, aff_var
);
4110 /* We need to shift the value if we are after the increment. */
4111 if (stmt_after_increment (loop
, cand
, at
))
4115 if (common_type
!= uutype
)
4116 cstep_common
= fold_convert (common_type
, cstep
);
4118 cstep_common
= cstep
;
4120 tree_to_aff_combination (cstep_common
, common_type
, &cstep_aff
);
4121 aff_combination_add (&aff_cbase
, &cstep_aff
);
4124 aff_combination_scale (&aff_cbase
, -rat
);
4125 aff_combination_add (aff_inv
, &aff_cbase
);
4126 if (common_type
!= uutype
)
4127 aff_combination_convert (aff_inv
, uutype
);
4129 aff_combination_scale (aff_var
, rat
);
4133 /* Determines the expression by that USE is expressed from induction variable
4134 CAND at statement AT in LOOP. The expression is stored in a decomposed
4135 form into AFF. Returns false if USE cannot be expressed using CAND. */
4138 get_computation_aff (class loop
*loop
, gimple
*at
, struct iv_use
*use
,
4139 struct iv_cand
*cand
, class aff_tree
*aff
)
4143 if (!get_computation_aff_1 (loop
, at
, use
, cand
, aff
, &aff_var
))
4146 aff_combination_add (aff
, &aff_var
);
4150 /* Return the type of USE. */
4153 get_use_type (struct iv_use
*use
)
4155 tree base_type
= TREE_TYPE (use
->iv
->base
);
4158 if (use
->type
== USE_REF_ADDRESS
)
4160 /* The base_type may be a void pointer. Create a pointer type based on
4161 the mem_ref instead. */
4162 type
= build_pointer_type (TREE_TYPE (*use
->op_p
));
4163 gcc_assert (TYPE_ADDR_SPACE (TREE_TYPE (type
))
4164 == TYPE_ADDR_SPACE (TREE_TYPE (base_type
)));
4172 /* Determines the expression by that USE is expressed from induction variable
4173 CAND at statement AT in LOOP. The computation is unshared. */
4176 get_computation_at (class loop
*loop
, gimple
*at
,
4177 struct iv_use
*use
, struct iv_cand
*cand
)
4180 tree type
= get_use_type (use
);
4182 if (!get_computation_aff (loop
, at
, use
, cand
, &aff
))
4184 unshare_aff_combination (&aff
);
4185 return fold_convert (type
, aff_combination_to_tree (&aff
));
4188 /* Like get_computation_at, but try harder, even if the computation
4189 is more expensive. Intended for debug stmts. */
4192 get_debug_computation_at (class loop
*loop
, gimple
*at
,
4193 struct iv_use
*use
, struct iv_cand
*cand
)
4195 if (tree ret
= get_computation_at (loop
, at
, use
, cand
))
4198 tree ubase
= use
->iv
->base
, ustep
= use
->iv
->step
;
4199 tree cbase
= cand
->iv
->base
, cstep
= cand
->iv
->step
;
4201 tree utype
= TREE_TYPE (ubase
), ctype
= TREE_TYPE (cbase
);
4204 /* We must have a precision to express the values of use. */
4205 if (TYPE_PRECISION (utype
) >= TYPE_PRECISION (ctype
))
4208 /* Try to handle the case that get_computation_at doesn't,
4210 use = ubase + (var - cbase) / ratio. */
4211 if (!constant_multiple_of (cstep
, fold_convert (TREE_TYPE (cstep
), ustep
),
4216 if (wi::neg_p (rat
))
4218 if (TYPE_UNSIGNED (ctype
))
4221 rat
= wi::neg (rat
);
4224 /* If both IVs can wrap around and CAND doesn't have a power of two step,
4225 it is unsafe. Consider uint16_t CAND with step 9, when wrapping around,
4226 the values will be ... 0xfff0, 0xfff9, 2, 11 ... and when use is say
4227 uint8_t with step 3, those values divided by 3 cast to uint8_t will be
4228 ... 0x50, 0x53, 0, 3 ... rather than expected 0x50, 0x53, 0x56, 0x59. */
4229 if (!use
->iv
->no_overflow
4230 && !cand
->iv
->no_overflow
4231 && !integer_pow2p (cstep
))
4234 int bits
= wi::exact_log2 (rat
);
4236 bits
= wi::floor_log2 (rat
) + 1;
4237 if (!cand
->iv
->no_overflow
4238 && TYPE_PRECISION (utype
) + bits
> TYPE_PRECISION (ctype
))
4241 var
= var_at_stmt (loop
, cand
, at
);
4243 if (POINTER_TYPE_P (ctype
))
4245 ctype
= unsigned_type_for (ctype
);
4246 cbase
= fold_convert (ctype
, cbase
);
4247 cstep
= fold_convert (ctype
, cstep
);
4248 var
= fold_convert (ctype
, var
);
4251 if (stmt_after_increment (loop
, cand
, at
))
4252 var
= fold_build2 (MINUS_EXPR
, TREE_TYPE (var
), var
,
4253 unshare_expr (cstep
));
4255 var
= fold_build2 (MINUS_EXPR
, TREE_TYPE (var
), var
, cbase
);
4256 var
= fold_build2 (EXACT_DIV_EXPR
, TREE_TYPE (var
), var
,
4257 wide_int_to_tree (TREE_TYPE (var
), rat
));
4258 if (POINTER_TYPE_P (utype
))
4260 var
= fold_convert (sizetype
, var
);
4262 var
= fold_build1 (NEGATE_EXPR
, sizetype
, var
);
4263 var
= fold_build2 (POINTER_PLUS_EXPR
, utype
, ubase
, var
);
4267 var
= fold_convert (utype
, var
);
4268 var
= fold_build2 (neg_p
? MINUS_EXPR
: PLUS_EXPR
, utype
,
4274 /* Adjust the cost COST for being in loop setup rather than loop body.
4275 If we're optimizing for space, the loop setup overhead is constant;
4276 if we're optimizing for speed, amortize it over the per-iteration cost.
4277 If ROUND_UP_P is true, the result is round up rather than to zero when
4278 optimizing for speed. */
4280 adjust_setup_cost (struct ivopts_data
*data
, int64_t cost
,
4281 bool round_up_p
= false)
4285 else if (optimize_loop_for_speed_p (data
->current_loop
))
4287 int64_t niters
= (int64_t) avg_loop_niter (data
->current_loop
);
4288 return (cost
+ (round_up_p
? niters
- 1 : 0)) / niters
;
4294 /* Calculate the SPEED or size cost of shiftadd EXPR in MODE. MULT is the
4295 EXPR operand holding the shift. COST0 and COST1 are the costs for
4296 calculating the operands of EXPR. Returns true if successful, and returns
4297 the cost in COST. */
4300 get_shiftadd_cost (tree expr
, scalar_int_mode mode
, comp_cost cost0
,
4301 comp_cost cost1
, tree mult
, bool speed
, comp_cost
*cost
)
4304 tree op1
= TREE_OPERAND (expr
, 1);
4305 tree cst
= TREE_OPERAND (mult
, 1);
4306 tree multop
= TREE_OPERAND (mult
, 0);
4307 int m
= exact_log2 (int_cst_value (cst
));
4308 int maxm
= MIN (BITS_PER_WORD
, GET_MODE_BITSIZE (mode
));
4309 int as_cost
, sa_cost
;
4312 if (!(m
>= 0 && m
< maxm
))
4316 mult_in_op1
= operand_equal_p (op1
, mult
, 0);
4318 as_cost
= add_cost (speed
, mode
) + shift_cost (speed
, mode
, m
);
4320 /* If the target has a cheap shift-and-add or shift-and-sub instruction,
4321 use that in preference to a shift insn followed by an add insn. */
4322 sa_cost
= (TREE_CODE (expr
) != MINUS_EXPR
4323 ? shiftadd_cost (speed
, mode
, m
)
4325 ? shiftsub1_cost (speed
, mode
, m
)
4326 : shiftsub0_cost (speed
, mode
, m
)));
4328 res
= comp_cost (MIN (as_cost
, sa_cost
), 0);
4329 res
+= (mult_in_op1
? cost0
: cost1
);
4331 STRIP_NOPS (multop
);
4332 if (!is_gimple_val (multop
))
4333 res
+= force_expr_to_var_cost (multop
, speed
);
4339 /* Estimates cost of forcing expression EXPR into a variable. */
4342 force_expr_to_var_cost (tree expr
, bool speed
)
4344 static bool costs_initialized
= false;
4345 static unsigned integer_cost
[2];
4346 static unsigned symbol_cost
[2];
4347 static unsigned address_cost
[2];
4349 comp_cost cost0
, cost1
, cost
;
4351 scalar_int_mode int_mode
;
4353 if (!costs_initialized
)
4355 tree type
= build_pointer_type (integer_type_node
);
4360 var
= create_tmp_var_raw (integer_type_node
, "test_var");
4361 TREE_STATIC (var
) = 1;
4362 x
= produce_memory_decl_rtl (var
, NULL
);
4363 SET_DECL_RTL (var
, x
);
4365 addr
= build1 (ADDR_EXPR
, type
, var
);
4368 for (i
= 0; i
< 2; i
++)
4370 integer_cost
[i
] = computation_cost (build_int_cst (integer_type_node
,
4373 symbol_cost
[i
] = computation_cost (addr
, i
) + 1;
4376 = computation_cost (fold_build_pointer_plus_hwi (addr
, 2000), i
) + 1;
4377 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4379 fprintf (dump_file
, "force_expr_to_var_cost %s costs:\n", i
? "speed" : "size");
4380 fprintf (dump_file
, " integer %d\n", (int) integer_cost
[i
]);
4381 fprintf (dump_file
, " symbol %d\n", (int) symbol_cost
[i
]);
4382 fprintf (dump_file
, " address %d\n", (int) address_cost
[i
]);
4383 fprintf (dump_file
, " other %d\n", (int) target_spill_cost
[i
]);
4384 fprintf (dump_file
, "\n");
4388 costs_initialized
= true;
4393 if (SSA_VAR_P (expr
))
4396 if (is_gimple_min_invariant (expr
))
4398 if (poly_int_tree_p (expr
))
4399 return comp_cost (integer_cost
[speed
], 0);
4401 if (TREE_CODE (expr
) == ADDR_EXPR
)
4403 tree obj
= TREE_OPERAND (expr
, 0);
4406 || TREE_CODE (obj
) == PARM_DECL
4407 || TREE_CODE (obj
) == RESULT_DECL
)
4408 return comp_cost (symbol_cost
[speed
], 0);
4411 return comp_cost (address_cost
[speed
], 0);
4414 switch (TREE_CODE (expr
))
4416 case POINTER_PLUS_EXPR
:
4420 case TRUNC_DIV_EXPR
:
4425 op0
= TREE_OPERAND (expr
, 0);
4426 op1
= TREE_OPERAND (expr
, 1);
4434 op0
= TREE_OPERAND (expr
, 0);
4438 /* See add_iv_candidate_for_doloop, for doloop may_be_zero case, we
4439 introduce COND_EXPR for IV base, need to support better cost estimation
4440 for this COND_EXPR and tcc_comparison. */
4442 op0
= TREE_OPERAND (expr
, 1);
4444 op1
= TREE_OPERAND (expr
, 2);
4453 case UNORDERED_EXPR
:
4463 op0
= TREE_OPERAND (expr
, 0);
4465 op1
= TREE_OPERAND (expr
, 1);
4470 /* Just an arbitrary value, FIXME. */
4471 return comp_cost (target_spill_cost
[speed
], 0);
4474 if (op0
== NULL_TREE
4475 || TREE_CODE (op0
) == SSA_NAME
|| CONSTANT_CLASS_P (op0
))
4478 cost0
= force_expr_to_var_cost (op0
, speed
);
4480 if (op1
== NULL_TREE
4481 || TREE_CODE (op1
) == SSA_NAME
|| CONSTANT_CLASS_P (op1
))
4484 cost1
= force_expr_to_var_cost (op1
, speed
);
4486 mode
= TYPE_MODE (TREE_TYPE (expr
));
4487 switch (TREE_CODE (expr
))
4489 case POINTER_PLUS_EXPR
:
4493 cost
= comp_cost (add_cost (speed
, mode
), 0);
4494 if (TREE_CODE (expr
) != NEGATE_EXPR
)
4496 tree mult
= NULL_TREE
;
4498 if (TREE_CODE (op1
) == MULT_EXPR
)
4500 else if (TREE_CODE (op0
) == MULT_EXPR
)
4503 if (mult
!= NULL_TREE
4504 && is_a
<scalar_int_mode
> (mode
, &int_mode
)
4505 && cst_and_fits_in_hwi (TREE_OPERAND (mult
, 1))
4506 && get_shiftadd_cost (expr
, int_mode
, cost0
, cost1
, mult
,
4514 tree inner_mode
, outer_mode
;
4515 outer_mode
= TREE_TYPE (expr
);
4516 inner_mode
= TREE_TYPE (op0
);
4517 cost
= comp_cost (convert_cost (TYPE_MODE (outer_mode
),
4518 TYPE_MODE (inner_mode
), speed
), 0);
4523 if (cst_and_fits_in_hwi (op0
))
4524 cost
= comp_cost (mult_by_coeff_cost (int_cst_value (op0
),
4526 else if (cst_and_fits_in_hwi (op1
))
4527 cost
= comp_cost (mult_by_coeff_cost (int_cst_value (op1
),
4530 return comp_cost (target_spill_cost
[speed
], 0);
4533 case TRUNC_DIV_EXPR
:
4534 /* Division by power of two is usually cheap, so we allow it. Forbid
4536 if (integer_pow2p (TREE_OPERAND (expr
, 1)))
4537 cost
= comp_cost (add_cost (speed
, mode
), 0);
4539 cost
= comp_cost (target_spill_cost
[speed
], 0);
4547 cost
= comp_cost (add_cost (speed
, mode
), 0);
4550 op0
= TREE_OPERAND (expr
, 0);
4552 if (op0
== NULL_TREE
|| TREE_CODE (op0
) == SSA_NAME
4553 || CONSTANT_CLASS_P (op0
))
4556 cost
= force_expr_to_var_cost (op0
, speed
);
4564 case UNORDERED_EXPR
:
4574 /* Simply use add cost for now, FIXME if there is some more accurate cost
4576 cost
= comp_cost (add_cost (speed
, mode
), 0);
4588 /* Estimates cost of forcing EXPR into a variable. INV_VARS is a set of the
4589 invariants the computation depends on. */
4592 force_var_cost (struct ivopts_data
*data
, tree expr
, bitmap
*inv_vars
)
4597 find_inv_vars (data
, &expr
, inv_vars
);
4598 return force_expr_to_var_cost (expr
, data
->speed
);
4601 /* Returns cost of auto-modifying address expression in shape base + offset.
4602 AINC_STEP is step size of the address IV. AINC_OFFSET is offset of the
4603 address expression. The address expression has ADDR_MODE in addr space
4604 AS. The memory access has MEM_MODE. SPEED means we are optimizing for
4609 AINC_PRE_INC
, /* Pre increment. */
4610 AINC_PRE_DEC
, /* Pre decrement. */
4611 AINC_POST_INC
, /* Post increment. */
4612 AINC_POST_DEC
, /* Post decrement. */
4613 AINC_NONE
/* Also the number of auto increment types. */
4616 struct ainc_cost_data
4618 int64_t costs
[AINC_NONE
];
4622 get_address_cost_ainc (poly_int64 ainc_step
, poly_int64 ainc_offset
,
4623 machine_mode addr_mode
, machine_mode mem_mode
,
4624 addr_space_t as
, bool speed
)
4626 if (!USE_LOAD_PRE_DECREMENT (mem_mode
)
4627 && !USE_STORE_PRE_DECREMENT (mem_mode
)
4628 && !USE_LOAD_POST_DECREMENT (mem_mode
)
4629 && !USE_STORE_POST_DECREMENT (mem_mode
)
4630 && !USE_LOAD_PRE_INCREMENT (mem_mode
)
4631 && !USE_STORE_PRE_INCREMENT (mem_mode
)
4632 && !USE_LOAD_POST_INCREMENT (mem_mode
)
4633 && !USE_STORE_POST_INCREMENT (mem_mode
))
4634 return infinite_cost
;
4636 static vec
<ainc_cost_data
*> ainc_cost_data_list
;
4637 unsigned idx
= (unsigned) as
* MAX_MACHINE_MODE
+ (unsigned) mem_mode
;
4638 if (idx
>= ainc_cost_data_list
.length ())
4640 unsigned nsize
= ((unsigned) as
+ 1) *MAX_MACHINE_MODE
;
4642 gcc_assert (nsize
> idx
);
4643 ainc_cost_data_list
.safe_grow_cleared (nsize
, true);
4646 ainc_cost_data
*data
= ainc_cost_data_list
[idx
];
4649 rtx reg
= gen_raw_REG (addr_mode
, LAST_VIRTUAL_REGISTER
+ 1);
4651 data
= (ainc_cost_data
*) xcalloc (1, sizeof (*data
));
4652 data
->costs
[AINC_PRE_DEC
] = INFTY
;
4653 data
->costs
[AINC_POST_DEC
] = INFTY
;
4654 data
->costs
[AINC_PRE_INC
] = INFTY
;
4655 data
->costs
[AINC_POST_INC
] = INFTY
;
4656 if (USE_LOAD_PRE_DECREMENT (mem_mode
)
4657 || USE_STORE_PRE_DECREMENT (mem_mode
))
4659 rtx addr
= gen_rtx_PRE_DEC (addr_mode
, reg
);
4661 if (memory_address_addr_space_p (mem_mode
, addr
, as
))
4662 data
->costs
[AINC_PRE_DEC
]
4663 = address_cost (addr
, mem_mode
, as
, speed
);
4665 if (USE_LOAD_POST_DECREMENT (mem_mode
)
4666 || USE_STORE_POST_DECREMENT (mem_mode
))
4668 rtx addr
= gen_rtx_POST_DEC (addr_mode
, reg
);
4670 if (memory_address_addr_space_p (mem_mode
, addr
, as
))
4671 data
->costs
[AINC_POST_DEC
]
4672 = address_cost (addr
, mem_mode
, as
, speed
);
4674 if (USE_LOAD_PRE_INCREMENT (mem_mode
)
4675 || USE_STORE_PRE_INCREMENT (mem_mode
))
4677 rtx addr
= gen_rtx_PRE_INC (addr_mode
, reg
);
4679 if (memory_address_addr_space_p (mem_mode
, addr
, as
))
4680 data
->costs
[AINC_PRE_INC
]
4681 = address_cost (addr
, mem_mode
, as
, speed
);
4683 if (USE_LOAD_POST_INCREMENT (mem_mode
)
4684 || USE_STORE_POST_INCREMENT (mem_mode
))
4686 rtx addr
= gen_rtx_POST_INC (addr_mode
, reg
);
4688 if (memory_address_addr_space_p (mem_mode
, addr
, as
))
4689 data
->costs
[AINC_POST_INC
]
4690 = address_cost (addr
, mem_mode
, as
, speed
);
4692 ainc_cost_data_list
[idx
] = data
;
4695 poly_int64 msize
= GET_MODE_SIZE (mem_mode
);
4696 if (known_eq (ainc_offset
, 0) && known_eq (msize
, ainc_step
))
4697 return comp_cost (data
->costs
[AINC_POST_INC
], 0);
4698 if (known_eq (ainc_offset
, 0) && known_eq (msize
, -ainc_step
))
4699 return comp_cost (data
->costs
[AINC_POST_DEC
], 0);
4700 if (known_eq (ainc_offset
, msize
) && known_eq (msize
, ainc_step
))
4701 return comp_cost (data
->costs
[AINC_PRE_INC
], 0);
4702 if (known_eq (ainc_offset
, -msize
) && known_eq (msize
, -ainc_step
))
4703 return comp_cost (data
->costs
[AINC_PRE_DEC
], 0);
4705 return infinite_cost
;
4708 /* Return cost of computing USE's address expression by using CAND.
4709 AFF_INV and AFF_VAR represent invariant and variant parts of the
4710 address expression, respectively. If AFF_INV is simple, store
4711 the loop invariant variables which are depended by it in INV_VARS;
4712 if AFF_INV is complicated, handle it as a new invariant expression
4713 and record it in INV_EXPR. RATIO indicates multiple times between
4714 steps of USE and CAND. If CAN_AUTOINC is nonNULL, store boolean
4715 value to it indicating if this is an auto-increment address. */
4718 get_address_cost (struct ivopts_data
*data
, struct iv_use
*use
,
4719 struct iv_cand
*cand
, aff_tree
*aff_inv
,
4720 aff_tree
*aff_var
, HOST_WIDE_INT ratio
,
4721 bitmap
*inv_vars
, iv_inv_expr_ent
**inv_expr
,
4722 bool *can_autoinc
, bool speed
)
4725 bool simple_inv
= true;
4726 tree comp_inv
= NULL_TREE
, type
= aff_var
->type
;
4727 comp_cost var_cost
= no_cost
, cost
= no_cost
;
4728 struct mem_address parts
= {NULL_TREE
, integer_one_node
,
4729 NULL_TREE
, NULL_TREE
, NULL_TREE
};
4730 machine_mode addr_mode
= TYPE_MODE (type
);
4731 machine_mode mem_mode
= TYPE_MODE (use
->mem_type
);
4732 addr_space_t as
= TYPE_ADDR_SPACE (TREE_TYPE (use
->iv
->base
));
4733 /* Only true if ratio != 1. */
4734 bool ok_with_ratio_p
= false;
4735 bool ok_without_ratio_p
= false;
4736 code_helper code
= ERROR_MARK
;
4738 if (use
->type
== USE_PTR_ADDRESS
)
4740 gcall
*call
= as_a
<gcall
*> (use
->stmt
);
4741 gcc_assert (gimple_call_internal_p (call
));
4742 code
= gimple_call_internal_fn (call
);
4745 if (!aff_combination_const_p (aff_inv
))
4747 parts
.index
= integer_one_node
;
4748 /* Addressing mode "base + index". */
4749 ok_without_ratio_p
= valid_mem_ref_p (mem_mode
, as
, &parts
, code
);
4752 parts
.step
= wide_int_to_tree (type
, ratio
);
4753 /* Addressing mode "base + index << scale". */
4754 ok_with_ratio_p
= valid_mem_ref_p (mem_mode
, as
, &parts
, code
);
4755 if (!ok_with_ratio_p
)
4756 parts
.step
= NULL_TREE
;
4758 if (ok_with_ratio_p
|| ok_without_ratio_p
)
4760 if (maybe_ne (aff_inv
->offset
, 0))
4762 parts
.offset
= wide_int_to_tree (sizetype
, aff_inv
->offset
);
4763 /* Addressing mode "base + index [<< scale] + offset". */
4764 if (!valid_mem_ref_p (mem_mode
, as
, &parts
, code
))
4765 parts
.offset
= NULL_TREE
;
4767 aff_inv
->offset
= 0;
4770 move_fixed_address_to_symbol (&parts
, aff_inv
);
4771 /* Base is fixed address and is moved to symbol part. */
4772 if (parts
.symbol
!= NULL_TREE
&& aff_combination_zero_p (aff_inv
))
4773 parts
.base
= NULL_TREE
;
4775 /* Addressing mode "symbol + base + index [<< scale] [+ offset]". */
4776 if (parts
.symbol
!= NULL_TREE
4777 && !valid_mem_ref_p (mem_mode
, as
, &parts
, code
))
4779 aff_combination_add_elt (aff_inv
, parts
.symbol
, 1);
4780 parts
.symbol
= NULL_TREE
;
4781 /* Reset SIMPLE_INV since symbol address needs to be computed
4782 outside of address expression in this case. */
4784 /* Symbol part is moved back to base part, it can't be NULL. */
4785 parts
.base
= integer_one_node
;
4789 parts
.index
= NULL_TREE
;
4793 poly_int64 ainc_step
;
4796 && ptrdiff_tree_p (cand
->iv
->step
, &ainc_step
))
4798 poly_int64 ainc_offset
= (aff_inv
->offset
).force_shwi ();
4800 if (stmt_after_increment (data
->current_loop
, cand
, use
->stmt
))
4801 ainc_offset
+= ainc_step
;
4802 cost
= get_address_cost_ainc (ainc_step
, ainc_offset
,
4803 addr_mode
, mem_mode
, as
, speed
);
4804 if (!cost
.infinite_cost_p ())
4806 *can_autoinc
= true;
4811 if (!aff_combination_zero_p (aff_inv
))
4813 parts
.offset
= wide_int_to_tree (sizetype
, aff_inv
->offset
);
4814 /* Addressing mode "base + offset". */
4815 if (!valid_mem_ref_p (mem_mode
, as
, &parts
, code
))
4816 parts
.offset
= NULL_TREE
;
4818 aff_inv
->offset
= 0;
4823 simple_inv
= (aff_inv
== NULL
4824 || aff_combination_const_p (aff_inv
)
4825 || aff_combination_singleton_var_p (aff_inv
));
4826 if (!aff_combination_zero_p (aff_inv
))
4827 comp_inv
= aff_combination_to_tree (aff_inv
);
4828 if (comp_inv
!= NULL_TREE
)
4829 cost
= force_var_cost (data
, comp_inv
, inv_vars
);
4830 if (ratio
!= 1 && parts
.step
== NULL_TREE
)
4831 var_cost
+= mult_by_coeff_cost (ratio
, addr_mode
, speed
);
4832 if (comp_inv
!= NULL_TREE
&& parts
.index
== NULL_TREE
)
4833 var_cost
+= add_cost (speed
, addr_mode
);
4835 if (comp_inv
&& inv_expr
&& !simple_inv
)
4837 *inv_expr
= get_loop_invariant_expr (data
, comp_inv
);
4838 /* Clear depends on. */
4839 if (*inv_expr
!= NULL
&& inv_vars
&& *inv_vars
)
4840 bitmap_clear (*inv_vars
);
4842 /* Cost of small invariant expression adjusted against loop niters
4843 is usually zero, which makes it difficult to be differentiated
4844 from candidate based on loop invariant variables. Secondly, the
4845 generated invariant expression may not be hoisted out of loop by
4846 following pass. We penalize the cost by rounding up in order to
4847 neutralize such effects. */
4848 cost
.cost
= adjust_setup_cost (data
, cost
.cost
, true);
4849 cost
.scratch
= cost
.cost
;
4853 addr
= addr_for_mem_ref (&parts
, as
, false);
4854 gcc_assert (memory_address_addr_space_p (mem_mode
, addr
, as
));
4855 cost
+= address_cost (addr
, mem_mode
, as
, speed
);
4857 if (parts
.symbol
!= NULL_TREE
)
4858 cost
.complexity
+= 1;
4859 /* Don't increase the complexity of adding a scaled index if it's
4860 the only kind of index that the target allows. */
4861 if (parts
.step
!= NULL_TREE
&& ok_without_ratio_p
)
4862 cost
.complexity
+= 1;
4863 if (parts
.base
!= NULL_TREE
&& parts
.index
!= NULL_TREE
)
4864 cost
.complexity
+= 1;
4865 if (parts
.offset
!= NULL_TREE
&& !integer_zerop (parts
.offset
))
4866 cost
.complexity
+= 1;
4871 /* Scale (multiply) the computed COST (except scratch part that should be
4872 hoisted out a loop) by header->frequency / AT->frequency, which makes
4873 expected cost more accurate. */
4876 get_scaled_computation_cost_at (ivopts_data
*data
, gimple
*at
, comp_cost cost
)
4879 && data
->current_loop
->header
->count
.to_frequency (cfun
) > 0)
4881 basic_block bb
= gimple_bb (at
);
4882 gcc_assert (cost
.scratch
<= cost
.cost
);
4883 int scale_factor
= (int)(intptr_t) bb
->aux
;
4884 if (scale_factor
== 1)
4888 = cost
.scratch
+ (cost
.cost
- cost
.scratch
) * scale_factor
;
4890 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4891 fprintf (dump_file
, "Scaling cost based on bb prob by %2.2f: "
4892 "%" PRId64
" (scratch: %" PRId64
") -> %" PRId64
"\n",
4893 1.0f
* scale_factor
, cost
.cost
, cost
.scratch
, scaled_cost
);
4895 cost
.cost
= scaled_cost
;
4901 /* Determines the cost of the computation by that USE is expressed
4902 from induction variable CAND. If ADDRESS_P is true, we just need
4903 to create an address from it, otherwise we want to get it into
4904 register. A set of invariants we depend on is stored in INV_VARS.
4905 If CAN_AUTOINC is nonnull, use it to record whether autoinc
4906 addressing is likely. If INV_EXPR is nonnull, record invariant
4907 expr entry in it. */
4910 get_computation_cost (struct ivopts_data
*data
, struct iv_use
*use
,
4911 struct iv_cand
*cand
, bool address_p
, bitmap
*inv_vars
,
4912 bool *can_autoinc
, iv_inv_expr_ent
**inv_expr
)
4914 gimple
*at
= use
->stmt
;
4915 tree ubase
= use
->iv
->base
, cbase
= cand
->iv
->base
;
4916 tree utype
= TREE_TYPE (ubase
), ctype
= TREE_TYPE (cbase
);
4917 tree comp_inv
= NULL_TREE
;
4918 HOST_WIDE_INT ratio
, aratio
;
4921 aff_tree aff_inv
, aff_var
;
4922 bool speed
= optimize_bb_for_speed_p (gimple_bb (at
));
4927 *can_autoinc
= false;
4931 /* Check if we have enough precision to express the values of use. */
4932 if (TYPE_PRECISION (utype
) > TYPE_PRECISION (ctype
))
4933 return infinite_cost
;
4936 || (use
->iv
->base_object
4937 && cand
->iv
->base_object
4938 && POINTER_TYPE_P (TREE_TYPE (use
->iv
->base_object
))
4939 && POINTER_TYPE_P (TREE_TYPE (cand
->iv
->base_object
))))
4941 /* Do not try to express address of an object with computation based
4942 on address of a different object. This may cause problems in rtl
4943 level alias analysis (that does not expect this to be happening,
4944 as this is illegal in C), and would be unlikely to be useful
4946 if (use
->iv
->base_object
4947 && cand
->iv
->base_object
4948 && !operand_equal_p (use
->iv
->base_object
, cand
->iv
->base_object
, 0))
4949 return infinite_cost
;
4952 if (!get_computation_aff_1 (data
->current_loop
, at
, use
,
4953 cand
, &aff_inv
, &aff_var
, &rat
)
4954 || !wi::fits_shwi_p (rat
))
4955 return infinite_cost
;
4957 ratio
= rat
.to_shwi ();
4960 cost
= get_address_cost (data
, use
, cand
, &aff_inv
, &aff_var
, ratio
,
4961 inv_vars
, inv_expr
, can_autoinc
, speed
);
4962 cost
= get_scaled_computation_cost_at (data
, at
, cost
);
4963 /* For doloop IV cand, add on the extra cost. */
4964 cost
+= cand
->doloop_p
? targetm
.doloop_cost_for_address
: 0;
4968 bool simple_inv
= (aff_combination_const_p (&aff_inv
)
4969 || aff_combination_singleton_var_p (&aff_inv
));
4970 tree signed_type
= signed_type_for (aff_combination_type (&aff_inv
));
4971 aff_combination_convert (&aff_inv
, signed_type
);
4972 if (!aff_combination_zero_p (&aff_inv
))
4973 comp_inv
= aff_combination_to_tree (&aff_inv
);
4975 cost
= force_var_cost (data
, comp_inv
, inv_vars
);
4976 if (comp_inv
&& inv_expr
&& !simple_inv
)
4978 *inv_expr
= get_loop_invariant_expr (data
, comp_inv
);
4979 /* Clear depends on. */
4980 if (*inv_expr
!= NULL
&& inv_vars
&& *inv_vars
)
4981 bitmap_clear (*inv_vars
);
4983 cost
.cost
= adjust_setup_cost (data
, cost
.cost
);
4984 /* Record setup cost in scratch field. */
4985 cost
.scratch
= cost
.cost
;
4987 /* Cost of constant integer can be covered when adding invariant part to
4989 else if (comp_inv
&& CONSTANT_CLASS_P (comp_inv
))
4992 /* Need type narrowing to represent use with cand. */
4993 if (TYPE_PRECISION (utype
) < TYPE_PRECISION (ctype
))
4995 machine_mode outer_mode
= TYPE_MODE (utype
);
4996 machine_mode inner_mode
= TYPE_MODE (ctype
);
4997 cost
+= comp_cost (convert_cost (outer_mode
, inner_mode
, speed
), 0);
5000 /* Turn a + i * (-c) into a - i * c. */
5001 if (ratio
< 0 && comp_inv
&& !integer_zerop (comp_inv
))
5007 cost
+= mult_by_coeff_cost (aratio
, TYPE_MODE (utype
), speed
);
5009 /* TODO: We may also need to check if we can compute a + i * 4 in one
5011 /* Need to add up the invariant and variant parts. */
5012 if (comp_inv
&& !integer_zerop (comp_inv
))
5013 cost
+= add_cost (speed
, TYPE_MODE (utype
));
5015 cost
= get_scaled_computation_cost_at (data
, at
, cost
);
5017 /* For doloop IV cand, add on the extra cost. */
5018 if (cand
->doloop_p
&& use
->type
== USE_NONLINEAR_EXPR
)
5019 cost
+= targetm
.doloop_cost_for_generic
;
5024 /* Determines cost of computing the use in GROUP with CAND in a generic
5028 determine_group_iv_cost_generic (struct ivopts_data
*data
,
5029 struct iv_group
*group
, struct iv_cand
*cand
)
5032 iv_inv_expr_ent
*inv_expr
= NULL
;
5033 bitmap inv_vars
= NULL
, inv_exprs
= NULL
;
5034 struct iv_use
*use
= group
->vuses
[0];
5036 /* The simple case first -- if we need to express value of the preserved
5037 original biv, the cost is 0. This also prevents us from counting the
5038 cost of increment twice -- once at this use and once in the cost of
5040 if (cand
->pos
== IP_ORIGINAL
&& cand
->incremented_at
== use
->stmt
)
5042 /* If the IV candidate involves undefined SSA values and is not the
5043 same IV as on the USE avoid using that candidate here. */
5044 else if (cand
->involves_undefs
5045 && (!use
->iv
|| !operand_equal_p (cand
->iv
->base
, use
->iv
->base
, 0)))
5048 cost
= get_computation_cost (data
, use
, cand
, false,
5049 &inv_vars
, NULL
, &inv_expr
);
5053 inv_exprs
= BITMAP_ALLOC (NULL
);
5054 bitmap_set_bit (inv_exprs
, inv_expr
->id
);
5056 set_group_iv_cost (data
, group
, cand
, cost
, inv_vars
,
5057 NULL_TREE
, ERROR_MARK
, inv_exprs
);
5058 return !cost
.infinite_cost_p ();
5061 /* Determines cost of computing uses in GROUP with CAND in addresses. */
5064 determine_group_iv_cost_address (struct ivopts_data
*data
,
5065 struct iv_group
*group
, struct iv_cand
*cand
)
5068 bitmap inv_vars
= NULL
, inv_exprs
= NULL
;
5070 iv_inv_expr_ent
*inv_expr
= NULL
;
5071 struct iv_use
*use
= group
->vuses
[0];
5072 comp_cost sum_cost
= no_cost
, cost
;
5074 cost
= get_computation_cost (data
, use
, cand
, true,
5075 &inv_vars
, &can_autoinc
, &inv_expr
);
5079 inv_exprs
= BITMAP_ALLOC (NULL
);
5080 bitmap_set_bit (inv_exprs
, inv_expr
->id
);
5083 if (!sum_cost
.infinite_cost_p () && cand
->ainc_use
== use
)
5086 sum_cost
-= cand
->cost_step
;
5087 /* If we generated the candidate solely for exploiting autoincrement
5088 opportunities, and it turns out it can't be used, set the cost to
5089 infinity to make sure we ignore it. */
5090 else if (cand
->pos
== IP_AFTER_USE
|| cand
->pos
== IP_BEFORE_USE
)
5091 sum_cost
= infinite_cost
;
5094 /* Uses in a group can share setup code, so only add setup cost once. */
5095 cost
-= cost
.scratch
;
5096 /* Compute and add costs for rest uses of this group. */
5097 for (i
= 1; i
< group
->vuses
.length () && !sum_cost
.infinite_cost_p (); i
++)
5099 struct iv_use
*next
= group
->vuses
[i
];
5101 /* TODO: We could skip computing cost for sub iv_use when it has the
5102 same cost as the first iv_use, but the cost really depends on the
5103 offset and where the iv_use is. */
5104 cost
= get_computation_cost (data
, next
, cand
, true,
5105 NULL
, &can_autoinc
, &inv_expr
);
5109 inv_exprs
= BITMAP_ALLOC (NULL
);
5111 bitmap_set_bit (inv_exprs
, inv_expr
->id
);
5115 set_group_iv_cost (data
, group
, cand
, sum_cost
, inv_vars
,
5116 NULL_TREE
, ERROR_MARK
, inv_exprs
);
5118 return !sum_cost
.infinite_cost_p ();
5121 /* Computes value of candidate CAND at position AT in iteration DESC->NITER,
5122 and stores it to VAL. */
5125 cand_value_at (class loop
*loop
, struct iv_cand
*cand
, gimple
*at
,
5126 class tree_niter_desc
*desc
, aff_tree
*val
)
5128 aff_tree step
, delta
, nit
;
5129 struct iv
*iv
= cand
->iv
;
5130 tree type
= TREE_TYPE (iv
->base
);
5131 tree niter
= desc
->niter
;
5132 bool after_adjust
= stmt_after_increment (loop
, cand
, at
);
5135 if (POINTER_TYPE_P (type
))
5136 steptype
= sizetype
;
5138 steptype
= unsigned_type_for (type
);
5140 /* If AFTER_ADJUST is required, the code below generates the equivalent
5141 of BASE + NITER * STEP + STEP, when ideally we'd prefer the expression
5142 BASE + (NITER + 1) * STEP, especially when NITER is often of the form
5143 SSA_NAME - 1. Unfortunately, guaranteeing that adding 1 to NITER
5144 doesn't overflow is tricky, so we peek inside the TREE_NITER_DESC
5145 class for common idioms that we know are safe. */
5147 && desc
->control
.no_overflow
5148 && integer_onep (desc
->control
.step
)
5149 && (desc
->cmp
== LT_EXPR
5150 || desc
->cmp
== NE_EXPR
)
5151 && TREE_CODE (desc
->bound
) == SSA_NAME
)
5153 if (integer_onep (desc
->control
.base
))
5155 niter
= desc
->bound
;
5156 after_adjust
= false;
5158 else if (TREE_CODE (niter
) == MINUS_EXPR
5159 && integer_onep (TREE_OPERAND (niter
, 1)))
5161 niter
= TREE_OPERAND (niter
, 0);
5162 after_adjust
= false;
5166 tree_to_aff_combination (iv
->step
, TREE_TYPE (iv
->step
), &step
);
5167 aff_combination_convert (&step
, steptype
);
5168 tree_to_aff_combination (niter
, TREE_TYPE (niter
), &nit
);
5169 aff_combination_convert (&nit
, steptype
);
5170 aff_combination_mult (&nit
, &step
, &delta
);
5172 aff_combination_add (&delta
, &step
);
5174 tree_to_aff_combination (iv
->base
, type
, val
);
5175 if (!POINTER_TYPE_P (type
))
5176 aff_combination_convert (val
, steptype
);
5177 aff_combination_add (val
, &delta
);
5180 /* Returns period of induction variable iv. */
5183 iv_period (struct iv
*iv
)
5185 tree step
= iv
->step
, period
, type
;
5188 gcc_assert (step
&& TREE_CODE (step
) == INTEGER_CST
);
5190 type
= unsigned_type_for (TREE_TYPE (step
));
5191 /* Period of the iv is lcm (step, type_range)/step -1,
5192 i.e., N*type_range/step - 1. Since type range is power
5193 of two, N == (step >> num_of_ending_zeros_binary (step),
5194 so the final result is
5196 (type_range >> num_of_ending_zeros_binary (step)) - 1
5199 pow2div
= num_ending_zeros (step
);
5201 period
= build_low_bits_mask (type
,
5202 (TYPE_PRECISION (type
)
5203 - tree_to_uhwi (pow2div
)));
5208 /* Returns the comparison operator used when eliminating the iv USE. */
5210 static enum tree_code
5211 iv_elimination_compare (struct ivopts_data
*data
, struct iv_use
*use
)
5213 class loop
*loop
= data
->current_loop
;
5217 ex_bb
= gimple_bb (use
->stmt
);
5218 exit
= EDGE_SUCC (ex_bb
, 0);
5219 if (flow_bb_inside_loop_p (loop
, exit
->dest
))
5220 exit
= EDGE_SUCC (ex_bb
, 1);
5222 return (exit
->flags
& EDGE_TRUE_VALUE
? EQ_EXPR
: NE_EXPR
);
5225 /* Returns true if we can prove that BASE - OFFSET does not overflow. For now,
5226 we only detect the situation that BASE = SOMETHING + OFFSET, where the
5227 calculation is performed in non-wrapping type.
5229 TODO: More generally, we could test for the situation that
5230 BASE = SOMETHING + OFFSET' and OFFSET is between OFFSET' and zero.
5231 This would require knowing the sign of OFFSET. */
5234 difference_cannot_overflow_p (struct ivopts_data
*data
, tree base
, tree offset
)
5236 enum tree_code code
;
5238 aff_tree aff_e1
, aff_e2
, aff_offset
;
5240 if (!nowrap_type_p (TREE_TYPE (base
)))
5243 base
= expand_simple_operations (base
);
5245 if (TREE_CODE (base
) == SSA_NAME
)
5247 gimple
*stmt
= SSA_NAME_DEF_STMT (base
);
5249 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
5252 code
= gimple_assign_rhs_code (stmt
);
5253 if (get_gimple_rhs_class (code
) != GIMPLE_BINARY_RHS
)
5256 e1
= gimple_assign_rhs1 (stmt
);
5257 e2
= gimple_assign_rhs2 (stmt
);
5261 code
= TREE_CODE (base
);
5262 if (get_gimple_rhs_class (code
) != GIMPLE_BINARY_RHS
)
5264 e1
= TREE_OPERAND (base
, 0);
5265 e2
= TREE_OPERAND (base
, 1);
5268 /* Use affine expansion as deeper inspection to prove the equality. */
5269 tree_to_aff_combination_expand (e2
, TREE_TYPE (e2
),
5270 &aff_e2
, &data
->name_expansion_cache
);
5271 tree_to_aff_combination_expand (offset
, TREE_TYPE (offset
),
5272 &aff_offset
, &data
->name_expansion_cache
);
5273 aff_combination_scale (&aff_offset
, -1);
5277 aff_combination_add (&aff_e2
, &aff_offset
);
5278 if (aff_combination_zero_p (&aff_e2
))
5281 tree_to_aff_combination_expand (e1
, TREE_TYPE (e1
),
5282 &aff_e1
, &data
->name_expansion_cache
);
5283 aff_combination_add (&aff_e1
, &aff_offset
);
5284 return aff_combination_zero_p (&aff_e1
);
5286 case POINTER_PLUS_EXPR
:
5287 aff_combination_add (&aff_e2
, &aff_offset
);
5288 return aff_combination_zero_p (&aff_e2
);
5295 /* Tries to replace loop exit by one formulated in terms of a LT_EXPR
5296 comparison with CAND. NITER describes the number of iterations of
5297 the loops. If successful, the comparison in COMP_P is altered accordingly.
5299 We aim to handle the following situation:
5315 Here, the number of iterations of the loop is (a + 1 > b) ? 0 : b - a - 1.
5316 We aim to optimize this to
5324 while (p < p_0 - a + b);
5326 This preserves the correctness, since the pointer arithmetics does not
5327 overflow. More precisely:
5329 1) if a + 1 <= b, then p_0 - a + b is the final value of p, hence there is no
5330 overflow in computing it or the values of p.
5331 2) if a + 1 > b, then we need to verify that the expression p_0 - a does not
5332 overflow. To prove this, we use the fact that p_0 = base + a. */
5335 iv_elimination_compare_lt (struct ivopts_data
*data
,
5336 struct iv_cand
*cand
, enum tree_code
*comp_p
,
5337 class tree_niter_desc
*niter
)
5339 tree cand_type
, a
, b
, mbz
, nit_type
= TREE_TYPE (niter
->niter
), offset
;
5340 class aff_tree nit
, tmpa
, tmpb
;
5341 enum tree_code comp
;
5344 /* We need to know that the candidate induction variable does not overflow.
5345 While more complex analysis may be used to prove this, for now just
5346 check that the variable appears in the original program and that it
5347 is computed in a type that guarantees no overflows. */
5348 cand_type
= TREE_TYPE (cand
->iv
->base
);
5349 if (cand
->pos
!= IP_ORIGINAL
|| !nowrap_type_p (cand_type
))
5352 /* Make sure that the loop iterates till the loop bound is hit, as otherwise
5353 the calculation of the BOUND could overflow, making the comparison
5355 if (!data
->loop_single_exit_p
)
5358 /* We need to be able to decide whether candidate is increasing or decreasing
5359 in order to choose the right comparison operator. */
5360 if (!cst_and_fits_in_hwi (cand
->iv
->step
))
5362 step
= int_cst_value (cand
->iv
->step
);
5364 /* Check that the number of iterations matches the expected pattern:
5365 a + 1 > b ? 0 : b - a - 1. */
5366 mbz
= niter
->may_be_zero
;
5367 if (TREE_CODE (mbz
) == GT_EXPR
)
5369 /* Handle a + 1 > b. */
5370 tree op0
= TREE_OPERAND (mbz
, 0);
5371 if (TREE_CODE (op0
) == PLUS_EXPR
&& integer_onep (TREE_OPERAND (op0
, 1)))
5373 a
= TREE_OPERAND (op0
, 0);
5374 b
= TREE_OPERAND (mbz
, 1);
5379 else if (TREE_CODE (mbz
) == LT_EXPR
)
5381 tree op1
= TREE_OPERAND (mbz
, 1);
5383 /* Handle b < a + 1. */
5384 if (TREE_CODE (op1
) == PLUS_EXPR
&& integer_onep (TREE_OPERAND (op1
, 1)))
5386 a
= TREE_OPERAND (op1
, 0);
5387 b
= TREE_OPERAND (mbz
, 0);
5395 /* Expected number of iterations is B - A - 1. Check that it matches
5396 the actual number, i.e., that B - A - NITER = 1. */
5397 tree_to_aff_combination (niter
->niter
, nit_type
, &nit
);
5398 tree_to_aff_combination (fold_convert (nit_type
, a
), nit_type
, &tmpa
);
5399 tree_to_aff_combination (fold_convert (nit_type
, b
), nit_type
, &tmpb
);
5400 aff_combination_scale (&nit
, -1);
5401 aff_combination_scale (&tmpa
, -1);
5402 aff_combination_add (&tmpb
, &tmpa
);
5403 aff_combination_add (&tmpb
, &nit
);
5404 if (tmpb
.n
!= 0 || maybe_ne (tmpb
.offset
, 1))
5407 /* Finally, check that CAND->IV->BASE - CAND->IV->STEP * A does not
5409 offset
= fold_build2 (MULT_EXPR
, TREE_TYPE (cand
->iv
->step
),
5411 fold_convert (TREE_TYPE (cand
->iv
->step
), a
));
5412 if (!difference_cannot_overflow_p (data
, cand
->iv
->base
, offset
))
5415 /* Determine the new comparison operator. */
5416 comp
= step
< 0 ? GT_EXPR
: LT_EXPR
;
5417 if (*comp_p
== NE_EXPR
)
5419 else if (*comp_p
== EQ_EXPR
)
5420 *comp_p
= invert_tree_comparison (comp
, false);
5427 /* Check whether it is possible to express the condition in USE by comparison
5428 of candidate CAND. If so, store the value compared with to BOUND, and the
5429 comparison operator to COMP. */
5432 may_eliminate_iv (struct ivopts_data
*data
,
5433 struct iv_use
*use
, struct iv_cand
*cand
, tree
*bound
,
5434 enum tree_code
*comp
)
5439 class loop
*loop
= data
->current_loop
;
5441 class tree_niter_desc
*desc
= NULL
;
5443 if (TREE_CODE (cand
->iv
->step
) != INTEGER_CST
)
5446 /* For now works only for exits that dominate the loop latch.
5447 TODO: extend to other conditions inside loop body. */
5448 ex_bb
= gimple_bb (use
->stmt
);
5449 if (use
->stmt
!= last_nondebug_stmt (ex_bb
)
5450 || gimple_code (use
->stmt
) != GIMPLE_COND
5451 || !dominated_by_p (CDI_DOMINATORS
, loop
->latch
, ex_bb
))
5454 exit
= EDGE_SUCC (ex_bb
, 0);
5455 if (flow_bb_inside_loop_p (loop
, exit
->dest
))
5456 exit
= EDGE_SUCC (ex_bb
, 1);
5457 if (flow_bb_inside_loop_p (loop
, exit
->dest
))
5460 desc
= niter_for_exit (data
, exit
);
5464 /* Determine whether we can use the variable to test the exit condition.
5465 This is the case iff the period of the induction variable is greater
5466 than the number of iterations for which the exit condition is true. */
5467 period
= iv_period (cand
->iv
);
5469 /* If the number of iterations is constant, compare against it directly. */
5470 if (TREE_CODE (desc
->niter
) == INTEGER_CST
)
5472 /* See cand_value_at. */
5473 if (stmt_after_increment (loop
, cand
, use
->stmt
))
5475 if (!tree_int_cst_lt (desc
->niter
, period
))
5480 if (tree_int_cst_lt (period
, desc
->niter
))
5485 /* If not, and if this is the only possible exit of the loop, see whether
5486 we can get a conservative estimate on the number of iterations of the
5487 entire loop and compare against that instead. */
5490 widest_int period_value
, max_niter
;
5492 max_niter
= desc
->max
;
5493 if (stmt_after_increment (loop
, cand
, use
->stmt
))
5495 period_value
= wi::to_widest (period
);
5496 if (wi::gtu_p (max_niter
, period_value
))
5498 /* See if we can take advantage of inferred loop bound
5500 if (data
->loop_single_exit_p
)
5502 if (!max_loop_iterations (loop
, &max_niter
))
5504 /* The loop bound is already adjusted by adding 1. */
5505 if (wi::gtu_p (max_niter
, period_value
))
5513 /* For doloop IV cand, the bound would be zero. It's safe whether
5514 may_be_zero set or not. */
5517 *bound
= build_int_cst (TREE_TYPE (cand
->iv
->base
), 0);
5518 *comp
= iv_elimination_compare (data
, use
);
5522 cand_value_at (loop
, cand
, use
->stmt
, desc
, &bnd
);
5524 *bound
= fold_convert (TREE_TYPE (cand
->iv
->base
),
5525 aff_combination_to_tree (&bnd
));
5526 *comp
= iv_elimination_compare (data
, use
);
5528 /* It is unlikely that computing the number of iterations using division
5529 would be more profitable than keeping the original induction variable. */
5530 bool cond_overflow_p
;
5531 if (expression_expensive_p (*bound
, &cond_overflow_p
))
5534 /* Sometimes, it is possible to handle the situation that the number of
5535 iterations may be zero unless additional assumptions by using <
5536 instead of != in the exit condition.
5538 TODO: we could also calculate the value MAY_BE_ZERO ? 0 : NITER and
5539 base the exit condition on it. However, that is often too
5541 if (!integer_zerop (desc
->may_be_zero
))
5542 return iv_elimination_compare_lt (data
, cand
, comp
, desc
);
5547 /* Calculates the cost of BOUND, if it is a PARM_DECL. A PARM_DECL must
5548 be copied, if it is used in the loop body and DATA->body_includes_call. */
5551 parm_decl_cost (struct ivopts_data
*data
, tree bound
)
5553 tree sbound
= bound
;
5554 STRIP_NOPS (sbound
);
5556 if (TREE_CODE (sbound
) == SSA_NAME
5557 && SSA_NAME_IS_DEFAULT_DEF (sbound
)
5558 && TREE_CODE (SSA_NAME_VAR (sbound
)) == PARM_DECL
5559 && data
->body_includes_call
)
5560 return COSTS_N_INSNS (1);
5565 /* Determines cost of computing the use in GROUP with CAND in a condition. */
5568 determine_group_iv_cost_cond (struct ivopts_data
*data
,
5569 struct iv_group
*group
, struct iv_cand
*cand
)
5571 tree bound
= NULL_TREE
;
5573 bitmap inv_exprs
= NULL
;
5574 bitmap inv_vars_elim
= NULL
, inv_vars_express
= NULL
, inv_vars
;
5575 comp_cost elim_cost
= infinite_cost
, express_cost
, cost
, bound_cost
;
5576 enum comp_iv_rewrite rewrite_type
;
5577 iv_inv_expr_ent
*inv_expr_elim
= NULL
, *inv_expr_express
= NULL
, *inv_expr
;
5578 tree
*control_var
, *bound_cst
;
5579 enum tree_code comp
= ERROR_MARK
;
5580 struct iv_use
*use
= group
->vuses
[0];
5582 /* Extract condition operands. */
5583 rewrite_type
= extract_cond_operands (data
, use
->stmt
, &control_var
,
5584 &bound_cst
, NULL
, &cmp_iv
);
5585 gcc_assert (rewrite_type
!= COMP_IV_NA
);
5587 /* Try iv elimination. */
5588 if (rewrite_type
== COMP_IV_ELIM
5589 && may_eliminate_iv (data
, use
, cand
, &bound
, &comp
))
5591 elim_cost
= force_var_cost (data
, bound
, &inv_vars_elim
);
5592 if (elim_cost
.cost
== 0)
5593 elim_cost
.cost
= parm_decl_cost (data
, bound
);
5594 else if (TREE_CODE (bound
) == INTEGER_CST
)
5596 /* If we replace a loop condition 'i < n' with 'p < base + n',
5597 inv_vars_elim will have 'base' and 'n' set, which implies that both
5598 'base' and 'n' will be live during the loop. More likely,
5599 'base + n' will be loop invariant, resulting in only one live value
5600 during the loop. So in that case we clear inv_vars_elim and set
5601 inv_expr_elim instead. */
5602 if (inv_vars_elim
&& bitmap_count_bits (inv_vars_elim
) > 1)
5604 inv_expr_elim
= get_loop_invariant_expr (data
, bound
);
5605 bitmap_clear (inv_vars_elim
);
5607 /* The bound is a loop invariant, so it will be only computed
5609 elim_cost
.cost
= adjust_setup_cost (data
, elim_cost
.cost
);
5612 /* When the condition is a comparison of the candidate IV against
5613 zero, prefer this IV.
5615 TODO: The constant that we're subtracting from the cost should
5616 be target-dependent. This information should be added to the
5617 target costs for each backend. */
5618 if (!elim_cost
.infinite_cost_p () /* Do not try to decrease infinite! */
5619 && integer_zerop (*bound_cst
)
5620 && (operand_equal_p (*control_var
, cand
->var_after
, 0)
5621 || operand_equal_p (*control_var
, cand
->var_before
, 0)))
5624 express_cost
= get_computation_cost (data
, use
, cand
, false,
5625 &inv_vars_express
, NULL
,
5628 find_inv_vars (data
, &cmp_iv
->base
, &inv_vars_express
);
5630 /* Count the cost of the original bound as well. */
5631 bound_cost
= force_var_cost (data
, *bound_cst
, NULL
);
5632 if (bound_cost
.cost
== 0)
5633 bound_cost
.cost
= parm_decl_cost (data
, *bound_cst
);
5634 else if (TREE_CODE (*bound_cst
) == INTEGER_CST
)
5635 bound_cost
.cost
= 0;
5636 express_cost
+= bound_cost
;
5638 /* Choose the better approach, preferring the eliminated IV. */
5639 if (elim_cost
<= express_cost
)
5642 inv_vars
= inv_vars_elim
;
5643 inv_vars_elim
= NULL
;
5644 inv_expr
= inv_expr_elim
;
5645 /* For doloop candidate/use pair, adjust to zero cost. */
5646 if (group
->doloop_p
&& cand
->doloop_p
&& elim_cost
.cost
> no_cost
.cost
)
5651 cost
= express_cost
;
5652 inv_vars
= inv_vars_express
;
5653 inv_vars_express
= NULL
;
5656 inv_expr
= inv_expr_express
;
5661 inv_exprs
= BITMAP_ALLOC (NULL
);
5662 bitmap_set_bit (inv_exprs
, inv_expr
->id
);
5664 set_group_iv_cost (data
, group
, cand
, cost
,
5665 inv_vars
, bound
, comp
, inv_exprs
);
5668 BITMAP_FREE (inv_vars_elim
);
5669 if (inv_vars_express
)
5670 BITMAP_FREE (inv_vars_express
);
5672 return !cost
.infinite_cost_p ();
5675 /* Determines cost of computing uses in GROUP with CAND. Returns false
5676 if USE cannot be represented with CAND. */
5679 determine_group_iv_cost (struct ivopts_data
*data
,
5680 struct iv_group
*group
, struct iv_cand
*cand
)
5682 switch (group
->type
)
5684 case USE_NONLINEAR_EXPR
:
5685 return determine_group_iv_cost_generic (data
, group
, cand
);
5687 case USE_REF_ADDRESS
:
5688 case USE_PTR_ADDRESS
:
5689 return determine_group_iv_cost_address (data
, group
, cand
);
5692 return determine_group_iv_cost_cond (data
, group
, cand
);
5699 /* Return true if get_computation_cost indicates that autoincrement is
5700 a possibility for the pair of USE and CAND, false otherwise. */
5703 autoinc_possible_for_pair (struct ivopts_data
*data
, struct iv_use
*use
,
5704 struct iv_cand
*cand
)
5706 if (!address_p (use
->type
))
5709 bool can_autoinc
= false;
5710 get_computation_cost (data
, use
, cand
, true, NULL
, &can_autoinc
, NULL
);
5714 /* Examine IP_ORIGINAL candidates to see if they are incremented next to a
5715 use that allows autoincrement, and set their AINC_USE if possible. */
5718 set_autoinc_for_original_candidates (struct ivopts_data
*data
)
5722 for (i
= 0; i
< data
->vcands
.length (); i
++)
5724 struct iv_cand
*cand
= data
->vcands
[i
];
5725 struct iv_use
*closest_before
= NULL
;
5726 struct iv_use
*closest_after
= NULL
;
5727 if (cand
->pos
!= IP_ORIGINAL
)
5730 for (j
= 0; j
< data
->vgroups
.length (); j
++)
5732 struct iv_group
*group
= data
->vgroups
[j
];
5733 struct iv_use
*use
= group
->vuses
[0];
5734 unsigned uid
= gimple_uid (use
->stmt
);
5736 if (gimple_bb (use
->stmt
) != gimple_bb (cand
->incremented_at
))
5739 if (uid
< gimple_uid (cand
->incremented_at
)
5740 && (closest_before
== NULL
5741 || uid
> gimple_uid (closest_before
->stmt
)))
5742 closest_before
= use
;
5744 if (uid
> gimple_uid (cand
->incremented_at
)
5745 && (closest_after
== NULL
5746 || uid
< gimple_uid (closest_after
->stmt
)))
5747 closest_after
= use
;
5750 if (closest_before
!= NULL
5751 && autoinc_possible_for_pair (data
, closest_before
, cand
))
5752 cand
->ainc_use
= closest_before
;
5753 else if (closest_after
!= NULL
5754 && autoinc_possible_for_pair (data
, closest_after
, cand
))
5755 cand
->ainc_use
= closest_after
;
5759 /* Relate compare use with all candidates. */
5762 relate_compare_use_with_all_cands (struct ivopts_data
*data
)
5764 unsigned i
, count
= data
->vcands
.length ();
5765 for (i
= 0; i
< data
->vgroups
.length (); i
++)
5767 struct iv_group
*group
= data
->vgroups
[i
];
5769 if (group
->type
== USE_COMPARE
)
5770 bitmap_set_range (group
->related_cands
, 0, count
);
5774 /* If PREFERRED_MODE is suitable and profitable, use the preferred
5775 PREFERRED_MODE to compute doloop iv base from niter: base = niter + 1. */
5778 compute_doloop_base_on_mode (machine_mode preferred_mode
, tree niter
,
5779 const widest_int
&iterations_max
)
5781 tree ntype
= TREE_TYPE (niter
);
5782 tree pref_type
= lang_hooks
.types
.type_for_mode (preferred_mode
, 1);
5784 return fold_build2 (PLUS_EXPR
, ntype
, unshare_expr (niter
),
5785 build_int_cst (ntype
, 1));
5787 gcc_assert (TREE_CODE (pref_type
) == INTEGER_TYPE
);
5789 int prec
= TYPE_PRECISION (ntype
);
5790 int pref_prec
= TYPE_PRECISION (pref_type
);
5794 /* Check if the PREFERRED_MODED is able to present niter. */
5795 if (pref_prec
> prec
5796 || wi::ltu_p (iterations_max
,
5797 widest_int::from (wi::max_value (pref_prec
, UNSIGNED
),
5800 /* No wrap, it is safe to use preferred type after niter + 1. */
5801 if (wi::ltu_p (iterations_max
,
5802 widest_int::from (wi::max_value (prec
, UNSIGNED
),
5805 /* This could help to optimize "-1 +1" pair when niter looks
5806 like "n-1": n is in original mode. "base = (n - 1) + 1"
5807 in PREFERRED_MODED: it could be base = (PREFERRED_TYPE)n. */
5808 base
= fold_build2 (PLUS_EXPR
, ntype
, unshare_expr (niter
),
5809 build_int_cst (ntype
, 1));
5810 base
= fold_convert (pref_type
, base
);
5813 /* To avoid wrap, convert niter to preferred type before plus 1. */
5816 niter
= fold_convert (pref_type
, niter
);
5817 base
= fold_build2 (PLUS_EXPR
, pref_type
, unshare_expr (niter
),
5818 build_int_cst (pref_type
, 1));
5822 base
= fold_build2 (PLUS_EXPR
, ntype
, unshare_expr (niter
),
5823 build_int_cst (ntype
, 1));
5827 /* Add one doloop dedicated IV candidate:
5828 - Base is (may_be_zero ? 1 : (niter + 1)).
5832 add_iv_candidate_for_doloop (struct ivopts_data
*data
)
5834 tree_niter_desc
*niter_desc
= niter_for_single_dom_exit (data
);
5835 gcc_assert (niter_desc
&& niter_desc
->assumptions
);
5837 tree niter
= niter_desc
->niter
;
5838 tree ntype
= TREE_TYPE (niter
);
5839 gcc_assert (TREE_CODE (ntype
) == INTEGER_TYPE
);
5841 tree may_be_zero
= niter_desc
->may_be_zero
;
5842 if (may_be_zero
&& integer_zerop (may_be_zero
))
5843 may_be_zero
= NULL_TREE
;
5846 if (COMPARISON_CLASS_P (may_be_zero
))
5848 niter
= fold_build3 (COND_EXPR
, ntype
, may_be_zero
,
5849 build_int_cst (ntype
, 0),
5850 rewrite_to_non_trapping_overflow (niter
));
5852 /* Don't try to obtain the iteration count expression when may_be_zero is
5853 integer_nonzerop (actually iteration count is one) or else. */
5858 machine_mode mode
= TYPE_MODE (ntype
);
5859 machine_mode pref_mode
= targetm
.preferred_doloop_mode (mode
);
5862 if (mode
!= pref_mode
)
5864 base
= compute_doloop_base_on_mode (pref_mode
, niter
, niter_desc
->max
);
5865 ntype
= TREE_TYPE (base
);
5868 base
= fold_build2 (PLUS_EXPR
, ntype
, unshare_expr (niter
),
5869 build_int_cst (ntype
, 1));
5872 add_candidate (data
, base
, build_int_cst (ntype
, -1), true, NULL
, NULL
, true);
5875 /* Finds the candidates for the induction variables. */
5878 find_iv_candidates (struct ivopts_data
*data
)
5880 /* Add commonly used ivs. */
5881 add_standard_iv_candidates (data
);
5883 /* Add doloop dedicated ivs. */
5884 if (data
->doloop_use_p
)
5885 add_iv_candidate_for_doloop (data
);
5887 /* Add old induction variables. */
5888 add_iv_candidate_for_bivs (data
);
5890 /* Add induction variables derived from uses. */
5891 add_iv_candidate_for_groups (data
);
5893 set_autoinc_for_original_candidates (data
);
5895 /* Record the important candidates. */
5896 record_important_candidates (data
);
5898 /* Relate compare iv_use with all candidates. */
5899 if (!data
->consider_all_candidates
)
5900 relate_compare_use_with_all_cands (data
);
5902 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
5906 fprintf (dump_file
, "\n<Important Candidates>:\t");
5907 for (i
= 0; i
< data
->vcands
.length (); i
++)
5908 if (data
->vcands
[i
]->important
)
5909 fprintf (dump_file
, " %d,", data
->vcands
[i
]->id
);
5910 fprintf (dump_file
, "\n");
5912 fprintf (dump_file
, "\n<Group, Cand> Related:\n");
5913 for (i
= 0; i
< data
->vgroups
.length (); i
++)
5915 struct iv_group
*group
= data
->vgroups
[i
];
5917 if (group
->related_cands
)
5919 fprintf (dump_file
, " Group %d:\t", group
->id
);
5920 dump_bitmap (dump_file
, group
->related_cands
);
5923 fprintf (dump_file
, "\n");
5927 /* Determines costs of computing use of iv with an iv candidate. */
5930 determine_group_iv_costs (struct ivopts_data
*data
)
5933 struct iv_cand
*cand
;
5934 struct iv_group
*group
;
5935 bitmap to_clear
= BITMAP_ALLOC (NULL
);
5937 alloc_use_cost_map (data
);
5939 for (i
= 0; i
< data
->vgroups
.length (); i
++)
5941 group
= data
->vgroups
[i
];
5943 if (data
->consider_all_candidates
)
5945 for (j
= 0; j
< data
->vcands
.length (); j
++)
5947 cand
= data
->vcands
[j
];
5948 determine_group_iv_cost (data
, group
, cand
);
5955 EXECUTE_IF_SET_IN_BITMAP (group
->related_cands
, 0, j
, bi
)
5957 cand
= data
->vcands
[j
];
5958 if (!determine_group_iv_cost (data
, group
, cand
))
5959 bitmap_set_bit (to_clear
, j
);
5962 /* Remove the candidates for that the cost is infinite from
5963 the list of related candidates. */
5964 bitmap_and_compl_into (group
->related_cands
, to_clear
);
5965 bitmap_clear (to_clear
);
5969 BITMAP_FREE (to_clear
);
5971 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
5975 /* Dump invariant variables. */
5976 fprintf (dump_file
, "\n<Invariant Vars>:\n");
5977 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, i
, bi
)
5979 struct version_info
*info
= ver_info (data
, i
);
5982 fprintf (dump_file
, "Inv %d:\t", info
->inv_id
);
5983 print_generic_expr (dump_file
, info
->name
, TDF_SLIM
);
5984 fprintf (dump_file
, "%s\n",
5985 info
->has_nonlin_use
? "" : "\t(eliminable)");
5989 /* Dump invariant expressions. */
5990 fprintf (dump_file
, "\n<Invariant Expressions>:\n");
5991 auto_vec
<iv_inv_expr_ent
*> list (data
->inv_expr_tab
->elements ());
5993 for (hash_table
<iv_inv_expr_hasher
>::iterator it
5994 = data
->inv_expr_tab
->begin (); it
!= data
->inv_expr_tab
->end ();
5996 list
.safe_push (*it
);
5998 list
.qsort (sort_iv_inv_expr_ent
);
6000 for (i
= 0; i
< list
.length (); ++i
)
6002 fprintf (dump_file
, "inv_expr %d: \t", list
[i
]->id
);
6003 print_generic_expr (dump_file
, list
[i
]->expr
, TDF_SLIM
);
6004 fprintf (dump_file
, "\n");
6007 fprintf (dump_file
, "\n<Group-candidate Costs>:\n");
6009 for (i
= 0; i
< data
->vgroups
.length (); i
++)
6011 group
= data
->vgroups
[i
];
6013 fprintf (dump_file
, "Group %d:\n", i
);
6014 fprintf (dump_file
, " cand\tcost\tcompl.\tinv.expr.\tinv.vars\n");
6015 for (j
= 0; j
< group
->n_map_members
; j
++)
6017 if (!group
->cost_map
[j
].cand
6018 || group
->cost_map
[j
].cost
.infinite_cost_p ())
6021 fprintf (dump_file
, " %d\t%" PRId64
"\t%d\t",
6022 group
->cost_map
[j
].cand
->id
,
6023 group
->cost_map
[j
].cost
.cost
,
6024 group
->cost_map
[j
].cost
.complexity
);
6025 if (!group
->cost_map
[j
].inv_exprs
6026 || bitmap_empty_p (group
->cost_map
[j
].inv_exprs
))
6027 fprintf (dump_file
, "NIL;\t");
6029 bitmap_print (dump_file
,
6030 group
->cost_map
[j
].inv_exprs
, "", ";\t");
6031 if (!group
->cost_map
[j
].inv_vars
6032 || bitmap_empty_p (group
->cost_map
[j
].inv_vars
))
6033 fprintf (dump_file
, "NIL;\n");
6035 bitmap_print (dump_file
,
6036 group
->cost_map
[j
].inv_vars
, "", "\n");
6039 fprintf (dump_file
, "\n");
6041 fprintf (dump_file
, "\n");
6045 /* Determines cost of the candidate CAND. */
6048 determine_iv_cost (struct ivopts_data
*data
, struct iv_cand
*cand
)
6050 comp_cost cost_base
;
6051 int64_t cost
, cost_step
;
6054 gcc_assert (cand
->iv
!= NULL
);
6056 /* There are two costs associated with the candidate -- its increment
6057 and its initialization. The second is almost negligible for any loop
6058 that rolls enough, so we take it just very little into account. */
6060 base
= cand
->iv
->base
;
6061 cost_base
= force_var_cost (data
, base
, NULL
);
6062 /* It will be exceptional that the iv register happens to be initialized with
6063 the proper value at no cost. In general, there will at least be a regcopy
6065 if (cost_base
.cost
== 0)
6066 cost_base
.cost
= COSTS_N_INSNS (1);
6067 /* Doloop decrement should be considered as zero cost. */
6071 cost_step
= add_cost (data
->speed
, TYPE_MODE (TREE_TYPE (base
)));
6072 cost
= cost_step
+ adjust_setup_cost (data
, cost_base
.cost
);
6074 /* Prefer the original ivs unless we may gain something by replacing it.
6075 The reason is to make debugging simpler; so this is not relevant for
6076 artificial ivs created by other optimization passes. */
6077 if ((cand
->pos
!= IP_ORIGINAL
6078 || !SSA_NAME_VAR (cand
->var_before
)
6079 || DECL_ARTIFICIAL (SSA_NAME_VAR (cand
->var_before
)))
6080 /* Prefer doloop as well. */
6084 /* Prefer not to insert statements into latch unless there are some
6085 already (so that we do not create unnecessary jumps). */
6086 if (cand
->pos
== IP_END
6087 && empty_block_p (ip_end_pos (data
->current_loop
)))
6091 cand
->cost_step
= cost_step
;
6094 /* Determines costs of computation of the candidates. */
6097 determine_iv_costs (struct ivopts_data
*data
)
6101 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
6103 fprintf (dump_file
, "<Candidate Costs>:\n");
6104 fprintf (dump_file
, " cand\tcost\n");
6107 for (i
= 0; i
< data
->vcands
.length (); i
++)
6109 struct iv_cand
*cand
= data
->vcands
[i
];
6111 determine_iv_cost (data
, cand
);
6113 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
6114 fprintf (dump_file
, " %d\t%d\n", i
, cand
->cost
);
6117 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
6118 fprintf (dump_file
, "\n");
6121 /* Estimate register pressure for loop having N_INVS invariants and N_CANDS
6122 induction variables. Note N_INVS includes both invariant variables and
6123 invariant expressions. */
6126 ivopts_estimate_reg_pressure (struct ivopts_data
*data
, unsigned n_invs
,
6130 unsigned n_old
= data
->regs_used
, n_new
= n_invs
+ n_cands
;
6131 unsigned regs_needed
= n_new
+ n_old
, available_regs
= target_avail_regs
;
6132 bool speed
= data
->speed
;
6134 /* If there is a call in the loop body, the call-clobbered registers
6135 are not available for loop invariants. */
6136 if (data
->body_includes_call
)
6137 available_regs
= available_regs
- target_clobbered_regs
;
6139 /* If we have enough registers. */
6140 if (regs_needed
+ target_res_regs
< available_regs
)
6142 /* If close to running out of registers, try to preserve them. */
6143 else if (regs_needed
<= available_regs
)
6144 cost
= target_reg_cost
[speed
] * regs_needed
;
6145 /* If we run out of available registers but the number of candidates
6146 does not, we penalize extra registers using target_spill_cost. */
6147 else if (n_cands
<= available_regs
)
6148 cost
= target_reg_cost
[speed
] * available_regs
6149 + target_spill_cost
[speed
] * (regs_needed
- available_regs
);
6150 /* If the number of candidates runs out available registers, we penalize
6151 extra candidate registers using target_spill_cost * 2. Because it is
6152 more expensive to spill induction variable than invariant. */
6154 cost
= target_reg_cost
[speed
] * available_regs
6155 + target_spill_cost
[speed
] * (n_cands
- available_regs
) * 2
6156 + target_spill_cost
[speed
] * (regs_needed
- n_cands
);
6158 /* Finally, add the number of candidates, so that we prefer eliminating
6159 induction variables if possible. */
6160 return cost
+ n_cands
;
6163 /* For each size of the induction variable set determine the penalty. */
6166 determine_set_costs (struct ivopts_data
*data
)
6172 class loop
*loop
= data
->current_loop
;
6175 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
6177 fprintf (dump_file
, "<Global Costs>:\n");
6178 fprintf (dump_file
, " target_avail_regs %d\n", target_avail_regs
);
6179 fprintf (dump_file
, " target_clobbered_regs %d\n", target_clobbered_regs
);
6180 fprintf (dump_file
, " target_reg_cost %d\n", target_reg_cost
[data
->speed
]);
6181 fprintf (dump_file
, " target_spill_cost %d\n", target_spill_cost
[data
->speed
]);
6185 for (psi
= gsi_start_phis (loop
->header
); !gsi_end_p (psi
); gsi_next (&psi
))
6188 op
= PHI_RESULT (phi
);
6190 if (virtual_operand_p (op
))
6193 if (get_iv (data
, op
))
6196 if (!POINTER_TYPE_P (TREE_TYPE (op
))
6197 && !INTEGRAL_TYPE_P (TREE_TYPE (op
)))
6203 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, j
, bi
)
6205 struct version_info
*info
= ver_info (data
, j
);
6207 if (info
->inv_id
&& info
->has_nonlin_use
)
6211 data
->regs_used
= n
;
6212 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
6213 fprintf (dump_file
, " regs_used %d\n", n
);
6215 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
6217 fprintf (dump_file
, " cost for size:\n");
6218 fprintf (dump_file
, " ivs\tcost\n");
6219 for (j
= 0; j
<= 2 * target_avail_regs
; j
++)
6220 fprintf (dump_file
, " %d\t%d\n", j
,
6221 ivopts_estimate_reg_pressure (data
, 0, j
));
6222 fprintf (dump_file
, "\n");
6226 /* Returns true if A is a cheaper cost pair than B. */
6229 cheaper_cost_pair (class cost_pair
*a
, class cost_pair
*b
)
6237 if (a
->cost
< b
->cost
)
6240 if (b
->cost
< a
->cost
)
6243 /* In case the costs are the same, prefer the cheaper candidate. */
6244 if (a
->cand
->cost
< b
->cand
->cost
)
6250 /* Compare if A is a more expensive cost pair than B. Return 1, 0 and -1
6251 for more expensive, equal and cheaper respectively. */
6254 compare_cost_pair (class cost_pair
*a
, class cost_pair
*b
)
6256 if (cheaper_cost_pair (a
, b
))
6258 if (cheaper_cost_pair (b
, a
))
6264 /* Returns candidate by that USE is expressed in IVS. */
6266 static class cost_pair
*
6267 iv_ca_cand_for_group (class iv_ca
*ivs
, struct iv_group
*group
)
6269 return ivs
->cand_for_group
[group
->id
];
6272 /* Computes the cost field of IVS structure. */
6275 iv_ca_recount_cost (struct ivopts_data
*data
, class iv_ca
*ivs
)
6277 comp_cost cost
= ivs
->cand_use_cost
;
6279 cost
+= ivs
->cand_cost
;
6280 cost
+= ivopts_estimate_reg_pressure (data
, ivs
->n_invs
, ivs
->n_cands
);
6284 /* Remove use of invariants in set INVS by decreasing counter in N_INV_USES
6288 iv_ca_set_remove_invs (class iv_ca
*ivs
, bitmap invs
, unsigned *n_inv_uses
)
6296 gcc_assert (n_inv_uses
!= NULL
);
6297 EXECUTE_IF_SET_IN_BITMAP (invs
, 0, iid
, bi
)
6300 if (n_inv_uses
[iid
] == 0)
6305 /* Set USE not to be expressed by any candidate in IVS. */
6308 iv_ca_set_no_cp (struct ivopts_data
*data
, class iv_ca
*ivs
,
6309 struct iv_group
*group
)
6311 unsigned gid
= group
->id
, cid
;
6312 class cost_pair
*cp
;
6314 cp
= ivs
->cand_for_group
[gid
];
6320 ivs
->cand_for_group
[gid
] = NULL
;
6321 ivs
->n_cand_uses
[cid
]--;
6323 if (ivs
->n_cand_uses
[cid
] == 0)
6325 bitmap_clear_bit (ivs
->cands
, cid
);
6326 if (!cp
->cand
->doloop_p
|| !targetm
.have_count_reg_decr_p
)
6328 ivs
->cand_cost
-= cp
->cand
->cost
;
6329 iv_ca_set_remove_invs (ivs
, cp
->cand
->inv_vars
, ivs
->n_inv_var_uses
);
6330 iv_ca_set_remove_invs (ivs
, cp
->cand
->inv_exprs
, ivs
->n_inv_expr_uses
);
6333 ivs
->cand_use_cost
-= cp
->cost
;
6334 iv_ca_set_remove_invs (ivs
, cp
->inv_vars
, ivs
->n_inv_var_uses
);
6335 iv_ca_set_remove_invs (ivs
, cp
->inv_exprs
, ivs
->n_inv_expr_uses
);
6336 iv_ca_recount_cost (data
, ivs
);
6339 /* Add use of invariants in set INVS by increasing counter in N_INV_USES and
6343 iv_ca_set_add_invs (class iv_ca
*ivs
, bitmap invs
, unsigned *n_inv_uses
)
6351 gcc_assert (n_inv_uses
!= NULL
);
6352 EXECUTE_IF_SET_IN_BITMAP (invs
, 0, iid
, bi
)
6355 if (n_inv_uses
[iid
] == 1)
6360 /* Set cost pair for GROUP in set IVS to CP. */
6363 iv_ca_set_cp (struct ivopts_data
*data
, class iv_ca
*ivs
,
6364 struct iv_group
*group
, class cost_pair
*cp
)
6366 unsigned gid
= group
->id
, cid
;
6368 if (ivs
->cand_for_group
[gid
] == cp
)
6371 if (ivs
->cand_for_group
[gid
])
6372 iv_ca_set_no_cp (data
, ivs
, group
);
6379 ivs
->cand_for_group
[gid
] = cp
;
6380 ivs
->n_cand_uses
[cid
]++;
6381 if (ivs
->n_cand_uses
[cid
] == 1)
6383 bitmap_set_bit (ivs
->cands
, cid
);
6384 if (!cp
->cand
->doloop_p
|| !targetm
.have_count_reg_decr_p
)
6386 ivs
->cand_cost
+= cp
->cand
->cost
;
6387 iv_ca_set_add_invs (ivs
, cp
->cand
->inv_vars
, ivs
->n_inv_var_uses
);
6388 iv_ca_set_add_invs (ivs
, cp
->cand
->inv_exprs
, ivs
->n_inv_expr_uses
);
6391 ivs
->cand_use_cost
+= cp
->cost
;
6392 iv_ca_set_add_invs (ivs
, cp
->inv_vars
, ivs
->n_inv_var_uses
);
6393 iv_ca_set_add_invs (ivs
, cp
->inv_exprs
, ivs
->n_inv_expr_uses
);
6394 iv_ca_recount_cost (data
, ivs
);
6398 /* Extend set IVS by expressing USE by some of the candidates in it
6399 if possible. Consider all important candidates if candidates in
6400 set IVS don't give any result. */
6403 iv_ca_add_group (struct ivopts_data
*data
, class iv_ca
*ivs
,
6404 struct iv_group
*group
)
6406 class cost_pair
*best_cp
= NULL
, *cp
;
6409 struct iv_cand
*cand
;
6411 gcc_assert (ivs
->upto
>= group
->id
);
6415 EXECUTE_IF_SET_IN_BITMAP (ivs
->cands
, 0, i
, bi
)
6417 cand
= data
->vcands
[i
];
6418 cp
= get_group_iv_cost (data
, group
, cand
);
6419 if (cheaper_cost_pair (cp
, best_cp
))
6423 if (best_cp
== NULL
)
6425 EXECUTE_IF_SET_IN_BITMAP (data
->important_candidates
, 0, i
, bi
)
6427 cand
= data
->vcands
[i
];
6428 cp
= get_group_iv_cost (data
, group
, cand
);
6429 if (cheaper_cost_pair (cp
, best_cp
))
6434 iv_ca_set_cp (data
, ivs
, group
, best_cp
);
6437 /* Get cost for assignment IVS. */
6440 iv_ca_cost (class iv_ca
*ivs
)
6442 /* This was a conditional expression but it triggered a bug in
6444 if (ivs
->bad_groups
)
6445 return infinite_cost
;
6450 /* Compare if applying NEW_CP to GROUP for IVS introduces more invariants
6451 than OLD_CP. Return 1, 0 and -1 for more, equal and fewer invariants
6455 iv_ca_compare_deps (struct ivopts_data
*data
, class iv_ca
*ivs
,
6456 struct iv_group
*group
, class cost_pair
*old_cp
,
6457 class cost_pair
*new_cp
)
6459 gcc_assert (old_cp
&& new_cp
&& old_cp
!= new_cp
);
6460 unsigned old_n_invs
= ivs
->n_invs
;
6461 iv_ca_set_cp (data
, ivs
, group
, new_cp
);
6462 unsigned new_n_invs
= ivs
->n_invs
;
6463 iv_ca_set_cp (data
, ivs
, group
, old_cp
);
6465 return new_n_invs
> old_n_invs
? 1 : (new_n_invs
< old_n_invs
? -1 : 0);
6468 /* Creates change of expressing GROUP by NEW_CP instead of OLD_CP and chains
6471 static struct iv_ca_delta
*
6472 iv_ca_delta_add (struct iv_group
*group
, class cost_pair
*old_cp
,
6473 class cost_pair
*new_cp
, struct iv_ca_delta
*next
)
6475 struct iv_ca_delta
*change
= XNEW (struct iv_ca_delta
);
6477 change
->group
= group
;
6478 change
->old_cp
= old_cp
;
6479 change
->new_cp
= new_cp
;
6480 change
->next
= next
;
6485 /* Joins two lists of changes L1 and L2. Destructive -- old lists
6488 static struct iv_ca_delta
*
6489 iv_ca_delta_join (struct iv_ca_delta
*l1
, struct iv_ca_delta
*l2
)
6491 struct iv_ca_delta
*last
;
6499 for (last
= l1
; last
->next
; last
= last
->next
)
6506 /* Reverse the list of changes DELTA, forming the inverse to it. */
6508 static struct iv_ca_delta
*
6509 iv_ca_delta_reverse (struct iv_ca_delta
*delta
)
6511 struct iv_ca_delta
*act
, *next
, *prev
= NULL
;
6513 for (act
= delta
; act
; act
= next
)
6519 std::swap (act
->old_cp
, act
->new_cp
);
6525 /* Commit changes in DELTA to IVS. If FORWARD is false, the changes are
6526 reverted instead. */
6529 iv_ca_delta_commit (struct ivopts_data
*data
, class iv_ca
*ivs
,
6530 struct iv_ca_delta
*delta
, bool forward
)
6532 class cost_pair
*from
, *to
;
6533 struct iv_ca_delta
*act
;
6536 delta
= iv_ca_delta_reverse (delta
);
6538 for (act
= delta
; act
; act
= act
->next
)
6542 gcc_assert (iv_ca_cand_for_group (ivs
, act
->group
) == from
);
6543 iv_ca_set_cp (data
, ivs
, act
->group
, to
);
6547 iv_ca_delta_reverse (delta
);
6550 /* Returns true if CAND is used in IVS. */
6553 iv_ca_cand_used_p (class iv_ca
*ivs
, struct iv_cand
*cand
)
6555 return ivs
->n_cand_uses
[cand
->id
] > 0;
6558 /* Returns number of induction variable candidates in the set IVS. */
6561 iv_ca_n_cands (class iv_ca
*ivs
)
6563 return ivs
->n_cands
;
6566 /* Free the list of changes DELTA. */
6569 iv_ca_delta_free (struct iv_ca_delta
**delta
)
6571 struct iv_ca_delta
*act
, *next
;
6573 for (act
= *delta
; act
; act
= next
)
6582 /* Allocates new iv candidates assignment. */
6584 static class iv_ca
*
6585 iv_ca_new (struct ivopts_data
*data
)
6587 class iv_ca
*nw
= XNEW (class iv_ca
);
6591 nw
->cand_for_group
= XCNEWVEC (class cost_pair
*,
6592 data
->vgroups
.length ());
6593 nw
->n_cand_uses
= XCNEWVEC (unsigned, data
->vcands
.length ());
6594 nw
->cands
= BITMAP_ALLOC (NULL
);
6597 nw
->cand_use_cost
= no_cost
;
6599 nw
->n_inv_var_uses
= XCNEWVEC (unsigned, data
->max_inv_var_id
+ 1);
6600 nw
->n_inv_expr_uses
= XCNEWVEC (unsigned, data
->max_inv_expr_id
+ 1);
6606 /* Free memory occupied by the set IVS. */
6609 iv_ca_free (class iv_ca
**ivs
)
6611 free ((*ivs
)->cand_for_group
);
6612 free ((*ivs
)->n_cand_uses
);
6613 BITMAP_FREE ((*ivs
)->cands
);
6614 free ((*ivs
)->n_inv_var_uses
);
6615 free ((*ivs
)->n_inv_expr_uses
);
6620 /* Dumps IVS to FILE. */
6623 iv_ca_dump (struct ivopts_data
*data
, FILE *file
, class iv_ca
*ivs
)
6626 comp_cost cost
= iv_ca_cost (ivs
);
6628 fprintf (file
, " cost: %" PRId64
" (complexity %d)\n", cost
.cost
,
6630 fprintf (file
, " reg_cost: %d\n",
6631 ivopts_estimate_reg_pressure (data
, ivs
->n_invs
, ivs
->n_cands
));
6632 fprintf (file
, " cand_cost: %" PRId64
"\n cand_group_cost: "
6633 "%" PRId64
" (complexity %d)\n", ivs
->cand_cost
,
6634 ivs
->cand_use_cost
.cost
, ivs
->cand_use_cost
.complexity
);
6635 bitmap_print (file
, ivs
->cands
, " candidates: ","\n");
6637 for (i
= 0; i
< ivs
->upto
; i
++)
6639 struct iv_group
*group
= data
->vgroups
[i
];
6640 class cost_pair
*cp
= iv_ca_cand_for_group (ivs
, group
);
6642 fprintf (file
, " group:%d --> iv_cand:%d, cost=("
6643 "%" PRId64
",%d)\n", group
->id
, cp
->cand
->id
,
6644 cp
->cost
.cost
, cp
->cost
.complexity
);
6646 fprintf (file
, " group:%d --> ??\n", group
->id
);
6649 const char *pref
= "";
6650 fprintf (file
, " invariant variables: ");
6651 for (i
= 1; i
<= data
->max_inv_var_id
; i
++)
6652 if (ivs
->n_inv_var_uses
[i
])
6654 fprintf (file
, "%s%d", pref
, i
);
6659 fprintf (file
, "\n invariant expressions: ");
6660 for (i
= 1; i
<= data
->max_inv_expr_id
; i
++)
6661 if (ivs
->n_inv_expr_uses
[i
])
6663 fprintf (file
, "%s%d", pref
, i
);
6667 fprintf (file
, "\n\n");
6670 /* Try changing candidate in IVS to CAND for each use. Return cost of the
6671 new set, and store differences in DELTA. Number of induction variables
6672 in the new set is stored to N_IVS. MIN_NCAND is a flag. When it is true
6673 the function will try to find a solution with mimimal iv candidates. */
6676 iv_ca_extend (struct ivopts_data
*data
, class iv_ca
*ivs
,
6677 struct iv_cand
*cand
, struct iv_ca_delta
**delta
,
6678 unsigned *n_ivs
, bool min_ncand
)
6682 struct iv_group
*group
;
6683 class cost_pair
*old_cp
, *new_cp
;
6686 for (i
= 0; i
< ivs
->upto
; i
++)
6688 group
= data
->vgroups
[i
];
6689 old_cp
= iv_ca_cand_for_group (ivs
, group
);
6692 && old_cp
->cand
== cand
)
6695 new_cp
= get_group_iv_cost (data
, group
, cand
);
6701 int cmp_invs
= iv_ca_compare_deps (data
, ivs
, group
, old_cp
, new_cp
);
6702 /* Skip if new_cp depends on more invariants. */
6706 int cmp_cost
= compare_cost_pair (new_cp
, old_cp
);
6707 /* Skip if new_cp is not cheaper. */
6708 if (cmp_cost
> 0 || (cmp_cost
== 0 && cmp_invs
== 0))
6712 *delta
= iv_ca_delta_add (group
, old_cp
, new_cp
, *delta
);
6715 iv_ca_delta_commit (data
, ivs
, *delta
, true);
6716 cost
= iv_ca_cost (ivs
);
6718 *n_ivs
= iv_ca_n_cands (ivs
);
6719 iv_ca_delta_commit (data
, ivs
, *delta
, false);
6724 /* Try narrowing set IVS by removing CAND. Return the cost of
6725 the new set and store the differences in DELTA. START is
6726 the candidate with which we start narrowing. */
6729 iv_ca_narrow (struct ivopts_data
*data
, class iv_ca
*ivs
,
6730 struct iv_cand
*cand
, struct iv_cand
*start
,
6731 struct iv_ca_delta
**delta
)
6734 struct iv_group
*group
;
6735 class cost_pair
*old_cp
, *new_cp
, *cp
;
6737 struct iv_cand
*cnd
;
6738 comp_cost cost
, best_cost
, acost
;
6741 for (i
= 0; i
< data
->vgroups
.length (); i
++)
6743 group
= data
->vgroups
[i
];
6745 old_cp
= iv_ca_cand_for_group (ivs
, group
);
6746 if (old_cp
->cand
!= cand
)
6749 best_cost
= iv_ca_cost (ivs
);
6750 /* Start narrowing with START. */
6751 new_cp
= get_group_iv_cost (data
, group
, start
);
6753 if (data
->consider_all_candidates
)
6755 EXECUTE_IF_SET_IN_BITMAP (ivs
->cands
, 0, ci
, bi
)
6757 if (ci
== cand
->id
|| (start
&& ci
== start
->id
))
6760 cnd
= data
->vcands
[ci
];
6762 cp
= get_group_iv_cost (data
, group
, cnd
);
6766 iv_ca_set_cp (data
, ivs
, group
, cp
);
6767 acost
= iv_ca_cost (ivs
);
6769 if (acost
< best_cost
)
6778 EXECUTE_IF_AND_IN_BITMAP (group
->related_cands
, ivs
->cands
, 0, ci
, bi
)
6780 if (ci
== cand
->id
|| (start
&& ci
== start
->id
))
6783 cnd
= data
->vcands
[ci
];
6785 cp
= get_group_iv_cost (data
, group
, cnd
);
6789 iv_ca_set_cp (data
, ivs
, group
, cp
);
6790 acost
= iv_ca_cost (ivs
);
6792 if (acost
< best_cost
)
6799 /* Restore to old cp for use. */
6800 iv_ca_set_cp (data
, ivs
, group
, old_cp
);
6804 iv_ca_delta_free (delta
);
6805 return infinite_cost
;
6808 *delta
= iv_ca_delta_add (group
, old_cp
, new_cp
, *delta
);
6811 iv_ca_delta_commit (data
, ivs
, *delta
, true);
6812 cost
= iv_ca_cost (ivs
);
6813 iv_ca_delta_commit (data
, ivs
, *delta
, false);
6818 /* Try optimizing the set of candidates IVS by removing candidates different
6819 from to EXCEPT_CAND from it. Return cost of the new set, and store
6820 differences in DELTA. */
6823 iv_ca_prune (struct ivopts_data
*data
, class iv_ca
*ivs
,
6824 struct iv_cand
*except_cand
, struct iv_ca_delta
**delta
)
6827 struct iv_ca_delta
*act_delta
, *best_delta
;
6829 comp_cost best_cost
, acost
;
6830 struct iv_cand
*cand
;
6833 best_cost
= iv_ca_cost (ivs
);
6835 EXECUTE_IF_SET_IN_BITMAP (ivs
->cands
, 0, i
, bi
)
6837 cand
= data
->vcands
[i
];
6839 if (cand
== except_cand
)
6842 acost
= iv_ca_narrow (data
, ivs
, cand
, except_cand
, &act_delta
);
6844 if (acost
< best_cost
)
6847 iv_ca_delta_free (&best_delta
);
6848 best_delta
= act_delta
;
6851 iv_ca_delta_free (&act_delta
);
6860 /* Recurse to possibly remove other unnecessary ivs. */
6861 iv_ca_delta_commit (data
, ivs
, best_delta
, true);
6862 best_cost
= iv_ca_prune (data
, ivs
, except_cand
, delta
);
6863 iv_ca_delta_commit (data
, ivs
, best_delta
, false);
6864 *delta
= iv_ca_delta_join (best_delta
, *delta
);
6868 /* Check if CAND_IDX is a candidate other than OLD_CAND and has
6869 cheaper local cost for GROUP than BEST_CP. Return pointer to
6870 the corresponding cost_pair, otherwise just return BEST_CP. */
6872 static class cost_pair
*
6873 cheaper_cost_with_cand (struct ivopts_data
*data
, struct iv_group
*group
,
6874 unsigned int cand_idx
, struct iv_cand
*old_cand
,
6875 class cost_pair
*best_cp
)
6877 struct iv_cand
*cand
;
6878 class cost_pair
*cp
;
6880 gcc_assert (old_cand
!= NULL
&& best_cp
!= NULL
);
6881 if (cand_idx
== old_cand
->id
)
6884 cand
= data
->vcands
[cand_idx
];
6885 cp
= get_group_iv_cost (data
, group
, cand
);
6886 if (cp
!= NULL
&& cheaper_cost_pair (cp
, best_cp
))
6892 /* Try breaking local optimal fixed-point for IVS by replacing candidates
6893 which are used by more than one iv uses. For each of those candidates,
6894 this function tries to represent iv uses under that candidate using
6895 other ones with lower local cost, then tries to prune the new set.
6896 If the new set has lower cost, It returns the new cost after recording
6897 candidate replacement in list DELTA. */
6900 iv_ca_replace (struct ivopts_data
*data
, class iv_ca
*ivs
,
6901 struct iv_ca_delta
**delta
)
6903 bitmap_iterator bi
, bj
;
6904 unsigned int i
, j
, k
;
6905 struct iv_cand
*cand
;
6906 comp_cost orig_cost
, acost
;
6907 struct iv_ca_delta
*act_delta
, *tmp_delta
;
6908 class cost_pair
*old_cp
, *best_cp
= NULL
;
6911 orig_cost
= iv_ca_cost (ivs
);
6913 EXECUTE_IF_SET_IN_BITMAP (ivs
->cands
, 0, i
, bi
)
6915 if (ivs
->n_cand_uses
[i
] == 1
6916 || ivs
->n_cand_uses
[i
] > ALWAYS_PRUNE_CAND_SET_BOUND
)
6919 cand
= data
->vcands
[i
];
6922 /* Represent uses under current candidate using other ones with
6923 lower local cost. */
6924 for (j
= 0; j
< ivs
->upto
; j
++)
6926 struct iv_group
*group
= data
->vgroups
[j
];
6927 old_cp
= iv_ca_cand_for_group (ivs
, group
);
6929 if (old_cp
->cand
!= cand
)
6933 if (data
->consider_all_candidates
)
6934 for (k
= 0; k
< data
->vcands
.length (); k
++)
6935 best_cp
= cheaper_cost_with_cand (data
, group
, k
,
6936 old_cp
->cand
, best_cp
);
6938 EXECUTE_IF_SET_IN_BITMAP (group
->related_cands
, 0, k
, bj
)
6939 best_cp
= cheaper_cost_with_cand (data
, group
, k
,
6940 old_cp
->cand
, best_cp
);
6942 if (best_cp
== old_cp
)
6945 act_delta
= iv_ca_delta_add (group
, old_cp
, best_cp
, act_delta
);
6947 /* No need for further prune. */
6951 /* Prune the new candidate set. */
6952 iv_ca_delta_commit (data
, ivs
, act_delta
, true);
6953 acost
= iv_ca_prune (data
, ivs
, NULL
, &tmp_delta
);
6954 iv_ca_delta_commit (data
, ivs
, act_delta
, false);
6955 act_delta
= iv_ca_delta_join (act_delta
, tmp_delta
);
6957 if (acost
< orig_cost
)
6963 iv_ca_delta_free (&act_delta
);
6969 /* Tries to extend the sets IVS in the best possible way in order to
6970 express the GROUP. If ORIGINALP is true, prefer candidates from
6971 the original set of IVs, otherwise favor important candidates not
6972 based on any memory object. */
6975 try_add_cand_for (struct ivopts_data
*data
, class iv_ca
*ivs
,
6976 struct iv_group
*group
, bool originalp
)
6978 comp_cost best_cost
, act_cost
;
6981 struct iv_cand
*cand
;
6982 struct iv_ca_delta
*best_delta
= NULL
, *act_delta
;
6983 class cost_pair
*cp
;
6985 iv_ca_add_group (data
, ivs
, group
);
6986 best_cost
= iv_ca_cost (ivs
);
6987 cp
= iv_ca_cand_for_group (ivs
, group
);
6990 best_delta
= iv_ca_delta_add (group
, NULL
, cp
, NULL
);
6991 iv_ca_set_no_cp (data
, ivs
, group
);
6994 /* If ORIGINALP is true, try to find the original IV for the use. Otherwise
6995 first try important candidates not based on any memory object. Only if
6996 this fails, try the specific ones. Rationale -- in loops with many
6997 variables the best choice often is to use just one generic biv. If we
6998 added here many ivs specific to the uses, the optimization algorithm later
6999 would be likely to get stuck in a local minimum, thus causing us to create
7000 too many ivs. The approach from few ivs to more seems more likely to be
7001 successful -- starting from few ivs, replacing an expensive use by a
7002 specific iv should always be a win. */
7003 EXECUTE_IF_SET_IN_BITMAP (group
->related_cands
, 0, i
, bi
)
7005 cand
= data
->vcands
[i
];
7007 if (originalp
&& cand
->pos
!=IP_ORIGINAL
)
7010 if (!originalp
&& cand
->iv
->base_object
!= NULL_TREE
)
7013 if (iv_ca_cand_used_p (ivs
, cand
))
7016 cp
= get_group_iv_cost (data
, group
, cand
);
7020 iv_ca_set_cp (data
, ivs
, group
, cp
);
7021 act_cost
= iv_ca_extend (data
, ivs
, cand
, &act_delta
, NULL
,
7023 iv_ca_set_no_cp (data
, ivs
, group
);
7024 act_delta
= iv_ca_delta_add (group
, NULL
, cp
, act_delta
);
7026 if (act_cost
< best_cost
)
7028 best_cost
= act_cost
;
7030 iv_ca_delta_free (&best_delta
);
7031 best_delta
= act_delta
;
7034 iv_ca_delta_free (&act_delta
);
7037 if (best_cost
.infinite_cost_p ())
7039 for (i
= 0; i
< group
->n_map_members
; i
++)
7041 cp
= group
->cost_map
+ i
;
7046 /* Already tried this. */
7047 if (cand
->important
)
7049 if (originalp
&& cand
->pos
== IP_ORIGINAL
)
7051 if (!originalp
&& cand
->iv
->base_object
== NULL_TREE
)
7055 if (iv_ca_cand_used_p (ivs
, cand
))
7059 iv_ca_set_cp (data
, ivs
, group
, cp
);
7060 act_cost
= iv_ca_extend (data
, ivs
, cand
, &act_delta
, NULL
, true);
7061 iv_ca_set_no_cp (data
, ivs
, group
);
7062 act_delta
= iv_ca_delta_add (group
,
7063 iv_ca_cand_for_group (ivs
, group
),
7066 if (act_cost
< best_cost
)
7068 best_cost
= act_cost
;
7071 iv_ca_delta_free (&best_delta
);
7072 best_delta
= act_delta
;
7075 iv_ca_delta_free (&act_delta
);
7079 iv_ca_delta_commit (data
, ivs
, best_delta
, true);
7080 iv_ca_delta_free (&best_delta
);
7082 return !best_cost
.infinite_cost_p ();
7085 /* Finds an initial assignment of candidates to uses. */
7087 static class iv_ca
*
7088 get_initial_solution (struct ivopts_data
*data
, bool originalp
)
7091 class iv_ca
*ivs
= iv_ca_new (data
);
7093 for (i
= 0; i
< data
->vgroups
.length (); i
++)
7094 if (!try_add_cand_for (data
, ivs
, data
->vgroups
[i
], originalp
))
7103 /* Tries to improve set of induction variables IVS. TRY_REPLACE_P
7104 points to a bool variable, this function tries to break local
7105 optimal fixed-point by replacing candidates in IVS if it's true. */
7108 try_improve_iv_set (struct ivopts_data
*data
,
7109 class iv_ca
*ivs
, bool *try_replace_p
)
7112 comp_cost acost
, best_cost
= iv_ca_cost (ivs
);
7113 struct iv_ca_delta
*best_delta
= NULL
, *act_delta
, *tmp_delta
;
7114 struct iv_cand
*cand
;
7116 /* Try extending the set of induction variables by one. */
7117 for (i
= 0; i
< data
->vcands
.length (); i
++)
7119 cand
= data
->vcands
[i
];
7121 if (iv_ca_cand_used_p (ivs
, cand
))
7124 acost
= iv_ca_extend (data
, ivs
, cand
, &act_delta
, &n_ivs
, false);
7128 /* If we successfully added the candidate and the set is small enough,
7129 try optimizing it by removing other candidates. */
7130 if (n_ivs
<= ALWAYS_PRUNE_CAND_SET_BOUND
)
7132 iv_ca_delta_commit (data
, ivs
, act_delta
, true);
7133 acost
= iv_ca_prune (data
, ivs
, cand
, &tmp_delta
);
7134 iv_ca_delta_commit (data
, ivs
, act_delta
, false);
7135 act_delta
= iv_ca_delta_join (act_delta
, tmp_delta
);
7138 if (acost
< best_cost
)
7141 iv_ca_delta_free (&best_delta
);
7142 best_delta
= act_delta
;
7145 iv_ca_delta_free (&act_delta
);
7150 /* Try removing the candidates from the set instead. */
7151 best_cost
= iv_ca_prune (data
, ivs
, NULL
, &best_delta
);
7153 if (!best_delta
&& *try_replace_p
)
7155 *try_replace_p
= false;
7156 /* So far candidate selecting algorithm tends to choose fewer IVs
7157 so that it can handle cases in which loops have many variables
7158 but the best choice is often to use only one general biv. One
7159 weakness is it can't handle opposite cases, in which different
7160 candidates should be chosen with respect to each use. To solve
7161 the problem, we replace candidates in a manner described by the
7162 comments of iv_ca_replace, thus give general algorithm a chance
7163 to break local optimal fixed-point in these cases. */
7164 best_cost
= iv_ca_replace (data
, ivs
, &best_delta
);
7171 iv_ca_delta_commit (data
, ivs
, best_delta
, true);
7172 iv_ca_delta_free (&best_delta
);
7173 return best_cost
== iv_ca_cost (ivs
);
7176 /* Attempts to find the optimal set of induction variables. We do simple
7177 greedy heuristic -- we try to replace at most one candidate in the selected
7178 solution and remove the unused ivs while this improves the cost. */
7180 static class iv_ca
*
7181 find_optimal_iv_set_1 (struct ivopts_data
*data
, bool originalp
)
7184 bool try_replace_p
= true;
7186 /* Get the initial solution. */
7187 set
= get_initial_solution (data
, originalp
);
7190 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7191 fprintf (dump_file
, "Unable to substitute for ivs, failed.\n");
7195 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7197 fprintf (dump_file
, "Initial set of candidates:\n");
7198 iv_ca_dump (data
, dump_file
, set
);
7201 while (try_improve_iv_set (data
, set
, &try_replace_p
))
7203 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7205 fprintf (dump_file
, "Improved to:\n");
7206 iv_ca_dump (data
, dump_file
, set
);
7210 /* If the set has infinite_cost, it can't be optimal. */
7211 if (iv_ca_cost (set
).infinite_cost_p ())
7213 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7215 "Overflow to infinite cost in try_improve_iv_set.\n");
7221 static class iv_ca
*
7222 find_optimal_iv_set (struct ivopts_data
*data
)
7225 comp_cost cost
, origcost
;
7226 class iv_ca
*set
, *origset
;
7228 /* Determine the cost based on a strategy that starts with original IVs,
7229 and try again using a strategy that prefers candidates not based
7231 origset
= find_optimal_iv_set_1 (data
, true);
7232 set
= find_optimal_iv_set_1 (data
, false);
7234 if (!origset
&& !set
)
7237 origcost
= origset
? iv_ca_cost (origset
) : infinite_cost
;
7238 cost
= set
? iv_ca_cost (set
) : infinite_cost
;
7240 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7242 fprintf (dump_file
, "Original cost %" PRId64
" (complexity %d)\n\n",
7243 origcost
.cost
, origcost
.complexity
);
7244 fprintf (dump_file
, "Final cost %" PRId64
" (complexity %d)\n\n",
7245 cost
.cost
, cost
.complexity
);
7248 /* Choose the one with the best cost. */
7249 if (origcost
<= cost
)
7256 iv_ca_free (&origset
);
7258 for (i
= 0; i
< data
->vgroups
.length (); i
++)
7260 struct iv_group
*group
= data
->vgroups
[i
];
7261 group
->selected
= iv_ca_cand_for_group (set
, group
)->cand
;
7267 /* Creates a new induction variable corresponding to CAND. */
7270 create_new_iv (struct ivopts_data
*data
, struct iv_cand
*cand
)
7272 gimple_stmt_iterator incr_pos
;
7275 struct iv_group
*group
;
7278 gcc_assert (cand
->iv
!= NULL
);
7283 incr_pos
= gsi_last_bb (ip_normal_pos (data
->current_loop
));
7287 incr_pos
= gsi_last_bb (ip_end_pos (data
->current_loop
));
7289 if (!gsi_end_p (incr_pos
) && stmt_ends_bb_p (gsi_stmt (incr_pos
)))
7291 edge e
= find_edge (gsi_bb (incr_pos
), data
->current_loop
->header
);
7292 incr_pos
= gsi_after_labels (split_edge (e
));
7301 incr_pos
= gsi_for_stmt (cand
->incremented_at
);
7305 /* Mark that the iv is preserved. */
7306 name_info (data
, cand
->var_before
)->preserve_biv
= true;
7307 name_info (data
, cand
->var_after
)->preserve_biv
= true;
7309 /* Rewrite the increment so that it uses var_before directly. */
7310 use
= find_interesting_uses_op (data
, cand
->var_after
);
7311 group
= data
->vgroups
[use
->group_id
];
7312 group
->selected
= cand
;
7316 gimple_add_tmp_var (cand
->var_before
);
7318 base
= unshare_expr (cand
->iv
->base
);
7320 create_iv (base
, PLUS_EXPR
, unshare_expr (cand
->iv
->step
),
7321 cand
->var_before
, data
->current_loop
,
7322 &incr_pos
, after
, &cand
->var_before
, &cand
->var_after
);
7325 /* Creates new induction variables described in SET. */
7328 create_new_ivs (struct ivopts_data
*data
, class iv_ca
*set
)
7331 struct iv_cand
*cand
;
7334 EXECUTE_IF_SET_IN_BITMAP (set
->cands
, 0, i
, bi
)
7336 cand
= data
->vcands
[i
];
7337 create_new_iv (data
, cand
);
7340 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7342 fprintf (dump_file
, "Selected IV set for loop %d",
7343 data
->current_loop
->num
);
7344 if (data
->loop_loc
!= UNKNOWN_LOCATION
)
7345 fprintf (dump_file
, " at %s:%d", LOCATION_FILE (data
->loop_loc
),
7346 LOCATION_LINE (data
->loop_loc
));
7347 fprintf (dump_file
, ", " HOST_WIDE_INT_PRINT_DEC
" avg niters",
7348 avg_loop_niter (data
->current_loop
));
7349 fprintf (dump_file
, ", %lu IVs:\n", bitmap_count_bits (set
->cands
));
7350 EXECUTE_IF_SET_IN_BITMAP (set
->cands
, 0, i
, bi
)
7352 cand
= data
->vcands
[i
];
7353 dump_cand (dump_file
, cand
);
7355 fprintf (dump_file
, "\n");
7359 /* Rewrites USE (definition of iv used in a nonlinear expression)
7360 using candidate CAND. */
7363 rewrite_use_nonlinear_expr (struct ivopts_data
*data
,
7364 struct iv_use
*use
, struct iv_cand
*cand
)
7367 gimple_stmt_iterator bsi
;
7368 tree comp
, type
= get_use_type (use
), tgt
;
7370 /* An important special case -- if we are asked to express value of
7371 the original iv by itself, just exit; there is no need to
7372 introduce a new computation (that might also need casting the
7373 variable to unsigned and back). */
7374 if (cand
->pos
== IP_ORIGINAL
7375 && cand
->incremented_at
== use
->stmt
)
7377 tree op
= NULL_TREE
;
7378 enum tree_code stmt_code
;
7380 gcc_assert (is_gimple_assign (use
->stmt
));
7381 gcc_assert (gimple_assign_lhs (use
->stmt
) == cand
->var_after
);
7383 /* Check whether we may leave the computation unchanged.
7384 This is the case only if it does not rely on other
7385 computations in the loop -- otherwise, the computation
7386 we rely upon may be removed in remove_unused_ivs,
7387 thus leading to ICE. */
7388 stmt_code
= gimple_assign_rhs_code (use
->stmt
);
7389 if (stmt_code
== PLUS_EXPR
7390 || stmt_code
== MINUS_EXPR
7391 || stmt_code
== POINTER_PLUS_EXPR
)
7393 if (gimple_assign_rhs1 (use
->stmt
) == cand
->var_before
)
7394 op
= gimple_assign_rhs2 (use
->stmt
);
7395 else if (gimple_assign_rhs2 (use
->stmt
) == cand
->var_before
)
7396 op
= gimple_assign_rhs1 (use
->stmt
);
7399 if (op
!= NULL_TREE
)
7401 if (expr_invariant_in_loop_p (data
->current_loop
, op
))
7403 if (TREE_CODE (op
) == SSA_NAME
)
7405 struct iv
*iv
= get_iv (data
, op
);
7406 if (iv
!= NULL
&& integer_zerop (iv
->step
))
7412 switch (gimple_code (use
->stmt
))
7415 tgt
= PHI_RESULT (use
->stmt
);
7417 /* If we should keep the biv, do not replace it. */
7418 if (name_info (data
, tgt
)->preserve_biv
)
7421 bsi
= gsi_after_labels (gimple_bb (use
->stmt
));
7425 tgt
= gimple_assign_lhs (use
->stmt
);
7426 bsi
= gsi_for_stmt (use
->stmt
);
7433 aff_tree aff_inv
, aff_var
;
7434 if (!get_computation_aff_1 (data
->current_loop
, use
->stmt
,
7435 use
, cand
, &aff_inv
, &aff_var
))
7438 unshare_aff_combination (&aff_inv
);
7439 unshare_aff_combination (&aff_var
);
7440 /* Prefer CSE opportunity than loop invariant by adding offset at last
7441 so that iv_uses have different offsets can be CSEed. */
7442 poly_widest_int offset
= aff_inv
.offset
;
7445 gimple_seq stmt_list
= NULL
, seq
= NULL
;
7446 tree comp_op1
= aff_combination_to_tree (&aff_inv
);
7447 tree comp_op2
= aff_combination_to_tree (&aff_var
);
7448 gcc_assert (comp_op1
&& comp_op2
);
7450 comp_op1
= force_gimple_operand (comp_op1
, &seq
, true, NULL
);
7451 gimple_seq_add_seq (&stmt_list
, seq
);
7452 comp_op2
= force_gimple_operand (comp_op2
, &seq
, true, NULL
);
7453 gimple_seq_add_seq (&stmt_list
, seq
);
7455 if (POINTER_TYPE_P (TREE_TYPE (comp_op2
)))
7456 std::swap (comp_op1
, comp_op2
);
7458 if (POINTER_TYPE_P (TREE_TYPE (comp_op1
)))
7460 comp
= fold_build_pointer_plus (comp_op1
,
7461 fold_convert (sizetype
, comp_op2
));
7462 comp
= fold_build_pointer_plus (comp
,
7463 wide_int_to_tree (sizetype
, offset
));
7467 comp
= fold_build2 (PLUS_EXPR
, TREE_TYPE (comp_op1
), comp_op1
,
7468 fold_convert (TREE_TYPE (comp_op1
), comp_op2
));
7469 comp
= fold_build2 (PLUS_EXPR
, TREE_TYPE (comp_op1
), comp
,
7470 wide_int_to_tree (TREE_TYPE (comp_op1
), offset
));
7473 comp
= fold_convert (type
, comp
);
7474 comp
= force_gimple_operand (comp
, &seq
, false, NULL
);
7475 gimple_seq_add_seq (&stmt_list
, seq
);
7476 if (gimple_code (use
->stmt
) != GIMPLE_PHI
7477 /* We can't allow re-allocating the stmt as it might be pointed
7479 && (get_gimple_rhs_num_ops (TREE_CODE (comp
))
7480 >= gimple_num_ops (gsi_stmt (bsi
))))
7482 comp
= force_gimple_operand (comp
, &seq
, true, NULL
);
7483 gimple_seq_add_seq (&stmt_list
, seq
);
7484 if (POINTER_TYPE_P (TREE_TYPE (tgt
)))
7486 duplicate_ssa_name_ptr_info (comp
, SSA_NAME_PTR_INFO (tgt
));
7487 /* As this isn't a plain copy we have to reset alignment
7489 if (SSA_NAME_PTR_INFO (comp
))
7490 mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (comp
));
7494 gsi_insert_seq_before (&bsi
, stmt_list
, GSI_SAME_STMT
);
7495 if (gimple_code (use
->stmt
) == GIMPLE_PHI
)
7497 ass
= gimple_build_assign (tgt
, comp
);
7498 gsi_insert_before (&bsi
, ass
, GSI_SAME_STMT
);
7500 bsi
= gsi_for_stmt (use
->stmt
);
7501 remove_phi_node (&bsi
, false);
7505 gimple_assign_set_rhs_from_tree (&bsi
, comp
);
7506 use
->stmt
= gsi_stmt (bsi
);
7510 /* Performs a peephole optimization to reorder the iv update statement with
7511 a mem ref to enable instruction combining in later phases. The mem ref uses
7512 the iv value before the update, so the reordering transformation requires
7513 adjustment of the offset. CAND is the selected IV_CAND.
7517 t = MEM_REF (base, iv1, 8, 16); // base, index, stride, offset
7525 directly propagating t over to (1) will introduce overlapping live range
7526 thus increase register pressure. This peephole transform it into:
7530 t = MEM_REF (base, iv2, 8, 8);
7537 adjust_iv_update_pos (struct iv_cand
*cand
, struct iv_use
*use
)
7540 gimple
*iv_update
, *stmt
;
7542 gimple_stmt_iterator gsi
, gsi_iv
;
7544 if (cand
->pos
!= IP_NORMAL
)
7547 var_after
= cand
->var_after
;
7548 iv_update
= SSA_NAME_DEF_STMT (var_after
);
7550 bb
= gimple_bb (iv_update
);
7551 gsi
= gsi_last_nondebug_bb (bb
);
7552 stmt
= gsi_stmt (gsi
);
7554 /* Only handle conditional statement for now. */
7555 if (gimple_code (stmt
) != GIMPLE_COND
)
7558 gsi_prev_nondebug (&gsi
);
7559 stmt
= gsi_stmt (gsi
);
7560 if (stmt
!= iv_update
)
7563 gsi_prev_nondebug (&gsi
);
7564 if (gsi_end_p (gsi
))
7567 stmt
= gsi_stmt (gsi
);
7568 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
7571 if (stmt
!= use
->stmt
)
7574 if (TREE_CODE (gimple_assign_lhs (stmt
)) != SSA_NAME
)
7577 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7579 fprintf (dump_file
, "Reordering \n");
7580 print_gimple_stmt (dump_file
, iv_update
, 0);
7581 print_gimple_stmt (dump_file
, use
->stmt
, 0);
7582 fprintf (dump_file
, "\n");
7585 gsi
= gsi_for_stmt (use
->stmt
);
7586 gsi_iv
= gsi_for_stmt (iv_update
);
7587 gsi_move_before (&gsi_iv
, &gsi
);
7589 cand
->pos
= IP_BEFORE_USE
;
7590 cand
->incremented_at
= use
->stmt
;
7593 /* Return the alias pointer type that should be used for a MEM_REF
7594 associated with USE, which has type USE_PTR_ADDRESS. */
7597 get_alias_ptr_type_for_ptr_address (iv_use
*use
)
7599 gcall
*call
= as_a
<gcall
*> (use
->stmt
);
7600 switch (gimple_call_internal_fn (call
))
7603 case IFN_MASK_STORE
:
7604 case IFN_MASK_LOAD_LANES
:
7605 case IFN_MASK_STORE_LANES
:
7606 case IFN_MASK_LEN_LOAD_LANES
:
7607 case IFN_MASK_LEN_STORE_LANES
:
7610 case IFN_MASK_LEN_LOAD
:
7611 case IFN_MASK_LEN_STORE
:
7612 /* The second argument contains the correct alias type. */
7613 gcc_assert (use
->op_p
= gimple_call_arg_ptr (call
, 0));
7614 return TREE_TYPE (gimple_call_arg (call
, 1));
7622 /* Rewrites USE (address that is an iv) using candidate CAND. */
7625 rewrite_use_address (struct ivopts_data
*data
,
7626 struct iv_use
*use
, struct iv_cand
*cand
)
7631 adjust_iv_update_pos (cand
, use
);
7632 ok
= get_computation_aff (data
->current_loop
, use
->stmt
, use
, cand
, &aff
);
7634 unshare_aff_combination (&aff
);
7636 /* To avoid undefined overflow problems, all IV candidates use unsigned
7637 integer types. The drawback is that this makes it impossible for
7638 create_mem_ref to distinguish an IV that is based on a memory object
7639 from one that represents simply an offset.
7641 To work around this problem, we pass a hint to create_mem_ref that
7642 indicates which variable (if any) in aff is an IV based on a memory
7643 object. Note that we only consider the candidate. If this is not
7644 based on an object, the base of the reference is in some subexpression
7645 of the use -- but these will use pointer types, so they are recognized
7646 by the create_mem_ref heuristics anyway. */
7647 tree iv
= var_at_stmt (data
->current_loop
, cand
, use
->stmt
);
7648 tree base_hint
= (cand
->iv
->base_object
) ? iv
: NULL_TREE
;
7649 gimple_stmt_iterator bsi
= gsi_for_stmt (use
->stmt
);
7650 tree type
= use
->mem_type
;
7651 tree alias_ptr_type
;
7652 if (use
->type
== USE_PTR_ADDRESS
)
7653 alias_ptr_type
= get_alias_ptr_type_for_ptr_address (use
);
7656 gcc_assert (type
== TREE_TYPE (*use
->op_p
));
7657 unsigned int align
= get_object_alignment (*use
->op_p
);
7658 if (align
!= TYPE_ALIGN (type
))
7659 type
= build_aligned_type (type
, align
);
7660 alias_ptr_type
= reference_alias_ptr_type (*use
->op_p
);
7662 tree ref
= create_mem_ref (&bsi
, type
, &aff
, alias_ptr_type
,
7663 iv
, base_hint
, data
->speed
);
7665 if (use
->type
== USE_PTR_ADDRESS
)
7667 ref
= fold_build1 (ADDR_EXPR
, build_pointer_type (use
->mem_type
), ref
);
7668 ref
= fold_convert (get_use_type (use
), ref
);
7669 ref
= force_gimple_operand_gsi (&bsi
, ref
, true, NULL_TREE
,
7670 true, GSI_SAME_STMT
);
7674 /* When we end up confused enough and have no suitable base but
7675 stuffed everything to index2 use a LEA for the address and
7676 create a plain MEM_REF to avoid basing a memory reference
7677 on address zero which create_mem_ref_raw does as fallback. */
7678 if (TREE_CODE (ref
) == TARGET_MEM_REF
7679 && TMR_INDEX2 (ref
) != NULL_TREE
7680 && integer_zerop (TREE_OPERAND (ref
, 0)))
7682 ref
= fold_build1 (ADDR_EXPR
, TREE_TYPE (TREE_OPERAND (ref
, 0)), ref
);
7683 ref
= force_gimple_operand_gsi (&bsi
, ref
, true, NULL_TREE
,
7684 true, GSI_SAME_STMT
);
7685 ref
= build2 (MEM_REF
, type
, ref
, build_zero_cst (alias_ptr_type
));
7687 copy_ref_info (ref
, *use
->op_p
);
7693 /* Rewrites USE (the condition such that one of the arguments is an iv) using
7697 rewrite_use_compare (struct ivopts_data
*data
,
7698 struct iv_use
*use
, struct iv_cand
*cand
)
7700 tree comp
, op
, bound
;
7701 gimple_stmt_iterator bsi
= gsi_for_stmt (use
->stmt
);
7702 enum tree_code compare
;
7703 struct iv_group
*group
= data
->vgroups
[use
->group_id
];
7704 class cost_pair
*cp
= get_group_iv_cost (data
, group
, cand
);
7709 tree var
= var_at_stmt (data
->current_loop
, cand
, use
->stmt
);
7710 tree var_type
= TREE_TYPE (var
);
7713 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
7715 fprintf (dump_file
, "Replacing exit test: ");
7716 print_gimple_stmt (dump_file
, use
->stmt
, 0, TDF_SLIM
);
7719 bound
= unshare_expr (fold_convert (var_type
, bound
));
7720 op
= force_gimple_operand (bound
, &stmts
, true, NULL_TREE
);
7722 gsi_insert_seq_on_edge_immediate (
7723 loop_preheader_edge (data
->current_loop
),
7726 gcond
*cond_stmt
= as_a
<gcond
*> (use
->stmt
);
7727 gimple_cond_set_lhs (cond_stmt
, var
);
7728 gimple_cond_set_code (cond_stmt
, compare
);
7729 gimple_cond_set_rhs (cond_stmt
, op
);
7733 /* The induction variable elimination failed; just express the original
7735 comp
= get_computation_at (data
->current_loop
, use
->stmt
, use
, cand
);
7736 gcc_assert (comp
!= NULL_TREE
);
7737 gcc_assert (use
->op_p
!= NULL
);
7738 *use
->op_p
= force_gimple_operand_gsi (&bsi
, comp
, true,
7739 SSA_NAME_VAR (*use
->op_p
),
7740 true, GSI_SAME_STMT
);
7743 /* Rewrite the groups using the selected induction variables. */
7746 rewrite_groups (struct ivopts_data
*data
)
7750 for (i
= 0; i
< data
->vgroups
.length (); i
++)
7752 struct iv_group
*group
= data
->vgroups
[i
];
7753 struct iv_cand
*cand
= group
->selected
;
7757 if (group
->type
== USE_NONLINEAR_EXPR
)
7759 for (j
= 0; j
< group
->vuses
.length (); j
++)
7761 rewrite_use_nonlinear_expr (data
, group
->vuses
[j
], cand
);
7762 update_stmt (group
->vuses
[j
]->stmt
);
7765 else if (address_p (group
->type
))
7767 for (j
= 0; j
< group
->vuses
.length (); j
++)
7769 rewrite_use_address (data
, group
->vuses
[j
], cand
);
7770 update_stmt (group
->vuses
[j
]->stmt
);
7775 gcc_assert (group
->type
== USE_COMPARE
);
7777 for (j
= 0; j
< group
->vuses
.length (); j
++)
7779 rewrite_use_compare (data
, group
->vuses
[j
], cand
);
7780 update_stmt (group
->vuses
[j
]->stmt
);
7786 /* Removes the ivs that are not used after rewriting. */
7789 remove_unused_ivs (struct ivopts_data
*data
, bitmap toremove
)
7794 /* Figure out an order in which to release SSA DEFs so that we don't
7795 release something that we'd have to propagate into a debug stmt
7797 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, j
, bi
)
7799 struct version_info
*info
;
7801 info
= ver_info (data
, j
);
7803 && !integer_zerop (info
->iv
->step
)
7805 && !info
->iv
->nonlin_use
7806 && !info
->preserve_biv
)
7808 bitmap_set_bit (toremove
, SSA_NAME_VERSION (info
->iv
->ssa_name
));
7810 tree def
= info
->iv
->ssa_name
;
7812 if (MAY_HAVE_DEBUG_BIND_STMTS
&& SSA_NAME_DEF_STMT (def
))
7814 imm_use_iterator imm_iter
;
7815 use_operand_p use_p
;
7819 FOR_EACH_IMM_USE_STMT (stmt
, imm_iter
, def
)
7821 if (!gimple_debug_bind_p (stmt
))
7824 /* We just want to determine whether to do nothing
7825 (count == 0), to substitute the computed
7826 expression into a single use of the SSA DEF by
7827 itself (count == 1), or to use a debug temp
7828 because the SSA DEF is used multiple times or as
7829 part of a larger expression (count > 1). */
7831 if (gimple_debug_bind_get_value (stmt
) != def
)
7841 struct iv_use dummy_use
;
7842 struct iv_cand
*best_cand
= NULL
, *cand
;
7843 unsigned i
, best_pref
= 0, cand_pref
;
7844 tree comp
= NULL_TREE
;
7846 memset (&dummy_use
, 0, sizeof (dummy_use
));
7847 dummy_use
.iv
= info
->iv
;
7848 for (i
= 0; i
< data
->vgroups
.length () && i
< 64; i
++)
7850 cand
= data
->vgroups
[i
]->selected
;
7851 if (cand
== best_cand
)
7853 cand_pref
= operand_equal_p (cand
->iv
->step
,
7857 += TYPE_MODE (TREE_TYPE (cand
->iv
->base
))
7858 == TYPE_MODE (TREE_TYPE (info
->iv
->base
))
7861 += TREE_CODE (cand
->iv
->base
) == INTEGER_CST
7863 if (best_cand
== NULL
|| best_pref
< cand_pref
)
7866 = get_debug_computation_at (data
->current_loop
,
7867 SSA_NAME_DEF_STMT (def
),
7872 best_pref
= cand_pref
;
7881 comp
= unshare_expr (comp
);
7884 tree vexpr
= build_debug_expr_decl (TREE_TYPE (comp
));
7885 /* FIXME: Is setting the mode really necessary? */
7886 if (SSA_NAME_VAR (def
))
7887 SET_DECL_MODE (vexpr
, DECL_MODE (SSA_NAME_VAR (def
)));
7889 SET_DECL_MODE (vexpr
, TYPE_MODE (TREE_TYPE (vexpr
)));
7891 = gimple_build_debug_bind (vexpr
, comp
, NULL
);
7892 gimple_stmt_iterator gsi
;
7894 if (gimple_code (SSA_NAME_DEF_STMT (def
)) == GIMPLE_PHI
)
7895 gsi
= gsi_after_labels (gimple_bb
7896 (SSA_NAME_DEF_STMT (def
)));
7898 gsi
= gsi_for_stmt (SSA_NAME_DEF_STMT (def
));
7900 gsi_insert_before (&gsi
, def_temp
, GSI_SAME_STMT
);
7904 FOR_EACH_IMM_USE_STMT (stmt
, imm_iter
, def
)
7906 if (!gimple_debug_bind_p (stmt
))
7909 FOR_EACH_IMM_USE_ON_STMT (use_p
, imm_iter
)
7910 SET_USE (use_p
, comp
);
7919 /* Frees memory occupied by class tree_niter_desc in *VALUE. Callback
7920 for hash_map::traverse. */
7923 free_tree_niter_desc (edge
const &, tree_niter_desc
*const &value
, void *)
7927 value
->~tree_niter_desc ();
7933 /* Frees data allocated by the optimization of a single loop. */
7936 free_loop_data (struct ivopts_data
*data
)
7944 data
->niters
->traverse
<void *, free_tree_niter_desc
> (NULL
);
7945 delete data
->niters
;
7946 data
->niters
= NULL
;
7949 EXECUTE_IF_SET_IN_BITMAP (data
->relevant
, 0, i
, bi
)
7951 struct version_info
*info
;
7953 info
= ver_info (data
, i
);
7955 info
->has_nonlin_use
= false;
7956 info
->preserve_biv
= false;
7959 bitmap_clear (data
->relevant
);
7960 bitmap_clear (data
->important_candidates
);
7962 for (i
= 0; i
< data
->vgroups
.length (); i
++)
7964 struct iv_group
*group
= data
->vgroups
[i
];
7966 for (j
= 0; j
< group
->vuses
.length (); j
++)
7967 free (group
->vuses
[j
]);
7968 group
->vuses
.release ();
7970 BITMAP_FREE (group
->related_cands
);
7971 for (j
= 0; j
< group
->n_map_members
; j
++)
7973 if (group
->cost_map
[j
].inv_vars
)
7974 BITMAP_FREE (group
->cost_map
[j
].inv_vars
);
7975 if (group
->cost_map
[j
].inv_exprs
)
7976 BITMAP_FREE (group
->cost_map
[j
].inv_exprs
);
7979 free (group
->cost_map
);
7982 data
->vgroups
.truncate (0);
7984 for (i
= 0; i
< data
->vcands
.length (); i
++)
7986 struct iv_cand
*cand
= data
->vcands
[i
];
7989 BITMAP_FREE (cand
->inv_vars
);
7990 if (cand
->inv_exprs
)
7991 BITMAP_FREE (cand
->inv_exprs
);
7994 data
->vcands
.truncate (0);
7996 if (data
->version_info_size
< num_ssa_names
)
7998 data
->version_info_size
= 2 * num_ssa_names
;
7999 free (data
->version_info
);
8000 data
->version_info
= XCNEWVEC (struct version_info
, data
->version_info_size
);
8003 data
->max_inv_var_id
= 0;
8004 data
->max_inv_expr_id
= 0;
8006 FOR_EACH_VEC_ELT (decl_rtl_to_reset
, i
, obj
)
8007 SET_DECL_RTL (obj
, NULL_RTX
);
8009 decl_rtl_to_reset
.truncate (0);
8011 data
->inv_expr_tab
->empty ();
8013 data
->iv_common_cand_tab
->empty ();
8014 data
->iv_common_cands
.truncate (0);
8017 /* Finalizes data structures used by the iv optimization pass. LOOPS is the
8021 tree_ssa_iv_optimize_finalize (struct ivopts_data
*data
)
8023 free_loop_data (data
);
8024 free (data
->version_info
);
8025 BITMAP_FREE (data
->relevant
);
8026 BITMAP_FREE (data
->important_candidates
);
8028 decl_rtl_to_reset
.release ();
8029 data
->vgroups
.release ();
8030 data
->vcands
.release ();
8031 delete data
->inv_expr_tab
;
8032 data
->inv_expr_tab
= NULL
;
8033 free_affine_expand_cache (&data
->name_expansion_cache
);
8034 if (data
->base_object_map
)
8035 delete data
->base_object_map
;
8036 delete data
->iv_common_cand_tab
;
8037 data
->iv_common_cand_tab
= NULL
;
8038 data
->iv_common_cands
.release ();
8039 obstack_free (&data
->iv_obstack
, NULL
);
8042 /* Returns true if the loop body BODY includes any function calls. */
8045 loop_body_includes_call (basic_block
*body
, unsigned num_nodes
)
8047 gimple_stmt_iterator gsi
;
8050 for (i
= 0; i
< num_nodes
; i
++)
8051 for (gsi
= gsi_start_bb (body
[i
]); !gsi_end_p (gsi
); gsi_next (&gsi
))
8053 gimple
*stmt
= gsi_stmt (gsi
);
8054 if (is_gimple_call (stmt
)
8055 && !gimple_call_internal_p (stmt
)
8056 && !is_inexpensive_builtin (gimple_call_fndecl (stmt
)))
8062 /* Determine cost scaling factor for basic blocks in loop. */
8063 #define COST_SCALING_FACTOR_BOUND (20)
8066 determine_scaling_factor (struct ivopts_data
*data
, basic_block
*body
)
8068 int lfreq
= data
->current_loop
->header
->count
.to_frequency (cfun
);
8069 if (!data
->speed
|| lfreq
<= 0)
8072 int max_freq
= lfreq
;
8073 for (unsigned i
= 0; i
< data
->current_loop
->num_nodes
; i
++)
8075 body
[i
]->aux
= (void *)(intptr_t) 1;
8076 if (max_freq
< body
[i
]->count
.to_frequency (cfun
))
8077 max_freq
= body
[i
]->count
.to_frequency (cfun
);
8079 if (max_freq
> lfreq
)
8081 int divisor
, factor
;
8082 /* Check if scaling factor itself needs to be scaled by the bound. This
8083 is to avoid overflow when scaling cost according to profile info. */
8084 if (max_freq
/ lfreq
> COST_SCALING_FACTOR_BOUND
)
8087 factor
= COST_SCALING_FACTOR_BOUND
;
8094 for (unsigned i
= 0; i
< data
->current_loop
->num_nodes
; i
++)
8096 int bfreq
= body
[i
]->count
.to_frequency (cfun
);
8100 body
[i
]->aux
= (void*)(intptr_t) (factor
* bfreq
/ divisor
);
8105 /* Find doloop comparison use and set its doloop_p on if found. */
8108 find_doloop_use (struct ivopts_data
*data
)
8110 struct loop
*loop
= data
->current_loop
;
8112 for (unsigned i
= 0; i
< data
->vgroups
.length (); i
++)
8114 struct iv_group
*group
= data
->vgroups
[i
];
8115 if (group
->type
== USE_COMPARE
)
8117 gcc_assert (group
->vuses
.length () == 1);
8118 struct iv_use
*use
= group
->vuses
[0];
8119 gimple
*stmt
= use
->stmt
;
8120 if (gimple_code (stmt
) == GIMPLE_COND
)
8122 basic_block bb
= gimple_bb (stmt
);
8123 edge true_edge
, false_edge
;
8124 extract_true_false_edges_from_block (bb
, &true_edge
, &false_edge
);
8125 /* This comparison is used for loop latch. Require latch is empty
8127 if ((loop
->latch
== true_edge
->dest
8128 || loop
->latch
== false_edge
->dest
)
8129 && empty_block_p (loop
->latch
))
8131 group
->doloop_p
= true;
8132 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
8134 fprintf (dump_file
, "Doloop cmp iv use: ");
8135 print_gimple_stmt (dump_file
, stmt
, TDF_DETAILS
);
8146 /* For the targets which support doloop, to predict whether later RTL doloop
8147 transformation will perform on this loop, further detect the doloop use and
8148 mark the flag doloop_use_p if predicted. */
8151 analyze_and_mark_doloop_use (struct ivopts_data
*data
)
8153 data
->doloop_use_p
= false;
8155 if (!flag_branch_on_count_reg
)
8158 if (data
->current_loop
->unroll
== USHRT_MAX
)
8161 if (!generic_predict_doloop_p (data
))
8164 if (find_doloop_use (data
))
8166 data
->doloop_use_p
= true;
8167 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
8169 struct loop
*loop
= data
->current_loop
;
8171 "Predict loop %d can perform"
8172 " doloop optimization later.\n",
8174 flow_loop_dump (loop
, dump_file
, NULL
, 1);
8179 /* Optimizes the LOOP. Returns true if anything changed. */
8182 tree_ssa_iv_optimize_loop (struct ivopts_data
*data
, class loop
*loop
,
8185 bool changed
= false;
8187 edge exit
= single_dom_exit (loop
);
8190 gcc_assert (!data
->niters
);
8191 data
->current_loop
= loop
;
8192 data
->loop_loc
= find_loop_location (loop
).get_location_t ();
8193 data
->speed
= optimize_loop_for_speed_p (loop
);
8195 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
8197 fprintf (dump_file
, "Processing loop %d", loop
->num
);
8198 if (data
->loop_loc
!= UNKNOWN_LOCATION
)
8199 fprintf (dump_file
, " at %s:%d", LOCATION_FILE (data
->loop_loc
),
8200 LOCATION_LINE (data
->loop_loc
));
8201 fprintf (dump_file
, "\n");
8205 fprintf (dump_file
, " single exit %d -> %d, exit condition ",
8206 exit
->src
->index
, exit
->dest
->index
);
8207 print_gimple_stmt (dump_file
, *gsi_last_bb (exit
->src
),
8209 fprintf (dump_file
, "\n");
8212 fprintf (dump_file
, "\n");
8215 body
= get_loop_body (loop
);
8216 data
->body_includes_call
= loop_body_includes_call (body
, loop
->num_nodes
);
8217 renumber_gimple_stmt_uids_in_blocks (body
, loop
->num_nodes
);
8219 data
->loop_single_exit_p
8220 = exit
!= NULL
&& loop_only_exit_p (loop
, body
, exit
);
8222 /* For each ssa name determines whether it behaves as an induction variable
8224 if (!find_induction_variables (data
, body
))
8227 /* Finds interesting uses (item 1). */
8228 find_interesting_uses (data
, body
);
8229 if (data
->vgroups
.length () > MAX_CONSIDERED_GROUPS
)
8232 /* Determine cost scaling factor for basic blocks in loop. */
8233 determine_scaling_factor (data
, body
);
8235 /* Analyze doloop possibility and mark the doloop use if predicted. */
8236 analyze_and_mark_doloop_use (data
);
8238 /* Finds candidates for the induction variables (item 2). */
8239 find_iv_candidates (data
);
8241 /* Calculates the costs (item 3, part 1). */
8242 determine_iv_costs (data
);
8243 determine_group_iv_costs (data
);
8244 determine_set_costs (data
);
8246 /* Find the optimal set of induction variables (item 3, part 2). */
8247 iv_ca
= find_optimal_iv_set (data
);
8248 /* Cleanup basic block aux field. */
8249 for (unsigned i
= 0; i
< data
->current_loop
->num_nodes
; i
++)
8250 body
[i
]->aux
= NULL
;
8255 /* Create the new induction variables (item 4, part 1). */
8256 create_new_ivs (data
, iv_ca
);
8257 iv_ca_free (&iv_ca
);
8259 /* Rewrite the uses (item 4, part 2). */
8260 rewrite_groups (data
);
8262 /* Remove the ivs that are unused after rewriting. */
8263 remove_unused_ivs (data
, toremove
);
8267 free_loop_data (data
);
8272 /* Main entry point. Optimizes induction variables in loops. */
8275 tree_ssa_iv_optimize (void)
8277 struct ivopts_data data
;
8278 auto_bitmap toremove
;
8280 tree_ssa_iv_optimize_init (&data
);
8281 mark_ssa_maybe_undefs ();
8283 /* Optimize the loops starting with the innermost ones. */
8284 for (auto loop
: loops_list (cfun
, LI_FROM_INNERMOST
))
8286 if (!dbg_cnt (ivopts_loop
))
8289 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
8290 flow_loop_dump (loop
, dump_file
, NULL
, 1);
8292 tree_ssa_iv_optimize_loop (&data
, loop
, toremove
);
8295 /* Remove eliminated IV defs. */
8296 release_defs_bitset (toremove
);
8298 /* We have changed the structure of induction variables; it might happen
8299 that definitions in the scev database refer to some of them that were
8302 /* Likewise niter and control-IV information. */
8303 free_numbers_of_iterations_estimates (cfun
);
8305 tree_ssa_iv_optimize_finalize (&data
);
8308 #include "gt-tree-ssa-loop-ivopts.h"