OSDN Git Service

PR middle-end/16790
[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       /* Fold away CONST_DECL to its value, if the type is scalar.  */
1872       if (TREE_CODE (base) == CONST_DECL
1873           && is_gimple_min_invariant (DECL_INITIAL (base)))
1874         return DECL_INITIAL (base);
1875
1876       /* Try folding *(&B+O) to B[X].  */
1877       t = maybe_fold_offset_to_array_ref (base, offset, TREE_TYPE (expr));
1878       if (t)
1879         return t;
1880
1881       /* Try folding *(&B+O) to B.X.  */
1882       t = maybe_fold_offset_to_component_ref (TREE_TYPE (base), base, offset,
1883                                               TREE_TYPE (expr), false);
1884       if (t)
1885         return t;
1886
1887       /* Fold *&B to B.  We can only do this if EXPR is the same type
1888          as BASE.  We can't do this if EXPR is the element type of an array
1889          and BASE is the array.  */
1890       if (integer_zerop (offset)
1891           && lang_hooks.types_compatible_p (TREE_TYPE (base),
1892                                             TREE_TYPE (expr)))
1893         return base;
1894     }
1895   else
1896     {
1897       /* We can get here for out-of-range string constant accesses, 
1898          such as "_"[3].  Bail out of the entire substitution search
1899          and arrange for the entire statement to be replaced by a
1900          call to __builtin_trap.  In all likelyhood this will all be
1901          constant-folded away, but in the meantime we can't leave with
1902          something that get_expr_operands can't understand.  */
1903
1904       t = base;
1905       STRIP_NOPS (t);
1906       if (TREE_CODE (t) == ADDR_EXPR
1907           && TREE_CODE (TREE_OPERAND (t, 0)) == STRING_CST)
1908         {
1909           /* FIXME: Except that this causes problems elsewhere with dead
1910              code not being deleted, and we abort in the rtl expanders 
1911              because we failed to remove some ssa_name.  In the meantime,
1912              just return zero.  */
1913           /* FIXME2: This condition should be signaled by
1914              fold_read_from_constant_string directly, rather than 
1915              re-checking for it here.  */
1916           return integer_zero_node;
1917         }
1918
1919       /* Try folding *(B+O) to B->X.  Still an improvement.  */
1920       if (POINTER_TYPE_P (TREE_TYPE (base)))
1921         {
1922           t = maybe_fold_offset_to_component_ref (TREE_TYPE (TREE_TYPE (base)),
1923                                                   base, offset,
1924                                                   TREE_TYPE (expr), true);
1925           if (t)
1926             return t;
1927         }
1928     }
1929
1930   /* Otherwise we had an offset that we could not simplify.  */
1931   return NULL_TREE;
1932 }
1933
1934 /* A subroutine of fold_stmt_r.  EXPR is a PLUS_EXPR.
1935
1936    A quaint feature extant in our address arithmetic is that there
1937    can be hidden type changes here.  The type of the result need
1938    not be the same as the type of the input pointer.
1939
1940    What we're after here is an expression of the form
1941         (T *)(&array + const)
1942    where the cast doesn't actually exist, but is implicit in the
1943    type of the PLUS_EXPR.  We'd like to turn this into
1944         &array[x]
1945    which may be able to propagate further.  */
1946
1947 static tree
1948 maybe_fold_stmt_addition (tree expr)
1949 {
1950   tree op0 = TREE_OPERAND (expr, 0);
1951   tree op1 = TREE_OPERAND (expr, 1);
1952   tree ptr_type = TREE_TYPE (expr);
1953   tree ptd_type;
1954   tree t;
1955   bool subtract = (TREE_CODE (expr) == MINUS_EXPR);
1956
1957   /* We're only interested in pointer arithmetic.  */
1958   if (!POINTER_TYPE_P (ptr_type))
1959     return NULL_TREE;
1960   /* Canonicalize the integral operand to op1.  */
1961   if (INTEGRAL_TYPE_P (TREE_TYPE (op0)))
1962     {
1963       if (subtract)
1964         return NULL_TREE;
1965       t = op0, op0 = op1, op1 = t;
1966     }
1967   /* It had better be a constant.  */
1968   if (TREE_CODE (op1) != INTEGER_CST)
1969     return NULL_TREE;
1970   /* The first operand should be an ADDR_EXPR.  */
1971   if (TREE_CODE (op0) != ADDR_EXPR)
1972     return NULL_TREE;
1973   op0 = TREE_OPERAND (op0, 0);
1974
1975   /* If the first operand is an ARRAY_REF, expand it so that we can fold
1976      the offset into it.  */
1977   while (TREE_CODE (op0) == ARRAY_REF)
1978     {
1979       tree array_obj = TREE_OPERAND (op0, 0);
1980       tree array_idx = TREE_OPERAND (op0, 1);
1981       tree elt_type = TREE_TYPE (op0);
1982       tree elt_size = TYPE_SIZE_UNIT (elt_type);
1983       tree min_idx;
1984
1985       if (TREE_CODE (array_idx) != INTEGER_CST)
1986         break;
1987       if (TREE_CODE (elt_size) != INTEGER_CST)
1988         break;
1989
1990       /* Un-bias the index by the min index of the array type.  */
1991       min_idx = TYPE_DOMAIN (TREE_TYPE (array_obj));
1992       if (min_idx)
1993         {
1994           min_idx = TYPE_MIN_VALUE (min_idx);
1995           if (min_idx)
1996             {
1997               if (TREE_CODE (min_idx) != INTEGER_CST)
1998                 break;
1999
2000               array_idx = convert (TREE_TYPE (min_idx), array_idx);
2001               if (!integer_zerop (min_idx))
2002                 array_idx = int_const_binop (MINUS_EXPR, array_idx,
2003                                              min_idx, 0);
2004             }
2005         }
2006
2007       /* Convert the index to a byte offset.  */
2008       array_idx = convert (sizetype, array_idx);
2009       array_idx = int_const_binop (MULT_EXPR, array_idx, elt_size, 0);
2010
2011       /* Update the operands for the next round, or for folding.  */
2012       /* If we're manipulating unsigned types, then folding into negative
2013          values can produce incorrect results.  Particularly if the type
2014          is smaller than the width of the pointer.  */
2015       if (subtract
2016           && TYPE_UNSIGNED (TREE_TYPE (op1))
2017           && tree_int_cst_lt (array_idx, op1))
2018         return NULL;
2019       op1 = int_const_binop (subtract ? MINUS_EXPR : PLUS_EXPR,
2020                              array_idx, op1, 0);
2021       subtract = false;
2022       op0 = array_obj;
2023     }
2024
2025   /* If we weren't able to fold the subtraction into another array reference,
2026      canonicalize the integer for passing to the array and component ref
2027      simplification functions.  */
2028   if (subtract)
2029     {
2030       if (TYPE_UNSIGNED (TREE_TYPE (op1)))
2031         return NULL;
2032       op1 = fold (build1 (NEGATE_EXPR, TREE_TYPE (op1), op1));
2033       /* ??? In theory fold should always produce another integer.  */
2034       if (TREE_CODE (op1) != INTEGER_CST)
2035         return NULL;
2036     }
2037
2038   ptd_type = TREE_TYPE (ptr_type);
2039
2040   /* At which point we can try some of the same things as for indirects.  */
2041   t = maybe_fold_offset_to_array_ref (op0, op1, ptd_type);
2042   if (!t)
2043     t = maybe_fold_offset_to_component_ref (TREE_TYPE (op0), op0, op1,
2044                                             ptd_type, false);
2045   if (t)
2046     t = build1 (ADDR_EXPR, ptr_type, t);
2047
2048   return t;
2049 }
2050
2051 /* Subroutine of fold_stmt called via walk_tree.  We perform several
2052    simplifications of EXPR_P, mostly having to do with pointer arithmetic.  */
2053
2054 static tree
2055 fold_stmt_r (tree *expr_p, int *walk_subtrees, void *data)
2056 {
2057   bool *changed_p = data;
2058   tree expr = *expr_p, t;
2059
2060   /* ??? It'd be nice if walk_tree had a pre-order option.  */
2061   switch (TREE_CODE (expr))
2062     {
2063     case INDIRECT_REF:
2064       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2065       if (t)
2066         return t;
2067       *walk_subtrees = 0;
2068
2069       t = maybe_fold_stmt_indirect (expr, TREE_OPERAND (expr, 0),
2070                                     integer_zero_node);
2071       break;
2072
2073       /* ??? Could handle ARRAY_REF here, as a variant of INDIRECT_REF.
2074          We'd only want to bother decomposing an existing ARRAY_REF if
2075          the base array is found to have another offset contained within.
2076          Otherwise we'd be wasting time.  */
2077
2078     case ADDR_EXPR:
2079       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2080       if (t)
2081         return t;
2082       *walk_subtrees = 0;
2083
2084       /* Set TREE_INVARIANT properly so that the value is properly
2085          considered constant, and so gets propagated as expected.  */
2086       if (*changed_p)
2087         recompute_tree_invarant_for_addr_expr (expr);
2088       return NULL_TREE;
2089
2090     case PLUS_EXPR:
2091     case MINUS_EXPR:
2092       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2093       if (t)
2094         return t;
2095       t = walk_tree (&TREE_OPERAND (expr, 1), fold_stmt_r, data, NULL);
2096       if (t)
2097         return t;
2098       *walk_subtrees = 0;
2099
2100       t = maybe_fold_stmt_addition (expr);
2101       break;
2102
2103     case COMPONENT_REF:
2104       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
2105       if (t)
2106         return t;
2107       *walk_subtrees = 0;
2108
2109       /* Make sure the FIELD_DECL is actually a field in the type on the lhs.
2110          We've already checked that the records are compatible, so we should
2111          come up with a set of compatible fields.  */
2112       {
2113         tree expr_record = TREE_TYPE (TREE_OPERAND (expr, 0));
2114         tree expr_field = TREE_OPERAND (expr, 1);
2115
2116         if (DECL_FIELD_CONTEXT (expr_field) != TYPE_MAIN_VARIANT (expr_record))
2117           {
2118             expr_field = find_compatible_field (expr_record, expr_field);
2119             TREE_OPERAND (expr, 1) = expr_field;
2120           }
2121       }
2122       break;
2123
2124     default:
2125       return NULL_TREE;
2126     }
2127
2128   if (t)
2129     {
2130       *expr_p = t;
2131       *changed_p = true;
2132     }
2133
2134   return NULL_TREE;
2135 }
2136
2137 /* Fold the statement pointed by STMT_P.  In some cases, this function may
2138    replace the whole statement with a new one.  Returns true iff folding
2139    makes any changes.  */
2140
2141 bool
2142 fold_stmt (tree *stmt_p)
2143 {
2144   tree rhs, result, stmt;
2145   bool changed = false;
2146
2147   stmt = *stmt_p;
2148
2149   /* If we replaced constants and the statement makes pointer dereferences,
2150      then we may need to fold instances of *&VAR into VAR, etc.  */
2151   if (walk_tree (stmt_p, fold_stmt_r, &changed, NULL))
2152     {
2153       *stmt_p
2154         = build_function_call_expr (implicit_built_in_decls[BUILT_IN_TRAP],
2155                                     NULL);
2156       return true;
2157     }
2158
2159   rhs = get_rhs (stmt);
2160   if (!rhs)
2161     return changed;
2162   result = NULL_TREE;
2163
2164   if (TREE_CODE (rhs) == CALL_EXPR)
2165     {
2166       tree callee;
2167
2168       /* Check for builtins that CCP can handle using information not
2169          available in the generic fold routines.  */
2170       callee = get_callee_fndecl (rhs);
2171       if (callee && DECL_BUILT_IN (callee))
2172         result = ccp_fold_builtin (stmt, rhs);
2173       else
2174         {
2175           /* Check for resolvable OBJ_TYPE_REF.  The only sorts we can resolve
2176              here are when we've propagated the address of a decl into the
2177              object slot.  */
2178           /* ??? Should perhaps do this in fold proper.  However, doing it
2179              there requires that we create a new CALL_EXPR, and that requires
2180              copying EH region info to the new node.  Easier to just do it
2181              here where we can just smash the call operand.  */
2182           callee = TREE_OPERAND (rhs, 0);
2183           if (TREE_CODE (callee) == OBJ_TYPE_REF
2184               && lang_hooks.fold_obj_type_ref
2185               && TREE_CODE (OBJ_TYPE_REF_OBJECT (callee)) == ADDR_EXPR
2186               && DECL_P (TREE_OPERAND (OBJ_TYPE_REF_OBJECT (callee), 0)))
2187             {
2188               tree t;
2189
2190               /* ??? Caution: Broken ADDR_EXPR semantics means that
2191                  looking at the type of the operand of the addr_expr
2192                  can yield an array type.  See silly exception in
2193                  check_pointer_types_r.  */
2194
2195               t = TREE_TYPE (TREE_TYPE (OBJ_TYPE_REF_OBJECT (callee)));
2196               t = lang_hooks.fold_obj_type_ref (callee, t);
2197               if (t)
2198                 {
2199                   TREE_OPERAND (rhs, 0) = t;
2200                   changed = true;
2201                 }
2202             }
2203         }
2204     }
2205
2206   /* If we couldn't fold the RHS, hand over to the generic fold routines.  */
2207   if (result == NULL_TREE)
2208     result = fold (rhs);
2209
2210   /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR that
2211      may have been added by fold, and "useless" type conversions that might
2212      now be apparent due to propagation.  */
2213   STRIP_USELESS_TYPE_CONVERSION (result);
2214
2215   if (result != rhs)
2216     changed |= set_rhs (stmt_p, result);
2217
2218   return changed;
2219 }
2220
2221 /* Get the main expression from statement STMT.  */
2222
2223 static tree
2224 get_rhs (tree stmt)
2225 {
2226   enum tree_code code = TREE_CODE (stmt);
2227
2228   switch (code)
2229     {
2230     case RETURN_EXPR:
2231       stmt = TREE_OPERAND (stmt, 0);
2232       if (!stmt || TREE_CODE (stmt) != MODIFY_EXPR)
2233         return stmt;
2234       /* FALLTHRU */
2235
2236     case MODIFY_EXPR:
2237       stmt = TREE_OPERAND (stmt, 1);
2238       if (TREE_CODE (stmt) == WITH_SIZE_EXPR)
2239         return TREE_OPERAND (stmt, 0);
2240       else
2241         return stmt;
2242
2243     case COND_EXPR:
2244       return COND_EXPR_COND (stmt);
2245     case SWITCH_EXPR:
2246       return SWITCH_COND (stmt);
2247     case GOTO_EXPR:
2248       return GOTO_DESTINATION (stmt);
2249     case LABEL_EXPR:
2250       return LABEL_EXPR_LABEL (stmt);
2251
2252     default:
2253       return stmt;
2254     }
2255 }
2256
2257
2258 /* Set the main expression of *STMT_P to EXPR.  */
2259
2260 static bool
2261 set_rhs (tree *stmt_p, tree expr)
2262 {
2263   tree stmt = *stmt_p, op;
2264   enum tree_code code = TREE_CODE (expr);
2265   stmt_ann_t ann;
2266
2267   /* Verify the constant folded result is valid gimple.  */
2268   if (TREE_CODE_CLASS (code) == '2')
2269     {
2270       if (!is_gimple_val (TREE_OPERAND (expr, 0))
2271           || !is_gimple_val (TREE_OPERAND (expr, 1)))
2272         return false;
2273     }
2274   else if (TREE_CODE_CLASS (code) == '1')
2275     {
2276       if (!is_gimple_val (TREE_OPERAND (expr, 0)))
2277         return false;
2278     }
2279
2280   switch (TREE_CODE (stmt))
2281     {
2282     case RETURN_EXPR:
2283       op = TREE_OPERAND (stmt, 0);
2284       if (TREE_CODE (op) != MODIFY_EXPR)
2285         {
2286           TREE_OPERAND (stmt, 0) = expr;
2287           break;
2288         }
2289       stmt = op;
2290       /* FALLTHRU */
2291
2292     case MODIFY_EXPR:
2293       op = TREE_OPERAND (stmt, 1);
2294       if (TREE_CODE (op) == WITH_SIZE_EXPR)
2295         stmt = op;
2296       TREE_OPERAND (stmt, 1) = expr;
2297       break;
2298
2299     case COND_EXPR:
2300       COND_EXPR_COND (stmt) = expr;
2301       break;
2302     case SWITCH_EXPR:
2303       SWITCH_COND (stmt) = expr;
2304       break;
2305     case GOTO_EXPR:
2306       GOTO_DESTINATION (stmt) = expr;
2307       break;
2308     case LABEL_EXPR:
2309       LABEL_EXPR_LABEL (stmt) = expr;
2310       break;
2311
2312     default:
2313       /* Replace the whole statement with EXPR.  If EXPR has no side
2314          effects, then replace *STMT_P with an empty statement.  */
2315       ann = stmt_ann (stmt);
2316       *stmt_p = TREE_SIDE_EFFECTS (expr) ? expr : build_empty_stmt ();
2317       (*stmt_p)->common.ann = (tree_ann_t) ann;
2318
2319       if (TREE_SIDE_EFFECTS (expr))
2320         {
2321           def_optype defs;
2322           v_may_def_optype v_may_defs;
2323           v_must_def_optype v_must_defs;
2324           size_t i;
2325
2326           /* Fix all the SSA_NAMEs created by *STMT_P to point to its new
2327              replacement.  */
2328           defs = DEF_OPS (ann);
2329           for (i = 0; i < NUM_DEFS (defs); i++)
2330             {
2331               tree var = DEF_OP (defs, i);
2332               if (TREE_CODE (var) == SSA_NAME)
2333                 SSA_NAME_DEF_STMT (var) = *stmt_p;
2334             }
2335
2336           v_may_defs = V_MAY_DEF_OPS (ann);
2337           for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
2338             {
2339               tree var = V_MAY_DEF_RESULT (v_may_defs, i);
2340               if (TREE_CODE (var) == SSA_NAME)
2341                 SSA_NAME_DEF_STMT (var) = *stmt_p;
2342             }
2343             
2344           v_must_defs = V_MUST_DEF_OPS (ann);
2345           for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
2346             {
2347               tree var = V_MUST_DEF_OP (v_must_defs, i);
2348               if (TREE_CODE (var) == SSA_NAME)
2349                 SSA_NAME_DEF_STMT (var) = *stmt_p;
2350             }
2351         }
2352       break;
2353     }
2354
2355   return true;
2356 }
2357
2358
2359 /* Return a default value for variable VAR using the following rules:
2360
2361    1- Function arguments are considered VARYING.
2362    
2363    2- Global and static variables that are declared constant are
2364       considered CONSTANT.
2365
2366    3- Any other virtually defined variable is considered UNKNOWN_VAL.
2367
2368    4- Any other value is considered UNDEFINED.  This is useful when
2369       considering PHI nodes.  PHI arguments that are undefined do not
2370       change the constant value of the PHI node, which allows for more
2371       constants to be propagated.  */
2372
2373 static value
2374 get_default_value (tree var)
2375 {
2376   value val;
2377   tree sym;
2378
2379   if (TREE_CODE (var) == SSA_NAME)
2380     sym = SSA_NAME_VAR (var);
2381   else
2382     {
2383 #ifdef ENABLE_CHECKING
2384       if (!DECL_P (var))
2385         abort ();
2386 #endif
2387       sym = var;
2388     }
2389
2390   val.lattice_val = UNDEFINED;
2391   val.const_val = NULL_TREE;
2392
2393   if (TREE_CODE (sym) == PARM_DECL || TREE_THIS_VOLATILE (sym))
2394     {
2395       /* Function arguments and volatile variables are considered VARYING.  */
2396       val.lattice_val = VARYING;
2397     }
2398   else if (TREE_STATIC (sym))
2399     {
2400       /* Globals and static variables are considered UNKNOWN_VAL,
2401          unless they are declared 'const'.  */
2402       if (TREE_READONLY (sym)
2403           && DECL_INITIAL (sym)
2404           && is_gimple_min_invariant (DECL_INITIAL (sym)))
2405         {
2406           val.lattice_val = CONSTANT;
2407           val.const_val = DECL_INITIAL (sym);
2408         }
2409       else
2410         {
2411           val.const_val = NULL_TREE;
2412           val.lattice_val = UNKNOWN_VAL;
2413         }
2414     }
2415   else if (!is_gimple_reg (sym))
2416     {
2417       val.const_val = NULL_TREE;
2418       val.lattice_val = UNKNOWN_VAL;
2419     }
2420   else
2421     {
2422       enum tree_code code;
2423       tree stmt = SSA_NAME_DEF_STMT (var);
2424
2425       if (!IS_EMPTY_STMT (stmt))
2426         {
2427           code = TREE_CODE (stmt);
2428           if (code != MODIFY_EXPR && code != PHI_NODE)
2429             val.lattice_val = VARYING;
2430         }
2431     }
2432
2433   return val;
2434 }
2435
2436
2437 /* Fold builtin call FN in statement STMT.  If it cannot be folded into a
2438    constant, return NULL_TREE.  Otherwise, return its constant value.  */
2439
2440 static tree
2441 ccp_fold_builtin (tree stmt, tree fn)
2442 {
2443   tree result, strlen_val[2];
2444   tree callee, arglist, a;
2445   int strlen_arg, i;
2446   bitmap visited;
2447   bool ignore;
2448
2449   ignore = TREE_CODE (stmt) != MODIFY_EXPR;
2450
2451   /* First try the generic builtin folder.  If that succeeds, return the
2452      result directly.  */
2453   result = fold_builtin (fn, ignore);
2454   if (result)
2455   {
2456     if (ignore)
2457       STRIP_NOPS (result);
2458     return result;
2459   }
2460
2461   /* Ignore MD builtins.  */
2462   callee = get_callee_fndecl (fn);
2463   if (DECL_BUILT_IN_CLASS (callee) == BUILT_IN_MD)
2464     return NULL_TREE;
2465
2466   /* If the builtin could not be folded, and it has no argument list,
2467      we're done.  */
2468   arglist = TREE_OPERAND (fn, 1);
2469   if (!arglist)
2470     return NULL_TREE;
2471
2472   /* Limit the work only for builtins we know how to simplify.  */
2473   switch (DECL_FUNCTION_CODE (callee))
2474     {
2475     case BUILT_IN_STRLEN:
2476     case BUILT_IN_FPUTS:
2477     case BUILT_IN_FPUTS_UNLOCKED:
2478       strlen_arg = 1;
2479       break;
2480     case BUILT_IN_STRCPY:
2481     case BUILT_IN_STRNCPY:
2482       strlen_arg = 2;
2483       break;
2484     default:
2485       return NULL_TREE;
2486     }
2487
2488   /* Try to use the dataflow information gathered by the CCP process.  */
2489   visited = BITMAP_XMALLOC ();
2490
2491   memset (strlen_val, 0, sizeof (strlen_val));
2492   for (i = 0, a = arglist;
2493        strlen_arg;
2494        i++, strlen_arg >>= 1, a = TREE_CHAIN (a))
2495     if (strlen_arg & 1)
2496       {
2497         bitmap_clear (visited);
2498         if (!get_strlen (TREE_VALUE (a), &strlen_val[i], visited))
2499           strlen_val[i] = NULL_TREE;
2500       }
2501
2502   BITMAP_XFREE (visited);
2503
2504   result = NULL_TREE;
2505   switch (DECL_FUNCTION_CODE (callee))
2506     {
2507     case BUILT_IN_STRLEN:
2508       if (strlen_val[0])
2509         {
2510           tree new = fold_convert (TREE_TYPE (fn), strlen_val[0]);
2511
2512           /* If the result is not a valid gimple value, or not a cast
2513              of a valid gimple value, then we can not use the result.  */
2514           if (is_gimple_val (new)
2515               || (is_gimple_cast (new)
2516                   && is_gimple_val (TREE_OPERAND (new, 0))))
2517             return new;
2518         }
2519       break;
2520
2521     case BUILT_IN_STRCPY:
2522       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
2523         result = fold_builtin_strcpy (fn, strlen_val[1]);
2524       break;
2525
2526     case BUILT_IN_STRNCPY:
2527       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
2528         result = fold_builtin_strncpy (fn, strlen_val[1]);
2529       break;
2530
2531     case BUILT_IN_FPUTS:
2532       result = fold_builtin_fputs (arglist,
2533                                    TREE_CODE (stmt) != MODIFY_EXPR, 0,
2534                                    strlen_val[0]);
2535       break;
2536
2537     case BUILT_IN_FPUTS_UNLOCKED:
2538       result = fold_builtin_fputs (arglist,
2539                                    TREE_CODE (stmt) != MODIFY_EXPR, 1,
2540                                    strlen_val[0]);
2541       break;
2542
2543     default:
2544       abort ();
2545     }
2546
2547   if (result && ignore)
2548     result = fold_ignored_result (result);
2549   return result;
2550 }
2551
2552
2553 /* Return the string length of ARG in LENGTH.  If ARG is an SSA name variable,
2554    follow its use-def chains.  If LENGTH is not NULL and its value is not
2555    equal to the length we determine, or if we are unable to determine the
2556    length, return false.  VISITED is a bitmap of visited variables.  */
2557
2558 static bool
2559 get_strlen (tree arg, tree *length, bitmap visited)
2560 {
2561   tree var, def_stmt, val;
2562   
2563   if (TREE_CODE (arg) != SSA_NAME)
2564     {
2565       val = c_strlen (arg, 1);
2566       if (!val)
2567         return false;
2568
2569       if (*length && simple_cst_equal (val, *length) != 1)
2570         return false;
2571
2572       *length = val;
2573       return true;
2574     }
2575
2576   /* If we were already here, break the infinite cycle.  */
2577   if (bitmap_bit_p (visited, SSA_NAME_VERSION (arg)))
2578     return true;
2579   bitmap_set_bit (visited, SSA_NAME_VERSION (arg));
2580
2581   var = arg;
2582   def_stmt = SSA_NAME_DEF_STMT (var);
2583
2584   switch (TREE_CODE (def_stmt))
2585     {
2586       case MODIFY_EXPR:
2587         {
2588           tree len, rhs;
2589           
2590           /* The RHS of the statement defining VAR must either have a
2591              constant length or come from another SSA_NAME with a constant
2592              length.  */
2593           rhs = TREE_OPERAND (def_stmt, 1);
2594           STRIP_NOPS (rhs);
2595           if (TREE_CODE (rhs) == SSA_NAME)
2596             return get_strlen (rhs, length, visited);
2597
2598           /* See if the RHS is a constant length.  */
2599           len = c_strlen (rhs, 1);
2600           if (len)
2601             {
2602               if (*length && simple_cst_equal (len, *length) != 1)
2603                 return false;
2604
2605               *length = len;
2606               return true;
2607             }
2608
2609           break;
2610         }
2611
2612       case PHI_NODE:
2613         {
2614           /* All the arguments of the PHI node must have the same constant
2615              length.  */
2616           int i;
2617
2618           for (i = 0; i < PHI_NUM_ARGS (def_stmt); i++)
2619             {
2620               tree arg = PHI_ARG_DEF (def_stmt, i);
2621
2622               /* If this PHI has itself as an argument, we cannot
2623                  determine the string length of this argument.  However,
2624                  if we can find a constant string length for the other
2625                  PHI args then we can still be sure that this is a
2626                  constant string length.  So be optimistic and just
2627                  continue with the next argument.  */
2628               if (arg == PHI_RESULT (def_stmt))
2629                 continue;
2630
2631               if (!get_strlen (arg, length, visited))
2632                 return false;
2633             }
2634
2635           return true;
2636         }
2637
2638       default:
2639         break;
2640     }
2641
2642
2643   return false;
2644 }
2645
2646 \f
2647 /* A simple pass that attempts to fold all builtin functions.  This pass
2648    is run after we've propagated as many constants as we can.  */
2649
2650 static void
2651 execute_fold_all_builtins (void)
2652 {
2653   basic_block bb;
2654   FOR_EACH_BB (bb)
2655     {
2656       block_stmt_iterator i;
2657       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
2658         {
2659           tree *stmtp = bsi_stmt_ptr (i);
2660           tree call = get_rhs (*stmtp);
2661           tree callee, result;
2662
2663           if (!call || TREE_CODE (call) != CALL_EXPR)
2664             continue;
2665           callee = get_callee_fndecl (call);
2666           if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
2667             continue;
2668
2669           result = ccp_fold_builtin (*stmtp, call);
2670           if (!result)
2671             switch (DECL_FUNCTION_CODE (callee))
2672               {
2673               case BUILT_IN_CONSTANT_P:
2674                 /* Resolve __builtin_constant_p.  If it hasn't been
2675                    folded to integer_one_node by now, it's fairly
2676                    certain that the value simply isn't constant.  */
2677                 result = integer_zero_node;
2678                 break;
2679
2680               default:
2681                 continue;
2682               }
2683
2684           if (dump_file && (dump_flags & TDF_DETAILS))
2685             {
2686               fprintf (dump_file, "Simplified\n  ");
2687               print_generic_stmt (dump_file, *stmtp, dump_flags);
2688             }
2689
2690           if (set_rhs (stmtp, result))
2691             modify_stmt (*stmtp);
2692
2693           if (dump_file && (dump_flags & TDF_DETAILS))
2694             {
2695               fprintf (dump_file, "to\n  ");
2696               print_generic_stmt (dump_file, *stmtp, dump_flags);
2697               fprintf (dump_file, "\n");
2698             }
2699         }
2700     }
2701 }
2702
2703 struct tree_opt_pass pass_fold_builtins = 
2704 {
2705   "fab",                                /* name */
2706   NULL,                                 /* gate */
2707   execute_fold_all_builtins,            /* execute */
2708   NULL,                                 /* sub */
2709   NULL,                                 /* next */
2710   0,                                    /* static_pass_number */
2711   0,                                    /* tv_id */
2712   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2713   0,                                    /* properties_provided */
2714   0,                                    /* properties_destroyed */
2715   0,                                    /* todo_flags_start */
2716   TODO_dump_func | TODO_verify_ssa      /* todo_flags_finish */
2717 };
2718
2719
2720 #include "gt-tree-ssa-ccp.h"