2015-06-11 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / gimple-ssa-strength-reduction.c
blobe5e9b6de8c527233f01a07e51f171acfe558c50d
1 /* Straight-line strength reduction.
2 Copyright (C) 2012-2015 Free Software Foundation, Inc.
3 Contributed by Bill Schmidt, IBM <wschmidt@linux.ibm.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* There are many algorithms for performing strength reduction on
22 loops. This is not one of them. IVOPTS handles strength reduction
23 of induction variables just fine. This pass is intended to pick
24 up the crumbs it leaves behind, by considering opportunities for
25 strength reduction along dominator paths.
27 Strength reduction addresses explicit multiplies, and certain
28 multiplies implicit in addressing expressions. It would also be
29 possible to apply strength reduction to divisions and modulos,
30 but such opportunities are relatively uncommon.
32 Strength reduction is also currently restricted to integer operations.
33 If desired, it could be extended to floating-point operations under
34 control of something like -funsafe-math-optimizations. */
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "input.h"
40 #include "alias.h"
41 #include "symtab.h"
42 #include "options.h"
43 #include "tree.h"
44 #include "fold-const.h"
45 #include "predict.h"
46 #include "tm.h"
47 #include "hard-reg-set.h"
48 #include "function.h"
49 #include "dominance.h"
50 #include "cfg.h"
51 #include "basic-block.h"
52 #include "tree-ssa-alias.h"
53 #include "internal-fn.h"
54 #include "gimple-expr.h"
55 #include "is-a.h"
56 #include "gimple.h"
57 #include "gimple-iterator.h"
58 #include "gimplify-me.h"
59 #include "stor-layout.h"
60 #include "rtl.h"
61 #include "flags.h"
62 #include "insn-config.h"
63 #include "expmed.h"
64 #include "dojump.h"
65 #include "explow.h"
66 #include "calls.h"
67 #include "emit-rtl.h"
68 #include "varasm.h"
69 #include "stmt.h"
70 #include "expr.h"
71 #include "tree-pass.h"
72 #include "cfgloop.h"
73 #include "gimple-pretty-print.h"
74 #include "gimple-ssa.h"
75 #include "tree-cfg.h"
76 #include "tree-phinodes.h"
77 #include "ssa-iterators.h"
78 #include "stringpool.h"
79 #include "tree-ssanames.h"
80 #include "domwalk.h"
81 #include "params.h"
82 #include "tree-ssa-address.h"
83 #include "tree-affine.h"
84 #include "wide-int-print.h"
85 #include "builtins.h"
87 /* Information about a strength reduction candidate. Each statement
88 in the candidate table represents an expression of one of the
89 following forms (the special case of CAND_REF will be described
90 later):
92 (CAND_MULT) S1: X = (B + i) * S
93 (CAND_ADD) S1: X = B + (i * S)
95 Here X and B are SSA names, i is an integer constant, and S is
96 either an SSA name or a constant. We call B the "base," i the
97 "index", and S the "stride."
99 Any statement S0 that dominates S1 and is of the form:
101 (CAND_MULT) S0: Y = (B + i') * S
102 (CAND_ADD) S0: Y = B + (i' * S)
104 is called a "basis" for S1. In both cases, S1 may be replaced by
106 S1': X = Y + (i - i') * S,
108 where (i - i') * S is folded to the extent possible.
110 All gimple statements are visited in dominator order, and each
111 statement that may contribute to one of the forms of S1 above is
112 given at least one entry in the candidate table. Such statements
113 include addition, pointer addition, subtraction, multiplication,
114 negation, copies, and nontrivial type casts. If a statement may
115 represent more than one expression of the forms of S1 above,
116 multiple "interpretations" are stored in the table and chained
117 together. Examples:
119 * An add of two SSA names may treat either operand as the base.
120 * A multiply of two SSA names, likewise.
121 * A copy or cast may be thought of as either a CAND_MULT with
122 i = 0 and S = 1, or as a CAND_ADD with i = 0 or S = 0.
124 Candidate records are allocated from an obstack. They are addressed
125 both from a hash table keyed on S1, and from a vector of candidate
126 pointers arranged in predominator order.
128 Opportunity note
129 ----------------
130 Currently we don't recognize:
132 S0: Y = (S * i') - B
133 S1: X = (S * i) - B
135 as a strength reduction opportunity, even though this S1 would
136 also be replaceable by the S1' above. This can be added if it
137 comes up in practice.
139 Strength reduction in addressing
140 --------------------------------
141 There is another kind of candidate known as CAND_REF. A CAND_REF
142 describes a statement containing a memory reference having
143 complex addressing that might benefit from strength reduction.
144 Specifically, we are interested in references for which
145 get_inner_reference returns a base address, offset, and bitpos as
146 follows:
148 base: MEM_REF (T1, C1)
149 offset: MULT_EXPR (PLUS_EXPR (T2, C2), C3)
150 bitpos: C4 * BITS_PER_UNIT
152 Here T1 and T2 are arbitrary trees, and C1, C2, C3, C4 are
153 arbitrary integer constants. Note that C2 may be zero, in which
154 case the offset will be MULT_EXPR (T2, C3).
156 When this pattern is recognized, the original memory reference
157 can be replaced with:
159 MEM_REF (POINTER_PLUS_EXPR (T1, MULT_EXPR (T2, C3)),
160 C1 + (C2 * C3) + C4)
162 which distributes the multiply to allow constant folding. When
163 two or more addressing expressions can be represented by MEM_REFs
164 of this form, differing only in the constants C1, C2, and C4,
165 making this substitution produces more efficient addressing during
166 the RTL phases. When there are not at least two expressions with
167 the same values of T1, T2, and C3, there is nothing to be gained
168 by the replacement.
170 Strength reduction of CAND_REFs uses the same infrastructure as
171 that used by CAND_MULTs and CAND_ADDs. We record T1 in the base (B)
172 field, MULT_EXPR (T2, C3) in the stride (S) field, and
173 C1 + (C2 * C3) + C4 in the index (i) field. A basis for a CAND_REF
174 is thus another CAND_REF with the same B and S values. When at
175 least two CAND_REFs are chained together using the basis relation,
176 each of them is replaced as above, resulting in improved code
177 generation for addressing.
179 Conditional candidates
180 ======================
182 Conditional candidates are best illustrated with an example.
183 Consider the code sequence:
185 (1) x_0 = ...;
186 (2) a_0 = x_0 * 5; MULT (B: x_0; i: 0; S: 5)
187 if (...)
188 (3) x_1 = x_0 + 1; ADD (B: x_0, i: 1; S: 1)
189 (4) x_2 = PHI <x_0, x_1>; PHI (B: x_0, i: 0, S: 1)
190 (5) x_3 = x_2 + 1; ADD (B: x_2, i: 1, S: 1)
191 (6) a_1 = x_3 * 5; MULT (B: x_2, i: 1; S: 5)
193 Here strength reduction is complicated by the uncertain value of x_2.
194 A legitimate transformation is:
196 (1) x_0 = ...;
197 (2) a_0 = x_0 * 5;
198 if (...)
200 (3) [x_1 = x_0 + 1;]
201 (3a) t_1 = a_0 + 5;
203 (4) [x_2 = PHI <x_0, x_1>;]
204 (4a) t_2 = PHI <a_0, t_1>;
205 (5) [x_3 = x_2 + 1;]
206 (6r) a_1 = t_2 + 5;
208 where the bracketed instructions may go dead.
210 To recognize this opportunity, we have to observe that statement (6)
211 has a "hidden basis" (2). The hidden basis is unlike a normal basis
212 in that the statement and the hidden basis have different base SSA
213 names (x_2 and x_0, respectively). The relationship is established
214 when a statement's base name (x_2) is defined by a phi statement (4),
215 each argument of which (x_0, x_1) has an identical "derived base name."
216 If the argument is defined by a candidate (as x_1 is by (3)) that is a
217 CAND_ADD having a stride of 1, the derived base name of the argument is
218 the base name of the candidate (x_0). Otherwise, the argument itself
219 is its derived base name (as is the case with argument x_0).
221 The hidden basis for statement (6) is the nearest dominating candidate
222 whose base name is the derived base name (x_0) of the feeding phi (4),
223 and whose stride is identical to that of the statement. We can then
224 create the new "phi basis" (4a) and feeding adds along incoming arcs (3a),
225 allowing the final replacement of (6) by the strength-reduced (6r).
227 To facilitate this, a new kind of candidate (CAND_PHI) is introduced.
228 A CAND_PHI is not a candidate for replacement, but is maintained in the
229 candidate table to ease discovery of hidden bases. Any phi statement
230 whose arguments share a common derived base name is entered into the
231 table with the derived base name, an (arbitrary) index of zero, and a
232 stride of 1. A statement with a hidden basis can then be detected by
233 simply looking up its feeding phi definition in the candidate table,
234 extracting the derived base name, and searching for a basis in the
235 usual manner after substituting the derived base name.
237 Note that the transformation is only valid when the original phi and
238 the statements that define the phi's arguments are all at the same
239 position in the loop hierarchy. */
242 /* Index into the candidate vector, offset by 1. VECs are zero-based,
243 while cand_idx's are one-based, with zero indicating null. */
244 typedef unsigned cand_idx;
246 /* The kind of candidate. */
247 enum cand_kind
249 CAND_MULT,
250 CAND_ADD,
251 CAND_REF,
252 CAND_PHI
255 struct slsr_cand_d
257 /* The candidate statement S1. */
258 gimple cand_stmt;
260 /* The base expression B: often an SSA name, but not always. */
261 tree base_expr;
263 /* The stride S. */
264 tree stride;
266 /* The index constant i. */
267 widest_int index;
269 /* The type of the candidate. This is normally the type of base_expr,
270 but casts may have occurred when combining feeding instructions.
271 A candidate can only be a basis for candidates of the same final type.
272 (For CAND_REFs, this is the type to be used for operand 1 of the
273 replacement MEM_REF.) */
274 tree cand_type;
276 /* The kind of candidate (CAND_MULT, etc.). */
277 enum cand_kind kind;
279 /* Index of this candidate in the candidate vector. */
280 cand_idx cand_num;
282 /* Index of the next candidate record for the same statement.
283 A statement may be useful in more than one way (e.g., due to
284 commutativity). So we can have multiple "interpretations"
285 of a statement. */
286 cand_idx next_interp;
288 /* Index of the basis statement S0, if any, in the candidate vector. */
289 cand_idx basis;
291 /* First candidate for which this candidate is a basis, if one exists. */
292 cand_idx dependent;
294 /* Next candidate having the same basis as this one. */
295 cand_idx sibling;
297 /* If this is a conditional candidate, the CAND_PHI candidate
298 that defines the base SSA name B. */
299 cand_idx def_phi;
301 /* Savings that can be expected from eliminating dead code if this
302 candidate is replaced. */
303 int dead_savings;
306 typedef struct slsr_cand_d slsr_cand, *slsr_cand_t;
307 typedef const struct slsr_cand_d *const_slsr_cand_t;
309 /* Pointers to candidates are chained together as part of a mapping
310 from base expressions to the candidates that use them. */
312 struct cand_chain_d
314 /* Base expression for the chain of candidates: often, but not
315 always, an SSA name. */
316 tree base_expr;
318 /* Pointer to a candidate. */
319 slsr_cand_t cand;
321 /* Chain pointer. */
322 struct cand_chain_d *next;
326 typedef struct cand_chain_d cand_chain, *cand_chain_t;
327 typedef const struct cand_chain_d *const_cand_chain_t;
329 /* Information about a unique "increment" associated with candidates
330 having an SSA name for a stride. An increment is the difference
331 between the index of the candidate and the index of its basis,
332 i.e., (i - i') as discussed in the module commentary.
334 When we are not going to generate address arithmetic we treat
335 increments that differ only in sign as the same, allowing sharing
336 of the cost of initializers. The absolute value of the increment
337 is stored in the incr_info. */
339 struct incr_info_d
341 /* The increment that relates a candidate to its basis. */
342 widest_int incr;
344 /* How many times the increment occurs in the candidate tree. */
345 unsigned count;
347 /* Cost of replacing candidates using this increment. Negative and
348 zero costs indicate replacement should be performed. */
349 int cost;
351 /* If this increment is profitable but is not -1, 0, or 1, it requires
352 an initializer T_0 = stride * incr to be found or introduced in the
353 nearest common dominator of all candidates. This field holds T_0
354 for subsequent use. */
355 tree initializer;
357 /* If the initializer was found to already exist, this is the block
358 where it was found. */
359 basic_block init_bb;
362 typedef struct incr_info_d incr_info, *incr_info_t;
364 /* Candidates are maintained in a vector. If candidate X dominates
365 candidate Y, then X appears before Y in the vector; but the
366 converse does not necessarily hold. */
367 static vec<slsr_cand_t> cand_vec;
369 enum cost_consts
371 COST_NEUTRAL = 0,
372 COST_INFINITE = 1000
375 enum stride_status
377 UNKNOWN_STRIDE = 0,
378 KNOWN_STRIDE = 1
381 enum phi_adjust_status
383 NOT_PHI_ADJUST = 0,
384 PHI_ADJUST = 1
387 enum count_phis_status
389 DONT_COUNT_PHIS = 0,
390 COUNT_PHIS = 1
393 /* Pointer map embodying a mapping from statements to candidates. */
394 static hash_map<gimple, slsr_cand_t> *stmt_cand_map;
396 /* Obstack for candidates. */
397 static struct obstack cand_obstack;
399 /* Obstack for candidate chains. */
400 static struct obstack chain_obstack;
402 /* An array INCR_VEC of incr_infos is used during analysis of related
403 candidates having an SSA name for a stride. INCR_VEC_LEN describes
404 its current length. MAX_INCR_VEC_LEN is used to avoid costly
405 pathological cases. */
406 static incr_info_t incr_vec;
407 static unsigned incr_vec_len;
408 const int MAX_INCR_VEC_LEN = 16;
410 /* For a chain of candidates with unknown stride, indicates whether or not
411 we must generate pointer arithmetic when replacing statements. */
412 static bool address_arithmetic_p;
414 /* Forward function declarations. */
415 static slsr_cand_t base_cand_from_table (tree);
416 static tree introduce_cast_before_cand (slsr_cand_t, tree, tree);
417 static bool legal_cast_p_1 (tree, tree);
419 /* Produce a pointer to the IDX'th candidate in the candidate vector. */
421 static slsr_cand_t
422 lookup_cand (cand_idx idx)
424 return cand_vec[idx - 1];
427 /* Helper for hashing a candidate chain header. */
429 struct cand_chain_hasher : typed_noop_remove <cand_chain>
431 typedef cand_chain *value_type;
432 typedef cand_chain *compare_type;
433 static inline hashval_t hash (const cand_chain *);
434 static inline bool equal (const cand_chain *, const cand_chain *);
437 inline hashval_t
438 cand_chain_hasher::hash (const cand_chain *p)
440 tree base_expr = p->base_expr;
441 return iterative_hash_expr (base_expr, 0);
444 inline bool
445 cand_chain_hasher::equal (const cand_chain *chain1, const cand_chain *chain2)
447 return operand_equal_p (chain1->base_expr, chain2->base_expr, 0);
450 /* Hash table embodying a mapping from base exprs to chains of candidates. */
451 static hash_table<cand_chain_hasher> *base_cand_map;
453 /* Pointer map used by tree_to_aff_combination_expand. */
454 static hash_map<tree, name_expansion *> *name_expansions;
455 /* Pointer map embodying a mapping from bases to alternative bases. */
456 static hash_map<tree, tree> *alt_base_map;
458 /* Given BASE, use the tree affine combiniation facilities to
459 find the underlying tree expression for BASE, with any
460 immediate offset excluded.
462 N.B. we should eliminate this backtracking with better forward
463 analysis in a future release. */
465 static tree
466 get_alternative_base (tree base)
468 tree *result = alt_base_map->get (base);
470 if (result == NULL)
472 tree expr;
473 aff_tree aff;
475 tree_to_aff_combination_expand (base, TREE_TYPE (base),
476 &aff, &name_expansions);
477 aff.offset = 0;
478 expr = aff_combination_to_tree (&aff);
480 gcc_assert (!alt_base_map->put (base, base == expr ? NULL : expr));
482 return expr == base ? NULL : expr;
485 return *result;
488 /* Look in the candidate table for a CAND_PHI that defines BASE and
489 return it if found; otherwise return NULL. */
491 static cand_idx
492 find_phi_def (tree base)
494 slsr_cand_t c;
496 if (TREE_CODE (base) != SSA_NAME)
497 return 0;
499 c = base_cand_from_table (base);
501 if (!c || c->kind != CAND_PHI)
502 return 0;
504 return c->cand_num;
507 /* Helper routine for find_basis_for_candidate. May be called twice:
508 once for the candidate's base expr, and optionally again either for
509 the candidate's phi definition or for a CAND_REF's alternative base
510 expression. */
512 static slsr_cand_t
513 find_basis_for_base_expr (slsr_cand_t c, tree base_expr)
515 cand_chain mapping_key;
516 cand_chain_t chain;
517 slsr_cand_t basis = NULL;
519 // Limit potential of N^2 behavior for long candidate chains.
520 int iters = 0;
521 int max_iters = PARAM_VALUE (PARAM_MAX_SLSR_CANDIDATE_SCAN);
523 mapping_key.base_expr = base_expr;
524 chain = base_cand_map->find (&mapping_key);
526 for (; chain && iters < max_iters; chain = chain->next, ++iters)
528 slsr_cand_t one_basis = chain->cand;
530 if (one_basis->kind != c->kind
531 || one_basis->cand_stmt == c->cand_stmt
532 || !operand_equal_p (one_basis->stride, c->stride, 0)
533 || !types_compatible_p (one_basis->cand_type, c->cand_type)
534 || !dominated_by_p (CDI_DOMINATORS,
535 gimple_bb (c->cand_stmt),
536 gimple_bb (one_basis->cand_stmt)))
537 continue;
539 if (!basis || basis->cand_num < one_basis->cand_num)
540 basis = one_basis;
543 return basis;
546 /* Use the base expr from candidate C to look for possible candidates
547 that can serve as a basis for C. Each potential basis must also
548 appear in a block that dominates the candidate statement and have
549 the same stride and type. If more than one possible basis exists,
550 the one with highest index in the vector is chosen; this will be
551 the most immediately dominating basis. */
553 static int
554 find_basis_for_candidate (slsr_cand_t c)
556 slsr_cand_t basis = find_basis_for_base_expr (c, c->base_expr);
558 /* If a candidate doesn't have a basis using its base expression,
559 it may have a basis hidden by one or more intervening phis. */
560 if (!basis && c->def_phi)
562 basic_block basis_bb, phi_bb;
563 slsr_cand_t phi_cand = lookup_cand (c->def_phi);
564 basis = find_basis_for_base_expr (c, phi_cand->base_expr);
566 if (basis)
568 /* A hidden basis must dominate the phi-definition of the
569 candidate's base name. */
570 phi_bb = gimple_bb (phi_cand->cand_stmt);
571 basis_bb = gimple_bb (basis->cand_stmt);
573 if (phi_bb == basis_bb
574 || !dominated_by_p (CDI_DOMINATORS, phi_bb, basis_bb))
576 basis = NULL;
577 c->basis = 0;
580 /* If we found a hidden basis, estimate additional dead-code
581 savings if the phi and its feeding statements can be removed. */
582 if (basis && has_single_use (gimple_phi_result (phi_cand->cand_stmt)))
583 c->dead_savings += phi_cand->dead_savings;
587 if (flag_expensive_optimizations && !basis && c->kind == CAND_REF)
589 tree alt_base_expr = get_alternative_base (c->base_expr);
590 if (alt_base_expr)
591 basis = find_basis_for_base_expr (c, alt_base_expr);
594 if (basis)
596 c->sibling = basis->dependent;
597 basis->dependent = c->cand_num;
598 return basis->cand_num;
601 return 0;
604 /* Record a mapping from BASE to C, indicating that C may potentially serve
605 as a basis using that base expression. BASE may be the same as
606 C->BASE_EXPR; alternatively BASE can be a different tree that share the
607 underlining expression of C->BASE_EXPR. */
609 static void
610 record_potential_basis (slsr_cand_t c, tree base)
612 cand_chain_t node;
613 cand_chain **slot;
615 gcc_assert (base);
617 node = (cand_chain_t) obstack_alloc (&chain_obstack, sizeof (cand_chain));
618 node->base_expr = base;
619 node->cand = c;
620 node->next = NULL;
621 slot = base_cand_map->find_slot (node, INSERT);
623 if (*slot)
625 cand_chain_t head = (cand_chain_t) (*slot);
626 node->next = head->next;
627 head->next = node;
629 else
630 *slot = node;
633 /* Allocate storage for a new candidate and initialize its fields.
634 Attempt to find a basis for the candidate.
636 For CAND_REF, an alternative base may also be recorded and used
637 to find a basis. This helps cases where the expression hidden
638 behind BASE (which is usually an SSA_NAME) has immediate offset,
639 e.g.
641 a2[i][j] = 1;
642 a2[i + 20][j] = 2; */
644 static slsr_cand_t
645 alloc_cand_and_find_basis (enum cand_kind kind, gimple gs, tree base,
646 const widest_int &index, tree stride, tree ctype,
647 unsigned savings)
649 slsr_cand_t c = (slsr_cand_t) obstack_alloc (&cand_obstack,
650 sizeof (slsr_cand));
651 c->cand_stmt = gs;
652 c->base_expr = base;
653 c->stride = stride;
654 c->index = index;
655 c->cand_type = ctype;
656 c->kind = kind;
657 c->cand_num = cand_vec.length () + 1;
658 c->next_interp = 0;
659 c->dependent = 0;
660 c->sibling = 0;
661 c->def_phi = kind == CAND_MULT ? find_phi_def (base) : 0;
662 c->dead_savings = savings;
664 cand_vec.safe_push (c);
666 if (kind == CAND_PHI)
667 c->basis = 0;
668 else
669 c->basis = find_basis_for_candidate (c);
671 record_potential_basis (c, base);
672 if (flag_expensive_optimizations && kind == CAND_REF)
674 tree alt_base = get_alternative_base (base);
675 if (alt_base)
676 record_potential_basis (c, alt_base);
679 return c;
682 /* Determine the target cost of statement GS when compiling according
683 to SPEED. */
685 static int
686 stmt_cost (gimple gs, bool speed)
688 tree lhs, rhs1, rhs2;
689 machine_mode lhs_mode;
691 gcc_assert (is_gimple_assign (gs));
692 lhs = gimple_assign_lhs (gs);
693 rhs1 = gimple_assign_rhs1 (gs);
694 lhs_mode = TYPE_MODE (TREE_TYPE (lhs));
696 switch (gimple_assign_rhs_code (gs))
698 case MULT_EXPR:
699 rhs2 = gimple_assign_rhs2 (gs);
701 if (tree_fits_shwi_p (rhs2))
702 return mult_by_coeff_cost (tree_to_shwi (rhs2), lhs_mode, speed);
704 gcc_assert (TREE_CODE (rhs1) != INTEGER_CST);
705 return mul_cost (speed, lhs_mode);
707 case PLUS_EXPR:
708 case POINTER_PLUS_EXPR:
709 case MINUS_EXPR:
710 return add_cost (speed, lhs_mode);
712 case NEGATE_EXPR:
713 return neg_cost (speed, lhs_mode);
715 CASE_CONVERT:
716 return convert_cost (lhs_mode, TYPE_MODE (TREE_TYPE (rhs1)), speed);
718 /* Note that we don't assign costs to copies that in most cases
719 will go away. */
720 default:
724 gcc_unreachable ();
725 return 0;
728 /* Look up the defining statement for BASE_IN and return a pointer
729 to its candidate in the candidate table, if any; otherwise NULL.
730 Only CAND_ADD and CAND_MULT candidates are returned. */
732 static slsr_cand_t
733 base_cand_from_table (tree base_in)
735 slsr_cand_t *result;
737 gimple def = SSA_NAME_DEF_STMT (base_in);
738 if (!def)
739 return (slsr_cand_t) NULL;
741 result = stmt_cand_map->get (def);
743 if (result && (*result)->kind != CAND_REF)
744 return *result;
746 return (slsr_cand_t) NULL;
749 /* Add an entry to the statement-to-candidate mapping. */
751 static void
752 add_cand_for_stmt (gimple gs, slsr_cand_t c)
754 gcc_assert (!stmt_cand_map->put (gs, c));
757 /* Given PHI which contains a phi statement, determine whether it
758 satisfies all the requirements of a phi candidate. If so, create
759 a candidate. Note that a CAND_PHI never has a basis itself, but
760 is used to help find a basis for subsequent candidates. */
762 static void
763 slsr_process_phi (gphi *phi, bool speed)
765 unsigned i;
766 tree arg0_base = NULL_TREE, base_type;
767 slsr_cand_t c;
768 struct loop *cand_loop = gimple_bb (phi)->loop_father;
769 unsigned savings = 0;
771 /* A CAND_PHI requires each of its arguments to have the same
772 derived base name. (See the module header commentary for a
773 definition of derived base names.) Furthermore, all feeding
774 definitions must be in the same position in the loop hierarchy
775 as PHI. */
777 for (i = 0; i < gimple_phi_num_args (phi); i++)
779 slsr_cand_t arg_cand;
780 tree arg = gimple_phi_arg_def (phi, i);
781 tree derived_base_name = NULL_TREE;
782 gimple arg_stmt = NULL;
783 basic_block arg_bb = NULL;
785 if (TREE_CODE (arg) != SSA_NAME)
786 return;
788 arg_cand = base_cand_from_table (arg);
790 if (arg_cand)
792 while (arg_cand->kind != CAND_ADD && arg_cand->kind != CAND_PHI)
794 if (!arg_cand->next_interp)
795 return;
797 arg_cand = lookup_cand (arg_cand->next_interp);
800 if (!integer_onep (arg_cand->stride))
801 return;
803 derived_base_name = arg_cand->base_expr;
804 arg_stmt = arg_cand->cand_stmt;
805 arg_bb = gimple_bb (arg_stmt);
807 /* Gather potential dead code savings if the phi statement
808 can be removed later on. */
809 if (has_single_use (arg))
811 if (gimple_code (arg_stmt) == GIMPLE_PHI)
812 savings += arg_cand->dead_savings;
813 else
814 savings += stmt_cost (arg_stmt, speed);
817 else
819 derived_base_name = arg;
821 if (SSA_NAME_IS_DEFAULT_DEF (arg))
822 arg_bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
823 else
824 gimple_bb (SSA_NAME_DEF_STMT (arg));
827 if (!arg_bb || arg_bb->loop_father != cand_loop)
828 return;
830 if (i == 0)
831 arg0_base = derived_base_name;
832 else if (!operand_equal_p (derived_base_name, arg0_base, 0))
833 return;
836 /* Create the candidate. "alloc_cand_and_find_basis" is named
837 misleadingly for this case, as no basis will be sought for a
838 CAND_PHI. */
839 base_type = TREE_TYPE (arg0_base);
841 c = alloc_cand_and_find_basis (CAND_PHI, phi, arg0_base,
842 0, integer_one_node, base_type, savings);
844 /* Add the candidate to the statement-candidate mapping. */
845 add_cand_for_stmt (phi, c);
848 /* Given PBASE which is a pointer to tree, look up the defining
849 statement for it and check whether the candidate is in the
850 form of:
852 X = B + (1 * S), S is integer constant
853 X = B + (i * S), S is integer one
855 If so, set PBASE to the candidate's base_expr and return double
856 int (i * S).
857 Otherwise, just return double int zero. */
859 static widest_int
860 backtrace_base_for_ref (tree *pbase)
862 tree base_in = *pbase;
863 slsr_cand_t base_cand;
865 STRIP_NOPS (base_in);
867 /* Strip off widening conversion(s) to handle cases where
868 e.g. 'B' is widened from an 'int' in order to calculate
869 a 64-bit address. */
870 if (CONVERT_EXPR_P (base_in)
871 && legal_cast_p_1 (base_in, TREE_OPERAND (base_in, 0)))
872 base_in = get_unwidened (base_in, NULL_TREE);
874 if (TREE_CODE (base_in) != SSA_NAME)
875 return 0;
877 base_cand = base_cand_from_table (base_in);
879 while (base_cand && base_cand->kind != CAND_PHI)
881 if (base_cand->kind == CAND_ADD
882 && base_cand->index == 1
883 && TREE_CODE (base_cand->stride) == INTEGER_CST)
885 /* X = B + (1 * S), S is integer constant. */
886 *pbase = base_cand->base_expr;
887 return wi::to_widest (base_cand->stride);
889 else if (base_cand->kind == CAND_ADD
890 && TREE_CODE (base_cand->stride) == INTEGER_CST
891 && integer_onep (base_cand->stride))
893 /* X = B + (i * S), S is integer one. */
894 *pbase = base_cand->base_expr;
895 return base_cand->index;
898 if (base_cand->next_interp)
899 base_cand = lookup_cand (base_cand->next_interp);
900 else
901 base_cand = NULL;
904 return 0;
907 /* Look for the following pattern:
909 *PBASE: MEM_REF (T1, C1)
911 *POFFSET: MULT_EXPR (T2, C3) [C2 is zero]
913 MULT_EXPR (PLUS_EXPR (T2, C2), C3)
915 MULT_EXPR (MINUS_EXPR (T2, -C2), C3)
917 *PINDEX: C4 * BITS_PER_UNIT
919 If not present, leave the input values unchanged and return FALSE.
920 Otherwise, modify the input values as follows and return TRUE:
922 *PBASE: T1
923 *POFFSET: MULT_EXPR (T2, C3)
924 *PINDEX: C1 + (C2 * C3) + C4
926 When T2 is recorded by a CAND_ADD in the form of (T2' + C5), it
927 will be further restructured to:
929 *PBASE: T1
930 *POFFSET: MULT_EXPR (T2', C3)
931 *PINDEX: C1 + (C2 * C3) + C4 + (C5 * C3) */
933 static bool
934 restructure_reference (tree *pbase, tree *poffset, widest_int *pindex,
935 tree *ptype)
937 tree base = *pbase, offset = *poffset;
938 widest_int index = *pindex;
939 tree mult_op0, t1, t2, type;
940 widest_int c1, c2, c3, c4, c5;
942 if (!base
943 || !offset
944 || TREE_CODE (base) != MEM_REF
945 || TREE_CODE (offset) != MULT_EXPR
946 || TREE_CODE (TREE_OPERAND (offset, 1)) != INTEGER_CST
947 || wi::umod_floor (index, BITS_PER_UNIT) != 0)
948 return false;
950 t1 = TREE_OPERAND (base, 0);
951 c1 = widest_int::from (mem_ref_offset (base), SIGNED);
952 type = TREE_TYPE (TREE_OPERAND (base, 1));
954 mult_op0 = TREE_OPERAND (offset, 0);
955 c3 = wi::to_widest (TREE_OPERAND (offset, 1));
957 if (TREE_CODE (mult_op0) == PLUS_EXPR)
959 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
961 t2 = TREE_OPERAND (mult_op0, 0);
962 c2 = wi::to_widest (TREE_OPERAND (mult_op0, 1));
964 else
965 return false;
967 else if (TREE_CODE (mult_op0) == MINUS_EXPR)
969 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
971 t2 = TREE_OPERAND (mult_op0, 0);
972 c2 = -wi::to_widest (TREE_OPERAND (mult_op0, 1));
974 else
975 return false;
977 else
979 t2 = mult_op0;
980 c2 = 0;
983 c4 = wi::lrshift (index, LOG2_BITS_PER_UNIT);
984 c5 = backtrace_base_for_ref (&t2);
986 *pbase = t1;
987 *poffset = fold_build2 (MULT_EXPR, sizetype, fold_convert (sizetype, t2),
988 wide_int_to_tree (sizetype, c3));
989 *pindex = c1 + c2 * c3 + c4 + c5 * c3;
990 *ptype = type;
992 return true;
995 /* Given GS which contains a data reference, create a CAND_REF entry in
996 the candidate table and attempt to find a basis. */
998 static void
999 slsr_process_ref (gimple gs)
1001 tree ref_expr, base, offset, type;
1002 HOST_WIDE_INT bitsize, bitpos;
1003 machine_mode mode;
1004 int unsignedp, volatilep;
1005 slsr_cand_t c;
1007 if (gimple_vdef (gs))
1008 ref_expr = gimple_assign_lhs (gs);
1009 else
1010 ref_expr = gimple_assign_rhs1 (gs);
1012 if (!handled_component_p (ref_expr)
1013 || TREE_CODE (ref_expr) == BIT_FIELD_REF
1014 || (TREE_CODE (ref_expr) == COMPONENT_REF
1015 && DECL_BIT_FIELD (TREE_OPERAND (ref_expr, 1))))
1016 return;
1018 base = get_inner_reference (ref_expr, &bitsize, &bitpos, &offset, &mode,
1019 &unsignedp, &volatilep, false);
1020 widest_int index = bitpos;
1022 if (!restructure_reference (&base, &offset, &index, &type))
1023 return;
1025 c = alloc_cand_and_find_basis (CAND_REF, gs, base, index, offset,
1026 type, 0);
1028 /* Add the candidate to the statement-candidate mapping. */
1029 add_cand_for_stmt (gs, c);
1032 /* Create a candidate entry for a statement GS, where GS multiplies
1033 two SSA names BASE_IN and STRIDE_IN. Propagate any known information
1034 about the two SSA names into the new candidate. Return the new
1035 candidate. */
1037 static slsr_cand_t
1038 create_mul_ssa_cand (gimple gs, tree base_in, tree stride_in, bool speed)
1040 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1041 widest_int index;
1042 unsigned savings = 0;
1043 slsr_cand_t c;
1044 slsr_cand_t base_cand = base_cand_from_table (base_in);
1046 /* Look at all interpretations of the base candidate, if necessary,
1047 to find information to propagate into this candidate. */
1048 while (base_cand && !base && base_cand->kind != CAND_PHI)
1051 if (base_cand->kind == CAND_MULT && integer_onep (base_cand->stride))
1053 /* Y = (B + i') * 1
1054 X = Y * Z
1055 ================
1056 X = (B + i') * Z */
1057 base = base_cand->base_expr;
1058 index = base_cand->index;
1059 stride = stride_in;
1060 ctype = base_cand->cand_type;
1061 if (has_single_use (base_in))
1062 savings = (base_cand->dead_savings
1063 + stmt_cost (base_cand->cand_stmt, speed));
1065 else if (base_cand->kind == CAND_ADD
1066 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1068 /* Y = B + (i' * S), S constant
1069 X = Y * Z
1070 ============================
1071 X = B + ((i' * S) * Z) */
1072 base = base_cand->base_expr;
1073 index = base_cand->index * wi::to_widest (base_cand->stride);
1074 stride = stride_in;
1075 ctype = base_cand->cand_type;
1076 if (has_single_use (base_in))
1077 savings = (base_cand->dead_savings
1078 + stmt_cost (base_cand->cand_stmt, speed));
1081 if (base_cand->next_interp)
1082 base_cand = lookup_cand (base_cand->next_interp);
1083 else
1084 base_cand = NULL;
1087 if (!base)
1089 /* No interpretations had anything useful to propagate, so
1090 produce X = (Y + 0) * Z. */
1091 base = base_in;
1092 index = 0;
1093 stride = stride_in;
1094 ctype = TREE_TYPE (base_in);
1097 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
1098 ctype, savings);
1099 return c;
1102 /* Create a candidate entry for a statement GS, where GS multiplies
1103 SSA name BASE_IN by constant STRIDE_IN. Propagate any known
1104 information about BASE_IN into the new candidate. Return the new
1105 candidate. */
1107 static slsr_cand_t
1108 create_mul_imm_cand (gimple gs, tree base_in, tree stride_in, bool speed)
1110 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1111 widest_int index, temp;
1112 unsigned savings = 0;
1113 slsr_cand_t c;
1114 slsr_cand_t base_cand = base_cand_from_table (base_in);
1116 /* Look at all interpretations of the base candidate, if necessary,
1117 to find information to propagate into this candidate. */
1118 while (base_cand && !base && base_cand->kind != CAND_PHI)
1120 if (base_cand->kind == CAND_MULT
1121 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1123 /* Y = (B + i') * S, S constant
1124 X = Y * c
1125 ============================
1126 X = (B + i') * (S * c) */
1127 temp = wi::to_widest (base_cand->stride) * wi::to_widest (stride_in);
1128 if (wi::fits_to_tree_p (temp, TREE_TYPE (stride_in)))
1130 base = base_cand->base_expr;
1131 index = base_cand->index;
1132 stride = wide_int_to_tree (TREE_TYPE (stride_in), temp);
1133 ctype = base_cand->cand_type;
1134 if (has_single_use (base_in))
1135 savings = (base_cand->dead_savings
1136 + stmt_cost (base_cand->cand_stmt, speed));
1139 else if (base_cand->kind == CAND_ADD && integer_onep (base_cand->stride))
1141 /* Y = B + (i' * 1)
1142 X = Y * c
1143 ===========================
1144 X = (B + i') * c */
1145 base = base_cand->base_expr;
1146 index = base_cand->index;
1147 stride = stride_in;
1148 ctype = base_cand->cand_type;
1149 if (has_single_use (base_in))
1150 savings = (base_cand->dead_savings
1151 + stmt_cost (base_cand->cand_stmt, speed));
1153 else if (base_cand->kind == CAND_ADD
1154 && base_cand->index == 1
1155 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1157 /* Y = B + (1 * S), S constant
1158 X = Y * c
1159 ===========================
1160 X = (B + S) * c */
1161 base = base_cand->base_expr;
1162 index = wi::to_widest (base_cand->stride);
1163 stride = stride_in;
1164 ctype = base_cand->cand_type;
1165 if (has_single_use (base_in))
1166 savings = (base_cand->dead_savings
1167 + stmt_cost (base_cand->cand_stmt, speed));
1170 if (base_cand->next_interp)
1171 base_cand = lookup_cand (base_cand->next_interp);
1172 else
1173 base_cand = NULL;
1176 if (!base)
1178 /* No interpretations had anything useful to propagate, so
1179 produce X = (Y + 0) * c. */
1180 base = base_in;
1181 index = 0;
1182 stride = stride_in;
1183 ctype = TREE_TYPE (base_in);
1186 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
1187 ctype, savings);
1188 return c;
1191 /* Given GS which is a multiply of scalar integers, make an appropriate
1192 entry in the candidate table. If this is a multiply of two SSA names,
1193 create two CAND_MULT interpretations and attempt to find a basis for
1194 each of them. Otherwise, create a single CAND_MULT and attempt to
1195 find a basis. */
1197 static void
1198 slsr_process_mul (gimple gs, tree rhs1, tree rhs2, bool speed)
1200 slsr_cand_t c, c2;
1202 /* If this is a multiply of an SSA name with itself, it is highly
1203 unlikely that we will get a strength reduction opportunity, so
1204 don't record it as a candidate. This simplifies the logic for
1205 finding a basis, so if this is removed that must be considered. */
1206 if (rhs1 == rhs2)
1207 return;
1209 if (TREE_CODE (rhs2) == SSA_NAME)
1211 /* Record an interpretation of this statement in the candidate table
1212 assuming RHS1 is the base expression and RHS2 is the stride. */
1213 c = create_mul_ssa_cand (gs, rhs1, rhs2, speed);
1215 /* Add the first interpretation to the statement-candidate mapping. */
1216 add_cand_for_stmt (gs, c);
1218 /* Record another interpretation of this statement assuming RHS1
1219 is the stride and RHS2 is the base expression. */
1220 c2 = create_mul_ssa_cand (gs, rhs2, rhs1, speed);
1221 c->next_interp = c2->cand_num;
1223 else
1225 /* Record an interpretation for the multiply-immediate. */
1226 c = create_mul_imm_cand (gs, rhs1, rhs2, speed);
1228 /* Add the interpretation to the statement-candidate mapping. */
1229 add_cand_for_stmt (gs, c);
1233 /* Create a candidate entry for a statement GS, where GS adds two
1234 SSA names BASE_IN and ADDEND_IN if SUBTRACT_P is false, and
1235 subtracts ADDEND_IN from BASE_IN otherwise. Propagate any known
1236 information about the two SSA names into the new candidate.
1237 Return the new candidate. */
1239 static slsr_cand_t
1240 create_add_ssa_cand (gimple gs, tree base_in, tree addend_in,
1241 bool subtract_p, bool speed)
1243 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL;
1244 widest_int index;
1245 unsigned savings = 0;
1246 slsr_cand_t c;
1247 slsr_cand_t base_cand = base_cand_from_table (base_in);
1248 slsr_cand_t addend_cand = base_cand_from_table (addend_in);
1250 /* The most useful transformation is a multiply-immediate feeding
1251 an add or subtract. Look for that first. */
1252 while (addend_cand && !base && addend_cand->kind != CAND_PHI)
1254 if (addend_cand->kind == CAND_MULT
1255 && addend_cand->index == 0
1256 && TREE_CODE (addend_cand->stride) == INTEGER_CST)
1258 /* Z = (B + 0) * S, S constant
1259 X = Y +/- Z
1260 ===========================
1261 X = Y + ((+/-1 * S) * B) */
1262 base = base_in;
1263 index = wi::to_widest (addend_cand->stride);
1264 if (subtract_p)
1265 index = -index;
1266 stride = addend_cand->base_expr;
1267 ctype = TREE_TYPE (base_in);
1268 if (has_single_use (addend_in))
1269 savings = (addend_cand->dead_savings
1270 + stmt_cost (addend_cand->cand_stmt, speed));
1273 if (addend_cand->next_interp)
1274 addend_cand = lookup_cand (addend_cand->next_interp);
1275 else
1276 addend_cand = NULL;
1279 while (base_cand && !base && base_cand->kind != CAND_PHI)
1281 if (base_cand->kind == CAND_ADD
1282 && (base_cand->index == 0
1283 || operand_equal_p (base_cand->stride,
1284 integer_zero_node, 0)))
1286 /* Y = B + (i' * S), i' * S = 0
1287 X = Y +/- Z
1288 ============================
1289 X = B + (+/-1 * Z) */
1290 base = base_cand->base_expr;
1291 index = subtract_p ? -1 : 1;
1292 stride = addend_in;
1293 ctype = base_cand->cand_type;
1294 if (has_single_use (base_in))
1295 savings = (base_cand->dead_savings
1296 + stmt_cost (base_cand->cand_stmt, speed));
1298 else if (subtract_p)
1300 slsr_cand_t subtrahend_cand = base_cand_from_table (addend_in);
1302 while (subtrahend_cand && !base && subtrahend_cand->kind != CAND_PHI)
1304 if (subtrahend_cand->kind == CAND_MULT
1305 && subtrahend_cand->index == 0
1306 && TREE_CODE (subtrahend_cand->stride) == INTEGER_CST)
1308 /* Z = (B + 0) * S, S constant
1309 X = Y - Z
1310 ===========================
1311 Value: X = Y + ((-1 * S) * B) */
1312 base = base_in;
1313 index = wi::to_widest (subtrahend_cand->stride);
1314 index = -index;
1315 stride = subtrahend_cand->base_expr;
1316 ctype = TREE_TYPE (base_in);
1317 if (has_single_use (addend_in))
1318 savings = (subtrahend_cand->dead_savings
1319 + stmt_cost (subtrahend_cand->cand_stmt, speed));
1322 if (subtrahend_cand->next_interp)
1323 subtrahend_cand = lookup_cand (subtrahend_cand->next_interp);
1324 else
1325 subtrahend_cand = NULL;
1329 if (base_cand->next_interp)
1330 base_cand = lookup_cand (base_cand->next_interp);
1331 else
1332 base_cand = NULL;
1335 if (!base)
1337 /* No interpretations had anything useful to propagate, so
1338 produce X = Y + (1 * Z). */
1339 base = base_in;
1340 index = subtract_p ? -1 : 1;
1341 stride = addend_in;
1342 ctype = TREE_TYPE (base_in);
1345 c = alloc_cand_and_find_basis (CAND_ADD, gs, base, index, stride,
1346 ctype, savings);
1347 return c;
1350 /* Create a candidate entry for a statement GS, where GS adds SSA
1351 name BASE_IN to constant INDEX_IN. Propagate any known information
1352 about BASE_IN into the new candidate. Return the new candidate. */
1354 static slsr_cand_t
1355 create_add_imm_cand (gimple gs, tree base_in, const widest_int &index_in,
1356 bool speed)
1358 enum cand_kind kind = CAND_ADD;
1359 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1360 widest_int index, multiple;
1361 unsigned savings = 0;
1362 slsr_cand_t c;
1363 slsr_cand_t base_cand = base_cand_from_table (base_in);
1365 while (base_cand && !base && base_cand->kind != CAND_PHI)
1367 signop sign = TYPE_SIGN (TREE_TYPE (base_cand->stride));
1369 if (TREE_CODE (base_cand->stride) == INTEGER_CST
1370 && wi::multiple_of_p (index_in, wi::to_widest (base_cand->stride),
1371 sign, &multiple))
1373 /* Y = (B + i') * S, S constant, c = kS for some integer k
1374 X = Y + c
1375 ============================
1376 X = (B + (i'+ k)) * S
1378 Y = B + (i' * S), S constant, c = kS for some integer k
1379 X = Y + c
1380 ============================
1381 X = (B + (i'+ k)) * S */
1382 kind = base_cand->kind;
1383 base = base_cand->base_expr;
1384 index = base_cand->index + multiple;
1385 stride = base_cand->stride;
1386 ctype = base_cand->cand_type;
1387 if (has_single_use (base_in))
1388 savings = (base_cand->dead_savings
1389 + stmt_cost (base_cand->cand_stmt, speed));
1392 if (base_cand->next_interp)
1393 base_cand = lookup_cand (base_cand->next_interp);
1394 else
1395 base_cand = NULL;
1398 if (!base)
1400 /* No interpretations had anything useful to propagate, so
1401 produce X = Y + (c * 1). */
1402 kind = CAND_ADD;
1403 base = base_in;
1404 index = index_in;
1405 stride = integer_one_node;
1406 ctype = TREE_TYPE (base_in);
1409 c = alloc_cand_and_find_basis (kind, gs, base, index, stride,
1410 ctype, savings);
1411 return c;
1414 /* Given GS which is an add or subtract of scalar integers or pointers,
1415 make at least one appropriate entry in the candidate table. */
1417 static void
1418 slsr_process_add (gimple gs, tree rhs1, tree rhs2, bool speed)
1420 bool subtract_p = gimple_assign_rhs_code (gs) == MINUS_EXPR;
1421 slsr_cand_t c = NULL, c2;
1423 if (TREE_CODE (rhs2) == SSA_NAME)
1425 /* First record an interpretation assuming RHS1 is the base expression
1426 and RHS2 is the stride. But it doesn't make sense for the
1427 stride to be a pointer, so don't record a candidate in that case. */
1428 if (!POINTER_TYPE_P (TREE_TYPE (rhs2)))
1430 c = create_add_ssa_cand (gs, rhs1, rhs2, subtract_p, speed);
1432 /* Add the first interpretation to the statement-candidate
1433 mapping. */
1434 add_cand_for_stmt (gs, c);
1437 /* If the two RHS operands are identical, or this is a subtract,
1438 we're done. */
1439 if (operand_equal_p (rhs1, rhs2, 0) || subtract_p)
1440 return;
1442 /* Otherwise, record another interpretation assuming RHS2 is the
1443 base expression and RHS1 is the stride, again provided that the
1444 stride is not a pointer. */
1445 if (!POINTER_TYPE_P (TREE_TYPE (rhs1)))
1447 c2 = create_add_ssa_cand (gs, rhs2, rhs1, false, speed);
1448 if (c)
1449 c->next_interp = c2->cand_num;
1450 else
1451 add_cand_for_stmt (gs, c2);
1454 else
1456 /* Record an interpretation for the add-immediate. */
1457 widest_int index = wi::to_widest (rhs2);
1458 if (subtract_p)
1459 index = -index;
1461 c = create_add_imm_cand (gs, rhs1, index, speed);
1463 /* Add the interpretation to the statement-candidate mapping. */
1464 add_cand_for_stmt (gs, c);
1468 /* Given GS which is a negate of a scalar integer, make an appropriate
1469 entry in the candidate table. A negate is equivalent to a multiply
1470 by -1. */
1472 static void
1473 slsr_process_neg (gimple gs, tree rhs1, bool speed)
1475 /* Record a CAND_MULT interpretation for the multiply by -1. */
1476 slsr_cand_t c = create_mul_imm_cand (gs, rhs1, integer_minus_one_node, speed);
1478 /* Add the interpretation to the statement-candidate mapping. */
1479 add_cand_for_stmt (gs, c);
1482 /* Help function for legal_cast_p, operating on two trees. Checks
1483 whether it's allowable to cast from RHS to LHS. See legal_cast_p
1484 for more details. */
1486 static bool
1487 legal_cast_p_1 (tree lhs, tree rhs)
1489 tree lhs_type, rhs_type;
1490 unsigned lhs_size, rhs_size;
1491 bool lhs_wraps, rhs_wraps;
1493 lhs_type = TREE_TYPE (lhs);
1494 rhs_type = TREE_TYPE (rhs);
1495 lhs_size = TYPE_PRECISION (lhs_type);
1496 rhs_size = TYPE_PRECISION (rhs_type);
1497 lhs_wraps = ANY_INTEGRAL_TYPE_P (lhs_type) && TYPE_OVERFLOW_WRAPS (lhs_type);
1498 rhs_wraps = ANY_INTEGRAL_TYPE_P (rhs_type) && TYPE_OVERFLOW_WRAPS (rhs_type);
1500 if (lhs_size < rhs_size
1501 || (rhs_wraps && !lhs_wraps)
1502 || (rhs_wraps && lhs_wraps && rhs_size != lhs_size))
1503 return false;
1505 return true;
1508 /* Return TRUE if GS is a statement that defines an SSA name from
1509 a conversion and is legal for us to combine with an add and multiply
1510 in the candidate table. For example, suppose we have:
1512 A = B + i;
1513 C = (type) A;
1514 D = C * S;
1516 Without the type-cast, we would create a CAND_MULT for D with base B,
1517 index i, and stride S. We want to record this candidate only if it
1518 is equivalent to apply the type cast following the multiply:
1520 A = B + i;
1521 E = A * S;
1522 D = (type) E;
1524 We will record the type with the candidate for D. This allows us
1525 to use a similar previous candidate as a basis. If we have earlier seen
1527 A' = B + i';
1528 C' = (type) A';
1529 D' = C' * S;
1531 we can replace D with
1533 D = D' + (i - i') * S;
1535 But if moving the type-cast would change semantics, we mustn't do this.
1537 This is legitimate for casts from a non-wrapping integral type to
1538 any integral type of the same or larger size. It is not legitimate
1539 to convert a wrapping type to a non-wrapping type, or to a wrapping
1540 type of a different size. I.e., with a wrapping type, we must
1541 assume that the addition B + i could wrap, in which case performing
1542 the multiply before or after one of the "illegal" type casts will
1543 have different semantics. */
1545 static bool
1546 legal_cast_p (gimple gs, tree rhs)
1548 if (!is_gimple_assign (gs)
1549 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (gs)))
1550 return false;
1552 return legal_cast_p_1 (gimple_assign_lhs (gs), rhs);
1555 /* Given GS which is a cast to a scalar integer type, determine whether
1556 the cast is legal for strength reduction. If so, make at least one
1557 appropriate entry in the candidate table. */
1559 static void
1560 slsr_process_cast (gimple gs, tree rhs1, bool speed)
1562 tree lhs, ctype;
1563 slsr_cand_t base_cand, c, c2;
1564 unsigned savings = 0;
1566 if (!legal_cast_p (gs, rhs1))
1567 return;
1569 lhs = gimple_assign_lhs (gs);
1570 base_cand = base_cand_from_table (rhs1);
1571 ctype = TREE_TYPE (lhs);
1573 if (base_cand && base_cand->kind != CAND_PHI)
1575 while (base_cand)
1577 /* Propagate all data from the base candidate except the type,
1578 which comes from the cast, and the base candidate's cast,
1579 which is no longer applicable. */
1580 if (has_single_use (rhs1))
1581 savings = (base_cand->dead_savings
1582 + stmt_cost (base_cand->cand_stmt, speed));
1584 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1585 base_cand->base_expr,
1586 base_cand->index, base_cand->stride,
1587 ctype, savings);
1588 if (base_cand->next_interp)
1589 base_cand = lookup_cand (base_cand->next_interp);
1590 else
1591 base_cand = NULL;
1594 else
1596 /* If nothing is known about the RHS, create fresh CAND_ADD and
1597 CAND_MULT interpretations:
1599 X = Y + (0 * 1)
1600 X = (Y + 0) * 1
1602 The first of these is somewhat arbitrary, but the choice of
1603 1 for the stride simplifies the logic for propagating casts
1604 into their uses. */
1605 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1,
1606 0, integer_one_node, ctype, 0);
1607 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1,
1608 0, integer_one_node, ctype, 0);
1609 c->next_interp = c2->cand_num;
1612 /* Add the first (or only) interpretation to the statement-candidate
1613 mapping. */
1614 add_cand_for_stmt (gs, c);
1617 /* Given GS which is a copy of a scalar integer type, make at least one
1618 appropriate entry in the candidate table.
1620 This interface is included for completeness, but is unnecessary
1621 if this pass immediately follows a pass that performs copy
1622 propagation, such as DOM. */
1624 static void
1625 slsr_process_copy (gimple gs, tree rhs1, bool speed)
1627 slsr_cand_t base_cand, c, c2;
1628 unsigned savings = 0;
1630 base_cand = base_cand_from_table (rhs1);
1632 if (base_cand && base_cand->kind != CAND_PHI)
1634 while (base_cand)
1636 /* Propagate all data from the base candidate. */
1637 if (has_single_use (rhs1))
1638 savings = (base_cand->dead_savings
1639 + stmt_cost (base_cand->cand_stmt, speed));
1641 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1642 base_cand->base_expr,
1643 base_cand->index, base_cand->stride,
1644 base_cand->cand_type, savings);
1645 if (base_cand->next_interp)
1646 base_cand = lookup_cand (base_cand->next_interp);
1647 else
1648 base_cand = NULL;
1651 else
1653 /* If nothing is known about the RHS, create fresh CAND_ADD and
1654 CAND_MULT interpretations:
1656 X = Y + (0 * 1)
1657 X = (Y + 0) * 1
1659 The first of these is somewhat arbitrary, but the choice of
1660 1 for the stride simplifies the logic for propagating casts
1661 into their uses. */
1662 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1,
1663 0, integer_one_node, TREE_TYPE (rhs1), 0);
1664 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1,
1665 0, integer_one_node, TREE_TYPE (rhs1), 0);
1666 c->next_interp = c2->cand_num;
1669 /* Add the first (or only) interpretation to the statement-candidate
1670 mapping. */
1671 add_cand_for_stmt (gs, c);
1674 class find_candidates_dom_walker : public dom_walker
1676 public:
1677 find_candidates_dom_walker (cdi_direction direction)
1678 : dom_walker (direction) {}
1679 virtual void before_dom_children (basic_block);
1682 /* Find strength-reduction candidates in block BB. */
1684 void
1685 find_candidates_dom_walker::before_dom_children (basic_block bb)
1687 bool speed = optimize_bb_for_speed_p (bb);
1689 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1690 gsi_next (&gsi))
1691 slsr_process_phi (gsi.phi (), speed);
1693 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
1694 gsi_next (&gsi))
1696 gimple gs = gsi_stmt (gsi);
1698 if (gimple_vuse (gs) && gimple_assign_single_p (gs))
1699 slsr_process_ref (gs);
1701 else if (is_gimple_assign (gs)
1702 && SCALAR_INT_MODE_P
1703 (TYPE_MODE (TREE_TYPE (gimple_assign_lhs (gs)))))
1705 tree rhs1 = NULL_TREE, rhs2 = NULL_TREE;
1707 switch (gimple_assign_rhs_code (gs))
1709 case MULT_EXPR:
1710 case PLUS_EXPR:
1711 rhs1 = gimple_assign_rhs1 (gs);
1712 rhs2 = gimple_assign_rhs2 (gs);
1713 /* Should never happen, but currently some buggy situations
1714 in earlier phases put constants in rhs1. */
1715 if (TREE_CODE (rhs1) != SSA_NAME)
1716 continue;
1717 break;
1719 /* Possible future opportunity: rhs1 of a ptr+ can be
1720 an ADDR_EXPR. */
1721 case POINTER_PLUS_EXPR:
1722 case MINUS_EXPR:
1723 rhs2 = gimple_assign_rhs2 (gs);
1724 /* Fall-through. */
1726 CASE_CONVERT:
1727 case MODIFY_EXPR:
1728 case NEGATE_EXPR:
1729 rhs1 = gimple_assign_rhs1 (gs);
1730 if (TREE_CODE (rhs1) != SSA_NAME)
1731 continue;
1732 break;
1734 default:
1738 switch (gimple_assign_rhs_code (gs))
1740 case MULT_EXPR:
1741 slsr_process_mul (gs, rhs1, rhs2, speed);
1742 break;
1744 case PLUS_EXPR:
1745 case POINTER_PLUS_EXPR:
1746 case MINUS_EXPR:
1747 slsr_process_add (gs, rhs1, rhs2, speed);
1748 break;
1750 case NEGATE_EXPR:
1751 slsr_process_neg (gs, rhs1, speed);
1752 break;
1754 CASE_CONVERT:
1755 slsr_process_cast (gs, rhs1, speed);
1756 break;
1758 case MODIFY_EXPR:
1759 slsr_process_copy (gs, rhs1, speed);
1760 break;
1762 default:
1769 /* Dump a candidate for debug. */
1771 static void
1772 dump_candidate (slsr_cand_t c)
1774 fprintf (dump_file, "%3d [%d] ", c->cand_num,
1775 gimple_bb (c->cand_stmt)->index);
1776 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1777 switch (c->kind)
1779 case CAND_MULT:
1780 fputs (" MULT : (", dump_file);
1781 print_generic_expr (dump_file, c->base_expr, 0);
1782 fputs (" + ", dump_file);
1783 print_decs (c->index, dump_file);
1784 fputs (") * ", dump_file);
1785 print_generic_expr (dump_file, c->stride, 0);
1786 fputs (" : ", dump_file);
1787 break;
1788 case CAND_ADD:
1789 fputs (" ADD : ", dump_file);
1790 print_generic_expr (dump_file, c->base_expr, 0);
1791 fputs (" + (", dump_file);
1792 print_decs (c->index, dump_file);
1793 fputs (" * ", dump_file);
1794 print_generic_expr (dump_file, c->stride, 0);
1795 fputs (") : ", dump_file);
1796 break;
1797 case CAND_REF:
1798 fputs (" REF : ", dump_file);
1799 print_generic_expr (dump_file, c->base_expr, 0);
1800 fputs (" + (", dump_file);
1801 print_generic_expr (dump_file, c->stride, 0);
1802 fputs (") + ", dump_file);
1803 print_decs (c->index, dump_file);
1804 fputs (" : ", dump_file);
1805 break;
1806 case CAND_PHI:
1807 fputs (" PHI : ", dump_file);
1808 print_generic_expr (dump_file, c->base_expr, 0);
1809 fputs (" + (unknown * ", dump_file);
1810 print_generic_expr (dump_file, c->stride, 0);
1811 fputs (") : ", dump_file);
1812 break;
1813 default:
1814 gcc_unreachable ();
1816 print_generic_expr (dump_file, c->cand_type, 0);
1817 fprintf (dump_file, "\n basis: %d dependent: %d sibling: %d\n",
1818 c->basis, c->dependent, c->sibling);
1819 fprintf (dump_file, " next-interp: %d dead-savings: %d\n",
1820 c->next_interp, c->dead_savings);
1821 if (c->def_phi)
1822 fprintf (dump_file, " phi: %d\n", c->def_phi);
1823 fputs ("\n", dump_file);
1826 /* Dump the candidate vector for debug. */
1828 static void
1829 dump_cand_vec (void)
1831 unsigned i;
1832 slsr_cand_t c;
1834 fprintf (dump_file, "\nStrength reduction candidate vector:\n\n");
1836 FOR_EACH_VEC_ELT (cand_vec, i, c)
1837 dump_candidate (c);
1840 /* Callback used to dump the candidate chains hash table. */
1843 ssa_base_cand_dump_callback (cand_chain **slot, void *ignored ATTRIBUTE_UNUSED)
1845 const_cand_chain_t chain = *slot;
1846 cand_chain_t p;
1848 print_generic_expr (dump_file, chain->base_expr, 0);
1849 fprintf (dump_file, " -> %d", chain->cand->cand_num);
1851 for (p = chain->next; p; p = p->next)
1852 fprintf (dump_file, " -> %d", p->cand->cand_num);
1854 fputs ("\n", dump_file);
1855 return 1;
1858 /* Dump the candidate chains. */
1860 static void
1861 dump_cand_chains (void)
1863 fprintf (dump_file, "\nStrength reduction candidate chains:\n\n");
1864 base_cand_map->traverse_noresize <void *, ssa_base_cand_dump_callback>
1865 (NULL);
1866 fputs ("\n", dump_file);
1869 /* Dump the increment vector for debug. */
1871 static void
1872 dump_incr_vec (void)
1874 if (dump_file && (dump_flags & TDF_DETAILS))
1876 unsigned i;
1878 fprintf (dump_file, "\nIncrement vector:\n\n");
1880 for (i = 0; i < incr_vec_len; i++)
1882 fprintf (dump_file, "%3d increment: ", i);
1883 print_decs (incr_vec[i].incr, dump_file);
1884 fprintf (dump_file, "\n count: %d", incr_vec[i].count);
1885 fprintf (dump_file, "\n cost: %d", incr_vec[i].cost);
1886 fputs ("\n initializer: ", dump_file);
1887 print_generic_expr (dump_file, incr_vec[i].initializer, 0);
1888 fputs ("\n\n", dump_file);
1893 /* Replace *EXPR in candidate C with an equivalent strength-reduced
1894 data reference. */
1896 static void
1897 replace_ref (tree *expr, slsr_cand_t c)
1899 tree add_expr, mem_ref, acc_type = TREE_TYPE (*expr);
1900 unsigned HOST_WIDE_INT misalign;
1901 unsigned align;
1903 /* Ensure the memory reference carries the minimum alignment
1904 requirement for the data type. See PR58041. */
1905 get_object_alignment_1 (*expr, &align, &misalign);
1906 if (misalign != 0)
1907 align = (misalign & -misalign);
1908 if (align < TYPE_ALIGN (acc_type))
1909 acc_type = build_aligned_type (acc_type, align);
1911 add_expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (c->base_expr),
1912 c->base_expr, c->stride);
1913 mem_ref = fold_build2 (MEM_REF, acc_type, add_expr,
1914 wide_int_to_tree (c->cand_type, c->index));
1916 /* Gimplify the base addressing expression for the new MEM_REF tree. */
1917 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
1918 TREE_OPERAND (mem_ref, 0)
1919 = force_gimple_operand_gsi (&gsi, TREE_OPERAND (mem_ref, 0),
1920 /*simple_p=*/true, NULL,
1921 /*before=*/true, GSI_SAME_STMT);
1922 copy_ref_info (mem_ref, *expr);
1923 *expr = mem_ref;
1924 update_stmt (c->cand_stmt);
1927 /* Replace CAND_REF candidate C, each sibling of candidate C, and each
1928 dependent of candidate C with an equivalent strength-reduced data
1929 reference. */
1931 static void
1932 replace_refs (slsr_cand_t c)
1934 if (dump_file && (dump_flags & TDF_DETAILS))
1936 fputs ("Replacing reference: ", dump_file);
1937 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1940 if (gimple_vdef (c->cand_stmt))
1942 tree *lhs = gimple_assign_lhs_ptr (c->cand_stmt);
1943 replace_ref (lhs, c);
1945 else
1947 tree *rhs = gimple_assign_rhs1_ptr (c->cand_stmt);
1948 replace_ref (rhs, c);
1951 if (dump_file && (dump_flags & TDF_DETAILS))
1953 fputs ("With: ", dump_file);
1954 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1955 fputs ("\n", dump_file);
1958 if (c->sibling)
1959 replace_refs (lookup_cand (c->sibling));
1961 if (c->dependent)
1962 replace_refs (lookup_cand (c->dependent));
1965 /* Return TRUE if candidate C is dependent upon a PHI. */
1967 static bool
1968 phi_dependent_cand_p (slsr_cand_t c)
1970 /* A candidate is not necessarily dependent upon a PHI just because
1971 it has a phi definition for its base name. It may have a basis
1972 that relies upon the same phi definition, in which case the PHI
1973 is irrelevant to this candidate. */
1974 return (c->def_phi
1975 && c->basis
1976 && lookup_cand (c->basis)->def_phi != c->def_phi);
1979 /* Calculate the increment required for candidate C relative to
1980 its basis. */
1982 static widest_int
1983 cand_increment (slsr_cand_t c)
1985 slsr_cand_t basis;
1987 /* If the candidate doesn't have a basis, just return its own
1988 index. This is useful in record_increments to help us find
1989 an existing initializer. Also, if the candidate's basis is
1990 hidden by a phi, then its own index will be the increment
1991 from the newly introduced phi basis. */
1992 if (!c->basis || phi_dependent_cand_p (c))
1993 return c->index;
1995 basis = lookup_cand (c->basis);
1996 gcc_assert (operand_equal_p (c->base_expr, basis->base_expr, 0));
1997 return c->index - basis->index;
2000 /* Calculate the increment required for candidate C relative to
2001 its basis. If we aren't going to generate pointer arithmetic
2002 for this candidate, return the absolute value of that increment
2003 instead. */
2005 static inline widest_int
2006 cand_abs_increment (slsr_cand_t c)
2008 widest_int increment = cand_increment (c);
2010 if (!address_arithmetic_p && wi::neg_p (increment))
2011 increment = -increment;
2013 return increment;
2016 /* Return TRUE iff candidate C has already been replaced under
2017 another interpretation. */
2019 static inline bool
2020 cand_already_replaced (slsr_cand_t c)
2022 return (gimple_bb (c->cand_stmt) == 0);
2025 /* Common logic used by replace_unconditional_candidate and
2026 replace_conditional_candidate. */
2028 static void
2029 replace_mult_candidate (slsr_cand_t c, tree basis_name, widest_int bump)
2031 tree target_type = TREE_TYPE (gimple_assign_lhs (c->cand_stmt));
2032 enum tree_code cand_code = gimple_assign_rhs_code (c->cand_stmt);
2034 /* It is highly unlikely, but possible, that the resulting
2035 bump doesn't fit in a HWI. Abandon the replacement
2036 in this case. This does not affect siblings or dependents
2037 of C. Restriction to signed HWI is conservative for unsigned
2038 types but allows for safe negation without twisted logic. */
2039 if (wi::fits_shwi_p (bump)
2040 && bump.to_shwi () != HOST_WIDE_INT_MIN
2041 /* It is not useful to replace casts, copies, or adds of
2042 an SSA name and a constant. */
2043 && cand_code != MODIFY_EXPR
2044 && !CONVERT_EXPR_CODE_P (cand_code)
2045 && cand_code != PLUS_EXPR
2046 && cand_code != POINTER_PLUS_EXPR
2047 && cand_code != MINUS_EXPR)
2049 enum tree_code code = PLUS_EXPR;
2050 tree bump_tree;
2051 gimple stmt_to_print = NULL;
2053 /* If the basis name and the candidate's LHS have incompatible
2054 types, introduce a cast. */
2055 if (!useless_type_conversion_p (target_type, TREE_TYPE (basis_name)))
2056 basis_name = introduce_cast_before_cand (c, target_type, basis_name);
2057 if (wi::neg_p (bump))
2059 code = MINUS_EXPR;
2060 bump = -bump;
2063 bump_tree = wide_int_to_tree (target_type, bump);
2065 if (dump_file && (dump_flags & TDF_DETAILS))
2067 fputs ("Replacing: ", dump_file);
2068 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
2071 if (bump == 0)
2073 tree lhs = gimple_assign_lhs (c->cand_stmt);
2074 gassign *copy_stmt = gimple_build_assign (lhs, basis_name);
2075 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2076 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
2077 gsi_replace (&gsi, copy_stmt, false);
2078 c->cand_stmt = copy_stmt;
2079 if (dump_file && (dump_flags & TDF_DETAILS))
2080 stmt_to_print = copy_stmt;
2082 else
2084 tree rhs1, rhs2;
2085 if (cand_code != NEGATE_EXPR) {
2086 rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2087 rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2089 if (cand_code != NEGATE_EXPR
2090 && ((operand_equal_p (rhs1, basis_name, 0)
2091 && operand_equal_p (rhs2, bump_tree, 0))
2092 || (operand_equal_p (rhs1, bump_tree, 0)
2093 && operand_equal_p (rhs2, basis_name, 0))))
2095 if (dump_file && (dump_flags & TDF_DETAILS))
2097 fputs ("(duplicate, not actually replacing)", dump_file);
2098 stmt_to_print = c->cand_stmt;
2101 else
2103 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2104 gimple_assign_set_rhs_with_ops (&gsi, code,
2105 basis_name, bump_tree);
2106 update_stmt (gsi_stmt (gsi));
2107 c->cand_stmt = gsi_stmt (gsi);
2108 if (dump_file && (dump_flags & TDF_DETAILS))
2109 stmt_to_print = gsi_stmt (gsi);
2113 if (dump_file && (dump_flags & TDF_DETAILS))
2115 fputs ("With: ", dump_file);
2116 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
2117 fputs ("\n", dump_file);
2122 /* Replace candidate C with an add or subtract. Note that we only
2123 operate on CAND_MULTs with known strides, so we will never generate
2124 a POINTER_PLUS_EXPR. Each candidate X = (B + i) * S is replaced by
2125 X = Y + ((i - i') * S), as described in the module commentary. The
2126 folded value ((i - i') * S) is referred to here as the "bump." */
2128 static void
2129 replace_unconditional_candidate (slsr_cand_t c)
2131 slsr_cand_t basis;
2133 if (cand_already_replaced (c))
2134 return;
2136 basis = lookup_cand (c->basis);
2137 widest_int bump = cand_increment (c) * wi::to_widest (c->stride);
2139 replace_mult_candidate (c, gimple_assign_lhs (basis->cand_stmt), bump);
2142 /* Return the index in the increment vector of the given INCREMENT,
2143 or -1 if not found. The latter can occur if more than
2144 MAX_INCR_VEC_LEN increments have been found. */
2146 static inline int
2147 incr_vec_index (const widest_int &increment)
2149 unsigned i;
2151 for (i = 0; i < incr_vec_len && increment != incr_vec[i].incr; i++)
2154 if (i < incr_vec_len)
2155 return i;
2156 else
2157 return -1;
2160 /* Create a new statement along edge E to add BASIS_NAME to the product
2161 of INCREMENT and the stride of candidate C. Create and return a new
2162 SSA name from *VAR to be used as the LHS of the new statement.
2163 KNOWN_STRIDE is true iff C's stride is a constant. */
2165 static tree
2166 create_add_on_incoming_edge (slsr_cand_t c, tree basis_name,
2167 widest_int increment, edge e, location_t loc,
2168 bool known_stride)
2170 basic_block insert_bb;
2171 gimple_stmt_iterator gsi;
2172 tree lhs, basis_type;
2173 gassign *new_stmt;
2175 /* If the add candidate along this incoming edge has the same
2176 index as C's hidden basis, the hidden basis represents this
2177 edge correctly. */
2178 if (increment == 0)
2179 return basis_name;
2181 basis_type = TREE_TYPE (basis_name);
2182 lhs = make_temp_ssa_name (basis_type, NULL, "slsr");
2184 if (known_stride)
2186 tree bump_tree;
2187 enum tree_code code = PLUS_EXPR;
2188 widest_int bump = increment * wi::to_widest (c->stride);
2189 if (wi::neg_p (bump))
2191 code = MINUS_EXPR;
2192 bump = -bump;
2195 bump_tree = wide_int_to_tree (basis_type, bump);
2196 new_stmt = gimple_build_assign (lhs, code, basis_name, bump_tree);
2198 else
2200 int i;
2201 bool negate_incr = (!address_arithmetic_p && wi::neg_p (increment));
2202 i = incr_vec_index (negate_incr ? -increment : increment);
2203 gcc_assert (i >= 0);
2205 if (incr_vec[i].initializer)
2207 enum tree_code code = negate_incr ? MINUS_EXPR : PLUS_EXPR;
2208 new_stmt = gimple_build_assign (lhs, code, basis_name,
2209 incr_vec[i].initializer);
2211 else if (increment == 1)
2212 new_stmt = gimple_build_assign (lhs, PLUS_EXPR, basis_name, c->stride);
2213 else if (increment == -1)
2214 new_stmt = gimple_build_assign (lhs, MINUS_EXPR, basis_name,
2215 c->stride);
2216 else
2217 gcc_unreachable ();
2220 insert_bb = single_succ_p (e->src) ? e->src : split_edge (e);
2221 gsi = gsi_last_bb (insert_bb);
2223 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
2224 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
2225 else
2226 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
2228 gimple_set_location (new_stmt, loc);
2230 if (dump_file && (dump_flags & TDF_DETAILS))
2232 fprintf (dump_file, "Inserting in block %d: ", insert_bb->index);
2233 print_gimple_stmt (dump_file, new_stmt, 0, 0);
2236 return lhs;
2239 /* Given a candidate C with BASIS_NAME being the LHS of C's basis which
2240 is hidden by the phi node FROM_PHI, create a new phi node in the same
2241 block as FROM_PHI. The new phi is suitable for use as a basis by C,
2242 with its phi arguments representing conditional adjustments to the
2243 hidden basis along conditional incoming paths. Those adjustments are
2244 made by creating add statements (and sometimes recursively creating
2245 phis) along those incoming paths. LOC is the location to attach to
2246 the introduced statements. KNOWN_STRIDE is true iff C's stride is a
2247 constant. */
2249 static tree
2250 create_phi_basis (slsr_cand_t c, gimple from_phi, tree basis_name,
2251 location_t loc, bool known_stride)
2253 int i;
2254 tree name, phi_arg;
2255 gphi *phi;
2256 vec<tree> phi_args;
2257 slsr_cand_t basis = lookup_cand (c->basis);
2258 int nargs = gimple_phi_num_args (from_phi);
2259 basic_block phi_bb = gimple_bb (from_phi);
2260 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (from_phi));
2261 phi_args.create (nargs);
2263 /* Process each argument of the existing phi that represents
2264 conditionally-executed add candidates. */
2265 for (i = 0; i < nargs; i++)
2267 edge e = (*phi_bb->preds)[i];
2268 tree arg = gimple_phi_arg_def (from_phi, i);
2269 tree feeding_def;
2271 /* If the phi argument is the base name of the CAND_PHI, then
2272 this incoming arc should use the hidden basis. */
2273 if (operand_equal_p (arg, phi_cand->base_expr, 0))
2274 if (basis->index == 0)
2275 feeding_def = gimple_assign_lhs (basis->cand_stmt);
2276 else
2278 widest_int incr = -basis->index;
2279 feeding_def = create_add_on_incoming_edge (c, basis_name, incr,
2280 e, loc, known_stride);
2282 else
2284 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2286 /* If there is another phi along this incoming edge, we must
2287 process it in the same fashion to ensure that all basis
2288 adjustments are made along its incoming edges. */
2289 if (gimple_code (arg_def) == GIMPLE_PHI)
2290 feeding_def = create_phi_basis (c, arg_def, basis_name,
2291 loc, known_stride);
2292 else
2294 slsr_cand_t arg_cand = base_cand_from_table (arg);
2295 widest_int diff = arg_cand->index - basis->index;
2296 feeding_def = create_add_on_incoming_edge (c, basis_name, diff,
2297 e, loc, known_stride);
2301 /* Because of recursion, we need to save the arguments in a vector
2302 so we can create the PHI statement all at once. Otherwise the
2303 storage for the half-created PHI can be reclaimed. */
2304 phi_args.safe_push (feeding_def);
2307 /* Create the new phi basis. */
2308 name = make_temp_ssa_name (TREE_TYPE (basis_name), NULL, "slsr");
2309 phi = create_phi_node (name, phi_bb);
2310 SSA_NAME_DEF_STMT (name) = phi;
2312 FOR_EACH_VEC_ELT (phi_args, i, phi_arg)
2314 edge e = (*phi_bb->preds)[i];
2315 add_phi_arg (phi, phi_arg, e, loc);
2318 update_stmt (phi);
2320 if (dump_file && (dump_flags & TDF_DETAILS))
2322 fputs ("Introducing new phi basis: ", dump_file);
2323 print_gimple_stmt (dump_file, phi, 0, 0);
2326 return name;
2329 /* Given a candidate C whose basis is hidden by at least one intervening
2330 phi, introduce a matching number of new phis to represent its basis
2331 adjusted by conditional increments along possible incoming paths. Then
2332 replace C as though it were an unconditional candidate, using the new
2333 basis. */
2335 static void
2336 replace_conditional_candidate (slsr_cand_t c)
2338 tree basis_name, name;
2339 slsr_cand_t basis;
2340 location_t loc;
2342 /* Look up the LHS SSA name from C's basis. This will be the
2343 RHS1 of the adds we will introduce to create new phi arguments. */
2344 basis = lookup_cand (c->basis);
2345 basis_name = gimple_assign_lhs (basis->cand_stmt);
2347 /* Create a new phi statement which will represent C's true basis
2348 after the transformation is complete. */
2349 loc = gimple_location (c->cand_stmt);
2350 name = create_phi_basis (c, lookup_cand (c->def_phi)->cand_stmt,
2351 basis_name, loc, KNOWN_STRIDE);
2352 /* Replace C with an add of the new basis phi and a constant. */
2353 widest_int bump = c->index * wi::to_widest (c->stride);
2355 replace_mult_candidate (c, name, bump);
2358 /* Compute the expected costs of inserting basis adjustments for
2359 candidate C with phi-definition PHI. The cost of inserting
2360 one adjustment is given by ONE_ADD_COST. If PHI has arguments
2361 which are themselves phi results, recursively calculate costs
2362 for those phis as well. */
2364 static int
2365 phi_add_costs (gimple phi, slsr_cand_t c, int one_add_cost)
2367 unsigned i;
2368 int cost = 0;
2369 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2371 /* If we work our way back to a phi that isn't dominated by the hidden
2372 basis, this isn't a candidate for replacement. Indicate this by
2373 returning an unreasonably high cost. It's not easy to detect
2374 these situations when determining the basis, so we defer the
2375 decision until now. */
2376 basic_block phi_bb = gimple_bb (phi);
2377 slsr_cand_t basis = lookup_cand (c->basis);
2378 basic_block basis_bb = gimple_bb (basis->cand_stmt);
2380 if (phi_bb == basis_bb || !dominated_by_p (CDI_DOMINATORS, phi_bb, basis_bb))
2381 return COST_INFINITE;
2383 for (i = 0; i < gimple_phi_num_args (phi); i++)
2385 tree arg = gimple_phi_arg_def (phi, i);
2387 if (arg != phi_cand->base_expr)
2389 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2391 if (gimple_code (arg_def) == GIMPLE_PHI)
2392 cost += phi_add_costs (arg_def, c, one_add_cost);
2393 else
2395 slsr_cand_t arg_cand = base_cand_from_table (arg);
2397 if (arg_cand->index != c->index)
2398 cost += one_add_cost;
2403 return cost;
2406 /* For candidate C, each sibling of candidate C, and each dependent of
2407 candidate C, determine whether the candidate is dependent upon a
2408 phi that hides its basis. If not, replace the candidate unconditionally.
2409 Otherwise, determine whether the cost of introducing compensation code
2410 for the candidate is offset by the gains from strength reduction. If
2411 so, replace the candidate and introduce the compensation code. */
2413 static void
2414 replace_uncond_cands_and_profitable_phis (slsr_cand_t c)
2416 if (phi_dependent_cand_p (c))
2418 if (c->kind == CAND_MULT)
2420 /* A candidate dependent upon a phi will replace a multiply by
2421 a constant with an add, and will insert at most one add for
2422 each phi argument. Add these costs with the potential dead-code
2423 savings to determine profitability. */
2424 bool speed = optimize_bb_for_speed_p (gimple_bb (c->cand_stmt));
2425 int mult_savings = stmt_cost (c->cand_stmt, speed);
2426 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2427 tree phi_result = gimple_phi_result (phi);
2428 int one_add_cost = add_cost (speed,
2429 TYPE_MODE (TREE_TYPE (phi_result)));
2430 int add_costs = one_add_cost + phi_add_costs (phi, c, one_add_cost);
2431 int cost = add_costs - mult_savings - c->dead_savings;
2433 if (dump_file && (dump_flags & TDF_DETAILS))
2435 fprintf (dump_file, " Conditional candidate %d:\n", c->cand_num);
2436 fprintf (dump_file, " add_costs = %d\n", add_costs);
2437 fprintf (dump_file, " mult_savings = %d\n", mult_savings);
2438 fprintf (dump_file, " dead_savings = %d\n", c->dead_savings);
2439 fprintf (dump_file, " cost = %d\n", cost);
2440 if (cost <= COST_NEUTRAL)
2441 fputs (" Replacing...\n", dump_file);
2442 else
2443 fputs (" Not replaced.\n", dump_file);
2446 if (cost <= COST_NEUTRAL)
2447 replace_conditional_candidate (c);
2450 else
2451 replace_unconditional_candidate (c);
2453 if (c->sibling)
2454 replace_uncond_cands_and_profitable_phis (lookup_cand (c->sibling));
2456 if (c->dependent)
2457 replace_uncond_cands_and_profitable_phis (lookup_cand (c->dependent));
2460 /* Count the number of candidates in the tree rooted at C that have
2461 not already been replaced under other interpretations. */
2463 static int
2464 count_candidates (slsr_cand_t c)
2466 unsigned count = cand_already_replaced (c) ? 0 : 1;
2468 if (c->sibling)
2469 count += count_candidates (lookup_cand (c->sibling));
2471 if (c->dependent)
2472 count += count_candidates (lookup_cand (c->dependent));
2474 return count;
2477 /* Increase the count of INCREMENT by one in the increment vector.
2478 INCREMENT is associated with candidate C. If INCREMENT is to be
2479 conditionally executed as part of a conditional candidate replacement,
2480 IS_PHI_ADJUST is true, otherwise false. If an initializer
2481 T_0 = stride * I is provided by a candidate that dominates all
2482 candidates with the same increment, also record T_0 for subsequent use. */
2484 static void
2485 record_increment (slsr_cand_t c, widest_int increment, bool is_phi_adjust)
2487 bool found = false;
2488 unsigned i;
2490 /* Treat increments that differ only in sign as identical so as to
2491 share initializers, unless we are generating pointer arithmetic. */
2492 if (!address_arithmetic_p && wi::neg_p (increment))
2493 increment = -increment;
2495 for (i = 0; i < incr_vec_len; i++)
2497 if (incr_vec[i].incr == increment)
2499 incr_vec[i].count++;
2500 found = true;
2502 /* If we previously recorded an initializer that doesn't
2503 dominate this candidate, it's not going to be useful to
2504 us after all. */
2505 if (incr_vec[i].initializer
2506 && !dominated_by_p (CDI_DOMINATORS,
2507 gimple_bb (c->cand_stmt),
2508 incr_vec[i].init_bb))
2510 incr_vec[i].initializer = NULL_TREE;
2511 incr_vec[i].init_bb = NULL;
2514 break;
2518 if (!found && incr_vec_len < MAX_INCR_VEC_LEN - 1)
2520 /* The first time we see an increment, create the entry for it.
2521 If this is the root candidate which doesn't have a basis, set
2522 the count to zero. We're only processing it so it can possibly
2523 provide an initializer for other candidates. */
2524 incr_vec[incr_vec_len].incr = increment;
2525 incr_vec[incr_vec_len].count = c->basis || is_phi_adjust ? 1 : 0;
2526 incr_vec[incr_vec_len].cost = COST_INFINITE;
2528 /* Optimistically record the first occurrence of this increment
2529 as providing an initializer (if it does); we will revise this
2530 opinion later if it doesn't dominate all other occurrences.
2531 Exception: increments of -1, 0, 1 never need initializers;
2532 and phi adjustments don't ever provide initializers. */
2533 if (c->kind == CAND_ADD
2534 && !is_phi_adjust
2535 && c->index == increment
2536 && (wi::gts_p (increment, 1)
2537 || wi::lts_p (increment, -1))
2538 && (gimple_assign_rhs_code (c->cand_stmt) == PLUS_EXPR
2539 || gimple_assign_rhs_code (c->cand_stmt) == POINTER_PLUS_EXPR))
2541 tree t0 = NULL_TREE;
2542 tree rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2543 tree rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2544 if (operand_equal_p (rhs1, c->base_expr, 0))
2545 t0 = rhs2;
2546 else if (operand_equal_p (rhs2, c->base_expr, 0))
2547 t0 = rhs1;
2548 if (t0
2549 && SSA_NAME_DEF_STMT (t0)
2550 && gimple_bb (SSA_NAME_DEF_STMT (t0)))
2552 incr_vec[incr_vec_len].initializer = t0;
2553 incr_vec[incr_vec_len++].init_bb
2554 = gimple_bb (SSA_NAME_DEF_STMT (t0));
2556 else
2558 incr_vec[incr_vec_len].initializer = NULL_TREE;
2559 incr_vec[incr_vec_len++].init_bb = NULL;
2562 else
2564 incr_vec[incr_vec_len].initializer = NULL_TREE;
2565 incr_vec[incr_vec_len++].init_bb = NULL;
2570 /* Given phi statement PHI that hides a candidate from its BASIS, find
2571 the increments along each incoming arc (recursively handling additional
2572 phis that may be present) and record them. These increments are the
2573 difference in index between the index-adjusting statements and the
2574 index of the basis. */
2576 static void
2577 record_phi_increments (slsr_cand_t basis, gimple phi)
2579 unsigned i;
2580 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2582 for (i = 0; i < gimple_phi_num_args (phi); i++)
2584 tree arg = gimple_phi_arg_def (phi, i);
2586 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2588 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2590 if (gimple_code (arg_def) == GIMPLE_PHI)
2591 record_phi_increments (basis, arg_def);
2592 else
2594 slsr_cand_t arg_cand = base_cand_from_table (arg);
2595 widest_int diff = arg_cand->index - basis->index;
2596 record_increment (arg_cand, diff, PHI_ADJUST);
2602 /* Determine how many times each unique increment occurs in the set
2603 of candidates rooted at C's parent, recording the data in the
2604 increment vector. For each unique increment I, if an initializer
2605 T_0 = stride * I is provided by a candidate that dominates all
2606 candidates with the same increment, also record T_0 for subsequent
2607 use. */
2609 static void
2610 record_increments (slsr_cand_t c)
2612 if (!cand_already_replaced (c))
2614 if (!phi_dependent_cand_p (c))
2615 record_increment (c, cand_increment (c), NOT_PHI_ADJUST);
2616 else
2618 /* A candidate with a basis hidden by a phi will have one
2619 increment for its relationship to the index represented by
2620 the phi, and potentially additional increments along each
2621 incoming edge. For the root of the dependency tree (which
2622 has no basis), process just the initial index in case it has
2623 an initializer that can be used by subsequent candidates. */
2624 record_increment (c, c->index, NOT_PHI_ADJUST);
2626 if (c->basis)
2627 record_phi_increments (lookup_cand (c->basis),
2628 lookup_cand (c->def_phi)->cand_stmt);
2632 if (c->sibling)
2633 record_increments (lookup_cand (c->sibling));
2635 if (c->dependent)
2636 record_increments (lookup_cand (c->dependent));
2639 /* Add up and return the costs of introducing add statements that
2640 require the increment INCR on behalf of candidate C and phi
2641 statement PHI. Accumulate into *SAVINGS the potential savings
2642 from removing existing statements that feed PHI and have no other
2643 uses. */
2645 static int
2646 phi_incr_cost (slsr_cand_t c, const widest_int &incr, gimple phi, int *savings)
2648 unsigned i;
2649 int cost = 0;
2650 slsr_cand_t basis = lookup_cand (c->basis);
2651 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2653 for (i = 0; i < gimple_phi_num_args (phi); i++)
2655 tree arg = gimple_phi_arg_def (phi, i);
2657 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2659 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2661 if (gimple_code (arg_def) == GIMPLE_PHI)
2663 int feeding_savings = 0;
2664 cost += phi_incr_cost (c, incr, arg_def, &feeding_savings);
2665 if (has_single_use (gimple_phi_result (arg_def)))
2666 *savings += feeding_savings;
2668 else
2670 slsr_cand_t arg_cand = base_cand_from_table (arg);
2671 widest_int diff = arg_cand->index - basis->index;
2673 if (incr == diff)
2675 tree basis_lhs = gimple_assign_lhs (basis->cand_stmt);
2676 tree lhs = gimple_assign_lhs (arg_cand->cand_stmt);
2677 cost += add_cost (true, TYPE_MODE (TREE_TYPE (basis_lhs)));
2678 if (has_single_use (lhs))
2679 *savings += stmt_cost (arg_cand->cand_stmt, true);
2685 return cost;
2688 /* Return the first candidate in the tree rooted at C that has not
2689 already been replaced, favoring siblings over dependents. */
2691 static slsr_cand_t
2692 unreplaced_cand_in_tree (slsr_cand_t c)
2694 if (!cand_already_replaced (c))
2695 return c;
2697 if (c->sibling)
2699 slsr_cand_t sib = unreplaced_cand_in_tree (lookup_cand (c->sibling));
2700 if (sib)
2701 return sib;
2704 if (c->dependent)
2706 slsr_cand_t dep = unreplaced_cand_in_tree (lookup_cand (c->dependent));
2707 if (dep)
2708 return dep;
2711 return NULL;
2714 /* Return TRUE if the candidates in the tree rooted at C should be
2715 optimized for speed, else FALSE. We estimate this based on the block
2716 containing the most dominant candidate in the tree that has not yet
2717 been replaced. */
2719 static bool
2720 optimize_cands_for_speed_p (slsr_cand_t c)
2722 slsr_cand_t c2 = unreplaced_cand_in_tree (c);
2723 gcc_assert (c2);
2724 return optimize_bb_for_speed_p (gimple_bb (c2->cand_stmt));
2727 /* Add COST_IN to the lowest cost of any dependent path starting at
2728 candidate C or any of its siblings, counting only candidates along
2729 such paths with increment INCR. Assume that replacing a candidate
2730 reduces cost by REPL_SAVINGS. Also account for savings from any
2731 statements that would go dead. If COUNT_PHIS is true, include
2732 costs of introducing feeding statements for conditional candidates. */
2734 static int
2735 lowest_cost_path (int cost_in, int repl_savings, slsr_cand_t c,
2736 const widest_int &incr, bool count_phis)
2738 int local_cost, sib_cost, savings = 0;
2739 widest_int cand_incr = cand_abs_increment (c);
2741 if (cand_already_replaced (c))
2742 local_cost = cost_in;
2743 else if (incr == cand_incr)
2744 local_cost = cost_in - repl_savings - c->dead_savings;
2745 else
2746 local_cost = cost_in - c->dead_savings;
2748 if (count_phis
2749 && phi_dependent_cand_p (c)
2750 && !cand_already_replaced (c))
2752 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2753 local_cost += phi_incr_cost (c, incr, phi, &savings);
2755 if (has_single_use (gimple_phi_result (phi)))
2756 local_cost -= savings;
2759 if (c->dependent)
2760 local_cost = lowest_cost_path (local_cost, repl_savings,
2761 lookup_cand (c->dependent), incr,
2762 count_phis);
2764 if (c->sibling)
2766 sib_cost = lowest_cost_path (cost_in, repl_savings,
2767 lookup_cand (c->sibling), incr,
2768 count_phis);
2769 local_cost = MIN (local_cost, sib_cost);
2772 return local_cost;
2775 /* Compute the total savings that would accrue from all replacements
2776 in the candidate tree rooted at C, counting only candidates with
2777 increment INCR. Assume that replacing a candidate reduces cost
2778 by REPL_SAVINGS. Also account for savings from statements that
2779 would go dead. */
2781 static int
2782 total_savings (int repl_savings, slsr_cand_t c, const widest_int &incr,
2783 bool count_phis)
2785 int savings = 0;
2786 widest_int cand_incr = cand_abs_increment (c);
2788 if (incr == cand_incr && !cand_already_replaced (c))
2789 savings += repl_savings + c->dead_savings;
2791 if (count_phis
2792 && phi_dependent_cand_p (c)
2793 && !cand_already_replaced (c))
2795 int phi_savings = 0;
2796 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2797 savings -= phi_incr_cost (c, incr, phi, &phi_savings);
2799 if (has_single_use (gimple_phi_result (phi)))
2800 savings += phi_savings;
2803 if (c->dependent)
2804 savings += total_savings (repl_savings, lookup_cand (c->dependent), incr,
2805 count_phis);
2807 if (c->sibling)
2808 savings += total_savings (repl_savings, lookup_cand (c->sibling), incr,
2809 count_phis);
2811 return savings;
2814 /* Use target-specific costs to determine and record which increments
2815 in the current candidate tree are profitable to replace, assuming
2816 MODE and SPEED. FIRST_DEP is the first dependent of the root of
2817 the candidate tree.
2819 One slight limitation here is that we don't account for the possible
2820 introduction of casts in some cases. See replace_one_candidate for
2821 the cases where these are introduced. This should probably be cleaned
2822 up sometime. */
2824 static void
2825 analyze_increments (slsr_cand_t first_dep, machine_mode mode, bool speed)
2827 unsigned i;
2829 for (i = 0; i < incr_vec_len; i++)
2831 HOST_WIDE_INT incr = incr_vec[i].incr.to_shwi ();
2833 /* If somehow this increment is bigger than a HWI, we won't
2834 be optimizing candidates that use it. And if the increment
2835 has a count of zero, nothing will be done with it. */
2836 if (!wi::fits_shwi_p (incr_vec[i].incr) || !incr_vec[i].count)
2837 incr_vec[i].cost = COST_INFINITE;
2839 /* Increments of 0, 1, and -1 are always profitable to replace,
2840 because they always replace a multiply or add with an add or
2841 copy, and may cause one or more existing instructions to go
2842 dead. Exception: -1 can't be assumed to be profitable for
2843 pointer addition. */
2844 else if (incr == 0
2845 || incr == 1
2846 || (incr == -1
2847 && (gimple_assign_rhs_code (first_dep->cand_stmt)
2848 != POINTER_PLUS_EXPR)))
2849 incr_vec[i].cost = COST_NEUTRAL;
2851 /* FORNOW: If we need to add an initializer, give up if a cast from
2852 the candidate's type to its stride's type can lose precision.
2853 This could eventually be handled better by expressly retaining the
2854 result of a cast to a wider type in the stride. Example:
2856 short int _1;
2857 _2 = (int) _1;
2858 _3 = _2 * 10;
2859 _4 = x + _3; ADD: x + (10 * _1) : int
2860 _5 = _2 * 15;
2861 _6 = x + _3; ADD: x + (15 * _1) : int
2863 Right now replacing _6 would cause insertion of an initializer
2864 of the form "short int T = _1 * 5;" followed by a cast to
2865 int, which could overflow incorrectly. Had we recorded _2 or
2866 (int)_1 as the stride, this wouldn't happen. However, doing
2867 this breaks other opportunities, so this will require some
2868 care. */
2869 else if (!incr_vec[i].initializer
2870 && TREE_CODE (first_dep->stride) != INTEGER_CST
2871 && !legal_cast_p_1 (first_dep->stride,
2872 gimple_assign_lhs (first_dep->cand_stmt)))
2874 incr_vec[i].cost = COST_INFINITE;
2876 /* If we need to add an initializer, make sure we don't introduce
2877 a multiply by a pointer type, which can happen in certain cast
2878 scenarios. FIXME: When cleaning up these cast issues, we can
2879 afford to introduce the multiply provided we cast out to an
2880 unsigned int of appropriate size. */
2881 else if (!incr_vec[i].initializer
2882 && TREE_CODE (first_dep->stride) != INTEGER_CST
2883 && POINTER_TYPE_P (TREE_TYPE (first_dep->stride)))
2885 incr_vec[i].cost = COST_INFINITE;
2887 /* For any other increment, if this is a multiply candidate, we
2888 must introduce a temporary T and initialize it with
2889 T_0 = stride * increment. When optimizing for speed, walk the
2890 candidate tree to calculate the best cost reduction along any
2891 path; if it offsets the fixed cost of inserting the initializer,
2892 replacing the increment is profitable. When optimizing for
2893 size, instead calculate the total cost reduction from replacing
2894 all candidates with this increment. */
2895 else if (first_dep->kind == CAND_MULT)
2897 int cost = mult_by_coeff_cost (incr, mode, speed);
2898 int repl_savings = mul_cost (speed, mode) - add_cost (speed, mode);
2899 if (speed)
2900 cost = lowest_cost_path (cost, repl_savings, first_dep,
2901 incr_vec[i].incr, COUNT_PHIS);
2902 else
2903 cost -= total_savings (repl_savings, first_dep, incr_vec[i].incr,
2904 COUNT_PHIS);
2906 incr_vec[i].cost = cost;
2909 /* If this is an add candidate, the initializer may already
2910 exist, so only calculate the cost of the initializer if it
2911 doesn't. We are replacing one add with another here, so the
2912 known replacement savings is zero. We will account for removal
2913 of dead instructions in lowest_cost_path or total_savings. */
2914 else
2916 int cost = 0;
2917 if (!incr_vec[i].initializer)
2918 cost = mult_by_coeff_cost (incr, mode, speed);
2920 if (speed)
2921 cost = lowest_cost_path (cost, 0, first_dep, incr_vec[i].incr,
2922 DONT_COUNT_PHIS);
2923 else
2924 cost -= total_savings (0, first_dep, incr_vec[i].incr,
2925 DONT_COUNT_PHIS);
2927 incr_vec[i].cost = cost;
2932 /* Return the nearest common dominator of BB1 and BB2. If the blocks
2933 are identical, return the earlier of C1 and C2 in *WHERE. Otherwise,
2934 if the NCD matches BB1, return C1 in *WHERE; if the NCD matches BB2,
2935 return C2 in *WHERE; and if the NCD matches neither, return NULL in
2936 *WHERE. Note: It is possible for one of C1 and C2 to be NULL. */
2938 static basic_block
2939 ncd_for_two_cands (basic_block bb1, basic_block bb2,
2940 slsr_cand_t c1, slsr_cand_t c2, slsr_cand_t *where)
2942 basic_block ncd;
2944 if (!bb1)
2946 *where = c2;
2947 return bb2;
2950 if (!bb2)
2952 *where = c1;
2953 return bb1;
2956 ncd = nearest_common_dominator (CDI_DOMINATORS, bb1, bb2);
2958 /* If both candidates are in the same block, the earlier
2959 candidate wins. */
2960 if (bb1 == ncd && bb2 == ncd)
2962 if (!c1 || (c2 && c2->cand_num < c1->cand_num))
2963 *where = c2;
2964 else
2965 *where = c1;
2968 /* Otherwise, if one of them produced a candidate in the
2969 dominator, that one wins. */
2970 else if (bb1 == ncd)
2971 *where = c1;
2973 else if (bb2 == ncd)
2974 *where = c2;
2976 /* If neither matches the dominator, neither wins. */
2977 else
2978 *where = NULL;
2980 return ncd;
2983 /* Consider all candidates that feed PHI. Find the nearest common
2984 dominator of those candidates requiring the given increment INCR.
2985 Further find and return the nearest common dominator of this result
2986 with block NCD. If the returned block contains one or more of the
2987 candidates, return the earliest candidate in the block in *WHERE. */
2989 static basic_block
2990 ncd_with_phi (slsr_cand_t c, const widest_int &incr, gphi *phi,
2991 basic_block ncd, slsr_cand_t *where)
2993 unsigned i;
2994 slsr_cand_t basis = lookup_cand (c->basis);
2995 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2997 for (i = 0; i < gimple_phi_num_args (phi); i++)
2999 tree arg = gimple_phi_arg_def (phi, i);
3001 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
3003 gimple arg_def = SSA_NAME_DEF_STMT (arg);
3005 if (gimple_code (arg_def) == GIMPLE_PHI)
3006 ncd = ncd_with_phi (c, incr, as_a <gphi *> (arg_def), ncd,
3007 where);
3008 else
3010 slsr_cand_t arg_cand = base_cand_from_table (arg);
3011 widest_int diff = arg_cand->index - basis->index;
3012 basic_block pred = gimple_phi_arg_edge (phi, i)->src;
3014 if ((incr == diff) || (!address_arithmetic_p && incr == -diff))
3015 ncd = ncd_for_two_cands (ncd, pred, *where, NULL, where);
3020 return ncd;
3023 /* Consider the candidate C together with any candidates that feed
3024 C's phi dependence (if any). Find and return the nearest common
3025 dominator of those candidates requiring the given increment INCR.
3026 If the returned block contains one or more of the candidates,
3027 return the earliest candidate in the block in *WHERE. */
3029 static basic_block
3030 ncd_of_cand_and_phis (slsr_cand_t c, const widest_int &incr, slsr_cand_t *where)
3032 basic_block ncd = NULL;
3034 if (cand_abs_increment (c) == incr)
3036 ncd = gimple_bb (c->cand_stmt);
3037 *where = c;
3040 if (phi_dependent_cand_p (c))
3041 ncd = ncd_with_phi (c, incr,
3042 as_a <gphi *> (lookup_cand (c->def_phi)->cand_stmt),
3043 ncd, where);
3045 return ncd;
3048 /* Consider all candidates in the tree rooted at C for which INCR
3049 represents the required increment of C relative to its basis.
3050 Find and return the basic block that most nearly dominates all
3051 such candidates. If the returned block contains one or more of
3052 the candidates, return the earliest candidate in the block in
3053 *WHERE. */
3055 static basic_block
3056 nearest_common_dominator_for_cands (slsr_cand_t c, const widest_int &incr,
3057 slsr_cand_t *where)
3059 basic_block sib_ncd = NULL, dep_ncd = NULL, this_ncd = NULL, ncd;
3060 slsr_cand_t sib_where = NULL, dep_where = NULL, this_where = NULL, new_where;
3062 /* First find the NCD of all siblings and dependents. */
3063 if (c->sibling)
3064 sib_ncd = nearest_common_dominator_for_cands (lookup_cand (c->sibling),
3065 incr, &sib_where);
3066 if (c->dependent)
3067 dep_ncd = nearest_common_dominator_for_cands (lookup_cand (c->dependent),
3068 incr, &dep_where);
3069 if (!sib_ncd && !dep_ncd)
3071 new_where = NULL;
3072 ncd = NULL;
3074 else if (sib_ncd && !dep_ncd)
3076 new_where = sib_where;
3077 ncd = sib_ncd;
3079 else if (dep_ncd && !sib_ncd)
3081 new_where = dep_where;
3082 ncd = dep_ncd;
3084 else
3085 ncd = ncd_for_two_cands (sib_ncd, dep_ncd, sib_where,
3086 dep_where, &new_where);
3088 /* If the candidate's increment doesn't match the one we're interested
3089 in (and nor do any increments for feeding defs of a phi-dependence),
3090 then the result depends only on siblings and dependents. */
3091 this_ncd = ncd_of_cand_and_phis (c, incr, &this_where);
3093 if (!this_ncd || cand_already_replaced (c))
3095 *where = new_where;
3096 return ncd;
3099 /* Otherwise, compare this candidate with the result from all siblings
3100 and dependents. */
3101 ncd = ncd_for_two_cands (ncd, this_ncd, new_where, this_where, where);
3103 return ncd;
3106 /* Return TRUE if the increment indexed by INDEX is profitable to replace. */
3108 static inline bool
3109 profitable_increment_p (unsigned index)
3111 return (incr_vec[index].cost <= COST_NEUTRAL);
3114 /* For each profitable increment in the increment vector not equal to
3115 0 or 1 (or -1, for non-pointer arithmetic), find the nearest common
3116 dominator of all statements in the candidate chain rooted at C
3117 that require that increment, and insert an initializer
3118 T_0 = stride * increment at that location. Record T_0 with the
3119 increment record. */
3121 static void
3122 insert_initializers (slsr_cand_t c)
3124 unsigned i;
3126 for (i = 0; i < incr_vec_len; i++)
3128 basic_block bb;
3129 slsr_cand_t where = NULL;
3130 gassign *init_stmt;
3131 tree stride_type, new_name, incr_tree;
3132 widest_int incr = incr_vec[i].incr;
3134 if (!profitable_increment_p (i)
3135 || incr == 1
3136 || (incr == -1
3137 && gimple_assign_rhs_code (c->cand_stmt) != POINTER_PLUS_EXPR)
3138 || incr == 0)
3139 continue;
3141 /* We may have already identified an existing initializer that
3142 will suffice. */
3143 if (incr_vec[i].initializer)
3145 if (dump_file && (dump_flags & TDF_DETAILS))
3147 fputs ("Using existing initializer: ", dump_file);
3148 print_gimple_stmt (dump_file,
3149 SSA_NAME_DEF_STMT (incr_vec[i].initializer),
3150 0, 0);
3152 continue;
3155 /* Find the block that most closely dominates all candidates
3156 with this increment. If there is at least one candidate in
3157 that block, the earliest one will be returned in WHERE. */
3158 bb = nearest_common_dominator_for_cands (c, incr, &where);
3160 /* Create a new SSA name to hold the initializer's value. */
3161 stride_type = TREE_TYPE (c->stride);
3162 new_name = make_temp_ssa_name (stride_type, NULL, "slsr");
3163 incr_vec[i].initializer = new_name;
3165 /* Create the initializer and insert it in the latest possible
3166 dominating position. */
3167 incr_tree = wide_int_to_tree (stride_type, incr);
3168 init_stmt = gimple_build_assign (new_name, MULT_EXPR,
3169 c->stride, incr_tree);
3170 if (where)
3172 gimple_stmt_iterator gsi = gsi_for_stmt (where->cand_stmt);
3173 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
3174 gimple_set_location (init_stmt, gimple_location (where->cand_stmt));
3176 else
3178 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3179 gimple basis_stmt = lookup_cand (c->basis)->cand_stmt;
3181 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
3182 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
3183 else
3184 gsi_insert_after (&gsi, init_stmt, GSI_SAME_STMT);
3186 gimple_set_location (init_stmt, gimple_location (basis_stmt));
3189 if (dump_file && (dump_flags & TDF_DETAILS))
3191 fputs ("Inserting initializer: ", dump_file);
3192 print_gimple_stmt (dump_file, init_stmt, 0, 0);
3197 /* Return TRUE iff all required increments for candidates feeding PHI
3198 are profitable to replace on behalf of candidate C. */
3200 static bool
3201 all_phi_incrs_profitable (slsr_cand_t c, gimple phi)
3203 unsigned i;
3204 slsr_cand_t basis = lookup_cand (c->basis);
3205 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
3207 for (i = 0; i < gimple_phi_num_args (phi); i++)
3209 tree arg = gimple_phi_arg_def (phi, i);
3211 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
3213 gimple arg_def = SSA_NAME_DEF_STMT (arg);
3215 if (gimple_code (arg_def) == GIMPLE_PHI)
3217 if (!all_phi_incrs_profitable (c, arg_def))
3218 return false;
3220 else
3222 int j;
3223 slsr_cand_t arg_cand = base_cand_from_table (arg);
3224 widest_int increment = arg_cand->index - basis->index;
3226 if (!address_arithmetic_p && wi::neg_p (increment))
3227 increment = -increment;
3229 j = incr_vec_index (increment);
3231 if (dump_file && (dump_flags & TDF_DETAILS))
3233 fprintf (dump_file, " Conditional candidate %d, phi: ",
3234 c->cand_num);
3235 print_gimple_stmt (dump_file, phi, 0, 0);
3236 fputs (" increment: ", dump_file);
3237 print_decs (increment, dump_file);
3238 if (j < 0)
3239 fprintf (dump_file,
3240 "\n Not replaced; incr_vec overflow.\n");
3241 else {
3242 fprintf (dump_file, "\n cost: %d\n", incr_vec[j].cost);
3243 if (profitable_increment_p (j))
3244 fputs (" Replacing...\n", dump_file);
3245 else
3246 fputs (" Not replaced.\n", dump_file);
3250 if (j < 0 || !profitable_increment_p (j))
3251 return false;
3256 return true;
3259 /* Create a NOP_EXPR that copies FROM_EXPR into a new SSA name of
3260 type TO_TYPE, and insert it in front of the statement represented
3261 by candidate C. Use *NEW_VAR to create the new SSA name. Return
3262 the new SSA name. */
3264 static tree
3265 introduce_cast_before_cand (slsr_cand_t c, tree to_type, tree from_expr)
3267 tree cast_lhs;
3268 gassign *cast_stmt;
3269 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3271 cast_lhs = make_temp_ssa_name (to_type, NULL, "slsr");
3272 cast_stmt = gimple_build_assign (cast_lhs, NOP_EXPR, from_expr);
3273 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
3274 gsi_insert_before (&gsi, cast_stmt, GSI_SAME_STMT);
3276 if (dump_file && (dump_flags & TDF_DETAILS))
3278 fputs (" Inserting: ", dump_file);
3279 print_gimple_stmt (dump_file, cast_stmt, 0, 0);
3282 return cast_lhs;
3285 /* Replace the RHS of the statement represented by candidate C with
3286 NEW_CODE, NEW_RHS1, and NEW_RHS2, provided that to do so doesn't
3287 leave C unchanged or just interchange its operands. The original
3288 operation and operands are in OLD_CODE, OLD_RHS1, and OLD_RHS2.
3289 If the replacement was made and we are doing a details dump,
3290 return the revised statement, else NULL. */
3292 static gimple
3293 replace_rhs_if_not_dup (enum tree_code new_code, tree new_rhs1, tree new_rhs2,
3294 enum tree_code old_code, tree old_rhs1, tree old_rhs2,
3295 slsr_cand_t c)
3297 if (new_code != old_code
3298 || ((!operand_equal_p (new_rhs1, old_rhs1, 0)
3299 || !operand_equal_p (new_rhs2, old_rhs2, 0))
3300 && (!operand_equal_p (new_rhs1, old_rhs2, 0)
3301 || !operand_equal_p (new_rhs2, old_rhs1, 0))))
3303 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3304 gimple_assign_set_rhs_with_ops (&gsi, new_code, new_rhs1, new_rhs2);
3305 update_stmt (gsi_stmt (gsi));
3306 c->cand_stmt = gsi_stmt (gsi);
3308 if (dump_file && (dump_flags & TDF_DETAILS))
3309 return gsi_stmt (gsi);
3312 else if (dump_file && (dump_flags & TDF_DETAILS))
3313 fputs (" (duplicate, not actually replacing)\n", dump_file);
3315 return NULL;
3318 /* Strength-reduce the statement represented by candidate C by replacing
3319 it with an equivalent addition or subtraction. I is the index into
3320 the increment vector identifying C's increment. NEW_VAR is used to
3321 create a new SSA name if a cast needs to be introduced. BASIS_NAME
3322 is the rhs1 to use in creating the add/subtract. */
3324 static void
3325 replace_one_candidate (slsr_cand_t c, unsigned i, tree basis_name)
3327 gimple stmt_to_print = NULL;
3328 tree orig_rhs1, orig_rhs2;
3329 tree rhs2;
3330 enum tree_code orig_code, repl_code;
3331 widest_int cand_incr;
3333 orig_code = gimple_assign_rhs_code (c->cand_stmt);
3334 orig_rhs1 = gimple_assign_rhs1 (c->cand_stmt);
3335 orig_rhs2 = gimple_assign_rhs2 (c->cand_stmt);
3336 cand_incr = cand_increment (c);
3338 if (dump_file && (dump_flags & TDF_DETAILS))
3340 fputs ("Replacing: ", dump_file);
3341 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
3342 stmt_to_print = c->cand_stmt;
3345 if (address_arithmetic_p)
3346 repl_code = POINTER_PLUS_EXPR;
3347 else
3348 repl_code = PLUS_EXPR;
3350 /* If the increment has an initializer T_0, replace the candidate
3351 statement with an add of the basis name and the initializer. */
3352 if (incr_vec[i].initializer)
3354 tree init_type = TREE_TYPE (incr_vec[i].initializer);
3355 tree orig_type = TREE_TYPE (orig_rhs2);
3357 if (types_compatible_p (orig_type, init_type))
3358 rhs2 = incr_vec[i].initializer;
3359 else
3360 rhs2 = introduce_cast_before_cand (c, orig_type,
3361 incr_vec[i].initializer);
3363 if (incr_vec[i].incr != cand_incr)
3365 gcc_assert (repl_code == PLUS_EXPR);
3366 repl_code = MINUS_EXPR;
3369 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
3370 orig_code, orig_rhs1, orig_rhs2,
3374 /* Otherwise, the increment is one of -1, 0, and 1. Replace
3375 with a subtract of the stride from the basis name, a copy
3376 from the basis name, or an add of the stride to the basis
3377 name, respectively. It may be necessary to introduce a
3378 cast (or reuse an existing cast). */
3379 else if (cand_incr == 1)
3381 tree stride_type = TREE_TYPE (c->stride);
3382 tree orig_type = TREE_TYPE (orig_rhs2);
3384 if (types_compatible_p (orig_type, stride_type))
3385 rhs2 = c->stride;
3386 else
3387 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride);
3389 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
3390 orig_code, orig_rhs1, orig_rhs2,
3394 else if (cand_incr == -1)
3396 tree stride_type = TREE_TYPE (c->stride);
3397 tree orig_type = TREE_TYPE (orig_rhs2);
3398 gcc_assert (repl_code != POINTER_PLUS_EXPR);
3400 if (types_compatible_p (orig_type, stride_type))
3401 rhs2 = c->stride;
3402 else
3403 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride);
3405 if (orig_code != MINUS_EXPR
3406 || !operand_equal_p (basis_name, orig_rhs1, 0)
3407 || !operand_equal_p (rhs2, orig_rhs2, 0))
3409 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3410 gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, basis_name, rhs2);
3411 update_stmt (gsi_stmt (gsi));
3412 c->cand_stmt = gsi_stmt (gsi);
3414 if (dump_file && (dump_flags & TDF_DETAILS))
3415 stmt_to_print = gsi_stmt (gsi);
3417 else if (dump_file && (dump_flags & TDF_DETAILS))
3418 fputs (" (duplicate, not actually replacing)\n", dump_file);
3421 else if (cand_incr == 0)
3423 tree lhs = gimple_assign_lhs (c->cand_stmt);
3424 tree lhs_type = TREE_TYPE (lhs);
3425 tree basis_type = TREE_TYPE (basis_name);
3427 if (types_compatible_p (lhs_type, basis_type))
3429 gassign *copy_stmt = gimple_build_assign (lhs, basis_name);
3430 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3431 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
3432 gsi_replace (&gsi, copy_stmt, false);
3433 c->cand_stmt = copy_stmt;
3435 if (dump_file && (dump_flags & TDF_DETAILS))
3436 stmt_to_print = copy_stmt;
3438 else
3440 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3441 gassign *cast_stmt = gimple_build_assign (lhs, NOP_EXPR, basis_name);
3442 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
3443 gsi_replace (&gsi, cast_stmt, false);
3444 c->cand_stmt = cast_stmt;
3446 if (dump_file && (dump_flags & TDF_DETAILS))
3447 stmt_to_print = cast_stmt;
3450 else
3451 gcc_unreachable ();
3453 if (dump_file && (dump_flags & TDF_DETAILS) && stmt_to_print)
3455 fputs ("With: ", dump_file);
3456 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
3457 fputs ("\n", dump_file);
3461 /* For each candidate in the tree rooted at C, replace it with
3462 an increment if such has been shown to be profitable. */
3464 static void
3465 replace_profitable_candidates (slsr_cand_t c)
3467 if (!cand_already_replaced (c))
3469 widest_int increment = cand_abs_increment (c);
3470 enum tree_code orig_code = gimple_assign_rhs_code (c->cand_stmt);
3471 int i;
3473 i = incr_vec_index (increment);
3475 /* Only process profitable increments. Nothing useful can be done
3476 to a cast or copy. */
3477 if (i >= 0
3478 && profitable_increment_p (i)
3479 && orig_code != MODIFY_EXPR
3480 && !CONVERT_EXPR_CODE_P (orig_code))
3482 if (phi_dependent_cand_p (c))
3484 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
3486 if (all_phi_incrs_profitable (c, phi))
3488 /* Look up the LHS SSA name from C's basis. This will be
3489 the RHS1 of the adds we will introduce to create new
3490 phi arguments. */
3491 slsr_cand_t basis = lookup_cand (c->basis);
3492 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
3494 /* Create a new phi statement that will represent C's true
3495 basis after the transformation is complete. */
3496 location_t loc = gimple_location (c->cand_stmt);
3497 tree name = create_phi_basis (c, phi, basis_name,
3498 loc, UNKNOWN_STRIDE);
3500 /* Replace C with an add of the new basis phi and the
3501 increment. */
3502 replace_one_candidate (c, i, name);
3505 else
3507 slsr_cand_t basis = lookup_cand (c->basis);
3508 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
3509 replace_one_candidate (c, i, basis_name);
3514 if (c->sibling)
3515 replace_profitable_candidates (lookup_cand (c->sibling));
3517 if (c->dependent)
3518 replace_profitable_candidates (lookup_cand (c->dependent));
3521 /* Analyze costs of related candidates in the candidate vector,
3522 and make beneficial replacements. */
3524 static void
3525 analyze_candidates_and_replace (void)
3527 unsigned i;
3528 slsr_cand_t c;
3530 /* Each candidate that has a null basis and a non-null
3531 dependent is the root of a tree of related statements.
3532 Analyze each tree to determine a subset of those
3533 statements that can be replaced with maximum benefit. */
3534 FOR_EACH_VEC_ELT (cand_vec, i, c)
3536 slsr_cand_t first_dep;
3538 if (c->basis != 0 || c->dependent == 0)
3539 continue;
3541 if (dump_file && (dump_flags & TDF_DETAILS))
3542 fprintf (dump_file, "\nProcessing dependency tree rooted at %d.\n",
3543 c->cand_num);
3545 first_dep = lookup_cand (c->dependent);
3547 /* If this is a chain of CAND_REFs, unconditionally replace
3548 each of them with a strength-reduced data reference. */
3549 if (c->kind == CAND_REF)
3550 replace_refs (c);
3552 /* If the common stride of all related candidates is a known
3553 constant, each candidate without a phi-dependence can be
3554 profitably replaced. Each replaces a multiply by a single
3555 add, with the possibility that a feeding add also goes dead.
3556 A candidate with a phi-dependence is replaced only if the
3557 compensation code it requires is offset by the strength
3558 reduction savings. */
3559 else if (TREE_CODE (c->stride) == INTEGER_CST)
3560 replace_uncond_cands_and_profitable_phis (first_dep);
3562 /* When the stride is an SSA name, it may still be profitable
3563 to replace some or all of the dependent candidates, depending
3564 on whether the introduced increments can be reused, or are
3565 less expensive to calculate than the replaced statements. */
3566 else
3568 machine_mode mode;
3569 bool speed;
3571 /* Determine whether we'll be generating pointer arithmetic
3572 when replacing candidates. */
3573 address_arithmetic_p = (c->kind == CAND_ADD
3574 && POINTER_TYPE_P (c->cand_type));
3576 /* If all candidates have already been replaced under other
3577 interpretations, nothing remains to be done. */
3578 if (!count_candidates (c))
3579 continue;
3581 /* Construct an array of increments for this candidate chain. */
3582 incr_vec = XNEWVEC (incr_info, MAX_INCR_VEC_LEN);
3583 incr_vec_len = 0;
3584 record_increments (c);
3586 /* Determine which increments are profitable to replace. */
3587 mode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (c->cand_stmt)));
3588 speed = optimize_cands_for_speed_p (c);
3589 analyze_increments (first_dep, mode, speed);
3591 /* Insert initializers of the form T_0 = stride * increment
3592 for use in profitable replacements. */
3593 insert_initializers (first_dep);
3594 dump_incr_vec ();
3596 /* Perform the replacements. */
3597 replace_profitable_candidates (first_dep);
3598 free (incr_vec);
3603 namespace {
3605 const pass_data pass_data_strength_reduction =
3607 GIMPLE_PASS, /* type */
3608 "slsr", /* name */
3609 OPTGROUP_NONE, /* optinfo_flags */
3610 TV_GIMPLE_SLSR, /* tv_id */
3611 ( PROP_cfg | PROP_ssa ), /* properties_required */
3612 0, /* properties_provided */
3613 0, /* properties_destroyed */
3614 0, /* todo_flags_start */
3615 0, /* todo_flags_finish */
3618 class pass_strength_reduction : public gimple_opt_pass
3620 public:
3621 pass_strength_reduction (gcc::context *ctxt)
3622 : gimple_opt_pass (pass_data_strength_reduction, ctxt)
3625 /* opt_pass methods: */
3626 virtual bool gate (function *) { return flag_tree_slsr; }
3627 virtual unsigned int execute (function *);
3629 }; // class pass_strength_reduction
3631 unsigned
3632 pass_strength_reduction::execute (function *fun)
3634 /* Create the obstack where candidates will reside. */
3635 gcc_obstack_init (&cand_obstack);
3637 /* Allocate the candidate vector. */
3638 cand_vec.create (128);
3640 /* Allocate the mapping from statements to candidate indices. */
3641 stmt_cand_map = new hash_map<gimple, slsr_cand_t>;
3643 /* Create the obstack where candidate chains will reside. */
3644 gcc_obstack_init (&chain_obstack);
3646 /* Allocate the mapping from base expressions to candidate chains. */
3647 base_cand_map = new hash_table<cand_chain_hasher> (500);
3649 /* Allocate the mapping from bases to alternative bases. */
3650 alt_base_map = new hash_map<tree, tree>;
3652 /* Initialize the loop optimizer. We need to detect flow across
3653 back edges, and this gives us dominator information as well. */
3654 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
3656 /* Walk the CFG in predominator order looking for strength reduction
3657 candidates. */
3658 find_candidates_dom_walker (CDI_DOMINATORS)
3659 .walk (fun->cfg->x_entry_block_ptr);
3661 if (dump_file && (dump_flags & TDF_DETAILS))
3663 dump_cand_vec ();
3664 dump_cand_chains ();
3667 delete alt_base_map;
3668 free_affine_expand_cache (&name_expansions);
3670 /* Analyze costs and make appropriate replacements. */
3671 analyze_candidates_and_replace ();
3673 loop_optimizer_finalize ();
3674 delete base_cand_map;
3675 base_cand_map = NULL;
3676 obstack_free (&chain_obstack, NULL);
3677 delete stmt_cand_map;
3678 cand_vec.release ();
3679 obstack_free (&cand_obstack, NULL);
3681 return 0;
3684 } // anon namespace
3686 gimple_opt_pass *
3687 make_pass_strength_reduction (gcc::context *ctxt)
3689 return new pass_strength_reduction (ctxt);