OSDN Git Service

* haifa-sched.c (extend_global): Split to extend_global_data and
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-propagate.c
1 /* Generic SSA value propagation engine.
2    Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by the
9    Free Software Foundation; either version 3, or (at your option) any
10    later version.
11
12    GCC is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15    for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GCC; see the file COPYING3.  If not see
19    <http://www.gnu.org/licenses/>.  */
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 #include "varray.h"
42 #include "vec.h"
43 #include "value-prof.h"
44 #include "gimple.h"
45
46 /* This file implements a generic value propagation engine based on
47    the same propagation used by the SSA-CCP algorithm [1].
48
49    Propagation is performed by simulating the execution of every
50    statement that produces the value being propagated.  Simulation
51    proceeds as follows:
52
53    1- Initially, all edges of the CFG are marked not executable and
54       the CFG worklist is seeded with all the statements in the entry
55       basic block (block 0).
56
57    2- Every statement S is simulated with a call to the call-back
58       function SSA_PROP_VISIT_STMT.  This evaluation may produce 3
59       results:
60
61         SSA_PROP_NOT_INTERESTING: Statement S produces nothing of
62             interest and does not affect any of the work lists.
63
64         SSA_PROP_VARYING: The value produced by S cannot be determined
65             at compile time.  Further simulation of S is not required.
66             If S is a conditional jump, all the outgoing edges for the
67             block are considered executable and added to the work
68             list.
69
70         SSA_PROP_INTERESTING: S produces a value that can be computed
71             at compile time.  Its result can be propagated into the
72             statements that feed from S.  Furthermore, if S is a
73             conditional jump, only the edge known to be taken is added
74             to the work list.  Edges that are known not to execute are
75             never simulated.
76
77    3- PHI nodes are simulated with a call to SSA_PROP_VISIT_PHI.  The
78       return value from SSA_PROP_VISIT_PHI has the same semantics as
79       described in #2.
80
81    4- Three work lists are kept.  Statements are only added to these
82       lists if they produce one of SSA_PROP_INTERESTING or
83       SSA_PROP_VARYING.
84
85         CFG_BLOCKS contains the list of blocks to be simulated.
86             Blocks are added to this list if their incoming edges are
87             found executable.
88
89         VARYING_SSA_EDGES contains the list of statements that feed
90             from statements that produce an SSA_PROP_VARYING result.
91             These are simulated first to speed up processing.
92
93         INTERESTING_SSA_EDGES contains the list of statements that
94             feed from statements that produce an SSA_PROP_INTERESTING
95             result.
96
97    5- Simulation terminates when all three work lists are drained.
98
99    Before calling ssa_propagate, it is important to clear
100    prop_simulate_again_p for all the statements in the program that
101    should be simulated.  This initialization allows an implementation
102    to specify which statements should never be simulated.
103
104    It is also important to compute def-use information before calling
105    ssa_propagate.
106
107    References:
108
109      [1] Constant propagation with conditional branches,
110          Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
111
112      [2] Building an Optimizing Compiler,
113          Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
114
115      [3] Advanced Compiler Design and Implementation,
116          Steven Muchnick, Morgan Kaufmann, 1997, Section 12.6  */
117
118 /* Function pointers used to parameterize the propagation engine.  */
119 static ssa_prop_visit_stmt_fn ssa_prop_visit_stmt;
120 static ssa_prop_visit_phi_fn ssa_prop_visit_phi;
121
122 /* Keep track of statements that have been added to one of the SSA
123    edges worklists.  This flag is used to avoid visiting statements
124    unnecessarily when draining an SSA edge worklist.  If while
125    simulating a basic block, we find a statement with
126    STMT_IN_SSA_EDGE_WORKLIST set, we clear it to prevent SSA edge
127    processing from visiting it again.
128
129    NOTE: users of the propagation engine are not allowed to use
130    the GF_PLF_1 flag.  */
131 #define STMT_IN_SSA_EDGE_WORKLIST       GF_PLF_1
132
133 /* A bitmap to keep track of executable blocks in the CFG.  */
134 static sbitmap executable_blocks;
135
136 /* Array of control flow edges on the worklist.  */
137 static VEC(basic_block,heap) *cfg_blocks;
138
139 static unsigned int cfg_blocks_num = 0;
140 static int cfg_blocks_tail;
141 static int cfg_blocks_head;
142
143 static sbitmap bb_in_list;
144
145 /* Worklist of SSA edges which will need reexamination as their
146    definition has changed.  SSA edges are def-use edges in the SSA
147    web.  For each D-U edge, we store the target statement or PHI node
148    U.  */
149 static GTY(()) VEC(gimple,gc) *interesting_ssa_edges;
150
151 /* Identical to INTERESTING_SSA_EDGES.  For performance reasons, the
152    list of SSA edges is split into two.  One contains all SSA edges
153    who need to be reexamined because their lattice value changed to
154    varying (this worklist), and the other contains all other SSA edges
155    to be reexamined (INTERESTING_SSA_EDGES).
156
157    Since most values in the program are VARYING, the ideal situation
158    is to move them to that lattice value as quickly as possible.
159    Thus, it doesn't make sense to process any other type of lattice
160    value until all VARYING values are propagated fully, which is one
161    thing using the VARYING worklist achieves.  In addition, if we
162    don't use a separate worklist for VARYING edges, we end up with
163    situations where lattice values move from
164    UNDEFINED->INTERESTING->VARYING instead of UNDEFINED->VARYING.  */
165 static GTY(()) VEC(gimple,gc) *varying_ssa_edges;
166
167
168 /* Return true if the block worklist empty.  */
169
170 static inline bool
171 cfg_blocks_empty_p (void)
172 {
173   return (cfg_blocks_num == 0);
174 }
175
176
177 /* Add a basic block to the worklist.  The block must not be already
178    in the worklist, and it must not be the ENTRY or EXIT block.  */
179
180 static void 
181 cfg_blocks_add (basic_block bb)
182 {
183   bool head = false;
184
185   gcc_assert (bb != ENTRY_BLOCK_PTR && bb != EXIT_BLOCK_PTR);
186   gcc_assert (!TEST_BIT (bb_in_list, bb->index));
187
188   if (cfg_blocks_empty_p ())
189     {
190       cfg_blocks_tail = cfg_blocks_head = 0;
191       cfg_blocks_num = 1;
192     }
193   else
194     {
195       cfg_blocks_num++;
196       if (cfg_blocks_num > VEC_length (basic_block, cfg_blocks))
197         {
198           /* We have to grow the array now.  Adjust to queue to occupy
199              the full space of the original array.  We do not need to
200              initialize the newly allocated portion of the array
201              because we keep track of CFG_BLOCKS_HEAD and
202              CFG_BLOCKS_HEAD.  */
203           cfg_blocks_tail = VEC_length (basic_block, cfg_blocks);
204           cfg_blocks_head = 0;
205           VEC_safe_grow (basic_block, heap, cfg_blocks, 2 * cfg_blocks_tail);
206         }
207       /* Minor optimization: we prefer to see blocks with more
208          predecessors later, because there is more of a chance that
209          the incoming edges will be executable.  */
210       else if (EDGE_COUNT (bb->preds)
211                >= EDGE_COUNT (VEC_index (basic_block, cfg_blocks,
212                                          cfg_blocks_head)->preds))
213         cfg_blocks_tail = ((cfg_blocks_tail + 1)
214                            % VEC_length (basic_block, cfg_blocks));
215       else
216         {
217           if (cfg_blocks_head == 0)
218             cfg_blocks_head = VEC_length (basic_block, cfg_blocks);
219           --cfg_blocks_head;
220           head = true;
221         }
222     }
223
224   VEC_replace (basic_block, cfg_blocks,
225                head ? cfg_blocks_head : cfg_blocks_tail,
226                bb);
227   SET_BIT (bb_in_list, bb->index);
228 }
229
230
231 /* Remove a block from the worklist.  */
232
233 static basic_block
234 cfg_blocks_get (void)
235 {
236   basic_block bb;
237
238   bb = VEC_index (basic_block, cfg_blocks, cfg_blocks_head);
239
240   gcc_assert (!cfg_blocks_empty_p ());
241   gcc_assert (bb);
242
243   cfg_blocks_head = ((cfg_blocks_head + 1)
244                      % VEC_length (basic_block, cfg_blocks));
245   --cfg_blocks_num;
246   RESET_BIT (bb_in_list, bb->index);
247
248   return bb;
249 }
250
251
252 /* We have just defined a new value for VAR.  If IS_VARYING is true,
253    add all immediate uses of VAR to VARYING_SSA_EDGES, otherwise add
254    them to INTERESTING_SSA_EDGES.  */
255
256 static void
257 add_ssa_edge (tree var, bool is_varying)
258 {
259   imm_use_iterator iter;
260   use_operand_p use_p;
261
262   FOR_EACH_IMM_USE_FAST (use_p, iter, var)
263     {
264       gimple use_stmt = USE_STMT (use_p);
265
266       if (prop_simulate_again_p (use_stmt)
267           && !gimple_plf (use_stmt, STMT_IN_SSA_EDGE_WORKLIST))
268         {
269           gimple_set_plf (use_stmt, STMT_IN_SSA_EDGE_WORKLIST, true);
270           if (is_varying)
271             VEC_safe_push (gimple, gc, varying_ssa_edges, use_stmt);
272           else
273             VEC_safe_push (gimple, gc, interesting_ssa_edges, use_stmt);
274         }
275     }
276 }
277
278
279 /* Add edge E to the control flow worklist.  */
280
281 static void
282 add_control_edge (edge e)
283 {
284   basic_block bb = e->dest;
285   if (bb == EXIT_BLOCK_PTR)
286     return;
287
288   /* If the edge had already been executed, skip it.  */
289   if (e->flags & EDGE_EXECUTABLE)
290     return;
291
292   e->flags |= EDGE_EXECUTABLE;
293
294   /* If the block is already in the list, we're done.  */
295   if (TEST_BIT (bb_in_list, bb->index))
296     return;
297
298   cfg_blocks_add (bb);
299
300   if (dump_file && (dump_flags & TDF_DETAILS))
301     fprintf (dump_file, "Adding Destination of edge (%d -> %d) to worklist\n\n",
302         e->src->index, e->dest->index);
303 }
304
305
306 /* Simulate the execution of STMT and update the work lists accordingly.  */
307
308 static void
309 simulate_stmt (gimple stmt)
310 {
311   enum ssa_prop_result val = SSA_PROP_NOT_INTERESTING;
312   edge taken_edge = NULL;
313   tree output_name = NULL_TREE;
314
315   /* Don't bother visiting statements that are already
316      considered varying by the propagator.  */
317   if (!prop_simulate_again_p (stmt))
318     return;
319
320   if (gimple_code (stmt) == GIMPLE_PHI)
321     {
322       val = ssa_prop_visit_phi (stmt);
323       output_name = gimple_phi_result (stmt);
324     }
325   else
326     val = ssa_prop_visit_stmt (stmt, &taken_edge, &output_name);
327
328   if (val == SSA_PROP_VARYING)
329     {
330       prop_set_simulate_again (stmt, false);
331
332       /* If the statement produced a new varying value, add the SSA
333          edges coming out of OUTPUT_NAME.  */
334       if (output_name)
335         add_ssa_edge (output_name, true);
336
337       /* If STMT transfers control out of its basic block, add
338          all outgoing edges to the work list.  */
339       if (stmt_ends_bb_p (stmt))
340         {
341           edge e;
342           edge_iterator ei;
343           basic_block bb = gimple_bb (stmt);
344           FOR_EACH_EDGE (e, ei, bb->succs)
345             add_control_edge (e);
346         }
347     }
348   else if (val == SSA_PROP_INTERESTING)
349     {
350       /* If the statement produced new value, add the SSA edges coming
351          out of OUTPUT_NAME.  */
352       if (output_name)
353         add_ssa_edge (output_name, false);
354
355       /* If we know which edge is going to be taken out of this block,
356          add it to the CFG work list.  */
357       if (taken_edge)
358         add_control_edge (taken_edge);
359     }
360 }
361
362 /* Process an SSA edge worklist.  WORKLIST is the SSA edge worklist to
363    drain.  This pops statements off the given WORKLIST and processes
364    them until there are no more statements on WORKLIST.
365    We take a pointer to WORKLIST because it may be reallocated when an
366    SSA edge is added to it in simulate_stmt.  */
367
368 static void
369 process_ssa_edge_worklist (VEC(gimple,gc) **worklist)
370 {
371   /* Drain the entire worklist.  */
372   while (VEC_length (gimple, *worklist) > 0)
373     {
374       basic_block bb;
375
376       /* Pull the statement to simulate off the worklist.  */
377       gimple stmt = VEC_pop (gimple, *worklist);
378
379       /* If this statement was already visited by simulate_block, then
380          we don't need to visit it again here.  */
381       if (!gimple_plf (stmt, STMT_IN_SSA_EDGE_WORKLIST))
382         continue;
383
384       /* STMT is no longer in a worklist.  */
385       gimple_set_plf (stmt, STMT_IN_SSA_EDGE_WORKLIST, false);
386
387       if (dump_file && (dump_flags & TDF_DETAILS))
388         {
389           fprintf (dump_file, "\nSimulating statement (from ssa_edges): ");
390           print_gimple_stmt (dump_file, stmt, 0, dump_flags);
391         }
392
393       bb = gimple_bb (stmt);
394
395       /* PHI nodes are always visited, regardless of whether or not
396          the destination block is executable.  Otherwise, visit the
397          statement only if its block is marked executable.  */
398       if (gimple_code (stmt) == GIMPLE_PHI
399           || TEST_BIT (executable_blocks, bb->index))
400         simulate_stmt (stmt);
401     }
402 }
403
404
405 /* Simulate the execution of BLOCK.  Evaluate the statement associated
406    with each variable reference inside the block.  */
407
408 static void
409 simulate_block (basic_block block)
410 {
411   gimple_stmt_iterator gsi;
412
413   /* There is nothing to do for the exit block.  */
414   if (block == EXIT_BLOCK_PTR)
415     return;
416
417   if (dump_file && (dump_flags & TDF_DETAILS))
418     fprintf (dump_file, "\nSimulating block %d\n", block->index);
419
420   /* Always simulate PHI nodes, even if we have simulated this block
421      before.  */
422   for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
423     simulate_stmt (gsi_stmt (gsi));
424
425   /* If this is the first time we've simulated this block, then we
426      must simulate each of its statements.  */
427   if (!TEST_BIT (executable_blocks, block->index))
428     {
429       gimple_stmt_iterator j;
430       unsigned int normal_edge_count;
431       edge e, normal_edge;
432       edge_iterator ei;
433
434       /* Note that we have simulated this block.  */
435       SET_BIT (executable_blocks, block->index);
436
437       for (j = gsi_start_bb (block); !gsi_end_p (j); gsi_next (&j))
438         {
439           gimple stmt = gsi_stmt (j);
440
441           /* If this statement is already in the worklist then
442              "cancel" it.  The reevaluation implied by the worklist
443              entry will produce the same value we generate here and
444              thus reevaluating it again from the worklist is
445              pointless.  */
446           if (gimple_plf (stmt, STMT_IN_SSA_EDGE_WORKLIST))
447             gimple_set_plf (stmt, STMT_IN_SSA_EDGE_WORKLIST, false);
448
449           simulate_stmt (stmt);
450         }
451
452       /* We can not predict when abnormal edges will be executed, so
453          once a block is considered executable, we consider any
454          outgoing abnormal edges as executable.
455
456          At the same time, if this block has only one successor that is
457          reached by non-abnormal edges, then add that successor to the
458          worklist.  */
459       normal_edge_count = 0;
460       normal_edge = NULL;
461       FOR_EACH_EDGE (e, ei, block->succs)
462         {
463           if (e->flags & EDGE_ABNORMAL)
464             add_control_edge (e);
465           else
466             {
467               normal_edge_count++;
468               normal_edge = e;
469             }
470         }
471
472       if (normal_edge_count == 1)
473         add_control_edge (normal_edge);
474     }
475 }
476
477
478 /* Initialize local data structures and work lists.  */
479
480 static void
481 ssa_prop_init (void)
482 {
483   edge e;
484   edge_iterator ei;
485   basic_block bb;
486   size_t i;
487
488   /* Worklists of SSA edges.  */
489   interesting_ssa_edges = VEC_alloc (gimple, gc, 20);
490   varying_ssa_edges = VEC_alloc (gimple, gc, 20);
491
492   executable_blocks = sbitmap_alloc (last_basic_block);
493   sbitmap_zero (executable_blocks);
494
495   bb_in_list = sbitmap_alloc (last_basic_block);
496   sbitmap_zero (bb_in_list);
497
498   if (dump_file && (dump_flags & TDF_DETAILS))
499     dump_immediate_uses (dump_file);
500
501   cfg_blocks = VEC_alloc (basic_block, heap, 20);
502   VEC_safe_grow (basic_block, heap, cfg_blocks, 20);
503
504   /* Initialize the values for every SSA_NAME.  */
505   for (i = 1; i < num_ssa_names; i++)
506     if (ssa_name (i))
507       SSA_NAME_VALUE (ssa_name (i)) = NULL_TREE;
508
509   /* Initially assume that every edge in the CFG is not executable.
510      (including the edges coming out of ENTRY_BLOCK_PTR).  */
511   FOR_ALL_BB (bb)
512     {
513       gimple_stmt_iterator si;
514
515       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
516         gimple_set_plf (gsi_stmt (si), STMT_IN_SSA_EDGE_WORKLIST, false);
517     
518       for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
519         gimple_set_plf (gsi_stmt (si), STMT_IN_SSA_EDGE_WORKLIST, false);
520
521       FOR_EACH_EDGE (e, ei, bb->succs)
522         e->flags &= ~EDGE_EXECUTABLE;
523     }
524
525   /* Seed the algorithm by adding the successors of the entry block to the
526      edge worklist.  */
527   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
528     add_control_edge (e);
529 }
530
531
532 /* Free allocated storage.  */
533
534 static void
535 ssa_prop_fini (void)
536 {
537   VEC_free (gimple, gc, interesting_ssa_edges);
538   VEC_free (gimple, gc, varying_ssa_edges);
539   VEC_free (basic_block, heap, cfg_blocks);
540   cfg_blocks = NULL;
541   sbitmap_free (bb_in_list);
542   sbitmap_free (executable_blocks);
543 }
544
545
546 /* Return true if EXPR is an acceptable right-hand-side for a
547    GIMPLE assignment.  We validate the entire tree, not just
548    the root node, thus catching expressions that embed complex
549    operands that are not permitted in GIMPLE.  This function
550    is needed because the folding routines in fold-const.c
551    may return such expressions in some cases, e.g., an array
552    access with an embedded index addition.  It may make more
553    sense to have folding routines that are sensitive to the
554    constraints on GIMPLE operands, rather than abandoning any
555    any attempt to fold if the usual folding turns out to be too
556    aggressive.  */
557
558 bool
559 valid_gimple_rhs_p (tree expr)
560 {
561   enum tree_code code = TREE_CODE (expr);
562
563   switch (TREE_CODE_CLASS (code))
564     {
565     case tcc_declaration:
566       if (!is_gimple_variable (expr))
567         return false;
568       break;
569
570     case tcc_constant:
571       /* All constants are ok.  */
572       break;
573
574     case tcc_binary:
575     case tcc_comparison:
576       if (!is_gimple_val (TREE_OPERAND (expr, 0))
577           || !is_gimple_val (TREE_OPERAND (expr, 1)))
578         return false;
579       break;
580
581     case tcc_unary:
582       if (!is_gimple_val (TREE_OPERAND (expr, 0)))
583         return false;
584       break;
585
586     case tcc_expression:
587       switch (code)
588         {
589         case ADDR_EXPR:
590           {
591             tree t;
592             if (is_gimple_min_invariant (expr))
593               return true;
594             t = TREE_OPERAND (expr, 0);
595             while (handled_component_p (t))
596               {
597                 /* ??? More checks needed, see the GIMPLE verifier.  */
598                 if ((TREE_CODE (t) == ARRAY_REF
599                      || TREE_CODE (t) == ARRAY_RANGE_REF)
600                     && !is_gimple_val (TREE_OPERAND (t, 1)))
601                   return false;
602                 t = TREE_OPERAND (t, 0);
603               }
604             if (!is_gimple_id (t))
605               return false;
606           }
607           break;
608
609         case TRUTH_NOT_EXPR:
610           if (!is_gimple_val (TREE_OPERAND (expr, 0)))
611             return false;
612           break;
613
614         case TRUTH_AND_EXPR:
615         case TRUTH_XOR_EXPR:
616         case TRUTH_OR_EXPR:
617           if (!is_gimple_val (TREE_OPERAND (expr, 0))
618               || !is_gimple_val (TREE_OPERAND (expr, 1)))
619             return false;
620           break;
621
622         case EXC_PTR_EXPR:
623         case FILTER_EXPR:
624           break;
625
626         default:
627           return false;
628         }
629       break;
630
631     case tcc_vl_exp:
632       return false;
633
634     case tcc_exceptional:
635       if (code != SSA_NAME)
636         return false;
637       break;
638
639     default:
640       return false;
641     }
642
643   return true;
644 }
645
646
647 /* Return true if EXPR is a CALL_EXPR suitable for representation
648    as a single GIMPLE_CALL statement.  If the arguments require
649    further gimplification, return false.  */
650
651 bool
652 valid_gimple_call_p (tree expr)
653 {
654   unsigned i, nargs;
655
656   if (TREE_CODE (expr) != CALL_EXPR)
657     return false;
658
659   nargs = call_expr_nargs (expr);
660   for (i = 0; i < nargs; i++)
661     if (! is_gimple_operand (CALL_EXPR_ARG (expr, i)))
662       return false;
663
664   return true;
665 }
666
667
668 /* Make SSA names defined by OLD_STMT point to NEW_STMT
669    as their defining statement.  */
670
671 void
672 move_ssa_defining_stmt_for_defs (gimple new_stmt, gimple old_stmt)
673 {
674   tree var;
675   ssa_op_iter iter;
676
677   if (gimple_in_ssa_p (cfun))
678     {
679       /* Make defined SSA_NAMEs point to the new
680          statement as their definition.  */
681       FOR_EACH_SSA_TREE_OPERAND (var, old_stmt, iter, SSA_OP_ALL_DEFS)
682         {
683           if (TREE_CODE (var) == SSA_NAME)
684             SSA_NAME_DEF_STMT (var) = new_stmt;
685         }
686     }
687 }
688
689
690 /* Update a GIMPLE_CALL statement at iterator *SI_P to reflect the
691    value of EXPR, which is expected to be the result of folding the
692    call.  This can only be done if EXPR is a CALL_EXPR with valid
693    GIMPLE operands as arguments, or if it is a suitable RHS expression
694    for a GIMPLE_ASSIGN.  More complex expressions will require
695    gimplification, which will introduce addtional statements.  In this
696    event, no update is performed, and the function returns false.
697    Note that we cannot mutate a GIMPLE_CALL in-place, so we always
698    replace the statement at *SI_P with an entirely new statement.
699    The new statement need not be a call, e.g., if the original call
700    folded to a constant.  */
701
702 bool
703 update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
704 {
705   tree lhs;
706
707   gimple stmt = gsi_stmt (*si_p);
708
709   gcc_assert (is_gimple_call (stmt));
710
711   lhs = gimple_call_lhs (stmt);
712
713   if (valid_gimple_call_p (expr))
714     {
715       /* The call has simplified to another call.  */
716       tree fn = CALL_EXPR_FN (expr);
717       unsigned i;
718       unsigned nargs = call_expr_nargs (expr);
719       VEC(tree, heap) *args = NULL;
720       gimple new_stmt;
721
722       if (nargs > 0)
723         {
724           args = VEC_alloc (tree, heap, nargs);
725           VEC_safe_grow (tree, heap, args, nargs);
726       
727           for (i = 0; i < nargs; i++)
728             VEC_replace (tree, args, i, CALL_EXPR_ARG (expr, i));
729         }
730
731       new_stmt = gimple_build_call_vec (fn, args);
732       gimple_call_set_lhs (new_stmt, lhs);
733       copy_virtual_operands (new_stmt, stmt);
734       move_ssa_defining_stmt_for_defs (new_stmt, stmt);
735       gimple_set_location (new_stmt, gimple_location (stmt));
736       gsi_replace (si_p, new_stmt, false);
737       VEC_free (tree, heap, args);
738
739       return true;
740     }
741   else if (valid_gimple_rhs_p (expr))
742     {
743       gimple new_stmt;
744
745       /* The call has simplified to an expression
746          that cannot be represented as a GIMPLE_CALL. */
747       if (lhs)
748         {
749           /* A value is expected.
750              Introduce a new GIMPLE_ASSIGN statement.  */
751           STRIP_USELESS_TYPE_CONVERSION (expr);
752           new_stmt = gimple_build_assign (lhs, expr);
753           copy_virtual_operands (new_stmt, stmt);
754           move_ssa_defining_stmt_for_defs (new_stmt, stmt);
755         }
756       else if (!TREE_SIDE_EFFECTS (expr))
757         {
758           /* No value is expected, and EXPR has no effect.
759              Replace it with an empty statement.  */
760           new_stmt = gimple_build_nop ();
761         }
762       else
763         {
764           /* No value is expected, but EXPR has an effect,
765              e.g., it could be a reference to a volatile
766              variable.  Create an assignment statement
767              with a dummy (unused) lhs variable.  */
768           STRIP_USELESS_TYPE_CONVERSION (expr);
769           lhs = create_tmp_var (TREE_TYPE (expr), NULL);
770           new_stmt = gimple_build_assign (lhs, expr);
771           add_referenced_var (lhs);
772           lhs = make_ssa_name (lhs, new_stmt);
773           gimple_assign_set_lhs (new_stmt, lhs);
774           copy_virtual_operands (new_stmt, stmt);
775           move_ssa_defining_stmt_for_defs (new_stmt, stmt);
776         }
777       gimple_set_location (new_stmt, gimple_location (stmt));
778       gsi_replace (si_p, new_stmt, false);
779       return true;
780     }
781   else
782     /* The call simplified to an expression that is
783        not a valid GIMPLE RHS.  */
784     return false;
785 }
786
787
788 /* Entry point to the propagation engine.
789
790    VISIT_STMT is called for every statement visited.
791    VISIT_PHI is called for every PHI node visited.  */
792
793 void
794 ssa_propagate (ssa_prop_visit_stmt_fn visit_stmt,
795                ssa_prop_visit_phi_fn visit_phi)
796 {
797   ssa_prop_visit_stmt = visit_stmt;
798   ssa_prop_visit_phi = visit_phi;
799
800   ssa_prop_init ();
801
802   /* Iterate until the worklists are empty.  */
803   while (!cfg_blocks_empty_p () 
804          || VEC_length (gimple, interesting_ssa_edges) > 0
805          || VEC_length (gimple, varying_ssa_edges) > 0)
806     {
807       if (!cfg_blocks_empty_p ())
808         {
809           /* Pull the next block to simulate off the worklist.  */
810           basic_block dest_block = cfg_blocks_get ();
811           simulate_block (dest_block);
812         }
813
814       /* In order to move things to varying as quickly as
815          possible,process the VARYING_SSA_EDGES worklist first.  */
816       process_ssa_edge_worklist (&varying_ssa_edges);
817
818       /* Now process the INTERESTING_SSA_EDGES worklist.  */
819       process_ssa_edge_worklist (&interesting_ssa_edges);
820     }
821
822   ssa_prop_fini ();
823 }
824
825
826 /* Return the first VDEF operand for STMT.  */
827
828 tree
829 first_vdef (gimple stmt)
830 {
831   ssa_op_iter iter;
832   tree op;
833
834   /* Simply return the first operand we arrive at.  */
835   FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_VIRTUAL_DEFS)
836     return (op);
837
838   gcc_unreachable ();
839 }
840
841
842 /* Return true if STMT is of the form 'LHS = mem_ref', where 'mem_ref'
843    is a non-volatile pointer dereference, a structure reference or a
844    reference to a single _DECL.  Ignore volatile memory references
845    because they are not interesting for the optimizers.  */
846
847 bool
848 stmt_makes_single_load (gimple stmt)
849 {
850   tree rhs;
851
852   if (gimple_code (stmt) != GIMPLE_ASSIGN)
853     return false;
854
855   /* Only a GIMPLE_SINGLE_RHS assignment may have a
856      declaration or reference as its RHS.  */
857   if (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
858       != GIMPLE_SINGLE_RHS)
859     return false;
860
861   if (ZERO_SSA_OPERANDS (stmt, SSA_OP_VDEF|SSA_OP_VUSE))
862     return false;
863
864   rhs = gimple_assign_rhs1 (stmt);
865
866   return (!TREE_THIS_VOLATILE (rhs)
867           && (DECL_P (rhs)
868               || REFERENCE_CLASS_P (rhs)));
869 }
870
871
872 /* Return true if STMT is of the form 'mem_ref = RHS', where 'mem_ref'
873    is a non-volatile pointer dereference, a structure reference or a
874    reference to a single _DECL.  Ignore volatile memory references
875    because they are not interesting for the optimizers.  */
876
877 bool
878 stmt_makes_single_store (gimple stmt)
879 {
880   tree lhs;
881
882   if (gimple_code (stmt) != GIMPLE_ASSIGN
883       && gimple_code (stmt) != GIMPLE_CALL)
884     return false;
885
886   if (ZERO_SSA_OPERANDS (stmt, SSA_OP_VDEF))
887     return false;
888
889   lhs = gimple_get_lhs (stmt);
890
891   /* A call statement may have a null LHS.  */
892   if (!lhs)
893     return false;
894
895   return (!TREE_THIS_VOLATILE (lhs)
896           && (DECL_P (lhs)
897               || REFERENCE_CLASS_P (lhs)));
898 }
899
900
901 /* If STMT makes a single memory load and all the virtual use operands
902    have the same value in array VALUES, return it.  Otherwise, return
903    NULL.  */
904
905 prop_value_t *
906 get_value_loaded_by (gimple stmt, prop_value_t *values)
907 {
908   ssa_op_iter i;
909   tree vuse;
910   prop_value_t *prev_val = NULL;
911   prop_value_t *val = NULL;
912
913   FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, i, SSA_OP_VIRTUAL_USES)
914     {
915       val = &values[SSA_NAME_VERSION (vuse)];
916       if (prev_val && prev_val->value != val->value)
917         return NULL;
918       prev_val = val;
919     }
920
921   return val;
922 }
923
924
925 /* Propagation statistics.  */
926 struct prop_stats_d
927 {
928   long num_const_prop;
929   long num_copy_prop;
930   long num_pred_folded;
931   long num_dce;
932 };
933
934 static struct prop_stats_d prop_stats;
935
936 /* Replace USE references in statement STMT with the values stored in
937    PROP_VALUE. Return true if at least one reference was replaced.  */
938
939 static bool
940 replace_uses_in (gimple stmt, prop_value_t *prop_value)
941 {
942   bool replaced = false;
943   use_operand_p use;
944   ssa_op_iter iter;
945
946   FOR_EACH_SSA_USE_OPERAND (use, stmt, iter, SSA_OP_USE)
947     {
948       tree tuse = USE_FROM_PTR (use);
949       tree val = prop_value[SSA_NAME_VERSION (tuse)].value;
950
951       if (val == tuse || val == NULL_TREE)
952         continue;
953
954       if (gimple_code (stmt) == GIMPLE_ASM
955           && !may_propagate_copy_into_asm (tuse))
956         continue;
957
958       if (!may_propagate_copy (tuse, val))
959         continue;
960
961       if (TREE_CODE (val) != SSA_NAME)
962         prop_stats.num_const_prop++;
963       else
964         prop_stats.num_copy_prop++;
965
966       propagate_value (use, val);
967
968       replaced = true;
969     }
970
971   return replaced;
972 }
973
974
975 /* Replace the VUSE references in statement STMT with the values
976    stored in PROP_VALUE.  Return true if a reference was replaced.
977
978    Replacing VUSE operands is slightly more complex than replacing
979    regular USEs.  We are only interested in two types of replacements
980    here:
981    
982    1- If the value to be replaced is a constant or an SSA name for a
983       GIMPLE register, then we are making a copy/constant propagation
984       from a memory store.  For instance,
985
986         # a_3 = VDEF <a_2>
987         a.b = x_1;
988         ...
989         # VUSE <a_3>
990         y_4 = a.b;
991
992       This replacement is only possible iff STMT is an assignment
993       whose RHS is identical to the LHS of the statement that created
994       the VUSE(s) that we are replacing.  Otherwise, we may do the
995       wrong replacement:
996
997         # a_3 = VDEF <a_2>
998         # b_5 = VDEF <b_4>
999         *p = 10;
1000         ...
1001         # VUSE <b_5>
1002         x_8 = b;
1003
1004       Even though 'b_5' acquires the value '10' during propagation,
1005       there is no way for the propagator to tell whether the
1006       replacement is correct in every reached use, because values are
1007       computed at definition sites.  Therefore, when doing final
1008       substitution of propagated values, we have to check each use
1009       site.  Since the RHS of STMT ('b') is different from the LHS of
1010       the originating statement ('*p'), we cannot replace 'b' with
1011       '10'.
1012
1013       Similarly, when merging values from PHI node arguments,
1014       propagators need to take care not to merge the same values
1015       stored in different locations:
1016
1017                 if (...)
1018                   # a_3 = VDEF <a_2>
1019                   a.b = 3;
1020                 else
1021                   # a_4 = VDEF <a_2>
1022                   a.c = 3;
1023                 # a_5 = PHI <a_3, a_4>
1024
1025       It would be wrong to propagate '3' into 'a_5' because that
1026       operation merges two stores to different memory locations.
1027
1028
1029    2- If the value to be replaced is an SSA name for a virtual
1030       register, then we simply replace each VUSE operand with its
1031       value from PROP_VALUE.  This is the same replacement done by
1032       replace_uses_in.  */
1033
1034 static bool
1035 replace_vuses_in (gimple stmt, prop_value_t *prop_value)
1036 {
1037   bool replaced = false;
1038   ssa_op_iter iter;
1039   use_operand_p vuse;
1040
1041   if (stmt_makes_single_load (stmt))
1042     {
1043       /* If STMT is an assignment whose RHS is a single memory load,
1044          see if we are trying to propagate a constant or a GIMPLE
1045          register (case #1 above).  */
1046       prop_value_t *val = get_value_loaded_by (stmt, prop_value);
1047       tree rhs = gimple_assign_rhs1 (stmt);
1048
1049       if (val
1050           && val->value
1051           && (is_gimple_reg (val->value)
1052               || is_gimple_min_invariant (val->value))
1053           && simple_cst_equal (rhs, val->mem_ref) == 1)
1054         {
1055           /* We can only perform the substitution if the load is done
1056              from the same memory location as the original store.
1057              Since we already know that there are no intervening
1058              stores between DEF_STMT and STMT, we only need to check
1059              that the RHS of STMT is the same as the memory reference
1060              propagated together with the value.  */
1061           gimple_assign_set_rhs1 (stmt, val->value);
1062
1063           if (TREE_CODE (val->value) != SSA_NAME)
1064             prop_stats.num_const_prop++;
1065           else
1066             prop_stats.num_copy_prop++;
1067
1068           /* Since we have replaced the whole RHS of STMT, there
1069              is no point in checking the other VUSEs, as they will
1070              all have the same value.  */
1071           return true;
1072         }
1073     }
1074
1075   /* Otherwise, the values for every VUSE operand must be other
1076      SSA_NAMEs that can be propagated into STMT.  */
1077   FOR_EACH_SSA_USE_OPERAND (vuse, stmt, iter, SSA_OP_VIRTUAL_USES)
1078     {
1079       tree var = USE_FROM_PTR (vuse);
1080       tree val = prop_value[SSA_NAME_VERSION (var)].value;
1081
1082       if (val == NULL_TREE || var == val)
1083         continue;
1084
1085       /* Constants and copies propagated between real and virtual
1086          operands are only possible in the cases handled above.  They
1087          should be ignored in any other context.  */
1088       if (is_gimple_min_invariant (val) || is_gimple_reg (val))
1089         continue;
1090
1091       propagate_value (vuse, val);
1092       prop_stats.num_copy_prop++;
1093       replaced = true;
1094     }
1095
1096   return replaced;
1097 }
1098
1099
1100 /* Replace propagated values into all the arguments for PHI using the
1101    values from PROP_VALUE.  */
1102
1103 static void
1104 replace_phi_args_in (gimple phi, prop_value_t *prop_value)
1105 {
1106   size_t i;
1107   bool replaced = false;
1108
1109   if (dump_file && (dump_flags & TDF_DETAILS))
1110     {
1111       fprintf (dump_file, "Folding PHI node: ");
1112       print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
1113     }
1114
1115   for (i = 0; i < gimple_phi_num_args (phi); i++)
1116     {
1117       tree arg = gimple_phi_arg_def (phi, i);
1118
1119       if (TREE_CODE (arg) == SSA_NAME)
1120         {
1121           tree val = prop_value[SSA_NAME_VERSION (arg)].value;
1122
1123           if (val && val != arg && may_propagate_copy (arg, val))
1124             {
1125               if (TREE_CODE (val) != SSA_NAME)
1126                 prop_stats.num_const_prop++;
1127               else
1128                 prop_stats.num_copy_prop++;
1129
1130               propagate_value (PHI_ARG_DEF_PTR (phi, i), val);
1131               replaced = true;
1132
1133               /* If we propagated a copy and this argument flows
1134                  through an abnormal edge, update the replacement
1135                  accordingly.  */
1136               if (TREE_CODE (val) == SSA_NAME
1137                   && gimple_phi_arg_edge (phi, i)->flags & EDGE_ABNORMAL)
1138                 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val) = 1;
1139             }
1140         }
1141     }
1142   
1143   if (dump_file && (dump_flags & TDF_DETAILS))
1144     {
1145       if (!replaced)
1146         fprintf (dump_file, "No folding possible\n");
1147       else
1148         {
1149           fprintf (dump_file, "Folded into: ");
1150           print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
1151           fprintf (dump_file, "\n");
1152         }
1153     }
1154 }
1155
1156
1157 /* If the statement pointed by SI has a predicate whose value can be
1158    computed using the value range information computed by VRP, compute
1159    its value and return true.  Otherwise, return false.  */
1160
1161 static bool
1162 fold_predicate_in (gimple_stmt_iterator *si)
1163 {
1164   bool assignment_p = false;
1165   tree val;
1166   gimple stmt = gsi_stmt (*si);
1167
1168   if (is_gimple_assign (stmt)
1169       && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
1170     {
1171       assignment_p = true;
1172       val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
1173                                       gimple_assign_rhs1 (stmt),
1174                                       gimple_assign_rhs2 (stmt),
1175                                       stmt);
1176     }
1177   else if (gimple_code (stmt) == GIMPLE_COND)
1178     val = vrp_evaluate_conditional (gimple_cond_code (stmt),
1179                                     gimple_cond_lhs (stmt),
1180                                     gimple_cond_rhs (stmt),
1181                                     stmt);
1182   else
1183     return false;
1184
1185
1186   if (val)
1187     {
1188       if (assignment_p)
1189         val = fold_convert (gimple_expr_type (stmt), val);
1190       
1191       if (dump_file)
1192         {
1193           fprintf (dump_file, "Folding predicate ");
1194           print_gimple_expr (dump_file, stmt, 0, 0);
1195           fprintf (dump_file, " to ");
1196           print_generic_expr (dump_file, val, 0);
1197           fprintf (dump_file, "\n");
1198         }
1199
1200       prop_stats.num_pred_folded++;
1201
1202       if (is_gimple_assign (stmt))
1203         gimple_assign_set_rhs_from_tree (si, val);
1204       else
1205         {
1206           gcc_assert (gimple_code (stmt) == GIMPLE_COND);
1207           if (integer_zerop (val))
1208             gimple_cond_make_false (stmt);
1209           else if (integer_onep (val))
1210             gimple_cond_make_true (stmt);
1211           else
1212             gcc_unreachable ();
1213         }
1214
1215       return true;
1216     }
1217
1218   return false;
1219 }
1220
1221
1222 /* Perform final substitution and folding of propagated values.
1223
1224    PROP_VALUE[I] contains the single value that should be substituted
1225    at every use of SSA name N_I.  If PROP_VALUE is NULL, no values are
1226    substituted.
1227
1228    If USE_RANGES_P is true, statements that contain predicate
1229    expressions are evaluated with a call to vrp_evaluate_conditional.
1230    This will only give meaningful results when called from tree-vrp.c
1231    (the information used by vrp_evaluate_conditional is built by the
1232    VRP pass).  
1233
1234    Return TRUE when something changed.  */
1235
1236 bool
1237 substitute_and_fold (prop_value_t *prop_value, bool use_ranges_p)
1238 {
1239   basic_block bb;
1240   bool something_changed = false;
1241
1242   if (prop_value == NULL && !use_ranges_p)
1243     return false;
1244
1245   if (dump_file && (dump_flags & TDF_DETAILS))
1246     fprintf (dump_file, "\nSubstituting values and folding statements\n\n");
1247
1248   memset (&prop_stats, 0, sizeof (prop_stats));
1249
1250   /* Substitute values in every statement of every basic block.  */
1251   FOR_EACH_BB (bb)
1252     {
1253       gimple_stmt_iterator i;
1254
1255       /* Propagate known values into PHI nodes.  */
1256       if (prop_value)
1257         for (i = gsi_start_phis (bb); !gsi_end_p (i); gsi_next (&i))
1258           replace_phi_args_in (gsi_stmt (i), prop_value);
1259
1260       /* Propagate known values into stmts.  Do a backward walk to expose
1261          more trivially deletable stmts.  */
1262       for (i = gsi_last_bb (bb); !gsi_end_p (i);)
1263         {
1264           bool did_replace;
1265           gimple stmt = gsi_stmt (i);
1266           enum gimple_code code = gimple_code (stmt);
1267
1268           /* Ignore ASSERT_EXPRs.  They are used by VRP to generate
1269              range information for names and they are discarded
1270              afterwards.  */
1271
1272           if (code == GIMPLE_ASSIGN
1273               && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
1274             {
1275               gsi_prev (&i);
1276               continue;
1277             }
1278
1279           /* No point propagating into a stmt whose result is not used,
1280              but instead we might be able to remove a trivially dead stmt.  */
1281           if (gimple_get_lhs (stmt)
1282               && TREE_CODE (gimple_get_lhs (stmt)) == SSA_NAME
1283               && has_zero_uses (gimple_get_lhs (stmt))
1284               && !stmt_could_throw_p (stmt)
1285               && !gimple_has_side_effects (stmt))
1286             {
1287               gimple_stmt_iterator i2;
1288
1289               if (dump_file && dump_flags & TDF_DETAILS)
1290                 {
1291                   fprintf (dump_file, "Removing dead stmt ");
1292                   print_gimple_stmt (dump_file, stmt, 0, 0);
1293                   fprintf (dump_file, "\n");
1294                 }
1295               prop_stats.num_dce++;
1296               gsi_prev (&i);
1297               i2 = gsi_for_stmt (stmt);
1298               gsi_remove (&i2, true);
1299               release_defs (stmt);
1300               continue;
1301             }
1302
1303           /* Record the state of the statement before replacements.  */
1304           push_stmt_changes (gsi_stmt_ptr (&i));
1305
1306           /* Replace the statement with its folded version and mark it
1307              folded.  */
1308           did_replace = false;
1309           if (dump_file && (dump_flags & TDF_DETAILS))
1310             {
1311               fprintf (dump_file, "Folding statement: ");
1312               print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1313             }
1314
1315           /* If we have range information, see if we can fold
1316              predicate expressions.  */
1317           if (use_ranges_p)
1318             {
1319               did_replace = fold_predicate_in (&i);
1320               /* fold_predicate_in should not have reallocated STMT.  */
1321               gcc_assert (gsi_stmt (i) == stmt);
1322             }
1323
1324           if (prop_value)
1325             {
1326               /* Only replace real uses if we couldn't fold the
1327                  statement using value range information (value range
1328                  information is not collected on virtuals, so we only
1329                  need to check this for real uses).  */
1330               if (!did_replace)
1331                 did_replace |= replace_uses_in (stmt, prop_value);
1332
1333               did_replace |= replace_vuses_in (stmt, prop_value);
1334             }
1335
1336           /* If we made a replacement, fold and cleanup the statement.  */
1337           if (did_replace)
1338             {
1339               gimple old_stmt = stmt;
1340
1341               fold_stmt (&i);
1342               stmt = gsi_stmt (i);
1343
1344               /* If we cleaned up EH information from the statement,
1345                  remove EH edges.  */
1346               if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
1347                 gimple_purge_dead_eh_edges (bb);
1348
1349               if (is_gimple_assign (stmt)
1350                   && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1351                       == GIMPLE_SINGLE_RHS))
1352               {
1353                 tree rhs = gimple_assign_rhs1 (stmt);
1354                 
1355                 if (TREE_CODE (rhs) == ADDR_EXPR)
1356                   recompute_tree_invariant_for_addr_expr (rhs);
1357               }
1358
1359               /* Determine what needs to be done to update the SSA form.  */
1360               pop_stmt_changes (gsi_stmt_ptr (&i));
1361               something_changed = true;
1362             }
1363           else
1364             {
1365               /* The statement was not modified, discard the change buffer.  */
1366               discard_stmt_changes (gsi_stmt_ptr (&i));
1367             }
1368
1369           if (dump_file && (dump_flags & TDF_DETAILS))
1370             {
1371               if (did_replace)
1372                 {
1373                   fprintf (dump_file, "Folded into: ");
1374                   print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1375                   fprintf (dump_file, "\n");
1376                 }
1377               else
1378                 fprintf (dump_file, "Not folded\n");
1379             }
1380
1381           /* Some statements may be simplified using ranges.  For
1382              example, division may be replaced by shifts, modulo
1383              replaced with bitwise and, etc.   Do this after 
1384              substituting constants, folding, etc so that we're
1385              presented with a fully propagated, canonicalized
1386              statement.  */
1387           if (use_ranges_p)
1388             simplify_stmt_using_ranges (stmt);
1389
1390           gsi_prev (&i);
1391         }
1392     }
1393
1394   statistics_counter_event (cfun, "Constants propagated",
1395                             prop_stats.num_const_prop);
1396   statistics_counter_event (cfun, "Copies propagated",
1397                             prop_stats.num_copy_prop);
1398   statistics_counter_event (cfun, "Predicates folded",
1399                             prop_stats.num_pred_folded);
1400   statistics_counter_event (cfun, "Statements deleted",
1401                             prop_stats.num_dce);
1402   return something_changed;
1403 }
1404
1405 #include "gt-tree-ssa-propagate.h"