* tree-ssa-loop-ivopts.c (get_computation_at): Reorder parameters.
[official-gcc.git] / gcc / tree-ssa-loop-ivopts.c
blob6eaeaf14807107f8dcd912851ab2491f3dc05922
1 /* Induction variable optimizations.
2 Copyright (C) 2003-2017 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
9 later version.
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
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* 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
25 following steps:
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
41 groups/uses" above
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
45 of three parts:
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
51 arrays, etc.).
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
62 removed.
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
67 would be complicated. */
69 #include "config.h"
70 #include "system.h"
71 #include "coretypes.h"
72 #include "backend.h"
73 #include "rtl.h"
74 #include "tree.h"
75 #include "gimple.h"
76 #include "cfghooks.h"
77 #include "tree-pass.h"
78 #include "memmodel.h"
79 #include "tm_p.h"
80 #include "ssa.h"
81 #include "expmed.h"
82 #include "insn-config.h"
83 #include "emit-rtl.h"
84 #include "recog.h"
85 #include "cgraph.h"
86 #include "gimple-pretty-print.h"
87 #include "alias.h"
88 #include "fold-const.h"
89 #include "stor-layout.h"
90 #include "tree-eh.h"
91 #include "gimplify.h"
92 #include "gimple-iterator.h"
93 #include "gimplify-me.h"
94 #include "tree-cfg.h"
95 #include "tree-ssa-loop-ivopts.h"
96 #include "tree-ssa-loop-manip.h"
97 #include "tree-ssa-loop-niter.h"
98 #include "tree-ssa-loop.h"
99 #include "explow.h"
100 #include "expr.h"
101 #include "tree-dfa.h"
102 #include "tree-ssa.h"
103 #include "cfgloop.h"
104 #include "tree-scalar-evolution.h"
105 #include "params.h"
106 #include "tree-affine.h"
107 #include "tree-ssa-propagate.h"
108 #include "tree-ssa-address.h"
109 #include "builtins.h"
110 #include "tree-vectorizer.h"
112 /* FIXME: Expressions are expanded to RTL in this pass to determine the
113 cost of different addressing modes. This should be moved to a TBD
114 interface between the GIMPLE and RTL worlds. */
116 /* The infinite cost. */
117 #define INFTY 10000000
119 /* Returns the expected number of loop iterations for LOOP.
120 The average trip count is computed from profile data if it
121 exists. */
123 static inline HOST_WIDE_INT
124 avg_loop_niter (struct loop *loop)
126 HOST_WIDE_INT niter = estimated_stmt_executions_int (loop);
127 if (niter == -1)
129 niter = likely_max_stmt_executions_int (loop);
131 if (niter == -1 || niter > PARAM_VALUE (PARAM_AVG_LOOP_NITER))
132 return PARAM_VALUE (PARAM_AVG_LOOP_NITER);
135 return niter;
138 struct iv_use;
140 /* Representation of the induction variable. */
141 struct iv
143 tree base; /* Initial value of the iv. */
144 tree base_object; /* A memory object to that the induction variable points. */
145 tree step; /* Step of the iv (constant only). */
146 tree ssa_name; /* The ssa name with the value. */
147 struct iv_use *nonlin_use; /* The identifier in the use if it is the case. */
148 bool biv_p; /* Is it a biv? */
149 bool no_overflow; /* True if the iv doesn't overflow. */
150 bool have_address_use;/* For biv, indicate if it's used in any address
151 type use. */
154 /* Per-ssa version information (induction variable descriptions, etc.). */
155 struct version_info
157 tree name; /* The ssa name. */
158 struct iv *iv; /* Induction variable description. */
159 bool has_nonlin_use; /* For a loop-level invariant, whether it is used in
160 an expression that is not an induction variable. */
161 bool preserve_biv; /* For the original biv, whether to preserve it. */
162 unsigned inv_id; /* Id of an invariant. */
165 /* Types of uses. */
166 enum use_type
168 USE_NONLINEAR_EXPR, /* Use in a nonlinear expression. */
169 USE_ADDRESS, /* Use in an address. */
170 USE_COMPARE /* Use is a compare. */
173 /* Cost of a computation. */
174 struct comp_cost
176 comp_cost (): cost (0), complexity (0), scratch (0)
179 comp_cost (int cost, unsigned complexity, int scratch = 0)
180 : cost (cost), complexity (complexity), scratch (scratch)
183 /* Returns true if COST is infinite. */
184 bool infinite_cost_p ();
186 /* Adds costs COST1 and COST2. */
187 friend comp_cost operator+ (comp_cost cost1, comp_cost cost2);
189 /* Adds COST to the comp_cost. */
190 comp_cost operator+= (comp_cost cost);
192 /* Adds constant C to this comp_cost. */
193 comp_cost operator+= (HOST_WIDE_INT c);
195 /* Subtracts constant C to this comp_cost. */
196 comp_cost operator-= (HOST_WIDE_INT c);
198 /* Divide the comp_cost by constant C. */
199 comp_cost operator/= (HOST_WIDE_INT c);
201 /* Multiply the comp_cost by constant C. */
202 comp_cost operator*= (HOST_WIDE_INT c);
204 /* Subtracts costs COST1 and COST2. */
205 friend comp_cost operator- (comp_cost cost1, comp_cost cost2);
207 /* Subtracts COST from this comp_cost. */
208 comp_cost operator-= (comp_cost cost);
210 /* Returns true if COST1 is smaller than COST2. */
211 friend bool operator< (comp_cost cost1, comp_cost cost2);
213 /* Returns true if COST1 and COST2 are equal. */
214 friend bool operator== (comp_cost cost1, comp_cost cost2);
216 /* Returns true if COST1 is smaller or equal than COST2. */
217 friend bool operator<= (comp_cost cost1, comp_cost cost2);
219 int cost; /* The runtime cost. */
220 unsigned complexity; /* The estimate of the complexity of the code for
221 the computation (in no concrete units --
222 complexity field should be larger for more
223 complex expressions and addressing modes). */
224 int scratch; /* Scratch used during cost computation. */
227 static const comp_cost no_cost;
228 static const comp_cost infinite_cost (INFTY, INFTY, INFTY);
230 bool
231 comp_cost::infinite_cost_p ()
233 return cost == INFTY;
236 comp_cost
237 operator+ (comp_cost cost1, comp_cost cost2)
239 if (cost1.infinite_cost_p () || cost2.infinite_cost_p ())
240 return infinite_cost;
242 cost1.cost += cost2.cost;
243 cost1.complexity += cost2.complexity;
245 return cost1;
248 comp_cost
249 operator- (comp_cost cost1, comp_cost cost2)
251 if (cost1.infinite_cost_p ())
252 return infinite_cost;
254 gcc_assert (!cost2.infinite_cost_p ());
256 cost1.cost -= cost2.cost;
257 cost1.complexity -= cost2.complexity;
259 return cost1;
262 comp_cost
263 comp_cost::operator+= (comp_cost cost)
265 *this = *this + cost;
266 return *this;
269 comp_cost
270 comp_cost::operator+= (HOST_WIDE_INT c)
272 if (infinite_cost_p ())
273 return *this;
275 this->cost += c;
277 return *this;
280 comp_cost
281 comp_cost::operator-= (HOST_WIDE_INT c)
283 if (infinite_cost_p ())
284 return *this;
286 this->cost -= c;
288 return *this;
291 comp_cost
292 comp_cost::operator/= (HOST_WIDE_INT c)
294 if (infinite_cost_p ())
295 return *this;
297 this->cost /= c;
299 return *this;
302 comp_cost
303 comp_cost::operator*= (HOST_WIDE_INT c)
305 if (infinite_cost_p ())
306 return *this;
308 this->cost *= c;
310 return *this;
313 comp_cost
314 comp_cost::operator-= (comp_cost cost)
316 *this = *this - cost;
317 return *this;
320 bool
321 operator< (comp_cost cost1, comp_cost cost2)
323 if (cost1.cost == cost2.cost)
324 return cost1.complexity < cost2.complexity;
326 return cost1.cost < cost2.cost;
329 bool
330 operator== (comp_cost cost1, comp_cost cost2)
332 return cost1.cost == cost2.cost
333 && cost1.complexity == cost2.complexity;
336 bool
337 operator<= (comp_cost cost1, comp_cost cost2)
339 return cost1 < cost2 || cost1 == cost2;
342 struct iv_inv_expr_ent;
344 /* The candidate - cost pair. */
345 struct cost_pair
347 struct iv_cand *cand; /* The candidate. */
348 comp_cost cost; /* The cost. */
349 enum tree_code comp; /* For iv elimination, the comparison. */
350 bitmap inv_vars; /* The list of invariants that have to be
351 preserved. */
352 bitmap inv_exprs; /* Loop invariant expressions. */
353 tree value; /* For final value elimination, the expression for
354 the final value of the iv. For iv elimination,
355 the new bound to compare with. */
356 iv_inv_expr_ent *inv_expr; /* Loop invariant expression. */
359 /* Use. */
360 struct iv_use
362 unsigned id; /* The id of the use. */
363 unsigned group_id; /* The group id the use belongs to. */
364 enum use_type type; /* Type of the use. */
365 struct iv *iv; /* The induction variable it is based on. */
366 gimple *stmt; /* Statement in that it occurs. */
367 tree *op_p; /* The place where it occurs. */
369 tree addr_base; /* Base address with const offset stripped. */
370 unsigned HOST_WIDE_INT addr_offset;
371 /* Const offset stripped from base address. */
374 /* Group of uses. */
375 struct iv_group
377 /* The id of the group. */
378 unsigned id;
379 /* Uses of the group are of the same type. */
380 enum use_type type;
381 /* The set of "related" IV candidates, plus the important ones. */
382 bitmap related_cands;
383 /* Number of IV candidates in the cost_map. */
384 unsigned n_map_members;
385 /* The costs wrto the iv candidates. */
386 struct cost_pair *cost_map;
387 /* The selected candidate for the group. */
388 struct iv_cand *selected;
389 /* Uses in the group. */
390 vec<struct iv_use *> vuses;
393 /* The position where the iv is computed. */
394 enum iv_position
396 IP_NORMAL, /* At the end, just before the exit condition. */
397 IP_END, /* At the end of the latch block. */
398 IP_BEFORE_USE, /* Immediately before a specific use. */
399 IP_AFTER_USE, /* Immediately after a specific use. */
400 IP_ORIGINAL /* The original biv. */
403 /* The induction variable candidate. */
404 struct iv_cand
406 unsigned id; /* The number of the candidate. */
407 bool important; /* Whether this is an "important" candidate, i.e. such
408 that it should be considered by all uses. */
409 ENUM_BITFIELD(iv_position) pos : 8; /* Where it is computed. */
410 gimple *incremented_at;/* For original biv, the statement where it is
411 incremented. */
412 tree var_before; /* The variable used for it before increment. */
413 tree var_after; /* The variable used for it after increment. */
414 struct iv *iv; /* The value of the candidate. NULL for
415 "pseudocandidate" used to indicate the possibility
416 to replace the final value of an iv by direct
417 computation of the value. */
418 unsigned cost; /* Cost of the candidate. */
419 unsigned cost_step; /* Cost of the candidate's increment operation. */
420 struct iv_use *ainc_use; /* For IP_{BEFORE,AFTER}_USE candidates, the place
421 where it is incremented. */
422 bitmap inv_vars; /* The list of invariants that are used in step of the
423 biv. */
424 struct iv *orig_iv; /* The original iv if this cand is added from biv with
425 smaller type. */
428 /* Hashtable entry for common candidate derived from iv uses. */
429 struct iv_common_cand
431 tree base;
432 tree step;
433 /* IV uses from which this common candidate is derived. */
434 auto_vec<struct iv_use *> uses;
435 hashval_t hash;
438 /* Hashtable helpers. */
440 struct iv_common_cand_hasher : delete_ptr_hash <iv_common_cand>
442 static inline hashval_t hash (const iv_common_cand *);
443 static inline bool equal (const iv_common_cand *, const iv_common_cand *);
446 /* Hash function for possible common candidates. */
448 inline hashval_t
449 iv_common_cand_hasher::hash (const iv_common_cand *ccand)
451 return ccand->hash;
454 /* Hash table equality function for common candidates. */
456 inline bool
457 iv_common_cand_hasher::equal (const iv_common_cand *ccand1,
458 const iv_common_cand *ccand2)
460 return (ccand1->hash == ccand2->hash
461 && operand_equal_p (ccand1->base, ccand2->base, 0)
462 && operand_equal_p (ccand1->step, ccand2->step, 0)
463 && (TYPE_PRECISION (TREE_TYPE (ccand1->base))
464 == TYPE_PRECISION (TREE_TYPE (ccand2->base))));
467 /* Loop invariant expression hashtable entry. */
469 struct iv_inv_expr_ent
471 /* Tree expression of the entry. */
472 tree expr;
473 /* Unique indentifier. */
474 int id;
475 /* Hash value. */
476 hashval_t hash;
479 /* Sort iv_inv_expr_ent pair A and B by id field. */
481 static int
482 sort_iv_inv_expr_ent (const void *a, const void *b)
484 const iv_inv_expr_ent * const *e1 = (const iv_inv_expr_ent * const *) (a);
485 const iv_inv_expr_ent * const *e2 = (const iv_inv_expr_ent * const *) (b);
487 unsigned id1 = (*e1)->id;
488 unsigned id2 = (*e2)->id;
490 if (id1 < id2)
491 return -1;
492 else if (id1 > id2)
493 return 1;
494 else
495 return 0;
498 /* Hashtable helpers. */
500 struct iv_inv_expr_hasher : free_ptr_hash <iv_inv_expr_ent>
502 static inline hashval_t hash (const iv_inv_expr_ent *);
503 static inline bool equal (const iv_inv_expr_ent *, const iv_inv_expr_ent *);
506 /* Hash function for loop invariant expressions. */
508 inline hashval_t
509 iv_inv_expr_hasher::hash (const iv_inv_expr_ent *expr)
511 return expr->hash;
514 /* Hash table equality function for expressions. */
516 inline bool
517 iv_inv_expr_hasher::equal (const iv_inv_expr_ent *expr1,
518 const iv_inv_expr_ent *expr2)
520 return expr1->hash == expr2->hash
521 && operand_equal_p (expr1->expr, expr2->expr, 0);
524 struct ivopts_data
526 /* The currently optimized loop. */
527 struct loop *current_loop;
528 source_location loop_loc;
530 /* Numbers of iterations for all exits of the current loop. */
531 hash_map<edge, tree_niter_desc *> *niters;
533 /* Number of registers used in it. */
534 unsigned regs_used;
536 /* The size of version_info array allocated. */
537 unsigned version_info_size;
539 /* The array of information for the ssa names. */
540 struct version_info *version_info;
542 /* The hashtable of loop invariant expressions created
543 by ivopt. */
544 hash_table<iv_inv_expr_hasher> *inv_expr_tab;
546 /* The bitmap of indices in version_info whose value was changed. */
547 bitmap relevant;
549 /* The uses of induction variables. */
550 vec<iv_group *> vgroups;
552 /* The candidates. */
553 vec<iv_cand *> vcands;
555 /* A bitmap of important candidates. */
556 bitmap important_candidates;
558 /* Cache used by tree_to_aff_combination_expand. */
559 hash_map<tree, name_expansion *> *name_expansion_cache;
561 /* The hashtable of common candidates derived from iv uses. */
562 hash_table<iv_common_cand_hasher> *iv_common_cand_tab;
564 /* The common candidates. */
565 vec<iv_common_cand *> iv_common_cands;
567 /* The maximum invariant variable id. */
568 unsigned max_inv_var_id;
570 /* The maximum invariant expression id. */
571 unsigned max_inv_expr_id;
573 /* Number of no_overflow BIVs which are not used in memory address. */
574 unsigned bivs_not_used_in_addr;
576 /* Obstack for iv structure. */
577 struct obstack iv_obstack;
579 /* Whether to consider just related and important candidates when replacing a
580 use. */
581 bool consider_all_candidates;
583 /* Are we optimizing for speed? */
584 bool speed;
586 /* Whether the loop body includes any function calls. */
587 bool body_includes_call;
589 /* Whether the loop body can only be exited via single exit. */
590 bool loop_single_exit_p;
593 /* An assignment of iv candidates to uses. */
595 struct iv_ca
597 /* The number of uses covered by the assignment. */
598 unsigned upto;
600 /* Number of uses that cannot be expressed by the candidates in the set. */
601 unsigned bad_groups;
603 /* Candidate assigned to a use, together with the related costs. */
604 struct cost_pair **cand_for_group;
606 /* Number of times each candidate is used. */
607 unsigned *n_cand_uses;
609 /* The candidates used. */
610 bitmap cands;
612 /* The number of candidates in the set. */
613 unsigned n_cands;
615 /* The number of invariants needed, including both invariant variants and
616 invariant expressions. */
617 unsigned n_invs;
619 /* Total cost of expressing uses. */
620 comp_cost cand_use_cost;
622 /* Total cost of candidates. */
623 unsigned cand_cost;
625 /* Number of times each invariant variable is used. */
626 unsigned *n_inv_var_uses;
628 /* Number of times each invariant expression is used. */
629 unsigned *n_inv_expr_uses;
631 /* Total cost of the assignment. */
632 comp_cost cost;
635 /* Difference of two iv candidate assignments. */
637 struct iv_ca_delta
639 /* Changed group. */
640 struct iv_group *group;
642 /* An old assignment (for rollback purposes). */
643 struct cost_pair *old_cp;
645 /* A new assignment. */
646 struct cost_pair *new_cp;
648 /* Next change in the list. */
649 struct iv_ca_delta *next;
652 /* Bound on number of candidates below that all candidates are considered. */
654 #define CONSIDER_ALL_CANDIDATES_BOUND \
655 ((unsigned) PARAM_VALUE (PARAM_IV_CONSIDER_ALL_CANDIDATES_BOUND))
657 /* If there are more iv occurrences, we just give up (it is quite unlikely that
658 optimizing such a loop would help, and it would take ages). */
660 #define MAX_CONSIDERED_GROUPS \
661 ((unsigned) PARAM_VALUE (PARAM_IV_MAX_CONSIDERED_USES))
663 /* If there are at most this number of ivs in the set, try removing unnecessary
664 ivs from the set always. */
666 #define ALWAYS_PRUNE_CAND_SET_BOUND \
667 ((unsigned) PARAM_VALUE (PARAM_IV_ALWAYS_PRUNE_CAND_SET_BOUND))
669 /* The list of trees for that the decl_rtl field must be reset is stored
670 here. */
672 static vec<tree> decl_rtl_to_reset;
674 static comp_cost force_expr_to_var_cost (tree, bool);
676 /* The single loop exit if it dominates the latch, NULL otherwise. */
678 edge
679 single_dom_exit (struct loop *loop)
681 edge exit = single_exit (loop);
683 if (!exit)
684 return NULL;
686 if (!just_once_each_iteration_p (loop, exit->src))
687 return NULL;
689 return exit;
692 /* Dumps information about the induction variable IV to FILE. Don't dump
693 variable's name if DUMP_NAME is FALSE. The information is dumped with
694 preceding spaces indicated by INDENT_LEVEL. */
696 void
697 dump_iv (FILE *file, struct iv *iv, bool dump_name, unsigned indent_level)
699 const char *p;
700 const char spaces[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'};
702 if (indent_level > 4)
703 indent_level = 4;
704 p = spaces + 8 - (indent_level << 1);
706 fprintf (file, "%sIV struct:\n", p);
707 if (iv->ssa_name && dump_name)
709 fprintf (file, "%s SSA_NAME:\t", p);
710 print_generic_expr (file, iv->ssa_name, TDF_SLIM);
711 fprintf (file, "\n");
714 fprintf (file, "%s Type:\t", p);
715 print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
716 fprintf (file, "\n");
718 fprintf (file, "%s Base:\t", p);
719 print_generic_expr (file, iv->base, TDF_SLIM);
720 fprintf (file, "\n");
722 fprintf (file, "%s Step:\t", p);
723 print_generic_expr (file, iv->step, TDF_SLIM);
724 fprintf (file, "\n");
726 if (iv->base_object)
728 fprintf (file, "%s Object:\t", p);
729 print_generic_expr (file, iv->base_object, TDF_SLIM);
730 fprintf (file, "\n");
733 fprintf (file, "%s Biv:\t%c\n", p, iv->biv_p ? 'Y' : 'N');
735 fprintf (file, "%s Overflowness wrto loop niter:\t%s\n",
736 p, iv->no_overflow ? "No-overflow" : "Overflow");
739 /* Dumps information about the USE to FILE. */
741 void
742 dump_use (FILE *file, struct iv_use *use)
744 fprintf (file, " Use %d.%d:\n", use->group_id, use->id);
745 fprintf (file, " At stmt:\t");
746 print_gimple_stmt (file, use->stmt, 0, 0);
747 fprintf (file, " At pos:\t");
748 if (use->op_p)
749 print_generic_expr (file, *use->op_p, TDF_SLIM);
750 fprintf (file, "\n");
751 dump_iv (file, use->iv, false, 2);
754 /* Dumps information about the uses to FILE. */
756 void
757 dump_groups (FILE *file, struct ivopts_data *data)
759 unsigned i, j;
760 struct iv_group *group;
762 for (i = 0; i < data->vgroups.length (); i++)
764 group = data->vgroups[i];
765 fprintf (file, "Group %d:\n", group->id);
766 if (group->type == USE_NONLINEAR_EXPR)
767 fprintf (file, " Type:\tGENERIC\n");
768 else if (group->type == USE_ADDRESS)
769 fprintf (file, " Type:\tADDRESS\n");
770 else
772 gcc_assert (group->type == USE_COMPARE);
773 fprintf (file, " Type:\tCOMPARE\n");
775 for (j = 0; j < group->vuses.length (); j++)
776 dump_use (file, group->vuses[j]);
780 /* Dumps information about induction variable candidate CAND to FILE. */
782 void
783 dump_cand (FILE *file, struct iv_cand *cand)
785 struct iv *iv = cand->iv;
787 fprintf (file, "Candidate %d:\n", cand->id);
788 if (cand->inv_vars)
790 fprintf (file, " Depend on inv.vars: ");
791 dump_bitmap (file, cand->inv_vars);
794 if (cand->var_before)
796 fprintf (file, " Var befor: ");
797 print_generic_expr (file, cand->var_before, TDF_SLIM);
798 fprintf (file, "\n");
800 if (cand->var_after)
802 fprintf (file, " Var after: ");
803 print_generic_expr (file, cand->var_after, TDF_SLIM);
804 fprintf (file, "\n");
807 switch (cand->pos)
809 case IP_NORMAL:
810 fprintf (file, " Incr POS: before exit test\n");
811 break;
813 case IP_BEFORE_USE:
814 fprintf (file, " Incr POS: before use %d\n", cand->ainc_use->id);
815 break;
817 case IP_AFTER_USE:
818 fprintf (file, " Incr POS: after use %d\n", cand->ainc_use->id);
819 break;
821 case IP_END:
822 fprintf (file, " Incr POS: at end\n");
823 break;
825 case IP_ORIGINAL:
826 fprintf (file, " Incr POS: orig biv\n");
827 break;
830 dump_iv (file, iv, false, 1);
833 /* Returns the info for ssa version VER. */
835 static inline struct version_info *
836 ver_info (struct ivopts_data *data, unsigned ver)
838 return data->version_info + ver;
841 /* Returns the info for ssa name NAME. */
843 static inline struct version_info *
844 name_info (struct ivopts_data *data, tree name)
846 return ver_info (data, SSA_NAME_VERSION (name));
849 /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
850 emitted in LOOP. */
852 static bool
853 stmt_after_ip_normal_pos (struct loop *loop, gimple *stmt)
855 basic_block bb = ip_normal_pos (loop), sbb = gimple_bb (stmt);
857 gcc_assert (bb);
859 if (sbb == loop->latch)
860 return true;
862 if (sbb != bb)
863 return false;
865 return stmt == last_stmt (bb);
868 /* Returns true if STMT if after the place where the original induction
869 variable CAND is incremented. If TRUE_IF_EQUAL is set, we return true
870 if the positions are identical. */
872 static bool
873 stmt_after_inc_pos (struct iv_cand *cand, gimple *stmt, bool true_if_equal)
875 basic_block cand_bb = gimple_bb (cand->incremented_at);
876 basic_block stmt_bb = gimple_bb (stmt);
878 if (!dominated_by_p (CDI_DOMINATORS, stmt_bb, cand_bb))
879 return false;
881 if (stmt_bb != cand_bb)
882 return true;
884 if (true_if_equal
885 && gimple_uid (stmt) == gimple_uid (cand->incremented_at))
886 return true;
887 return gimple_uid (stmt) > gimple_uid (cand->incremented_at);
890 /* Returns true if STMT if after the place where the induction variable
891 CAND is incremented in LOOP. */
893 static bool
894 stmt_after_increment (struct loop *loop, struct iv_cand *cand, gimple *stmt)
896 switch (cand->pos)
898 case IP_END:
899 return false;
901 case IP_NORMAL:
902 return stmt_after_ip_normal_pos (loop, stmt);
904 case IP_ORIGINAL:
905 case IP_AFTER_USE:
906 return stmt_after_inc_pos (cand, stmt, false);
908 case IP_BEFORE_USE:
909 return stmt_after_inc_pos (cand, stmt, true);
911 default:
912 gcc_unreachable ();
916 /* Returns true if EXP is a ssa name that occurs in an abnormal phi node. */
918 static bool
919 abnormal_ssa_name_p (tree exp)
921 if (!exp)
922 return false;
924 if (TREE_CODE (exp) != SSA_NAME)
925 return false;
927 return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp) != 0;
930 /* Returns false if BASE or INDEX contains a ssa name that occurs in an
931 abnormal phi node. Callback for for_each_index. */
933 static bool
934 idx_contains_abnormal_ssa_name_p (tree base, tree *index,
935 void *data ATTRIBUTE_UNUSED)
937 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
939 if (abnormal_ssa_name_p (TREE_OPERAND (base, 2)))
940 return false;
941 if (abnormal_ssa_name_p (TREE_OPERAND (base, 3)))
942 return false;
945 return !abnormal_ssa_name_p (*index);
948 /* Returns true if EXPR contains a ssa name that occurs in an
949 abnormal phi node. */
951 bool
952 contains_abnormal_ssa_name_p (tree expr)
954 enum tree_code code;
955 enum tree_code_class codeclass;
957 if (!expr)
958 return false;
960 code = TREE_CODE (expr);
961 codeclass = TREE_CODE_CLASS (code);
963 if (code == SSA_NAME)
964 return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (expr) != 0;
966 if (code == INTEGER_CST
967 || is_gimple_min_invariant (expr))
968 return false;
970 if (code == ADDR_EXPR)
971 return !for_each_index (&TREE_OPERAND (expr, 0),
972 idx_contains_abnormal_ssa_name_p,
973 NULL);
975 if (code == COND_EXPR)
976 return contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0))
977 || contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1))
978 || contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 2));
980 switch (codeclass)
982 case tcc_binary:
983 case tcc_comparison:
984 if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1)))
985 return true;
987 /* Fallthru. */
988 case tcc_unary:
989 if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0)))
990 return true;
992 break;
994 default:
995 gcc_unreachable ();
998 return false;
1001 /* Returns the structure describing number of iterations determined from
1002 EXIT of DATA->current_loop, or NULL if something goes wrong. */
1004 static struct tree_niter_desc *
1005 niter_for_exit (struct ivopts_data *data, edge exit)
1007 struct tree_niter_desc *desc;
1008 tree_niter_desc **slot;
1010 if (!data->niters)
1012 data->niters = new hash_map<edge, tree_niter_desc *>;
1013 slot = NULL;
1015 else
1016 slot = data->niters->get (exit);
1018 if (!slot)
1020 /* Try to determine number of iterations. We cannot safely work with ssa
1021 names that appear in phi nodes on abnormal edges, so that we do not
1022 create overlapping life ranges for them (PR 27283). */
1023 desc = XNEW (struct tree_niter_desc);
1024 if (!number_of_iterations_exit (data->current_loop,
1025 exit, desc, true)
1026 || contains_abnormal_ssa_name_p (desc->niter))
1028 XDELETE (desc);
1029 desc = NULL;
1031 data->niters->put (exit, desc);
1033 else
1034 desc = *slot;
1036 return desc;
1039 /* Returns the structure describing number of iterations determined from
1040 single dominating exit of DATA->current_loop, or NULL if something
1041 goes wrong. */
1043 static struct tree_niter_desc *
1044 niter_for_single_dom_exit (struct ivopts_data *data)
1046 edge exit = single_dom_exit (data->current_loop);
1048 if (!exit)
1049 return NULL;
1051 return niter_for_exit (data, exit);
1054 /* Initializes data structures used by the iv optimization pass, stored
1055 in DATA. */
1057 static void
1058 tree_ssa_iv_optimize_init (struct ivopts_data *data)
1060 data->version_info_size = 2 * num_ssa_names;
1061 data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
1062 data->relevant = BITMAP_ALLOC (NULL);
1063 data->important_candidates = BITMAP_ALLOC (NULL);
1064 data->max_inv_var_id = 0;
1065 data->max_inv_expr_id = 0;
1066 data->niters = NULL;
1067 data->vgroups.create (20);
1068 data->vcands.create (20);
1069 data->inv_expr_tab = new hash_table<iv_inv_expr_hasher> (10);
1070 data->name_expansion_cache = NULL;
1071 data->iv_common_cand_tab = new hash_table<iv_common_cand_hasher> (10);
1072 data->iv_common_cands.create (20);
1073 decl_rtl_to_reset.create (20);
1074 gcc_obstack_init (&data->iv_obstack);
1077 /* Returns a memory object to that EXPR points. In case we are able to
1078 determine that it does not point to any such object, NULL is returned. */
1080 static tree
1081 determine_base_object (tree expr)
1083 enum tree_code code = TREE_CODE (expr);
1084 tree base, obj;
1086 /* If this is a pointer casted to any type, we need to determine
1087 the base object for the pointer; so handle conversions before
1088 throwing away non-pointer expressions. */
1089 if (CONVERT_EXPR_P (expr))
1090 return determine_base_object (TREE_OPERAND (expr, 0));
1092 if (!POINTER_TYPE_P (TREE_TYPE (expr)))
1093 return NULL_TREE;
1095 switch (code)
1097 case INTEGER_CST:
1098 return NULL_TREE;
1100 case ADDR_EXPR:
1101 obj = TREE_OPERAND (expr, 0);
1102 base = get_base_address (obj);
1104 if (!base)
1105 return expr;
1107 if (TREE_CODE (base) == MEM_REF)
1108 return determine_base_object (TREE_OPERAND (base, 0));
1110 return fold_convert (ptr_type_node,
1111 build_fold_addr_expr (base));
1113 case POINTER_PLUS_EXPR:
1114 return determine_base_object (TREE_OPERAND (expr, 0));
1116 case PLUS_EXPR:
1117 case MINUS_EXPR:
1118 /* Pointer addition is done solely using POINTER_PLUS_EXPR. */
1119 gcc_unreachable ();
1121 default:
1122 return fold_convert (ptr_type_node, expr);
1126 /* Return true if address expression with non-DECL_P operand appears
1127 in EXPR. */
1129 static bool
1130 contain_complex_addr_expr (tree expr)
1132 bool res = false;
1134 STRIP_NOPS (expr);
1135 switch (TREE_CODE (expr))
1137 case POINTER_PLUS_EXPR:
1138 case PLUS_EXPR:
1139 case MINUS_EXPR:
1140 res |= contain_complex_addr_expr (TREE_OPERAND (expr, 0));
1141 res |= contain_complex_addr_expr (TREE_OPERAND (expr, 1));
1142 break;
1144 case ADDR_EXPR:
1145 return (!DECL_P (TREE_OPERAND (expr, 0)));
1147 default:
1148 return false;
1151 return res;
1154 /* Allocates an induction variable with given initial value BASE and step STEP
1155 for loop LOOP. NO_OVERFLOW implies the iv doesn't overflow. */
1157 static struct iv *
1158 alloc_iv (struct ivopts_data *data, tree base, tree step,
1159 bool no_overflow = false)
1161 tree expr = base;
1162 struct iv *iv = (struct iv*) obstack_alloc (&data->iv_obstack,
1163 sizeof (struct iv));
1164 gcc_assert (step != NULL_TREE);
1166 /* Lower address expression in base except ones with DECL_P as operand.
1167 By doing this:
1168 1) More accurate cost can be computed for address expressions;
1169 2) Duplicate candidates won't be created for bases in different
1170 forms, like &a[0] and &a. */
1171 STRIP_NOPS (expr);
1172 if ((TREE_CODE (expr) == ADDR_EXPR && !DECL_P (TREE_OPERAND (expr, 0)))
1173 || contain_complex_addr_expr (expr))
1175 aff_tree comb;
1176 tree_to_aff_combination (expr, TREE_TYPE (expr), &comb);
1177 base = fold_convert (TREE_TYPE (base), aff_combination_to_tree (&comb));
1180 iv->base = base;
1181 iv->base_object = determine_base_object (base);
1182 iv->step = step;
1183 iv->biv_p = false;
1184 iv->nonlin_use = NULL;
1185 iv->ssa_name = NULL_TREE;
1186 if (!no_overflow
1187 && !iv_can_overflow_p (data->current_loop, TREE_TYPE (base),
1188 base, step))
1189 no_overflow = true;
1190 iv->no_overflow = no_overflow;
1191 iv->have_address_use = false;
1193 return iv;
1196 /* Sets STEP and BASE for induction variable IV. NO_OVERFLOW implies the IV
1197 doesn't overflow. */
1199 static void
1200 set_iv (struct ivopts_data *data, tree iv, tree base, tree step,
1201 bool no_overflow)
1203 struct version_info *info = name_info (data, iv);
1205 gcc_assert (!info->iv);
1207 bitmap_set_bit (data->relevant, SSA_NAME_VERSION (iv));
1208 info->iv = alloc_iv (data, base, step, no_overflow);
1209 info->iv->ssa_name = iv;
1212 /* Finds induction variable declaration for VAR. */
1214 static struct iv *
1215 get_iv (struct ivopts_data *data, tree var)
1217 basic_block bb;
1218 tree type = TREE_TYPE (var);
1220 if (!POINTER_TYPE_P (type)
1221 && !INTEGRAL_TYPE_P (type))
1222 return NULL;
1224 if (!name_info (data, var)->iv)
1226 bb = gimple_bb (SSA_NAME_DEF_STMT (var));
1228 if (!bb
1229 || !flow_bb_inside_loop_p (data->current_loop, bb))
1230 set_iv (data, var, var, build_int_cst (type, 0), true);
1233 return name_info (data, var)->iv;
1236 /* Return the first non-invariant ssa var found in EXPR. */
1238 static tree
1239 extract_single_var_from_expr (tree expr)
1241 int i, n;
1242 tree tmp;
1243 enum tree_code code;
1245 if (!expr || is_gimple_min_invariant (expr))
1246 return NULL;
1248 code = TREE_CODE (expr);
1249 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1251 n = TREE_OPERAND_LENGTH (expr);
1252 for (i = 0; i < n; i++)
1254 tmp = extract_single_var_from_expr (TREE_OPERAND (expr, i));
1256 if (tmp)
1257 return tmp;
1260 return (TREE_CODE (expr) == SSA_NAME) ? expr : NULL;
1263 /* Finds basic ivs. */
1265 static bool
1266 find_bivs (struct ivopts_data *data)
1268 gphi *phi;
1269 affine_iv iv;
1270 tree step, type, base, stop;
1271 bool found = false;
1272 struct loop *loop = data->current_loop;
1273 gphi_iterator psi;
1275 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1277 phi = psi.phi ();
1279 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
1280 continue;
1282 if (virtual_operand_p (PHI_RESULT (phi)))
1283 continue;
1285 if (!simple_iv (loop, loop, PHI_RESULT (phi), &iv, true))
1286 continue;
1288 if (integer_zerop (iv.step))
1289 continue;
1291 step = iv.step;
1292 base = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1293 /* Stop expanding iv base at the first ssa var referred by iv step.
1294 Ideally we should stop at any ssa var, because that's expensive
1295 and unusual to happen, we just do it on the first one.
1297 See PR64705 for the rationale. */
1298 stop = extract_single_var_from_expr (step);
1299 base = expand_simple_operations (base, stop);
1300 if (contains_abnormal_ssa_name_p (base)
1301 || contains_abnormal_ssa_name_p (step))
1302 continue;
1304 type = TREE_TYPE (PHI_RESULT (phi));
1305 base = fold_convert (type, base);
1306 if (step)
1308 if (POINTER_TYPE_P (type))
1309 step = convert_to_ptrofftype (step);
1310 else
1311 step = fold_convert (type, step);
1314 set_iv (data, PHI_RESULT (phi), base, step, iv.no_overflow);
1315 found = true;
1318 return found;
1321 /* Marks basic ivs. */
1323 static void
1324 mark_bivs (struct ivopts_data *data)
1326 gphi *phi;
1327 gimple *def;
1328 tree var;
1329 struct iv *iv, *incr_iv;
1330 struct loop *loop = data->current_loop;
1331 basic_block incr_bb;
1332 gphi_iterator psi;
1334 data->bivs_not_used_in_addr = 0;
1335 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1337 phi = psi.phi ();
1339 iv = get_iv (data, PHI_RESULT (phi));
1340 if (!iv)
1341 continue;
1343 var = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1344 def = SSA_NAME_DEF_STMT (var);
1345 /* Don't mark iv peeled from other one as biv. */
1346 if (def
1347 && gimple_code (def) == GIMPLE_PHI
1348 && gimple_bb (def) == loop->header)
1349 continue;
1351 incr_iv = get_iv (data, var);
1352 if (!incr_iv)
1353 continue;
1355 /* If the increment is in the subloop, ignore it. */
1356 incr_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
1357 if (incr_bb->loop_father != data->current_loop
1358 || (incr_bb->flags & BB_IRREDUCIBLE_LOOP))
1359 continue;
1361 iv->biv_p = true;
1362 incr_iv->biv_p = true;
1363 if (iv->no_overflow)
1364 data->bivs_not_used_in_addr++;
1365 if (incr_iv->no_overflow)
1366 data->bivs_not_used_in_addr++;
1370 /* Checks whether STMT defines a linear induction variable and stores its
1371 parameters to IV. */
1373 static bool
1374 find_givs_in_stmt_scev (struct ivopts_data *data, gimple *stmt, affine_iv *iv)
1376 tree lhs, stop;
1377 struct loop *loop = data->current_loop;
1379 iv->base = NULL_TREE;
1380 iv->step = NULL_TREE;
1382 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1383 return false;
1385 lhs = gimple_assign_lhs (stmt);
1386 if (TREE_CODE (lhs) != SSA_NAME)
1387 return false;
1389 if (!simple_iv (loop, loop_containing_stmt (stmt), lhs, iv, true))
1390 return false;
1392 /* Stop expanding iv base at the first ssa var referred by iv step.
1393 Ideally we should stop at any ssa var, because that's expensive
1394 and unusual to happen, we just do it on the first one.
1396 See PR64705 for the rationale. */
1397 stop = extract_single_var_from_expr (iv->step);
1398 iv->base = expand_simple_operations (iv->base, stop);
1399 if (contains_abnormal_ssa_name_p (iv->base)
1400 || contains_abnormal_ssa_name_p (iv->step))
1401 return false;
1403 /* If STMT could throw, then do not consider STMT as defining a GIV.
1404 While this will suppress optimizations, we can not safely delete this
1405 GIV and associated statements, even if it appears it is not used. */
1406 if (stmt_could_throw_p (stmt))
1407 return false;
1409 return true;
1412 /* Finds general ivs in statement STMT. */
1414 static void
1415 find_givs_in_stmt (struct ivopts_data *data, gimple *stmt)
1417 affine_iv iv;
1419 if (!find_givs_in_stmt_scev (data, stmt, &iv))
1420 return;
1422 set_iv (data, gimple_assign_lhs (stmt), iv.base, iv.step, iv.no_overflow);
1425 /* Finds general ivs in basic block BB. */
1427 static void
1428 find_givs_in_bb (struct ivopts_data *data, basic_block bb)
1430 gimple_stmt_iterator bsi;
1432 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1433 find_givs_in_stmt (data, gsi_stmt (bsi));
1436 /* Finds general ivs. */
1438 static void
1439 find_givs (struct ivopts_data *data)
1441 struct loop *loop = data->current_loop;
1442 basic_block *body = get_loop_body_in_dom_order (loop);
1443 unsigned i;
1445 for (i = 0; i < loop->num_nodes; i++)
1446 find_givs_in_bb (data, body[i]);
1447 free (body);
1450 /* For each ssa name defined in LOOP determines whether it is an induction
1451 variable and if so, its initial value and step. */
1453 static bool
1454 find_induction_variables (struct ivopts_data *data)
1456 unsigned i;
1457 bitmap_iterator bi;
1459 if (!find_bivs (data))
1460 return false;
1462 find_givs (data);
1463 mark_bivs (data);
1465 if (dump_file && (dump_flags & TDF_DETAILS))
1467 struct tree_niter_desc *niter = niter_for_single_dom_exit (data);
1469 if (niter)
1471 fprintf (dump_file, " number of iterations ");
1472 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1473 if (!integer_zerop (niter->may_be_zero))
1475 fprintf (dump_file, "; zero if ");
1476 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1478 fprintf (dump_file, "\n");
1481 fprintf (dump_file, "\n<Induction Vars>:\n");
1482 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1484 struct version_info *info = ver_info (data, i);
1485 if (info->iv && info->iv->step && !integer_zerop (info->iv->step))
1486 dump_iv (dump_file, ver_info (data, i)->iv, true, 0);
1490 return true;
1493 /* Records a use of TYPE at *USE_P in STMT whose value is IV in GROUP.
1494 For address type use, ADDR_BASE is the stripped IV base, ADDR_OFFSET
1495 is the const offset stripped from IV base; for other types use, both
1496 are zero by default. */
1498 static struct iv_use *
1499 record_use (struct iv_group *group, tree *use_p, struct iv *iv,
1500 gimple *stmt, enum use_type type, tree addr_base,
1501 unsigned HOST_WIDE_INT addr_offset)
1503 struct iv_use *use = XCNEW (struct iv_use);
1505 use->id = group->vuses.length ();
1506 use->group_id = group->id;
1507 use->type = type;
1508 use->iv = iv;
1509 use->stmt = stmt;
1510 use->op_p = use_p;
1511 use->addr_base = addr_base;
1512 use->addr_offset = addr_offset;
1514 group->vuses.safe_push (use);
1515 return use;
1518 /* Checks whether OP is a loop-level invariant and if so, records it.
1519 NONLINEAR_USE is true if the invariant is used in a way we do not
1520 handle specially. */
1522 static void
1523 record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
1525 basic_block bb;
1526 struct version_info *info;
1528 if (TREE_CODE (op) != SSA_NAME
1529 || virtual_operand_p (op))
1530 return;
1532 bb = gimple_bb (SSA_NAME_DEF_STMT (op));
1533 if (bb
1534 && flow_bb_inside_loop_p (data->current_loop, bb))
1535 return;
1537 info = name_info (data, op);
1538 info->name = op;
1539 info->has_nonlin_use |= nonlinear_use;
1540 if (!info->inv_id)
1541 info->inv_id = ++data->max_inv_var_id;
1542 bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
1545 static tree
1546 strip_offset (tree expr, unsigned HOST_WIDE_INT *offset);
1548 /* Record a group of TYPE. */
1550 static struct iv_group *
1551 record_group (struct ivopts_data *data, enum use_type type)
1553 struct iv_group *group = XCNEW (struct iv_group);
1555 group->id = data->vgroups.length ();
1556 group->type = type;
1557 group->related_cands = BITMAP_ALLOC (NULL);
1558 group->vuses.create (1);
1560 data->vgroups.safe_push (group);
1561 return group;
1564 /* Record a use of TYPE at *USE_P in STMT whose value is IV in a group.
1565 New group will be created if there is no existing group for the use. */
1567 static struct iv_use *
1568 record_group_use (struct ivopts_data *data, tree *use_p,
1569 struct iv *iv, gimple *stmt, enum use_type type)
1571 tree addr_base = NULL;
1572 struct iv_group *group = NULL;
1573 unsigned HOST_WIDE_INT addr_offset = 0;
1575 /* Record non address type use in a new group. */
1576 if (type == USE_ADDRESS && iv->base_object)
1578 unsigned int i;
1580 addr_base = strip_offset (iv->base, &addr_offset);
1581 for (i = 0; i < data->vgroups.length (); i++)
1583 struct iv_use *use;
1585 group = data->vgroups[i];
1586 use = group->vuses[0];
1587 if (use->type != USE_ADDRESS || !use->iv->base_object)
1588 continue;
1590 /* Check if it has the same stripped base and step. */
1591 if (operand_equal_p (iv->base_object, use->iv->base_object, 0)
1592 && operand_equal_p (iv->step, use->iv->step, 0)
1593 && operand_equal_p (addr_base, use->addr_base, 0))
1594 break;
1596 if (i == data->vgroups.length ())
1597 group = NULL;
1600 if (!group)
1601 group = record_group (data, type);
1603 return record_use (group, use_p, iv, stmt, type, addr_base, addr_offset);
1606 /* Checks whether the use OP is interesting and if so, records it. */
1608 static struct iv_use *
1609 find_interesting_uses_op (struct ivopts_data *data, tree op)
1611 struct iv *iv;
1612 gimple *stmt;
1613 struct iv_use *use;
1615 if (TREE_CODE (op) != SSA_NAME)
1616 return NULL;
1618 iv = get_iv (data, op);
1619 if (!iv)
1620 return NULL;
1622 if (iv->nonlin_use)
1624 gcc_assert (iv->nonlin_use->type == USE_NONLINEAR_EXPR);
1625 return iv->nonlin_use;
1628 if (integer_zerop (iv->step))
1630 record_invariant (data, op, true);
1631 return NULL;
1634 stmt = SSA_NAME_DEF_STMT (op);
1635 gcc_assert (gimple_code (stmt) == GIMPLE_PHI || is_gimple_assign (stmt));
1637 use = record_group_use (data, NULL, iv, stmt, USE_NONLINEAR_EXPR);
1638 iv->nonlin_use = use;
1639 return use;
1642 /* Given a condition in statement STMT, checks whether it is a compare
1643 of an induction variable and an invariant. If this is the case,
1644 CONTROL_VAR is set to location of the iv, BOUND to the location of
1645 the invariant, IV_VAR and IV_BOUND are set to the corresponding
1646 induction variable descriptions, and true is returned. If this is not
1647 the case, CONTROL_VAR and BOUND are set to the arguments of the
1648 condition and false is returned. */
1650 static bool
1651 extract_cond_operands (struct ivopts_data *data, gimple *stmt,
1652 tree **control_var, tree **bound,
1653 struct iv **iv_var, struct iv **iv_bound)
1655 /* The objects returned when COND has constant operands. */
1656 static struct iv const_iv;
1657 static tree zero;
1658 tree *op0 = &zero, *op1 = &zero;
1659 struct iv *iv0 = &const_iv, *iv1 = &const_iv;
1660 bool ret = false;
1662 if (gimple_code (stmt) == GIMPLE_COND)
1664 gcond *cond_stmt = as_a <gcond *> (stmt);
1665 op0 = gimple_cond_lhs_ptr (cond_stmt);
1666 op1 = gimple_cond_rhs_ptr (cond_stmt);
1668 else
1670 op0 = gimple_assign_rhs1_ptr (stmt);
1671 op1 = gimple_assign_rhs2_ptr (stmt);
1674 zero = integer_zero_node;
1675 const_iv.step = integer_zero_node;
1677 if (TREE_CODE (*op0) == SSA_NAME)
1678 iv0 = get_iv (data, *op0);
1679 if (TREE_CODE (*op1) == SSA_NAME)
1680 iv1 = get_iv (data, *op1);
1682 /* Exactly one of the compared values must be an iv, and the other one must
1683 be an invariant. */
1684 if (!iv0 || !iv1)
1685 goto end;
1687 if (integer_zerop (iv0->step))
1689 /* Control variable may be on the other side. */
1690 std::swap (op0, op1);
1691 std::swap (iv0, iv1);
1693 ret = !integer_zerop (iv0->step) && integer_zerop (iv1->step);
1695 end:
1696 if (control_var)
1697 *control_var = op0;
1698 if (iv_var)
1699 *iv_var = iv0;
1700 if (bound)
1701 *bound = op1;
1702 if (iv_bound)
1703 *iv_bound = iv1;
1705 return ret;
1708 /* Checks whether the condition in STMT is interesting and if so,
1709 records it. */
1711 static void
1712 find_interesting_uses_cond (struct ivopts_data *data, gimple *stmt)
1714 tree *var_p, *bound_p;
1715 struct iv *var_iv;
1717 if (!extract_cond_operands (data, stmt, &var_p, &bound_p, &var_iv, NULL))
1719 find_interesting_uses_op (data, *var_p);
1720 find_interesting_uses_op (data, *bound_p);
1721 return;
1724 record_group_use (data, NULL, var_iv, stmt, USE_COMPARE);
1727 /* Returns the outermost loop EXPR is obviously invariant in
1728 relative to the loop LOOP, i.e. if all its operands are defined
1729 outside of the returned loop. Returns NULL if EXPR is not
1730 even obviously invariant in LOOP. */
1732 struct loop *
1733 outermost_invariant_loop_for_expr (struct loop *loop, tree expr)
1735 basic_block def_bb;
1736 unsigned i, len;
1738 if (is_gimple_min_invariant (expr))
1739 return current_loops->tree_root;
1741 if (TREE_CODE (expr) == SSA_NAME)
1743 def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
1744 if (def_bb)
1746 if (flow_bb_inside_loop_p (loop, def_bb))
1747 return NULL;
1748 return superloop_at_depth (loop,
1749 loop_depth (def_bb->loop_father) + 1);
1752 return current_loops->tree_root;
1755 if (!EXPR_P (expr))
1756 return NULL;
1758 unsigned maxdepth = 0;
1759 len = TREE_OPERAND_LENGTH (expr);
1760 for (i = 0; i < len; i++)
1762 struct loop *ivloop;
1763 if (!TREE_OPERAND (expr, i))
1764 continue;
1766 ivloop = outermost_invariant_loop_for_expr (loop, TREE_OPERAND (expr, i));
1767 if (!ivloop)
1768 return NULL;
1769 maxdepth = MAX (maxdepth, loop_depth (ivloop));
1772 return superloop_at_depth (loop, maxdepth);
1775 /* Returns true if expression EXPR is obviously invariant in LOOP,
1776 i.e. if all its operands are defined outside of the LOOP. LOOP
1777 should not be the function body. */
1779 bool
1780 expr_invariant_in_loop_p (struct loop *loop, tree expr)
1782 basic_block def_bb;
1783 unsigned i, len;
1785 gcc_assert (loop_depth (loop) > 0);
1787 if (is_gimple_min_invariant (expr))
1788 return true;
1790 if (TREE_CODE (expr) == SSA_NAME)
1792 def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
1793 if (def_bb
1794 && flow_bb_inside_loop_p (loop, def_bb))
1795 return false;
1797 return true;
1800 if (!EXPR_P (expr))
1801 return false;
1803 len = TREE_OPERAND_LENGTH (expr);
1804 for (i = 0; i < len; i++)
1805 if (TREE_OPERAND (expr, i)
1806 && !expr_invariant_in_loop_p (loop, TREE_OPERAND (expr, i)))
1807 return false;
1809 return true;
1812 /* Given expression EXPR which computes inductive values with respect
1813 to loop recorded in DATA, this function returns biv from which EXPR
1814 is derived by tracing definition chains of ssa variables in EXPR. */
1816 static struct iv*
1817 find_deriving_biv_for_expr (struct ivopts_data *data, tree expr)
1819 struct iv *iv;
1820 unsigned i, n;
1821 tree e2, e1;
1822 enum tree_code code;
1823 gimple *stmt;
1825 if (expr == NULL_TREE)
1826 return NULL;
1828 if (is_gimple_min_invariant (expr))
1829 return NULL;
1831 code = TREE_CODE (expr);
1832 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1834 n = TREE_OPERAND_LENGTH (expr);
1835 for (i = 0; i < n; i++)
1837 iv = find_deriving_biv_for_expr (data, TREE_OPERAND (expr, i));
1838 if (iv)
1839 return iv;
1843 /* Stop if it's not ssa name. */
1844 if (code != SSA_NAME)
1845 return NULL;
1847 iv = get_iv (data, expr);
1848 if (!iv || integer_zerop (iv->step))
1849 return NULL;
1850 else if (iv->biv_p)
1851 return iv;
1853 stmt = SSA_NAME_DEF_STMT (expr);
1854 if (gphi *phi = dyn_cast <gphi *> (stmt))
1856 ssa_op_iter iter;
1857 use_operand_p use_p;
1858 basic_block phi_bb = gimple_bb (phi);
1860 /* Skip loop header PHI that doesn't define biv. */
1861 if (phi_bb->loop_father == data->current_loop)
1862 return NULL;
1864 if (virtual_operand_p (gimple_phi_result (phi)))
1865 return NULL;
1867 FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
1869 tree use = USE_FROM_PTR (use_p);
1870 iv = find_deriving_biv_for_expr (data, use);
1871 if (iv)
1872 return iv;
1874 return NULL;
1876 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1877 return NULL;
1879 e1 = gimple_assign_rhs1 (stmt);
1880 code = gimple_assign_rhs_code (stmt);
1881 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1882 return find_deriving_biv_for_expr (data, e1);
1884 switch (code)
1886 case MULT_EXPR:
1887 case PLUS_EXPR:
1888 case MINUS_EXPR:
1889 case POINTER_PLUS_EXPR:
1890 /* Increments, decrements and multiplications by a constant
1891 are simple. */
1892 e2 = gimple_assign_rhs2 (stmt);
1893 iv = find_deriving_biv_for_expr (data, e2);
1894 if (iv)
1895 return iv;
1896 gcc_fallthrough ();
1898 CASE_CONVERT:
1899 /* Casts are simple. */
1900 return find_deriving_biv_for_expr (data, e1);
1902 default:
1903 break;
1906 return NULL;
1909 /* Record BIV, its predecessor and successor that they are used in
1910 address type uses. */
1912 static void
1913 record_biv_for_address_use (struct ivopts_data *data, struct iv *biv)
1915 unsigned i;
1916 tree type, base_1, base_2;
1917 bitmap_iterator bi;
1919 if (!biv || !biv->biv_p || integer_zerop (biv->step)
1920 || biv->have_address_use || !biv->no_overflow)
1921 return;
1923 type = TREE_TYPE (biv->base);
1924 if (!INTEGRAL_TYPE_P (type))
1925 return;
1927 biv->have_address_use = true;
1928 data->bivs_not_used_in_addr--;
1929 base_1 = fold_build2 (PLUS_EXPR, type, biv->base, biv->step);
1930 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1932 struct iv *iv = ver_info (data, i)->iv;
1934 if (!iv || !iv->biv_p || integer_zerop (iv->step)
1935 || iv->have_address_use || !iv->no_overflow)
1936 continue;
1938 if (type != TREE_TYPE (iv->base)
1939 || !INTEGRAL_TYPE_P (TREE_TYPE (iv->base)))
1940 continue;
1942 if (!operand_equal_p (biv->step, iv->step, 0))
1943 continue;
1945 base_2 = fold_build2 (PLUS_EXPR, type, iv->base, iv->step);
1946 if (operand_equal_p (base_1, iv->base, 0)
1947 || operand_equal_p (base_2, biv->base, 0))
1949 iv->have_address_use = true;
1950 data->bivs_not_used_in_addr--;
1955 /* Cumulates the steps of indices into DATA and replaces their values with the
1956 initial ones. Returns false when the value of the index cannot be determined.
1957 Callback for for_each_index. */
1959 struct ifs_ivopts_data
1961 struct ivopts_data *ivopts_data;
1962 gimple *stmt;
1963 tree step;
1966 static bool
1967 idx_find_step (tree base, tree *idx, void *data)
1969 struct ifs_ivopts_data *dta = (struct ifs_ivopts_data *) data;
1970 struct iv *iv;
1971 bool use_overflow_semantics = false;
1972 tree step, iv_base, iv_step, lbound, off;
1973 struct loop *loop = dta->ivopts_data->current_loop;
1975 /* If base is a component ref, require that the offset of the reference
1976 be invariant. */
1977 if (TREE_CODE (base) == COMPONENT_REF)
1979 off = component_ref_field_offset (base);
1980 return expr_invariant_in_loop_p (loop, off);
1983 /* If base is array, first check whether we will be able to move the
1984 reference out of the loop (in order to take its address in strength
1985 reduction). In order for this to work we need both lower bound
1986 and step to be loop invariants. */
1987 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
1989 /* Moreover, for a range, the size needs to be invariant as well. */
1990 if (TREE_CODE (base) == ARRAY_RANGE_REF
1991 && !expr_invariant_in_loop_p (loop, TYPE_SIZE (TREE_TYPE (base))))
1992 return false;
1994 step = array_ref_element_size (base);
1995 lbound = array_ref_low_bound (base);
1997 if (!expr_invariant_in_loop_p (loop, step)
1998 || !expr_invariant_in_loop_p (loop, lbound))
1999 return false;
2002 if (TREE_CODE (*idx) != SSA_NAME)
2003 return true;
2005 iv = get_iv (dta->ivopts_data, *idx);
2006 if (!iv)
2007 return false;
2009 /* XXX We produce for a base of *D42 with iv->base being &x[0]
2010 *&x[0], which is not folded and does not trigger the
2011 ARRAY_REF path below. */
2012 *idx = iv->base;
2014 if (integer_zerop (iv->step))
2015 return true;
2017 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
2019 step = array_ref_element_size (base);
2021 /* We only handle addresses whose step is an integer constant. */
2022 if (TREE_CODE (step) != INTEGER_CST)
2023 return false;
2025 else
2026 /* The step for pointer arithmetics already is 1 byte. */
2027 step = size_one_node;
2029 iv_base = iv->base;
2030 iv_step = iv->step;
2031 if (iv->no_overflow && nowrap_type_p (TREE_TYPE (iv_step)))
2032 use_overflow_semantics = true;
2034 if (!convert_affine_scev (dta->ivopts_data->current_loop,
2035 sizetype, &iv_base, &iv_step, dta->stmt,
2036 use_overflow_semantics))
2038 /* The index might wrap. */
2039 return false;
2042 step = fold_build2 (MULT_EXPR, sizetype, step, iv_step);
2043 dta->step = fold_build2 (PLUS_EXPR, sizetype, dta->step, step);
2045 if (dta->ivopts_data->bivs_not_used_in_addr)
2047 if (!iv->biv_p)
2048 iv = find_deriving_biv_for_expr (dta->ivopts_data, iv->ssa_name);
2050 record_biv_for_address_use (dta->ivopts_data, iv);
2052 return true;
2055 /* Records use in index IDX. Callback for for_each_index. Ivopts data
2056 object is passed to it in DATA. */
2058 static bool
2059 idx_record_use (tree base, tree *idx,
2060 void *vdata)
2062 struct ivopts_data *data = (struct ivopts_data *) vdata;
2063 find_interesting_uses_op (data, *idx);
2064 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
2066 find_interesting_uses_op (data, array_ref_element_size (base));
2067 find_interesting_uses_op (data, array_ref_low_bound (base));
2069 return true;
2072 /* If we can prove that TOP = cst * BOT for some constant cst,
2073 store cst to MUL and return true. Otherwise return false.
2074 The returned value is always sign-extended, regardless of the
2075 signedness of TOP and BOT. */
2077 static bool
2078 constant_multiple_of (tree top, tree bot, widest_int *mul)
2080 tree mby;
2081 enum tree_code code;
2082 unsigned precision = TYPE_PRECISION (TREE_TYPE (top));
2083 widest_int res, p0, p1;
2085 STRIP_NOPS (top);
2086 STRIP_NOPS (bot);
2088 if (operand_equal_p (top, bot, 0))
2090 *mul = 1;
2091 return true;
2094 code = TREE_CODE (top);
2095 switch (code)
2097 case MULT_EXPR:
2098 mby = TREE_OPERAND (top, 1);
2099 if (TREE_CODE (mby) != INTEGER_CST)
2100 return false;
2102 if (!constant_multiple_of (TREE_OPERAND (top, 0), bot, &res))
2103 return false;
2105 *mul = wi::sext (res * wi::to_widest (mby), precision);
2106 return true;
2108 case PLUS_EXPR:
2109 case MINUS_EXPR:
2110 if (!constant_multiple_of (TREE_OPERAND (top, 0), bot, &p0)
2111 || !constant_multiple_of (TREE_OPERAND (top, 1), bot, &p1))
2112 return false;
2114 if (code == MINUS_EXPR)
2115 p1 = -p1;
2116 *mul = wi::sext (p0 + p1, precision);
2117 return true;
2119 case INTEGER_CST:
2120 if (TREE_CODE (bot) != INTEGER_CST)
2121 return false;
2123 p0 = widest_int::from (top, SIGNED);
2124 p1 = widest_int::from (bot, SIGNED);
2125 if (p1 == 0)
2126 return false;
2127 *mul = wi::sext (wi::divmod_trunc (p0, p1, SIGNED, &res), precision);
2128 return res == 0;
2130 default:
2131 return false;
2135 /* Return true if memory reference REF with step STEP may be unaligned. */
2137 static bool
2138 may_be_unaligned_p (tree ref, tree step)
2140 /* TARGET_MEM_REFs are translated directly to valid MEMs on the target,
2141 thus they are not misaligned. */
2142 if (TREE_CODE (ref) == TARGET_MEM_REF)
2143 return false;
2145 unsigned int align = TYPE_ALIGN (TREE_TYPE (ref));
2146 if (GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref))) > align)
2147 align = GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref)));
2149 unsigned HOST_WIDE_INT bitpos;
2150 unsigned int ref_align;
2151 get_object_alignment_1 (ref, &ref_align, &bitpos);
2152 if (ref_align < align
2153 || (bitpos % align) != 0
2154 || (bitpos % BITS_PER_UNIT) != 0)
2155 return true;
2157 unsigned int trailing_zeros = tree_ctz (step);
2158 if (trailing_zeros < HOST_BITS_PER_INT
2159 && (1U << trailing_zeros) * BITS_PER_UNIT < align)
2160 return true;
2162 return false;
2165 /* Return true if EXPR may be non-addressable. */
2167 bool
2168 may_be_nonaddressable_p (tree expr)
2170 switch (TREE_CODE (expr))
2172 case TARGET_MEM_REF:
2173 /* TARGET_MEM_REFs are translated directly to valid MEMs on the
2174 target, thus they are always addressable. */
2175 return false;
2177 case MEM_REF:
2178 /* Likewise for MEM_REFs, modulo the storage order. */
2179 return REF_REVERSE_STORAGE_ORDER (expr);
2181 case BIT_FIELD_REF:
2182 if (REF_REVERSE_STORAGE_ORDER (expr))
2183 return true;
2184 return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2186 case COMPONENT_REF:
2187 if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr, 0))))
2188 return true;
2189 return DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1))
2190 || may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2192 case ARRAY_REF:
2193 case ARRAY_RANGE_REF:
2194 if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr, 0))))
2195 return true;
2196 return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2198 case VIEW_CONVERT_EXPR:
2199 /* This kind of view-conversions may wrap non-addressable objects
2200 and make them look addressable. After some processing the
2201 non-addressability may be uncovered again, causing ADDR_EXPRs
2202 of inappropriate objects to be built. */
2203 if (is_gimple_reg (TREE_OPERAND (expr, 0))
2204 || !is_gimple_addressable (TREE_OPERAND (expr, 0)))
2205 return true;
2206 return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2208 CASE_CONVERT:
2209 return true;
2211 default:
2212 break;
2215 return false;
2218 /* Finds addresses in *OP_P inside STMT. */
2220 static void
2221 find_interesting_uses_address (struct ivopts_data *data, gimple *stmt,
2222 tree *op_p)
2224 tree base = *op_p, step = size_zero_node;
2225 struct iv *civ;
2226 struct ifs_ivopts_data ifs_ivopts_data;
2228 /* Do not play with volatile memory references. A bit too conservative,
2229 perhaps, but safe. */
2230 if (gimple_has_volatile_ops (stmt))
2231 goto fail;
2233 /* Ignore bitfields for now. Not really something terribly complicated
2234 to handle. TODO. */
2235 if (TREE_CODE (base) == BIT_FIELD_REF)
2236 goto fail;
2238 base = unshare_expr (base);
2240 if (TREE_CODE (base) == TARGET_MEM_REF)
2242 tree type = build_pointer_type (TREE_TYPE (base));
2243 tree astep;
2245 if (TMR_BASE (base)
2246 && TREE_CODE (TMR_BASE (base)) == SSA_NAME)
2248 civ = get_iv (data, TMR_BASE (base));
2249 if (!civ)
2250 goto fail;
2252 TMR_BASE (base) = civ->base;
2253 step = civ->step;
2255 if (TMR_INDEX2 (base)
2256 && TREE_CODE (TMR_INDEX2 (base)) == SSA_NAME)
2258 civ = get_iv (data, TMR_INDEX2 (base));
2259 if (!civ)
2260 goto fail;
2262 TMR_INDEX2 (base) = civ->base;
2263 step = civ->step;
2265 if (TMR_INDEX (base)
2266 && TREE_CODE (TMR_INDEX (base)) == SSA_NAME)
2268 civ = get_iv (data, TMR_INDEX (base));
2269 if (!civ)
2270 goto fail;
2272 TMR_INDEX (base) = civ->base;
2273 astep = civ->step;
2275 if (astep)
2277 if (TMR_STEP (base))
2278 astep = fold_build2 (MULT_EXPR, type, TMR_STEP (base), astep);
2280 step = fold_build2 (PLUS_EXPR, type, step, astep);
2284 if (integer_zerop (step))
2285 goto fail;
2286 base = tree_mem_ref_addr (type, base);
2288 else
2290 ifs_ivopts_data.ivopts_data = data;
2291 ifs_ivopts_data.stmt = stmt;
2292 ifs_ivopts_data.step = size_zero_node;
2293 if (!for_each_index (&base, idx_find_step, &ifs_ivopts_data)
2294 || integer_zerop (ifs_ivopts_data.step))
2295 goto fail;
2296 step = ifs_ivopts_data.step;
2298 /* Check that the base expression is addressable. This needs
2299 to be done after substituting bases of IVs into it. */
2300 if (may_be_nonaddressable_p (base))
2301 goto fail;
2303 /* Moreover, on strict alignment platforms, check that it is
2304 sufficiently aligned. */
2305 if (STRICT_ALIGNMENT && may_be_unaligned_p (base, step))
2306 goto fail;
2308 base = build_fold_addr_expr (base);
2310 /* Substituting bases of IVs into the base expression might
2311 have caused folding opportunities. */
2312 if (TREE_CODE (base) == ADDR_EXPR)
2314 tree *ref = &TREE_OPERAND (base, 0);
2315 while (handled_component_p (*ref))
2316 ref = &TREE_OPERAND (*ref, 0);
2317 if (TREE_CODE (*ref) == MEM_REF)
2319 tree tem = fold_binary (MEM_REF, TREE_TYPE (*ref),
2320 TREE_OPERAND (*ref, 0),
2321 TREE_OPERAND (*ref, 1));
2322 if (tem)
2323 *ref = tem;
2328 civ = alloc_iv (data, base, step);
2329 /* Fail if base object of this memory reference is unknown. */
2330 if (civ->base_object == NULL_TREE)
2331 goto fail;
2333 record_group_use (data, op_p, civ, stmt, USE_ADDRESS);
2334 return;
2336 fail:
2337 for_each_index (op_p, idx_record_use, data);
2340 /* Finds and records invariants used in STMT. */
2342 static void
2343 find_invariants_stmt (struct ivopts_data *data, gimple *stmt)
2345 ssa_op_iter iter;
2346 use_operand_p use_p;
2347 tree op;
2349 FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2351 op = USE_FROM_PTR (use_p);
2352 record_invariant (data, op, false);
2356 /* Finds interesting uses of induction variables in the statement STMT. */
2358 static void
2359 find_interesting_uses_stmt (struct ivopts_data *data, gimple *stmt)
2361 struct iv *iv;
2362 tree op, *lhs, *rhs;
2363 ssa_op_iter iter;
2364 use_operand_p use_p;
2365 enum tree_code code;
2367 find_invariants_stmt (data, stmt);
2369 if (gimple_code (stmt) == GIMPLE_COND)
2371 find_interesting_uses_cond (data, stmt);
2372 return;
2375 if (is_gimple_assign (stmt))
2377 lhs = gimple_assign_lhs_ptr (stmt);
2378 rhs = gimple_assign_rhs1_ptr (stmt);
2380 if (TREE_CODE (*lhs) == SSA_NAME)
2382 /* If the statement defines an induction variable, the uses are not
2383 interesting by themselves. */
2385 iv = get_iv (data, *lhs);
2387 if (iv && !integer_zerop (iv->step))
2388 return;
2391 code = gimple_assign_rhs_code (stmt);
2392 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
2393 && (REFERENCE_CLASS_P (*rhs)
2394 || is_gimple_val (*rhs)))
2396 if (REFERENCE_CLASS_P (*rhs))
2397 find_interesting_uses_address (data, stmt, rhs);
2398 else
2399 find_interesting_uses_op (data, *rhs);
2401 if (REFERENCE_CLASS_P (*lhs))
2402 find_interesting_uses_address (data, stmt, lhs);
2403 return;
2405 else if (TREE_CODE_CLASS (code) == tcc_comparison)
2407 find_interesting_uses_cond (data, stmt);
2408 return;
2411 /* TODO -- we should also handle address uses of type
2413 memory = call (whatever);
2417 call (memory). */
2420 if (gimple_code (stmt) == GIMPLE_PHI
2421 && gimple_bb (stmt) == data->current_loop->header)
2423 iv = get_iv (data, PHI_RESULT (stmt));
2425 if (iv && !integer_zerop (iv->step))
2426 return;
2429 FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2431 op = USE_FROM_PTR (use_p);
2433 if (TREE_CODE (op) != SSA_NAME)
2434 continue;
2436 iv = get_iv (data, op);
2437 if (!iv)
2438 continue;
2440 find_interesting_uses_op (data, op);
2444 /* Finds interesting uses of induction variables outside of loops
2445 on loop exit edge EXIT. */
2447 static void
2448 find_interesting_uses_outside (struct ivopts_data *data, edge exit)
2450 gphi *phi;
2451 gphi_iterator psi;
2452 tree def;
2454 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2456 phi = psi.phi ();
2457 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2458 if (!virtual_operand_p (def))
2459 find_interesting_uses_op (data, def);
2463 /* Compute maximum offset of [base + offset] addressing mode
2464 for memory reference represented by USE. */
2466 static HOST_WIDE_INT
2467 compute_max_addr_offset (struct iv_use *use)
2469 int width;
2470 rtx reg, addr;
2471 HOST_WIDE_INT i, off;
2472 unsigned list_index, num;
2473 addr_space_t as;
2474 machine_mode mem_mode, addr_mode;
2475 static vec<HOST_WIDE_INT> max_offset_list;
2477 as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
2478 mem_mode = TYPE_MODE (TREE_TYPE (*use->op_p));
2480 num = max_offset_list.length ();
2481 list_index = (unsigned) as * MAX_MACHINE_MODE + (unsigned) mem_mode;
2482 if (list_index >= num)
2484 max_offset_list.safe_grow (list_index + MAX_MACHINE_MODE);
2485 for (; num < max_offset_list.length (); num++)
2486 max_offset_list[num] = -1;
2489 off = max_offset_list[list_index];
2490 if (off != -1)
2491 return off;
2493 addr_mode = targetm.addr_space.address_mode (as);
2494 reg = gen_raw_REG (addr_mode, LAST_VIRTUAL_REGISTER + 1);
2495 addr = gen_rtx_fmt_ee (PLUS, addr_mode, reg, NULL_RTX);
2497 width = GET_MODE_BITSIZE (addr_mode) - 1;
2498 if (width > (HOST_BITS_PER_WIDE_INT - 1))
2499 width = HOST_BITS_PER_WIDE_INT - 1;
2501 for (i = width; i > 0; i--)
2503 off = (HOST_WIDE_INT_1U << i) - 1;
2504 XEXP (addr, 1) = gen_int_mode (off, addr_mode);
2505 if (memory_address_addr_space_p (mem_mode, addr, as))
2506 break;
2508 /* For some strict-alignment targets, the offset must be naturally
2509 aligned. Try an aligned offset if mem_mode is not QImode. */
2510 off = (HOST_WIDE_INT_1U << i);
2511 if (off > GET_MODE_SIZE (mem_mode) && mem_mode != QImode)
2513 off -= GET_MODE_SIZE (mem_mode);
2514 XEXP (addr, 1) = gen_int_mode (off, addr_mode);
2515 if (memory_address_addr_space_p (mem_mode, addr, as))
2516 break;
2519 if (i == 0)
2520 off = 0;
2522 max_offset_list[list_index] = off;
2523 return off;
2526 /* Comparison function to sort group in ascending order of addr_offset. */
2528 static int
2529 group_compare_offset (const void *a, const void *b)
2531 const struct iv_use *const *u1 = (const struct iv_use *const *) a;
2532 const struct iv_use *const *u2 = (const struct iv_use *const *) b;
2534 if ((*u1)->addr_offset != (*u2)->addr_offset)
2535 return (*u1)->addr_offset < (*u2)->addr_offset ? -1 : 1;
2536 else
2537 return 0;
2540 /* Check if small groups should be split. Return true if no group
2541 contains more than two uses with distinct addr_offsets. Return
2542 false otherwise. We want to split such groups because:
2544 1) Small groups don't have much benefit and may interfer with
2545 general candidate selection.
2546 2) Size for problem with only small groups is usually small and
2547 general algorithm can handle it well.
2549 TODO -- Above claim may not hold when we want to merge memory
2550 accesses with conseuctive addresses. */
2552 static bool
2553 split_small_address_groups_p (struct ivopts_data *data)
2555 unsigned int i, j, distinct = 1;
2556 struct iv_use *pre;
2557 struct iv_group *group;
2559 for (i = 0; i < data->vgroups.length (); i++)
2561 group = data->vgroups[i];
2562 if (group->vuses.length () == 1)
2563 continue;
2565 gcc_assert (group->type == USE_ADDRESS);
2566 if (group->vuses.length () == 2)
2568 if (group->vuses[0]->addr_offset > group->vuses[1]->addr_offset)
2569 std::swap (group->vuses[0], group->vuses[1]);
2571 else
2572 group->vuses.qsort (group_compare_offset);
2574 if (distinct > 2)
2575 continue;
2577 distinct = 1;
2578 for (pre = group->vuses[0], j = 1; j < group->vuses.length (); j++)
2580 if (group->vuses[j]->addr_offset != pre->addr_offset)
2582 pre = group->vuses[j];
2583 distinct++;
2586 if (distinct > 2)
2587 break;
2591 return (distinct <= 2);
2594 /* For each group of address type uses, this function further groups
2595 these uses according to the maximum offset supported by target's
2596 [base + offset] addressing mode. */
2598 static void
2599 split_address_groups (struct ivopts_data *data)
2601 unsigned int i, j;
2602 HOST_WIDE_INT max_offset = -1;
2604 /* Reset max offset to split all small groups. */
2605 if (split_small_address_groups_p (data))
2606 max_offset = 0;
2608 for (i = 0; i < data->vgroups.length (); i++)
2610 struct iv_group *group = data->vgroups[i];
2611 struct iv_use *use = group->vuses[0];
2613 use->id = 0;
2614 use->group_id = group->id;
2615 if (group->vuses.length () == 1)
2616 continue;
2618 if (max_offset != 0)
2619 max_offset = compute_max_addr_offset (use);
2621 for (j = 1; j < group->vuses.length (); j++)
2623 struct iv_use *next = group->vuses[j];
2625 /* Only uses with offset that can fit in offset part against
2626 the first use can be grouped together. */
2627 if (next->addr_offset - use->addr_offset
2628 > (unsigned HOST_WIDE_INT) max_offset)
2629 break;
2631 next->id = j;
2632 next->group_id = group->id;
2634 /* Split group. */
2635 if (j < group->vuses.length ())
2637 struct iv_group *new_group = record_group (data, group->type);
2638 new_group->vuses.safe_splice (group->vuses);
2639 new_group->vuses.block_remove (0, j);
2640 group->vuses.truncate (j);
2645 /* Finds uses of the induction variables that are interesting. */
2647 static void
2648 find_interesting_uses (struct ivopts_data *data)
2650 basic_block bb;
2651 gimple_stmt_iterator bsi;
2652 basic_block *body = get_loop_body (data->current_loop);
2653 unsigned i;
2654 edge e;
2656 for (i = 0; i < data->current_loop->num_nodes; i++)
2658 edge_iterator ei;
2659 bb = body[i];
2661 FOR_EACH_EDGE (e, ei, bb->succs)
2662 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
2663 && !flow_bb_inside_loop_p (data->current_loop, e->dest))
2664 find_interesting_uses_outside (data, e);
2666 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2667 find_interesting_uses_stmt (data, gsi_stmt (bsi));
2668 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2669 if (!is_gimple_debug (gsi_stmt (bsi)))
2670 find_interesting_uses_stmt (data, gsi_stmt (bsi));
2673 split_address_groups (data);
2675 if (dump_file && (dump_flags & TDF_DETAILS))
2677 bitmap_iterator bi;
2679 fprintf (dump_file, "\n<Invariant Vars>:\n");
2680 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
2682 struct version_info *info = ver_info (data, i);
2683 if (info->inv_id)
2685 fprintf (dump_file, "Inv %d:\t", info->inv_id);
2686 print_generic_expr (dump_file, info->name, TDF_SLIM);
2687 fprintf (dump_file, "%s\n",
2688 info->has_nonlin_use ? "" : "\t(eliminable)");
2692 fprintf (dump_file, "\n<IV Groups>:\n");
2693 dump_groups (dump_file, data);
2694 fprintf (dump_file, "\n");
2697 free (body);
2700 /* Strips constant offsets from EXPR and stores them to OFFSET. If INSIDE_ADDR
2701 is true, assume we are inside an address. If TOP_COMPREF is true, assume
2702 we are at the top-level of the processed address. */
2704 static tree
2705 strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
2706 HOST_WIDE_INT *offset)
2708 tree op0 = NULL_TREE, op1 = NULL_TREE, tmp, step;
2709 enum tree_code code;
2710 tree type, orig_type = TREE_TYPE (expr);
2711 HOST_WIDE_INT off0, off1, st;
2712 tree orig_expr = expr;
2714 STRIP_NOPS (expr);
2716 type = TREE_TYPE (expr);
2717 code = TREE_CODE (expr);
2718 *offset = 0;
2720 switch (code)
2722 case INTEGER_CST:
2723 if (!cst_and_fits_in_hwi (expr)
2724 || integer_zerop (expr))
2725 return orig_expr;
2727 *offset = int_cst_value (expr);
2728 return build_int_cst (orig_type, 0);
2730 case POINTER_PLUS_EXPR:
2731 case PLUS_EXPR:
2732 case MINUS_EXPR:
2733 op0 = TREE_OPERAND (expr, 0);
2734 op1 = TREE_OPERAND (expr, 1);
2736 op0 = strip_offset_1 (op0, false, false, &off0);
2737 op1 = strip_offset_1 (op1, false, false, &off1);
2739 *offset = (code == MINUS_EXPR ? off0 - off1 : off0 + off1);
2740 if (op0 == TREE_OPERAND (expr, 0)
2741 && op1 == TREE_OPERAND (expr, 1))
2742 return orig_expr;
2744 if (integer_zerop (op1))
2745 expr = op0;
2746 else if (integer_zerop (op0))
2748 if (code == MINUS_EXPR)
2749 expr = fold_build1 (NEGATE_EXPR, type, op1);
2750 else
2751 expr = op1;
2753 else
2754 expr = fold_build2 (code, type, op0, op1);
2756 return fold_convert (orig_type, expr);
2758 case MULT_EXPR:
2759 op1 = TREE_OPERAND (expr, 1);
2760 if (!cst_and_fits_in_hwi (op1))
2761 return orig_expr;
2763 op0 = TREE_OPERAND (expr, 0);
2764 op0 = strip_offset_1 (op0, false, false, &off0);
2765 if (op0 == TREE_OPERAND (expr, 0))
2766 return orig_expr;
2768 *offset = off0 * int_cst_value (op1);
2769 if (integer_zerop (op0))
2770 expr = op0;
2771 else
2772 expr = fold_build2 (MULT_EXPR, type, op0, op1);
2774 return fold_convert (orig_type, expr);
2776 case ARRAY_REF:
2777 case ARRAY_RANGE_REF:
2778 if (!inside_addr)
2779 return orig_expr;
2781 step = array_ref_element_size (expr);
2782 if (!cst_and_fits_in_hwi (step))
2783 break;
2785 st = int_cst_value (step);
2786 op1 = TREE_OPERAND (expr, 1);
2787 op1 = strip_offset_1 (op1, false, false, &off1);
2788 *offset = off1 * st;
2790 if (top_compref
2791 && integer_zerop (op1))
2793 /* Strip the component reference completely. */
2794 op0 = TREE_OPERAND (expr, 0);
2795 op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
2796 *offset += off0;
2797 return op0;
2799 break;
2801 case COMPONENT_REF:
2803 tree field;
2805 if (!inside_addr)
2806 return orig_expr;
2808 tmp = component_ref_field_offset (expr);
2809 field = TREE_OPERAND (expr, 1);
2810 if (top_compref
2811 && cst_and_fits_in_hwi (tmp)
2812 && cst_and_fits_in_hwi (DECL_FIELD_BIT_OFFSET (field)))
2814 HOST_WIDE_INT boffset, abs_off;
2816 /* Strip the component reference completely. */
2817 op0 = TREE_OPERAND (expr, 0);
2818 op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
2819 boffset = int_cst_value (DECL_FIELD_BIT_OFFSET (field));
2820 abs_off = abs_hwi (boffset) / BITS_PER_UNIT;
2821 if (boffset < 0)
2822 abs_off = -abs_off;
2824 *offset = off0 + int_cst_value (tmp) + abs_off;
2825 return op0;
2828 break;
2830 case ADDR_EXPR:
2831 op0 = TREE_OPERAND (expr, 0);
2832 op0 = strip_offset_1 (op0, true, true, &off0);
2833 *offset += off0;
2835 if (op0 == TREE_OPERAND (expr, 0))
2836 return orig_expr;
2838 expr = build_fold_addr_expr (op0);
2839 return fold_convert (orig_type, expr);
2841 case MEM_REF:
2842 /* ??? Offset operand? */
2843 inside_addr = false;
2844 break;
2846 default:
2847 return orig_expr;
2850 /* Default handling of expressions for that we want to recurse into
2851 the first operand. */
2852 op0 = TREE_OPERAND (expr, 0);
2853 op0 = strip_offset_1 (op0, inside_addr, false, &off0);
2854 *offset += off0;
2856 if (op0 == TREE_OPERAND (expr, 0)
2857 && (!op1 || op1 == TREE_OPERAND (expr, 1)))
2858 return orig_expr;
2860 expr = copy_node (expr);
2861 TREE_OPERAND (expr, 0) = op0;
2862 if (op1)
2863 TREE_OPERAND (expr, 1) = op1;
2865 /* Inside address, we might strip the top level component references,
2866 thus changing type of the expression. Handling of ADDR_EXPR
2867 will fix that. */
2868 expr = fold_convert (orig_type, expr);
2870 return expr;
2873 /* Strips constant offsets from EXPR and stores them to OFFSET. */
2875 static tree
2876 strip_offset (tree expr, unsigned HOST_WIDE_INT *offset)
2878 HOST_WIDE_INT off;
2879 tree core = strip_offset_1 (expr, false, false, &off);
2880 *offset = off;
2881 return core;
2884 /* Returns variant of TYPE that can be used as base for different uses.
2885 We return unsigned type with the same precision, which avoids problems
2886 with overflows. */
2888 static tree
2889 generic_type_for (tree type)
2891 if (POINTER_TYPE_P (type))
2892 return unsigned_type_for (type);
2894 if (TYPE_UNSIGNED (type))
2895 return type;
2897 return unsigned_type_for (type);
2900 /* Private data for walk_tree. */
2902 struct walk_tree_data
2904 bitmap *inv_vars;
2905 struct ivopts_data *idata;
2908 /* Callback function for walk_tree, it records invariants and symbol
2909 reference in *EXPR_P. DATA is the structure storing result info. */
2911 static tree
2912 find_inv_vars_cb (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
2914 struct walk_tree_data *wdata = (struct walk_tree_data*) data;
2915 struct version_info *info;
2917 if (TREE_CODE (*expr_p) != SSA_NAME)
2918 return NULL_TREE;
2920 info = name_info (wdata->idata, *expr_p);
2921 if (!info->inv_id || info->has_nonlin_use)
2922 return NULL_TREE;
2924 if (!*wdata->inv_vars)
2925 *wdata->inv_vars = BITMAP_ALLOC (NULL);
2926 bitmap_set_bit (*wdata->inv_vars, info->inv_id);
2928 return NULL_TREE;
2931 /* Records invariants in *EXPR_P. INV_VARS is the bitmap to that we should
2932 store it. */
2934 static inline void
2935 find_inv_vars (struct ivopts_data *data, tree *expr_p, bitmap *inv_vars)
2937 struct walk_tree_data wdata;
2939 if (!inv_vars)
2940 return;
2942 wdata.idata = data;
2943 wdata.inv_vars = inv_vars;
2944 walk_tree (expr_p, find_inv_vars_cb, &wdata, NULL);
2947 /* Adds a candidate BASE + STEP * i. Important field is set to IMPORTANT and
2948 position to POS. If USE is not NULL, the candidate is set as related to
2949 it. If both BASE and STEP are NULL, we add a pseudocandidate for the
2950 replacement of the final value of the iv by a direct computation. */
2952 static struct iv_cand *
2953 add_candidate_1 (struct ivopts_data *data,
2954 tree base, tree step, bool important, enum iv_position pos,
2955 struct iv_use *use, gimple *incremented_at,
2956 struct iv *orig_iv = NULL)
2958 unsigned i;
2959 struct iv_cand *cand = NULL;
2960 tree type, orig_type;
2962 gcc_assert (base && step);
2964 /* -fkeep-gc-roots-live means that we have to keep a real pointer
2965 live, but the ivopts code may replace a real pointer with one
2966 pointing before or after the memory block that is then adjusted
2967 into the memory block during the loop. FIXME: It would likely be
2968 better to actually force the pointer live and still use ivopts;
2969 for example, it would be enough to write the pointer into memory
2970 and keep it there until after the loop. */
2971 if (flag_keep_gc_roots_live && POINTER_TYPE_P (TREE_TYPE (base)))
2972 return NULL;
2974 /* For non-original variables, make sure their values are computed in a type
2975 that does not invoke undefined behavior on overflows (since in general,
2976 we cannot prove that these induction variables are non-wrapping). */
2977 if (pos != IP_ORIGINAL)
2979 orig_type = TREE_TYPE (base);
2980 type = generic_type_for (orig_type);
2981 if (type != orig_type)
2983 base = fold_convert (type, base);
2984 step = fold_convert (type, step);
2988 for (i = 0; i < data->vcands.length (); i++)
2990 cand = data->vcands[i];
2992 if (cand->pos != pos)
2993 continue;
2995 if (cand->incremented_at != incremented_at
2996 || ((pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
2997 && cand->ainc_use != use))
2998 continue;
3000 if (operand_equal_p (base, cand->iv->base, 0)
3001 && operand_equal_p (step, cand->iv->step, 0)
3002 && (TYPE_PRECISION (TREE_TYPE (base))
3003 == TYPE_PRECISION (TREE_TYPE (cand->iv->base))))
3004 break;
3007 if (i == data->vcands.length ())
3009 cand = XCNEW (struct iv_cand);
3010 cand->id = i;
3011 cand->iv = alloc_iv (data, base, step);
3012 cand->pos = pos;
3013 if (pos != IP_ORIGINAL)
3015 cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
3016 cand->var_after = cand->var_before;
3018 cand->important = important;
3019 cand->incremented_at = incremented_at;
3020 data->vcands.safe_push (cand);
3022 if (TREE_CODE (step) != INTEGER_CST)
3023 find_inv_vars (data, &step, &cand->inv_vars);
3025 if (pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
3026 cand->ainc_use = use;
3027 else
3028 cand->ainc_use = NULL;
3030 cand->orig_iv = orig_iv;
3031 if (dump_file && (dump_flags & TDF_DETAILS))
3032 dump_cand (dump_file, cand);
3035 cand->important |= important;
3037 /* Relate candidate to the group for which it is added. */
3038 if (use)
3039 bitmap_set_bit (data->vgroups[use->group_id]->related_cands, i);
3041 return cand;
3044 /* Returns true if incrementing the induction variable at the end of the LOOP
3045 is allowed.
3047 The purpose is to avoid splitting latch edge with a biv increment, thus
3048 creating a jump, possibly confusing other optimization passes and leaving
3049 less freedom to scheduler. So we allow IP_END_POS only if IP_NORMAL_POS
3050 is not available (so we do not have a better alternative), or if the latch
3051 edge is already nonempty. */
3053 static bool
3054 allow_ip_end_pos_p (struct loop *loop)
3056 if (!ip_normal_pos (loop))
3057 return true;
3059 if (!empty_block_p (ip_end_pos (loop)))
3060 return true;
3062 return false;
3065 /* If possible, adds autoincrement candidates BASE + STEP * i based on use USE.
3066 Important field is set to IMPORTANT. */
3068 static void
3069 add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
3070 bool important, struct iv_use *use)
3072 basic_block use_bb = gimple_bb (use->stmt);
3073 machine_mode mem_mode;
3074 unsigned HOST_WIDE_INT cstepi;
3076 /* If we insert the increment in any position other than the standard
3077 ones, we must ensure that it is incremented once per iteration.
3078 It must not be in an inner nested loop, or one side of an if
3079 statement. */
3080 if (use_bb->loop_father != data->current_loop
3081 || !dominated_by_p (CDI_DOMINATORS, data->current_loop->latch, use_bb)
3082 || stmt_could_throw_p (use->stmt)
3083 || !cst_and_fits_in_hwi (step))
3084 return;
3086 cstepi = int_cst_value (step);
3088 mem_mode = TYPE_MODE (TREE_TYPE (*use->op_p));
3089 if (((USE_LOAD_PRE_INCREMENT (mem_mode)
3090 || USE_STORE_PRE_INCREMENT (mem_mode))
3091 && GET_MODE_SIZE (mem_mode) == cstepi)
3092 || ((USE_LOAD_PRE_DECREMENT (mem_mode)
3093 || USE_STORE_PRE_DECREMENT (mem_mode))
3094 && GET_MODE_SIZE (mem_mode) == -cstepi))
3096 enum tree_code code = MINUS_EXPR;
3097 tree new_base;
3098 tree new_step = step;
3100 if (POINTER_TYPE_P (TREE_TYPE (base)))
3102 new_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
3103 code = POINTER_PLUS_EXPR;
3105 else
3106 new_step = fold_convert (TREE_TYPE (base), new_step);
3107 new_base = fold_build2 (code, TREE_TYPE (base), base, new_step);
3108 add_candidate_1 (data, new_base, step, important, IP_BEFORE_USE, use,
3109 use->stmt);
3111 if (((USE_LOAD_POST_INCREMENT (mem_mode)
3112 || USE_STORE_POST_INCREMENT (mem_mode))
3113 && GET_MODE_SIZE (mem_mode) == cstepi)
3114 || ((USE_LOAD_POST_DECREMENT (mem_mode)
3115 || USE_STORE_POST_DECREMENT (mem_mode))
3116 && GET_MODE_SIZE (mem_mode) == -cstepi))
3118 add_candidate_1 (data, base, step, important, IP_AFTER_USE, use,
3119 use->stmt);
3123 /* Adds a candidate BASE + STEP * i. Important field is set to IMPORTANT and
3124 position to POS. If USE is not NULL, the candidate is set as related to
3125 it. The candidate computation is scheduled before exit condition and at
3126 the end of loop. */
3128 static void
3129 add_candidate (struct ivopts_data *data,
3130 tree base, tree step, bool important, struct iv_use *use,
3131 struct iv *orig_iv = NULL)
3133 if (ip_normal_pos (data->current_loop))
3134 add_candidate_1 (data, base, step, important,
3135 IP_NORMAL, use, NULL, orig_iv);
3136 if (ip_end_pos (data->current_loop)
3137 && allow_ip_end_pos_p (data->current_loop))
3138 add_candidate_1 (data, base, step, important, IP_END, use, NULL, orig_iv);
3141 /* Adds standard iv candidates. */
3143 static void
3144 add_standard_iv_candidates (struct ivopts_data *data)
3146 add_candidate (data, integer_zero_node, integer_one_node, true, NULL);
3148 /* The same for a double-integer type if it is still fast enough. */
3149 if (TYPE_PRECISION
3150 (long_integer_type_node) > TYPE_PRECISION (integer_type_node)
3151 && TYPE_PRECISION (long_integer_type_node) <= BITS_PER_WORD)
3152 add_candidate (data, build_int_cst (long_integer_type_node, 0),
3153 build_int_cst (long_integer_type_node, 1), true, NULL);
3155 /* The same for a double-integer type if it is still fast enough. */
3156 if (TYPE_PRECISION
3157 (long_long_integer_type_node) > TYPE_PRECISION (long_integer_type_node)
3158 && TYPE_PRECISION (long_long_integer_type_node) <= BITS_PER_WORD)
3159 add_candidate (data, build_int_cst (long_long_integer_type_node, 0),
3160 build_int_cst (long_long_integer_type_node, 1), true, NULL);
3164 /* Adds candidates bases on the old induction variable IV. */
3166 static void
3167 add_iv_candidate_for_biv (struct ivopts_data *data, struct iv *iv)
3169 gimple *phi;
3170 tree def;
3171 struct iv_cand *cand;
3173 /* Check if this biv is used in address type use. */
3174 if (iv->no_overflow && iv->have_address_use
3175 && INTEGRAL_TYPE_P (TREE_TYPE (iv->base))
3176 && TYPE_PRECISION (TREE_TYPE (iv->base)) < TYPE_PRECISION (sizetype))
3178 tree base = fold_convert (sizetype, iv->base);
3179 tree step = fold_convert (sizetype, iv->step);
3181 /* Add iv cand of same precision as index part in TARGET_MEM_REF. */
3182 add_candidate (data, base, step, true, NULL, iv);
3183 /* Add iv cand of the original type only if it has nonlinear use. */
3184 if (iv->nonlin_use)
3185 add_candidate (data, iv->base, iv->step, true, NULL);
3187 else
3188 add_candidate (data, iv->base, iv->step, true, NULL);
3190 /* The same, but with initial value zero. */
3191 if (POINTER_TYPE_P (TREE_TYPE (iv->base)))
3192 add_candidate (data, size_int (0), iv->step, true, NULL);
3193 else
3194 add_candidate (data, build_int_cst (TREE_TYPE (iv->base), 0),
3195 iv->step, true, NULL);
3197 phi = SSA_NAME_DEF_STMT (iv->ssa_name);
3198 if (gimple_code (phi) == GIMPLE_PHI)
3200 /* Additionally record the possibility of leaving the original iv
3201 untouched. */
3202 def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (data->current_loop));
3203 /* Don't add candidate if it's from another PHI node because
3204 it's an affine iv appearing in the form of PEELED_CHREC. */
3205 phi = SSA_NAME_DEF_STMT (def);
3206 if (gimple_code (phi) != GIMPLE_PHI)
3208 cand = add_candidate_1 (data,
3209 iv->base, iv->step, true, IP_ORIGINAL, NULL,
3210 SSA_NAME_DEF_STMT (def));
3211 if (cand)
3213 cand->var_before = iv->ssa_name;
3214 cand->var_after = def;
3217 else
3218 gcc_assert (gimple_bb (phi) == data->current_loop->header);
3222 /* Adds candidates based on the old induction variables. */
3224 static void
3225 add_iv_candidate_for_bivs (struct ivopts_data *data)
3227 unsigned i;
3228 struct iv *iv;
3229 bitmap_iterator bi;
3231 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
3233 iv = ver_info (data, i)->iv;
3234 if (iv && iv->biv_p && !integer_zerop (iv->step))
3235 add_iv_candidate_for_biv (data, iv);
3239 /* Record common candidate {BASE, STEP} derived from USE in hashtable. */
3241 static void
3242 record_common_cand (struct ivopts_data *data, tree base,
3243 tree step, struct iv_use *use)
3245 struct iv_common_cand ent;
3246 struct iv_common_cand **slot;
3248 ent.base = base;
3249 ent.step = step;
3250 ent.hash = iterative_hash_expr (base, 0);
3251 ent.hash = iterative_hash_expr (step, ent.hash);
3253 slot = data->iv_common_cand_tab->find_slot (&ent, INSERT);
3254 if (*slot == NULL)
3256 *slot = new iv_common_cand ();
3257 (*slot)->base = base;
3258 (*slot)->step = step;
3259 (*slot)->uses.create (8);
3260 (*slot)->hash = ent.hash;
3261 data->iv_common_cands.safe_push ((*slot));
3264 gcc_assert (use != NULL);
3265 (*slot)->uses.safe_push (use);
3266 return;
3269 /* Comparison function used to sort common candidates. */
3271 static int
3272 common_cand_cmp (const void *p1, const void *p2)
3274 unsigned n1, n2;
3275 const struct iv_common_cand *const *const ccand1
3276 = (const struct iv_common_cand *const *)p1;
3277 const struct iv_common_cand *const *const ccand2
3278 = (const struct iv_common_cand *const *)p2;
3280 n1 = (*ccand1)->uses.length ();
3281 n2 = (*ccand2)->uses.length ();
3282 return n2 - n1;
3285 /* Adds IV candidates based on common candidated recorded. */
3287 static void
3288 add_iv_candidate_derived_from_uses (struct ivopts_data *data)
3290 unsigned i, j;
3291 struct iv_cand *cand_1, *cand_2;
3293 data->iv_common_cands.qsort (common_cand_cmp);
3294 for (i = 0; i < data->iv_common_cands.length (); i++)
3296 struct iv_common_cand *ptr = data->iv_common_cands[i];
3298 /* Only add IV candidate if it's derived from multiple uses. */
3299 if (ptr->uses.length () <= 1)
3300 break;
3302 cand_1 = NULL;
3303 cand_2 = NULL;
3304 if (ip_normal_pos (data->current_loop))
3305 cand_1 = add_candidate_1 (data, ptr->base, ptr->step,
3306 false, IP_NORMAL, NULL, NULL);
3308 if (ip_end_pos (data->current_loop)
3309 && allow_ip_end_pos_p (data->current_loop))
3310 cand_2 = add_candidate_1 (data, ptr->base, ptr->step,
3311 false, IP_END, NULL, NULL);
3313 /* Bind deriving uses and the new candidates. */
3314 for (j = 0; j < ptr->uses.length (); j++)
3316 struct iv_group *group = data->vgroups[ptr->uses[j]->group_id];
3317 if (cand_1)
3318 bitmap_set_bit (group->related_cands, cand_1->id);
3319 if (cand_2)
3320 bitmap_set_bit (group->related_cands, cand_2->id);
3324 /* Release data since it is useless from this point. */
3325 data->iv_common_cand_tab->empty ();
3326 data->iv_common_cands.truncate (0);
3329 /* Adds candidates based on the value of USE's iv. */
3331 static void
3332 add_iv_candidate_for_use (struct ivopts_data *data, struct iv_use *use)
3334 unsigned HOST_WIDE_INT offset;
3335 tree base;
3336 tree basetype;
3337 struct iv *iv = use->iv;
3339 add_candidate (data, iv->base, iv->step, false, use);
3341 /* Record common candidate for use in case it can be shared by others. */
3342 record_common_cand (data, iv->base, iv->step, use);
3344 /* Record common candidate with initial value zero. */
3345 basetype = TREE_TYPE (iv->base);
3346 if (POINTER_TYPE_P (basetype))
3347 basetype = sizetype;
3348 record_common_cand (data, build_int_cst (basetype, 0), iv->step, use);
3350 /* Record common candidate with constant offset stripped in base.
3351 Like the use itself, we also add candidate directly for it. */
3352 base = strip_offset (iv->base, &offset);
3353 if (offset || base != iv->base)
3355 record_common_cand (data, base, iv->step, use);
3356 add_candidate (data, base, iv->step, false, use);
3359 /* Record common candidate with base_object removed in base. */
3360 base = iv->base;
3361 STRIP_NOPS (base);
3362 if (iv->base_object != NULL && TREE_CODE (base) == POINTER_PLUS_EXPR)
3364 tree step = iv->step;
3366 STRIP_NOPS (step);
3367 base = TREE_OPERAND (base, 1);
3368 step = fold_convert (sizetype, step);
3369 record_common_cand (data, base, step, use);
3370 /* Also record common candidate with offset stripped. */
3371 base = strip_offset (base, &offset);
3372 if (offset)
3373 record_common_cand (data, base, step, use);
3376 /* At last, add auto-incremental candidates. Make such variables
3377 important since other iv uses with same base object may be based
3378 on it. */
3379 if (use != NULL && use->type == USE_ADDRESS)
3380 add_autoinc_candidates (data, iv->base, iv->step, true, use);
3383 /* Adds candidates based on the uses. */
3385 static void
3386 add_iv_candidate_for_groups (struct ivopts_data *data)
3388 unsigned i;
3390 /* Only add candidate for the first use in group. */
3391 for (i = 0; i < data->vgroups.length (); i++)
3393 struct iv_group *group = data->vgroups[i];
3395 gcc_assert (group->vuses[0] != NULL);
3396 add_iv_candidate_for_use (data, group->vuses[0]);
3398 add_iv_candidate_derived_from_uses (data);
3401 /* Record important candidates and add them to related_cands bitmaps. */
3403 static void
3404 record_important_candidates (struct ivopts_data *data)
3406 unsigned i;
3407 struct iv_group *group;
3409 for (i = 0; i < data->vcands.length (); i++)
3411 struct iv_cand *cand = data->vcands[i];
3413 if (cand->important)
3414 bitmap_set_bit (data->important_candidates, i);
3417 data->consider_all_candidates = (data->vcands.length ()
3418 <= CONSIDER_ALL_CANDIDATES_BOUND);
3420 /* Add important candidates to groups' related_cands bitmaps. */
3421 for (i = 0; i < data->vgroups.length (); i++)
3423 group = data->vgroups[i];
3424 bitmap_ior_into (group->related_cands, data->important_candidates);
3428 /* Allocates the data structure mapping the (use, candidate) pairs to costs.
3429 If consider_all_candidates is true, we use a two-dimensional array, otherwise
3430 we allocate a simple list to every use. */
3432 static void
3433 alloc_use_cost_map (struct ivopts_data *data)
3435 unsigned i, size, s;
3437 for (i = 0; i < data->vgroups.length (); i++)
3439 struct iv_group *group = data->vgroups[i];
3441 if (data->consider_all_candidates)
3442 size = data->vcands.length ();
3443 else
3445 s = bitmap_count_bits (group->related_cands);
3447 /* Round up to the power of two, so that moduling by it is fast. */
3448 size = s ? (1 << ceil_log2 (s)) : 1;
3451 group->n_map_members = size;
3452 group->cost_map = XCNEWVEC (struct cost_pair, size);
3456 /* Sets cost of (GROUP, CAND) pair to COST and record that it depends
3457 on invariants INV_VARS and that the value used in expressing it is
3458 VALUE, and in case of iv elimination the comparison operator is COMP. */
3460 static void
3461 set_group_iv_cost (struct ivopts_data *data,
3462 struct iv_group *group, struct iv_cand *cand,
3463 comp_cost cost, bitmap inv_vars, tree value,
3464 enum tree_code comp, bitmap inv_exprs)
3466 unsigned i, s;
3468 if (cost.infinite_cost_p ())
3470 BITMAP_FREE (inv_vars);
3471 BITMAP_FREE (inv_exprs);
3472 return;
3475 if (data->consider_all_candidates)
3477 group->cost_map[cand->id].cand = cand;
3478 group->cost_map[cand->id].cost = cost;
3479 group->cost_map[cand->id].inv_vars = inv_vars;
3480 group->cost_map[cand->id].inv_exprs = inv_exprs;
3481 group->cost_map[cand->id].value = value;
3482 group->cost_map[cand->id].comp = comp;
3483 return;
3486 /* n_map_members is a power of two, so this computes modulo. */
3487 s = cand->id & (group->n_map_members - 1);
3488 for (i = s; i < group->n_map_members; i++)
3489 if (!group->cost_map[i].cand)
3490 goto found;
3491 for (i = 0; i < s; i++)
3492 if (!group->cost_map[i].cand)
3493 goto found;
3495 gcc_unreachable ();
3497 found:
3498 group->cost_map[i].cand = cand;
3499 group->cost_map[i].cost = cost;
3500 group->cost_map[i].inv_vars = inv_vars;
3501 group->cost_map[i].inv_exprs = inv_exprs;
3502 group->cost_map[i].value = value;
3503 group->cost_map[i].comp = comp;
3506 /* Gets cost of (GROUP, CAND) pair. */
3508 static struct cost_pair *
3509 get_group_iv_cost (struct ivopts_data *data, struct iv_group *group,
3510 struct iv_cand *cand)
3512 unsigned i, s;
3513 struct cost_pair *ret;
3515 if (!cand)
3516 return NULL;
3518 if (data->consider_all_candidates)
3520 ret = group->cost_map + cand->id;
3521 if (!ret->cand)
3522 return NULL;
3524 return ret;
3527 /* n_map_members is a power of two, so this computes modulo. */
3528 s = cand->id & (group->n_map_members - 1);
3529 for (i = s; i < group->n_map_members; i++)
3530 if (group->cost_map[i].cand == cand)
3531 return group->cost_map + i;
3532 else if (group->cost_map[i].cand == NULL)
3533 return NULL;
3534 for (i = 0; i < s; i++)
3535 if (group->cost_map[i].cand == cand)
3536 return group->cost_map + i;
3537 else if (group->cost_map[i].cand == NULL)
3538 return NULL;
3540 return NULL;
3543 /* Produce DECL_RTL for object obj so it looks like it is stored in memory. */
3544 static rtx
3545 produce_memory_decl_rtl (tree obj, int *regno)
3547 addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (obj));
3548 machine_mode address_mode = targetm.addr_space.address_mode (as);
3549 rtx x;
3551 gcc_assert (obj);
3552 if (TREE_STATIC (obj) || DECL_EXTERNAL (obj))
3554 const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
3555 x = gen_rtx_SYMBOL_REF (address_mode, name);
3556 SET_SYMBOL_REF_DECL (x, obj);
3557 x = gen_rtx_MEM (DECL_MODE (obj), x);
3558 set_mem_addr_space (x, as);
3559 targetm.encode_section_info (obj, x, true);
3561 else
3563 x = gen_raw_REG (address_mode, (*regno)++);
3564 x = gen_rtx_MEM (DECL_MODE (obj), x);
3565 set_mem_addr_space (x, as);
3568 return x;
3571 /* Prepares decl_rtl for variables referred in *EXPR_P. Callback for
3572 walk_tree. DATA contains the actual fake register number. */
3574 static tree
3575 prepare_decl_rtl (tree *expr_p, int *ws, void *data)
3577 tree obj = NULL_TREE;
3578 rtx x = NULL_RTX;
3579 int *regno = (int *) data;
3581 switch (TREE_CODE (*expr_p))
3583 case ADDR_EXPR:
3584 for (expr_p = &TREE_OPERAND (*expr_p, 0);
3585 handled_component_p (*expr_p);
3586 expr_p = &TREE_OPERAND (*expr_p, 0))
3587 continue;
3588 obj = *expr_p;
3589 if (DECL_P (obj) && HAS_RTL_P (obj) && !DECL_RTL_SET_P (obj))
3590 x = produce_memory_decl_rtl (obj, regno);
3591 break;
3593 case SSA_NAME:
3594 *ws = 0;
3595 obj = SSA_NAME_VAR (*expr_p);
3596 /* Defer handling of anonymous SSA_NAMEs to the expander. */
3597 if (!obj)
3598 return NULL_TREE;
3599 if (!DECL_RTL_SET_P (obj))
3600 x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
3601 break;
3603 case VAR_DECL:
3604 case PARM_DECL:
3605 case RESULT_DECL:
3606 *ws = 0;
3607 obj = *expr_p;
3609 if (DECL_RTL_SET_P (obj))
3610 break;
3612 if (DECL_MODE (obj) == BLKmode)
3613 x = produce_memory_decl_rtl (obj, regno);
3614 else
3615 x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
3617 break;
3619 default:
3620 break;
3623 if (x)
3625 decl_rtl_to_reset.safe_push (obj);
3626 SET_DECL_RTL (obj, x);
3629 return NULL_TREE;
3632 /* Determines cost of the computation of EXPR. */
3634 static unsigned
3635 computation_cost (tree expr, bool speed)
3637 rtx_insn *seq;
3638 rtx rslt;
3639 tree type = TREE_TYPE (expr);
3640 unsigned cost;
3641 /* Avoid using hard regs in ways which may be unsupported. */
3642 int regno = LAST_VIRTUAL_REGISTER + 1;
3643 struct cgraph_node *node = cgraph_node::get (current_function_decl);
3644 enum node_frequency real_frequency = node->frequency;
3646 node->frequency = NODE_FREQUENCY_NORMAL;
3647 crtl->maybe_hot_insn_p = speed;
3648 walk_tree (&expr, prepare_decl_rtl, &regno, NULL);
3649 start_sequence ();
3650 rslt = expand_expr (expr, NULL_RTX, TYPE_MODE (type), EXPAND_NORMAL);
3651 seq = get_insns ();
3652 end_sequence ();
3653 default_rtl_profile ();
3654 node->frequency = real_frequency;
3656 cost = seq_cost (seq, speed);
3657 if (MEM_P (rslt))
3658 cost += address_cost (XEXP (rslt, 0), TYPE_MODE (type),
3659 TYPE_ADDR_SPACE (type), speed);
3660 else if (!REG_P (rslt))
3661 cost += set_src_cost (rslt, TYPE_MODE (type), speed);
3663 return cost;
3666 /* Returns variable containing the value of candidate CAND at statement AT. */
3668 static tree
3669 var_at_stmt (struct loop *loop, struct iv_cand *cand, gimple *stmt)
3671 if (stmt_after_increment (loop, cand, stmt))
3672 return cand->var_after;
3673 else
3674 return cand->var_before;
3677 /* If A is (TYPE) BA and B is (TYPE) BB, and the types of BA and BB have the
3678 same precision that is at least as wide as the precision of TYPE, stores
3679 BA to A and BB to B, and returns the type of BA. Otherwise, returns the
3680 type of A and B. */
3682 static tree
3683 determine_common_wider_type (tree *a, tree *b)
3685 tree wider_type = NULL;
3686 tree suba, subb;
3687 tree atype = TREE_TYPE (*a);
3689 if (CONVERT_EXPR_P (*a))
3691 suba = TREE_OPERAND (*a, 0);
3692 wider_type = TREE_TYPE (suba);
3693 if (TYPE_PRECISION (wider_type) < TYPE_PRECISION (atype))
3694 return atype;
3696 else
3697 return atype;
3699 if (CONVERT_EXPR_P (*b))
3701 subb = TREE_OPERAND (*b, 0);
3702 if (TYPE_PRECISION (wider_type) != TYPE_PRECISION (TREE_TYPE (subb)))
3703 return atype;
3705 else
3706 return atype;
3708 *a = suba;
3709 *b = subb;
3710 return wider_type;
3713 /* Determines the expression by that USE is expressed from induction variable
3714 CAND at statement AT in LOOP. The expression is stored in a decomposed
3715 form into AFF. Returns false if USE cannot be expressed using CAND. */
3717 static bool
3718 get_computation_aff (struct loop *loop,
3719 struct iv_use *use, struct iv_cand *cand, gimple *at,
3720 struct aff_tree *aff)
3722 tree ubase = use->iv->base;
3723 tree ustep = use->iv->step;
3724 tree cbase = cand->iv->base;
3725 tree cstep = cand->iv->step, cstep_common;
3726 tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
3727 tree common_type, var;
3728 tree uutype;
3729 aff_tree cbase_aff, var_aff;
3730 widest_int rat;
3732 if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
3734 /* We do not have a precision to express the values of use. */
3735 return false;
3738 var = var_at_stmt (loop, cand, at);
3739 uutype = unsigned_type_for (utype);
3741 /* If the conversion is not noop, perform it. */
3742 if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
3744 if (cand->orig_iv != NULL && CONVERT_EXPR_P (cbase)
3745 && (CONVERT_EXPR_P (cstep) || TREE_CODE (cstep) == INTEGER_CST))
3747 tree inner_base, inner_step, inner_type;
3748 inner_base = TREE_OPERAND (cbase, 0);
3749 if (CONVERT_EXPR_P (cstep))
3750 inner_step = TREE_OPERAND (cstep, 0);
3751 else
3752 inner_step = cstep;
3754 inner_type = TREE_TYPE (inner_base);
3755 /* If candidate is added from a biv whose type is smaller than
3756 ctype, we know both candidate and the biv won't overflow.
3757 In this case, it's safe to skip the convertion in candidate.
3758 As an example, (unsigned short)((unsigned long)A) equals to
3759 (unsigned short)A, if A has a type no larger than short. */
3760 if (TYPE_PRECISION (inner_type) <= TYPE_PRECISION (uutype))
3762 cbase = inner_base;
3763 cstep = inner_step;
3766 cstep = fold_convert (uutype, cstep);
3767 cbase = fold_convert (uutype, cbase);
3768 var = fold_convert (uutype, var);
3771 /* Ratio is 1 when computing the value of biv cand by itself.
3772 We can't rely on constant_multiple_of in this case because the
3773 use is created after the original biv is selected. The call
3774 could fail because of inconsistent fold behavior. See PR68021
3775 for more information. */
3776 if (cand->pos == IP_ORIGINAL && cand->incremented_at == use->stmt)
3778 gcc_assert (is_gimple_assign (use->stmt));
3779 gcc_assert (use->iv->ssa_name == cand->var_after);
3780 gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
3781 rat = 1;
3783 else if (!constant_multiple_of (ustep, cstep, &rat))
3784 return false;
3786 /* In case both UBASE and CBASE are shortened to UUTYPE from some common
3787 type, we achieve better folding by computing their difference in this
3788 wider type, and cast the result to UUTYPE. We do not need to worry about
3789 overflows, as all the arithmetics will in the end be performed in UUTYPE
3790 anyway. */
3791 common_type = determine_common_wider_type (&ubase, &cbase);
3793 /* use = ubase - ratio * cbase + ratio * var. */
3794 tree_to_aff_combination (ubase, common_type, aff);
3795 tree_to_aff_combination (cbase, common_type, &cbase_aff);
3796 tree_to_aff_combination (var, uutype, &var_aff);
3798 /* We need to shift the value if we are after the increment. */
3799 if (stmt_after_increment (loop, cand, at))
3801 aff_tree cstep_aff;
3803 if (common_type != uutype)
3804 cstep_common = fold_convert (common_type, cstep);
3805 else
3806 cstep_common = cstep;
3808 tree_to_aff_combination (cstep_common, common_type, &cstep_aff);
3809 aff_combination_add (&cbase_aff, &cstep_aff);
3812 aff_combination_scale (&cbase_aff, -rat);
3813 aff_combination_add (aff, &cbase_aff);
3814 if (common_type != uutype)
3815 aff_combination_convert (aff, uutype);
3817 aff_combination_scale (&var_aff, rat);
3818 aff_combination_add (aff, &var_aff);
3820 return true;
3823 /* Return the type of USE. */
3825 static tree
3826 get_use_type (struct iv_use *use)
3828 tree base_type = TREE_TYPE (use->iv->base);
3829 tree type;
3831 if (use->type == USE_ADDRESS)
3833 /* The base_type may be a void pointer. Create a pointer type based on
3834 the mem_ref instead. */
3835 type = build_pointer_type (TREE_TYPE (*use->op_p));
3836 gcc_assert (TYPE_ADDR_SPACE (TREE_TYPE (type))
3837 == TYPE_ADDR_SPACE (TREE_TYPE (base_type)));
3839 else
3840 type = base_type;
3842 return type;
3845 /* Determines the expression by that USE is expressed from induction variable
3846 CAND at statement AT in LOOP. The computation is unshared. */
3848 static tree
3849 get_computation_at (struct loop *loop, gimple *at,
3850 struct iv_use *use, struct iv_cand *cand)
3852 aff_tree aff;
3853 tree type = get_use_type (use);
3855 if (!get_computation_aff (loop, use, cand, at, &aff))
3856 return NULL_TREE;
3857 unshare_aff_combination (&aff);
3858 return fold_convert (type, aff_combination_to_tree (&aff));
3861 /* Adjust the cost COST for being in loop setup rather than loop body.
3862 If we're optimizing for space, the loop setup overhead is constant;
3863 if we're optimizing for speed, amortize it over the per-iteration cost. */
3864 static unsigned
3865 adjust_setup_cost (struct ivopts_data *data, unsigned cost)
3867 if (cost == INFTY)
3868 return cost;
3869 else if (optimize_loop_for_speed_p (data->current_loop))
3870 return cost / avg_loop_niter (data->current_loop);
3871 else
3872 return cost;
3875 /* Returns true if multiplying by RATIO is allowed in an address. Test the
3876 validity for a memory reference accessing memory of mode MODE in
3877 address space AS. */
3880 bool
3881 multiplier_allowed_in_address_p (HOST_WIDE_INT ratio, machine_mode mode,
3882 addr_space_t as)
3884 #define MAX_RATIO 128
3885 unsigned int data_index = (int) as * MAX_MACHINE_MODE + (int) mode;
3886 static vec<sbitmap> valid_mult_list;
3887 sbitmap valid_mult;
3889 if (data_index >= valid_mult_list.length ())
3890 valid_mult_list.safe_grow_cleared (data_index + 1);
3892 valid_mult = valid_mult_list[data_index];
3893 if (!valid_mult)
3895 machine_mode address_mode = targetm.addr_space.address_mode (as);
3896 rtx reg1 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 1);
3897 rtx reg2 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 2);
3898 rtx addr, scaled;
3899 HOST_WIDE_INT i;
3901 valid_mult = sbitmap_alloc (2 * MAX_RATIO + 1);
3902 bitmap_clear (valid_mult);
3903 scaled = gen_rtx_fmt_ee (MULT, address_mode, reg1, NULL_RTX);
3904 addr = gen_rtx_fmt_ee (PLUS, address_mode, scaled, reg2);
3905 for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
3907 XEXP (scaled, 1) = gen_int_mode (i, address_mode);
3908 if (memory_address_addr_space_p (mode, addr, as)
3909 || memory_address_addr_space_p (mode, scaled, as))
3910 bitmap_set_bit (valid_mult, i + MAX_RATIO);
3913 if (dump_file && (dump_flags & TDF_DETAILS))
3915 fprintf (dump_file, " allowed multipliers:");
3916 for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
3917 if (bitmap_bit_p (valid_mult, i + MAX_RATIO))
3918 fprintf (dump_file, " %d", (int) i);
3919 fprintf (dump_file, "\n");
3920 fprintf (dump_file, "\n");
3923 valid_mult_list[data_index] = valid_mult;
3926 if (ratio > MAX_RATIO || ratio < -MAX_RATIO)
3927 return false;
3929 return bitmap_bit_p (valid_mult, ratio + MAX_RATIO);
3932 /* Returns cost of address in shape symbol + var + OFFSET + RATIO * index.
3933 If SYMBOL_PRESENT is false, symbol is omitted. If VAR_PRESENT is false,
3934 variable is omitted. Compute the cost for a memory reference that accesses
3935 a memory location of mode MEM_MODE in address space AS.
3937 MAY_AUTOINC is set to true if the autoincrement (increasing index by
3938 size of MEM_MODE / RATIO) is available. To make this determination, we
3939 look at the size of the increment to be made, which is given in CSTEP.
3940 CSTEP may be zero if the step is unknown.
3941 STMT_AFTER_INC is true iff the statement we're looking at is after the
3942 increment of the original biv.
3944 TODO -- there must be some better way. This all is quite crude. */
3946 enum ainc_type
3948 AINC_PRE_INC, /* Pre increment. */
3949 AINC_PRE_DEC, /* Pre decrement. */
3950 AINC_POST_INC, /* Post increment. */
3951 AINC_POST_DEC, /* Post decrement. */
3952 AINC_NONE /* Also the number of auto increment types. */
3955 struct address_cost_data
3957 HOST_WIDE_INT min_offset, max_offset;
3958 unsigned costs[2][2][2][2];
3959 unsigned ainc_costs[AINC_NONE];
3963 static comp_cost
3964 get_address_cost (bool symbol_present, bool var_present,
3965 unsigned HOST_WIDE_INT offset, HOST_WIDE_INT ratio,
3966 HOST_WIDE_INT cstep, machine_mode mem_mode,
3967 addr_space_t as, bool speed,
3968 bool stmt_after_inc, bool *may_autoinc)
3970 machine_mode address_mode = targetm.addr_space.address_mode (as);
3971 static vec<address_cost_data *> address_cost_data_list;
3972 unsigned int data_index = (int) as * MAX_MACHINE_MODE + (int) mem_mode;
3973 address_cost_data *data;
3974 static bool has_preinc[MAX_MACHINE_MODE], has_postinc[MAX_MACHINE_MODE];
3975 static bool has_predec[MAX_MACHINE_MODE], has_postdec[MAX_MACHINE_MODE];
3976 unsigned cost, acost, complexity;
3977 enum ainc_type autoinc_type;
3978 bool offset_p, ratio_p, autoinc;
3979 HOST_WIDE_INT s_offset, autoinc_offset, msize;
3980 unsigned HOST_WIDE_INT mask;
3981 unsigned bits;
3983 if (data_index >= address_cost_data_list.length ())
3984 address_cost_data_list.safe_grow_cleared (data_index + 1);
3986 data = address_cost_data_list[data_index];
3987 if (!data)
3989 HOST_WIDE_INT i;
3990 HOST_WIDE_INT rat, off = 0;
3991 int old_cse_not_expected, width;
3992 unsigned sym_p, var_p, off_p, rat_p, add_c;
3993 rtx_insn *seq;
3994 rtx addr, base;
3995 rtx reg0, reg1;
3997 data = (address_cost_data *) xcalloc (1, sizeof (*data));
3999 reg1 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 1);
4001 width = GET_MODE_BITSIZE (address_mode) - 1;
4002 if (width > (HOST_BITS_PER_WIDE_INT - 1))
4003 width = HOST_BITS_PER_WIDE_INT - 1;
4004 addr = gen_rtx_fmt_ee (PLUS, address_mode, reg1, NULL_RTX);
4006 for (i = width; i >= 0; i--)
4008 off = -(HOST_WIDE_INT_1U << i);
4009 XEXP (addr, 1) = gen_int_mode (off, address_mode);
4010 if (memory_address_addr_space_p (mem_mode, addr, as))
4011 break;
4013 data->min_offset = (i == -1? 0 : off);
4015 for (i = width; i >= 0; i--)
4017 off = (HOST_WIDE_INT_1U << i) - 1;
4018 XEXP (addr, 1) = gen_int_mode (off, address_mode);
4019 if (memory_address_addr_space_p (mem_mode, addr, as))
4020 break;
4021 /* For some strict-alignment targets, the offset must be naturally
4022 aligned. Try an aligned offset if mem_mode is not QImode. */
4023 off = mem_mode != QImode
4024 ? (HOST_WIDE_INT_1U << i)
4025 - GET_MODE_SIZE (mem_mode)
4026 : 0;
4027 if (off > 0)
4029 XEXP (addr, 1) = gen_int_mode (off, address_mode);
4030 if (memory_address_addr_space_p (mem_mode, addr, as))
4031 break;
4034 if (i == -1)
4035 off = 0;
4036 data->max_offset = off;
4038 if (dump_file && (dump_flags & TDF_DETAILS))
4040 fprintf (dump_file, "get_address_cost:\n");
4041 fprintf (dump_file, " min offset %s " HOST_WIDE_INT_PRINT_DEC "\n",
4042 GET_MODE_NAME (mem_mode),
4043 data->min_offset);
4044 fprintf (dump_file, " max offset %s " HOST_WIDE_INT_PRINT_DEC "\n",
4045 GET_MODE_NAME (mem_mode),
4046 data->max_offset);
4049 rat = 1;
4050 for (i = 2; i <= MAX_RATIO; i++)
4051 if (multiplier_allowed_in_address_p (i, mem_mode, as))
4053 rat = i;
4054 break;
4057 /* Compute the cost of various addressing modes. */
4058 acost = 0;
4059 reg0 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 1);
4060 reg1 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 2);
4062 if (USE_LOAD_PRE_DECREMENT (mem_mode)
4063 || USE_STORE_PRE_DECREMENT (mem_mode))
4065 addr = gen_rtx_PRE_DEC (address_mode, reg0);
4066 has_predec[mem_mode]
4067 = memory_address_addr_space_p (mem_mode, addr, as);
4069 if (has_predec[mem_mode])
4070 data->ainc_costs[AINC_PRE_DEC]
4071 = address_cost (addr, mem_mode, as, speed);
4073 if (USE_LOAD_POST_DECREMENT (mem_mode)
4074 || USE_STORE_POST_DECREMENT (mem_mode))
4076 addr = gen_rtx_POST_DEC (address_mode, reg0);
4077 has_postdec[mem_mode]
4078 = memory_address_addr_space_p (mem_mode, addr, as);
4080 if (has_postdec[mem_mode])
4081 data->ainc_costs[AINC_POST_DEC]
4082 = address_cost (addr, mem_mode, as, speed);
4084 if (USE_LOAD_PRE_INCREMENT (mem_mode)
4085 || USE_STORE_PRE_DECREMENT (mem_mode))
4087 addr = gen_rtx_PRE_INC (address_mode, reg0);
4088 has_preinc[mem_mode]
4089 = memory_address_addr_space_p (mem_mode, addr, as);
4091 if (has_preinc[mem_mode])
4092 data->ainc_costs[AINC_PRE_INC]
4093 = address_cost (addr, mem_mode, as, speed);
4095 if (USE_LOAD_POST_INCREMENT (mem_mode)
4096 || USE_STORE_POST_INCREMENT (mem_mode))
4098 addr = gen_rtx_POST_INC (address_mode, reg0);
4099 has_postinc[mem_mode]
4100 = memory_address_addr_space_p (mem_mode, addr, as);
4102 if (has_postinc[mem_mode])
4103 data->ainc_costs[AINC_POST_INC]
4104 = address_cost (addr, mem_mode, as, speed);
4106 for (i = 0; i < 16; i++)
4108 sym_p = i & 1;
4109 var_p = (i >> 1) & 1;
4110 off_p = (i >> 2) & 1;
4111 rat_p = (i >> 3) & 1;
4113 addr = reg0;
4114 if (rat_p)
4115 addr = gen_rtx_fmt_ee (MULT, address_mode, addr,
4116 gen_int_mode (rat, address_mode));
4118 if (var_p)
4119 addr = gen_rtx_fmt_ee (PLUS, address_mode, addr, reg1);
4121 if (sym_p)
4123 base = gen_rtx_SYMBOL_REF (address_mode, ggc_strdup (""));
4124 /* ??? We can run into trouble with some backends by presenting
4125 it with symbols which haven't been properly passed through
4126 targetm.encode_section_info. By setting the local bit, we
4127 enhance the probability of things working. */
4128 SYMBOL_REF_FLAGS (base) = SYMBOL_FLAG_LOCAL;
4130 if (off_p)
4131 base = gen_rtx_fmt_e (CONST, address_mode,
4132 gen_rtx_fmt_ee
4133 (PLUS, address_mode, base,
4134 gen_int_mode (off, address_mode)));
4136 else if (off_p)
4137 base = gen_int_mode (off, address_mode);
4138 else
4139 base = NULL_RTX;
4141 if (base)
4142 addr = gen_rtx_fmt_ee (PLUS, address_mode, addr, base);
4144 start_sequence ();
4145 /* To avoid splitting addressing modes, pretend that no cse will
4146 follow. */
4147 old_cse_not_expected = cse_not_expected;
4148 cse_not_expected = true;
4149 addr = memory_address_addr_space (mem_mode, addr, as);
4150 cse_not_expected = old_cse_not_expected;
4151 seq = get_insns ();
4152 end_sequence ();
4154 acost = seq_cost (seq, speed);
4155 acost += address_cost (addr, mem_mode, as, speed);
4157 if (!acost)
4158 acost = 1;
4159 data->costs[sym_p][var_p][off_p][rat_p] = acost;
4162 /* On some targets, it is quite expensive to load symbol to a register,
4163 which makes addresses that contain symbols look much more expensive.
4164 However, the symbol will have to be loaded in any case before the
4165 loop (and quite likely we have it in register already), so it does not
4166 make much sense to penalize them too heavily. So make some final
4167 tweaks for the SYMBOL_PRESENT modes:
4169 If VAR_PRESENT is false, and the mode obtained by changing symbol to
4170 var is cheaper, use this mode with small penalty.
4171 If VAR_PRESENT is true, try whether the mode with
4172 SYMBOL_PRESENT = false is cheaper even with cost of addition, and
4173 if this is the case, use it. */
4174 add_c = add_cost (speed, address_mode);
4175 for (i = 0; i < 8; i++)
4177 var_p = i & 1;
4178 off_p = (i >> 1) & 1;
4179 rat_p = (i >> 2) & 1;
4181 acost = data->costs[0][1][off_p][rat_p] + 1;
4182 if (var_p)
4183 acost += add_c;
4185 if (acost < data->costs[1][var_p][off_p][rat_p])
4186 data->costs[1][var_p][off_p][rat_p] = acost;
4189 if (dump_file && (dump_flags & TDF_DETAILS))
4191 fprintf (dump_file, "<Address Costs>:\n");
4193 for (i = 0; i < 16; i++)
4195 sym_p = i & 1;
4196 var_p = (i >> 1) & 1;
4197 off_p = (i >> 2) & 1;
4198 rat_p = (i >> 3) & 1;
4200 fprintf (dump_file, " ");
4201 if (sym_p)
4202 fprintf (dump_file, "sym + ");
4203 if (var_p)
4204 fprintf (dump_file, "var + ");
4205 if (off_p)
4206 fprintf (dump_file, "cst + ");
4207 if (rat_p)
4208 fprintf (dump_file, "rat * ");
4210 acost = data->costs[sym_p][var_p][off_p][rat_p];
4211 fprintf (dump_file, "index costs %d\n", acost);
4213 if (has_predec[mem_mode] || has_postdec[mem_mode]
4214 || has_preinc[mem_mode] || has_postinc[mem_mode])
4215 fprintf (dump_file, " May include autoinc/dec\n");
4216 fprintf (dump_file, "\n");
4219 address_cost_data_list[data_index] = data;
4222 bits = GET_MODE_BITSIZE (address_mode);
4223 mask = ~(HOST_WIDE_INT_M1U << (bits - 1) << 1);
4224 offset &= mask;
4225 if ((offset >> (bits - 1) & 1))
4226 offset |= ~mask;
4227 s_offset = offset;
4229 autoinc = false;
4230 autoinc_type = AINC_NONE;
4231 msize = GET_MODE_SIZE (mem_mode);
4232 autoinc_offset = offset;
4233 if (stmt_after_inc)
4234 autoinc_offset += ratio * cstep;
4235 if (symbol_present || var_present || ratio != 1)
4236 autoinc = false;
4237 else
4239 if (has_postinc[mem_mode] && autoinc_offset == 0
4240 && msize == cstep)
4241 autoinc_type = AINC_POST_INC;
4242 else if (has_postdec[mem_mode] && autoinc_offset == 0
4243 && msize == -cstep)
4244 autoinc_type = AINC_POST_DEC;
4245 else if (has_preinc[mem_mode] && autoinc_offset == msize
4246 && msize == cstep)
4247 autoinc_type = AINC_PRE_INC;
4248 else if (has_predec[mem_mode] && autoinc_offset == -msize
4249 && msize == -cstep)
4250 autoinc_type = AINC_PRE_DEC;
4252 if (autoinc_type != AINC_NONE)
4253 autoinc = true;
4256 cost = 0;
4257 offset_p = (s_offset != 0
4258 && data->min_offset <= s_offset
4259 && s_offset <= data->max_offset);
4260 ratio_p = (ratio != 1
4261 && multiplier_allowed_in_address_p (ratio, mem_mode, as));
4263 if (ratio != 1 && !ratio_p)
4264 cost += mult_by_coeff_cost (ratio, address_mode, speed);
4266 if (s_offset && !offset_p && !symbol_present)
4267 cost += add_cost (speed, address_mode);
4269 if (may_autoinc)
4270 *may_autoinc = autoinc;
4271 if (autoinc)
4272 acost = data->ainc_costs[autoinc_type];
4273 else
4274 acost = data->costs[symbol_present][var_present][offset_p][ratio_p];
4275 complexity = (symbol_present != 0) + (var_present != 0) + offset_p + ratio_p;
4276 return comp_cost (cost + acost, complexity);
4279 /* Calculate the SPEED or size cost of shiftadd EXPR in MODE. MULT is the
4280 EXPR operand holding the shift. COST0 and COST1 are the costs for
4281 calculating the operands of EXPR. Returns true if successful, and returns
4282 the cost in COST. */
4284 static bool
4285 get_shiftadd_cost (tree expr, machine_mode mode, comp_cost cost0,
4286 comp_cost cost1, tree mult, bool speed, comp_cost *cost)
4288 comp_cost res;
4289 tree op1 = TREE_OPERAND (expr, 1);
4290 tree cst = TREE_OPERAND (mult, 1);
4291 tree multop = TREE_OPERAND (mult, 0);
4292 int m = exact_log2 (int_cst_value (cst));
4293 int maxm = MIN (BITS_PER_WORD, GET_MODE_BITSIZE (mode));
4294 int as_cost, sa_cost;
4295 bool mult_in_op1;
4297 if (!(m >= 0 && m < maxm))
4298 return false;
4300 STRIP_NOPS (op1);
4301 mult_in_op1 = operand_equal_p (op1, mult, 0);
4303 as_cost = add_cost (speed, mode) + shift_cost (speed, mode, m);
4305 /* If the target has a cheap shift-and-add or shift-and-sub instruction,
4306 use that in preference to a shift insn followed by an add insn. */
4307 sa_cost = (TREE_CODE (expr) != MINUS_EXPR
4308 ? shiftadd_cost (speed, mode, m)
4309 : (mult_in_op1
4310 ? shiftsub1_cost (speed, mode, m)
4311 : shiftsub0_cost (speed, mode, m)));
4313 res = comp_cost (MIN (as_cost, sa_cost), 0);
4314 res += (mult_in_op1 ? cost0 : cost1);
4316 STRIP_NOPS (multop);
4317 if (!is_gimple_val (multop))
4318 res += force_expr_to_var_cost (multop, speed);
4320 *cost = res;
4321 return true;
4324 /* Estimates cost of forcing expression EXPR into a variable. */
4326 static comp_cost
4327 force_expr_to_var_cost (tree expr, bool speed)
4329 static bool costs_initialized = false;
4330 static unsigned integer_cost [2];
4331 static unsigned symbol_cost [2];
4332 static unsigned address_cost [2];
4333 tree op0, op1;
4334 comp_cost cost0, cost1, cost;
4335 machine_mode mode;
4337 if (!costs_initialized)
4339 tree type = build_pointer_type (integer_type_node);
4340 tree var, addr;
4341 rtx x;
4342 int i;
4344 var = create_tmp_var_raw (integer_type_node, "test_var");
4345 TREE_STATIC (var) = 1;
4346 x = produce_memory_decl_rtl (var, NULL);
4347 SET_DECL_RTL (var, x);
4349 addr = build1 (ADDR_EXPR, type, var);
4352 for (i = 0; i < 2; i++)
4354 integer_cost[i] = computation_cost (build_int_cst (integer_type_node,
4355 2000), i);
4357 symbol_cost[i] = computation_cost (addr, i) + 1;
4359 address_cost[i]
4360 = computation_cost (fold_build_pointer_plus_hwi (addr, 2000), i) + 1;
4361 if (dump_file && (dump_flags & TDF_DETAILS))
4363 fprintf (dump_file, "force_expr_to_var_cost %s costs:\n", i ? "speed" : "size");
4364 fprintf (dump_file, " integer %d\n", (int) integer_cost[i]);
4365 fprintf (dump_file, " symbol %d\n", (int) symbol_cost[i]);
4366 fprintf (dump_file, " address %d\n", (int) address_cost[i]);
4367 fprintf (dump_file, " other %d\n", (int) target_spill_cost[i]);
4368 fprintf (dump_file, "\n");
4372 costs_initialized = true;
4375 STRIP_NOPS (expr);
4377 if (SSA_VAR_P (expr))
4378 return no_cost;
4380 if (is_gimple_min_invariant (expr))
4382 if (TREE_CODE (expr) == INTEGER_CST)
4383 return comp_cost (integer_cost [speed], 0);
4385 if (TREE_CODE (expr) == ADDR_EXPR)
4387 tree obj = TREE_OPERAND (expr, 0);
4389 if (VAR_P (obj)
4390 || TREE_CODE (obj) == PARM_DECL
4391 || TREE_CODE (obj) == RESULT_DECL)
4392 return comp_cost (symbol_cost [speed], 0);
4395 return comp_cost (address_cost [speed], 0);
4398 switch (TREE_CODE (expr))
4400 case POINTER_PLUS_EXPR:
4401 case PLUS_EXPR:
4402 case MINUS_EXPR:
4403 case MULT_EXPR:
4404 op0 = TREE_OPERAND (expr, 0);
4405 op1 = TREE_OPERAND (expr, 1);
4406 STRIP_NOPS (op0);
4407 STRIP_NOPS (op1);
4408 break;
4410 CASE_CONVERT:
4411 case NEGATE_EXPR:
4412 op0 = TREE_OPERAND (expr, 0);
4413 STRIP_NOPS (op0);
4414 op1 = NULL_TREE;
4415 break;
4417 default:
4418 /* Just an arbitrary value, FIXME. */
4419 return comp_cost (target_spill_cost[speed], 0);
4422 if (op0 == NULL_TREE
4423 || TREE_CODE (op0) == SSA_NAME || CONSTANT_CLASS_P (op0))
4424 cost0 = no_cost;
4425 else
4426 cost0 = force_expr_to_var_cost (op0, speed);
4428 if (op1 == NULL_TREE
4429 || TREE_CODE (op1) == SSA_NAME || CONSTANT_CLASS_P (op1))
4430 cost1 = no_cost;
4431 else
4432 cost1 = force_expr_to_var_cost (op1, speed);
4434 mode = TYPE_MODE (TREE_TYPE (expr));
4435 switch (TREE_CODE (expr))
4437 case POINTER_PLUS_EXPR:
4438 case PLUS_EXPR:
4439 case MINUS_EXPR:
4440 case NEGATE_EXPR:
4441 cost = comp_cost (add_cost (speed, mode), 0);
4442 if (TREE_CODE (expr) != NEGATE_EXPR)
4444 tree mult = NULL_TREE;
4445 comp_cost sa_cost;
4446 if (TREE_CODE (op1) == MULT_EXPR)
4447 mult = op1;
4448 else if (TREE_CODE (op0) == MULT_EXPR)
4449 mult = op0;
4451 if (mult != NULL_TREE
4452 && cst_and_fits_in_hwi (TREE_OPERAND (mult, 1))
4453 && get_shiftadd_cost (expr, mode, cost0, cost1, mult,
4454 speed, &sa_cost))
4455 return sa_cost;
4457 break;
4459 CASE_CONVERT:
4461 tree inner_mode, outer_mode;
4462 outer_mode = TREE_TYPE (expr);
4463 inner_mode = TREE_TYPE (op0);
4464 cost = comp_cost (convert_cost (TYPE_MODE (outer_mode),
4465 TYPE_MODE (inner_mode), speed), 0);
4467 break;
4469 case MULT_EXPR:
4470 if (cst_and_fits_in_hwi (op0))
4471 cost = comp_cost (mult_by_coeff_cost (int_cst_value (op0),
4472 mode, speed), 0);
4473 else if (cst_and_fits_in_hwi (op1))
4474 cost = comp_cost (mult_by_coeff_cost (int_cst_value (op1),
4475 mode, speed), 0);
4476 else
4477 return comp_cost (target_spill_cost [speed], 0);
4478 break;
4480 default:
4481 gcc_unreachable ();
4484 cost += cost0;
4485 cost += cost1;
4487 /* Bound the cost by target_spill_cost. The parts of complicated
4488 computations often are either loop invariant or at least can
4489 be shared between several iv uses, so letting this grow without
4490 limits would not give reasonable results. */
4491 if (cost.cost > (int) target_spill_cost [speed])
4492 cost.cost = target_spill_cost [speed];
4494 return cost;
4497 /* Estimates cost of forcing EXPR into a variable. INV_VARS is a set of the
4498 invariants the computation depends on. */
4500 static comp_cost
4501 force_var_cost (struct ivopts_data *data, tree expr, bitmap *inv_vars)
4503 if (!expr)
4504 return no_cost;
4506 find_inv_vars (data, &expr, inv_vars);
4507 return force_expr_to_var_cost (expr, data->speed);
4510 /* Estimates cost of expressing address ADDR as var + symbol + offset. The
4511 value of offset is added to OFFSET, SYMBOL_PRESENT and VAR_PRESENT are set
4512 to false if the corresponding part is missing. inv_vars is a set of the
4513 invariants the computation depends on. */
4515 static comp_cost
4516 split_address_cost (struct ivopts_data *data,
4517 tree addr, bool *symbol_present, bool *var_present,
4518 unsigned HOST_WIDE_INT *offset, bitmap *inv_vars)
4520 tree core;
4521 HOST_WIDE_INT bitsize;
4522 HOST_WIDE_INT bitpos;
4523 tree toffset;
4524 machine_mode mode;
4525 int unsignedp, reversep, volatilep;
4527 core = get_inner_reference (addr, &bitsize, &bitpos, &toffset, &mode,
4528 &unsignedp, &reversep, &volatilep);
4530 if (toffset != 0
4531 || bitpos % BITS_PER_UNIT != 0
4532 || reversep
4533 || !VAR_P (core))
4535 *symbol_present = false;
4536 *var_present = true;
4537 find_inv_vars (data, &addr, inv_vars);
4538 return comp_cost (target_spill_cost[data->speed], 0);
4541 *offset += bitpos / BITS_PER_UNIT;
4542 if (TREE_STATIC (core)
4543 || DECL_EXTERNAL (core))
4545 *symbol_present = true;
4546 *var_present = false;
4547 return no_cost;
4550 *symbol_present = false;
4551 *var_present = true;
4552 return no_cost;
4555 /* Estimates cost of expressing difference of addresses E1 - E2 as
4556 var + symbol + offset. The value of offset is added to OFFSET,
4557 SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
4558 part is missing. inv_vars is a set of the invariants the computation
4559 depends on. */
4561 static comp_cost
4562 ptr_difference_cost (struct ivopts_data *data,
4563 tree e1, tree e2, bool *symbol_present, bool *var_present,
4564 unsigned HOST_WIDE_INT *offset, bitmap *inv_vars)
4566 HOST_WIDE_INT diff = 0;
4567 aff_tree aff_e1, aff_e2;
4568 tree type;
4570 gcc_assert (TREE_CODE (e1) == ADDR_EXPR);
4572 if (ptr_difference_const (e1, e2, &diff))
4574 *offset += diff;
4575 *symbol_present = false;
4576 *var_present = false;
4577 return no_cost;
4580 if (integer_zerop (e2))
4581 return split_address_cost (data, TREE_OPERAND (e1, 0),
4582 symbol_present, var_present, offset, inv_vars);
4584 *symbol_present = false;
4585 *var_present = true;
4587 type = signed_type_for (TREE_TYPE (e1));
4588 tree_to_aff_combination (e1, type, &aff_e1);
4589 tree_to_aff_combination (e2, type, &aff_e2);
4590 aff_combination_scale (&aff_e2, -1);
4591 aff_combination_add (&aff_e1, &aff_e2);
4593 return force_var_cost (data, aff_combination_to_tree (&aff_e1), inv_vars);
4596 /* Estimates cost of expressing difference E1 - E2 as
4597 var + symbol + offset. The value of offset is added to OFFSET,
4598 SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
4599 part is missing. INV_VARS is a set of the invariants the computation
4600 depends on. */
4602 static comp_cost
4603 difference_cost (struct ivopts_data *data,
4604 tree e1, tree e2, bool *symbol_present, bool *var_present,
4605 unsigned HOST_WIDE_INT *offset, bitmap *inv_vars)
4607 machine_mode mode = TYPE_MODE (TREE_TYPE (e1));
4608 unsigned HOST_WIDE_INT off1, off2;
4609 aff_tree aff_e1, aff_e2;
4610 tree type;
4612 e1 = strip_offset (e1, &off1);
4613 e2 = strip_offset (e2, &off2);
4614 *offset += off1 - off2;
4616 STRIP_NOPS (e1);
4617 STRIP_NOPS (e2);
4619 if (TREE_CODE (e1) == ADDR_EXPR)
4620 return ptr_difference_cost (data, e1, e2, symbol_present, var_present,
4621 offset, inv_vars);
4622 *symbol_present = false;
4624 if (operand_equal_p (e1, e2, 0))
4626 *var_present = false;
4627 return no_cost;
4630 *var_present = true;
4632 if (integer_zerop (e2))
4633 return force_var_cost (data, e1, inv_vars);
4635 if (integer_zerop (e1))
4637 comp_cost cost = force_var_cost (data, e2, inv_vars);
4638 cost += mult_by_coeff_cost (-1, mode, data->speed);
4639 return cost;
4642 type = signed_type_for (TREE_TYPE (e1));
4643 tree_to_aff_combination (e1, type, &aff_e1);
4644 tree_to_aff_combination (e2, type, &aff_e2);
4645 aff_combination_scale (&aff_e2, -1);
4646 aff_combination_add (&aff_e1, &aff_e2);
4648 return force_var_cost (data, aff_combination_to_tree (&aff_e1), inv_vars);
4651 /* Returns true if AFF1 and AFF2 are identical. */
4653 static bool
4654 compare_aff_trees (aff_tree *aff1, aff_tree *aff2)
4656 unsigned i;
4658 if (aff1->n != aff2->n)
4659 return false;
4661 for (i = 0; i < aff1->n; i++)
4663 if (aff1->elts[i].coef != aff2->elts[i].coef)
4664 return false;
4666 if (!operand_equal_p (aff1->elts[i].val, aff2->elts[i].val, 0))
4667 return false;
4669 return true;
4672 /* Stores EXPR in DATA->inv_expr_tab, return pointer to iv_inv_expr_ent. */
4674 static iv_inv_expr_ent *
4675 record_inv_expr (struct ivopts_data *data, tree expr)
4677 struct iv_inv_expr_ent ent;
4678 struct iv_inv_expr_ent **slot;
4680 ent.expr = expr;
4681 ent.hash = iterative_hash_expr (expr, 0);
4682 slot = data->inv_expr_tab->find_slot (&ent, INSERT);
4684 if (!*slot)
4686 *slot = XNEW (struct iv_inv_expr_ent);
4687 (*slot)->expr = expr;
4688 (*slot)->hash = ent.hash;
4689 (*slot)->id = data->max_inv_expr_id++;
4692 return *slot;
4695 /* Returns the invariant expression if expression UBASE - RATIO * CBASE
4696 requires a new compiler generated temporary. Returns -1 otherwise.
4697 ADDRESS_P is a flag indicating if the expression is for address
4698 computation. */
4700 static iv_inv_expr_ent *
4701 get_loop_invariant_expr (struct ivopts_data *data, tree ubase,
4702 tree cbase, HOST_WIDE_INT ratio,
4703 bool address_p)
4705 aff_tree ubase_aff, cbase_aff;
4706 tree expr, ub, cb;
4708 STRIP_NOPS (ubase);
4709 STRIP_NOPS (cbase);
4710 ub = ubase;
4711 cb = cbase;
4713 if ((TREE_CODE (ubase) == INTEGER_CST)
4714 && (TREE_CODE (cbase) == INTEGER_CST))
4715 return NULL;
4717 /* Strips the constant part. */
4718 if (TREE_CODE (ubase) == PLUS_EXPR
4719 || TREE_CODE (ubase) == MINUS_EXPR
4720 || TREE_CODE (ubase) == POINTER_PLUS_EXPR)
4722 if (TREE_CODE (TREE_OPERAND (ubase, 1)) == INTEGER_CST)
4723 ubase = TREE_OPERAND (ubase, 0);
4726 /* Strips the constant part. */
4727 if (TREE_CODE (cbase) == PLUS_EXPR
4728 || TREE_CODE (cbase) == MINUS_EXPR
4729 || TREE_CODE (cbase) == POINTER_PLUS_EXPR)
4731 if (TREE_CODE (TREE_OPERAND (cbase, 1)) == INTEGER_CST)
4732 cbase = TREE_OPERAND (cbase, 0);
4735 if (address_p)
4737 if (((TREE_CODE (ubase) == SSA_NAME)
4738 || (TREE_CODE (ubase) == ADDR_EXPR
4739 && is_gimple_min_invariant (ubase)))
4740 && (TREE_CODE (cbase) == INTEGER_CST))
4741 return NULL;
4743 if (((TREE_CODE (cbase) == SSA_NAME)
4744 || (TREE_CODE (cbase) == ADDR_EXPR
4745 && is_gimple_min_invariant (cbase)))
4746 && (TREE_CODE (ubase) == INTEGER_CST))
4747 return NULL;
4750 if (ratio == 1)
4752 if (operand_equal_p (ubase, cbase, 0))
4753 return NULL;
4755 if (TREE_CODE (ubase) == ADDR_EXPR
4756 && TREE_CODE (cbase) == ADDR_EXPR)
4758 tree usym, csym;
4760 usym = TREE_OPERAND (ubase, 0);
4761 csym = TREE_OPERAND (cbase, 0);
4762 if (TREE_CODE (usym) == ARRAY_REF)
4764 tree ind = TREE_OPERAND (usym, 1);
4765 if (TREE_CODE (ind) == INTEGER_CST
4766 && tree_fits_shwi_p (ind)
4767 && tree_to_shwi (ind) == 0)
4768 usym = TREE_OPERAND (usym, 0);
4770 if (TREE_CODE (csym) == ARRAY_REF)
4772 tree ind = TREE_OPERAND (csym, 1);
4773 if (TREE_CODE (ind) == INTEGER_CST
4774 && tree_fits_shwi_p (ind)
4775 && tree_to_shwi (ind) == 0)
4776 csym = TREE_OPERAND (csym, 0);
4778 if (operand_equal_p (usym, csym, 0))
4779 return NULL;
4781 /* Now do more complex comparison */
4782 tree_to_aff_combination (ubase, TREE_TYPE (ubase), &ubase_aff);
4783 tree_to_aff_combination (cbase, TREE_TYPE (cbase), &cbase_aff);
4784 if (compare_aff_trees (&ubase_aff, &cbase_aff))
4785 return NULL;
4788 tree_to_aff_combination (ub, TREE_TYPE (ub), &ubase_aff);
4789 tree_to_aff_combination (cb, TREE_TYPE (cb), &cbase_aff);
4791 aff_combination_scale (&cbase_aff, -1 * ratio);
4792 aff_combination_add (&ubase_aff, &cbase_aff);
4793 expr = aff_combination_to_tree (&ubase_aff);
4794 return record_inv_expr (data, expr);
4797 /* Scale (multiply) the computed COST (except scratch part that should be
4798 hoisted out a loop) by header->frequency / AT->frequency,
4799 which makes expected cost more accurate. */
4801 static comp_cost
4802 get_scaled_computation_cost_at (ivopts_data *data, gimple *at, iv_cand *cand,
4803 comp_cost cost)
4805 int loop_freq = data->current_loop->header->frequency;
4806 int bb_freq = gimple_bb (at)->frequency;
4807 if (loop_freq != 0)
4809 gcc_assert (cost.scratch <= cost.cost);
4810 int scaled_cost
4811 = cost.scratch + (cost.cost - cost.scratch) * bb_freq / loop_freq;
4813 if (dump_file && (dump_flags & TDF_DETAILS))
4814 fprintf (dump_file, "Scaling iv_use based on cand %d "
4815 "by %2.2f: %d (scratch: %d) -> %d (%d/%d)\n",
4816 cand->id, 1.0f * bb_freq / loop_freq, cost.cost,
4817 cost.scratch, scaled_cost, bb_freq, loop_freq);
4819 cost.cost = scaled_cost;
4822 return cost;
4825 /* Determines the cost of the computation by that USE is expressed
4826 from induction variable CAND. If ADDRESS_P is true, we just need
4827 to create an address from it, otherwise we want to get it into
4828 register. A set of invariants we depend on is stored in INV_VARS.
4829 If CAN_AUTOINC is nonnull, use it to record whether autoinc
4830 addressing is likely. If INV_EXPR is nonnull, record invariant
4831 expr entry in it. */
4833 static comp_cost
4834 get_computation_cost (struct ivopts_data *data, struct iv_use *use,
4835 struct iv_cand *cand, bool address_p, bitmap *inv_vars,
4836 bool *can_autoinc, iv_inv_expr_ent **inv_expr)
4838 gimple *at = use->stmt;
4839 tree ubase = use->iv->base, ustep = use->iv->step;
4840 tree cbase, cstep;
4841 tree utype = TREE_TYPE (ubase), ctype;
4842 unsigned HOST_WIDE_INT cstepi, offset = 0;
4843 HOST_WIDE_INT ratio, aratio;
4844 bool var_present, symbol_present, stmt_is_after_inc;
4845 comp_cost cost;
4846 widest_int rat;
4847 bool speed = optimize_bb_for_speed_p (gimple_bb (at));
4848 machine_mode mem_mode = (address_p
4849 ? TYPE_MODE (TREE_TYPE (*use->op_p))
4850 : VOIDmode);
4852 if (inv_vars)
4853 *inv_vars = NULL;
4855 cbase = cand->iv->base;
4856 cstep = cand->iv->step;
4857 ctype = TREE_TYPE (cbase);
4859 if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
4861 /* We do not have a precision to express the values of use. */
4862 return infinite_cost;
4865 if (address_p
4866 || (use->iv->base_object
4867 && cand->iv->base_object
4868 && POINTER_TYPE_P (TREE_TYPE (use->iv->base_object))
4869 && POINTER_TYPE_P (TREE_TYPE (cand->iv->base_object))))
4871 /* Do not try to express address of an object with computation based
4872 on address of a different object. This may cause problems in rtl
4873 level alias analysis (that does not expect this to be happening,
4874 as this is illegal in C), and would be unlikely to be useful
4875 anyway. */
4876 if (use->iv->base_object
4877 && cand->iv->base_object
4878 && !operand_equal_p (use->iv->base_object, cand->iv->base_object, 0))
4879 return infinite_cost;
4882 if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
4884 /* TODO -- add direct handling of this case. */
4885 goto fallback;
4888 /* CSTEPI is removed from the offset in case statement is after the
4889 increment. If the step is not constant, we use zero instead.
4890 This is a bit imprecise (there is the extra addition), but
4891 redundancy elimination is likely to transform the code so that
4892 it uses value of the variable before increment anyway,
4893 so it is not that much unrealistic. */
4894 if (cst_and_fits_in_hwi (cstep))
4895 cstepi = int_cst_value (cstep);
4896 else
4897 cstepi = 0;
4899 if (!constant_multiple_of (ustep, cstep, &rat))
4900 return infinite_cost;
4902 if (wi::fits_shwi_p (rat))
4903 ratio = rat.to_shwi ();
4904 else
4905 return infinite_cost;
4907 STRIP_NOPS (cbase);
4908 ctype = TREE_TYPE (cbase);
4910 stmt_is_after_inc = stmt_after_increment (data->current_loop, cand, at);
4912 /* use = ubase + ratio * (var - cbase). If either cbase is a constant
4913 or ratio == 1, it is better to handle this like
4915 ubase - ratio * cbase + ratio * var
4917 (also holds in the case ratio == -1, TODO. */
4919 if (cst_and_fits_in_hwi (cbase))
4921 offset = - ratio * (unsigned HOST_WIDE_INT) int_cst_value (cbase);
4922 cost = difference_cost (data,
4923 ubase, build_int_cst (utype, 0),
4924 &symbol_present, &var_present, &offset,
4925 inv_vars);
4926 cost /= avg_loop_niter (data->current_loop);
4928 else if (ratio == 1)
4930 tree real_cbase = cbase;
4932 /* Check to see if any adjustment is needed. */
4933 if (cstepi == 0 && stmt_is_after_inc)
4935 aff_tree real_cbase_aff;
4936 aff_tree cstep_aff;
4938 tree_to_aff_combination (cbase, TREE_TYPE (real_cbase),
4939 &real_cbase_aff);
4940 tree_to_aff_combination (cstep, TREE_TYPE (cstep), &cstep_aff);
4942 aff_combination_add (&real_cbase_aff, &cstep_aff);
4943 real_cbase = aff_combination_to_tree (&real_cbase_aff);
4946 cost = difference_cost (data,
4947 ubase, real_cbase,
4948 &symbol_present, &var_present, &offset,
4949 inv_vars);
4950 cost /= avg_loop_niter (data->current_loop);
4952 else if (address_p
4953 && !POINTER_TYPE_P (ctype)
4954 && multiplier_allowed_in_address_p
4955 (ratio, mem_mode,
4956 TYPE_ADDR_SPACE (TREE_TYPE (utype))))
4958 tree real_cbase = cbase;
4960 if (cstepi == 0 && stmt_is_after_inc)
4962 if (POINTER_TYPE_P (ctype))
4963 real_cbase = fold_build2 (POINTER_PLUS_EXPR, ctype, cbase, cstep);
4964 else
4965 real_cbase = fold_build2 (PLUS_EXPR, ctype, cbase, cstep);
4967 real_cbase = fold_build2 (MULT_EXPR, ctype, real_cbase,
4968 build_int_cst (ctype, ratio));
4969 cost = difference_cost (data,
4970 ubase, real_cbase,
4971 &symbol_present, &var_present, &offset,
4972 inv_vars);
4973 cost /= avg_loop_niter (data->current_loop);
4975 else
4977 cost = force_var_cost (data, cbase, inv_vars);
4978 cost += difference_cost (data, ubase, build_int_cst (utype, 0),
4979 &symbol_present, &var_present, &offset,
4980 inv_vars);
4981 cost /= avg_loop_niter (data->current_loop);
4982 cost += add_cost (data->speed, TYPE_MODE (ctype));
4985 /* Record setup cost in scratch field. */
4986 cost.scratch = cost.cost;
4988 if (inv_expr && inv_vars && *inv_vars)
4990 *inv_expr = get_loop_invariant_expr (data, ubase, cbase, ratio,
4991 address_p);
4992 /* Clear depends on. */
4993 if (*inv_expr != NULL)
4994 bitmap_clear (*inv_vars);
4997 /* If we are after the increment, the value of the candidate is higher by
4998 one iteration. */
4999 if (stmt_is_after_inc)
5000 offset -= ratio * cstepi;
5002 /* Now the computation is in shape symbol + var1 + const + ratio * var2.
5003 (symbol/var1/const parts may be omitted). If we are looking for an
5004 address, find the cost of addressing this. */
5005 if (address_p)
5007 cost += get_address_cost (symbol_present, var_present,
5008 offset, ratio, cstepi,
5009 mem_mode,
5010 TYPE_ADDR_SPACE (TREE_TYPE (utype)),
5011 speed, stmt_is_after_inc, can_autoinc);
5012 return get_scaled_computation_cost_at (data, at, cand, cost);
5015 /* Otherwise estimate the costs for computing the expression. */
5016 if (!symbol_present && !var_present && !offset)
5018 if (ratio != 1)
5019 cost += mult_by_coeff_cost (ratio, TYPE_MODE (ctype), speed);
5020 return get_scaled_computation_cost_at (data, at, cand, cost);
5023 /* Symbol + offset should be compile-time computable so consider that they
5024 are added once to the variable, if present. */
5025 if (var_present && (symbol_present || offset))
5026 cost += adjust_setup_cost (data,
5027 add_cost (speed, TYPE_MODE (ctype)));
5029 /* Having offset does not affect runtime cost in case it is added to
5030 symbol, but it increases complexity. */
5031 if (offset)
5032 cost.complexity++;
5034 cost += add_cost (speed, TYPE_MODE (ctype));
5036 aratio = ratio > 0 ? ratio : -ratio;
5037 if (aratio != 1)
5038 cost += mult_by_coeff_cost (aratio, TYPE_MODE (ctype), speed);
5040 return get_scaled_computation_cost_at (data, at, cand, cost);
5042 fallback:
5043 if (can_autoinc)
5044 *can_autoinc = false;
5046 /* Just get the expression, expand it and measure the cost. */
5047 tree comp = get_computation_at (data->current_loop, at, use, cand);
5049 if (!comp)
5050 return infinite_cost;
5052 if (address_p)
5053 comp = build_simple_mem_ref (comp);
5055 cost = comp_cost (computation_cost (comp, speed), 0);
5057 return get_scaled_computation_cost_at (data, at, cand, cost);
5060 /* Determines cost of computing the use in GROUP with CAND in a generic
5061 expression. */
5063 static bool
5064 determine_group_iv_cost_generic (struct ivopts_data *data,
5065 struct iv_group *group, struct iv_cand *cand)
5067 comp_cost cost;
5068 iv_inv_expr_ent *inv_expr = NULL;
5069 bitmap inv_vars = NULL, inv_exprs = NULL;
5070 struct iv_use *use = group->vuses[0];
5072 /* The simple case first -- if we need to express value of the preserved
5073 original biv, the cost is 0. This also prevents us from counting the
5074 cost of increment twice -- once at this use and once in the cost of
5075 the candidate. */
5076 if (cand->pos == IP_ORIGINAL && cand->incremented_at == use->stmt)
5077 cost = no_cost;
5078 else
5079 cost = get_computation_cost (data, use, cand, false,
5080 &inv_vars, NULL, &inv_expr);
5082 if (inv_expr)
5084 inv_exprs = BITMAP_ALLOC (NULL);
5085 bitmap_set_bit (inv_exprs, inv_expr->id);
5087 set_group_iv_cost (data, group, cand, cost, inv_vars,
5088 NULL_TREE, ERROR_MARK, inv_exprs);
5089 return !cost.infinite_cost_p ();
5092 /* Determines cost of computing uses in GROUP with CAND in addresses. */
5094 static bool
5095 determine_group_iv_cost_address (struct ivopts_data *data,
5096 struct iv_group *group, struct iv_cand *cand)
5098 unsigned i;
5099 bitmap inv_vars = NULL, inv_exprs = NULL;
5100 bool can_autoinc;
5101 iv_inv_expr_ent *inv_expr = NULL;
5102 struct iv_use *use = group->vuses[0];
5103 comp_cost sum_cost = no_cost, cost;
5105 cost = get_computation_cost (data, use, cand, true,
5106 &inv_vars, &can_autoinc, &inv_expr);
5108 if (inv_expr)
5110 inv_exprs = BITMAP_ALLOC (NULL);
5111 bitmap_set_bit (inv_exprs, inv_expr->id);
5113 sum_cost = cost;
5114 if (!sum_cost.infinite_cost_p () && cand->ainc_use == use)
5116 if (can_autoinc)
5117 sum_cost -= cand->cost_step;
5118 /* If we generated the candidate solely for exploiting autoincrement
5119 opportunities, and it turns out it can't be used, set the cost to
5120 infinity to make sure we ignore it. */
5121 else if (cand->pos == IP_AFTER_USE || cand->pos == IP_BEFORE_USE)
5122 sum_cost = infinite_cost;
5125 /* Uses in a group can share setup code, so only add setup cost once. */
5126 cost -= cost.scratch;
5127 /* Compute and add costs for rest uses of this group. */
5128 for (i = 1; i < group->vuses.length () && !sum_cost.infinite_cost_p (); i++)
5130 struct iv_use *next = group->vuses[i];
5132 /* TODO: We could skip computing cost for sub iv_use when it has the
5133 same cost as the first iv_use, but the cost really depends on the
5134 offset and where the iv_use is. */
5135 cost = get_computation_cost (data, next, cand, true,
5136 NULL, &can_autoinc, NULL);
5137 sum_cost += cost;
5139 set_group_iv_cost (data, group, cand, sum_cost, inv_vars,
5140 NULL_TREE, ERROR_MARK, inv_exprs);
5142 return !sum_cost.infinite_cost_p ();
5145 /* Computes value of candidate CAND at position AT in iteration NITER, and
5146 stores it to VAL. */
5148 static void
5149 cand_value_at (struct loop *loop, struct iv_cand *cand, gimple *at, tree niter,
5150 aff_tree *val)
5152 aff_tree step, delta, nit;
5153 struct iv *iv = cand->iv;
5154 tree type = TREE_TYPE (iv->base);
5155 tree steptype;
5156 if (POINTER_TYPE_P (type))
5157 steptype = sizetype;
5158 else
5159 steptype = unsigned_type_for (type);
5161 tree_to_aff_combination (iv->step, TREE_TYPE (iv->step), &step);
5162 aff_combination_convert (&step, steptype);
5163 tree_to_aff_combination (niter, TREE_TYPE (niter), &nit);
5164 aff_combination_convert (&nit, steptype);
5165 aff_combination_mult (&nit, &step, &delta);
5166 if (stmt_after_increment (loop, cand, at))
5167 aff_combination_add (&delta, &step);
5169 tree_to_aff_combination (iv->base, type, val);
5170 if (!POINTER_TYPE_P (type))
5171 aff_combination_convert (val, steptype);
5172 aff_combination_add (val, &delta);
5175 /* Returns period of induction variable iv. */
5177 static tree
5178 iv_period (struct iv *iv)
5180 tree step = iv->step, period, type;
5181 tree pow2div;
5183 gcc_assert (step && TREE_CODE (step) == INTEGER_CST);
5185 type = unsigned_type_for (TREE_TYPE (step));
5186 /* Period of the iv is lcm (step, type_range)/step -1,
5187 i.e., N*type_range/step - 1. Since type range is power
5188 of two, N == (step >> num_of_ending_zeros_binary (step),
5189 so the final result is
5191 (type_range >> num_of_ending_zeros_binary (step)) - 1
5194 pow2div = num_ending_zeros (step);
5196 period = build_low_bits_mask (type,
5197 (TYPE_PRECISION (type)
5198 - tree_to_uhwi (pow2div)));
5200 return period;
5203 /* Returns the comparison operator used when eliminating the iv USE. */
5205 static enum tree_code
5206 iv_elimination_compare (struct ivopts_data *data, struct iv_use *use)
5208 struct loop *loop = data->current_loop;
5209 basic_block ex_bb;
5210 edge exit;
5212 ex_bb = gimple_bb (use->stmt);
5213 exit = EDGE_SUCC (ex_bb, 0);
5214 if (flow_bb_inside_loop_p (loop, exit->dest))
5215 exit = EDGE_SUCC (ex_bb, 1);
5217 return (exit->flags & EDGE_TRUE_VALUE ? EQ_EXPR : NE_EXPR);
5220 /* Returns true if we can prove that BASE - OFFSET does not overflow. For now,
5221 we only detect the situation that BASE = SOMETHING + OFFSET, where the
5222 calculation is performed in non-wrapping type.
5224 TODO: More generally, we could test for the situation that
5225 BASE = SOMETHING + OFFSET' and OFFSET is between OFFSET' and zero.
5226 This would require knowing the sign of OFFSET. */
5228 static bool
5229 difference_cannot_overflow_p (struct ivopts_data *data, tree base, tree offset)
5231 enum tree_code code;
5232 tree e1, e2;
5233 aff_tree aff_e1, aff_e2, aff_offset;
5235 if (!nowrap_type_p (TREE_TYPE (base)))
5236 return false;
5238 base = expand_simple_operations (base);
5240 if (TREE_CODE (base) == SSA_NAME)
5242 gimple *stmt = SSA_NAME_DEF_STMT (base);
5244 if (gimple_code (stmt) != GIMPLE_ASSIGN)
5245 return false;
5247 code = gimple_assign_rhs_code (stmt);
5248 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
5249 return false;
5251 e1 = gimple_assign_rhs1 (stmt);
5252 e2 = gimple_assign_rhs2 (stmt);
5254 else
5256 code = TREE_CODE (base);
5257 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
5258 return false;
5259 e1 = TREE_OPERAND (base, 0);
5260 e2 = TREE_OPERAND (base, 1);
5263 /* Use affine expansion as deeper inspection to prove the equality. */
5264 tree_to_aff_combination_expand (e2, TREE_TYPE (e2),
5265 &aff_e2, &data->name_expansion_cache);
5266 tree_to_aff_combination_expand (offset, TREE_TYPE (offset),
5267 &aff_offset, &data->name_expansion_cache);
5268 aff_combination_scale (&aff_offset, -1);
5269 switch (code)
5271 case PLUS_EXPR:
5272 aff_combination_add (&aff_e2, &aff_offset);
5273 if (aff_combination_zero_p (&aff_e2))
5274 return true;
5276 tree_to_aff_combination_expand (e1, TREE_TYPE (e1),
5277 &aff_e1, &data->name_expansion_cache);
5278 aff_combination_add (&aff_e1, &aff_offset);
5279 return aff_combination_zero_p (&aff_e1);
5281 case POINTER_PLUS_EXPR:
5282 aff_combination_add (&aff_e2, &aff_offset);
5283 return aff_combination_zero_p (&aff_e2);
5285 default:
5286 return false;
5290 /* Tries to replace loop exit by one formulated in terms of a LT_EXPR
5291 comparison with CAND. NITER describes the number of iterations of
5292 the loops. If successful, the comparison in COMP_P is altered accordingly.
5294 We aim to handle the following situation:
5296 sometype *base, *p;
5297 int a, b, i;
5299 i = a;
5300 p = p_0 = base + a;
5304 bla (*p);
5305 p++;
5306 i++;
5308 while (i < b);
5310 Here, the number of iterations of the loop is (a + 1 > b) ? 0 : b - a - 1.
5311 We aim to optimize this to
5313 p = p_0 = base + a;
5316 bla (*p);
5317 p++;
5319 while (p < p_0 - a + b);
5321 This preserves the correctness, since the pointer arithmetics does not
5322 overflow. More precisely:
5324 1) if a + 1 <= b, then p_0 - a + b is the final value of p, hence there is no
5325 overflow in computing it or the values of p.
5326 2) if a + 1 > b, then we need to verify that the expression p_0 - a does not
5327 overflow. To prove this, we use the fact that p_0 = base + a. */
5329 static bool
5330 iv_elimination_compare_lt (struct ivopts_data *data,
5331 struct iv_cand *cand, enum tree_code *comp_p,
5332 struct tree_niter_desc *niter)
5334 tree cand_type, a, b, mbz, nit_type = TREE_TYPE (niter->niter), offset;
5335 struct aff_tree nit, tmpa, tmpb;
5336 enum tree_code comp;
5337 HOST_WIDE_INT step;
5339 /* We need to know that the candidate induction variable does not overflow.
5340 While more complex analysis may be used to prove this, for now just
5341 check that the variable appears in the original program and that it
5342 is computed in a type that guarantees no overflows. */
5343 cand_type = TREE_TYPE (cand->iv->base);
5344 if (cand->pos != IP_ORIGINAL || !nowrap_type_p (cand_type))
5345 return false;
5347 /* Make sure that the loop iterates till the loop bound is hit, as otherwise
5348 the calculation of the BOUND could overflow, making the comparison
5349 invalid. */
5350 if (!data->loop_single_exit_p)
5351 return false;
5353 /* We need to be able to decide whether candidate is increasing or decreasing
5354 in order to choose the right comparison operator. */
5355 if (!cst_and_fits_in_hwi (cand->iv->step))
5356 return false;
5357 step = int_cst_value (cand->iv->step);
5359 /* Check that the number of iterations matches the expected pattern:
5360 a + 1 > b ? 0 : b - a - 1. */
5361 mbz = niter->may_be_zero;
5362 if (TREE_CODE (mbz) == GT_EXPR)
5364 /* Handle a + 1 > b. */
5365 tree op0 = TREE_OPERAND (mbz, 0);
5366 if (TREE_CODE (op0) == PLUS_EXPR && integer_onep (TREE_OPERAND (op0, 1)))
5368 a = TREE_OPERAND (op0, 0);
5369 b = TREE_OPERAND (mbz, 1);
5371 else
5372 return false;
5374 else if (TREE_CODE (mbz) == LT_EXPR)
5376 tree op1 = TREE_OPERAND (mbz, 1);
5378 /* Handle b < a + 1. */
5379 if (TREE_CODE (op1) == PLUS_EXPR && integer_onep (TREE_OPERAND (op1, 1)))
5381 a = TREE_OPERAND (op1, 0);
5382 b = TREE_OPERAND (mbz, 0);
5384 else
5385 return false;
5387 else
5388 return false;
5390 /* Expected number of iterations is B - A - 1. Check that it matches
5391 the actual number, i.e., that B - A - NITER = 1. */
5392 tree_to_aff_combination (niter->niter, nit_type, &nit);
5393 tree_to_aff_combination (fold_convert (nit_type, a), nit_type, &tmpa);
5394 tree_to_aff_combination (fold_convert (nit_type, b), nit_type, &tmpb);
5395 aff_combination_scale (&nit, -1);
5396 aff_combination_scale (&tmpa, -1);
5397 aff_combination_add (&tmpb, &tmpa);
5398 aff_combination_add (&tmpb, &nit);
5399 if (tmpb.n != 0 || tmpb.offset != 1)
5400 return false;
5402 /* Finally, check that CAND->IV->BASE - CAND->IV->STEP * A does not
5403 overflow. */
5404 offset = fold_build2 (MULT_EXPR, TREE_TYPE (cand->iv->step),
5405 cand->iv->step,
5406 fold_convert (TREE_TYPE (cand->iv->step), a));
5407 if (!difference_cannot_overflow_p (data, cand->iv->base, offset))
5408 return false;
5410 /* Determine the new comparison operator. */
5411 comp = step < 0 ? GT_EXPR : LT_EXPR;
5412 if (*comp_p == NE_EXPR)
5413 *comp_p = comp;
5414 else if (*comp_p == EQ_EXPR)
5415 *comp_p = invert_tree_comparison (comp, false);
5416 else
5417 gcc_unreachable ();
5419 return true;
5422 /* Check whether it is possible to express the condition in USE by comparison
5423 of candidate CAND. If so, store the value compared with to BOUND, and the
5424 comparison operator to COMP. */
5426 static bool
5427 may_eliminate_iv (struct ivopts_data *data,
5428 struct iv_use *use, struct iv_cand *cand, tree *bound,
5429 enum tree_code *comp)
5431 basic_block ex_bb;
5432 edge exit;
5433 tree period;
5434 struct loop *loop = data->current_loop;
5435 aff_tree bnd;
5436 struct tree_niter_desc *desc = NULL;
5438 if (TREE_CODE (cand->iv->step) != INTEGER_CST)
5439 return false;
5441 /* For now works only for exits that dominate the loop latch.
5442 TODO: extend to other conditions inside loop body. */
5443 ex_bb = gimple_bb (use->stmt);
5444 if (use->stmt != last_stmt (ex_bb)
5445 || gimple_code (use->stmt) != GIMPLE_COND
5446 || !dominated_by_p (CDI_DOMINATORS, loop->latch, ex_bb))
5447 return false;
5449 exit = EDGE_SUCC (ex_bb, 0);
5450 if (flow_bb_inside_loop_p (loop, exit->dest))
5451 exit = EDGE_SUCC (ex_bb, 1);
5452 if (flow_bb_inside_loop_p (loop, exit->dest))
5453 return false;
5455 desc = niter_for_exit (data, exit);
5456 if (!desc)
5457 return false;
5459 /* Determine whether we can use the variable to test the exit condition.
5460 This is the case iff the period of the induction variable is greater
5461 than the number of iterations for which the exit condition is true. */
5462 period = iv_period (cand->iv);
5464 /* If the number of iterations is constant, compare against it directly. */
5465 if (TREE_CODE (desc->niter) == INTEGER_CST)
5467 /* See cand_value_at. */
5468 if (stmt_after_increment (loop, cand, use->stmt))
5470 if (!tree_int_cst_lt (desc->niter, period))
5471 return false;
5473 else
5475 if (tree_int_cst_lt (period, desc->niter))
5476 return false;
5480 /* If not, and if this is the only possible exit of the loop, see whether
5481 we can get a conservative estimate on the number of iterations of the
5482 entire loop and compare against that instead. */
5483 else
5485 widest_int period_value, max_niter;
5487 max_niter = desc->max;
5488 if (stmt_after_increment (loop, cand, use->stmt))
5489 max_niter += 1;
5490 period_value = wi::to_widest (period);
5491 if (wi::gtu_p (max_niter, period_value))
5493 /* See if we can take advantage of inferred loop bound
5494 information. */
5495 if (data->loop_single_exit_p)
5497 if (!max_loop_iterations (loop, &max_niter))
5498 return false;
5499 /* The loop bound is already adjusted by adding 1. */
5500 if (wi::gtu_p (max_niter, period_value))
5501 return false;
5503 else
5504 return false;
5508 cand_value_at (loop, cand, use->stmt, desc->niter, &bnd);
5510 *bound = fold_convert (TREE_TYPE (cand->iv->base),
5511 aff_combination_to_tree (&bnd));
5512 *comp = iv_elimination_compare (data, use);
5514 /* It is unlikely that computing the number of iterations using division
5515 would be more profitable than keeping the original induction variable. */
5516 if (expression_expensive_p (*bound))
5517 return false;
5519 /* Sometimes, it is possible to handle the situation that the number of
5520 iterations may be zero unless additional assumptions by using <
5521 instead of != in the exit condition.
5523 TODO: we could also calculate the value MAY_BE_ZERO ? 0 : NITER and
5524 base the exit condition on it. However, that is often too
5525 expensive. */
5526 if (!integer_zerop (desc->may_be_zero))
5527 return iv_elimination_compare_lt (data, cand, comp, desc);
5529 return true;
5532 /* Calculates the cost of BOUND, if it is a PARM_DECL. A PARM_DECL must
5533 be copied, if it is used in the loop body and DATA->body_includes_call. */
5535 static int
5536 parm_decl_cost (struct ivopts_data *data, tree bound)
5538 tree sbound = bound;
5539 STRIP_NOPS (sbound);
5541 if (TREE_CODE (sbound) == SSA_NAME
5542 && SSA_NAME_IS_DEFAULT_DEF (sbound)
5543 && TREE_CODE (SSA_NAME_VAR (sbound)) == PARM_DECL
5544 && data->body_includes_call)
5545 return COSTS_N_INSNS (1);
5547 return 0;
5550 /* Determines cost of computing the use in GROUP with CAND in a condition. */
5552 static bool
5553 determine_group_iv_cost_cond (struct ivopts_data *data,
5554 struct iv_group *group, struct iv_cand *cand)
5556 tree bound = NULL_TREE;
5557 struct iv *cmp_iv;
5558 bitmap inv_exprs = NULL;
5559 bitmap inv_vars_elim = NULL, inv_vars_express = NULL, inv_vars;
5560 comp_cost elim_cost, express_cost, cost, bound_cost;
5561 bool ok;
5562 iv_inv_expr_ent *inv_expr_elim = NULL, *inv_expr_express = NULL, *inv_expr;
5563 tree *control_var, *bound_cst;
5564 enum tree_code comp = ERROR_MARK;
5565 struct iv_use *use = group->vuses[0];
5567 /* Try iv elimination. */
5568 if (may_eliminate_iv (data, use, cand, &bound, &comp))
5570 elim_cost = force_var_cost (data, bound, &inv_vars_elim);
5571 if (elim_cost.cost == 0)
5572 elim_cost.cost = parm_decl_cost (data, bound);
5573 else if (TREE_CODE (bound) == INTEGER_CST)
5574 elim_cost.cost = 0;
5575 /* If we replace a loop condition 'i < n' with 'p < base + n',
5576 inv_vars_elim will have 'base' and 'n' set, which implies that both
5577 'base' and 'n' will be live during the loop. More likely,
5578 'base + n' will be loop invariant, resulting in only one live value
5579 during the loop. So in that case we clear inv_vars_elim and set
5580 inv_expr_elim instead. */
5581 if (inv_vars_elim && bitmap_count_bits (inv_vars_elim) > 1)
5583 inv_expr_elim = record_inv_expr (data, bound);
5584 bitmap_clear (inv_vars_elim);
5586 /* The bound is a loop invariant, so it will be only computed
5587 once. */
5588 elim_cost.cost = adjust_setup_cost (data, elim_cost.cost);
5590 else
5591 elim_cost = infinite_cost;
5593 /* Try expressing the original giv. If it is compared with an invariant,
5594 note that we cannot get rid of it. */
5595 ok = extract_cond_operands (data, use->stmt, &control_var, &bound_cst,
5596 NULL, &cmp_iv);
5597 gcc_assert (ok);
5599 /* When the condition is a comparison of the candidate IV against
5600 zero, prefer this IV.
5602 TODO: The constant that we're subtracting from the cost should
5603 be target-dependent. This information should be added to the
5604 target costs for each backend. */
5605 if (!elim_cost.infinite_cost_p () /* Do not try to decrease infinite! */
5606 && integer_zerop (*bound_cst)
5607 && (operand_equal_p (*control_var, cand->var_after, 0)
5608 || operand_equal_p (*control_var, cand->var_before, 0)))
5609 elim_cost -= 1;
5611 express_cost = get_computation_cost (data, use, cand, false,
5612 &inv_vars_express, NULL,
5613 &inv_expr_express);
5614 if (cmp_iv != NULL)
5615 find_inv_vars (data, &cmp_iv->base, &inv_vars_express);
5617 /* Count the cost of the original bound as well. */
5618 bound_cost = force_var_cost (data, *bound_cst, NULL);
5619 if (bound_cost.cost == 0)
5620 bound_cost.cost = parm_decl_cost (data, *bound_cst);
5621 else if (TREE_CODE (*bound_cst) == INTEGER_CST)
5622 bound_cost.cost = 0;
5623 express_cost += bound_cost;
5625 /* Choose the better approach, preferring the eliminated IV. */
5626 if (elim_cost <= express_cost)
5628 cost = elim_cost;
5629 inv_vars = inv_vars_elim;
5630 inv_vars_elim = NULL;
5631 inv_expr = inv_expr_elim;
5633 else
5635 cost = express_cost;
5636 inv_vars = inv_vars_express;
5637 inv_vars_express = NULL;
5638 bound = NULL_TREE;
5639 comp = ERROR_MARK;
5640 inv_expr = inv_expr_express;
5643 if (inv_expr)
5645 inv_exprs = BITMAP_ALLOC (NULL);
5646 bitmap_set_bit (inv_exprs, inv_expr->id);
5648 set_group_iv_cost (data, group, cand, cost,
5649 inv_vars, bound, comp, inv_exprs);
5651 if (inv_vars_elim)
5652 BITMAP_FREE (inv_vars_elim);
5653 if (inv_vars_express)
5654 BITMAP_FREE (inv_vars_express);
5656 return !cost.infinite_cost_p ();
5659 /* Determines cost of computing uses in GROUP with CAND. Returns false
5660 if USE cannot be represented with CAND. */
5662 static bool
5663 determine_group_iv_cost (struct ivopts_data *data,
5664 struct iv_group *group, struct iv_cand *cand)
5666 switch (group->type)
5668 case USE_NONLINEAR_EXPR:
5669 return determine_group_iv_cost_generic (data, group, cand);
5671 case USE_ADDRESS:
5672 return determine_group_iv_cost_address (data, group, cand);
5674 case USE_COMPARE:
5675 return determine_group_iv_cost_cond (data, group, cand);
5677 default:
5678 gcc_unreachable ();
5682 /* Return true if get_computation_cost indicates that autoincrement is
5683 a possibility for the pair of USE and CAND, false otherwise. */
5685 static bool
5686 autoinc_possible_for_pair (struct ivopts_data *data, struct iv_use *use,
5687 struct iv_cand *cand)
5689 bitmap inv_vars;
5690 bool can_autoinc;
5691 comp_cost cost;
5693 if (use->type != USE_ADDRESS)
5694 return false;
5696 cost = get_computation_cost (data, use, cand, true, &inv_vars,
5697 &can_autoinc, NULL);
5699 BITMAP_FREE (inv_vars);
5701 return !cost.infinite_cost_p () && can_autoinc;
5704 /* Examine IP_ORIGINAL candidates to see if they are incremented next to a
5705 use that allows autoincrement, and set their AINC_USE if possible. */
5707 static void
5708 set_autoinc_for_original_candidates (struct ivopts_data *data)
5710 unsigned i, j;
5712 for (i = 0; i < data->vcands.length (); i++)
5714 struct iv_cand *cand = data->vcands[i];
5715 struct iv_use *closest_before = NULL;
5716 struct iv_use *closest_after = NULL;
5717 if (cand->pos != IP_ORIGINAL)
5718 continue;
5720 for (j = 0; j < data->vgroups.length (); j++)
5722 struct iv_group *group = data->vgroups[j];
5723 struct iv_use *use = group->vuses[0];
5724 unsigned uid = gimple_uid (use->stmt);
5726 if (gimple_bb (use->stmt) != gimple_bb (cand->incremented_at))
5727 continue;
5729 if (uid < gimple_uid (cand->incremented_at)
5730 && (closest_before == NULL
5731 || uid > gimple_uid (closest_before->stmt)))
5732 closest_before = use;
5734 if (uid > gimple_uid (cand->incremented_at)
5735 && (closest_after == NULL
5736 || uid < gimple_uid (closest_after->stmt)))
5737 closest_after = use;
5740 if (closest_before != NULL
5741 && autoinc_possible_for_pair (data, closest_before, cand))
5742 cand->ainc_use = closest_before;
5743 else if (closest_after != NULL
5744 && autoinc_possible_for_pair (data, closest_after, cand))
5745 cand->ainc_use = closest_after;
5749 /* Finds the candidates for the induction variables. */
5751 static void
5752 find_iv_candidates (struct ivopts_data *data)
5754 /* Add commonly used ivs. */
5755 add_standard_iv_candidates (data);
5757 /* Add old induction variables. */
5758 add_iv_candidate_for_bivs (data);
5760 /* Add induction variables derived from uses. */
5761 add_iv_candidate_for_groups (data);
5763 set_autoinc_for_original_candidates (data);
5765 /* Record the important candidates. */
5766 record_important_candidates (data);
5768 if (dump_file && (dump_flags & TDF_DETAILS))
5770 unsigned i;
5772 fprintf (dump_file, "\n<Important Candidates>:\t");
5773 for (i = 0; i < data->vcands.length (); i++)
5774 if (data->vcands[i]->important)
5775 fprintf (dump_file, " %d,", data->vcands[i]->id);
5776 fprintf (dump_file, "\n");
5778 fprintf (dump_file, "\n<Group, Cand> Related:\n");
5779 for (i = 0; i < data->vgroups.length (); i++)
5781 struct iv_group *group = data->vgroups[i];
5783 if (group->related_cands)
5785 fprintf (dump_file, " Group %d:\t", group->id);
5786 dump_bitmap (dump_file, group->related_cands);
5789 fprintf (dump_file, "\n");
5793 /* Determines costs of computing use of iv with an iv candidate. */
5795 static void
5796 determine_group_iv_costs (struct ivopts_data *data)
5798 unsigned i, j;
5799 struct iv_cand *cand;
5800 struct iv_group *group;
5801 bitmap to_clear = BITMAP_ALLOC (NULL);
5803 alloc_use_cost_map (data);
5805 for (i = 0; i < data->vgroups.length (); i++)
5807 group = data->vgroups[i];
5809 if (data->consider_all_candidates)
5811 for (j = 0; j < data->vcands.length (); j++)
5813 cand = data->vcands[j];
5814 determine_group_iv_cost (data, group, cand);
5817 else
5819 bitmap_iterator bi;
5821 EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, j, bi)
5823 cand = data->vcands[j];
5824 if (!determine_group_iv_cost (data, group, cand))
5825 bitmap_set_bit (to_clear, j);
5828 /* Remove the candidates for that the cost is infinite from
5829 the list of related candidates. */
5830 bitmap_and_compl_into (group->related_cands, to_clear);
5831 bitmap_clear (to_clear);
5835 BITMAP_FREE (to_clear);
5837 if (dump_file && (dump_flags & TDF_DETAILS))
5839 fprintf (dump_file, "\n<Invariant Expressions>:\n");
5840 auto_vec <iv_inv_expr_ent *> list (data->inv_expr_tab->elements ());
5842 for (hash_table<iv_inv_expr_hasher>::iterator it
5843 = data->inv_expr_tab->begin (); it != data->inv_expr_tab->end ();
5844 ++it)
5845 list.safe_push (*it);
5847 list.qsort (sort_iv_inv_expr_ent);
5849 for (i = 0; i < list.length (); ++i)
5851 fprintf (dump_file, "inv_expr %d: \t", list[i]->id);
5852 print_generic_expr (dump_file, list[i]->expr, TDF_SLIM);
5853 fprintf (dump_file, "\n");
5856 fprintf (dump_file, "\n<Group-candidate Costs>:\n");
5858 for (i = 0; i < data->vgroups.length (); i++)
5860 group = data->vgroups[i];
5862 fprintf (dump_file, "Group %d:\n", i);
5863 fprintf (dump_file, " cand\tcost\tcompl.\tinv.expr.\tinv.vars\n");
5864 for (j = 0; j < group->n_map_members; j++)
5866 if (!group->cost_map[j].cand
5867 || group->cost_map[j].cost.infinite_cost_p ())
5868 continue;
5870 fprintf (dump_file, " %d\t%d\t%d\t",
5871 group->cost_map[j].cand->id,
5872 group->cost_map[j].cost.cost,
5873 group->cost_map[j].cost.complexity);
5874 if (!group->cost_map[j].inv_exprs
5875 || bitmap_empty_p (group->cost_map[j].inv_exprs))
5876 fprintf (dump_file, "NIL;\t");
5877 else
5878 bitmap_print (dump_file,
5879 group->cost_map[j].inv_exprs, "", ";\t");
5880 if (!group->cost_map[j].inv_vars
5881 || bitmap_empty_p (group->cost_map[j].inv_vars))
5882 fprintf (dump_file, "NIL;\n");
5883 else
5884 bitmap_print (dump_file,
5885 group->cost_map[j].inv_vars, "", "\n");
5888 fprintf (dump_file, "\n");
5890 fprintf (dump_file, "\n");
5894 /* Determines cost of the candidate CAND. */
5896 static void
5897 determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
5899 comp_cost cost_base;
5900 unsigned cost, cost_step;
5901 tree base;
5903 gcc_assert (cand->iv != NULL);
5905 /* There are two costs associated with the candidate -- its increment
5906 and its initialization. The second is almost negligible for any loop
5907 that rolls enough, so we take it just very little into account. */
5909 base = cand->iv->base;
5910 cost_base = force_var_cost (data, base, NULL);
5911 /* It will be exceptional that the iv register happens to be initialized with
5912 the proper value at no cost. In general, there will at least be a regcopy
5913 or a const set. */
5914 if (cost_base.cost == 0)
5915 cost_base.cost = COSTS_N_INSNS (1);
5916 cost_step = add_cost (data->speed, TYPE_MODE (TREE_TYPE (base)));
5918 cost = cost_step + adjust_setup_cost (data, cost_base.cost);
5920 /* Prefer the original ivs unless we may gain something by replacing it.
5921 The reason is to make debugging simpler; so this is not relevant for
5922 artificial ivs created by other optimization passes. */
5923 if (cand->pos != IP_ORIGINAL
5924 || !SSA_NAME_VAR (cand->var_before)
5925 || DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
5926 cost++;
5928 /* Prefer not to insert statements into latch unless there are some
5929 already (so that we do not create unnecessary jumps). */
5930 if (cand->pos == IP_END
5931 && empty_block_p (ip_end_pos (data->current_loop)))
5932 cost++;
5934 cand->cost = cost;
5935 cand->cost_step = cost_step;
5938 /* Determines costs of computation of the candidates. */
5940 static void
5941 determine_iv_costs (struct ivopts_data *data)
5943 unsigned i;
5945 if (dump_file && (dump_flags & TDF_DETAILS))
5947 fprintf (dump_file, "<Candidate Costs>:\n");
5948 fprintf (dump_file, " cand\tcost\n");
5951 for (i = 0; i < data->vcands.length (); i++)
5953 struct iv_cand *cand = data->vcands[i];
5955 determine_iv_cost (data, cand);
5957 if (dump_file && (dump_flags & TDF_DETAILS))
5958 fprintf (dump_file, " %d\t%d\n", i, cand->cost);
5961 if (dump_file && (dump_flags & TDF_DETAILS))
5962 fprintf (dump_file, "\n");
5965 /* Calculates cost for having N_REGS registers. This number includes
5966 induction variables, invariant variables and invariant expressions. */
5968 static unsigned
5969 ivopts_global_cost_for_size (struct ivopts_data *data, unsigned n_regs)
5971 unsigned cost = estimate_reg_pressure_cost (n_regs,
5972 data->regs_used, data->speed,
5973 data->body_includes_call);
5974 /* Add n_regs to the cost, so that we prefer eliminating ivs if possible. */
5975 return n_regs + cost;
5978 /* For each size of the induction variable set determine the penalty. */
5980 static void
5981 determine_set_costs (struct ivopts_data *data)
5983 unsigned j, n;
5984 gphi *phi;
5985 gphi_iterator psi;
5986 tree op;
5987 struct loop *loop = data->current_loop;
5988 bitmap_iterator bi;
5990 if (dump_file && (dump_flags & TDF_DETAILS))
5992 fprintf (dump_file, "<Global Costs>:\n");
5993 fprintf (dump_file, " target_avail_regs %d\n", target_avail_regs);
5994 fprintf (dump_file, " target_clobbered_regs %d\n", target_clobbered_regs);
5995 fprintf (dump_file, " target_reg_cost %d\n", target_reg_cost[data->speed]);
5996 fprintf (dump_file, " target_spill_cost %d\n", target_spill_cost[data->speed]);
5999 n = 0;
6000 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
6002 phi = psi.phi ();
6003 op = PHI_RESULT (phi);
6005 if (virtual_operand_p (op))
6006 continue;
6008 if (get_iv (data, op))
6009 continue;
6011 n++;
6014 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
6016 struct version_info *info = ver_info (data, j);
6018 if (info->inv_id && info->has_nonlin_use)
6019 n++;
6022 data->regs_used = n;
6023 if (dump_file && (dump_flags & TDF_DETAILS))
6024 fprintf (dump_file, " regs_used %d\n", n);
6026 if (dump_file && (dump_flags & TDF_DETAILS))
6028 fprintf (dump_file, " cost for size:\n");
6029 fprintf (dump_file, " ivs\tcost\n");
6030 for (j = 0; j <= 2 * target_avail_regs; j++)
6031 fprintf (dump_file, " %d\t%d\n", j,
6032 ivopts_global_cost_for_size (data, j));
6033 fprintf (dump_file, "\n");
6037 /* Returns true if A is a cheaper cost pair than B. */
6039 static bool
6040 cheaper_cost_pair (struct cost_pair *a, struct cost_pair *b)
6042 if (!a)
6043 return false;
6045 if (!b)
6046 return true;
6048 if (a->cost < b->cost)
6049 return true;
6051 if (b->cost < a->cost)
6052 return false;
6054 /* In case the costs are the same, prefer the cheaper candidate. */
6055 if (a->cand->cost < b->cand->cost)
6056 return true;
6058 return false;
6062 /* Returns candidate by that USE is expressed in IVS. */
6064 static struct cost_pair *
6065 iv_ca_cand_for_group (struct iv_ca *ivs, struct iv_group *group)
6067 return ivs->cand_for_group[group->id];
6070 /* Computes the cost field of IVS structure. */
6072 static void
6073 iv_ca_recount_cost (struct ivopts_data *data, struct iv_ca *ivs)
6075 comp_cost cost = ivs->cand_use_cost;
6077 cost += ivs->cand_cost;
6078 cost += ivopts_global_cost_for_size (data, ivs->n_invs + ivs->n_cands);
6079 ivs->cost = cost;
6082 /* Remove use of invariants in set INVS by decreasing counter in N_INV_USES
6083 and IVS. */
6085 static void
6086 iv_ca_set_remove_invs (struct iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
6088 bitmap_iterator bi;
6089 unsigned iid;
6091 if (!invs)
6092 return;
6094 gcc_assert (n_inv_uses != NULL);
6095 EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
6097 n_inv_uses[iid]--;
6098 if (n_inv_uses[iid] == 0)
6099 ivs->n_invs--;
6103 /* Set USE not to be expressed by any candidate in IVS. */
6105 static void
6106 iv_ca_set_no_cp (struct ivopts_data *data, struct iv_ca *ivs,
6107 struct iv_group *group)
6109 unsigned gid = group->id, cid;
6110 struct cost_pair *cp;
6112 cp = ivs->cand_for_group[gid];
6113 if (!cp)
6114 return;
6115 cid = cp->cand->id;
6117 ivs->bad_groups++;
6118 ivs->cand_for_group[gid] = NULL;
6119 ivs->n_cand_uses[cid]--;
6121 if (ivs->n_cand_uses[cid] == 0)
6123 bitmap_clear_bit (ivs->cands, cid);
6124 ivs->n_cands--;
6125 ivs->cand_cost -= cp->cand->cost;
6126 iv_ca_set_remove_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses);
6129 ivs->cand_use_cost -= cp->cost;
6130 iv_ca_set_remove_invs (ivs, cp->inv_vars, ivs->n_inv_var_uses);
6131 iv_ca_set_remove_invs (ivs, cp->inv_exprs, ivs->n_inv_expr_uses);
6132 iv_ca_recount_cost (data, ivs);
6135 /* Add use of invariants in set INVS by increasing counter in N_INV_USES and
6136 IVS. */
6138 static void
6139 iv_ca_set_add_invs (struct iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
6141 bitmap_iterator bi;
6142 unsigned iid;
6144 if (!invs)
6145 return;
6147 gcc_assert (n_inv_uses != NULL);
6148 EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
6150 n_inv_uses[iid]++;
6151 if (n_inv_uses[iid] == 1)
6152 ivs->n_invs++;
6156 /* Set cost pair for GROUP in set IVS to CP. */
6158 static void
6159 iv_ca_set_cp (struct ivopts_data *data, struct iv_ca *ivs,
6160 struct iv_group *group, struct cost_pair *cp)
6162 unsigned gid = group->id, cid;
6164 if (ivs->cand_for_group[gid] == cp)
6165 return;
6167 if (ivs->cand_for_group[gid])
6168 iv_ca_set_no_cp (data, ivs, group);
6170 if (cp)
6172 cid = cp->cand->id;
6174 ivs->bad_groups--;
6175 ivs->cand_for_group[gid] = cp;
6176 ivs->n_cand_uses[cid]++;
6177 if (ivs->n_cand_uses[cid] == 1)
6179 bitmap_set_bit (ivs->cands, cid);
6180 ivs->n_cands++;
6181 ivs->cand_cost += cp->cand->cost;
6182 iv_ca_set_add_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses);
6185 ivs->cand_use_cost += cp->cost;
6186 iv_ca_set_add_invs (ivs, cp->inv_vars, ivs->n_inv_var_uses);
6187 iv_ca_set_add_invs (ivs, cp->inv_exprs, ivs->n_inv_expr_uses);
6188 iv_ca_recount_cost (data, ivs);
6192 /* Extend set IVS by expressing USE by some of the candidates in it
6193 if possible. Consider all important candidates if candidates in
6194 set IVS don't give any result. */
6196 static void
6197 iv_ca_add_group (struct ivopts_data *data, struct iv_ca *ivs,
6198 struct iv_group *group)
6200 struct cost_pair *best_cp = NULL, *cp;
6201 bitmap_iterator bi;
6202 unsigned i;
6203 struct iv_cand *cand;
6205 gcc_assert (ivs->upto >= group->id);
6206 ivs->upto++;
6207 ivs->bad_groups++;
6209 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
6211 cand = data->vcands[i];
6212 cp = get_group_iv_cost (data, group, cand);
6213 if (cheaper_cost_pair (cp, best_cp))
6214 best_cp = cp;
6217 if (best_cp == NULL)
6219 EXECUTE_IF_SET_IN_BITMAP (data->important_candidates, 0, i, bi)
6221 cand = data->vcands[i];
6222 cp = get_group_iv_cost (data, group, cand);
6223 if (cheaper_cost_pair (cp, best_cp))
6224 best_cp = cp;
6228 iv_ca_set_cp (data, ivs, group, best_cp);
6231 /* Get cost for assignment IVS. */
6233 static comp_cost
6234 iv_ca_cost (struct iv_ca *ivs)
6236 /* This was a conditional expression but it triggered a bug in
6237 Sun C 5.5. */
6238 if (ivs->bad_groups)
6239 return infinite_cost;
6240 else
6241 return ivs->cost;
6244 /* Returns true if all dependences of CP are among invariants in IVS. */
6246 static bool
6247 iv_ca_has_deps (struct iv_ca *ivs, struct cost_pair *cp)
6249 unsigned i;
6250 bitmap_iterator bi;
6252 if (cp->inv_vars)
6253 EXECUTE_IF_SET_IN_BITMAP (cp->inv_vars, 0, i, bi)
6254 if (ivs->n_inv_var_uses[i] == 0)
6255 return false;
6257 if (cp->inv_exprs)
6258 EXECUTE_IF_SET_IN_BITMAP (cp->inv_exprs, 0, i, bi)
6259 if (ivs->n_inv_expr_uses[i] == 0)
6260 return false;
6262 return true;
6265 /* Creates change of expressing GROUP by NEW_CP instead of OLD_CP and chains
6266 it before NEXT. */
6268 static struct iv_ca_delta *
6269 iv_ca_delta_add (struct iv_group *group, struct cost_pair *old_cp,
6270 struct cost_pair *new_cp, struct iv_ca_delta *next)
6272 struct iv_ca_delta *change = XNEW (struct iv_ca_delta);
6274 change->group = group;
6275 change->old_cp = old_cp;
6276 change->new_cp = new_cp;
6277 change->next = next;
6279 return change;
6282 /* Joins two lists of changes L1 and L2. Destructive -- old lists
6283 are rewritten. */
6285 static struct iv_ca_delta *
6286 iv_ca_delta_join (struct iv_ca_delta *l1, struct iv_ca_delta *l2)
6288 struct iv_ca_delta *last;
6290 if (!l2)
6291 return l1;
6293 if (!l1)
6294 return l2;
6296 for (last = l1; last->next; last = last->next)
6297 continue;
6298 last->next = l2;
6300 return l1;
6303 /* Reverse the list of changes DELTA, forming the inverse to it. */
6305 static struct iv_ca_delta *
6306 iv_ca_delta_reverse (struct iv_ca_delta *delta)
6308 struct iv_ca_delta *act, *next, *prev = NULL;
6310 for (act = delta; act; act = next)
6312 next = act->next;
6313 act->next = prev;
6314 prev = act;
6316 std::swap (act->old_cp, act->new_cp);
6319 return prev;
6322 /* Commit changes in DELTA to IVS. If FORWARD is false, the changes are
6323 reverted instead. */
6325 static void
6326 iv_ca_delta_commit (struct ivopts_data *data, struct iv_ca *ivs,
6327 struct iv_ca_delta *delta, bool forward)
6329 struct cost_pair *from, *to;
6330 struct iv_ca_delta *act;
6332 if (!forward)
6333 delta = iv_ca_delta_reverse (delta);
6335 for (act = delta; act; act = act->next)
6337 from = act->old_cp;
6338 to = act->new_cp;
6339 gcc_assert (iv_ca_cand_for_group (ivs, act->group) == from);
6340 iv_ca_set_cp (data, ivs, act->group, to);
6343 if (!forward)
6344 iv_ca_delta_reverse (delta);
6347 /* Returns true if CAND is used in IVS. */
6349 static bool
6350 iv_ca_cand_used_p (struct iv_ca *ivs, struct iv_cand *cand)
6352 return ivs->n_cand_uses[cand->id] > 0;
6355 /* Returns number of induction variable candidates in the set IVS. */
6357 static unsigned
6358 iv_ca_n_cands (struct iv_ca *ivs)
6360 return ivs->n_cands;
6363 /* Free the list of changes DELTA. */
6365 static void
6366 iv_ca_delta_free (struct iv_ca_delta **delta)
6368 struct iv_ca_delta *act, *next;
6370 for (act = *delta; act; act = next)
6372 next = act->next;
6373 free (act);
6376 *delta = NULL;
6379 /* Allocates new iv candidates assignment. */
6381 static struct iv_ca *
6382 iv_ca_new (struct ivopts_data *data)
6384 struct iv_ca *nw = XNEW (struct iv_ca);
6386 nw->upto = 0;
6387 nw->bad_groups = 0;
6388 nw->cand_for_group = XCNEWVEC (struct cost_pair *,
6389 data->vgroups.length ());
6390 nw->n_cand_uses = XCNEWVEC (unsigned, data->vcands.length ());
6391 nw->cands = BITMAP_ALLOC (NULL);
6392 nw->n_cands = 0;
6393 nw->n_invs = 0;
6394 nw->cand_use_cost = no_cost;
6395 nw->cand_cost = 0;
6396 nw->n_inv_var_uses = XCNEWVEC (unsigned, data->max_inv_var_id + 1);
6397 nw->n_inv_expr_uses = XCNEWVEC (unsigned, data->max_inv_expr_id + 1);
6398 nw->cost = no_cost;
6400 return nw;
6403 /* Free memory occupied by the set IVS. */
6405 static void
6406 iv_ca_free (struct iv_ca **ivs)
6408 free ((*ivs)->cand_for_group);
6409 free ((*ivs)->n_cand_uses);
6410 BITMAP_FREE ((*ivs)->cands);
6411 free ((*ivs)->n_inv_var_uses);
6412 free ((*ivs)->n_inv_expr_uses);
6413 free (*ivs);
6414 *ivs = NULL;
6417 /* Dumps IVS to FILE. */
6419 static void
6420 iv_ca_dump (struct ivopts_data *data, FILE *file, struct iv_ca *ivs)
6422 unsigned i;
6423 comp_cost cost = iv_ca_cost (ivs);
6425 fprintf (file, " cost: %d (complexity %d)\n", cost.cost,
6426 cost.complexity);
6427 fprintf (file, " cand_cost: %d\n cand_group_cost: %d (complexity %d)\n",
6428 ivs->cand_cost, ivs->cand_use_cost.cost,
6429 ivs->cand_use_cost.complexity);
6430 bitmap_print (file, ivs->cands, " candidates: ","\n");
6432 for (i = 0; i < ivs->upto; i++)
6434 struct iv_group *group = data->vgroups[i];
6435 struct cost_pair *cp = iv_ca_cand_for_group (ivs, group);
6436 if (cp)
6437 fprintf (file, " group:%d --> iv_cand:%d, cost=(%d,%d)\n",
6438 group->id, cp->cand->id, cp->cost.cost,
6439 cp->cost.complexity);
6440 else
6441 fprintf (file, " group:%d --> ??\n", group->id);
6444 const char *pref = "";
6445 fprintf (file, " invariant variables: ");
6446 for (i = 1; i <= data->max_inv_var_id; i++)
6447 if (ivs->n_inv_var_uses[i])
6449 fprintf (file, "%s%d", pref, i);
6450 pref = ", ";
6453 pref = "";
6454 fprintf (file, "\n invariant expressions: ");
6455 for (i = 1; i <= data->max_inv_expr_id; i++)
6456 if (ivs->n_inv_expr_uses[i])
6458 fprintf (file, "%s%d", pref, i);
6459 pref = ", ";
6462 fprintf (file, "\n\n");
6465 /* Try changing candidate in IVS to CAND for each use. Return cost of the
6466 new set, and store differences in DELTA. Number of induction variables
6467 in the new set is stored to N_IVS. MIN_NCAND is a flag. When it is true
6468 the function will try to find a solution with mimimal iv candidates. */
6470 static comp_cost
6471 iv_ca_extend (struct ivopts_data *data, struct iv_ca *ivs,
6472 struct iv_cand *cand, struct iv_ca_delta **delta,
6473 unsigned *n_ivs, bool min_ncand)
6475 unsigned i;
6476 comp_cost cost;
6477 struct iv_group *group;
6478 struct cost_pair *old_cp, *new_cp;
6480 *delta = NULL;
6481 for (i = 0; i < ivs->upto; i++)
6483 group = data->vgroups[i];
6484 old_cp = iv_ca_cand_for_group (ivs, group);
6486 if (old_cp
6487 && old_cp->cand == cand)
6488 continue;
6490 new_cp = get_group_iv_cost (data, group, cand);
6491 if (!new_cp)
6492 continue;
6494 if (!min_ncand && !iv_ca_has_deps (ivs, new_cp))
6495 continue;
6497 if (!min_ncand && !cheaper_cost_pair (new_cp, old_cp))
6498 continue;
6500 *delta = iv_ca_delta_add (group, old_cp, new_cp, *delta);
6503 iv_ca_delta_commit (data, ivs, *delta, true);
6504 cost = iv_ca_cost (ivs);
6505 if (n_ivs)
6506 *n_ivs = iv_ca_n_cands (ivs);
6507 iv_ca_delta_commit (data, ivs, *delta, false);
6509 return cost;
6512 /* Try narrowing set IVS by removing CAND. Return the cost of
6513 the new set and store the differences in DELTA. START is
6514 the candidate with which we start narrowing. */
6516 static comp_cost
6517 iv_ca_narrow (struct ivopts_data *data, struct iv_ca *ivs,
6518 struct iv_cand *cand, struct iv_cand *start,
6519 struct iv_ca_delta **delta)
6521 unsigned i, ci;
6522 struct iv_group *group;
6523 struct cost_pair *old_cp, *new_cp, *cp;
6524 bitmap_iterator bi;
6525 struct iv_cand *cnd;
6526 comp_cost cost, best_cost, acost;
6528 *delta = NULL;
6529 for (i = 0; i < data->vgroups.length (); i++)
6531 group = data->vgroups[i];
6533 old_cp = iv_ca_cand_for_group (ivs, group);
6534 if (old_cp->cand != cand)
6535 continue;
6537 best_cost = iv_ca_cost (ivs);
6538 /* Start narrowing with START. */
6539 new_cp = get_group_iv_cost (data, group, start);
6541 if (data->consider_all_candidates)
6543 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, ci, bi)
6545 if (ci == cand->id || (start && ci == start->id))
6546 continue;
6548 cnd = data->vcands[ci];
6550 cp = get_group_iv_cost (data, group, cnd);
6551 if (!cp)
6552 continue;
6554 iv_ca_set_cp (data, ivs, group, cp);
6555 acost = iv_ca_cost (ivs);
6557 if (acost < best_cost)
6559 best_cost = acost;
6560 new_cp = cp;
6564 else
6566 EXECUTE_IF_AND_IN_BITMAP (group->related_cands, ivs->cands, 0, ci, bi)
6568 if (ci == cand->id || (start && ci == start->id))
6569 continue;
6571 cnd = data->vcands[ci];
6573 cp = get_group_iv_cost (data, group, cnd);
6574 if (!cp)
6575 continue;
6577 iv_ca_set_cp (data, ivs, group, cp);
6578 acost = iv_ca_cost (ivs);
6580 if (acost < best_cost)
6582 best_cost = acost;
6583 new_cp = cp;
6587 /* Restore to old cp for use. */
6588 iv_ca_set_cp (data, ivs, group, old_cp);
6590 if (!new_cp)
6592 iv_ca_delta_free (delta);
6593 return infinite_cost;
6596 *delta = iv_ca_delta_add (group, old_cp, new_cp, *delta);
6599 iv_ca_delta_commit (data, ivs, *delta, true);
6600 cost = iv_ca_cost (ivs);
6601 iv_ca_delta_commit (data, ivs, *delta, false);
6603 return cost;
6606 /* Try optimizing the set of candidates IVS by removing candidates different
6607 from to EXCEPT_CAND from it. Return cost of the new set, and store
6608 differences in DELTA. */
6610 static comp_cost
6611 iv_ca_prune (struct ivopts_data *data, struct iv_ca *ivs,
6612 struct iv_cand *except_cand, struct iv_ca_delta **delta)
6614 bitmap_iterator bi;
6615 struct iv_ca_delta *act_delta, *best_delta;
6616 unsigned i;
6617 comp_cost best_cost, acost;
6618 struct iv_cand *cand;
6620 best_delta = NULL;
6621 best_cost = iv_ca_cost (ivs);
6623 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
6625 cand = data->vcands[i];
6627 if (cand == except_cand)
6628 continue;
6630 acost = iv_ca_narrow (data, ivs, cand, except_cand, &act_delta);
6632 if (acost < best_cost)
6634 best_cost = acost;
6635 iv_ca_delta_free (&best_delta);
6636 best_delta = act_delta;
6638 else
6639 iv_ca_delta_free (&act_delta);
6642 if (!best_delta)
6644 *delta = NULL;
6645 return best_cost;
6648 /* Recurse to possibly remove other unnecessary ivs. */
6649 iv_ca_delta_commit (data, ivs, best_delta, true);
6650 best_cost = iv_ca_prune (data, ivs, except_cand, delta);
6651 iv_ca_delta_commit (data, ivs, best_delta, false);
6652 *delta = iv_ca_delta_join (best_delta, *delta);
6653 return best_cost;
6656 /* Check if CAND_IDX is a candidate other than OLD_CAND and has
6657 cheaper local cost for GROUP than BEST_CP. Return pointer to
6658 the corresponding cost_pair, otherwise just return BEST_CP. */
6660 static struct cost_pair*
6661 cheaper_cost_with_cand (struct ivopts_data *data, struct iv_group *group,
6662 unsigned int cand_idx, struct iv_cand *old_cand,
6663 struct cost_pair *best_cp)
6665 struct iv_cand *cand;
6666 struct cost_pair *cp;
6668 gcc_assert (old_cand != NULL && best_cp != NULL);
6669 if (cand_idx == old_cand->id)
6670 return best_cp;
6672 cand = data->vcands[cand_idx];
6673 cp = get_group_iv_cost (data, group, cand);
6674 if (cp != NULL && cheaper_cost_pair (cp, best_cp))
6675 return cp;
6677 return best_cp;
6680 /* Try breaking local optimal fixed-point for IVS by replacing candidates
6681 which are used by more than one iv uses. For each of those candidates,
6682 this function tries to represent iv uses under that candidate using
6683 other ones with lower local cost, then tries to prune the new set.
6684 If the new set has lower cost, It returns the new cost after recording
6685 candidate replacement in list DELTA. */
6687 static comp_cost
6688 iv_ca_replace (struct ivopts_data *data, struct iv_ca *ivs,
6689 struct iv_ca_delta **delta)
6691 bitmap_iterator bi, bj;
6692 unsigned int i, j, k;
6693 struct iv_cand *cand;
6694 comp_cost orig_cost, acost;
6695 struct iv_ca_delta *act_delta, *tmp_delta;
6696 struct cost_pair *old_cp, *best_cp = NULL;
6698 *delta = NULL;
6699 orig_cost = iv_ca_cost (ivs);
6701 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
6703 if (ivs->n_cand_uses[i] == 1
6704 || ivs->n_cand_uses[i] > ALWAYS_PRUNE_CAND_SET_BOUND)
6705 continue;
6707 cand = data->vcands[i];
6709 act_delta = NULL;
6710 /* Represent uses under current candidate using other ones with
6711 lower local cost. */
6712 for (j = 0; j < ivs->upto; j++)
6714 struct iv_group *group = data->vgroups[j];
6715 old_cp = iv_ca_cand_for_group (ivs, group);
6717 if (old_cp->cand != cand)
6718 continue;
6720 best_cp = old_cp;
6721 if (data->consider_all_candidates)
6722 for (k = 0; k < data->vcands.length (); k++)
6723 best_cp = cheaper_cost_with_cand (data, group, k,
6724 old_cp->cand, best_cp);
6725 else
6726 EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, k, bj)
6727 best_cp = cheaper_cost_with_cand (data, group, k,
6728 old_cp->cand, best_cp);
6730 if (best_cp == old_cp)
6731 continue;
6733 act_delta = iv_ca_delta_add (group, old_cp, best_cp, act_delta);
6735 /* No need for further prune. */
6736 if (!act_delta)
6737 continue;
6739 /* Prune the new candidate set. */
6740 iv_ca_delta_commit (data, ivs, act_delta, true);
6741 acost = iv_ca_prune (data, ivs, NULL, &tmp_delta);
6742 iv_ca_delta_commit (data, ivs, act_delta, false);
6743 act_delta = iv_ca_delta_join (act_delta, tmp_delta);
6745 if (acost < orig_cost)
6747 *delta = act_delta;
6748 return acost;
6750 else
6751 iv_ca_delta_free (&act_delta);
6754 return orig_cost;
6757 /* Tries to extend the sets IVS in the best possible way in order to
6758 express the GROUP. If ORIGINALP is true, prefer candidates from
6759 the original set of IVs, otherwise favor important candidates not
6760 based on any memory object. */
6762 static bool
6763 try_add_cand_for (struct ivopts_data *data, struct iv_ca *ivs,
6764 struct iv_group *group, bool originalp)
6766 comp_cost best_cost, act_cost;
6767 unsigned i;
6768 bitmap_iterator bi;
6769 struct iv_cand *cand;
6770 struct iv_ca_delta *best_delta = NULL, *act_delta;
6771 struct cost_pair *cp;
6773 iv_ca_add_group (data, ivs, group);
6774 best_cost = iv_ca_cost (ivs);
6775 cp = iv_ca_cand_for_group (ivs, group);
6776 if (cp)
6778 best_delta = iv_ca_delta_add (group, NULL, cp, NULL);
6779 iv_ca_set_no_cp (data, ivs, group);
6782 /* If ORIGINALP is true, try to find the original IV for the use. Otherwise
6783 first try important candidates not based on any memory object. Only if
6784 this fails, try the specific ones. Rationale -- in loops with many
6785 variables the best choice often is to use just one generic biv. If we
6786 added here many ivs specific to the uses, the optimization algorithm later
6787 would be likely to get stuck in a local minimum, thus causing us to create
6788 too many ivs. The approach from few ivs to more seems more likely to be
6789 successful -- starting from few ivs, replacing an expensive use by a
6790 specific iv should always be a win. */
6791 EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, i, bi)
6793 cand = data->vcands[i];
6795 if (originalp && cand->pos !=IP_ORIGINAL)
6796 continue;
6798 if (!originalp && cand->iv->base_object != NULL_TREE)
6799 continue;
6801 if (iv_ca_cand_used_p (ivs, cand))
6802 continue;
6804 cp = get_group_iv_cost (data, group, cand);
6805 if (!cp)
6806 continue;
6808 iv_ca_set_cp (data, ivs, group, cp);
6809 act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL,
6810 true);
6811 iv_ca_set_no_cp (data, ivs, group);
6812 act_delta = iv_ca_delta_add (group, NULL, cp, act_delta);
6814 if (act_cost < best_cost)
6816 best_cost = act_cost;
6818 iv_ca_delta_free (&best_delta);
6819 best_delta = act_delta;
6821 else
6822 iv_ca_delta_free (&act_delta);
6825 if (best_cost.infinite_cost_p ())
6827 for (i = 0; i < group->n_map_members; i++)
6829 cp = group->cost_map + i;
6830 cand = cp->cand;
6831 if (!cand)
6832 continue;
6834 /* Already tried this. */
6835 if (cand->important)
6837 if (originalp && cand->pos == IP_ORIGINAL)
6838 continue;
6839 if (!originalp && cand->iv->base_object == NULL_TREE)
6840 continue;
6843 if (iv_ca_cand_used_p (ivs, cand))
6844 continue;
6846 act_delta = NULL;
6847 iv_ca_set_cp (data, ivs, group, cp);
6848 act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL, true);
6849 iv_ca_set_no_cp (data, ivs, group);
6850 act_delta = iv_ca_delta_add (group,
6851 iv_ca_cand_for_group (ivs, group),
6852 cp, act_delta);
6854 if (act_cost < best_cost)
6856 best_cost = act_cost;
6858 if (best_delta)
6859 iv_ca_delta_free (&best_delta);
6860 best_delta = act_delta;
6862 else
6863 iv_ca_delta_free (&act_delta);
6867 iv_ca_delta_commit (data, ivs, best_delta, true);
6868 iv_ca_delta_free (&best_delta);
6870 return !best_cost.infinite_cost_p ();
6873 /* Finds an initial assignment of candidates to uses. */
6875 static struct iv_ca *
6876 get_initial_solution (struct ivopts_data *data, bool originalp)
6878 unsigned i;
6879 struct iv_ca *ivs = iv_ca_new (data);
6881 for (i = 0; i < data->vgroups.length (); i++)
6882 if (!try_add_cand_for (data, ivs, data->vgroups[i], originalp))
6884 iv_ca_free (&ivs);
6885 return NULL;
6888 return ivs;
6891 /* Tries to improve set of induction variables IVS. TRY_REPLACE_P
6892 points to a bool variable, this function tries to break local
6893 optimal fixed-point by replacing candidates in IVS if it's true. */
6895 static bool
6896 try_improve_iv_set (struct ivopts_data *data,
6897 struct iv_ca *ivs, bool *try_replace_p)
6899 unsigned i, n_ivs;
6900 comp_cost acost, best_cost = iv_ca_cost (ivs);
6901 struct iv_ca_delta *best_delta = NULL, *act_delta, *tmp_delta;
6902 struct iv_cand *cand;
6904 /* Try extending the set of induction variables by one. */
6905 for (i = 0; i < data->vcands.length (); i++)
6907 cand = data->vcands[i];
6909 if (iv_ca_cand_used_p (ivs, cand))
6910 continue;
6912 acost = iv_ca_extend (data, ivs, cand, &act_delta, &n_ivs, false);
6913 if (!act_delta)
6914 continue;
6916 /* If we successfully added the candidate and the set is small enough,
6917 try optimizing it by removing other candidates. */
6918 if (n_ivs <= ALWAYS_PRUNE_CAND_SET_BOUND)
6920 iv_ca_delta_commit (data, ivs, act_delta, true);
6921 acost = iv_ca_prune (data, ivs, cand, &tmp_delta);
6922 iv_ca_delta_commit (data, ivs, act_delta, false);
6923 act_delta = iv_ca_delta_join (act_delta, tmp_delta);
6926 if (acost < best_cost)
6928 best_cost = acost;
6929 iv_ca_delta_free (&best_delta);
6930 best_delta = act_delta;
6932 else
6933 iv_ca_delta_free (&act_delta);
6936 if (!best_delta)
6938 /* Try removing the candidates from the set instead. */
6939 best_cost = iv_ca_prune (data, ivs, NULL, &best_delta);
6941 if (!best_delta && *try_replace_p)
6943 *try_replace_p = false;
6944 /* So far candidate selecting algorithm tends to choose fewer IVs
6945 so that it can handle cases in which loops have many variables
6946 but the best choice is often to use only one general biv. One
6947 weakness is it can't handle opposite cases, in which different
6948 candidates should be chosen with respect to each use. To solve
6949 the problem, we replace candidates in a manner described by the
6950 comments of iv_ca_replace, thus give general algorithm a chance
6951 to break local optimal fixed-point in these cases. */
6952 best_cost = iv_ca_replace (data, ivs, &best_delta);
6955 if (!best_delta)
6956 return false;
6959 iv_ca_delta_commit (data, ivs, best_delta, true);
6960 gcc_assert (best_cost == iv_ca_cost (ivs));
6961 iv_ca_delta_free (&best_delta);
6962 return true;
6965 /* Attempts to find the optimal set of induction variables. We do simple
6966 greedy heuristic -- we try to replace at most one candidate in the selected
6967 solution and remove the unused ivs while this improves the cost. */
6969 static struct iv_ca *
6970 find_optimal_iv_set_1 (struct ivopts_data *data, bool originalp)
6972 struct iv_ca *set;
6973 bool try_replace_p = true;
6975 /* Get the initial solution. */
6976 set = get_initial_solution (data, originalp);
6977 if (!set)
6979 if (dump_file && (dump_flags & TDF_DETAILS))
6980 fprintf (dump_file, "Unable to substitute for ivs, failed.\n");
6981 return NULL;
6984 if (dump_file && (dump_flags & TDF_DETAILS))
6986 fprintf (dump_file, "Initial set of candidates:\n");
6987 iv_ca_dump (data, dump_file, set);
6990 while (try_improve_iv_set (data, set, &try_replace_p))
6992 if (dump_file && (dump_flags & TDF_DETAILS))
6994 fprintf (dump_file, "Improved to:\n");
6995 iv_ca_dump (data, dump_file, set);
6999 return set;
7002 static struct iv_ca *
7003 find_optimal_iv_set (struct ivopts_data *data)
7005 unsigned i;
7006 comp_cost cost, origcost;
7007 struct iv_ca *set, *origset;
7009 /* Determine the cost based on a strategy that starts with original IVs,
7010 and try again using a strategy that prefers candidates not based
7011 on any IVs. */
7012 origset = find_optimal_iv_set_1 (data, true);
7013 set = find_optimal_iv_set_1 (data, false);
7015 if (!origset && !set)
7016 return NULL;
7018 origcost = origset ? iv_ca_cost (origset) : infinite_cost;
7019 cost = set ? iv_ca_cost (set) : infinite_cost;
7021 if (dump_file && (dump_flags & TDF_DETAILS))
7023 fprintf (dump_file, "Original cost %d (complexity %d)\n\n",
7024 origcost.cost, origcost.complexity);
7025 fprintf (dump_file, "Final cost %d (complexity %d)\n\n",
7026 cost.cost, cost.complexity);
7029 /* Choose the one with the best cost. */
7030 if (origcost <= cost)
7032 if (set)
7033 iv_ca_free (&set);
7034 set = origset;
7036 else if (origset)
7037 iv_ca_free (&origset);
7039 for (i = 0; i < data->vgroups.length (); i++)
7041 struct iv_group *group = data->vgroups[i];
7042 group->selected = iv_ca_cand_for_group (set, group)->cand;
7045 return set;
7048 /* Creates a new induction variable corresponding to CAND. */
7050 static void
7051 create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
7053 gimple_stmt_iterator incr_pos;
7054 tree base;
7055 struct iv_use *use;
7056 struct iv_group *group;
7057 bool after = false;
7059 gcc_assert (cand->iv != NULL);
7061 switch (cand->pos)
7063 case IP_NORMAL:
7064 incr_pos = gsi_last_bb (ip_normal_pos (data->current_loop));
7065 break;
7067 case IP_END:
7068 incr_pos = gsi_last_bb (ip_end_pos (data->current_loop));
7069 after = true;
7070 break;
7072 case IP_AFTER_USE:
7073 after = true;
7074 /* fall through */
7075 case IP_BEFORE_USE:
7076 incr_pos = gsi_for_stmt (cand->incremented_at);
7077 break;
7079 case IP_ORIGINAL:
7080 /* Mark that the iv is preserved. */
7081 name_info (data, cand->var_before)->preserve_biv = true;
7082 name_info (data, cand->var_after)->preserve_biv = true;
7084 /* Rewrite the increment so that it uses var_before directly. */
7085 use = find_interesting_uses_op (data, cand->var_after);
7086 group = data->vgroups[use->group_id];
7087 group->selected = cand;
7088 return;
7091 gimple_add_tmp_var (cand->var_before);
7093 base = unshare_expr (cand->iv->base);
7095 create_iv (base, unshare_expr (cand->iv->step),
7096 cand->var_before, data->current_loop,
7097 &incr_pos, after, &cand->var_before, &cand->var_after);
7100 /* Creates new induction variables described in SET. */
7102 static void
7103 create_new_ivs (struct ivopts_data *data, struct iv_ca *set)
7105 unsigned i;
7106 struct iv_cand *cand;
7107 bitmap_iterator bi;
7109 EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
7111 cand = data->vcands[i];
7112 create_new_iv (data, cand);
7115 if (dump_file && (dump_flags & TDF_DETAILS))
7117 fprintf (dump_file, "Selected IV set for loop %d",
7118 data->current_loop->num);
7119 if (data->loop_loc != UNKNOWN_LOCATION)
7120 fprintf (dump_file, " at %s:%d", LOCATION_FILE (data->loop_loc),
7121 LOCATION_LINE (data->loop_loc));
7122 fprintf (dump_file, ", " HOST_WIDE_INT_PRINT_DEC " avg niters",
7123 avg_loop_niter (data->current_loop));
7124 fprintf (dump_file, ", %lu IVs:\n", bitmap_count_bits (set->cands));
7125 EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
7127 cand = data->vcands[i];
7128 dump_cand (dump_file, cand);
7130 fprintf (dump_file, "\n");
7134 /* Rewrites USE (definition of iv used in a nonlinear expression)
7135 using candidate CAND. */
7137 static void
7138 rewrite_use_nonlinear_expr (struct ivopts_data *data,
7139 struct iv_use *use, struct iv_cand *cand)
7141 tree comp;
7142 tree tgt;
7143 gassign *ass;
7144 gimple_stmt_iterator bsi;
7146 /* An important special case -- if we are asked to express value of
7147 the original iv by itself, just exit; there is no need to
7148 introduce a new computation (that might also need casting the
7149 variable to unsigned and back). */
7150 if (cand->pos == IP_ORIGINAL
7151 && cand->incremented_at == use->stmt)
7153 tree op = NULL_TREE;
7154 enum tree_code stmt_code;
7156 gcc_assert (is_gimple_assign (use->stmt));
7157 gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
7159 /* Check whether we may leave the computation unchanged.
7160 This is the case only if it does not rely on other
7161 computations in the loop -- otherwise, the computation
7162 we rely upon may be removed in remove_unused_ivs,
7163 thus leading to ICE. */
7164 stmt_code = gimple_assign_rhs_code (use->stmt);
7165 if (stmt_code == PLUS_EXPR
7166 || stmt_code == MINUS_EXPR
7167 || stmt_code == POINTER_PLUS_EXPR)
7169 if (gimple_assign_rhs1 (use->stmt) == cand->var_before)
7170 op = gimple_assign_rhs2 (use->stmt);
7171 else if (gimple_assign_rhs2 (use->stmt) == cand->var_before)
7172 op = gimple_assign_rhs1 (use->stmt);
7175 if (op != NULL_TREE)
7177 if (expr_invariant_in_loop_p (data->current_loop, op))
7178 return;
7179 if (TREE_CODE (op) == SSA_NAME)
7181 struct iv *iv = get_iv (data, op);
7182 if (iv != NULL && integer_zerop (iv->step))
7183 return;
7188 comp = get_computation_at (data->current_loop, use->stmt, use, cand);
7189 gcc_assert (comp != NULL_TREE);
7191 switch (gimple_code (use->stmt))
7193 case GIMPLE_PHI:
7194 tgt = PHI_RESULT (use->stmt);
7196 /* If we should keep the biv, do not replace it. */
7197 if (name_info (data, tgt)->preserve_biv)
7198 return;
7200 bsi = gsi_after_labels (gimple_bb (use->stmt));
7201 break;
7203 case GIMPLE_ASSIGN:
7204 tgt = gimple_assign_lhs (use->stmt);
7205 bsi = gsi_for_stmt (use->stmt);
7206 break;
7208 default:
7209 gcc_unreachable ();
7212 if (!valid_gimple_rhs_p (comp)
7213 || (gimple_code (use->stmt) != GIMPLE_PHI
7214 /* We can't allow re-allocating the stmt as it might be pointed
7215 to still. */
7216 && (get_gimple_rhs_num_ops (TREE_CODE (comp))
7217 >= gimple_num_ops (gsi_stmt (bsi)))))
7219 comp = force_gimple_operand_gsi (&bsi, comp, true, NULL_TREE,
7220 true, GSI_SAME_STMT);
7221 if (POINTER_TYPE_P (TREE_TYPE (tgt)))
7223 duplicate_ssa_name_ptr_info (comp, SSA_NAME_PTR_INFO (tgt));
7224 /* As this isn't a plain copy we have to reset alignment
7225 information. */
7226 if (SSA_NAME_PTR_INFO (comp))
7227 mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (comp));
7231 if (gimple_code (use->stmt) == GIMPLE_PHI)
7233 ass = gimple_build_assign (tgt, comp);
7234 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
7236 bsi = gsi_for_stmt (use->stmt);
7237 remove_phi_node (&bsi, false);
7239 else
7241 gimple_assign_set_rhs_from_tree (&bsi, comp);
7242 use->stmt = gsi_stmt (bsi);
7246 /* Performs a peephole optimization to reorder the iv update statement with
7247 a mem ref to enable instruction combining in later phases. The mem ref uses
7248 the iv value before the update, so the reordering transformation requires
7249 adjustment of the offset. CAND is the selected IV_CAND.
7251 Example:
7253 t = MEM_REF (base, iv1, 8, 16); // base, index, stride, offset
7254 iv2 = iv1 + 1;
7256 if (t < val) (1)
7257 goto L;
7258 goto Head;
7261 directly propagating t over to (1) will introduce overlapping live range
7262 thus increase register pressure. This peephole transform it into:
7265 iv2 = iv1 + 1;
7266 t = MEM_REF (base, iv2, 8, 8);
7267 if (t < val)
7268 goto L;
7269 goto Head;
7272 static void
7273 adjust_iv_update_pos (struct iv_cand *cand, struct iv_use *use)
7275 tree var_after;
7276 gimple *iv_update, *stmt;
7277 basic_block bb;
7278 gimple_stmt_iterator gsi, gsi_iv;
7280 if (cand->pos != IP_NORMAL)
7281 return;
7283 var_after = cand->var_after;
7284 iv_update = SSA_NAME_DEF_STMT (var_after);
7286 bb = gimple_bb (iv_update);
7287 gsi = gsi_last_nondebug_bb (bb);
7288 stmt = gsi_stmt (gsi);
7290 /* Only handle conditional statement for now. */
7291 if (gimple_code (stmt) != GIMPLE_COND)
7292 return;
7294 gsi_prev_nondebug (&gsi);
7295 stmt = gsi_stmt (gsi);
7296 if (stmt != iv_update)
7297 return;
7299 gsi_prev_nondebug (&gsi);
7300 if (gsi_end_p (gsi))
7301 return;
7303 stmt = gsi_stmt (gsi);
7304 if (gimple_code (stmt) != GIMPLE_ASSIGN)
7305 return;
7307 if (stmt != use->stmt)
7308 return;
7310 if (TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
7311 return;
7313 if (dump_file && (dump_flags & TDF_DETAILS))
7315 fprintf (dump_file, "Reordering \n");
7316 print_gimple_stmt (dump_file, iv_update, 0, 0);
7317 print_gimple_stmt (dump_file, use->stmt, 0, 0);
7318 fprintf (dump_file, "\n");
7321 gsi = gsi_for_stmt (use->stmt);
7322 gsi_iv = gsi_for_stmt (iv_update);
7323 gsi_move_before (&gsi_iv, &gsi);
7325 cand->pos = IP_BEFORE_USE;
7326 cand->incremented_at = use->stmt;
7329 /* Rewrites USE (address that is an iv) using candidate CAND. */
7331 static void
7332 rewrite_use_address (struct ivopts_data *data,
7333 struct iv_use *use, struct iv_cand *cand)
7335 aff_tree aff;
7336 bool ok;
7338 adjust_iv_update_pos (cand, use);
7339 ok = get_computation_aff (data->current_loop, use, cand, use->stmt, &aff);
7340 gcc_assert (ok);
7341 unshare_aff_combination (&aff);
7343 /* To avoid undefined overflow problems, all IV candidates use unsigned
7344 integer types. The drawback is that this makes it impossible for
7345 create_mem_ref to distinguish an IV that is based on a memory object
7346 from one that represents simply an offset.
7348 To work around this problem, we pass a hint to create_mem_ref that
7349 indicates which variable (if any) in aff is an IV based on a memory
7350 object. Note that we only consider the candidate. If this is not
7351 based on an object, the base of the reference is in some subexpression
7352 of the use -- but these will use pointer types, so they are recognized
7353 by the create_mem_ref heuristics anyway. */
7354 tree iv = var_at_stmt (data->current_loop, cand, use->stmt);
7355 tree base_hint = (cand->iv->base_object) ? iv : NULL_TREE;
7356 gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
7357 tree type = TREE_TYPE (*use->op_p);
7358 unsigned int align = get_object_alignment (*use->op_p);
7359 if (align != TYPE_ALIGN (type))
7360 type = build_aligned_type (type, align);
7362 tree ref = create_mem_ref (&bsi, type, &aff,
7363 reference_alias_ptr_type (*use->op_p),
7364 iv, base_hint, data->speed);
7366 copy_ref_info (ref, *use->op_p);
7367 *use->op_p = ref;
7370 /* Rewrites USE (the condition such that one of the arguments is an iv) using
7371 candidate CAND. */
7373 static void
7374 rewrite_use_compare (struct ivopts_data *data,
7375 struct iv_use *use, struct iv_cand *cand)
7377 tree comp, *var_p, op, bound;
7378 gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
7379 enum tree_code compare;
7380 struct iv_group *group = data->vgroups[use->group_id];
7381 struct cost_pair *cp = get_group_iv_cost (data, group, cand);
7382 bool ok;
7384 bound = cp->value;
7385 if (bound)
7387 tree var = var_at_stmt (data->current_loop, cand, use->stmt);
7388 tree var_type = TREE_TYPE (var);
7389 gimple_seq stmts;
7391 if (dump_file && (dump_flags & TDF_DETAILS))
7393 fprintf (dump_file, "Replacing exit test: ");
7394 print_gimple_stmt (dump_file, use->stmt, 0, TDF_SLIM);
7396 compare = cp->comp;
7397 bound = unshare_expr (fold_convert (var_type, bound));
7398 op = force_gimple_operand (bound, &stmts, true, NULL_TREE);
7399 if (stmts)
7400 gsi_insert_seq_on_edge_immediate (
7401 loop_preheader_edge (data->current_loop),
7402 stmts);
7404 gcond *cond_stmt = as_a <gcond *> (use->stmt);
7405 gimple_cond_set_lhs (cond_stmt, var);
7406 gimple_cond_set_code (cond_stmt, compare);
7407 gimple_cond_set_rhs (cond_stmt, op);
7408 return;
7411 /* The induction variable elimination failed; just express the original
7412 giv. */
7413 comp = get_computation_at (data->current_loop, use->stmt, use, cand);
7414 gcc_assert (comp != NULL_TREE);
7416 ok = extract_cond_operands (data, use->stmt, &var_p, NULL, NULL, NULL);
7417 gcc_assert (ok);
7419 *var_p = force_gimple_operand_gsi (&bsi, comp, true, SSA_NAME_VAR (*var_p),
7420 true, GSI_SAME_STMT);
7423 /* Rewrite the groups using the selected induction variables. */
7425 static void
7426 rewrite_groups (struct ivopts_data *data)
7428 unsigned i, j;
7430 for (i = 0; i < data->vgroups.length (); i++)
7432 struct iv_group *group = data->vgroups[i];
7433 struct iv_cand *cand = group->selected;
7435 gcc_assert (cand);
7437 if (group->type == USE_NONLINEAR_EXPR)
7439 for (j = 0; j < group->vuses.length (); j++)
7441 rewrite_use_nonlinear_expr (data, group->vuses[j], cand);
7442 update_stmt (group->vuses[j]->stmt);
7445 else if (group->type == USE_ADDRESS)
7447 for (j = 0; j < group->vuses.length (); j++)
7449 rewrite_use_address (data, group->vuses[j], cand);
7450 update_stmt (group->vuses[j]->stmt);
7453 else
7455 gcc_assert (group->type == USE_COMPARE);
7457 for (j = 0; j < group->vuses.length (); j++)
7459 rewrite_use_compare (data, group->vuses[j], cand);
7460 update_stmt (group->vuses[j]->stmt);
7466 /* Removes the ivs that are not used after rewriting. */
7468 static void
7469 remove_unused_ivs (struct ivopts_data *data)
7471 unsigned j;
7472 bitmap_iterator bi;
7473 bitmap toremove = BITMAP_ALLOC (NULL);
7475 /* Figure out an order in which to release SSA DEFs so that we don't
7476 release something that we'd have to propagate into a debug stmt
7477 afterwards. */
7478 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
7480 struct version_info *info;
7482 info = ver_info (data, j);
7483 if (info->iv
7484 && !integer_zerop (info->iv->step)
7485 && !info->inv_id
7486 && !info->iv->nonlin_use
7487 && !info->preserve_biv)
7489 bitmap_set_bit (toremove, SSA_NAME_VERSION (info->iv->ssa_name));
7491 tree def = info->iv->ssa_name;
7493 if (MAY_HAVE_DEBUG_STMTS && SSA_NAME_DEF_STMT (def))
7495 imm_use_iterator imm_iter;
7496 use_operand_p use_p;
7497 gimple *stmt;
7498 int count = 0;
7500 FOR_EACH_IMM_USE_STMT (stmt, imm_iter, def)
7502 if (!gimple_debug_bind_p (stmt))
7503 continue;
7505 /* We just want to determine whether to do nothing
7506 (count == 0), to substitute the computed
7507 expression into a single use of the SSA DEF by
7508 itself (count == 1), or to use a debug temp
7509 because the SSA DEF is used multiple times or as
7510 part of a larger expression (count > 1). */
7511 count++;
7512 if (gimple_debug_bind_get_value (stmt) != def)
7513 count++;
7515 if (count > 1)
7516 BREAK_FROM_IMM_USE_STMT (imm_iter);
7519 if (!count)
7520 continue;
7522 struct iv_use dummy_use;
7523 struct iv_cand *best_cand = NULL, *cand;
7524 unsigned i, best_pref = 0, cand_pref;
7526 memset (&dummy_use, 0, sizeof (dummy_use));
7527 dummy_use.iv = info->iv;
7528 for (i = 0; i < data->vgroups.length () && i < 64; i++)
7530 cand = data->vgroups[i]->selected;
7531 if (cand == best_cand)
7532 continue;
7533 cand_pref = operand_equal_p (cand->iv->step,
7534 info->iv->step, 0)
7535 ? 4 : 0;
7536 cand_pref
7537 += TYPE_MODE (TREE_TYPE (cand->iv->base))
7538 == TYPE_MODE (TREE_TYPE (info->iv->base))
7539 ? 2 : 0;
7540 cand_pref
7541 += TREE_CODE (cand->iv->base) == INTEGER_CST
7542 ? 1 : 0;
7543 if (best_cand == NULL || best_pref < cand_pref)
7545 best_cand = cand;
7546 best_pref = cand_pref;
7550 if (!best_cand)
7551 continue;
7553 tree comp = get_computation_at (data->current_loop,
7554 SSA_NAME_DEF_STMT (def),
7555 &dummy_use, best_cand);
7556 if (!comp)
7557 continue;
7559 if (count > 1)
7561 tree vexpr = make_node (DEBUG_EXPR_DECL);
7562 DECL_ARTIFICIAL (vexpr) = 1;
7563 TREE_TYPE (vexpr) = TREE_TYPE (comp);
7564 if (SSA_NAME_VAR (def))
7565 SET_DECL_MODE (vexpr, DECL_MODE (SSA_NAME_VAR (def)));
7566 else
7567 SET_DECL_MODE (vexpr, TYPE_MODE (TREE_TYPE (vexpr)));
7568 gdebug *def_temp
7569 = gimple_build_debug_bind (vexpr, comp, NULL);
7570 gimple_stmt_iterator gsi;
7572 if (gimple_code (SSA_NAME_DEF_STMT (def)) == GIMPLE_PHI)
7573 gsi = gsi_after_labels (gimple_bb
7574 (SSA_NAME_DEF_STMT (def)));
7575 else
7576 gsi = gsi_for_stmt (SSA_NAME_DEF_STMT (def));
7578 gsi_insert_before (&gsi, def_temp, GSI_SAME_STMT);
7579 comp = vexpr;
7582 FOR_EACH_IMM_USE_STMT (stmt, imm_iter, def)
7584 if (!gimple_debug_bind_p (stmt))
7585 continue;
7587 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
7588 SET_USE (use_p, comp);
7590 update_stmt (stmt);
7596 release_defs_bitset (toremove);
7598 BITMAP_FREE (toremove);
7601 /* Frees memory occupied by struct tree_niter_desc in *VALUE. Callback
7602 for hash_map::traverse. */
7604 bool
7605 free_tree_niter_desc (edge const &, tree_niter_desc *const &value, void *)
7607 free (value);
7608 return true;
7611 /* Frees data allocated by the optimization of a single loop. */
7613 static void
7614 free_loop_data (struct ivopts_data *data)
7616 unsigned i, j;
7617 bitmap_iterator bi;
7618 tree obj;
7620 if (data->niters)
7622 data->niters->traverse<void *, free_tree_niter_desc> (NULL);
7623 delete data->niters;
7624 data->niters = NULL;
7627 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
7629 struct version_info *info;
7631 info = ver_info (data, i);
7632 info->iv = NULL;
7633 info->has_nonlin_use = false;
7634 info->preserve_biv = false;
7635 info->inv_id = 0;
7637 bitmap_clear (data->relevant);
7638 bitmap_clear (data->important_candidates);
7640 for (i = 0; i < data->vgroups.length (); i++)
7642 struct iv_group *group = data->vgroups[i];
7644 for (j = 0; j < group->vuses.length (); j++)
7645 free (group->vuses[j]);
7646 group->vuses.release ();
7648 BITMAP_FREE (group->related_cands);
7649 for (j = 0; j < group->n_map_members; j++)
7651 if (group->cost_map[j].inv_vars)
7652 BITMAP_FREE (group->cost_map[j].inv_vars);
7653 if (group->cost_map[j].inv_exprs)
7654 BITMAP_FREE (group->cost_map[j].inv_exprs);
7657 free (group->cost_map);
7658 free (group);
7660 data->vgroups.truncate (0);
7662 for (i = 0; i < data->vcands.length (); i++)
7664 struct iv_cand *cand = data->vcands[i];
7666 if (cand->inv_vars)
7667 BITMAP_FREE (cand->inv_vars);
7668 free (cand);
7670 data->vcands.truncate (0);
7672 if (data->version_info_size < num_ssa_names)
7674 data->version_info_size = 2 * num_ssa_names;
7675 free (data->version_info);
7676 data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
7679 data->max_inv_var_id = 0;
7680 data->max_inv_expr_id = 0;
7682 FOR_EACH_VEC_ELT (decl_rtl_to_reset, i, obj)
7683 SET_DECL_RTL (obj, NULL_RTX);
7685 decl_rtl_to_reset.truncate (0);
7687 data->inv_expr_tab->empty ();
7689 data->iv_common_cand_tab->empty ();
7690 data->iv_common_cands.truncate (0);
7693 /* Finalizes data structures used by the iv optimization pass. LOOPS is the
7694 loop tree. */
7696 static void
7697 tree_ssa_iv_optimize_finalize (struct ivopts_data *data)
7699 free_loop_data (data);
7700 free (data->version_info);
7701 BITMAP_FREE (data->relevant);
7702 BITMAP_FREE (data->important_candidates);
7704 decl_rtl_to_reset.release ();
7705 data->vgroups.release ();
7706 data->vcands.release ();
7707 delete data->inv_expr_tab;
7708 data->inv_expr_tab = NULL;
7709 free_affine_expand_cache (&data->name_expansion_cache);
7710 delete data->iv_common_cand_tab;
7711 data->iv_common_cand_tab = NULL;
7712 data->iv_common_cands.release ();
7713 obstack_free (&data->iv_obstack, NULL);
7716 /* Returns true if the loop body BODY includes any function calls. */
7718 static bool
7719 loop_body_includes_call (basic_block *body, unsigned num_nodes)
7721 gimple_stmt_iterator gsi;
7722 unsigned i;
7724 for (i = 0; i < num_nodes; i++)
7725 for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
7727 gimple *stmt = gsi_stmt (gsi);
7728 if (is_gimple_call (stmt)
7729 && !gimple_call_internal_p (stmt)
7730 && !is_inexpensive_builtin (gimple_call_fndecl (stmt)))
7731 return true;
7733 return false;
7736 /* Optimizes the LOOP. Returns true if anything changed. */
7738 static bool
7739 tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
7741 bool changed = false;
7742 struct iv_ca *iv_ca;
7743 edge exit = single_dom_exit (loop);
7744 basic_block *body;
7746 gcc_assert (!data->niters);
7747 data->current_loop = loop;
7748 data->loop_loc = find_loop_location (loop);
7749 data->speed = optimize_loop_for_speed_p (loop);
7751 if (dump_file && (dump_flags & TDF_DETAILS))
7753 fprintf (dump_file, "Processing loop %d", loop->num);
7754 if (data->loop_loc != UNKNOWN_LOCATION)
7755 fprintf (dump_file, " at %s:%d", LOCATION_FILE (data->loop_loc),
7756 LOCATION_LINE (data->loop_loc));
7757 fprintf (dump_file, "\n");
7759 if (exit)
7761 fprintf (dump_file, " single exit %d -> %d, exit condition ",
7762 exit->src->index, exit->dest->index);
7763 print_gimple_stmt (dump_file, last_stmt (exit->src), 0, TDF_SLIM);
7764 fprintf (dump_file, "\n");
7767 fprintf (dump_file, "\n");
7770 body = get_loop_body (loop);
7771 data->body_includes_call = loop_body_includes_call (body, loop->num_nodes);
7772 renumber_gimple_stmt_uids_in_blocks (body, loop->num_nodes);
7773 free (body);
7775 data->loop_single_exit_p = exit != NULL && loop_only_exit_p (loop, exit);
7777 /* For each ssa name determines whether it behaves as an induction variable
7778 in some loop. */
7779 if (!find_induction_variables (data))
7780 goto finish;
7782 /* Finds interesting uses (item 1). */
7783 find_interesting_uses (data);
7784 if (data->vgroups.length () > MAX_CONSIDERED_GROUPS)
7785 goto finish;
7787 /* Finds candidates for the induction variables (item 2). */
7788 find_iv_candidates (data);
7790 /* Calculates the costs (item 3, part 1). */
7791 determine_iv_costs (data);
7792 determine_group_iv_costs (data);
7793 determine_set_costs (data);
7795 /* Find the optimal set of induction variables (item 3, part 2). */
7796 iv_ca = find_optimal_iv_set (data);
7797 if (!iv_ca)
7798 goto finish;
7799 changed = true;
7801 /* Create the new induction variables (item 4, part 1). */
7802 create_new_ivs (data, iv_ca);
7803 iv_ca_free (&iv_ca);
7805 /* Rewrite the uses (item 4, part 2). */
7806 rewrite_groups (data);
7808 /* Remove the ivs that are unused after rewriting. */
7809 remove_unused_ivs (data);
7811 /* We have changed the structure of induction variables; it might happen
7812 that definitions in the scev database refer to some of them that were
7813 eliminated. */
7814 scev_reset ();
7816 finish:
7817 free_loop_data (data);
7819 return changed;
7822 /* Main entry point. Optimizes induction variables in loops. */
7824 void
7825 tree_ssa_iv_optimize (void)
7827 struct loop *loop;
7828 struct ivopts_data data;
7830 tree_ssa_iv_optimize_init (&data);
7832 /* Optimize the loops starting with the innermost ones. */
7833 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
7835 if (dump_file && (dump_flags & TDF_DETAILS))
7836 flow_loop_dump (loop, dump_file, NULL, 1);
7838 tree_ssa_iv_optimize_loop (&data, loop);
7841 tree_ssa_iv_optimize_finalize (&data);