OSDN Git Service

gcc/
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-copy.c
1 /* Copy propagation and SSA_NAME replacement support routines.
2    Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "flags.h"
27 #include "rtl.h"
28 #include "tm_p.h"
29 #include "ggc.h"
30 #include "basic-block.h"
31 #include "output.h"
32 #include "expr.h"
33 #include "function.h"
34 #include "diagnostic.h"
35 #include "timevar.h"
36 #include "tree-dump.h"
37 #include "tree-flow.h"
38 #include "tree-pass.h"
39 #include "tree-ssa-propagate.h"
40 #include "langhooks.h"
41
42 /* This file implements the copy propagation pass and provides a
43    handful of interfaces for performing const/copy propagation and
44    simple expression replacement which keep variable annotations
45    up-to-date.
46
47    We require that for any copy operation where the RHS and LHS have
48    a non-null memory tag the memory tag be the same.   It is OK
49    for one or both of the memory tags to be NULL.
50
51    We also require tracking if a variable is dereferenced in a load or
52    store operation.
53
54    We enforce these requirements by having all copy propagation and
55    replacements of one SSA_NAME with a different SSA_NAME to use the
56    APIs defined in this file.  */
57
58 /* Return true if we may propagate ORIG into DEST, false otherwise.  */
59
60 bool
61 may_propagate_copy (tree dest, tree orig)
62 {
63   tree type_d = TREE_TYPE (dest);
64   tree type_o = TREE_TYPE (orig);
65
66   /* For memory partitions, copies are OK as long as the memory symbol
67      belongs to the partition.  */
68   if (TREE_CODE (dest) == SSA_NAME
69       && TREE_CODE (SSA_NAME_VAR (dest)) == MEMORY_PARTITION_TAG)
70     return (TREE_CODE (orig) == SSA_NAME
71             && !is_gimple_reg (orig)
72             && (SSA_NAME_VAR (dest) == SSA_NAME_VAR (orig)
73                 || bitmap_bit_p (MPT_SYMBOLS (SSA_NAME_VAR (dest)),
74                                  DECL_UID (SSA_NAME_VAR (orig)))));
75
76   if (TREE_CODE (orig) == SSA_NAME
77       && TREE_CODE (SSA_NAME_VAR (orig)) == MEMORY_PARTITION_TAG)
78     return (TREE_CODE (dest) == SSA_NAME
79             && !is_gimple_reg (dest)
80             && (SSA_NAME_VAR (dest) == SSA_NAME_VAR (orig)
81                 || bitmap_bit_p (MPT_SYMBOLS (SSA_NAME_VAR (orig)),
82                                  DECL_UID (SSA_NAME_VAR (dest)))));
83   
84   /* Do not copy between types for which we *do* need a conversion.  */
85   if (!tree_ssa_useless_type_conversion_1 (type_d, type_o))
86     return false;
87
88   /* FIXME.  GIMPLE is allowing pointer assignments and comparisons of
89      pointers that have different alias sets.  This means that these
90      pointers will have different memory tags associated to them.
91
92      If we allow copy propagation in these cases, statements de-referencing
93      the new pointer will now have a reference to a different memory tag
94      with potentially incorrect SSA information.
95
96      This was showing up in libjava/java/util/zip/ZipFile.java with code
97      like:
98
99         struct java.io.BufferedInputStream *T.660;
100         struct java.io.BufferedInputStream *T.647;
101         struct java.io.InputStream *is;
102         struct java.io.InputStream *is.662;
103         [ ... ]
104         T.660 = T.647;
105         is = T.660;     <-- This ought to be type-casted
106         is.662 = is;
107
108      Also, f/name.c exposed a similar problem with a COND_EXPR predicate
109      that was causing DOM to generate and equivalence with two pointers of
110      alias-incompatible types:
111
112         struct _ffename_space *n;
113         struct _ffename *ns;
114         [ ... ]
115         if (n == ns)
116           goto lab;
117         ...
118         lab:
119         return n;
120
121      I think that GIMPLE should emit the appropriate type-casts.  For the
122      time being, blocking copy-propagation in these cases is the safe thing
123      to do.  */
124   if (TREE_CODE (dest) == SSA_NAME
125       && TREE_CODE (orig) == SSA_NAME
126       && POINTER_TYPE_P (type_d)
127       && POINTER_TYPE_P (type_o))
128     {
129       tree mt_dest = symbol_mem_tag (SSA_NAME_VAR (dest));
130       tree mt_orig = symbol_mem_tag (SSA_NAME_VAR (orig));
131       if (mt_dest && mt_orig && mt_dest != mt_orig)
132         return false;
133       else if (!lang_hooks.types_compatible_p (type_d, type_o))
134         return false;
135       else if (get_alias_set (TREE_TYPE (type_d)) != 
136                get_alias_set (TREE_TYPE (type_o)))
137         return false;
138
139       /* Also verify flow-sensitive information is compatible.  */
140       if (SSA_NAME_PTR_INFO (orig) && SSA_NAME_PTR_INFO (dest))
141         {
142           struct ptr_info_def *orig_ptr_info = SSA_NAME_PTR_INFO (orig);
143           struct ptr_info_def *dest_ptr_info = SSA_NAME_PTR_INFO (dest);
144
145           if (orig_ptr_info->name_mem_tag
146               && dest_ptr_info->name_mem_tag
147               && orig_ptr_info->pt_vars
148               && dest_ptr_info->pt_vars
149               && !bitmap_intersect_p (dest_ptr_info->pt_vars,
150                                       orig_ptr_info->pt_vars))
151             return false;
152         }
153     }
154
155   /* If the destination is a SSA_NAME for a virtual operand, then we have
156      some special cases to handle.  */
157   if (TREE_CODE (dest) == SSA_NAME && !is_gimple_reg (dest))
158     {
159       /* If both operands are SSA_NAMEs referring to virtual operands, then
160          we can always propagate.  */
161       if (TREE_CODE (orig) == SSA_NAME
162           && !is_gimple_reg (orig))
163         return true;
164
165       /* We have a "copy" from something like a constant into a virtual
166          operand.  Reject these.  */
167       return false;
168     }
169
170   /* If ORIG flows in from an abnormal edge, it cannot be propagated.  */
171   if (TREE_CODE (orig) == SSA_NAME
172       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig))
173     return false;
174
175   /* If DEST is an SSA_NAME that flows from an abnormal edge, then it
176      cannot be replaced.  */
177   if (TREE_CODE (dest) == SSA_NAME
178       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (dest))
179     return false;
180
181   /* Anything else is OK.  */
182   return true;
183 }
184
185 /* Similarly, but we know that we're propagating into an ASM_EXPR.  */
186
187 bool
188 may_propagate_copy_into_asm (tree dest)
189 {
190   /* Hard register operands of asms are special.  Do not bypass.  */
191   return !(TREE_CODE (dest) == SSA_NAME
192            && TREE_CODE (SSA_NAME_VAR (dest)) == VAR_DECL
193            && DECL_HARD_REGISTER (SSA_NAME_VAR (dest)));
194 }
195
196
197 /* Given two SSA_NAMEs pointers ORIG and NEW such that we are copy
198    propagating NEW into ORIG, consolidate aliasing information so that
199    they both share the same memory tags.  */
200
201 void
202 merge_alias_info (tree orig, tree new)
203 {
204   tree new_sym = SSA_NAME_VAR (new);
205   tree orig_sym = SSA_NAME_VAR (orig);
206   var_ann_t new_ann = var_ann (new_sym);
207   var_ann_t orig_ann = var_ann (orig_sym);
208
209   /* No merging necessary when memory partitions are involved.  */
210   if (factoring_name_p (new))
211     {
212       gcc_assert (!is_gimple_reg (orig_sym));
213       return;
214     }
215   else if (factoring_name_p (orig))
216     {
217       gcc_assert (!is_gimple_reg (new_sym));
218       return;
219     }
220
221   gcc_assert (POINTER_TYPE_P (TREE_TYPE (orig)));
222   gcc_assert (POINTER_TYPE_P (TREE_TYPE (new)));
223
224 #if defined ENABLE_CHECKING
225   gcc_assert (lang_hooks.types_compatible_p (TREE_TYPE (orig),
226                                              TREE_TYPE (new)));
227
228   /* If the pointed-to alias sets are different, these two pointers
229      would never have the same memory tag.  In this case, NEW should
230      not have been propagated into ORIG.  */
231   gcc_assert (get_alias_set (TREE_TYPE (TREE_TYPE (new_sym)))
232               == get_alias_set (TREE_TYPE (TREE_TYPE (orig_sym))));
233 #endif
234
235   /* Synchronize the symbol tags.  If both pointers had a tag and they
236      are different, then something has gone wrong.  Symbol tags can
237      always be merged because they are flow insensitive, all the SSA
238      names of the same base DECL share the same symbol tag.  */
239   if (new_ann->symbol_mem_tag == NULL_TREE)
240     new_ann->symbol_mem_tag = orig_ann->symbol_mem_tag;
241   else if (orig_ann->symbol_mem_tag == NULL_TREE)
242     orig_ann->symbol_mem_tag = new_ann->symbol_mem_tag;
243   else
244     gcc_assert (new_ann->symbol_mem_tag == orig_ann->symbol_mem_tag);
245
246   /* Check that flow-sensitive information is compatible.  Notice that
247      we may not merge flow-sensitive information here.  This function
248      is called when propagating equivalences dictated by the IL, like
249      a copy operation P_i = Q_j, and from equivalences dictated by
250      control-flow, like if (P_i == Q_j).
251      
252      In the former case, P_i and Q_j are equivalent in every block
253      dominated by the assignment, so their flow-sensitive information
254      is always the same.  However, in the latter case, the pointers
255      P_i and Q_j are only equivalent in one of the sub-graphs out of
256      the predicate, so their flow-sensitive information is not the
257      same in every block dominated by the predicate.
258
259      Since we cannot distinguish one case from another in this
260      function, we can only make sure that if P_i and Q_j have
261      flow-sensitive information, they should be compatible.  */
262   if (SSA_NAME_PTR_INFO (orig) && SSA_NAME_PTR_INFO (new))
263     {
264       struct ptr_info_def *orig_ptr_info = SSA_NAME_PTR_INFO (orig);
265       struct ptr_info_def *new_ptr_info = SSA_NAME_PTR_INFO (new);
266
267       /* Note that pointer NEW and ORIG may actually have different
268          pointed-to variables (e.g., PR 18291 represented in
269          testsuite/gcc.c-torture/compile/pr18291.c).  However, since
270          NEW is being copy-propagated into ORIG, it must always be
271          true that the pointed-to set for pointer NEW is the same, or
272          a subset, of the pointed-to set for pointer ORIG.  If this
273          isn't the case, we shouldn't have been able to do the
274          propagation of NEW into ORIG.  */
275       if (orig_ptr_info->name_mem_tag
276           && new_ptr_info->name_mem_tag
277           && orig_ptr_info->pt_vars
278           && new_ptr_info->pt_vars)
279         gcc_assert (bitmap_intersect_p (new_ptr_info->pt_vars,
280                                         orig_ptr_info->pt_vars));
281     }
282 }   
283
284
285 /* Common code for propagate_value and replace_exp.
286
287    Replace use operand OP_P with VAL.  FOR_PROPAGATION indicates if the
288    replacement is done to propagate a value or not.  */
289
290 static void
291 replace_exp_1 (use_operand_p op_p, tree val,
292                bool for_propagation ATTRIBUTE_UNUSED)
293 {
294   tree op = USE_FROM_PTR (op_p);
295
296 #if defined ENABLE_CHECKING
297   gcc_assert (!(for_propagation
298                 && TREE_CODE (op) == SSA_NAME
299                 && TREE_CODE (val) == SSA_NAME
300                 && !may_propagate_copy (op, val)));
301 #endif
302
303   if (TREE_CODE (val) == SSA_NAME)
304     {
305       if (TREE_CODE (op) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (op)))
306         merge_alias_info (op, val);
307       SET_USE (op_p, val);
308     }
309   else
310     SET_USE (op_p, unsave_expr_now (val));
311 }
312
313
314 /* Propagate the value VAL (assumed to be a constant or another SSA_NAME)
315    into the operand pointed to by OP_P.
316
317    Use this version for const/copy propagation as it will perform additional
318    checks to ensure validity of the const/copy propagation.  */
319
320 void
321 propagate_value (use_operand_p op_p, tree val)
322 {
323   replace_exp_1 (op_p, val, true);
324 }
325
326
327 /* Propagate the value VAL (assumed to be a constant or another SSA_NAME)
328    into the tree pointed to by OP_P.
329
330    Use this version for const/copy propagation when SSA operands are not
331    available.  It will perform the additional checks to ensure validity of
332    the const/copy propagation, but will not update any operand information.
333    Be sure to mark the stmt as modified.  */
334
335 void
336 propagate_tree_value (tree *op_p, tree val)
337 {
338 #if defined ENABLE_CHECKING
339   gcc_assert (!(TREE_CODE (val) == SSA_NAME
340                 && TREE_CODE (*op_p) == SSA_NAME
341                 && !may_propagate_copy (*op_p, val)));
342 #endif
343
344   if (TREE_CODE (val) == SSA_NAME)
345     {
346       if (TREE_CODE (*op_p) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (*op_p)))
347         merge_alias_info (*op_p, val);
348       *op_p = val;
349     }
350   else
351     *op_p = unsave_expr_now (val);
352 }
353
354
355 /* Replace *OP_P with value VAL (assumed to be a constant or another SSA_NAME).
356
357    Use this version when not const/copy propagating values.  For example,
358    PRE uses this version when building expressions as they would appear
359    in specific blocks taking into account actions of PHI nodes.  */
360
361 void
362 replace_exp (use_operand_p op_p, tree val)
363 {
364   replace_exp_1 (op_p, val, false);
365 }
366
367
368 /*---------------------------------------------------------------------------
369                                 Copy propagation
370 ---------------------------------------------------------------------------*/
371 /* During propagation, we keep chains of variables that are copies of
372    one another.  If variable X_i is a copy of X_j and X_j is a copy of
373    X_k, COPY_OF will contain:
374
375         COPY_OF[i].VALUE = X_j
376         COPY_OF[j].VALUE = X_k
377         COPY_OF[k].VALUE = X_k
378
379    After propagation, the copy-of value for each variable X_i is
380    converted into the final value by walking the copy-of chains and
381    updating COPY_OF[i].VALUE to be the last element of the chain.  */
382 static prop_value_t *copy_of;
383
384 /* Used in set_copy_of_val to determine if the last link of a copy-of
385    chain has changed.  */
386 static tree *cached_last_copy_of;
387
388 /* True if we are doing copy propagation on loads and stores.  */
389 static bool do_store_copy_prop;
390
391
392 /* Return true if this statement may generate a useful copy.  */
393
394 static bool
395 stmt_may_generate_copy (tree stmt)
396 {
397   tree lhs, rhs;
398   stmt_ann_t ann;
399
400   if (TREE_CODE (stmt) == PHI_NODE)
401     return !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (stmt));
402
403   if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
404     return false;
405
406   lhs = GIMPLE_STMT_OPERAND (stmt, 0);
407   rhs = GIMPLE_STMT_OPERAND (stmt, 1);
408   ann = stmt_ann (stmt);
409
410   /* If the statement has volatile operands, it won't generate a
411      useful copy.  */
412   if (ann->has_volatile_ops)
413     return false;
414
415   /* If we are not doing store copy-prop, statements with loads and/or
416      stores will never generate a useful copy.  */
417   if (!do_store_copy_prop
418       && !ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
419     return false;
420
421   /* Otherwise, the only statements that generate useful copies are
422      assignments whose RHS is just an SSA name that doesn't flow
423      through abnormal edges.  */
424   return (do_store_copy_prop
425           && TREE_CODE (lhs) == SSA_NAME)
426          || (TREE_CODE (rhs) == SSA_NAME
427              && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs));
428 }
429
430
431 /* Return the copy-of value for VAR.  */
432
433 static inline prop_value_t *
434 get_copy_of_val (tree var)
435 {
436   prop_value_t *val = &copy_of[SSA_NAME_VERSION (var)];
437
438   if (val->value == NULL_TREE
439       && !stmt_may_generate_copy (SSA_NAME_DEF_STMT (var)))
440     {
441       /* If the variable will never generate a useful copy relation,
442          make it its own copy.  */
443       val->value = var;
444       val->mem_ref = NULL_TREE;
445     }
446
447   return val;
448 }
449
450
451 /* Return last link in the copy-of chain for VAR.  */
452
453 static tree
454 get_last_copy_of (tree var)
455 {
456   tree last;
457   int i;
458
459   /* Traverse COPY_OF starting at VAR until we get to the last
460      link in the chain.  Since it is possible to have cycles in PHI
461      nodes, the copy-of chain may also contain cycles.
462      
463      To avoid infinite loops and to avoid traversing lengthy copy-of
464      chains, we artificially limit the maximum number of chains we are
465      willing to traverse.
466
467      The value 5 was taken from a compiler and runtime library
468      bootstrap and a mixture of C and C++ code from various sources.
469      More than 82% of all copy-of chains were shorter than 5 links.  */
470 #define LIMIT   5
471
472   last = var;
473   for (i = 0; i < LIMIT; i++)
474     {
475       tree copy = copy_of[SSA_NAME_VERSION (last)].value;
476       if (copy == NULL_TREE || copy == last)
477         break;
478       last = copy;
479     }
480
481   /* If we have reached the limit, then we are either in a copy-of
482      cycle or the copy-of chain is too long.  In this case, just
483      return VAR so that it is not considered a copy of anything.  */
484   return (i < LIMIT ? last : var);
485 }
486
487
488 /* Set FIRST to be the first variable in the copy-of chain for DEST.
489    If DEST's copy-of value or its copy-of chain has changed, return
490    true.
491
492    MEM_REF is the memory reference where FIRST is stored.  This is
493    used when DEST is a non-register and we are copy propagating loads
494    and stores.  */
495
496 static inline bool
497 set_copy_of_val (tree dest, tree first, tree mem_ref)
498 {
499   unsigned int dest_ver = SSA_NAME_VERSION (dest);
500   tree old_first, old_last, new_last;
501   
502   /* Set FIRST to be the first link in COPY_OF[DEST].  If that
503      changed, return true.  */
504   old_first = copy_of[dest_ver].value;
505   copy_of[dest_ver].value = first;
506   copy_of[dest_ver].mem_ref = mem_ref;
507
508   if (old_first != first)
509     return true;
510
511   /* If FIRST and OLD_FIRST are the same, we need to check whether the
512      copy-of chain starting at FIRST ends in a different variable.  If
513      the copy-of chain starting at FIRST ends up in a different
514      variable than the last cached value we had for DEST, then return
515      true because DEST is now a copy of a different variable.
516
517      This test is necessary because even though the first link in the
518      copy-of chain may not have changed, if any of the variables in
519      the copy-of chain changed its final value, DEST will now be the
520      copy of a different variable, so we have to do another round of
521      propagation for everything that depends on DEST.  */
522   old_last = cached_last_copy_of[dest_ver];
523   new_last = get_last_copy_of (dest);
524   cached_last_copy_of[dest_ver] = new_last;
525
526   return (old_last != new_last);
527 }
528
529
530 /* Dump the copy-of value for variable VAR to FILE.  */
531
532 static void
533 dump_copy_of (FILE *file, tree var)
534 {
535   tree val;
536   sbitmap visited;
537
538   print_generic_expr (file, var, dump_flags);
539
540   if (TREE_CODE (var) != SSA_NAME)
541     return;
542     
543   visited = sbitmap_alloc (num_ssa_names);
544   sbitmap_zero (visited);
545   SET_BIT (visited, SSA_NAME_VERSION (var));
546   
547   fprintf (file, " copy-of chain: ");
548
549   val = var;
550   print_generic_expr (file, val, 0);
551   fprintf (file, " ");
552   while (copy_of[SSA_NAME_VERSION (val)].value)
553     {
554       fprintf (file, "-> ");
555       val = copy_of[SSA_NAME_VERSION (val)].value;
556       print_generic_expr (file, val, 0);
557       fprintf (file, " ");
558       if (TEST_BIT (visited, SSA_NAME_VERSION (val)))
559         break;
560       SET_BIT (visited, SSA_NAME_VERSION (val));
561     }
562
563   val = get_copy_of_val (var)->value;
564   if (val == NULL_TREE)
565     fprintf (file, "[UNDEFINED]");
566   else if (val != var)
567     fprintf (file, "[COPY]");
568   else
569     fprintf (file, "[NOT A COPY]");
570   
571   sbitmap_free (visited);
572 }
573
574
575 /* Evaluate the RHS of STMT.  If it produces a valid copy, set the LHS
576    value and store the LHS into *RESULT_P.  If STMT generates more
577    than one name (i.e., STMT is an aliased store), it is enough to
578    store the first name in the VDEF list into *RESULT_P.  After
579    all, the names generated will be VUSEd in the same statements.  */
580
581 static enum ssa_prop_result
582 copy_prop_visit_assignment (tree stmt, tree *result_p)
583 {
584   tree lhs, rhs;
585   prop_value_t *rhs_val;
586
587   lhs = GIMPLE_STMT_OPERAND (stmt, 0);
588   rhs = GIMPLE_STMT_OPERAND (stmt, 1);
589
590   gcc_assert (TREE_CODE (rhs) == SSA_NAME);
591
592   rhs_val = get_copy_of_val (rhs);
593
594   if (TREE_CODE (lhs) == SSA_NAME)
595     {
596       /* Straight copy between two SSA names.  First, make sure that
597          we can propagate the RHS into uses of LHS.  */
598       if (!may_propagate_copy (lhs, rhs))
599         return SSA_PROP_VARYING;
600
601       /* Notice that in the case of assignments, we make the LHS be a
602          copy of RHS's value, not of RHS itself.  This avoids keeping
603          unnecessary copy-of chains (assignments cannot be in a cycle
604          like PHI nodes), speeding up the propagation process.
605          This is different from what we do in copy_prop_visit_phi_node. 
606          In those cases, we are interested in the copy-of chains.  */
607       *result_p = lhs;
608       if (set_copy_of_val (*result_p, rhs_val->value, rhs_val->mem_ref))
609         return SSA_PROP_INTERESTING;
610       else
611         return SSA_PROP_NOT_INTERESTING;
612     }
613   else if (stmt_makes_single_store (stmt))
614     {
615       /* Otherwise, set the names in VDEF operands to be a copy
616          of RHS.  */
617       ssa_op_iter i;
618       tree vdef;
619       bool changed;
620
621       /* This should only be executed when doing store copy-prop.  */
622       gcc_assert (do_store_copy_prop);
623
624       /* Set the value of every VDEF to RHS_VAL.  */
625       changed = false;
626       FOR_EACH_SSA_TREE_OPERAND (vdef, stmt, i, SSA_OP_VIRTUAL_DEFS)
627         changed |= set_copy_of_val (vdef, rhs_val->value, lhs);
628       
629       /* Note that for propagation purposes, we are only interested in
630          visiting statements that load the exact same memory reference
631          stored here.  Those statements will have the exact same list
632          of virtual uses, so it is enough to set the output of this
633          statement to be its first virtual definition.  */
634       *result_p = first_vdef (stmt);
635
636       if (changed)
637         return SSA_PROP_INTERESTING;
638       else
639         return SSA_PROP_NOT_INTERESTING;
640     }
641
642
643   return SSA_PROP_VARYING;
644 }
645
646
647 /* Visit the COND_EXPR STMT.  Return SSA_PROP_INTERESTING
648    if it can determine which edge will be taken.  Otherwise, return
649    SSA_PROP_VARYING.  */
650
651 static enum ssa_prop_result
652 copy_prop_visit_cond_stmt (tree stmt, edge *taken_edge_p)
653 {
654   enum ssa_prop_result retval;
655   tree cond;
656
657   cond = COND_EXPR_COND (stmt);
658   retval = SSA_PROP_VARYING;
659
660   /* The only conditionals that we may be able to compute statically
661      are predicates involving two SSA_NAMEs.  */
662   if (COMPARISON_CLASS_P (cond)
663       && TREE_CODE (TREE_OPERAND (cond, 0)) == SSA_NAME
664       && TREE_CODE (TREE_OPERAND (cond, 1)) == SSA_NAME)
665     {
666       tree op0 = get_last_copy_of (TREE_OPERAND (cond, 0));
667       tree op1 = get_last_copy_of (TREE_OPERAND (cond, 1));
668
669       /* See if we can determine the predicate's value.  */
670       if (dump_file && (dump_flags & TDF_DETAILS))
671         {
672           fprintf (dump_file, "Trying to determine truth value of ");
673           fprintf (dump_file, "predicate ");
674           print_generic_stmt (dump_file, cond, 0);
675         }
676
677       /* We can fold COND and get a useful result only when we have
678          the same SSA_NAME on both sides of a comparison operator.  */
679       if (op0 == op1)
680         {
681           tree folded_cond = fold_binary (TREE_CODE (cond), boolean_type_node,
682                                           op0, op1);
683           if (folded_cond)
684             {
685               basic_block bb = bb_for_stmt (stmt);
686               *taken_edge_p = find_taken_edge (bb, folded_cond);
687               if (*taken_edge_p)
688                 retval = SSA_PROP_INTERESTING;
689             }
690         }
691     }
692
693   if (dump_file && (dump_flags & TDF_DETAILS) && *taken_edge_p)
694     fprintf (dump_file, "\nConditional will always take edge %d->%d\n",
695              (*taken_edge_p)->src->index, (*taken_edge_p)->dest->index);
696
697   return retval;
698 }
699
700
701 /* Evaluate statement STMT.  If the statement produces a new output
702    value, return SSA_PROP_INTERESTING and store the SSA_NAME holding
703    the new value in *RESULT_P.
704
705    If STMT is a conditional branch and we can determine its truth
706    value, set *TAKEN_EDGE_P accordingly.
707
708    If the new value produced by STMT is varying, return
709    SSA_PROP_VARYING.  */
710
711 static enum ssa_prop_result
712 copy_prop_visit_stmt (tree stmt, edge *taken_edge_p, tree *result_p)
713 {
714   enum ssa_prop_result retval;
715
716   if (dump_file && (dump_flags & TDF_DETAILS))
717     {
718       fprintf (dump_file, "\nVisiting statement:\n");
719       print_generic_stmt (dump_file, stmt, dump_flags);
720       fprintf (dump_file, "\n");
721     }
722
723   if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
724       && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == SSA_NAME
725       && (do_store_copy_prop
726           || TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 0)) == SSA_NAME))
727     {
728       /* If the statement is a copy assignment, evaluate its RHS to
729          see if the lattice value of its output has changed.  */
730       retval = copy_prop_visit_assignment (stmt, result_p);
731     }
732   else if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
733            && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 0)) == SSA_NAME
734            && do_store_copy_prop
735            && stmt_makes_single_load (stmt))
736     {
737       /* If the statement is a copy assignment with a memory load
738          on the RHS, see if we know the value of this load and
739          update the lattice accordingly.  */
740       prop_value_t *val = get_value_loaded_by (stmt, copy_of);
741       if (val
742           && val->mem_ref
743           && is_gimple_reg (val->value)
744           && operand_equal_p (val->mem_ref, GIMPLE_STMT_OPERAND (stmt, 1), 0))
745         {
746           bool changed;
747           changed = set_copy_of_val (GIMPLE_STMT_OPERAND (stmt, 0),
748                                      val->value, val->mem_ref);
749           if (changed)
750             {
751               *result_p = GIMPLE_STMT_OPERAND (stmt, 0);
752               retval = SSA_PROP_INTERESTING;
753             }
754           else
755             retval = SSA_PROP_NOT_INTERESTING;
756         }
757       else
758         retval = SSA_PROP_VARYING;
759     }
760   else if (TREE_CODE (stmt) == COND_EXPR)
761     {
762       /* See if we can determine which edge goes out of a conditional
763          jump.  */
764       retval = copy_prop_visit_cond_stmt (stmt, taken_edge_p);
765     }
766   else
767     retval = SSA_PROP_VARYING;
768
769   if (retval == SSA_PROP_VARYING)
770     {
771       tree def;
772       ssa_op_iter i;
773
774       /* Any other kind of statement is not interesting for constant
775          propagation and, therefore, not worth simulating.  */
776       if (dump_file && (dump_flags & TDF_DETAILS))
777         fprintf (dump_file, "No interesting values produced.\n");
778
779       /* The assignment is not a copy operation.  Don't visit this
780          statement again and mark all the definitions in the statement
781          to be copies of nothing.  */
782       FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_ALL_DEFS)
783         set_copy_of_val (def, def, NULL_TREE);
784     }
785
786   return retval;
787 }
788
789
790 /* Visit PHI node PHI.  If all the arguments produce the same value,
791    set it to be the value of the LHS of PHI.  */
792
793 static enum ssa_prop_result
794 copy_prop_visit_phi_node (tree phi)
795 {
796   enum ssa_prop_result retval;
797   int i;
798   tree lhs;
799   prop_value_t phi_val = { 0, NULL_TREE, NULL_TREE };
800
801   lhs = PHI_RESULT (phi);
802
803   if (dump_file && (dump_flags & TDF_DETAILS))
804     {
805       fprintf (dump_file, "\nVisiting PHI node: ");
806       print_generic_expr (dump_file, phi, dump_flags);
807       fprintf (dump_file, "\n\n");
808     }
809
810   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
811     {
812       prop_value_t *arg_val;
813       tree arg = PHI_ARG_DEF (phi, i);
814       edge e = PHI_ARG_EDGE (phi, i);
815
816       /* We don't care about values flowing through non-executable
817          edges.  */
818       if (!(e->flags & EDGE_EXECUTABLE))
819         continue;
820
821       /* Constants in the argument list never generate a useful copy.
822          Similarly, names that flow through abnormal edges cannot be
823          used to derive copies.  */
824       if (TREE_CODE (arg) != SSA_NAME || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (arg))
825         {
826           phi_val.value = lhs;
827           break;
828         }
829
830       /* Avoid copy propagation from an inner into an outer loop.
831          Otherwise, this may move loop variant variables outside of
832          their loops and prevent coalescing opportunities.  If the
833          value was loop invariant, it will be hoisted by LICM and
834          exposed for copy propagation.  */
835       if (loop_depth_of_name (arg) > loop_depth_of_name (lhs))
836         {
837           phi_val.value = lhs;
838           break;
839         }
840
841       /* If the LHS appears in the argument list, ignore it.  It is
842          irrelevant as a copy.  */
843       if (arg == lhs || get_last_copy_of (arg) == lhs)
844         continue;
845
846       if (dump_file && (dump_flags & TDF_DETAILS))
847         {
848           fprintf (dump_file, "\tArgument #%d: ", i);
849           dump_copy_of (dump_file, arg);
850           fprintf (dump_file, "\n");
851         }
852
853       arg_val = get_copy_of_val (arg);
854
855       /* If the LHS didn't have a value yet, make it a copy of the
856          first argument we find.  Notice that while we make the LHS be
857          a copy of the argument itself, we take the memory reference
858          from the argument's value so that we can compare it to the
859          memory reference of all the other arguments.  */
860       if (phi_val.value == NULL_TREE)
861         {
862           phi_val.value = arg;
863           phi_val.mem_ref = arg_val->mem_ref;
864           continue;
865         }
866
867       /* If PHI_VAL and ARG don't have a common copy-of chain, then
868          this PHI node cannot be a copy operation.  Also, if we are
869          copy propagating stores and these two arguments came from
870          different memory references, they cannot be considered
871          copies.  */
872       if (get_last_copy_of (phi_val.value) != get_last_copy_of (arg)
873           || (do_store_copy_prop
874               && phi_val.mem_ref
875               && arg_val->mem_ref
876               && simple_cst_equal (phi_val.mem_ref, arg_val->mem_ref) != 1))
877         {
878           phi_val.value = lhs;
879           break;
880         }
881     }
882
883   if (phi_val.value && set_copy_of_val (lhs, phi_val.value, phi_val.mem_ref))
884     retval = (phi_val.value != lhs) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
885   else
886     retval = SSA_PROP_NOT_INTERESTING;
887
888   if (dump_file && (dump_flags & TDF_DETAILS))
889     {
890       fprintf (dump_file, "\nPHI node ");
891       dump_copy_of (dump_file, lhs);
892       fprintf (dump_file, "\nTelling the propagator to ");
893       if (retval == SSA_PROP_INTERESTING)
894         fprintf (dump_file, "add SSA edges out of this PHI and continue.");
895       else if (retval == SSA_PROP_VARYING)
896         fprintf (dump_file, "add SSA edges out of this PHI and never visit again.");
897       else
898         fprintf (dump_file, "do nothing with SSA edges and keep iterating.");
899       fprintf (dump_file, "\n\n");
900     }
901
902   return retval;
903 }
904
905
906 /* Initialize structures used for copy propagation.   PHIS_ONLY is true
907    if we should only consider PHI nodes as generating copy propagation
908    opportunities.  */
909
910 static void
911 init_copy_prop (void)
912 {
913   basic_block bb;
914
915   copy_of = XCNEWVEC (prop_value_t, num_ssa_names);
916
917   cached_last_copy_of = XCNEWVEC (tree, num_ssa_names);
918
919   FOR_EACH_BB (bb)
920     {
921       block_stmt_iterator si;
922       tree phi, def;
923       int depth = bb->loop_depth;
924
925       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
926         {
927           tree stmt = bsi_stmt (si);
928           ssa_op_iter iter;
929
930           /* The only statements that we care about are those that may
931              generate useful copies.  We also need to mark conditional
932              jumps so that their outgoing edges are added to the work
933              lists of the propagator.
934
935              Avoid copy propagation from an inner into an outer loop.
936              Otherwise, this may move loop variant variables outside of
937              their loops and prevent coalescing opportunities.  If the
938              value was loop invariant, it will be hoisted by LICM and
939              exposed for copy propagation.  */
940           if (stmt_ends_bb_p (stmt))
941             DONT_SIMULATE_AGAIN (stmt) = false;
942           else if (stmt_may_generate_copy (stmt)
943                    && loop_depth_of_name (GIMPLE_STMT_OPERAND (stmt, 1)) <= depth)
944             DONT_SIMULATE_AGAIN (stmt) = false;
945           else
946             DONT_SIMULATE_AGAIN (stmt) = true;
947
948           /* Mark all the outputs of this statement as not being
949              the copy of anything.  */
950           FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
951             if (DONT_SIMULATE_AGAIN (stmt))
952               set_copy_of_val (def, def, NULL_TREE);
953             else
954               cached_last_copy_of[SSA_NAME_VERSION (def)] = def;
955         }
956
957       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
958         {
959           def = PHI_RESULT (phi);
960           if (!do_store_copy_prop && !is_gimple_reg (def))
961             DONT_SIMULATE_AGAIN (phi) = true;
962           else
963             DONT_SIMULATE_AGAIN (phi) = false;
964
965           if (DONT_SIMULATE_AGAIN (phi))
966             set_copy_of_val (def, def, NULL_TREE);
967           else
968             cached_last_copy_of[SSA_NAME_VERSION (def)] = def;
969         }
970     }
971 }
972
973
974 /* Deallocate memory used in copy propagation and do final
975    substitution.  */
976
977 static void
978 fini_copy_prop (void)
979 {
980   size_t i;
981   prop_value_t *tmp;
982   
983   /* Set the final copy-of value for each variable by traversing the
984      copy-of chains.  */
985   tmp = XCNEWVEC (prop_value_t, num_ssa_names);
986   for (i = 1; i < num_ssa_names; i++)
987     {
988       tree var = ssa_name (i);
989       if (var && copy_of[i].value && copy_of[i].value != var)
990         tmp[i].value = get_last_copy_of (var);
991     }
992
993   substitute_and_fold (tmp, false);
994
995   free (cached_last_copy_of);
996   free (copy_of);
997   free (tmp);
998 }
999
1000
1001 /* Main entry point to the copy propagator.
1002
1003    PHIS_ONLY is true if we should only consider PHI nodes as generating
1004    copy propagation opportunities. 
1005
1006    The algorithm propagates the value COPY-OF using ssa_propagate.  For
1007    every variable X_i, COPY-OF(X_i) indicates which variable is X_i created
1008    from.  The following example shows how the algorithm proceeds at a
1009    high level:
1010
1011             1   a_24 = x_1
1012             2   a_2 = PHI <a_24, x_1>
1013             3   a_5 = PHI <a_2>
1014             4   x_1 = PHI <x_298, a_5, a_2>
1015
1016    The end result should be that a_2, a_5, a_24 and x_1 are a copy of
1017    x_298.  Propagation proceeds as follows.
1018
1019    Visit #1: a_24 is copy-of x_1.  Value changed.
1020    Visit #2: a_2 is copy-of x_1.  Value changed.
1021    Visit #3: a_5 is copy-of x_1.  Value changed.
1022    Visit #4: x_1 is copy-of x_298.  Value changed.
1023    Visit #1: a_24 is copy-of x_298.  Value changed.
1024    Visit #2: a_2 is copy-of x_298.  Value changed.
1025    Visit #3: a_5 is copy-of x_298.  Value changed.
1026    Visit #4: x_1 is copy-of x_298.  Stable state reached.
1027    
1028    When visiting PHI nodes, we only consider arguments that flow
1029    through edges marked executable by the propagation engine.  So,
1030    when visiting statement #2 for the first time, we will only look at
1031    the first argument (a_24) and optimistically assume that its value
1032    is the copy of a_24 (x_1).
1033
1034    The problem with this approach is that it may fail to discover copy
1035    relations in PHI cycles.  Instead of propagating copy-of
1036    values, we actually propagate copy-of chains.  For instance:
1037
1038                 A_3 = B_1;
1039                 C_9 = A_3;
1040                 D_4 = C_9;
1041                 X_i = D_4;
1042
1043    In this code fragment, COPY-OF (X_i) = { D_4, C_9, A_3, B_1 }.
1044    Obviously, we are only really interested in the last value of the
1045    chain, however the propagator needs to access the copy-of chain
1046    when visiting PHI nodes.
1047
1048    To represent the copy-of chain, we use the array COPY_CHAINS, which
1049    holds the first link in the copy-of chain for every variable.
1050    If variable X_i is a copy of X_j, which in turn is a copy of X_k,
1051    the array will contain:
1052
1053                 COPY_CHAINS[i] = X_j
1054                 COPY_CHAINS[j] = X_k
1055                 COPY_CHAINS[k] = X_k
1056
1057    Keeping copy-of chains instead of copy-of values directly becomes
1058    important when visiting PHI nodes.  Suppose that we had the
1059    following PHI cycle, such that x_52 is already considered a copy of
1060    x_53:
1061
1062             1   x_54 = PHI <x_53, x_52>
1063             2   x_53 = PHI <x_898, x_54>
1064    
1065    Visit #1: x_54 is copy-of x_53 (because x_52 is copy-of x_53)
1066    Visit #2: x_53 is copy-of x_898 (because x_54 is a copy of x_53,
1067                                     so it is considered irrelevant
1068                                     as a copy).
1069    Visit #1: x_54 is copy-of nothing (x_53 is a copy-of x_898 and
1070                                       x_52 is a copy of x_53, so
1071                                       they don't match)
1072    Visit #2: x_53 is copy-of nothing
1073
1074    This problem is avoided by keeping a chain of copies, instead of
1075    the final copy-of value.  Propagation will now only keep the first
1076    element of a variable's copy-of chain.  When visiting PHI nodes,
1077    arguments are considered equal if their copy-of chains end in the
1078    same variable.  So, as long as their copy-of chains overlap, we
1079    know that they will be a copy of the same variable, regardless of
1080    which variable that may be).
1081    
1082    Propagation would then proceed as follows (the notation a -> b
1083    means that a is a copy-of b):
1084
1085    Visit #1: x_54 = PHI <x_53, x_52>
1086                 x_53 -> x_53
1087                 x_52 -> x_53
1088                 Result: x_54 -> x_53.  Value changed.  Add SSA edges.
1089
1090    Visit #1: x_53 = PHI <x_898, x_54>
1091                 x_898 -> x_898
1092                 x_54 -> x_53
1093                 Result: x_53 -> x_898.  Value changed.  Add SSA edges.
1094
1095    Visit #2: x_54 = PHI <x_53, x_52>
1096                 x_53 -> x_898
1097                 x_52 -> x_53 -> x_898
1098                 Result: x_54 -> x_898.  Value changed.  Add SSA edges.
1099
1100    Visit #2: x_53 = PHI <x_898, x_54>
1101                 x_898 -> x_898
1102                 x_54 -> x_898
1103                 Result: x_53 -> x_898.  Value didn't change.  Stable state
1104
1105    Once the propagator stabilizes, we end up with the desired result
1106    x_53 and x_54 are both copies of x_898.  */
1107
1108 static void
1109 execute_copy_prop (bool store_copy_prop)
1110 {
1111   do_store_copy_prop = store_copy_prop;
1112   init_copy_prop ();
1113   ssa_propagate (copy_prop_visit_stmt, copy_prop_visit_phi_node);
1114   fini_copy_prop ();
1115 }
1116
1117
1118 static bool
1119 gate_copy_prop (void)
1120 {
1121   return flag_tree_copy_prop != 0;
1122 }
1123
1124 static unsigned int
1125 do_copy_prop (void)
1126 {
1127   execute_copy_prop (false);
1128   return 0;
1129 }
1130
1131 struct tree_opt_pass pass_copy_prop =
1132 {
1133   "copyprop",                           /* name */
1134   gate_copy_prop,                       /* gate */
1135   do_copy_prop,                         /* execute */
1136   NULL,                                 /* sub */
1137   NULL,                                 /* next */
1138   0,                                    /* static_pass_number */
1139   TV_TREE_COPY_PROP,                    /* tv_id */
1140   PROP_ssa | PROP_cfg,                  /* properties_required */
1141   0,                                    /* properties_provided */
1142   0,                                    /* properties_destroyed */
1143   0,                                    /* todo_flags_start */
1144   TODO_cleanup_cfg
1145     | TODO_dump_func
1146     | TODO_ggc_collect
1147     | TODO_verify_ssa
1148     | TODO_update_ssa,                  /* todo_flags_finish */
1149   0                                     /* letter */
1150 };
1151
1152 static bool
1153 gate_store_copy_prop (void)
1154 {
1155   /* STORE-COPY-PROP is enabled only with -ftree-store-copy-prop, but
1156      when -fno-tree-store-copy-prop is specified, we should run
1157      regular COPY-PROP. That's why the pass is enabled with either
1158      flag.  */
1159   return flag_tree_store_copy_prop != 0 || flag_tree_copy_prop != 0;
1160 }
1161
1162 static unsigned int
1163 store_copy_prop (void)
1164 {
1165   /* If STORE-COPY-PROP is not enabled, we just run regular COPY-PROP.  */
1166   execute_copy_prop (flag_tree_store_copy_prop != 0);
1167   return 0;
1168 }
1169
1170 struct tree_opt_pass pass_store_copy_prop =
1171 {
1172   "store_copyprop",                     /* name */
1173   gate_store_copy_prop,                 /* gate */
1174   store_copy_prop,                      /* execute */
1175   NULL,                                 /* sub */
1176   NULL,                                 /* next */
1177   0,                                    /* static_pass_number */
1178   TV_TREE_STORE_COPY_PROP,              /* tv_id */
1179   PROP_ssa | PROP_alias | PROP_cfg,     /* properties_required */
1180   0,                                    /* properties_provided */
1181   0,                                    /* properties_destroyed */
1182   0,                                    /* todo_flags_start */
1183   TODO_dump_func
1184     | TODO_cleanup_cfg
1185     | TODO_ggc_collect
1186     | TODO_verify_ssa
1187     | TODO_update_ssa,                  /* todo_flags_finish */
1188   0                                     /* letter */
1189 };