OSDN Git Service

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