1 /* Loop invariant motion.
2 Copyright (C) 2003-2023 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
22 #include "coretypes.h"
27 #include "tree-pass.h"
29 #include "gimple-pretty-print.h"
30 #include "fold-const.h"
34 #include "gimple-iterator.h"
36 #include "tree-ssa-loop-manip.h"
37 #include "tree-ssa-loop.h"
38 #include "tree-into-ssa.h"
40 #include "tree-affine.h"
41 #include "tree-ssa-propagate.h"
42 #include "trans-mem.h"
43 #include "gimple-fold.h"
44 #include "tree-scalar-evolution.h"
45 #include "tree-ssa-loop-niter.h"
52 /* TODO: Support for predicated code motion. I.e.
63 Where COND and INV are invariants, but evaluating INV may trap or be
64 invalid from some other reason if !COND. This may be transformed to
74 /* The auxiliary data kept for each statement. */
78 class loop
*max_loop
; /* The outermost loop in that the statement
81 class loop
*tgt_loop
; /* The loop out of that we want to move the
84 class loop
*always_executed_in
;
85 /* The outermost loop for that we are sure
86 the statement is executed if the loop
89 unsigned cost
; /* Cost of the computation performed by the
92 unsigned ref
; /* The simple_mem_ref in this stmt or 0. */
94 vec
<gimple
*> depends
; /* Vector of statements that must be also
95 hoisted out of the loop when this statement
96 is hoisted; i.e. those that define the
97 operands of the statement and are inside of
101 /* Maps statements to their lim_aux_data. */
103 static hash_map
<gimple
*, lim_aux_data
*> *lim_aux_data_map
;
105 /* Description of a memory reference location. */
109 tree
*ref
; /* The reference itself. */
110 gimple
*stmt
; /* The statement in that it occurs. */
114 /* Description of a memory reference. */
119 unsigned id
: 30; /* ID assigned to the memory reference
120 (its index in memory_accesses.refs_list) */
121 unsigned ref_canonical
: 1; /* Whether mem.ref was canonicalized. */
122 unsigned ref_decomposed
: 1; /* Whether the ref was hashed from mem. */
123 hashval_t hash
; /* Its hash value. */
125 /* The memory access itself and associated caching of alias-oracle
126 query meta-data. We are using mem.ref == error_mark_node for the
127 case the reference is represented by its single access stmt
128 in accesses_in_loop[0]. */
131 bitmap stored
; /* The set of loops in that this memory location
133 bitmap loaded
; /* The set of loops in that this memory location
135 vec
<mem_ref_loc
> accesses_in_loop
;
136 /* The locations of the accesses. */
138 /* The following set is computed on demand. */
139 bitmap_head dep_loop
; /* The set of loops in that the memory
140 reference is {in,}dependent in
144 /* We use six bits per loop in the ref->dep_loop bitmap to record
145 the dep_kind x dep_state combinations. */
147 enum dep_kind
{ lim_raw
, sm_war
, sm_waw
};
148 enum dep_state
{ dep_unknown
, dep_independent
, dep_dependent
};
150 /* coldest outermost loop for given loop. */
151 vec
<class loop
*> coldest_outermost_loop
;
152 /* hotter outer loop nearest to given loop. */
153 vec
<class loop
*> hotter_than_inner_loop
;
155 /* Populate the loop dependence cache of REF for LOOP, KIND with STATE. */
158 record_loop_dependence (class loop
*loop
, im_mem_ref
*ref
,
159 dep_kind kind
, dep_state state
)
161 gcc_assert (state
!= dep_unknown
);
162 unsigned bit
= 6 * loop
->num
+ kind
* 2 + state
== dep_dependent
? 1 : 0;
163 bitmap_set_bit (&ref
->dep_loop
, bit
);
166 /* Query the loop dependence cache of REF for LOOP, KIND. */
169 query_loop_dependence (class loop
*loop
, im_mem_ref
*ref
, dep_kind kind
)
171 unsigned first_bit
= 6 * loop
->num
+ kind
* 2;
172 if (bitmap_bit_p (&ref
->dep_loop
, first_bit
))
173 return dep_independent
;
174 else if (bitmap_bit_p (&ref
->dep_loop
, first_bit
+ 1))
175 return dep_dependent
;
179 /* Mem_ref hashtable helpers. */
181 struct mem_ref_hasher
: nofree_ptr_hash
<im_mem_ref
>
183 typedef ao_ref
*compare_type
;
184 static inline hashval_t
hash (const im_mem_ref
*);
185 static inline bool equal (const im_mem_ref
*, const ao_ref
*);
188 /* A hash function for class im_mem_ref object OBJ. */
191 mem_ref_hasher::hash (const im_mem_ref
*mem
)
196 /* An equality function for class im_mem_ref object MEM1 with
197 memory reference OBJ2. */
200 mem_ref_hasher::equal (const im_mem_ref
*mem1
, const ao_ref
*obj2
)
202 if (obj2
->max_size_known_p ())
203 return (mem1
->ref_decomposed
204 && ((TREE_CODE (mem1
->mem
.base
) == MEM_REF
205 && TREE_CODE (obj2
->base
) == MEM_REF
206 && operand_equal_p (TREE_OPERAND (mem1
->mem
.base
, 0),
207 TREE_OPERAND (obj2
->base
, 0), 0)
208 && known_eq (mem_ref_offset (mem1
->mem
.base
) * BITS_PER_UNIT
+ mem1
->mem
.offset
,
209 mem_ref_offset (obj2
->base
) * BITS_PER_UNIT
+ obj2
->offset
))
210 || (operand_equal_p (mem1
->mem
.base
, obj2
->base
, 0)
211 && known_eq (mem1
->mem
.offset
, obj2
->offset
)))
212 && known_eq (mem1
->mem
.size
, obj2
->size
)
213 && known_eq (mem1
->mem
.max_size
, obj2
->max_size
)
214 && mem1
->mem
.volatile_p
== obj2
->volatile_p
215 && (mem1
->mem
.ref_alias_set
== obj2
->ref_alias_set
216 /* We are not canonicalizing alias-sets but for the
217 special-case we didn't canonicalize yet and the
218 incoming ref is a alias-set zero MEM we pick
219 the correct one already. */
220 || (!mem1
->ref_canonical
221 && (TREE_CODE (obj2
->ref
) == MEM_REF
222 || TREE_CODE (obj2
->ref
) == TARGET_MEM_REF
)
223 && obj2
->ref_alias_set
== 0)
224 /* Likewise if there's a canonical ref with alias-set zero. */
225 || (mem1
->ref_canonical
&& mem1
->mem
.ref_alias_set
== 0))
226 && types_compatible_p (TREE_TYPE (mem1
->mem
.ref
),
227 TREE_TYPE (obj2
->ref
)));
229 return operand_equal_p (mem1
->mem
.ref
, obj2
->ref
, 0);
233 /* Description of memory accesses in loops. */
237 /* The hash table of memory references accessed in loops. */
238 hash_table
<mem_ref_hasher
> *refs
;
240 /* The list of memory references. */
241 vec
<im_mem_ref
*> refs_list
;
243 /* The set of memory references accessed in each loop. */
244 vec
<bitmap_head
> refs_loaded_in_loop
;
246 /* The set of memory references stored in each loop. */
247 vec
<bitmap_head
> refs_stored_in_loop
;
249 /* The set of memory references stored in each loop, including subloops . */
250 vec
<bitmap_head
> all_refs_stored_in_loop
;
252 /* Cache for expanding memory addresses. */
253 hash_map
<tree
, name_expansion
*> *ttae_cache
;
256 /* Obstack for the bitmaps in the above data structures. */
257 static bitmap_obstack lim_bitmap_obstack
;
258 static obstack mem_ref_obstack
;
260 static bool ref_indep_loop_p (class loop
*, im_mem_ref
*, dep_kind
);
261 static bool ref_always_accessed_p (class loop
*, im_mem_ref
*, bool);
262 static bool refs_independent_p (im_mem_ref
*, im_mem_ref
*, bool = true);
264 /* Minimum cost of an expensive expression. */
265 #define LIM_EXPENSIVE ((unsigned) param_lim_expensive)
267 /* The outermost loop for which execution of the header guarantees that the
268 block will be executed. */
269 #define ALWAYS_EXECUTED_IN(BB) ((class loop *) (BB)->aux)
270 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
272 /* ID of the shared unanalyzable mem. */
273 #define UNANALYZABLE_MEM_ID 0
275 /* Whether the reference was analyzable. */
276 #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
278 static struct lim_aux_data
*
279 init_lim_data (gimple
*stmt
)
281 lim_aux_data
*p
= XCNEW (struct lim_aux_data
);
282 lim_aux_data_map
->put (stmt
, p
);
287 static struct lim_aux_data
*
288 get_lim_data (gimple
*stmt
)
290 lim_aux_data
**p
= lim_aux_data_map
->get (stmt
);
297 /* Releases the memory occupied by DATA. */
300 free_lim_aux_data (struct lim_aux_data
*data
)
302 data
->depends
.release ();
307 clear_lim_data (gimple
*stmt
)
309 lim_aux_data
**p
= lim_aux_data_map
->get (stmt
);
313 free_lim_aux_data (*p
);
318 /* The possibilities of statement movement. */
321 MOVE_IMPOSSIBLE
, /* No movement -- side effect expression. */
322 MOVE_PRESERVE_EXECUTION
, /* Must not cause the non-executed statement
323 become executed -- memory accesses, ... */
324 MOVE_POSSIBLE
/* Unlimited movement. */
328 /* If it is possible to hoist the statement STMT unconditionally,
329 returns MOVE_POSSIBLE.
330 If it is possible to hoist the statement STMT, but we must avoid making
331 it executed if it would not be executed in the original program (e.g.
332 because it may trap), return MOVE_PRESERVE_EXECUTION.
333 Otherwise return MOVE_IMPOSSIBLE. */
336 movement_possibility_1 (gimple
*stmt
)
339 enum move_pos ret
= MOVE_POSSIBLE
;
341 if (flag_unswitch_loops
342 && gimple_code (stmt
) == GIMPLE_COND
)
344 /* If we perform unswitching, force the operands of the invariant
345 condition to be moved out of the loop. */
346 return MOVE_POSSIBLE
;
349 if (gimple_code (stmt
) == GIMPLE_PHI
350 && gimple_phi_num_args (stmt
) <= 2
351 && !virtual_operand_p (gimple_phi_result (stmt
))
352 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt
)))
353 return MOVE_POSSIBLE
;
355 if (gimple_get_lhs (stmt
) == NULL_TREE
)
356 return MOVE_IMPOSSIBLE
;
358 if (gimple_vdef (stmt
))
359 return MOVE_IMPOSSIBLE
;
361 if (stmt_ends_bb_p (stmt
)
362 || gimple_has_volatile_ops (stmt
)
363 || gimple_has_side_effects (stmt
)
364 || stmt_could_throw_p (cfun
, stmt
))
365 return MOVE_IMPOSSIBLE
;
367 if (is_gimple_call (stmt
))
369 /* While pure or const call is guaranteed to have no side effects, we
370 cannot move it arbitrarily. Consider code like
372 char *s = something ();
382 Here the strlen call cannot be moved out of the loop, even though
383 s is invariant. In addition to possibly creating a call with
384 invalid arguments, moving out a function call that is not executed
385 may cause performance regressions in case the call is costly and
386 not executed at all. */
387 ret
= MOVE_PRESERVE_EXECUTION
;
388 lhs
= gimple_call_lhs (stmt
);
390 else if (is_gimple_assign (stmt
))
391 lhs
= gimple_assign_lhs (stmt
);
393 return MOVE_IMPOSSIBLE
;
395 if (TREE_CODE (lhs
) == SSA_NAME
396 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs
))
397 return MOVE_IMPOSSIBLE
;
399 if (TREE_CODE (lhs
) != SSA_NAME
400 || gimple_could_trap_p (stmt
))
401 return MOVE_PRESERVE_EXECUTION
;
403 /* Non local loads in a transaction cannot be hoisted out. Well,
404 unless the load happens on every path out of the loop, but we
405 don't take this into account yet. */
407 && gimple_in_transaction (stmt
)
408 && gimple_assign_single_p (stmt
))
410 tree rhs
= gimple_assign_rhs1 (stmt
);
411 if (DECL_P (rhs
) && is_global_var (rhs
))
415 fprintf (dump_file
, "Cannot hoist conditional load of ");
416 print_generic_expr (dump_file
, rhs
, TDF_SLIM
);
417 fprintf (dump_file
, " because it is in a transaction.\n");
419 return MOVE_IMPOSSIBLE
;
427 movement_possibility (gimple
*stmt
)
429 enum move_pos pos
= movement_possibility_1 (stmt
);
430 if (pos
== MOVE_POSSIBLE
)
433 ssa_op_iter ssa_iter
;
434 FOR_EACH_PHI_OR_STMT_USE (use_p
, stmt
, ssa_iter
, SSA_OP_USE
)
435 if (TREE_CODE (USE_FROM_PTR (use_p
)) == SSA_NAME
436 && ssa_name_maybe_undef_p (USE_FROM_PTR (use_p
)))
437 return MOVE_PRESERVE_EXECUTION
;
443 /* Compare the profile count inequality of bb and loop's preheader, it is
444 three-state as stated in profile-count.h, FALSE is returned if inequality
445 cannot be decided. */
447 bb_colder_than_loop_preheader (basic_block bb
, class loop
*loop
)
449 gcc_assert (bb
&& loop
);
450 return bb
->count
< loop_preheader_edge (loop
)->src
->count
;
453 /* Check coldest loop between OUTERMOST_LOOP and LOOP by comparing profile
455 It does three steps check:
456 1) Check whether CURR_BB is cold in it's own loop_father, if it is cold, just
457 return NULL which means it should not be moved out at all;
458 2) CURR_BB is NOT cold, check if pre-computed COLDEST_LOOP is outside of
459 OUTERMOST_LOOP, if it is inside of OUTERMOST_LOOP, return the COLDEST_LOOP;
460 3) If COLDEST_LOOP is outside of OUTERMOST_LOOP, check whether there is a
461 hotter loop between OUTERMOST_LOOP and loop in pre-computed
462 HOTTER_THAN_INNER_LOOP, return it's nested inner loop, otherwise return
464 At last, the coldest_loop is inside of OUTERMOST_LOOP, just return it as
468 get_coldest_out_loop (class loop
*outermost_loop
, class loop
*loop
,
471 gcc_assert (outermost_loop
== loop
472 || flow_loop_nested_p (outermost_loop
, loop
));
474 /* If bb_colder_than_loop_preheader returns false due to three-state
475 comparision, OUTERMOST_LOOP is returned finally to preserve the behavior.
476 Otherwise, return the coldest loop between OUTERMOST_LOOP and LOOP. */
477 if (curr_bb
&& bb_colder_than_loop_preheader (curr_bb
, loop
))
480 class loop
*coldest_loop
= coldest_outermost_loop
[loop
->num
];
481 if (loop_depth (coldest_loop
) < loop_depth (outermost_loop
))
483 class loop
*hotter_loop
= hotter_than_inner_loop
[loop
->num
];
485 || loop_depth (hotter_loop
) < loop_depth (outermost_loop
))
486 return outermost_loop
;
488 /* hotter_loop is between OUTERMOST_LOOP and LOOP like:
489 [loop tree root, ..., coldest_loop, ..., outermost_loop, ...,
490 hotter_loop, second_coldest_loop, ..., loop]
491 return second_coldest_loop to be the hoist target. */
493 for (aloop
= hotter_loop
->inner
; aloop
; aloop
= aloop
->next
)
494 if (aloop
== loop
|| flow_loop_nested_p (aloop
, loop
))
500 /* Suppose that operand DEF is used inside the LOOP. Returns the outermost
501 loop to that we could move the expression using DEF if it did not have
502 other operands, i.e. the outermost loop enclosing LOOP in that the value
503 of DEF is invariant. */
506 outermost_invariant_loop (tree def
, class loop
*loop
)
510 class loop
*max_loop
;
511 struct lim_aux_data
*lim_data
;
514 return superloop_at_depth (loop
, 1);
516 if (TREE_CODE (def
) != SSA_NAME
)
518 gcc_assert (is_gimple_min_invariant (def
));
519 return superloop_at_depth (loop
, 1);
522 def_stmt
= SSA_NAME_DEF_STMT (def
);
523 def_bb
= gimple_bb (def_stmt
);
525 return superloop_at_depth (loop
, 1);
527 max_loop
= find_common_loop (loop
, def_bb
->loop_father
);
529 lim_data
= get_lim_data (def_stmt
);
530 if (lim_data
!= NULL
&& lim_data
->max_loop
!= NULL
)
531 max_loop
= find_common_loop (max_loop
,
532 loop_outer (lim_data
->max_loop
));
533 if (max_loop
== loop
)
535 max_loop
= superloop_at_depth (loop
, loop_depth (max_loop
) + 1);
540 /* DATA is a structure containing information associated with a statement
541 inside LOOP. DEF is one of the operands of this statement.
543 Find the outermost loop enclosing LOOP in that value of DEF is invariant
544 and record this in DATA->max_loop field. If DEF itself is defined inside
545 this loop as well (i.e. we need to hoist it out of the loop if we want
546 to hoist the statement represented by DATA), record the statement in that
547 DEF is defined to the DATA->depends list. Additionally if ADD_COST is true,
548 add the cost of the computation of DEF to the DATA->cost.
550 If DEF is not invariant in LOOP, return false. Otherwise return TRUE. */
553 add_dependency (tree def
, struct lim_aux_data
*data
, class loop
*loop
,
556 gimple
*def_stmt
= SSA_NAME_DEF_STMT (def
);
557 basic_block def_bb
= gimple_bb (def_stmt
);
558 class loop
*max_loop
;
559 struct lim_aux_data
*def_data
;
564 max_loop
= outermost_invariant_loop (def
, loop
);
568 if (flow_loop_nested_p (data
->max_loop
, max_loop
))
569 data
->max_loop
= max_loop
;
571 def_data
= get_lim_data (def_stmt
);
576 /* Only add the cost if the statement defining DEF is inside LOOP,
577 i.e. if it is likely that by moving the invariants dependent
578 on it, we will be able to avoid creating a new register for
579 it (since it will be only used in these dependent invariants). */
580 && def_bb
->loop_father
== loop
)
581 data
->cost
+= def_data
->cost
;
583 data
->depends
.safe_push (def_stmt
);
588 /* Returns an estimate for a cost of statement STMT. The values here
589 are just ad-hoc constants, similar to costs for inlining. */
592 stmt_cost (gimple
*stmt
)
594 /* Always try to create possibilities for unswitching. */
595 if (gimple_code (stmt
) == GIMPLE_COND
596 || gimple_code (stmt
) == GIMPLE_PHI
)
597 return LIM_EXPENSIVE
;
599 /* We should be hoisting calls if possible. */
600 if (is_gimple_call (stmt
))
604 /* Unless the call is a builtin_constant_p; this always folds to a
605 constant, so moving it is useless. */
606 fndecl
= gimple_call_fndecl (stmt
);
607 if (fndecl
&& fndecl_built_in_p (fndecl
, BUILT_IN_CONSTANT_P
))
610 return LIM_EXPENSIVE
;
613 /* Hoisting memory references out should almost surely be a win. */
614 if (gimple_references_memory_p (stmt
))
615 return LIM_EXPENSIVE
;
617 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
620 enum tree_code code
= gimple_assign_rhs_code (stmt
);
624 case WIDEN_MULT_EXPR
:
625 case WIDEN_MULT_PLUS_EXPR
:
626 case WIDEN_MULT_MINUS_EXPR
:
638 /* Division and multiplication are usually expensive. */
639 return LIM_EXPENSIVE
;
643 case WIDEN_LSHIFT_EXPR
:
646 /* Shifts and rotates are usually expensive. */
647 return LIM_EXPENSIVE
;
651 /* Conditionals are expensive. */
652 return LIM_EXPENSIVE
;
655 /* Make vector construction cost proportional to the number
657 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt
));
661 /* Whether or not something is wrapped inside a PAREN_EXPR
662 should not change move cost. Nor should an intermediate
663 unpropagated SSA name copy. */
667 /* Comparisons are usually expensive. */
668 if (TREE_CODE_CLASS (code
) == tcc_comparison
)
669 return LIM_EXPENSIVE
;
674 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
675 REF is independent. If REF is not independent in LOOP, NULL is returned
679 outermost_indep_loop (class loop
*outer
, class loop
*loop
, im_mem_ref
*ref
)
683 if (ref
->stored
&& bitmap_bit_p (ref
->stored
, loop
->num
))
688 aloop
= superloop_at_depth (loop
, loop_depth (aloop
) + 1))
689 if ((!ref
->stored
|| !bitmap_bit_p (ref
->stored
, aloop
->num
))
690 && ref_indep_loop_p (aloop
, ref
, lim_raw
))
693 if (ref_indep_loop_p (loop
, ref
, lim_raw
))
699 /* If there is a simple load or store to a memory reference in STMT, returns
700 the location of the memory reference, and sets IS_STORE according to whether
701 it is a store or load. Otherwise, returns NULL. */
704 simple_mem_ref_in_stmt (gimple
*stmt
, bool *is_store
)
708 /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns. */
709 if (!gimple_assign_single_p (stmt
))
712 lhs
= gimple_assign_lhs_ptr (stmt
);
713 rhs
= gimple_assign_rhs1_ptr (stmt
);
715 if (TREE_CODE (*lhs
) == SSA_NAME
&& gimple_vuse (stmt
))
720 else if (gimple_vdef (stmt
)
721 && (TREE_CODE (*rhs
) == SSA_NAME
|| is_gimple_min_invariant (*rhs
)))
730 /* From a controlling predicate in DOM determine the arguments from
731 the PHI node PHI that are chosen if the predicate evaluates to
732 true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
733 they are non-NULL. Returns true if the arguments can be determined,
734 else return false. */
737 extract_true_false_args_from_phi (basic_block dom
, gphi
*phi
,
738 tree
*true_arg_p
, tree
*false_arg_p
)
741 if (! extract_true_false_controlled_edges (dom
, gimple_bb (phi
),
746 *true_arg_p
= PHI_ARG_DEF (phi
, te
->dest_idx
);
748 *false_arg_p
= PHI_ARG_DEF (phi
, fe
->dest_idx
);
753 /* Determine the outermost loop to that it is possible to hoist a statement
754 STMT and store it to LIM_DATA (STMT)->max_loop. To do this we determine
755 the outermost loop in that the value computed by STMT is invariant.
756 If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
757 we preserve the fact whether STMT is executed. It also fills other related
758 information to LIM_DATA (STMT).
760 The function returns false if STMT cannot be hoisted outside of the loop it
761 is defined in, and true otherwise. */
764 determine_max_movement (gimple
*stmt
, bool must_preserve_exec
)
766 basic_block bb
= gimple_bb (stmt
);
767 class loop
*loop
= bb
->loop_father
;
769 struct lim_aux_data
*lim_data
= get_lim_data (stmt
);
773 if (must_preserve_exec
)
774 level
= ALWAYS_EXECUTED_IN (bb
);
776 level
= superloop_at_depth (loop
, 1);
777 lim_data
->max_loop
= get_coldest_out_loop (level
, loop
, bb
);
778 if (!lim_data
->max_loop
)
781 if (gphi
*phi
= dyn_cast
<gphi
*> (stmt
))
784 unsigned min_cost
= UINT_MAX
;
785 unsigned total_cost
= 0;
786 struct lim_aux_data
*def_data
;
788 /* We will end up promoting dependencies to be unconditionally
789 evaluated. For this reason the PHI cost (and thus the
790 cost we remove from the loop by doing the invariant motion)
791 is that of the cheapest PHI argument dependency chain. */
792 FOR_EACH_PHI_ARG (use_p
, phi
, iter
, SSA_OP_USE
)
794 val
= USE_FROM_PTR (use_p
);
796 if (TREE_CODE (val
) != SSA_NAME
)
798 /* Assign const 1 to constants. */
799 min_cost
= MIN (min_cost
, 1);
803 if (!add_dependency (val
, lim_data
, loop
, false))
806 gimple
*def_stmt
= SSA_NAME_DEF_STMT (val
);
807 if (gimple_bb (def_stmt
)
808 && gimple_bb (def_stmt
)->loop_father
== loop
)
810 def_data
= get_lim_data (def_stmt
);
813 min_cost
= MIN (min_cost
, def_data
->cost
);
814 total_cost
+= def_data
->cost
;
819 min_cost
= MIN (min_cost
, total_cost
);
820 lim_data
->cost
+= min_cost
;
822 if (gimple_phi_num_args (phi
) > 1)
824 basic_block dom
= get_immediate_dominator (CDI_DOMINATORS
, bb
);
826 if (gsi_end_p (gsi_last_bb (dom
)))
828 cond
= gsi_stmt (gsi_last_bb (dom
));
829 if (gimple_code (cond
) != GIMPLE_COND
)
831 /* Verify that this is an extended form of a diamond and
832 the PHI arguments are completely controlled by the
834 if (!extract_true_false_args_from_phi (dom
, phi
, NULL
, NULL
))
837 /* Fold in dependencies and cost of the condition. */
838 FOR_EACH_SSA_TREE_OPERAND (val
, cond
, iter
, SSA_OP_USE
)
840 if (!add_dependency (val
, lim_data
, loop
, false))
842 def_data
= get_lim_data (SSA_NAME_DEF_STMT (val
));
844 lim_data
->cost
+= def_data
->cost
;
847 /* We want to avoid unconditionally executing very expensive
848 operations. As costs for our dependencies cannot be
849 negative just claim we are not invariand for this case.
850 We also are not sure whether the control-flow inside the
852 if (total_cost
- min_cost
>= 2 * LIM_EXPENSIVE
854 && total_cost
/ min_cost
<= 2))
857 /* Assume that the control-flow in the loop will vanish.
858 ??? We should verify this and not artificially increase
859 the cost if that is not the case. */
860 lim_data
->cost
+= stmt_cost (stmt
);
866 /* A stmt that receives abnormal edges cannot be hoisted. */
867 if (is_a
<gcall
*> (stmt
)
868 && (gimple_call_flags (stmt
) & ECF_RETURNS_TWICE
))
871 FOR_EACH_SSA_TREE_OPERAND (val
, stmt
, iter
, SSA_OP_USE
)
872 if (!add_dependency (val
, lim_data
, loop
, true))
875 if (gimple_vuse (stmt
))
878 = lim_data
? memory_accesses
.refs_list
[lim_data
->ref
] : NULL
;
880 && MEM_ANALYZABLE (ref
))
882 lim_data
->max_loop
= outermost_indep_loop (lim_data
->max_loop
,
884 if (!lim_data
->max_loop
)
887 else if (! add_dependency (gimple_vuse (stmt
), lim_data
, loop
, false))
891 lim_data
->cost
+= stmt_cost (stmt
);
896 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
897 and that one of the operands of this statement is computed by STMT.
898 Ensure that STMT (together with all the statements that define its
899 operands) is hoisted at least out of the loop LEVEL. */
902 set_level (gimple
*stmt
, class loop
*orig_loop
, class loop
*level
)
904 class loop
*stmt_loop
= gimple_bb (stmt
)->loop_father
;
905 struct lim_aux_data
*lim_data
;
909 stmt_loop
= find_common_loop (orig_loop
, stmt_loop
);
910 lim_data
= get_lim_data (stmt
);
911 if (lim_data
!= NULL
&& lim_data
->tgt_loop
!= NULL
)
912 stmt_loop
= find_common_loop (stmt_loop
,
913 loop_outer (lim_data
->tgt_loop
));
914 if (flow_loop_nested_p (stmt_loop
, level
))
917 gcc_assert (level
== lim_data
->max_loop
918 || flow_loop_nested_p (lim_data
->max_loop
, level
));
920 lim_data
->tgt_loop
= level
;
921 FOR_EACH_VEC_ELT (lim_data
->depends
, i
, dep_stmt
)
922 set_level (dep_stmt
, orig_loop
, level
);
925 /* Determines an outermost loop from that we want to hoist the statement STMT.
926 For now we chose the outermost possible loop. TODO -- use profiling
927 information to set it more sanely. */
930 set_profitable_level (gimple
*stmt
)
932 set_level (stmt
, gimple_bb (stmt
)->loop_father
, get_lim_data (stmt
)->max_loop
);
935 /* Returns true if STMT is a call that has side effects. */
938 nonpure_call_p (gimple
*stmt
)
940 if (gimple_code (stmt
) != GIMPLE_CALL
)
943 return gimple_has_side_effects (stmt
);
946 /* Rewrite a/b to a*(1/b). Return the invariant stmt to process. */
949 rewrite_reciprocal (gimple_stmt_iterator
*bsi
)
951 gassign
*stmt
, *stmt1
, *stmt2
;
952 tree name
, lhs
, type
;
954 gimple_stmt_iterator gsi
;
956 stmt
= as_a
<gassign
*> (gsi_stmt (*bsi
));
957 lhs
= gimple_assign_lhs (stmt
);
958 type
= TREE_TYPE (lhs
);
960 real_one
= build_one_cst (type
);
962 name
= make_temp_ssa_name (type
, NULL
, "reciptmp");
963 stmt1
= gimple_build_assign (name
, RDIV_EXPR
, real_one
,
964 gimple_assign_rhs2 (stmt
));
965 stmt2
= gimple_build_assign (lhs
, MULT_EXPR
, name
,
966 gimple_assign_rhs1 (stmt
));
968 /* Replace division stmt with reciprocal and multiply stmts.
969 The multiply stmt is not invariant, so update iterator
970 and avoid rescanning. */
972 gsi_insert_before (bsi
, stmt1
, GSI_NEW_STMT
);
973 gsi_replace (&gsi
, stmt2
, true);
975 /* Continue processing with invariant reciprocal statement. */
979 /* Check if the pattern at *BSI is a bittest of the form
980 (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0. */
983 rewrite_bittest (gimple_stmt_iterator
*bsi
)
990 tree lhs
, name
, t
, a
, b
;
993 stmt
= as_a
<gassign
*> (gsi_stmt (*bsi
));
994 lhs
= gimple_assign_lhs (stmt
);
996 /* Verify that the single use of lhs is a comparison against zero. */
997 if (TREE_CODE (lhs
) != SSA_NAME
998 || !single_imm_use (lhs
, &use
, &use_stmt
))
1000 cond_stmt
= dyn_cast
<gcond
*> (use_stmt
);
1003 if (gimple_cond_lhs (cond_stmt
) != lhs
1004 || (gimple_cond_code (cond_stmt
) != NE_EXPR
1005 && gimple_cond_code (cond_stmt
) != EQ_EXPR
)
1006 || !integer_zerop (gimple_cond_rhs (cond_stmt
)))
1009 /* Get at the operands of the shift. The rhs is TMP1 & 1. */
1010 stmt1
= SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt
));
1011 if (gimple_code (stmt1
) != GIMPLE_ASSIGN
)
1014 /* There is a conversion in between possibly inserted by fold. */
1015 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1
)))
1017 t
= gimple_assign_rhs1 (stmt1
);
1018 if (TREE_CODE (t
) != SSA_NAME
1019 || !has_single_use (t
))
1021 stmt1
= SSA_NAME_DEF_STMT (t
);
1022 if (gimple_code (stmt1
) != GIMPLE_ASSIGN
)
1026 /* Verify that B is loop invariant but A is not. Verify that with
1027 all the stmt walking we are still in the same loop. */
1028 if (gimple_assign_rhs_code (stmt1
) != RSHIFT_EXPR
1029 || loop_containing_stmt (stmt1
) != loop_containing_stmt (stmt
))
1032 a
= gimple_assign_rhs1 (stmt1
);
1033 b
= gimple_assign_rhs2 (stmt1
);
1035 if (outermost_invariant_loop (b
, loop_containing_stmt (stmt1
)) != NULL
1036 && outermost_invariant_loop (a
, loop_containing_stmt (stmt1
)) == NULL
)
1038 gimple_stmt_iterator rsi
;
1041 t
= fold_build2 (LSHIFT_EXPR
, TREE_TYPE (a
),
1042 build_int_cst (TREE_TYPE (a
), 1), b
);
1043 name
= make_temp_ssa_name (TREE_TYPE (a
), NULL
, "shifttmp");
1044 stmt1
= gimple_build_assign (name
, t
);
1047 t
= fold_build2 (BIT_AND_EXPR
, TREE_TYPE (a
), a
, name
);
1048 name
= make_temp_ssa_name (TREE_TYPE (a
), NULL
, "shifttmp");
1049 stmt2
= gimple_build_assign (name
, t
);
1051 /* Replace the SSA_NAME we compare against zero. Adjust
1052 the type of zero accordingly. */
1053 SET_USE (use
, name
);
1054 gimple_cond_set_rhs (cond_stmt
,
1055 build_int_cst_type (TREE_TYPE (name
),
1058 /* Don't use gsi_replace here, none of the new assignments sets
1059 the variable originally set in stmt. Move bsi to stmt1, and
1060 then remove the original stmt, so that we get a chance to
1061 retain debug info for it. */
1063 gsi_insert_before (bsi
, stmt1
, GSI_NEW_STMT
);
1064 gsi_insert_before (&rsi
, stmt2
, GSI_SAME_STMT
);
1065 gimple
*to_release
= gsi_stmt (rsi
);
1066 gsi_remove (&rsi
, true);
1067 release_defs (to_release
);
1075 /* Determine the outermost loops in that statements in basic block BB are
1076 invariant, and record them to the LIM_DATA associated with the
1080 compute_invariantness (basic_block bb
)
1083 gimple_stmt_iterator bsi
;
1085 bool maybe_never
= ALWAYS_EXECUTED_IN (bb
) == NULL
;
1086 class loop
*outermost
= ALWAYS_EXECUTED_IN (bb
);
1087 struct lim_aux_data
*lim_data
;
1089 if (!loop_outer (bb
->loop_father
))
1092 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1093 fprintf (dump_file
, "Basic block %d (loop %d -- depth %d):\n\n",
1094 bb
->index
, bb
->loop_father
->num
, loop_depth (bb
->loop_father
));
1096 /* Look at PHI nodes, but only if there is at most two.
1097 ??? We could relax this further by post-processing the inserted
1098 code and transforming adjacent cond-exprs with the same predicate
1099 to control flow again. */
1100 bsi
= gsi_start_phis (bb
);
1101 if (!gsi_end_p (bsi
)
1102 && ((gsi_next (&bsi
), gsi_end_p (bsi
))
1103 || (gsi_next (&bsi
), gsi_end_p (bsi
))))
1104 for (bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
1106 stmt
= gsi_stmt (bsi
);
1108 pos
= movement_possibility (stmt
);
1109 if (pos
== MOVE_IMPOSSIBLE
)
1112 lim_data
= get_lim_data (stmt
);
1114 lim_data
= init_lim_data (stmt
);
1115 lim_data
->always_executed_in
= outermost
;
1117 if (!determine_max_movement (stmt
, false))
1119 lim_data
->max_loop
= NULL
;
1123 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1125 print_gimple_stmt (dump_file
, stmt
, 2);
1126 fprintf (dump_file
, " invariant up to level %d, cost %d.\n\n",
1127 loop_depth (lim_data
->max_loop
),
1131 if (lim_data
->cost
>= LIM_EXPENSIVE
)
1132 set_profitable_level (stmt
);
1135 for (bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
1137 stmt
= gsi_stmt (bsi
);
1139 pos
= movement_possibility (stmt
);
1140 if (pos
== MOVE_IMPOSSIBLE
)
1142 if (nonpure_call_p (stmt
))
1147 /* Make sure to note always_executed_in for stores to make
1148 store-motion work. */
1149 else if (stmt_makes_single_store (stmt
))
1151 struct lim_aux_data
*lim_data
= get_lim_data (stmt
);
1153 lim_data
= init_lim_data (stmt
);
1154 lim_data
->always_executed_in
= outermost
;
1159 if (is_gimple_assign (stmt
)
1160 && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt
))
1161 == GIMPLE_BINARY_RHS
))
1163 tree op0
= gimple_assign_rhs1 (stmt
);
1164 tree op1
= gimple_assign_rhs2 (stmt
);
1165 class loop
*ol1
= outermost_invariant_loop (op1
,
1166 loop_containing_stmt (stmt
));
1168 /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1169 to be hoisted out of loop, saving expensive divide. */
1170 if (pos
== MOVE_POSSIBLE
1171 && gimple_assign_rhs_code (stmt
) == RDIV_EXPR
1172 && flag_unsafe_math_optimizations
1173 && !flag_trapping_math
1175 && outermost_invariant_loop (op0
, ol1
) == NULL
)
1176 stmt
= rewrite_reciprocal (&bsi
);
1178 /* If the shift count is invariant, convert (A >> B) & 1 to
1179 A & (1 << B) allowing the bit mask to be hoisted out of the loop
1180 saving an expensive shift. */
1181 if (pos
== MOVE_POSSIBLE
1182 && gimple_assign_rhs_code (stmt
) == BIT_AND_EXPR
1183 && integer_onep (op1
)
1184 && TREE_CODE (op0
) == SSA_NAME
1185 && has_single_use (op0
))
1186 stmt
= rewrite_bittest (&bsi
);
1189 lim_data
= get_lim_data (stmt
);
1191 lim_data
= init_lim_data (stmt
);
1192 lim_data
->always_executed_in
= outermost
;
1194 if (maybe_never
&& pos
== MOVE_PRESERVE_EXECUTION
)
1197 if (!determine_max_movement (stmt
, pos
== MOVE_PRESERVE_EXECUTION
))
1199 lim_data
->max_loop
= NULL
;
1203 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1205 print_gimple_stmt (dump_file
, stmt
, 2);
1206 fprintf (dump_file
, " invariant up to level %d, cost %d.\n\n",
1207 loop_depth (lim_data
->max_loop
),
1211 if (lim_data
->cost
>= LIM_EXPENSIVE
)
1212 set_profitable_level (stmt
);
1216 /* Hoist the statements in basic block BB out of the loops prescribed by
1217 data stored in LIM_DATA structures associated with each statement. Callback
1218 for walk_dominator_tree. */
1221 move_computations_worker (basic_block bb
)
1225 struct lim_aux_data
*lim_data
;
1226 unsigned int todo
= 0;
1228 if (!loop_outer (bb
->loop_father
))
1231 for (gphi_iterator bsi
= gsi_start_phis (bb
); !gsi_end_p (bsi
); )
1234 gphi
*stmt
= bsi
.phi ();
1236 lim_data
= get_lim_data (stmt
);
1237 if (lim_data
== NULL
)
1243 cost
= lim_data
->cost
;
1244 level
= lim_data
->tgt_loop
;
1245 clear_lim_data (stmt
);
1253 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1255 fprintf (dump_file
, "Moving PHI node\n");
1256 print_gimple_stmt (dump_file
, stmt
, 0);
1257 fprintf (dump_file
, "(cost %u) out of loop %d.\n\n",
1261 if (gimple_phi_num_args (stmt
) == 1)
1263 tree arg
= PHI_ARG_DEF (stmt
, 0);
1264 new_stmt
= gimple_build_assign (gimple_phi_result (stmt
),
1265 TREE_CODE (arg
), arg
);
1269 basic_block dom
= get_immediate_dominator (CDI_DOMINATORS
, bb
);
1270 gimple
*cond
= gsi_stmt (gsi_last_bb (dom
));
1271 tree arg0
= NULL_TREE
, arg1
= NULL_TREE
, t
;
1272 /* Get the PHI arguments corresponding to the true and false
1274 extract_true_false_args_from_phi (dom
, stmt
, &arg0
, &arg1
);
1275 gcc_assert (arg0
&& arg1
);
1276 t
= make_ssa_name (boolean_type_node
);
1277 new_stmt
= gimple_build_assign (t
, gimple_cond_code (cond
),
1278 gimple_cond_lhs (cond
),
1279 gimple_cond_rhs (cond
));
1280 gsi_insert_on_edge (loop_preheader_edge (level
), new_stmt
);
1281 new_stmt
= gimple_build_assign (gimple_phi_result (stmt
),
1282 COND_EXPR
, t
, arg0
, arg1
);
1283 todo
|= TODO_cleanup_cfg
;
1285 if (!ALWAYS_EXECUTED_IN (bb
)
1286 || (ALWAYS_EXECUTED_IN (bb
) != level
1287 && !flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb
), level
)))
1288 reset_flow_sensitive_info (gimple_assign_lhs (new_stmt
));
1289 gsi_insert_on_edge (loop_preheader_edge (level
), new_stmt
);
1290 remove_phi_node (&bsi
, false);
1293 for (gimple_stmt_iterator bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); )
1297 gimple
*stmt
= gsi_stmt (bsi
);
1299 lim_data
= get_lim_data (stmt
);
1300 if (lim_data
== NULL
)
1306 cost
= lim_data
->cost
;
1307 level
= lim_data
->tgt_loop
;
1308 clear_lim_data (stmt
);
1316 /* We do not really want to move conditionals out of the loop; we just
1317 placed it here to force its operands to be moved if necessary. */
1318 if (gimple_code (stmt
) == GIMPLE_COND
)
1324 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1326 fprintf (dump_file
, "Moving statement\n");
1327 print_gimple_stmt (dump_file
, stmt
, 0);
1328 fprintf (dump_file
, "(cost %u) out of loop %d.\n\n",
1332 e
= loop_preheader_edge (level
);
1333 gcc_assert (!gimple_vdef (stmt
));
1334 if (gimple_vuse (stmt
))
1336 /* The new VUSE is the one from the virtual PHI in the loop
1337 header or the one already present. */
1339 for (gsi2
= gsi_start_phis (e
->dest
);
1340 !gsi_end_p (gsi2
); gsi_next (&gsi2
))
1342 gphi
*phi
= gsi2
.phi ();
1343 if (virtual_operand_p (gimple_phi_result (phi
)))
1345 SET_USE (gimple_vuse_op (stmt
),
1346 PHI_ARG_DEF_FROM_EDGE (phi
, e
));
1351 gsi_remove (&bsi
, false);
1352 if (gimple_has_lhs (stmt
)
1353 && TREE_CODE (gimple_get_lhs (stmt
)) == SSA_NAME
1354 && (!ALWAYS_EXECUTED_IN (bb
)
1355 || !(ALWAYS_EXECUTED_IN (bb
) == level
1356 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb
), level
))))
1357 reset_flow_sensitive_info (gimple_get_lhs (stmt
));
1358 /* In case this is a stmt that is not unconditionally executed
1359 when the target loop header is executed and the stmt may
1360 invoke undefined integer or pointer overflow rewrite it to
1361 unsigned arithmetic. */
1362 if (is_gimple_assign (stmt
)
1363 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt
)))
1364 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (gimple_assign_lhs (stmt
)))
1365 && arith_code_with_undefined_signed_overflow
1366 (gimple_assign_rhs_code (stmt
))
1367 && (!ALWAYS_EXECUTED_IN (bb
)
1368 || !(ALWAYS_EXECUTED_IN (bb
) == level
1369 || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb
), level
))))
1370 gsi_insert_seq_on_edge (e
, rewrite_to_defined_overflow (stmt
));
1372 gsi_insert_on_edge (e
, stmt
);
1378 /* Checks whether the statement defining variable *INDEX can be hoisted
1379 out of the loop passed in DATA. Callback for for_each_index. */
1382 may_move_till (tree ref
, tree
*index
, void *data
)
1384 class loop
*loop
= (class loop
*) data
, *max_loop
;
1386 /* If REF is an array reference, check also that the step and the lower
1387 bound is invariant in LOOP. */
1388 if (TREE_CODE (ref
) == ARRAY_REF
)
1390 tree step
= TREE_OPERAND (ref
, 3);
1391 tree lbound
= TREE_OPERAND (ref
, 2);
1393 max_loop
= outermost_invariant_loop (step
, loop
);
1397 max_loop
= outermost_invariant_loop (lbound
, loop
);
1402 max_loop
= outermost_invariant_loop (*index
, loop
);
1409 /* If OP is SSA NAME, force the statement that defines it to be
1410 moved out of the LOOP. ORIG_LOOP is the loop in that EXPR is used. */
1413 force_move_till_op (tree op
, class loop
*orig_loop
, class loop
*loop
)
1418 || is_gimple_min_invariant (op
))
1421 gcc_assert (TREE_CODE (op
) == SSA_NAME
);
1423 stmt
= SSA_NAME_DEF_STMT (op
);
1424 if (gimple_nop_p (stmt
))
1427 set_level (stmt
, orig_loop
, loop
);
1430 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1431 the LOOP. The reference REF is used in the loop ORIG_LOOP. Callback for
1437 class loop
*orig_loop
;
1441 force_move_till (tree ref
, tree
*index
, void *data
)
1443 struct fmt_data
*fmt_data
= (struct fmt_data
*) data
;
1445 if (TREE_CODE (ref
) == ARRAY_REF
)
1447 tree step
= TREE_OPERAND (ref
, 3);
1448 tree lbound
= TREE_OPERAND (ref
, 2);
1450 force_move_till_op (step
, fmt_data
->orig_loop
, fmt_data
->loop
);
1451 force_move_till_op (lbound
, fmt_data
->orig_loop
, fmt_data
->loop
);
1454 force_move_till_op (*index
, fmt_data
->orig_loop
, fmt_data
->loop
);
1459 /* A function to free the mem_ref object OBJ. */
1462 memref_free (class im_mem_ref
*mem
)
1464 mem
->accesses_in_loop
.release ();
1467 /* Allocates and returns a memory reference description for MEM whose hash
1468 value is HASH and id is ID. */
1471 mem_ref_alloc (ao_ref
*mem
, unsigned hash
, unsigned id
)
1473 im_mem_ref
*ref
= XOBNEW (&mem_ref_obstack
, class im_mem_ref
);
1477 ao_ref_init (&ref
->mem
, error_mark_node
);
1479 ref
->ref_canonical
= false;
1480 ref
->ref_decomposed
= false;
1484 bitmap_initialize (&ref
->dep_loop
, &lim_bitmap_obstack
);
1485 ref
->accesses_in_loop
.create (1);
1490 /* Records memory reference location *LOC in LOOP to the memory reference
1491 description REF. The reference occurs in statement STMT. */
1494 record_mem_ref_loc (im_mem_ref
*ref
, gimple
*stmt
, tree
*loc
)
1499 ref
->accesses_in_loop
.safe_push (aref
);
1502 /* Set the LOOP bit in REF stored bitmap and allocate that if
1503 necessary. Return whether a bit was changed. */
1506 set_ref_stored_in_loop (im_mem_ref
*ref
, class loop
*loop
)
1509 ref
->stored
= BITMAP_ALLOC (&lim_bitmap_obstack
);
1510 return bitmap_set_bit (ref
->stored
, loop
->num
);
1513 /* Marks reference REF as stored in LOOP. */
1516 mark_ref_stored (im_mem_ref
*ref
, class loop
*loop
)
1518 while (loop
!= current_loops
->tree_root
1519 && set_ref_stored_in_loop (ref
, loop
))
1520 loop
= loop_outer (loop
);
1523 /* Set the LOOP bit in REF loaded bitmap and allocate that if
1524 necessary. Return whether a bit was changed. */
1527 set_ref_loaded_in_loop (im_mem_ref
*ref
, class loop
*loop
)
1530 ref
->loaded
= BITMAP_ALLOC (&lim_bitmap_obstack
);
1531 return bitmap_set_bit (ref
->loaded
, loop
->num
);
1534 /* Marks reference REF as loaded in LOOP. */
1537 mark_ref_loaded (im_mem_ref
*ref
, class loop
*loop
)
1539 while (loop
!= current_loops
->tree_root
1540 && set_ref_loaded_in_loop (ref
, loop
))
1541 loop
= loop_outer (loop
);
1544 /* Gathers memory references in statement STMT in LOOP, storing the
1545 information about them in the memory_accesses structure. Marks
1546 the vops accessed through unrecognized statements there as
1550 gather_mem_refs_stmt (class loop
*loop
, gimple
*stmt
)
1559 if (!gimple_vuse (stmt
))
1562 mem
= simple_mem_ref_in_stmt (stmt
, &is_stored
);
1563 if (!mem
&& is_gimple_assign (stmt
))
1565 /* For aggregate copies record distinct references but use them
1566 only for disambiguation purposes. */
1567 id
= memory_accesses
.refs_list
.length ();
1568 ref
= mem_ref_alloc (NULL
, 0, id
);
1569 memory_accesses
.refs_list
.safe_push (ref
);
1570 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1572 fprintf (dump_file
, "Unhandled memory reference %u: ", id
);
1573 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
1575 record_mem_ref_loc (ref
, stmt
, mem
);
1576 is_stored
= gimple_vdef (stmt
);
1580 /* We use the shared mem_ref for all unanalyzable refs. */
1581 id
= UNANALYZABLE_MEM_ID
;
1582 ref
= memory_accesses
.refs_list
[id
];
1583 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1585 fprintf (dump_file
, "Unanalyzed memory reference %u: ", id
);
1586 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
1588 is_stored
= gimple_vdef (stmt
);
1592 /* We are looking for equal refs that might differ in structure
1593 such as a.b vs. MEM[&a + 4]. So we key off the ao_ref but
1594 make sure we can canonicalize the ref in the hashtable if
1595 non-operand_equal_p refs are found. For the lookup we mark
1596 the case we want strict equality with aor.max_size == -1. */
1598 ao_ref_init (&aor
, *mem
);
1600 ao_ref_alias_set (&aor
);
1601 HOST_WIDE_INT offset
, size
, max_size
;
1602 poly_int64 saved_maxsize
= aor
.max_size
, mem_off
;
1604 bool ref_decomposed
;
1605 if (aor
.max_size_known_p ()
1606 && aor
.offset
.is_constant (&offset
)
1607 && aor
.size
.is_constant (&size
)
1608 && aor
.max_size
.is_constant (&max_size
)
1610 && (size
% BITS_PER_UNIT
) == 0
1611 /* We're canonicalizing to a MEM where TYPE_SIZE specifies the
1612 size. Make sure this is consistent with the extraction. */
1613 && poly_int_tree_p (TYPE_SIZE (TREE_TYPE (*mem
)))
1614 && known_eq (wi::to_poly_offset (TYPE_SIZE (TREE_TYPE (*mem
))),
1616 && (mem_base
= get_addr_base_and_unit_offset (aor
.ref
, &mem_off
)))
1618 ref_decomposed
= true;
1619 tree base
= ao_ref_base (&aor
);
1621 HOST_WIDE_INT mcoffset
;
1622 if (TREE_CODE (base
) == MEM_REF
1623 && (mem_ref_offset (base
) * BITS_PER_UNIT
+ offset
).to_shwi (&moffset
)
1624 && moffset
.is_constant (&mcoffset
))
1626 hash
= iterative_hash_expr (TREE_OPERAND (base
, 0), 0);
1627 hash
= iterative_hash_host_wide_int (mcoffset
, hash
);
1631 hash
= iterative_hash_expr (base
, 0);
1632 hash
= iterative_hash_host_wide_int (offset
, hash
);
1634 hash
= iterative_hash_host_wide_int (size
, hash
);
1638 ref_decomposed
= false;
1639 hash
= iterative_hash_expr (aor
.ref
, 0);
1642 slot
= memory_accesses
.refs
->find_slot_with_hash (&aor
, hash
, INSERT
);
1643 aor
.max_size
= saved_maxsize
;
1646 if (!(*slot
)->ref_canonical
1647 && !operand_equal_p (*mem
, (*slot
)->mem
.ref
, 0))
1649 /* If we didn't yet canonicalize the hashtable ref (which
1650 we'll end up using for code insertion) and hit a second
1651 equal ref that is not structurally equivalent create
1652 a canonical ref which is a bare MEM_REF. */
1653 if (TREE_CODE (*mem
) == MEM_REF
1654 || TREE_CODE (*mem
) == TARGET_MEM_REF
)
1656 (*slot
)->mem
.ref
= *mem
;
1657 (*slot
)->mem
.base_alias_set
= ao_ref_base_alias_set (&aor
);
1661 tree ref_alias_type
= reference_alias_ptr_type (*mem
);
1662 unsigned int ref_align
= get_object_alignment (*mem
);
1663 tree ref_type
= TREE_TYPE (*mem
);
1664 tree tmp
= build1 (ADDR_EXPR
, ptr_type_node
,
1665 unshare_expr (mem_base
));
1666 if (TYPE_ALIGN (ref_type
) != ref_align
)
1667 ref_type
= build_aligned_type (ref_type
, ref_align
);
1669 = fold_build2 (MEM_REF
, ref_type
, tmp
,
1670 build_int_cst (ref_alias_type
, mem_off
));
1671 if ((*slot
)->mem
.volatile_p
)
1672 TREE_THIS_VOLATILE (new_ref
) = 1;
1673 (*slot
)->mem
.ref
= new_ref
;
1674 /* Make sure the recorded base and offset are consistent
1675 with the newly built ref. */
1676 if (TREE_CODE (TREE_OPERAND (new_ref
, 0)) == ADDR_EXPR
)
1680 (*slot
)->mem
.base
= new_ref
;
1681 (*slot
)->mem
.offset
= 0;
1683 gcc_checking_assert (TREE_CODE ((*slot
)->mem
.ref
) == MEM_REF
1684 && is_gimple_mem_ref_addr
1685 (TREE_OPERAND ((*slot
)->mem
.ref
,
1687 (*slot
)->mem
.base_alias_set
= (*slot
)->mem
.ref_alias_set
;
1689 (*slot
)->ref_canonical
= true;
1696 id
= memory_accesses
.refs_list
.length ();
1697 ref
= mem_ref_alloc (&aor
, hash
, id
);
1698 ref
->ref_decomposed
= ref_decomposed
;
1699 memory_accesses
.refs_list
.safe_push (ref
);
1702 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1704 fprintf (dump_file
, "Memory reference %u: ", id
);
1705 print_generic_expr (dump_file
, ref
->mem
.ref
, TDF_SLIM
);
1706 fprintf (dump_file
, "\n");
1710 record_mem_ref_loc (ref
, stmt
, mem
);
1714 bitmap_set_bit (&memory_accesses
.refs_stored_in_loop
[loop
->num
], ref
->id
);
1715 mark_ref_stored (ref
, loop
);
1717 /* A not simple memory op is also a read when it is a write. */
1718 if (!is_stored
|| id
== UNANALYZABLE_MEM_ID
1719 || ref
->mem
.ref
== error_mark_node
)
1721 bitmap_set_bit (&memory_accesses
.refs_loaded_in_loop
[loop
->num
], ref
->id
);
1722 mark_ref_loaded (ref
, loop
);
1724 init_lim_data (stmt
)->ref
= ref
->id
;
1728 static unsigned *bb_loop_postorder
;
1730 /* qsort sort function to sort blocks after their loop fathers postorder. */
1733 sort_bbs_in_loop_postorder_cmp (const void *bb1_
, const void *bb2_
,
1734 void *bb_loop_postorder_
)
1736 unsigned *bb_loop_postorder
= (unsigned *)bb_loop_postorder_
;
1737 basic_block bb1
= *(const basic_block
*)bb1_
;
1738 basic_block bb2
= *(const basic_block
*)bb2_
;
1739 class loop
*loop1
= bb1
->loop_father
;
1740 class loop
*loop2
= bb2
->loop_father
;
1741 if (loop1
->num
== loop2
->num
)
1742 return bb1
->index
- bb2
->index
;
1743 return bb_loop_postorder
[loop1
->num
] < bb_loop_postorder
[loop2
->num
] ? -1 : 1;
1746 /* qsort sort function to sort ref locs after their loop fathers postorder. */
1749 sort_locs_in_loop_postorder_cmp (const void *loc1_
, const void *loc2_
,
1750 void *bb_loop_postorder_
)
1752 unsigned *bb_loop_postorder
= (unsigned *)bb_loop_postorder_
;
1753 const mem_ref_loc
*loc1
= (const mem_ref_loc
*)loc1_
;
1754 const mem_ref_loc
*loc2
= (const mem_ref_loc
*)loc2_
;
1755 class loop
*loop1
= gimple_bb (loc1
->stmt
)->loop_father
;
1756 class loop
*loop2
= gimple_bb (loc2
->stmt
)->loop_father
;
1757 if (loop1
->num
== loop2
->num
)
1759 return bb_loop_postorder
[loop1
->num
] < bb_loop_postorder
[loop2
->num
] ? -1 : 1;
1762 /* Gathers memory references in loops. */
1765 analyze_memory_references (bool store_motion
)
1767 gimple_stmt_iterator bsi
;
1768 basic_block bb
, *bbs
;
1772 /* Collect all basic-blocks in loops and sort them after their
1775 bbs
= XNEWVEC (basic_block
, n_basic_blocks_for_fn (cfun
) - NUM_FIXED_BLOCKS
);
1776 FOR_EACH_BB_FN (bb
, cfun
)
1777 if (bb
->loop_father
!= current_loops
->tree_root
)
1780 gcc_sort_r (bbs
, n
, sizeof (basic_block
), sort_bbs_in_loop_postorder_cmp
,
1783 /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
1784 That results in better locality for all the bitmaps. It also
1785 automatically sorts the location list of gathered memory references
1786 after their loop postorder number allowing to binary-search it. */
1787 for (i
= 0; i
< n
; ++i
)
1789 basic_block bb
= bbs
[i
];
1790 for (bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
1791 gather_mem_refs_stmt (bb
->loop_father
, gsi_stmt (bsi
));
1794 /* Verify the list of gathered memory references is sorted after their
1795 loop postorder number. */
1799 FOR_EACH_VEC_ELT (memory_accesses
.refs_list
, i
, ref
)
1800 for (unsigned j
= 1; j
< ref
->accesses_in_loop
.length (); ++j
)
1801 gcc_assert (sort_locs_in_loop_postorder_cmp
1802 (&ref
->accesses_in_loop
[j
-1], &ref
->accesses_in_loop
[j
],
1803 bb_loop_postorder
) <= 0);
1811 /* Propagate the information about accessed memory references up
1812 the loop hierarchy. */
1813 for (auto loop
: loops_list (cfun
, LI_FROM_INNERMOST
))
1815 /* Finalize the overall touched references (including subloops). */
1816 bitmap_ior_into (&memory_accesses
.all_refs_stored_in_loop
[loop
->num
],
1817 &memory_accesses
.refs_stored_in_loop
[loop
->num
]);
1819 /* Propagate the information about accessed memory references up
1820 the loop hierarchy. */
1821 outer
= loop_outer (loop
);
1822 if (outer
== current_loops
->tree_root
)
1825 bitmap_ior_into (&memory_accesses
.all_refs_stored_in_loop
[outer
->num
],
1826 &memory_accesses
.all_refs_stored_in_loop
[loop
->num
]);
1830 /* Returns true if MEM1 and MEM2 may alias. TTAE_CACHE is used as a cache in
1831 tree_to_aff_combination_expand. */
1834 mem_refs_may_alias_p (im_mem_ref
*mem1
, im_mem_ref
*mem2
,
1835 hash_map
<tree
, name_expansion
*> **ttae_cache
,
1838 gcc_checking_assert (mem1
->mem
.ref
!= error_mark_node
1839 && mem2
->mem
.ref
!= error_mark_node
);
1841 /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1842 object and their offset differ in such a way that the locations cannot
1843 overlap, then they cannot alias. */
1844 poly_widest_int size1
, size2
;
1845 aff_tree off1
, off2
;
1847 /* Perform basic offset and type-based disambiguation. */
1848 if (!refs_may_alias_p_1 (&mem1
->mem
, &mem2
->mem
, tbaa_p
))
1851 /* The expansion of addresses may be a bit expensive, thus we only do
1852 the check at -O2 and higher optimization levels. */
1856 get_inner_reference_aff (mem1
->mem
.ref
, &off1
, &size1
);
1857 get_inner_reference_aff (mem2
->mem
.ref
, &off2
, &size2
);
1858 aff_combination_expand (&off1
, ttae_cache
);
1859 aff_combination_expand (&off2
, ttae_cache
);
1860 aff_combination_scale (&off1
, -1);
1861 aff_combination_add (&off2
, &off1
);
1863 if (aff_comb_cannot_overlap_p (&off2
, size1
, size2
))
1869 /* Compare function for bsearch searching for reference locations
1873 find_ref_loc_in_loop_cmp (const void *loop_
, const void *loc_
,
1874 void *bb_loop_postorder_
)
1876 unsigned *bb_loop_postorder
= (unsigned *)bb_loop_postorder_
;
1877 class loop
*loop
= (class loop
*)const_cast<void *>(loop_
);
1878 mem_ref_loc
*loc
= (mem_ref_loc
*)const_cast<void *>(loc_
);
1879 class loop
*loc_loop
= gimple_bb (loc
->stmt
)->loop_father
;
1880 if (loop
->num
== loc_loop
->num
1881 || flow_loop_nested_p (loop
, loc_loop
))
1883 return (bb_loop_postorder
[loop
->num
] < bb_loop_postorder
[loc_loop
->num
]
1887 /* Iterates over all locations of REF in LOOP and its subloops calling
1888 fn.operator() with the location as argument. When that operator
1889 returns true the iteration is stopped and true is returned.
1890 Otherwise false is returned. */
1892 template <typename FN
>
1894 for_all_locs_in_loop (class loop
*loop
, im_mem_ref
*ref
, FN fn
)
1899 /* Search for the cluster of locs in the accesses_in_loop vector
1900 which is sorted after postorder index of the loop father. */
1901 loc
= ref
->accesses_in_loop
.bsearch (loop
, find_ref_loc_in_loop_cmp
,
1906 /* We have found one location inside loop or its sub-loops. Iterate
1907 both forward and backward to cover the whole cluster. */
1908 i
= loc
- ref
->accesses_in_loop
.address ();
1912 mem_ref_loc
*l
= &ref
->accesses_in_loop
[i
];
1913 if (!flow_bb_inside_loop_p (loop
, gimple_bb (l
->stmt
)))
1918 for (i
= loc
- ref
->accesses_in_loop
.address ();
1919 i
< ref
->accesses_in_loop
.length (); ++i
)
1921 mem_ref_loc
*l
= &ref
->accesses_in_loop
[i
];
1922 if (!flow_bb_inside_loop_p (loop
, gimple_bb (l
->stmt
)))
1931 /* Rewrites location LOC by TMP_VAR. */
1933 class rewrite_mem_ref_loc
1936 rewrite_mem_ref_loc (tree tmp_var_
) : tmp_var (tmp_var_
) {}
1937 bool operator () (mem_ref_loc
*loc
);
1942 rewrite_mem_ref_loc::operator () (mem_ref_loc
*loc
)
1944 *loc
->ref
= tmp_var
;
1945 update_stmt (loc
->stmt
);
1949 /* Rewrites all references to REF in LOOP by variable TMP_VAR. */
1952 rewrite_mem_refs (class loop
*loop
, im_mem_ref
*ref
, tree tmp_var
)
1954 for_all_locs_in_loop (loop
, ref
, rewrite_mem_ref_loc (tmp_var
));
1957 /* Stores the first reference location in LOCP. */
1959 class first_mem_ref_loc_1
1962 first_mem_ref_loc_1 (mem_ref_loc
**locp_
) : locp (locp_
) {}
1963 bool operator () (mem_ref_loc
*loc
);
1968 first_mem_ref_loc_1::operator () (mem_ref_loc
*loc
)
1974 /* Returns the first reference location to REF in LOOP. */
1976 static mem_ref_loc
*
1977 first_mem_ref_loc (class loop
*loop
, im_mem_ref
*ref
)
1979 mem_ref_loc
*locp
= NULL
;
1980 for_all_locs_in_loop (loop
, ref
, first_mem_ref_loc_1 (&locp
));
1984 /* Helper function for execute_sm. Emit code to store TMP_VAR into
1987 The store is only done if MEM has changed. We do this so no
1988 changes to MEM occur on code paths that did not originally store
1991 The common case for execute_sm will transform:
2011 This function will generate:
2028 In case MEM and TMP_VAR are NULL the function will return the then
2029 block so the caller can insert (X) and other related stmts.
2033 execute_sm_if_changed (edge ex
, tree mem
, tree tmp_var
, tree flag
,
2034 edge preheader
, hash_set
<basic_block
> *flag_bbs
,
2035 edge
&append_cond_position
, edge
&last_cond_fallthru
)
2037 basic_block new_bb
, then_bb
, old_dest
;
2038 bool loop_has_only_one_exit
;
2040 gimple_stmt_iterator gsi
;
2042 bool irr
= ex
->flags
& EDGE_IRREDUCIBLE_LOOP
;
2044 profile_count count_sum
= profile_count::zero ();
2045 int nbbs
= 0, ncount
= 0;
2046 profile_probability flag_probability
= profile_probability::uninitialized ();
2048 /* Flag is set in FLAG_BBS. Determine probability that flag will be true
2051 This code may look fancy, but it cannot update profile very realistically
2052 because we do not know the probability that flag will be true at given
2055 We look for two interesting extremes
2056 - when exit is dominated by block setting the flag, we know it will
2057 always be true. This is a common case.
2058 - when all blocks setting the flag have very low frequency we know
2059 it will likely be false.
2060 In all other cases we default to 2/3 for flag being true. */
2062 for (hash_set
<basic_block
>::iterator it
= flag_bbs
->begin ();
2063 it
!= flag_bbs
->end (); ++it
)
2065 if ((*it
)->count
.initialized_p ())
2066 count_sum
+= (*it
)->count
, ncount
++;
2067 if (dominated_by_p (CDI_DOMINATORS
, ex
->src
, *it
))
2068 flag_probability
= profile_probability::always ();
2072 profile_probability cap
2073 = profile_probability::guessed_always ().apply_scale (2, 3);
2075 if (flag_probability
.initialized_p ())
2077 else if (ncount
== nbbs
2078 && preheader
->count () >= count_sum
&& preheader
->count ().nonzero_p ())
2080 flag_probability
= count_sum
.probability_in (preheader
->count ());
2081 if (flag_probability
> cap
)
2082 flag_probability
= cap
;
2085 if (!flag_probability
.initialized_p ())
2086 flag_probability
= cap
;
2088 /* ?? Insert store after previous store if applicable. See note
2090 if (append_cond_position
)
2091 ex
= append_cond_position
;
2093 loop_has_only_one_exit
= single_pred_p (ex
->dest
);
2095 if (loop_has_only_one_exit
)
2096 ex
= split_block_after_labels (ex
->dest
);
2099 for (gphi_iterator gpi
= gsi_start_phis (ex
->dest
);
2100 !gsi_end_p (gpi
); gsi_next (&gpi
))
2102 gphi
*phi
= gpi
.phi ();
2103 if (virtual_operand_p (gimple_phi_result (phi
)))
2106 /* When the destination has a non-virtual PHI node with multiple
2107 predecessors make sure we preserve the PHI structure by
2108 forcing a forwarder block so that hoisting of that PHI will
2115 old_dest
= ex
->dest
;
2116 new_bb
= split_edge (ex
);
2117 if (append_cond_position
)
2118 new_bb
->count
+= last_cond_fallthru
->count ();
2119 then_bb
= create_empty_bb (new_bb
);
2120 then_bb
->count
= new_bb
->count
.apply_probability (flag_probability
);
2122 then_bb
->flags
= BB_IRREDUCIBLE_LOOP
;
2123 add_bb_to_loop (then_bb
, new_bb
->loop_father
);
2125 gsi
= gsi_start_bb (new_bb
);
2126 stmt
= gimple_build_cond (NE_EXPR
, flag
, boolean_false_node
,
2127 NULL_TREE
, NULL_TREE
);
2128 gsi_insert_after (&gsi
, stmt
, GSI_CONTINUE_LINKING
);
2130 /* Insert actual store. */
2133 gsi
= gsi_start_bb (then_bb
);
2134 stmt
= gimple_build_assign (unshare_expr (mem
), tmp_var
);
2135 gsi_insert_after (&gsi
, stmt
, GSI_CONTINUE_LINKING
);
2138 edge e1
= single_succ_edge (new_bb
);
2139 edge e2
= make_edge (new_bb
, then_bb
,
2140 EDGE_TRUE_VALUE
| (irr
? EDGE_IRREDUCIBLE_LOOP
: 0));
2141 e2
->probability
= flag_probability
;
2143 e1
->flags
|= EDGE_FALSE_VALUE
| (irr
? EDGE_IRREDUCIBLE_LOOP
: 0);
2144 e1
->flags
&= ~EDGE_FALLTHRU
;
2146 e1
->probability
= flag_probability
.invert ();
2148 then_old_edge
= make_single_succ_edge (then_bb
, old_dest
,
2149 EDGE_FALLTHRU
| (irr
? EDGE_IRREDUCIBLE_LOOP
: 0));
2151 set_immediate_dominator (CDI_DOMINATORS
, then_bb
, new_bb
);
2153 if (append_cond_position
)
2155 basic_block prevbb
= last_cond_fallthru
->src
;
2156 redirect_edge_succ (last_cond_fallthru
, new_bb
);
2157 set_immediate_dominator (CDI_DOMINATORS
, new_bb
, prevbb
);
2158 set_immediate_dominator (CDI_DOMINATORS
, old_dest
,
2159 recompute_dominator (CDI_DOMINATORS
, old_dest
));
2162 /* ?? Because stores may alias, they must happen in the exact
2163 sequence they originally happened. Save the position right after
2164 the (_lsm) store we just created so we can continue appending after
2165 it and maintain the original order. */
2166 append_cond_position
= then_old_edge
;
2167 last_cond_fallthru
= find_edge (new_bb
, old_dest
);
2169 if (!loop_has_only_one_exit
)
2170 for (gphi_iterator gpi
= gsi_start_phis (old_dest
);
2171 !gsi_end_p (gpi
); gsi_next (&gpi
))
2173 gphi
*phi
= gpi
.phi ();
2176 for (i
= 0; i
< gimple_phi_num_args (phi
); i
++)
2177 if (gimple_phi_arg_edge (phi
, i
)->src
== new_bb
)
2179 tree arg
= gimple_phi_arg_def (phi
, i
);
2180 add_phi_arg (phi
, arg
, then_old_edge
, UNKNOWN_LOCATION
);
2188 /* When REF is set on the location, set flag indicating the store. */
2190 class sm_set_flag_if_changed
2193 sm_set_flag_if_changed (tree flag_
, hash_set
<basic_block
> *bbs_
)
2194 : flag (flag_
), bbs (bbs_
) {}
2195 bool operator () (mem_ref_loc
*loc
);
2197 hash_set
<basic_block
> *bbs
;
2201 sm_set_flag_if_changed::operator () (mem_ref_loc
*loc
)
2203 /* Only set the flag for writes. */
2204 if (is_gimple_assign (loc
->stmt
)
2205 && gimple_assign_lhs_ptr (loc
->stmt
) == loc
->ref
)
2207 gimple_stmt_iterator gsi
= gsi_for_stmt (loc
->stmt
);
2208 gimple
*stmt
= gimple_build_assign (flag
, boolean_true_node
);
2209 gsi_insert_after (&gsi
, stmt
, GSI_CONTINUE_LINKING
);
2210 bbs
->add (gimple_bb (stmt
));
2215 /* Helper function for execute_sm. On every location where REF is
2216 set, set an appropriate flag indicating the store. */
2219 execute_sm_if_changed_flag_set (class loop
*loop
, im_mem_ref
*ref
,
2220 hash_set
<basic_block
> *bbs
)
2223 char *str
= get_lsm_tmp_name (ref
->mem
.ref
, ~0, "_flag");
2224 flag
= create_tmp_reg (boolean_type_node
, str
);
2225 for_all_locs_in_loop (loop
, ref
, sm_set_flag_if_changed (flag
, bbs
));
2233 hash_set
<basic_block
> flag_bbs
;
2236 /* Executes store motion of memory reference REF from LOOP.
2237 Exits from the LOOP are stored in EXITS. The initialization of the
2238 temporary variable is put to the preheader of the loop, and assignments
2239 to the reference from the temporary variable are emitted to exits. */
2242 execute_sm (class loop
*loop
, im_mem_ref
*ref
,
2243 hash_map
<im_mem_ref
*, sm_aux
*> &aux_map
, bool maybe_mt
,
2244 bool use_other_flag_var
)
2247 struct fmt_data fmt_data
;
2248 struct lim_aux_data
*lim_data
;
2249 bool multi_threaded_model_p
= false;
2250 gimple_stmt_iterator gsi
;
2251 sm_aux
*aux
= new sm_aux
;
2253 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2255 fprintf (dump_file
, "Executing store motion of ");
2256 print_generic_expr (dump_file
, ref
->mem
.ref
);
2257 fprintf (dump_file
, " from loop %d\n", loop
->num
);
2260 aux
->tmp_var
= create_tmp_reg (TREE_TYPE (ref
->mem
.ref
),
2261 get_lsm_tmp_name (ref
->mem
.ref
, ~0));
2263 fmt_data
.loop
= loop
;
2264 fmt_data
.orig_loop
= loop
;
2265 for_each_index (&ref
->mem
.ref
, force_move_till
, &fmt_data
);
2267 bool always_stored
= ref_always_accessed_p (loop
, ref
, true);
2269 && (bb_in_transaction (loop_preheader_edge (loop
)->src
)
2270 || (! flag_store_data_races
&& ! always_stored
)))
2271 multi_threaded_model_p
= true;
2273 if (multi_threaded_model_p
&& !use_other_flag_var
)
2275 = execute_sm_if_changed_flag_set (loop
, ref
, &aux
->flag_bbs
);
2277 aux
->store_flag
= NULL_TREE
;
2279 /* Remember variable setup. */
2280 aux_map
.put (ref
, aux
);
2282 rewrite_mem_refs (loop
, ref
, aux
->tmp_var
);
2284 /* Emit the load code on a random exit edge or into the latch if
2285 the loop does not exit, so that we are sure it will be processed
2286 by move_computations after all dependencies. */
2287 gsi
= gsi_for_stmt (first_mem_ref_loc (loop
, ref
)->stmt
);
2289 /* Avoid doing a load if there was no load of the ref in the loop.
2290 Esp. when the ref is not always stored we cannot optimize it
2291 away later. But when it is not always stored we must use a conditional
2293 if ((!always_stored
&& !multi_threaded_model_p
)
2294 || (ref
->loaded
&& bitmap_bit_p (ref
->loaded
, loop
->num
)))
2295 load
= gimple_build_assign (aux
->tmp_var
, unshare_expr (ref
->mem
.ref
));
2298 /* If not emitting a load mark the uninitialized state on the
2299 loop entry as not to be warned for. */
2300 tree uninit
= create_tmp_reg (TREE_TYPE (aux
->tmp_var
));
2301 suppress_warning (uninit
, OPT_Wuninitialized
);
2302 load
= gimple_build_assign (aux
->tmp_var
, uninit
);
2304 lim_data
= init_lim_data (load
);
2305 lim_data
->max_loop
= loop
;
2306 lim_data
->tgt_loop
= loop
;
2307 gsi_insert_before (&gsi
, load
, GSI_SAME_STMT
);
2309 if (aux
->store_flag
)
2311 load
= gimple_build_assign (aux
->store_flag
, boolean_false_node
);
2312 lim_data
= init_lim_data (load
);
2313 lim_data
->max_loop
= loop
;
2314 lim_data
->tgt_loop
= loop
;
2315 gsi_insert_before (&gsi
, load
, GSI_SAME_STMT
);
2319 /* sm_ord is used for ordinary stores we can retain order with respect
2321 sm_unord is used for conditional executed stores which need to be
2322 able to execute in arbitrary order with respect to other stores
2323 sm_other is used for stores we do not try to apply store motion to. */
2324 enum sm_kind
{ sm_ord
, sm_unord
, sm_other
};
2328 seq_entry (unsigned f
, sm_kind k
, tree fr
= NULL
)
2329 : first (f
), second (k
), from (fr
) {}
2336 execute_sm_exit (class loop
*loop
, edge ex
, vec
<seq_entry
> &seq
,
2337 hash_map
<im_mem_ref
*, sm_aux
*> &aux_map
, sm_kind kind
,
2338 edge
&append_cond_position
, edge
&last_cond_fallthru
)
2340 /* Sink the stores to exit from the loop. */
2341 for (unsigned i
= seq
.length (); i
> 0; --i
)
2343 im_mem_ref
*ref
= memory_accesses
.refs_list
[seq
[i
-1].first
];
2344 if (seq
[i
-1].second
== sm_other
)
2346 gcc_assert (kind
== sm_ord
&& seq
[i
-1].from
!= NULL_TREE
);
2347 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2349 fprintf (dump_file
, "Re-issueing dependent store of ");
2350 print_generic_expr (dump_file
, ref
->mem
.ref
);
2351 fprintf (dump_file
, " from loop %d on exit %d -> %d\n",
2352 loop
->num
, ex
->src
->index
, ex
->dest
->index
);
2354 gassign
*store
= gimple_build_assign (unshare_expr (ref
->mem
.ref
),
2356 gsi_insert_on_edge (ex
, store
);
2360 sm_aux
*aux
= *aux_map
.get (ref
);
2361 if (!aux
->store_flag
|| kind
== sm_ord
)
2364 store
= gimple_build_assign (unshare_expr (ref
->mem
.ref
),
2366 gsi_insert_on_edge (ex
, store
);
2369 execute_sm_if_changed (ex
, ref
->mem
.ref
, aux
->tmp_var
,
2371 loop_preheader_edge (loop
), &aux
->flag_bbs
,
2372 append_cond_position
, last_cond_fallthru
);
2377 /* Push the SM candidate at index PTR in the sequence SEQ down until
2378 we hit the next SM candidate. Return true if that went OK and
2379 false if we could not disambiguate agains another unrelated ref.
2380 Update *AT to the index where the candidate now resides. */
2383 sm_seq_push_down (vec
<seq_entry
> &seq
, unsigned ptr
, unsigned *at
)
2386 for (; ptr
> 0; --ptr
)
2388 seq_entry
&new_cand
= seq
[ptr
];
2389 seq_entry
&against
= seq
[ptr
-1];
2390 if (against
.second
== sm_ord
2391 || (against
.second
== sm_other
&& against
.from
!= NULL_TREE
))
2392 /* Found the tail of the sequence. */
2394 /* We may not ignore self-dependences here. */
2395 if (new_cand
.first
== against
.first
2396 || !refs_independent_p (memory_accesses
.refs_list
[new_cand
.first
],
2397 memory_accesses
.refs_list
[against
.first
],
2399 /* ??? Prune new_cand from the list of refs to apply SM to. */
2401 std::swap (new_cand
, against
);
2407 /* Computes the sequence of stores from candidates in REFS_NOT_IN_SEQ to SEQ
2408 walking backwards from VDEF (or the end of BB if VDEF is NULL). */
2411 sm_seq_valid_bb (class loop
*loop
, basic_block bb
, tree vdef
,
2412 vec
<seq_entry
> &seq
, bitmap refs_not_in_seq
,
2413 bitmap refs_not_supported
, bool forked
,
2414 bitmap fully_visited
)
2417 for (gimple_stmt_iterator gsi
= gsi_last_bb (bb
); !gsi_end_p (gsi
);
2420 vdef
= gimple_vdef (gsi_stmt (gsi
));
2426 gphi
*vphi
= get_virtual_phi (bb
);
2428 vdef
= gimple_phi_result (vphi
);
2432 if (single_pred_p (bb
))
2433 /* This handles the perfect nest case. */
2434 return sm_seq_valid_bb (loop
, single_pred (bb
), vdef
,
2435 seq
, refs_not_in_seq
, refs_not_supported
,
2436 forked
, fully_visited
);
2441 gimple
*def
= SSA_NAME_DEF_STMT (vdef
);
2442 if (gimple_bb (def
) != bb
)
2444 /* If we forked by processing a PHI do not allow our walk to
2445 merge again until we handle that robustly. */
2448 /* Mark refs_not_in_seq as unsupported. */
2449 bitmap_ior_into (refs_not_supported
, refs_not_in_seq
);
2452 /* Otherwise it doesn't really matter if we end up in different
2454 bb
= gimple_bb (def
);
2456 if (gphi
*phi
= dyn_cast
<gphi
*> (def
))
2458 /* Handle CFG merges. Until we handle forks (gimple_bb (def) != bb)
2459 this is still linear.
2460 Eventually we want to cache intermediate results per BB
2461 (but we can't easily cache for different exits?). */
2462 /* Stop at PHIs with possible backedges. */
2463 if (bb
== bb
->loop_father
->header
2464 || bb
->flags
& BB_IRREDUCIBLE_LOOP
)
2466 /* Mark refs_not_in_seq as unsupported. */
2467 bitmap_ior_into (refs_not_supported
, refs_not_in_seq
);
2470 if (gimple_phi_num_args (phi
) == 1)
2471 return sm_seq_valid_bb (loop
, gimple_phi_arg_edge (phi
, 0)->src
,
2472 gimple_phi_arg_def (phi
, 0), seq
,
2473 refs_not_in_seq
, refs_not_supported
,
2474 false, fully_visited
);
2475 if (bitmap_bit_p (fully_visited
,
2476 SSA_NAME_VERSION (gimple_phi_result (phi
))))
2478 auto_vec
<seq_entry
> first_edge_seq
;
2479 auto_bitmap
tem_refs_not_in_seq (&lim_bitmap_obstack
);
2481 bitmap_copy (tem_refs_not_in_seq
, refs_not_in_seq
);
2482 eret
= sm_seq_valid_bb (loop
, gimple_phi_arg_edge (phi
, 0)->src
,
2483 gimple_phi_arg_def (phi
, 0),
2485 tem_refs_not_in_seq
, refs_not_supported
,
2486 true, fully_visited
);
2489 /* Simplify our lives by pruning the sequence of !sm_ord. */
2490 while (!first_edge_seq
.is_empty ()
2491 && first_edge_seq
.last ().second
!= sm_ord
)
2492 first_edge_seq
.pop ();
2493 for (unsigned int i
= 1; i
< gimple_phi_num_args (phi
); ++i
)
2495 tree vuse
= gimple_phi_arg_def (phi
, i
);
2496 edge e
= gimple_phi_arg_edge (phi
, i
);
2497 auto_vec
<seq_entry
> edge_seq
;
2498 bitmap_and_compl (tem_refs_not_in_seq
,
2499 refs_not_in_seq
, refs_not_supported
);
2500 /* If we've marked all refs we search for as unsupported
2501 we can stop processing and use the sequence as before
2503 if (bitmap_empty_p (tem_refs_not_in_seq
))
2505 eret
= sm_seq_valid_bb (loop
, e
->src
, vuse
, edge_seq
,
2506 tem_refs_not_in_seq
, refs_not_supported
,
2507 true, fully_visited
);
2510 /* Simplify our lives by pruning the sequence of !sm_ord. */
2511 while (!edge_seq
.is_empty ()
2512 && edge_seq
.last ().second
!= sm_ord
)
2514 unsigned min_len
= MIN(first_edge_seq
.length (),
2515 edge_seq
.length ());
2516 /* Incrementally merge seqs into first_edge_seq. */
2517 int first_uneq
= -1;
2518 auto_vec
<seq_entry
, 2> extra_refs
;
2519 for (unsigned int i
= 0; i
< min_len
; ++i
)
2521 /* ??? We can more intelligently merge when we face different
2522 order by additional sinking operations in one sequence.
2523 For now we simply mark them as to be processed by the
2524 not order-preserving SM code. */
2525 if (first_edge_seq
[i
].first
!= edge_seq
[i
].first
)
2527 if (first_edge_seq
[i
].second
== sm_ord
)
2528 bitmap_set_bit (refs_not_supported
,
2529 first_edge_seq
[i
].first
);
2530 if (edge_seq
[i
].second
== sm_ord
)
2531 bitmap_set_bit (refs_not_supported
, edge_seq
[i
].first
);
2532 first_edge_seq
[i
].second
= sm_other
;
2533 first_edge_seq
[i
].from
= NULL_TREE
;
2534 /* Record the dropped refs for later processing. */
2535 if (first_uneq
== -1)
2537 extra_refs
.safe_push (seq_entry (edge_seq
[i
].first
,
2538 sm_other
, NULL_TREE
));
2540 /* sm_other prevails. */
2541 else if (first_edge_seq
[i
].second
!= edge_seq
[i
].second
)
2543 /* Make sure the ref is marked as not supported. */
2544 bitmap_set_bit (refs_not_supported
,
2545 first_edge_seq
[i
].first
);
2546 first_edge_seq
[i
].second
= sm_other
;
2547 first_edge_seq
[i
].from
= NULL_TREE
;
2549 else if (first_edge_seq
[i
].second
== sm_other
2550 && first_edge_seq
[i
].from
!= NULL_TREE
2551 && (edge_seq
[i
].from
== NULL_TREE
2552 || !operand_equal_p (first_edge_seq
[i
].from
,
2553 edge_seq
[i
].from
, 0)))
2554 first_edge_seq
[i
].from
= NULL_TREE
;
2556 /* Any excess elements become sm_other since they are now
2557 coonditionally executed. */
2558 if (first_edge_seq
.length () > edge_seq
.length ())
2560 for (unsigned i
= edge_seq
.length ();
2561 i
< first_edge_seq
.length (); ++i
)
2563 if (first_edge_seq
[i
].second
== sm_ord
)
2564 bitmap_set_bit (refs_not_supported
,
2565 first_edge_seq
[i
].first
);
2566 first_edge_seq
[i
].second
= sm_other
;
2569 else if (edge_seq
.length () > first_edge_seq
.length ())
2571 if (first_uneq
== -1)
2572 first_uneq
= first_edge_seq
.length ();
2573 for (unsigned i
= first_edge_seq
.length ();
2574 i
< edge_seq
.length (); ++i
)
2576 if (edge_seq
[i
].second
== sm_ord
)
2577 bitmap_set_bit (refs_not_supported
, edge_seq
[i
].first
);
2578 extra_refs
.safe_push (seq_entry (edge_seq
[i
].first
,
2579 sm_other
, NULL_TREE
));
2582 /* Put unmerged refs at first_uneq to force dependence checking
2584 if (first_uneq
!= -1)
2586 /* Missing ordered_splice_at. */
2587 if ((unsigned)first_uneq
== first_edge_seq
.length ())
2588 first_edge_seq
.safe_splice (extra_refs
);
2591 unsigned fes_length
= first_edge_seq
.length ();
2592 first_edge_seq
.safe_grow (fes_length
2593 + extra_refs
.length ());
2594 memmove (&first_edge_seq
[first_uneq
+ extra_refs
.length ()],
2595 &first_edge_seq
[first_uneq
],
2596 (fes_length
- first_uneq
) * sizeof (seq_entry
));
2597 memcpy (&first_edge_seq
[first_uneq
],
2598 extra_refs
.address (),
2599 extra_refs
.length () * sizeof (seq_entry
));
2603 /* Use the sequence from the first edge and push SMs down. */
2604 for (unsigned i
= 0; i
< first_edge_seq
.length (); ++i
)
2606 unsigned id
= first_edge_seq
[i
].first
;
2607 seq
.safe_push (first_edge_seq
[i
]);
2609 if ((first_edge_seq
[i
].second
== sm_ord
2610 || (first_edge_seq
[i
].second
== sm_other
2611 && first_edge_seq
[i
].from
!= NULL_TREE
))
2612 && !sm_seq_push_down (seq
, seq
.length () - 1, &new_idx
))
2614 if (first_edge_seq
[i
].second
== sm_ord
)
2615 bitmap_set_bit (refs_not_supported
, id
);
2616 /* Mark it sm_other. */
2617 seq
[new_idx
].second
= sm_other
;
2618 seq
[new_idx
].from
= NULL_TREE
;
2621 bitmap_set_bit (fully_visited
,
2622 SSA_NAME_VERSION (gimple_phi_result (phi
)));
2625 lim_aux_data
*data
= get_lim_data (def
);
2627 if (data
->ref
== UNANALYZABLE_MEM_ID
)
2629 /* Stop at memory references which we can't move. */
2630 else if (memory_accesses
.refs_list
[data
->ref
]->mem
.ref
== error_mark_node
2631 || TREE_THIS_VOLATILE
2632 (memory_accesses
.refs_list
[data
->ref
]->mem
.ref
))
2634 /* Mark refs_not_in_seq as unsupported. */
2635 bitmap_ior_into (refs_not_supported
, refs_not_in_seq
);
2638 /* One of the stores we want to apply SM to and we've not yet seen. */
2639 else if (bitmap_clear_bit (refs_not_in_seq
, data
->ref
))
2641 seq
.safe_push (seq_entry (data
->ref
, sm_ord
));
2643 /* 1) push it down the queue until a SMed
2644 and not ignored ref is reached, skipping all not SMed refs
2645 and ignored refs via non-TBAA disambiguation. */
2647 if (!sm_seq_push_down (seq
, seq
.length () - 1, &new_idx
)
2648 /* If that fails but we did not fork yet continue, we'll see
2649 to re-materialize all of the stores in the sequence then.
2650 Further stores will only be pushed up to this one. */
2653 bitmap_set_bit (refs_not_supported
, data
->ref
);
2654 /* Mark it sm_other. */
2655 seq
[new_idx
].second
= sm_other
;
2658 /* 2) check whether we've seen all refs we want to SM and if so
2659 declare success for the active exit */
2660 if (bitmap_empty_p (refs_not_in_seq
))
2664 /* Another store not part of the final sequence. Simply push it. */
2665 seq
.safe_push (seq_entry (data
->ref
, sm_other
,
2666 gimple_assign_rhs1 (def
)));
2668 vdef
= gimple_vuse (def
);
2673 /* Hoists memory references MEM_REFS out of LOOP. EXITS is the list of exit
2674 edges of the LOOP. */
2677 hoist_memory_references (class loop
*loop
, bitmap mem_refs
,
2678 const vec
<edge
> &exits
)
2684 /* There's a special case we can use ordered re-materialization for
2685 conditionally excuted stores which is when all stores in the loop
2686 happen in the same basic-block. In that case we know we'll reach
2687 all stores and thus can simply process that BB and emit a single
2688 conditional block of ordered materializations. See PR102436. */
2689 basic_block single_store_bb
= NULL
;
2690 EXECUTE_IF_SET_IN_BITMAP (&memory_accesses
.all_refs_stored_in_loop
[loop
->num
],
2694 ref
= memory_accesses
.refs_list
[i
];
2695 for (auto loc
: ref
->accesses_in_loop
)
2696 if (!gimple_vdef (loc
.stmt
))
2698 else if (!single_store_bb
)
2700 single_store_bb
= gimple_bb (loc
.stmt
);
2701 bool conditional
= false;
2702 for (edge e
: exits
)
2703 if (!dominated_by_p (CDI_DOMINATORS
, e
->src
, single_store_bb
))
2705 /* Conditional as seen from e. */
2715 else if (single_store_bb
!= gimple_bb (loc
.stmt
))
2722 single_store_bb
= NULL
;
2726 if (single_store_bb
)
2728 /* Analyze the single block with stores. */
2729 auto_bitmap fully_visited
;
2730 auto_bitmap refs_not_supported
;
2731 auto_bitmap refs_not_in_seq
;
2732 auto_vec
<seq_entry
> seq
;
2733 bitmap_copy (refs_not_in_seq
, mem_refs
);
2734 int res
= sm_seq_valid_bb (loop
, single_store_bb
, NULL_TREE
,
2735 seq
, refs_not_in_seq
, refs_not_supported
,
2736 false, fully_visited
);
2739 /* Unhandled refs can still fail this. */
2740 bitmap_clear (mem_refs
);
2744 /* We cannot handle sm_other since we neither remember the
2745 stored location nor the value at the point we execute them. */
2746 for (unsigned i
= 0; i
< seq
.length (); ++i
)
2749 if (seq
[i
].second
== sm_other
2750 && seq
[i
].from
!= NULL_TREE
)
2751 seq
[i
].from
= NULL_TREE
;
2752 else if ((seq
[i
].second
== sm_ord
2753 || (seq
[i
].second
== sm_other
2754 && seq
[i
].from
!= NULL_TREE
))
2755 && !sm_seq_push_down (seq
, i
, &new_i
))
2757 bitmap_set_bit (refs_not_supported
, seq
[new_i
].first
);
2758 seq
[new_i
].second
= sm_other
;
2759 seq
[new_i
].from
= NULL_TREE
;
2762 bitmap_and_compl_into (mem_refs
, refs_not_supported
);
2763 if (bitmap_empty_p (mem_refs
))
2767 while (seq
.last ().second
== sm_other
2768 && seq
.last ().from
== NULL_TREE
)
2771 hash_map
<im_mem_ref
*, sm_aux
*> aux_map
;
2773 /* Execute SM but delay the store materialization for ordered
2774 sequences on exit. */
2775 bool first_p
= true;
2776 EXECUTE_IF_SET_IN_BITMAP (mem_refs
, 0, i
, bi
)
2778 ref
= memory_accesses
.refs_list
[i
];
2779 execute_sm (loop
, ref
, aux_map
, true, !first_p
);
2783 /* Get at the single flag variable we eventually produced. */
2785 = memory_accesses
.refs_list
[bitmap_first_set_bit (mem_refs
)];
2786 sm_aux
*aux
= *aux_map
.get (ref
);
2788 /* Materialize ordered store sequences on exits. */
2790 FOR_EACH_VEC_ELT (exits
, i
, e
)
2792 edge append_cond_position
= NULL
;
2793 edge last_cond_fallthru
= NULL
;
2795 /* Construct the single flag variable control flow and insert
2796 the ordered seq of stores in the then block. With
2797 -fstore-data-races we can do the stores unconditionally. */
2798 if (aux
->store_flag
)
2801 (execute_sm_if_changed (e
, NULL_TREE
, NULL_TREE
,
2803 loop_preheader_edge (loop
),
2804 &aux
->flag_bbs
, append_cond_position
,
2805 last_cond_fallthru
));
2806 execute_sm_exit (loop
, insert_e
, seq
, aux_map
, sm_ord
,
2807 append_cond_position
, last_cond_fallthru
);
2808 gsi_commit_one_edge_insert (insert_e
, NULL
);
2811 for (hash_map
<im_mem_ref
*, sm_aux
*>::iterator iter
= aux_map
.begin ();
2812 iter
!= aux_map
.end (); ++iter
)
2813 delete (*iter
).second
;
2818 /* To address PR57359 before actually applying store-motion check
2819 the candidates found for validity with regards to reordering
2820 relative to other stores which we until here disambiguated using
2821 TBAA which isn't valid.
2822 What matters is the order of the last stores to the mem_refs
2823 with respect to the other stores of the loop at the point of the
2826 /* For each exit compute the store order, pruning from mem_refs
2828 /* The complexity of this is at least
2829 O(number of exits * number of SM refs) but more approaching
2830 O(number of exits * number of SM refs * number of stores). */
2831 /* ??? Somehow do this in a single sweep over the loop body. */
2832 auto_vec
<std::pair
<edge
, vec
<seq_entry
> > > sms
;
2833 auto_bitmap
refs_not_supported (&lim_bitmap_obstack
);
2835 FOR_EACH_VEC_ELT (exits
, i
, e
)
2839 auto_bitmap
refs_not_in_seq (&lim_bitmap_obstack
);
2840 bitmap_and_compl (refs_not_in_seq
, mem_refs
, refs_not_supported
);
2841 if (bitmap_empty_p (refs_not_in_seq
))
2846 auto_bitmap fully_visited
;
2847 int res
= sm_seq_valid_bb (loop
, e
->src
, NULL_TREE
,
2848 seq
, refs_not_in_seq
,
2849 refs_not_supported
, false,
2853 bitmap_copy (refs_not_supported
, mem_refs
);
2857 sms
.safe_push (std::make_pair (e
, seq
));
2860 /* Prune pruned mem_refs from earlier processed exits. */
2861 bool changed
= !bitmap_empty_p (refs_not_supported
);
2865 std::pair
<edge
, vec
<seq_entry
> > *seq
;
2866 FOR_EACH_VEC_ELT (sms
, i
, seq
)
2868 bool need_to_push
= false;
2869 for (unsigned i
= 0; i
< seq
->second
.length (); ++i
)
2871 sm_kind kind
= seq
->second
[i
].second
;
2872 if (kind
== sm_other
&& seq
->second
[i
].from
== NULL_TREE
)
2874 unsigned id
= seq
->second
[i
].first
;
2877 && bitmap_bit_p (refs_not_supported
, id
))
2879 seq
->second
[i
].second
= sm_other
;
2880 gcc_assert (seq
->second
[i
].from
== NULL_TREE
);
2881 need_to_push
= true;
2883 else if (need_to_push
2884 && !sm_seq_push_down (seq
->second
, i
, &new_idx
))
2886 /* We need to push down both sm_ord and sm_other
2887 but for the latter we need to disqualify all
2891 if (bitmap_set_bit (refs_not_supported
, id
))
2893 seq
->second
[new_idx
].second
= sm_other
;
2897 for (unsigned j
= seq
->second
.length () - 1;
2899 if (seq
->second
[j
].second
== sm_ord
2900 && bitmap_set_bit (refs_not_supported
,
2901 seq
->second
[j
].first
))
2903 seq
->second
.truncate (new_idx
);
2910 std::pair
<edge
, vec
<seq_entry
> > *seq
;
2911 FOR_EACH_VEC_ELT (sms
, i
, seq
)
2913 /* Prune sm_other from the end. */
2914 while (!seq
->second
.is_empty ()
2915 && seq
->second
.last ().second
== sm_other
)
2917 /* Prune duplicates from the start. */
2918 auto_bitmap
seen (&lim_bitmap_obstack
);
2920 for (j
= k
= 0; j
< seq
->second
.length (); ++j
)
2921 if (bitmap_set_bit (seen
, seq
->second
[j
].first
))
2924 seq
->second
[k
] = seq
->second
[j
];
2927 seq
->second
.truncate (k
);
2930 FOR_EACH_VEC_ELT (seq
->second
, j
, e
)
2931 gcc_assert (e
->second
== sm_ord
2932 || (e
->second
== sm_other
&& e
->from
!= NULL_TREE
));
2935 /* Verify dependence for refs we cannot handle with the order preserving
2936 code (refs_not_supported) or prune them from mem_refs. */
2937 auto_vec
<seq_entry
> unord_refs
;
2938 EXECUTE_IF_SET_IN_BITMAP (refs_not_supported
, 0, i
, bi
)
2940 ref
= memory_accesses
.refs_list
[i
];
2941 if (!ref_indep_loop_p (loop
, ref
, sm_waw
))
2942 bitmap_clear_bit (mem_refs
, i
);
2943 /* We've now verified store order for ref with respect to all other
2944 stores in the loop does not matter. */
2946 unord_refs
.safe_push (seq_entry (i
, sm_unord
));
2949 hash_map
<im_mem_ref
*, sm_aux
*> aux_map
;
2951 /* Execute SM but delay the store materialization for ordered
2952 sequences on exit. */
2953 EXECUTE_IF_SET_IN_BITMAP (mem_refs
, 0, i
, bi
)
2955 ref
= memory_accesses
.refs_list
[i
];
2956 execute_sm (loop
, ref
, aux_map
, bitmap_bit_p (refs_not_supported
, i
),
2960 /* Materialize ordered store sequences on exits. */
2961 FOR_EACH_VEC_ELT (exits
, i
, e
)
2963 edge append_cond_position
= NULL
;
2964 edge last_cond_fallthru
= NULL
;
2965 if (i
< sms
.length ())
2967 gcc_assert (sms
[i
].first
== e
);
2968 execute_sm_exit (loop
, e
, sms
[i
].second
, aux_map
, sm_ord
,
2969 append_cond_position
, last_cond_fallthru
);
2970 sms
[i
].second
.release ();
2972 if (!unord_refs
.is_empty ())
2973 execute_sm_exit (loop
, e
, unord_refs
, aux_map
, sm_unord
,
2974 append_cond_position
, last_cond_fallthru
);
2975 /* Commit edge inserts here to preserve the order of stores
2976 when an exit exits multiple loops. */
2977 gsi_commit_one_edge_insert (e
, NULL
);
2980 for (hash_map
<im_mem_ref
*, sm_aux
*>::iterator iter
= aux_map
.begin ();
2981 iter
!= aux_map
.end (); ++iter
)
2982 delete (*iter
).second
;
2985 class ref_always_accessed
2988 ref_always_accessed (class loop
*loop_
, bool stored_p_
)
2989 : loop (loop_
), stored_p (stored_p_
) {}
2990 bool operator () (mem_ref_loc
*loc
);
2996 ref_always_accessed::operator () (mem_ref_loc
*loc
)
2998 class loop
*must_exec
;
3000 struct lim_aux_data
*lim_data
= get_lim_data (loc
->stmt
);
3004 /* If we require an always executed store make sure the statement
3008 tree lhs
= gimple_get_lhs (loc
->stmt
);
3010 || !(DECL_P (lhs
) || REFERENCE_CLASS_P (lhs
)))
3014 must_exec
= lim_data
->always_executed_in
;
3018 if (must_exec
== loop
3019 || flow_loop_nested_p (must_exec
, loop
))
3025 /* Returns true if REF is always accessed in LOOP. If STORED_P is true
3026 make sure REF is always stored to in LOOP. */
3029 ref_always_accessed_p (class loop
*loop
, im_mem_ref
*ref
, bool stored_p
)
3031 return for_all_locs_in_loop (loop
, ref
,
3032 ref_always_accessed (loop
, stored_p
));
3035 /* Returns true if REF1 and REF2 are independent. */
3038 refs_independent_p (im_mem_ref
*ref1
, im_mem_ref
*ref2
, bool tbaa_p
)
3043 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3044 fprintf (dump_file
, "Querying dependency of refs %u and %u: ",
3045 ref1
->id
, ref2
->id
);
3047 if (mem_refs_may_alias_p (ref1
, ref2
, &memory_accesses
.ttae_cache
, tbaa_p
))
3049 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3050 fprintf (dump_file
, "dependent.\n");
3055 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3056 fprintf (dump_file
, "independent.\n");
3061 /* Returns true if REF is independent on all other accessess in LOOP.
3062 KIND specifies the kind of dependence to consider.
3063 lim_raw assumes REF is not stored in LOOP and disambiguates RAW
3064 dependences so if true REF can be hoisted out of LOOP
3065 sm_war disambiguates a store REF against all other loads to see
3066 whether the store can be sunk across loads out of LOOP
3067 sm_waw disambiguates a store REF against all other stores to see
3068 whether the store can be sunk across stores out of LOOP. */
3071 ref_indep_loop_p (class loop
*loop
, im_mem_ref
*ref
, dep_kind kind
)
3073 bool indep_p
= true;
3074 bitmap refs_to_check
;
3077 refs_to_check
= &memory_accesses
.refs_loaded_in_loop
[loop
->num
];
3079 refs_to_check
= &memory_accesses
.refs_stored_in_loop
[loop
->num
];
3081 if (bitmap_bit_p (refs_to_check
, UNANALYZABLE_MEM_ID
)
3082 || ref
->mem
.ref
== error_mark_node
)
3086 /* tri-state, { unknown, independent, dependent } */
3087 dep_state state
= query_loop_dependence (loop
, ref
, kind
);
3088 if (state
!= dep_unknown
)
3089 return state
== dep_independent
? true : false;
3091 class loop
*inner
= loop
->inner
;
3094 if (!ref_indep_loop_p (inner
, ref
, kind
))
3099 inner
= inner
->next
;
3106 EXECUTE_IF_SET_IN_BITMAP (refs_to_check
, 0, i
, bi
)
3108 im_mem_ref
*aref
= memory_accesses
.refs_list
[i
];
3109 if (aref
->mem
.ref
== error_mark_node
)
3111 gimple
*stmt
= aref
->accesses_in_loop
[0].stmt
;
3113 && ref_maybe_used_by_stmt_p (stmt
, &ref
->mem
,
3115 || stmt_may_clobber_ref_p_1 (stmt
, &ref
->mem
,
3122 else if (!refs_independent_p (ref
, aref
, kind
!= sm_waw
))
3131 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3132 fprintf (dump_file
, "Querying %s dependencies of ref %u in loop %d: %s\n",
3133 kind
== lim_raw
? "RAW" : (kind
== sm_war
? "SM WAR" : "SM WAW"),
3134 ref
->id
, loop
->num
, indep_p
? "independent" : "dependent");
3136 /* Record the computed result in the cache. */
3137 record_loop_dependence (loop
, ref
, kind
,
3138 indep_p
? dep_independent
: dep_dependent
);
3143 class ref_in_loop_hot_body
3146 ref_in_loop_hot_body (class loop
*loop_
) : l (loop_
) {}
3147 bool operator () (mem_ref_loc
*loc
);
3151 /* Check the coldest loop between loop L and innermost loop. If there is one
3152 cold loop between L and INNER_LOOP, store motion can be performed, otherwise
3153 no cold loop means no store motion. get_coldest_out_loop also handles cases
3154 when l is inner_loop. */
3156 ref_in_loop_hot_body::operator () (mem_ref_loc
*loc
)
3158 basic_block curr_bb
= gimple_bb (loc
->stmt
);
3159 class loop
*inner_loop
= curr_bb
->loop_father
;
3160 return get_coldest_out_loop (l
, inner_loop
, curr_bb
);
3164 /* Returns true if we can perform store motion of REF from LOOP. */
3167 can_sm_ref_p (class loop
*loop
, im_mem_ref
*ref
)
3171 /* Can't hoist unanalyzable refs. */
3172 if (!MEM_ANALYZABLE (ref
))
3175 /* Can't hoist/sink aggregate copies. */
3176 if (ref
->mem
.ref
== error_mark_node
)
3179 /* It should be movable. */
3180 if (!is_gimple_reg_type (TREE_TYPE (ref
->mem
.ref
))
3181 || TREE_THIS_VOLATILE (ref
->mem
.ref
)
3182 || !for_each_index (&ref
->mem
.ref
, may_move_till
, loop
))
3185 /* If it can throw fail, we do not properly update EH info. */
3186 if (tree_could_throw_p (ref
->mem
.ref
))
3189 /* If it can trap, it must be always executed in LOOP.
3190 Readonly memory locations may trap when storing to them, but
3191 tree_could_trap_p is a predicate for rvalues, so check that
3193 base
= get_base_address (ref
->mem
.ref
);
3194 if ((tree_could_trap_p (ref
->mem
.ref
)
3195 || (DECL_P (base
) && TREE_READONLY (base
)))
3196 /* ??? We can at least use false here, allowing loads? We
3197 are forcing conditional stores if the ref is not always
3198 stored to later anyway. So this would only guard
3199 the load we need to emit. Thus when the ref is not
3200 loaded we can elide this completely? */
3201 && !ref_always_accessed_p (loop
, ref
, true))
3204 /* Verify all loads of ref can be hoisted. */
3206 && bitmap_bit_p (ref
->loaded
, loop
->num
)
3207 && !ref_indep_loop_p (loop
, ref
, lim_raw
))
3210 /* Verify the candidate can be disambiguated against all loads,
3211 that is, we can elide all in-loop stores. Disambiguation
3212 against stores is done later when we cannot guarantee preserving
3213 the order of stores. */
3214 if (!ref_indep_loop_p (loop
, ref
, sm_war
))
3217 /* Verify whether the candidate is hot for LOOP. Only do store motion if the
3218 candidate's profile count is hot. Statement in cold BB shouldn't be moved
3219 out of it's loop_father. */
3220 if (!for_all_locs_in_loop (loop
, ref
, ref_in_loop_hot_body (loop
)))
3226 /* Marks the references in LOOP for that store motion should be performed
3227 in REFS_TO_SM. SM_EXECUTED is the set of references for that store
3228 motion was performed in one of the outer loops. */
3231 find_refs_for_sm (class loop
*loop
, bitmap sm_executed
, bitmap refs_to_sm
)
3233 bitmap refs
= &memory_accesses
.all_refs_stored_in_loop
[loop
->num
];
3238 EXECUTE_IF_AND_COMPL_IN_BITMAP (refs
, sm_executed
, 0, i
, bi
)
3240 ref
= memory_accesses
.refs_list
[i
];
3241 if (can_sm_ref_p (loop
, ref
) && dbg_cnt (lim
))
3242 bitmap_set_bit (refs_to_sm
, i
);
3246 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
3247 for a store motion optimization (i.e. whether we can insert statement
3251 loop_suitable_for_sm (class loop
*loop ATTRIBUTE_UNUSED
,
3252 const vec
<edge
> &exits
)
3257 FOR_EACH_VEC_ELT (exits
, i
, ex
)
3258 if (ex
->flags
& (EDGE_ABNORMAL
| EDGE_EH
))
3264 /* Try to perform store motion for all memory references modified inside
3265 LOOP. SM_EXECUTED is the bitmap of the memory references for that
3266 store motion was executed in one of the outer loops. */
3269 store_motion_loop (class loop
*loop
, bitmap sm_executed
)
3271 auto_vec
<edge
> exits
= get_loop_exit_edges (loop
);
3272 class loop
*subloop
;
3273 bitmap sm_in_loop
= BITMAP_ALLOC (&lim_bitmap_obstack
);
3275 if (loop_suitable_for_sm (loop
, exits
))
3277 find_refs_for_sm (loop
, sm_executed
, sm_in_loop
);
3278 if (!bitmap_empty_p (sm_in_loop
))
3279 hoist_memory_references (loop
, sm_in_loop
, exits
);
3282 bitmap_ior_into (sm_executed
, sm_in_loop
);
3283 for (subloop
= loop
->inner
; subloop
!= NULL
; subloop
= subloop
->next
)
3284 store_motion_loop (subloop
, sm_executed
);
3285 bitmap_and_compl_into (sm_executed
, sm_in_loop
);
3286 BITMAP_FREE (sm_in_loop
);
3289 /* Try to perform store motion for all memory references modified inside
3293 do_store_motion (void)
3296 bitmap sm_executed
= BITMAP_ALLOC (&lim_bitmap_obstack
);
3298 for (loop
= current_loops
->tree_root
->inner
; loop
!= NULL
; loop
= loop
->next
)
3299 store_motion_loop (loop
, sm_executed
);
3301 BITMAP_FREE (sm_executed
);
3304 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
3305 for each such basic block bb records the outermost loop for that execution
3306 of its header implies execution of bb. CONTAINS_CALL is the bitmap of
3307 blocks that contain a nonpure call. */
3310 fill_always_executed_in_1 (class loop
*loop
, sbitmap contains_call
)
3312 basic_block bb
= NULL
, last
= NULL
;
3314 class loop
*inn_loop
= loop
;
3316 if (ALWAYS_EXECUTED_IN (loop
->header
) == NULL
)
3318 auto_vec
<basic_block
, 64> worklist
;
3319 worklist
.reserve_exact (loop
->num_nodes
);
3320 worklist
.quick_push (loop
->header
);
3324 bb
= worklist
.pop ();
3326 if (!flow_bb_inside_loop_p (inn_loop
, bb
))
3328 /* When we are leaving a possibly infinite inner loop
3329 we have to stop processing. */
3330 if (!finite_loop_p (inn_loop
))
3332 /* If the loop was finite we can continue with processing
3333 the loop we exited to. */
3334 inn_loop
= bb
->loop_father
;
3337 if (dominated_by_p (CDI_DOMINATORS
, loop
->latch
, bb
))
3340 if (bitmap_bit_p (contains_call
, bb
->index
))
3343 /* If LOOP exits from this BB stop processing. */
3344 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3345 if (!flow_bb_inside_loop_p (loop
, e
->dest
))
3350 /* A loop might be infinite (TODO use simple loop analysis
3351 to disprove this if possible). */
3352 if (bb
->flags
& BB_IRREDUCIBLE_LOOP
)
3355 if (bb
->loop_father
->header
== bb
)
3356 /* Record that we enter into a subloop since it might not
3358 /* ??? Entering into a not always executed subloop makes
3359 fill_always_executed_in quadratic in loop depth since
3360 we walk those loops N times. This is not a problem
3361 in practice though, see PR102253 for a worst-case testcase. */
3362 inn_loop
= bb
->loop_father
;
3364 /* Walk the body of LOOP sorted by dominance relation. Additionally,
3365 if a basic block S dominates the latch, then only blocks dominated
3367 This is get_loop_body_in_dom_order using a worklist algorithm and
3368 stopping once we are no longer interested in visiting further
3370 unsigned old_len
= worklist
.length ();
3371 unsigned postpone
= 0;
3372 for (basic_block son
= first_dom_son (CDI_DOMINATORS
, bb
);
3374 son
= next_dom_son (CDI_DOMINATORS
, son
))
3376 if (!flow_bb_inside_loop_p (loop
, son
))
3378 if (dominated_by_p (CDI_DOMINATORS
, loop
->latch
, son
))
3379 postpone
= worklist
.length ();
3380 worklist
.quick_push (son
);
3383 /* Postponing the block that dominates the latch means
3384 processing it last and thus putting it earliest in the
3386 std::swap (worklist
[old_len
], worklist
[postpone
]);
3388 while (!worklist
.is_empty ());
3392 if (dump_enabled_p ())
3393 dump_printf (MSG_NOTE
, "BB %d is always executed in loop %d\n",
3394 last
->index
, loop
->num
);
3395 SET_ALWAYS_EXECUTED_IN (last
, loop
);
3396 if (last
== loop
->header
)
3398 last
= get_immediate_dominator (CDI_DOMINATORS
, last
);
3402 for (loop
= loop
->inner
; loop
; loop
= loop
->next
)
3403 fill_always_executed_in_1 (loop
, contains_call
);
3406 /* Fills ALWAYS_EXECUTED_IN information for basic blocks, i.e.
3407 for each such basic block bb records the outermost loop for that execution
3408 of its header implies execution of bb. */
3411 fill_always_executed_in (void)
3416 auto_sbitmap
contains_call (last_basic_block_for_fn (cfun
));
3417 bitmap_clear (contains_call
);
3418 FOR_EACH_BB_FN (bb
, cfun
)
3420 gimple_stmt_iterator gsi
;
3421 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
3423 if (nonpure_call_p (gsi_stmt (gsi
)))
3427 if (!gsi_end_p (gsi
))
3428 bitmap_set_bit (contains_call
, bb
->index
);
3431 for (loop
= current_loops
->tree_root
->inner
; loop
; loop
= loop
->next
)
3432 fill_always_executed_in_1 (loop
, contains_call
);
3435 /* Find the coldest loop preheader for LOOP, also find the nearest hotter loop
3436 to LOOP. Then recursively iterate each inner loop. */
3439 fill_coldest_and_hotter_out_loop (class loop
*coldest_loop
,
3440 class loop
*hotter_loop
, class loop
*loop
)
3442 if (bb_colder_than_loop_preheader (loop_preheader_edge (loop
)->src
,
3444 coldest_loop
= loop
;
3446 coldest_outermost_loop
[loop
->num
] = coldest_loop
;
3448 hotter_than_inner_loop
[loop
->num
] = NULL
;
3449 class loop
*outer_loop
= loop_outer (loop
);
3451 && bb_colder_than_loop_preheader (loop_preheader_edge (loop
)->src
,
3453 hotter_than_inner_loop
[loop
->num
] = hotter_loop
;
3455 if (outer_loop
&& outer_loop
!= current_loops
->tree_root
3456 && bb_colder_than_loop_preheader (loop_preheader_edge (loop
)->src
,
3458 hotter_than_inner_loop
[loop
->num
] = outer_loop
;
3460 if (dump_enabled_p ())
3462 dump_printf (MSG_NOTE
, "loop %d's coldest_outermost_loop is %d, ",
3463 loop
->num
, coldest_loop
->num
);
3464 if (hotter_than_inner_loop
[loop
->num
])
3465 dump_printf (MSG_NOTE
, "hotter_than_inner_loop is %d\n",
3466 hotter_than_inner_loop
[loop
->num
]->num
);
3468 dump_printf (MSG_NOTE
, "hotter_than_inner_loop is NULL\n");
3471 class loop
*inner_loop
;
3472 for (inner_loop
= loop
->inner
; inner_loop
; inner_loop
= inner_loop
->next
)
3473 fill_coldest_and_hotter_out_loop (coldest_loop
,
3474 hotter_than_inner_loop
[loop
->num
],
3478 /* Compute the global information needed by the loop invariant motion pass. */
3481 tree_ssa_lim_initialize (bool store_motion
)
3485 bitmap_obstack_initialize (&lim_bitmap_obstack
);
3486 gcc_obstack_init (&mem_ref_obstack
);
3487 lim_aux_data_map
= new hash_map
<gimple
*, lim_aux_data
*>;
3490 compute_transaction_bits ();
3492 memory_accesses
.refs
= new hash_table
<mem_ref_hasher
> (100);
3493 memory_accesses
.refs_list
.create (100);
3494 /* Allocate a special, unanalyzable mem-ref with ID zero. */
3495 memory_accesses
.refs_list
.quick_push
3496 (mem_ref_alloc (NULL
, 0, UNANALYZABLE_MEM_ID
));
3498 memory_accesses
.refs_loaded_in_loop
.create (number_of_loops (cfun
));
3499 memory_accesses
.refs_loaded_in_loop
.quick_grow (number_of_loops (cfun
));
3500 memory_accesses
.refs_stored_in_loop
.create (number_of_loops (cfun
));
3501 memory_accesses
.refs_stored_in_loop
.quick_grow (number_of_loops (cfun
));
3504 memory_accesses
.all_refs_stored_in_loop
.create (number_of_loops (cfun
));
3505 memory_accesses
.all_refs_stored_in_loop
.quick_grow
3506 (number_of_loops (cfun
));
3509 for (i
= 0; i
< number_of_loops (cfun
); i
++)
3511 bitmap_initialize (&memory_accesses
.refs_loaded_in_loop
[i
],
3512 &lim_bitmap_obstack
);
3513 bitmap_initialize (&memory_accesses
.refs_stored_in_loop
[i
],
3514 &lim_bitmap_obstack
);
3516 bitmap_initialize (&memory_accesses
.all_refs_stored_in_loop
[i
],
3517 &lim_bitmap_obstack
);
3520 memory_accesses
.ttae_cache
= NULL
;
3522 /* Initialize bb_loop_postorder with a mapping from loop->num to
3523 its postorder index. */
3525 bb_loop_postorder
= XNEWVEC (unsigned, number_of_loops (cfun
));
3526 for (auto loop
: loops_list (cfun
, LI_FROM_INNERMOST
))
3527 bb_loop_postorder
[loop
->num
] = i
++;
3530 /* Cleans up after the invariant motion pass. */
3533 tree_ssa_lim_finalize (void)
3539 FOR_EACH_BB_FN (bb
, cfun
)
3540 SET_ALWAYS_EXECUTED_IN (bb
, NULL
);
3542 bitmap_obstack_release (&lim_bitmap_obstack
);
3543 delete lim_aux_data_map
;
3545 delete memory_accesses
.refs
;
3546 memory_accesses
.refs
= NULL
;
3548 FOR_EACH_VEC_ELT (memory_accesses
.refs_list
, i
, ref
)
3550 memory_accesses
.refs_list
.release ();
3551 obstack_free (&mem_ref_obstack
, NULL
);
3553 memory_accesses
.refs_loaded_in_loop
.release ();
3554 memory_accesses
.refs_stored_in_loop
.release ();
3555 memory_accesses
.all_refs_stored_in_loop
.release ();
3557 if (memory_accesses
.ttae_cache
)
3558 free_affine_expand_cache (&memory_accesses
.ttae_cache
);
3560 free (bb_loop_postorder
);
3562 coldest_outermost_loop
.release ();
3563 hotter_than_inner_loop
.release ();
3566 /* Moves invariants from loops. Only "expensive" invariants are moved out --
3567 i.e. those that are likely to be win regardless of the register pressure.
3568 Only perform store motion if STORE_MOTION is true. */
3571 loop_invariant_motion_in_fun (function
*fun
, bool store_motion
)
3573 unsigned int todo
= 0;
3575 tree_ssa_lim_initialize (store_motion
);
3577 mark_ssa_maybe_undefs ();
3579 /* Gathers information about memory accesses in the loops. */
3580 analyze_memory_references (store_motion
);
3582 /* Fills ALWAYS_EXECUTED_IN information for basic blocks. */
3583 fill_always_executed_in ();
3585 /* Pre-compute coldest outermost loop and nearest hotter loop of each loop.
3588 coldest_outermost_loop
.create (number_of_loops (cfun
));
3589 coldest_outermost_loop
.safe_grow_cleared (number_of_loops (cfun
));
3590 hotter_than_inner_loop
.create (number_of_loops (cfun
));
3591 hotter_than_inner_loop
.safe_grow_cleared (number_of_loops (cfun
));
3592 for (loop
= current_loops
->tree_root
->inner
; loop
!= NULL
; loop
= loop
->next
)
3593 fill_coldest_and_hotter_out_loop (loop
, NULL
, loop
);
3595 int *rpo
= XNEWVEC (int, last_basic_block_for_fn (fun
));
3596 int n
= pre_and_rev_post_order_compute_fn (fun
, NULL
, rpo
, false);
3598 /* For each statement determine the outermost loop in that it is
3599 invariant and cost for computing the invariant. */
3600 for (int i
= 0; i
< n
; ++i
)
3601 compute_invariantness (BASIC_BLOCK_FOR_FN (fun
, rpo
[i
]));
3603 /* Execute store motion. Force the necessary invariants to be moved
3604 out of the loops as well. */
3609 rpo
= XNEWVEC (int, last_basic_block_for_fn (fun
));
3610 n
= pre_and_rev_post_order_compute_fn (fun
, NULL
, rpo
, false);
3612 /* Move the expressions that are expensive enough. */
3613 for (int i
= 0; i
< n
; ++i
)
3614 todo
|= move_computations_worker (BASIC_BLOCK_FOR_FN (fun
, rpo
[i
]));
3618 gsi_commit_edge_inserts ();
3619 if (need_ssa_update_p (fun
))
3620 rewrite_into_loop_closed_ssa (NULL
, TODO_update_ssa
);
3622 tree_ssa_lim_finalize ();
3627 /* Loop invariant motion pass. */
3631 const pass_data pass_data_lim
=
3633 GIMPLE_PASS
, /* type */
3635 OPTGROUP_LOOP
, /* optinfo_flags */
3637 PROP_cfg
, /* properties_required */
3638 0, /* properties_provided */
3639 0, /* properties_destroyed */
3640 0, /* todo_flags_start */
3641 0, /* todo_flags_finish */
3644 class pass_lim
: public gimple_opt_pass
3647 pass_lim (gcc::context
*ctxt
)
3648 : gimple_opt_pass (pass_data_lim
, ctxt
)
3651 /* opt_pass methods: */
3652 opt_pass
* clone () final override
{ return new pass_lim (m_ctxt
); }
3653 bool gate (function
*) final override
{ return flag_tree_loop_im
!= 0; }
3654 unsigned int execute (function
*) final override
;
3656 }; // class pass_lim
3659 pass_lim::execute (function
*fun
)
3661 bool in_loop_pipeline
= scev_initialized_p ();
3662 if (!in_loop_pipeline
)
3663 loop_optimizer_init (LOOPS_NORMAL
| LOOPS_HAVE_RECORDED_EXITS
);
3665 if (number_of_loops (fun
) <= 1)
3667 unsigned int todo
= loop_invariant_motion_in_fun (fun
, flag_move_loop_stores
);
3669 if (!in_loop_pipeline
)
3670 loop_optimizer_finalize ();
3679 make_pass_lim (gcc::context
*ctxt
)
3681 return new pass_lim (ctxt
);