OSDN Git Service

c8ab92a896beab2cf8496e4c1f89a89882a212ff
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-ccp.c
1 /* Conditional constant propagation pass for the GNU compiler.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3    Adapted from original RTL SSA-CCP by Daniel Berlin <dberlin@dberlin.org>
4    Adapted to GIMPLE trees by Diego Novillo <dnovillo@redhat.com>
5
6 This file is part of GCC.
7    
8 GCC is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12    
13 GCC is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17    
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21 02111-1307, USA.  */
22
23 /* Conditional constant propagation.
24
25    References:
26
27      Constant propagation with conditional branches,
28      Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
29
30      Building an Optimizing Compiler,
31      Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
32
33      Advanced Compiler Design and Implementation,
34      Steven Muchnick, Morgan Kaufmann, 1997, Section 12.6  */
35
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "tm.h"
40 #include "errors.h"
41 #include "ggc.h"
42 #include "tree.h"
43 #include "langhooks.h"
44
45 /* These RTL headers are needed for basic-block.h.  */
46 #include "rtl.h"
47 #include "tm_p.h"
48 #include "hard-reg-set.h"
49 #include "basic-block.h"
50
51 #include "diagnostic.h"
52 #include "tree-inline.h"
53 #include "tree-flow.h"
54 #include "tree-gimple.h"
55 #include "tree-dump.h"
56 #include "tree-pass.h"
57 #include "timevar.h"
58 #include "expr.h"
59 #include "flags.h"
60
61
62 /* Possible lattice values.  */
63 typedef enum
64 {
65   UNINITIALIZED = 0,
66   UNDEFINED,
67   UNKNOWN_VAL,
68   CONSTANT,
69   VARYING
70 } latticevalue;
71
72 /* Use the TREE_VISITED bitflag to mark statements and PHI nodes that have
73    been deemed VARYING and shouldn't be simulated again.  */
74 #define DONT_SIMULATE_AGAIN(T)  TREE_VISITED (T)
75
76 /* Main structure for CCP.  Contains the lattice value and, if it's a
77     constant, the constant value.  */
78 typedef struct
79 {
80   latticevalue lattice_val;
81   tree const_val;
82 } value;
83
84 /* A bitmap to keep track of executable blocks in the CFG.  */
85 static sbitmap executable_blocks;
86
87 /* Array of control flow edges on the worklist.  */
88 static GTY(()) varray_type cfg_blocks = NULL;
89
90 static unsigned int cfg_blocks_num = 0;
91 static int cfg_blocks_tail;
92 static int cfg_blocks_head;
93
94 static sbitmap bb_in_list;
95
96 /* This is used to track the current value of each variable.  */
97 static value *value_vector;
98
99 /* Worklist of SSA edges which will need reexamination as their definition
100    has changed.  SSA edges are def-use edges in the SSA web.  For each
101    edge, we store the definition statement or PHI node D.  The destination
102    nodes that need to be visited are accessed using immediate_uses
103    (D).  */
104 static GTY(()) varray_type ssa_edges;
105
106 /* Identical to SSA_EDGES.  For performance reasons, the list of SSA
107    edges is split into two.  One contains all SSA edges who need to be
108    reexamined because their lattice value changed to varying (this
109    worklist), and the other contains all other SSA edges to be
110    reexamined (ssa_edges).
111    
112    Since most values in the program are varying, the ideal situation
113    is to move them to that lattice value as quickly as possible.
114    Thus, it doesn't make sense to process any other type of lattice
115    value until all varying values are propagated fully, which is one
116    thing using the varying worklist achieves.  In addition, if you
117    don't use a separate worklist for varying edges, you end up with
118    situations where lattice values move from
119    undefined->constant->varying instead of undefined->varying.
120 */
121 static GTY(()) varray_type varying_ssa_edges;
122
123
124 static void initialize (void);
125 static void finalize (void);
126 static void visit_phi_node (tree);
127 static tree ccp_fold (tree);
128 static value cp_lattice_meet (value, value);
129 static void visit_stmt (tree);
130 static void visit_cond_stmt (tree);
131 static void visit_assignment (tree);
132 static void add_var_to_ssa_edges_worklist (tree, value);
133 static void add_outgoing_control_edges (basic_block);
134 static void add_control_edge (edge);
135 static void def_to_varying (tree);
136 static void set_lattice_value (tree, value);
137 static void simulate_block (basic_block);
138 static void simulate_stmt (tree);
139 static void substitute_and_fold (void);
140 static value evaluate_stmt (tree);
141 static void dump_lattice_value (FILE *, const char *, value);
142 static bool replace_uses_in (tree, bool *);
143 static bool replace_vuse_in (tree, bool *);
144 static latticevalue likely_value (tree);
145 static tree get_rhs (tree);
146 static bool set_rhs (tree *, tree);
147 static value *get_value (tree);
148 static value get_default_value (tree);
149 static tree ccp_fold_builtin (tree, tree);
150 static bool get_strlen (tree, tree *, bitmap);
151 static inline bool cfg_blocks_empty_p (void);
152 static void cfg_blocks_add (basic_block);
153 static basic_block cfg_blocks_get (void);
154 static bool need_imm_uses_for (tree var);
155
156 /* Process an SSA edge worklist.  WORKLIST is the SSA edge worklist to
157    drain. This pops statements off the given WORKLIST and processes
158    them until there are no more statements on WORKLIST.  */
159
160 static void
161 process_ssa_edge_worklist (varray_type *worklist)
162 {
163   /* Drain the entire worklist.  */
164   while (VARRAY_ACTIVE_SIZE (*worklist) > 0)
165     {
166       /* Pull the statement to simulate off the worklist.  */
167       tree stmt = VARRAY_TOP_TREE (*worklist);
168       stmt_ann_t ann = stmt_ann (stmt);
169       VARRAY_POP (*worklist);
170       
171       /* visit_stmt can "cancel" reevaluation of some statements.
172          If it does, then in_ccp_worklist will be zero.  */
173       if (ann->in_ccp_worklist)
174         {
175           ann->in_ccp_worklist = 0;
176           simulate_stmt (stmt);
177         }
178     } 
179 }
180  
181 /* Main entry point for SSA Conditional Constant Propagation.  FNDECL is
182    the declaration for the function to optimize.
183    
184    On exit, VARS_TO_RENAME will contain the symbols that have been exposed by
185    the propagation of ADDR_EXPR expressions into pointer dereferences and need
186    to be renamed into SSA.
187
188    PHASE indicates which dump file from the DUMP_FILES array to use when
189    dumping debugging information.  */
190
191 static void
192 tree_ssa_ccp (void)
193 {
194   initialize ();
195
196   /* Iterate until the worklists are empty.  */
197   while (!cfg_blocks_empty_p () 
198          || VARRAY_ACTIVE_SIZE (ssa_edges) > 0
199          || VARRAY_ACTIVE_SIZE (varying_ssa_edges) > 0)
200     {
201       if (!cfg_blocks_empty_p ())
202         {
203           /* Pull the next block to simulate off the worklist.  */
204           basic_block dest_block = cfg_blocks_get ();
205           simulate_block (dest_block);
206         }
207
208       /* In order to move things to varying as quickly as
209          possible,process the VARYING_SSA_EDGES worklist first.  */
210       process_ssa_edge_worklist (&varying_ssa_edges);
211
212       /* Now process the SSA_EDGES worklist.  */
213       process_ssa_edge_worklist (&ssa_edges);
214     }
215
216   /* Now perform substitutions based on the known constant values.  */
217   substitute_and_fold ();
218
219   /* Now cleanup any unreachable code.  */
220   cleanup_tree_cfg ();
221
222   /* Free allocated memory.  */
223   finalize ();
224
225   /* Debugging dumps.  */
226   if (dump_file && (dump_flags & TDF_DETAILS))
227     {
228       dump_referenced_vars (dump_file);
229       fprintf (dump_file, "\n\n");
230     }
231 }
232
233 static bool
234 gate_ccp (void)
235 {
236   return flag_tree_ccp != 0;
237 }
238
239 struct tree_opt_pass pass_ccp = 
240 {
241   "ccp",                                /* name */
242   gate_ccp,                             /* gate */
243   tree_ssa_ccp,                         /* execute */
244   NULL,                                 /* sub */
245   NULL,                                 /* next */
246   0,                                    /* static_pass_number */
247   TV_TREE_CCP,                          /* tv_id */
248   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
249   0,                                    /* properties_provided */
250   0,                                    /* properties_destroyed */
251   0,                                    /* todo_flags_start */
252   TODO_dump_func | TODO_rename_vars
253     | TODO_ggc_collect | TODO_verify_ssa
254     | TODO_verify_stmts                 /* todo_flags_finish */
255 };
256
257
258 /* Get the constant value associated with variable VAR.  */
259
260 static value *
261 get_value (tree var)
262 {
263   value *val;
264
265 #if defined ENABLE_CHECKING
266   if (TREE_CODE (var) != SSA_NAME)
267     abort ();
268 #endif
269
270   val = &value_vector[SSA_NAME_VERSION (var)];
271   if (val->lattice_val == UNINITIALIZED)
272     *val = get_default_value (var);
273
274   return val;
275 }
276
277
278 /* Simulate the execution of BLOCK.  Evaluate the statement associated
279    with each variable reference inside the block.  */
280
281 static void
282 simulate_block (basic_block block)
283 {
284   tree phi;
285
286   /* There is nothing to do for the exit block.  */
287   if (block == EXIT_BLOCK_PTR)
288     return;
289
290   if (dump_file && (dump_flags & TDF_DETAILS))
291     fprintf (dump_file, "\nSimulating block %d\n", block->index);
292
293   /* Always simulate PHI nodes, even if we have simulated this block
294      before.  */
295   for (phi = phi_nodes (block); phi; phi = PHI_CHAIN (phi))
296     visit_phi_node (phi);
297
298   /* If this is the first time we've simulated this block, then we
299      must simulate each of its statements.  */
300   if (!TEST_BIT (executable_blocks, block->index))
301     {
302       block_stmt_iterator j;
303       unsigned int normal_edge_count;
304       edge e, normal_edge;
305
306       /* Note that we have simulated this block.  */
307       SET_BIT (executable_blocks, block->index);
308
309       for (j = bsi_start (block); !bsi_end_p (j); bsi_next (&j))
310         visit_stmt (bsi_stmt (j));
311
312       /* We can not predict when abnormal edges will be executed, so
313          once a block is considered executable, we consider any
314          outgoing abnormal edges as executable.
315
316          At the same time, if this block has only one successor that is
317          reached by non-abnormal edges, then add that successor to the
318          worklist.  */
319       normal_edge_count = 0;
320       normal_edge = NULL;
321       for (e = block->succ; e; e = e->succ_next)
322         {
323           if (e->flags & EDGE_ABNORMAL)
324             {
325               add_control_edge (e);
326             }
327           else
328             {
329               normal_edge_count++;
330               normal_edge = e;
331             }
332         }
333
334         if (normal_edge_count == 1)
335           add_control_edge (normal_edge);
336     }
337 }
338
339
340 /* Follow the def-use edges for statement DEF_STMT and simulate all the
341    statements reached by it.  */
342
343 static void
344 simulate_stmt (tree use_stmt)
345 {
346   basic_block use_bb = bb_for_stmt (use_stmt);
347
348   if (dump_file && (dump_flags & TDF_DETAILS))
349     {
350       fprintf (dump_file, "\nSimulating statement (from ssa_edges): ");
351       print_generic_stmt (dump_file, use_stmt, dump_flags);
352     }
353
354   if (TREE_CODE (use_stmt) == PHI_NODE)
355     {
356       /* PHI nodes are always visited, regardless of whether or not the
357          destination block is executable.  */
358       visit_phi_node (use_stmt);
359     }
360   else if (TEST_BIT (executable_blocks, use_bb->index))
361     {
362       /* Otherwise, visit the statement containing the use reached by
363          DEF, only if the destination block is marked executable.  */
364       visit_stmt (use_stmt);
365     }
366 }
367
368
369 /* Perform final substitution and folding.  After this pass the program
370    should still be in SSA form.  */
371
372 static void
373 substitute_and_fold (void)
374 {
375   basic_block bb;
376
377   if (dump_file && (dump_flags & TDF_DETAILS))
378     fprintf (dump_file,
379              "\nSubstituing constants and folding statements\n\n");
380
381   /* Substitute constants in every statement of every basic block.  */
382   FOR_EACH_BB (bb)
383     {
384       block_stmt_iterator i;
385       tree phi;
386
387       /* Propagate our known constants into PHI nodes.  */
388       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
389         {
390           int i;
391
392           for (i = 0; i < PHI_NUM_ARGS (phi); i++)
393             {
394               value *new_val;
395               use_operand_p orig_p = PHI_ARG_DEF_PTR (phi, i);
396               tree orig = USE_FROM_PTR (orig_p);
397
398               if (! SSA_VAR_P (orig))
399                 break;
400
401               new_val = get_value (orig);
402               if (new_val->lattice_val == CONSTANT
403                   && may_propagate_copy (orig, new_val->const_val))
404                 SET_USE (orig_p, new_val->const_val);
405             }
406         }
407
408       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
409         {
410           bool replaced_address;
411           tree stmt = bsi_stmt (i);
412
413           /* Skip statements that have been folded already.  */
414           if (stmt_modified_p (stmt) || !is_exec_stmt (stmt))
415             continue;
416
417           /* Replace the statement with its folded version and mark it
418              folded.  */
419           if (dump_file && (dump_flags & TDF_DETAILS))
420             {
421               fprintf (dump_file, "Line %d: replaced ", get_lineno (stmt));
422               print_generic_stmt (dump_file, stmt, TDF_SLIM);
423             }
424
425           if (replace_uses_in (stmt, &replaced_address)
426               || replace_vuse_in (stmt, &replaced_address))
427             {
428               bool changed = fold_stmt (bsi_stmt_ptr (i));
429               stmt = bsi_stmt(i);
430               modify_stmt (stmt);
431               /* If we folded a builtin function, we'll likely
432                  need to rename VDEFs.  */
433               if (replaced_address || changed)
434                 {
435                   mark_new_vars_to_rename (stmt, vars_to_rename);
436                   if (maybe_clean_eh_stmt (stmt))
437                     tree_purge_dead_eh_edges (bb);
438                 }
439             }
440
441           if (dump_file && (dump_flags & TDF_DETAILS))
442             {
443               fprintf (dump_file, " with ");
444               print_generic_stmt (dump_file, stmt, TDF_SLIM);
445               fprintf (dump_file, "\n");
446             }
447         }
448     }
449 }
450
451
452 /* Loop through the PHI_NODE's parameters for BLOCK and compare their
453    lattice values to determine PHI_NODE's lattice value.  The value of a
454    PHI node is determined calling cp_lattice_meet() with all the arguments
455    of the PHI node that are incoming via executable edges.  */
456
457 static void
458 visit_phi_node (tree phi)
459 {
460   bool short_circuit = 0;
461   value phi_val, *curr_val;
462   int i;
463
464   /* If the PHI node has already been deemed to be VARYING, don't simulate
465      it again.  */
466   if (DONT_SIMULATE_AGAIN (phi))
467     return;
468
469   if (dump_file && (dump_flags & TDF_DETAILS))
470     {
471       fprintf (dump_file, "\nVisiting PHI node: ");
472       print_generic_expr (dump_file, phi, dump_flags);
473     }
474
475   curr_val = get_value (PHI_RESULT (phi));
476   switch (curr_val->lattice_val)
477     {
478     case VARYING:
479       if (dump_file && (dump_flags & TDF_DETAILS))
480         fprintf (dump_file, "\n   Shortcircuit. Default of VARYING.");
481       short_circuit = 1;
482       break;
483
484     case CONSTANT:
485       phi_val = *curr_val;
486       break;
487
488     case UNKNOWN_VAL:
489       /* To avoid the default value of UNKNOWN_VAL overriding
490          that of its possible constant arguments, temporarily
491          set the phi node's default lattice value to be 
492          UNDEFINED. At the same time, place something other
493          than NULL_TREE in phi_val.const_val as a flag to
494          check when setting a new state for this phi node to
495          ensure that we avoid incorrect state transitions from
496          UNKNOWN_VAL to UNDEFINED. */
497       phi_val.lattice_val = UNDEFINED;
498       phi_val.const_val = phi;
499       break;
500
501     case UNDEFINED:
502     case UNINITIALIZED:
503       phi_val.lattice_val = UNDEFINED;
504       phi_val.const_val = NULL_TREE;
505       break;
506
507     default:
508       abort ();
509     }
510
511   /* If the variable is volatile or the variable is never referenced in a
512      real operand, then consider the PHI node VARYING.  */
513   if (short_circuit || TREE_THIS_VOLATILE (SSA_NAME_VAR (PHI_RESULT (phi))))
514     {
515       phi_val.lattice_val = VARYING;
516       phi_val.const_val = NULL;
517     }
518   else
519     for (i = 0; i < PHI_NUM_ARGS (phi); i++)
520       {
521         /* Compute the meet operator over all the PHI arguments.  */
522         edge e = PHI_ARG_EDGE (phi, i);
523
524         if (dump_file && (dump_flags & TDF_DETAILS))
525           {
526             fprintf (dump_file,
527                      "\n    Argument #%d (%d -> %d %sexecutable)\n",
528                      i, e->src->index, e->dest->index,
529                      (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
530           }
531
532         /* If the incoming edge is executable, Compute the meet operator for
533            the existing value of the PHI node and the current PHI argument.  */
534         if (e->flags & EDGE_EXECUTABLE)
535           {
536             tree rdef = PHI_ARG_DEF (phi, i);
537             value *rdef_val, val;
538
539             if (is_gimple_min_invariant (rdef))
540               {
541                 val.lattice_val = CONSTANT;
542                 val.const_val = rdef;
543                 rdef_val = &val;
544               }
545             else
546               rdef_val = get_value (rdef);
547
548             phi_val = cp_lattice_meet (phi_val, *rdef_val);
549
550             if (dump_file && (dump_flags & TDF_DETAILS))
551               {
552                 fprintf (dump_file, "\t");
553                 print_generic_expr (dump_file, rdef, dump_flags);
554                 dump_lattice_value (dump_file, "\tValue: ", *rdef_val);
555                 fprintf (dump_file, "\n");
556               }
557
558             if (phi_val.lattice_val == VARYING)
559               break;
560           }
561       }
562
563   if (dump_file && (dump_flags & TDF_DETAILS))
564     {
565       dump_lattice_value (dump_file, "\n    PHI node value: ", phi_val);
566       fprintf (dump_file, "\n\n");
567     }
568
569   /* Check for an invalid change from UNKNOWN_VAL to UNDEFINED. */
570   if (phi_val.lattice_val != UNDEFINED || phi_val.const_val == NULL_TREE)
571     {
572       set_lattice_value (PHI_RESULT (phi), phi_val);
573       if (phi_val.lattice_val == VARYING)
574         DONT_SIMULATE_AGAIN (phi) = 1;
575     }
576 }
577
578
579 /* Compute the meet operator between VAL1 and VAL2:
580
581                 any  M UNDEFINED     = any
582                 any  M VARYING       = VARYING
583                 any  M UNKNOWN_VAL   = UNKNOWN_VAL
584                 Ci   M Cj            = Ci       if (i == j)
585                 Ci   M Cj            = VARYING  if (i != j)  */
586 static value
587 cp_lattice_meet (value val1, value val2)
588 {
589   value result;
590
591   /* any M UNDEFINED = any.  */
592   if (val1.lattice_val == UNDEFINED)
593     return val2;
594   else if (val2.lattice_val == UNDEFINED)
595     return val1;
596
597   /* any M VARYING = VARYING.  */
598   if (val1.lattice_val == VARYING || val2.lattice_val == VARYING)
599     {
600       result.lattice_val = VARYING;
601       result.const_val = NULL_TREE;
602       return result;
603     }
604
605   /* any M UNKNOWN_VAL = UNKNOWN_VAL.  */
606   if (val1.lattice_val == UNKNOWN_VAL 
607       || val2.lattice_val == UNKNOWN_VAL)
608     {
609       result.lattice_val = UNKNOWN_VAL;
610       result.const_val = NULL_TREE;
611       return result;
612     }
613
614   /* Ci M Cj = Ci       if (i == j)
615      Ci M Cj = VARYING  if (i != j)  */
616   if (simple_cst_equal (val1.const_val, val2.const_val) == 1)
617     {
618       result.lattice_val = CONSTANT;
619       result.const_val = val1.const_val;
620     }
621   else
622     {
623       result.lattice_val = VARYING;
624       result.const_val = NULL_TREE;
625     }
626
627   return result;
628 }
629
630
631 /* Evaluate statement STMT.  If the statement produces an output value and
632    its evaluation changes the lattice value of its output, do the following:
633
634    - If the statement is an assignment, add all the SSA edges starting at
635      this definition.
636
637    - If the statement is a conditional branch:
638         . If the statement evaluates to non-constant, add all edges to
639           worklist.
640         . If the statement is constant, add the edge executed as the
641           result of the branch.  */
642
643 static void
644 visit_stmt (tree stmt)
645 {
646   size_t i;
647   stmt_ann_t ann;
648   def_optype defs;
649   v_may_def_optype v_may_defs;
650   v_must_def_optype v_must_defs;
651
652   /* If the statement has already been deemed to be VARYING, don't simulate
653      it again.  */
654   if (DONT_SIMULATE_AGAIN (stmt))
655     return;
656
657   if (dump_file && (dump_flags & TDF_DETAILS))
658     {
659       fprintf (dump_file, "\nVisiting statement: ");
660       print_generic_stmt (dump_file, stmt, TDF_SLIM);
661       fprintf (dump_file, "\n");
662     }
663
664   ann = stmt_ann (stmt);
665
666   /* If this statement is already in the worklist then "cancel" it.  The
667      reevaluation implied by the worklist entry will produce the same
668      value we generate here and thus reevaluating it again from the
669      worklist is pointless.  */
670   if (ann->in_ccp_worklist)
671     ann->in_ccp_worklist = 0;
672
673   /* Now examine the statement.  If the statement is an assignment that
674      produces a single output value, evaluate its RHS to see if the lattice
675      value of its output has changed.  */
676   v_must_defs = V_MUST_DEF_OPS (ann);
677   v_may_defs = V_MAY_DEF_OPS (ann);
678   if (TREE_CODE (stmt) == MODIFY_EXPR
679       && NUM_V_MAY_DEFS (v_may_defs) == 0
680       && (NUM_V_MUST_DEFS (v_must_defs) == 1
681           || TREE_CODE (TREE_OPERAND (stmt, 0)) == SSA_NAME))
682     visit_assignment (stmt);
683
684   /* Definitions made by statements other than assignments to SSA_NAMEs
685      represent unknown modifications to their outputs.  Mark them VARYING.  */
686   else if (NUM_DEFS (defs = DEF_OPS (ann)) != 0)
687     {
688       DONT_SIMULATE_AGAIN (stmt) = 1;
689       for (i = 0; i < NUM_DEFS (defs); i++)
690         {
691           tree def = DEF_OP (defs, i);
692           def_to_varying (def);
693         }
694     }
695
696   /* If STMT is a conditional branch, see if we can determine which branch
697      will be taken.  */
698   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
699     visit_cond_stmt (stmt);
700
701   /* Any other kind of statement is not interesting for constant
702      propagation and, therefore, not worth simulating.  */
703   else
704     {
705       DONT_SIMULATE_AGAIN (stmt) = 1;
706
707       /* If STMT is a computed goto, then mark all the output edges
708          executable.  */
709       if (computed_goto_p (stmt))
710         add_outgoing_control_edges (bb_for_stmt (stmt));
711     }
712
713   /* Mark all V_MAY_DEF operands VARYING.  */
714   v_may_defs = V_MAY_DEF_OPS (ann);
715   for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
716     def_to_varying (V_MAY_DEF_RESULT (v_may_defs, i));
717     
718 }
719
720
721 /* Visit the assignment statement STMT.  Set the value of its LHS to the
722    value computed by the RHS.  */
723
724 static void
725 visit_assignment (tree stmt)
726 {
727   value val;
728   tree lhs, rhs;
729   vuse_optype vuses;
730   v_must_def_optype v_must_defs;
731
732   lhs = TREE_OPERAND (stmt, 0);
733   rhs = TREE_OPERAND (stmt, 1);
734   vuses = STMT_VUSE_OPS (stmt);
735   v_must_defs = STMT_V_MUST_DEF_OPS (stmt);
736
737 #if defined ENABLE_CHECKING
738   if (NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt)) > 0
739       || (NUM_V_MUST_DEFS (v_must_defs) != 1
740           && TREE_CODE (lhs) != SSA_NAME))
741     abort ();
742 #endif
743
744   /* We require the SSA version number of the lhs for the value_vector.
745      Make sure we have it.  */
746   if (TREE_CODE (lhs) != SSA_NAME)
747     {
748       /* If we make it here, then stmt only has one definition:
749          a V_MUST_DEF.  */
750       lhs = V_MUST_DEF_OP (v_must_defs, 0);
751     }
752
753   if (TREE_CODE (rhs) == SSA_NAME)
754     {
755       /* For a simple copy operation, we copy the lattice values.  */
756       value *nval = get_value (rhs);
757       val = *nval;
758     }
759   else if (DECL_P (rhs) 
760            && NUM_VUSES (vuses) == 1
761            && rhs == SSA_NAME_VAR (VUSE_OP (vuses, 0)))
762     {
763       /* Same as above, but the rhs is not a gimple register and yet
764         has a known VUSE.  */
765       value *nval = get_value (VUSE_OP (vuses, 0));
766       val = *nval;
767     }
768   else
769     {
770       /* Evaluate the statement.  */
771       val = evaluate_stmt (stmt);
772     }
773
774   /* FIXME: Hack.  If this was a definition of a bitfield, we need to widen
775      the constant value into the type of the destination variable.  This
776      should not be necessary if GCC represented bitfields properly.  */
777   {
778     tree lhs = TREE_OPERAND (stmt, 0);
779     if (val.lattice_val == CONSTANT
780         && TREE_CODE (lhs) == COMPONENT_REF
781         && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
782       {
783         tree w = widen_bitfield (val.const_val, TREE_OPERAND (lhs, 1), lhs);
784
785         if (w && is_gimple_min_invariant (w))
786           val.const_val = w;
787         else
788           {
789             val.lattice_val = VARYING;
790             val.const_val = NULL;
791           }
792       }
793   }
794
795   /* If LHS is not a gimple register, then it cannot take on an
796      UNDEFINED value. */
797   if (!is_gimple_reg (SSA_NAME_VAR (lhs)) 
798       && val.lattice_val == UNDEFINED)
799     val.lattice_val = UNKNOWN_VAL;      
800
801   /* Set the lattice value of the statement's output.  */
802   set_lattice_value (lhs, val);
803   if (val.lattice_val == VARYING)
804     DONT_SIMULATE_AGAIN (stmt) = 1;
805 }
806
807
808 /* Visit the conditional statement STMT.  If it evaluates to a constant value,
809    mark outgoing edges appropriately.  */
810
811 static void
812 visit_cond_stmt (tree stmt)
813 {
814   edge e;
815   value val;
816   basic_block block;
817
818   block = bb_for_stmt (stmt);
819   val = evaluate_stmt (stmt);
820
821   /* Find which edge out of the conditional block will be taken and add it
822      to the worklist.  If no single edge can be determined statically, add
823      all outgoing edges from BLOCK.  */
824   e = find_taken_edge (block, val.const_val);
825   if (e)
826     add_control_edge (e);
827   else
828     {
829       DONT_SIMULATE_AGAIN (stmt) = 1;
830       add_outgoing_control_edges (block);
831     }
832 }
833
834
835 /* Add all the edges coming out of BB to the control flow worklist.  */
836
837 static void
838 add_outgoing_control_edges (basic_block bb)
839 {
840   edge e;
841
842   for (e = bb->succ; e; e = e->succ_next)
843     add_control_edge (e);
844 }
845
846
847 /* Add edge E to the control flow worklist.  */
848
849 static void
850 add_control_edge (edge e)
851 {
852   basic_block bb = e->dest;
853   if (bb == EXIT_BLOCK_PTR)
854     return;
855
856   /* If the edge had already been executed, skip it.  */
857   if (e->flags & EDGE_EXECUTABLE)
858       return;
859
860   e->flags |= EDGE_EXECUTABLE;
861
862   /* If the block is already in the list, we're done.  */
863   if (TEST_BIT (bb_in_list, bb->index))
864     return;
865
866   cfg_blocks_add (bb);
867
868   if (dump_file && (dump_flags & TDF_DETAILS))
869     fprintf (dump_file, "Adding Destination of edge (%d -> %d) to worklist\n\n",
870              e->src->index, e->dest->index);
871 }
872
873
874 /* CCP specific front-end to the non-destructive constant folding routines.
875
876    Attempt to simplify the RHS of STMT knowing that one or more
877    operands are constants.
878
879    If simplification is possible, return the simplified RHS,
880    otherwise return the original RHS.  */
881
882 static tree
883 ccp_fold (tree stmt)
884 {
885   tree rhs = get_rhs (stmt);
886   enum tree_code code = TREE_CODE (rhs);
887   int kind = TREE_CODE_CLASS (code);
888   tree retval = NULL_TREE;
889   vuse_optype vuses;
890   
891   vuses = STMT_VUSE_OPS (stmt);
892
893   /* If the RHS is just a variable, then that variable must now have
894      a constant value that we can return directly.  */
895   if (TREE_CODE (rhs) == SSA_NAME)
896     return get_value (rhs)->const_val;
897   else if (DECL_P (rhs) 
898            && NUM_VUSES (vuses) == 1
899            && rhs == SSA_NAME_VAR (VUSE_OP (vuses, 0)))
900     return get_value (VUSE_OP (vuses, 0))->const_val;
901
902   /* Unary operators.  Note that we know the single operand must
903      be a constant.  So this should almost always return a
904      simplified RHS.  */
905   if (kind == '1')
906     {
907       /* Handle unary operators which can appear in GIMPLE form.  */
908       tree op0 = TREE_OPERAND (rhs, 0);
909
910       /* Simplify the operand down to a constant.  */
911       if (TREE_CODE (op0) == SSA_NAME)
912         {
913           value *val = get_value (op0);
914           if (val->lattice_val == CONSTANT)
915             op0 = get_value (op0)->const_val;
916         }
917
918       retval = nondestructive_fold_unary_to_constant (code,
919                                                       TREE_TYPE (rhs),
920                                                       op0);
921
922       /* If we folded, but did not create an invariant, then we can not
923          use this expression.  */
924       if (retval && ! is_gimple_min_invariant (retval))
925         return NULL;
926
927       /* If we could not fold the expression, but the arguments are all
928          constants and gimple values, then build and return the new
929          expression. 
930
931          In some cases the new expression is still something we can
932          use as a replacement for an argument.  This happens with
933          NOP conversions of types for example.
934
935          In other cases the new expression can not be used as a
936          replacement for an argument (as it would create non-gimple
937          code).  But the new expression can still be used to derive
938          other constants.  */
939       if (! retval && is_gimple_min_invariant (op0))
940         return build1 (code, TREE_TYPE (rhs), op0);
941     }
942
943   /* Binary and comparison operators.  We know one or both of the
944      operands are constants.  */
945   else if (kind == '2'
946            || kind == '<'
947            || code == TRUTH_AND_EXPR
948            || code == TRUTH_OR_EXPR
949            || code == TRUTH_XOR_EXPR)
950     {
951       /* Handle binary and comparison operators that can appear in
952          GIMPLE form.  */
953       tree op0 = TREE_OPERAND (rhs, 0);
954       tree op1 = TREE_OPERAND (rhs, 1);
955
956       /* Simplify the operands down to constants when appropriate.  */
957       if (TREE_CODE (op0) == SSA_NAME)
958         {
959           value *val = get_value (op0);
960           if (val->lattice_val == CONSTANT)
961             op0 = val->const_val;
962         }
963
964       if (TREE_CODE (op1) == SSA_NAME)
965         {
966           value *val = get_value (op1);
967           if (val->lattice_val == CONSTANT)
968             op1 = val->const_val;
969         }
970
971       retval = nondestructive_fold_binary_to_constant (code,
972                                                        TREE_TYPE (rhs),
973                                                        op0, op1);
974
975       /* If we folded, but did not create an invariant, then we can not
976          use this expression.  */
977       if (retval && ! is_gimple_min_invariant (retval))
978         return NULL;
979       
980       /* If we could not fold the expression, but the arguments are all
981          constants and gimple values, then build and return the new
982          expression. 
983
984          In some cases the new expression is still something we can
985          use as a replacement for an argument.  This happens with
986          NOP conversions of types for example.
987
988          In other cases the new expression can not be used as a
989          replacement for an argument (as it would create non-gimple
990          code).  But the new expression can still be used to derive
991          other constants.  */
992       if (! retval
993           && is_gimple_min_invariant (op0)
994           && is_gimple_min_invariant (op1))
995         return build (code, TREE_TYPE (rhs), op0, op1);
996     }
997
998   /* We may be able to fold away calls to builtin functions if their
999      arguments are constants.  */
1000   else if (code == CALL_EXPR
1001            && TREE_CODE (TREE_OPERAND (rhs, 0)) == ADDR_EXPR
1002            && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0))
1003                == FUNCTION_DECL)
1004            && DECL_BUILT_IN (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0)))
1005     {
1006       use_optype uses = STMT_USE_OPS (stmt);
1007       if (NUM_USES (uses) != 0)
1008         {
1009           tree *orig;
1010           size_t i;
1011
1012           /* Preserve the original values of every operand.  */
1013           orig = xmalloc (sizeof (tree) * NUM_USES (uses));
1014           for (i = 0; i < NUM_USES (uses); i++)
1015             orig[i] = USE_OP (uses, i);
1016
1017           /* Substitute operands with their values and try to fold.  */
1018           replace_uses_in (stmt, NULL);
1019           retval = fold_builtin (rhs, false);
1020
1021           /* Restore operands to their original form.  */
1022           for (i = 0; i < NUM_USES (uses); i++)
1023             SET_USE_OP (uses, i, orig[i]);
1024           free (orig);
1025         }
1026     }
1027   else
1028     return rhs;
1029
1030   /* If we got a simplified form, see if we need to convert its type.  */
1031   if (retval)
1032     return fold_convert (TREE_TYPE (rhs), retval);
1033
1034   /* No simplification was possible.  */
1035   return rhs;
1036 }
1037
1038
1039 /* Evaluate statement STMT.  */
1040
1041 static value
1042 evaluate_stmt (tree stmt)
1043 {
1044   value val;
1045   tree simplified;
1046   latticevalue likelyvalue = likely_value (stmt);
1047
1048   /* If the statement is likely to have a CONSTANT result, then try
1049      to fold the statement to determine the constant value.  */
1050   if (likelyvalue == CONSTANT)
1051     simplified = ccp_fold (stmt);
1052   /* If the statement is likely to have a VARYING result, then do not
1053      bother folding the statement.  */
1054   else if (likelyvalue == VARYING)
1055     simplified = get_rhs (stmt);
1056   /* Otherwise the statement is likely to have an UNDEFINED value and
1057      there will be nothing to do.  */
1058   else
1059     simplified = NULL_TREE;
1060
1061   if (simplified && is_gimple_min_invariant (simplified))
1062     {
1063       /* The statement produced a constant value.  */
1064       val.lattice_val = CONSTANT;
1065       val.const_val = simplified;
1066     }
1067   else
1068     {
1069       /* The statement produced a nonconstant value.  If the statement
1070          had undefined or virtual operands, then the result of the 
1071          statement should be undefined or virtual respectively.  
1072          Else the result of the statement is VARYING.  */
1073       val.lattice_val = (likelyvalue == UNDEFINED ? UNDEFINED : VARYING);
1074       val.lattice_val = (likelyvalue == UNKNOWN_VAL 
1075                            ? UNKNOWN_VAL : val.lattice_val);
1076       val.const_val = NULL_TREE;
1077     }
1078
1079   return val;
1080 }
1081
1082
1083 /* Debugging dumps.  */
1084
1085 static void
1086 dump_lattice_value (FILE *outf, const char *prefix, value val)
1087 {
1088   switch (val.lattice_val)
1089     {
1090     case UNDEFINED:
1091       fprintf (outf, "%sUNDEFINED", prefix);
1092       break;
1093     case VARYING:
1094       fprintf (outf, "%sVARYING", prefix);
1095       break;
1096     case UNKNOWN_VAL:
1097       fprintf (outf, "%sUNKNOWN_VAL", prefix);
1098       break;
1099     case CONSTANT:
1100       fprintf (outf, "%sCONSTANT ", prefix);
1101       print_generic_expr (outf, val.const_val, dump_flags);
1102       break;
1103     default:
1104       abort ();
1105     }
1106 }
1107
1108 /* Given a constant value VAL for bitfield FIELD, and a destination
1109    variable VAR, return VAL appropriately widened to fit into VAR.  If
1110    FIELD is wider than HOST_WIDE_INT, NULL is returned.  */
1111
1112 tree
1113 widen_bitfield (tree val, tree field, tree var)
1114 {
1115   unsigned HOST_WIDE_INT var_size, field_size;
1116   tree wide_val;
1117   unsigned HOST_WIDE_INT mask;
1118   unsigned int i;
1119
1120   /* We can only do this if the size of the type and field and VAL are
1121      all constants representable in HOST_WIDE_INT.  */
1122   if (!host_integerp (TYPE_SIZE (TREE_TYPE (var)), 1)
1123       || !host_integerp (DECL_SIZE (field), 1)
1124       || !host_integerp (val, 0))
1125     return NULL_TREE;
1126
1127   var_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1);
1128   field_size = tree_low_cst (DECL_SIZE (field), 1);
1129
1130   /* Give up if either the bitfield or the variable are too wide.  */
1131   if (field_size > HOST_BITS_PER_WIDE_INT || var_size > HOST_BITS_PER_WIDE_INT)
1132     return NULL_TREE;
1133
1134 #if defined ENABLE_CHECKING
1135   if (var_size < field_size)
1136     abort ();
1137 #endif
1138
1139   /* If the sign bit of the value is not set or the field's type is unsigned,
1140      just mask off the high order bits of the value.  */
1141   if (DECL_UNSIGNED (field)
1142       || !(tree_low_cst (val, 0) & (((HOST_WIDE_INT)1) << (field_size - 1))))
1143     {
1144       /* Zero extension.  Build a mask with the lower 'field_size' bits
1145          set and a BIT_AND_EXPR node to clear the high order bits of
1146          the value.  */
1147       for (i = 0, mask = 0; i < field_size; i++)
1148         mask |= ((HOST_WIDE_INT) 1) << i;
1149
1150       wide_val = build (BIT_AND_EXPR, TREE_TYPE (var), val, 
1151                         fold_convert (TREE_TYPE (var), build_int_2 (mask, 0)));
1152     }
1153   else
1154     {
1155       /* Sign extension.  Create a mask with the upper 'field_size'
1156          bits set and a BIT_IOR_EXPR to set the high order bits of the
1157          value.  */
1158       for (i = 0, mask = 0; i < (var_size - field_size); i++)
1159         mask |= ((HOST_WIDE_INT) 1) << (var_size - i - 1);
1160
1161       wide_val = build (BIT_IOR_EXPR, TREE_TYPE (var), val,
1162                         fold_convert (TREE_TYPE (var), build_int_2 (mask, 0)));
1163     }
1164
1165   return fold (wide_val);
1166 }
1167
1168
1169 /* Function indicating whether we ought to include information for 'var'
1170    when calculating immediate uses.  */
1171
1172 static bool
1173 need_imm_uses_for (tree var)
1174 {
1175   return get_value (var)->lattice_val != VARYING;
1176 }
1177
1178
1179 /* Initialize local data structures and worklists for CCP.  */
1180
1181 static void
1182 initialize (void)
1183 {
1184   edge e;
1185   basic_block bb;
1186   sbitmap virtual_var;
1187
1188   /* Worklists of SSA edges.  */
1189   VARRAY_TREE_INIT (ssa_edges, 20, "ssa_edges");
1190   VARRAY_TREE_INIT (varying_ssa_edges, 20, "varying_ssa_edges");
1191
1192   executable_blocks = sbitmap_alloc (last_basic_block);
1193   sbitmap_zero (executable_blocks);
1194
1195   bb_in_list = sbitmap_alloc (last_basic_block);
1196   sbitmap_zero (bb_in_list);
1197
1198   value_vector = (value *) xmalloc (num_ssa_names * sizeof (value));
1199   memset (value_vector, 0, num_ssa_names * sizeof (value));
1200
1201   /* 1 if ssa variable is used in a virtual variable context.  */
1202   virtual_var = sbitmap_alloc (num_ssa_names);
1203   sbitmap_zero (virtual_var);
1204
1205   /* Initialize default values and simulation flags for PHI nodes, statements 
1206      and edges.  */
1207   FOR_EACH_BB (bb)
1208     {
1209       block_stmt_iterator i;
1210       tree stmt;
1211       stmt_ann_t ann;
1212       def_optype defs;
1213       v_may_def_optype v_may_defs;
1214       v_must_def_optype v_must_defs;
1215       size_t x;
1216       int vary;
1217
1218       /* Get the default value for each definition.  */
1219       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
1220         {
1221           vary = 0;
1222           stmt = bsi_stmt (i);
1223           get_stmt_operands (stmt);
1224           ann = stmt_ann (stmt);
1225           defs = DEF_OPS (ann);
1226           for (x = 0; x < NUM_DEFS (defs); x++)
1227             {
1228               tree def = DEF_OP (defs, x);
1229               if (get_value (def)->lattice_val == VARYING)
1230                 vary = 1;
1231             }
1232           
1233           /* Get the default value for each V_MUST_DEF.  */
1234           v_must_defs = V_MUST_DEF_OPS (ann);
1235           for (x = 0; x < NUM_V_MUST_DEFS (v_must_defs); x++)
1236             {
1237               tree v_must_def = V_MUST_DEF_OP (v_must_defs, x);
1238               if (get_value (v_must_def)->lattice_val == VARYING)
1239                 vary = 1;
1240             }
1241           
1242           DONT_SIMULATE_AGAIN (stmt) = vary;
1243
1244           /* Mark all V_MAY_DEF operands VARYING.  */
1245           v_may_defs = V_MAY_DEF_OPS (ann);
1246           for (x = 0; x < NUM_V_MAY_DEFS (v_may_defs); x++)
1247             {
1248               tree res = V_MAY_DEF_RESULT (v_may_defs, x);
1249               get_value (res)->lattice_val = VARYING;
1250               SET_BIT (virtual_var, SSA_NAME_VERSION (res));
1251             }
1252         }
1253
1254       for (e = bb->succ; e; e = e->succ_next)
1255         e->flags &= ~EDGE_EXECUTABLE;
1256     }
1257
1258   /* Now process PHI nodes.  */
1259   FOR_EACH_BB (bb)
1260     {
1261       tree phi, var;
1262       int x;
1263       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1264         {
1265           value *val;
1266           val = get_value (PHI_RESULT (phi));
1267           if (val->lattice_val != VARYING)
1268             {
1269               for (x = 0; x < PHI_NUM_ARGS (phi); x++)
1270                 {
1271                   var = PHI_ARG_DEF (phi, x);
1272                   /* If one argument has a V_MAY_DEF, 
1273                      the result is varying.  */
1274                   if (TREE_CODE (var) == SSA_NAME)
1275                     {
1276                       if (TEST_BIT (virtual_var, SSA_NAME_VERSION (var)))
1277                         {
1278                           val->lattice_val = VARYING;
1279                           SET_BIT (virtual_var, 
1280                                    SSA_NAME_VERSION (PHI_RESULT (phi)));
1281                           break;
1282                         }
1283                     }
1284         }
1285             }
1286           DONT_SIMULATE_AGAIN (phi) = ((val->lattice_val == VARYING) ? 1 : 0);
1287         }
1288     }
1289
1290   sbitmap_free (virtual_var);
1291   /* Compute immediate uses for variables we care about.  */
1292   compute_immediate_uses (TDFA_USE_OPS | TDFA_USE_VOPS, need_imm_uses_for);
1293
1294   if (dump_file && (dump_flags & TDF_DETAILS))
1295     dump_immediate_uses (dump_file);
1296
1297   VARRAY_BB_INIT (cfg_blocks, 20, "cfg_blocks");
1298
1299   /* Seed the algorithm by adding the successors of the entry block to the
1300      edge worklist.  */
1301   for (e = ENTRY_BLOCK_PTR->succ; e; e = e->succ_next)
1302     {
1303       if (e->dest != EXIT_BLOCK_PTR)
1304         {
1305           e->flags |= EDGE_EXECUTABLE;
1306           cfg_blocks_add (e->dest);
1307         }
1308     }
1309 }
1310
1311
1312 /* Free allocated storage.  */
1313
1314 static void
1315 finalize (void)
1316 {
1317   ssa_edges = NULL;
1318   varying_ssa_edges = NULL;
1319   cfg_blocks = NULL;
1320   free (value_vector);
1321   sbitmap_free (bb_in_list);
1322   sbitmap_free (executable_blocks);
1323   free_df ();
1324 }
1325
1326 /* Is the block worklist empty.  */
1327
1328 static inline bool
1329 cfg_blocks_empty_p (void)
1330 {
1331   return (cfg_blocks_num == 0);
1332 }
1333
1334 /* Add a basic block to the worklist.  */
1335
1336 static void 
1337 cfg_blocks_add (basic_block bb)
1338 {
1339    if (bb == ENTRY_BLOCK_PTR || bb == EXIT_BLOCK_PTR)
1340      return;
1341
1342    if (TEST_BIT (bb_in_list, bb->index))
1343      return;
1344
1345     if (cfg_blocks_empty_p ())
1346       {
1347         cfg_blocks_tail = cfg_blocks_head = 0;
1348         cfg_blocks_num = 1;
1349       }
1350     else
1351       {
1352         cfg_blocks_num++;
1353         if (cfg_blocks_num > VARRAY_SIZE (cfg_blocks))
1354           {
1355             /* We have to grow the array now.  Adjust to queue to occupy the
1356                full space of the original array.  */
1357             cfg_blocks_tail = VARRAY_SIZE (cfg_blocks);
1358             cfg_blocks_head = 0;
1359             VARRAY_GROW (cfg_blocks, 2 * VARRAY_SIZE (cfg_blocks));
1360           }
1361         else
1362           cfg_blocks_tail = (cfg_blocks_tail + 1) % VARRAY_SIZE (cfg_blocks);
1363       }
1364     VARRAY_BB (cfg_blocks, cfg_blocks_tail) = bb;
1365     SET_BIT (bb_in_list, bb->index);
1366 }
1367
1368 /* Remove a block from the worklist.  */
1369
1370 static basic_block
1371 cfg_blocks_get (void)
1372 {
1373   basic_block bb;
1374
1375   bb = VARRAY_BB (cfg_blocks, cfg_blocks_head);
1376
1377 #ifdef ENABLE_CHECKING
1378   if (cfg_blocks_empty_p () || !bb)
1379     abort ();
1380 #endif
1381
1382   cfg_blocks_head = (cfg_blocks_head + 1) % VARRAY_SIZE (cfg_blocks);
1383   --cfg_blocks_num;
1384   RESET_BIT (bb_in_list, bb->index);
1385
1386   return bb;
1387 }
1388
1389 /* We have just defined a new value for VAR.  Add all immediate uses
1390    of VAR to the ssa_edges or varying_ssa_edges worklist.  */
1391 static void
1392 add_var_to_ssa_edges_worklist (tree var, value val)
1393 {
1394   tree stmt = SSA_NAME_DEF_STMT (var);
1395   dataflow_t df = get_immediate_uses (stmt);
1396   int num_uses = num_immediate_uses (df);
1397   int i;
1398
1399   for (i = 0; i < num_uses; i++)
1400     {
1401       tree use = immediate_use (df, i);
1402
1403       if (!DONT_SIMULATE_AGAIN (use))
1404         {
1405           stmt_ann_t ann = stmt_ann (use);
1406           if (ann->in_ccp_worklist == 0)
1407             {
1408               ann->in_ccp_worklist = 1;
1409               if (val.lattice_val == VARYING)
1410                 VARRAY_PUSH_TREE (varying_ssa_edges, use);
1411               else
1412                 VARRAY_PUSH_TREE (ssa_edges, use);
1413             }
1414         }
1415     }
1416 }
1417
1418 /* Set the lattice value for the variable VAR to VARYING.  */
1419
1420 static void
1421 def_to_varying (tree var)
1422 {
1423   value val;
1424   val.lattice_val = VARYING;
1425   val.const_val = NULL_TREE;
1426   set_lattice_value (var, val);
1427 }
1428
1429 /* Set the lattice value for variable VAR to VAL.  */
1430
1431 static void
1432 set_lattice_value (tree var, value val)
1433 {
1434   value *old = get_value (var);
1435
1436 #ifdef ENABLE_CHECKING
1437   if (val.lattice_val == UNDEFINED)
1438     {
1439       /* CONSTANT->UNDEFINED is never a valid state transition.  */
1440       if (old->lattice_val == CONSTANT)
1441         abort ();
1442         
1443       /* UNKNOWN_VAL->UNDEFINED is never a valid state transition.  */
1444       if (old->lattice_val == UNKNOWN_VAL)
1445         abort ();
1446
1447       /* VARYING->UNDEFINED is generally not a valid state transition,
1448          except for values which are initialized to VARYING.  */
1449       if (old->lattice_val == VARYING
1450           && get_default_value (var).lattice_val != VARYING)
1451         abort ();
1452     }
1453   else if (val.lattice_val == CONSTANT)
1454     {
1455       /* VARYING -> CONSTANT is an invalid state transition, except
1456          for objects which start off in a VARYING state.  */
1457       if (old->lattice_val == VARYING
1458           && get_default_value (var).lattice_val != VARYING)
1459         abort ();
1460     }
1461 #endif
1462
1463   /* If the constant for VAR has changed, then this VAR is really varying.  */
1464   if (old->lattice_val == CONSTANT && val.lattice_val == CONSTANT
1465       && !simple_cst_equal (old->const_val, val.const_val))
1466     {
1467       val.lattice_val = VARYING;
1468       val.const_val = NULL_TREE;
1469     }
1470
1471   if (old->lattice_val != val.lattice_val)
1472     {
1473       if (dump_file && (dump_flags & TDF_DETAILS))
1474         {
1475           dump_lattice_value (dump_file,
1476                               "Lattice value changed to ", val);
1477           fprintf (dump_file, ".  Adding definition to SSA edges.\n");
1478         }
1479
1480       add_var_to_ssa_edges_worklist (var, val);
1481       *old = val;
1482     }
1483 }
1484
1485 /* Replace USE references in statement STMT with their immediate reaching
1486    definition.  Return true if at least one reference was replaced.  If
1487    REPLACED_ADDRESSES_P is given, it will be set to true if an address
1488    constant was replaced.  */
1489
1490 static bool
1491 replace_uses_in (tree stmt, bool *replaced_addresses_p)
1492 {
1493   bool replaced = false;
1494   use_optype uses;
1495   size_t i;
1496
1497   if (replaced_addresses_p)
1498     *replaced_addresses_p = false;
1499
1500   get_stmt_operands (stmt);
1501
1502   uses = STMT_USE_OPS (stmt);
1503   for (i = 0; i < NUM_USES (uses); i++)
1504     {
1505       use_operand_p use = USE_OP_PTR (uses, i);
1506       value *val = get_value (USE_FROM_PTR (use));
1507
1508       if (val->lattice_val == CONSTANT)
1509         {
1510           SET_USE (use, val->const_val);
1511           replaced = true;
1512           if (POINTER_TYPE_P (TREE_TYPE (USE_FROM_PTR (use))) 
1513               && replaced_addresses_p)
1514             *replaced_addresses_p = true;
1515         }
1516     }
1517
1518   return replaced;
1519 }
1520
1521 /* Replace the VUSE references in statement STMT with its immediate reaching
1522    definition.  Return true if the reference was replaced.  If
1523    REPLACED_ADDRESSES_P is given, it will be set to true if an address
1524    constant was replaced.  */
1525
1526 static bool
1527 replace_vuse_in (tree stmt, bool *replaced_addresses_p)
1528 {
1529   bool replaced = false;
1530   vuse_optype vuses;
1531   use_operand_p vuse;
1532   value *val;
1533
1534   if (replaced_addresses_p)
1535     *replaced_addresses_p = false;
1536
1537   get_stmt_operands (stmt);
1538
1539   vuses = STMT_VUSE_OPS (stmt);
1540
1541   if (NUM_VUSES (vuses) != 1)
1542     return false;
1543
1544   vuse = VUSE_OP_PTR (vuses, 0);
1545   val = get_value (USE_FROM_PTR (vuse));
1546
1547   if (val->lattice_val == CONSTANT
1548       && TREE_CODE (stmt) == MODIFY_EXPR
1549       && DECL_P (TREE_OPERAND (stmt, 1))
1550       && TREE_OPERAND (stmt, 1) == SSA_NAME_VAR (USE_FROM_PTR (vuse)))
1551     {
1552       TREE_OPERAND (stmt, 1) = val->const_val;
1553       replaced = true;
1554       if (POINTER_TYPE_P (TREE_TYPE (USE_FROM_PTR (vuse))) 
1555           && replaced_addresses_p)
1556         *replaced_addresses_p = true;
1557     }
1558
1559   return replaced;
1560 }
1561
1562 /* Return the likely latticevalue for STMT.
1563
1564    If STMT has no operands, then return CONSTANT.
1565
1566    Else if any operands of STMT are undefined, then return UNDEFINED.
1567
1568    Else if any operands of STMT are constants, then return CONSTANT.
1569
1570    Else return VARYING.  */
1571
1572 static latticevalue
1573 likely_value (tree stmt)
1574 {
1575   use_optype uses;
1576   vuse_optype vuses;
1577   size_t i;
1578   int found_constant = 0;
1579   stmt_ann_t ann;
1580
1581   /* If the statement makes aliased loads or has volatile operands, it
1582      won't fold to a constant value.  */
1583   ann = stmt_ann (stmt);
1584   if (ann->makes_aliased_loads || ann->has_volatile_ops)
1585     return VARYING;
1586
1587   /* A CALL_EXPR is assumed to be varying.  This may be overly conservative,
1588      in the presence of const and pure calls.  */
1589   if (get_call_expr_in (stmt) != NULL_TREE)
1590     return VARYING;
1591
1592   get_stmt_operands (stmt);
1593
1594   uses = USE_OPS (ann);
1595   for (i = 0; i < NUM_USES (uses); i++)
1596     {
1597       tree use = USE_OP (uses, i);
1598       value *val = get_value (use);
1599
1600       if (val->lattice_val == UNDEFINED)
1601         return UNDEFINED;
1602
1603       if (val->lattice_val == CONSTANT)
1604         found_constant = 1;
1605     }
1606     
1607   vuses = VUSE_OPS (ann);
1608   
1609   if (NUM_VUSES (vuses))
1610     {
1611       tree vuse = VUSE_OP (vuses, 0);
1612       value *val = get_value (vuse);
1613       
1614       if (val->lattice_val == UNKNOWN_VAL)
1615         return UNKNOWN_VAL;
1616         
1617 #ifdef ENABLE_CHECKING
1618   /* There should be no VUSE operands that are UNDEFINED. */
1619   if (val->lattice_val == UNDEFINED)
1620     abort ();
1621 #endif
1622         
1623       if (val->lattice_val == CONSTANT)
1624         found_constant = 1;
1625     }
1626
1627   return ((found_constant || (!uses && !vuses)) ? CONSTANT : VARYING);
1628 }
1629
1630 /* A subroutine of fold_stmt_r.  Attempts to fold *(A+O) to A[X].
1631    BASE is an array type.  OFFSET is a byte displacement.  ORIG_TYPE
1632    is the desired result type.  */
1633
1634 static tree
1635 maybe_fold_offset_to_array_ref (tree base, tree offset, tree orig_type)
1636 {
1637   tree min_idx, idx, elt_offset = integer_zero_node;
1638   tree array_type, elt_type, elt_size;
1639
1640   /* If BASE is an ARRAY_REF, we can pick up another offset (this time
1641      measured in units of the size of elements type) from that ARRAY_REF).
1642      We can't do anything if either is variable.
1643
1644      The case we handle here is *(&A[N]+O).  */
1645   if (TREE_CODE (base) == ARRAY_REF)
1646     {
1647       tree low_bound = array_ref_low_bound (base);
1648
1649       elt_offset = TREE_OPERAND (base, 1);
1650       if (TREE_CODE (low_bound) != INTEGER_CST
1651           || TREE_CODE (elt_offset) != INTEGER_CST)
1652         return NULL_TREE;
1653
1654       elt_offset = int_const_binop (MINUS_EXPR, elt_offset, low_bound, 0);
1655       base = TREE_OPERAND (base, 0);
1656     }
1657
1658   /* Ignore stupid user tricks of indexing non-array variables.  */
1659   array_type = TREE_TYPE (base);
1660   if (TREE_CODE (array_type) != ARRAY_TYPE)
1661     return NULL_TREE;
1662   elt_type = TREE_TYPE (array_type);
1663   if (!lang_hooks.types_compatible_p (orig_type, elt_type))
1664     return NULL_TREE;
1665         
1666   /* If OFFSET and ELT_OFFSET are zero, we don't care about the size of the
1667      element type (so we can use the alignment if it's not constant).
1668      Otherwise, compute the offset as an index by using a division.  If the
1669      division isn't exact, then don't do anything.  */
1670   elt_size = TYPE_SIZE_UNIT (elt_type);
1671   if (integer_zerop (offset))
1672     {
1673       if (TREE_CODE (elt_size) != INTEGER_CST)
1674         elt_size = size_int (TYPE_ALIGN (elt_type));
1675
1676       idx = integer_zero_node;
1677     }
1678   else
1679     {
1680       unsigned HOST_WIDE_INT lquo, lrem;
1681       HOST_WIDE_INT hquo, hrem;
1682
1683       if (TREE_CODE (elt_size) != INTEGER_CST
1684           || div_and_round_double (TRUNC_DIV_EXPR, 1,
1685                                    TREE_INT_CST_LOW (offset),
1686                                    TREE_INT_CST_HIGH (offset),
1687                                    TREE_INT_CST_LOW (elt_size),
1688                                    TREE_INT_CST_HIGH (elt_size),
1689                                    &lquo, &hquo, &lrem, &hrem)
1690           || lrem || hrem)
1691         return NULL_TREE;
1692
1693       idx = build_int_2 (lquo, hquo);
1694     }
1695
1696   /* Assume the low bound is zero.  If there is a domain type, get the
1697      low bound, if any, convert the index into that type, and add the
1698      low bound.  */
1699   min_idx = integer_zero_node;
1700   if (TYPE_DOMAIN (array_type))
1701     {
1702       if (TYPE_MIN_VALUE (TYPE_DOMAIN (array_type)))
1703         min_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (array_type));
1704       else
1705         min_idx = fold_convert (TYPE_DOMAIN (array_type), min_idx);
1706
1707       if (TREE_CODE (min_idx) != INTEGER_CST)
1708         return NULL_TREE;
1709
1710       idx = fold_convert (TYPE_DOMAIN (array_type), idx);
1711       elt_offset = fold_convert (TYPE_DOMAIN (array_type), elt_offset);
1712     }
1713
1714   if (!integer_zerop (min_idx))
1715     idx = int_const_binop (PLUS_EXPR, idx, min_idx, 0);
1716   if (!integer_zerop (elt_offset))
1717     idx = int_const_binop (PLUS_EXPR, idx, elt_offset, 0);
1718
1719   return build (ARRAY_REF, orig_type, base, idx, min_idx,
1720                 size_int (tree_low_cst (elt_size, 1)
1721                           / (TYPE_ALIGN (elt_type) / BITS_PER_UNIT)));
1722 }
1723
1724 /* A subroutine of fold_stmt_r.  Attempts to fold *(S+O) to S.X.
1725    BASE is a record type.  OFFSET is a byte displacement.  ORIG_TYPE
1726    is the desired result type.  */
1727 /* ??? This doesn't handle class inheritance.  */
1728
1729 static tree
1730 maybe_fold_offset_to_component_ref (tree record_type, tree base, tree offset,
1731                                     tree orig_type, bool base_is_ptr)
1732 {
1733   tree f, t, field_type, tail_array_field;
1734
1735   if (TREE_CODE (record_type) != RECORD_TYPE
1736       && TREE_CODE (record_type) != UNION_TYPE
1737       && TREE_CODE (record_type) != QUAL_UNION_TYPE)
1738     return NULL_TREE;
1739
1740   /* Short-circuit silly cases.  */
1741   if (lang_hooks.types_compatible_p (record_type, orig_type))
1742     return NULL_TREE;
1743
1744   tail_array_field = NULL_TREE;
1745   for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f))
1746     {
1747       int cmp;
1748
1749       if (TREE_CODE (f) != FIELD_DECL)
1750         continue;
1751       if (DECL_BIT_FIELD (f))
1752         continue;
1753       if (TREE_CODE (DECL_FIELD_OFFSET (f)) != INTEGER_CST)
1754         continue;
1755
1756       /* ??? Java creates "interesting" fields for representing base classes.
1757          They have no name, and have no context.  With no context, we get into
1758          trouble with nonoverlapping_component_refs_p.  Skip them.  */
1759       if (!DECL_FIELD_CONTEXT (f))
1760         continue;
1761
1762       /* The previous array field isn't at the end.  */
1763       tail_array_field = NULL_TREE;
1764
1765       /* Check to see if this offset overlaps with the field.  */
1766       cmp = tree_int_cst_compare (DECL_FIELD_OFFSET (f), offset);
1767       if (cmp > 0)
1768         continue;
1769
1770       field_type = TREE_TYPE (f);
1771       if (cmp < 0)
1772         {
1773           /* Don't care about offsets into the middle of scalars.  */
1774           if (!AGGREGATE_TYPE_P (field_type))
1775             continue;
1776
1777           /* Check for array at the end of the struct.  This is often
1778              used as for flexible array members.  We should be able to
1779              turn this into an array access anyway.  */
1780           if (TREE_CODE (field_type) == ARRAY_TYPE)
1781             tail_array_field = f;
1782
1783           /* Check the end of the field against the offset.  */
1784           if (!DECL_SIZE_UNIT (f)
1785               || TREE_CODE (DECL_SIZE_UNIT (f)) != INTEGER_CST)
1786             continue;
1787           t = int_const_binop (MINUS_EXPR, offset, DECL_FIELD_OFFSET (f), 1);
1788           if (!tree_int_cst_lt (t, DECL_SIZE_UNIT (f)))
1789             continue;
1790
1791           /* If we matched, then set offset to the displacement into
1792              this field.  */
1793           offset = t;
1794         }
1795
1796       /* Here we exactly match the offset being checked.  If the types match,
1797          then we can return that field.  */
1798       else if (lang_hooks.types_compatible_p (orig_type, field_type))
1799         {
1800           if (base_is_ptr)
1801             base = build1 (INDIRECT_REF, record_type, base);
1802           t = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1803           return t;
1804         }
1805
1806       /* Don't care about type-punning of scalars.  */
1807       else if (!AGGREGATE_TYPE_P (field_type))
1808         return NULL_TREE;
1809
1810       goto found;
1811     }
1812
1813   if (!tail_array_field)
1814     return NULL_TREE;
1815
1816   f = tail_array_field;
1817   field_type = TREE_TYPE (f);
1818
1819  found:
1820   /* If we get here, we've got an aggregate field, and a possibly 
1821      nonzero offset into them.  Recurse and hope for a valid match.  */
1822   if (base_is_ptr)
1823     base = build1 (INDIRECT_REF, record_type, base);
1824   base = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1825
1826   t = maybe_fold_offset_to_array_ref (base, offset, orig_type);
1827   if (t)
1828     return t;
1829   return maybe_fold_offset_to_component_ref (field_type, base, offset,
1830                                              orig_type, false);
1831 }
1832
1833 /* A subroutine of fold_stmt_r.  Attempt to simplify *(BASE+OFFSET).
1834    Return the simplified expression, or NULL if nothing could be done.  */
1835
1836 static tree
1837 maybe_fold_stmt_indirect (tree expr, tree base, tree offset)
1838 {
1839   tree t;
1840
1841   /* We may well have constructed a double-nested PLUS_EXPR via multiple
1842      substitutions.  Fold that down to one.  Remove NON_LVALUE_EXPRs that
1843      are sometimes added.  */
1844   base = fold (base);
1845   STRIP_NOPS (base);
1846   TREE_OPERAND (expr, 0) = base;
1847
1848   /* One possibility is that the address reduces to a string constant.  */
1849   t = fold_read_from_constant_string (expr);
1850   if (t)
1851     return t;
1852
1853   /* Add in any offset from a PLUS_EXPR.  */
1854   if (TREE_CODE (base) == PLUS_EXPR)
1855     {
1856       tree offset2;
1857
1858       offset2 = TREE_OPERAND (base, 1);
1859       if (TREE_CODE (offset2) != INTEGER_CST)
1860         return NULL_TREE;
1861       base = TREE_OPERAND (base, 0);
1862
1863       offset = int_const_binop (PLUS_EXPR, offset, offset2, 1);
1864     }
1865
1866   if (TREE_CODE (base) == ADDR_EXPR)
1867     {
1868       /* Strip the ADDR_EXPR.  */
1869       base = TREE_OPERAND (base, 0);
1870
1871       /* Try folding *(&B+O) to B[X].  */
1872       t = maybe_fold_offset_to_array_ref (base, offset, TREE_TYPE (expr));
1873       if (t)
1874         return t;
1875
1876       /* Try folding *(&B+O) to B.X.  */
1877       t = maybe_fold_offset_to_component_ref (TREE_TYPE (base), base, offset,
1878                                               TREE_TYPE (expr), false);
1879       if (t)
1880         return t;
1881
1882       /* Fold *&B to B.  We can only do this if EXPR is the same type
1883          as BASE.  We can't do this if EXPR is the element type of an array
1884          and BASE is the array.  */
1885       if (integer_zerop (offset)
1886           && lang_hooks.types_compatible_p (TREE_TYPE (base),
1887                                             TREE_TYPE (expr)))
1888         return base;
1889     }
1890   else
1891     {
1892       /* We can get here for out-of-range string constant accesses, 
1893          such as "_"[3].  Bail out of the entire substitution search
1894          and arrange for the entire statement to be replaced by a
1895          call to __builtin_trap.  In all likelyhood this will all be
1896          constant-folded away, but in the meantime we can't leave with
1897          something that get_expr_operands can't understand.  */
1898
1899       t = base;
1900       STRIP_NOPS (t);
1901       if (TREE_CODE (t) == ADDR_EXPR
1902           && TREE_CODE (TREE_OPERAND (t, 0)) == STRING_CST)
1903         {
1904           /* FIXME: Except that this causes problems elsewhere with dead
1905              code not being deleted, and we abort in the rtl expanders 
1906              because we failed to remove some ssa_name.  In the meantime,
1907              just return zero.  */
1908           /* FIXME2: This condition should be signaled by
1909              fold_read_from_constant_string directly, rather than 
1910              re-checking for it here.  */
1911           return integer_zero_node;
1912         }
1913
1914       /* Try folding *(B+O) to B->X.  Still an improvement.  */
1915       if (POINTER_TYPE_P (TREE_TYPE (base)))
1916         {
1917           t = maybe_fold_offset_to_component_ref (TREE_TYPE (TREE_TYPE (base)),
1918                                                   base, offset,
1919                                                   TREE_TYPE (expr), true);
1920           if (t)
1921             return t;
1922         }
1923     }
1924
1925   /* Otherwise we had an offset that we could not simplify.  */
1926   return NULL_TREE;
1927 }
1928
1929 /* A subroutine of fold_stmt_r.  EXPR is a PLUS_EXPR.
1930
1931    A quaint feature extant in our address arithmetic is that there
1932    can be hidden type changes here.  The type of the result need
1933    not be the same as the type of the input pointer.
1934
1935    What we're after here is an expression of the form
1936         (T *)(&array + const)
1937    where the cast doesn't actually exist, but is implicit in the
1938    type of the PLUS_EXPR.  We'd like to turn this into
1939         &array[x]
1940    which may be able to propagate further.  */
1941
1942 static tree
1943 maybe_fold_stmt_addition (tree expr)
1944 {
1945   tree op0 = TREE_OPERAND (expr, 0);
1946   tree op1 = TREE_OPERAND (expr, 1);
1947   tree ptr_type = TREE_TYPE (expr);
1948   tree ptd_type;
1949   tree t;
1950   bool subtract = (TREE_CODE (expr) == MINUS_EXPR);
1951
1952   /* We're only interested in pointer arithmetic.  */
1953   if (!POINTER_TYPE_P (ptr_type))
1954     return NULL_TREE;
1955   /* Canonicalize the integral operand to op1.  */
1956   if (INTEGRAL_TYPE_P (TREE_TYPE (op0)))
1957     {
1958       if (subtract)
1959         return NULL_TREE;
1960       t = op0, op0 = op1, op1 = t;
1961     }
1962   /* It had better be a constant.  */
1963   if (TREE_CODE (op1) != INTEGER_CST)
1964     return NULL_TREE;
1965   /* The first operand should be an ADDR_EXPR.  */
1966   if (TREE_CODE (op0) != ADDR_EXPR)
1967     return NULL_TREE;
1968   op0 = TREE_OPERAND (op0, 0);
1969
1970   /* If the first operand is an ARRAY_REF, expand it so that we can fold
1971      the offset into it.  */
1972   while (TREE_CODE (op0) == ARRAY_REF)
1973     {
1974       tree array_obj = TREE_OPERAND (op0, 0);
1975       tree array_idx = TREE_OPERAND (op0, 1);
1976       tree elt_type = TREE_TYPE (op0);
1977       tree elt_size = TYPE_SIZE_UNIT (elt_type);
1978       tree min_idx;
1979
1980       if (TREE_CODE (array_idx) != INTEGER_CST)
1981         break;
1982       if (TREE_CODE (elt_size) != INTEGER_CST)
1983         break;
1984
1985       /* Un-bias the index by the min index of the array type.  */
1986       min_idx = TYPE_DOMAIN (TREE_TYPE (array_obj));
1987       if (min_idx)
1988         {
1989           min_idx = TYPE_MIN_VALUE (min_idx);
1990           if (min_idx)
1991             {
1992               if (TREE_CODE (min_idx) != INTEGER_CST)
1993                 break;
1994
1995               array_idx = convert (TREE_TYPE (min_idx), array_idx);
1996               if (!integer_zerop (min_idx))
1997                 array_idx = int_const_binop (MINUS_EXPR, array_idx,
1998                                              min_idx, 0);
1999             }
2000         }
2001
2002       /* Convert the index to a byte offset.  */
2003       array_idx = convert (sizetype, array_idx);
2004       array_idx = int_const_binop (MULT_EXPR, array_idx, elt_size, 0);
2005
2006       /* Update the operands for the next round, or for folding.  */
2007       /* If we're manipulating unsigned types, then folding into negative
2008          values can produce incorrect results.  Particularly if the type
2009          is smaller than the width of the pointer.  */
2010       if (subtract
2011           && TYPE_UNSIGNED (TREE_TYPE (op1))
2012           && tree_int_cst_lt (array_idx, op1))
2013         return NULL;
2014       op1 = int_const_binop (subtract ? MINUS_EXPR : PLUS_EXPR,
2015                              array_idx, op1, 0);
2016       subtract = false;
2017       op0 = array_obj;
2018     }
2019
2020   /* If we weren't able to fold the subtraction into another array reference,
2021      canonicalize the integer for passing to the array and component ref
2022      simplification functions.  */
2023   if (subtract)
2024     {
2025       if (TYPE_UNSIGNED (TREE_TYPE (op1)))
2026         return NULL;
2027       op1 = fold (build1 (NEGATE_EXPR, TREE_TYPE (op1), op1));
2028       /* ??? In theory fold should always produce another integer.  */
2029       if (TREE_CODE (op1) != INTEGER_CST)
2030         return NULL;
2031     }
2032
2033   ptd_type = TREE_TYPE (ptr_type);
2034
2035   /* At which point we can try some of the same things as for indirects.  */
2036   t = maybe_fold_offset_to_array_ref (op0, op1, ptd_type);
2037   if (!t)
2038     t = maybe_fold_offset_to_component_ref (TREE_TYPE (op0), op0, op1,
2039                                             ptd_type, false);
2040   if (t)
2041     t = build1 (ADDR_EXPR, ptr_type, t);
2042
2043   return t;
2044 }
2045
2046 /* Subroutine of fold_stmt called via walk_tree.  We perform several
2047    simplifications of EXPR_P, mostly having to do with pointer arithmetic.  */
2048
2049 static tree
2050 fold_stmt_r (tree *expr_p, int *walk_subtrees, void *data)
2051 {
2052   bool *changed_p = data;
2053   tree expr = *expr_p, t;
2054
2055   /* ??? It'd be nice if walk_tree had a pre-order option.  */
2056   switch (TREE_CODE (expr))
2057     {
2058     case INDIRECT_REF:
2059       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2060       if (t)
2061         return t;
2062       *walk_subtrees = 0;
2063
2064       t = maybe_fold_stmt_indirect (expr, TREE_OPERAND (expr, 0),
2065                                     integer_zero_node);
2066       break;
2067
2068       /* ??? Could handle ARRAY_REF here, as a variant of INDIRECT_REF.
2069          We'd only want to bother decomposing an existing ARRAY_REF if
2070          the base array is found to have another offset contained within.
2071          Otherwise we'd be wasting time.  */
2072
2073     case ADDR_EXPR:
2074       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2075       if (t)
2076         return t;
2077       *walk_subtrees = 0;
2078
2079       /* Set TREE_INVARIANT properly so that the value is properly
2080          considered constant, and so gets propagated as expected.  */
2081       if (*changed_p)
2082         recompute_tree_invarant_for_addr_expr (expr);
2083       return NULL_TREE;
2084
2085     case PLUS_EXPR:
2086     case MINUS_EXPR:
2087       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2088       if (t)
2089         return t;
2090       t = walk_tree (&TREE_OPERAND (expr, 1), fold_stmt_r, data, NULL);
2091       if (t)
2092         return t;
2093       *walk_subtrees = 0;
2094
2095       t = maybe_fold_stmt_addition (expr);
2096       break;
2097
2098     case COMPONENT_REF:
2099       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2100       if (t)
2101         return t;
2102       *walk_subtrees = 0;
2103
2104       /* Make sure the FIELD_DECL is actually a field in the type on the lhs.
2105          We've already checked that the records are compatible, so we should
2106          come up with a set of compatible fields.  */
2107       {
2108         tree expr_record = TREE_TYPE (TREE_OPERAND (expr, 0));
2109         tree expr_field = TREE_OPERAND (expr, 1);
2110
2111         if (DECL_FIELD_CONTEXT (expr_field) != TYPE_MAIN_VARIANT (expr_record))
2112           {
2113             expr_field = find_compatible_field (expr_record, expr_field);
2114             TREE_OPERAND (expr, 1) = expr_field;
2115           }
2116       }
2117       break;
2118
2119     default:
2120       return NULL_TREE;
2121     }
2122
2123   if (t)
2124     {
2125       *expr_p = t;
2126       *changed_p = true;
2127     }
2128
2129   return NULL_TREE;
2130 }
2131
2132 /* Fold the statement pointed by STMT_P.  In some cases, this function may
2133    replace the whole statement with a new one.  Returns true iff folding
2134    makes any changes.  */
2135
2136 bool
2137 fold_stmt (tree *stmt_p)
2138 {
2139   tree rhs, result, stmt;
2140   bool changed = false;
2141
2142   stmt = *stmt_p;
2143
2144   /* If we replaced constants and the statement makes pointer dereferences,
2145      then we may need to fold instances of *&VAR into VAR, etc.  */
2146   if (walk_tree (stmt_p, fold_stmt_r, &changed, NULL))
2147     {
2148       *stmt_p
2149         = build_function_call_expr (implicit_built_in_decls[BUILT_IN_TRAP],
2150                                     NULL);
2151       return true;
2152     }
2153
2154   rhs = get_rhs (stmt);
2155   if (!rhs)
2156     return changed;
2157   result = NULL_TREE;
2158
2159   if (TREE_CODE (rhs) == CALL_EXPR)
2160     {
2161       tree callee;
2162
2163       /* Check for builtins that CCP can handle using information not
2164          available in the generic fold routines.  */
2165       callee = get_callee_fndecl (rhs);
2166       if (callee && DECL_BUILT_IN (callee))
2167         result = ccp_fold_builtin (stmt, rhs);
2168       else
2169         {
2170           /* Check for resolvable OBJ_TYPE_REF.  The only sorts we can resolve
2171              here are when we've propagated the address of a decl into the
2172              object slot.  */
2173           /* ??? Should perhaps do this in fold proper.  However, doing it
2174              there requires that we create a new CALL_EXPR, and that requires
2175              copying EH region info to the new node.  Easier to just do it
2176              here where we can just smash the call operand.  */
2177           callee = TREE_OPERAND (rhs, 0);
2178           if (TREE_CODE (callee) == OBJ_TYPE_REF
2179               && lang_hooks.fold_obj_type_ref
2180               && TREE_CODE (OBJ_TYPE_REF_OBJECT (callee)) == ADDR_EXPR
2181               && DECL_P (TREE_OPERAND (OBJ_TYPE_REF_OBJECT (callee), 0)))
2182             {
2183               tree t;
2184
2185               /* ??? Caution: Broken ADDR_EXPR semantics means that
2186                  looking at the type of the operand of the addr_expr
2187                  can yield an array type.  See silly exception in
2188                  check_pointer_types_r.  */
2189
2190               t = TREE_TYPE (TREE_TYPE (OBJ_TYPE_REF_OBJECT (callee)));
2191               t = lang_hooks.fold_obj_type_ref (callee, t);
2192               if (t)
2193                 {
2194                   TREE_OPERAND (rhs, 0) = t;
2195                   changed = true;
2196                 }
2197             }
2198         }
2199     }
2200
2201   /* If we couldn't fold the RHS, hand over to the generic fold routines.  */
2202   if (result == NULL_TREE)
2203     result = fold (rhs);
2204
2205   /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR that
2206      may have been added by fold, and "useless" type conversions that might
2207      now be apparent due to propagation.  */
2208   STRIP_USELESS_TYPE_CONVERSION (result);
2209
2210   if (result != rhs)
2211     changed |= set_rhs (stmt_p, result);
2212
2213   return changed;
2214 }
2215
2216 /* Get the main expression from statement STMT.  */
2217
2218 static tree
2219 get_rhs (tree stmt)
2220 {
2221   enum tree_code code = TREE_CODE (stmt);
2222
2223   switch (code)
2224     {
2225     case RETURN_EXPR:
2226       stmt = TREE_OPERAND (stmt, 0);
2227       if (!stmt || TREE_CODE (stmt) != MODIFY_EXPR)
2228         return stmt;
2229       /* FALLTHRU */
2230
2231     case MODIFY_EXPR:
2232       stmt = TREE_OPERAND (stmt, 1);
2233       if (TREE_CODE (stmt) == WITH_SIZE_EXPR)
2234         return TREE_OPERAND (stmt, 0);
2235       else
2236         return stmt;
2237
2238     case COND_EXPR:
2239       return COND_EXPR_COND (stmt);
2240     case SWITCH_EXPR:
2241       return SWITCH_COND (stmt);
2242     case GOTO_EXPR:
2243       return GOTO_DESTINATION (stmt);
2244     case LABEL_EXPR:
2245       return LABEL_EXPR_LABEL (stmt);
2246
2247     default:
2248       return stmt;
2249     }
2250 }
2251
2252
2253 /* Set the main expression of *STMT_P to EXPR.  */
2254
2255 static bool
2256 set_rhs (tree *stmt_p, tree expr)
2257 {
2258   tree stmt = *stmt_p, op;
2259   enum tree_code code = TREE_CODE (expr);
2260   stmt_ann_t ann;
2261
2262   /* Verify the constant folded result is valid gimple.  */
2263   if (TREE_CODE_CLASS (code) == '2')
2264     {
2265       if (!is_gimple_val (TREE_OPERAND (expr, 0))
2266           || !is_gimple_val (TREE_OPERAND (expr, 1)))
2267         return false;
2268     }
2269   else if (TREE_CODE_CLASS (code) == '1')
2270     {
2271       if (!is_gimple_val (TREE_OPERAND (expr, 0)))
2272         return false;
2273     }
2274
2275   switch (TREE_CODE (stmt))
2276     {
2277     case RETURN_EXPR:
2278       op = TREE_OPERAND (stmt, 0);
2279       if (TREE_CODE (op) != MODIFY_EXPR)
2280         {
2281           TREE_OPERAND (stmt, 0) = expr;
2282           break;
2283         }
2284       stmt = op;
2285       /* FALLTHRU */
2286
2287     case MODIFY_EXPR:
2288       op = TREE_OPERAND (stmt, 1);
2289       if (TREE_CODE (op) == WITH_SIZE_EXPR)
2290         stmt = op;
2291       TREE_OPERAND (stmt, 1) = expr;
2292       break;
2293
2294     case COND_EXPR:
2295       COND_EXPR_COND (stmt) = expr;
2296       break;
2297     case SWITCH_EXPR:
2298       SWITCH_COND (stmt) = expr;
2299       break;
2300     case GOTO_EXPR:
2301       GOTO_DESTINATION (stmt) = expr;
2302       break;
2303     case LABEL_EXPR:
2304       LABEL_EXPR_LABEL (stmt) = expr;
2305       break;
2306
2307     default:
2308       /* Replace the whole statement with EXPR.  If EXPR has no side
2309          effects, then replace *STMT_P with an empty statement.  */
2310       ann = stmt_ann (stmt);
2311       *stmt_p = TREE_SIDE_EFFECTS (expr) ? expr : build_empty_stmt ();
2312       (*stmt_p)->common.ann = (tree_ann_t) ann;
2313
2314       if (TREE_SIDE_EFFECTS (expr))
2315         {
2316           def_optype defs;
2317           v_may_def_optype v_may_defs;
2318           v_must_def_optype v_must_defs;
2319           size_t i;
2320
2321           /* Fix all the SSA_NAMEs created by *STMT_P to point to its new
2322              replacement.  */
2323           defs = DEF_OPS (ann);
2324           for (i = 0; i < NUM_DEFS (defs); i++)
2325             {
2326               tree var = DEF_OP (defs, i);
2327               if (TREE_CODE (var) == SSA_NAME)
2328                 SSA_NAME_DEF_STMT (var) = *stmt_p;
2329             }
2330
2331           v_may_defs = V_MAY_DEF_OPS (ann);
2332           for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
2333             {
2334               tree var = V_MAY_DEF_RESULT (v_may_defs, i);
2335               if (TREE_CODE (var) == SSA_NAME)
2336                 SSA_NAME_DEF_STMT (var) = *stmt_p;
2337             }
2338             
2339           v_must_defs = V_MUST_DEF_OPS (ann);
2340           for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
2341             {
2342               tree var = V_MUST_DEF_OP (v_must_defs, i);
2343               if (TREE_CODE (var) == SSA_NAME)
2344                 SSA_NAME_DEF_STMT (var) = *stmt_p;
2345             }
2346         }
2347       break;
2348     }
2349
2350   return true;
2351 }
2352
2353
2354 /* Return a default value for variable VAR using the following rules:
2355
2356    1- Function arguments are considered VARYING.
2357    
2358    2- Global and static variables that are declared constant are
2359       considered CONSTANT.
2360
2361    3- Any other virtually defined variable is considered UNKNOWN_VAL.
2362
2363    4- Any other value is considered UNDEFINED.  This is useful when
2364       considering PHI nodes.  PHI arguments that are undefined do not
2365       change the constant value of the PHI node, which allows for more
2366       constants to be propagated.  */
2367
2368 static value
2369 get_default_value (tree var)
2370 {
2371   value val;
2372   tree sym;
2373
2374   if (TREE_CODE (var) == SSA_NAME)
2375     sym = SSA_NAME_VAR (var);
2376   else
2377     {
2378 #ifdef ENABLE_CHECKING
2379       if (!DECL_P (var))
2380         abort ();
2381 #endif
2382       sym = var;
2383     }
2384
2385   val.lattice_val = UNDEFINED;
2386   val.const_val = NULL_TREE;
2387
2388   if (TREE_CODE (sym) == PARM_DECL || TREE_THIS_VOLATILE (sym))
2389     {
2390       /* Function arguments and volatile variables are considered VARYING.  */
2391       val.lattice_val = VARYING;
2392     }
2393   else if (TREE_STATIC (sym))
2394     {
2395       /* Globals and static variables are considered UNKNOWN_VAL,
2396          unless they are declared 'const'.  */
2397       if (TREE_READONLY (sym)
2398           && DECL_INITIAL (sym)
2399           && is_gimple_min_invariant (DECL_INITIAL (sym)))
2400         {
2401           val.lattice_val = CONSTANT;
2402           val.const_val = DECL_INITIAL (sym);
2403         }
2404       else
2405         {
2406           val.const_val = NULL_TREE;
2407           val.lattice_val = UNKNOWN_VAL;
2408         }
2409     }
2410   else if (!is_gimple_reg (sym))
2411     {
2412       val.const_val = NULL_TREE;
2413       val.lattice_val = UNKNOWN_VAL;
2414     }
2415   else
2416     {
2417       enum tree_code code;
2418       tree stmt = SSA_NAME_DEF_STMT (var);
2419
2420       if (!IS_EMPTY_STMT (stmt))
2421         {
2422           code = TREE_CODE (stmt);
2423           if (code != MODIFY_EXPR && code != PHI_NODE)
2424             val.lattice_val = VARYING;
2425         }
2426     }
2427
2428   return val;
2429 }
2430
2431
2432 /* Fold builtin call FN in statement STMT.  If it cannot be folded into a
2433    constant, return NULL_TREE.  Otherwise, return its constant value.  */
2434
2435 static tree
2436 ccp_fold_builtin (tree stmt, tree fn)
2437 {
2438   tree result, strlen_val[2];
2439   tree callee, arglist, a;
2440   int strlen_arg, i;
2441   bitmap visited;
2442   bool ignore;
2443
2444   ignore = TREE_CODE (stmt) != MODIFY_EXPR;
2445
2446   /* First try the generic builtin folder.  If that succeeds, return the
2447      result directly.  */
2448   result = fold_builtin (fn, ignore);
2449   if (result)
2450   {
2451     if (ignore)
2452       STRIP_NOPS (result);
2453     return result;
2454   }
2455
2456   /* Ignore MD builtins.  */
2457   callee = get_callee_fndecl (fn);
2458   if (DECL_BUILT_IN_CLASS (callee) == BUILT_IN_MD)
2459     return NULL_TREE;
2460
2461   /* If the builtin could not be folded, and it has no argument list,
2462      we're done.  */
2463   arglist = TREE_OPERAND (fn, 1);
2464   if (!arglist)
2465     return NULL_TREE;
2466
2467   /* Limit the work only for builtins we know how to simplify.  */
2468   switch (DECL_FUNCTION_CODE (callee))
2469     {
2470     case BUILT_IN_STRLEN:
2471     case BUILT_IN_FPUTS:
2472     case BUILT_IN_FPUTS_UNLOCKED:
2473       strlen_arg = 1;
2474       break;
2475     case BUILT_IN_STRCPY:
2476     case BUILT_IN_STRNCPY:
2477       strlen_arg = 2;
2478       break;
2479     default:
2480       return NULL_TREE;
2481     }
2482
2483   /* Try to use the dataflow information gathered by the CCP process.  */
2484   visited = BITMAP_XMALLOC ();
2485
2486   memset (strlen_val, 0, sizeof (strlen_val));
2487   for (i = 0, a = arglist;
2488        strlen_arg;
2489        i++, strlen_arg >>= 1, a = TREE_CHAIN (a))
2490     if (strlen_arg & 1)
2491       {
2492         bitmap_clear (visited);
2493         if (!get_strlen (TREE_VALUE (a), &strlen_val[i], visited))
2494           strlen_val[i] = NULL_TREE;
2495       }
2496
2497   BITMAP_XFREE (visited);
2498
2499   result = NULL_TREE;
2500   switch (DECL_FUNCTION_CODE (callee))
2501     {
2502     case BUILT_IN_STRLEN:
2503       if (strlen_val[0])
2504         {
2505           tree new = fold_convert (TREE_TYPE (fn), strlen_val[0]);
2506
2507           /* If the result is not a valid gimple value, or not a cast
2508              of a valid gimple value, then we can not use the result.  */
2509           if (is_gimple_val (new)
2510               || (is_gimple_cast (new)
2511                   && is_gimple_val (TREE_OPERAND (new, 0))))
2512             return new;
2513         }
2514       break;
2515
2516     case BUILT_IN_STRCPY:
2517       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
2518         result = fold_builtin_strcpy (fn, strlen_val[1]);
2519       break;
2520
2521     case BUILT_IN_STRNCPY:
2522       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
2523         result = fold_builtin_strncpy (fn, strlen_val[1]);
2524       break;
2525
2526     case BUILT_IN_FPUTS:
2527       result = fold_builtin_fputs (arglist,
2528                                    TREE_CODE (stmt) != MODIFY_EXPR, 0,
2529                                    strlen_val[0]);
2530       break;
2531
2532     case BUILT_IN_FPUTS_UNLOCKED:
2533       result = fold_builtin_fputs (arglist,
2534                                    TREE_CODE (stmt) != MODIFY_EXPR, 1,
2535                                    strlen_val[0]);
2536       break;
2537
2538     default:
2539       abort ();
2540     }
2541
2542   if (result && ignore)
2543     result = fold_ignored_result (result);
2544   return result;
2545 }
2546
2547
2548 /* Return the string length of ARG in LENGTH.  If ARG is an SSA name variable,
2549    follow its use-def chains.  If LENGTH is not NULL and its value is not
2550    equal to the length we determine, or if we are unable to determine the
2551    length, return false.  VISITED is a bitmap of visited variables.  */
2552
2553 static bool
2554 get_strlen (tree arg, tree *length, bitmap visited)
2555 {
2556   tree var, def_stmt, val;
2557   
2558   if (TREE_CODE (arg) != SSA_NAME)
2559     {
2560       val = c_strlen (arg, 1);
2561       if (!val)
2562         return false;
2563
2564       if (*length && simple_cst_equal (val, *length) != 1)
2565         return false;
2566
2567       *length = val;
2568       return true;
2569     }
2570
2571   /* If we were already here, break the infinite cycle.  */
2572   if (bitmap_bit_p (visited, SSA_NAME_VERSION (arg)))
2573     return true;
2574   bitmap_set_bit (visited, SSA_NAME_VERSION (arg));
2575
2576   var = arg;
2577   def_stmt = SSA_NAME_DEF_STMT (var);
2578
2579   switch (TREE_CODE (def_stmt))
2580     {
2581       case MODIFY_EXPR:
2582         {
2583           tree len, rhs;
2584           
2585           /* The RHS of the statement defining VAR must either have a
2586              constant length or come from another SSA_NAME with a constant
2587              length.  */
2588           rhs = TREE_OPERAND (def_stmt, 1);
2589           STRIP_NOPS (rhs);
2590           if (TREE_CODE (rhs) == SSA_NAME)
2591             return get_strlen (rhs, length, visited);
2592
2593           /* See if the RHS is a constant length.  */
2594           len = c_strlen (rhs, 1);
2595           if (len)
2596             {
2597               if (*length && simple_cst_equal (len, *length) != 1)
2598                 return false;
2599
2600               *length = len;
2601               return true;
2602             }
2603
2604           break;
2605         }
2606
2607       case PHI_NODE:
2608         {
2609           /* All the arguments of the PHI node must have the same constant
2610              length.  */
2611           int i;
2612
2613           for (i = 0; i < PHI_NUM_ARGS (def_stmt); i++)
2614             {
2615               tree arg = PHI_ARG_DEF (def_stmt, i);
2616
2617               /* If this PHI has itself as an argument, we cannot
2618                  determine the string length of this argument.  However,
2619                  if we can find a constant string length for the other
2620                  PHI args then we can still be sure that this is a
2621                  constant string length.  So be optimistic and just
2622                  continue with the next argument.  */
2623               if (arg == PHI_RESULT (def_stmt))
2624                 continue;
2625
2626               if (!get_strlen (arg, length, visited))
2627                 return false;
2628             }
2629
2630           return true;
2631         }
2632
2633       default:
2634         break;
2635     }
2636
2637
2638   return false;
2639 }
2640
2641 \f
2642 /* A simple pass that attempts to fold all builtin functions.  This pass
2643    is run after we've propagated as many constants as we can.  */
2644
2645 static void
2646 execute_fold_all_builtins (void)
2647 {
2648   basic_block bb;
2649   FOR_EACH_BB (bb)
2650     {
2651       block_stmt_iterator i;
2652       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
2653         {
2654           tree *stmtp = bsi_stmt_ptr (i);
2655           tree call = get_rhs (*stmtp);
2656           tree callee, result;
2657
2658           if (!call || TREE_CODE (call) != CALL_EXPR)
2659             continue;
2660           callee = get_callee_fndecl (call);
2661           if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
2662             continue;
2663
2664           result = ccp_fold_builtin (*stmtp, call);
2665           if (!result)
2666             switch (DECL_FUNCTION_CODE (callee))
2667               {
2668               case BUILT_IN_CONSTANT_P:
2669                 /* Resolve __builtin_constant_p.  If it hasn't been
2670                    folded to integer_one_node by now, it's fairly
2671                    certain that the value simply isn't constant.  */
2672                 result = integer_zero_node;
2673                 break;
2674
2675               default:
2676                 continue;
2677               }
2678
2679           if (dump_file && (dump_flags & TDF_DETAILS))
2680             {
2681               fprintf (dump_file, "Simplified\n  ");
2682               print_generic_stmt (dump_file, *stmtp, dump_flags);
2683             }
2684
2685           if (set_rhs (stmtp, result))
2686             modify_stmt (*stmtp);
2687
2688           if (dump_file && (dump_flags & TDF_DETAILS))
2689             {
2690               fprintf (dump_file, "to\n  ");
2691               print_generic_stmt (dump_file, *stmtp, dump_flags);
2692               fprintf (dump_file, "\n");
2693             }
2694         }
2695     }
2696 }
2697
2698 struct tree_opt_pass pass_fold_builtins = 
2699 {
2700   "fab",                                /* name */
2701   NULL,                                 /* gate */
2702   execute_fold_all_builtins,            /* execute */
2703   NULL,                                 /* sub */
2704   NULL,                                 /* next */
2705   0,                                    /* static_pass_number */
2706   0,                                    /* tv_id */
2707   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2708   0,                                    /* properties_provided */
2709   0,                                    /* properties_destroyed */
2710   0,                                    /* todo_flags_start */
2711   TODO_dump_func | TODO_verify_ssa      /* todo_flags_finish */
2712 };
2713
2714
2715 #include "gt-tree-ssa-ccp.h"