* tree-ssa-ccp.c (ccp_fold): Remove code that produces
[official-gcc.git] / gcc / tree-ssa-ccp.c
blob01b608bd50df0117104ba5ad5aff14ee766e1380
1 /* Conditional constant propagation pass for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005
3 Free Software Foundation, Inc.
4 Adapted from original RTL SSA-CCP by Daniel Berlin <dberlin@dberlin.org>
5 Adapted to GIMPLE trees by Diego Novillo <dnovillo@redhat.com>
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING. If not, write to the Free
21 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 02111-1307, USA. */
24 /* Conditional constant propagation (CCP) is based on the SSA
25 propagation engine (tree-ssa-propagate.c). Constant assignments of
26 the form VAR = CST are propagated from the assignments into uses of
27 VAR, which in turn may generate new constants. The simulation uses
28 a four level lattice to keep track of constant values associated
29 with SSA names. Given an SSA name V_i, it may take one of the
30 following values:
32 UNINITIALIZED -> This is the default starting value. V_i
33 has not been processed yet.
35 UNDEFINED -> V_i is a local variable whose definition
36 has not been processed yet. Therefore we
37 don't yet know if its value is a constant
38 or not.
40 CONSTANT -> V_i has been found to hold a constant
41 value C.
43 VARYING -> V_i cannot take a constant value, or if it
44 does, it is not possible to determine it
45 at compile time.
47 The core of SSA-CCP is in ccp_visit_stmt and ccp_visit_phi_node:
49 1- In ccp_visit_stmt, we are interested in assignments whose RHS
50 evaluates into a constant and conditional jumps whose predicate
51 evaluates into a boolean true or false. When an assignment of
52 the form V_i = CONST is found, V_i's lattice value is set to
53 CONSTANT and CONST is associated with it. This causes the
54 propagation engine to add all the SSA edges coming out the
55 assignment into the worklists, so that statements that use V_i
56 can be visited.
58 If the statement is a conditional with a constant predicate, we
59 mark the outgoing edges as executable or not executable
60 depending on the predicate's value. This is then used when
61 visiting PHI nodes to know when a PHI argument can be ignored.
64 2- In ccp_visit_phi_node, if all the PHI arguments evaluate to the
65 same constant C, then the LHS of the PHI is set to C. This
66 evaluation is known as the "meet operation". Since one of the
67 goals of this evaluation is to optimistically return constant
68 values as often as possible, it uses two main short cuts:
70 - If an argument is flowing in through a non-executable edge, it
71 is ignored. This is useful in cases like this:
73 if (PRED)
74 a_9 = 3;
75 else
76 a_10 = 100;
77 a_11 = PHI (a_9, a_10)
79 If PRED is known to always evaluate to false, then we can
80 assume that a_11 will always take its value from a_10, meaning
81 that instead of consider it VARYING (a_9 and a_10 have
82 different values), we can consider it CONSTANT 100.
84 - If an argument has an UNDEFINED value, then it does not affect
85 the outcome of the meet operation. If a variable V_i has an
86 UNDEFINED value, it means that either its defining statement
87 hasn't been visited yet or V_i has no defining statement, in
88 which case the original symbol 'V' is being used
89 uninitialized. Since 'V' is a local variable, the compiler
90 may assume any initial value for it.
93 After propagation, every variable V_i that ends up with a lattice
94 value of CONSTANT will have the associated constant value in the
95 array CONST_VAL[i].VALUE. That is fed into substitute_and_fold for
96 final substitution and folding.
99 Constant propagation in stores and loads (STORE-CCP)
100 ----------------------------------------------------
102 While CCP has all the logic to propagate constants in GIMPLE
103 registers, it is missing the ability to associate constants with
104 stores and loads (i.e., pointer dereferences, structures and
105 global/aliased variables). We don't keep loads and stores in
106 SSA, but we do build a factored use-def web for them (in the
107 virtual operands).
109 For instance, consider the following code fragment:
111 struct A a;
112 const int B = 42;
114 void foo (int i)
116 if (i > 10)
117 a.a = 42;
118 else
120 a.b = 21;
121 a.a = a.b + 21;
124 if (a.a != B)
125 never_executed ();
128 We should be able to deduce that the predicate 'a.a != B' is always
129 false. To achieve this, we associate constant values to the SSA
130 names in the V_MAY_DEF and V_MUST_DEF operands for each store.
131 Additionally, since we also glob partial loads/stores with the base
132 symbol, we also keep track of the memory reference where the
133 constant value was stored (in the MEM_REF field of PROP_VALUE_T).
134 For instance,
136 # a_5 = V_MAY_DEF <a_4>
137 a.a = 2;
139 # VUSE <a_5>
140 x_3 = a.b;
142 In the example above, CCP will associate value '2' with 'a_5', but
143 it would be wrong to replace the load from 'a.b' with '2', because
144 '2' had been stored into a.a.
146 To support STORE-CCP, it is necessary to add a new value to the
147 constant propagation lattice. When evaluating a load for a memory
148 reference we can no longer assume a value of UNDEFINED if we
149 haven't seen a preceding store to the same memory location.
150 Consider, for instance global variables:
152 int A;
154 foo (int i)
156 if (i_3 > 10)
157 A_4 = 3;
158 # A_5 = PHI (A_4, A_2);
160 # VUSE <A_5>
161 A.0_6 = A;
163 return A.0_6;
166 The value of A_2 cannot be assumed to be UNDEFINED, as it may have
167 been defined outside of foo. If we were to assume it UNDEFINED, we
168 would erroneously optimize the above into 'return 3;'. Therefore,
169 when doing STORE-CCP, we introduce a fifth lattice value
170 (UNKNOWN_VAL), which overrides any other value when computing the
171 meet operation in PHI nodes.
173 Though STORE-CCP is not too expensive, it does have to do more work
174 than regular CCP, so it is only enabled at -O2. Both regular CCP
175 and STORE-CCP use the exact same algorithm. The only distinction
176 is that when doing STORE-CCP, the boolean variable DO_STORE_CCP is
177 set to true. This affects the evaluation of statements and PHI
178 nodes.
180 References:
182 Constant propagation with conditional branches,
183 Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
185 Building an Optimizing Compiler,
186 Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
188 Advanced Compiler Design and Implementation,
189 Steven Muchnick, Morgan Kaufmann, 1997, Section 12.6 */
191 #include "config.h"
192 #include "system.h"
193 #include "coretypes.h"
194 #include "tm.h"
195 #include "tree.h"
196 #include "flags.h"
197 #include "rtl.h"
198 #include "tm_p.h"
199 #include "ggc.h"
200 #include "basic-block.h"
201 #include "output.h"
202 #include "errors.h"
203 #include "expr.h"
204 #include "function.h"
205 #include "diagnostic.h"
206 #include "timevar.h"
207 #include "tree-dump.h"
208 #include "tree-flow.h"
209 #include "tree-pass.h"
210 #include "tree-ssa-propagate.h"
211 #include "langhooks.h"
212 #include "target.h"
215 /* Possible lattice values. */
216 typedef enum
218 UNINITIALIZED = 0,
219 UNDEFINED,
220 UNKNOWN_VAL,
221 CONSTANT,
222 VARYING
223 } ccp_lattice_t;
225 /* Array of propagated constant values. After propagation,
226 CONST_VAL[I].VALUE holds the constant value for SSA_NAME(I). If
227 the constant is held in an SSA name representing a memory store
228 (i.e., a V_MAY_DEF or V_MUST_DEF), CONST_VAL[I].MEM_REF will
229 contain the actual memory reference used to store (i.e., the LHS of
230 the assignment doing the store). */
231 prop_value_t *const_val;
233 /* True if we are also propagating constants in stores and loads. */
234 static bool do_store_ccp;
236 /* Dump constant propagation value VAL to file OUTF prefixed by PREFIX. */
238 static void
239 dump_lattice_value (FILE *outf, const char *prefix, prop_value_t val)
241 switch (val.lattice_val)
243 case UNINITIALIZED:
244 fprintf (outf, "%sUNINITIALIZED", prefix);
245 break;
246 case UNDEFINED:
247 fprintf (outf, "%sUNDEFINED", prefix);
248 break;
249 case VARYING:
250 fprintf (outf, "%sVARYING", prefix);
251 break;
252 case UNKNOWN_VAL:
253 fprintf (outf, "%sUNKNOWN_VAL", prefix);
254 break;
255 case CONSTANT:
256 fprintf (outf, "%sCONSTANT ", prefix);
257 print_generic_expr (outf, val.value, dump_flags);
258 break;
259 default:
260 gcc_unreachable ();
265 /* Print lattice value VAL to stderr. */
267 void debug_lattice_value (prop_value_t val);
269 void
270 debug_lattice_value (prop_value_t val)
272 dump_lattice_value (stderr, "", val);
273 fprintf (stderr, "\n");
277 /* Compute a default value for variable VAR and store it in the
278 CONST_VAL array. The following rules are used to get default
279 values:
281 1- Global and static variables that are declared constant are
282 considered CONSTANT.
284 2- Any other value is considered UNDEFINED. This is useful when
285 considering PHI nodes. PHI arguments that are undefined do not
286 change the constant value of the PHI node, which allows for more
287 constants to be propagated.
289 3- If SSA_NAME_VALUE is set and it is a constant, its value is
290 used.
292 4- Variables defined by statements other than assignments and PHI
293 nodes are considered VARYING.
295 5- Variables that are not GIMPLE registers are considered
296 UNKNOWN_VAL, which is really a stronger version of UNDEFINED.
297 It's used to avoid the short circuit evaluation implied by
298 UNDEFINED in ccp_lattice_meet. */
300 static prop_value_t
301 get_default_value (tree var)
303 tree sym = SSA_NAME_VAR (var);
304 prop_value_t val = { UNINITIALIZED, NULL_TREE, NULL_TREE };
306 if (!do_store_ccp && !is_gimple_reg (var))
308 /* Short circuit for regular CCP. We are not interested in any
309 non-register when DO_STORE_CCP is false. */
310 val.lattice_val = VARYING;
312 else if (SSA_NAME_VALUE (var)
313 && is_gimple_min_invariant (SSA_NAME_VALUE (var)))
315 val.lattice_val = CONSTANT;
316 val.value = SSA_NAME_VALUE (var);
318 else if (TREE_STATIC (sym)
319 && TREE_READONLY (sym)
320 && DECL_INITIAL (sym)
321 && is_gimple_min_invariant (DECL_INITIAL (sym)))
323 /* Globals and static variables declared 'const' take their
324 initial value. */
325 val.lattice_val = CONSTANT;
326 val.value = DECL_INITIAL (sym);
327 val.mem_ref = sym;
329 else
331 tree stmt = SSA_NAME_DEF_STMT (var);
333 if (IS_EMPTY_STMT (stmt))
335 /* Variables defined by an empty statement are those used
336 before being initialized. If VAR is a local variable, we
337 can assume initially that it is UNDEFINED. If we are
338 doing STORE-CCP, function arguments and non-register
339 variables are initially UNKNOWN_VAL, because we cannot
340 discard the value incoming from outside of this function
341 (see ccp_lattice_meet for details). */
342 if (is_gimple_reg (sym) && TREE_CODE (sym) != PARM_DECL)
343 val.lattice_val = UNDEFINED;
344 else if (do_store_ccp)
345 val.lattice_val = UNKNOWN_VAL;
346 else
347 val.lattice_val = VARYING;
349 else if (TREE_CODE (stmt) == MODIFY_EXPR
350 || TREE_CODE (stmt) == PHI_NODE)
352 /* Any other variable defined by an assignment or a PHI node
353 is considered UNDEFINED (or UNKNOWN_VAL if VAR is not a
354 GIMPLE register). */
355 val.lattice_val = is_gimple_reg (sym) ? UNDEFINED : UNKNOWN_VAL;
357 else
359 /* Otherwise, VAR will never take on a constant value. */
360 val.lattice_val = VARYING;
364 return val;
368 /* Get the constant value associated with variable VAR. If
369 MAY_USE_DEFAULT_P is true, call get_default_value on variables that
370 have the lattice value UNINITIALIZED. */
372 static prop_value_t *
373 get_value (tree var, bool may_use_default_p)
375 prop_value_t *val = &const_val[SSA_NAME_VERSION (var)];
376 if (may_use_default_p && val->lattice_val == UNINITIALIZED)
377 *val = get_default_value (var);
379 return val;
383 /* Set the value for variable VAR to NEW_VAL. Return true if the new
384 value is different from VAR's previous value. */
386 static bool
387 set_lattice_value (tree var, prop_value_t new_val)
389 prop_value_t *old_val = get_value (var, false);
391 /* Lattice transitions must always be monotonically increasing in
392 value. We allow two exceptions:
394 1- If *OLD_VAL and NEW_VAL are the same, return false to
395 inform the caller that this was a non-transition.
397 2- If we are doing store-ccp (i.e., DOING_STORE_CCP is true),
398 allow CONSTANT->UNKNOWN_VAL. The UNKNOWN_VAL state is a
399 special type of UNDEFINED state which prevents the short
400 circuit evaluation of PHI arguments (see ccp_visit_phi_node
401 and ccp_lattice_meet). */
402 gcc_assert (old_val->lattice_val <= new_val.lattice_val
403 || (old_val->lattice_val == new_val.lattice_val
404 && old_val->value == new_val.value
405 && old_val->mem_ref == new_val.mem_ref)
406 || (do_store_ccp
407 && old_val->lattice_val == CONSTANT
408 && new_val.lattice_val == UNKNOWN_VAL));
410 if (old_val->lattice_val != new_val.lattice_val)
412 if (dump_file && (dump_flags & TDF_DETAILS))
414 dump_lattice_value (dump_file, "Lattice value changed to ", new_val);
415 fprintf (dump_file, ". %sdding SSA edges to worklist.\n",
416 new_val.lattice_val != UNDEFINED ? "A" : "Not a");
419 *old_val = new_val;
421 /* Transitions UNINITIALIZED -> UNDEFINED are never interesting
422 for propagation purposes. In these cases return false to
423 avoid doing useless work. */
424 return (new_val.lattice_val != UNDEFINED);
427 return false;
431 /* Return the likely CCP lattice value for STMT.
433 If STMT has no operands, then return CONSTANT.
435 Else if any operands of STMT are undefined, then return UNDEFINED.
437 Else if any operands of STMT are constants, then return CONSTANT.
439 Else return VARYING. */
441 static ccp_lattice_t
442 likely_value (tree stmt)
444 bool found_constant;
445 stmt_ann_t ann;
446 tree use;
447 ssa_op_iter iter;
449 ann = stmt_ann (stmt);
451 /* If the statement has volatile operands, it won't fold to a
452 constant value. */
453 if (ann->has_volatile_ops)
454 return VARYING;
456 /* If we are not doing store-ccp, statements with loads
457 and/or stores will never fold into a constant. */
458 if (!do_store_ccp
459 && (ann->makes_aliased_stores
460 || ann->makes_aliased_loads
461 || !ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS)))
462 return VARYING;
465 /* A CALL_EXPR is assumed to be varying. NOTE: This may be overly
466 conservative, in the presence of const and pure calls. */
467 if (get_call_expr_in (stmt) != NULL_TREE)
468 return VARYING;
470 /* Anything other than assignments and conditional jumps are not
471 interesting for CCP. */
472 if (TREE_CODE (stmt) != MODIFY_EXPR
473 && TREE_CODE (stmt) != COND_EXPR
474 && TREE_CODE (stmt) != SWITCH_EXPR)
475 return VARYING;
477 found_constant = false;
478 FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE|SSA_OP_VUSE)
480 prop_value_t *val = get_value (use, true);
482 if (val->lattice_val == VARYING)
483 return VARYING;
485 if (val->lattice_val == UNKNOWN_VAL)
487 /* UNKNOWN_VAL is invalid when not doing STORE-CCP. */
488 gcc_assert (do_store_ccp);
489 return UNKNOWN_VAL;
492 if (val->lattice_val == CONSTANT)
493 found_constant = true;
496 if (found_constant
497 || ZERO_SSA_OPERANDS (stmt, SSA_OP_USE)
498 || ZERO_SSA_OPERANDS (stmt, SSA_OP_VUSE))
499 return CONSTANT;
501 return UNDEFINED;
505 /* Initialize local data structures for CCP. */
507 static void
508 ccp_initialize (void)
510 basic_block bb;
512 const_val = xmalloc (num_ssa_names * sizeof (*const_val));
513 memset (const_val, 0, num_ssa_names * sizeof (*const_val));
515 /* Initialize simulation flags for PHI nodes and statements. */
516 FOR_EACH_BB (bb)
518 block_stmt_iterator i;
520 for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
522 bool is_varying = false;
523 tree stmt = bsi_stmt (i);
525 if (likely_value (stmt) == VARYING)
528 tree def;
529 ssa_op_iter iter;
531 /* If the statement will not produce a constant, mark
532 all its outputs VARYING. */
533 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
534 get_value (def, false)->lattice_val = VARYING;
536 /* Never mark conditional jumps with DONT_SIMULATE_AGAIN,
537 otherwise the propagator will never add the outgoing
538 control edges. */
539 if (TREE_CODE (stmt) != COND_EXPR
540 && TREE_CODE (stmt) != SWITCH_EXPR)
541 is_varying = true;
544 DONT_SIMULATE_AGAIN (stmt) = is_varying;
548 /* Now process PHI nodes. */
549 FOR_EACH_BB (bb)
551 tree phi;
553 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
555 int i;
556 tree arg;
557 prop_value_t *val = get_value (PHI_RESULT (phi), false);
559 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
561 arg = PHI_ARG_DEF (phi, i);
563 if (TREE_CODE (arg) == SSA_NAME
564 && get_value (arg, false)->lattice_val == VARYING)
566 val->lattice_val = VARYING;
567 break;
571 DONT_SIMULATE_AGAIN (phi) = (val->lattice_val == VARYING);
577 /* Do final substitution of propagated values, cleanup the flowgraph and
578 free allocated storage. */
580 static void
581 ccp_finalize (void)
583 /* Perform substitutions based on the known constant values. */
584 substitute_and_fold (const_val);
586 free (const_val);
590 /* Compute the meet operator between *VAL1 and *VAL2. Store the result
591 in VAL1.
593 any M UNDEFINED = any
594 any M UNKNOWN_VAL = UNKNOWN_VAL
595 any M VARYING = VARYING
596 Ci M Cj = Ci if (i == j)
597 Ci M Cj = VARYING if (i != j)
599 Lattice values UNKNOWN_VAL and UNDEFINED are similar but have
600 different semantics at PHI nodes. Both values imply that we don't
601 know whether the variable is constant or not. However, UNKNOWN_VAL
602 values override all others. For instance, suppose that A is a
603 global variable:
605 +------+
607 | / \
608 | / \
609 | | A_1 = 4
610 | \ /
611 | \ /
612 | A_3 = PHI (A_2, A_1)
613 | ... = A_3
615 +----+
617 If the edge into A_2 is not executable, the first visit to A_3 will
618 yield the constant 4. But the second visit to A_3 will be with A_2
619 in state UNKNOWN_VAL. We can no longer conclude that A_3 is 4
620 because A_2 may have been set in another function. If we had used
621 the lattice value UNDEFINED, we would have had wrongly concluded
622 that A_3 is 4. */
625 static void
626 ccp_lattice_meet (prop_value_t *val1, prop_value_t *val2)
628 if (val1->lattice_val == UNDEFINED)
630 /* UNDEFINED M any = any */
631 *val1 = *val2;
633 else if (val2->lattice_val == UNDEFINED)
635 /* any M UNDEFINED = any
636 Nothing to do. VAL1 already contains the value we want. */
639 else if (val1->lattice_val == UNKNOWN_VAL
640 || val2->lattice_val == UNKNOWN_VAL)
642 /* UNKNOWN_VAL values are invalid if we are not doing STORE-CCP. */
643 gcc_assert (do_store_ccp);
645 /* any M UNKNOWN_VAL = UNKNOWN_VAL. */
646 val1->lattice_val = UNKNOWN_VAL;
647 val1->value = NULL_TREE;
648 val1->mem_ref = NULL_TREE;
650 else if (val1->lattice_val == VARYING
651 || val2->lattice_val == VARYING)
653 /* any M VARYING = VARYING. */
654 val1->lattice_val = VARYING;
655 val1->value = NULL_TREE;
656 val1->mem_ref = NULL_TREE;
658 else if (val1->lattice_val == CONSTANT
659 && val2->lattice_val == CONSTANT
660 && simple_cst_equal (val1->value, val2->value) == 1
661 && (!do_store_ccp
662 || simple_cst_equal (val1->mem_ref, val2->mem_ref) == 1))
664 /* Ci M Cj = Ci if (i == j)
665 Ci M Cj = VARYING if (i != j)
667 If these two values come from memory stores, make sure that
668 they come from the same memory reference. */
669 val1->lattice_val = CONSTANT;
670 val1->value = val1->value;
671 val1->mem_ref = val1->mem_ref;
673 else
675 /* Any other combination is VARYING. */
676 val1->lattice_val = VARYING;
677 val1->value = NULL_TREE;
678 val1->mem_ref = NULL_TREE;
683 /* Loop through the PHI_NODE's parameters for BLOCK and compare their
684 lattice values to determine PHI_NODE's lattice value. The value of a
685 PHI node is determined calling ccp_lattice_meet with all the arguments
686 of the PHI node that are incoming via executable edges. */
688 static enum ssa_prop_result
689 ccp_visit_phi_node (tree phi)
691 int i;
692 prop_value_t *old_val, new_val;
694 if (dump_file && (dump_flags & TDF_DETAILS))
696 fprintf (dump_file, "\nVisiting PHI node: ");
697 print_generic_expr (dump_file, phi, dump_flags);
700 old_val = get_value (PHI_RESULT (phi), false);
701 switch (old_val->lattice_val)
703 case VARYING:
704 return SSA_PROP_VARYING;
706 case CONSTANT:
707 new_val = *old_val;
708 break;
710 case UNKNOWN_VAL:
711 /* To avoid the default value of UNKNOWN_VAL overriding
712 that of its possible constant arguments, temporarily
713 set the PHI node's default lattice value to be
714 UNDEFINED. If the PHI node's old value was UNKNOWN_VAL and
715 the new value is UNDEFINED, then we prevent the invalid
716 transition by not calling set_lattice_value. */
717 gcc_assert (do_store_ccp);
719 /* FALLTHRU */
721 case UNDEFINED:
722 case UNINITIALIZED:
723 new_val.lattice_val = UNDEFINED;
724 new_val.value = NULL_TREE;
725 new_val.mem_ref = NULL_TREE;
726 break;
728 default:
729 gcc_unreachable ();
732 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
734 /* Compute the meet operator over all the PHI arguments flowing
735 through executable edges. */
736 edge e = PHI_ARG_EDGE (phi, i);
738 if (dump_file && (dump_flags & TDF_DETAILS))
740 fprintf (dump_file,
741 "\n Argument #%d (%d -> %d %sexecutable)\n",
742 i, e->src->index, e->dest->index,
743 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
746 /* If the incoming edge is executable, Compute the meet operator for
747 the existing value of the PHI node and the current PHI argument. */
748 if (e->flags & EDGE_EXECUTABLE)
750 tree arg = PHI_ARG_DEF (phi, i);
751 prop_value_t arg_val;
753 if (is_gimple_min_invariant (arg))
755 arg_val.lattice_val = CONSTANT;
756 arg_val.value = arg;
757 arg_val.mem_ref = NULL_TREE;
759 else
760 arg_val = *(get_value (arg, true));
762 ccp_lattice_meet (&new_val, &arg_val);
764 if (dump_file && (dump_flags & TDF_DETAILS))
766 fprintf (dump_file, "\t");
767 print_generic_expr (dump_file, arg, dump_flags);
768 dump_lattice_value (dump_file, "\tValue: ", arg_val);
769 fprintf (dump_file, "\n");
772 if (new_val.lattice_val == VARYING)
773 break;
777 if (dump_file && (dump_flags & TDF_DETAILS))
779 dump_lattice_value (dump_file, "\n PHI node value: ", new_val);
780 fprintf (dump_file, "\n\n");
783 /* Check for an invalid change from UNKNOWN_VAL to UNDEFINED. */
784 if (do_store_ccp
785 && old_val->lattice_val == UNKNOWN_VAL
786 && new_val.lattice_val == UNDEFINED)
787 return SSA_PROP_NOT_INTERESTING;
789 /* Otherwise, make the transition to the new value. */
790 if (set_lattice_value (PHI_RESULT (phi), new_val))
792 if (new_val.lattice_val == VARYING)
793 return SSA_PROP_VARYING;
794 else
795 return SSA_PROP_INTERESTING;
797 else
798 return SSA_PROP_NOT_INTERESTING;
802 /* CCP specific front-end to the non-destructive constant folding
803 routines.
805 Attempt to simplify the RHS of STMT knowing that one or more
806 operands are constants.
808 If simplification is possible, return the simplified RHS,
809 otherwise return the original RHS. */
811 static tree
812 ccp_fold (tree stmt)
814 tree rhs = get_rhs (stmt);
815 enum tree_code code = TREE_CODE (rhs);
816 enum tree_code_class kind = TREE_CODE_CLASS (code);
817 tree retval = NULL_TREE;
819 if (TREE_CODE (rhs) == SSA_NAME)
821 /* If the RHS is an SSA_NAME, return its known constant value,
822 if any. */
823 return get_value (rhs, true)->value;
825 else if (do_store_ccp && stmt_makes_single_load (stmt))
827 /* If the RHS is a memory load, see if the VUSEs associated with
828 it are a valid constant for that memory load. */
829 prop_value_t *val = get_value_loaded_by (stmt, const_val);
830 if (val && simple_cst_equal (val->mem_ref, rhs) == 1)
831 return val->value;
832 else
833 return NULL_TREE;
836 /* Unary operators. Note that we know the single operand must
837 be a constant. So this should almost always return a
838 simplified RHS. */
839 if (kind == tcc_unary)
841 /* Handle unary operators which can appear in GIMPLE form. */
842 tree op0 = TREE_OPERAND (rhs, 0);
844 /* Simplify the operand down to a constant. */
845 if (TREE_CODE (op0) == SSA_NAME)
847 prop_value_t *val = get_value (op0, true);
848 if (val->lattice_val == CONSTANT)
849 op0 = get_value (op0, true)->value;
852 retval = fold_unary (code, TREE_TYPE (rhs), op0);
854 /* If we folded, but did not create an invariant, then we can not
855 use this expression. */
856 if (retval && ! is_gimple_min_invariant (retval))
857 return NULL;
860 /* Binary and comparison operators. We know one or both of the
861 operands are constants. */
862 else if (kind == tcc_binary
863 || kind == tcc_comparison
864 || code == TRUTH_AND_EXPR
865 || code == TRUTH_OR_EXPR
866 || code == TRUTH_XOR_EXPR)
868 /* Handle binary and comparison operators that can appear in
869 GIMPLE form. */
870 tree op0 = TREE_OPERAND (rhs, 0);
871 tree op1 = TREE_OPERAND (rhs, 1);
873 /* Simplify the operands down to constants when appropriate. */
874 if (TREE_CODE (op0) == SSA_NAME)
876 prop_value_t *val = get_value (op0, true);
877 if (val->lattice_val == CONSTANT)
878 op0 = val->value;
881 if (TREE_CODE (op1) == SSA_NAME)
883 prop_value_t *val = get_value (op1, true);
884 if (val->lattice_val == CONSTANT)
885 op1 = val->value;
888 retval = fold_binary (code, TREE_TYPE (rhs), op0, op1);
890 /* If we folded, but did not create an invariant, then we can not
891 use this expression. */
892 if (retval && ! is_gimple_min_invariant (retval))
893 return NULL;
896 /* We may be able to fold away calls to builtin functions if their
897 arguments are constants. */
898 else if (code == CALL_EXPR
899 && TREE_CODE (TREE_OPERAND (rhs, 0)) == ADDR_EXPR
900 && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0))
901 == FUNCTION_DECL)
902 && DECL_BUILT_IN (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0)))
904 if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_USE))
906 tree *orig, var;
907 tree fndecl, arglist;
908 size_t i = 0;
909 ssa_op_iter iter;
910 use_operand_p var_p;
912 /* Preserve the original values of every operand. */
913 orig = xmalloc (sizeof (tree) * NUM_SSA_OPERANDS (stmt, SSA_OP_USE));
914 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_USE)
915 orig[i++] = var;
917 /* Substitute operands with their values and try to fold. */
918 replace_uses_in (stmt, NULL, const_val);
919 fndecl = get_callee_fndecl (rhs);
920 arglist = TREE_OPERAND (rhs, 1);
921 retval = fold_builtin (fndecl, arglist, false);
923 /* Restore operands to their original form. */
924 i = 0;
925 FOR_EACH_SSA_USE_OPERAND (var_p, stmt, iter, SSA_OP_USE)
926 SET_USE (var_p, orig[i++]);
927 free (orig);
930 else
931 return rhs;
933 /* If we got a simplified form, see if we need to convert its type. */
934 if (retval)
935 return fold_convert (TREE_TYPE (rhs), retval);
937 /* No simplification was possible. */
938 return rhs;
942 /* Return the tree representing the element referenced by T if T is an
943 ARRAY_REF or COMPONENT_REF into constant aggregates. Return
944 NULL_TREE otherwise. */
946 static tree
947 fold_const_aggregate_ref (tree t)
949 prop_value_t *value;
950 tree base, ctor, idx, field, elt;
952 switch (TREE_CODE (t))
954 case ARRAY_REF:
955 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
956 DECL_INITIAL. If BASE is a nested reference into another
957 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
958 the inner reference. */
959 base = TREE_OPERAND (t, 0);
960 switch (TREE_CODE (base))
962 case VAR_DECL:
963 if (!TREE_READONLY (base)
964 || TREE_CODE (TREE_TYPE (base)) != ARRAY_TYPE
965 || !targetm.binds_local_p (base))
966 return NULL_TREE;
968 ctor = DECL_INITIAL (base);
969 break;
971 case ARRAY_REF:
972 case COMPONENT_REF:
973 ctor = fold_const_aggregate_ref (base);
974 break;
976 default:
977 return NULL_TREE;
980 if (ctor == NULL_TREE
981 || TREE_CODE (ctor) != CONSTRUCTOR
982 || !TREE_STATIC (ctor))
983 return NULL_TREE;
985 /* Get the index. If we have an SSA_NAME, try to resolve it
986 with the current lattice value for the SSA_NAME. */
987 idx = TREE_OPERAND (t, 1);
988 switch (TREE_CODE (idx))
990 case SSA_NAME:
991 if ((value = get_value (idx, true))
992 && value->lattice_val == CONSTANT
993 && TREE_CODE (value->value) == INTEGER_CST)
994 idx = value->value;
995 else
996 return NULL_TREE;
997 break;
999 case INTEGER_CST:
1000 break;
1002 default:
1003 return NULL_TREE;
1006 /* Whoo-hoo! I'll fold ya baby. Yeah! */
1007 for (elt = CONSTRUCTOR_ELTS (ctor);
1008 (elt && !tree_int_cst_equal (TREE_PURPOSE (elt), idx));
1009 elt = TREE_CHAIN (elt))
1012 if (elt)
1013 return TREE_VALUE (elt);
1014 break;
1016 case COMPONENT_REF:
1017 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
1018 DECL_INITIAL. If BASE is a nested reference into another
1019 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
1020 the inner reference. */
1021 base = TREE_OPERAND (t, 0);
1022 switch (TREE_CODE (base))
1024 case VAR_DECL:
1025 if (!TREE_READONLY (base)
1026 || TREE_CODE (TREE_TYPE (base)) != RECORD_TYPE
1027 || !targetm.binds_local_p (base))
1028 return NULL_TREE;
1030 ctor = DECL_INITIAL (base);
1031 break;
1033 case ARRAY_REF:
1034 case COMPONENT_REF:
1035 ctor = fold_const_aggregate_ref (base);
1036 break;
1038 default:
1039 return NULL_TREE;
1042 if (ctor == NULL_TREE
1043 || TREE_CODE (ctor) != CONSTRUCTOR
1044 || !TREE_STATIC (ctor))
1045 return NULL_TREE;
1047 field = TREE_OPERAND (t, 1);
1049 for (elt = CONSTRUCTOR_ELTS (ctor); elt; elt = TREE_CHAIN (elt))
1050 if (TREE_PURPOSE (elt) == field
1051 /* FIXME: Handle bit-fields. */
1052 && ! DECL_BIT_FIELD (TREE_PURPOSE (elt)))
1053 return TREE_VALUE (elt);
1054 break;
1056 default:
1057 break;
1060 return NULL_TREE;
1063 /* Evaluate statement STMT. */
1065 static prop_value_t
1066 evaluate_stmt (tree stmt)
1068 prop_value_t val;
1069 tree simplified;
1070 ccp_lattice_t likelyvalue = likely_value (stmt);
1072 val.mem_ref = NULL_TREE;
1074 /* If the statement is likely to have a CONSTANT result, then try
1075 to fold the statement to determine the constant value. */
1076 if (likelyvalue == CONSTANT)
1077 simplified = ccp_fold (stmt);
1078 /* If the statement is likely to have a VARYING result, then do not
1079 bother folding the statement. */
1080 else if (likelyvalue == VARYING)
1081 simplified = get_rhs (stmt);
1082 /* If the statement is an ARRAY_REF or COMPONENT_REF into constant
1083 aggregates, extract the referenced constant. Otherwise the
1084 statement is likely to have an UNDEFINED value, and there will be
1085 nothing to do. Note that fold_const_aggregate_ref returns
1086 NULL_TREE if the first case does not match. */
1087 else
1088 simplified = fold_const_aggregate_ref (get_rhs (stmt));
1090 if (simplified && is_gimple_min_invariant (simplified))
1092 /* The statement produced a constant value. */
1093 val.lattice_val = CONSTANT;
1094 val.value = simplified;
1096 else
1098 /* The statement produced a nonconstant value. If the statement
1099 had UNDEFINED operands, then the result of the statement
1100 should be UNDEFINED. Otherwise, the statement is VARYING. */
1101 val.lattice_val = (likelyvalue == UNDEFINED) ? UNDEFINED : VARYING;
1102 val.value = NULL_TREE;
1105 return val;
1109 /* Visit the assignment statement STMT. Set the value of its LHS to the
1110 value computed by the RHS and store LHS in *OUTPUT_P. If STMT
1111 creates virtual definitions, set the value of each new name to that
1112 of the RHS (if we can derive a constant out of the RHS). */
1114 static enum ssa_prop_result
1115 visit_assignment (tree stmt, tree *output_p)
1117 prop_value_t val;
1118 tree lhs, rhs;
1119 enum ssa_prop_result retval;
1121 lhs = TREE_OPERAND (stmt, 0);
1122 rhs = TREE_OPERAND (stmt, 1);
1124 if (TREE_CODE (rhs) == SSA_NAME)
1126 /* For a simple copy operation, we copy the lattice values. */
1127 prop_value_t *nval = get_value (rhs, true);
1128 val = *nval;
1130 else if (do_store_ccp && stmt_makes_single_load (stmt))
1132 /* Same as above, but the RHS is not a gimple register and yet
1133 has a known VUSE. If STMT is loading from the same memory
1134 location that created the SSA_NAMEs for the virtual operands,
1135 we can propagate the value on the RHS. */
1136 prop_value_t *nval = get_value_loaded_by (stmt, const_val);
1138 if (nval && simple_cst_equal (nval->mem_ref, rhs) == 1)
1139 val = *nval;
1140 else
1141 val = evaluate_stmt (stmt);
1143 else
1144 /* Evaluate the statement. */
1145 val = evaluate_stmt (stmt);
1147 /* If the original LHS was a VIEW_CONVERT_EXPR, modify the constant
1148 value to be a VIEW_CONVERT_EXPR of the old constant value.
1150 ??? Also, if this was a definition of a bitfield, we need to widen
1151 the constant value into the type of the destination variable. This
1152 should not be necessary if GCC represented bitfields properly. */
1154 tree orig_lhs = TREE_OPERAND (stmt, 0);
1156 if (TREE_CODE (orig_lhs) == VIEW_CONVERT_EXPR
1157 && val.lattice_val == CONSTANT)
1159 tree w = fold (build1 (VIEW_CONVERT_EXPR,
1160 TREE_TYPE (TREE_OPERAND (orig_lhs, 0)),
1161 val.value));
1163 orig_lhs = TREE_OPERAND (orig_lhs, 0);
1164 if (w && is_gimple_min_invariant (w))
1165 val.value = w;
1166 else
1168 val.lattice_val = VARYING;
1169 val.value = NULL;
1173 if (val.lattice_val == CONSTANT
1174 && TREE_CODE (orig_lhs) == COMPONENT_REF
1175 && DECL_BIT_FIELD (TREE_OPERAND (orig_lhs, 1)))
1177 tree w = widen_bitfield (val.value, TREE_OPERAND (orig_lhs, 1),
1178 orig_lhs);
1180 if (w && is_gimple_min_invariant (w))
1181 val.value = w;
1182 else
1184 val.lattice_val = VARYING;
1185 val.value = NULL_TREE;
1186 val.mem_ref = NULL_TREE;
1191 retval = SSA_PROP_NOT_INTERESTING;
1193 /* Set the lattice value of the statement's output. */
1194 if (TREE_CODE (lhs) == SSA_NAME)
1196 /* If STMT is an assignment to an SSA_NAME, we only have one
1197 value to set. */
1198 if (set_lattice_value (lhs, val))
1200 *output_p = lhs;
1201 if (val.lattice_val == VARYING)
1202 retval = SSA_PROP_VARYING;
1203 else
1204 retval = SSA_PROP_INTERESTING;
1207 else if (do_store_ccp && stmt_makes_single_store (stmt))
1209 /* Otherwise, set the names in V_MAY_DEF/V_MUST_DEF operands
1210 to the new constant value and mark the LHS as the memory
1211 reference associated with VAL. */
1212 ssa_op_iter i;
1213 tree vdef;
1214 bool changed;
1216 /* Stores cannot take on an UNDEFINED value. */
1217 if (val.lattice_val == UNDEFINED)
1218 val.lattice_val = UNKNOWN_VAL;
1220 /* Mark VAL as stored in the LHS of this assignment. */
1221 val.mem_ref = lhs;
1223 /* Set the value of every VDEF to VAL. */
1224 changed = false;
1225 FOR_EACH_SSA_TREE_OPERAND (vdef, stmt, i, SSA_OP_VIRTUAL_DEFS)
1226 changed |= set_lattice_value (vdef, val);
1228 /* Note that for propagation purposes, we are only interested in
1229 visiting statements that load the exact same memory reference
1230 stored here. Those statements will have the exact same list
1231 of virtual uses, so it is enough to set the output of this
1232 statement to be its first virtual definition. */
1233 *output_p = first_vdef (stmt);
1234 if (changed)
1236 if (val.lattice_val == VARYING)
1237 retval = SSA_PROP_VARYING;
1238 else
1239 retval = SSA_PROP_INTERESTING;
1243 return retval;
1247 /* Visit the conditional statement STMT. Return SSA_PROP_INTERESTING
1248 if it can determine which edge will be taken. Otherwise, return
1249 SSA_PROP_VARYING. */
1251 static enum ssa_prop_result
1252 visit_cond_stmt (tree stmt, edge *taken_edge_p)
1254 prop_value_t val;
1255 basic_block block;
1257 block = bb_for_stmt (stmt);
1258 val = evaluate_stmt (stmt);
1260 /* Find which edge out of the conditional block will be taken and add it
1261 to the worklist. If no single edge can be determined statically,
1262 return SSA_PROP_VARYING to feed all the outgoing edges to the
1263 propagation engine. */
1264 *taken_edge_p = val.value ? find_taken_edge (block, val.value) : 0;
1265 if (*taken_edge_p)
1266 return SSA_PROP_INTERESTING;
1267 else
1268 return SSA_PROP_VARYING;
1272 /* Evaluate statement STMT. If the statement produces an output value and
1273 its evaluation changes the lattice value of its output, return
1274 SSA_PROP_INTERESTING and set *OUTPUT_P to the SSA_NAME holding the
1275 output value.
1277 If STMT is a conditional branch and we can determine its truth
1278 value, set *TAKEN_EDGE_P accordingly. If STMT produces a varying
1279 value, return SSA_PROP_VARYING. */
1281 static enum ssa_prop_result
1282 ccp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
1284 tree def;
1285 ssa_op_iter iter;
1287 if (dump_file && (dump_flags & TDF_DETAILS))
1289 fprintf (dump_file, "\nVisiting statement:\n");
1290 print_generic_stmt (dump_file, stmt, dump_flags);
1291 fprintf (dump_file, "\n");
1294 if (TREE_CODE (stmt) == MODIFY_EXPR)
1296 /* If the statement is an assignment that produces a single
1297 output value, evaluate its RHS to see if the lattice value of
1298 its output has changed. */
1299 return visit_assignment (stmt, output_p);
1301 else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1303 /* If STMT is a conditional branch, see if we can determine
1304 which branch will be taken. */
1305 return visit_cond_stmt (stmt, taken_edge_p);
1308 /* Any other kind of statement is not interesting for constant
1309 propagation and, therefore, not worth simulating. */
1310 if (dump_file && (dump_flags & TDF_DETAILS))
1311 fprintf (dump_file, "No interesting values produced. Marked VARYING.\n");
1313 /* Definitions made by statements other than assignments to
1314 SSA_NAMEs represent unknown modifications to their outputs.
1315 Mark them VARYING. */
1316 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
1318 prop_value_t v = { VARYING, NULL_TREE, NULL_TREE };
1319 set_lattice_value (def, v);
1322 return SSA_PROP_VARYING;
1326 /* Main entry point for SSA Conditional Constant Propagation. */
1328 static void
1329 execute_ssa_ccp (bool store_ccp)
1331 do_store_ccp = store_ccp;
1332 ccp_initialize ();
1333 ssa_propagate (ccp_visit_stmt, ccp_visit_phi_node);
1334 ccp_finalize ();
1338 static void
1339 do_ssa_ccp (void)
1341 execute_ssa_ccp (false);
1345 static bool
1346 gate_ccp (void)
1348 return flag_tree_ccp != 0;
1352 struct tree_opt_pass pass_ccp =
1354 "ccp", /* name */
1355 gate_ccp, /* gate */
1356 do_ssa_ccp, /* execute */
1357 NULL, /* sub */
1358 NULL, /* next */
1359 0, /* static_pass_number */
1360 TV_TREE_CCP, /* tv_id */
1361 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
1362 0, /* properties_provided */
1363 0, /* properties_destroyed */
1364 0, /* todo_flags_start */
1365 TODO_cleanup_cfg | TODO_dump_func | TODO_update_ssa
1366 | TODO_ggc_collect | TODO_verify_ssa
1367 | TODO_verify_stmts, /* todo_flags_finish */
1368 0 /* letter */
1372 static void
1373 do_ssa_store_ccp (void)
1375 /* If STORE-CCP is not enabled, we just run regular CCP. */
1376 execute_ssa_ccp (flag_tree_store_ccp != 0);
1379 static bool
1380 gate_store_ccp (void)
1382 /* STORE-CCP is enabled only with -ftree-store-ccp, but when
1383 -fno-tree-store-ccp is specified, we should run regular CCP.
1384 That's why the pass is enabled with either flag. */
1385 return flag_tree_store_ccp != 0 || flag_tree_ccp != 0;
1389 struct tree_opt_pass pass_store_ccp =
1391 "store_ccp", /* name */
1392 gate_store_ccp, /* gate */
1393 do_ssa_store_ccp, /* execute */
1394 NULL, /* sub */
1395 NULL, /* next */
1396 0, /* static_pass_number */
1397 TV_TREE_STORE_CCP, /* tv_id */
1398 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
1399 0, /* properties_provided */
1400 0, /* properties_destroyed */
1401 0, /* todo_flags_start */
1402 TODO_dump_func | TODO_update_ssa
1403 | TODO_ggc_collect | TODO_verify_ssa
1404 | TODO_cleanup_cfg
1405 | TODO_verify_stmts, /* todo_flags_finish */
1406 0 /* letter */
1409 /* Given a constant value VAL for bitfield FIELD, and a destination
1410 variable VAR, return VAL appropriately widened to fit into VAR. If
1411 FIELD is wider than HOST_WIDE_INT, NULL is returned. */
1413 tree
1414 widen_bitfield (tree val, tree field, tree var)
1416 unsigned HOST_WIDE_INT var_size, field_size;
1417 tree wide_val;
1418 unsigned HOST_WIDE_INT mask;
1419 unsigned int i;
1421 /* We can only do this if the size of the type and field and VAL are
1422 all constants representable in HOST_WIDE_INT. */
1423 if (!host_integerp (TYPE_SIZE (TREE_TYPE (var)), 1)
1424 || !host_integerp (DECL_SIZE (field), 1)
1425 || !host_integerp (val, 0))
1426 return NULL_TREE;
1428 var_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1);
1429 field_size = tree_low_cst (DECL_SIZE (field), 1);
1431 /* Give up if either the bitfield or the variable are too wide. */
1432 if (field_size > HOST_BITS_PER_WIDE_INT || var_size > HOST_BITS_PER_WIDE_INT)
1433 return NULL_TREE;
1435 gcc_assert (var_size >= field_size);
1437 /* If the sign bit of the value is not set or the field's type is unsigned,
1438 just mask off the high order bits of the value. */
1439 if (DECL_UNSIGNED (field)
1440 || !(tree_low_cst (val, 0) & (((HOST_WIDE_INT)1) << (field_size - 1))))
1442 /* Zero extension. Build a mask with the lower 'field_size' bits
1443 set and a BIT_AND_EXPR node to clear the high order bits of
1444 the value. */
1445 for (i = 0, mask = 0; i < field_size; i++)
1446 mask |= ((HOST_WIDE_INT) 1) << i;
1448 wide_val = build2 (BIT_AND_EXPR, TREE_TYPE (var), val,
1449 build_int_cst (TREE_TYPE (var), mask));
1451 else
1453 /* Sign extension. Create a mask with the upper 'field_size'
1454 bits set and a BIT_IOR_EXPR to set the high order bits of the
1455 value. */
1456 for (i = 0, mask = 0; i < (var_size - field_size); i++)
1457 mask |= ((HOST_WIDE_INT) 1) << (var_size - i - 1);
1459 wide_val = build2 (BIT_IOR_EXPR, TREE_TYPE (var), val,
1460 build_int_cst (TREE_TYPE (var), mask));
1463 return fold (wide_val);
1467 /* A subroutine of fold_stmt_r. Attempts to fold *(A+O) to A[X].
1468 BASE is an array type. OFFSET is a byte displacement. ORIG_TYPE
1469 is the desired result type. */
1471 static tree
1472 maybe_fold_offset_to_array_ref (tree base, tree offset, tree orig_type)
1474 tree min_idx, idx, elt_offset = integer_zero_node;
1475 tree array_type, elt_type, elt_size;
1477 /* If BASE is an ARRAY_REF, we can pick up another offset (this time
1478 measured in units of the size of elements type) from that ARRAY_REF).
1479 We can't do anything if either is variable.
1481 The case we handle here is *(&A[N]+O). */
1482 if (TREE_CODE (base) == ARRAY_REF)
1484 tree low_bound = array_ref_low_bound (base);
1486 elt_offset = TREE_OPERAND (base, 1);
1487 if (TREE_CODE (low_bound) != INTEGER_CST
1488 || TREE_CODE (elt_offset) != INTEGER_CST)
1489 return NULL_TREE;
1491 elt_offset = int_const_binop (MINUS_EXPR, elt_offset, low_bound, 0);
1492 base = TREE_OPERAND (base, 0);
1495 /* Ignore stupid user tricks of indexing non-array variables. */
1496 array_type = TREE_TYPE (base);
1497 if (TREE_CODE (array_type) != ARRAY_TYPE)
1498 return NULL_TREE;
1499 elt_type = TREE_TYPE (array_type);
1500 if (!lang_hooks.types_compatible_p (orig_type, elt_type))
1501 return NULL_TREE;
1503 /* If OFFSET and ELT_OFFSET are zero, we don't care about the size of the
1504 element type (so we can use the alignment if it's not constant).
1505 Otherwise, compute the offset as an index by using a division. If the
1506 division isn't exact, then don't do anything. */
1507 elt_size = TYPE_SIZE_UNIT (elt_type);
1508 if (integer_zerop (offset))
1510 if (TREE_CODE (elt_size) != INTEGER_CST)
1511 elt_size = size_int (TYPE_ALIGN (elt_type));
1513 idx = integer_zero_node;
1515 else
1517 unsigned HOST_WIDE_INT lquo, lrem;
1518 HOST_WIDE_INT hquo, hrem;
1520 if (TREE_CODE (elt_size) != INTEGER_CST
1521 || div_and_round_double (TRUNC_DIV_EXPR, 1,
1522 TREE_INT_CST_LOW (offset),
1523 TREE_INT_CST_HIGH (offset),
1524 TREE_INT_CST_LOW (elt_size),
1525 TREE_INT_CST_HIGH (elt_size),
1526 &lquo, &hquo, &lrem, &hrem)
1527 || lrem || hrem)
1528 return NULL_TREE;
1530 idx = build_int_cst_wide (NULL_TREE, lquo, hquo);
1533 /* Assume the low bound is zero. If there is a domain type, get the
1534 low bound, if any, convert the index into that type, and add the
1535 low bound. */
1536 min_idx = integer_zero_node;
1537 if (TYPE_DOMAIN (array_type))
1539 if (TYPE_MIN_VALUE (TYPE_DOMAIN (array_type)))
1540 min_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (array_type));
1541 else
1542 min_idx = fold_convert (TYPE_DOMAIN (array_type), min_idx);
1544 if (TREE_CODE (min_idx) != INTEGER_CST)
1545 return NULL_TREE;
1547 idx = fold_convert (TYPE_DOMAIN (array_type), idx);
1548 elt_offset = fold_convert (TYPE_DOMAIN (array_type), elt_offset);
1551 if (!integer_zerop (min_idx))
1552 idx = int_const_binop (PLUS_EXPR, idx, min_idx, 0);
1553 if (!integer_zerop (elt_offset))
1554 idx = int_const_binop (PLUS_EXPR, idx, elt_offset, 0);
1556 return build (ARRAY_REF, orig_type, base, idx, min_idx,
1557 size_int (tree_low_cst (elt_size, 1)
1558 / (TYPE_ALIGN_UNIT (elt_type))));
1562 /* A subroutine of fold_stmt_r. Attempts to fold *(S+O) to S.X.
1563 BASE is a record type. OFFSET is a byte displacement. ORIG_TYPE
1564 is the desired result type. */
1565 /* ??? This doesn't handle class inheritance. */
1567 static tree
1568 maybe_fold_offset_to_component_ref (tree record_type, tree base, tree offset,
1569 tree orig_type, bool base_is_ptr)
1571 tree f, t, field_type, tail_array_field, field_offset;
1573 if (TREE_CODE (record_type) != RECORD_TYPE
1574 && TREE_CODE (record_type) != UNION_TYPE
1575 && TREE_CODE (record_type) != QUAL_UNION_TYPE)
1576 return NULL_TREE;
1578 /* Short-circuit silly cases. */
1579 if (lang_hooks.types_compatible_p (record_type, orig_type))
1580 return NULL_TREE;
1582 tail_array_field = NULL_TREE;
1583 for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f))
1585 int cmp;
1587 if (TREE_CODE (f) != FIELD_DECL)
1588 continue;
1589 if (DECL_BIT_FIELD (f))
1590 continue;
1592 field_offset = byte_position (f);
1593 if (TREE_CODE (field_offset) != INTEGER_CST)
1594 continue;
1596 /* ??? Java creates "interesting" fields for representing base classes.
1597 They have no name, and have no context. With no context, we get into
1598 trouble with nonoverlapping_component_refs_p. Skip them. */
1599 if (!DECL_FIELD_CONTEXT (f))
1600 continue;
1602 /* The previous array field isn't at the end. */
1603 tail_array_field = NULL_TREE;
1605 /* Check to see if this offset overlaps with the field. */
1606 cmp = tree_int_cst_compare (field_offset, offset);
1607 if (cmp > 0)
1608 continue;
1610 field_type = TREE_TYPE (f);
1612 /* Here we exactly match the offset being checked. If the types match,
1613 then we can return that field. */
1614 if (cmp == 0
1615 && lang_hooks.types_compatible_p (orig_type, field_type))
1617 if (base_is_ptr)
1618 base = build1 (INDIRECT_REF, record_type, base);
1619 t = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1620 return t;
1623 /* Don't care about offsets into the middle of scalars. */
1624 if (!AGGREGATE_TYPE_P (field_type))
1625 continue;
1627 /* Check for array at the end of the struct. This is often
1628 used as for flexible array members. We should be able to
1629 turn this into an array access anyway. */
1630 if (TREE_CODE (field_type) == ARRAY_TYPE)
1631 tail_array_field = f;
1633 /* Check the end of the field against the offset. */
1634 if (!DECL_SIZE_UNIT (f)
1635 || TREE_CODE (DECL_SIZE_UNIT (f)) != INTEGER_CST)
1636 continue;
1637 t = int_const_binop (MINUS_EXPR, offset, field_offset, 1);
1638 if (!tree_int_cst_lt (t, DECL_SIZE_UNIT (f)))
1639 continue;
1641 /* If we matched, then set offset to the displacement into
1642 this field. */
1643 offset = t;
1644 goto found;
1647 if (!tail_array_field)
1648 return NULL_TREE;
1650 f = tail_array_field;
1651 field_type = TREE_TYPE (f);
1652 offset = int_const_binop (MINUS_EXPR, offset, byte_position (f), 1);
1654 found:
1655 /* If we get here, we've got an aggregate field, and a possibly
1656 nonzero offset into them. Recurse and hope for a valid match. */
1657 if (base_is_ptr)
1658 base = build1 (INDIRECT_REF, record_type, base);
1659 base = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1661 t = maybe_fold_offset_to_array_ref (base, offset, orig_type);
1662 if (t)
1663 return t;
1664 return maybe_fold_offset_to_component_ref (field_type, base, offset,
1665 orig_type, false);
1669 /* A subroutine of fold_stmt_r. Attempt to simplify *(BASE+OFFSET).
1670 Return the simplified expression, or NULL if nothing could be done. */
1672 static tree
1673 maybe_fold_stmt_indirect (tree expr, tree base, tree offset)
1675 tree t;
1677 /* We may well have constructed a double-nested PLUS_EXPR via multiple
1678 substitutions. Fold that down to one. Remove NON_LVALUE_EXPRs that
1679 are sometimes added. */
1680 base = fold (base);
1681 STRIP_TYPE_NOPS (base);
1682 TREE_OPERAND (expr, 0) = base;
1684 /* One possibility is that the address reduces to a string constant. */
1685 t = fold_read_from_constant_string (expr);
1686 if (t)
1687 return t;
1689 /* Add in any offset from a PLUS_EXPR. */
1690 if (TREE_CODE (base) == PLUS_EXPR)
1692 tree offset2;
1694 offset2 = TREE_OPERAND (base, 1);
1695 if (TREE_CODE (offset2) != INTEGER_CST)
1696 return NULL_TREE;
1697 base = TREE_OPERAND (base, 0);
1699 offset = int_const_binop (PLUS_EXPR, offset, offset2, 1);
1702 if (TREE_CODE (base) == ADDR_EXPR)
1704 /* Strip the ADDR_EXPR. */
1705 base = TREE_OPERAND (base, 0);
1707 /* Fold away CONST_DECL to its value, if the type is scalar. */
1708 if (TREE_CODE (base) == CONST_DECL
1709 && is_gimple_min_invariant (DECL_INITIAL (base)))
1710 return DECL_INITIAL (base);
1712 /* Try folding *(&B+O) to B[X]. */
1713 t = maybe_fold_offset_to_array_ref (base, offset, TREE_TYPE (expr));
1714 if (t)
1715 return t;
1717 /* Try folding *(&B+O) to B.X. */
1718 t = maybe_fold_offset_to_component_ref (TREE_TYPE (base), base, offset,
1719 TREE_TYPE (expr), false);
1720 if (t)
1721 return t;
1723 /* Fold *&B to B. We can only do this if EXPR is the same type
1724 as BASE. We can't do this if EXPR is the element type of an array
1725 and BASE is the array. */
1726 if (integer_zerop (offset)
1727 && lang_hooks.types_compatible_p (TREE_TYPE (base),
1728 TREE_TYPE (expr)))
1729 return base;
1731 else
1733 /* We can get here for out-of-range string constant accesses,
1734 such as "_"[3]. Bail out of the entire substitution search
1735 and arrange for the entire statement to be replaced by a
1736 call to __builtin_trap. In all likelihood this will all be
1737 constant-folded away, but in the meantime we can't leave with
1738 something that get_expr_operands can't understand. */
1740 t = base;
1741 STRIP_NOPS (t);
1742 if (TREE_CODE (t) == ADDR_EXPR
1743 && TREE_CODE (TREE_OPERAND (t, 0)) == STRING_CST)
1745 /* FIXME: Except that this causes problems elsewhere with dead
1746 code not being deleted, and we die in the rtl expanders
1747 because we failed to remove some ssa_name. In the meantime,
1748 just return zero. */
1749 /* FIXME2: This condition should be signaled by
1750 fold_read_from_constant_string directly, rather than
1751 re-checking for it here. */
1752 return integer_zero_node;
1755 /* Try folding *(B+O) to B->X. Still an improvement. */
1756 if (POINTER_TYPE_P (TREE_TYPE (base)))
1758 t = maybe_fold_offset_to_component_ref (TREE_TYPE (TREE_TYPE (base)),
1759 base, offset,
1760 TREE_TYPE (expr), true);
1761 if (t)
1762 return t;
1766 /* Otherwise we had an offset that we could not simplify. */
1767 return NULL_TREE;
1771 /* A subroutine of fold_stmt_r. EXPR is a PLUS_EXPR.
1773 A quaint feature extant in our address arithmetic is that there
1774 can be hidden type changes here. The type of the result need
1775 not be the same as the type of the input pointer.
1777 What we're after here is an expression of the form
1778 (T *)(&array + const)
1779 where the cast doesn't actually exist, but is implicit in the
1780 type of the PLUS_EXPR. We'd like to turn this into
1781 &array[x]
1782 which may be able to propagate further. */
1784 static tree
1785 maybe_fold_stmt_addition (tree expr)
1787 tree op0 = TREE_OPERAND (expr, 0);
1788 tree op1 = TREE_OPERAND (expr, 1);
1789 tree ptr_type = TREE_TYPE (expr);
1790 tree ptd_type;
1791 tree t;
1792 bool subtract = (TREE_CODE (expr) == MINUS_EXPR);
1794 /* We're only interested in pointer arithmetic. */
1795 if (!POINTER_TYPE_P (ptr_type))
1796 return NULL_TREE;
1797 /* Canonicalize the integral operand to op1. */
1798 if (INTEGRAL_TYPE_P (TREE_TYPE (op0)))
1800 if (subtract)
1801 return NULL_TREE;
1802 t = op0, op0 = op1, op1 = t;
1804 /* It had better be a constant. */
1805 if (TREE_CODE (op1) != INTEGER_CST)
1806 return NULL_TREE;
1807 /* The first operand should be an ADDR_EXPR. */
1808 if (TREE_CODE (op0) != ADDR_EXPR)
1809 return NULL_TREE;
1810 op0 = TREE_OPERAND (op0, 0);
1812 /* If the first operand is an ARRAY_REF, expand it so that we can fold
1813 the offset into it. */
1814 while (TREE_CODE (op0) == ARRAY_REF)
1816 tree array_obj = TREE_OPERAND (op0, 0);
1817 tree array_idx = TREE_OPERAND (op0, 1);
1818 tree elt_type = TREE_TYPE (op0);
1819 tree elt_size = TYPE_SIZE_UNIT (elt_type);
1820 tree min_idx;
1822 if (TREE_CODE (array_idx) != INTEGER_CST)
1823 break;
1824 if (TREE_CODE (elt_size) != INTEGER_CST)
1825 break;
1827 /* Un-bias the index by the min index of the array type. */
1828 min_idx = TYPE_DOMAIN (TREE_TYPE (array_obj));
1829 if (min_idx)
1831 min_idx = TYPE_MIN_VALUE (min_idx);
1832 if (min_idx)
1834 if (TREE_CODE (min_idx) != INTEGER_CST)
1835 break;
1837 array_idx = convert (TREE_TYPE (min_idx), array_idx);
1838 if (!integer_zerop (min_idx))
1839 array_idx = int_const_binop (MINUS_EXPR, array_idx,
1840 min_idx, 0);
1844 /* Convert the index to a byte offset. */
1845 array_idx = convert (sizetype, array_idx);
1846 array_idx = int_const_binop (MULT_EXPR, array_idx, elt_size, 0);
1848 /* Update the operands for the next round, or for folding. */
1849 /* If we're manipulating unsigned types, then folding into negative
1850 values can produce incorrect results. Particularly if the type
1851 is smaller than the width of the pointer. */
1852 if (subtract
1853 && TYPE_UNSIGNED (TREE_TYPE (op1))
1854 && tree_int_cst_lt (array_idx, op1))
1855 return NULL;
1856 op1 = int_const_binop (subtract ? MINUS_EXPR : PLUS_EXPR,
1857 array_idx, op1, 0);
1858 subtract = false;
1859 op0 = array_obj;
1862 /* If we weren't able to fold the subtraction into another array reference,
1863 canonicalize the integer for passing to the array and component ref
1864 simplification functions. */
1865 if (subtract)
1867 if (TYPE_UNSIGNED (TREE_TYPE (op1)))
1868 return NULL;
1869 op1 = fold (build1 (NEGATE_EXPR, TREE_TYPE (op1), op1));
1870 /* ??? In theory fold should always produce another integer. */
1871 if (TREE_CODE (op1) != INTEGER_CST)
1872 return NULL;
1875 ptd_type = TREE_TYPE (ptr_type);
1877 /* At which point we can try some of the same things as for indirects. */
1878 t = maybe_fold_offset_to_array_ref (op0, op1, ptd_type);
1879 if (!t)
1880 t = maybe_fold_offset_to_component_ref (TREE_TYPE (op0), op0, op1,
1881 ptd_type, false);
1882 if (t)
1883 t = build1 (ADDR_EXPR, ptr_type, t);
1885 return t;
1889 /* Subroutine of fold_stmt called via walk_tree. We perform several
1890 simplifications of EXPR_P, mostly having to do with pointer arithmetic. */
1892 static tree
1893 fold_stmt_r (tree *expr_p, int *walk_subtrees, void *data)
1895 bool *changed_p = data;
1896 tree expr = *expr_p, t;
1898 /* ??? It'd be nice if walk_tree had a pre-order option. */
1899 switch (TREE_CODE (expr))
1901 case INDIRECT_REF:
1902 t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1903 if (t)
1904 return t;
1905 *walk_subtrees = 0;
1907 t = maybe_fold_stmt_indirect (expr, TREE_OPERAND (expr, 0),
1908 integer_zero_node);
1909 break;
1911 /* ??? Could handle ARRAY_REF here, as a variant of INDIRECT_REF.
1912 We'd only want to bother decomposing an existing ARRAY_REF if
1913 the base array is found to have another offset contained within.
1914 Otherwise we'd be wasting time. */
1916 case ADDR_EXPR:
1917 t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1918 if (t)
1919 return t;
1920 *walk_subtrees = 0;
1922 /* Set TREE_INVARIANT properly so that the value is properly
1923 considered constant, and so gets propagated as expected. */
1924 if (*changed_p)
1925 recompute_tree_invarant_for_addr_expr (expr);
1926 return NULL_TREE;
1928 case PLUS_EXPR:
1929 case MINUS_EXPR:
1930 t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1931 if (t)
1932 return t;
1933 t = walk_tree (&TREE_OPERAND (expr, 1), fold_stmt_r, data, NULL);
1934 if (t)
1935 return t;
1936 *walk_subtrees = 0;
1938 t = maybe_fold_stmt_addition (expr);
1939 break;
1941 case COMPONENT_REF:
1942 t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1943 if (t)
1944 return t;
1945 *walk_subtrees = 0;
1947 /* Make sure the FIELD_DECL is actually a field in the type on the lhs.
1948 We've already checked that the records are compatible, so we should
1949 come up with a set of compatible fields. */
1951 tree expr_record = TREE_TYPE (TREE_OPERAND (expr, 0));
1952 tree expr_field = TREE_OPERAND (expr, 1);
1954 if (DECL_FIELD_CONTEXT (expr_field) != TYPE_MAIN_VARIANT (expr_record))
1956 expr_field = find_compatible_field (expr_record, expr_field);
1957 TREE_OPERAND (expr, 1) = expr_field;
1960 break;
1962 default:
1963 return NULL_TREE;
1966 if (t)
1968 *expr_p = t;
1969 *changed_p = true;
1972 return NULL_TREE;
1976 /* Return the string length of ARG in LENGTH. If ARG is an SSA name variable,
1977 follow its use-def chains. If LENGTH is not NULL and its value is not
1978 equal to the length we determine, or if we are unable to determine the
1979 length, return false. VISITED is a bitmap of visited variables. */
1981 static bool
1982 get_strlen (tree arg, tree *length, bitmap visited)
1984 tree var, def_stmt, val;
1986 if (TREE_CODE (arg) != SSA_NAME)
1988 val = c_strlen (arg, 1);
1989 if (!val)
1990 return false;
1992 if (*length && simple_cst_equal (val, *length) != 1)
1993 return false;
1995 *length = val;
1996 return true;
1999 /* If we were already here, break the infinite cycle. */
2000 if (bitmap_bit_p (visited, SSA_NAME_VERSION (arg)))
2001 return true;
2002 bitmap_set_bit (visited, SSA_NAME_VERSION (arg));
2004 var = arg;
2005 def_stmt = SSA_NAME_DEF_STMT (var);
2007 switch (TREE_CODE (def_stmt))
2009 case MODIFY_EXPR:
2011 tree len, rhs;
2013 /* The RHS of the statement defining VAR must either have a
2014 constant length or come from another SSA_NAME with a constant
2015 length. */
2016 rhs = TREE_OPERAND (def_stmt, 1);
2017 STRIP_NOPS (rhs);
2018 if (TREE_CODE (rhs) == SSA_NAME)
2019 return get_strlen (rhs, length, visited);
2021 /* See if the RHS is a constant length. */
2022 len = c_strlen (rhs, 1);
2023 if (len)
2025 if (*length && simple_cst_equal (len, *length) != 1)
2026 return false;
2028 *length = len;
2029 return true;
2032 break;
2035 case PHI_NODE:
2037 /* All the arguments of the PHI node must have the same constant
2038 length. */
2039 int i;
2041 for (i = 0; i < PHI_NUM_ARGS (def_stmt); i++)
2043 tree arg = PHI_ARG_DEF (def_stmt, i);
2045 /* If this PHI has itself as an argument, we cannot
2046 determine the string length of this argument. However,
2047 if we can find a constant string length for the other
2048 PHI args then we can still be sure that this is a
2049 constant string length. So be optimistic and just
2050 continue with the next argument. */
2051 if (arg == PHI_RESULT (def_stmt))
2052 continue;
2054 if (!get_strlen (arg, length, visited))
2055 return false;
2058 return true;
2061 default:
2062 break;
2066 return false;
2070 /* Fold builtin call FN in statement STMT. If it cannot be folded into a
2071 constant, return NULL_TREE. Otherwise, return its constant value. */
2073 static tree
2074 ccp_fold_builtin (tree stmt, tree fn)
2076 tree result, strlen_val[2];
2077 tree callee, arglist, a;
2078 int strlen_arg, i;
2079 bitmap visited;
2080 bool ignore;
2082 ignore = TREE_CODE (stmt) != MODIFY_EXPR;
2084 /* First try the generic builtin folder. If that succeeds, return the
2085 result directly. */
2086 callee = get_callee_fndecl (fn);
2087 arglist = TREE_OPERAND (fn, 1);
2088 result = fold_builtin (callee, arglist, ignore);
2089 if (result)
2091 if (ignore)
2092 STRIP_NOPS (result);
2093 return result;
2096 /* Ignore MD builtins. */
2097 if (DECL_BUILT_IN_CLASS (callee) == BUILT_IN_MD)
2098 return NULL_TREE;
2100 /* If the builtin could not be folded, and it has no argument list,
2101 we're done. */
2102 if (!arglist)
2103 return NULL_TREE;
2105 /* Limit the work only for builtins we know how to simplify. */
2106 switch (DECL_FUNCTION_CODE (callee))
2108 case BUILT_IN_STRLEN:
2109 case BUILT_IN_FPUTS:
2110 case BUILT_IN_FPUTS_UNLOCKED:
2111 strlen_arg = 1;
2112 break;
2113 case BUILT_IN_STRCPY:
2114 case BUILT_IN_STRNCPY:
2115 strlen_arg = 2;
2116 break;
2117 default:
2118 return NULL_TREE;
2121 /* Try to use the dataflow information gathered by the CCP process. */
2122 visited = BITMAP_ALLOC (NULL);
2124 memset (strlen_val, 0, sizeof (strlen_val));
2125 for (i = 0, a = arglist;
2126 strlen_arg;
2127 i++, strlen_arg >>= 1, a = TREE_CHAIN (a))
2128 if (strlen_arg & 1)
2130 bitmap_clear (visited);
2131 if (!get_strlen (TREE_VALUE (a), &strlen_val[i], visited))
2132 strlen_val[i] = NULL_TREE;
2135 BITMAP_FREE (visited);
2137 result = NULL_TREE;
2138 switch (DECL_FUNCTION_CODE (callee))
2140 case BUILT_IN_STRLEN:
2141 if (strlen_val[0])
2143 tree new = fold_convert (TREE_TYPE (fn), strlen_val[0]);
2145 /* If the result is not a valid gimple value, or not a cast
2146 of a valid gimple value, then we can not use the result. */
2147 if (is_gimple_val (new)
2148 || (is_gimple_cast (new)
2149 && is_gimple_val (TREE_OPERAND (new, 0))))
2150 return new;
2152 break;
2154 case BUILT_IN_STRCPY:
2155 if (strlen_val[1] && is_gimple_val (strlen_val[1]))
2157 tree fndecl = get_callee_fndecl (fn);
2158 tree arglist = TREE_OPERAND (fn, 1);
2159 result = fold_builtin_strcpy (fndecl, arglist, strlen_val[1]);
2161 break;
2163 case BUILT_IN_STRNCPY:
2164 if (strlen_val[1] && is_gimple_val (strlen_val[1]))
2166 tree fndecl = get_callee_fndecl (fn);
2167 tree arglist = TREE_OPERAND (fn, 1);
2168 result = fold_builtin_strncpy (fndecl, arglist, strlen_val[1]);
2170 break;
2172 case BUILT_IN_FPUTS:
2173 result = fold_builtin_fputs (arglist,
2174 TREE_CODE (stmt) != MODIFY_EXPR, 0,
2175 strlen_val[0]);
2176 break;
2178 case BUILT_IN_FPUTS_UNLOCKED:
2179 result = fold_builtin_fputs (arglist,
2180 TREE_CODE (stmt) != MODIFY_EXPR, 1,
2181 strlen_val[0]);
2182 break;
2184 default:
2185 gcc_unreachable ();
2188 if (result && ignore)
2189 result = fold_ignored_result (result);
2190 return result;
2194 /* Fold the statement pointed by STMT_P. In some cases, this function may
2195 replace the whole statement with a new one. Returns true iff folding
2196 makes any changes. */
2198 bool
2199 fold_stmt (tree *stmt_p)
2201 tree rhs, result, stmt;
2202 bool changed = false;
2204 stmt = *stmt_p;
2206 /* If we replaced constants and the statement makes pointer dereferences,
2207 then we may need to fold instances of *&VAR into VAR, etc. */
2208 if (walk_tree (stmt_p, fold_stmt_r, &changed, NULL))
2210 *stmt_p
2211 = build_function_call_expr (implicit_built_in_decls[BUILT_IN_TRAP],
2212 NULL);
2213 return true;
2216 rhs = get_rhs (stmt);
2217 if (!rhs)
2218 return changed;
2219 result = NULL_TREE;
2221 if (TREE_CODE (rhs) == CALL_EXPR)
2223 tree callee;
2225 /* Check for builtins that CCP can handle using information not
2226 available in the generic fold routines. */
2227 callee = get_callee_fndecl (rhs);
2228 if (callee && DECL_BUILT_IN (callee))
2229 result = ccp_fold_builtin (stmt, rhs);
2230 else
2232 /* Check for resolvable OBJ_TYPE_REF. The only sorts we can resolve
2233 here are when we've propagated the address of a decl into the
2234 object slot. */
2235 /* ??? Should perhaps do this in fold proper. However, doing it
2236 there requires that we create a new CALL_EXPR, and that requires
2237 copying EH region info to the new node. Easier to just do it
2238 here where we can just smash the call operand. */
2239 callee = TREE_OPERAND (rhs, 0);
2240 if (TREE_CODE (callee) == OBJ_TYPE_REF
2241 && lang_hooks.fold_obj_type_ref
2242 && TREE_CODE (OBJ_TYPE_REF_OBJECT (callee)) == ADDR_EXPR
2243 && DECL_P (TREE_OPERAND
2244 (OBJ_TYPE_REF_OBJECT (callee), 0)))
2246 tree t;
2248 /* ??? Caution: Broken ADDR_EXPR semantics means that
2249 looking at the type of the operand of the addr_expr
2250 can yield an array type. See silly exception in
2251 check_pointer_types_r. */
2253 t = TREE_TYPE (TREE_TYPE (OBJ_TYPE_REF_OBJECT (callee)));
2254 t = lang_hooks.fold_obj_type_ref (callee, t);
2255 if (t)
2257 TREE_OPERAND (rhs, 0) = t;
2258 changed = true;
2264 /* If we couldn't fold the RHS, hand over to the generic fold routines. */
2265 if (result == NULL_TREE)
2266 result = fold (rhs);
2268 /* Strip away useless type conversions. Both the NON_LVALUE_EXPR that
2269 may have been added by fold, and "useless" type conversions that might
2270 now be apparent due to propagation. */
2271 STRIP_USELESS_TYPE_CONVERSION (result);
2273 if (result != rhs)
2274 changed |= set_rhs (stmt_p, result);
2276 return changed;
2279 /* Perform the minimal folding on statement STMT. Only operations like
2280 *&x created by constant propagation are handled. The statement cannot
2281 be replaced with a new one. */
2283 bool
2284 fold_stmt_inplace (tree stmt)
2286 tree old_stmt = stmt, rhs, new_rhs;
2287 bool changed = false;
2289 walk_tree (&stmt, fold_stmt_r, &changed, NULL);
2290 gcc_assert (stmt == old_stmt);
2292 rhs = get_rhs (stmt);
2293 if (!rhs || rhs == stmt)
2294 return changed;
2296 new_rhs = fold (rhs);
2297 if (new_rhs == rhs)
2298 return changed;
2300 changed |= set_rhs (&stmt, new_rhs);
2301 gcc_assert (stmt == old_stmt);
2303 return changed;
2306 /* Convert EXPR into a GIMPLE value suitable for substitution on the
2307 RHS of an assignment. Insert the necessary statements before
2308 iterator *SI_P. */
2310 static tree
2311 convert_to_gimple_builtin (block_stmt_iterator *si_p, tree expr)
2313 tree_stmt_iterator ti;
2314 tree stmt = bsi_stmt (*si_p);
2315 tree tmp, stmts = NULL;
2317 push_gimplify_context ();
2318 tmp = get_initialized_tmp_var (expr, &stmts, NULL);
2319 pop_gimplify_context (NULL);
2321 if (EXPR_HAS_LOCATION (stmt))
2322 annotate_all_with_locus (&stmts, EXPR_LOCATION (stmt));
2324 /* The replacement can expose previously unreferenced variables. */
2325 for (ti = tsi_start (stmts); !tsi_end_p (ti); tsi_next (&ti))
2327 tree new_stmt = tsi_stmt (ti);
2328 find_new_referenced_vars (tsi_stmt_ptr (ti));
2329 bsi_insert_before (si_p, new_stmt, BSI_NEW_STMT);
2330 mark_new_vars_to_rename (bsi_stmt (*si_p));
2331 bsi_next (si_p);
2334 return tmp;
2338 /* A simple pass that attempts to fold all builtin functions. This pass
2339 is run after we've propagated as many constants as we can. */
2341 static void
2342 execute_fold_all_builtins (void)
2344 bool cfg_changed = false;
2345 basic_block bb;
2346 FOR_EACH_BB (bb)
2348 block_stmt_iterator i;
2349 for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
2351 tree *stmtp = bsi_stmt_ptr (i);
2352 tree old_stmt = *stmtp;
2353 tree call = get_rhs (*stmtp);
2354 tree callee, result;
2356 if (!call || TREE_CODE (call) != CALL_EXPR)
2357 continue;
2358 callee = get_callee_fndecl (call);
2359 if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
2360 continue;
2362 result = ccp_fold_builtin (*stmtp, call);
2363 if (!result)
2364 switch (DECL_FUNCTION_CODE (callee))
2366 case BUILT_IN_CONSTANT_P:
2367 /* Resolve __builtin_constant_p. If it hasn't been
2368 folded to integer_one_node by now, it's fairly
2369 certain that the value simply isn't constant. */
2370 result = integer_zero_node;
2371 break;
2373 default:
2374 continue;
2377 if (dump_file && (dump_flags & TDF_DETAILS))
2379 fprintf (dump_file, "Simplified\n ");
2380 print_generic_stmt (dump_file, *stmtp, dump_flags);
2383 if (!set_rhs (stmtp, result))
2385 result = convert_to_gimple_builtin (&i, result);
2386 if (result)
2388 bool ok = set_rhs (stmtp, result);
2390 gcc_assert (ok);
2393 update_stmt (*stmtp);
2394 if (maybe_clean_or_replace_eh_stmt (old_stmt, *stmtp)
2395 && tree_purge_dead_eh_edges (bb))
2396 cfg_changed = true;
2398 if (dump_file && (dump_flags & TDF_DETAILS))
2400 fprintf (dump_file, "to\n ");
2401 print_generic_stmt (dump_file, *stmtp, dump_flags);
2402 fprintf (dump_file, "\n");
2407 /* Delete unreachable blocks. */
2408 if (cfg_changed)
2409 cleanup_tree_cfg ();
2413 struct tree_opt_pass pass_fold_builtins =
2415 "fab", /* name */
2416 NULL, /* gate */
2417 execute_fold_all_builtins, /* execute */
2418 NULL, /* sub */
2419 NULL, /* next */
2420 0, /* static_pass_number */
2421 0, /* tv_id */
2422 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
2423 0, /* properties_provided */
2424 0, /* properties_destroyed */
2425 0, /* todo_flags_start */
2426 TODO_dump_func
2427 | TODO_verify_ssa
2428 | TODO_update_ssa, /* todo_flags_finish */
2429 0 /* letter */