2014-04-24 Segher Boessenkool <segher@kernel.crashing.org>
[official-gcc.git] / gcc / gimple-ssa-strength-reduction.c
blobff55d0eff67f1ae716dc6eff975a54ba6800033d
1 /* Straight-line strength reduction.
2 Copyright (C) 2012-2014 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 "tree.h"
40 #include "pointer-set.h"
41 #include "hash-table.h"
42 #include "basic-block.h"
43 #include "tree-ssa-alias.h"
44 #include "internal-fn.h"
45 #include "gimple-expr.h"
46 #include "is-a.h"
47 #include "gimple.h"
48 #include "gimple-iterator.h"
49 #include "gimplify-me.h"
50 #include "stor-layout.h"
51 #include "expr.h"
52 #include "tree-pass.h"
53 #include "cfgloop.h"
54 #include "gimple-pretty-print.h"
55 #include "gimple-ssa.h"
56 #include "tree-cfg.h"
57 #include "tree-phinodes.h"
58 #include "ssa-iterators.h"
59 #include "stringpool.h"
60 #include "tree-ssanames.h"
61 #include "domwalk.h"
62 #include "expmed.h"
63 #include "params.h"
64 #include "tree-ssa-address.h"
65 #include "tree-affine.h"
67 /* Information about a strength reduction candidate. Each statement
68 in the candidate table represents an expression of one of the
69 following forms (the special case of CAND_REF will be described
70 later):
72 (CAND_MULT) S1: X = (B + i) * S
73 (CAND_ADD) S1: X = B + (i * S)
75 Here X and B are SSA names, i is an integer constant, and S is
76 either an SSA name or a constant. We call B the "base," i the
77 "index", and S the "stride."
79 Any statement S0 that dominates S1 and is of the form:
81 (CAND_MULT) S0: Y = (B + i') * S
82 (CAND_ADD) S0: Y = B + (i' * S)
84 is called a "basis" for S1. In both cases, S1 may be replaced by
86 S1': X = Y + (i - i') * S,
88 where (i - i') * S is folded to the extent possible.
90 All gimple statements are visited in dominator order, and each
91 statement that may contribute to one of the forms of S1 above is
92 given at least one entry in the candidate table. Such statements
93 include addition, pointer addition, subtraction, multiplication,
94 negation, copies, and nontrivial type casts. If a statement may
95 represent more than one expression of the forms of S1 above,
96 multiple "interpretations" are stored in the table and chained
97 together. Examples:
99 * An add of two SSA names may treat either operand as the base.
100 * A multiply of two SSA names, likewise.
101 * A copy or cast may be thought of as either a CAND_MULT with
102 i = 0 and S = 1, or as a CAND_ADD with i = 0 or S = 0.
104 Candidate records are allocated from an obstack. They are addressed
105 both from a hash table keyed on S1, and from a vector of candidate
106 pointers arranged in predominator order.
108 Opportunity note
109 ----------------
110 Currently we don't recognize:
112 S0: Y = (S * i') - B
113 S1: X = (S * i) - B
115 as a strength reduction opportunity, even though this S1 would
116 also be replaceable by the S1' above. This can be added if it
117 comes up in practice.
119 Strength reduction in addressing
120 --------------------------------
121 There is another kind of candidate known as CAND_REF. A CAND_REF
122 describes a statement containing a memory reference having
123 complex addressing that might benefit from strength reduction.
124 Specifically, we are interested in references for which
125 get_inner_reference returns a base address, offset, and bitpos as
126 follows:
128 base: MEM_REF (T1, C1)
129 offset: MULT_EXPR (PLUS_EXPR (T2, C2), C3)
130 bitpos: C4 * BITS_PER_UNIT
132 Here T1 and T2 are arbitrary trees, and C1, C2, C3, C4 are
133 arbitrary integer constants. Note that C2 may be zero, in which
134 case the offset will be MULT_EXPR (T2, C3).
136 When this pattern is recognized, the original memory reference
137 can be replaced with:
139 MEM_REF (POINTER_PLUS_EXPR (T1, MULT_EXPR (T2, C3)),
140 C1 + (C2 * C3) + C4)
142 which distributes the multiply to allow constant folding. When
143 two or more addressing expressions can be represented by MEM_REFs
144 of this form, differing only in the constants C1, C2, and C4,
145 making this substitution produces more efficient addressing during
146 the RTL phases. When there are not at least two expressions with
147 the same values of T1, T2, and C3, there is nothing to be gained
148 by the replacement.
150 Strength reduction of CAND_REFs uses the same infrastructure as
151 that used by CAND_MULTs and CAND_ADDs. We record T1 in the base (B)
152 field, MULT_EXPR (T2, C3) in the stride (S) field, and
153 C1 + (C2 * C3) + C4 in the index (i) field. A basis for a CAND_REF
154 is thus another CAND_REF with the same B and S values. When at
155 least two CAND_REFs are chained together using the basis relation,
156 each of them is replaced as above, resulting in improved code
157 generation for addressing.
159 Conditional candidates
160 ======================
162 Conditional candidates are best illustrated with an example.
163 Consider the code sequence:
165 (1) x_0 = ...;
166 (2) a_0 = x_0 * 5; MULT (B: x_0; i: 0; S: 5)
167 if (...)
168 (3) x_1 = x_0 + 1; ADD (B: x_0, i: 1; S: 1)
169 (4) x_2 = PHI <x_0, x_1>; PHI (B: x_0, i: 0, S: 1)
170 (5) x_3 = x_2 + 1; ADD (B: x_2, i: 1, S: 1)
171 (6) a_1 = x_3 * 5; MULT (B: x_2, i: 1; S: 5)
173 Here strength reduction is complicated by the uncertain value of x_2.
174 A legitimate transformation is:
176 (1) x_0 = ...;
177 (2) a_0 = x_0 * 5;
178 if (...)
180 (3) [x_1 = x_0 + 1;]
181 (3a) t_1 = a_0 + 5;
183 (4) [x_2 = PHI <x_0, x_1>;]
184 (4a) t_2 = PHI <a_0, t_1>;
185 (5) [x_3 = x_2 + 1;]
186 (6r) a_1 = t_2 + 5;
188 where the bracketed instructions may go dead.
190 To recognize this opportunity, we have to observe that statement (6)
191 has a "hidden basis" (2). The hidden basis is unlike a normal basis
192 in that the statement and the hidden basis have different base SSA
193 names (x_2 and x_0, respectively). The relationship is established
194 when a statement's base name (x_2) is defined by a phi statement (4),
195 each argument of which (x_0, x_1) has an identical "derived base name."
196 If the argument is defined by a candidate (as x_1 is by (3)) that is a
197 CAND_ADD having a stride of 1, the derived base name of the argument is
198 the base name of the candidate (x_0). Otherwise, the argument itself
199 is its derived base name (as is the case with argument x_0).
201 The hidden basis for statement (6) is the nearest dominating candidate
202 whose base name is the derived base name (x_0) of the feeding phi (4),
203 and whose stride is identical to that of the statement. We can then
204 create the new "phi basis" (4a) and feeding adds along incoming arcs (3a),
205 allowing the final replacement of (6) by the strength-reduced (6r).
207 To facilitate this, a new kind of candidate (CAND_PHI) is introduced.
208 A CAND_PHI is not a candidate for replacement, but is maintained in the
209 candidate table to ease discovery of hidden bases. Any phi statement
210 whose arguments share a common derived base name is entered into the
211 table with the derived base name, an (arbitrary) index of zero, and a
212 stride of 1. A statement with a hidden basis can then be detected by
213 simply looking up its feeding phi definition in the candidate table,
214 extracting the derived base name, and searching for a basis in the
215 usual manner after substituting the derived base name.
217 Note that the transformation is only valid when the original phi and
218 the statements that define the phi's arguments are all at the same
219 position in the loop hierarchy. */
222 /* Index into the candidate vector, offset by 1. VECs are zero-based,
223 while cand_idx's are one-based, with zero indicating null. */
224 typedef unsigned cand_idx;
226 /* The kind of candidate. */
227 enum cand_kind
229 CAND_MULT,
230 CAND_ADD,
231 CAND_REF,
232 CAND_PHI
235 struct slsr_cand_d
237 /* The candidate statement S1. */
238 gimple cand_stmt;
240 /* The base expression B: often an SSA name, but not always. */
241 tree base_expr;
243 /* The stride S. */
244 tree stride;
246 /* The index constant i. */
247 double_int index;
249 /* The type of the candidate. This is normally the type of base_expr,
250 but casts may have occurred when combining feeding instructions.
251 A candidate can only be a basis for candidates of the same final type.
252 (For CAND_REFs, this is the type to be used for operand 1 of the
253 replacement MEM_REF.) */
254 tree cand_type;
256 /* The kind of candidate (CAND_MULT, etc.). */
257 enum cand_kind kind;
259 /* Index of this candidate in the candidate vector. */
260 cand_idx cand_num;
262 /* Index of the next candidate record for the same statement.
263 A statement may be useful in more than one way (e.g., due to
264 commutativity). So we can have multiple "interpretations"
265 of a statement. */
266 cand_idx next_interp;
268 /* Index of the basis statement S0, if any, in the candidate vector. */
269 cand_idx basis;
271 /* First candidate for which this candidate is a basis, if one exists. */
272 cand_idx dependent;
274 /* Next candidate having the same basis as this one. */
275 cand_idx sibling;
277 /* If this is a conditional candidate, the CAND_PHI candidate
278 that defines the base SSA name B. */
279 cand_idx def_phi;
281 /* Savings that can be expected from eliminating dead code if this
282 candidate is replaced. */
283 int dead_savings;
286 typedef struct slsr_cand_d slsr_cand, *slsr_cand_t;
287 typedef const struct slsr_cand_d *const_slsr_cand_t;
289 /* Pointers to candidates are chained together as part of a mapping
290 from base expressions to the candidates that use them. */
292 struct cand_chain_d
294 /* Base expression for the chain of candidates: often, but not
295 always, an SSA name. */
296 tree base_expr;
298 /* Pointer to a candidate. */
299 slsr_cand_t cand;
301 /* Chain pointer. */
302 struct cand_chain_d *next;
306 typedef struct cand_chain_d cand_chain, *cand_chain_t;
307 typedef const struct cand_chain_d *const_cand_chain_t;
309 /* Information about a unique "increment" associated with candidates
310 having an SSA name for a stride. An increment is the difference
311 between the index of the candidate and the index of its basis,
312 i.e., (i - i') as discussed in the module commentary.
314 When we are not going to generate address arithmetic we treat
315 increments that differ only in sign as the same, allowing sharing
316 of the cost of initializers. The absolute value of the increment
317 is stored in the incr_info. */
319 struct incr_info_d
321 /* The increment that relates a candidate to its basis. */
322 double_int incr;
324 /* How many times the increment occurs in the candidate tree. */
325 unsigned count;
327 /* Cost of replacing candidates using this increment. Negative and
328 zero costs indicate replacement should be performed. */
329 int cost;
331 /* If this increment is profitable but is not -1, 0, or 1, it requires
332 an initializer T_0 = stride * incr to be found or introduced in the
333 nearest common dominator of all candidates. This field holds T_0
334 for subsequent use. */
335 tree initializer;
337 /* If the initializer was found to already exist, this is the block
338 where it was found. */
339 basic_block init_bb;
342 typedef struct incr_info_d incr_info, *incr_info_t;
344 /* Candidates are maintained in a vector. If candidate X dominates
345 candidate Y, then X appears before Y in the vector; but the
346 converse does not necessarily hold. */
347 static vec<slsr_cand_t> cand_vec;
349 enum cost_consts
351 COST_NEUTRAL = 0,
352 COST_INFINITE = 1000
355 enum stride_status
357 UNKNOWN_STRIDE = 0,
358 KNOWN_STRIDE = 1
361 enum phi_adjust_status
363 NOT_PHI_ADJUST = 0,
364 PHI_ADJUST = 1
367 enum count_phis_status
369 DONT_COUNT_PHIS = 0,
370 COUNT_PHIS = 1
373 /* Pointer map embodying a mapping from statements to candidates. */
374 static struct pointer_map_t *stmt_cand_map;
376 /* Obstack for candidates. */
377 static struct obstack cand_obstack;
379 /* Obstack for candidate chains. */
380 static struct obstack chain_obstack;
382 /* An array INCR_VEC of incr_infos is used during analysis of related
383 candidates having an SSA name for a stride. INCR_VEC_LEN describes
384 its current length. MAX_INCR_VEC_LEN is used to avoid costly
385 pathological cases. */
386 static incr_info_t incr_vec;
387 static unsigned incr_vec_len;
388 const int MAX_INCR_VEC_LEN = 16;
390 /* For a chain of candidates with unknown stride, indicates whether or not
391 we must generate pointer arithmetic when replacing statements. */
392 static bool address_arithmetic_p;
394 /* Forward function declarations. */
395 static slsr_cand_t base_cand_from_table (tree);
396 static tree introduce_cast_before_cand (slsr_cand_t, tree, tree);
397 static bool legal_cast_p_1 (tree, tree);
399 /* Produce a pointer to the IDX'th candidate in the candidate vector. */
401 static slsr_cand_t
402 lookup_cand (cand_idx idx)
404 return cand_vec[idx - 1];
407 /* Helper for hashing a candidate chain header. */
409 struct cand_chain_hasher : typed_noop_remove <cand_chain>
411 typedef cand_chain value_type;
412 typedef cand_chain compare_type;
413 static inline hashval_t hash (const value_type *);
414 static inline bool equal (const value_type *, const compare_type *);
417 inline hashval_t
418 cand_chain_hasher::hash (const value_type *p)
420 tree base_expr = p->base_expr;
421 return iterative_hash_expr (base_expr, 0);
424 inline bool
425 cand_chain_hasher::equal (const value_type *chain1, const compare_type *chain2)
427 return operand_equal_p (chain1->base_expr, chain2->base_expr, 0);
430 /* Hash table embodying a mapping from base exprs to chains of candidates. */
431 static hash_table <cand_chain_hasher> base_cand_map;
433 /* Pointer map used by tree_to_aff_combination_expand. */
434 static struct pointer_map_t *name_expansions;
435 /* Pointer map embodying a mapping from bases to alternative bases. */
436 static struct pointer_map_t *alt_base_map;
438 /* Given BASE, use the tree affine combiniation facilities to
439 find the underlying tree expression for BASE, with any
440 immediate offset excluded.
442 N.B. we should eliminate this backtracking with better forward
443 analysis in a future release. */
445 static tree
446 get_alternative_base (tree base)
448 tree *result = (tree *) pointer_map_contains (alt_base_map, base);
450 if (result == NULL)
452 tree expr;
453 aff_tree aff;
455 tree_to_aff_combination_expand (base, TREE_TYPE (base),
456 &aff, &name_expansions);
457 aff.offset = tree_to_double_int (integer_zero_node);
458 expr = aff_combination_to_tree (&aff);
460 result = (tree *) pointer_map_insert (alt_base_map, base);
461 gcc_assert (!*result);
463 if (expr == base)
464 *result = NULL;
465 else
466 *result = expr;
469 return *result;
472 /* Look in the candidate table for a CAND_PHI that defines BASE and
473 return it if found; otherwise return NULL. */
475 static cand_idx
476 find_phi_def (tree base)
478 slsr_cand_t c;
480 if (TREE_CODE (base) != SSA_NAME)
481 return 0;
483 c = base_cand_from_table (base);
485 if (!c || c->kind != CAND_PHI)
486 return 0;
488 return c->cand_num;
491 /* Helper routine for find_basis_for_candidate. May be called twice:
492 once for the candidate's base expr, and optionally again either for
493 the candidate's phi definition or for a CAND_REF's alternative base
494 expression. */
496 static slsr_cand_t
497 find_basis_for_base_expr (slsr_cand_t c, tree base_expr)
499 cand_chain mapping_key;
500 cand_chain_t chain;
501 slsr_cand_t basis = NULL;
503 // Limit potential of N^2 behavior for long candidate chains.
504 int iters = 0;
505 int max_iters = PARAM_VALUE (PARAM_MAX_SLSR_CANDIDATE_SCAN);
507 mapping_key.base_expr = base_expr;
508 chain = base_cand_map.find (&mapping_key);
510 for (; chain && iters < max_iters; chain = chain->next, ++iters)
512 slsr_cand_t one_basis = chain->cand;
514 if (one_basis->kind != c->kind
515 || one_basis->cand_stmt == c->cand_stmt
516 || !operand_equal_p (one_basis->stride, c->stride, 0)
517 || !types_compatible_p (one_basis->cand_type, c->cand_type)
518 || !dominated_by_p (CDI_DOMINATORS,
519 gimple_bb (c->cand_stmt),
520 gimple_bb (one_basis->cand_stmt)))
521 continue;
523 if (!basis || basis->cand_num < one_basis->cand_num)
524 basis = one_basis;
527 return basis;
530 /* Use the base expr from candidate C to look for possible candidates
531 that can serve as a basis for C. Each potential basis must also
532 appear in a block that dominates the candidate statement and have
533 the same stride and type. If more than one possible basis exists,
534 the one with highest index in the vector is chosen; this will be
535 the most immediately dominating basis. */
537 static int
538 find_basis_for_candidate (slsr_cand_t c)
540 slsr_cand_t basis = find_basis_for_base_expr (c, c->base_expr);
542 /* If a candidate doesn't have a basis using its base expression,
543 it may have a basis hidden by one or more intervening phis. */
544 if (!basis && c->def_phi)
546 basic_block basis_bb, phi_bb;
547 slsr_cand_t phi_cand = lookup_cand (c->def_phi);
548 basis = find_basis_for_base_expr (c, phi_cand->base_expr);
550 if (basis)
552 /* A hidden basis must dominate the phi-definition of the
553 candidate's base name. */
554 phi_bb = gimple_bb (phi_cand->cand_stmt);
555 basis_bb = gimple_bb (basis->cand_stmt);
557 if (phi_bb == basis_bb
558 || !dominated_by_p (CDI_DOMINATORS, phi_bb, basis_bb))
560 basis = NULL;
561 c->basis = 0;
564 /* If we found a hidden basis, estimate additional dead-code
565 savings if the phi and its feeding statements can be removed. */
566 if (basis && has_single_use (gimple_phi_result (phi_cand->cand_stmt)))
567 c->dead_savings += phi_cand->dead_savings;
571 if (flag_expensive_optimizations && !basis && c->kind == CAND_REF)
573 tree alt_base_expr = get_alternative_base (c->base_expr);
574 if (alt_base_expr)
575 basis = find_basis_for_base_expr (c, alt_base_expr);
578 if (basis)
580 c->sibling = basis->dependent;
581 basis->dependent = c->cand_num;
582 return basis->cand_num;
585 return 0;
588 /* Record a mapping from BASE to C, indicating that C may potentially serve
589 as a basis using that base expression. BASE may be the same as
590 C->BASE_EXPR; alternatively BASE can be a different tree that share the
591 underlining expression of C->BASE_EXPR. */
593 static void
594 record_potential_basis (slsr_cand_t c, tree base)
596 cand_chain_t node;
597 cand_chain **slot;
599 gcc_assert (base);
601 node = (cand_chain_t) obstack_alloc (&chain_obstack, sizeof (cand_chain));
602 node->base_expr = base;
603 node->cand = c;
604 node->next = NULL;
605 slot = base_cand_map.find_slot (node, INSERT);
607 if (*slot)
609 cand_chain_t head = (cand_chain_t) (*slot);
610 node->next = head->next;
611 head->next = node;
613 else
614 *slot = node;
617 /* Allocate storage for a new candidate and initialize its fields.
618 Attempt to find a basis for the candidate.
620 For CAND_REF, an alternative base may also be recorded and used
621 to find a basis. This helps cases where the expression hidden
622 behind BASE (which is usually an SSA_NAME) has immediate offset,
623 e.g.
625 a2[i][j] = 1;
626 a2[i + 20][j] = 2; */
628 static slsr_cand_t
629 alloc_cand_and_find_basis (enum cand_kind kind, gimple gs, tree base,
630 double_int index, tree stride, tree ctype,
631 unsigned savings)
633 slsr_cand_t c = (slsr_cand_t) obstack_alloc (&cand_obstack,
634 sizeof (slsr_cand));
635 c->cand_stmt = gs;
636 c->base_expr = base;
637 c->stride = stride;
638 c->index = index;
639 c->cand_type = ctype;
640 c->kind = kind;
641 c->cand_num = cand_vec.length () + 1;
642 c->next_interp = 0;
643 c->dependent = 0;
644 c->sibling = 0;
645 c->def_phi = kind == CAND_MULT ? find_phi_def (base) : 0;
646 c->dead_savings = savings;
648 cand_vec.safe_push (c);
650 if (kind == CAND_PHI)
651 c->basis = 0;
652 else
653 c->basis = find_basis_for_candidate (c);
655 record_potential_basis (c, base);
656 if (flag_expensive_optimizations && kind == CAND_REF)
658 tree alt_base = get_alternative_base (base);
659 if (alt_base)
660 record_potential_basis (c, alt_base);
663 return c;
666 /* Determine the target cost of statement GS when compiling according
667 to SPEED. */
669 static int
670 stmt_cost (gimple gs, bool speed)
672 tree lhs, rhs1, rhs2;
673 enum machine_mode lhs_mode;
675 gcc_assert (is_gimple_assign (gs));
676 lhs = gimple_assign_lhs (gs);
677 rhs1 = gimple_assign_rhs1 (gs);
678 lhs_mode = TYPE_MODE (TREE_TYPE (lhs));
680 switch (gimple_assign_rhs_code (gs))
682 case MULT_EXPR:
683 rhs2 = gimple_assign_rhs2 (gs);
685 if (tree_fits_shwi_p (rhs2))
686 return mult_by_coeff_cost (tree_to_shwi (rhs2), lhs_mode, speed);
688 gcc_assert (TREE_CODE (rhs1) != INTEGER_CST);
689 return mul_cost (speed, lhs_mode);
691 case PLUS_EXPR:
692 case POINTER_PLUS_EXPR:
693 case MINUS_EXPR:
694 return add_cost (speed, lhs_mode);
696 case NEGATE_EXPR:
697 return neg_cost (speed, lhs_mode);
699 case NOP_EXPR:
700 return convert_cost (lhs_mode, TYPE_MODE (TREE_TYPE (rhs1)), speed);
702 /* Note that we don't assign costs to copies that in most cases
703 will go away. */
704 default:
708 gcc_unreachable ();
709 return 0;
712 /* Look up the defining statement for BASE_IN and return a pointer
713 to its candidate in the candidate table, if any; otherwise NULL.
714 Only CAND_ADD and CAND_MULT candidates are returned. */
716 static slsr_cand_t
717 base_cand_from_table (tree base_in)
719 slsr_cand_t *result;
721 gimple def = SSA_NAME_DEF_STMT (base_in);
722 if (!def)
723 return (slsr_cand_t) NULL;
725 result = (slsr_cand_t *) pointer_map_contains (stmt_cand_map, def);
727 if (result && (*result)->kind != CAND_REF)
728 return *result;
730 return (slsr_cand_t) NULL;
733 /* Add an entry to the statement-to-candidate mapping. */
735 static void
736 add_cand_for_stmt (gimple gs, slsr_cand_t c)
738 void **slot = pointer_map_insert (stmt_cand_map, gs);
739 gcc_assert (!*slot);
740 *slot = c;
743 /* Given PHI which contains a phi statement, determine whether it
744 satisfies all the requirements of a phi candidate. If so, create
745 a candidate. Note that a CAND_PHI never has a basis itself, but
746 is used to help find a basis for subsequent candidates. */
748 static void
749 slsr_process_phi (gimple phi, bool speed)
751 unsigned i;
752 tree arg0_base = NULL_TREE, base_type;
753 slsr_cand_t c;
754 struct loop *cand_loop = gimple_bb (phi)->loop_father;
755 unsigned savings = 0;
757 /* A CAND_PHI requires each of its arguments to have the same
758 derived base name. (See the module header commentary for a
759 definition of derived base names.) Furthermore, all feeding
760 definitions must be in the same position in the loop hierarchy
761 as PHI. */
763 for (i = 0; i < gimple_phi_num_args (phi); i++)
765 slsr_cand_t arg_cand;
766 tree arg = gimple_phi_arg_def (phi, i);
767 tree derived_base_name = NULL_TREE;
768 gimple arg_stmt = NULL;
769 basic_block arg_bb = NULL;
771 if (TREE_CODE (arg) != SSA_NAME)
772 return;
774 arg_cand = base_cand_from_table (arg);
776 if (arg_cand)
778 while (arg_cand->kind != CAND_ADD && arg_cand->kind != CAND_PHI)
780 if (!arg_cand->next_interp)
781 return;
783 arg_cand = lookup_cand (arg_cand->next_interp);
786 if (!integer_onep (arg_cand->stride))
787 return;
789 derived_base_name = arg_cand->base_expr;
790 arg_stmt = arg_cand->cand_stmt;
791 arg_bb = gimple_bb (arg_stmt);
793 /* Gather potential dead code savings if the phi statement
794 can be removed later on. */
795 if (has_single_use (arg))
797 if (gimple_code (arg_stmt) == GIMPLE_PHI)
798 savings += arg_cand->dead_savings;
799 else
800 savings += stmt_cost (arg_stmt, speed);
803 else
805 derived_base_name = arg;
807 if (SSA_NAME_IS_DEFAULT_DEF (arg))
808 arg_bb = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
809 else
810 gimple_bb (SSA_NAME_DEF_STMT (arg));
813 if (!arg_bb || arg_bb->loop_father != cand_loop)
814 return;
816 if (i == 0)
817 arg0_base = derived_base_name;
818 else if (!operand_equal_p (derived_base_name, arg0_base, 0))
819 return;
822 /* Create the candidate. "alloc_cand_and_find_basis" is named
823 misleadingly for this case, as no basis will be sought for a
824 CAND_PHI. */
825 base_type = TREE_TYPE (arg0_base);
827 c = alloc_cand_and_find_basis (CAND_PHI, phi, arg0_base, double_int_zero,
828 integer_one_node, base_type, savings);
830 /* Add the candidate to the statement-candidate mapping. */
831 add_cand_for_stmt (phi, c);
834 /* Given PBASE which is a pointer to tree, look up the defining
835 statement for it and check whether the candidate is in the
836 form of:
838 X = B + (1 * S), S is integer constant
839 X = B + (i * S), S is integer one
841 If so, set PBASE to the candidate's base_expr and return double
842 int (i * S).
843 Otherwise, just return double int zero. */
845 static double_int
846 backtrace_base_for_ref (tree *pbase)
848 tree base_in = *pbase;
849 slsr_cand_t base_cand;
851 STRIP_NOPS (base_in);
853 /* Strip off widening conversion(s) to handle cases where
854 e.g. 'B' is widened from an 'int' in order to calculate
855 a 64-bit address. */
856 if (CONVERT_EXPR_P (base_in)
857 && legal_cast_p_1 (base_in, TREE_OPERAND (base_in, 0)))
858 base_in = get_unwidened (base_in, NULL_TREE);
860 if (TREE_CODE (base_in) != SSA_NAME)
861 return tree_to_double_int (integer_zero_node);
863 base_cand = base_cand_from_table (base_in);
865 while (base_cand && base_cand->kind != CAND_PHI)
867 if (base_cand->kind == CAND_ADD
868 && base_cand->index.is_one ()
869 && TREE_CODE (base_cand->stride) == INTEGER_CST)
871 /* X = B + (1 * S), S is integer constant. */
872 *pbase = base_cand->base_expr;
873 return tree_to_double_int (base_cand->stride);
875 else if (base_cand->kind == CAND_ADD
876 && TREE_CODE (base_cand->stride) == INTEGER_CST
877 && integer_onep (base_cand->stride))
879 /* X = B + (i * S), S is integer one. */
880 *pbase = base_cand->base_expr;
881 return base_cand->index;
884 if (base_cand->next_interp)
885 base_cand = lookup_cand (base_cand->next_interp);
886 else
887 base_cand = NULL;
890 return tree_to_double_int (integer_zero_node);
893 /* Look for the following pattern:
895 *PBASE: MEM_REF (T1, C1)
897 *POFFSET: MULT_EXPR (T2, C3) [C2 is zero]
899 MULT_EXPR (PLUS_EXPR (T2, C2), C3)
901 MULT_EXPR (MINUS_EXPR (T2, -C2), C3)
903 *PINDEX: C4 * BITS_PER_UNIT
905 If not present, leave the input values unchanged and return FALSE.
906 Otherwise, modify the input values as follows and return TRUE:
908 *PBASE: T1
909 *POFFSET: MULT_EXPR (T2, C3)
910 *PINDEX: C1 + (C2 * C3) + C4
912 When T2 is recorded by a CAND_ADD in the form of (T2' + C5), it
913 will be further restructured to:
915 *PBASE: T1
916 *POFFSET: MULT_EXPR (T2', C3)
917 *PINDEX: C1 + (C2 * C3) + C4 + (C5 * C3) */
919 static bool
920 restructure_reference (tree *pbase, tree *poffset, double_int *pindex,
921 tree *ptype)
923 tree base = *pbase, offset = *poffset;
924 double_int index = *pindex;
925 double_int bpu = double_int::from_uhwi (BITS_PER_UNIT);
926 tree mult_op0, mult_op1, t1, t2, type;
927 double_int c1, c2, c3, c4, c5;
929 if (!base
930 || !offset
931 || TREE_CODE (base) != MEM_REF
932 || TREE_CODE (offset) != MULT_EXPR
933 || TREE_CODE (TREE_OPERAND (offset, 1)) != INTEGER_CST
934 || !index.umod (bpu, FLOOR_MOD_EXPR).is_zero ())
935 return false;
937 t1 = TREE_OPERAND (base, 0);
938 c1 = mem_ref_offset (base);
939 type = TREE_TYPE (TREE_OPERAND (base, 1));
941 mult_op0 = TREE_OPERAND (offset, 0);
942 mult_op1 = TREE_OPERAND (offset, 1);
944 c3 = tree_to_double_int (mult_op1);
946 if (TREE_CODE (mult_op0) == PLUS_EXPR)
948 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
950 t2 = TREE_OPERAND (mult_op0, 0);
951 c2 = tree_to_double_int (TREE_OPERAND (mult_op0, 1));
953 else
954 return false;
956 else if (TREE_CODE (mult_op0) == MINUS_EXPR)
958 if (TREE_CODE (TREE_OPERAND (mult_op0, 1)) == INTEGER_CST)
960 t2 = TREE_OPERAND (mult_op0, 0);
961 c2 = -tree_to_double_int (TREE_OPERAND (mult_op0, 1));
963 else
964 return false;
966 else
968 t2 = mult_op0;
969 c2 = double_int_zero;
972 c4 = index.udiv (bpu, FLOOR_DIV_EXPR);
973 c5 = backtrace_base_for_ref (&t2);
975 *pbase = t1;
976 *poffset = fold_build2 (MULT_EXPR, sizetype, fold_convert (sizetype, t2),
977 double_int_to_tree (sizetype, c3));
978 *pindex = c1 + c2 * c3 + c4 + c5 * c3;
979 *ptype = type;
981 return true;
984 /* Given GS which contains a data reference, create a CAND_REF entry in
985 the candidate table and attempt to find a basis. */
987 static void
988 slsr_process_ref (gimple gs)
990 tree ref_expr, base, offset, type;
991 HOST_WIDE_INT bitsize, bitpos;
992 enum machine_mode mode;
993 int unsignedp, volatilep;
994 double_int index;
995 slsr_cand_t c;
997 if (gimple_vdef (gs))
998 ref_expr = gimple_assign_lhs (gs);
999 else
1000 ref_expr = gimple_assign_rhs1 (gs);
1002 if (!handled_component_p (ref_expr)
1003 || TREE_CODE (ref_expr) == BIT_FIELD_REF
1004 || (TREE_CODE (ref_expr) == COMPONENT_REF
1005 && DECL_BIT_FIELD (TREE_OPERAND (ref_expr, 1))))
1006 return;
1008 base = get_inner_reference (ref_expr, &bitsize, &bitpos, &offset, &mode,
1009 &unsignedp, &volatilep, false);
1010 index = double_int::from_uhwi (bitpos);
1012 if (!restructure_reference (&base, &offset, &index, &type))
1013 return;
1015 c = alloc_cand_and_find_basis (CAND_REF, gs, base, index, offset,
1016 type, 0);
1018 /* Add the candidate to the statement-candidate mapping. */
1019 add_cand_for_stmt (gs, c);
1022 /* Create a candidate entry for a statement GS, where GS multiplies
1023 two SSA names BASE_IN and STRIDE_IN. Propagate any known information
1024 about the two SSA names into the new candidate. Return the new
1025 candidate. */
1027 static slsr_cand_t
1028 create_mul_ssa_cand (gimple gs, tree base_in, tree stride_in, bool speed)
1030 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1031 double_int index;
1032 unsigned savings = 0;
1033 slsr_cand_t c;
1034 slsr_cand_t base_cand = base_cand_from_table (base_in);
1036 /* Look at all interpretations of the base candidate, if necessary,
1037 to find information to propagate into this candidate. */
1038 while (base_cand && !base && base_cand->kind != CAND_PHI)
1041 if (base_cand->kind == CAND_MULT && integer_onep (base_cand->stride))
1043 /* Y = (B + i') * 1
1044 X = Y * Z
1045 ================
1046 X = (B + i') * Z */
1047 base = base_cand->base_expr;
1048 index = base_cand->index;
1049 stride = stride_in;
1050 ctype = base_cand->cand_type;
1051 if (has_single_use (base_in))
1052 savings = (base_cand->dead_savings
1053 + stmt_cost (base_cand->cand_stmt, speed));
1055 else if (base_cand->kind == CAND_ADD
1056 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1058 /* Y = B + (i' * S), S constant
1059 X = Y * Z
1060 ============================
1061 X = B + ((i' * S) * Z) */
1062 base = base_cand->base_expr;
1063 index = base_cand->index * tree_to_double_int (base_cand->stride);
1064 stride = stride_in;
1065 ctype = base_cand->cand_type;
1066 if (has_single_use (base_in))
1067 savings = (base_cand->dead_savings
1068 + stmt_cost (base_cand->cand_stmt, speed));
1071 if (base_cand->next_interp)
1072 base_cand = lookup_cand (base_cand->next_interp);
1073 else
1074 base_cand = NULL;
1077 if (!base)
1079 /* No interpretations had anything useful to propagate, so
1080 produce X = (Y + 0) * Z. */
1081 base = base_in;
1082 index = double_int_zero;
1083 stride = stride_in;
1084 ctype = TREE_TYPE (base_in);
1087 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
1088 ctype, savings);
1089 return c;
1092 /* Create a candidate entry for a statement GS, where GS multiplies
1093 SSA name BASE_IN by constant STRIDE_IN. Propagate any known
1094 information about BASE_IN into the new candidate. Return the new
1095 candidate. */
1097 static slsr_cand_t
1098 create_mul_imm_cand (gimple gs, tree base_in, tree stride_in, bool speed)
1100 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1101 double_int index, temp;
1102 unsigned savings = 0;
1103 slsr_cand_t c;
1104 slsr_cand_t base_cand = base_cand_from_table (base_in);
1106 /* Look at all interpretations of the base candidate, if necessary,
1107 to find information to propagate into this candidate. */
1108 while (base_cand && !base && base_cand->kind != CAND_PHI)
1110 if (base_cand->kind == CAND_MULT
1111 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1113 /* Y = (B + i') * S, S constant
1114 X = Y * c
1115 ============================
1116 X = (B + i') * (S * c) */
1117 base = base_cand->base_expr;
1118 index = base_cand->index;
1119 temp = tree_to_double_int (base_cand->stride)
1120 * tree_to_double_int (stride_in);
1121 stride = double_int_to_tree (TREE_TYPE (stride_in), temp);
1122 ctype = base_cand->cand_type;
1123 if (has_single_use (base_in))
1124 savings = (base_cand->dead_savings
1125 + stmt_cost (base_cand->cand_stmt, speed));
1127 else if (base_cand->kind == CAND_ADD && integer_onep (base_cand->stride))
1129 /* Y = B + (i' * 1)
1130 X = Y * c
1131 ===========================
1132 X = (B + i') * c */
1133 base = base_cand->base_expr;
1134 index = base_cand->index;
1135 stride = stride_in;
1136 ctype = base_cand->cand_type;
1137 if (has_single_use (base_in))
1138 savings = (base_cand->dead_savings
1139 + stmt_cost (base_cand->cand_stmt, speed));
1141 else if (base_cand->kind == CAND_ADD
1142 && base_cand->index.is_one ()
1143 && TREE_CODE (base_cand->stride) == INTEGER_CST)
1145 /* Y = B + (1 * S), S constant
1146 X = Y * c
1147 ===========================
1148 X = (B + S) * c */
1149 base = base_cand->base_expr;
1150 index = tree_to_double_int (base_cand->stride);
1151 stride = stride_in;
1152 ctype = base_cand->cand_type;
1153 if (has_single_use (base_in))
1154 savings = (base_cand->dead_savings
1155 + stmt_cost (base_cand->cand_stmt, speed));
1158 if (base_cand->next_interp)
1159 base_cand = lookup_cand (base_cand->next_interp);
1160 else
1161 base_cand = NULL;
1164 if (!base)
1166 /* No interpretations had anything useful to propagate, so
1167 produce X = (Y + 0) * c. */
1168 base = base_in;
1169 index = double_int_zero;
1170 stride = stride_in;
1171 ctype = TREE_TYPE (base_in);
1174 c = alloc_cand_and_find_basis (CAND_MULT, gs, base, index, stride,
1175 ctype, savings);
1176 return c;
1179 /* Given GS which is a multiply of scalar integers, make an appropriate
1180 entry in the candidate table. If this is a multiply of two SSA names,
1181 create two CAND_MULT interpretations and attempt to find a basis for
1182 each of them. Otherwise, create a single CAND_MULT and attempt to
1183 find a basis. */
1185 static void
1186 slsr_process_mul (gimple gs, tree rhs1, tree rhs2, bool speed)
1188 slsr_cand_t c, c2;
1190 /* If this is a multiply of an SSA name with itself, it is highly
1191 unlikely that we will get a strength reduction opportunity, so
1192 don't record it as a candidate. This simplifies the logic for
1193 finding a basis, so if this is removed that must be considered. */
1194 if (rhs1 == rhs2)
1195 return;
1197 if (TREE_CODE (rhs2) == SSA_NAME)
1199 /* Record an interpretation of this statement in the candidate table
1200 assuming RHS1 is the base expression and RHS2 is the stride. */
1201 c = create_mul_ssa_cand (gs, rhs1, rhs2, speed);
1203 /* Add the first interpretation to the statement-candidate mapping. */
1204 add_cand_for_stmt (gs, c);
1206 /* Record another interpretation of this statement assuming RHS1
1207 is the stride and RHS2 is the base expression. */
1208 c2 = create_mul_ssa_cand (gs, rhs2, rhs1, speed);
1209 c->next_interp = c2->cand_num;
1211 else
1213 /* Record an interpretation for the multiply-immediate. */
1214 c = create_mul_imm_cand (gs, rhs1, rhs2, speed);
1216 /* Add the interpretation to the statement-candidate mapping. */
1217 add_cand_for_stmt (gs, c);
1221 /* Create a candidate entry for a statement GS, where GS adds two
1222 SSA names BASE_IN and ADDEND_IN if SUBTRACT_P is false, and
1223 subtracts ADDEND_IN from BASE_IN otherwise. Propagate any known
1224 information about the two SSA names into the new candidate.
1225 Return the new candidate. */
1227 static slsr_cand_t
1228 create_add_ssa_cand (gimple gs, tree base_in, tree addend_in,
1229 bool subtract_p, bool speed)
1231 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL;
1232 double_int index;
1233 unsigned savings = 0;
1234 slsr_cand_t c;
1235 slsr_cand_t base_cand = base_cand_from_table (base_in);
1236 slsr_cand_t addend_cand = base_cand_from_table (addend_in);
1238 /* The most useful transformation is a multiply-immediate feeding
1239 an add or subtract. Look for that first. */
1240 while (addend_cand && !base && addend_cand->kind != CAND_PHI)
1242 if (addend_cand->kind == CAND_MULT
1243 && addend_cand->index.is_zero ()
1244 && TREE_CODE (addend_cand->stride) == INTEGER_CST)
1246 /* Z = (B + 0) * S, S constant
1247 X = Y +/- Z
1248 ===========================
1249 X = Y + ((+/-1 * S) * B) */
1250 base = base_in;
1251 index = tree_to_double_int (addend_cand->stride);
1252 if (subtract_p)
1253 index = -index;
1254 stride = addend_cand->base_expr;
1255 ctype = TREE_TYPE (base_in);
1256 if (has_single_use (addend_in))
1257 savings = (addend_cand->dead_savings
1258 + stmt_cost (addend_cand->cand_stmt, speed));
1261 if (addend_cand->next_interp)
1262 addend_cand = lookup_cand (addend_cand->next_interp);
1263 else
1264 addend_cand = NULL;
1267 while (base_cand && !base && base_cand->kind != CAND_PHI)
1269 if (base_cand->kind == CAND_ADD
1270 && (base_cand->index.is_zero ()
1271 || operand_equal_p (base_cand->stride,
1272 integer_zero_node, 0)))
1274 /* Y = B + (i' * S), i' * S = 0
1275 X = Y +/- Z
1276 ============================
1277 X = B + (+/-1 * Z) */
1278 base = base_cand->base_expr;
1279 index = subtract_p ? double_int_minus_one : double_int_one;
1280 stride = addend_in;
1281 ctype = base_cand->cand_type;
1282 if (has_single_use (base_in))
1283 savings = (base_cand->dead_savings
1284 + stmt_cost (base_cand->cand_stmt, speed));
1286 else if (subtract_p)
1288 slsr_cand_t subtrahend_cand = base_cand_from_table (addend_in);
1290 while (subtrahend_cand && !base && subtrahend_cand->kind != CAND_PHI)
1292 if (subtrahend_cand->kind == CAND_MULT
1293 && subtrahend_cand->index.is_zero ()
1294 && TREE_CODE (subtrahend_cand->stride) == INTEGER_CST)
1296 /* Z = (B + 0) * S, S constant
1297 X = Y - Z
1298 ===========================
1299 Value: X = Y + ((-1 * S) * B) */
1300 base = base_in;
1301 index = tree_to_double_int (subtrahend_cand->stride);
1302 index = -index;
1303 stride = subtrahend_cand->base_expr;
1304 ctype = TREE_TYPE (base_in);
1305 if (has_single_use (addend_in))
1306 savings = (subtrahend_cand->dead_savings
1307 + stmt_cost (subtrahend_cand->cand_stmt, speed));
1310 if (subtrahend_cand->next_interp)
1311 subtrahend_cand = lookup_cand (subtrahend_cand->next_interp);
1312 else
1313 subtrahend_cand = NULL;
1317 if (base_cand->next_interp)
1318 base_cand = lookup_cand (base_cand->next_interp);
1319 else
1320 base_cand = NULL;
1323 if (!base)
1325 /* No interpretations had anything useful to propagate, so
1326 produce X = Y + (1 * Z). */
1327 base = base_in;
1328 index = subtract_p ? double_int_minus_one : double_int_one;
1329 stride = addend_in;
1330 ctype = TREE_TYPE (base_in);
1333 c = alloc_cand_and_find_basis (CAND_ADD, gs, base, index, stride,
1334 ctype, savings);
1335 return c;
1338 /* Create a candidate entry for a statement GS, where GS adds SSA
1339 name BASE_IN to constant INDEX_IN. Propagate any known information
1340 about BASE_IN into the new candidate. Return the new candidate. */
1342 static slsr_cand_t
1343 create_add_imm_cand (gimple gs, tree base_in, double_int index_in, bool speed)
1345 enum cand_kind kind = CAND_ADD;
1346 tree base = NULL_TREE, stride = NULL_TREE, ctype = NULL_TREE;
1347 double_int index, multiple;
1348 unsigned savings = 0;
1349 slsr_cand_t c;
1350 slsr_cand_t base_cand = base_cand_from_table (base_in);
1352 while (base_cand && !base && base_cand->kind != CAND_PHI)
1354 bool unsigned_p = TYPE_UNSIGNED (TREE_TYPE (base_cand->stride));
1356 if (TREE_CODE (base_cand->stride) == INTEGER_CST
1357 && index_in.multiple_of (tree_to_double_int (base_cand->stride),
1358 unsigned_p, &multiple))
1360 /* Y = (B + i') * S, S constant, c = kS for some integer k
1361 X = Y + c
1362 ============================
1363 X = (B + (i'+ k)) * S
1365 Y = B + (i' * S), S constant, c = kS for some integer k
1366 X = Y + c
1367 ============================
1368 X = (B + (i'+ k)) * S */
1369 kind = base_cand->kind;
1370 base = base_cand->base_expr;
1371 index = base_cand->index + multiple;
1372 stride = base_cand->stride;
1373 ctype = base_cand->cand_type;
1374 if (has_single_use (base_in))
1375 savings = (base_cand->dead_savings
1376 + stmt_cost (base_cand->cand_stmt, speed));
1379 if (base_cand->next_interp)
1380 base_cand = lookup_cand (base_cand->next_interp);
1381 else
1382 base_cand = NULL;
1385 if (!base)
1387 /* No interpretations had anything useful to propagate, so
1388 produce X = Y + (c * 1). */
1389 kind = CAND_ADD;
1390 base = base_in;
1391 index = index_in;
1392 stride = integer_one_node;
1393 ctype = TREE_TYPE (base_in);
1396 c = alloc_cand_and_find_basis (kind, gs, base, index, stride,
1397 ctype, savings);
1398 return c;
1401 /* Given GS which is an add or subtract of scalar integers or pointers,
1402 make at least one appropriate entry in the candidate table. */
1404 static void
1405 slsr_process_add (gimple gs, tree rhs1, tree rhs2, bool speed)
1407 bool subtract_p = gimple_assign_rhs_code (gs) == MINUS_EXPR;
1408 slsr_cand_t c = NULL, c2;
1410 if (TREE_CODE (rhs2) == SSA_NAME)
1412 /* First record an interpretation assuming RHS1 is the base expression
1413 and RHS2 is the stride. But it doesn't make sense for the
1414 stride to be a pointer, so don't record a candidate in that case. */
1415 if (!POINTER_TYPE_P (TREE_TYPE (rhs2)))
1417 c = create_add_ssa_cand (gs, rhs1, rhs2, subtract_p, speed);
1419 /* Add the first interpretation to the statement-candidate
1420 mapping. */
1421 add_cand_for_stmt (gs, c);
1424 /* If the two RHS operands are identical, or this is a subtract,
1425 we're done. */
1426 if (operand_equal_p (rhs1, rhs2, 0) || subtract_p)
1427 return;
1429 /* Otherwise, record another interpretation assuming RHS2 is the
1430 base expression and RHS1 is the stride, again provided that the
1431 stride is not a pointer. */
1432 if (!POINTER_TYPE_P (TREE_TYPE (rhs1)))
1434 c2 = create_add_ssa_cand (gs, rhs2, rhs1, false, speed);
1435 if (c)
1436 c->next_interp = c2->cand_num;
1437 else
1438 add_cand_for_stmt (gs, c2);
1441 else
1443 double_int index;
1445 /* Record an interpretation for the add-immediate. */
1446 index = tree_to_double_int (rhs2);
1447 if (subtract_p)
1448 index = -index;
1450 c = create_add_imm_cand (gs, rhs1, index, speed);
1452 /* Add the interpretation to the statement-candidate mapping. */
1453 add_cand_for_stmt (gs, c);
1457 /* Given GS which is a negate of a scalar integer, make an appropriate
1458 entry in the candidate table. A negate is equivalent to a multiply
1459 by -1. */
1461 static void
1462 slsr_process_neg (gimple gs, tree rhs1, bool speed)
1464 /* Record a CAND_MULT interpretation for the multiply by -1. */
1465 slsr_cand_t c = create_mul_imm_cand (gs, rhs1, integer_minus_one_node, speed);
1467 /* Add the interpretation to the statement-candidate mapping. */
1468 add_cand_for_stmt (gs, c);
1471 /* Help function for legal_cast_p, operating on two trees. Checks
1472 whether it's allowable to cast from RHS to LHS. See legal_cast_p
1473 for more details. */
1475 static bool
1476 legal_cast_p_1 (tree lhs, tree rhs)
1478 tree lhs_type, rhs_type;
1479 unsigned lhs_size, rhs_size;
1480 bool lhs_wraps, rhs_wraps;
1482 lhs_type = TREE_TYPE (lhs);
1483 rhs_type = TREE_TYPE (rhs);
1484 lhs_size = TYPE_PRECISION (lhs_type);
1485 rhs_size = TYPE_PRECISION (rhs_type);
1486 lhs_wraps = TYPE_OVERFLOW_WRAPS (lhs_type);
1487 rhs_wraps = TYPE_OVERFLOW_WRAPS (rhs_type);
1489 if (lhs_size < rhs_size
1490 || (rhs_wraps && !lhs_wraps)
1491 || (rhs_wraps && lhs_wraps && rhs_size != lhs_size))
1492 return false;
1494 return true;
1497 /* Return TRUE if GS is a statement that defines an SSA name from
1498 a conversion and is legal for us to combine with an add and multiply
1499 in the candidate table. For example, suppose we have:
1501 A = B + i;
1502 C = (type) A;
1503 D = C * S;
1505 Without the type-cast, we would create a CAND_MULT for D with base B,
1506 index i, and stride S. We want to record this candidate only if it
1507 is equivalent to apply the type cast following the multiply:
1509 A = B + i;
1510 E = A * S;
1511 D = (type) E;
1513 We will record the type with the candidate for D. This allows us
1514 to use a similar previous candidate as a basis. If we have earlier seen
1516 A' = B + i';
1517 C' = (type) A';
1518 D' = C' * S;
1520 we can replace D with
1522 D = D' + (i - i') * S;
1524 But if moving the type-cast would change semantics, we mustn't do this.
1526 This is legitimate for casts from a non-wrapping integral type to
1527 any integral type of the same or larger size. It is not legitimate
1528 to convert a wrapping type to a non-wrapping type, or to a wrapping
1529 type of a different size. I.e., with a wrapping type, we must
1530 assume that the addition B + i could wrap, in which case performing
1531 the multiply before or after one of the "illegal" type casts will
1532 have different semantics. */
1534 static bool
1535 legal_cast_p (gimple gs, tree rhs)
1537 if (!is_gimple_assign (gs)
1538 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (gs)))
1539 return false;
1541 return legal_cast_p_1 (gimple_assign_lhs (gs), rhs);
1544 /* Given GS which is a cast to a scalar integer type, determine whether
1545 the cast is legal for strength reduction. If so, make at least one
1546 appropriate entry in the candidate table. */
1548 static void
1549 slsr_process_cast (gimple gs, tree rhs1, bool speed)
1551 tree lhs, ctype;
1552 slsr_cand_t base_cand, c, c2;
1553 unsigned savings = 0;
1555 if (!legal_cast_p (gs, rhs1))
1556 return;
1558 lhs = gimple_assign_lhs (gs);
1559 base_cand = base_cand_from_table (rhs1);
1560 ctype = TREE_TYPE (lhs);
1562 if (base_cand && base_cand->kind != CAND_PHI)
1564 while (base_cand)
1566 /* Propagate all data from the base candidate except the type,
1567 which comes from the cast, and the base candidate's cast,
1568 which is no longer applicable. */
1569 if (has_single_use (rhs1))
1570 savings = (base_cand->dead_savings
1571 + stmt_cost (base_cand->cand_stmt, speed));
1573 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1574 base_cand->base_expr,
1575 base_cand->index, base_cand->stride,
1576 ctype, savings);
1577 if (base_cand->next_interp)
1578 base_cand = lookup_cand (base_cand->next_interp);
1579 else
1580 base_cand = NULL;
1583 else
1585 /* If nothing is known about the RHS, create fresh CAND_ADD and
1586 CAND_MULT interpretations:
1588 X = Y + (0 * 1)
1589 X = (Y + 0) * 1
1591 The first of these is somewhat arbitrary, but the choice of
1592 1 for the stride simplifies the logic for propagating casts
1593 into their uses. */
1594 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1, double_int_zero,
1595 integer_one_node, ctype, 0);
1596 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1, double_int_zero,
1597 integer_one_node, ctype, 0);
1598 c->next_interp = c2->cand_num;
1601 /* Add the first (or only) interpretation to the statement-candidate
1602 mapping. */
1603 add_cand_for_stmt (gs, c);
1606 /* Given GS which is a copy of a scalar integer type, make at least one
1607 appropriate entry in the candidate table.
1609 This interface is included for completeness, but is unnecessary
1610 if this pass immediately follows a pass that performs copy
1611 propagation, such as DOM. */
1613 static void
1614 slsr_process_copy (gimple gs, tree rhs1, bool speed)
1616 slsr_cand_t base_cand, c, c2;
1617 unsigned savings = 0;
1619 base_cand = base_cand_from_table (rhs1);
1621 if (base_cand && base_cand->kind != CAND_PHI)
1623 while (base_cand)
1625 /* Propagate all data from the base candidate. */
1626 if (has_single_use (rhs1))
1627 savings = (base_cand->dead_savings
1628 + stmt_cost (base_cand->cand_stmt, speed));
1630 c = alloc_cand_and_find_basis (base_cand->kind, gs,
1631 base_cand->base_expr,
1632 base_cand->index, base_cand->stride,
1633 base_cand->cand_type, savings);
1634 if (base_cand->next_interp)
1635 base_cand = lookup_cand (base_cand->next_interp);
1636 else
1637 base_cand = NULL;
1640 else
1642 /* If nothing is known about the RHS, create fresh CAND_ADD and
1643 CAND_MULT interpretations:
1645 X = Y + (0 * 1)
1646 X = (Y + 0) * 1
1648 The first of these is somewhat arbitrary, but the choice of
1649 1 for the stride simplifies the logic for propagating casts
1650 into their uses. */
1651 c = alloc_cand_and_find_basis (CAND_ADD, gs, rhs1, double_int_zero,
1652 integer_one_node, TREE_TYPE (rhs1), 0);
1653 c2 = alloc_cand_and_find_basis (CAND_MULT, gs, rhs1, double_int_zero,
1654 integer_one_node, TREE_TYPE (rhs1), 0);
1655 c->next_interp = c2->cand_num;
1658 /* Add the first (or only) interpretation to the statement-candidate
1659 mapping. */
1660 add_cand_for_stmt (gs, c);
1663 class find_candidates_dom_walker : public dom_walker
1665 public:
1666 find_candidates_dom_walker (cdi_direction direction)
1667 : dom_walker (direction) {}
1668 virtual void before_dom_children (basic_block);
1671 /* Find strength-reduction candidates in block BB. */
1673 void
1674 find_candidates_dom_walker::before_dom_children (basic_block bb)
1676 bool speed = optimize_bb_for_speed_p (bb);
1677 gimple_stmt_iterator gsi;
1679 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1680 slsr_process_phi (gsi_stmt (gsi), speed);
1682 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1684 gimple gs = gsi_stmt (gsi);
1686 if (gimple_vuse (gs) && gimple_assign_single_p (gs))
1687 slsr_process_ref (gs);
1689 else if (is_gimple_assign (gs)
1690 && SCALAR_INT_MODE_P
1691 (TYPE_MODE (TREE_TYPE (gimple_assign_lhs (gs)))))
1693 tree rhs1 = NULL_TREE, rhs2 = NULL_TREE;
1695 switch (gimple_assign_rhs_code (gs))
1697 case MULT_EXPR:
1698 case PLUS_EXPR:
1699 rhs1 = gimple_assign_rhs1 (gs);
1700 rhs2 = gimple_assign_rhs2 (gs);
1701 /* Should never happen, but currently some buggy situations
1702 in earlier phases put constants in rhs1. */
1703 if (TREE_CODE (rhs1) != SSA_NAME)
1704 continue;
1705 break;
1707 /* Possible future opportunity: rhs1 of a ptr+ can be
1708 an ADDR_EXPR. */
1709 case POINTER_PLUS_EXPR:
1710 case MINUS_EXPR:
1711 rhs2 = gimple_assign_rhs2 (gs);
1712 /* Fall-through. */
1714 case NOP_EXPR:
1715 case MODIFY_EXPR:
1716 case NEGATE_EXPR:
1717 rhs1 = gimple_assign_rhs1 (gs);
1718 if (TREE_CODE (rhs1) != SSA_NAME)
1719 continue;
1720 break;
1722 default:
1726 switch (gimple_assign_rhs_code (gs))
1728 case MULT_EXPR:
1729 slsr_process_mul (gs, rhs1, rhs2, speed);
1730 break;
1732 case PLUS_EXPR:
1733 case POINTER_PLUS_EXPR:
1734 case MINUS_EXPR:
1735 slsr_process_add (gs, rhs1, rhs2, speed);
1736 break;
1738 case NEGATE_EXPR:
1739 slsr_process_neg (gs, rhs1, speed);
1740 break;
1742 case NOP_EXPR:
1743 slsr_process_cast (gs, rhs1, speed);
1744 break;
1746 case MODIFY_EXPR:
1747 slsr_process_copy (gs, rhs1, speed);
1748 break;
1750 default:
1757 /* Dump a candidate for debug. */
1759 static void
1760 dump_candidate (slsr_cand_t c)
1762 fprintf (dump_file, "%3d [%d] ", c->cand_num,
1763 gimple_bb (c->cand_stmt)->index);
1764 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1765 switch (c->kind)
1767 case CAND_MULT:
1768 fputs (" MULT : (", dump_file);
1769 print_generic_expr (dump_file, c->base_expr, 0);
1770 fputs (" + ", dump_file);
1771 dump_double_int (dump_file, c->index, false);
1772 fputs (") * ", dump_file);
1773 print_generic_expr (dump_file, c->stride, 0);
1774 fputs (" : ", dump_file);
1775 break;
1776 case CAND_ADD:
1777 fputs (" ADD : ", dump_file);
1778 print_generic_expr (dump_file, c->base_expr, 0);
1779 fputs (" + (", dump_file);
1780 dump_double_int (dump_file, c->index, false);
1781 fputs (" * ", dump_file);
1782 print_generic_expr (dump_file, c->stride, 0);
1783 fputs (") : ", dump_file);
1784 break;
1785 case CAND_REF:
1786 fputs (" REF : ", dump_file);
1787 print_generic_expr (dump_file, c->base_expr, 0);
1788 fputs (" + (", dump_file);
1789 print_generic_expr (dump_file, c->stride, 0);
1790 fputs (") + ", dump_file);
1791 dump_double_int (dump_file, c->index, false);
1792 fputs (" : ", dump_file);
1793 break;
1794 case CAND_PHI:
1795 fputs (" PHI : ", dump_file);
1796 print_generic_expr (dump_file, c->base_expr, 0);
1797 fputs (" + (unknown * ", dump_file);
1798 print_generic_expr (dump_file, c->stride, 0);
1799 fputs (") : ", dump_file);
1800 break;
1801 default:
1802 gcc_unreachable ();
1804 print_generic_expr (dump_file, c->cand_type, 0);
1805 fprintf (dump_file, "\n basis: %d dependent: %d sibling: %d\n",
1806 c->basis, c->dependent, c->sibling);
1807 fprintf (dump_file, " next-interp: %d dead-savings: %d\n",
1808 c->next_interp, c->dead_savings);
1809 if (c->def_phi)
1810 fprintf (dump_file, " phi: %d\n", c->def_phi);
1811 fputs ("\n", dump_file);
1814 /* Dump the candidate vector for debug. */
1816 static void
1817 dump_cand_vec (void)
1819 unsigned i;
1820 slsr_cand_t c;
1822 fprintf (dump_file, "\nStrength reduction candidate vector:\n\n");
1824 FOR_EACH_VEC_ELT (cand_vec, i, c)
1825 dump_candidate (c);
1828 /* Callback used to dump the candidate chains hash table. */
1831 ssa_base_cand_dump_callback (cand_chain **slot, void *ignored ATTRIBUTE_UNUSED)
1833 const_cand_chain_t chain = *slot;
1834 cand_chain_t p;
1836 print_generic_expr (dump_file, chain->base_expr, 0);
1837 fprintf (dump_file, " -> %d", chain->cand->cand_num);
1839 for (p = chain->next; p; p = p->next)
1840 fprintf (dump_file, " -> %d", p->cand->cand_num);
1842 fputs ("\n", dump_file);
1843 return 1;
1846 /* Dump the candidate chains. */
1848 static void
1849 dump_cand_chains (void)
1851 fprintf (dump_file, "\nStrength reduction candidate chains:\n\n");
1852 base_cand_map.traverse_noresize <void *, ssa_base_cand_dump_callback> (NULL);
1853 fputs ("\n", dump_file);
1856 /* Dump the increment vector for debug. */
1858 static void
1859 dump_incr_vec (void)
1861 if (dump_file && (dump_flags & TDF_DETAILS))
1863 unsigned i;
1865 fprintf (dump_file, "\nIncrement vector:\n\n");
1867 for (i = 0; i < incr_vec_len; i++)
1869 fprintf (dump_file, "%3d increment: ", i);
1870 dump_double_int (dump_file, incr_vec[i].incr, false);
1871 fprintf (dump_file, "\n count: %d", incr_vec[i].count);
1872 fprintf (dump_file, "\n cost: %d", incr_vec[i].cost);
1873 fputs ("\n initializer: ", dump_file);
1874 print_generic_expr (dump_file, incr_vec[i].initializer, 0);
1875 fputs ("\n\n", dump_file);
1880 /* Replace *EXPR in candidate C with an equivalent strength-reduced
1881 data reference. */
1883 static void
1884 replace_ref (tree *expr, slsr_cand_t c)
1886 tree add_expr, mem_ref, acc_type = TREE_TYPE (*expr);
1887 unsigned HOST_WIDE_INT misalign;
1888 unsigned align;
1890 /* Ensure the memory reference carries the minimum alignment
1891 requirement for the data type. See PR58041. */
1892 get_object_alignment_1 (*expr, &align, &misalign);
1893 if (misalign != 0)
1894 align = (misalign & -misalign);
1895 if (align < TYPE_ALIGN (acc_type))
1896 acc_type = build_aligned_type (acc_type, align);
1898 add_expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (c->base_expr),
1899 c->base_expr, c->stride);
1900 mem_ref = fold_build2 (MEM_REF, acc_type, add_expr,
1901 double_int_to_tree (c->cand_type, c->index));
1903 /* Gimplify the base addressing expression for the new MEM_REF tree. */
1904 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
1905 TREE_OPERAND (mem_ref, 0)
1906 = force_gimple_operand_gsi (&gsi, TREE_OPERAND (mem_ref, 0),
1907 /*simple_p=*/true, NULL,
1908 /*before=*/true, GSI_SAME_STMT);
1909 copy_ref_info (mem_ref, *expr);
1910 *expr = mem_ref;
1911 update_stmt (c->cand_stmt);
1914 /* Replace CAND_REF candidate C, each sibling of candidate C, and each
1915 dependent of candidate C with an equivalent strength-reduced data
1916 reference. */
1918 static void
1919 replace_refs (slsr_cand_t c)
1921 if (dump_file && (dump_flags & TDF_DETAILS))
1923 fputs ("Replacing reference: ", dump_file);
1924 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1927 if (gimple_vdef (c->cand_stmt))
1929 tree *lhs = gimple_assign_lhs_ptr (c->cand_stmt);
1930 replace_ref (lhs, c);
1932 else
1934 tree *rhs = gimple_assign_rhs1_ptr (c->cand_stmt);
1935 replace_ref (rhs, c);
1938 if (dump_file && (dump_flags & TDF_DETAILS))
1940 fputs ("With: ", dump_file);
1941 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
1942 fputs ("\n", dump_file);
1945 if (c->sibling)
1946 replace_refs (lookup_cand (c->sibling));
1948 if (c->dependent)
1949 replace_refs (lookup_cand (c->dependent));
1952 /* Return TRUE if candidate C is dependent upon a PHI. */
1954 static bool
1955 phi_dependent_cand_p (slsr_cand_t c)
1957 /* A candidate is not necessarily dependent upon a PHI just because
1958 it has a phi definition for its base name. It may have a basis
1959 that relies upon the same phi definition, in which case the PHI
1960 is irrelevant to this candidate. */
1961 return (c->def_phi
1962 && c->basis
1963 && lookup_cand (c->basis)->def_phi != c->def_phi);
1966 /* Calculate the increment required for candidate C relative to
1967 its basis. */
1969 static double_int
1970 cand_increment (slsr_cand_t c)
1972 slsr_cand_t basis;
1974 /* If the candidate doesn't have a basis, just return its own
1975 index. This is useful in record_increments to help us find
1976 an existing initializer. Also, if the candidate's basis is
1977 hidden by a phi, then its own index will be the increment
1978 from the newly introduced phi basis. */
1979 if (!c->basis || phi_dependent_cand_p (c))
1980 return c->index;
1982 basis = lookup_cand (c->basis);
1983 gcc_assert (operand_equal_p (c->base_expr, basis->base_expr, 0));
1984 return c->index - basis->index;
1987 /* Calculate the increment required for candidate C relative to
1988 its basis. If we aren't going to generate pointer arithmetic
1989 for this candidate, return the absolute value of that increment
1990 instead. */
1992 static inline double_int
1993 cand_abs_increment (slsr_cand_t c)
1995 double_int increment = cand_increment (c);
1997 if (!address_arithmetic_p && increment.is_negative ())
1998 increment = -increment;
2000 return increment;
2003 /* Return TRUE iff candidate C has already been replaced under
2004 another interpretation. */
2006 static inline bool
2007 cand_already_replaced (slsr_cand_t c)
2009 return (gimple_bb (c->cand_stmt) == 0);
2012 /* Common logic used by replace_unconditional_candidate and
2013 replace_conditional_candidate. */
2015 static void
2016 replace_mult_candidate (slsr_cand_t c, tree basis_name, double_int bump)
2018 tree target_type = TREE_TYPE (gimple_assign_lhs (c->cand_stmt));
2019 enum tree_code cand_code = gimple_assign_rhs_code (c->cand_stmt);
2021 /* It is highly unlikely, but possible, that the resulting
2022 bump doesn't fit in a HWI. Abandon the replacement
2023 in this case. This does not affect siblings or dependents
2024 of C. Restriction to signed HWI is conservative for unsigned
2025 types but allows for safe negation without twisted logic. */
2026 if (bump.fits_shwi ()
2027 && bump.to_shwi () != HOST_WIDE_INT_MIN
2028 /* It is not useful to replace casts, copies, or adds of
2029 an SSA name and a constant. */
2030 && cand_code != MODIFY_EXPR
2031 && cand_code != NOP_EXPR
2032 && cand_code != PLUS_EXPR
2033 && cand_code != POINTER_PLUS_EXPR
2034 && cand_code != MINUS_EXPR)
2036 enum tree_code code = PLUS_EXPR;
2037 tree bump_tree;
2038 gimple stmt_to_print = NULL;
2040 /* If the basis name and the candidate's LHS have incompatible
2041 types, introduce a cast. */
2042 if (!useless_type_conversion_p (target_type, TREE_TYPE (basis_name)))
2043 basis_name = introduce_cast_before_cand (c, target_type, basis_name);
2044 if (bump.is_negative ())
2046 code = MINUS_EXPR;
2047 bump = -bump;
2050 bump_tree = double_int_to_tree (target_type, bump);
2052 if (dump_file && (dump_flags & TDF_DETAILS))
2054 fputs ("Replacing: ", dump_file);
2055 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
2058 if (bump.is_zero ())
2060 tree lhs = gimple_assign_lhs (c->cand_stmt);
2061 gimple copy_stmt = gimple_build_assign (lhs, basis_name);
2062 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2063 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
2064 gsi_replace (&gsi, copy_stmt, false);
2065 c->cand_stmt = copy_stmt;
2066 if (dump_file && (dump_flags & TDF_DETAILS))
2067 stmt_to_print = copy_stmt;
2069 else
2071 tree rhs1, rhs2;
2072 if (cand_code != NEGATE_EXPR) {
2073 rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2074 rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2076 if (cand_code != NEGATE_EXPR
2077 && ((operand_equal_p (rhs1, basis_name, 0)
2078 && operand_equal_p (rhs2, bump_tree, 0))
2079 || (operand_equal_p (rhs1, bump_tree, 0)
2080 && operand_equal_p (rhs2, basis_name, 0))))
2082 if (dump_file && (dump_flags & TDF_DETAILS))
2084 fputs ("(duplicate, not actually replacing)", dump_file);
2085 stmt_to_print = c->cand_stmt;
2088 else
2090 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
2091 gimple_assign_set_rhs_with_ops (&gsi, code,
2092 basis_name, bump_tree);
2093 update_stmt (gsi_stmt (gsi));
2094 c->cand_stmt = gsi_stmt (gsi);
2095 if (dump_file && (dump_flags & TDF_DETAILS))
2096 stmt_to_print = gsi_stmt (gsi);
2100 if (dump_file && (dump_flags & TDF_DETAILS))
2102 fputs ("With: ", dump_file);
2103 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
2104 fputs ("\n", dump_file);
2109 /* Replace candidate C with an add or subtract. Note that we only
2110 operate on CAND_MULTs with known strides, so we will never generate
2111 a POINTER_PLUS_EXPR. Each candidate X = (B + i) * S is replaced by
2112 X = Y + ((i - i') * S), as described in the module commentary. The
2113 folded value ((i - i') * S) is referred to here as the "bump." */
2115 static void
2116 replace_unconditional_candidate (slsr_cand_t c)
2118 slsr_cand_t basis;
2119 double_int stride, bump;
2121 if (cand_already_replaced (c))
2122 return;
2124 basis = lookup_cand (c->basis);
2125 stride = tree_to_double_int (c->stride);
2126 bump = cand_increment (c) * stride;
2128 replace_mult_candidate (c, gimple_assign_lhs (basis->cand_stmt), bump);
2131 /* Return the index in the increment vector of the given INCREMENT,
2132 or -1 if not found. The latter can occur if more than
2133 MAX_INCR_VEC_LEN increments have been found. */
2135 static inline int
2136 incr_vec_index (double_int increment)
2138 unsigned i;
2140 for (i = 0; i < incr_vec_len && increment != incr_vec[i].incr; i++)
2143 if (i < incr_vec_len)
2144 return i;
2145 else
2146 return -1;
2149 /* Create a new statement along edge E to add BASIS_NAME to the product
2150 of INCREMENT and the stride of candidate C. Create and return a new
2151 SSA name from *VAR to be used as the LHS of the new statement.
2152 KNOWN_STRIDE is true iff C's stride is a constant. */
2154 static tree
2155 create_add_on_incoming_edge (slsr_cand_t c, tree basis_name,
2156 double_int increment, edge e, location_t loc,
2157 bool known_stride)
2159 basic_block insert_bb;
2160 gimple_stmt_iterator gsi;
2161 tree lhs, basis_type;
2162 gimple new_stmt;
2164 /* If the add candidate along this incoming edge has the same
2165 index as C's hidden basis, the hidden basis represents this
2166 edge correctly. */
2167 if (increment.is_zero ())
2168 return basis_name;
2170 basis_type = TREE_TYPE (basis_name);
2171 lhs = make_temp_ssa_name (basis_type, NULL, "slsr");
2173 if (known_stride)
2175 tree bump_tree;
2176 enum tree_code code = PLUS_EXPR;
2177 double_int bump = increment * tree_to_double_int (c->stride);
2178 if (bump.is_negative ())
2180 code = MINUS_EXPR;
2181 bump = -bump;
2184 bump_tree = double_int_to_tree (basis_type, bump);
2185 new_stmt = gimple_build_assign_with_ops (code, lhs, basis_name,
2186 bump_tree);
2188 else
2190 int i;
2191 bool negate_incr = (!address_arithmetic_p && increment.is_negative ());
2192 i = incr_vec_index (negate_incr ? -increment : increment);
2193 gcc_assert (i >= 0);
2195 if (incr_vec[i].initializer)
2197 enum tree_code code = negate_incr ? MINUS_EXPR : PLUS_EXPR;
2198 new_stmt = gimple_build_assign_with_ops (code, lhs, basis_name,
2199 incr_vec[i].initializer);
2201 else if (increment.is_one ())
2202 new_stmt = gimple_build_assign_with_ops (PLUS_EXPR, lhs, basis_name,
2203 c->stride);
2204 else if (increment.is_minus_one ())
2205 new_stmt = gimple_build_assign_with_ops (MINUS_EXPR, lhs, basis_name,
2206 c->stride);
2207 else
2208 gcc_unreachable ();
2211 insert_bb = single_succ_p (e->src) ? e->src : split_edge (e);
2212 gsi = gsi_last_bb (insert_bb);
2214 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
2215 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
2216 else
2217 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
2219 gimple_set_location (new_stmt, loc);
2221 if (dump_file && (dump_flags & TDF_DETAILS))
2223 fprintf (dump_file, "Inserting in block %d: ", insert_bb->index);
2224 print_gimple_stmt (dump_file, new_stmt, 0, 0);
2227 return lhs;
2230 /* Given a candidate C with BASIS_NAME being the LHS of C's basis which
2231 is hidden by the phi node FROM_PHI, create a new phi node in the same
2232 block as FROM_PHI. The new phi is suitable for use as a basis by C,
2233 with its phi arguments representing conditional adjustments to the
2234 hidden basis along conditional incoming paths. Those adjustments are
2235 made by creating add statements (and sometimes recursively creating
2236 phis) along those incoming paths. LOC is the location to attach to
2237 the introduced statements. KNOWN_STRIDE is true iff C's stride is a
2238 constant. */
2240 static tree
2241 create_phi_basis (slsr_cand_t c, gimple from_phi, tree basis_name,
2242 location_t loc, bool known_stride)
2244 int i;
2245 tree name, phi_arg;
2246 gimple phi;
2247 vec<tree> phi_args;
2248 slsr_cand_t basis = lookup_cand (c->basis);
2249 int nargs = gimple_phi_num_args (from_phi);
2250 basic_block phi_bb = gimple_bb (from_phi);
2251 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (from_phi));
2252 phi_args.create (nargs);
2254 /* Process each argument of the existing phi that represents
2255 conditionally-executed add candidates. */
2256 for (i = 0; i < nargs; i++)
2258 edge e = (*phi_bb->preds)[i];
2259 tree arg = gimple_phi_arg_def (from_phi, i);
2260 tree feeding_def;
2262 /* If the phi argument is the base name of the CAND_PHI, then
2263 this incoming arc should use the hidden basis. */
2264 if (operand_equal_p (arg, phi_cand->base_expr, 0))
2265 if (basis->index.is_zero ())
2266 feeding_def = gimple_assign_lhs (basis->cand_stmt);
2267 else
2269 double_int incr = -basis->index;
2270 feeding_def = create_add_on_incoming_edge (c, basis_name, incr,
2271 e, loc, known_stride);
2273 else
2275 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2277 /* If there is another phi along this incoming edge, we must
2278 process it in the same fashion to ensure that all basis
2279 adjustments are made along its incoming edges. */
2280 if (gimple_code (arg_def) == GIMPLE_PHI)
2281 feeding_def = create_phi_basis (c, arg_def, basis_name,
2282 loc, known_stride);
2283 else
2285 slsr_cand_t arg_cand = base_cand_from_table (arg);
2286 double_int diff = arg_cand->index - basis->index;
2287 feeding_def = create_add_on_incoming_edge (c, basis_name, diff,
2288 e, loc, known_stride);
2292 /* Because of recursion, we need to save the arguments in a vector
2293 so we can create the PHI statement all at once. Otherwise the
2294 storage for the half-created PHI can be reclaimed. */
2295 phi_args.safe_push (feeding_def);
2298 /* Create the new phi basis. */
2299 name = make_temp_ssa_name (TREE_TYPE (basis_name), NULL, "slsr");
2300 phi = create_phi_node (name, phi_bb);
2301 SSA_NAME_DEF_STMT (name) = phi;
2303 FOR_EACH_VEC_ELT (phi_args, i, phi_arg)
2305 edge e = (*phi_bb->preds)[i];
2306 add_phi_arg (phi, phi_arg, e, loc);
2309 update_stmt (phi);
2311 if (dump_file && (dump_flags & TDF_DETAILS))
2313 fputs ("Introducing new phi basis: ", dump_file);
2314 print_gimple_stmt (dump_file, phi, 0, 0);
2317 return name;
2320 /* Given a candidate C whose basis is hidden by at least one intervening
2321 phi, introduce a matching number of new phis to represent its basis
2322 adjusted by conditional increments along possible incoming paths. Then
2323 replace C as though it were an unconditional candidate, using the new
2324 basis. */
2326 static void
2327 replace_conditional_candidate (slsr_cand_t c)
2329 tree basis_name, name;
2330 slsr_cand_t basis;
2331 location_t loc;
2332 double_int stride, bump;
2334 /* Look up the LHS SSA name from C's basis. This will be the
2335 RHS1 of the adds we will introduce to create new phi arguments. */
2336 basis = lookup_cand (c->basis);
2337 basis_name = gimple_assign_lhs (basis->cand_stmt);
2339 /* Create a new phi statement which will represent C's true basis
2340 after the transformation is complete. */
2341 loc = gimple_location (c->cand_stmt);
2342 name = create_phi_basis (c, lookup_cand (c->def_phi)->cand_stmt,
2343 basis_name, loc, KNOWN_STRIDE);
2344 /* Replace C with an add of the new basis phi and a constant. */
2345 stride = tree_to_double_int (c->stride);
2346 bump = c->index * stride;
2348 replace_mult_candidate (c, name, bump);
2351 /* Compute the expected costs of inserting basis adjustments for
2352 candidate C with phi-definition PHI. The cost of inserting
2353 one adjustment is given by ONE_ADD_COST. If PHI has arguments
2354 which are themselves phi results, recursively calculate costs
2355 for those phis as well. */
2357 static int
2358 phi_add_costs (gimple phi, slsr_cand_t c, int one_add_cost)
2360 unsigned i;
2361 int cost = 0;
2362 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2364 /* If we work our way back to a phi that isn't dominated by the hidden
2365 basis, this isn't a candidate for replacement. Indicate this by
2366 returning an unreasonably high cost. It's not easy to detect
2367 these situations when determining the basis, so we defer the
2368 decision until now. */
2369 basic_block phi_bb = gimple_bb (phi);
2370 slsr_cand_t basis = lookup_cand (c->basis);
2371 basic_block basis_bb = gimple_bb (basis->cand_stmt);
2373 if (phi_bb == basis_bb || !dominated_by_p (CDI_DOMINATORS, phi_bb, basis_bb))
2374 return COST_INFINITE;
2376 for (i = 0; i < gimple_phi_num_args (phi); i++)
2378 tree arg = gimple_phi_arg_def (phi, i);
2380 if (arg != phi_cand->base_expr)
2382 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2384 if (gimple_code (arg_def) == GIMPLE_PHI)
2385 cost += phi_add_costs (arg_def, c, one_add_cost);
2386 else
2388 slsr_cand_t arg_cand = base_cand_from_table (arg);
2390 if (arg_cand->index != c->index)
2391 cost += one_add_cost;
2396 return cost;
2399 /* For candidate C, each sibling of candidate C, and each dependent of
2400 candidate C, determine whether the candidate is dependent upon a
2401 phi that hides its basis. If not, replace the candidate unconditionally.
2402 Otherwise, determine whether the cost of introducing compensation code
2403 for the candidate is offset by the gains from strength reduction. If
2404 so, replace the candidate and introduce the compensation code. */
2406 static void
2407 replace_uncond_cands_and_profitable_phis (slsr_cand_t c)
2409 if (phi_dependent_cand_p (c))
2411 if (c->kind == CAND_MULT)
2413 /* A candidate dependent upon a phi will replace a multiply by
2414 a constant with an add, and will insert at most one add for
2415 each phi argument. Add these costs with the potential dead-code
2416 savings to determine profitability. */
2417 bool speed = optimize_bb_for_speed_p (gimple_bb (c->cand_stmt));
2418 int mult_savings = stmt_cost (c->cand_stmt, speed);
2419 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2420 tree phi_result = gimple_phi_result (phi);
2421 int one_add_cost = add_cost (speed,
2422 TYPE_MODE (TREE_TYPE (phi_result)));
2423 int add_costs = one_add_cost + phi_add_costs (phi, c, one_add_cost);
2424 int cost = add_costs - mult_savings - c->dead_savings;
2426 if (dump_file && (dump_flags & TDF_DETAILS))
2428 fprintf (dump_file, " Conditional candidate %d:\n", c->cand_num);
2429 fprintf (dump_file, " add_costs = %d\n", add_costs);
2430 fprintf (dump_file, " mult_savings = %d\n", mult_savings);
2431 fprintf (dump_file, " dead_savings = %d\n", c->dead_savings);
2432 fprintf (dump_file, " cost = %d\n", cost);
2433 if (cost <= COST_NEUTRAL)
2434 fputs (" Replacing...\n", dump_file);
2435 else
2436 fputs (" Not replaced.\n", dump_file);
2439 if (cost <= COST_NEUTRAL)
2440 replace_conditional_candidate (c);
2443 else
2444 replace_unconditional_candidate (c);
2446 if (c->sibling)
2447 replace_uncond_cands_and_profitable_phis (lookup_cand (c->sibling));
2449 if (c->dependent)
2450 replace_uncond_cands_and_profitable_phis (lookup_cand (c->dependent));
2453 /* Count the number of candidates in the tree rooted at C that have
2454 not already been replaced under other interpretations. */
2456 static int
2457 count_candidates (slsr_cand_t c)
2459 unsigned count = cand_already_replaced (c) ? 0 : 1;
2461 if (c->sibling)
2462 count += count_candidates (lookup_cand (c->sibling));
2464 if (c->dependent)
2465 count += count_candidates (lookup_cand (c->dependent));
2467 return count;
2470 /* Increase the count of INCREMENT by one in the increment vector.
2471 INCREMENT is associated with candidate C. If INCREMENT is to be
2472 conditionally executed as part of a conditional candidate replacement,
2473 IS_PHI_ADJUST is true, otherwise false. If an initializer
2474 T_0 = stride * I is provided by a candidate that dominates all
2475 candidates with the same increment, also record T_0 for subsequent use. */
2477 static void
2478 record_increment (slsr_cand_t c, double_int increment, bool is_phi_adjust)
2480 bool found = false;
2481 unsigned i;
2483 /* Treat increments that differ only in sign as identical so as to
2484 share initializers, unless we are generating pointer arithmetic. */
2485 if (!address_arithmetic_p && increment.is_negative ())
2486 increment = -increment;
2488 for (i = 0; i < incr_vec_len; i++)
2490 if (incr_vec[i].incr == increment)
2492 incr_vec[i].count++;
2493 found = true;
2495 /* If we previously recorded an initializer that doesn't
2496 dominate this candidate, it's not going to be useful to
2497 us after all. */
2498 if (incr_vec[i].initializer
2499 && !dominated_by_p (CDI_DOMINATORS,
2500 gimple_bb (c->cand_stmt),
2501 incr_vec[i].init_bb))
2503 incr_vec[i].initializer = NULL_TREE;
2504 incr_vec[i].init_bb = NULL;
2507 break;
2511 if (!found && incr_vec_len < MAX_INCR_VEC_LEN - 1)
2513 /* The first time we see an increment, create the entry for it.
2514 If this is the root candidate which doesn't have a basis, set
2515 the count to zero. We're only processing it so it can possibly
2516 provide an initializer for other candidates. */
2517 incr_vec[incr_vec_len].incr = increment;
2518 incr_vec[incr_vec_len].count = c->basis || is_phi_adjust ? 1 : 0;
2519 incr_vec[incr_vec_len].cost = COST_INFINITE;
2521 /* Optimistically record the first occurrence of this increment
2522 as providing an initializer (if it does); we will revise this
2523 opinion later if it doesn't dominate all other occurrences.
2524 Exception: increments of -1, 0, 1 never need initializers;
2525 and phi adjustments don't ever provide initializers. */
2526 if (c->kind == CAND_ADD
2527 && !is_phi_adjust
2528 && c->index == increment
2529 && (increment.sgt (double_int_one)
2530 || increment.slt (double_int_minus_one))
2531 && (gimple_assign_rhs_code (c->cand_stmt) == PLUS_EXPR
2532 || gimple_assign_rhs_code (c->cand_stmt) == POINTER_PLUS_EXPR))
2534 tree t0 = NULL_TREE;
2535 tree rhs1 = gimple_assign_rhs1 (c->cand_stmt);
2536 tree rhs2 = gimple_assign_rhs2 (c->cand_stmt);
2537 if (operand_equal_p (rhs1, c->base_expr, 0))
2538 t0 = rhs2;
2539 else if (operand_equal_p (rhs2, c->base_expr, 0))
2540 t0 = rhs1;
2541 if (t0
2542 && SSA_NAME_DEF_STMT (t0)
2543 && gimple_bb (SSA_NAME_DEF_STMT (t0)))
2545 incr_vec[incr_vec_len].initializer = t0;
2546 incr_vec[incr_vec_len++].init_bb
2547 = gimple_bb (SSA_NAME_DEF_STMT (t0));
2549 else
2551 incr_vec[incr_vec_len].initializer = NULL_TREE;
2552 incr_vec[incr_vec_len++].init_bb = NULL;
2555 else
2557 incr_vec[incr_vec_len].initializer = NULL_TREE;
2558 incr_vec[incr_vec_len++].init_bb = NULL;
2563 /* Given phi statement PHI that hides a candidate from its BASIS, find
2564 the increments along each incoming arc (recursively handling additional
2565 phis that may be present) and record them. These increments are the
2566 difference in index between the index-adjusting statements and the
2567 index of the basis. */
2569 static void
2570 record_phi_increments (slsr_cand_t basis, gimple phi)
2572 unsigned i;
2573 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2575 for (i = 0; i < gimple_phi_num_args (phi); i++)
2577 tree arg = gimple_phi_arg_def (phi, i);
2579 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2581 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2583 if (gimple_code (arg_def) == GIMPLE_PHI)
2584 record_phi_increments (basis, arg_def);
2585 else
2587 slsr_cand_t arg_cand = base_cand_from_table (arg);
2588 double_int diff = arg_cand->index - basis->index;
2589 record_increment (arg_cand, diff, PHI_ADJUST);
2595 /* Determine how many times each unique increment occurs in the set
2596 of candidates rooted at C's parent, recording the data in the
2597 increment vector. For each unique increment I, if an initializer
2598 T_0 = stride * I is provided by a candidate that dominates all
2599 candidates with the same increment, also record T_0 for subsequent
2600 use. */
2602 static void
2603 record_increments (slsr_cand_t c)
2605 if (!cand_already_replaced (c))
2607 if (!phi_dependent_cand_p (c))
2608 record_increment (c, cand_increment (c), NOT_PHI_ADJUST);
2609 else
2611 /* A candidate with a basis hidden by a phi will have one
2612 increment for its relationship to the index represented by
2613 the phi, and potentially additional increments along each
2614 incoming edge. For the root of the dependency tree (which
2615 has no basis), process just the initial index in case it has
2616 an initializer that can be used by subsequent candidates. */
2617 record_increment (c, c->index, NOT_PHI_ADJUST);
2619 if (c->basis)
2620 record_phi_increments (lookup_cand (c->basis),
2621 lookup_cand (c->def_phi)->cand_stmt);
2625 if (c->sibling)
2626 record_increments (lookup_cand (c->sibling));
2628 if (c->dependent)
2629 record_increments (lookup_cand (c->dependent));
2632 /* Add up and return the costs of introducing add statements that
2633 require the increment INCR on behalf of candidate C and phi
2634 statement PHI. Accumulate into *SAVINGS the potential savings
2635 from removing existing statements that feed PHI and have no other
2636 uses. */
2638 static int
2639 phi_incr_cost (slsr_cand_t c, double_int incr, gimple phi, int *savings)
2641 unsigned i;
2642 int cost = 0;
2643 slsr_cand_t basis = lookup_cand (c->basis);
2644 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2646 for (i = 0; i < gimple_phi_num_args (phi); i++)
2648 tree arg = gimple_phi_arg_def (phi, i);
2650 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2652 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2654 if (gimple_code (arg_def) == GIMPLE_PHI)
2656 int feeding_savings = 0;
2657 cost += phi_incr_cost (c, incr, arg_def, &feeding_savings);
2658 if (has_single_use (gimple_phi_result (arg_def)))
2659 *savings += feeding_savings;
2661 else
2663 slsr_cand_t arg_cand = base_cand_from_table (arg);
2664 double_int diff = arg_cand->index - basis->index;
2666 if (incr == diff)
2668 tree basis_lhs = gimple_assign_lhs (basis->cand_stmt);
2669 tree lhs = gimple_assign_lhs (arg_cand->cand_stmt);
2670 cost += add_cost (true, TYPE_MODE (TREE_TYPE (basis_lhs)));
2671 if (has_single_use (lhs))
2672 *savings += stmt_cost (arg_cand->cand_stmt, true);
2678 return cost;
2681 /* Return the first candidate in the tree rooted at C that has not
2682 already been replaced, favoring siblings over dependents. */
2684 static slsr_cand_t
2685 unreplaced_cand_in_tree (slsr_cand_t c)
2687 if (!cand_already_replaced (c))
2688 return c;
2690 if (c->sibling)
2692 slsr_cand_t sib = unreplaced_cand_in_tree (lookup_cand (c->sibling));
2693 if (sib)
2694 return sib;
2697 if (c->dependent)
2699 slsr_cand_t dep = unreplaced_cand_in_tree (lookup_cand (c->dependent));
2700 if (dep)
2701 return dep;
2704 return NULL;
2707 /* Return TRUE if the candidates in the tree rooted at C should be
2708 optimized for speed, else FALSE. We estimate this based on the block
2709 containing the most dominant candidate in the tree that has not yet
2710 been replaced. */
2712 static bool
2713 optimize_cands_for_speed_p (slsr_cand_t c)
2715 slsr_cand_t c2 = unreplaced_cand_in_tree (c);
2716 gcc_assert (c2);
2717 return optimize_bb_for_speed_p (gimple_bb (c2->cand_stmt));
2720 /* Add COST_IN to the lowest cost of any dependent path starting at
2721 candidate C or any of its siblings, counting only candidates along
2722 such paths with increment INCR. Assume that replacing a candidate
2723 reduces cost by REPL_SAVINGS. Also account for savings from any
2724 statements that would go dead. If COUNT_PHIS is true, include
2725 costs of introducing feeding statements for conditional candidates. */
2727 static int
2728 lowest_cost_path (int cost_in, int repl_savings, slsr_cand_t c,
2729 double_int incr, bool count_phis)
2731 int local_cost, sib_cost, savings = 0;
2732 double_int cand_incr = cand_abs_increment (c);
2734 if (cand_already_replaced (c))
2735 local_cost = cost_in;
2736 else if (incr == cand_incr)
2737 local_cost = cost_in - repl_savings - c->dead_savings;
2738 else
2739 local_cost = cost_in - c->dead_savings;
2741 if (count_phis
2742 && phi_dependent_cand_p (c)
2743 && !cand_already_replaced (c))
2745 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2746 local_cost += phi_incr_cost (c, incr, phi, &savings);
2748 if (has_single_use (gimple_phi_result (phi)))
2749 local_cost -= savings;
2752 if (c->dependent)
2753 local_cost = lowest_cost_path (local_cost, repl_savings,
2754 lookup_cand (c->dependent), incr,
2755 count_phis);
2757 if (c->sibling)
2759 sib_cost = lowest_cost_path (cost_in, repl_savings,
2760 lookup_cand (c->sibling), incr,
2761 count_phis);
2762 local_cost = MIN (local_cost, sib_cost);
2765 return local_cost;
2768 /* Compute the total savings that would accrue from all replacements
2769 in the candidate tree rooted at C, counting only candidates with
2770 increment INCR. Assume that replacing a candidate reduces cost
2771 by REPL_SAVINGS. Also account for savings from statements that
2772 would go dead. */
2774 static int
2775 total_savings (int repl_savings, slsr_cand_t c, double_int incr,
2776 bool count_phis)
2778 int savings = 0;
2779 double_int cand_incr = cand_abs_increment (c);
2781 if (incr == cand_incr && !cand_already_replaced (c))
2782 savings += repl_savings + c->dead_savings;
2784 if (count_phis
2785 && phi_dependent_cand_p (c)
2786 && !cand_already_replaced (c))
2788 int phi_savings = 0;
2789 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
2790 savings -= phi_incr_cost (c, incr, phi, &phi_savings);
2792 if (has_single_use (gimple_phi_result (phi)))
2793 savings += phi_savings;
2796 if (c->dependent)
2797 savings += total_savings (repl_savings, lookup_cand (c->dependent), incr,
2798 count_phis);
2800 if (c->sibling)
2801 savings += total_savings (repl_savings, lookup_cand (c->sibling), incr,
2802 count_phis);
2804 return savings;
2807 /* Use target-specific costs to determine and record which increments
2808 in the current candidate tree are profitable to replace, assuming
2809 MODE and SPEED. FIRST_DEP is the first dependent of the root of
2810 the candidate tree.
2812 One slight limitation here is that we don't account for the possible
2813 introduction of casts in some cases. See replace_one_candidate for
2814 the cases where these are introduced. This should probably be cleaned
2815 up sometime. */
2817 static void
2818 analyze_increments (slsr_cand_t first_dep, enum machine_mode mode, bool speed)
2820 unsigned i;
2822 for (i = 0; i < incr_vec_len; i++)
2824 HOST_WIDE_INT incr = incr_vec[i].incr.to_shwi ();
2826 /* If somehow this increment is bigger than a HWI, we won't
2827 be optimizing candidates that use it. And if the increment
2828 has a count of zero, nothing will be done with it. */
2829 if (!incr_vec[i].incr.fits_shwi () || !incr_vec[i].count)
2830 incr_vec[i].cost = COST_INFINITE;
2832 /* Increments of 0, 1, and -1 are always profitable to replace,
2833 because they always replace a multiply or add with an add or
2834 copy, and may cause one or more existing instructions to go
2835 dead. Exception: -1 can't be assumed to be profitable for
2836 pointer addition. */
2837 else if (incr == 0
2838 || incr == 1
2839 || (incr == -1
2840 && (gimple_assign_rhs_code (first_dep->cand_stmt)
2841 != POINTER_PLUS_EXPR)))
2842 incr_vec[i].cost = COST_NEUTRAL;
2844 /* FORNOW: If we need to add an initializer, give up if a cast from
2845 the candidate's type to its stride's type can lose precision.
2846 This could eventually be handled better by expressly retaining the
2847 result of a cast to a wider type in the stride. Example:
2849 short int _1;
2850 _2 = (int) _1;
2851 _3 = _2 * 10;
2852 _4 = x + _3; ADD: x + (10 * _1) : int
2853 _5 = _2 * 15;
2854 _6 = x + _3; ADD: x + (15 * _1) : int
2856 Right now replacing _6 would cause insertion of an initializer
2857 of the form "short int T = _1 * 5;" followed by a cast to
2858 int, which could overflow incorrectly. Had we recorded _2 or
2859 (int)_1 as the stride, this wouldn't happen. However, doing
2860 this breaks other opportunities, so this will require some
2861 care. */
2862 else if (!incr_vec[i].initializer
2863 && TREE_CODE (first_dep->stride) != INTEGER_CST
2864 && !legal_cast_p_1 (first_dep->stride,
2865 gimple_assign_lhs (first_dep->cand_stmt)))
2867 incr_vec[i].cost = COST_INFINITE;
2869 /* If we need to add an initializer, make sure we don't introduce
2870 a multiply by a pointer type, which can happen in certain cast
2871 scenarios. FIXME: When cleaning up these cast issues, we can
2872 afford to introduce the multiply provided we cast out to an
2873 unsigned int of appropriate size. */
2874 else if (!incr_vec[i].initializer
2875 && TREE_CODE (first_dep->stride) != INTEGER_CST
2876 && POINTER_TYPE_P (TREE_TYPE (first_dep->stride)))
2878 incr_vec[i].cost = COST_INFINITE;
2880 /* For any other increment, if this is a multiply candidate, we
2881 must introduce a temporary T and initialize it with
2882 T_0 = stride * increment. When optimizing for speed, walk the
2883 candidate tree to calculate the best cost reduction along any
2884 path; if it offsets the fixed cost of inserting the initializer,
2885 replacing the increment is profitable. When optimizing for
2886 size, instead calculate the total cost reduction from replacing
2887 all candidates with this increment. */
2888 else if (first_dep->kind == CAND_MULT)
2890 int cost = mult_by_coeff_cost (incr, mode, speed);
2891 int repl_savings = mul_cost (speed, mode) - add_cost (speed, mode);
2892 if (speed)
2893 cost = lowest_cost_path (cost, repl_savings, first_dep,
2894 incr_vec[i].incr, COUNT_PHIS);
2895 else
2896 cost -= total_savings (repl_savings, first_dep, incr_vec[i].incr,
2897 COUNT_PHIS);
2899 incr_vec[i].cost = cost;
2902 /* If this is an add candidate, the initializer may already
2903 exist, so only calculate the cost of the initializer if it
2904 doesn't. We are replacing one add with another here, so the
2905 known replacement savings is zero. We will account for removal
2906 of dead instructions in lowest_cost_path or total_savings. */
2907 else
2909 int cost = 0;
2910 if (!incr_vec[i].initializer)
2911 cost = mult_by_coeff_cost (incr, mode, speed);
2913 if (speed)
2914 cost = lowest_cost_path (cost, 0, first_dep, incr_vec[i].incr,
2915 DONT_COUNT_PHIS);
2916 else
2917 cost -= total_savings (0, first_dep, incr_vec[i].incr,
2918 DONT_COUNT_PHIS);
2920 incr_vec[i].cost = cost;
2925 /* Return the nearest common dominator of BB1 and BB2. If the blocks
2926 are identical, return the earlier of C1 and C2 in *WHERE. Otherwise,
2927 if the NCD matches BB1, return C1 in *WHERE; if the NCD matches BB2,
2928 return C2 in *WHERE; and if the NCD matches neither, return NULL in
2929 *WHERE. Note: It is possible for one of C1 and C2 to be NULL. */
2931 static basic_block
2932 ncd_for_two_cands (basic_block bb1, basic_block bb2,
2933 slsr_cand_t c1, slsr_cand_t c2, slsr_cand_t *where)
2935 basic_block ncd;
2937 if (!bb1)
2939 *where = c2;
2940 return bb2;
2943 if (!bb2)
2945 *where = c1;
2946 return bb1;
2949 ncd = nearest_common_dominator (CDI_DOMINATORS, bb1, bb2);
2951 /* If both candidates are in the same block, the earlier
2952 candidate wins. */
2953 if (bb1 == ncd && bb2 == ncd)
2955 if (!c1 || (c2 && c2->cand_num < c1->cand_num))
2956 *where = c2;
2957 else
2958 *where = c1;
2961 /* Otherwise, if one of them produced a candidate in the
2962 dominator, that one wins. */
2963 else if (bb1 == ncd)
2964 *where = c1;
2966 else if (bb2 == ncd)
2967 *where = c2;
2969 /* If neither matches the dominator, neither wins. */
2970 else
2971 *where = NULL;
2973 return ncd;
2976 /* Consider all candidates that feed PHI. Find the nearest common
2977 dominator of those candidates requiring the given increment INCR.
2978 Further find and return the nearest common dominator of this result
2979 with block NCD. If the returned block contains one or more of the
2980 candidates, return the earliest candidate in the block in *WHERE. */
2982 static basic_block
2983 ncd_with_phi (slsr_cand_t c, double_int incr, gimple phi,
2984 basic_block ncd, slsr_cand_t *where)
2986 unsigned i;
2987 slsr_cand_t basis = lookup_cand (c->basis);
2988 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
2990 for (i = 0; i < gimple_phi_num_args (phi); i++)
2992 tree arg = gimple_phi_arg_def (phi, i);
2994 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
2996 gimple arg_def = SSA_NAME_DEF_STMT (arg);
2998 if (gimple_code (arg_def) == GIMPLE_PHI)
2999 ncd = ncd_with_phi (c, incr, arg_def, ncd, where);
3000 else
3002 slsr_cand_t arg_cand = base_cand_from_table (arg);
3003 double_int diff = arg_cand->index - basis->index;
3004 basic_block pred = gimple_phi_arg_edge (phi, i)->src;
3006 if ((incr == diff) || (!address_arithmetic_p && incr == -diff))
3007 ncd = ncd_for_two_cands (ncd, pred, *where, NULL, where);
3012 return ncd;
3015 /* Consider the candidate C together with any candidates that feed
3016 C's phi dependence (if any). Find and return the nearest common
3017 dominator of those candidates requiring the given increment INCR.
3018 If the returned block contains one or more of the candidates,
3019 return the earliest candidate in the block in *WHERE. */
3021 static basic_block
3022 ncd_of_cand_and_phis (slsr_cand_t c, double_int incr, slsr_cand_t *where)
3024 basic_block ncd = NULL;
3026 if (cand_abs_increment (c) == incr)
3028 ncd = gimple_bb (c->cand_stmt);
3029 *where = c;
3032 if (phi_dependent_cand_p (c))
3033 ncd = ncd_with_phi (c, incr, lookup_cand (c->def_phi)->cand_stmt,
3034 ncd, where);
3036 return ncd;
3039 /* Consider all candidates in the tree rooted at C for which INCR
3040 represents the required increment of C relative to its basis.
3041 Find and return the basic block that most nearly dominates all
3042 such candidates. If the returned block contains one or more of
3043 the candidates, return the earliest candidate in the block in
3044 *WHERE. */
3046 static basic_block
3047 nearest_common_dominator_for_cands (slsr_cand_t c, double_int incr,
3048 slsr_cand_t *where)
3050 basic_block sib_ncd = NULL, dep_ncd = NULL, this_ncd = NULL, ncd;
3051 slsr_cand_t sib_where = NULL, dep_where = NULL, this_where = NULL, new_where;
3053 /* First find the NCD of all siblings and dependents. */
3054 if (c->sibling)
3055 sib_ncd = nearest_common_dominator_for_cands (lookup_cand (c->sibling),
3056 incr, &sib_where);
3057 if (c->dependent)
3058 dep_ncd = nearest_common_dominator_for_cands (lookup_cand (c->dependent),
3059 incr, &dep_where);
3060 if (!sib_ncd && !dep_ncd)
3062 new_where = NULL;
3063 ncd = NULL;
3065 else if (sib_ncd && !dep_ncd)
3067 new_where = sib_where;
3068 ncd = sib_ncd;
3070 else if (dep_ncd && !sib_ncd)
3072 new_where = dep_where;
3073 ncd = dep_ncd;
3075 else
3076 ncd = ncd_for_two_cands (sib_ncd, dep_ncd, sib_where,
3077 dep_where, &new_where);
3079 /* If the candidate's increment doesn't match the one we're interested
3080 in (and nor do any increments for feeding defs of a phi-dependence),
3081 then the result depends only on siblings and dependents. */
3082 this_ncd = ncd_of_cand_and_phis (c, incr, &this_where);
3084 if (!this_ncd || cand_already_replaced (c))
3086 *where = new_where;
3087 return ncd;
3090 /* Otherwise, compare this candidate with the result from all siblings
3091 and dependents. */
3092 ncd = ncd_for_two_cands (ncd, this_ncd, new_where, this_where, where);
3094 return ncd;
3097 /* Return TRUE if the increment indexed by INDEX is profitable to replace. */
3099 static inline bool
3100 profitable_increment_p (unsigned index)
3102 return (incr_vec[index].cost <= COST_NEUTRAL);
3105 /* For each profitable increment in the increment vector not equal to
3106 0 or 1 (or -1, for non-pointer arithmetic), find the nearest common
3107 dominator of all statements in the candidate chain rooted at C
3108 that require that increment, and insert an initializer
3109 T_0 = stride * increment at that location. Record T_0 with the
3110 increment record. */
3112 static void
3113 insert_initializers (slsr_cand_t c)
3115 unsigned i;
3117 for (i = 0; i < incr_vec_len; i++)
3119 basic_block bb;
3120 slsr_cand_t where = NULL;
3121 gimple init_stmt;
3122 tree stride_type, new_name, incr_tree;
3123 double_int incr = incr_vec[i].incr;
3125 if (!profitable_increment_p (i)
3126 || incr.is_one ()
3127 || (incr.is_minus_one ()
3128 && gimple_assign_rhs_code (c->cand_stmt) != POINTER_PLUS_EXPR)
3129 || incr.is_zero ())
3130 continue;
3132 /* We may have already identified an existing initializer that
3133 will suffice. */
3134 if (incr_vec[i].initializer)
3136 if (dump_file && (dump_flags & TDF_DETAILS))
3138 fputs ("Using existing initializer: ", dump_file);
3139 print_gimple_stmt (dump_file,
3140 SSA_NAME_DEF_STMT (incr_vec[i].initializer),
3141 0, 0);
3143 continue;
3146 /* Find the block that most closely dominates all candidates
3147 with this increment. If there is at least one candidate in
3148 that block, the earliest one will be returned in WHERE. */
3149 bb = nearest_common_dominator_for_cands (c, incr, &where);
3151 /* Create a new SSA name to hold the initializer's value. */
3152 stride_type = TREE_TYPE (c->stride);
3153 new_name = make_temp_ssa_name (stride_type, NULL, "slsr");
3154 incr_vec[i].initializer = new_name;
3156 /* Create the initializer and insert it in the latest possible
3157 dominating position. */
3158 incr_tree = double_int_to_tree (stride_type, incr);
3159 init_stmt = gimple_build_assign_with_ops (MULT_EXPR, new_name,
3160 c->stride, incr_tree);
3161 if (where)
3163 gimple_stmt_iterator gsi = gsi_for_stmt (where->cand_stmt);
3164 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
3165 gimple_set_location (init_stmt, gimple_location (where->cand_stmt));
3167 else
3169 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3170 gimple basis_stmt = lookup_cand (c->basis)->cand_stmt;
3172 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
3173 gsi_insert_before (&gsi, init_stmt, GSI_SAME_STMT);
3174 else
3175 gsi_insert_after (&gsi, init_stmt, GSI_SAME_STMT);
3177 gimple_set_location (init_stmt, gimple_location (basis_stmt));
3180 if (dump_file && (dump_flags & TDF_DETAILS))
3182 fputs ("Inserting initializer: ", dump_file);
3183 print_gimple_stmt (dump_file, init_stmt, 0, 0);
3188 /* Return TRUE iff all required increments for candidates feeding PHI
3189 are profitable to replace on behalf of candidate C. */
3191 static bool
3192 all_phi_incrs_profitable (slsr_cand_t c, gimple phi)
3194 unsigned i;
3195 slsr_cand_t basis = lookup_cand (c->basis);
3196 slsr_cand_t phi_cand = base_cand_from_table (gimple_phi_result (phi));
3198 for (i = 0; i < gimple_phi_num_args (phi); i++)
3200 tree arg = gimple_phi_arg_def (phi, i);
3202 if (!operand_equal_p (arg, phi_cand->base_expr, 0))
3204 gimple arg_def = SSA_NAME_DEF_STMT (arg);
3206 if (gimple_code (arg_def) == GIMPLE_PHI)
3208 if (!all_phi_incrs_profitable (c, arg_def))
3209 return false;
3211 else
3213 int j;
3214 slsr_cand_t arg_cand = base_cand_from_table (arg);
3215 double_int increment = arg_cand->index - basis->index;
3217 if (!address_arithmetic_p && increment.is_negative ())
3218 increment = -increment;
3220 j = incr_vec_index (increment);
3222 if (dump_file && (dump_flags & TDF_DETAILS))
3224 fprintf (dump_file, " Conditional candidate %d, phi: ",
3225 c->cand_num);
3226 print_gimple_stmt (dump_file, phi, 0, 0);
3227 fputs (" increment: ", dump_file);
3228 dump_double_int (dump_file, increment, false);
3229 if (j < 0)
3230 fprintf (dump_file,
3231 "\n Not replaced; incr_vec overflow.\n");
3232 else {
3233 fprintf (dump_file, "\n cost: %d\n", incr_vec[j].cost);
3234 if (profitable_increment_p (j))
3235 fputs (" Replacing...\n", dump_file);
3236 else
3237 fputs (" Not replaced.\n", dump_file);
3241 if (j < 0 || !profitable_increment_p (j))
3242 return false;
3247 return true;
3250 /* Create a NOP_EXPR that copies FROM_EXPR into a new SSA name of
3251 type TO_TYPE, and insert it in front of the statement represented
3252 by candidate C. Use *NEW_VAR to create the new SSA name. Return
3253 the new SSA name. */
3255 static tree
3256 introduce_cast_before_cand (slsr_cand_t c, tree to_type, tree from_expr)
3258 tree cast_lhs;
3259 gimple cast_stmt;
3260 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3262 cast_lhs = make_temp_ssa_name (to_type, NULL, "slsr");
3263 cast_stmt = gimple_build_assign_with_ops (NOP_EXPR, cast_lhs,
3264 from_expr, NULL_TREE);
3265 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
3266 gsi_insert_before (&gsi, cast_stmt, GSI_SAME_STMT);
3268 if (dump_file && (dump_flags & TDF_DETAILS))
3270 fputs (" Inserting: ", dump_file);
3271 print_gimple_stmt (dump_file, cast_stmt, 0, 0);
3274 return cast_lhs;
3277 /* Replace the RHS of the statement represented by candidate C with
3278 NEW_CODE, NEW_RHS1, and NEW_RHS2, provided that to do so doesn't
3279 leave C unchanged or just interchange its operands. The original
3280 operation and operands are in OLD_CODE, OLD_RHS1, and OLD_RHS2.
3281 If the replacement was made and we are doing a details dump,
3282 return the revised statement, else NULL. */
3284 static gimple
3285 replace_rhs_if_not_dup (enum tree_code new_code, tree new_rhs1, tree new_rhs2,
3286 enum tree_code old_code, tree old_rhs1, tree old_rhs2,
3287 slsr_cand_t c)
3289 if (new_code != old_code
3290 || ((!operand_equal_p (new_rhs1, old_rhs1, 0)
3291 || !operand_equal_p (new_rhs2, old_rhs2, 0))
3292 && (!operand_equal_p (new_rhs1, old_rhs2, 0)
3293 || !operand_equal_p (new_rhs2, old_rhs1, 0))))
3295 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3296 gimple_assign_set_rhs_with_ops (&gsi, new_code, new_rhs1, new_rhs2);
3297 update_stmt (gsi_stmt (gsi));
3298 c->cand_stmt = gsi_stmt (gsi);
3300 if (dump_file && (dump_flags & TDF_DETAILS))
3301 return gsi_stmt (gsi);
3304 else if (dump_file && (dump_flags & TDF_DETAILS))
3305 fputs (" (duplicate, not actually replacing)\n", dump_file);
3307 return NULL;
3310 /* Strength-reduce the statement represented by candidate C by replacing
3311 it with an equivalent addition or subtraction. I is the index into
3312 the increment vector identifying C's increment. NEW_VAR is used to
3313 create a new SSA name if a cast needs to be introduced. BASIS_NAME
3314 is the rhs1 to use in creating the add/subtract. */
3316 static void
3317 replace_one_candidate (slsr_cand_t c, unsigned i, tree basis_name)
3319 gimple stmt_to_print = NULL;
3320 tree orig_rhs1, orig_rhs2;
3321 tree rhs2;
3322 enum tree_code orig_code, repl_code;
3323 double_int cand_incr;
3325 orig_code = gimple_assign_rhs_code (c->cand_stmt);
3326 orig_rhs1 = gimple_assign_rhs1 (c->cand_stmt);
3327 orig_rhs2 = gimple_assign_rhs2 (c->cand_stmt);
3328 cand_incr = cand_increment (c);
3330 if (dump_file && (dump_flags & TDF_DETAILS))
3332 fputs ("Replacing: ", dump_file);
3333 print_gimple_stmt (dump_file, c->cand_stmt, 0, 0);
3334 stmt_to_print = c->cand_stmt;
3337 if (address_arithmetic_p)
3338 repl_code = POINTER_PLUS_EXPR;
3339 else
3340 repl_code = PLUS_EXPR;
3342 /* If the increment has an initializer T_0, replace the candidate
3343 statement with an add of the basis name and the initializer. */
3344 if (incr_vec[i].initializer)
3346 tree init_type = TREE_TYPE (incr_vec[i].initializer);
3347 tree orig_type = TREE_TYPE (orig_rhs2);
3349 if (types_compatible_p (orig_type, init_type))
3350 rhs2 = incr_vec[i].initializer;
3351 else
3352 rhs2 = introduce_cast_before_cand (c, orig_type,
3353 incr_vec[i].initializer);
3355 if (incr_vec[i].incr != cand_incr)
3357 gcc_assert (repl_code == PLUS_EXPR);
3358 repl_code = MINUS_EXPR;
3361 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
3362 orig_code, orig_rhs1, orig_rhs2,
3366 /* Otherwise, the increment is one of -1, 0, and 1. Replace
3367 with a subtract of the stride from the basis name, a copy
3368 from the basis name, or an add of the stride to the basis
3369 name, respectively. It may be necessary to introduce a
3370 cast (or reuse an existing cast). */
3371 else if (cand_incr.is_one ())
3373 tree stride_type = TREE_TYPE (c->stride);
3374 tree orig_type = TREE_TYPE (orig_rhs2);
3376 if (types_compatible_p (orig_type, stride_type))
3377 rhs2 = c->stride;
3378 else
3379 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride);
3381 stmt_to_print = replace_rhs_if_not_dup (repl_code, basis_name, rhs2,
3382 orig_code, orig_rhs1, orig_rhs2,
3386 else if (cand_incr.is_minus_one ())
3388 tree stride_type = TREE_TYPE (c->stride);
3389 tree orig_type = TREE_TYPE (orig_rhs2);
3390 gcc_assert (repl_code != POINTER_PLUS_EXPR);
3392 if (types_compatible_p (orig_type, stride_type))
3393 rhs2 = c->stride;
3394 else
3395 rhs2 = introduce_cast_before_cand (c, orig_type, c->stride);
3397 if (orig_code != MINUS_EXPR
3398 || !operand_equal_p (basis_name, orig_rhs1, 0)
3399 || !operand_equal_p (rhs2, orig_rhs2, 0))
3401 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3402 gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, basis_name, rhs2);
3403 update_stmt (gsi_stmt (gsi));
3404 c->cand_stmt = gsi_stmt (gsi);
3406 if (dump_file && (dump_flags & TDF_DETAILS))
3407 stmt_to_print = gsi_stmt (gsi);
3409 else if (dump_file && (dump_flags & TDF_DETAILS))
3410 fputs (" (duplicate, not actually replacing)\n", dump_file);
3413 else if (cand_incr.is_zero ())
3415 tree lhs = gimple_assign_lhs (c->cand_stmt);
3416 tree lhs_type = TREE_TYPE (lhs);
3417 tree basis_type = TREE_TYPE (basis_name);
3419 if (types_compatible_p (lhs_type, basis_type))
3421 gimple copy_stmt = gimple_build_assign (lhs, basis_name);
3422 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3423 gimple_set_location (copy_stmt, gimple_location (c->cand_stmt));
3424 gsi_replace (&gsi, copy_stmt, false);
3425 c->cand_stmt = copy_stmt;
3427 if (dump_file && (dump_flags & TDF_DETAILS))
3428 stmt_to_print = copy_stmt;
3430 else
3432 gimple_stmt_iterator gsi = gsi_for_stmt (c->cand_stmt);
3433 gimple cast_stmt = gimple_build_assign_with_ops (NOP_EXPR, lhs,
3434 basis_name,
3435 NULL_TREE);
3436 gimple_set_location (cast_stmt, gimple_location (c->cand_stmt));
3437 gsi_replace (&gsi, cast_stmt, false);
3438 c->cand_stmt = cast_stmt;
3440 if (dump_file && (dump_flags & TDF_DETAILS))
3441 stmt_to_print = cast_stmt;
3444 else
3445 gcc_unreachable ();
3447 if (dump_file && (dump_flags & TDF_DETAILS) && stmt_to_print)
3449 fputs ("With: ", dump_file);
3450 print_gimple_stmt (dump_file, stmt_to_print, 0, 0);
3451 fputs ("\n", dump_file);
3455 /* For each candidate in the tree rooted at C, replace it with
3456 an increment if such has been shown to be profitable. */
3458 static void
3459 replace_profitable_candidates (slsr_cand_t c)
3461 if (!cand_already_replaced (c))
3463 double_int increment = cand_abs_increment (c);
3464 enum tree_code orig_code = gimple_assign_rhs_code (c->cand_stmt);
3465 int i;
3467 i = incr_vec_index (increment);
3469 /* Only process profitable increments. Nothing useful can be done
3470 to a cast or copy. */
3471 if (i >= 0
3472 && profitable_increment_p (i)
3473 && orig_code != MODIFY_EXPR
3474 && orig_code != NOP_EXPR)
3476 if (phi_dependent_cand_p (c))
3478 gimple phi = lookup_cand (c->def_phi)->cand_stmt;
3480 if (all_phi_incrs_profitable (c, phi))
3482 /* Look up the LHS SSA name from C's basis. This will be
3483 the RHS1 of the adds we will introduce to create new
3484 phi arguments. */
3485 slsr_cand_t basis = lookup_cand (c->basis);
3486 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
3488 /* Create a new phi statement that will represent C's true
3489 basis after the transformation is complete. */
3490 location_t loc = gimple_location (c->cand_stmt);
3491 tree name = create_phi_basis (c, phi, basis_name,
3492 loc, UNKNOWN_STRIDE);
3494 /* Replace C with an add of the new basis phi and the
3495 increment. */
3496 replace_one_candidate (c, i, name);
3499 else
3501 slsr_cand_t basis = lookup_cand (c->basis);
3502 tree basis_name = gimple_assign_lhs (basis->cand_stmt);
3503 replace_one_candidate (c, i, basis_name);
3508 if (c->sibling)
3509 replace_profitable_candidates (lookup_cand (c->sibling));
3511 if (c->dependent)
3512 replace_profitable_candidates (lookup_cand (c->dependent));
3515 /* Analyze costs of related candidates in the candidate vector,
3516 and make beneficial replacements. */
3518 static void
3519 analyze_candidates_and_replace (void)
3521 unsigned i;
3522 slsr_cand_t c;
3524 /* Each candidate that has a null basis and a non-null
3525 dependent is the root of a tree of related statements.
3526 Analyze each tree to determine a subset of those
3527 statements that can be replaced with maximum benefit. */
3528 FOR_EACH_VEC_ELT (cand_vec, i, c)
3530 slsr_cand_t first_dep;
3532 if (c->basis != 0 || c->dependent == 0)
3533 continue;
3535 if (dump_file && (dump_flags & TDF_DETAILS))
3536 fprintf (dump_file, "\nProcessing dependency tree rooted at %d.\n",
3537 c->cand_num);
3539 first_dep = lookup_cand (c->dependent);
3541 /* If this is a chain of CAND_REFs, unconditionally replace
3542 each of them with a strength-reduced data reference. */
3543 if (c->kind == CAND_REF)
3544 replace_refs (c);
3546 /* If the common stride of all related candidates is a known
3547 constant, each candidate without a phi-dependence can be
3548 profitably replaced. Each replaces a multiply by a single
3549 add, with the possibility that a feeding add also goes dead.
3550 A candidate with a phi-dependence is replaced only if the
3551 compensation code it requires is offset by the strength
3552 reduction savings. */
3553 else if (TREE_CODE (c->stride) == INTEGER_CST)
3554 replace_uncond_cands_and_profitable_phis (first_dep);
3556 /* When the stride is an SSA name, it may still be profitable
3557 to replace some or all of the dependent candidates, depending
3558 on whether the introduced increments can be reused, or are
3559 less expensive to calculate than the replaced statements. */
3560 else
3562 enum machine_mode mode;
3563 bool speed;
3565 /* Determine whether we'll be generating pointer arithmetic
3566 when replacing candidates. */
3567 address_arithmetic_p = (c->kind == CAND_ADD
3568 && POINTER_TYPE_P (c->cand_type));
3570 /* If all candidates have already been replaced under other
3571 interpretations, nothing remains to be done. */
3572 if (!count_candidates (c))
3573 continue;
3575 /* Construct an array of increments for this candidate chain. */
3576 incr_vec = XNEWVEC (incr_info, MAX_INCR_VEC_LEN);
3577 incr_vec_len = 0;
3578 record_increments (c);
3580 /* Determine which increments are profitable to replace. */
3581 mode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (c->cand_stmt)));
3582 speed = optimize_cands_for_speed_p (c);
3583 analyze_increments (first_dep, mode, speed);
3585 /* Insert initializers of the form T_0 = stride * increment
3586 for use in profitable replacements. */
3587 insert_initializers (first_dep);
3588 dump_incr_vec ();
3590 /* Perform the replacements. */
3591 replace_profitable_candidates (first_dep);
3592 free (incr_vec);
3597 namespace {
3599 const pass_data pass_data_strength_reduction =
3601 GIMPLE_PASS, /* type */
3602 "slsr", /* name */
3603 OPTGROUP_NONE, /* optinfo_flags */
3604 true, /* has_execute */
3605 TV_GIMPLE_SLSR, /* tv_id */
3606 ( PROP_cfg | PROP_ssa ), /* properties_required */
3607 0, /* properties_provided */
3608 0, /* properties_destroyed */
3609 0, /* todo_flags_start */
3610 TODO_verify_ssa, /* todo_flags_finish */
3613 class pass_strength_reduction : public gimple_opt_pass
3615 public:
3616 pass_strength_reduction (gcc::context *ctxt)
3617 : gimple_opt_pass (pass_data_strength_reduction, ctxt)
3620 /* opt_pass methods: */
3621 virtual bool gate (function *) { return flag_tree_slsr; }
3622 virtual unsigned int execute (function *);
3624 }; // class pass_strength_reduction
3626 unsigned
3627 pass_strength_reduction::execute (function *fun)
3629 /* Create the obstack where candidates will reside. */
3630 gcc_obstack_init (&cand_obstack);
3632 /* Allocate the candidate vector. */
3633 cand_vec.create (128);
3635 /* Allocate the mapping from statements to candidate indices. */
3636 stmt_cand_map = pointer_map_create ();
3638 /* Create the obstack where candidate chains will reside. */
3639 gcc_obstack_init (&chain_obstack);
3641 /* Allocate the mapping from base expressions to candidate chains. */
3642 base_cand_map.create (500);
3644 /* Allocate the mapping from bases to alternative bases. */
3645 alt_base_map = pointer_map_create ();
3647 /* Initialize the loop optimizer. We need to detect flow across
3648 back edges, and this gives us dominator information as well. */
3649 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
3651 /* Walk the CFG in predominator order looking for strength reduction
3652 candidates. */
3653 find_candidates_dom_walker (CDI_DOMINATORS)
3654 .walk (fun->cfg->x_entry_block_ptr);
3656 if (dump_file && (dump_flags & TDF_DETAILS))
3658 dump_cand_vec ();
3659 dump_cand_chains ();
3662 pointer_map_destroy (alt_base_map);
3663 free_affine_expand_cache (&name_expansions);
3665 /* Analyze costs and make appropriate replacements. */
3666 analyze_candidates_and_replace ();
3668 loop_optimizer_finalize ();
3669 base_cand_map.dispose ();
3670 obstack_free (&chain_obstack, NULL);
3671 pointer_map_destroy (stmt_cand_map);
3672 cand_vec.release ();
3673 obstack_free (&cand_obstack, NULL);
3675 return 0;
3678 } // anon namespace
3680 gimple_opt_pass *
3681 make_pass_strength_reduction (gcc::context *ctxt)
3683 return new pass_strength_reduction (ctxt);