* config/epiphany/epiphany.md (GPR_1): New constant.
[official-gcc.git] / gcc / tree-ssa-loop-im.c
blob085789165a2e8effbca97dff0b4cd411b2f51f02
1 /* Loop invariant motion.
2 Copyright (C) 2003-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "tm_p.h"
26 #include "basic-block.h"
27 #include "gimple-pretty-print.h"
28 #include "tree-flow.h"
29 #include "cfgloop.h"
30 #include "domwalk.h"
31 #include "params.h"
32 #include "tree-pass.h"
33 #include "flags.h"
34 #include "hashtab.h"
35 #include "tree-affine.h"
36 #include "pointer-set.h"
37 #include "tree-ssa-propagate.h"
39 /* TODO: Support for predicated code motion. I.e.
41 while (1)
43 if (cond)
45 a = inv;
46 something;
50 Where COND and INV are invariants, but evaluating INV may trap or be
51 invalid from some other reason if !COND. This may be transformed to
53 if (cond)
54 a = inv;
55 while (1)
57 if (cond)
58 something;
59 } */
61 /* The auxiliary data kept for each statement. */
63 struct lim_aux_data
65 struct loop *max_loop; /* The outermost loop in that the statement
66 is invariant. */
68 struct loop *tgt_loop; /* The loop out of that we want to move the
69 invariant. */
71 struct loop *always_executed_in;
72 /* The outermost loop for that we are sure
73 the statement is executed if the loop
74 is entered. */
76 unsigned cost; /* Cost of the computation performed by the
77 statement. */
79 vec<gimple> depends; /* Vector of statements that must be also
80 hoisted out of the loop when this statement
81 is hoisted; i.e. those that define the
82 operands of the statement and are inside of
83 the MAX_LOOP loop. */
86 /* Maps statements to their lim_aux_data. */
88 static struct pointer_map_t *lim_aux_data_map;
90 /* Description of a memory reference location. */
92 typedef struct mem_ref_loc
94 tree *ref; /* The reference itself. */
95 gimple stmt; /* The statement in that it occurs. */
96 } *mem_ref_loc_p;
99 /* Description of a memory reference. */
101 typedef struct mem_ref
103 unsigned id; /* ID assigned to the memory reference
104 (its index in memory_accesses.refs_list) */
105 hashval_t hash; /* Its hash value. */
107 /* The memory access itself and associated caching of alias-oracle
108 query meta-data. */
109 ao_ref mem;
111 bitmap_head stored; /* The set of loops in that this memory location
112 is stored to. */
113 vec<vec<mem_ref_loc> > accesses_in_loop;
114 /* The locations of the accesses. Vector
115 indexed by the loop number. */
117 /* The following sets are computed on demand. We keep both set and
118 its complement, so that we know whether the information was
119 already computed or not. */
120 bitmap_head indep_loop; /* The set of loops in that the memory
121 reference is independent, meaning:
122 If it is stored in the loop, this store
123 is independent on all other loads and
124 stores.
125 If it is only loaded, then it is independent
126 on all stores in the loop. */
127 bitmap_head dep_loop; /* The complement of INDEP_LOOP. */
128 } *mem_ref_p;
130 /* We use two bits per loop in the ref->{in,}dep_loop bitmaps, the first
131 to record (in)dependence against stores in the loop and its subloops, the
132 second to record (in)dependence against all references in the loop
133 and its subloops. */
134 #define LOOP_DEP_BIT(loopnum, storedp) (2 * (loopnum) + (storedp ? 1 : 0))
138 /* Description of memory accesses in loops. */
140 static struct
142 /* The hash table of memory references accessed in loops. */
143 htab_t refs;
145 /* The list of memory references. */
146 vec<mem_ref_p> refs_list;
148 /* The set of memory references accessed in each loop. */
149 vec<bitmap_head> refs_in_loop;
151 /* The set of memory references stored in each loop. */
152 vec<bitmap_head> refs_stored_in_loop;
154 /* The set of memory references stored in each loop, including subloops . */
155 vec<bitmap_head> all_refs_stored_in_loop;
157 /* Cache for expanding memory addresses. */
158 struct pointer_map_t *ttae_cache;
159 } memory_accesses;
161 /* Obstack for the bitmaps in the above data structures. */
162 static bitmap_obstack lim_bitmap_obstack;
164 static bool ref_indep_loop_p (struct loop *, mem_ref_p);
166 /* Minimum cost of an expensive expression. */
167 #define LIM_EXPENSIVE ((unsigned) PARAM_VALUE (PARAM_LIM_EXPENSIVE))
169 /* The outermost loop for which execution of the header guarantees that the
170 block will be executed. */
171 #define ALWAYS_EXECUTED_IN(BB) ((struct loop *) (BB)->aux)
172 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
174 /* ID of the shared unanalyzable mem. */
175 #define UNANALYZABLE_MEM_ID 0
177 /* Whether the reference was analyzable. */
178 #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
180 static struct lim_aux_data *
181 init_lim_data (gimple stmt)
183 void **p = pointer_map_insert (lim_aux_data_map, stmt);
185 *p = XCNEW (struct lim_aux_data);
186 return (struct lim_aux_data *) *p;
189 static struct lim_aux_data *
190 get_lim_data (gimple stmt)
192 void **p = pointer_map_contains (lim_aux_data_map, stmt);
193 if (!p)
194 return NULL;
196 return (struct lim_aux_data *) *p;
199 /* Releases the memory occupied by DATA. */
201 static void
202 free_lim_aux_data (struct lim_aux_data *data)
204 data->depends.release();
205 free (data);
208 static void
209 clear_lim_data (gimple stmt)
211 void **p = pointer_map_contains (lim_aux_data_map, stmt);
212 if (!p)
213 return;
215 free_lim_aux_data ((struct lim_aux_data *) *p);
216 *p = NULL;
219 /* Calls CBCK for each index in memory reference ADDR_P. There are two
220 kinds situations handled; in each of these cases, the memory reference
221 and DATA are passed to the callback:
223 Access to an array: ARRAY_{RANGE_}REF (base, index). In this case we also
224 pass the pointer to the index to the callback.
226 Pointer dereference: INDIRECT_REF (addr). In this case we also pass the
227 pointer to addr to the callback.
229 If the callback returns false, the whole search stops and false is returned.
230 Otherwise the function returns true after traversing through the whole
231 reference *ADDR_P. */
233 bool
234 for_each_index (tree *addr_p, bool (*cbck) (tree, tree *, void *), void *data)
236 tree *nxt, *idx;
238 for (; ; addr_p = nxt)
240 switch (TREE_CODE (*addr_p))
242 case SSA_NAME:
243 return cbck (*addr_p, addr_p, data);
245 case MEM_REF:
246 nxt = &TREE_OPERAND (*addr_p, 0);
247 return cbck (*addr_p, nxt, data);
249 case BIT_FIELD_REF:
250 case VIEW_CONVERT_EXPR:
251 case REALPART_EXPR:
252 case IMAGPART_EXPR:
253 nxt = &TREE_OPERAND (*addr_p, 0);
254 break;
256 case COMPONENT_REF:
257 /* If the component has varying offset, it behaves like index
258 as well. */
259 idx = &TREE_OPERAND (*addr_p, 2);
260 if (*idx
261 && !cbck (*addr_p, idx, data))
262 return false;
264 nxt = &TREE_OPERAND (*addr_p, 0);
265 break;
267 case ARRAY_REF:
268 case ARRAY_RANGE_REF:
269 nxt = &TREE_OPERAND (*addr_p, 0);
270 if (!cbck (*addr_p, &TREE_OPERAND (*addr_p, 1), data))
271 return false;
272 break;
274 case VAR_DECL:
275 case PARM_DECL:
276 case CONST_DECL:
277 case STRING_CST:
278 case RESULT_DECL:
279 case VECTOR_CST:
280 case COMPLEX_CST:
281 case INTEGER_CST:
282 case REAL_CST:
283 case FIXED_CST:
284 case CONSTRUCTOR:
285 return true;
287 case ADDR_EXPR:
288 gcc_assert (is_gimple_min_invariant (*addr_p));
289 return true;
291 case TARGET_MEM_REF:
292 idx = &TMR_BASE (*addr_p);
293 if (*idx
294 && !cbck (*addr_p, idx, data))
295 return false;
296 idx = &TMR_INDEX (*addr_p);
297 if (*idx
298 && !cbck (*addr_p, idx, data))
299 return false;
300 idx = &TMR_INDEX2 (*addr_p);
301 if (*idx
302 && !cbck (*addr_p, idx, data))
303 return false;
304 return true;
306 default:
307 gcc_unreachable ();
312 /* If it is possible to hoist the statement STMT unconditionally,
313 returns MOVE_POSSIBLE.
314 If it is possible to hoist the statement STMT, but we must avoid making
315 it executed if it would not be executed in the original program (e.g.
316 because it may trap), return MOVE_PRESERVE_EXECUTION.
317 Otherwise return MOVE_IMPOSSIBLE. */
319 enum move_pos
320 movement_possibility (gimple stmt)
322 tree lhs;
323 enum move_pos ret = MOVE_POSSIBLE;
325 if (flag_unswitch_loops
326 && gimple_code (stmt) == GIMPLE_COND)
328 /* If we perform unswitching, force the operands of the invariant
329 condition to be moved out of the loop. */
330 return MOVE_POSSIBLE;
333 if (gimple_code (stmt) == GIMPLE_PHI
334 && gimple_phi_num_args (stmt) <= 2
335 && !virtual_operand_p (gimple_phi_result (stmt))
336 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
337 return MOVE_POSSIBLE;
339 if (gimple_get_lhs (stmt) == NULL_TREE)
340 return MOVE_IMPOSSIBLE;
342 if (gimple_vdef (stmt))
343 return MOVE_IMPOSSIBLE;
345 if (stmt_ends_bb_p (stmt)
346 || gimple_has_volatile_ops (stmt)
347 || gimple_has_side_effects (stmt)
348 || stmt_could_throw_p (stmt))
349 return MOVE_IMPOSSIBLE;
351 if (is_gimple_call (stmt))
353 /* While pure or const call is guaranteed to have no side effects, we
354 cannot move it arbitrarily. Consider code like
356 char *s = something ();
358 while (1)
360 if (s)
361 t = strlen (s);
362 else
363 t = 0;
366 Here the strlen call cannot be moved out of the loop, even though
367 s is invariant. In addition to possibly creating a call with
368 invalid arguments, moving out a function call that is not executed
369 may cause performance regressions in case the call is costly and
370 not executed at all. */
371 ret = MOVE_PRESERVE_EXECUTION;
372 lhs = gimple_call_lhs (stmt);
374 else if (is_gimple_assign (stmt))
375 lhs = gimple_assign_lhs (stmt);
376 else
377 return MOVE_IMPOSSIBLE;
379 if (TREE_CODE (lhs) == SSA_NAME
380 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
381 return MOVE_IMPOSSIBLE;
383 if (TREE_CODE (lhs) != SSA_NAME
384 || gimple_could_trap_p (stmt))
385 return MOVE_PRESERVE_EXECUTION;
387 /* Non local loads in a transaction cannot be hoisted out. Well,
388 unless the load happens on every path out of the loop, but we
389 don't take this into account yet. */
390 if (flag_tm
391 && gimple_in_transaction (stmt)
392 && gimple_assign_single_p (stmt))
394 tree rhs = gimple_assign_rhs1 (stmt);
395 if (DECL_P (rhs) && is_global_var (rhs))
397 if (dump_file)
399 fprintf (dump_file, "Cannot hoist conditional load of ");
400 print_generic_expr (dump_file, rhs, TDF_SLIM);
401 fprintf (dump_file, " because it is in a transaction.\n");
403 return MOVE_IMPOSSIBLE;
407 return ret;
410 /* Suppose that operand DEF is used inside the LOOP. Returns the outermost
411 loop to that we could move the expression using DEF if it did not have
412 other operands, i.e. the outermost loop enclosing LOOP in that the value
413 of DEF is invariant. */
415 static struct loop *
416 outermost_invariant_loop (tree def, struct loop *loop)
418 gimple def_stmt;
419 basic_block def_bb;
420 struct loop *max_loop;
421 struct lim_aux_data *lim_data;
423 if (!def)
424 return superloop_at_depth (loop, 1);
426 if (TREE_CODE (def) != SSA_NAME)
428 gcc_assert (is_gimple_min_invariant (def));
429 return superloop_at_depth (loop, 1);
432 def_stmt = SSA_NAME_DEF_STMT (def);
433 def_bb = gimple_bb (def_stmt);
434 if (!def_bb)
435 return superloop_at_depth (loop, 1);
437 max_loop = find_common_loop (loop, def_bb->loop_father);
439 lim_data = get_lim_data (def_stmt);
440 if (lim_data != NULL && lim_data->max_loop != NULL)
441 max_loop = find_common_loop (max_loop,
442 loop_outer (lim_data->max_loop));
443 if (max_loop == loop)
444 return NULL;
445 max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
447 return max_loop;
450 /* DATA is a structure containing information associated with a statement
451 inside LOOP. DEF is one of the operands of this statement.
453 Find the outermost loop enclosing LOOP in that value of DEF is invariant
454 and record this in DATA->max_loop field. If DEF itself is defined inside
455 this loop as well (i.e. we need to hoist it out of the loop if we want
456 to hoist the statement represented by DATA), record the statement in that
457 DEF is defined to the DATA->depends list. Additionally if ADD_COST is true,
458 add the cost of the computation of DEF to the DATA->cost.
460 If DEF is not invariant in LOOP, return false. Otherwise return TRUE. */
462 static bool
463 add_dependency (tree def, struct lim_aux_data *data, struct loop *loop,
464 bool add_cost)
466 gimple def_stmt = SSA_NAME_DEF_STMT (def);
467 basic_block def_bb = gimple_bb (def_stmt);
468 struct loop *max_loop;
469 struct lim_aux_data *def_data;
471 if (!def_bb)
472 return true;
474 max_loop = outermost_invariant_loop (def, loop);
475 if (!max_loop)
476 return false;
478 if (flow_loop_nested_p (data->max_loop, max_loop))
479 data->max_loop = max_loop;
481 def_data = get_lim_data (def_stmt);
482 if (!def_data)
483 return true;
485 if (add_cost
486 /* Only add the cost if the statement defining DEF is inside LOOP,
487 i.e. if it is likely that by moving the invariants dependent
488 on it, we will be able to avoid creating a new register for
489 it (since it will be only used in these dependent invariants). */
490 && def_bb->loop_father == loop)
491 data->cost += def_data->cost;
493 data->depends.safe_push (def_stmt);
495 return true;
498 /* Returns an estimate for a cost of statement STMT. The values here
499 are just ad-hoc constants, similar to costs for inlining. */
501 static unsigned
502 stmt_cost (gimple stmt)
504 /* Always try to create possibilities for unswitching. */
505 if (gimple_code (stmt) == GIMPLE_COND
506 || gimple_code (stmt) == GIMPLE_PHI)
507 return LIM_EXPENSIVE;
509 /* We should be hoisting calls if possible. */
510 if (is_gimple_call (stmt))
512 tree fndecl;
514 /* Unless the call is a builtin_constant_p; this always folds to a
515 constant, so moving it is useless. */
516 fndecl = gimple_call_fndecl (stmt);
517 if (fndecl
518 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
519 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CONSTANT_P)
520 return 0;
522 return LIM_EXPENSIVE;
525 /* Hoisting memory references out should almost surely be a win. */
526 if (gimple_references_memory_p (stmt))
527 return LIM_EXPENSIVE;
529 if (gimple_code (stmt) != GIMPLE_ASSIGN)
530 return 1;
532 switch (gimple_assign_rhs_code (stmt))
534 case MULT_EXPR:
535 case WIDEN_MULT_EXPR:
536 case WIDEN_MULT_PLUS_EXPR:
537 case WIDEN_MULT_MINUS_EXPR:
538 case DOT_PROD_EXPR:
539 case FMA_EXPR:
540 case TRUNC_DIV_EXPR:
541 case CEIL_DIV_EXPR:
542 case FLOOR_DIV_EXPR:
543 case ROUND_DIV_EXPR:
544 case EXACT_DIV_EXPR:
545 case CEIL_MOD_EXPR:
546 case FLOOR_MOD_EXPR:
547 case ROUND_MOD_EXPR:
548 case TRUNC_MOD_EXPR:
549 case RDIV_EXPR:
550 /* Division and multiplication are usually expensive. */
551 return LIM_EXPENSIVE;
553 case LSHIFT_EXPR:
554 case RSHIFT_EXPR:
555 case WIDEN_LSHIFT_EXPR:
556 case LROTATE_EXPR:
557 case RROTATE_EXPR:
558 /* Shifts and rotates are usually expensive. */
559 return LIM_EXPENSIVE;
561 case CONSTRUCTOR:
562 /* Make vector construction cost proportional to the number
563 of elements. */
564 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
566 case SSA_NAME:
567 case PAREN_EXPR:
568 /* Whether or not something is wrapped inside a PAREN_EXPR
569 should not change move cost. Nor should an intermediate
570 unpropagated SSA name copy. */
571 return 0;
573 default:
574 return 1;
578 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
579 REF is independent. If REF is not independent in LOOP, NULL is returned
580 instead. */
582 static struct loop *
583 outermost_indep_loop (struct loop *outer, struct loop *loop, mem_ref_p ref)
585 struct loop *aloop;
587 if (bitmap_bit_p (&ref->stored, loop->num))
588 return NULL;
590 for (aloop = outer;
591 aloop != loop;
592 aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
593 if (!bitmap_bit_p (&ref->stored, aloop->num)
594 && ref_indep_loop_p (aloop, ref))
595 return aloop;
597 if (ref_indep_loop_p (loop, ref))
598 return loop;
599 else
600 return NULL;
603 /* If there is a simple load or store to a memory reference in STMT, returns
604 the location of the memory reference, and sets IS_STORE according to whether
605 it is a store or load. Otherwise, returns NULL. */
607 static tree *
608 simple_mem_ref_in_stmt (gimple stmt, bool *is_store)
610 tree *lhs, *rhs;
612 /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns. */
613 if (!gimple_assign_single_p (stmt))
614 return NULL;
616 lhs = gimple_assign_lhs_ptr (stmt);
617 rhs = gimple_assign_rhs1_ptr (stmt);
619 if (TREE_CODE (*lhs) == SSA_NAME && gimple_vuse (stmt))
621 *is_store = false;
622 return rhs;
624 else if (gimple_vdef (stmt)
625 && (TREE_CODE (*rhs) == SSA_NAME || is_gimple_min_invariant (*rhs)))
627 *is_store = true;
628 return lhs;
630 else
631 return NULL;
634 /* Returns the memory reference contained in STMT. */
636 static mem_ref_p
637 mem_ref_in_stmt (gimple stmt)
639 bool store;
640 tree *mem = simple_mem_ref_in_stmt (stmt, &store);
641 hashval_t hash;
642 mem_ref_p ref;
644 if (!mem)
645 return NULL;
646 gcc_assert (!store);
648 hash = iterative_hash_expr (*mem, 0);
649 ref = (mem_ref_p) htab_find_with_hash (memory_accesses.refs, *mem, hash);
651 gcc_assert (ref != NULL);
652 return ref;
655 /* From a controlling predicate in DOM determine the arguments from
656 the PHI node PHI that are chosen if the predicate evaluates to
657 true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
658 they are non-NULL. Returns true if the arguments can be determined,
659 else return false. */
661 static bool
662 extract_true_false_args_from_phi (basic_block dom, gimple phi,
663 tree *true_arg_p, tree *false_arg_p)
665 basic_block bb = gimple_bb (phi);
666 edge true_edge, false_edge, tem;
667 tree arg0 = NULL_TREE, arg1 = NULL_TREE;
669 /* We have to verify that one edge into the PHI node is dominated
670 by the true edge of the predicate block and the other edge
671 dominated by the false edge. This ensures that the PHI argument
672 we are going to take is completely determined by the path we
673 take from the predicate block.
674 We can only use BB dominance checks below if the destination of
675 the true/false edges are dominated by their edge, thus only
676 have a single predecessor. */
677 extract_true_false_edges_from_block (dom, &true_edge, &false_edge);
678 tem = EDGE_PRED (bb, 0);
679 if (tem == true_edge
680 || (single_pred_p (true_edge->dest)
681 && (tem->src == true_edge->dest
682 || dominated_by_p (CDI_DOMINATORS,
683 tem->src, true_edge->dest))))
684 arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
685 else if (tem == false_edge
686 || (single_pred_p (false_edge->dest)
687 && (tem->src == false_edge->dest
688 || dominated_by_p (CDI_DOMINATORS,
689 tem->src, false_edge->dest))))
690 arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
691 else
692 return false;
693 tem = EDGE_PRED (bb, 1);
694 if (tem == true_edge
695 || (single_pred_p (true_edge->dest)
696 && (tem->src == true_edge->dest
697 || dominated_by_p (CDI_DOMINATORS,
698 tem->src, true_edge->dest))))
699 arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
700 else if (tem == false_edge
701 || (single_pred_p (false_edge->dest)
702 && (tem->src == false_edge->dest
703 || dominated_by_p (CDI_DOMINATORS,
704 tem->src, false_edge->dest))))
705 arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
706 else
707 return false;
708 if (!arg0 || !arg1)
709 return false;
711 if (true_arg_p)
712 *true_arg_p = arg0;
713 if (false_arg_p)
714 *false_arg_p = arg1;
716 return true;
719 /* Determine the outermost loop to that it is possible to hoist a statement
720 STMT and store it to LIM_DATA (STMT)->max_loop. To do this we determine
721 the outermost loop in that the value computed by STMT is invariant.
722 If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
723 we preserve the fact whether STMT is executed. It also fills other related
724 information to LIM_DATA (STMT).
726 The function returns false if STMT cannot be hoisted outside of the loop it
727 is defined in, and true otherwise. */
729 static bool
730 determine_max_movement (gimple stmt, bool must_preserve_exec)
732 basic_block bb = gimple_bb (stmt);
733 struct loop *loop = bb->loop_father;
734 struct loop *level;
735 struct lim_aux_data *lim_data = get_lim_data (stmt);
736 tree val;
737 ssa_op_iter iter;
739 if (must_preserve_exec)
740 level = ALWAYS_EXECUTED_IN (bb);
741 else
742 level = superloop_at_depth (loop, 1);
743 lim_data->max_loop = level;
745 if (gimple_code (stmt) == GIMPLE_PHI)
747 use_operand_p use_p;
748 unsigned min_cost = UINT_MAX;
749 unsigned total_cost = 0;
750 struct lim_aux_data *def_data;
752 /* We will end up promoting dependencies to be unconditionally
753 evaluated. For this reason the PHI cost (and thus the
754 cost we remove from the loop by doing the invariant motion)
755 is that of the cheapest PHI argument dependency chain. */
756 FOR_EACH_PHI_ARG (use_p, stmt, iter, SSA_OP_USE)
758 val = USE_FROM_PTR (use_p);
759 if (TREE_CODE (val) != SSA_NAME)
760 continue;
761 if (!add_dependency (val, lim_data, loop, false))
762 return false;
763 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
764 if (def_data)
766 min_cost = MIN (min_cost, def_data->cost);
767 total_cost += def_data->cost;
771 lim_data->cost += min_cost;
773 if (gimple_phi_num_args (stmt) > 1)
775 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
776 gimple cond;
777 if (gsi_end_p (gsi_last_bb (dom)))
778 return false;
779 cond = gsi_stmt (gsi_last_bb (dom));
780 if (gimple_code (cond) != GIMPLE_COND)
781 return false;
782 /* Verify that this is an extended form of a diamond and
783 the PHI arguments are completely controlled by the
784 predicate in DOM. */
785 if (!extract_true_false_args_from_phi (dom, stmt, NULL, NULL))
786 return false;
788 /* Fold in dependencies and cost of the condition. */
789 FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
791 if (!add_dependency (val, lim_data, loop, false))
792 return false;
793 def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
794 if (def_data)
795 total_cost += def_data->cost;
798 /* We want to avoid unconditionally executing very expensive
799 operations. As costs for our dependencies cannot be
800 negative just claim we are not invariand for this case.
801 We also are not sure whether the control-flow inside the
802 loop will vanish. */
803 if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
804 && !(min_cost != 0
805 && total_cost / min_cost <= 2))
806 return false;
808 /* Assume that the control-flow in the loop will vanish.
809 ??? We should verify this and not artificially increase
810 the cost if that is not the case. */
811 lim_data->cost += stmt_cost (stmt);
814 return true;
816 else
817 FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
818 if (!add_dependency (val, lim_data, loop, true))
819 return false;
821 if (gimple_vuse (stmt))
823 mem_ref_p ref = mem_ref_in_stmt (stmt);
825 if (ref)
827 lim_data->max_loop
828 = outermost_indep_loop (lim_data->max_loop, loop, ref);
829 if (!lim_data->max_loop)
830 return false;
832 else
834 if ((val = gimple_vuse (stmt)) != NULL_TREE)
836 if (!add_dependency (val, lim_data, loop, false))
837 return false;
842 lim_data->cost += stmt_cost (stmt);
844 return true;
847 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
848 and that one of the operands of this statement is computed by STMT.
849 Ensure that STMT (together with all the statements that define its
850 operands) is hoisted at least out of the loop LEVEL. */
852 static void
853 set_level (gimple stmt, struct loop *orig_loop, struct loop *level)
855 struct loop *stmt_loop = gimple_bb (stmt)->loop_father;
856 struct lim_aux_data *lim_data;
857 gimple dep_stmt;
858 unsigned i;
860 stmt_loop = find_common_loop (orig_loop, stmt_loop);
861 lim_data = get_lim_data (stmt);
862 if (lim_data != NULL && lim_data->tgt_loop != NULL)
863 stmt_loop = find_common_loop (stmt_loop,
864 loop_outer (lim_data->tgt_loop));
865 if (flow_loop_nested_p (stmt_loop, level))
866 return;
868 gcc_assert (level == lim_data->max_loop
869 || flow_loop_nested_p (lim_data->max_loop, level));
871 lim_data->tgt_loop = level;
872 FOR_EACH_VEC_ELT (lim_data->depends, i, dep_stmt)
873 set_level (dep_stmt, orig_loop, level);
876 /* Determines an outermost loop from that we want to hoist the statement STMT.
877 For now we chose the outermost possible loop. TODO -- use profiling
878 information to set it more sanely. */
880 static void
881 set_profitable_level (gimple stmt)
883 set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
886 /* Returns true if STMT is a call that has side effects. */
888 static bool
889 nonpure_call_p (gimple stmt)
891 if (gimple_code (stmt) != GIMPLE_CALL)
892 return false;
894 return gimple_has_side_effects (stmt);
897 /* Rewrite a/b to a*(1/b). Return the invariant stmt to process. */
899 static gimple
900 rewrite_reciprocal (gimple_stmt_iterator *bsi)
902 gimple stmt, stmt1, stmt2;
903 tree name, lhs, type;
904 tree real_one;
905 gimple_stmt_iterator gsi;
907 stmt = gsi_stmt (*bsi);
908 lhs = gimple_assign_lhs (stmt);
909 type = TREE_TYPE (lhs);
911 real_one = build_one_cst (type);
913 name = make_temp_ssa_name (type, NULL, "reciptmp");
914 stmt1 = gimple_build_assign_with_ops (RDIV_EXPR, name, real_one,
915 gimple_assign_rhs2 (stmt));
917 stmt2 = gimple_build_assign_with_ops (MULT_EXPR, lhs, name,
918 gimple_assign_rhs1 (stmt));
920 /* Replace division stmt with reciprocal and multiply stmts.
921 The multiply stmt is not invariant, so update iterator
922 and avoid rescanning. */
923 gsi = *bsi;
924 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
925 gsi_replace (&gsi, stmt2, true);
927 /* Continue processing with invariant reciprocal statement. */
928 return stmt1;
931 /* Check if the pattern at *BSI is a bittest of the form
932 (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0. */
934 static gimple
935 rewrite_bittest (gimple_stmt_iterator *bsi)
937 gimple stmt, use_stmt, stmt1, stmt2;
938 tree lhs, name, t, a, b;
939 use_operand_p use;
941 stmt = gsi_stmt (*bsi);
942 lhs = gimple_assign_lhs (stmt);
944 /* Verify that the single use of lhs is a comparison against zero. */
945 if (TREE_CODE (lhs) != SSA_NAME
946 || !single_imm_use (lhs, &use, &use_stmt)
947 || gimple_code (use_stmt) != GIMPLE_COND)
948 return stmt;
949 if (gimple_cond_lhs (use_stmt) != lhs
950 || (gimple_cond_code (use_stmt) != NE_EXPR
951 && gimple_cond_code (use_stmt) != EQ_EXPR)
952 || !integer_zerop (gimple_cond_rhs (use_stmt)))
953 return stmt;
955 /* Get at the operands of the shift. The rhs is TMP1 & 1. */
956 stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
957 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
958 return stmt;
960 /* There is a conversion in between possibly inserted by fold. */
961 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
963 t = gimple_assign_rhs1 (stmt1);
964 if (TREE_CODE (t) != SSA_NAME
965 || !has_single_use (t))
966 return stmt;
967 stmt1 = SSA_NAME_DEF_STMT (t);
968 if (gimple_code (stmt1) != GIMPLE_ASSIGN)
969 return stmt;
972 /* Verify that B is loop invariant but A is not. Verify that with
973 all the stmt walking we are still in the same loop. */
974 if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
975 || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
976 return stmt;
978 a = gimple_assign_rhs1 (stmt1);
979 b = gimple_assign_rhs2 (stmt1);
981 if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
982 && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
984 gimple_stmt_iterator rsi;
986 /* 1 << B */
987 t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
988 build_int_cst (TREE_TYPE (a), 1), b);
989 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
990 stmt1 = gimple_build_assign (name, t);
992 /* A & (1 << B) */
993 t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
994 name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
995 stmt2 = gimple_build_assign (name, t);
997 /* Replace the SSA_NAME we compare against zero. Adjust
998 the type of zero accordingly. */
999 SET_USE (use, name);
1000 gimple_cond_set_rhs (use_stmt, build_int_cst_type (TREE_TYPE (name), 0));
1002 /* Don't use gsi_replace here, none of the new assignments sets
1003 the variable originally set in stmt. Move bsi to stmt1, and
1004 then remove the original stmt, so that we get a chance to
1005 retain debug info for it. */
1006 rsi = *bsi;
1007 gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1008 gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
1009 gsi_remove (&rsi, true);
1011 return stmt1;
1014 return stmt;
1018 /* Determine the outermost loops in that statements in basic block BB are
1019 invariant, and record them to the LIM_DATA associated with the statements.
1020 Callback for walk_dominator_tree. */
1022 static void
1023 determine_invariantness_stmt (struct dom_walk_data *dw_data ATTRIBUTE_UNUSED,
1024 basic_block bb)
1026 enum move_pos pos;
1027 gimple_stmt_iterator bsi;
1028 gimple stmt;
1029 bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
1030 struct loop *outermost = ALWAYS_EXECUTED_IN (bb);
1031 struct lim_aux_data *lim_data;
1033 if (!loop_outer (bb->loop_father))
1034 return;
1036 if (dump_file && (dump_flags & TDF_DETAILS))
1037 fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
1038 bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
1040 /* Look at PHI nodes, but only if there is at most two.
1041 ??? We could relax this further by post-processing the inserted
1042 code and transforming adjacent cond-exprs with the same predicate
1043 to control flow again. */
1044 bsi = gsi_start_phis (bb);
1045 if (!gsi_end_p (bsi)
1046 && ((gsi_next (&bsi), gsi_end_p (bsi))
1047 || (gsi_next (&bsi), gsi_end_p (bsi))))
1048 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1050 stmt = gsi_stmt (bsi);
1052 pos = movement_possibility (stmt);
1053 if (pos == MOVE_IMPOSSIBLE)
1054 continue;
1056 lim_data = init_lim_data (stmt);
1057 lim_data->always_executed_in = outermost;
1059 if (!determine_max_movement (stmt, false))
1061 lim_data->max_loop = NULL;
1062 continue;
1065 if (dump_file && (dump_flags & TDF_DETAILS))
1067 print_gimple_stmt (dump_file, stmt, 2, 0);
1068 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1069 loop_depth (lim_data->max_loop),
1070 lim_data->cost);
1073 if (lim_data->cost >= LIM_EXPENSIVE)
1074 set_profitable_level (stmt);
1077 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1079 stmt = gsi_stmt (bsi);
1081 pos = movement_possibility (stmt);
1082 if (pos == MOVE_IMPOSSIBLE)
1084 if (nonpure_call_p (stmt))
1086 maybe_never = true;
1087 outermost = NULL;
1089 /* Make sure to note always_executed_in for stores to make
1090 store-motion work. */
1091 else if (stmt_makes_single_store (stmt))
1093 struct lim_aux_data *lim_data = init_lim_data (stmt);
1094 lim_data->always_executed_in = outermost;
1096 continue;
1099 if (is_gimple_assign (stmt)
1100 && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1101 == GIMPLE_BINARY_RHS))
1103 tree op0 = gimple_assign_rhs1 (stmt);
1104 tree op1 = gimple_assign_rhs2 (stmt);
1105 struct loop *ol1 = outermost_invariant_loop (op1,
1106 loop_containing_stmt (stmt));
1108 /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1109 to be hoisted out of loop, saving expensive divide. */
1110 if (pos == MOVE_POSSIBLE
1111 && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1112 && flag_unsafe_math_optimizations
1113 && !flag_trapping_math
1114 && ol1 != NULL
1115 && outermost_invariant_loop (op0, ol1) == NULL)
1116 stmt = rewrite_reciprocal (&bsi);
1118 /* If the shift count is invariant, convert (A >> B) & 1 to
1119 A & (1 << B) allowing the bit mask to be hoisted out of the loop
1120 saving an expensive shift. */
1121 if (pos == MOVE_POSSIBLE
1122 && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1123 && integer_onep (op1)
1124 && TREE_CODE (op0) == SSA_NAME
1125 && has_single_use (op0))
1126 stmt = rewrite_bittest (&bsi);
1129 lim_data = init_lim_data (stmt);
1130 lim_data->always_executed_in = outermost;
1132 if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1133 continue;
1135 if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1137 lim_data->max_loop = NULL;
1138 continue;
1141 if (dump_file && (dump_flags & TDF_DETAILS))
1143 print_gimple_stmt (dump_file, stmt, 2, 0);
1144 fprintf (dump_file, " invariant up to level %d, cost %d.\n\n",
1145 loop_depth (lim_data->max_loop),
1146 lim_data->cost);
1149 if (lim_data->cost >= LIM_EXPENSIVE)
1150 set_profitable_level (stmt);
1154 /* For each statement determines the outermost loop in that it is invariant,
1155 statements on whose motion it depends and the cost of the computation.
1156 This information is stored to the LIM_DATA structure associated with
1157 each statement. */
1159 static void
1160 determine_invariantness (void)
1162 struct dom_walk_data walk_data;
1164 memset (&walk_data, 0, sizeof (struct dom_walk_data));
1165 walk_data.dom_direction = CDI_DOMINATORS;
1166 walk_data.before_dom_children = determine_invariantness_stmt;
1168 init_walk_dominator_tree (&walk_data);
1169 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1170 fini_walk_dominator_tree (&walk_data);
1173 /* Hoist the statements in basic block BB out of the loops prescribed by
1174 data stored in LIM_DATA structures associated with each statement. Callback
1175 for walk_dominator_tree. */
1177 static void
1178 move_computations_stmt (struct dom_walk_data *dw_data,
1179 basic_block bb)
1181 struct loop *level;
1182 gimple_stmt_iterator bsi;
1183 gimple stmt;
1184 unsigned cost = 0;
1185 struct lim_aux_data *lim_data;
1187 if (!loop_outer (bb->loop_father))
1188 return;
1190 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1192 gimple new_stmt;
1193 stmt = gsi_stmt (bsi);
1195 lim_data = get_lim_data (stmt);
1196 if (lim_data == NULL)
1198 gsi_next (&bsi);
1199 continue;
1202 cost = lim_data->cost;
1203 level = lim_data->tgt_loop;
1204 clear_lim_data (stmt);
1206 if (!level)
1208 gsi_next (&bsi);
1209 continue;
1212 if (dump_file && (dump_flags & TDF_DETAILS))
1214 fprintf (dump_file, "Moving PHI node\n");
1215 print_gimple_stmt (dump_file, stmt, 0, 0);
1216 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1217 cost, level->num);
1220 if (gimple_phi_num_args (stmt) == 1)
1222 tree arg = PHI_ARG_DEF (stmt, 0);
1223 new_stmt = gimple_build_assign_with_ops (TREE_CODE (arg),
1224 gimple_phi_result (stmt),
1225 arg, NULL_TREE);
1226 SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1228 else
1230 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1231 gimple cond = gsi_stmt (gsi_last_bb (dom));
1232 tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1233 /* Get the PHI arguments corresponding to the true and false
1234 edges of COND. */
1235 extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1236 gcc_assert (arg0 && arg1);
1237 t = build2 (gimple_cond_code (cond), boolean_type_node,
1238 gimple_cond_lhs (cond), gimple_cond_rhs (cond));
1239 new_stmt = gimple_build_assign_with_ops (COND_EXPR,
1240 gimple_phi_result (stmt),
1241 t, arg0, arg1);
1242 SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1243 *((unsigned int *)(dw_data->global_data)) |= TODO_cleanup_cfg;
1245 gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1246 remove_phi_node (&bsi, false);
1249 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1251 edge e;
1253 stmt = gsi_stmt (bsi);
1255 lim_data = get_lim_data (stmt);
1256 if (lim_data == NULL)
1258 gsi_next (&bsi);
1259 continue;
1262 cost = lim_data->cost;
1263 level = lim_data->tgt_loop;
1264 clear_lim_data (stmt);
1266 if (!level)
1268 gsi_next (&bsi);
1269 continue;
1272 /* We do not really want to move conditionals out of the loop; we just
1273 placed it here to force its operands to be moved if necessary. */
1274 if (gimple_code (stmt) == GIMPLE_COND)
1275 continue;
1277 if (dump_file && (dump_flags & TDF_DETAILS))
1279 fprintf (dump_file, "Moving statement\n");
1280 print_gimple_stmt (dump_file, stmt, 0, 0);
1281 fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1282 cost, level->num);
1285 e = loop_preheader_edge (level);
1286 gcc_assert (!gimple_vdef (stmt));
1287 if (gimple_vuse (stmt))
1289 /* The new VUSE is the one from the virtual PHI in the loop
1290 header or the one already present. */
1291 gimple_stmt_iterator gsi2;
1292 for (gsi2 = gsi_start_phis (e->dest);
1293 !gsi_end_p (gsi2); gsi_next (&gsi2))
1295 gimple phi = gsi_stmt (gsi2);
1296 if (virtual_operand_p (gimple_phi_result (phi)))
1298 gimple_set_vuse (stmt, PHI_ARG_DEF_FROM_EDGE (phi, e));
1299 break;
1303 gsi_remove (&bsi, false);
1304 gsi_insert_on_edge (e, stmt);
1308 /* Hoist the statements out of the loops prescribed by data stored in
1309 LIM_DATA structures associated with each statement.*/
1311 static unsigned int
1312 move_computations (void)
1314 struct dom_walk_data walk_data;
1315 unsigned int todo = 0;
1317 memset (&walk_data, 0, sizeof (struct dom_walk_data));
1318 walk_data.global_data = &todo;
1319 walk_data.dom_direction = CDI_DOMINATORS;
1320 walk_data.before_dom_children = move_computations_stmt;
1322 init_walk_dominator_tree (&walk_data);
1323 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1324 fini_walk_dominator_tree (&walk_data);
1326 gsi_commit_edge_inserts ();
1327 if (need_ssa_update_p (cfun))
1328 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1330 return todo;
1333 /* Checks whether the statement defining variable *INDEX can be hoisted
1334 out of the loop passed in DATA. Callback for for_each_index. */
1336 static bool
1337 may_move_till (tree ref, tree *index, void *data)
1339 struct loop *loop = (struct loop *) data, *max_loop;
1341 /* If REF is an array reference, check also that the step and the lower
1342 bound is invariant in LOOP. */
1343 if (TREE_CODE (ref) == ARRAY_REF)
1345 tree step = TREE_OPERAND (ref, 3);
1346 tree lbound = TREE_OPERAND (ref, 2);
1348 max_loop = outermost_invariant_loop (step, loop);
1349 if (!max_loop)
1350 return false;
1352 max_loop = outermost_invariant_loop (lbound, loop);
1353 if (!max_loop)
1354 return false;
1357 max_loop = outermost_invariant_loop (*index, loop);
1358 if (!max_loop)
1359 return false;
1361 return true;
1364 /* If OP is SSA NAME, force the statement that defines it to be
1365 moved out of the LOOP. ORIG_LOOP is the loop in that EXPR is used. */
1367 static void
1368 force_move_till_op (tree op, struct loop *orig_loop, struct loop *loop)
1370 gimple stmt;
1372 if (!op
1373 || is_gimple_min_invariant (op))
1374 return;
1376 gcc_assert (TREE_CODE (op) == SSA_NAME);
1378 stmt = SSA_NAME_DEF_STMT (op);
1379 if (gimple_nop_p (stmt))
1380 return;
1382 set_level (stmt, orig_loop, loop);
1385 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1386 the LOOP. The reference REF is used in the loop ORIG_LOOP. Callback for
1387 for_each_index. */
1389 struct fmt_data
1391 struct loop *loop;
1392 struct loop *orig_loop;
1395 static bool
1396 force_move_till (tree ref, tree *index, void *data)
1398 struct fmt_data *fmt_data = (struct fmt_data *) data;
1400 if (TREE_CODE (ref) == ARRAY_REF)
1402 tree step = TREE_OPERAND (ref, 3);
1403 tree lbound = TREE_OPERAND (ref, 2);
1405 force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1406 force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1409 force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1411 return true;
1414 /* A hash function for struct mem_ref object OBJ. */
1416 static hashval_t
1417 memref_hash (const void *obj)
1419 const struct mem_ref *const mem = (const struct mem_ref *) obj;
1421 return mem->hash;
1424 /* An equality function for struct mem_ref object OBJ1 with
1425 memory reference OBJ2. */
1427 static int
1428 memref_eq (const void *obj1, const void *obj2)
1430 const struct mem_ref *const mem1 = (const struct mem_ref *) obj1;
1432 return operand_equal_p (mem1->mem.ref, (const_tree) obj2, 0);
1435 /* A function to free the mem_ref object OBJ. */
1437 static void
1438 memref_free (struct mem_ref *mem)
1440 unsigned i;
1441 vec<mem_ref_loc> *accs;
1443 FOR_EACH_VEC_ELT (mem->accesses_in_loop, i, accs)
1444 accs->release ();
1445 mem->accesses_in_loop.release ();
1447 free (mem);
1450 /* Allocates and returns a memory reference description for MEM whose hash
1451 value is HASH and id is ID. */
1453 static mem_ref_p
1454 mem_ref_alloc (tree mem, unsigned hash, unsigned id)
1456 mem_ref_p ref = XNEW (struct mem_ref);
1457 ao_ref_init (&ref->mem, mem);
1458 ref->id = id;
1459 ref->hash = hash;
1460 bitmap_initialize (&ref->stored, &lim_bitmap_obstack);
1461 bitmap_initialize (&ref->indep_loop, &lim_bitmap_obstack);
1462 bitmap_initialize (&ref->dep_loop, &lim_bitmap_obstack);
1463 ref->accesses_in_loop.create (0);
1465 return ref;
1468 /* Records memory reference location *LOC in LOOP to the memory reference
1469 description REF. The reference occurs in statement STMT. */
1471 static void
1472 record_mem_ref_loc (mem_ref_p ref, struct loop *loop, gimple stmt, tree *loc)
1474 mem_ref_loc aref;
1476 if (ref->accesses_in_loop.length ()
1477 <= (unsigned) loop->num)
1478 ref->accesses_in_loop.safe_grow_cleared (loop->num + 1);
1480 aref.stmt = stmt;
1481 aref.ref = loc;
1482 ref->accesses_in_loop[loop->num].safe_push (aref);
1485 /* Marks reference REF as stored in LOOP. */
1487 static void
1488 mark_ref_stored (mem_ref_p ref, struct loop *loop)
1490 while (loop != current_loops->tree_root
1491 && bitmap_set_bit (&ref->stored, loop->num))
1492 loop = loop_outer (loop);
1495 /* Gathers memory references in statement STMT in LOOP, storing the
1496 information about them in the memory_accesses structure. Marks
1497 the vops accessed through unrecognized statements there as
1498 well. */
1500 static void
1501 gather_mem_refs_stmt (struct loop *loop, gimple stmt)
1503 tree *mem = NULL;
1504 hashval_t hash;
1505 PTR *slot;
1506 mem_ref_p ref;
1507 bool is_stored;
1508 unsigned id;
1510 if (!gimple_vuse (stmt))
1511 return;
1513 mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1514 if (!mem)
1516 /* We use the shared mem_ref for all unanalyzable refs. */
1517 id = UNANALYZABLE_MEM_ID;
1518 ref = memory_accesses.refs_list[id];
1519 if (dump_file && (dump_flags & TDF_DETAILS))
1521 fprintf (dump_file, "Unanalyzed memory reference %u: ", id);
1522 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1524 is_stored = gimple_vdef (stmt);
1526 else
1528 hash = iterative_hash_expr (*mem, 0);
1529 slot = htab_find_slot_with_hash (memory_accesses.refs,
1530 *mem, hash, INSERT);
1531 if (*slot)
1533 ref = (mem_ref_p) *slot;
1534 id = ref->id;
1536 else
1538 id = memory_accesses.refs_list.length ();
1539 ref = mem_ref_alloc (*mem, hash, id);
1540 memory_accesses.refs_list.safe_push (ref);
1541 *slot = ref;
1543 if (dump_file && (dump_flags & TDF_DETAILS))
1545 fprintf (dump_file, "Memory reference %u: ", id);
1546 print_generic_expr (dump_file, ref->mem.ref, TDF_SLIM);
1547 fprintf (dump_file, "\n");
1551 record_mem_ref_loc (ref, loop, stmt, mem);
1553 bitmap_set_bit (&memory_accesses.refs_in_loop[loop->num], ref->id);
1554 if (is_stored)
1556 bitmap_set_bit (&memory_accesses.refs_stored_in_loop[loop->num], ref->id);
1557 mark_ref_stored (ref, loop);
1559 return;
1562 static unsigned *bb_loop_postorder;
1564 /* qsort sort function to sort blocks after their loop fathers postorder. */
1566 static int
1567 sort_bbs_in_loop_postorder_cmp (const void *bb1_, const void *bb2_)
1569 basic_block bb1 = *(basic_block *)const_cast<void *>(bb1_);
1570 basic_block bb2 = *(basic_block *)const_cast<void *>(bb2_);
1571 struct loop *loop1 = bb1->loop_father;
1572 struct loop *loop2 = bb2->loop_father;
1573 if (loop1->num == loop2->num)
1574 return 0;
1575 return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
1578 /* Gathers memory references in loops. */
1580 static void
1581 analyze_memory_references (void)
1583 gimple_stmt_iterator bsi;
1584 basic_block bb, *bbs;
1585 struct loop *loop, *outer;
1586 loop_iterator li;
1587 unsigned i, n;
1589 /* Initialize bb_loop_postorder with a mapping from loop->num to
1590 its postorder index. */
1591 i = 0;
1592 bb_loop_postorder = XNEWVEC (unsigned, number_of_loops ());
1593 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1594 bb_loop_postorder[loop->num] = i++;
1595 /* Collect all basic-blocks in loops and sort them after their
1596 loops postorder. */
1597 i = 0;
1598 bbs = XNEWVEC (basic_block, n_basic_blocks - NUM_FIXED_BLOCKS);
1599 FOR_EACH_BB (bb)
1600 if (bb->loop_father != current_loops->tree_root)
1601 bbs[i++] = bb;
1602 n = i;
1603 qsort (bbs, n, sizeof (basic_block), sort_bbs_in_loop_postorder_cmp);
1604 free (bb_loop_postorder);
1606 /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
1607 That results in better locality for all the bitmaps. */
1608 for (i = 0; i < n; ++i)
1610 basic_block bb = bbs[i];
1611 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1612 gather_mem_refs_stmt (bb->loop_father, gsi_stmt (bsi));
1615 free (bbs);
1617 /* Propagate the information about accessed memory references up
1618 the loop hierarchy. */
1619 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1621 /* Finalize the overall touched references (including subloops). */
1622 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[loop->num],
1623 &memory_accesses.refs_stored_in_loop[loop->num]);
1625 /* Propagate the information about accessed memory references up
1626 the loop hierarchy. */
1627 outer = loop_outer (loop);
1628 if (outer == current_loops->tree_root)
1629 continue;
1631 bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[outer->num],
1632 &memory_accesses.all_refs_stored_in_loop[loop->num]);
1636 /* Returns true if MEM1 and MEM2 may alias. TTAE_CACHE is used as a cache in
1637 tree_to_aff_combination_expand. */
1639 static bool
1640 mem_refs_may_alias_p (mem_ref_p mem1, mem_ref_p mem2,
1641 struct pointer_map_t **ttae_cache)
1643 /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1644 object and their offset differ in such a way that the locations cannot
1645 overlap, then they cannot alias. */
1646 double_int size1, size2;
1647 aff_tree off1, off2;
1649 /* Perform basic offset and type-based disambiguation. */
1650 if (!refs_may_alias_p_1 (&mem1->mem, &mem2->mem, true))
1651 return false;
1653 /* The expansion of addresses may be a bit expensive, thus we only do
1654 the check at -O2 and higher optimization levels. */
1655 if (optimize < 2)
1656 return true;
1658 get_inner_reference_aff (mem1->mem.ref, &off1, &size1);
1659 get_inner_reference_aff (mem2->mem.ref, &off2, &size2);
1660 aff_combination_expand (&off1, ttae_cache);
1661 aff_combination_expand (&off2, ttae_cache);
1662 aff_combination_scale (&off1, double_int_minus_one);
1663 aff_combination_add (&off2, &off1);
1665 if (aff_comb_cannot_overlap_p (&off2, size1, size2))
1666 return false;
1668 return true;
1671 /* Iterates over all locations of REF in LOOP and its subloops calling
1672 fn.operator() with the location as argument. When that operator
1673 returns true the iteration is stopped and true is returned.
1674 Otherwise false is returned. */
1676 template <typename FN>
1677 static bool
1678 for_all_locs_in_loop (struct loop *loop, mem_ref_p ref, FN fn)
1680 unsigned i;
1681 mem_ref_loc_p loc;
1682 struct loop *subloop;
1684 if (ref->accesses_in_loop.length () > (unsigned) loop->num)
1685 FOR_EACH_VEC_ELT (ref->accesses_in_loop[loop->num], i, loc)
1686 if (fn (loc))
1687 return true;
1689 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
1690 if (for_all_locs_in_loop (subloop, ref, fn))
1691 return true;
1693 return false;
1696 /* Rewrites location LOC by TMP_VAR. */
1698 struct rewrite_mem_ref_loc
1700 rewrite_mem_ref_loc (tree tmp_var_) : tmp_var (tmp_var_) {}
1701 bool operator()(mem_ref_loc_p loc);
1702 tree tmp_var;
1705 bool
1706 rewrite_mem_ref_loc::operator()(mem_ref_loc_p loc)
1708 *loc->ref = tmp_var;
1709 update_stmt (loc->stmt);
1710 return false;
1713 /* Rewrites all references to REF in LOOP by variable TMP_VAR. */
1715 static void
1716 rewrite_mem_refs (struct loop *loop, mem_ref_p ref, tree tmp_var)
1718 for_all_locs_in_loop (loop, ref, rewrite_mem_ref_loc (tmp_var));
1721 /* The name and the length of the currently generated variable
1722 for lsm. */
1723 #define MAX_LSM_NAME_LENGTH 40
1724 static char lsm_tmp_name[MAX_LSM_NAME_LENGTH + 1];
1725 static int lsm_tmp_name_length;
1727 /* Adds S to lsm_tmp_name. */
1729 static void
1730 lsm_tmp_name_add (const char *s)
1732 int l = strlen (s) + lsm_tmp_name_length;
1733 if (l > MAX_LSM_NAME_LENGTH)
1734 return;
1736 strcpy (lsm_tmp_name + lsm_tmp_name_length, s);
1737 lsm_tmp_name_length = l;
1740 /* Stores the name for temporary variable that replaces REF to
1741 lsm_tmp_name. */
1743 static void
1744 gen_lsm_tmp_name (tree ref)
1746 const char *name;
1748 switch (TREE_CODE (ref))
1750 case MEM_REF:
1751 case TARGET_MEM_REF:
1752 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1753 lsm_tmp_name_add ("_");
1754 break;
1756 case ADDR_EXPR:
1757 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1758 break;
1760 case BIT_FIELD_REF:
1761 case VIEW_CONVERT_EXPR:
1762 case ARRAY_RANGE_REF:
1763 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1764 break;
1766 case REALPART_EXPR:
1767 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1768 lsm_tmp_name_add ("_RE");
1769 break;
1771 case IMAGPART_EXPR:
1772 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1773 lsm_tmp_name_add ("_IM");
1774 break;
1776 case COMPONENT_REF:
1777 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1778 lsm_tmp_name_add ("_");
1779 name = get_name (TREE_OPERAND (ref, 1));
1780 if (!name)
1781 name = "F";
1782 lsm_tmp_name_add (name);
1783 break;
1785 case ARRAY_REF:
1786 gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1787 lsm_tmp_name_add ("_I");
1788 break;
1790 case SSA_NAME:
1791 case VAR_DECL:
1792 case PARM_DECL:
1793 name = get_name (ref);
1794 if (!name)
1795 name = "D";
1796 lsm_tmp_name_add (name);
1797 break;
1799 case STRING_CST:
1800 lsm_tmp_name_add ("S");
1801 break;
1803 case RESULT_DECL:
1804 lsm_tmp_name_add ("R");
1805 break;
1807 case INTEGER_CST:
1808 /* Nothing. */
1809 break;
1811 default:
1812 gcc_unreachable ();
1816 /* Determines name for temporary variable that replaces REF.
1817 The name is accumulated into the lsm_tmp_name variable.
1818 N is added to the name of the temporary. */
1820 char *
1821 get_lsm_tmp_name (tree ref, unsigned n)
1823 char ns[2];
1825 lsm_tmp_name_length = 0;
1826 gen_lsm_tmp_name (ref);
1827 lsm_tmp_name_add ("_lsm");
1828 if (n < 10)
1830 ns[0] = '0' + n;
1831 ns[1] = 0;
1832 lsm_tmp_name_add (ns);
1834 return lsm_tmp_name;
1837 struct prev_flag_edges {
1838 /* Edge to insert new flag comparison code. */
1839 edge append_cond_position;
1841 /* Edge for fall through from previous flag comparison. */
1842 edge last_cond_fallthru;
1845 /* Helper function for execute_sm. Emit code to store TMP_VAR into
1846 MEM along edge EX.
1848 The store is only done if MEM has changed. We do this so no
1849 changes to MEM occur on code paths that did not originally store
1850 into it.
1852 The common case for execute_sm will transform:
1854 for (...) {
1855 if (foo)
1856 stuff;
1857 else
1858 MEM = TMP_VAR;
1861 into:
1863 lsm = MEM;
1864 for (...) {
1865 if (foo)
1866 stuff;
1867 else
1868 lsm = TMP_VAR;
1870 MEM = lsm;
1872 This function will generate:
1874 lsm = MEM;
1876 lsm_flag = false;
1878 for (...) {
1879 if (foo)
1880 stuff;
1881 else {
1882 lsm = TMP_VAR;
1883 lsm_flag = true;
1886 if (lsm_flag) <--
1887 MEM = lsm; <--
1890 static void
1891 execute_sm_if_changed (edge ex, tree mem, tree tmp_var, tree flag)
1893 basic_block new_bb, then_bb, old_dest;
1894 bool loop_has_only_one_exit;
1895 edge then_old_edge, orig_ex = ex;
1896 gimple_stmt_iterator gsi;
1897 gimple stmt;
1898 struct prev_flag_edges *prev_edges = (struct prev_flag_edges *) ex->aux;
1900 /* ?? Insert store after previous store if applicable. See note
1901 below. */
1902 if (prev_edges)
1903 ex = prev_edges->append_cond_position;
1905 loop_has_only_one_exit = single_pred_p (ex->dest);
1907 if (loop_has_only_one_exit)
1908 ex = split_block_after_labels (ex->dest);
1910 old_dest = ex->dest;
1911 new_bb = split_edge (ex);
1912 then_bb = create_empty_bb (new_bb);
1913 if (current_loops && new_bb->loop_father)
1914 add_bb_to_loop (then_bb, new_bb->loop_father);
1916 gsi = gsi_start_bb (new_bb);
1917 stmt = gimple_build_cond (NE_EXPR, flag, boolean_false_node,
1918 NULL_TREE, NULL_TREE);
1919 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1921 gsi = gsi_start_bb (then_bb);
1922 /* Insert actual store. */
1923 stmt = gimple_build_assign (unshare_expr (mem), tmp_var);
1924 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1926 make_edge (new_bb, then_bb, EDGE_TRUE_VALUE);
1927 make_edge (new_bb, old_dest, EDGE_FALSE_VALUE);
1928 then_old_edge = make_edge (then_bb, old_dest, EDGE_FALLTHRU);
1930 set_immediate_dominator (CDI_DOMINATORS, then_bb, new_bb);
1932 if (prev_edges)
1934 basic_block prevbb = prev_edges->last_cond_fallthru->src;
1935 redirect_edge_succ (prev_edges->last_cond_fallthru, new_bb);
1936 set_immediate_dominator (CDI_DOMINATORS, new_bb, prevbb);
1937 set_immediate_dominator (CDI_DOMINATORS, old_dest,
1938 recompute_dominator (CDI_DOMINATORS, old_dest));
1941 /* ?? Because stores may alias, they must happen in the exact
1942 sequence they originally happened. Save the position right after
1943 the (_lsm) store we just created so we can continue appending after
1944 it and maintain the original order. */
1946 struct prev_flag_edges *p;
1948 if (orig_ex->aux)
1949 orig_ex->aux = NULL;
1950 alloc_aux_for_edge (orig_ex, sizeof (struct prev_flag_edges));
1951 p = (struct prev_flag_edges *) orig_ex->aux;
1952 p->append_cond_position = then_old_edge;
1953 p->last_cond_fallthru = find_edge (new_bb, old_dest);
1954 orig_ex->aux = (void *) p;
1957 if (!loop_has_only_one_exit)
1958 for (gsi = gsi_start_phis (old_dest); !gsi_end_p (gsi); gsi_next (&gsi))
1960 gimple phi = gsi_stmt (gsi);
1961 unsigned i;
1963 for (i = 0; i < gimple_phi_num_args (phi); i++)
1964 if (gimple_phi_arg_edge (phi, i)->src == new_bb)
1966 tree arg = gimple_phi_arg_def (phi, i);
1967 add_phi_arg (phi, arg, then_old_edge, UNKNOWN_LOCATION);
1968 update_stmt (phi);
1971 /* Remove the original fall through edge. This was the
1972 single_succ_edge (new_bb). */
1973 EDGE_SUCC (new_bb, 0)->flags &= ~EDGE_FALLTHRU;
1976 /* When REF is set on the location, set flag indicating the store. */
1978 struct sm_set_flag_if_changed
1980 sm_set_flag_if_changed (tree flag_) : flag (flag_) {}
1981 bool operator()(mem_ref_loc_p loc);
1982 tree flag;
1985 bool
1986 sm_set_flag_if_changed::operator()(mem_ref_loc_p loc)
1988 /* Only set the flag for writes. */
1989 if (is_gimple_assign (loc->stmt)
1990 && gimple_assign_lhs_ptr (loc->stmt) == loc->ref)
1992 gimple_stmt_iterator gsi = gsi_for_stmt (loc->stmt);
1993 gimple stmt = gimple_build_assign (flag, boolean_true_node);
1994 gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
1996 return false;
1999 /* Helper function for execute_sm. On every location where REF is
2000 set, set an appropriate flag indicating the store. */
2002 static tree
2003 execute_sm_if_changed_flag_set (struct loop *loop, mem_ref_p ref)
2005 tree flag;
2006 char *str = get_lsm_tmp_name (ref->mem.ref, ~0);
2007 lsm_tmp_name_add ("_flag");
2008 flag = create_tmp_reg (boolean_type_node, str);
2009 for_all_locs_in_loop (loop, ref, sm_set_flag_if_changed (flag));
2010 return flag;
2013 /* Executes store motion of memory reference REF from LOOP.
2014 Exits from the LOOP are stored in EXITS. The initialization of the
2015 temporary variable is put to the preheader of the loop, and assignments
2016 to the reference from the temporary variable are emitted to exits. */
2018 static void
2019 execute_sm (struct loop *loop, vec<edge> exits, mem_ref_p ref)
2021 tree tmp_var, store_flag;
2022 unsigned i;
2023 gimple load;
2024 struct fmt_data fmt_data;
2025 edge ex, latch_edge;
2026 struct lim_aux_data *lim_data;
2027 bool multi_threaded_model_p = false;
2029 if (dump_file && (dump_flags & TDF_DETAILS))
2031 fprintf (dump_file, "Executing store motion of ");
2032 print_generic_expr (dump_file, ref->mem.ref, 0);
2033 fprintf (dump_file, " from loop %d\n", loop->num);
2036 tmp_var = create_tmp_reg (TREE_TYPE (ref->mem.ref),
2037 get_lsm_tmp_name (ref->mem.ref, ~0));
2039 fmt_data.loop = loop;
2040 fmt_data.orig_loop = loop;
2041 for_each_index (&ref->mem.ref, force_move_till, &fmt_data);
2043 if (block_in_transaction (loop_preheader_edge (loop)->src)
2044 || !PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES))
2045 multi_threaded_model_p = true;
2047 if (multi_threaded_model_p)
2048 store_flag = execute_sm_if_changed_flag_set (loop, ref);
2050 rewrite_mem_refs (loop, ref, tmp_var);
2052 /* Emit the load code into the latch, so that we are sure it will
2053 be processed after all dependencies. */
2054 latch_edge = loop_latch_edge (loop);
2056 /* FIXME/TODO: For the multi-threaded variant, we could avoid this
2057 load altogether, since the store is predicated by a flag. We
2058 could, do the load only if it was originally in the loop. */
2059 load = gimple_build_assign (tmp_var, unshare_expr (ref->mem.ref));
2060 lim_data = init_lim_data (load);
2061 lim_data->max_loop = loop;
2062 lim_data->tgt_loop = loop;
2063 gsi_insert_on_edge (latch_edge, load);
2065 if (multi_threaded_model_p)
2067 load = gimple_build_assign (store_flag, boolean_false_node);
2068 lim_data = init_lim_data (load);
2069 lim_data->max_loop = loop;
2070 lim_data->tgt_loop = loop;
2071 gsi_insert_on_edge (latch_edge, load);
2074 /* Sink the store to every exit from the loop. */
2075 FOR_EACH_VEC_ELT (exits, i, ex)
2076 if (!multi_threaded_model_p)
2078 gimple store;
2079 store = gimple_build_assign (unshare_expr (ref->mem.ref), tmp_var);
2080 gsi_insert_on_edge (ex, store);
2082 else
2083 execute_sm_if_changed (ex, ref->mem.ref, tmp_var, store_flag);
2086 /* Hoists memory references MEM_REFS out of LOOP. EXITS is the list of exit
2087 edges of the LOOP. */
2089 static void
2090 hoist_memory_references (struct loop *loop, bitmap mem_refs,
2091 vec<edge> exits)
2093 mem_ref_p ref;
2094 unsigned i;
2095 bitmap_iterator bi;
2097 EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2099 ref = memory_accesses.refs_list[i];
2100 execute_sm (loop, exits, ref);
2104 struct ref_always_accessed
2106 ref_always_accessed (struct loop *loop_, tree base_, bool stored_p_)
2107 : loop (loop_), base (base_), stored_p (stored_p_) {}
2108 bool operator()(mem_ref_loc_p loc);
2109 struct loop *loop;
2110 tree base;
2111 bool stored_p;
2114 bool
2115 ref_always_accessed::operator()(mem_ref_loc_p loc)
2117 struct loop *must_exec;
2119 if (!get_lim_data (loc->stmt))
2120 return false;
2122 /* If we require an always executed store make sure the statement
2123 stores to the reference. */
2124 if (stored_p)
2126 tree lhs;
2127 if (!gimple_get_lhs (loc->stmt))
2128 return false;
2129 lhs = get_base_address (gimple_get_lhs (loc->stmt));
2130 if (!lhs)
2131 return false;
2132 if (INDIRECT_REF_P (lhs)
2133 || TREE_CODE (lhs) == MEM_REF)
2134 lhs = TREE_OPERAND (lhs, 0);
2135 if (lhs != base)
2136 return false;
2139 must_exec = get_lim_data (loc->stmt)->always_executed_in;
2140 if (!must_exec)
2141 return false;
2143 if (must_exec == loop
2144 || flow_loop_nested_p (must_exec, loop))
2145 return true;
2147 return false;
2150 /* Returns true if REF is always accessed in LOOP. If STORED_P is true
2151 make sure REF is always stored to in LOOP. */
2153 static bool
2154 ref_always_accessed_p (struct loop *loop, mem_ref_p ref, bool stored_p)
2156 tree base = ao_ref_base (&ref->mem);
2157 if (TREE_CODE (base) == MEM_REF)
2158 base = TREE_OPERAND (base, 0);
2160 return for_all_locs_in_loop (loop, ref,
2161 ref_always_accessed (loop, base, stored_p));
2164 /* Returns true if REF1 and REF2 are independent. */
2166 static bool
2167 refs_independent_p (mem_ref_p ref1, mem_ref_p ref2)
2169 if (ref1 == ref2)
2170 return true;
2172 if (dump_file && (dump_flags & TDF_DETAILS))
2173 fprintf (dump_file, "Querying dependency of refs %u and %u: ",
2174 ref1->id, ref2->id);
2176 if (mem_refs_may_alias_p (ref1, ref2, &memory_accesses.ttae_cache))
2178 if (dump_file && (dump_flags & TDF_DETAILS))
2179 fprintf (dump_file, "dependent.\n");
2180 return false;
2182 else
2184 if (dump_file && (dump_flags & TDF_DETAILS))
2185 fprintf (dump_file, "independent.\n");
2186 return true;
2190 /* Mark REF dependent on stores or loads (according to STORED_P) in LOOP
2191 and its super-loops. */
2193 static void
2194 record_dep_loop (struct loop *loop, mem_ref_p ref, bool stored_p)
2196 /* We can propagate dependent-in-loop bits up the loop
2197 hierarchy to all outer loops. */
2198 while (loop != current_loops->tree_root
2199 && bitmap_set_bit (&ref->dep_loop, LOOP_DEP_BIT (loop->num, stored_p)))
2200 loop = loop_outer (loop);
2203 /* Returns true if REF is independent on all other memory references in
2204 LOOP. */
2206 static bool
2207 ref_indep_loop_p_1 (struct loop *loop, mem_ref_p ref, bool stored_p)
2209 bitmap refs_to_check;
2210 unsigned i;
2211 bitmap_iterator bi;
2212 mem_ref_p aref;
2214 if (stored_p)
2215 refs_to_check = &memory_accesses.refs_in_loop[loop->num];
2216 else
2217 refs_to_check = &memory_accesses.refs_stored_in_loop[loop->num];
2219 if (bitmap_bit_p (refs_to_check, UNANALYZABLE_MEM_ID))
2220 return false;
2222 EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
2224 aref = memory_accesses.refs_list[i];
2225 if (!refs_independent_p (ref, aref))
2226 return false;
2229 return true;
2232 /* Returns true if REF is independent on all other memory references in
2233 LOOP. Wrapper over ref_indep_loop_p_1, caching its results. */
2235 static bool
2236 ref_indep_loop_p_2 (struct loop *loop, mem_ref_p ref, bool stored_p)
2238 stored_p |= bitmap_bit_p (&ref->stored, loop->num);
2240 if (bitmap_bit_p (&ref->indep_loop, LOOP_DEP_BIT (loop->num, stored_p)))
2241 return true;
2242 if (bitmap_bit_p (&ref->dep_loop, LOOP_DEP_BIT (loop->num, stored_p)))
2243 return false;
2245 struct loop *inner = loop->inner;
2246 while (inner)
2248 if (!ref_indep_loop_p_2 (inner, ref, stored_p))
2249 return false;
2250 inner = inner->next;
2253 bool indep_p = ref_indep_loop_p_1 (loop, ref, stored_p);
2255 if (dump_file && (dump_flags & TDF_DETAILS))
2256 fprintf (dump_file, "Querying dependencies of ref %u in loop %d: %s\n",
2257 ref->id, loop->num, indep_p ? "independent" : "dependent");
2259 /* Record the computed result in the cache. */
2260 if (indep_p)
2262 if (bitmap_set_bit (&ref->indep_loop, LOOP_DEP_BIT (loop->num, stored_p))
2263 && stored_p)
2265 /* If it's independend against all refs then it's independent
2266 against stores, too. */
2267 bitmap_set_bit (&ref->indep_loop, LOOP_DEP_BIT (loop->num, false));
2270 else
2272 record_dep_loop (loop, ref, stored_p);
2273 if (!stored_p)
2275 /* If it's dependent against stores it's dependent against
2276 all refs, too. */
2277 record_dep_loop (loop, ref, true);
2281 return indep_p;
2284 /* Returns true if REF is independent on all other memory references in
2285 LOOP. */
2287 static bool
2288 ref_indep_loop_p (struct loop *loop, mem_ref_p ref)
2290 gcc_checking_assert (MEM_ANALYZABLE (ref));
2292 return ref_indep_loop_p_2 (loop, ref, false);
2295 /* Returns true if we can perform store motion of REF from LOOP. */
2297 static bool
2298 can_sm_ref_p (struct loop *loop, mem_ref_p ref)
2300 tree base;
2302 /* Can't hoist unanalyzable refs. */
2303 if (!MEM_ANALYZABLE (ref))
2304 return false;
2306 /* It should be movable. */
2307 if (!is_gimple_reg_type (TREE_TYPE (ref->mem.ref))
2308 || TREE_THIS_VOLATILE (ref->mem.ref)
2309 || !for_each_index (&ref->mem.ref, may_move_till, loop))
2310 return false;
2312 /* If it can throw fail, we do not properly update EH info. */
2313 if (tree_could_throw_p (ref->mem.ref))
2314 return false;
2316 /* If it can trap, it must be always executed in LOOP.
2317 Readonly memory locations may trap when storing to them, but
2318 tree_could_trap_p is a predicate for rvalues, so check that
2319 explicitly. */
2320 base = get_base_address (ref->mem.ref);
2321 if ((tree_could_trap_p (ref->mem.ref)
2322 || (DECL_P (base) && TREE_READONLY (base)))
2323 && !ref_always_accessed_p (loop, ref, true))
2324 return false;
2326 /* And it must be independent on all other memory references
2327 in LOOP. */
2328 if (!ref_indep_loop_p (loop, ref))
2329 return false;
2331 return true;
2334 /* Marks the references in LOOP for that store motion should be performed
2335 in REFS_TO_SM. SM_EXECUTED is the set of references for that store
2336 motion was performed in one of the outer loops. */
2338 static void
2339 find_refs_for_sm (struct loop *loop, bitmap sm_executed, bitmap refs_to_sm)
2341 bitmap refs = &memory_accesses.all_refs_stored_in_loop[loop->num];
2342 unsigned i;
2343 bitmap_iterator bi;
2344 mem_ref_p ref;
2346 EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
2348 ref = memory_accesses.refs_list[i];
2349 if (can_sm_ref_p (loop, ref))
2350 bitmap_set_bit (refs_to_sm, i);
2354 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
2355 for a store motion optimization (i.e. whether we can insert statement
2356 on its exits). */
2358 static bool
2359 loop_suitable_for_sm (struct loop *loop ATTRIBUTE_UNUSED,
2360 vec<edge> exits)
2362 unsigned i;
2363 edge ex;
2365 FOR_EACH_VEC_ELT (exits, i, ex)
2366 if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
2367 return false;
2369 return true;
2372 /* Try to perform store motion for all memory references modified inside
2373 LOOP. SM_EXECUTED is the bitmap of the memory references for that
2374 store motion was executed in one of the outer loops. */
2376 static void
2377 store_motion_loop (struct loop *loop, bitmap sm_executed)
2379 vec<edge> exits = get_loop_exit_edges (loop);
2380 struct loop *subloop;
2381 bitmap sm_in_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
2383 if (loop_suitable_for_sm (loop, exits))
2385 find_refs_for_sm (loop, sm_executed, sm_in_loop);
2386 hoist_memory_references (loop, sm_in_loop, exits);
2388 exits.release ();
2390 bitmap_ior_into (sm_executed, sm_in_loop);
2391 for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
2392 store_motion_loop (subloop, sm_executed);
2393 bitmap_and_compl_into (sm_executed, sm_in_loop);
2394 BITMAP_FREE (sm_in_loop);
2397 /* Try to perform store motion for all memory references modified inside
2398 loops. */
2400 static void
2401 store_motion (void)
2403 struct loop *loop;
2404 bitmap sm_executed = BITMAP_ALLOC (&lim_bitmap_obstack);
2406 for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
2407 store_motion_loop (loop, sm_executed);
2409 BITMAP_FREE (sm_executed);
2410 gsi_commit_edge_inserts ();
2413 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
2414 for each such basic block bb records the outermost loop for that execution
2415 of its header implies execution of bb. CONTAINS_CALL is the bitmap of
2416 blocks that contain a nonpure call. */
2418 static void
2419 fill_always_executed_in_1 (struct loop *loop, sbitmap contains_call)
2421 basic_block bb = NULL, *bbs, last = NULL;
2422 unsigned i;
2423 edge e;
2424 struct loop *inn_loop = loop;
2426 if (ALWAYS_EXECUTED_IN (loop->header) == NULL)
2428 bbs = get_loop_body_in_dom_order (loop);
2430 for (i = 0; i < loop->num_nodes; i++)
2432 edge_iterator ei;
2433 bb = bbs[i];
2435 if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2436 last = bb;
2438 if (bitmap_bit_p (contains_call, bb->index))
2439 break;
2441 FOR_EACH_EDGE (e, ei, bb->succs)
2442 if (!flow_bb_inside_loop_p (loop, e->dest))
2443 break;
2444 if (e)
2445 break;
2447 /* A loop might be infinite (TODO use simple loop analysis
2448 to disprove this if possible). */
2449 if (bb->flags & BB_IRREDUCIBLE_LOOP)
2450 break;
2452 if (!flow_bb_inside_loop_p (inn_loop, bb))
2453 break;
2455 if (bb->loop_father->header == bb)
2457 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2458 break;
2460 /* In a loop that is always entered we may proceed anyway.
2461 But record that we entered it and stop once we leave it. */
2462 inn_loop = bb->loop_father;
2466 while (1)
2468 SET_ALWAYS_EXECUTED_IN (last, loop);
2469 if (last == loop->header)
2470 break;
2471 last = get_immediate_dominator (CDI_DOMINATORS, last);
2474 free (bbs);
2477 for (loop = loop->inner; loop; loop = loop->next)
2478 fill_always_executed_in_1 (loop, contains_call);
2481 /* Fills ALWAYS_EXECUTED_IN information for basic blocks, i.e.
2482 for each such basic block bb records the outermost loop for that execution
2483 of its header implies execution of bb. */
2485 static void
2486 fill_always_executed_in (void)
2488 sbitmap contains_call = sbitmap_alloc (last_basic_block);
2489 basic_block bb;
2490 struct loop *loop;
2492 bitmap_clear (contains_call);
2493 FOR_EACH_BB (bb)
2495 gimple_stmt_iterator gsi;
2496 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2498 if (nonpure_call_p (gsi_stmt (gsi)))
2499 break;
2502 if (!gsi_end_p (gsi))
2503 bitmap_set_bit (contains_call, bb->index);
2506 for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
2507 fill_always_executed_in_1 (loop, contains_call);
2509 sbitmap_free (contains_call);
2513 /* Compute the global information needed by the loop invariant motion pass. */
2515 static void
2516 tree_ssa_lim_initialize (void)
2518 unsigned i;
2520 bitmap_obstack_initialize (&lim_bitmap_obstack);
2521 lim_aux_data_map = pointer_map_create ();
2523 if (flag_tm)
2524 compute_transaction_bits ();
2526 alloc_aux_for_edges (0);
2528 memory_accesses.refs = htab_create (100, memref_hash, memref_eq, NULL);
2529 memory_accesses.refs_list.create (100);
2530 /* Allocate a special, unanalyzable mem-ref with ID zero. */
2531 memory_accesses.refs_list.quick_push
2532 (mem_ref_alloc (error_mark_node, 0, UNANALYZABLE_MEM_ID));
2534 memory_accesses.refs_in_loop.create (number_of_loops ());
2535 memory_accesses.refs_in_loop.quick_grow (number_of_loops ());
2536 memory_accesses.refs_stored_in_loop.create (number_of_loops ());
2537 memory_accesses.refs_stored_in_loop.quick_grow (number_of_loops ());
2538 memory_accesses.all_refs_stored_in_loop.create (number_of_loops ());
2539 memory_accesses.all_refs_stored_in_loop.quick_grow (number_of_loops ());
2541 for (i = 0; i < number_of_loops (); i++)
2543 bitmap_initialize (&memory_accesses.refs_in_loop[i],
2544 &lim_bitmap_obstack);
2545 bitmap_initialize (&memory_accesses.refs_stored_in_loop[i],
2546 &lim_bitmap_obstack);
2547 bitmap_initialize (&memory_accesses.all_refs_stored_in_loop[i],
2548 &lim_bitmap_obstack);
2551 memory_accesses.ttae_cache = NULL;
2554 /* Cleans up after the invariant motion pass. */
2556 static void
2557 tree_ssa_lim_finalize (void)
2559 basic_block bb;
2560 unsigned i;
2561 mem_ref_p ref;
2563 free_aux_for_edges ();
2565 FOR_EACH_BB (bb)
2566 SET_ALWAYS_EXECUTED_IN (bb, NULL);
2568 bitmap_obstack_release (&lim_bitmap_obstack);
2569 pointer_map_destroy (lim_aux_data_map);
2571 htab_delete (memory_accesses.refs);
2573 FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
2574 memref_free (ref);
2575 memory_accesses.refs_list.release ();
2577 memory_accesses.refs_in_loop.release ();
2578 memory_accesses.refs_stored_in_loop.release ();
2579 memory_accesses.all_refs_stored_in_loop.release ();
2581 if (memory_accesses.ttae_cache)
2582 free_affine_expand_cache (&memory_accesses.ttae_cache);
2585 /* Moves invariants from loops. Only "expensive" invariants are moved out --
2586 i.e. those that are likely to be win regardless of the register pressure. */
2588 unsigned int
2589 tree_ssa_lim (void)
2591 unsigned int todo;
2593 tree_ssa_lim_initialize ();
2595 /* Gathers information about memory accesses in the loops. */
2596 analyze_memory_references ();
2598 /* Fills ALWAYS_EXECUTED_IN information for basic blocks. */
2599 fill_always_executed_in ();
2601 /* For each statement determine the outermost loop in that it is
2602 invariant and cost for computing the invariant. */
2603 determine_invariantness ();
2605 /* Execute store motion. Force the necessary invariants to be moved
2606 out of the loops as well. */
2607 store_motion ();
2609 /* Move the expressions that are expensive enough. */
2610 todo = move_computations ();
2612 tree_ssa_lim_finalize ();
2614 return todo;